{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dropdown",
  "type": "registry:ui",
  "title": "<ui-dropdown>",
  "description": "Carbon-style dropdown: a custom list box, the counterpart of ui-select (native `<select>`) — Carbon ships both as `Select` and `Dropdown`. Use this when options need a consistent look across platforms or per-option styling; use ui-select for plain forms. 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-dropdown",
    "@kanok-ui/core-listbox",
    "@kanok-ui/core-popup",
    "@kanok-ui/core-typeahead",
    "@kanok-ui/shared-element",
    "@kanok-ui/shared-events",
    "@kanok-ui/shared-field",
    "@kanok-ui/shared-form-control",
    "@kanok-ui/shared-listbox",
    "@kanok-ui/shared-localize",
    "@kanok-ui/shared-position",
    "@kanok-ui/shared-quiet-focus",
    "@kanok-ui/shared-skeleton",
    "@kanok-ui/shared-slots",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/dropdown/dropdown-skeleton.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/dropdown/dropdown-skeleton.ts",
      "content": "import { customElement } from 'lit/decorators.js';\nimport { UiFieldSkeleton } from '../shared/skeleton.ts';\n\n/**\n * Carbon `DropdownSkeleton` (`cds-dropdown-skeleton`): the shape of a `<ui-dropdown>` while its data loads — a 75×14 label bar, 8px, then\n * the field's bar at its `size` (sm 32 / md 40 / lg 48px). Hidden from assistive tech. Also for ComboBox and MultiSelect, as in Carbon.\n *\n * @csspart label - The label bar\n * @csspart field - The field bar\n */\n@customElement('ui-dropdown-skeleton')\nexport class UiDropdownSkeleton extends UiFieldSkeleton {}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-dropdown-skeleton': UiDropdownSkeleton;\n    }\n}\n"
    },
    {
      "path": "src/primitives/dropdown/dropdown.styles.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/dropdown/dropdown.styles.ts",
      "content": "import { css } from 'lit';\n\n/** Styles of `<ui-dropdown>`. */\nexport const dropdownStyles = css`\n    :host {\n        --_h: var(--ui-field-height-lg, 48px);\n\n        display: block;\n        font-family: var(--ui-font-family);\n    }\n\n    :host([size='sm']) {\n        --_h: var(--ui-field-height-sm, 32px);\n    }\n\n    :host([size='md']) {\n        --_h: var(--ui-field-height-md, 40px);\n    }\n\n    .field {\n        position: relative;\n    }\n\n    .trigger {\n        box-sizing: border-box;\n        display: flex;\n        align-items: center;\n        width: 100%;\n        height: var(--_h);\n        margin: 0;\n        padding: 0 calc(var(--ui-space-md) * 2 + 16px) 0 var(--ui-space-md);\n        /* Carbon: an underline only; --ui-field-border (all sides), --ui-field-radius and --ui-field-background let a design outline the box */\n        border: var(--ui-field-border, none);\n        border-bottom: 1px solid var(--ui-field-underline-color, var(--ui-ink-subtle));\n        border-radius: var(--ui-field-radius, var(--ui-radius-none));\n        background-color: var(--ui-field-background, var(--ui-surface-1));\n        color: var(--ui-ink);\n        font: var(--ui-font-body-sm);\n        letter-spacing: var(--ui-tracking-body);\n        text-align: start;\n        cursor: pointer;\n        outline: var(--ui-field-focus-width, 2px) solid transparent; /* the ring's width (Kanok: 1.5px, on the field's own border) */\n        outline-offset: calc(-1 * var(--ui-field-focus-width, 2px));\n        transition:\n            background-color var(--ui-duration-fast) var(--ui-easing),\n            border-color var(--ui-duration-fast) var(--ui-easing),\n            border-bottom-color var(--ui-duration-fast) var(--ui-easing),\n            outline-color var(--ui-duration-fast) var(--ui-easing),\n            box-shadow var(--ui-duration-fast) var(--ui-easing);\n    }\n\n    .trigger:hover {\n        background-color: var(--ui-ghost-hover);\n        border-color: var(--ui-field-hover-border-color, var(--ui-border-strong-1));\n        border-bottom-color: var(--ui-field-hover-border-color, var(--ui-border-strong-1));\n    }\n\n    /* open, the field keeps its fill under the pointer (--ui-field-open-background; Carbon: the hover fill) */\n    .trigger[aria-expanded='true']:hover {\n        background-color: var(--ui-field-open-background, var(--ui-ghost-hover));\n    }\n\n    .trigger:focus,\n    .trigger[aria-expanded='true'] {\n        border-color: var(--ui-field-focus-border-color, inherit);\n        border-bottom-color: var(--ui-field-focus-border-color, var(--ui-ink-subtle));\n        outline-color: var(--ui-focus);\n        box-shadow: var(--ui-field-focus-halo, none); /* a design's halo outside the ring (Kanok: none) */\n    }\n\n    .text {\n        overflow: hidden;\n        white-space: nowrap;\n        text-overflow: ellipsis;\n    }\n\n    .placeholder .text {\n        color: var(--ui-ink-muted);\n    }\n\n    .invalid .trigger {\n        outline-color: var(--ui-error);\n        box-shadow: var(--ui-field-invalid-halo, none); /* a design's error halo (Kanok: Pixiv's red ring) */\n    }\n\n    .invalid .trigger:focus {\n        outline-color: var(--ui-focus);\n        box-shadow: var(--ui-field-invalid-halo, var(--ui-field-focus-halo, none)); /* an error keeps its halo while focused (Kanok: Pixiv's red) */\n    }\n\n    .trigger:disabled {\n        border-color: var(--ui-field-disabled-border-color, currentColor currentColor transparent);\n        color: var(--ui-ink-disabled);\n        cursor: not-allowed;\n        background-color: var(--ui-field-background, var(--ui-surface-1));\n    }\n\n    :host([readonly]) .trigger {\n        background-color: var(--ui-field-readonly-background, transparent);\n        border-color: var(--ui-field-readonly-border-color, currentColor currentColor var(--ui-hairline));\n        cursor: default;\n    }\n\n    .icons {\n        position: absolute;\n        inset-block: 0;\n        inset-inline-end: var(--ui-space-md); /* Carbon list-box menu icon: 24px box 12px from the end, so the 16px glyph is 16px from it */\n        display: flex;\n        align-items: center;\n        gap: var(--ui-space-xs);\n        pointer-events: none;\n    }\n\n    .chevron {\n        width: 16px;\n        height: 16px;\n        fill: var(--ui-ink);\n        transition: transform var(--ui-duration-fast) var(--ui-easing);\n    }\n\n    .open .chevron {\n        transform: rotate(180deg);\n    }\n\n    :host([readonly]) .chevron {\n        fill: var(--ui-ink-subtle);\n    }\n\n    .trigger:disabled ~ .icons .chevron {\n        fill: var(--ui-ink-disabled);\n    }\n\n    .has-status .trigger {\n        padding-inline-end: 64px; /* Carbon list-box field with a status icon */\n    }\n\n    /* Carbon inline dropdown (measured on react.carbondesignsystem.com): label, field and message in one row */\n    :host([inline]) {\n        display: inline-grid;\n        grid-template-columns: auto auto auto;\n        justify-content: start;\n        align-items: center;\n        column-gap: var(--ui-space-xs);\n    }\n\n    :host([inline]) .label {\n        margin-bottom: 0;\n        font: var(--ui-font-body-sm);\n        letter-spacing: var(--ui-tracking-body);\n    }\n\n    :host([inline]) .trigger {\n        width: auto;\n        min-width: 0;\n        background-color: transparent;\n        border-color: var(--ui-field-inline-border-color, currentColor currentColor transparent);\n    }\n\n    :host([inline]) .trigger:hover {\n        background-color: var(--ui-ghost-hover);\n    }\n\n    :host([inline]) .has-status .trigger {\n        padding-inline-end: 64px;\n    }\n\n    :host([inline]) .icons {\n        inset-inline-end: var(--ui-space-md);\n    }\n\n    /* the error / warning sits after the field; Carbon's inline dropdown has no helper line */\n    :host([inline]) .warn,\n    :host([inline]) .error {\n        margin: 0;\n    }\n\n    :host([inline]) .helper {\n        display: none;\n    }\n\n    @media (forced-colors: active) {\n        .trigger {\n            border: 1px solid FieldText;\n        }\n        .trigger:focus {\n            outline-color: Highlight;\n        }\n        .chevron {\n            fill: FieldText;\n        }\n    }\n`;\n\n/** Styles of `<ui-dropdown>` when fluid (`fluid`, or inside a `<ui-fluid-form>`): the 64px box with the label inside. */\nexport const dropdownFluidStyles = css`\n    /* the 64px box is the field's; the open list keeps its rows (--_h), not Carbon's 64px fluid rows (user's choice) */\n    :host([data-fluid]) .trigger,\n    :host([data-fluid]) .has-status .trigger {\n        height: 64px;\n        padding: 33px 48px 13px var(--ui-space-md);\n    }\n\n    /* Carbon fluid dropdown: the chevron 34px down, 16px from the end */\n    :host([data-fluid]) .icons {\n        align-items: flex-start;\n        padding-block-start: 34px;\n        inset-inline-end: var(--ui-space-md);\n    }\n`;\n"
    },
    {
      "path": "src/primitives/dropdown/dropdown.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/dropdown/dropdown.ts",
      "content": "import { LitElement, html, nothing } from 'lit';\nimport type { OpenDetail } from '../shared/events.ts';\nimport { customElement, property, query, state } from 'lit/decorators.js';\nimport { fieldTextStyles, messageId, pickMessage, renderMessage, renderStatusIcon, srOnlyStyles, uid, renderLabelText, barWhenDisabled, selectedOptionValue, customErrorMessage, pickErrorText, syncFluid, fluidFieldStyles, markStatus } from '../shared/field.ts';\nimport { FormControlController } from '../shared/form-control.ts';\nimport { SlotController } from '../shared/slots.ts';\nimport { placeFloating } from '../shared/position.ts';\nimport { LocalizeController } from '../shared/localize.ts';\nimport {\n    flattenGroups,\n    listboxStyles,\n    listboxEmptyStyles,\n    readOptionGroups,\n    renderGroupedRows,\n    sameOption,\n    type OptionData,\n    type OptionGroup,\n    renderOptionText,\n} from '../shared/listbox.ts';\nimport { UiElement } from '../shared/element.ts';\nimport { markQuiet } from '../shared/quiet-focus.ts';\nimport { Typeahead } from '../../core/typeahead.ts';\nimport { dropdownKey, openingRow, type DropdownStep } from '../../core/dropdown.ts';\nimport { reconcileActive } from '../../core/listbox.ts';\nimport { outsidePress, scrollIntoList, trackAnchor } from '../../core/popup.ts';\nimport { dropdownStyles, dropdownFluidStyles } from './dropdown.styles.ts';\n\n/**\n * Carbon-style dropdown: a custom list box, the counterpart of ui-select (native `<select>`) —\n * Carbon ships both as `Select` and `Dropdown`. Use this when options need a consistent look\n * across platforms or per-option styling; use ui-select for plain forms.\n *\n * Follows the WAI-ARIA APG \"Select-Only Combobox\" pattern: the field is a button with\n * role=combobox, the list is role=listbox, focus stays on the field and the active option\n * is exposed through aria-activedescendant.\n *\n * - Keys as Carbon (React Dropdown traced key by key; cds-dropdown's code agrees where it works):\n *   closed: ↓ Enter Space Alt+↓ open (on the chosen option, else the first); ↑ does nothing;\n *   Home / End open on the first / last option; typing a letter opens on the next match.\n * - Open: ↓ ↑ move (no wrap), PageUp / PageDown move by 10, Home / End, typing jumps to a match,\n *   Enter / Space / Alt+↑ select the active option and close; Esc closes unchanged; Tab closes\n *   unchanged and moves on (Carbon doesn't pick on Tab).\n * - Author `<option value>` children (same markup as ui-select), optionally inside `<optgroup>`,\n *   which become labelled groups in the list. `disabled` options are shown but skipped.\n *   Form-associated: submits `value`; honours `required`. A `value` no option has shows the placeholder and\n *   counts as no choice (submits '', fails `required`) once the options are there and not `loading`.\n * - `inline`: label, borderless field and error / warning in one row, no helper line (Carbon's\n *   inline dropdown; toolbars).\n * - `readonly` keeps and submits the value but can't be opened; `warn` is a non-blocking warning.\n * - `loading` (no Carbon counterpart): the list shows one \"Loading…\" row instead of the options\n *   (busy, announced) and the keys pick nothing; with `ui-toggle` an app can load the options the\n *   first time the list opens.\n * - The field carries an explicit `tabindex=\"0\"`: Safari's default Tab order skips plain buttons\n *   but not elements with a tabindex, and a form control must be reachable like a native `<select>`.\n * - State on the host for app styles: `data-open` while the list is open, `data-show-error` /\n *   `data-show-warn` while the error / warning line shows, `data-placeholder` while the placeholder\n *   is the shown choice (e.g. `ui-dropdown[data-open]::part(base)`).\n *\n * @cssstate open - While its list or calendar is open (also `[data-open]`)\n * @cssstate show-error - While its error message shows (also `[data-show-error]`)\n * @cssstate show-warn - While its warning message shows (also `[data-show-warn]`)\n * @cssstate placeholder - While the placeholder is the shown choice (also `[data-placeholder]`)\n * @fires change - When the user picks a different option\n * @fires input - Whenever `value` changes, just before `change` (as ui-combobox and ui-multi-select)\n * @fires ui-toggle - detail: { open } after the list opens or closes (Carbon `cds-dropdown-toggled`)\n * @slot label - Label content with markup; the `label` attribute is the plain-text fallback\n * @slot helper-text - Helper text with markup (links, bold); overrides `helper-text`\n * @slot warn-text - Warning text shown while `warn`; overrides `warn-text`\n * @slot invalid-text - Error text shown while invalid; overrides `invalid-text`\n * @csspart option-description - Second line of an option (`<option data-description>`)\n * @csspart base - The field box\n * @csspart label - The label\n * @csspart input - The field button (role=combobox)\n * @csspart chevron - The arrow icon\n * @csspart status-icon - The error / warning icon\n * @csspart helper-text - The helper line\n * @csspart warning-text - The warning line\n * @csspart warn-text - Same line as `warning-text` (named after the `warn-text` attribute / slot)\n * @csspart error-text - The error line\n * @csspart invalid-text - Same line as `error-text` (named after the `invalid-text` attribute / slot)\n * @csspart menu - The floating list\n * @csspart option - Each row\n * @csspart group-label - An `<optgroup>` heading\n * @cssprop --ui-field-border - Border on every side of the box (default none: Carbon's underline only; Kanok: a 1px outline)\n * @cssprop --ui-field-disabled-border-color - Border colour when disabled (default: the underline transparent)\n * @cssprop --ui-field-readonly-border-color - Border colour when read-only (default: a hairline underline)\n * @cssprop --ui-field-inline-border-color - Border colour of the `inline` variant (default: no underline)\n * @cssprop --ui-field-radius - Corner radius of the box (default 0; Kanok: 6px)\n * @cssprop --ui-field-background - Fill of the box (default `--ui-surface-1`; Kanok: transparent)\n * @cssprop --ui-label-font - Font of the label (default `--ui-font-caption`; Kanok: 14px semibold)\n * @cssprop --ui-label-color - Colour of the label (default `--ui-ink-muted`; Kanok: `--ui-ink`)\n * @cssprop --ui-menu-radius - Corner radius of the open list (default 0; Kanok: 8px)\n * @cssprop --ui-menu-border - Border around the list (default none; Kanok: a hairline)\n * @cssprop --ui-menu-shadow - `box-shadow` of the list (default Carbon's 0 2px 6px)\n * @cssprop --ui-menu-padding - Padding of the open list (default 0; Kanok: 4px, rows inset)\n * @cssprop --ui-menu-item-radius - Corner radius of a row (default 0; Kanok: 6px)\n * @cssprop --ui-menu-item-ink - Text of a row at rest (default `--ui-ink-muted`; Kanok: `--ui-ink`)\n * @cssprop --ui-menu-divider - Rule between rows (default `--ui-row-divider`; Kanok: none)\n * @cssprop --ui-menu-item-selected - Fill of the chosen row (default `--ui-surface-2`; Kanok: `--ui-highlight`)\n * @cssprop --ui-menu-item-selected-hover - The chosen row under the pointer (default `--ui-layer-selected-hover`; Kanok: the highlight a shade deeper)\n * @cssprop --ui-field-readonly-background - The box's fill when read-only (default transparent; Kanok: a faint ink tint, so read-only reads as set and never weaker than disabled)\n * @cssprop --ui-field-open-background - The box's fill while its list is open (default the field's hover fill; Kanok: transparent)\n * @cssprop --ui-fluid-background / --ui-fluid-gap - A fluid box's fill and the space under it (default the layer's fill, 0: boxes that touch; Kanok: transparent, 8px)\n * @cssprop --ui-menu-item-active-outline / --ui-menu-item-active-background - The keyboard-highlighted row: its ring and its fill (default focus, transparent)\n * @cssprop --ui-menu-item-pressed - Fill of a pressed option (default `--ui-surface-2`; Kanok: the 20% pressed tint)\n */\n@customElement('ui-dropdown')\nexport class UiDropdown extends UiElement {\n    static override hostStates: readonly string[] = ['open', 'show-error', 'show-warn', 'placeholder'];\n\n    static readonly formAssociated = true;\n\n    static override readonly shadowRootOptions: ShadowRootInit = {\n        ...LitElement.shadowRootOptions,\n        delegatesFocus: true,\n    };\n\n    static override readonly styles = [\n        fieldTextStyles,\n        srOnlyStyles,\n        listboxStyles,\n        listboxEmptyStyles,\n        dropdownStyles,\n        fluidFieldStyles,\n        dropdownFluidStyles,\n    ];\n\n    /** Visible label text; the `label` slot replaces it when markup is needed. */\n    @property() label = '';\n\n    /** Keep the label for screen readers but don't show it. */\n    @property({ type: Boolean, attribute: 'hide-label' }) hideLabel = false;\n\n    /** Helper text under the field, shown while there is no error or warning. */\n    @property({ attribute: 'helper-text' }) helperText = '';\n\n    /** Error text shown while `invalid` or while the field fails validation. */\n    @property({ attribute: 'invalid-text' }) invalidText = '';\n\n    /** Forces the error state, e.g. after server-side validation. */\n    @property({ type: Boolean, reflect: true }) invalid = false;\n\n    /** Non-blocking warning; shown when there is no error. */\n    @property({ type: Boolean, reflect: true }) warn = false;\n\n    /** Text of the warning shown while `warn`. */\n    @property({ attribute: 'warn-text' }) warnText = '';\n\n    /** Text shown in the field while nothing is selected (Carbon's `label`). */\n    @property() placeholder = '';\n\n    @property() value = '';\n\n    /** Reflected: form-associated elements submit under the `name` attribute. */\n    @property({ reflect: true }) name = '';\n\n    /** Field height: sm 32px, md 40px, lg 48px (tokens `--ui-field-height-*`). */\n    @property({ reflect: true }) size: 'sm' | 'md' | 'lg' = 'md'; // Carbon default (40px)\n\n    /** Preferred side for the list; it flips when there is no room. */\n    @property() direction: 'bottom' | 'top' = 'bottom';\n\n    /** Disables the control; a disabled `<fieldset>` ancestor does the same. */\n    @property({ type: Boolean, reflect: true }) disabled = false;\n\n    /** Blocks form submission while the field is empty. */\n    @property({ type: Boolean, reflect: true }) required = false;\n\n    /** Shows and submits the value but blocks changes. */\n    @property({ type: Boolean, reflect: true }) readonly = false;\n\n    /** The options are on their way: the list shows \"Loading…\" and the keys pick nothing (no Carbon counterpart). */\n    @property({ type: Boolean, reflect: true }) loading = false;\n\n    /** Carbon `FluidDropdown`: the label inside a 64px box, an error / warning inside it. `<ui-fluid-form>` sets it for every field inside. */\n    @property({ type: Boolean, reflect: true }) fluid = false;\n\n    /** Label beside a compact, borderless field. */\n    @property({ type: Boolean, reflect: true }) inline = false;\n\n    @state() private groups: OptionGroup[] = [];\n\n    @state() private options: OptionData[] = [];\n\n    @state() private open = false;\n\n    /** Option that holds the visual focus while the list is open; -1 = none. */\n    @state() private activeIndex = -1;\n\n    @state() private touched = false;\n\n    /** Disabled, reset defaults, validation on submit and the name given from outside (shared by the form fields). */\n    private readonly formControl = new FormControlController(this, { reveal: () => (this.touched = true) });\n\n    @query('.trigger') private readonly trigger!: HTMLButtonElement;\n\n    @query('.menu') private readonly menu!: HTMLElement;\n\n\n    /** Message from `setCustomValidity()`; '' = none. */\n    private customValidityMessage = '';\n\n    /** Like `<input>.setCustomValidity()`: a non-empty message makes the field invalid (and is shown as its error once touched) until cleared with ''. */\n    setCustomValidity(message: string) {\n        this.customValidityMessage = message;\n        if (!this.hasUpdated) return;\n        this.syncValidity();\n        this.requestUpdate();\n    }\n    private readonly localize = new LocalizeController(this);\n    private readonly fieldId = uid('ui-dropdown');\n    /** Created on connect: there is no MutationObserver when Lit renders on the server. */\n    private observer?: MutationObserver;\n    private defaultValue = '';\n    private readonly typed = new Typeahead();\n\n    override connectedCallback() {\n        super.connectedCallback();\n        syncFluid(this, this.fluid);\n        // first connection only: moving the element must not change what reset goes back to\n        this.formControl.captureDefaults(() => {\n            // like a native select, `<option selected>` is the initial (and reset) choice unless `value` is set\n            if (!this.value && !this.hasAttribute('value')) this.value = selectedOptionValue(this) ?? '';\n            this.defaultValue = this.value;\n        });\n        this.readOptions();\n        // the options inside changed; not the host's own attributes (its open, error and status marks would read the\n        // options again and render the whole list a second time)\n        this.observer ??= new MutationObserver((records) => {\n            if (records.some((r) => r.type !== 'attributes' || r.target !== this)) this.readOptions();\n        });\n        this.observer.observe(this, { childList: true, subtree: true, characterData: true, attributes: true });\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.observer?.disconnect();\n        this.removeMenuListeners();\n    }\n\n    get form() {\n        return this.internals.form;\n    }\n\n    get validationMessage() {\n        return this.internals.validationMessage;\n    }\n\n    /** Whether the field takes part in constraint validation (not while disabled), as natively. */\n    get willValidate() {\n        return this.internals.willValidate;\n    }\n\n    /** The `<label>`s that point at this field. */\n    get labels() {\n        return this.internals.labels;\n    }\n\n    reportValidity() {\n        return this.formControl.reportValidity(this.internals);\n    }\n\n    get validity() {\n        return this.internals.validity;\n    }\n\n    checkValidity() {\n        return this.internals.checkValidity();\n    }\n\n    formResetCallback() {\n        this.value = this.defaultValue;\n        this.touched = false;\n    }\n\n    /** Back/forward cache and autofill hand the saved value back here. */\n    formStateRestoreCallback(state: string | File | FormData | null) {\n        if (typeof state === 'string') this.value = state;\n    }\n\n    /** From an ancestor `<fieldset>`; kept apart so it never overwrites the author's `disabled`. */\n    formDisabledCallback(disabled: boolean) {\n        this.formControl.setFieldsetDisabled(disabled);\n    }\n\n    private get isDisabled() {\n        return this.formControl.disabled;\n    }\n\n    private get interactive() {\n        return !this.isDisabled && !this.readonly;\n    }\n\n    private get selectedIndex() {\n        return this.options.findIndex((o) => o.value === this.value);\n    }\n\n    protected override willUpdate(changed: Map<string, unknown>) {\n        syncFluid(this, this.fluid);\n        this.syncValidity();\n        // the options changed (or came) while the list is open: the highlight stays on a row that exists (core reconcileActive)\n        if (this.open && (changed.has('options') || changed.has('loading'))) {\n            const wasLoading = changed.has('loading') ? changed.get('loading') === true : this.loading;\n            const before = wasLoading ? [] : ((changed.get('options') as OptionData[] | undefined) ?? this.options);\n            this.activeIndex = reconcileActive(this.listed, before, this.activeIndex, {\n                open: true,\n                loading: this.loading,\n                arrived: wasLoading && !this.loading,\n                same: sameOption,\n                opening: (options) => openingRow(options, this.selectedIndex),\n            });\n        }\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('open')) {\n            if (this.open) markQuiet(this); // opened by a press: no keyboard ring on the highlighted row in Kanok\n            this.onOpenChanged();\n            if (changed.get('open') !== undefined) this.dispatchEvent(new CustomEvent('ui-toggle', { detail: { open: this.open }, bubbles: true, composed: true }));\n        } else if (this.open && changed.has('activeIndex')) this.scrollActiveIntoView();\n        this.syncHostState();\n    }\n\n    /** Internal states as presence attributes on the host, so app styles can select them (same conditions as render). */\n    private syncHostState() {\n        const kind = this.fieldMessage?.kind;\n        this.toggleAttribute('data-open', this.open);\n        this.toggleAttribute('data-show-error', kind === 'error');\n        this.toggleAttribute('data-show-warn', kind === 'warn');\n        this.toggleAttribute('data-placeholder', !this.options[this.selectedIndex]);\n    }\n\n    /** The options the keys move through: none while `loading`. */\n    private get listed() {\n        return this.loading ? [] : this.options;\n    }\n\n    /**\n     * A value no option has (a stale saved value, a typo) while the options are there: the field shows its\n     * placeholder, so it submits as no choice and doesn't satisfy `required` — what is sent is what is seen. While\n     * the options are still coming (none yet, or `loading`) the value is kept for them.\n     */\n    private get unmatched() {\n        return !!this.value && this.options.length > 0 && !this.loading && this.selectedIndex < 0;\n    }\n\n    private syncValidity() {\n        if (barWhenDisabled(this.internals, this.isDisabled)) return;\n        const unmatched = this.unmatched;\n        this.internals.setFormValue(unmatched ? '' : this.value);\n        const anchor = this.trigger ?? undefined;\n        const customError = customErrorMessage(this.invalid, this.invalidText, this.customValidityMessage);\n        if (customError) {\n            this.internals.setValidity({ customError: true }, customError, anchor);\n        } else if (this.required && (!this.value || unmatched)) {\n            this.internals.setValidity({ valueMissing: true }, this.localize.t.list.required, anchor);\n        } else {\n            this.internals.setValidity({});\n        }\n    }\n\n    private readOptions() {\n        this.groups = readOptionGroups(this);\n        this.options = flattenGroups(this.groups);\n    }\n\n    // ---- open / close ----\n\n    private openMenu(startIndex?: number) {\n        if (!this.interactive || this.open) return;\n        const start = this.loading ? -1 : (startIndex ?? openingRow(this.options, this.selectedIndex));\n        this.activeIndex = start;\n        this.open = true;\n    }\n\n    private close() {\n        this.open = false;\n        this.activeIndex = -1;\n    }\n\n    /** Mouse: Carbon highlights the chosen option, or nothing when none is chosen (the keyboard starts on the first). */\n    private toggle() {\n        if (this.open) this.close();\n        else this.openMenu(this.selectedIndex);\n    }\n\n    private readonly reposition = () => this.position();\n\n    private onOpenChanged() {\n        if (this.open) {\n            this.menu.showPopover();\n            this.position();\n            this.scrollActiveIntoView();\n            // on its field while open (scrolling ancestors in any shadow root, layout shifts); a finger scroll doesn't close it\n            this.stopTracking = trackAnchor(this.trigger, this.menu, this.reposition);\n            this.stopOutside = outsidePress(document, this.onDocumentPointerDown);\n        } else {\n            if (this.menu.matches(':popover-open')) this.menu.hidePopover();\n            this.removeMenuListeners();\n        }\n    }\n\n    private stopTracking?: () => void;\n    private stopOutside?: () => void;\n\n    private removeMenuListeners() {\n        this.stopTracking?.();\n        this.stopOutside?.();\n        this.stopTracking = this.stopOutside = undefined;\n    }\n\n    private position() {\n        this.menu.style.width = `${this.trigger.getBoundingClientRect().width}px`;\n        placeFloating(this.trigger, this.menu, `${this.direction}-start`, 0, { size: true });\n    }\n\n    private scrollActiveIntoView() {\n        // the list only, never the page (scrollIntoView would scroll the page too when the list sits partly off screen)\n        const active = this.menu.querySelector<HTMLElement>('.option.active');\n        if (active) scrollIntoList(active, this.menu);\n    }\n\n    /** Outside click closes without changing the value (the field itself toggles via its click handler). */\n    private readonly onDocumentPointerDown = (event: PointerEvent) => {\n        const path = event.composedPath();\n        if (!path.includes(this.menu) && !path.includes(this.trigger)) this.close();\n    };\n\n    private onTriggerFocusOut() {\n        if (this.open) this.close();\n    }\n\n    // ---- selection ----\n\n    private selectIndex(index: number) {\n        const option = this.options[index];\n        if (!option || option.disabled) return;\n        this.touched = true;\n        if (option.value !== this.value) {\n            this.value = option.value;\n            this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n            this.dispatchEvent(new Event('change', { bubbles: true }));\n        }\n    }\n\n    // ---- keyboard ----\n\n    /** The keyboard model of core/dropdown (Carbon Dropdown, traced key by key). */\n    private onTriggerKeydown(event: KeyboardEvent) {\n        if (!this.interactive) return;\n        const step = dropdownKey({ open: this.open, active: this.activeIndex, selected: this.selectedIndex }, this.listed, event, this.typed);\n        if (!step) return;\n        if (step.handled) event.preventDefault();\n        this.apply(step);\n    }\n\n    private apply(step: DropdownStep) {\n        if (step.pick !== undefined) this.selectIndex(step.pick);\n        if (!step.open) this.close();\n        else if (this.open) this.activeIndex = step.active;\n        else this.openMenu(step.active);\n    }\n\n    // ---- render ----\n\n    private get busy() {\n        return this.loading ? 'true' : nothing;\n    }\n\n    /** \"Loading…\" for screen readers: the disabled row in the list is never announced (WCAG 4.1.3). */\n    private get statusText() {\n        return this.open && this.loading ? this.localize.t.list.loadingOptions : '';\n    }\n\n    /** The options, or one \"Loading…\" row (never announced as an option: the status says it). */\n    private renderRows() {\n        if (this.loading) return html`<li class=\"empty\" part=\"empty\" role=\"option\" aria-disabled=\"true\" aria-selected=\"false\">${this.localize.t.list.loadingOptions}</li>`;\n        return renderGroupedRows(this.groups, this.fieldId, (o, i) => this.renderOption(o, i));\n    }\n\n    private renderOption(o: OptionData, i: number) {\n        const selected = o.value === this.value;\n        const classes = ['option', i === this.activeIndex ? 'active' : ''].join(' ');\n        return html`<li\n            id=\"${this.fieldId}-opt-${i}\"\n            class=${classes}\n            part=\"option\"\n            role=\"option\"\n            aria-selected=${selected ? 'true' : 'false'}\n            aria-disabled=${o.disabled ? 'true' : nothing}\n            @click=${() => this.onOptionClick(i)}\n        >\n            ${renderOptionText(o)}\n            ${selected ? this.renderCheck() : nothing}\n        </li>`;\n    }\n\n    private renderCheck() {\n        return html`<svg class=\"check\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n            <path d=\"m6.5 12.5-4-4 .7-.7 3.3 3.3 7.3-7.3.7.7z\" />\n        </svg>`;\n    }\n\n    private onOptionClick(i: number) {\n        this.selectIndex(i);\n        this.close();\n    }\n\n    private readonly slots = new SlotController(this);\n\n    private renderLabel() {\n        // no label of its own: an unseen one with the name given from outside (aria-label, a <label for>), if any\n        const unlabelled = !this.label && !this.slots.has('label');\n        const outside = unlabelled ? this.formControl.fallbackName(this.label, this.internals) : '';\n        if (unlabelled && !outside) return nothing;\n        return html`<span class=${this.hideLabel || unlabelled ? 'sr-only' : 'label'} part=\"label\" id=\"${this.fieldId}-label\">${renderLabelText(this.label, outside)}</span>`;\n    }\n\n    private get showError() {\n        return this.interactive && (this.invalid || (this.touched && !this.internals.validity.valid));\n    }\n\n    /** The one message line: error > warning > helper. */\n    private get fieldMessage() {\n        return pickMessage({\n            showError: this.showError,\n            errorText: pickErrorText(this.invalid, this.customValidityMessage, this.invalidText || this.internals.validationMessage),\n            showWarn: this.warn && this.interactive,\n            warnText: this.warnText,\n            helperText: this.helperText,\n            slots: this.slots,\n        });\n    }\n\n    override render() {\n        const showError = this.showError;\n        const message = this.fieldMessage;\n        markStatus(this, message);\n        const selected = this.options[this.selectedIndex];\n        const classes = [\n            showError ? 'invalid' : '',\n            message && message.kind !== 'helper' ? 'has-status' : '',\n            selected ? '' : 'placeholder',\n            this.open ? 'open' : '',\n        ]\n            .filter(Boolean)\n            .join(' ');\n        const active = this.open && this.activeIndex >= 0 ? `${this.fieldId}-opt-${this.activeIndex}` : nothing;\n\n        return html`\n            ${this.renderLabel()}\n            <div class=\"field ${classes}\" part=\"base\">\n                <button\n                    class=\"trigger\"\n                    part=\"input\"\n                    type=\"button\"\n                    tabindex=\"0\"\n                    role=\"combobox\"\n                    aria-haspopup=\"listbox\"\n                    aria-expanded=${this.open ? 'true' : 'false'}\n                    aria-controls=\"${this.fieldId}-list\"\n                    aria-activedescendant=${active}\n                    aria-labelledby=\"${this.fieldId}-label ${this.fieldId}-value\"\n                    aria-readonly=${this.readonly ? 'true' : nothing}\n                    aria-required=${this.required ? 'true' : nothing}\n                    aria-invalid=${showError ? 'true' : 'false'}\n                    aria-describedby=${messageId(this.fieldId, message) ?? nothing}\n                    ?disabled=${this.isDisabled}\n                    @click=${this.toggle}\n                    @keydown=${this.onTriggerKeydown}\n                    @focusout=${this.onTriggerFocusOut}\n                    @blur=${() => (this.touched = true)}\n                >\n                    <span class=\"text\" id=\"${this.fieldId}-value\">${selected?.label ?? this.placeholder}</span>\n                </button>\n                <span class=\"icons\" aria-hidden=\"true\">\n                    ${renderStatusIcon(message)}\n                    <svg class=\"chevron\" part=\"chevron\" viewBox=\"0 0 16 16\"><path d=\"M8 11 3 6l.7-.7L8 9.6l4.3-4.3.7.7z\" /></svg>\n                </span>\n            </div>\n            ${renderMessage(this.fieldId, message)}\n            <ul\n                class=\"menu\"\n                part=\"menu\"\n                id=\"${this.fieldId}-list\"\n                popover=\"manual\"\n                role=\"listbox\"\n                tabindex=\"-1\"\n                aria-labelledby=\"${this.fieldId}-label\"\n                aria-busy=${this.busy}\n                @mousedown=${(e: Event) => e.preventDefault()}\n            >\n                ${this.open ? this.renderRows() : nothing}\n            </ul>\n            <span class=\"sr-only\" role=\"status\">${this.statusText}</span>\n        `;\n    }\n}\n\nexport interface UiDropdownEventMap extends HTMLElementEventMap {\n    'ui-toggle': CustomEvent<OpenDetail>;\n}\n\n/** Typed listeners for UiDropdown's events (declaration merging with the class). */\nexport interface UiDropdown {\n    addEventListener<K extends keyof UiDropdownEventMap>(type: K, listener: (this: UiDropdown, event: UiDropdownEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiDropdownEventMap>(type: K, listener: (this: UiDropdown, event: UiDropdownEventMap[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-dropdown': UiDropdown;\n    }\n}\n"
    }
  ]
}
