utils.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import { hierarchy } from 'd3-hierarchy'
  2. export const RELATIONS = [
  3. 'parents',
  4. 'siblings',
  5. 'children'
  6. ]
  7. export const DATA_LEVELS = {
  8. initial: 0,
  9. partial: 1,
  10. full: 2
  11. }
  12. export const ID_VARIANTS = {
  13. 9: 'depart',
  14. 22: 'critique',
  15. 63: 'echo',
  16. 6: 'reflexion',
  17. 7: 'lecture',
  18. 8: 'sensible',
  19. 23: 'kit'
  20. // undefined: 'creation'
  21. }
  22. export const VARIANT_IDS = Object.fromEntries(
  23. Object.entries(ID_VARIANTS).map(([key, value]) => [value, key])
  24. )
  25. export function parseNodesQueryParams ({ mode, nodes = [] }) {
  26. let nodebook = typeof nodes === 'string' ? [nodes] : nodes
  27. nodebook = nodebook.map(ids => {
  28. return typeof ids === 'string'
  29. ? ids.split(',').map(id => parseInt(id))
  30. : [...ids]
  31. })
  32. return { mode, nodebook }
  33. }
  34. export function getUniqueNodesIds (tree) {
  35. function extractId (ids, node) {
  36. ids.add(node.id)
  37. for (const relation of RELATIONS) {
  38. if (relation in node && node[relation]) {
  39. for (const subNode of node[relation]) {
  40. extractId(ids, subNode)
  41. }
  42. }
  43. }
  44. return ids
  45. }
  46. return Array.from(extractId(new Set(), tree))
  47. }
  48. export function getRelatedNodesIds (nodes) {
  49. const ids = new Set()
  50. for (const node of nodes) {
  51. for (const relation of RELATIONS) {
  52. if (relation in node && node[relation]) {
  53. node[relation].forEach(({ id }) => {
  54. ids.add(id)
  55. })
  56. }
  57. }
  58. }
  59. return Array.from(ids)
  60. }
  61. export function buildTree (treeData, nodesData) {
  62. const uniqueIds = []
  63. const nodes = []
  64. const links = []
  65. const h = hierarchy(treeData, (node) => {
  66. return RELATIONS.reduce((acc, relation) => {
  67. if (node[relation]) {
  68. node[relation].forEach((item, i) => {
  69. item.linkType = relation
  70. })
  71. return [...acc, ...node[relation]]
  72. }
  73. return acc
  74. }, [])
  75. })
  76. h.each(node => {
  77. node.id = node.data.id
  78. if (!uniqueIds.includes(node.id)) {
  79. uniqueIds.push(node.id)
  80. node.data = nodesData.find(n => n.id === node.id)
  81. nodes.push(node)
  82. if (node.children) {
  83. node.children.forEach(child => {
  84. const asSource = links.find(link => link.source === node.id && link.target === child.data.id)
  85. const asTarget = links.find(link => link.source === child.data.id && link.target === node.id)
  86. if (!asSource && !asTarget) {
  87. links.push({ source: node.id, target: child.data.id, linkType: child.data.linkType })
  88. }
  89. })
  90. }
  91. }
  92. })
  93. return {
  94. nodes,
  95. links
  96. }
  97. }