'use strict';

var index = require('./index-n_pDKBY2.js');

const treeViewItemCss = ".tree-item{position:relative;cursor:pointer;list-style:none}.tree-item.tree-item--expanded{position:relative}.tree-item.tree-item--has-children{position:relative}.tree-item.tree-item--has-children .tree-item__header>.tree-item__chevron-container{display:flex}.tree-item.tree-item--has-children.tree-item--expanded .tree-item__header>.tree-item__chevron-container::after{display:block}.tree-item--disabled{cursor:not-allowed;pointer-events:none;color:#BFBBBB}.tree-item__content{display:flex;flex-direction:row}.tree-item__content:hover .tree-item__checkbox-container,.tree-item__content:hover .tree-item__header{background-color:#F7F7F7}.tree-item__checkbox-container{position:sticky;left:0;z-index:10;padding:4px;background-color:#FFFFFF}.tree-item__header{flex-grow:1;display:flex;align-items:center;white-space:nowrap;height:20px;padding-top:4px;padding-right:16px;padding-bottom:4px;padding-left:8px}.tree-item__chevron-container{display:none;align-items:center;margin-right:8px;height:20px}.tree-item__chevron-container::after{--height-line-start:28px;display:none;content:\"\";position:absolute;z-index:1;top:var(--height-line-start);left:auto;margin-left:8px;width:1px;height:calc(100% - var(--height-line-start));background-color:#EEEDED}.tree-item--disabled .tree-item__chevron-container::after{color:#EEEDED}.tree-item__chevron.chevron-down{transform:rotate(90deg)}.tree-item__chevron.chevron-right{transform:rotate(0)}.tree-item__label-icon-container{display:flex;align-items:center}.tree-item__label-icon-container:focus{outline:none}.tree-item__label-icon-container:focus-visible{outline:2px solid #0A8276;outline-offset:2px;border-radius:1px}.tree-item__icon-container{position:relative;width:16px;height:16px}.tree-item__icon-container ifx-icon{position:absolute;left:0;top:0;opacity:1;transition:opacity 0.2s ease-in-out}.tree-item__icon-container ifx-icon.icon--hidden{opacity:0}.tree-item__label{padding-left:8px}.tree-item__children{display:none}.tree-item[aria-expanded=true]>.tree-item__children{display:block}";

const TreeViewItem = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.ifxTreeViewItemExpandChange = index.createEvent(this, "ifxTreeViewItemExpandChange", 7);
        this.ifxTreeViewItemCheckChange = index.createEvent(this, "ifxTreeViewItemCheckChange", 7);
        this.ifxTreeViewItemDisableChange = index.createEvent(this, "ifxTreeViewItemDisableChange", 7);
        this.expanded = false;
        this.initiallyExpanded = false;
        this.disableItem = false;
        this.initiallySelected = false;
        this.hasChildren = false;
        this.isChecked = false;
        this.partialChecked = false;
        this.level = 0;
        this.disableAllItems = false;
        this.expandAllItems = false;
        this.suppressExpandEvents = false;
        this.findChildren = () => Array.from(this.host.children)
            .filter((child) => child instanceof HTMLElement && child.tagName === 'IFX-TREE-VIEW-ITEM');
        this.calculateNodeLevel = () => {
            let level = 0, parent = this.host.parentElement;
            while (parent) {
                if (parent.tagName === 'IFX-TREE-VIEW-ITEM')
                    level++;
                parent = parent.parentElement;
            }
            return level;
        };
        this.handleStateChange = (event) => {
            if (this.disabled)
                return;
            event.stopPropagation();
            this.updateCheckState(event.detail.checked);
        };
        this.handleCheckboxChange = (event) => {
            var _a, _b;
            if (this.disabled)
                return;
            this.updateCheckState((_b = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.checked) !== null && _b !== void 0 ? _b : !this.isChecked);
        };
        this.handleHeaderClick = ({ target }) => {
            if (this.disabled)
                return;
            if (!target.closest('.tree-item__checkbox-container, .tree-item__chevron-container')) {
                if (this.hasChildren) {
                    const newCheckedState = !this.isChecked;
                    this.updateCheckState(newCheckedState);
                    const affectedItems = newCheckedState
                        ? this.expandOrCollapseAllDescendants(true)
                        : this.expandOrCollapseAllDescendants(false);
                    this.ifxTreeViewItemExpandChange.emit({
                        expanded: newCheckedState,
                        affectedItems,
                        component: this
                    });
                }
                else {
                    this.updateCheckState(!this.isChecked);
                }
            }
        };
        this.toggleExpand = () => {
            if (this.disabled || !this.hasChildren)
                return;
            this.expanded = !this.expanded;
        };
        this.handleKeyDown = (event) => {
            var _a, _b, _c, _d, _e, _f;
            const allItems = Array.from(((_a = this.host.closest('ifx-tree-view')) === null || _a === void 0 ? void 0 : _a.querySelectorAll('ifx-tree-view-item')) || []);
            const visibleItems = allItems.filter(item => {
                var _a, _b;
                let parent = (_a = item.parentElement) === null || _a === void 0 ? void 0 : _a.closest('ifx-tree-view-item');
                while (parent) {
                    const parentCmp = parent;
                    if (!(parentCmp.expandAllItems || parentCmp.expanded))
                        return false;
                    parent = (_b = parent.parentElement) === null || _b === void 0 ? void 0 : _b.closest('ifx-tree-view-item');
                }
                return true;
            });
            const currentIndex = visibleItems.findIndex(el => el === this.host);
            const focusLabelIcon = (el) => el === null || el === void 0 ? void 0 : el.focus();
            switch (event.key) {
                case 'ArrowDown': {
                    event.preventDefault();
                    for (let i = currentIndex + 1; i < visibleItems.length; i++) {
                        const next = visibleItems[i];
                        if (!next.disabled) {
                            focusLabelIcon((_b = next.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector('.tree-item__label-icon-container'));
                            break;
                        }
                    }
                    break;
                }
                case 'ArrowUp': {
                    event.preventDefault();
                    for (let i = currentIndex - 1; i >= 0; i--) {
                        const prev = visibleItems[i];
                        if (!prev.disabled) {
                            focusLabelIcon((_c = prev.shadowRoot) === null || _c === void 0 ? void 0 : _c.querySelector('.tree-item__label-icon-container'));
                            break;
                        }
                    }
                    break;
                }
                case 'ArrowRight': {
                    event.preventDefault();
                    if (!this.isExpanded && this.hasChildren) {
                        this.expanded = true;
                    }
                    else if (this.isExpanded && this.hasChildren) {
                        const firstChild = this.host.querySelector('ifx-tree-view-item');
                        if (firstChild && !firstChild.disabled) {
                            focusLabelIcon((_d = firstChild.shadowRoot) === null || _d === void 0 ? void 0 : _d.querySelector('.tree-item__label-icon-container'));
                        }
                    }
                    break;
                }
                case 'ArrowLeft': {
                    event.preventDefault();
                    if (this.isExpanded && this.hasChildren) {
                        this.expanded = false;
                    }
                    else {
                        const parent = (_e = this.host.parentElement) === null || _e === void 0 ? void 0 : _e.closest('ifx-tree-view-item');
                        if (parent && !parent.disabled) {
                            focusLabelIcon((_f = parent.shadowRoot) === null || _f === void 0 ? void 0 : _f.querySelector('.tree-item__label-icon-container'));
                        }
                    }
                    break;
                }
                case ' ':
                case 'Enter': {
                    event.preventDefault();
                    if (this.hasChildren) {
                        const newCheckedState = !this.isChecked;
                        this.updateCheckState(newCheckedState);
                        const affectedItems = newCheckedState
                            ? this.expandOrCollapseAllDescendants(true)
                            : this.expandOrCollapseAllDescendants(false);
                        this.ifxTreeViewItemExpandChange.emit({
                            expanded: newCheckedState,
                            affectedItems,
                            component: this
                        });
                    }
                    else {
                        this.updateCheckState(!this.isChecked);
                    }
                    break;
                }
            }
        };
    }
    get disabled() {
        return this.disableAllItems || this.disableItem;
    }
    get isExpanded() {
        return this.expandAllItems || this.expanded;
    }
    componentWillLoad() {
        this.expanded = this.initiallyExpanded;
        this.hasChildren = this.findChildren().length > 0;
        this.level = this.calculateNodeLevel();
        this.host.setAttribute('data-level', this.level.toString());
        this.isChecked = this.initiallySelected;
        this.host.addEventListener('internal-check-state-change', this.handleStateChange);
    }
    componentDidLoad() {
        this.observeParentAttribute('disable-all-items', val => this.disableAllItems = val);
        this.observeParentAttribute('data-expand-all-items', val => this.expandAllItems = val, true);
        if (this.shouldExpandFromParent())
            this.expandAllDescendants();
        this.host['__stencil_instance'] = this;
        if (this.initiallySelected)
            setTimeout(() => this.updateParentState(), 0);
    }
    observeParentAttribute(attr, cb, breakOnAttr = false) {
        let parent = this.host.parentElement;
        while (parent) {
            if (parent.tagName === 'IFX-TREE-VIEW' || (breakOnAttr && parent.hasAttribute(attr))) {
                const observer = new MutationObserver(() => cb(parent.hasAttribute(attr)));
                observer.observe(parent, { attributes: true });
                cb(parent.hasAttribute(attr));
                break;
            }
            parent = parent.parentElement;
        }
    }
    shouldExpandFromParent() {
        let parent = this.host.parentElement;
        while (parent) {
            if (parent.tagName === 'IFX-TREE-VIEW' &&
                (parent.hasAttribute('expand-all-items') || parent.hasAttribute('data-expand-all-items')))
                return true;
            parent = parent.parentElement;
        }
        return false;
    }
    expandAllDescendants() {
        this.expanded = true;
        this.findChildren().forEach(child => {
            var _a, _b;
            child.expanded = true;
            (_b = (_a = child).expandAllDescendants) === null || _b === void 0 ? void 0 : _b.call(_a);
        });
    }
    expandOrCollapseAllDescendants(expand) {
        this.suppressExpandEvents = true;
        const affectedItems = [];
        this.expanded = expand;
        if (this.hasChildren)
            affectedItems.push({ expanded: expand, value: this.value });
        this.findChildren().forEach(child => {
            const childInstance = child['__stencil_instance'];
            if (childInstance && childInstance.hasChildren) {
                childInstance.suppressExpandEvents = true;
                childInstance.expanded = expand;
                affectedItems.push({ expanded: expand, value: childInstance.value });
                if (childInstance.hasChildren) {
                    const childAffected = childInstance.expandOrCollapseAllDescendants(expand);
                    affectedItems.push(...childAffected);
                }
            }
        });
        this.suppressExpandEvents = false;
        return affectedItems;
    }
    async updateCheckState(checked, fromParent = false) {
        if (this.disabled)
            return;
        if (!fromParent && this.hasChildren) {
            const affected = this.collectDescendantStates(checked);
            this.setNodeState({ isChecked: checked, partialChecked: false }, false);
            await this.updateChildrenSilently(checked);
            this.ifxTreeViewItemCheckChange.emit({
                checked,
                indeterminate: false,
                value: this.value,
                affectedChildItems: affected,
                component: this,
            });
            this.updateParentState();
        }
        else if (fromParent) {
            this.setNodeState({ isChecked: checked, partialChecked: false }, false);
        }
        else {
            this.setNodeState({ isChecked: checked, partialChecked: false });
            await this.updateChildrenState(checked);
            this.updateParentState();
        }
    }
    async updateChildrenSilently(checked) {
        for (const child of this.findChildren()) {
            const childInstance = child['__stencil_instance'];
            if (childInstance && !childInstance.disabled) {
                childInstance.setNodeState({ isChecked: checked, partialChecked: false }, false);
                await childInstance.updateChildrenSilently(checked);
            }
        }
    }
    handleExpandedChange(newValue) {
        if (!this.suppressExpandEvents) {
            this.ifxTreeViewItemExpandChange.emit({
                expanded: newValue,
                value: this.value,
                affectedItems: [{ expanded: newValue, value: this.value }],
                component: this
            });
        }
    }
    handleDisableItemChange(newValue) {
        this.ifxTreeViewItemDisableChange.emit({ disabled: newValue, component: this });
    }
    setNodeState(state, emitEvent = true) {
        this.isChecked = state.isChecked;
        this.partialChecked = state.partialChecked;
        if (emitEvent) {
            this.ifxTreeViewItemCheckChange.emit({
                checked: this.isChecked,
                indeterminate: this.partialChecked,
                value: this.value,
                level: this.level,
                disabled: this.disabled,
                component: this
            });
        }
    }
    collectDescendantStates(checked) {
        const descendants = [];
        const collect = (el, skipSelf = false) => {
            let instance = el === this.host ? this : el['__stencil_instance'];
            if (!skipSelf && !(instance === null || instance === void 0 ? void 0 : instance.disabled)) {
                descendants.push({
                    checked,
                    indeterminate: false,
                    value: instance === null || instance === void 0 ? void 0 : instance.value,
                });
            }
            Array.from(el.children)
                .forEach(child => {
                if (child.tagName === 'IFX-TREE-VIEW-ITEM')
                    collect(child, false);
            });
        };
        Array.from(this.host.children)
            .forEach(child => {
            if (child.tagName === 'IFX-TREE-VIEW-ITEM')
                collect(child, false);
        });
        return descendants;
    }
    async updateChildrenState(checked) {
        for (const child of this.findChildren()) {
            const childInstance = child['__stencil_instance'];
            if (childInstance && !childInstance.disabled) {
                await child.componentOnReady();
                child.dispatchEvent(new CustomEvent('internal-check-state-change', {
                    detail: { checked },
                    bubbles: false,
                    composed: true
                }));
            }
        }
    }
    findSiblingNodes(parent) {
        return Array.from(parent.children)
            .filter((child) => child instanceof HTMLElement && child.tagName === 'IFX-TREE-VIEW-ITEM');
    }
    updateParentState() {
        var _a;
        const parent = (_a = this.host.parentElement) === null || _a === void 0 ? void 0 : _a.closest('ifx-tree-view-item');
        if (!parent)
            return;
        setTimeout(() => {
            const parentInstance = parent['__stencil_instance'];
            if (!parentInstance)
                return;
            const siblings = this.findSiblingNodes(parent);
            const { allChecked, someChecked } = this.calculateSiblingStates(siblings);
            parentInstance.setNodeState({
                isChecked: allChecked,
                partialChecked: !allChecked && someChecked
            }, false);
            parentInstance.updateParentState();
        }, 0);
    }
    calculateSiblingStates(siblings) {
        const states = siblings.map(sib => {
            const instance = sib['__stencil_instance'];
            return { checked: instance === null || instance === void 0 ? void 0 : instance.isChecked, partial: instance === null || instance === void 0 ? void 0 : instance.partialChecked };
        });
        const checkedCount = states.filter(state => state.checked).length;
        const partialCount = states.filter(state => state.partial).length;
        return {
            allChecked: states.length > 0 && checkedCount === states.length && partialCount === 0,
            someChecked: checkedCount > 0 || partialCount > 0
        };
    }
    render() {
        return (index.h("div", { key: '06430c8297a83b8ede5128151c7393c3fd03e2a2', class: {
                'tree-item': true,
                'tree-item--expanded': this.isExpanded,
                'tree-item--has-children': this.hasChildren,
                'tree-item--disabled': this.disabled,
            }, role: "treeitem", "aria-expanded": this.isExpanded ? 'true' : 'false', "data-level": this.level, "aria-disabled": this.disabled ? 'true' : undefined, "aria-label": this.ariaLabel }, index.h("div", { key: '2de63b8310c477646aeaf8deb3131bba1dc3801d', class: "tree-item__content" }, index.h("div", { key: '4269b1df1e670ec4106c1c4462cdd1dbe3cee7bd', class: "tree-item__checkbox-container", onClick: e => e.stopPropagation() }, index.h("ifx-checkbox", { key: '819444dfb6c9dd52a0aa703796c3e59c90616a79', size: 's', checked: this.partialChecked ? false : this.isChecked, indeterminate: this.partialChecked, onIfxChange: this.handleCheckboxChange, disabled: this.disabled })), index.h("div", { key: '2b4f487b08fbb77eed104ecee0774033c26f96fd', class: "tree-item__header", style: { paddingLeft: `${this.level * 24 + 10}px` }, onClick: this.handleHeaderClick, tabIndex: -1, "aria-disabled": this.disabled ? 'true' : undefined }, this.hasChildren && (index.h("div", { key: '59770cbe680dce25156ded6580dad90d3f4cc880', class: "tree-item__chevron-container", onClick: this.toggleExpand }, index.h("ifx-icon", { key: 'ef7ef1761781d4c179ee696e08af6d24af7d9b9f', class: `tree-item__chevron ${this.isExpanded ? 'chevron-down' : 'chevron-right'}`, icon: "chevron-right-16" }), index.h("div", { key: '99ec9f0abe191fde4a158484fb3b74d9d4ce524e', class: "tree-item__line" }))), index.h("div", { key: 'e91ecf4d195285403ac2229fc838e470c0e46ba6', class: "tree-item__label-icon-container", tabIndex: this.disabled ? -1 : 0, onKeyDown: this.handleKeyDown }, index.h("div", { key: 'a4b44e04c85234486602bdce7be330c7b9775233', class: "tree-item__icon-container" }, this.hasChildren ? (index.h(index.Fragment, null, index.h("ifx-icon", { class: { 'icon--hidden': this.isExpanded }, icon: "folder-16" }), index.h("ifx-icon", { class: { 'icon--hidden': !this.isExpanded }, icon: "folder-open-16" }))) : (index.h("ifx-icon", { icon: "file-16" }))), index.h("span", { key: '855ebc797490c23969a22b31fe8df64ffae2ff32', class: "tree-item__label" }, index.h("slot", { key: '92d518b2c916f43229ca5f9a9c38809b08888d09' }))))), this.isExpanded && index.h("div", { key: '769744e6235899295020700585f278ae8f3ba091', class: "tree-item__children" }, index.h("slot", { key: '4e760a8d309e22549df336927b955a35036c1826', name: "children" }))));
    }
    get host() { return index.getElement(this); }
    static get watchers() { return {
        "expanded": ["handleExpandedChange"],
        "disableItem": ["handleDisableItemChange"]
    }; }
};
TreeViewItem.style = treeViewItemCss;

exports.ifx_tree_view_item = TreeViewItem;
//# sourceMappingURL=ifx-tree-view-item.entry.cjs.js.map

//# sourceMappingURL=ifx-tree-view-item.cjs.entry.js.map