{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "combobox",
  "type": "registry:ui",
  "title": "<ui-combobox>",
  "description": "Carbon-style combo box: a text box with a filterable list (Carbon `ComboBox`, built on downshift's useCombobox). The counterpart of ui-dropdown for long lists, searching and server-side lookups. 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-combobox",
    "@kanok-ui/core-listbox",
    "@kanok-ui/core-popup",
    "@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-slots",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/combobox/combobox.styles.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/combobox/combobox.styles.ts",
      "content": "import { css } from 'lit';\n\n/** Styles of `<ui-combobox>`. */\nexport const comboboxStyles = 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    input {\n        box-sizing: border-box;\n        width: 100%;\n        height: var(--_h);\n        margin: 0;\n        padding: 0 48px 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        font-size: var(--ui-field-font-size, 14px);\n        letter-spacing: var(--ui-tracking-body);\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        /* Carbon: the combo box's box is a text-input, background-color and outline at fast-01 */\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    input:hover:not(:disabled):not(:focus) {\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    input::placeholder {\n        color: var(--ui-ink-placeholder);\n        opacity: 1;\n    }\n\n    input:focus,\n    .open input {\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    .invalid input {\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 input:focus {\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-invalid-halo, var(--ui-field-focus-halo, none)); /* an error keeps its halo while focused (Kanok: Pixiv's red) */\n    }\n\n    input:disabled {\n        border-color: var(--ui-field-disabled-border-color, currentColor currentColor transparent);\n        color: var(--ui-ink-disabled);\n        cursor: not-allowed;\n    }\n\n    input:read-only:not(:disabled) {\n        background-color: var(--ui-field-readonly-background, transparent);\n        border-color: var(--ui-field-readonly-border-color, currentColor currentColor var(--ui-hairline));\n    }\n\n    @media (forced-colors: active) {\n        input {\n            border: 1px solid FieldText;\n        }\n        input:focus {\n            outline-color: Highlight;\n        }\n    }\n`;\n\n/** Styles of `<ui-combobox>` when fluid (`fluid`, or inside a `<ui-fluid-form>`): the 64px box with the label inside. */\nexport const comboboxFluidStyles = 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]) input,\n    :host([data-fluid]) .has-status input {\n        height: 64px;\n        padding: 33px 64px 13px var(--ui-space-md);\n    }\n\n    :host([data-fluid]) .has-clear input,\n    :host([data-fluid]) .has-status.has-clear input {\n        padding-inline-end: 96px;\n    }\n\n`;\n"
    },
    {
      "path": "src/primitives/combobox/combobox.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/combobox/combobox.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, type FieldMessage, 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    listboxControlStyles,\n    listboxEmptyStyles,\n    listboxStyles,\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 { comboFilter, comboboxKey, commitText, committedText, highlightForText, syncedComboText, type ComboStep } from '../../core/combobox.ts';\nimport { reconcileActive } from '../../core/listbox.ts';\nimport { outsidePress, scrollIntoList, trackAnchor } from '../../core/popup.ts';\nimport { comboboxStyles, comboboxFluidStyles } from './combobox.styles.ts';\n\n/** How typed text narrows the list. Carbon shows every item unless a filter is given (`none`). */\nexport type ComboboxFilter = 'none' | 'contains' | 'starts-with';\n\n/**\n * Carbon-style combo box: a text box with a filterable list (Carbon `ComboBox`, built on\n * downshift's useCombobox). The counterpart of ui-dropdown for long lists, searching and\n * server-side lookups.\n *\n * - Options are `<option value>` children (optionally in `<optgroup>`), like ui-select / ui-dropdown. For a server search,\n *   listen to `ui-input` on the host, fetch with its `value` (`inputValue`), re-render the options and toggle\n *   `loading`; the list shows \"Searching…\" / \"No matching items\" rows meanwhile.\n * - `filter`: `none` (Carbon default — all options stay visible), `contains` or `starts-with`.\n * - Keys as Carbon (React ComboBox traced key by key; cds-combo-box agrees on typing): typing opens\n *   the list and highlights the first option containing the text. ↓ / ↑ open (↑ on the last option)\n *   and move the highlight (no wrap), Alt+↓ opens without a highlight, Alt+↑ picks the highlight and\n *   closes. Enter picks the highlight, or — with no highlight — the first option containing the\n *   text; Esc closes, and when already closed clears the field. Tab / blur don't pick the highlight\n *   (Carbon): an exact match is committed, otherwise the text snaps back to the selected option\n *   unless `allow-custom-value` lets free text stand.\n * - Clicking the text box opens the list (never closes it); the chevron toggles; × clears. Neither\n *   button takes focus or a Tab stop (Carbon `tabindex=\"-1\"`): Esc on a closed list clears from\n *   the keyboard. `hide-clear` drops × (not in Carbon, which always shows it).\n * - Form-associated: submits `value` (the option's value, or the free text with\n *   `allow-custom-value`); honours `required`. `readonly` keeps and submits the value.\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-has-value` while the box holds text\n *   (e.g. `ui-combobox[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 has-value - While it holds a value (also `[data-has-value]`)\n * @fires change - When the committed value changes\n * @fires input - Whenever `value` changes, as ui-dropdown and ui-multi-select; also native and composed as the user types, where `value` is unchanged (kept for compatibility: listen to `ui-input` for the typing)\n * @fires ui-input - detail: { value } the typed text (`inputValue`), as the user types\n * @fires ui-toggle - detail: { open } after the list opens or closes\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 text box (role=combobox)\n * @csspart clear-button - The × button\n * @csspart toggle - The chevron button\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 * @csspart empty - The \"searching\" / \"no results\" row\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-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-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-icon-control-radius - Corners of its small icon buttons, their hover fill and ring (default 0; Kanok: round)\n * @cssprop --ui-menu-item-pressed - Fill of a pressed option (default `--ui-surface-2`; Kanok: the 20% pressed tint)\n */\n@customElement('ui-combobox')\nexport class UiCombobox extends UiElement {\n    static override hostStates: readonly string[] = ['open', 'show-error', 'show-warn', 'has-value'];\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        listboxControlStyles,\n        listboxEmptyStyles,\n        comboboxStyles,\n        fluidFieldStyles,\n        comboboxFluidStyles,\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    @property() placeholder = '';\n\n    /** Committed value: the chosen option's value, or free text with `allow-custom-value`. */\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    @property() filter: ComboboxFilter = 'none';\n\n    /** Keep text that matches no option as the value instead of snapping back. */\n    @property({ type: Boolean, attribute: 'allow-custom-value' }) allowCustomValue = false;\n\n    /** No × button (Carbon always shows one while there is text); Escape on a closed list still clears. */\n    @property({ type: Boolean, reflect: true, attribute: 'hide-clear' }) hideClear = false;\n\n    /** Shows a \"Searching…\" row while a server lookup is running. */\n    @property({ type: Boolean, reflect: true }) loading = false;\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    /** Carbon `FluidComboBox`: 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    @state() private groups: OptionGroup[] = [];\n\n    @state() private options: OptionData[] = [];\n\n    @state() private text = '';\n\n    @state() private open = false;\n\n    /** Highlighted row, as an index into the filtered list; -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('input') private readonly input!: HTMLInputElement;\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-combobox');\n    /** Created on connect: there is no MutationObserver when Lit renders on the server. */\n    private observer?: MutationObserver;\n    private defaultValue = '';\n    private lastSyncedValue: string | null = null;\n    /** The rows listed at the last update: where the highlight was before the options changed. */\n    private shownRows: OptionData[] = [];\n\n    /** What the user currently sees in the text box. */\n    get inputValue() {\n        return this.text;\n    }\n\n    set inputValue(text: string) {\n        this.text = text;\n    }\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.lastSyncedValue = null;\n        this.requestUpdate('value');\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 messages() {\n        return this.localize.t.list;\n    }\n\n    /** Text the box should show for the committed value. */\n    private get committedText() {\n        return committedText(this.options, this.value, this.allowCustomValue);\n    }\n\n    /**\n     * Text still equal to the committed choice doesn't filter: opening the list to change a\n     * selection shows every option (MUI / React Aria behaviour; Carbon would show one row).\n     */\n    private get filteredGroups(): OptionGroup[] {\n        return [...comboFilter(this.groups, this.text, this.committedText, this.filter)];\n    }\n\n    private get filtered(): OptionData[] {\n        return flattenGroups(this.filteredGroups);\n    }\n\n    protected override willUpdate(changed: Map<string, unknown>) {\n        syncFluid(this, this.fluid);\n        // External value changes (and reset) re-fill the text box; our own commits set text themselves. Text the user\n        // hasn't touched follows the options: they came after the value (an async list) or were renamed (core).\n        if (changed.has('value') || changed.has('options')) {\n            const previousOptions = (changed.get('options') as OptionData[] | undefined) ?? this.options;\n            const next = syncedComboText({ text: this.text, value: this.value, syncedValue: this.lastSyncedValue, previousOptions }, this.options, this.allowCustomValue);\n            if (next !== undefined) this.text = next;\n            this.lastSyncedValue = this.value;\n        }\n        // the options changed, a search started (\"Searching…\") or its results came while open: the highlight stays on a\n        // row that exists, else goes to the text's match (core reconcileActive)\n        const listed = this.loading ? [] : this.filtered;\n        if (this.open && (changed.has('options') || changed.has('loading'))) {\n            const wasLoading = changed.has('loading') ? changed.get('loading') === true : this.loading;\n            this.activeIndex = reconcileActive(listed, wasLoading ? [] : this.shownRows, this.activeIndex, {\n                open: true,\n                loading: this.loading,\n                arrived: wasLoading && !this.loading,\n                same: sameOption,\n                opening: (rows) => highlightForText(rows, this.text),\n            });\n        }\n        this.shownRows = listed;\n        this.syncValidity();\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') || changed.has('text') || changed.has('options'))) {\n            this.position();\n            this.scrollActiveIntoView();\n        }\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-has-value', this.text !== '');\n    }\n\n    private syncValidity() {\n        if (barWhenDisabled(this.internals, this.isDisabled)) return;\n        this.internals.setFormValue(this.value);\n        const anchor = this.input ?? 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) {\n            this.internals.setValidity({ valueMissing: true }, this.messages.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(active = -1) {\n        if (!this.interactive) return;\n        this.activeIndex = active;\n        this.open = true;\n    }\n\n    private close() {\n        this.open = false;\n        this.activeIndex = -1;\n    }\n\n    /** Closing without a pick: text that matches no option snaps back (Carbon), unless free text is allowed. */\n    private closeAndSettle() {\n        this.commitText();\n        this.close();\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.input, 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        if (!this.menu.matches(':popover-open')) return;\n        this.menu.style.width = `${this.input.getBoundingClientRect().width}px`;\n        placeFloating(this.input, 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    private readonly onDocumentPointerDown = (event: PointerEvent) => {\n        const path = event.composedPath();\n        if (!path.includes(this.menu) && !path.includes(this.input) && !path.includes(this.shadowRoot!.querySelector('.controls')!)) {\n            this.closeAndSettle();\n        }\n    };\n\n    // ---- committing ----\n\n    private setValue(next: string) {\n        this.lastSyncedValue = next;\n        if (next === this.value) return;\n        this.value = next;\n        this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n        this.dispatchEvent(new Event('change', { bubbles: true }));\n    }\n\n    private selectOption(option: { value: string; label: string; disabled?: boolean } | undefined) {\n        if (!option || option.disabled) return false;\n        this.touched = true;\n        this.text = option.label;\n        this.setValue(option.value);\n        return true;\n    }\n\n    /** Blur / toggle-close rules from Carbon's state reducer. */\n    private commitText() {\n        const next = commitText(this.text, this.options, this.value, this.allowCustomValue);\n        if (next.value !== this.value || next.text !== this.text) this.touched = true;\n        this.text = next.text;\n        this.setValue(next.value);\n    }\n\n    private clear() {\n        this.touched = true;\n        this.text = '';\n        this.setValue('');\n        this.close();\n        this.input.focus();\n    }\n\n    // ---- keyboard ----\n\n    private selectedIndexIn(list: OptionData[]) {\n        return list.findIndex((o) => o.value === this.value && !o.disabled);\n    }\n\n    /** The keyboard of core/combobox (Carbon ComboBox, traced key by key). */\n    private onKeydown(event: KeyboardEvent) {\n        if (!this.interactive) return;\n        const step = comboboxKey({ open: this.open, active: this.activeIndex, text: this.text, value: this.value, loading: this.loading }, this.filtered, this.options, event, this.allowCustomValue);\n        if (!step) return;\n        if (step.handled) event.preventDefault();\n        this.apply(step);\n    }\n\n    private apply(step: ComboStep) {\n        if (step.pick !== undefined) this.selectOption(this.filtered[step.pick]);\n        if (step.pickOption) this.selectOption(step.pickOption);\n        if (step.commit) this.commitText();\n        if (step.clearText) this.text = '';\n        if (step.clearValue) this.setValue('');\n        if (step.close) this.close();\n        else if (step.open && !this.open) this.openMenu(step.active ?? -1);\n        else if (step.active !== undefined) this.activeIndex = step.active;\n    }\n\n    // ---- pointer ----\n\n    /** Carbon (downshift findHighlightedIndex): typing highlights the first enabled option that contains the text. */\n    private onInput() {\n        this.text = this.input.value;\n        this.dispatchEvent(new CustomEvent('ui-input', { detail: { value: this.text }, bubbles: true, composed: true }));\n        const match = this.loading ? -1 : highlightForText(this.filtered, this.text);\n        if (this.open) this.activeIndex = match;\n        else this.openMenu(match);\n    }\n\n    /** Carbon (web components and React): a mouse opening highlights the chosen option, or nothing when none is chosen. */\n    private openFromPointer() {\n        this.openMenu(this.selectedIndexIn(this.filtered));\n    }\n\n    private onInputClick() {\n        if (!this.open) this.openFromPointer();\n    }\n\n    private onToggleClick() {\n        if (this.open) this.closeAndSettle();\n        else this.openFromPointer();\n        this.input.focus();\n    }\n\n    /** Focus leaving the text box (Tab, or a click on something focusable): Carbon's InputBlur — an exact match or a snap back, never the highlight. */\n    private onFocusOut() {\n        this.commitText();\n        this.touched = true;\n        this.close();\n    }\n\n    private onOptionClick(i: number) {\n        if (this.selectOption(this.filtered[i])) this.close();\n    }\n\n    // ---- render ----\n\n    private renderOption(o: OptionData, i: number) {\n        const selected = o.value === this.value;\n        return html`<li\n            id=\"${this.fieldId}-opt-${i}\"\n            class=\"option ${i === this.activeIndex ? 'active' : ''}\"\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 renderRows() {\n        const m = this.messages;\n        if (this.loading) return html`<li class=\"empty\" part=\"empty\" role=\"option\" aria-disabled=\"true\" aria-selected=\"false\">${m.searching}</li>`;\n        const groups = this.filteredGroups;\n        if (groups.length === 0) return html`<li class=\"empty\" part=\"empty\" role=\"option\" aria-disabled=\"true\" aria-selected=\"false\">${m.noResults}</li>`;\n        return renderGroupedRows(groups, this.fieldId, (o, i) => this.renderOption(o, i));\n    }\n\n    /** \"Searching…\" / \"No matching items\" for screen readers: the disabled rows in the list are never announced (WCAG 4.1.3). */\n    private get statusText() {\n        if (!this.open) return '';\n        if (this.loading) return this.messages.searching;\n        return this.filteredGroups.length === 0 ? this.messages.noResults : '';\n    }\n\n    private renderClear(show: boolean) {\n        if (!show) return nothing;\n        return html`<button class=\"clear\" part=\"clear-button\" type=\"button\" tabindex=\"-1\" aria-label=${this.messages.clear} @click=${this.clear}>\n            <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n                <path d=\"m12 4.7-.7-.7L8 7.3 4.7 4l-.7.7L7.3 8 4 11.3l.7.7L8 8.7l3.3 3.3.7-.7L8.7 8z\" />\n            </svg>\n        </button>`;\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`<label class=${this.hideLabel || unlabelled ? 'sr-only' : 'label'} part=\"label\" id=\"${this.fieldId}-label\" for=${this.fieldId}>${renderLabelText(this.label, outside)}</label>`;\n    }\n\n    private fieldClasses(showError: boolean, message: FieldMessage | null, showClear: boolean) {\n        return [\n            showError ? 'invalid' : '',\n            message && message.kind !== 'helper' ? 'has-status' : '',\n            showClear ? 'has-clear' : '',\n            this.open ? 'open' : '',\n        ]\n            .filter(Boolean)\n            .join(' ');\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(): FieldMessage | null {\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    /** × shows: there is text and the field can change. */\n    private get showClear() {\n        return this.interactive && this.text !== '' && !this.hideClear;\n    }\n\n    override render() {\n        const m = this.messages;\n        const showError = this.showError;\n        const message = this.fieldMessage;\n        markStatus(this, message);\n        const showClear = this.showClear;\n        const classes = this.fieldClasses(showError, message, showClear);\n        const active = this.open && !this.loading && this.activeIndex >= 0 ? `${this.fieldId}-opt-${this.activeIndex}` : nothing;\n\n        return html`\n            ${this.renderLabel()}\n            <div class=\"field ${classes}\" part=\"base\">\n                <input\n                    part=\"input\"\n                    id=${this.fieldId}\n                    type=\"text\"\n                    role=\"combobox\"\n                    autocomplete=\"off\"\n                    aria-autocomplete=\"list\"\n                    aria-haspopup=\"listbox\"\n                    aria-expanded=${this.open ? 'true' : 'false'}\n                    aria-controls=\"${this.fieldId}-list\"\n                    aria-activedescendant=${active}\n                    aria-required=${this.required ? 'true' : nothing}\n                    aria-invalid=${showError ? 'true' : 'false'}\n                    aria-describedby=${messageId(this.fieldId, message) ?? nothing}\n                    placeholder=${this.placeholder}\n                    .value=${this.text}\n                    ?disabled=${this.isDisabled}\n                    ?readonly=${this.readonly}\n                    @input=${this.onInput}\n                    @keydown=${this.onKeydown}\n                    @click=${this.onInputClick}\n                    @focusout=${this.onFocusOut}\n                />\n                <span class=\"controls\" @mousedown=${(e: Event) => e.preventDefault()}>\n                    <span class=\"status\">${renderStatusIcon(message)}</span>\n                    ${this.renderClear(showClear)}\n                    <button\n                        class=\"toggle\"\n                        part=\"toggle\"\n                        type=\"button\"\n                        tabindex=\"-1\"\n                        aria-label=${this.open ? m.closeList : m.openList}\n                        aria-expanded=${this.open ? 'true' : 'false'}\n                        aria-controls=\"${this.fieldId}-list\"\n                        ?disabled=${!this.interactive}\n                        @click=${this.onToggleClick}\n                    >\n                        <svg 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                    </button>\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.loading ? 'true' : nothing}\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 UiComboboxEventMap extends HTMLElementEventMap {\n    'ui-toggle': CustomEvent<OpenDetail>;\n    'ui-input': CustomEvent<{ value: string }>;\n}\n\n/** Typed listeners for UiCombobox's events (declaration merging with the class). */\nexport interface UiCombobox {\n    addEventListener<K extends keyof UiComboboxEventMap>(type: K, listener: (this: UiCombobox, event: UiComboboxEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiComboboxEventMap>(type: K, listener: (this: UiCombobox, event: UiComboboxEventMap[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-combobox': UiCombobox;\n    }\n}\n"
    }
  ]
}
