// #region Imports
import { directive, PartType } from 'lit/directive.js';
import { DirectiveBase } from '../Abstracts/DirectiveBase';
/**
 * Generic recursive rendering directive for tree structures.
 *
 * @private
 */
class TreeDirective extends DirectiveBase {
    // #region Ctor
    constructor(args) {
        super(args);
        if (args.type !== PartType.CHILD) {
            throw new Error('The "tree" directive can only be used in child parts');
        }
    }
    // #endregion
    // #region Methods
    /**
     * @public
     */
    render(root, childSelector, renderParent, renderChild, options = {}) {
        return this.renderNode(root, childSelector, renderParent, renderChild, options);
    }
    /**
     * @public
     */
    update(_part, [root, childSelector, renderParent, renderChild, options]) {
        return this.render(root, childSelector, renderParent, renderChild, options ?? {});
    }
    /**
     * @private
     */
    renderNode(node, childSelector, renderParent, renderChild, options) {
        // Apply filter early
        if (options.filter && !options.filter(node)) {
            return null;
        }
        // Fetch & optionally transform children
        let children = childSelector(node) ?? [];
        if (options.filter) {
            children = children.filter(options.filter);
        }
        if (options.sort) {
            children = [...children].sort(options.sort);
        }
        // Render based on presence of children
        if (children.length > 0) {
            const renderedChildren = children.map((child) => this.renderNode(child, childSelector, renderParent, renderChild, options));
            return renderParent(node, renderedChildren);
        }
        return renderChild(node);
    }
}
/**
 * Renders recursive tree-like structures with optional filtering and sorting.
 *
 * @public
 * @param root - Root node to start recursion.
 * @param childSelector - Function to extract children from each node.
 * @param renderParent - Template for nodes with children.
 * @param renderChild - Template for leaf nodes.
 * @param options - Optional filter and sort logic.
 */
export const tree = directive(TreeDirective);
//# sourceMappingURL=TreeDirective.js.map