import { hierarchy } from 'd3-hierarchy' export const RELATIONS = [ 'parents', 'siblings', 'children' ] export const DATA_LEVELS = { initial: 0, partial: 1, full: 2 } export const ID_VARIANTS = { 9: 'depart', 22: 'critique', 63: 'echo', 6: 'reflexion', 7: 'lecture', 8: 'sensible', 23: 'kit' // undefined: 'creation' } export const VARIANT_IDS = Object.fromEntries( Object.entries(ID_VARIANTS).map(([key, value]) => [value, key]) ) export function parseNodesQueryParams ({ mode, nodes = [] }) { let nodebook = typeof nodes === 'string' ? [nodes] : nodes nodebook = nodebook.map(ids => { return typeof ids === 'string' ? ids.split(',').map(id => parseInt(id)) : [...ids] }) return { mode, nodebook } } export function getUniqueNodesIds (tree) { function extractId (ids, node) { ids.add(node.id) for (const relation of RELATIONS) { if (relation in node && node[relation]) { for (const subNode of node[relation]) { extractId(ids, subNode) } } } return ids } return Array.from(extractId(new Set(), tree)) } export function getRelatedNodesIds (nodes) { const ids = new Set() for (const node of nodes) { for (const relation of RELATIONS) { if (relation in node && node[relation]) { node[relation].forEach(({ id }) => { ids.add(id) }) } } } return Array.from(ids) } export function buildTree (treeData, nodesData) { const uniqueIds = [] const nodes = [] const links = [] const h = hierarchy(treeData, (node) => { return RELATIONS.reduce((acc, relation) => { if (node[relation]) { node[relation].forEach((item, i) => { item.linkType = relation }) return [...acc, ...node[relation]] } return acc }, []) }) h.each(node => { node.id = node.data.id if (!uniqueIds.includes(node.id)) { uniqueIds.push(node.id) node.data = nodesData.find(n => n.id === node.id) nodes.push(node) if (node.children) { node.children.forEach(child => { const asSource = links.find(link => link.source === node.id && link.target === child.data.id) const asTarget = links.find(link => link.source === child.data.id && link.target === node.id) if (!asSource && !asTarget) { links.push({ source: node.id, target: child.data.id, linkType: child.data.linkType }) } }) } } }) return { nodes, links } }