# Combobox

Autocomplete input with a list of suggestions.

Source: https://webjs.dev/ui/docs/components/combobox

```ts
import { html } from '@webjsdev/core';

const frameworks = ['Next.js', 'SvelteKit', 'Nuxt.js', 'Remix', 'Astro'];

export default function ComboboxBasic() {
  return html`
    <ui-combobox>
      <ui-combobox-input placeholder="Select a framework" aria-label="Framework"></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Installation

```bash
npx @webjsdev/ui add combobox
```

### Copy and paste the following code into your project.

````ts title="components/ui/combobox.ts"
/**
 * Combobox: a text input that filters a list of choices as you type, for one
 * value or, in chips mode, several. Tier-2. It follows Base UI's Combobox,
 * which shadcn builds on: typing filters the list, the arrow keys highlight
 * while focus stays in the input, Enter picks, and the choice lives in a real
 * form control, one `<input type="hidden" name>` per chosen value, so the
 * form submits it with or without JavaScript.
 *
 * shadcn parity:
 *   Combobox (multiple, value, disabled)
 *                            → <ui-combobox name multiple value disabled>
 *   ComboboxInput (showTrigger, showClear)
 *                            → <ui-combobox-input placeholder input-id show-trigger="false" show-clear>
 *   ComboboxContent (side, align, sideOffset)
 *                            → <ui-combobox-content side align side-offset>
 *   ComboboxList / ComboboxEmpty / ComboboxSeparator
 *                            → <ui-combobox-list> / <ui-combobox-empty> / <ui-combobox-separator>
 *   ComboboxGroup + ComboboxLabel
 *                            → <ui-combobox-group> + <ui-combobox-label>
 *   ComboboxItem value       → <ui-combobox-item value>
 *   ComboboxChips + ComboboxChip + ComboboxChipsInput
 *                            → <ui-combobox-chips> around <ui-combobox-chips-input>; the
 *                              chips are drawn from the chosen values
 *   onValueChange            → `ui-value-change` ({ detail: { value } }), a string, or a
 *                              string array with `multiple`
 *   onOpenChange             → `ui-open-change` ({ detail: { open } })
 *
 * `value` holds the initial choice: one value, or with `multiple` a comma
 * separated list. An item's label is its text. The list filters on labels,
 * case-insensitively, and the content carries `data-empty` when nothing
 * matches, which is what shows `<ui-combobox-empty>`.
 *
 * Keyboard (as Base UI's): ArrowDown / ArrowUp open the list and move the
 * highlight, Enter picks the highlighted item, Escape closes, Tab closes and
 * moves on. With `multiple`, picking toggles and keeps the list open, and
 * Backspace in an empty input removes the last chip. Leaving a single
 * combobox puts the chosen item's label back in the input.
 *
 * A11y (handled by the element, plus your part): the input is a
 * `role="combobox"` controlling a `role="listbox"` (multiselectable with
 * `multiple`), pointing at the highlighted `role="option"` through
 * `aria-activedescendant`; options carry `aria-selected`, a group is named by
 * its label, and each chip's remove button names the value it removes. Your
 * part: name the input, with `<label for>` matching `input-id`, or an
 * `aria-label` on the input part.
 *
 * @example
 * ```html
 * <label for="framework" class=${labelClass()}>Framework</label>
 * <ui-combobox name="framework">
 *   <ui-combobox-input input-id="framework" placeholder="Select a framework"></ui-combobox-input>
 *   <ui-combobox-content>
 *     <ui-combobox-empty>No items found.</ui-combobox-empty>
 *     <ui-combobox-list>
 *       <ui-combobox-item value="next">Next.js</ui-combobox-item>
 *       <ui-combobox-item value="sveltekit">SvelteKit</ui-combobox-item>
 *       <ui-combobox-item value="astro">Astro</ui-combobox-item>
 *     </ui-combobox-list>
 *   </ui-combobox-content>
 * </ui-combobox>
 * ```
 */
import { WebComponent, html, prop, signal, nothing } from '@webjsdev/core';
import { cn } from '../lib/utils.ts';
import { positionFloating } from './floating.ts';
import type { PopoverSide, PopoverAlign } from './popover.ts';
import { buttonClass } from './button.ts';
import { inputGroupClass, inputGroupInputClass, inputGroupAddonClass, inputGroupButtonClass } from './input-group.ts';

/** The input group around a single combobox's input (the element applies them). */
export const comboboxInputClass = (): string => 'w-auto';
/** The trigger button (the element applies them). */
export const comboboxTriggerClass = (): string => "[&_svg:not([class*='size-'])]:size-4";
/** The trigger's chevron. */
export const comboboxTriggerIconClass = (): string => 'size-4 text-muted-foreground pointer-events-none';
/** The clear button (the element applies them). */
export const comboboxClearClass = (): string => '';
/** The clear button's icon. */
export const comboboxClearIconClass = (): string => 'pointer-events-none';
/** The popup's classes (the element applies them). */
export const comboboxContentClass = (): string =>
  'fixed m-0 max-h-96 overflow-hidden rounded-md bg-popover p-0 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none group/combobox-content z-50 max-h-(--available-height) origin-(--transform-origin) w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+--spacing(7))] data-[chips=true]:min-w-(--anchor-width) not-open:hidden';
/** The list's classes (the element applies them). */
export const comboboxListClass = (): string => 'max-h-[min(calc(--spacing(96)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 p-1 data-[empty]:p-0 overflow-y-auto overscroll-contain';
/** An item's classes (the element applies them). */
export const comboboxItemClass = (): string =>
  "gap-2 rounded-sm py-1.5 pe-8 ps-2 text-sm data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground [&_svg:not([class*='size-'])]:size-4 relative flex w-full cursor-default items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0";
/** A chosen item's check mark slot. */
export const comboboxItemIndicatorClass = (): string => 'pointer-events-none absolute end-2 flex size-4 items-center justify-center';
/** A chosen item's check mark. */
export const comboboxItemIndicatorIconClass = (): string => 'size-4 pointer-coarse:size-5 pointer-events-none';
/** A group's classes (the element applies them). */
export const comboboxGroupClass = (): string => '';
/** A group label's classes (the element applies them). */
export const comboboxLabelClass = (): string => 'px-2 py-1.5 text-xs text-muted-foreground pointer-coarse:px-3 pointer-coarse:py-2 pointer-coarse:text-sm';
/** The empty state's classes (the element applies them). */
export const comboboxEmptyClass = (): string => 'hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-[empty]/combobox-content:flex';
/** A separator's classes (the element applies them). */
export const comboboxSeparatorClass = (): string => '-mx-1 my-1 h-px bg-border';
/** The chips box (the element applies them). */
export const comboboxChipsClass = (): string => 'flex min-h-9 flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 py-1.5 text-sm shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 has-aria-invalid:border-destructive has-aria-invalid:ring-[3px] has-aria-invalid:ring-destructive/20 has-data-[slot=combobox-chip]:px-1.5 dark:bg-input/30 dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40';
/** One chip (the element applies them). */
export const comboboxChipClass = (): string =>
  'flex h-[calc(--spacing(5.5))] w-fit items-center justify-center gap-1 rounded-sm bg-muted px-1.5 text-xs font-medium whitespace-nowrap text-foreground has-data-[slot=combobox-chip-remove]:pe-0 has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50';
/** A chip's remove button (the element applies them). */
export const comboboxChipRemoveClass = (): string => '-ms-1 opacity-50 hover:opacity-100';
/** A chip's remove icon. */
export const comboboxChipIndicatorIconClass = (): string => 'pointer-events-none';
/** The input inside the chips box (the element applies them). */
export const comboboxChipInputClass = (): string => 'min-w-16 flex-1 outline-none';

const ROOT = 'ui-combobox';
let uid = 0;

function X_ICON(cls: string) {
  return html`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" class=${cls}><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>`;
}

export class UiCombobox extends WebComponent({
  name: String,
  multiple: Boolean,
  disabled: Boolean,
  value: String,
  open: prop(Boolean, { reflect: true }),
}) {
  // The chosen values (the form's view of `value`).
  readonly #values = signal<string[]>([]);
  readonly #query = signal('');
  readonly highlighted = signal('');
  _id = '';
  _parsed = false;

  constructor() {
    super();
    this.name = '';
    this.multiple = false;
    this.disabled = false;
    this.value = '';
    this.open = false;
  }

  connectedCallback(): void {
    super.connectedCallback?.();
    this._id ||= `ui-combobox-${++uid}`;
  }

  // Empty before connect (the server never connects an element), so the
  // served markup carries no `-list` id that every combobox would share.
  get listId(): string | null {
    return this._id ? `${this._id}-list` : null;
  }

  // The initial choice, read from the attribute once.
  _initial(): string[] {
    const v = this.value ?? '';
    if (!v) return [];
    return this.multiple ? v.split(',').map((s) => s.trim()).filter(Boolean) : [v];
  }

  willUpdate(changedProperties: Map<string, unknown>): void {
    super.willUpdate?.(changedProperties);
    if (!this._parsed) {
      this._parsed = true;
      this.#values.set(this._initial());
    }
  }

  render() {
    const name = this.name;
    return html`<div data-slot="combobox" class="relative" @keydown=${this._onKeyDown} @focusout=${this._onFocusOut}><slot></slot>${name
      ? this.#values.get().map((v) => html`<input type="hidden" name=${name} value=${v}>`)
      : ''}</div>`;
  }

  _own<T extends Element>(selector: string): T[] {
    if (typeof this.querySelectorAll !== 'function') return [];
    return Array.from(this.querySelectorAll<T>(selector)).filter((el) => el.closest(ROOT) === this);
  }

  _items(): UiComboboxItem[] {
    return this._own<UiComboboxItem>(`${ROOT}-item`);
  }

  /** The text field: the single input, or the input inside the chips box. */
  _input(): HTMLInputElement | null {
    return this.querySelector<HTMLInputElement>('input[data-slot="input-group-control"], input[data-slot="combobox-chip-input"]');
  }

  /**
   * What the popup sits against: the chips box, else the text field itself, as
   * Base UI's popup anchors to Combobox.Input. Its width is --anchor-width, so
   * the styles' `min-w-[calc(var(--anchor-width)+--spacing(7))]` adds back the
   * trigger button and the list spans the input group, as shadcn's does. (The
   * group as the anchor made the list a button's width wider than the field.)
   */
  _anchor(): HTMLElement | null {
    return this.querySelector<HTMLElement>('[data-slot="combobox-chips"]')
      ?? this.querySelector<HTMLElement>('input[data-slot="input-group-control"]')
      ?? this.querySelector<HTMLElement>('[data-slot="input-group"]');
  }

  _panel(): HTMLElement | null {
    return this.querySelector<HTMLElement>('[data-slot="combobox-content"]');
  }

  /** The label of the item with `value`, else the value itself. */
  labelOf(value: string): string {
    return this._items().find((i) => i.itemValue === value)?.label ?? value;
  }

  /** The items that match the typed text, in order. */
  visibleItems(): UiComboboxItem[] {
    const q = this.#query.get().trim().toLowerCase();
    return this._items().filter((i) => !q || i.label.toLowerCase().includes(q));
  }

  _emit(type: string, detail: unknown): void {
    this.dispatchEvent(new CustomEvent(type, { bubbles: true, detail }));
  }

  show(): void {
    if (this.disabled || this.open) return;
    this.open = true;
    this._emit('ui-open-change', { open: true });
  }

  hide(): void {
    if (!this.open) return;
    this.open = false;
    this._emit('ui-open-change', { open: false });
  }

  /** Choose (or, with `multiple`, toggle) the item with `value`. */
  choose(value: string): void {
    const item = this._items().find((i) => i.itemValue === value);
    if (!item || item.disabled) return;
    const input = this._input();
    if (this.multiple) {
      const values = this.#values.get();
      this.#values.set(values.includes(value) ? values.filter((v) => v !== value) : [...values, value]);
      this.#query.set('');
      if (input) input.value = '';
    } else {
      this.#values.set([value]);
      this.#query.set('');
      if (input) input.value = item.label;
      this.hide();
    }
    this._emit('ui-value-change', { value: this.multiple ? [...this.#values.get()] : value });
  }

  /**
   * Remove one chosen value. Not named `remove`: that would override the
   * native Element.remove(), so taking the element out of the page would
   * silently do nothing instead.
   */
  removeValue(value: string): void {
    const values = this.#values.get();
    if (!values.includes(value)) return;
    const next = values.filter((v) => v !== value);
    this.#values.set(next);
    this._emit('ui-value-change', { value: this.multiple ? [...next] : '' });
  }

  /** Clear every chosen value and the typed text. */
  clear(): void {
    const input = this._input();
    if (input) input.value = '';
    this.#query.set('');
    this.#values.set([]);
    this._emit('ui-value-change', { value: this.multiple ? [] : '' });
    input?.focus();
  }

  _setQuery(text: string): void {
    this.#query.set(text);
    this.show();
    // A new filter highlights its first match.
    const first = this.visibleItems().find((i) => !i.disabled);
    this.highlighted.set(first?.itemValue ?? '');
  }

  updated(changedProperties: Map<string, unknown>): void {
    super.updated?.(changedProperties);
    this._syncParts();
    if (changedProperties.has('open') && changedProperties.get('open') !== undefined) {
      queueMicrotask(() => (this.open ? this._afterOpen() : this._afterClose()));
    }
  }

  // Push the state into every part.
  _syncParts(): void {
    const visible = new Set(this.visibleItems());
    for (const item of this._items()) {
      item.state?.set({
        visible: visible.has(item),
        selected: this.#values.get().includes(item.itemValue),
        highlighted: this.open && item.itemValue === this.highlighted.get() && visible.has(item),
      });
    }
    for (const g of this._own<UiComboboxGroup>(`${ROOT}-group`)) {
      g.shown?.set(this._items().some((i) => i.closest(`${ROOT}-group`) === g && visible.has(i)));
    }
    const empty = visible.size === 0;
    for (const part of this._own<UiComboboxContent | UiComboboxList>(`${ROOT}-content, ${ROOT}-list`)) part.empty?.set(empty);
    for (const content of this._own<UiComboboxContent>(`${ROOT}-content`)) content.open?.set(this.open);
    for (const field of this._own<UiComboboxInput | UiComboboxChipsInput>(`${ROOT}-input, ${ROOT}-chips-input`)) {
      const h = this._items().find((i) => i.itemValue === this.highlighted.get() && visible.has(i));
      field.state?.set({ open: this.open, activeId: this.open && h ? h.optionId : '', hasValue: this.#values.get().length > 0 });
    }
    for (const chips of this._own<UiComboboxChips>(`${ROOT}-chips`)) chips.chips?.set(this.#values.get().map((v) => ({ value: v, label: this.labelOf(v) })));
    // A single combobox shows its choice in the input until the user types.
    const input = this._input();
    if (input && !this.multiple && !this.open && !this.#query.get()) {
      const first = this.#values.get()[0];
      const label = first ? this.labelOf(first) : '';
      if (input.value !== label && document.activeElement !== input) input.value = label;
    }
  }

  _afterOpen(): void {
    const panel = this._panel() as (HTMLElement & { showPopover?: () => void }) | null;
    const anchor = this._anchor();
    if (!panel || !anchor) return;
    if (typeof panel.showPopover === 'function' && !panel.matches(':popover-open')) panel.showPopover();
    this._reposition();
    document.addEventListener('pointerdown', this._onDocPointerDown, true);
    window.addEventListener('resize', this._reposition);
    if (!this.highlighted.get()) {
      const start = this._items().find((i) => this.#values.get().includes(i.itemValue) && !i.disabled)
        ?? this.visibleItems().find((i) => !i.disabled);
      this.highlighted.set(start?.itemValue ?? '');
    }
  }

  _afterClose(): void {
    const panel = this._panel() as (HTMLElement & { hidePopover?: () => void }) | null;
    if (panel && typeof panel.hidePopover === 'function' && panel.matches(':popover-open')) panel.hidePopover();
    document.removeEventListener('pointerdown', this._onDocPointerDown, true);
    window.removeEventListener('resize', this._reposition);
    this.highlighted.set('');
    if (!this.multiple) this.#query.set('');
  }

  _reposition = (): void => {
    const panel = this._panel();
    const anchor = this._anchor();
    const host = this.querySelector(`${ROOT}-content`);
    if (!panel || !anchor || !host) return;
    const a = anchor.getBoundingClientRect();
    panel.style.setProperty('--anchor-width', `${a.width}px`);
    panel.style.setProperty('--available-width', `${window.innerWidth - 16}px`);
    panel.style.setProperty('--available-height', `${Math.max(window.innerHeight - a.bottom, a.top) - 12}px`);
    positionFloating(anchor, panel, {
      side: (host.getAttribute('side') ?? 'bottom') as PopoverSide,
      align: (host.getAttribute('align') ?? 'start') as PopoverAlign,
      sideOffset: Number(host.getAttribute('side-offset') ?? 6),
      alignOffset: Number(host.getAttribute('align-offset') ?? 0),
    });
  };

  _move(by: number): void {
    const enabled = this.visibleItems().filter((i) => !i.disabled);
    if (!enabled.length) return;
    const at = enabled.findIndex((i) => i.itemValue === this.highlighted.get());
    const next = at < 0 ? (by > 0 ? 0 : enabled.length - 1) : Math.max(0, Math.min(enabled.length - 1, at + by));
    this.highlighted.set(enabled[next].itemValue);
    enabled[next].scrollIntoViewIfShown();
  }

  _onKeyDown = (e: KeyboardEvent): void => {
    const input = this._input();
    if (!input || e.target !== input || e.isComposing) return;
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      e.preventDefault();
      if (!this.open) { this.show(); return; }
      this._move(e.key === 'ArrowDown' ? 1 : -1);
    } else if (e.key === 'Enter') {
      if (!this.open || !this.highlighted.get()) return;
      e.preventDefault();
      this.choose(this.highlighted.get());
    } else if (e.key === 'Escape') {
      if (!this.open) return;
      e.preventDefault();
      this.hide();
    } else if (e.key === 'Tab') {
      this.hide();
    } else if (e.key === 'Backspace' && this.multiple && !input.value && this.#values.get().length) {
      const values = this.#values.get();
      this.removeValue(values[values.length - 1]);
    }
  };

  _onInput(text: string): void {
    this._setQuery(text);
  }

  _onFocusOut = (e: FocusEvent): void => {
    const next = e.relatedTarget as Node | null;
    if (next && this.contains(next)) return;
    this.hide();
    // Leaving a single combobox puts its choice back in the input.
    if (!this.multiple) {
      this.#query.set('');
      const input = this._input();
      const first = this.#values.get()[0];
      if (input) input.value = first ? this.labelOf(first) : '';
    }
  };

  _onDocPointerDown = (e: Event): void => {
    if (e.composedPath().includes(this)) return;
    this.hide();
  };
}
UiCombobox.register('ui-combobox');

type FieldState = { open: boolean; activeId: string; hasValue: boolean };

function rootOf(el: Element): UiCombobox | null {
  return (typeof el.closest === 'function' ? el.closest(ROOT) : null) as UiCombobox | null;
}

// A part connected after the root's first update (a client render appends
// children in order) asks the root to push its state again.
function announce(el: Element): void {
  const root = rootOf(el);
  if (root) queueMicrotask(() => root.requestUpdate?.());
}

// --------------------------------------------------------------------------
// <ui-combobox-input>
// --------------------------------------------------------------------------

export class UiComboboxInput extends WebComponent({
  placeholder: String,
  inputId: prop(String, { attribute: 'input-id' }),
  showTrigger: prop(String, { attribute: 'show-trigger' }),
  showClear: prop(Boolean, { attribute: 'show-clear' }),
  // The field state an author writes on the host belongs on the input, the
  // focusable control, as shadcn passes ComboboxInput's props to its input:
  // `aria-invalid` for the error look and the announcement, and
  // `aria-describedby` for the error text. Observed, so a re-validation that
  // changes them reaches the input.
  invalid: prop(String, { attribute: 'aria-invalid' }),
  describedBy: prop(String, { attribute: 'aria-describedby' }),
}) {
  readonly state = signal<FieldState>({ open: false, activeId: '', hasValue: false });
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  constructor() {
    super();
    this.placeholder = '';
    this.inputId = '';
    this.invalid = '';
    this.describedBy = '';
    this.showTrigger = 'true';
    this.showClear = false;
  }

  render() {
    const root = rootOf(this);
    const s = this.state.get();
    const disabled = !!root?.disabled;
    return html`<div data-slot="input-group" class=${cn(inputGroupClass(), comboboxInputClass())}><input
      data-slot="input-group-control"
      id=${this.inputId || nothing}
      type="text"
      role="combobox"
      autocomplete="off"
      aria-autocomplete="list"
      aria-expanded=${s.open ? 'true' : 'false'}
      aria-controls=${root?.listId || nothing}
      aria-activedescendant=${s.activeId || nothing}
      aria-label=${this.getAttribute?.('aria-label') || nothing}
      aria-invalid=${this.invalid === 'true' ? 'true' : nothing}
      aria-describedby=${this.describedBy || nothing}
      placeholder=${this.placeholder || nothing}
      ?disabled=${disabled}
      class=${inputGroupInputClass()}
      @input=${(e: Event) => rootOf(this)?._onInput((e.target as HTMLInputElement).value)}
      @click=${() => rootOf(this)?.show()}
    ><div data-slot="input-group-addon" data-align="inline-end" class=${inputGroupAddonClass({ align: 'inline-end' })}>${this.showTrigger !== 'false'
      ? html`<button
          type="button"
          data-slot="input-group-button"
          tabindex="-1"
          aria-label="Open"
          ?disabled=${disabled}
          class=${cn(buttonClass({ variant: 'ghost' }), inputGroupButtonClass({ size: 'icon-xs' }), 'group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent', comboboxTriggerClass())}
          @click=${this._onTrigger}
        ><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" class=${comboboxTriggerIconClass()}><path d="m6 9 6 6 6-6"></path></svg></button>`
      : ''}${this.showClear && s.hasValue
      ? html`<button
          type="button"
          data-slot="combobox-clear"
          aria-label="Clear"
          ?disabled=${disabled}
          class=${cn(buttonClass({ variant: 'ghost' }), inputGroupButtonClass({ size: 'icon-xs' }), comboboxClearClass())}
          @click=${() => rootOf(this)?.clear()}
        >${X_ICON(comboboxClearIconClass())}</button>`
      : ''}</div></div>`;
  }

  _onTrigger = (): void => {
    const root = rootOf(this);
    if (!root) return;
    root._input()?.focus();
    if (root.open) root.hide();
    else root.show();
  };
}
UiComboboxInput.register('ui-combobox-input');

// --------------------------------------------------------------------------
// <ui-combobox-content> and <ui-combobox-list>
// --------------------------------------------------------------------------

export class UiComboboxContent extends WebComponent {
  readonly open = signal(false);
  readonly empty = signal(false);
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  constructor() {
    super();
  }

  render() {
    const chips = !!rootOf(this)?.querySelector?.('[data-slot="combobox-chips"]');
    return html`<div
      data-slot="combobox-content"
      popover="manual"
      data-state=${this.open.get() ? 'open' : 'closed'}
      ?data-empty=${this.empty.get()}
      data-chips=${chips ? 'true' : 'false'}
      class=${comboboxContentClass()}
      @pointerdown=${(e: PointerEvent) => { if (!(e.target as Element).closest('input')) e.preventDefault(); }}
    ><slot></slot></div>`;
  }
}
UiComboboxContent.register('ui-combobox-content');

export class UiComboboxList extends WebComponent {
  readonly empty = signal(false);
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  constructor() {
    super();
  }

  render() {
    const root = rootOf(this);
    return html`<div
      data-slot="combobox-list"
      role="listbox"
      id=${root?.listId || nothing}
      aria-multiselectable=${root?.multiple ? 'true' : nothing}
      ?data-empty=${this.empty.get()}
      class=${comboboxListClass()}
    ><slot></slot></div>`;
  }
}
UiComboboxList.register('ui-combobox-list');

// --------------------------------------------------------------------------
// <ui-combobox-item>
// --------------------------------------------------------------------------

type ItemState = { visible: boolean; selected: boolean; highlighted: boolean };

export class UiComboboxItem extends WebComponent({
  value: String,
  disabled: Boolean,
}) {
  readonly state = signal<ItemState>({ visible: true, selected: false, highlighted: false });
  _id = '';

  constructor() {
    super();
    this.value = '';
    this.disabled = false;
  }

  connectedCallback(): void {
    super.connectedCallback?.();
    this._id ||= `ui-combobox-item-${++uid}`;
    announce(this);
  }

  get optionId(): string {
    return `${this._id}-option`;
  }

  /** The item's label: its text. */
  get label(): string {
    const text = this.querySelector?.('[data-slot="combobox-item-text"]')?.textContent ?? this.textContent ?? '';
    return text.trim();
  }

  /** The item's value: its `value` attribute, else its label. */
  get itemValue(): string {
    return this.value || this.label;
  }

  scrollIntoViewIfShown(): void {
    const option = this.querySelector?.<HTMLElement>('[role="option"]');
    if (option && typeof option.scrollIntoView === 'function') option.scrollIntoView({ block: 'nearest' });
  }

  updated(changedProperties: Map<string, unknown>): void {
    super.updated?.(changedProperties);
    this.hidden = !this.state.get().visible;
  }

  render() {
    const s = this.state.get();
    return html`<div
      data-slot="combobox-item"
      role="option"
      id=${this._id ? this.optionId : nothing}
      aria-selected=${s.selected ? 'true' : 'false'}
      ?data-selected=${s.selected}
      ?data-highlighted=${s.highlighted}
      aria-disabled=${this.disabled ? 'true' : nothing}
      ?data-disabled=${this.disabled}
      class=${comboboxItemClass()}
      @pointermove=${this._onPointerMove}
      @click=${this._onClick}
    ><span data-slot="combobox-item-text" class="flex flex-1 gap-2"><slot></slot></span><span class=${comboboxItemIndicatorClass()}>${s.selected
      ? html`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" class=${comboboxItemIndicatorIconClass()}><path d="M20 6 9 17l-5-5"></path></svg>`
      : ''}</span></div>`;
  }

  _onPointerMove = (): void => {
    const root = rootOf(this);
    if (!root || this.disabled || this.state.get().highlighted) return;
    root.highlighted?.set(this.itemValue);
  };

  _onClick = (): void => {
    rootOf(this)?.choose(this.itemValue);
  };
}
UiComboboxItem.register('ui-combobox-item');

// --------------------------------------------------------------------------
// <ui-combobox-group>, <ui-combobox-label>, <ui-combobox-empty>, <ui-combobox-separator>
// --------------------------------------------------------------------------

export class UiComboboxGroup extends WebComponent {
  readonly shown = signal(true);
  constructor() {
    super();
  }

  updated(changedProperties: Map<string, unknown>): void {
    super.updated?.(changedProperties);
    this.hidden = !this.shown.get();
  }

  /** The group's label, or null on the server, where there is no DOM to query. */
  _label(): Element | null {
    return typeof this.querySelector === 'function' ? this.querySelector('ui-combobox-label [data-slot="combobox-label"]') : null;
  }

  render() {
    const label = this._label();
    return html`<div data-slot="combobox-group" role="group" aria-labelledby=${label?.id || nothing} class=${comboboxGroupClass()}><slot></slot></div>`;
  }

  connectedCallback(): void {
    super.connectedCallback?.();
    // The label renders after the group, so name the group once it has.
    queueMicrotask(() => this.requestUpdate?.());
    announce(this);
  }
}
UiComboboxGroup.register('ui-combobox-group');

export class UiComboboxLabel extends WebComponent {
  _id = '';

  connectedCallback(): void {
    this._id ||= `ui-combobox-label-${++uid}`;
    super.connectedCallback?.();
  }

  render() {
    return html`<div data-slot="combobox-label" id=${this._id || nothing} class=${comboboxLabelClass()}><slot></slot></div>`;
  }
}
UiComboboxLabel.register('ui-combobox-label');

export class UiComboboxEmpty extends WebComponent {
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  render() {
    return html`<div data-slot="combobox-empty" class=${comboboxEmptyClass()}><slot></slot></div>`;
  }
}
UiComboboxEmpty.register('ui-combobox-empty');

export class UiComboboxSeparator extends WebComponent {
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  render() {
    return html`<div data-slot="combobox-separator" role="separator" class=${comboboxSeparatorClass()}></div>`;
  }
}
UiComboboxSeparator.register('ui-combobox-separator');

// --------------------------------------------------------------------------
// <ui-combobox-chips> and <ui-combobox-chips-input>
// --------------------------------------------------------------------------

export class UiComboboxChips extends WebComponent {
  readonly chips = signal<{ value: string; label: string }[]>([]);
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  constructor() {
    super();
  }

  render() {
    const root = rootOf(this);
    const disabled = !!root?.disabled;
    return html`<div data-slot="combobox-chips" class=${comboboxChipsClass()} @click=${this._focusInput}>${this.chips.get().map((c) => html`<div
      data-slot="combobox-chip" class=${comboboxChipClass()}
    >${c.label}<button
      type="button"
      data-slot="combobox-chip-remove"
      aria-label=${`Remove ${c.label}`}
      ?disabled=${disabled}
      class=${cn(buttonClass({ variant: 'ghost', size: 'icon-xs' }), comboboxChipRemoveClass())}
      @click=${(e: Event) => { e.stopPropagation(); rootOf(this)?.removeValue(c.value); rootOf(this)?._input()?.focus(); }}
    >${X_ICON(comboboxChipIndicatorIconClass())}</button></div>`)}<slot></slot></div>`;
  }

  _focusInput = (e: Event): void => {
    if ((e.target as Element).closest('button')) return;
    rootOf(this)?._input()?.focus();
  };
}
UiComboboxChips.register('ui-combobox-chips');

export class UiComboboxChipsInput extends WebComponent({
  placeholder: String,
  inputId: prop(String, { attribute: 'input-id' }),
}) {
  readonly state = signal<FieldState>({ open: false, activeId: '', hasValue: false });
  connectedCallback(): void {
    super.connectedCallback?.();
    announce(this);
  }

  constructor() {
    super();
    this.placeholder = '';
    this.inputId = '';
  }

  render() {
    const root = rootOf(this);
    const s = this.state.get();
    return html`<input
      data-slot="combobox-chip-input"
      id=${this.inputId || nothing}
      type="text"
      role="combobox"
      autocomplete="off"
      aria-autocomplete="list"
      aria-expanded=${s.open ? 'true' : 'false'}
      aria-controls=${root?.listId || nothing}
      aria-activedescendant=${s.activeId || nothing}
      aria-label=${this.getAttribute?.('aria-label') || nothing}
      placeholder=${this.placeholder || nothing}
      ?disabled=${!!root?.disabled}
      class=${comboboxChipInputClass()}
      @input=${(e: Event) => rootOf(this)?._onInput((e.target as HTMLInputElement).value)}
      @click=${() => rootOf(this)?.show()}
    >`;
  }
}
UiComboboxChipsInput.register('ui-combobox-chips-input');
````

### Update the import paths to match your project setup.

## Usage

```ts
import '#components/ui/combobox.ts';
```

```ts
const frameworks = ['Next.js', 'SvelteKit', 'Nuxt.js', 'Remix', 'Astro'];

export function exampleCombobox() {
  return html`
    <ui-combobox name="framework">
      <ui-combobox-input placeholder="Select a framework" aria-label="Framework"></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Composition

### Simple

A single-line input and a flat list (see Basic).

```text
ui-combobox
├── ui-combobox-input
└── ui-combobox-content
    ├── ui-combobox-empty
    └── ui-combobox-list
        ├── ui-combobox-item
        └── ui-combobox-item
```

### With chips

Multi-select with `multiple`, chips, and a chips input (see Multiple). The chips are drawn from the chosen values, so the markup holds only the chips input.

```text
ui-combobox multiple
├── ui-combobox-chips
│   └── ui-combobox-chips-input
└── ui-combobox-content
    ├── ui-combobox-empty
    └── ui-combobox-list
        ├── ui-combobox-item
        └── ui-combobox-item
```

### With groups and collection

Items nested in each `<ui-combobox-group>`, with a separator between groups (see Groups). The items go straight into the group, after its label.

```text
ui-combobox
├── ui-combobox-input
└── ui-combobox-content
    ├── ui-combobox-empty
    └── ui-combobox-list
        ├── ui-combobox-group
        │   ├── ui-combobox-label
        │   ├── ui-combobox-item
        │   ├── ui-combobox-item
        │   └── ui-combobox-separator
        └── ui-combobox-group
            ├── ui-combobox-label
            ├── ui-combobox-item
            └── ui-combobox-item
```

## Custom Items

When your items are objects, render one `<ui-combobox-item>` per object, with the object's id as its `value` and its label as its text. The list filters on the text, and the form submits the value.

```ts
type Framework = {
  label: string;
  value: string;
};

const frameworks: Framework[] = [
  { label: 'Next.js', value: 'next' },
  { label: 'SvelteKit', value: 'sveltekit' },
  { label: 'Nuxt', value: 'nuxt' },
];

export function exampleComboboxCustomItems() {
  return html`
    <ui-combobox name="framework">
      <ui-combobox-input placeholder="Select a framework" aria-label="Framework"></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks.map((framework) => html`
            <ui-combobox-item value=${framework.value}>${framework.label}</ui-combobox-item>
          `)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Multiple Selection

Use `multiple` with chips for multi-select behavior. `value` holds the initial choice as a comma separated list, every choice is submitted as its own `name` entry, and `ui-value-change` reports the array as it changes.

```ts
const frameworks = ['Next.js', 'SvelteKit', 'Nuxt.js', 'Remix', 'Astro'];

export function exampleComboboxMultiple() {
  return html`
    <ui-combobox name="frameworks" multiple @ui-value-change=${(e: CustomEvent<{ value: string[] }>) => console.log(e.detail.value)}>
      <ui-combobox-chips>
        <ui-combobox-chips-input placeholder="Add framework" aria-label="Frameworks"></ui-combobox-chips-input>
      </ui-combobox-chips>
      <ui-combobox-content>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Basic

A simple combobox with a list of frameworks.

```ts
import { html } from '@webjsdev/core';

const frameworks = ['Next.js', 'SvelteKit', 'Nuxt.js', 'Remix', 'Astro'];

export default function ComboboxBasic() {
  return html`
    <ui-combobox>
      <ui-combobox-input placeholder="Select a framework" aria-label="Framework"></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Multiple

A combobox with multiple selection using `multiple` and `<ui-combobox-chips>`.

```ts
import { html } from '@webjsdev/core';

const frameworks = ['Next.js', 'SvelteKit', 'Nuxt.js', 'Remix', 'Astro'];

// The chips are drawn from the chosen values, so the markup holds only the
// chips input. `value` is the initial choice, comma separated.
export default function ComboboxMultiple() {
  return html`
    <ui-combobox multiple value=${frameworks[0]} class="w-full max-w-xs">
      <ui-combobox-chips>
        <ui-combobox-chips-input aria-label="Frameworks"></ui-combobox-chips-input>
      </ui-combobox-chips>
      <ui-combobox-content>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Clear Button

Use the `show-clear` attribute to show a clear button.

```ts
import { html } from '@webjsdev/core';

const frameworks = ['Next.js', 'SvelteKit', 'Nuxt.js', 'Remix', 'Astro'];

export default function ComboboxWithClear() {
  return html`
    <ui-combobox value=${frameworks[0]}>
      <ui-combobox-input placeholder="Select a framework" aria-label="Framework" show-clear></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Groups

Use `<ui-combobox-group>` and `<ui-combobox-separator>` to group items.

```ts
import { html } from '@webjsdev/core';

const timezones = [
  {
    value: 'Americas',
    items: [
      '(GMT-5) New York',
      '(GMT-8) Los Angeles',
      '(GMT-6) Chicago',
      '(GMT-5) Toronto',
      '(GMT-8) Vancouver',
      '(GMT-3) São Paulo',
    ],
  },
  {
    value: 'Europe',
    items: [
      '(GMT+0) London',
      '(GMT+1) Paris',
      '(GMT+1) Berlin',
      '(GMT+1) Rome',
      '(GMT+1) Madrid',
      '(GMT+1) Amsterdam',
    ],
  },
  {
    value: 'Asia/Pacific',
    items: [
      '(GMT+9) Tokyo',
      '(GMT+8) Shanghai',
      '(GMT+8) Singapore',
      '(GMT+4) Dubai',
      '(GMT+11) Sydney',
      '(GMT+9) Seoul',
    ],
  },
];

export default function ComboboxWithGroupsAndSeparator() {
  return html`
    <ui-combobox>
      <ui-combobox-input placeholder="Select a timezone" aria-label="Timezone"></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No timezones found.</ui-combobox-empty>
        <ui-combobox-list>
          ${timezones.map((group, index) => html`
            <ui-combobox-group>
              <ui-combobox-label>${group.value}</ui-combobox-label>
              ${group.items.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
              ${index < timezones.length - 1 ? html`<ui-combobox-separator></ui-combobox-separator>` : ''}
            </ui-combobox-group>
          `)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Custom Items

You can render custom markup inside `<ui-combobox-item>`. The item's whole text is what the list filters on.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  itemClass, itemContentClass, itemTitleClass, itemDescriptionClass,
} from '#components/ui/item.ts';

const countries = [
  { code: '', value: '', continent: '', label: 'Select country' },
  { code: 'ar', value: 'argentina', label: 'Argentina', continent: 'South America' },
  { code: 'au', value: 'australia', label: 'Australia', continent: 'Oceania' },
  { code: 'br', value: 'brazil', label: 'Brazil', continent: 'South America' },
  { code: 'ca', value: 'canada', label: 'Canada', continent: 'North America' },
  { code: 'cn', value: 'china', label: 'China', continent: 'Asia' },
  { code: 'co', value: 'colombia', label: 'Colombia', continent: 'South America' },
  { code: 'eg', value: 'egypt', label: 'Egypt', continent: 'Africa' },
  { code: 'fr', value: 'france', label: 'France', continent: 'Europe' },
  { code: 'de', value: 'germany', label: 'Germany', continent: 'Europe' },
  { code: 'it', value: 'italy', label: 'Italy', continent: 'Europe' },
  { code: 'jp', value: 'japan', label: 'Japan', continent: 'Asia' },
  { code: 'ke', value: 'kenya', label: 'Kenya', continent: 'Africa' },
  { code: 'mx', value: 'mexico', label: 'Mexico', continent: 'North America' },
  { code: 'nz', value: 'new-zealand', label: 'New Zealand', continent: 'Oceania' },
  { code: 'ng', value: 'nigeria', label: 'Nigeria', continent: 'Africa' },
  { code: 'za', value: 'south-africa', label: 'South Africa', continent: 'Africa' },
  { code: 'kr', value: 'south-korea', label: 'South Korea', continent: 'Asia' },
  { code: 'gb', value: 'united-kingdom', label: 'United Kingdom', continent: 'Europe' },
  { code: 'us', value: 'united-states', label: 'United States', continent: 'North America' },
];

// An item's value is its `value` attribute and its label is its text, so an
// object list maps to items with the id as the value.
export default function ComboboxWithCustomItems() {
  return html`
    <ui-combobox>
      <ui-combobox-input placeholder="Search countries..." aria-label="Country"></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No countries found.</ui-combobox-empty>
        <ui-combobox-list>
          ${countries.filter((country) => country.code !== '').map((country) => html`
            <ui-combobox-item value=${country.value}>
              <div data-slot="item" data-variant="default" data-size="xs" class=${cn(itemClass({ size: 'xs' }), 'p-0')}>
                <div data-slot="item-content" class=${itemContentClass()}>
                  <div data-slot="item-title" class=${cn(itemTitleClass(), 'whitespace-nowrap')}>${country.label}</div>
                  <p data-slot="item-description" class=${itemDescriptionClass()}>${country.continent} (${country.code})</p>
                </div>
              </div>
            </ui-combobox-item>
          `)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Invalid

The input part renders its own input and does not pass `aria-invalid` on to it yet, so mark the invalid state on the field around the combobox, with `data-invalid` and an error message.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { fieldClass, fieldLabelClass, fieldErrorClass } from '#components/ui/field.ts';

const frameworks = ['Next.js', 'SvelteKit', 'Nuxt.js', 'Remix', 'Astro'];

// The input part renders its own input and does not pass aria-invalid on to
// it yet, so the invalid state is carried by the field around it:
// data-invalid on the field, and the error below the control.
export default function ComboboxInvalid() {
  return html`
    <div role="group" data-slot="field" data-orientation="vertical" data-invalid="true" class=${cn(fieldClass(), 'w-full max-w-xs')}>
      <label data-slot="field-label" for="combobox-invalid" class=${fieldLabelClass()}>Framework</label>
      <ui-combobox>
        <ui-combobox-input input-id="combobox-invalid" placeholder="Select a framework"></ui-combobox-input>
        <ui-combobox-content>
          <ui-combobox-empty>No items found.</ui-combobox-empty>
          <ui-combobox-list>
            ${frameworks.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
          </ui-combobox-list>
        </ui-combobox-content>
      </ui-combobox>
      <div role="alert" data-slot="field-error" class=${fieldErrorClass()}>Please select a framework.</div>
    </div>
  `;
}
```

## Disabled

Use the `disabled` attribute on `<ui-combobox>` to disable the combobox.

```ts
import { html } from '@webjsdev/core';

const frameworks = ['Next.js', 'SvelteKit', 'Nuxt.js', 'Remix', 'Astro'];

export default function ComboboxDisabled() {
  return html`
    <ui-combobox disabled>
      <ui-combobox-input placeholder="Select a framework" aria-label="Framework"></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Auto Highlight

The combobox always highlights the first match as you type, so Enter picks it.

```ts
import { html } from '@webjsdev/core';

const frameworks = ['Next.js', 'SvelteKit', 'Nuxt.js', 'Remix', 'Astro'];

// Typing highlights the first match on its own, so there is nothing to set.
export default function ComboboxAutoHighlight() {
  return html`
    <ui-combobox>
      <ui-combobox-input placeholder="Select a framework" aria-label="Framework"></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No items found.</ui-combobox-empty>
        <ui-combobox-list>
          ${frameworks.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## Popup

The combobox opens from its own input, and does not take a button trigger. To open a searchable list from a button, put a [Command](https://webjs.dev/ui/docs/components/command) in a [Popover](https://webjs.dev/ui/docs/components/popover), with the search field inside the popup, and listen for `ui-select` to show the choice on the button.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import { popoverContentClass } from '#components/ui/popover.ts';
import { ChevronDownIcon } from '#lib/ui/lucide.ts';

const countries = [
  { code: '', value: '', continent: '', label: 'Select country' },
  { code: 'ar', value: 'argentina', label: 'Argentina', continent: 'South America' },
  { code: 'au', value: 'australia', label: 'Australia', continent: 'Oceania' },
  { code: 'br', value: 'brazil', label: 'Brazil', continent: 'South America' },
  { code: 'ca', value: 'canada', label: 'Canada', continent: 'North America' },
  { code: 'cn', value: 'china', label: 'China', continent: 'Asia' },
  { code: 'co', value: 'colombia', label: 'Colombia', continent: 'South America' },
  { code: 'eg', value: 'egypt', label: 'Egypt', continent: 'Africa' },
  { code: 'fr', value: 'france', label: 'France', continent: 'Europe' },
  { code: 'de', value: 'germany', label: 'Germany', continent: 'Europe' },
  { code: 'it', value: 'italy', label: 'Italy', continent: 'Europe' },
  { code: 'jp', value: 'japan', label: 'Japan', continent: 'Asia' },
  { code: 'ke', value: 'kenya', label: 'Kenya', continent: 'Africa' },
  { code: 'mx', value: 'mexico', label: 'Mexico', continent: 'North America' },
  { code: 'nz', value: 'new-zealand', label: 'New Zealand', continent: 'Oceania' },
  { code: 'ng', value: 'nigeria', label: 'Nigeria', continent: 'Africa' },
  { code: 'za', value: 'south-africa', label: 'South Africa', continent: 'Africa' },
  { code: 'kr', value: 'south-korea', label: 'South Korea', continent: 'Asia' },
  { code: 'gb', value: 'united-kingdom', label: 'United Kingdom', continent: 'Europe' },
  { code: 'us', value: 'united-states', label: 'United States', continent: 'North America' },
];

// The combobox opens from its own input, so a list opened from a button is
// a Command in a Popover: the button shows the choice, and the search field
// sits inside the popup. Listen for `ui-select` to set the button's text.
export default function ComboboxPopup() {
  return html`
    <button type="button" popovertarget="combobox-popup" aria-haspopup="dialog" aria-expanded="false" data-slot="button" data-variant="outline" data-size="default" class=${cn(buttonClass({ variant: 'outline' }), 'w-64 justify-between font-normal')}>
      <span>${countries[0].label}</span>
      ${ChevronDownIcon()}
    </button>
    <div id="combobox-popup" popover role="dialog" aria-label="Select country" data-slot="popover-content" class=${cn(popoverContentClass({ align: 'start' }), 'w-64 p-0')}>
      <ui-command label="Countries">
        <ui-command-input placeholder="Search"></ui-command-input>
        <ui-command-list>
          <ui-command-empty>No items found.</ui-command-empty>
          ${countries.map((item) => html`<ui-command-item value=${item.value || 'none'}>${item.label}</ui-command-item>`)}
        </ui-command-list>
      </ui-command>
    </div>
  `;
}
```

## Input Group

The input part renders its own [Input Group](https://webjs.dev/ui/docs/components/input-group), with the trigger as its addon, and does not take an addon of its own yet.

```ts
import { html } from '@webjsdev/core';

const timezones = [
  {
    value: 'Americas',
    items: [
      '(GMT-5) New York',
      '(GMT-8) Los Angeles',
      '(GMT-6) Chicago',
      '(GMT-5) Toronto',
      '(GMT-8) Vancouver',
      '(GMT-3) São Paulo',
    ],
  },
  {
    value: 'Europe',
    items: [
      '(GMT+0) London',
      '(GMT+1) Paris',
      '(GMT+1) Berlin',
      '(GMT+1) Rome',
      '(GMT+1) Madrid',
      '(GMT+1) Amsterdam',
    ],
  },
  {
    value: 'Asia/Pacific',
    items: [
      '(GMT+9) Tokyo',
      '(GMT+8) Shanghai',
      '(GMT+8) Singapore',
      '(GMT+4) Dubai',
      '(GMT+11) Sydney',
      '(GMT+9) Seoul',
    ],
  },
];

// The input part renders its own input group, with the trigger as its one
// addon, and takes no addon of its own yet.
export default function ComboboxInputGroup() {
  return html`
    <ui-combobox>
      <ui-combobox-input placeholder="Select a timezone" aria-label="Timezone"></ui-combobox-input>
      <ui-combobox-content>
        <ui-combobox-empty>No timezones found.</ui-combobox-empty>
        <ui-combobox-list>
          ${timezones.map((group) => html`
            <ui-combobox-group>
              <ui-combobox-label>${group.value}</ui-combobox-label>
              ${group.items.map((item) => html`<ui-combobox-item value=${item}>${item}</ui-combobox-item>`)}
            </ui-combobox-group>
          `)}
        </ui-combobox-list>
      </ui-combobox-content>
    </ui-combobox>
  `;
}
```

## RTL

To enable RTL support, see the [RTL configuration guide](https://webjs.dev/ui/docs/rtl).

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { fieldClass, fieldLabelClass } from '#components/ui/field.ts';

const categories = ['technology', 'design', 'business', 'marketing', 'education', 'health'] as const;

const translations = {
  en: {
    dir: 'ltr',
    values: {
      label: 'Categories',
      placeholder: 'Add categories',
      empty: 'No categories found.',
      technology: 'Technology',
      design: 'Design',
      business: 'Business',
      marketing: 'Marketing',
      education: 'Education',
      health: 'Health',
    },
  },
  ar: {
    dir: 'rtl',
    values: {
      label: 'الفئات',
      placeholder: 'أضف فئات',
      empty: 'لم يتم العثور على فئات.',
      technology: 'التكنولوجيا',
      design: 'التصميم',
      business: 'الأعمال',
      marketing: 'التسويق',
      education: 'التعليم',
      health: 'الصحة',
    },
  },
  he: {
    dir: 'rtl',
    values: {
      label: 'קטגוריות',
      placeholder: 'הוסף קטגוריות',
      empty: 'לא נמצאו קטגוריות.',
      technology: 'טכנולוגיה',
      design: 'עיצוב',
      business: 'עסקים',
      marketing: 'שיווק',
      education: 'חינוך',
      health: 'בריאות',
    },
  },
};

// The provider is the dir attribute: every part styles itself with logical
// properties, so dir="rtl" on the field flips the whole control. A chip
// shows its item's label, so the values stay the English keys.
export default function ComboboxRtl() {
  const lang = 'ar';
  const { dir, values: t } = translations[lang];

  return html`
    <div role="group" data-slot="field" data-orientation="vertical" dir=${dir} lang=${lang} class=${cn(fieldClass(), 'mx-auto w-full max-w-xs')}>
      <label data-slot="field-label" for="combobox-rtl" class=${fieldLabelClass()}>${t.label}</label>
      <ui-combobox multiple value=${categories[0]}>
        <ui-combobox-chips>
          <ui-combobox-chips-input input-id="combobox-rtl" placeholder=${t.placeholder}></ui-combobox-chips-input>
        </ui-combobox-chips>
        <ui-combobox-content dir=${dir}>
          <ui-combobox-empty>${t.empty}</ui-combobox-empty>
          <ui-combobox-list>
            ${categories.map((item) => html`<ui-combobox-item value=${item}>${t[item]}</ui-combobox-item>`)}
          </ui-combobox-list>
        </ui-combobox-content>
      </ui-combobox>
    </div>
  `;
}
```

## API Reference

Typing filters the list, the arrow keys highlight while focus stays in the input, and Enter picks. The choice lives in a real form control, one `<input type="hidden" name>` per chosen value, served by the server, so the form submits it with or without JavaScript.

### Elements

| Element | Description |
| --- | --- |
| `<ui-combobox>` | The root. Holds the value, the open state and the hidden form inputs. |
| `<ui-combobox-input>` | The text field, a `role="combobox"` input in an input group with the trigger button and the optional clear button. |
| `<ui-combobox-content>` | The popup, placed against the input, or against the chips box with `multiple`. |
| `<ui-combobox-list>` | The `role="listbox"` holding the items. |
| `<ui-combobox-item>` | One choice, a `role="option"` with a check mark when chosen. |
| `<ui-combobox-empty>` | Shown when nothing matches the typed text. |
| `<ui-combobox-group>` | A `role="group"` of items, named by its label, hidden when none of its items match. |
| `<ui-combobox-label>` | A group heading. |
| `<ui-combobox-separator>` | A divider between groups. |
| `<ui-combobox-chips>` | The chips box for `multiple`. Draws one chip per chosen value, each with a remove button that names its value. |
| `<ui-combobox-chips-input>` | The text field inside the chips box. |

### ui-combobox

| Attribute | Type | Default |
| --- | --- | --- |
| `name` | `string` | - |
| `value` | `string`, comma separated with `multiple` | - |
| `multiple` | `boolean` | `false` |
| `disabled` | `boolean` | `false` |
| `open` | `boolean`, reflected | `false` |

From code, `show()` and `hide()` open and close the list, `choose(value)` picks an item, `removeValue(value)` drops one choice, and `clear()` drops them all.

### ui-combobox-input

| Attribute | Type | Default |
| --- | --- | --- |
| `placeholder` | `string` | - |
| `input-id` | `string`, the id a `<label for>` points at | - |
| `aria-label` | `string`, passed to the input | - |
| `show-trigger` | `"true" \| "false"` | `"true"` |
| `show-clear` | `boolean` | `false` |

`<ui-combobox-chips-input>` takes the same `placeholder`, `input-id` and `aria-label`.

### ui-combobox-content

| Attribute | Type | Default |
| --- | --- | --- |
| `side` | `"top" \| "right" \| "bottom" \| "left"` | `"bottom"` |
| `align` | `"start" \| "center" \| "end"` | `"start"` |
| `side-offset` | `number` | `6` |
| `align-offset` | `number` | `0` |

### ui-combobox-item

| Attribute | Type | Default |
| --- | --- | --- |
| `value` | `string` | The item's text |
| `disabled` | `boolean` | `false` |

### Events

| Event | Detail | Fires |
| --- | --- | --- |
| `ui-value-change` | `{ value: string }`, or `{ value: string[] }` with `multiple` | When the choice changes. |
| `ui-open-change` | `{ open: boolean }` | When the list opens or closes. |

### Keyboard

ArrowDown and ArrowUp open the list and move the highlight, Enter picks the highlighted item, Escape closes, and Tab closes and moves on. With `multiple`, picking toggles an item and keeps the list open, and Backspace in an empty input removes the last chip. Leaving a single combobox puts the chosen item's label back in the input.
