import { useMemo } from "react";
/**
 * This util performantly builds a nested list of tree items from a giant flat
 * list of items by linking items together with the provided `parentId`. This
 * will also recursively build the tree and _hopefully_ all items will be added.
 *
 * @since 6.0.0 Updated to include the {@link TreeItemChildIds}
 */ export function buildTree(options) {
    const { sort, nodes, parentId, treeItemChildIds } = options;
    const childIds = treeItemChildIds.get(parentId) || new Set();
    const childItems = [];
    // doing a "reverse" order filter/move so that the items array shrinks while
    // looping. This makes it so that the entire items array doesn't need to
    // continually be looped through as more items are added to the tree, only the
    // remaining items will have to be looped
    let i = nodes.length;
    while(i > 0){
        i -= 1;
        if (nodes[i] && nodes[i].parentId === parentId) {
            const [item] = nodes.splice(i, 1);
            childIds.add(item.itemId);
            // shallow cloning so childItems doesn't get applied to the original data
            // set
            childItems.unshift({
                ...item
            });
        }
    }
    if (!childItems.length) {
        return undefined;
    }
    treeItemChildIds.set(parentId, childIds);
    childItems.forEach((childItem)=>{
        childItem.items = buildTree({
            sort,
            nodes,
            parentId: childItem.itemId,
            treeItemChildIds
        });
    });
    return sort(childItems);
}
/**
 * This is mostly an internal hook, but can be used to build tree-like
 * data structures without the need of the `Tree` component.
 *
 * @see {@link https://react-md.dev/components/tree | Tree Demos}
 * @since 6.0.0 converted to use an object argument instead of
 * multiple arguments. Also logs any orphaned items that do not have a parent
 */ export function useTreeItems(options) {
    const { data, sort, rootId } = options;
    return useMemo(()=>{
        const values = Object.values(data);
        const treeItemChildIds = new Map();
        const items = buildTree({
            sort,
            nodes: values,
            parentId: rootId,
            treeItemChildIds
        });
        if (process.env.NODE_ENV !== "production" && values.length) {
            /* eslint-disable no-console */ console.warn("The following tree items are orphaned without a parent:");
            console.warn(values.slice());
        }
        return {
            items: items || [],
            treeItemChildIds
        };
    }, [
        data,
        rootId,
        sort
    ]);
}

//# sourceMappingURL=useTreeItems.js.map