import { __decorate } from "tslib";
import { attr, observable } from '@ni/fast-element';
import { TreeView as FoundationTreeView, DesignSystem, isTreeItemElement } from '@ni/fast-foundation';
import { TreeItem } from '../tree-item';
import { styles } from './styles';
import { template } from './template';
import { TreeViewSelectionMode } from './types';
/**
 * A function that returns a nimble-tree-view registration for configuring the component with a DesignSystem.
 * Implements {@link @ni/fast-foundation#treeViewTemplate}
 *
 *
 * @public
 * @remarks
 * Generates HTML Element: \<nimble-tree-view\>
 *
 */
export class TreeView extends FoundationTreeView {
    constructor() {
        super(...arguments);
        this.selectionMode = TreeViewSelectionMode.all;
        /**
         * @internal
         */
        this.selectedItems = [];
    }
    handleClick(e) {
        if (e.defaultPrevented) {
            // handled, do nothing
            return false;
        }
        if (!(e.target instanceof Element) || !isTreeItemElement(e.target)) {
            // not a tree item, ignore
            return true;
        }
        const item = e.target;
        if (item.disabled) {
            return false;
        }
        if (this.canSelect(item)) {
            item.selected = true;
        }
        else if (this.itemHasChildren(item)) {
            item.expanded = !item.expanded;
        }
        return true;
    }
    canSelect(item) {
        switch (this.selectionMode) {
            case TreeViewSelectionMode.all:
                return true;
            case TreeViewSelectionMode.none:
                return false;
            case TreeViewSelectionMode.leavesOnly:
                return !this.itemHasChildren(item);
            default:
                return true;
        }
    }
    itemHasChildren(item) {
        const treeItemChild = item.querySelector('[role="treeitem"]');
        return treeItemChild !== null;
    }
    selectedItemsChanged() {
        for (const item of Array.from(this.children)) {
            if (item instanceof TreeItem) {
                item.groupSelected = false;
            }
        }
        for (let item of this.selectedItems) {
            while (item.parentElement !== null && item.parentElement !== this) {
                item = item.parentElement;
            }
            if (item instanceof TreeItem) {
                item.groupSelected = true;
            }
        }
    }
}
__decorate([
    attr({ attribute: 'selection-mode' })
], TreeView.prototype, "selectionMode", void 0);
__decorate([
    observable
], TreeView.prototype, "selectedItems", void 0);
const nimbleTreeView = TreeView.compose({
    baseName: 'tree-view',
    baseClass: FoundationTreeView,
    template,
    styles
});
DesignSystem.getOrCreate().withPrefix('nimble').register(nimbleTreeView());
export const treeViewTag = 'nimble-tree-view';
//# sourceMappingURL=index.js.map