import * as i0 from '@angular/core';
import { inject, ChangeDetectorRef, input, EventEmitter, ElementRef, Component, Input, Output, ViewChild, NgModule } from '@angular/core';
import * as i1$1 from '@seniorsistemas/angular-components/loading-state';
import { LoadingStateModule } from '@seniorsistemas/angular-components/loading-state';
import { trigger, transition, style, animate, query, stagger } from '@angular/animations';
import { TranslateService, TranslateModule } from '@ngx-translate/core';
import * as i1 from '@angular/forms';
import { FormsModule } from '@angular/forms';
import * as i2 from 'primeng/inputtext';
import { InputTextModule } from 'primeng/inputtext';

class TreeNodeItemComponent {
    cdr = inject(ChangeDetectorRef);
    translateService = inject(TranslateService);
    ariaLevel = input(0);
    showCheckbox = input(false);
    treeNodeItem;
    treeNodeItemClicked = new EventEmitter();
    treeNodeEdit = new EventEmitter();
    nodeExpanded = new EventEmitter();
    nodeCollapsed = new EventEmitter();
    input;
    get hasChildren() {
        return !!(this.treeNodeItem?.children && this.treeNodeItem.children.length > 0);
    }
    get editable() {
        return this.treeNodeItem?.editable || false;
    }
    get ariaLabel() {
        return `${this.translateService.instant('platform.angular_components.select')} ${this.treeNodeItem.label}`;
    }
    expandNode() {
        if (this.hasChildren && !this.treeNodeItem.isExpanded) {
            this.toggleExpanded(this.treeNodeItem);
        }
    }
    collapseNode() {
        if (this.hasChildren && this.treeNodeItem.isExpanded) {
            this.toggleExpanded(this.treeNodeItem);
        }
    }
    onCheckboxEnter(node) {
        const newState = node.checked === true ? false : true;
        node.checked = newState;
        this.treeNodeItemClicked.emit({ item: node, event: new KeyboardEvent('keydown', { key: 'Enter' }) });
    }
    handleTreeNodeItemClick(event, treeNodeItem) {
        const item = treeNodeItem || this.treeNodeItem;
        this.treeNodeItemClicked.emit({ item, event });
    }
    handleTreeNodeItemClicked({ event, item }) {
        if (item.isEditing) {
            return;
        }
        this.handleTreeNodeItemClick(event, item);
    }
    toggleExpanded(treeNodeItem) {
        treeNodeItem.isExpanded = !treeNodeItem.isExpanded;
        if (treeNodeItem.isExpanded) {
            this.nodeExpanded.emit(treeNodeItem);
        }
        else {
            this.nodeCollapsed.emit(treeNodeItem);
        }
    }
    toggleEditing($event) {
        $event.stopPropagation();
        this.treeNodeItem.isEditing = !this.treeNodeItem.isEditing;
        this.cdr.detectChanges();
        if (this.treeNodeItem.isEditing) {
            this.treeNodeItem.editNewValue = this.treeNodeItem.label;
            const input = this.input?.nativeElement;
            input?.focus();
        }
    }
    cancelEdit($event) {
        $event.stopPropagation();
        this.treeNodeItem.isEditing = false;
        this.treeNodeItem.editNewValue = '';
        this.treeNodeItem.editPreviousValue = '';
        this.cdr.detectChanges();
    }
    saveEdit($event) {
        $event.stopPropagation();
        this.treeNodeItem.isEditing = false;
        if (!this.treeNodeItem.editNewValue) {
            return;
        }
        this.treeNodeItem.editPreviousValue = this.treeNodeItem.label;
        this.treeNodeItem.label = this.treeNodeItem.editNewValue;
        const revertAction = () => {
            this.treeNodeItem.label = this.treeNodeItem.editPreviousValue;
            this.treeNodeItem.isEditing = false;
            this.cdr.detectChanges();
        };
        this.treeNodeEdit.emit({
            revertAction,
            item: this.treeNodeItem,
            newValue: this.treeNodeItem.editNewValue,
            previousValue: this.treeNodeItem.editPreviousValue,
        });
    }
    treeNodeEditChildEvent(payload) {
        this.treeNodeEdit.emit(payload);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: TreeNodeItemComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "18.2.14", type: TreeNodeItemComponent, selector: "s-tree-node-item", inputs: { ariaLevel: { classPropertyName: "ariaLevel", publicName: "ariaLevel", isSignal: true, isRequired: false, transformFunction: null }, showCheckbox: { classPropertyName: "showCheckbox", publicName: "showCheckbox", isSignal: true, isRequired: false, transformFunction: null }, treeNodeItem: { classPropertyName: "treeNodeItem", publicName: "treeNodeItem", isSignal: false, isRequired: false, transformFunction: null } }, outputs: { treeNodeItemClicked: "treeNodeItemClicked", treeNodeEdit: "treeNodeEdit", nodeExpanded: "nodeExpanded", nodeCollapsed: "nodeCollapsed" }, viewQueries: [{ propertyName: "input", first: true, predicate: ["input"], descendants: true, read: ElementRef }], ngImport: i0, template: "@if (treeNodeItem) {\n    <div\n        class=\"tree-node-item\"\n        role=\"treeitem\"\n        [class.tree-node-item-selected]=\"treeNodeItem.checked\"\n        [class.selectable]=\"hasChildren\"\n        [attr.aria-expanded]=\"hasChildren ? treeNodeItem.isExpanded : null\"\n        [attr.aria-selected]=\"treeNodeItem.checked === true\"\n        [attr.aria-label]=\"treeNodeItem.label\"\n        [attr.aria-level]=\"ariaLevel()\"\n        tabindex=\"0\"\n        (keydown.enter)=\"handleTreeNodeItemClick($event)\"\n        (keydown.arrowRight)=\"expandNode()\"\n        (keydown.arrowLeft)=\"collapseNode()\"\n    >\n        @if (hasChildren || treeNodeItem.leaf === true) {\n            <div\n                class=\"arrow\"\n                (click)=\"toggleExpanded(treeNodeItem)\"\n            >\n                @if (!treeNodeItem.isExpanded) {\n                    <i [class]=\"treeNodeItem.collapsedIcon || 'fas fa-chevron-right'\"></i>\n                }\n                @if (treeNodeItem.isExpanded) {\n                    <i [class]=\"treeNodeItem.expandedIcon || 'fas fa-chevron-down'\"></i>\n                }\n            </div>\n        }\n\n        <div\n            class=\"tree-node-item-text\"\n            (click)=\"handleTreeNodeItemClick($event)\"\n        >\n            @if (treeNodeItem.icon || treeNodeItem.isEditing) {\n                <span class=\"tree-node-item-text-icon\">\n                    @if (treeNodeItem.icon && !treeNodeItem.isEditing) {\n                        <i [class]=\"treeNodeItem.icon\"></i>\n                    }\n                    @if (treeNodeItem.isEditing) {\n                        <i\n                            class=\"fas fa-edit edit\"\n                            (click)=\"saveEdit($event)\"\n                        ></i>\n                    }\n                </span>\n            }\n\n            @if (showCheckbox() && !treeNodeItem.isEditing) {\n                <span class=\"tree-node-item-text-checkbox\">\n                    <input\n                        type=\"checkbox\"\n                        [checked]=\"treeNodeItem.checked === true\"\n                        [indeterminate]=\"treeNodeItem.checked === null\"\n                        [attr.aria-checked]=\"treeNodeItem.checked === null ? 'mixed' : treeNodeItem.checked\"\n                        [attr.aria-label]=\"ariaLabel\"\n                        role=\"checkbox\"\n                        tabindex=\"0\"\n                        (keydown.enter)=\"onCheckboxEnter(treeNodeItem)\"\n                    />\n                </span>\n            }\n\n            <span class=\"tree-node-item-text-label\">\n                @if (treeNodeItem.isEditing) {\n                    <input\n                        #input\n                        type=\"text\"\n                        pInputText\n                        class=\"tree-node-item-text-input\"\n                        [(ngModel)]=\"treeNodeItem.editNewValue\"\n                        (keydown.enter)=\"saveEdit($event)\"\n                        (keydown.escape)=\"cancelEdit($event)\"\n                        (click)=\"$event.stopPropagation()\"\n                        aria-label=\"Editar nome do item\"\n                        aria-live=\"polite\"\n                    />\n                } @else if (!treeNodeItem.isEditing) {\n                    {{ treeNodeItem.label }}\n                }\n            </span>\n\n            @if (editable) {\n                <span class=\"tree-node-item-text-editable\">\n                    <i\n                        class=\"fas fa-pencil-alt\"\n                        (click)=\"toggleEditing($event)\"\n                        aria-label=\"Editar item\"\n                        tabindex=\"0\"\n                    ></i>\n                </span>\n            }\n        </div>\n    </div>\n}\n\n@if (hasChildren && treeNodeItem.isExpanded) {\n    <div\n        @fadeExpand\n        class=\"child\"\n        role=\"group\"\n        @childrenAnimation\n    >\n        @for (child of treeNodeItem.children; track $index) {\n            <s-tree-node-item\n                [showCheckbox]=\"showCheckbox()\"\n                [treeNodeItem]=\"child\"\n                [ariaLevel]=\"ariaLevel() + 1\"\n                (treeNodeItemClicked)=\"handleTreeNodeItemClicked($event)\"\n                (treeNodeEdit)=\"treeNodeEditChildEvent($event)\"\n                (nodeExpanded)=\"nodeExpanded.emit($event)\"\n                (nodeCollapsed)=\"nodeCollapsed.emit($event)\"\n                class=\"child-item\"\n            />\n        }\n    </div>\n}\n\n", styles: [".tree-node-item{width:100%;display:flex;cursor:pointer}.tree-node-item .arrow{padding:3px 9px;display:flex;align-items:center;justify-content:center}.tree-node-item-text{flex:1;display:flex;padding:3px 0;align-items:center}.tree-node-item-text:hover{background:#f1f7f8}.tree-node-item-text-icon{display:flex;align-items:center;justify-content:center;padding-right:9px}.tree-node-item-text-icon .edit{color:#428bca}.tree-node-item-text-label{color:#212533;font-family:Open Sans;font-size:14px;font-style:normal;font-weight:400;line-height:150%;display:flex;flex:1}.tree-node-item-text-checkbox{padding-right:9px;display:flex}.tree-node-item-text-checkbox input[type=checkbox]{accent-color:#428bca;width:14px;height:14px}.tree-node-item-text-editable{display:flex;align-items:center;justify-content:flex-end}.tree-node-item-text-editable i{padding:9px}.tree-node-item-text-input{flex:1}.tree-node-item.selectable .tree-node-item-text-label{font-family:Open Sans;font-size:14px;font-style:normal;font-weight:700}.tree-node-item.selectable *{cursor:pointer}.tree-node-item-selected .tree-node-item-text{background:#d5e8ec}.child{overflow:hidden;padding-left:2.2em;display:flex;flex-direction:column;gap:5px}.child-item:first-child{padding-top:5px}\n"], dependencies: [{ kind: "directive", type: i1.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i2.InputText, selector: "[pInputText]", inputs: ["variant", "fluid", "pSize"] }, { kind: "component", type: TreeNodeItemComponent, selector: "s-tree-node-item", inputs: ["ariaLevel", "showCheckbox", "treeNodeItem"], outputs: ["treeNodeItemClicked", "treeNodeEdit", "nodeExpanded", "nodeCollapsed"] }], animations: [
            trigger('fadeExpand', [
                transition(':enter', [
                    style({ height: '0px', opacity: 0, overflow: 'hidden' }),
                    animate('200ms ease-out', style({ height: '*', opacity: 1 })),
                ]),
                transition(':leave', [animate('150ms ease-in', style({ height: '0px', opacity: 0 }))]),
            ]),
            trigger('childrenAnimation', [
                transition(':enter', [
                    query(':enter', [
                        style({ opacity: 0, transform: 'translateY(-10px)' }),
                        stagger(60, [animate('200ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))]),
                    ], { optional: true }),
                ]),
            ]),
        ] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: TreeNodeItemComponent, decorators: [{
            type: Component,
            args: [{ selector: 's-tree-node-item', animations: [
                        trigger('fadeExpand', [
                            transition(':enter', [
                                style({ height: '0px', opacity: 0, overflow: 'hidden' }),
                                animate('200ms ease-out', style({ height: '*', opacity: 1 })),
                            ]),
                            transition(':leave', [animate('150ms ease-in', style({ height: '0px', opacity: 0 }))]),
                        ]),
                        trigger('childrenAnimation', [
                            transition(':enter', [
                                query(':enter', [
                                    style({ opacity: 0, transform: 'translateY(-10px)' }),
                                    stagger(60, [animate('200ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))]),
                                ], { optional: true }),
                            ]),
                        ]),
                    ], template: "@if (treeNodeItem) {\n    <div\n        class=\"tree-node-item\"\n        role=\"treeitem\"\n        [class.tree-node-item-selected]=\"treeNodeItem.checked\"\n        [class.selectable]=\"hasChildren\"\n        [attr.aria-expanded]=\"hasChildren ? treeNodeItem.isExpanded : null\"\n        [attr.aria-selected]=\"treeNodeItem.checked === true\"\n        [attr.aria-label]=\"treeNodeItem.label\"\n        [attr.aria-level]=\"ariaLevel()\"\n        tabindex=\"0\"\n        (keydown.enter)=\"handleTreeNodeItemClick($event)\"\n        (keydown.arrowRight)=\"expandNode()\"\n        (keydown.arrowLeft)=\"collapseNode()\"\n    >\n        @if (hasChildren || treeNodeItem.leaf === true) {\n            <div\n                class=\"arrow\"\n                (click)=\"toggleExpanded(treeNodeItem)\"\n            >\n                @if (!treeNodeItem.isExpanded) {\n                    <i [class]=\"treeNodeItem.collapsedIcon || 'fas fa-chevron-right'\"></i>\n                }\n                @if (treeNodeItem.isExpanded) {\n                    <i [class]=\"treeNodeItem.expandedIcon || 'fas fa-chevron-down'\"></i>\n                }\n            </div>\n        }\n\n        <div\n            class=\"tree-node-item-text\"\n            (click)=\"handleTreeNodeItemClick($event)\"\n        >\n            @if (treeNodeItem.icon || treeNodeItem.isEditing) {\n                <span class=\"tree-node-item-text-icon\">\n                    @if (treeNodeItem.icon && !treeNodeItem.isEditing) {\n                        <i [class]=\"treeNodeItem.icon\"></i>\n                    }\n                    @if (treeNodeItem.isEditing) {\n                        <i\n                            class=\"fas fa-edit edit\"\n                            (click)=\"saveEdit($event)\"\n                        ></i>\n                    }\n                </span>\n            }\n\n            @if (showCheckbox() && !treeNodeItem.isEditing) {\n                <span class=\"tree-node-item-text-checkbox\">\n                    <input\n                        type=\"checkbox\"\n                        [checked]=\"treeNodeItem.checked === true\"\n                        [indeterminate]=\"treeNodeItem.checked === null\"\n                        [attr.aria-checked]=\"treeNodeItem.checked === null ? 'mixed' : treeNodeItem.checked\"\n                        [attr.aria-label]=\"ariaLabel\"\n                        role=\"checkbox\"\n                        tabindex=\"0\"\n                        (keydown.enter)=\"onCheckboxEnter(treeNodeItem)\"\n                    />\n                </span>\n            }\n\n            <span class=\"tree-node-item-text-label\">\n                @if (treeNodeItem.isEditing) {\n                    <input\n                        #input\n                        type=\"text\"\n                        pInputText\n                        class=\"tree-node-item-text-input\"\n                        [(ngModel)]=\"treeNodeItem.editNewValue\"\n                        (keydown.enter)=\"saveEdit($event)\"\n                        (keydown.escape)=\"cancelEdit($event)\"\n                        (click)=\"$event.stopPropagation()\"\n                        aria-label=\"Editar nome do item\"\n                        aria-live=\"polite\"\n                    />\n                } @else if (!treeNodeItem.isEditing) {\n                    {{ treeNodeItem.label }}\n                }\n            </span>\n\n            @if (editable) {\n                <span class=\"tree-node-item-text-editable\">\n                    <i\n                        class=\"fas fa-pencil-alt\"\n                        (click)=\"toggleEditing($event)\"\n                        aria-label=\"Editar item\"\n                        tabindex=\"0\"\n                    ></i>\n                </span>\n            }\n        </div>\n    </div>\n}\n\n@if (hasChildren && treeNodeItem.isExpanded) {\n    <div\n        @fadeExpand\n        class=\"child\"\n        role=\"group\"\n        @childrenAnimation\n    >\n        @for (child of treeNodeItem.children; track $index) {\n            <s-tree-node-item\n                [showCheckbox]=\"showCheckbox()\"\n                [treeNodeItem]=\"child\"\n                [ariaLevel]=\"ariaLevel() + 1\"\n                (treeNodeItemClicked)=\"handleTreeNodeItemClicked($event)\"\n                (treeNodeEdit)=\"treeNodeEditChildEvent($event)\"\n                (nodeExpanded)=\"nodeExpanded.emit($event)\"\n                (nodeCollapsed)=\"nodeCollapsed.emit($event)\"\n                class=\"child-item\"\n            />\n        }\n    </div>\n}\n\n", styles: [".tree-node-item{width:100%;display:flex;cursor:pointer}.tree-node-item .arrow{padding:3px 9px;display:flex;align-items:center;justify-content:center}.tree-node-item-text{flex:1;display:flex;padding:3px 0;align-items:center}.tree-node-item-text:hover{background:#f1f7f8}.tree-node-item-text-icon{display:flex;align-items:center;justify-content:center;padding-right:9px}.tree-node-item-text-icon .edit{color:#428bca}.tree-node-item-text-label{color:#212533;font-family:Open Sans;font-size:14px;font-style:normal;font-weight:400;line-height:150%;display:flex;flex:1}.tree-node-item-text-checkbox{padding-right:9px;display:flex}.tree-node-item-text-checkbox input[type=checkbox]{accent-color:#428bca;width:14px;height:14px}.tree-node-item-text-editable{display:flex;align-items:center;justify-content:flex-end}.tree-node-item-text-editable i{padding:9px}.tree-node-item-text-input{flex:1}.tree-node-item.selectable .tree-node-item-text-label{font-family:Open Sans;font-size:14px;font-style:normal;font-weight:700}.tree-node-item.selectable *{cursor:pointer}.tree-node-item-selected .tree-node-item-text{background:#d5e8ec}.child{overflow:hidden;padding-left:2.2em;display:flex;flex-direction:column;gap:5px}.child-item:first-child{padding-top:5px}\n"] }]
        }], propDecorators: { treeNodeItem: [{
                type: Input
            }], treeNodeItemClicked: [{
                type: Output
            }], treeNodeEdit: [{
                type: Output
            }], nodeExpanded: [{
                type: Output
            }], nodeCollapsed: [{
                type: Output
            }], input: [{
                type: ViewChild,
                args: ['input', { read: ElementRef }]
            }] } });

/**
 * @description Componente de árvore hierárquica com suporte a seleção única ou múltipla,
 * checkboxes, noós expansíveis e edição inline de rótulos. Gerencia o estado interno
 * dos nós e emite eventos na seleção, expansão, colapso e edição.
 *
 * @example
 * ```html
 * <s-tree
 *   [treeData]="nos"
 *   selectionMode="multiple"
 *   [showCheckbox]="true"
 *   (selectedChange)="onSelecaoMudou($event)" />
 * ```
 *
 * @category Data
 */
class TreeComponent {
    /** @description Lista de nós raíz da árvore. @default [] */
    treeData = [];
    _selected = [];
    /** @description Nó(s) selecionado(s). Suporta array ou item único dependendo de `selectionMode`. @default [] */
    get selected() {
        return this._selected;
    }
    set selected(value) {
        if (!value) {
            value = [];
        }
        if (!Array.isArray(value)) {
            value = [value];
        }
        this._selected = value;
    }
    /** @description Exibe indicador de carregamento nos nós. @default false */
    loading = false;
    /** @description Modo de seleção: `'single'` ou `'multiple'`. @default 'single' */
    selectionMode = 'single';
    /** @description Exibe checkboxes nos nós para seleção visual. @default false */
    showCheckbox = false;
    /** @description Expão todos os nós inicialmente. @default false */
    allExpanded = false;
    /** @description Emitido quando a seleção muda, com o(s) nó(s) selecionado(s). */
    selectedChange = new EventEmitter();
    /** @description Emitido quando o usuário clica em um nó da árvore. */
    treeNodeItemClicked = new EventEmitter();
    /** @description Emitido após uma edição inline de rótulo de nó. */
    treeNodeEdit = new EventEmitter();
    /** @description Emitido quando um nó é expandido pelo usuário. */
    nodeExpanded = new EventEmitter();
    /** @description Emitido quando um nó é colapsado pelo usuário. */
    nodeCollapsed = new EventEmitter();
    ngOnChanges(changes) {
        this.onChanges(changes);
    }
    onTreeNodeItemClicked({ item }) {
        this.treeNodeItemClicked.emit(parseInternalTreeNodeItem(item));
        this.toggleChecked(item);
    }
    onTreeNodeEdit(payload) {
        const { revertAction, item, newValue, previousValue } = payload;
        this.treeNodeEdit.emit({
            revertAction,
            item: parseInternalTreeNodeItem(item),
            newValue,
            previousValue,
        });
    }
    onNodeExpanded(item) {
        this.nodeExpanded.emit(parseInternalTreeNodeItem(item));
    }
    onNodeCollapsed(item) {
        this.nodeCollapsed.emit(parseInternalTreeNodeItem(item));
    }
    toggleChecked(treeNodeItem) {
        const elementCheckState = !treeNodeItem.checked;
        if (!this.multiple) {
            flattenTree(this.treeData).forEach((x) => (x.checked = false));
            this.selected = [treeNodeItem];
        }
        treeNodeItem.checked = elementCheckState;
        if (this.multiple) {
            this.checkTreeDataChildren(treeNodeItem);
        }
        this.setSelected();
    }
    checkTreeDataChildren(selectedTreeNode) {
        const parentChecked = selectedTreeNode.checked;
        if (selectedTreeNode.children) {
            selectedTreeNode.children.forEach((item) => {
                const childrens = flattenTree(item.children || []);
                item.checked = parentChecked;
                childrens.forEach((child) => (child.checked = parentChecked));
            });
        }
        const getNodeChildrenSummary = (node) => {
            const children = node.children ?? [];
            const allChildrenChecked = children.every((y) => y.checked === true);
            const someChildrenChecked = children.some((y) => y.checked === true || y.checked === null);
            const allChildrenUnchecked = children.every((y) => y.checked === false || y.checked === undefined);
            return { allChildrenChecked, someChildrenChecked, allChildrenUnchecked };
        };
        const updateCheckedStateRecursively = (node) => {
            if (!node.children?.length)
                return;
            node.children.forEach(updateCheckedStateRecursively);
            const { allChildrenChecked, someChildrenChecked, allChildrenUnchecked } = getNodeChildrenSummary(node);
            if (allChildrenChecked) {
                node.checked = true;
            }
            else if (someChildrenChecked) {
                node.checked = null;
            }
            else if (allChildrenUnchecked) {
                node.checked = false;
            }
        };
        this.treeData.forEach(updateCheckedStateRecursively);
    }
    setSelected() {
        const selected = this.selectedElements;
        this.selected = [...selected];
        this.selectedChange.emit(selected);
    }
    onChanges(changes) {
        const allExpandedChanges = changes['allExpanded'];
        const _checkIsFirstChangeWithValue = (value) => {
            if (!changes[value]) {
                return;
            }
            return ((!changes[value].previousValue || changes[value].previousValue.length === 0) &&
                changes[value].currentValue?.length > 0);
        };
        if (_checkIsFirstChangeWithValue('selected')) {
            this.syncSelectedChanges();
        }
        if (_checkIsFirstChangeWithValue('treeData')) {
            const isAllExpanded = this.allExpanded;
            if (isAllExpanded) {
                this.expandAll();
            }
        }
        if (allExpandedChanges) {
            if (this.allExpanded) {
                this.expandAll();
            }
            else {
                this.collapseAll();
            }
        }
    }
    syncSelectedChanges() {
        const treeFlatten = flattenTree(this.treeData);
        this.selected.forEach((selectedItem) => {
            const item = treeFlatten.find((item) => item.id === selectedItem.id);
            if (item) {
                item.checked = true;
            }
            if (item && item.children && this.multiple) {
                item.children.forEach((child) => {
                    child.checked = true;
                    const existChildInSelectedList = this.selected.some((item) => item.id === child.id);
                    if (!existChildInSelectedList) {
                        this.selected.push(child);
                    }
                });
            }
        });
        const selectedElements = this.selectedElements;
        const selectedElementsNotInSelectedList = selectedElements.filter((x) => !this.selected.some((y) => y.id === x.id));
        selectedElementsNotInSelectedList.forEach((item) => {
            this.checkTreeDataChildren(item);
        });
        this.setSelected();
    }
    collapseAll() {
        const flatten = flattenTree(this.treeData);
        flatten.forEach((item) => {
            item.isExpanded = false;
        });
    }
    expandAll() {
        const flatten = flattenTree(this.treeData);
        flatten.forEach((item) => {
            item.isExpanded = true;
        });
    }
    get selectedElements() {
        return flattenTree(this.treeData)
            .filter((x) => x.checked)
            .filter((x) => x.leaf !== true && !x.children?.length);
    }
    get multiple() {
        return this.selectionMode === 'multiple';
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: TreeComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "18.2.14", type: TreeComponent, selector: "s-tree", inputs: { treeData: "treeData", selected: "selected", loading: "loading", selectionMode: "selectionMode", showCheckbox: "showCheckbox", allExpanded: "allExpanded" }, outputs: { selectedChange: "selectedChange", treeNodeItemClicked: "treeNodeItemClicked", treeNodeEdit: "treeNodeEdit", nodeExpanded: "nodeExpanded", nodeCollapsed: "nodeCollapsed" }, usesOnChanges: true, ngImport: i0, template: "<div class=\"tree\" *sLoadingState=\"loading\">\n    @for(item of treeData; track $index) {\n        <s-tree-node-item\n            [showCheckbox]=\"showCheckbox\"\n            [treeNodeItem]=\"item\"\n            (nodeExpanded)=\"onNodeExpanded($event)\"\n            (nodeCollapsed)=\"onNodeCollapsed($event)\"\n            (treeNodeEdit)=\"onTreeNodeEdit($event)\"\n            (treeNodeItemClicked)=\"onTreeNodeItemClicked($event)\">\n        </s-tree-node-item>\n\n    }\n</div>\n", styles: [".tree{display:flex;flex-direction:column;gap:5px;border:1px solid #dddddd;border-radius:4px;padding:15px;margin:15px}\n"], dependencies: [{ kind: "directive", type: i1$1.LoadingStateDirective, selector: "[sLoadingState]", inputs: ["sLoadingState"] }, { kind: "component", type: TreeNodeItemComponent, selector: "s-tree-node-item", inputs: ["ariaLevel", "showCheckbox", "treeNodeItem"], outputs: ["treeNodeItemClicked", "treeNodeEdit", "nodeExpanded", "nodeCollapsed"] }] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: TreeComponent, decorators: [{
            type: Component,
            args: [{ selector: 's-tree', template: "<div class=\"tree\" *sLoadingState=\"loading\">\n    @for(item of treeData; track $index) {\n        <s-tree-node-item\n            [showCheckbox]=\"showCheckbox\"\n            [treeNodeItem]=\"item\"\n            (nodeExpanded)=\"onNodeExpanded($event)\"\n            (nodeCollapsed)=\"onNodeCollapsed($event)\"\n            (treeNodeEdit)=\"onTreeNodeEdit($event)\"\n            (treeNodeItemClicked)=\"onTreeNodeItemClicked($event)\">\n        </s-tree-node-item>\n\n    }\n</div>\n", styles: [".tree{display:flex;flex-direction:column;gap:5px;border:1px solid #dddddd;border-radius:4px;padding:15px;margin:15px}\n"] }]
        }], propDecorators: { treeData: [{
                type: Input
            }], selected: [{
                type: Input
            }], loading: [{
                type: Input
            }], selectionMode: [{
                type: Input
            }], showCheckbox: [{
                type: Input
            }], allExpanded: [{
                type: Input
            }], selectedChange: [{
                type: Output
            }], treeNodeItemClicked: [{
                type: Output
            }], treeNodeEdit: [{
                type: Output
            }], nodeExpanded: [{
                type: Output
            }], nodeCollapsed: [{
                type: Output
            }] } });
const flattenTree = (tree) => {
    const result = [];
    function traverse(nodes) {
        for (const node of nodes) {
            result.push(node);
            if (node.children && node.children.length) {
                traverse(node.children);
            }
        }
    }
    traverse(tree);
    return result;
};
const parseInternalTreeNodeItem = (internalTreeNodeItem) => {
    const { id, label, icon, checked, isExpanded, payload, editable, children } = internalTreeNodeItem;
    const object = {
        id,
        label,
        icon,
        checked,
        isExpanded,
        payload,
        editable,
        _children: children?.map(parseInternalTreeNodeItem),
        get children() {
            return this._children;
        },
        set children(value) {
            this._children = value;
            internalTreeNodeItem.children = value;
        },
    };
    Object.defineProperty(object, '_children', {
        enumerable: false,
    });
    return object;
};

class TreeModule {
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: TreeModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
    static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: TreeModule, declarations: [TreeComponent, TreeNodeItemComponent], imports: [FormsModule, InputTextModule, LoadingStateModule, TranslateModule], exports: [TreeComponent] });
    static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: TreeModule, imports: [FormsModule, InputTextModule, LoadingStateModule, TranslateModule] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: TreeModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [TreeComponent, TreeNodeItemComponent],
                    imports: [FormsModule, InputTextModule, LoadingStateModule, TranslateModule],
                    exports: [TreeComponent],
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { TreeComponent, TreeModule };
//# sourceMappingURL=seniorsistemas-angular-components-tree.mjs.map
