Browse Source

fix children not displayed if first occurence of a node is the leave of the tree

axolotle 3 years ago
parent
commit
f00c250b0e
1 changed files with 23 additions and 16 deletions
  1. 23 16
      src/helpers/d3Data.js

+ 23 - 16
src/helpers/d3Data.js

@@ -43,33 +43,40 @@ export function toManyManyData (rawData) {
   h.each(node => {
     if (node.parent && node.children) {
       const id = node.parent.data.id
+      // Remove reference of parent in child's children.
       node.children = node.children.filter(child => child.data.id !== id)
     }
   })
 
-  const ids = []
-  const nodes = []
   const links = []
-  flatten(h.descendants()).filter(node => {
-    if (!ids.includes(node.data.id)) {
-      ids.push(node.data.id)
-      return true
+  const nodes = flatten(h.descendants()).reduce((nodes, node) => {
+    const sameNode = nodes.find(n => node.data.id === n.data.id)
+    if (sameNode) {
+      if (!node.children) return nodes
+      node.children.forEach(child => {
+        if (!sameNode.children.find(c => child.data.id === c.data.id)) {
+          sameNode.children.push(child)
+        }
+      })
+    } else {
+      if (!node.children) node.children = []
+      nodes.push(node)
     }
-    return false
-  }).forEach(({ data, children, depth }) => {
-    nodes.push({ id: data.id, data })
+    return nodes
+  }, []).map(({ data, children, depth }) => {
     if (children) {
       children.forEach(child => {
         links.push({ source: data.id, target: child.data.id })
       })
     }
-  })
-
-  nodes.forEach(node => {
-    Object.assign(node.data, {
-      type: node.data.__typename.toLowerCase(),
-      class: 'family-' + node.data.familles[0].id
-    })
+    return {
+      id: data.id,
+      data: {
+        ...data,
+        type: data.__typename.toLowerCase(),
+        class: 'family-' + data.familles[0].id
+      }
+    }
   })
   return { nodes, links }
 }