{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tree-view",
  "type": "registry:ui",
  "title": "<ui-tree-view>",
  "description": "Carbon `TreeView`: a `role=tree` of nested `<ui-tree-node>`s with a Carbon label. Click or Space selects (and makes the node `active`); `multiselect` toggles with Ctrl / ⌘ + click or Space and selects all with Ctrl + A. Up / Down move through the visible nodes, Home / End jump, Left / Right collapse / expand (or move to the parent / first child). Sizes sm 32px (default) / xs 24px. Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [
    "lit@^3.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/core-tree",
    "@kanok-ui/core-typeahead",
    "@kanok-ui/shared-element",
    "@kanok-ui/shared-field",
    "@kanok-ui/shared-localize",
    "@kanok-ui/shared-navigate",
    "@kanok-ui/shared-slots",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/tree-view/tree-node.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/tree-view/tree-node.ts",
      "content": "import { html, css, nothing } from 'lit';\nimport { customElement, property, state } from 'lit/decorators.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { srOnlyStyles, uid } from '../shared/field.ts';\nimport { SlotController } from '../shared/slots.ts';\nimport { LocalizeController } from '../shared/localize.ts';\nimport { treeNodeIndent, treeNodeOffset } from '../../core/tree.ts';\nimport { UiElement } from '../shared/element.ts';\nimport { followLink } from '../shared/navigate.ts';\nimport type { TreeNodeToggleDetail, TreeLazyLoadDetail } from './tree-view-shared.ts';\n\n/** What the node sets to name itself when it has end content. */\nconst NAME_ATTRIBUTES = ['aria-label', 'aria-labelledby', 'aria-describedby'] as const;\n\nconst caret = html`<svg class=\"caret\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M8 11 3 6l.7-.7L8 9.6l4.3-4.3.7.7z\" /></svg>`;\n\n/** Carbon's small loader (as ui-inline-loading), in place of the caret while a lazy branch loads. */\nconst spinner = html`<svg class=\"spinner\" viewBox=\"0 0 100 100\" aria-hidden=\"true\"><circle class=\"track\" cx=\"50%\" cy=\"50%\" r=\"42\" /><circle class=\"stroke\" cx=\"50%\" cy=\"50%\" r=\"42\" /></svg>`;\n\n/**\n * One node of a `<ui-tree-view>` (Carbon `TreeNode`). Nest `<ui-tree-node>`s as children to make\n * a branch (expand with the caret, Enter, or Right; collapse with Left); `href` turns the label into\n * a link. Selection, focus and `active` are managed by the tree.\n *\n * Children loaded on demand (Carbon has no pattern; this is Shoelace's `lazy`): a `lazy` node is a\n * branch before it has children. Expanding it the first time sets `loading` (a spinner replaces the\n * caret, `aria-busy`, \"Loading\" for screen readers) and fires `ui-lazy-load`; append the child\n * `<ui-tree-node>`s and `lazy` / `loading` clear themselves. No children to add: set `lazy = false`\n * (it becomes a leaf). A failed load: set `loading = false` — the node collapses and can be retried.\n *\n * @slot - Child nodes\n * @slot icon - 16px icon before the label\n * @slot label - Rich label (Carbon React's `label` node): replaces the `label` text, which stays the plain-text fallback\n * @slot end - Beyond Carbon: content at the end of the row (an amount, a count, a badge), kept whole while the label truncates; it then describes the node, which the label alone names\n * @fires ui-toggle - detail: { expanded, value } when the branch opens / closes\n * @fires ui-lazy-load - detail: { value } when a `lazy` node is expanded and its children should be fetched\n * @csspart label - The row\n * @csspart toggle - The caret button (branches)\n * @csspart children - The `role=group` container\n * @csspart end - The end content's wrapper (beyond Carbon)\n * @fires ui-navigate - detail: { href } (cancelable) on a plain click of the link; cancel it to route client-side (README: SPA router)\n * @cssprop --ui-tree-background / --ui-tree-row-radius - Row fill and corners (default the layer, 0; Kanok: transparent, 6px)\n * @cssprop --ui-tree-selected / --ui-tree-selected-hover - The selected row's fill and its hover (default layer-selected, layer-selected-hover; Kanok: the highlight tint)\n * @cssprop --ui-tree-mark / --ui-tree-mark-width / --ui-tree-mark-inset / --ui-tree-mark-radius - The selected row's start mark (default interactive, 4px, full height, square; Kanok: none, the tint alone — forced colours still show it)\n * @cssprop --ui-tree-pointer-outline - The ring of a node focused by a click, not the keyboard (default the focus ring, as Carbon; Kanok: none)\n */\n@customElement('ui-tree-node')\nexport class UiTreeNode extends UiElement {\n    static override readonly styles = [srOnlyStyles, css`\n        /* --ui-tree-*: a design can drop the fill, round the rows and mark the active one as the side nav's current page */\n        :host {\n            display: block;\n            background-color: var(--ui-tree-background, var(--ui-layer-1));\n            color: var(--ui-ink-muted);\n            outline: none;\n            cursor: pointer;\n        }\n\n        /*\n         * The node's indent (--_indent) is drawn by its parts, not :host padding, so a page-wide CSS reset\n         * can't remove it. The row bleeds back to the tree's edge so hover / selection span the full width (Carbon offset).\n         */\n        .label {\n            position: relative;\n            display: flex;\n            flex: 1;\n            align-items: center;\n            box-sizing: border-box;\n            min-block-size: 32px;\n            margin-inline-start: calc(var(--_indent, 16px) - var(--_offset, 16px));\n            border-radius: var(--ui-tree-row-radius, 0);\n            padding-inline-start: var(--_offset, 16px);\n            font: var(--ui-font-body-sm);\n            line-height: 18px; /* body-compact-01 */\n            letter-spacing: var(--ui-tracking-body);\n        }\n\n        :host([data-leaf]) .label {\n            padding-block: 7px;\n        }\n\n        :host([data-size='xs']) .label {\n            min-block-size: 24px;\n        }\n\n        :host([data-size='xs'][data-leaf]) .label {\n            padding-block: 0;\n        }\n\n        .label:hover {\n            background-color: var(--ui-layer-hover-1);\n            color: var(--ui-ink);\n        }\n\n        :host(:focus) > .label {\n            outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n            outline-offset: -2px;\n        }\n\n        /* focus a click brought, not the keyboard: a design can drop the ring there (--ui-tree-pointer-outline) */\n        :host(:focus:not(:focus-visible)) > .label {\n            outline-color: var(--ui-tree-pointer-outline, var(--ui-focus));\n        }\n\n        :host([data-selected]) > .label {\n            background-color: var(--ui-tree-selected, var(--ui-layer-selected-1));\n            color: var(--ui-ink);\n        }\n\n        :host([data-selected]) > .label:hover {\n            background-color: var(--ui-tree-selected-hover, var(--ui-layer-selected-hover-1, var(--ui-layer-active-1)));\n        }\n\n        :host([data-active]) > .label::before {\n            content: '';\n            position: absolute;\n            inset-block-start: var(--ui-tree-mark-inset, 0px);\n            inset-inline-start: 0;\n            block-size: calc(100% - 2 * var(--ui-tree-mark-inset, 0px));\n            inline-size: var(--ui-tree-mark-width, 4px);\n            border-radius: var(--ui-tree-mark-radius, 0);\n            background-color: var(--ui-tree-mark, var(--ui-interactive, var(--ui-primary)));\n        }\n\n        :host([disabled]),\n        :host([disabled]) .label:hover {\n            background-color: var(--ui-tree-background, var(--ui-field-1, var(--ui-layer-1)));\n            color: var(--ui-ink-disabled);\n            cursor: not-allowed;\n        }\n\n        :host([disabled]:focus) > .label {\n            outline: none;\n        }\n\n        .toggle {\n            display: flex;\n            align-items: center;\n            box-sizing: border-box;\n            inline-size: 24px;\n            block-size: 24px;\n            margin-inline: -4px 4px;\n            padding: 0 0 0 4px;\n            border: 0;\n            background: transparent;\n            color: inherit;\n            cursor: pointer;\n            outline: none;\n        }\n\n        .caret {\n            width: 16px;\n            height: 16px;\n            fill: var(--ui-icon-secondary);\n            transform: rotate(-90deg);\n            transition: all var(--ui-duration-moderate) var(--ui-easing); /* Carbon toggle-icon: the turn and the hover fill, fast-02 */\n        }\n\n        :host([expanded]) .caret {\n            transform: rotate(0);\n        }\n\n        .spinner {\n            width: 16px;\n            height: 16px;\n            animation: rotate 690ms linear infinite;\n        }\n\n        /* Carbon's small Loading: r 42 in a 100 box, a 276.46 dash (the r 44 circumference), a 48 % arc */\n        .spinner circle {\n            fill: none;\n            stroke-dasharray: 276.46 276.46;\n            stroke-linecap: butt;\n            stroke-width: 16;\n        }\n\n        .spinner .track {\n            stroke: var(--ui-layer-active-1);\n            stroke-dashoffset: -22;\n        }\n\n        .spinner .stroke {\n            stroke: var(--ui-interactive);\n            stroke-dashoffset: 143.76;\n        }\n\n        @keyframes rotate {\n            to {\n                transform: rotate(360deg);\n            }\n        }\n\n        @media (prefers-reduced-motion: reduce) {\n            .spinner {\n                animation-duration: 0s;\n            }\n        }\n\n        .label:hover .caret,\n        :host([data-selected]) > .label .caret,\n        .label:hover ::slotted([slot='icon']),\n        :host([data-selected]) > .label ::slotted([slot='icon']) {\n            fill: var(--ui-icon-primary);\n        }\n\n        :host([disabled]) .caret,\n        :host([disabled]) ::slotted([slot='icon']) {\n            fill: var(--ui-icon-disabled);\n        }\n\n        .details {\n            display: flex;\n            align-items: center;\n            min-inline-size: 0;\n        }\n\n        ::slotted([slot='icon']) {\n            flex-shrink: 0;\n            width: 16px;\n            height: 16px;\n            margin-inline: var(--ui-space-xs);\n            fill: var(--ui-icon-secondary);\n        }\n\n        .toggle + .details ::slotted([slot='icon']) {\n            margin-inline-start: var(--ui-space-xxs);\n        }\n\n        /* beyond Carbon: the end content (slot end) stays whole and end-aligned; the label takes the rest and truncates */\n        .end {\n            display: flex;\n            flex-shrink: 0;\n            align-items: center;\n            margin-inline-start: auto;\n            padding-inline: var(--ui-space-xs) var(--ui-space-md);\n        }\n\n        .text {\n            overflow: hidden;\n            text-overflow: ellipsis;\n            white-space: nowrap;\n        }\n\n        a.text {\n            color: inherit;\n            text-decoration: none;\n        }\n\n        .children {\n            margin: 0;\n            margin-inline-start: var(--_indent, 16px);\n            padding: 0;\n            list-style: none;\n        }\n\n        .children[hidden] {\n            display: none;\n        }\n\n        @media (forced-colors: active) {\n            :host([data-selected]) > .label {\n                outline: 1px solid Highlight;\n            }\n\n            :host([data-active]) > .label::before {\n                inline-size: 4px; /* shown here even where a design hides it */\n                background-color: Highlight;\n            }\n        }\n    `];\n\n    @property() label = '';\n\n    /** Identifies the node in `selected` / `active`; defaults to `label`. */\n    @property() value = '';\n\n    @property({ type: Boolean, reflect: true }) expanded = false;\n\n    @property({ type: Boolean, reflect: true }) disabled = false;\n\n    @property() href = '';\n\n    /** A branch whose children aren't loaded yet: it shows a caret and fires `ui-lazy-load` when first expanded. */\n    @property({ type: Boolean, reflect: true }) lazy = false;\n\n    /** The children are being fetched; set by the node when a `lazy` branch opens, cleared when children arrive. */\n    @property({ type: Boolean, reflect: true }) loading = false;\n\n    /** Set by the tree. */\n    @property({ type: Number, attribute: false }) depth = 0;\n\n    @state() private hasChildren = false;\n\n    private readonly ids = uid('ui-tree-node');\n    private readonly slots = new SlotController(this);\n    private readonly localize = new LocalizeController(this);\n    /** The node set its own aria-label / aria-labelledby / aria-describedby (end content in use). */\n    private namedByParts = false;\n\n    /** Has child nodes, or is `lazy` and will have them. */\n    get isBranch() {\n        return this.lazy || this.childTreeNodes.length > 0;\n    }\n\n    /** What identifies the node in the tree's `selected` / `active`: `value`, else `label`, else the label slot's text. (Was `nodeValue`, which shadowed DOM `Node.nodeValue`.) */\n    get treeValue() {\n        return this.value || this.label || this.labelText;\n    }\n\n    /** The label as text, which type-ahead matches: the `label` slot's text when it is used, else `label`. */\n    get labelText() {\n        const rich = this.slotted('label');\n        return rich.length ? rich.map((el) => el.textContent ?? '').join('').trim() : this.label;\n    }\n\n    /** Light-DOM children assigned to slot `name` (none under Lit SSR, where children aren't visible). */\n    private slotted(name: string): HTMLElement[] {\n        if (typeof this.querySelectorAll !== 'function') return [];\n        return [...this.querySelectorAll<HTMLElement>(`:scope > [slot=\"${name}\"]`)];\n    }\n\n    /** Direct child nodes. */\n    get childTreeNodes(): UiTreeNode[] {\n        if (typeof this.querySelectorAll !== 'function') return []; // children aren't visible under Lit SSR\n        return [...this.querySelectorAll<UiTreeNode>(':scope > ui-tree-node')];\n    }\n\n    /** The enclosing node, or null at the top level. */\n    get parentTreeNode(): UiTreeNode | null {\n        return this.parentElement?.closest?.<UiTreeNode>('ui-tree-node') ?? null;\n    }\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'treeitem');\n        if (!this.hasAttribute('tabindex')) this.tabIndex = -1;\n    }\n\n    protected override willUpdate(changed: Map<string, unknown>) {\n        this.hasChildren = this.childTreeNodes.length > 0;\n        if (this.hasChildren && (this.lazy || this.loading)) {\n            // the children arrived\n            this.lazy = false;\n            this.loading = false;\n        } else if (changed.get('loading') === true && !this.loading && this.lazy) {\n            this.expanded = false; // the load failed: close so expanding retries\n        } else if (changed.get('lazy') === true && !this.hasChildren) {\n            this.loading = false; // nothing to load: now a leaf\n            this.expanded = false;\n        }\n    }\n\n    private get branch() {\n        return this.hasChildren || this.lazy;\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        const icon = this.slots.has('icon');\n        const branch = this.branch;\n        this.toggleAttribute('data-leaf', !branch);\n        this.toggleAttribute('data-icon', icon);\n        this.style.setProperty('--_indent', `${treeNodeIndent(branch, icon)}px`);\n        this.style.setProperty('--_offset', `${treeNodeOffset(this.depth, branch, icon)}px`);\n        if (branch) this.setAttribute('aria-expanded', this.expanded ? 'true' : 'false');\n        else this.removeAttribute('aria-expanded');\n        if (this.loading) this.setAttribute('aria-busy', 'true');\n        else this.removeAttribute('aria-busy');\n        if (this.disabled) this.setAttribute('aria-disabled', 'true');\n        else this.removeAttribute('aria-disabled');\n        this.syncName();\n        if (changed.has('expanded') && changed.get('expanded') !== undefined) {\n            this.dispatchEvent(new CustomEvent('ui-toggle', { detail: { expanded: this.expanded, value: this.treeValue }, bubbles: true, composed: true }));\n        }\n        if (changed.has('expanded') && this.expanded && this.lazy && !this.hasChildren && !this.loading) {\n            this.loading = true;\n            this.dispatchEvent(new CustomEvent('ui-lazy-load', { detail: { value: this.treeValue }, bubbles: true, composed: true }));\n        }\n    }\n\n    /**\n     * With end content the label alone names the treeitem and the end content describes it (else the name\n     * would end with the amount); without, the row's content names it, as before. An author's own name wins.\n     */\n    private syncName() {\n        if (!this.namedByParts && (this.hasAttribute('aria-label') || this.hasAttribute('aria-labelledby'))) return;\n        const end = this.slotted('end');\n        if (!end.length) {\n            if (this.namedByParts) for (const name of NAME_ATTRIBUTES) this.removeAttribute(name);\n            this.namedByParts = false;\n            return;\n        }\n        const rich = this.slotted('label');\n        if (rich.length) {\n            this.setAttribute('aria-labelledby', this.idsOf(rich, 'label'));\n            this.removeAttribute('aria-label');\n        } else {\n            this.setAttribute('aria-label', this.label);\n            this.removeAttribute('aria-labelledby');\n        }\n        this.setAttribute('aria-describedby', this.idsOf(end, 'end'));\n        this.namedByParts = true;\n    }\n\n    /** The ids of slotted elements (given one when they have none), for aria-labelledby / aria-describedby. */\n    private idsOf(elements: HTMLElement[], slot: string) {\n        return elements\n            .map((el, i) => {\n                el.id ||= `${this.ids}-${slot}-${i}`;\n                return el.id;\n            })\n            .join(' ');\n    }\n\n    /** Expand / collapse (branches only, including `lazy` ones). */\n    toggle(expanded = !this.expanded) {\n        if (!this.isBranch || this.disabled) return;\n        this.expanded = expanded;\n    }\n\n    /** Children added or removed (e.g. a lazy load): re-render, and let the tree set their depth, size and tab stops. */\n    private onChildrenChange() {\n        this.requestUpdate();\n        this.closest('ui-tree-view')?.requestUpdate();\n    }\n\n    private onToggleClick(event: MouseEvent) {\n        event.stopPropagation();\n        this.toggle();\n    }\n\n    override render() {\n        const label = html`<slot name=\"label\">${this.label}</slot>`;\n        const text = this.href && !this.disabled ? html`<a class=\"text\" href=${this.href} tabindex=\"-1\" @click=${followLink}>${label}</a>` : html`<span class=\"text\">${label}</span>`;\n        const branch = this.branch;\n        const toggleIcon = this.loading ? spinner : caret;\n        return html`\n            <div class=\"label\" part=\"label\" id=${`${this.ids}-label`}>\n                ${branch ? html`<button class=\"toggle\" part=\"toggle\" type=\"button\" tabindex=\"-1\" aria-hidden=\"true\" ?disabled=${this.disabled} @click=${this.onToggleClick}>${toggleIcon}</button>` : nothing}\n                <span class=\"details\"><slot name=\"icon\"></slot>${text}</span>\n                ${this.slots.has('end') ? html`<span class=\"end\" part=\"end\"><slot name=\"end\"></slot></span>` : nothing}\n                ${this.loading ? html`<span class=\"sr-only\">, ${this.localize.t.common.loading}</span>` : nothing}\n            </div>\n            <div class=\"children\" part=\"children\" role=${ifDefined(branch ? 'group' : undefined)} aria-labelledby=${ifDefined(branch ? `${this.ids}-label` : undefined)} ?hidden=${branch && !this.expanded}>\n                <slot @slotchange=${this.onChildrenChange}></slot>\n            </div>\n        `;\n    }\n}\n\nexport interface UiTreeNodeEventMap extends HTMLElementEventMap {\n    'ui-toggle': CustomEvent<TreeNodeToggleDetail>;\n    'ui-lazy-load': CustomEvent<TreeLazyLoadDetail>;\n}\n\n/** Typed listeners for UiTreeNode's events (declaration merging with the class). */\nexport interface UiTreeNode {\n    addEventListener<K extends keyof UiTreeNodeEventMap>(type: K, listener: (this: UiTreeNode, event: UiTreeNodeEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiTreeNodeEventMap>(type: K, listener: (this: UiTreeNode, event: UiTreeNodeEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void;\n    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-tree-node': UiTreeNode;\n    }\n}\n"
    },
    {
      "path": "src/primitives/tree-view/tree-view-shared.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/tree-view/tree-view-shared.ts",
      "content": "\nexport interface TreeNodeToggleDetail {\n    expanded: boolean;\n    value: string;\n}\n\nexport interface TreeLazyLoadDetail {\n    value: string;\n}\n"
    },
    {
      "path": "src/primitives/tree-view/tree-view.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/tree-view/tree-view.ts",
      "content": "// Its child elements are one per file beside it; this module re-exports them (one entry point).\nimport { css, html, nothing } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { fieldTextStyles, uid } from '../shared/field.ts';\nimport { Typeahead } from '../../core/typeahead.ts';\nimport { visibleTreeNodes, treeTabStop, treeDepth, nextTreeSelection, sameTreeSelection, treeMoveTarget, treeSideStep } from '../../core/tree.ts';\nimport { UiElement } from '../shared/element.ts';\nimport type { UiTreeNode } from './tree-node.ts';\nimport type { TreeNodeToggleDetail, TreeLazyLoadDetail } from './tree-view-shared.ts';\nexport * from './tree-node.ts';\nexport type { TreeNodeToggleDetail, TreeLazyLoadDetail } from './tree-view-shared.ts';\n\nexport type TreeViewSize = 'xs' | 'sm';\n\n/**\n * Carbon `TreeView`: a `role=tree` of nested `<ui-tree-node>`s with a Carbon label. Click or\n * Space selects (and makes the node `active`); `multiselect` toggles with Ctrl / ⌘ + click or Space and\n * selects all with Ctrl + A. Up / Down move through the visible nodes, Home / End jump, Left /\n * Right collapse / expand (or move to the parent / first child). Sizes sm 32px (default) / xs 24px.\n *\n * @slot - Top-level `<ui-tree-node>`s\n * @fires ui-select - detail: { selected: string[], value } after a selection change\n * @fires ui-activate - detail: { active } when a node becomes the active one\n * @csspart label - The tree label\n * @csspart tree - The `role=tree` container\n * @cssprop --ui-tree-selected / --ui-tree-mark - The selected row's fill and mark (on `<ui-tree-node>`, with the other --ui-tree-* settings)\n */\n@customElement('ui-tree-view')\nexport class UiTreeView extends UiElement {\n    static override readonly styles = [fieldTextStyles, css`\n        :host {\n            display: block;\n            overflow: hidden;\n            font-family: var(--ui-font-family);\n        }\n\n        .label {\n            display: block;\n        }\n\n        .tree {\n            margin: 0;\n            padding: 0;\n        }\n    `];\n\n    @property() label = '';\n\n    @property({ type: Boolean, attribute: 'hide-label' }) hideLabel = false;\n\n    @property({ reflect: true }) size: TreeViewSize = 'sm';\n\n    @property({ type: Boolean, reflect: true }) multiselect = false;\n\n    /** Selected node values. */\n    @property({ attribute: false }) selected: string[] = [];\n\n    /** The node that was last activated (4px marker). */\n    @property() active = '';\n\n    private readonly ids = uid('ui-tree-view');\n\n    override connectedCallback() {\n        super.connectedCallback();\n        this.addEventListener('click', this.onClick);\n        this.addEventListener('keydown', this.onKeydown);\n        this.addEventListener('focusin', this.onFocusIn);\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.removeEventListener('click', this.onClick);\n        this.removeEventListener('keydown', this.onKeydown);\n        this.removeEventListener('focusin', this.onFocusIn);\n    }\n\n    /** Every node, document order. */\n    get nodes(): UiTreeNode[] {\n        return [...this.querySelectorAll<UiTreeNode>('ui-tree-node')];\n    }\n\n    /** Nodes whose every ancestor is expanded (what the user can see / arrow through). */\n    private visibleNodes() {\n        return visibleTreeNodes(this.nodes, (n) => n.parentTreeNode, (n) => n.expanded);\n    }\n\n    protected override updated() {\n        this.sync();\n    }\n\n    private sync() {\n        const nodes = this.nodes;\n        // APG tree: exactly one Tab stop, on a node the user can see and use\n        const reachable = this.visibleNodes().filter((n) => !n.disabled);\n        const focusable = treeTabStop(reachable, (n) => n.tabIndex === 0, (n) => this.selected.includes(n.treeValue));\n        for (const node of nodes) {\n            node.depth = treeDepth(node, (n) => n.parentTreeNode);\n            node.dataset.size = this.size;\n            node.toggleAttribute('data-selected', this.selected.includes(node.treeValue));\n            node.toggleAttribute('data-active', this.active !== '' && node.treeValue === this.active);\n            node.setAttribute('aria-selected', this.selected.includes(node.treeValue) ? 'true' : 'false');\n            node.tabIndex = node === focusable ? 0 : -1;\n        }\n    }\n\n    private nodeOf(target: EventTarget | null) {\n        return (target as Element | null)?.closest?.('ui-tree-node') as UiTreeNode | null;\n    }\n\n    /** Replace the selection with `node`, or with `toggle` add / remove it (Ctrl / ⌘ + click, Space in a multiselect tree). */\n    private select(node: UiTreeNode, event: MouseEvent | KeyboardEvent, toggle = this.multiselect && (event.metaKey || event.ctrlKey)) {\n        if (node.disabled) return;\n        const value = node.treeValue;\n        const next = nextTreeSelection(this.selected, value, toggle);\n        if (!toggle) this.activate(value);\n        if (sameTreeSelection(next, this.selected)) return;\n        this.selected = next;\n        this.sync();\n        this.dispatchEvent(new CustomEvent('ui-select', { detail: { selected: next, value }, bubbles: true, composed: true }));\n    }\n\n    private activate(value: string) {\n        if (this.active === value) return;\n        this.active = value;\n        this.sync();\n        this.dispatchEvent(new CustomEvent('ui-activate', { detail: { active: value }, bubbles: true, composed: true }));\n    }\n\n    private focusNode(node: UiTreeNode) {\n        for (const n of this.nodes) n.tabIndex = n === node ? 0 : -1;\n        node.focus();\n    }\n\n    private readonly onFocusIn = (event: FocusEvent) => {\n        const node = this.nodeOf(event.target);\n        if (node) for (const n of this.nodes) n.tabIndex = n === node ? 0 : -1;\n    };\n\n    private readonly onClick = (event: MouseEvent) => {\n        const node = this.nodeOf(event.target);\n        if (!node || node.disabled) return;\n        this.focusNode(node);\n        this.select(node, event);\n    };\n\n    private readonly onKeydown = (event: KeyboardEvent) => {\n        const node = this.nodeOf(event.target);\n        if (!node) return;\n        switch (event.key) {\n            case 'ArrowDown':\n            case 'ArrowUp':\n            case 'Home':\n            case 'End':\n                this.moveFocus(node, event);\n                break;\n            case 'ArrowRight':\n            case 'ArrowLeft':\n                this.sideStep(node, event);\n                break;\n            case 'Enter':\n                this.enter(node, event);\n                break;\n            case ' ':\n                event.preventDefault();\n                this.select(node, event, this.multiselect); // APG multi-select tree: Space toggles the focused node\n                break;\n            case 'a':\n            case 'A':\n                if ((event.ctrlKey || event.metaKey) && this.multiselect) this.selectAll(node, event);\n                else this.typeaheadTo(node, event);\n                break;\n            default:\n                this.typeaheadTo(node, event);\n        }\n    };\n\n    private readonly typeahead = new Typeahead();\n\n    /** APG: typing a character moves to the next visible node whose label (not its end content) starts with it. */\n    private typeaheadTo(node: UiTreeNode, event: KeyboardEvent) {\n        const visible = this.visibleNodes().filter((n) => !n.disabled);\n        const target = visible[this.typeahead.match(event, visible, visible.indexOf(node), (n) => n.labelText || n.textContent || '') ?? -1];\n        if (!target) return;\n        event.preventDefault();\n        this.focusNode(target);\n    }\n\n    private moveFocus(node: UiTreeNode, event: KeyboardEvent) {\n        event.preventDefault();\n        const target = treeMoveTarget(event.key, node, this.visibleNodes());\n        if (target) this.focusNode(target);\n    }\n\n    /** Right / Left: expand or go to the first child (a lazy branch still loading has none yet); collapse or go to the parent. */\n    private sideStep(node: UiTreeNode, event: KeyboardEvent) {\n        const rtl = getComputedStyle(this).direction === 'rtl';\n        const step = treeSideStep(event.key, { branch: node.isBranch, expanded: node.expanded, disabled: node.disabled, firstChild: node.childTreeNodes[0], parent: node.parentTreeNode }, rtl);\n        if (!step.handled) return;\n        event.preventDefault();\n        if (step.expand !== undefined) node.toggle(step.expand);\n        else if (step.focus) this.focusNode(step.focus);\n    }\n\n    private enter(node: UiTreeNode, event: KeyboardEvent) {\n        event.preventDefault();\n        if (node.isBranch) node.toggle();\n        this.select(node, event);\n        if (node.href && !node.disabled) node.shadowRoot?.querySelector<HTMLAnchorElement>('a')?.click();\n    }\n\n    private selectAll(node: UiTreeNode, event: KeyboardEvent) {\n        event.preventDefault();\n        const all = this.nodes.filter((n) => !n.disabled).map((n) => n.treeValue);\n        this.selected = all;\n        this.sync();\n        this.dispatchEvent(new CustomEvent('ui-select', { detail: { selected: all, value: node.treeValue }, bubbles: true, composed: true }));\n    }\n\n    override render() {\n        return html`\n            ${this.hideLabel || !this.label ? nothing : html`<span class=\"label\" part=\"label\" id=\"${this.ids}-label\">${this.label}</span>`}\n            <div class=\"tree\" part=\"tree\" role=\"tree\" aria-label=${ifDefined(this.hideLabel ? this.label : undefined)} aria-labelledby=${ifDefined(this.hideLabel || !this.label ? undefined : `${this.ids}-label`)} aria-multiselectable=${ifDefined(this.multiselect ? 'true' : undefined)}>\n                <slot @slotchange=${() => this.sync()}></slot>\n            </div>\n        `;\n    }\n}\n\nexport interface TreeSelectDetail {\n    selected: string[];\n    value: string;\n}\n\nexport interface TreeActivateDetail {\n    active: string;\n}\n\nexport interface UiTreeViewEventMap extends HTMLElementEventMap {\n    'ui-select': CustomEvent<TreeSelectDetail>;\n    'ui-activate': CustomEvent<TreeActivateDetail>;\n    'ui-toggle': CustomEvent<TreeNodeToggleDetail>;\n    'ui-lazy-load': CustomEvent<TreeLazyLoadDetail>;\n}\n\n/** Typed listeners for UiTreeView's events (declaration merging with the class). */\nexport interface UiTreeView {\n    addEventListener<K extends keyof UiTreeViewEventMap>(type: K, listener: (this: UiTreeView, event: UiTreeViewEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiTreeViewEventMap>(type: K, listener: (this: UiTreeView, event: UiTreeViewEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void;\n    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-tree-view': UiTreeView;\n    }\n}\n"
    }
  ]
}
