"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flattenTree = flattenTree;
exports.buildTree = buildTree;
exports.getDragDepth = getDragDepth;
exports.getProjection = getProjection;
exports.getDescendants = getDescendants;
function flattenTree(items, parentId = null, depth = 0) {
    return items.reduce((acc, item, index) => {
        return [
            ...acc,
            { ...item, parentId, depth, index },
            ...flattenTree(item.children, item.id, depth + 1),
        ];
    }, []);
}
function buildTree(flattenedItems) {
    const root = { id: 'root', block: {}, children: [] };
    const nodes = { [root.id]: root };
    const items = flattenedItems.map((item) => {
        return { ...item, children: [] };
    });
    for (const item of items) {
        const { id } = item;
        const parentId = item.parentId ?? root.id;
        const parent = nodes[parentId] ?? items.find((x) => x.id === parentId);
        if (!parent) {
            continue;
        }
        const node = { ...item, children: [] };
        nodes[id] = node;
        parent.children.push(node);
    }
    return root.children;
}
function getDragDepth(offset, indentationWidth) {
    return Math.round(offset / indentationWidth);
}
function getProjection(items, targetId, projectedDepth) {
    const targetItemIndex = items.findIndex(({ id }) => id === targetId);
    const previousItem = items[targetItemIndex - 1];
    const targetItem = items[targetItemIndex];
    const nextItem = items[targetItemIndex + 1];
    const maxDepth = getMaxDepth(targetItem, previousItem);
    const minDepth = getMinDepth(nextItem);
    let depth = projectedDepth;
    if (projectedDepth >= maxDepth) {
        depth = maxDepth;
    }
    else if (projectedDepth < minDepth) {
        depth = minDepth;
    }
    return { depth, maxDepth, minDepth, parentId: getParentId() };
    function getParentId() {
        if (depth === 0 || !previousItem) {
            return null;
        }
        if (depth === previousItem.depth) {
            return previousItem.parentId;
        }
        if (depth > previousItem.depth) {
            return previousItem.id;
        }
        const newParent = items
            .slice(0, targetItemIndex)
            .reverse()
            .find((item) => item.depth === depth)?.parentId;
        return newParent ?? null;
    }
}
function getMaxDepth(targetItem, previousItem) {
    if (!previousItem) {
        return 0;
    }
    return Math.min(targetItem.depth + 1, previousItem.depth + 1);
}
function getMinDepth(nextItem) {
    return nextItem ? nextItem.depth : 0;
}
function getDescendants(items, parentId) {
    const directChildren = items.filter((item) => item.parentId === parentId);
    return directChildren.reduce((descendants, child) => {
        return new Set([...descendants, child.id, ...getDescendants(items, child.id)]);
    }, new Set());
}
//# sourceMappingURL=common.js.map
