{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "menu",
  "type": "registry:ui",
  "title": "<ui-menu>",
  "description": "Carbon `Menu`: the floating `role=menu` list behind `<ui-overflow-menu>` and `<ui-menu-button>`, usable on its own with `show(anchor)`. Lives in the top layer (`popover=\"manual\"`) at document coordinates next to `anchor` (flips when it doesn't fit). On open, focus moves to the first enabled item; Up/Down wrap, Home/End jump; Escape or Tab close and return focus; so does activating an item, clicking outside or focus leaving. 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-popup",
    "@kanok-ui/core-roving",
    "@kanok-ui/core-typeahead",
    "@kanok-ui/shared-align",
    "@kanok-ui/shared-element",
    "@kanok-ui/shared-events",
    "@kanok-ui/shared-field",
    "@kanok-ui/shared-position",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/menu/menu-divider.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/menu/menu-divider.ts",
      "content": "import { css, html } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { UiElement } from '../shared/element.ts';\n\n/** Carbon `MenuItemDivider`: a 1px separator with 4px above and below. */\n@customElement('ui-menu-divider')\nexport class UiMenuDivider extends UiElement {\n    static override readonly styles = css`\n        :host {\n            display: block;\n        }\n\n        /* the 4px above and below sit on the line and collapse through the host: a page-wide CSS reset would remove a :host margin */\n        .line {\n            block-size: 1px;\n            margin-block: var(--ui-space-xxs);\n            background-color: var(--ui-hairline);\n        }\n    `;\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'separator');\n    }\n\n    override render() {\n        return html`<div class=\"line\"></div>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-menu-divider': UiMenuDivider;\n    }\n}\n"
    },
    {
      "path": "src/primitives/menu/menu-group.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/menu/menu-group.ts",
      "content": "import { css, html } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { setManagedAttribute } from '../shared/field.ts';\nimport { UiElement } from '../shared/element.ts';\nimport { UiMenuItem } from './menu-item.ts';\n\n/**\n * Carbon `MenuItemGroup` (`role=group` named by `label`) and `MenuItemRadioGroup`\n * (`selection=\"single\"`: its items become `menuitemradio`, exactly one is `checked`).\n *\n * @slot - `<ui-menu-item>` elements\n * @fires ui-change - detail: { value } when the checked radio item changes\n */\n@customElement('ui-menu-group')\nexport class UiMenuGroup extends UiElement {\n    static override readonly styles = css`\n        :host {\n            display: block;\n        }\n    `;\n\n    @property() label = '';\n\n    @property() selection: 'none' | 'single' = 'none';\n\n    /** The checked item's value in `selection=\"single\"`. */\n    @property() value = '';\n\n    get items(): UiMenuItem[] {\n        return [...this.querySelectorAll<UiMenuItem>(':scope > ui-menu-item')];\n    }\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'group');\n        this.addEventListener('ui-select', this.onSelect as EventListener);\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.removeEventListener('ui-select', this.onSelect as EventListener);\n    }\n\n    protected override updated() {\n        setManagedAttribute(this, 'aria-label', this.label || null);\n        this.sync();\n    }\n\n    private sync() {\n        const single = this.selection === 'single';\n        for (const item of this.items) {\n            item.radio = single;\n            if (single) item.checked = item.selectValue === this.value;\n        }\n    }\n\n    private readonly onSelect = (event: CustomEvent<{ value: string }>) => {\n        if (this.selection !== 'single' || !(event.target instanceof UiMenuItem)) return;\n        const next = event.target.selectValue;\n        if (next === this.value) return;\n        this.value = next;\n        this.sync();\n        this.dispatchEvent(new CustomEvent('ui-change', { detail: { value: next }, bubbles: true, composed: true }));\n    };\n\n    override render() {\n        return html`<slot @slotchange=${() => this.sync()}></slot>`;\n    }\n}\n\nexport interface MenuGroupChangeDetail {\n    value: string;\n}\n\nexport interface UiMenuGroupEventMap extends HTMLElementEventMap {\n    'ui-change': CustomEvent<MenuGroupChangeDetail>;\n}\n\n/** Typed listeners for UiMenuGroup's events (declaration merging with the class). */\nexport interface UiMenuGroup {\n    addEventListener<K extends keyof UiMenuGroupEventMap>(type: K, listener: (this: UiMenuGroup, event: UiMenuGroupEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiMenuGroupEventMap>(type: K, listener: (this: UiMenuGroup, event: UiMenuGroupEventMap[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-menu-group': UiMenuGroup;\n    }\n}\n"
    },
    {
      "path": "src/primitives/menu/menu-item.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/menu/menu-item.ts",
      "content": "import { svg, css, html, nothing } from 'lit';\nimport { customElement, property, state, query } from 'lit/decorators.js';\nimport { srOnlyStyles, setManagedAttribute } from '../shared/field.ts';\nimport { isOwnEvent, type OpenDetail } from '../shared/events.ts';\nimport { UiElement } from '../shared/element.ts';\nimport type { UiMenu } from './menu.ts';\nimport { deepActiveElement, type MenuFocus, type MenuSize, type MenuSelectDetail } from './menu-shared.ts';\n\nexport type MenuItemKind = 'default' | 'danger';\n\nconst checkmark = svg`<path d=\"M6 12.4 2.3 8.7l.7-.7 3 3 6.3-6.3.7.7z\" />`;\n\nconst chevronRight = svg`<path d=\"M11 8 6 13l-.7-.7L9.6 8 5.3 3.7 6 3z\" />`;\n\n/** Hover intent before a submenu opens / closes (Carbon `hoverIntentDelay`). */\nconst SUBMENU_DELAY = 150;\n\n/** Children of a `<ui-menu-item>` that make up its submenu. */\nconst SUBMENU_CHILDREN = 'ui-menu-item, ui-menu-group, ui-menu-divider';\n\n/**\n * Carbon `MenuItem` / `MenuItemSelectable` (`selectable`) / radio item (inside a\n * `<ui-menu-group selection=\"single\">`). Activating it (click, Enter, Space) fires `ui-select`\n * and closes the menu. `kind=\"danger\"` turns red on hover/focus; `danger-description` is read\n * after the label. `shortcut` is a hint only (nothing is registered).\n *\n * Submenu (Carbon nested `MenuItem`): put `<ui-menu-item>`s (and groups / dividers) inside an item.\n * It shows a chevron and opens them in a `<ui-menu>` beside it — on hover, click, Enter, Space or\n * Right Arrow (Left in RTL), which focuses the first item; Left Arrow or Escape closes just that\n * level and returns focus to the item. Activating a leaf fires `ui-select` and closes every level.\n *\n * @slot - Extra label content after `label`; `<ui-menu-item>` children move to the submenu\n * @slot submenu - The submenu's items (children that are menu items get this slot automatically)\n * @slot icon - 16px icon (shown when any item in the menu has one — Carbon `renderIcon`)\n * @fires ui-select - detail: { value, label, checked } when activated (not when disabled)\n * @csspart icon - Icon cell\n * @csspart label - Label cell\n * @csspart shortcut - Shortcut hint\n * @csspart submenu - The nested `<ui-menu>`\n * @csspart submenu-icon - The chevron of an item with a submenu\n * @cssprop --ui-menu-item-height - Row height for every size (default 24 / 32 / 40 / 48px by size; Kanok: 32px)\n * @cssprop --ui-menu-item-active-outline / --ui-menu-item-active-background - The focused row: its ring and its fill (default focus, transparent)\n * @cssprop --ui-menu-item-pointer-outline - The ring of a row focused by a mouse open or click, not the keyboard (default the focused row's ring, as Carbon; Kanok: none)\n */\n@customElement('ui-menu-item')\nexport class UiMenuItem extends UiElement {\n    static override readonly styles = [srOnlyStyles, css`\n        /* a row: the menu settings of shared/listbox.ts (--ui-menu-item-radius / -ink) apply here too */\n        :host {\n            display: block;\n            border-radius: var(--ui-menu-item-radius, 0);\n            color: var(--ui-menu-item-ink, var(--ui-ink-muted));\n            font: var(--ui-font-body-sm);\n            line-height: 18px; /* body-short-01 */\n            letter-spacing: var(--ui-tracking-body);\n            cursor: pointer;\n            outline: none;\n            transition: background-color var(--ui-duration-fast) var(--ui-easing);\n        }\n\n        /* the row's grid and 16px padding, on a part rather than :host so a page-wide CSS reset can't remove the padding */\n        .base {\n            display: grid;\n            grid-template-columns: 1fr max-content;\n            align-items: center;\n            column-gap: var(--ui-space-xs);\n            box-sizing: border-box;\n            block-size: var(--ui-menu-item-height, var(--_row, 32px)); /* a design can give every menu one row height */\n            padding-inline: var(--ui-space-md);\n        }\n\n        :host([data-size='xs']) {\n            --_row: 24px;\n        }\n\n        :host([data-size='md']) {\n            --_row: 40px;\n        }\n\n        :host([data-size='lg']) {\n            --_row: 48px;\n        }\n\n        :host([data-icons]) .base,\n        :host([data-selectable]) .base {\n            grid-template-columns: 1rem 1fr max-content;\n        }\n\n        :host([data-icons][data-selectable]) .base {\n            grid-template-columns: 1rem 1rem 1fr max-content;\n        }\n\n        :host(:hover) {\n            background-color: var(--ui-ghost-hover);\n            color: var(--ui-ink);\n        }\n\n        /* :focus, not :focus-visible: opening by mouse moves focus to the first item and Carbon rings it too */\n        :host(:focus) {\n            outline: var(--ui-focus-width, 2px) solid var(--ui-menu-item-active-outline, var(--ui-focus));\n            outline-offset: -2px;\n        }\n\n        /* focus that the keyboard didn't bring (a mouse open or click): a design can drop the ring there (the hover tint shows the row) */\n        :host(:focus:not(:focus-visible)) {\n            outline-color: var(--ui-menu-item-pointer-outline, var(--ui-menu-item-active-outline, var(--ui-focus)));\n        }\n\n        /* --ui-menu-item-active-*: a design can show the focused row as a fill instead of the ring, as the lists' highlight */\n        :host(:focus:not(:hover, [kind='danger'], [aria-expanded='true'])) {\n            background-color: var(--ui-menu-item-active-background, transparent);\n        }\n\n        @media screen and (prefers-contrast) {\n            :host(:focus) {\n                outline-style: dotted;\n            }\n        }\n\n        @media (forced-colors: active) {\n            :host(:focus) {\n                outline-color: Highlight;\n            }\n        }\n\n        :host([kind='danger']:hover),\n        :host([kind='danger']:focus) {\n            background-color: var(--ui-button-danger);\n            color: var(--ui-on-primary);\n        }\n\n        :host([disabled]),\n        :host([disabled]:hover) {\n            background-color: transparent;\n            color: var(--ui-ink-disabled);\n            cursor: not-allowed;\n        }\n\n        .selection,\n        .icon {\n            display: none;\n            align-items: center;\n        }\n\n        :host([data-selectable]) .selection,\n        :host([data-icons]) .icon {\n            display: flex;\n        }\n\n        .selection svg,\n        ::slotted([slot='icon']) {\n            width: 16px;\n            height: 16px;\n            fill: currentColor;\n        }\n\n        .label {\n            overflow: hidden;\n            text-overflow: ellipsis;\n            white-space: nowrap;\n        }\n\n        .shortcut,\n        .submenu-icon {\n            display: flex;\n        }\n\n        .submenu-icon svg {\n            width: 16px;\n            height: 16px;\n            fill: currentColor;\n        }\n\n        :host(:dir(rtl)) .submenu-icon svg {\n            transform: scaleX(-1);\n        }\n\n        /* Carbon keeps the parent highlighted while its submenu is open */\n        :host([aria-expanded='true']) {\n            background-color: var(--ui-ghost-hover);\n            color: var(--ui-ink);\n        }\n    `];\n\n    @property() label = '';\n\n    /** Reported in `ui-select`; defaults to `label`. */\n    @property() value = '';\n\n    @property() shortcut = '';\n\n    @property({ reflect: true }) kind: MenuItemKind = 'default';\n\n    @property({ type: Boolean, reflect: true }) disabled = false;\n\n    /** Carbon `MenuItemSelectable`: a `menuitemcheckbox` that toggles `checked`. */\n    @property({ type: Boolean, reflect: true }) selectable = false;\n\n    @property({ type: Boolean, reflect: true }) checked = false;\n\n    @property({ attribute: 'danger-description' }) dangerDescription = '';\n\n    /** Set by `<ui-menu-group selection=\"single\">`: this item is a `menuitemradio`. */\n    @property({ type: Boolean, attribute: false }) radio = false;\n\n    /** True when the item has child items, which it shows in a submenu. */\n    @state() private hasSubmenu = false;\n\n    @state() private submenuOpen = false;\n\n    @query('ui-menu') private readonly submenu?: UiMenu;\n\n    private hoverTimer?: ReturnType<typeof setTimeout>;\n\n    get selectValue() {\n        return this.value || this.label;\n    }\n\n    constructor() {\n        super();\n        this.addEventListener('click', (event) => {\n            // a click on one of the submenu's items bubbles here too; only clicks on this item activate it\n            if (event.composedPath().find((node) => node instanceof UiMenuItem) !== this) return;\n            this.activate();\n        });\n        this.addEventListener('keydown', this.onKeydown);\n        this.addEventListener('pointerenter', this.onPointerEnter);\n        this.addEventListener('pointerleave', this.onPointerLeave);\n        this.addEventListener('focusout', this.onFocusOut);\n    }\n\n    private readonly onKeydown = (event: KeyboardEvent) => {\n        if (event.target !== this) return; // keys from the submenu's items are its own\n        const opensSubmenu = event.key === (this.matches(':dir(rtl)') ? 'ArrowLeft' : 'ArrowRight');\n        if (event.key === 'Enter' || event.key === ' ' || (opensSubmenu && this.hasSubmenu)) {\n            event.preventDefault();\n            event.stopPropagation();\n            if (opensSubmenu) this.openSubmenu('first');\n            else this.activate();\n        }\n    };\n\n    private readonly onPointerEnter = () => {\n        if (!this.hasSubmenu || this.disabled) return;\n        clearTimeout(this.hoverTimer);\n        this.hoverTimer = setTimeout(() => this.openSubmenu('none'), SUBMENU_DELAY);\n    };\n\n    /** Leaving the item and its submenu (which is inside it in the DOM, so moving into it doesn't count). */\n    private readonly onPointerLeave = () => {\n        clearTimeout(this.hoverTimer);\n        if (!this.submenuOpen) return;\n        this.hoverTimer = setTimeout(() => {\n            if (!this.submenu?.contains(deepActiveElement()) && !this.querySelector(':scope > [slot=\"submenu\"]:focus-within')) this.closeSubmenu();\n        }, SUBMENU_DELAY);\n    };\n\n    private readonly onFocusOut = (event: FocusEvent) => {\n        const next = event.relatedTarget as Node | null;\n        if (next && (this.contains(next) || this.shadowRoot?.contains(next))) return;\n        this.closeSubmenu();\n    };\n\n    /** Open the submenu; `focus` picks the item that takes focus (`none` for hover). */\n    openSubmenu(focus: MenuFocus = 'first') {\n        if (!this.hasSubmenu || this.disabled || !this.submenu) return;\n        clearTimeout(this.hoverTimer);\n        if (this.submenu.open) {\n            if (focus !== 'none') this.submenu.focusItem(focus);\n            return;\n        }\n        this.submenu.show(this, focus);\n    }\n\n    closeSubmenu() {\n        clearTimeout(this.hoverTimer);\n        this.submenu?.hide();\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        clearTimeout(this.hoverTimer);\n    }\n\n    /** Children that are menu items go to the submenu; anything else stays label content. */\n    private readonly onDefaultSlotChange = (event: Event) => {\n        for (const el of (event.target as HTMLSlotElement).assignedElements()) {\n            if (el.matches(SUBMENU_CHILDREN)) el.setAttribute('slot', 'submenu');\n        }\n        this.syncHasSubmenu();\n    };\n\n    private readonly syncHasSubmenu = () => {\n        this.hasSubmenu = this.querySelector(':scope > [slot=\"submenu\"]') !== null;\n    };\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('tabindex')) this.tabIndex = -1;\n        this.syncHasSubmenu(); // children an author already put in slot=\"submenu\"\n    }\n\n    protected override updated() {\n        let role = 'menuitem';\n        if (this.radio) role = 'menuitemradio';\n        else if (this.selectable) role = 'menuitemcheckbox';\n        setManagedAttribute(this, 'role', role);\n        if (this.radio || this.selectable) this.setAttribute('aria-checked', this.checked ? 'true' : 'false');\n        else this.removeAttribute('aria-checked');\n        if (this.disabled) this.setAttribute('aria-disabled', 'true');\n        else this.removeAttribute('aria-disabled');\n        setManagedAttribute(this, 'aria-haspopup', this.hasSubmenu ? 'menu' : null);\n        setManagedAttribute(this, 'aria-expanded', this.hasSubmenu ? String(this.submenuOpen) : null);\n        if (this.submenu) this.submenu.size = (this.dataset.size as MenuSize | undefined) ?? 'sm';\n    }\n\n    /** What a click / Enter / Space does: opens the submenu, else toggles / selects and fires `ui-select`. */\n    activate() {\n        if (this.disabled) return;\n        if (this.hasSubmenu) {\n            this.openSubmenu('first');\n            return;\n        }\n        if (this.selectable) this.checked = !this.checked;\n        if (this.radio) this.checked = true;\n        this.dispatchEvent(\n            new CustomEvent('ui-select', { detail: { value: this.selectValue, label: this.label, checked: this.checked }, bubbles: true, composed: true }),\n        );\n    }\n\n    private readonly onSubmenuToggle = (event: CustomEvent<OpenDetail>) => {\n        if (isOwnEvent(event)) this.submenuOpen = event.detail.open;\n    };\n\n    /** The trailing cell: the submenu chevron, else the shortcut hint. */\n    private renderEnd() {\n        if (this.hasSubmenu) return html`<span class=\"submenu-icon\" part=\"submenu-icon\" aria-hidden=\"true\"><svg viewBox=\"0 0 16 16\">${chevronRight}</svg></span>`;\n        return this.shortcut ? html`<span class=\"shortcut\" part=\"shortcut\">${this.shortcut}</span>` : html``;\n    }\n\n    override render() {\n        const danger = this.kind === 'danger' && this.dangerDescription;\n        return html`<span class=\"base\">\n            <span class=\"selection\" aria-hidden=\"true\"><svg viewBox=\"0 0 16 16\">${this.checked ? checkmark : nothing}</svg></span>\n            <span class=\"icon\" part=\"icon\"><slot name=\"icon\"></slot></span>\n            <span class=\"label\" part=\"label\">${this.label}<slot @slotchange=${this.onDefaultSlotChange}></slot>${danger ? html`<span class=\"sr-only\">${this.dangerDescription}</span>` : nothing}</span>\n            ${this.renderEnd()}</span>\n            ${this.hasSubmenu\n                ? html`<ui-menu part=\"submenu\" label=${this.label} @ui-toggle=${this.onSubmenuToggle}><slot name=\"submenu\" @slotchange=${this.syncHasSubmenu}></slot></ui-menu>`\n                : nothing}\n        `;\n    }\n}\n\nexport interface UiMenuItemEventMap extends HTMLElementEventMap {\n    'ui-select': CustomEvent<MenuSelectDetail>;\n}\n\n/** Typed listeners for UiMenuItem's events (declaration merging with the class). */\nexport interface UiMenuItem {\n    addEventListener<K extends keyof UiMenuItemEventMap>(type: K, listener: (this: UiMenuItem, event: UiMenuItemEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiMenuItemEventMap>(type: K, listener: (this: UiMenuItem, event: UiMenuItemEventMap[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-menu-item': UiMenuItem;\n    }\n}\n"
    },
    {
      "path": "src/primitives/menu/menu-shared.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/menu/menu-shared.ts",
      "content": "import type { UiMenu } from './menu.ts';\n\n/** Row heights: xs 24 · sm 32 (Carbon default) · md 40 · lg 48. */\nexport type MenuSize = 'xs' | 'sm' | 'md' | 'lg';\n\n/** Which item takes focus when a menu opens; `none` keeps focus where it is (a submenu opened by hover). */\nexport type MenuFocus = 'first' | 'last' | 'none';\n\n/** The focused element, following shadow roots down. */\nexport function deepActiveElement(): HTMLElement | null {\n    let el: Element | null = document.activeElement;\n    while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;\n    return el as HTMLElement | null;\n}\n\n/**\n * Keyboard opening for a menu button (APG): Down Arrow opens on the first item, Up Arrow on the last.\n * Returns true when it handled the key.\n */\nexport function openMenuFromKey(event: KeyboardEvent, menu: UiMenu, anchor: Element) {\n    if ((event.key !== 'ArrowDown' && event.key !== 'ArrowUp') || menu.open) return false;\n    event.preventDefault();\n    menu.show(anchor, event.key === 'ArrowUp' ? 'last' : 'first');\n    return true;\n}\n\n/** `ui-select` of a menu item (bubbles through menus, menu buttons and overflow menus). */\nexport interface MenuSelectDetail {\n    value: string;\n    label: string;\n    checked: boolean;\n}\n"
    },
    {
      "path": "src/primitives/menu/menu.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/menu/menu.ts",
      "content": "// Its child elements are one per file beside it; this module re-exports them (one entry point).\nimport { css, html } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { setManagedAttribute } from '../shared/field.ts';\nimport { placeFloating } from '../shared/position.ts';\nimport { Typeahead } from '../../core/typeahead.ts';\nimport type { OpenDetail } from '../shared/events.ts';\nimport { WithAlign } from '../shared/align.ts';\nimport { UiElement } from '../shared/element.ts';\nimport { rovingTarget } from '../../core/roving.ts';\nimport { UiMenuItem } from './menu-item.ts';\nimport { UiMenuGroup } from './menu-group.ts';\nimport { deepActiveElement, type MenuSize, type MenuFocus, type MenuSelectDetail } from './menu-shared.ts';\nimport { outsidePress, trackAnchor } from '../../core/popup.ts';\nexport * from './menu-item.ts';\nexport * from './menu-divider.ts';\nexport * from './menu-group.ts';\nexport { openMenuFromKey } from './menu-shared.ts';\nexport type { MenuSize, MenuFocus, MenuSelectDetail } from './menu-shared.ts';\n\nexport type MenuPlacement = 'top' | 'top-start' | 'top-end' | 'bottom' | 'bottom-start' | 'bottom-end';\n\n/** Where Carbon puts a submenu (measured on react.carbondesignsystem.com): 2px beside the item and 2px below its top. */\nconst SUBMENU_OFFSET = 2;\n\n/** Items in flattened-tree order: direct children, through `<slot>`s and groups. */\nexport function collectMenuItems(root: Element): UiMenuItem[] {\n    const out: UiMenuItem[] = [];\n    const visit = (nodes: Element[]) => {\n        for (const node of nodes) {\n            if (node instanceof HTMLSlotElement) visit(node.assignedElements({ flatten: true }));\n            else if (node instanceof UiMenuItem) out.push(node);\n            else if (node instanceof UiMenuGroup) visit([...node.children]);\n        }\n    };\n    visit([...root.children]);\n    return out;\n}\n\n/**\n * Carbon `Menu`: the floating `role=menu` list behind `<ui-overflow-menu>` and `<ui-menu-button>`,\n * usable on its own with `show(anchor)`. Lives in the top layer (`popover=\"manual\"`) at document\n * coordinates next to `anchor` (flips when it doesn't fit). On open, focus moves to the first\n * enabled item; Up/Down wrap, Home/End jump; Escape or Tab close and return focus; so does\n * activating an item, clicking outside or focus leaving.\n *\n * Nested submenus: `<ui-menu-item>`s inside an item (see `<ui-menu-item>`).\n *\n * @slot - `<ui-menu-item>`, `<ui-menu-divider>`, `<ui-menu-group>`\n * @fires ui-toggle - detail: { open } after it opens or closes\n * @attr align - Carbon's name for `placement` (same values)\n * @cssprop --ui-menu-padding / --ui-menu-border / --ui-menu-radius / --ui-menu-shadow - The menu box, as the dropdown lists\n * @cssprop --ui-menu-item-radius / --ui-menu-item-ink - Its rows (on `<ui-menu-item>`)\n * @cssprop --ui-menu-min-width / --ui-menu-max-width - Width range (default 160px to 288px; Kanok: 180px to 320px)\n * @cssprop --ui-menu-item-height / --ui-menu-item-active-outline / --ui-menu-item-active-background - Every row's height and the focused row's ring or fill (on `<ui-menu-item>`)\n */\n@customElement('ui-menu')\nexport class UiMenu extends WithAlign(UiElement) {\n    static override readonly styles = css`\n        :host {\n            position: absolute; /* document coordinates in the top layer, see position.ts */\n            inset: auto;\n            display: none;\n            box-sizing: border-box;\n            /* --ui-menu-min-width / -max-width: a design can let a menu grow to its labels (Carbon: 160 to 288px) */\n            min-inline-size: var(--ui-menu-min-width, 160px);\n            max-inline-size: var(--ui-menu-max-width, 288px);\n            margin: 0;\n            /* the menu settings, as the dropdown lists (shared/listbox.ts) */\n            padding: var(--ui-menu-padding, 0);\n            border: var(--ui-menu-border, none);\n            border-radius: var(--ui-menu-radius, 0);\n            background-color: var(--ui-overlay-background, var(--ui-surface-1)); /* a design can raise floating surfaces (--ui-overlay-background) */\n            color: var(--ui-ink);\n            font-family: var(--ui-font-family);\n            box-shadow: var(--ui-menu-shadow, 0 2px 6px rgb(0 0 0 / 0.3));\n            /* the room left beside its anchor (core/popup placePopup): a long menu scrolls instead of running past the screen */\n            max-block-size: var(--ui-available-height, none);\n            overflow-y: auto;\n            overscroll-behavior: contain; /* scrolling past the end doesn't scroll the page */\n            outline: none;\n        }\n\n        :host(:popover-open) {\n            display: block;\n        }\n\n        /* 4px above the first item and below the last, on a part: a page-wide CSS reset would remove :host padding */\n        .base {\n            padding-block: var(--ui-space-xxs);\n        }\n\n        :host([data-icons]) {\n            min-inline-size: 192px;\n        }\n\n        :host([data-side='top']) {\n            box-shadow: var(--ui-menu-shadow, 0 -2px 6px rgb(0 0 0 / 0.3));\n        }\n\n        /* Carbon .cds--menu--open:focus, focus-outline('border'): 1px, no offset (focused only when no item is enabled) */\n        :host(:focus) {\n            outline: 1px solid var(--ui-focus);\n        }\n\n        @media screen and (prefers-contrast) {\n            :host(:focus) {\n                outline-style: dotted;\n            }\n        }\n\n        /* an outline, not a border: a page-wide CSS reset would remove a :host border */\n        @media (forced-colors: active) {\n            :host {\n                outline: 1px solid CanvasText;\n                outline-offset: -1px;\n            }\n        }\n    `;\n\n    @property({ type: Boolean, reflect: true }) open = false;\n\n    /** Accessible name of the menu (the trigger's label). */\n    @property() label = '';\n\n    @property({ reflect: true }) size: MenuSize = 'sm';\n\n    @property() placement: MenuPlacement = 'bottom-start';\n\n    /** Make the menu as wide as the anchor (Carbon menu button with `bottom` / `top`). */\n    @property({ type: Boolean, attribute: 'match-width' }) matchWidth = false;\n\n    /** What the menu is positioned against; `show(anchor)` sets it. */\n    @property({ attribute: false }) anchor: Element | null = null;\n\n    private returnFocus: HTMLElement | null = null;\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'menu');\n        if (!this.hasAttribute('tabindex')) this.tabIndex = -1;\n        if (!this.hasAttribute('popover')) this.setAttribute('popover', 'manual');\n        this.addEventListener('keydown', this.onKeydown);\n        this.addEventListener('focusout', this.onFocusOut);\n        this.addEventListener('ui-select', this.hide);\n        this.addEventListener('slotchange', this.sync); // a <slot> passed in as a child (overflow menu, menu button)\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.removeEventListener('keydown', this.onKeydown);\n        this.removeEventListener('focusout', this.onFocusOut);\n        this.removeEventListener('ui-select', this.hide);\n        this.removeEventListener('slotchange', this.sync);\n        this.stopTracking();\n    }\n\n    /**\n     * Open next to `anchor`; `focus: 'last'` starts on the last item (Up Arrow on a menu button),\n     * `none` leaves focus where it is (a submenu opened by hover).\n     */\n    show(anchor?: Element, focus: MenuFocus = 'first') {\n        if (anchor) this.anchor = anchor;\n        this.initialFocus = focus;\n        this.open = true;\n    }\n\n    /** Focus the first or last enabled item. */\n    focusItem(which: 'first' | 'last') {\n        const items = this.enabledItems();\n        (which === 'last' ? items.at(-1) : items[0])?.focus();\n    }\n\n    /** A submenu: the `<ui-menu>` a `<ui-menu-item>` renders for its child items. */\n    private get parentItem(): UiMenuItem | null {\n        const host = (this.getRootNode() as ShadowRoot).host;\n        return host instanceof UiMenuItem ? host : null;\n    }\n\n    private initialFocus: MenuFocus = 'first';\n    private readonly typeahead = new Typeahead();\n\n    readonly hide = () => {\n        this.open = false;\n    };\n\n    get items() {\n        return collectMenuItems(this);\n    }\n\n    private enabledItems() {\n        return this.items.filter((i) => !i.disabled);\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('size')) this.sync();\n        if (changed.has('label')) setManagedAttribute(this, 'aria-label', this.label || null);\n        if (!changed.has('open')) return;\n        if (this.open) this.onOpen();\n        else this.onClose();\n        if (changed.get('open') !== undefined) {\n            // a submenu's toggle stays inside its item, so it can't reach a menu button listening on the outer menu\n            this.dispatchEvent(new CustomEvent('ui-toggle', { detail: { open: this.open }, bubbles: true, composed: !this.parentItem }));\n        }\n    }\n\n    private onOpen() {\n        // Where focus goes back to on close: whatever had it, else the anchor (opened by script / a programmatic click).\n        const active = deepActiveElement();\n        this.returnFocus = active && active !== document.body ? active : (this.anchor as HTMLElement | null);\n        if (this.parentItem) this.returnFocus = this.parentItem; // a submenu gives focus back to its item\n        if (!this.matches(':popover-open')) this.showPopover();\n        this.sync();\n        this.position();\n        if (this.initialFocus !== 'none') {\n            const items = this.enabledItems();\n            const first = this.initialFocus === 'last' ? items.at(-1) : items[0];\n            (first ?? this).focus();\n        }\n        this.initialFocus = 'first';\n        // on its anchor while open (scrolling ancestors in any shadow root, layout shifts); a finger scroll doesn't close it\n        this.stopTracking();\n        this.untrack = trackAnchor(this.anchor ?? this, this, this.reposition);\n        this.stopOutside = outsidePress(document, this.onDocumentPointerDown);\n    }\n\n    /** Inside the menu in the flattened tree: items may be light-DOM children slotted in from a parent component. */\n    private isInside(node: Node | null) {\n        if (!node) return false;\n        return node === this || this.contains(node) || !!this.shadowRoot?.contains(node) || this.items.some((i) => i.contains(node));\n    }\n\n    private onClose() {\n        const focusInside = this.isInside(deepActiveElement());\n        for (const item of this.items) item.closeSubmenu(); // nested popovers don't close with their parent\n        if (this.matches(':popover-open')) this.hidePopover();\n        this.stopTracking();\n        if (focusInside) {\n            this.returnFocus?.focus();\n            if (this.isInside(deepActiveElement())) deepActiveElement()?.blur(); // nothing took focus back (e.g. a non-focusable anchor)\n        }\n        this.returnFocus = null;\n    }\n\n    private untrack?: () => void;\n    private stopOutside?: () => void;\n\n    private stopTracking() {\n        this.untrack?.();\n        this.stopOutside?.();\n        this.untrack = this.stopOutside = undefined;\n    }\n\n    private readonly reposition = () => this.position();\n\n    private position() {\n        if (!this.anchor) return;\n        if (this.parentItem) {\n            // beside the item like Carbon's; flips to the other side when there is no room\n            const rtl = this.parentItem.matches(':dir(rtl)');\n            this.dataset.side = placeFloating(this.anchor, this, rtl ? 'left-start' : 'right-start', SUBMENU_OFFSET, { size: true });\n            this.style.top = `${Number.parseFloat(this.style.top) + SUBMENU_OFFSET}px`;\n            return;\n        }\n        if (this.matchWidth) this.style.width = `${this.anchor.getBoundingClientRect().width}px`;\n        this.dataset.side = placeFloating(this.anchor, this, this.placement, 0, { size: true });\n    }\n\n    /** Push row size and the icon / selection columns to every item (Carbon `with-icons` / `with-selectable-items`). */\n    private readonly sync = () => {\n        const items = this.items;\n        const icons = items.some((i) => i.querySelector(':scope > [slot=\"icon\"]'));\n        const selectable = items.some((i) => i.selectable || i.radio);\n        for (const item of items) {\n            item.dataset.size = this.size;\n            item.toggleAttribute('data-icons', icons);\n            item.toggleAttribute('data-selectable', selectable);\n        }\n        this.toggleAttribute('data-icons', icons);\n    };\n\n    private readonly onDocumentPointerDown = (event: PointerEvent) => {\n        const path = event.composedPath();\n        if (!path.includes(this) && !(this.anchor && path.includes(this.anchor))) this.hide();\n    };\n\n    private readonly onFocusOut = (event: FocusEvent) => {\n        if (!this.isInside(event.relatedTarget as Node | null)) this.hide();\n    };\n\n    private readonly onKeydown = (event: KeyboardEvent) => {\n        const submenu = this.parentItem !== null;\n        const closesLevel = event.key === (this.matches(':dir(rtl)') ? 'ArrowRight' : 'ArrowLeft');\n        if (submenu && (event.key === 'Escape' || closesLevel)) {\n            // just this level: focus goes back to the parent item, the outer menu stays open\n            event.preventDefault();\n            event.stopPropagation();\n            this.hide();\n            return;\n        }\n        if (event.key === 'Escape' || event.key === 'Tab') {\n            event.preventDefault();\n            this.hide();\n            return;\n        }\n        const items = this.enabledItems();\n        if (!items.length) return;\n        const current = items.findIndex((i) => i === event.target || i.contains(event.target as Node));\n        const moved = rovingTarget(items.length, current, event.key, { orientation: 'vertical' });\n        const index = moved ?? this.typeahead.match(event, items, current, (i) => i.label || i.textContent || '');\n        const next = index === undefined ? undefined : items[index];\n        if (!next) return;\n        event.preventDefault();\n        if (submenu) event.stopPropagation(); // the outer menu would move its own focus too\n        next.focus();\n    };\n\n    override render() {\n        return html`<div class=\"base\"><slot @slotchange=${this.sync}></slot></div>`;\n    }\n}\n\nexport interface UiMenuEventMap extends HTMLElementEventMap {\n    'ui-toggle': CustomEvent<OpenDetail>;\n    'ui-select': CustomEvent<MenuSelectDetail>;\n}\n\n/** Typed listeners for UiMenu's events (declaration merging with the class). */\nexport interface UiMenu {\n    addEventListener<K extends keyof UiMenuEventMap>(type: K, listener: (this: UiMenu, event: UiMenuEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiMenuEventMap>(type: K, listener: (this: UiMenu, event: UiMenuEventMap[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-menu': UiMenu;\n    }\n}\n"
    }
  ]
}
