d3Data.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { hierarchy } from 'd3-hierarchy'
  2. function flatten (arr, accumulator = []) {
  3. return arr.reduce((acc, child) => {
  4. acc.push(child)
  5. return child.children ? flatten(child.children, acc) : acc
  6. }, accumulator)
  7. }
  8. function getLinked (text) {
  9. const types = ['text_en_rebond', 'text_produits', 'text_de_depart']
  10. return types.reduce((acc, type) => {
  11. // Handle `null` and `undefined`
  12. return text[type] ? [...acc, ...text[type]] : acc
  13. }, [])
  14. }
  15. export function toSingleManyData (rawData) {
  16. rawData.first = true
  17. const h = hierarchy(rawData, d => getLinked(d))
  18. h.each(node => {
  19. if (node.parent && node.children) {
  20. const id = node.parent.data.id
  21. node.children = node.children.filter(child => child.data.id !== id)
  22. }
  23. })
  24. const nodes = h.descendants()
  25. const links = h.links()
  26. nodes.forEach(node => {
  27. Object.assign(node.data, {
  28. type: node.data.__typename.toLowerCase(),
  29. class: 'family-' + node.data.familles[0].id
  30. })
  31. })
  32. return { nodes, links }
  33. }
  34. export function toManyManyData (rawData) {
  35. rawData.first = true
  36. const h = hierarchy(rawData, d => getLinked(d))
  37. h.each(node => {
  38. if (node.parent && node.children) {
  39. const id = node.parent.data.id
  40. node.children = node.children.filter(child => child.data.id !== id)
  41. }
  42. })
  43. const ids = []
  44. const nodes = []
  45. const links = []
  46. flatten(h.descendants()).filter(node => {
  47. if (!ids.includes(node.data.id)) {
  48. ids.push(node.data.id)
  49. return true
  50. }
  51. return false
  52. }).forEach(({ data, children, depth }) => {
  53. nodes.push({ id: data.id, data })
  54. if (children) {
  55. children.forEach(child => {
  56. links.push({ source: data.id, target: child.data.id })
  57. })
  58. }
  59. })
  60. nodes.forEach(node => {
  61. Object.assign(node.data, {
  62. type: node.data.__typename.toLowerCase(),
  63. class: 'family-' + node.data.familles[0].id
  64. })
  65. })
  66. return { nodes, links }
  67. }