import type { FloatingNodeType } from "../types"; /** * Tree walks over a flat `FloatingNodeType[]` list, each node storing * its `parentId`. Ported 1:1 from the React source; no reactivity in * play here. */ export function getNodeChildren( nodes: Array, id: string | undefined, onlyOpenChildren = true, ): Array { const directChildren = nodes.filter((node) => node.parentId === id); return directChildren.flatMap((child) => [ ...(!onlyOpenChildren || child.context?.open ? [child] : []), ...getNodeChildren(nodes, child.id, onlyOpenChildren), ]); } export function getDeepestNode( nodes: Array, id: string | undefined, ): FloatingNodeType | undefined { let deepestNodeId: string | undefined; let maxDepth = -1; function findDeepest(nodeId: string | undefined, depth: number) { if (depth > maxDepth) { deepestNodeId = nodeId; maxDepth = depth; } const children = getNodeChildren(nodes, nodeId); children.forEach((child) => { findDeepest(child.id, depth + 1); }); } findDeepest(id, 0); return nodes.find((node) => node.id === deepestNodeId); } export function getNodeAncestors( nodes: Array, id: string | undefined, ): Array { let allAncestors: Array = []; let currentParentId = nodes.find((node) => node.id === id)?.parentId; while (currentParentId) { const currentNode = nodes.find((node) => node.id === currentParentId); currentParentId = currentNode?.parentId; if (currentNode) { allAncestors = allAncestors.concat(currentNode); } } return allAncestors; }