{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "multi-select",
  "type": "registry:ui",
  "title": "<ui-multi-select>",
  "description": "Carbon-style multi select (Carbon `MultiSelect`, downshift useSelect + useMultipleSelection): a field that always shows its placeholder text, a count tag with a clear button once something is chosen, and a list of checkbox rows that stays open while choosing. 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-field",
    "@kanok-ui/core-listbox",
    "@kanok-ui/core-multi-select",
    "@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-slots",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/multi-select/multi-select.styles.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/multi-select/multi-select.styles.ts",
      "content": "import { css } from 'lit';\n\n/** Styles of `<ui-multi-select>`. */\nexport const multiSelectStyles = 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        gap: var(--ui-space-xs);\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    .trigger .text {\n        overflow: hidden;\n        white-space: nowrap;\n        text-overflow: ellipsis;\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    /* Count tag (Carbon list-box__selection--multi): number + clear-all button */\n    .tag {\n        position: absolute;\n        inset-block: 0;\n        inset-inline-start: var(--ui-space-md);\n        display: flex;\n        align-items: center;\n        height: 24px;\n        margin-block: auto;\n        padding-inline-start: var(--ui-space-xs);\n        border-radius: var(--ui-radius-pill);\n        /* Carbon: an inverse (ink) pill; a design can soften it (--ui-count-tag-*, Kanok: link-coloured text on the highlight) */\n        background-color: var(--ui-count-tag-background, var(--ui-ink));\n        color: var(--ui-count-tag-ink, var(--ui-inverse-ink));\n        font: var(--ui-font-caption);\n        letter-spacing: var(--ui-tracking-caption);\n    }\n\n    .tag button {\n        display: grid;\n        place-items: center;\n        width: 24px;\n        height: 24px;\n        padding: 0;\n        border: none;\n        border-radius: var(--ui-radius-pill);\n        background: transparent;\n        color: inherit;\n        cursor: pointer;\n        transition: background-color var(--ui-duration-fast) var(--ui-easing); /* Carbon tag__close-icon */\n    }\n\n    .tag button:hover {\n        background-color: var(--ui-count-tag-hover, var(--ui-secondary-hover));\n    }\n\n    .tag button:focus-visible {\n        outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n        outline-offset: var(--ui-focus-offset, -2px);\n    }\n\n    .tag svg {\n        width: 16px;\n        height: 16px;\n        fill: currentColor;\n    }\n\n    .has-tag .trigger {\n        padding-inline-start: calc(var(--ui-space-md) + 48px + var(--ui-space-xs));\n    }\n\n    :host([readonly]) .tag button,\n    .trigger:disabled ~ .tag button,\n    .filterable.disabled .tag button {\n        display: none;\n    }\n\n    :host([readonly]) .tag,\n    .trigger:disabled ~ .tag,\n    .filterable.disabled .tag {\n        padding-inline-end: var(--ui-space-xs);\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    /* checkbox inside a row */\n    .box {\n        position: relative;\n        display: block;\n        flex: none;\n        box-sizing: border-box;\n        width: 16px;\n        height: 16px;\n        margin-inline-end: 22px; /* Carbon multiselect row: 28px label inset + 10px text inset − 16px box */\n        /* the checkbox settings (--ui-checkbox-*), as <ui-checkbox> */\n        border: 1px solid var(--ui-checkbox-border, var(--ui-ink));\n        border-radius: var(--ui-radius-xs);\n        background-color: transparent;\n    }\n\n    /* a two-line row: Carbon centres the box on both lines; a design can pin it to the label (--ui-option-box-*) */\n    .option:has(.two-line) .box {\n        align-self: var(--ui-option-box-align, auto);\n        margin-block-start: var(--ui-option-box-offset, 0px);\n    }\n\n    /* Carbon's check mark: a 9×5 L of 1.5px borders rotated −45° about its bottom-right corner (checkbox.scss ::after) */\n    .box::after {\n        content: '';\n        position: absolute;\n        /* Carbon frame: box at 3px from the label, mark at 7px → 4px / 0.5px from the box edge; our frame is the 1px-bordered box, hence 3 / -0.5 */\n        top: -0.5px;\n        inset-inline-start: 3px;\n        box-sizing: border-box;\n        width: 9px;\n        height: 5px;\n        border-bottom: 1.5px solid var(--ui-checkbox-mark, var(--ui-icon-inverse));\n        border-left: 1.5px solid var(--ui-checkbox-mark, var(--ui-icon-inverse));\n        transform: scale(0) rotate(-45deg);\n        transform-origin: bottom right;\n    }\n\n    .option[aria-selected='true'] .box,\n    .option.mixed .box {\n        background-color: var(--ui-checkbox-checked, var(--ui-ink));\n        border-color: var(--ui-checkbox-checked, var(--ui-ink));\n    }\n\n    .option[aria-selected='true'] .box::after {\n        transform: scale(1) rotate(-45deg);\n    }\n\n    .option.mixed .box::after {\n        top: 4px; /* Carbon indeterminate: 8px bar, 2px thick, 11px − 3px margin from the label */\n        inset-inline-start: 3px;\n        width: 8px;\n        border-left-width: 0;\n        border-bottom-width: 2px;\n        transform: scale(1) rotate(0deg);\n    }\n\n    .option[aria-disabled='true'] .box {\n        border-color: var(--ui-ink-disabled);\n    }\n\n    .select-all {\n        border-bottom: 1px solid var(--ui-hairline);\n    }\n\n    /*\n     * filterable (Carbon cds--multi-select--filterable, measured on web-components.carbondesignsystem.com):\n     * the count tag 16px from the start, the text 8px after it; × and chevron as ComboBox.\n     */\n    .filterable {\n        box-sizing: border-box;\n        display: flex;\n        align-items: center;\n        height: var(--_h);\n        border: var(--ui-field-border, none); /* the field settings, as the other boxes */\n        border-bottom: 1px solid var(--ui-field-underline-color, var(--ui-ink-subtle));\n        border-radius: var(--ui-field-radius, 0);\n        background-color: var(--ui-field-background, var(--ui-surface-1));\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            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    .filterable: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    .filterable.open:hover {\n        background-color: var(--ui-field-open-background, var(--ui-ghost-hover));\n    }\n\n    .filterable:focus-within,\n    .filterable.open {\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    .filterable.invalid {\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    .filterable.invalid:focus-within {\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    .filterable .tag {\n        position: static;\n        flex: none;\n        margin-inline: var(--ui-space-md) var(--ui-space-xs);\n    }\n\n    .filterable input {\n        box-sizing: border-box;\n        flex: 1;\n        min-width: 0;\n        height: 100%;\n        margin: 0;\n        padding: 0 48px 0 var(--ui-space-md);\n        border: none;\n        background: transparent;\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: none;\n    }\n\n    .filterable.has-tag input {\n        padding-inline-start: 0;\n    }\n\n    /* room for × and the status icon as ui-combobox (the rule above would keep 48px and let text run under them) */\n    .filterable.has-clear input {\n        padding-inline-end: 70px;\n    }\n\n    .filterable.has-status input {\n        padding-inline-end: 64px;\n    }\n\n    .filterable.has-status.has-clear input {\n        padding-inline-end: 105px;\n    }\n\n    .filterable input::placeholder {\n        color: var(--ui-ink-placeholder);\n        opacity: 1;\n    }\n\n    .filterable.disabled {\n        border-color: var(--ui-field-disabled-border-color, currentColor currentColor transparent);\n        background-color: var(--ui-field-background, var(--ui-surface-1));\n    }\n\n    .filterable input:disabled {\n        color: var(--ui-ink-disabled);\n        cursor: not-allowed;\n    }\n\n    :host([readonly]) .filterable {\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        .trigger,\n        .filterable {\n            border: 1px solid FieldText;\n        }\n        .trigger:focus,\n        .filterable:focus-within {\n            outline-color: Highlight;\n        }\n        .chevron,\n        .tag svg {\n            fill: FieldText;\n        }\n        .box {\n            border-color: FieldText;\n        }\n        .option[aria-selected='true'] .box,\n        .option.mixed .box {\n            forced-color-adjust: none;\n            background-color: Highlight;\n            border-color: Highlight;\n        }\n    }\n`;\n\n/** Styles of `<ui-multi-select>` when fluid (`fluid`, or inside a `<ui-fluid-form>`): the 64px box with the label inside. */\nexport const multiSelectFluidStyles = 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    :host([data-fluid]) .filterable {\n        height: 64px;\n    }\n\n    :host([data-fluid]) .trigger,\n    :host([data-fluid]) .has-status .trigger {\n        padding: 33px 48px 13px var(--ui-space-md);\n    }\n\n    :host([data-fluid]) .has-tag .trigger {\n        padding-inline-start: calc(var(--ui-space-md) + 48px + var(--ui-space-xs));\n    }\n\n    /* the count tag on the value's line */\n    :host([data-fluid]) .tag {\n        inset-block: 30px auto;\n        margin-block: 0;\n    }\n\n    :host([data-fluid]) .filterable {\n        align-items: flex-start;\n    }\n\n    :host([data-fluid]) .filterable input {\n        padding-block: 33px 13px;\n        padding-inline-end: 64px;\n    }\n\n    :host([data-fluid]) .filterable.has-clear input {\n        padding-inline-end: 96px;\n    }\n\n    :host([data-fluid]) .filterable .tag {\n        margin-block-start: 30px;\n    }\n\n    /* Carbon fluid multi-select: the chevron 34px down, 12px from the end */\n    :host([data-fluid]) .icons {\n        inset-inline-end: var(--ui-space-sm);\n        --ui-fluid-icon-end: 4px;\n        align-items: flex-start;\n        padding-block-start: 34px;\n    }\n`;\n"
    },
    {
      "path": "src/primitives/multi-select/multi-select.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/multi-select/multi-select.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, 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    hasLabelledGroup,\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 { filterGroups, matchesText, reconcileActive } from '../../core/listbox.ts';\nimport { SELECT_ALL, multiFilterKey, multiFirst, multiSelectKey, orderRows, selectAllState, toggleAllValue, toggleValue, type MultiStep } from '../../core/multi-select.ts';\nimport { Typeahead } from '../../core/typeahead.ts';\nimport type { FieldMessage } from '../../core/field.ts';\nimport { outsidePress, scrollIntoList, trackAnchor } from '../../core/popup.ts';\nimport { multiSelectStyles, multiSelectFluidStyles } from './multi-select.styles.ts';\n\n/** When chosen options move to the top of the list (Carbon `selectionFeedback`). */\nexport type SelectionFeedback = 'top-after-reopen' | 'top' | 'fixed';\n\n/** How the text of a `filterable` multi select narrows the list; `none` leaves it to a server search. */\nexport type MultiSelectFilter = 'contains' | 'starts-with' | 'none';\n\n/**\n * Carbon-style multi select (Carbon `MultiSelect`, downshift useSelect + useMultipleSelection):\n * a field that always shows its placeholder text, a count tag with a clear button once something\n * is chosen, and a list of checkbox rows that stays open while choosing.\n *\n * - Options are `<option value>` children (`selected` marks initial choices); `value` is the\n *   array of chosen values. Submits one form entry per chosen value under `name`.\n * - Keys as Carbon (React MultiSelect traced key by key): ↓ Enter Space open (↑ doesn't); while open\n *   ↓ ↑ PageUp PageDown Home End move, Enter / Space toggle the row (the list stays open), typing jumps\n *   to a match, Esc closes. Delete / Backspace / Esc on the closed field clear every choice. The ×\n *   buttons are no Tab stops (Carbon `tabindex=\"-1\"`).\n * - `selection-feedback`: chosen rows move to the top on the next open (`top-after-reopen`,\n *   default), at once (`top`) or never (`fixed`). Author order is kept otherwise — Carbon\n *   additionally sorts alphabetically; we don't, because `<option>` order is the author's intent.\n *   With `<optgroup>`s the groups stay as authored and nothing moves.\n * - `select-all` adds a first row that checks / unchecks every enabled option (indeterminate in between).\n * - `filterable` (Carbon `FilterableMultiSelect` / `cds-multi-select filterable`): the field is a text box\n *   that narrows the list as you type (`filter`: `contains`, Carbon's rule, or `starts-with`) and\n *   highlights the first row; × clears the text. Choosing keeps the text and the list open; Enter\n *   toggles the highlight (Space types a space), Esc closes and, on a closed list, clears the\n *   choices and the text; leaving the field clears the text. \"Select all\" acts on the rows shown.\n *   Clicking the text box opens the list but never closes it, and no match shows a \"No matching\n *   items\" row — both as ui-combobox (Carbon closes, and shows an empty list; user's choice).\n *   For a server search set `filter=\"none\"`, listen to `ui-input`, fetch with its `value`, replace\n *   the options and toggle `loading`; keep chosen `<option>`s in the list so their rows stay.\n * - `loading` without `filterable` (no Carbon counterpart): one \"Loading…\" row instead of the\n *   options, busy and announced, the keys pick nothing; with `ui-toggle` an app can load the\n *   options the first time the list opens.\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 at least one option\n *   is chosen (the count tag shows) (e.g. `ui-multi-select[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 - Whenever the set of chosen values changes\n * @fires ui-toggle - detail: { open } after the list opens or closes (Carbon React `onMenuChange`)\n * @fires input - Whenever the set of chosen values changes, as ui-dropdown and ui-combobox; with `filterable`, 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`) with `filterable`, as the user types or when the text is emptied\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, or the text box with `filterable` (role=combobox)\n * @csspart toggle - The chevron button (`filterable`)\n * @csspart clear-filter-button - The × that clears the text (`filterable`)\n * @csspart empty - The \"searching\" / \"no results\" row (`filterable`)\n * @csspart tag - The selected-count pill\n * @cssprop --ui-count-tag-background - The count pill's fill (default `--ui-ink`); also `--ui-count-tag-ink` (`--ui-inverse-ink`) and `--ui-count-tag-hover` (its ×, `--ui-secondary-hover`)\n * @csspart clear-button - The × inside the pill\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 select-all - The \"Select all\" row\n * @csspart checkbox - The box drawn in 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-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-option-box-align / --ui-option-box-offset - A two-line row's checkbox: `align-self` and top margin (default auto, 0: centred; Kanok: beside the label line)\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 * @cssprop --ui-focus-offset - `outline-offset` of its focus ring (default -2px: inside; Kanok: 2px outside)\n */\n@customElement('ui-multi-select')\nexport class UiMultiSelect 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        multiSelectStyles,\n        fluidFieldStyles,\n        multiSelectFluidStyles,\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 always shown in the field (Carbon's `label`), e.g. \"Choose options\". */\n    @property() placeholder = '';\n\n    /** Chosen option values. Initial choices can also come from `<option selected>`. */\n    @property({ attribute: false }) value: string[] = [];\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({ attribute: 'selection-feedback' }) selectionFeedback: SelectionFeedback = 'top-after-reopen';\n\n    /** Adds a \"Select all\" row. */\n    @property({ type: Boolean, attribute: 'select-all' }) selectAll = false;\n\n    /** The field is a text box that narrows the list (Carbon `FilterableMultiSelect` / `filterable`). */\n    @property({ type: Boolean, reflect: true }) filterable = false;\n\n    /** With `filterable`: `contains` (Carbon), `starts-with`, or `none` to leave the list to a server search. */\n    @property() filter: MultiSelectFilter = 'contains';\n\n    /** The options are on their way: \"Searching…\" with `filterable` (a server search), else \"Loading…\"; the keys pick nothing. */\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 `FluidMultiSelect`: 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 open = false;\n\n    /** Highlighted row: index into the displayed rows, SELECT_ALL for the first row, -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    /** Values that were chosen when the list last opened (for `top-after-reopen`). */\n    @state() private pinned: string[] = [];\n\n    /** Text typed into a `filterable` field. */\n    @state() private text = '';\n\n    @query('.trigger') private readonly trigger!: HTMLButtonElement | null;\n\n    @query('input') private readonly input!: HTMLInputElement | null;\n\n    @query('.field') private readonly field!: HTMLElement;\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-multi-select');\n    /** Created on connect: there is no MutationObserver when Lit renders on the server. */\n    private observer?: MutationObserver;\n    private defaultValue: string[] = [];\n    private readonly typed = new Typeahead();\n\n    /** With `filterable`, what the user typed; set it to search for something. */\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        this.readOptions();\n        // first connection only: moving the element must neither re-select the `<option selected>` choices the user\n        // cleared nor change what reset goes back to\n        this.formControl.captureDefaults(() => {\n            if (this.value.length === 0) {\n                this.value = [...this.querySelectorAll('option')].filter((o) => o.hasAttribute('selected')).map((o) => o.value);\n            }\n            this.defaultValue = [...this.value];\n        });\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.text = '';\n        this.touched = false;\n    }\n\n    /** Back/forward cache hands the saved values back here. */\n    formStateRestoreCallback(state: string | File | FormData | null) {\n        if (state instanceof FormData) this.value = state.getAll(this.name).map(String);\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    private isChosen(o: OptionData) {\n        return this.value.includes(o.value);\n    }\n\n    /** The typed text narrows the list (`filterable`, a filter other than `none`, some text). */\n    private get filtering() {\n        return this.filterable && this.filter !== 'none' && this.text.trim() !== '';\n    }\n\n    private isShown(o: OptionData) {\n        return !this.filtering || matchesText(o.label, this.text, this.filter);\n    }\n\n    /** The groups shown: as authored, narrowed by the typed text. */\n    private get shownGroups(): OptionGroup[] {\n        if (!this.filtering) return this.groups;\n        return filterGroups(this.groups, (o) => this.isShown(o));\n    }\n\n    /** Rows in display order: chosen ones first per `selection-feedback`, author order otherwise; narrowed by the typed text. */\n    private get rows(): OptionData[] {\n        if (this.loading) return [];\n        const grouped = hasLabelledGroup(this.groups);\n        const shown = grouped ? flattenGroups(this.shownGroups) : this.options.filter((o) => this.isShown(o));\n        return orderRows(shown, this.value, this.pinned, this.selectionFeedback, grouped);\n    }\n\n    /** Enabled options \"Select all\" acts on: the rows shown (Carbon, filterable). */\n    private get enabledOptions() {\n        return this.options.filter((o) => !o.disabled && this.isShown(o));\n    }\n\n    /** The \"Select all\" row shows while it has rows to act on (Carbon hides it when the filter leaves none). */\n    private get showSelectAll() {\n        return this.selectAll && !this.loading && this.enabledOptions.length > 0;\n    }\n\n    /** 'all' | 'some' | 'none' of the enabled options are chosen. */\n    private get selectAllState() {\n        return selectAllState(this.enabledOptions, this.value);\n    }\n\n    protected override willUpdate(changed: Map<string, unknown>) {\n        syncFluid(this, this.fluid);\n        this.syncValidity();\n        // a search started (no rows: no highlight) or its results came while the list is open (highlight as on opening)\n        if (this.open && changed.has('loading') && changed.get('loading') !== undefined) this.activeIndex = this.reconciled([]);\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.value.length > 0);\n    }\n\n    private syncValidity() {\n        if (barWhenDisabled(this.internals, this.isDisabled)) return;\n        const data = new FormData();\n        for (const v of this.value) data.append(this.name, v);\n        this.internals.setFormValue(this.isDisabled || !this.name ? null : data);\n        const anchor = this.input ?? 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.length === 0) {\n            this.internals.setValidity({ valueMissing: true }, this.messages.required, anchor);\n        } else {\n            this.internals.setValidity({});\n        }\n    }\n\n    private readOptions() {\n        const before = this.rows;\n        this.groups = readOptionGroups(this);\n        this.options = flattenGroups(this.groups);\n        // new options while open (a server search): the highlight stays on its option where it still is, else on a row that exists\n        if (this.open) this.activeIndex = this.reconciled(before);\n    }\n\n    /** The highlight once the rows changed from `before` (core reconcileActive); \"Select all\" stays while it shows. */\n    private reconciled(before: OptionData[]) {\n        if (this.activeIndex === SELECT_ALL && this.showSelectAll && !this.loading) return SELECT_ALL;\n        return reconcileActive(this.rows, before, this.activeIndex === SELECT_ALL ? -1 : this.activeIndex, { open: true, loading: this.loading, same: sameOption, opening: () => this.firstEnabled() });\n    }\n\n    /** Rows in display order, grouped only when `<optgroup>`s are authored; \"Searching…\" / \"No matching items\" while filterable. */\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\">${this.filterable ? m.searching : m.loadingOptions}</li>`;\n        if (this.filterable && this.rows.length === 0) return html`<li class=\"empty\" part=\"empty\" role=\"option\" aria-disabled=\"true\" aria-selected=\"false\">${m.noResults}</li>`;\n        if (hasLabelledGroup(this.groups)) return renderGroupedRows(this.shownGroups, this.fieldId, (o, i) => this.renderRow(o, i));\n        return this.rows.map((o, i) => this.renderRow(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.filterable ? this.messages.searching : this.messages.loadingOptions;\n        return this.filterable && this.rows.length === 0 ? this.messages.noResults : '';\n    }\n\n    // ---- open / close ----\n\n    private openMenu(startIndex?: number) {\n        if (!this.interactive || this.open) return;\n        this.pinned = [...this.value];\n        // Carbon: with choices made, the first (chosen) row is highlighted; otherwise the first row.\n        this.activeIndex = startIndex ?? this.firstEnabled();\n        this.open = true;\n    }\n\n    private close() {\n        this.open = false;\n        this.activeIndex = -1;\n    }\n\n    /** Carbon filterable: closing by a click or leaving the field drops the typed text. */\n    private closeAndClearText() {\n        this.close();\n        this.resetText();\n    }\n\n    /** Empties the typed text; fires `ui-input` (and `input`) like typing would, so a server search can reset its options. */\n    private resetText() {\n        if (this.text === '') return;\n        this.text = '';\n        this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n        this.emitTyping();\n    }\n\n    private emitTyping() {\n        this.dispatchEvent(new CustomEvent('ui-input', { detail: { value: this.text }, bubbles: true, composed: true }));\n    }\n\n    /** Mouse: Carbon highlights the first chosen row, or nothing when none is chosen (the keyboard starts on the first row). */\n    private toggle() {\n        if (this.open) this.close();\n        else this.openMenu(this.value.length > 0 ? undefined : -1);\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.field, 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.field.getBoundingClientRect().width}px`;\n        placeFloating(this.field, 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.field)) return;\n        if (this.filterable) this.closeAndClearText();\n        else this.close();\n    };\n\n    private onTriggerFocusOut() {\n        if (this.open) this.close();\n        this.touched = true;\n    }\n\n    // ---- selection ----\n\n    /** `input` means \"the value changed\" with or without `filterable`; the typing has `ui-input`. */\n    private setValue(next: string[]) {\n        this.touched = true;\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 toggleOption(option: OptionData | undefined) {\n        if (!option || option.disabled) return;\n        this.setValue(toggleValue(this.value, option));\n    }\n\n    private toggleSelectAll() {\n        this.setValue(toggleAllValue(this.value, this.enabledOptions));\n    }\n\n    private toggleActive() {\n        if (this.activeIndex === SELECT_ALL) this.toggleSelectAll();\n        else this.toggleOption(this.rows[this.activeIndex]);\n    }\n\n    private clearAll() {\n        if (this.value.length > 0) this.setValue([]);\n        (this.input ?? this.trigger)?.focus();\n    }\n\n    // ---- keyboard ----\n\n    private firstEnabled() {\n        return multiFirst(this.rows, this.showSelectAll);\n    }\n\n    /** The button's keys (core/multi-select, Carbon MultiSelect traced key by key). */\n    private onTriggerKeydown(event: KeyboardEvent) {\n        if (!this.interactive) return;\n        const step = multiSelectKey({ open: this.open, active: this.activeIndex, hasValue: this.value.length > 0 }, this.rows, this.showSelectAll, event, this.typed);\n        if (!step) return;\n        if (step.handled) event.preventDefault();\n        this.apply(step);\n    }\n\n    private apply(step: MultiStep) {\n        if (step.clearAll) this.setValue([]);\n        if (step.clearText) this.resetText();\n        if (step.toggle !== undefined) {\n            this.activeIndex = step.toggle;\n            this.toggleActive();\n        }\n        if (step.close) this.close();\n        else if (step.open && !this.open) this.openMenu(step.active);\n        else if (step.active !== undefined) this.activeIndex = step.active;\n    }\n\n    // ---- filterable ----\n\n    /** The text box's keys (core/multi-select, Carbon FilterableMultiSelect). */\n    private onFilterKeydown(event: KeyboardEvent) {\n        if (!this.interactive) return;\n        const step = multiFilterKey({ open: this.open, active: this.activeIndex, hasValue: this.value.length > 0 }, this.rows, this.showSelectAll, event);\n        if (!step) return;\n        if (step.handled) event.preventDefault();\n        this.apply(step);\n    }\n\n    /** Typing narrows the list, opens it and highlights the first row (Carbon). */\n    private onFilterInput() {\n        this.text = this.input?.value ?? '';\n        this.emitTyping();\n        if (!this.interactive) return;\n        if (this.open) this.activeIndex = this.firstEnabled();\n        else this.openMenu();\n    }\n\n    /** As ui-combobox: a click opens the list (highlighting the first chosen row, or nothing) and never closes it. */\n    private onFilterClick() {\n        if (!this.open) this.openMenu(this.value.length > 0 ? undefined : -1);\n    }\n\n    private onToggleClick() {\n        if (this.open) this.closeAndClearText();\n        else this.openMenu(this.value.length > 0 ? undefined : -1);\n        this.input?.focus();\n    }\n\n    private clearText() {\n        this.resetText();\n        this.input?.focus();\n        if (this.open) this.activeIndex = this.firstEnabled();\n    }\n\n    /** Focus leaving the field (the text box, × or the tag's ×, not to one of them) closes the list and drops the text (Carbon). */\n    private onFilterFocusOut(event: FocusEvent) {\n        if (event.relatedTarget instanceof Node && this.shadowRoot!.contains(event.relatedTarget)) return;\n        this.closeAndClearText();\n        this.touched = true;\n    }\n\n    // ---- render ----\n\n    private renderBox() {\n        return html`<span class=\"box\" part=\"checkbox\" aria-hidden=\"true\">\n        </span>`;\n    }\n\n    private renderSelectAllRow() {\n        if (!this.showSelectAll) return nothing;\n        const state = this.selectAllState;\n        return html`<li\n            id=\"${this.fieldId}-opt-all\"\n            class=\"option select-all ${this.activeIndex === SELECT_ALL ? 'active' : ''} ${state === 'some' ? 'mixed' : ''}\"\n            part=\"option select-all\"\n            role=\"option\"\n            aria-selected=${state === 'all' ? 'true' : 'false'}\n            aria-checked=${state === 'some' ? 'mixed' : nothing}\n            @click=${() => {\n                this.activeIndex = SELECT_ALL; // the keyboard carries on from the row clicked\n                this.toggleSelectAll();\n            }}\n        >\n            ${this.renderBox()}\n            <span class=\"text\">${this.messages.selectAll}</span>\n        </li>`;\n    }\n\n    private renderRow(o: OptionData, i: number) {\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=${this.isChosen(o) ? 'true' : 'false'}\n            aria-disabled=${o.disabled ? 'true' : nothing}\n            @click=${() => {\n                if (!o.disabled) this.activeIndex = i; // the keyboard carries on from the row clicked\n                this.toggleOption(o);\n            }}\n        >\n            ${this.renderBox()}\n            ${renderOptionText(o)}\n        </li>`;\n    }\n\n    /** With `filterable`, the tag's × doesn't take focus, so the text box keeps it. */\n    private readonly onTagButtonMousedown = (event: Event) => {\n        if (this.filterable) event.preventDefault();\n    };\n\n    private renderTag() {\n        const n = this.value.length;\n        if (n === 0) return nothing;\n        const m = this.messages;\n        return html`<span class=\"tag\" part=\"tag\">\n            <span aria-hidden=\"true\">${n}</span>\n            <span class=\"sr-only\" id=\"${this.fieldId}-count\">${m.selectedCount(n)}</span>\n            <button\n                type=\"button\"\n                part=\"clear-button\"\n                tabindex=\"-1\"\n                aria-label=${m.clearAll}\n                ?disabled=${!this.interactive}\n                @mousedown=${this.onTagButtonMousedown}\n                @click=${this.clearAll}\n            >\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        </span>`;\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 activeId() {\n        if (!this.open || this.activeIndex === -1) return nothing;\n        return this.activeIndex === SELECT_ALL ? `${this.fieldId}-opt-all` : `${this.fieldId}-opt-${this.activeIndex}`;\n    }\n\n    /** The trigger always shows the placeholder, so the selected count (and any message) describes it. */\n    private describedBy(message: ReturnType<typeof pickMessage>) {\n        const ids = [this.value.length > 0 ? `${this.fieldId}-count` : '', messageId(this.fieldId, message) ?? ''].filter(Boolean);\n        return ids.length ? ids.join(' ') : nothing;\n    }\n\n    private renderTrigger(showError: boolean, message: ReturnType<typeof pickMessage>) {\n        return html`<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=${this.activeId()}\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=${this.describedBy(message)}\n                ?disabled=${this.isDisabled}\n                @click=${this.toggle}\n                @keydown=${this.onTriggerKeydown}\n                @focusout=${this.onTriggerFocusOut}\n            >\n                <span class=\"text\" id=\"${this.fieldId}-value\">${this.placeholder}</span>\n            </button>\n            ${this.renderTag()}\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    }\n\n    /** `filterable`: count tag, text box, then status / × / chevron as ui-combobox. */\n    private renderFilterField(showError: boolean, message: ReturnType<typeof pickMessage>) {\n        const m = this.messages;\n        return html`${this.renderTag()}\n            <input\n                part=\"input\"\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=${this.activeId()}\n                aria-labelledby=\"${this.fieldId}-label\"\n                aria-required=${this.required ? 'true' : nothing}\n                aria-invalid=${showError ? 'true' : 'false'}\n                aria-describedby=${this.describedBy(message)}\n                placeholder=${this.placeholder || nothing}\n                .value=${this.text}\n                ?disabled=${this.isDisabled}\n                ?readonly=${this.readonly}\n                @input=${this.onFilterInput}\n                @keydown=${this.onFilterKeydown}\n                @click=${this.onFilterClick}\n            />\n            <span class=\"controls\" @mousedown=${(e: Event) => e.preventDefault()}>\n                <span class=\"status\">${renderStatusIcon(message)}</span>\n                ${this.renderClearText()}\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    }\n\n    private renderClearText() {\n        if (!this.showClearText) return nothing;\n        return html`<button class=\"clear\" part=\"clear-filter-button\" type=\"button\" tabindex=\"-1\" aria-label=${this.messages.clear} @click=${this.clearText}>\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 get showClearText() {\n        return this.filterable && this.interactive && this.text !== '';\n    }\n\n    /** The field's state classes: invalid, status icon, tags, open, filterable, clear button, disabled. */\n    private fieldClasses(showError: boolean, message: FieldMessage | null) {\n        return [\n            showError ? 'invalid' : '',\n            message && message.kind !== 'helper' ? 'has-status' : '',\n            this.value.length > 0 ? 'has-tag' : '',\n            this.open ? 'open' : '',\n            this.filterable ? 'filterable' : '',\n            this.showClearText ? 'has-clear' : '',\n            this.filterable && this.isDisabled ? 'disabled' : '',\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    override render() {\n        const showError = this.showError;\n        const message = this.fieldMessage;\n        markStatus(this, message);\n        const classes = this.fieldClasses(showError, message);\n\n        return html`\n            ${this.renderLabel()}\n            <div class=\"field ${classes}\" part=\"base\" @focusout=${this.filterable ? this.onFilterFocusOut : nothing}>\n                ${this.filterable ? this.renderFilterField(showError, message) : this.renderTrigger(showError, message)}\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-multiselectable=\"true\"\n                aria-labelledby=\"${this.fieldId}-label\"\n                aria-busy=${this.loading ? 'true' : nothing}\n                @mousedown=${(e: Event) => e.preventDefault()}\n            >\n                ${this.open ? html`${this.renderSelectAllRow()}${this.renderRows()}` : nothing}\n            </ul>\n            <span class=\"sr-only\" role=\"status\">${this.statusText}</span>\n        `;\n    }\n}\n\nexport interface UiMultiSelectEventMap extends HTMLElementEventMap {\n    'ui-toggle': CustomEvent<OpenDetail>;\n    'ui-input': CustomEvent<{ value: string }>;\n}\n\n/** Typed listeners for UiMultiSelect's events (declaration merging with the class). */\nexport interface UiMultiSelect {\n    addEventListener<K extends keyof UiMultiSelectEventMap>(type: K, listener: (this: UiMultiSelect, event: UiMultiSelectEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiMultiSelectEventMap>(type: K, listener: (this: UiMultiSelect, event: UiMultiSelectEventMap[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-multi-select': UiMultiSelect;\n    }\n}\n"
    }
  ]
}
