# Combobox

Input teks dengan daftar saran terfilter di popover, mengikuti pola WAI-ARIA Combobox dengan autocomplete list.

- Kategori: Form
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/combobox.json
- CLI: `npx markasui@latest add combobox`

## Kapan dipakai

Memilih satu nilai dari daftar panjang saat mengetik untuk mencari lebih cepat daripada menggulir: negara, kota, pengguna, tag.

- Pakai Select untuk daftar pendek di bawah sekitar 10 opsi
- Isi name agar value terpilih, bukan label yang tampil, yang terkirim
- Mengetik mengosongkan value terpilih sampai opsi dipilih lagi; validasi value-nya, bukan teksnya

## Kode

### Blade

Simpan di `resources/views/components/markas/combobox.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'options' => [],
    'label' => null,
    'hint' => null,
    'error' => null,
    'name' => null,
    'value' => '',
    'emptyLabel' => 'No results',
])

@php
    $wrapper = 'grid gap-1.5';
    $labelClass = 'text-sm font-medium text-ink';
    $control = 'relative';
    $field = 'h-10 w-full rounded-md border border-line bg-surface ps-3 pe-9 text-sm text-ink transition-colors duration-150 ease-out placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none';
    $chevron = 'pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted';
    $panel = 'inset-auto m-0 max-h-60 overflow-y-auto rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay';
    $optionClass = 'flex cursor-pointer items-center justify-between gap-2 rounded-md px-3 py-2 text-sm text-ink hover:bg-subtle aria-selected:bg-subtle';
    $check = 'size-4 shrink-0 text-primary';
    $emptyClass = 'px-3 py-2 text-sm text-muted';
    $hintClass = 'text-sm text-muted';
    $errorClass = 'text-sm text-danger';

    $options = array_values(array_map(fn ($option) => ['value' => (string) $option['value'], 'label' => (string) $option['label']], $options));
    $value = (string) $value;
    $text = collect($options)->firstWhere('value', $value)['label'] ?? '';
    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-combobox|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $name).'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $id = $attributes->get('id') ?? 'markas-combobox-'.hash('xxh32', $idKey.$idIndex);
    $listId = $id.'-listbox';
    $describedBy = $error ? $id.'-error' : ($hint ? $id.'-hint' : null);
@endphp

<div
    x-data="{
        options: @js($options),
        value: @js($value),
        text: @js($text),
        filter: '',
        active: -1,
        open: false,
        unfollow: null,
        {{-- value is bound by wire:model and x-model (x-modelable): show the matching label when it changes from outside. --}}
        init() {
            this.$watch('value', (next) => {
                const option = this.options.find((entry) => entry.value === String(next ?? ''));
                if (option) this.text = option.label;
                else if (document.activeElement !== this.$refs.input) this.text = this.filter = '';
            });
        },
        {{-- Indeks opsi (di daftar asli) yang labelnya memuat teks filter. --}}
        get visible() {
            const query = this.filter.trim().toLowerCase();
            return this.options.flatMap((option, index) => (option.label.toLowerCase().includes(query) ? [index] : []));
        },
        optionId(index) {
            return @js($id) + '-option-' + index;
        },
        isChecked(index) {
            return this.value !== '' && this.options[index].value === String(this.value ?? '');
        },
        commit(next) {
            if (next === String(this.value ?? '')) return;
            this.value = next;
            {{-- Dispatch from the input: it carries the user's attributes (x-on:, wire:), the list is outside it. --}}
            this.$refs.input.dispatchEvent(new CustomEvent('markas-change', { detail: next, bubbles: true }));
        },
        show() {
            if (!this.open) this.$refs.panel.showPopover();
        },
        hide() {
            this.active = -1;
            if (this.open) this.$refs.panel.hidePopover();
        },
        select(index) {
            const option = this.options[index];
            if (!option) return;
            this.commit(option.value);
            this.text = option.label;
            this.filter = '';
            this.hide();
        },
        move(step) {
            const list = this.visible;
            if (list.length === 0) return;
            const position = list.indexOf(this.active);
            const next = position === -1 ? (step === 1 ? 0 : list.length - 1) : (position + step + list.length) % list.length;
            this.setActive(list[next] ?? -1);
        },
        setActive(index) {
            this.active = index;
            if (index < 0) return;
            this.$nextTick(() => document.getElementById(this.optionId(index))?.scrollIntoView({ block: 'nearest' }));
        },
        onInput(event) {
            this.text = event.target.value;
            this.filter = event.target.value;
            this.active = -1;
            this.commit('');
            this.show();
        },
        onKeydown(event) {
            if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
                event.preventDefault();
                const step = event.key === 'ArrowDown' ? 1 : -1;
                if (this.open) return this.move(step);
                this.show();
                const list = this.visible;
                return this.setActive((step === 1 ? list[0] : list[list.length - 1]) ?? -1);
            }
            if (event.key === 'Enter' && this.open && this.active >= 0) {
                event.preventDefault();
                return this.select(this.active);
            }
            if (event.key !== 'Escape') return;
            event.preventDefault();
            if (this.open) return this.hide();
            this.text = '';
            this.filter = '';
            this.commit('');
        },
        {{-- Letakkan daftar di bawah input selebar input, pindah ke atas kalau tidak muat. --}}
        place() {
            const gap = 4;
            const anchor = this.$refs.input.getBoundingClientRect();
            this.$refs.panel.style.width = anchor.width + 'px';
            const { height } = this.$refs.panel.getBoundingClientRect();
            const below = anchor.bottom + gap;
            const above = anchor.top - gap - height;
            const fitsBelow = below + height <= window.innerHeight;
            this.$refs.panel.style.top = (fitsBelow || above < 0 ? below : above) + 'px';
            this.$refs.panel.style.left = anchor.left + 'px';
        },
        {{-- Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. --}}
        follow() {
            this.unfollow?.();
            const update = () => this.place();
            const scrollOptions = { capture: true, passive: true };
            window.addEventListener('scroll', update, scrollOptions);
            window.addEventListener('resize', update, { passive: true });
            this.unfollow = () => {
                window.removeEventListener('scroll', update, scrollOptions);
                window.removeEventListener('resize', update);
                this.unfollow = null;
            };
        },
        destroy() {
            this.unfollow?.();
        },
        {{-- beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya. --}}
        onBeforeToggle(event) {
            this.open = event.newState === 'open';
        },
        onToggle(event) {
            if (event.newState !== 'open') return this.unfollow?.();
            this.place();
            this.follow();
        },
    }"
    x-modelable="value"
    {{ $attributes->whereStartsWith(['wire:model', 'x-model']) }}
    class="{{ $wrapper }}"
>
    @if ($label)
        <label id="{{ $id }}-label" for="{{ $id }}" class="{{ $labelClass }}">{{ $label }}</label>
    @endif
    <div class="{{ $control }}">
        <input
            x-ref="input"
            {{ $attributes->whereDoesntStartWith(['wire:model', 'x-model'])->merge([
                'id' => $id,
                'type' => 'text',
                'role' => 'combobox',
                'autocomplete' => 'off',
                'aria-autocomplete' => 'list',
                'aria-expanded' => 'false',
                'aria-controls' => $listId,
                'aria-invalid' => $error ? 'true' : null,
                'aria-describedby' => $describedBy,
                'data-state' => 'closed',
                'value' => $text,
            ])->class([$field]) }}
            :value="text"
            :aria-expanded="open ? 'true' : 'false'"
            :aria-activedescendant="active >= 0 ? optionId(active) : null"
            :data-state="open ? 'open' : 'closed'"
            @input="onInput($event)"
            @keydown="onKeydown($event)"
            @blur="hide()"
            @click="show()"
        />
        <svg class="{{ $chevron }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
    </div>
    @if ($name)
        <input type="hidden" name="{{ $name }}" value="{{ $value }}" :value="value" />
    @endif
    <div
        x-ref="panel"
        id="{{ $id }}-popup"
        popover="manual"
        wire:ignore.self
        data-state="closed"
        :data-state="open ? 'open' : 'closed'"
        @beforetoggle="onBeforeToggle($event)"
        @toggle="onToggle($event)"
        @mousedown.prevent
        class="{{ $panel }}"
    >
        {{-- Alpine owns the options (and their state) after the first render, so Livewire skips the list when it re-renders. --}}
        <ul id="{{ $listId }}" role="listbox" wire:ignore @if ($label) aria-labelledby="{{ $id }}-label" @endif>
            @foreach ($options as $index => $option)
                <li
                    id="{{ $id }}-option-{{ $index }}"
                    role="option"
                    aria-selected="false"
                    data-state="{{ $value !== '' && $option['value'] === $value ? 'checked' : 'unchecked' }}"
                    x-show="visible.includes({{ $index }})"
                    :aria-selected="active === {{ $index }} ? 'true' : 'false'"
                    :data-state="isChecked({{ $index }}) ? 'checked' : 'unchecked'"
                    @click="select({{ $index }})"
                    class="{{ $optionClass }}"
                >{{ $option['label'] }}<svg x-show="isChecked({{ $index }})" @if (! ($value !== '' && $option['value'] === $value)) style="display: none" @endif class="{{ $check }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L20 7" /></svg></li>
            @endforeach
        </ul>
        <p x-show="visible.length === 0" wire:ignore @if (count($options) > 0) style="display: none" @endif class="{{ $emptyClass }}">{{ $emptyLabel }}</p>
    </div>
    @if ($error)
        <p id="{{ $id }}-error" class="{{ $errorClass }}">{{ $error }}</p>
    @elseif ($hint)
        <p id="{{ $id }}-hint" class="{{ $hintClass }}">{{ $hint }}</p>
    @endif
</div>
```

```blade
<x-markas.combobox
    name="country"
    label="Negara"
    placeholder="Cari negara"
    empty-label="Tidak ada hasil"
    :value="old('country', 'id')"
    :options="[
        ['value' => 'au', 'label' => 'Australia'],
        ['value' => 'id', 'label' => 'Indonesia'],
        ['value' => 'jp', 'label' => 'Jepang'],
    ]"
    :error="$errors->first('country')"
    x-on:markas-change="console.log($event.detail)"
/>
```

Butuh Alpine.js. Mengubah pilihan memancarkan event `markas-change` dengan value di `$event.detail` (string kosong saat dikosongkan).

### Livewire

```blade
<x-markas.combobox label="Country" wire:model.live="country" :options="$countries" />
```

`wire:model` terhubung ke value terpilih (bukan teks ketikan) lewat `x-modelable`. Mengubah properti di server menampilkan label yang cocok. `.live` mengirim request hanya saat opsi dipilih atau dikosongkan, bukan setiap ketikan.

### React

Simpan di `src/components/markas/Combobox.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

import {
  useEffect,
  useId,
  useRef,
  useState,
  type ChangeEvent,
  type ComponentProps,
  type FocusEvent,
  type KeyboardEvent,
  type MouseEvent,
  type ReactNode,
  type ToggleEvent,
} from "react";

const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control = "relative";
const field =
  "h-10 w-full rounded-md border border-line bg-surface ps-3 pe-9 text-sm text-ink transition-colors duration-150 ease-out placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
const chevron =
  "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
const panel =
  "inset-auto m-0 max-h-60 overflow-y-auto rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const optionClass =
  "flex cursor-pointer items-center justify-between gap-2 rounded-md px-3 py-2 text-sm text-ink hover:bg-subtle aria-selected:bg-subtle";
const check = "size-4 shrink-0 text-primary";
const emptyClass = "px-3 py-2 text-sm text-muted";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const GAP = 4;

/** Letakkan daftar di bawah input selebar input, pindah ke atas kalau tidak muat. */
function placeList(anchorEl: HTMLElement, panelEl: HTMLElement) {
  const anchor = anchorEl.getBoundingClientRect();
  panelEl.style.width = `${anchor.width}px`;
  const { height } = panelEl.getBoundingClientRect();
  const below = anchor.bottom + GAP;
  const above = anchor.top - GAP - height;
  const fitsBelow = below + height <= window.innerHeight;
  panelEl.style.top = `${fitsBelow || above < 0 ? below : above}px`;
  panelEl.style.left = `${anchor.left}px`;
}

/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
  const scrollOptions = { capture: true, passive: true };
  window.addEventListener("scroll", update, scrollOptions);
  window.addEventListener("resize", update, { passive: true });
  return () => {
    window.removeEventListener("scroll", update, scrollOptions);
    window.removeEventListener("resize", update);
  };
}

export type ComboboxOption = { value: string; label: string };

/** Indeks opsi (di daftar asli) yang labelnya memuat teks filter. */
const matchingIndexes = (options: ComboboxOption[], filter: string) => {
  const query = filter.trim().toLowerCase();
  return options.flatMap((option, index) =>
    option.label.toLowerCase().includes(query) ? [index] : [],
  );
};

const labelOf = (options: ComboboxOption[], value: string) =>
  options.find((option) => option.value === value)?.label ?? "";

export type ComboboxProps = Omit<
  ComponentProps<"input">,
  "value" | "defaultValue" | "type" | "role" | "name"
> & {
  options: ComboboxOption[];
  label?: ReactNode;
  hint?: ReactNode;
  error?: ReactNode;
  name?: string;
  value?: string;
  defaultValue?: string;
  emptyLabel?: string;
  onValueChange?: (value: string) => void;
};

export function Combobox({
  options,
  label,
  hint,
  error,
  name,
  value,
  defaultValue = "",
  emptyLabel = "No results",
  onValueChange,
  id,
  className,
  onChange,
  onKeyDown,
  onBlur,
  onClick,
  ...props
}: ComboboxProps) {
  const generatedId = useId();
  const inputId = id ?? generatedId;
  const listId = `${inputId}-listbox`;
  const inputRef = useRef<HTMLInputElement>(null);
  const panelRef = useRef<HTMLDivElement>(null);
  const [internalValue, setInternalValue] = useState(value ?? defaultValue);
  const selected = value ?? internalValue;
  const [text, setText] = useState(() => labelOf(options, selected));
  const [filter, setFilter] = useState("");
  const [active, setActive] = useState(-1);
  const [open, setOpen] = useState(false);
  const isOpen = useRef(false);
  const lastValue = useRef(selected);

  const visible = matchingIndexes(options, filter);
  const describedBy = error
    ? `${inputId}-error`
    : hint
      ? `${inputId}-hint`
      : undefined;
  const optionId = (index: number) => `${inputId}-option-${index}`;

  // Nilai terkontrol yang berubah dari luar menyamakan teks input.
  useEffect(() => {
    if (selected === lastValue.current) return;
    lastValue.current = selected;
    setText(labelOf(options, selected));
  }, [selected, options]);

  useEffect(() => {
    if (!open) return;
    return followViewport(() => {
      if (inputRef.current && panelRef.current)
        placeList(inputRef.current, panelRef.current);
    });
  }, [open]);

  useEffect(() => {
    if (active < 0) return;
    document.getElementById(optionId(active))?.scrollIntoView?.({
      block: "nearest",
    });
  });

  const commit = (next: string) => {
    if (next === selected) return;
    lastValue.current = next;
    setInternalValue(next);
    onValueChange?.(next);
  };

  const show = () => {
    if (!isOpen.current) panelRef.current?.showPopover();
  };
  const hide = () => {
    setActive(-1);
    if (isOpen.current) panelRef.current?.hidePopover();
  };

  const select = (index: number) => {
    const option = options[index];
    if (!option) return;
    commit(option.value);
    setText(option.label);
    setFilter("");
    hide();
  };

  const move = (step: 1 | -1) => {
    if (visible.length === 0) return;
    const position = visible.indexOf(active);
    const next =
      position === -1
        ? step === 1
          ? 0
          : visible.length - 1
        : (position + step + visible.length) % visible.length;
    setActive(visible[next] ?? -1);
  };

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    onChange?.(event);
    setText(event.currentTarget.value);
    setFilter(event.currentTarget.value);
    setActive(-1);
    commit("");
    show();
  };

  const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    onKeyDown?.(event);
    if (event.key === "ArrowDown" || event.key === "ArrowUp") {
      event.preventDefault();
      const step = event.key === "ArrowDown" ? 1 : -1;
      if (isOpen.current) return move(step);
      show();
      const edge = step === 1 ? visible[0] : visible[visible.length - 1];
      return setActive(edge ?? -1);
    }
    if (event.key === "Enter" && isOpen.current && active >= 0) {
      event.preventDefault();
      return select(active);
    }
    if (event.key !== "Escape") return;
    event.preventDefault();
    if (isOpen.current) return hide();
    setText("");
    setFilter("");
    commit("");
  };

  const handleBlur = (event: FocusEvent<HTMLInputElement>) => {
    onBlur?.(event);
    hide();
  };

  const handleClick = (event: MouseEvent<HTMLInputElement>) => {
    onClick?.(event);
    show();
  };

  // beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya.
  const handleBeforeToggle = (event: ToggleEvent<HTMLDivElement>) => {
    isOpen.current = event.newState === "open";
    setOpen(isOpen.current);
  };
  const handleToggle = (event: ToggleEvent<HTMLDivElement>) => {
    if (event.newState === "open" && inputRef.current && panelRef.current)
      placeList(inputRef.current, panelRef.current);
  };

  return (
    <div className={wrapper}>
      {label && (
        <label id={`${inputId}-label`} htmlFor={inputId} className={labelClass}>
          {label}
        </label>
      )}
      <div className={control}>
        <input
          ref={inputRef}
          id={inputId}
          type="text"
          role="combobox"
          autoComplete="off"
          aria-autocomplete="list"
          aria-expanded={open}
          aria-controls={listId}
          aria-activedescendant={active >= 0 ? optionId(active) : undefined}
          aria-invalid={error ? true : undefined}
          aria-describedby={describedBy}
          data-state={open ? "open" : "closed"}
          className={cx(field, className)}
          {...props}
          value={text}
          onChange={handleChange}
          onKeyDown={handleKeyDown}
          onBlur={handleBlur}
          onClick={handleClick}
        />
        <svg
          className={chevron}
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </div>
      {name && <input type="hidden" name={name} value={selected} />}
      <div
        ref={panelRef}
        id={`${inputId}-popup`}
        popover="manual"
        data-state={open ? "open" : "closed"}
        className={panel}
        onBeforeToggle={handleBeforeToggle}
        onToggle={handleToggle}
        onMouseDown={(event) => event.preventDefault()}
      >
        <ul
          id={listId}
          role="listbox"
          aria-labelledby={label ? `${inputId}-label` : undefined}
        >
          {visible.map((index) => {
            const option = options[index]!;
            const isSelected = option.value === selected && selected !== "";
            return (
              <li
                key={index}
                id={optionId(index)}
                role="option"
                aria-selected={index === active}
                data-state={isSelected ? "checked" : "unchecked"}
                className={optionClass}
                onClick={() => select(index)}
              >
                {option.label}
                {isSelected && (
                  <svg
                    className={check}
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    aria-hidden="true"
                  >
                    <path d="m5 12 5 5L20 7" />
                  </svg>
                )}
              </li>
            );
          })}
        </ul>
        {visible.length === 0 && <p className={emptyClass}>{emptyLabel}</p>}
      </div>
      {error ? (
        <p id={`${inputId}-error`} className={errorClass}>
          {error}
        </p>
      ) : hint ? (
        <p id={`${inputId}-hint`} className={hintClass}>
          {hint}
        </p>
      ) : null}
    </div>
  );
}
```

```tsx
import { useState } from "react";
import { Combobox } from "@/components/markas/Combobox";

const [country, setCountry] = useState("id");

<Combobox
  name="country"
  label="Negara"
  placeholder="Cari negara"
  emptyLabel="Tidak ada hasil"
  options={[
    { value: "au", label: "Australia" },
    { value: "id", label: "Indonesia" },
    { value: "jp", label: "Jepang" },
  ]}
  value={country}
  onValueChange={setCountry}
/>;
```

### Vue

Simpan di `src/components/markas/Combobox.vue`. Tanpa dependensi tambahan.

```vue
<script setup lang="ts">
import {
  computed,
  nextTick,
  onBeforeUnmount,
  ref,
  useId,
  useTemplateRef,
  watch,
} from "vue";

export type ComboboxOption = { value: string; label: string };

defineOptions({ inheritAttrs: false });

const props = withDefaults(
  defineProps<{
    options: ComboboxOption[];
    label?: string;
    hint?: string;
    error?: string;
    name?: string;
    emptyLabel?: string;
    id?: string;
  }>(),
  {
    label: undefined,
    hint: undefined,
    error: undefined,
    name: undefined,
    emptyLabel: "No results",
    id: undefined,
  },
);
const model = defineModel<string>({ default: "" });

const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control = "relative";
const field =
  "h-10 w-full rounded-md border border-line bg-surface ps-3 pe-9 text-sm text-ink transition-colors duration-150 ease-out placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
const chevron =
  "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
const panel =
  "inset-auto m-0 max-h-60 overflow-y-auto rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const optionClass =
  "flex cursor-pointer items-center justify-between gap-2 rounded-md px-3 py-2 text-sm text-ink hover:bg-subtle aria-selected:bg-subtle";
const check = "size-4 shrink-0 text-primary";
const emptyClass = "px-3 py-2 text-sm text-muted";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";

const GAP = 4;

/** Letakkan daftar di bawah input selebar input, pindah ke atas kalau tidak muat. */
function placeList(anchorEl: HTMLElement, panelEl: HTMLElement) {
  const anchor = anchorEl.getBoundingClientRect();
  panelEl.style.width = `${anchor.width}px`;
  const { height } = panelEl.getBoundingClientRect();
  const below = anchor.bottom + GAP;
  const above = anchor.top - GAP - height;
  const fitsBelow = below + height <= window.innerHeight;
  panelEl.style.top = `${fitsBelow || above < 0 ? below : above}px`;
  panelEl.style.left = `${anchor.left}px`;
}

/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
  const scrollOptions = { capture: true, passive: true };
  window.addEventListener("scroll", update, scrollOptions);
  window.addEventListener("resize", update, { passive: true });
  return () => {
    window.removeEventListener("scroll", update, scrollOptions);
    window.removeEventListener("resize", update);
  };
}

/** Indeks opsi (di daftar asli) yang labelnya memuat teks filter. */
const matchingIndexes = (options: ComboboxOption[], filter: string) => {
  const query = filter.trim().toLowerCase();
  return options.flatMap((option, index) =>
    option.label.toLowerCase().includes(query) ? [index] : [],
  );
};

const labelOf = (options: ComboboxOption[], value: string) =>
  options.find((option) => option.value === value)?.label ?? "";

const generatedId = useId();
const inputId = computed(() => props.id ?? generatedId);
const listId = computed(() => `${inputId.value}-listbox`);
const inputEl = useTemplateRef<HTMLInputElement>("input");
const panelEl = useTemplateRef<HTMLDivElement>("popup");
const text = ref(labelOf(props.options, model.value));
const filter = ref("");
const active = ref(-1);
const open = ref(false);
let lastValue = model.value;
let unfollow: (() => void) | undefined;

const visible = computed(() => matchingIndexes(props.options, filter.value));
const describedBy = computed(() =>
  props.error
    ? `${inputId.value}-error`
    : props.hint
      ? `${inputId.value}-hint`
      : undefined,
);
const optionId = (index: number) => `${inputId.value}-option-${index}`;

// Nilai v-model yang berubah dari luar menyamakan teks input.
watch(model, (value) => {
  if (value === lastValue) return;
  lastValue = value;
  text.value = labelOf(props.options, value);
});

watch(active, async (index) => {
  if (index < 0) return;
  await nextTick();
  document.getElementById(optionId(index))?.scrollIntoView?.({
    block: "nearest",
  });
});

function commit(next: string) {
  if (next === model.value) return;
  lastValue = next;
  model.value = next;
}

function show() {
  if (!open.value) panelEl.value?.showPopover();
}

function hide() {
  active.value = -1;
  if (open.value) panelEl.value?.hidePopover();
}

function select(index: number) {
  const option = props.options[index];
  if (!option) return;
  commit(option.value);
  text.value = option.label;
  filter.value = "";
  hide();
}

function move(step: 1 | -1) {
  const list = visible.value;
  if (list.length === 0) return;
  const position = list.indexOf(active.value);
  const next =
    position === -1
      ? step === 1
        ? 0
        : list.length - 1
      : (position + step + list.length) % list.length;
  active.value = list[next] ?? -1;
}

function onInput(event: Event) {
  const value = (event.target as HTMLInputElement).value;
  text.value = value;
  filter.value = value;
  active.value = -1;
  commit("");
  show();
}

function onKeydown(event: KeyboardEvent) {
  if (event.key === "ArrowDown" || event.key === "ArrowUp") {
    event.preventDefault();
    const step = event.key === "ArrowDown" ? 1 : -1;
    if (open.value) return move(step);
    show();
    const list = visible.value;
    active.value = (step === 1 ? list[0] : list[list.length - 1]) ?? -1;
    return;
  }
  if (event.key === "Enter" && open.value && active.value >= 0) {
    event.preventDefault();
    return select(active.value);
  }
  if (event.key !== "Escape") return;
  event.preventDefault();
  if (open.value) return hide();
  text.value = "";
  filter.value = "";
  commit("");
}

function place() {
  if (inputEl.value && panelEl.value) placeList(inputEl.value, panelEl.value);
}

function stopFollowing() {
  unfollow?.();
  unfollow = undefined;
}

// beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya.
function onBeforeToggle(event: Event) {
  open.value = (event as ToggleEvent).newState === "open";
}

function onToggle(event: Event) {
  stopFollowing();
  if ((event as ToggleEvent).newState !== "open") return;
  place();
  unfollow = followViewport(place);
}

onBeforeUnmount(stopFollowing);
</script>

<template>
  <div :class="wrapper">
    <label
      v-if="props.label"
      :id="`${inputId}-label`"
      :for="inputId"
      :class="labelClass"
      >{{ props.label }}</label
    >
    <div :class="control">
      <input
        :id="inputId"
        ref="input"
        type="text"
        role="combobox"
        autocomplete="off"
        aria-autocomplete="list"
        :aria-expanded="open ? 'true' : 'false'"
        :aria-controls="listId"
        :aria-activedescendant="active >= 0 ? optionId(active) : undefined"
        :aria-invalid="props.error ? 'true' : undefined"
        :aria-describedby="describedBy"
        :data-state="open ? 'open' : 'closed'"
        :class="field"
        v-bind="$attrs"
        :value="text"
        @input="onInput"
        @keydown="onKeydown"
        @blur="hide"
        @click="show"
      />
      <svg
        :class="chevron"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path d="m6 9 6 6 6-6" />
      </svg>
    </div>
    <input v-if="props.name" type="hidden" :name="props.name" :value="model" />
    <div
      :id="`${inputId}-popup`"
      ref="popup"
      popover="manual"
      :data-state="open ? 'open' : 'closed'"
      :class="panel"
      @beforetoggle="onBeforeToggle"
      @toggle="onToggle"
      @mousedown.prevent
    >
      <ul
        :id="listId"
        role="listbox"
        :aria-labelledby="props.label ? `${inputId}-label` : undefined"
      >
        <li
          v-for="index in visible"
          :id="optionId(index)"
          :key="index"
          role="option"
          :aria-selected="index === active ? 'true' : 'false'"
          :data-state="
            props.options[index]?.value === model && model !== ''
              ? 'checked'
              : 'unchecked'
          "
          :class="optionClass"
          @click="select(index)"
        >
          {{ props.options[index]?.label }}
          <svg
            v-if="props.options[index]?.value === model && model !== ''"
            :class="check"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m5 12 5 5L20 7" />
          </svg>
        </li>
      </ul>
      <p v-if="visible.length === 0" :class="emptyClass">
        {{ props.emptyLabel }}
      </p>
    </div>
    <p v-if="props.error" :id="`${inputId}-error`" :class="errorClass">
      {{ props.error }}
    </p>
    <p v-else-if="props.hint" :id="`${inputId}-hint`" :class="hintClass">
      {{ props.hint }}
    </p>
  </div>
</template>
```

```vue
<script setup lang="ts">
import { ref } from "vue";
import Combobox from "@/components/markas/Combobox.vue";

const country = ref("id");
const countries = [
  { value: "au", label: "Australia" },
  { value: "id", label: "Indonesia" },
  { value: "jp", label: "Jepang" },
];
</script>

<template>
  <Combobox
    v-model="country"
    name="country"
    label="Negara"
    placeholder="Cari negara"
    empty-label="Tidak ada hasil"
    :options="countries"
  />
</template>
```

### Svelte

Simpan di `src/lib/components/markas/Combobox.svelte`. Tanpa dependensi tambahan.

```svelte
<script lang="ts" module>
  export type ComboboxOption = { value: string; label: string };
</script>

<script lang="ts">
  import { tick, untrack } from "svelte";
  import type { HTMLInputAttributes } from "svelte/elements";

  const wrapper = "grid gap-1.5";
  const labelClass = "text-sm font-medium text-ink";
  const control = "relative";
  const field =
    "h-10 w-full rounded-md border border-line bg-surface ps-3 pe-9 text-sm text-ink transition-colors duration-150 ease-out placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
  const chevron =
    "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
  const panel =
    "inset-auto m-0 max-h-60 overflow-y-auto rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
  const optionClass =
    "flex cursor-pointer items-center justify-between gap-2 rounded-md px-3 py-2 text-sm text-ink hover:bg-subtle aria-selected:bg-subtle";
  const check = "size-4 shrink-0 text-primary";
  const emptyClass = "px-3 py-2 text-sm text-muted";
  const hintClass = "text-sm text-muted";
  const errorClass = "text-sm text-danger";

  const GAP = 4;

  type Props = Omit<HTMLInputAttributes, "value" | "type" | "role" | "name"> & {
    options: ComboboxOption[];
    label?: string;
    hint?: string;
    error?: string;
    name?: string;
    value?: string;
    emptyLabel?: string;
    /** Called when the selected value changes, with "" when cleared. */
    onvaluechange?: (value: string) => void;
  };

  let {
    options,
    label,
    hint,
    error,
    name,
    value = $bindable(""),
    emptyLabel = "No results",
    onvaluechange,
    id,
    class: className,
    oninput,
    onkeydown,
    onblur,
    onclick,
    ...rest
  }: Props = $props();

  const labelOf = (list: ComboboxOption[], selected: string) =>
    list.find((option) => option.value === selected)?.label ?? "";

  const generatedId = $props.id();
  const inputId = $derived(id ?? generatedId);
  const listId = $derived(`${inputId}-listbox`);
  const describedBy = $derived(
    error ? `${inputId}-error` : hint ? `${inputId}-hint` : undefined,
  );
  const optionId = (index: number) => `${inputId}-option-${index}`;

  let inputEl = $state<HTMLInputElement>();
  let panelEl = $state<HTMLDivElement>();
  let text = $state(untrack(() => labelOf(options, value)));
  let filter = $state("");
  let active = $state(-1);
  let open = $state(false);
  let lastValue = untrack(() => value);

  /** Indexes (in the original list) of options whose label contains the filter text. */
  const visible = $derived.by(() => {
    const query = filter.trim().toLowerCase();
    return options.flatMap((option, index) =>
      option.label.toLowerCase().includes(query) ? [index] : [],
    );
  });

  // A value changed from outside syncs the input text.
  $effect(() => {
    if (value === lastValue) return;
    lastValue = value;
    text = labelOf(options, value);
  });

  /** Place the list below the input at its width, flip above when it does not fit. */
  function place() {
    if (!inputEl || !panelEl) return;
    const anchor = inputEl.getBoundingClientRect();
    panelEl.style.width = `${anchor.width}px`;
    const { height } = panelEl.getBoundingClientRect();
    const below = anchor.bottom + GAP;
    const above = anchor.top - GAP - height;
    const fitsBelow = below + height <= window.innerHeight;
    panelEl.style.top = `${fitsBelow || above < 0 ? below : above}px`;
    panelEl.style.left = `${anchor.left}px`;
  }

  // Re-place the list while the page scrolls or the window resizes.
  $effect(() => {
    if (!open) return;
    const scrollOptions = { capture: true, passive: true };
    window.addEventListener("scroll", place, scrollOptions);
    window.addEventListener("resize", place, { passive: true });
    return () => {
      window.removeEventListener("scroll", place, scrollOptions);
      window.removeEventListener("resize", place);
    };
  });

  async function setActive(index: number) {
    active = index;
    if (index < 0) return;
    await tick();
    document
      .getElementById(optionId(index))
      ?.scrollIntoView?.({ block: "nearest" });
  }

  function commit(next: string) {
    if (next === value) return;
    lastValue = next;
    value = next;
    onvaluechange?.(next);
  }

  function show() {
    if (!open) panelEl?.showPopover();
  }

  function hide() {
    active = -1;
    if (open) panelEl?.hidePopover();
  }

  function select(index: number) {
    const option = options[index];
    if (!option) return;
    commit(option.value);
    text = option.label;
    filter = "";
    hide();
  }

  function move(step: 1 | -1) {
    if (visible.length === 0) return;
    const position = visible.indexOf(active);
    const next =
      position === -1
        ? step === 1
          ? 0
          : visible.length - 1
        : (position + step + visible.length) % visible.length;
    setActive(visible[next] ?? -1);
  }

  function handleInput(
    event: Event & { currentTarget: EventTarget & HTMLInputElement },
  ) {
    oninput?.(event);
    text = event.currentTarget.value;
    filter = event.currentTarget.value;
    active = -1;
    commit("");
    show();
  }

  function handleKeydown(
    event: KeyboardEvent & { currentTarget: EventTarget & HTMLInputElement },
  ) {
    onkeydown?.(event);
    if (event.key === "ArrowDown" || event.key === "ArrowUp") {
      event.preventDefault();
      const step = event.key === "ArrowDown" ? 1 : -1;
      if (open) return move(step);
      show();
      const edge = step === 1 ? visible[0] : visible[visible.length - 1];
      return setActive(edge ?? -1);
    }
    if (event.key === "Enter" && open && active >= 0) {
      event.preventDefault();
      return select(active);
    }
    if (event.key !== "Escape") return;
    event.preventDefault();
    if (open) return hide();
    text = "";
    filter = "";
    commit("");
  }

  function handleBlur(
    event: FocusEvent & { currentTarget: EventTarget & HTMLInputElement },
  ) {
    onblur?.(event);
    hide();
  }

  function handleClick(
    event: MouseEvent & { currentTarget: EventTarget & HTMLInputElement },
  ) {
    onclick?.(event);
    show();
  }

  // beforetoggle runs synchronously, so the state is current for the next key press.
  function handleBeforeToggle(event: ToggleEvent) {
    open = event.newState === "open";
  }

  function handleToggle(event: ToggleEvent) {
    if (event.newState === "open") place();
  }
</script>

<div class={wrapper}>
  {#if label}
    <label id={`${inputId}-label`} for={inputId} class={labelClass}
      >{label}</label
    >
  {/if}
  <div class={control}>
    <input
      bind:this={inputEl}
      id={inputId}
      type="text"
      role="combobox"
      autocomplete="off"
      aria-autocomplete="list"
      aria-expanded={open}
      aria-controls={listId}
      aria-activedescendant={active >= 0 ? optionId(active) : undefined}
      aria-invalid={error ? "true" : undefined}
      aria-describedby={describedBy}
      data-state={open ? "open" : "closed"}
      class={[field, className]}
      {...rest}
      value={text}
      oninput={handleInput}
      onkeydown={handleKeydown}
      onblur={handleBlur}
      onclick={handleClick}
    />
    <svg
      class={chevron}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="1.5"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  </div>
  {#if name}
    <input type="hidden" {name} {value} />
  {/if}
  <!-- svelte-ignore a11y_no_static_element_interactions -->
  <div
    bind:this={panelEl}
    id={`${inputId}-popup`}
    popover="manual"
    data-state={open ? "open" : "closed"}
    class={panel}
    onbeforetoggle={handleBeforeToggle}
    ontoggle={handleToggle}
    onmousedown={(event) => event.preventDefault()}
  >
    <ul
      id={listId}
      role="listbox"
      aria-labelledby={label ? `${inputId}-label` : undefined}
    >
      {#each visible as index (index)}
        {@const option = options[index]!}
        {@const isSelected = option.value === value && value !== ""}
        <!-- svelte-ignore a11y_click_events_have_key_events -->
        <li
          id={optionId(index)}
          role="option"
          aria-selected={index === active}
          data-state={isSelected ? "checked" : "unchecked"}
          class={optionClass}
          onclick={() => select(index)}
        >
          {option.label}
          {#if isSelected}
            <svg
              class={check}
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m5 12 5 5L20 7" />
            </svg>
          {/if}
        </li>
      {/each}
    </ul>
    {#if visible.length === 0}
      <p class={emptyClass}>{emptyLabel}</p>
    {/if}
  </div>
  {#if error}
    <p id={`${inputId}-error`} class={errorClass}>{error}</p>
  {:else if hint}
    <p id={`${inputId}-hint`} class={hintClass}>{hint}</p>
  {/if}
</div>
```

```svelte
<script lang="ts">
  import Combobox from "$lib/components/markas/Combobox.svelte";

  let country = $state("id");
  const countries = [
    { value: "au", label: "Australia" },
    { value: "id", label: "Indonesia" },
    { value: "jp", label: "Jepang" },
  ];
</script>

<Combobox
  bind:value={country}
  name="country"
  label="Negara"
  placeholder="Cari negara"
  emptyLabel="Tidak ada hasil"
  options={countries}
/>
```

### Astro

Simpan di `src/components/markas/Combobox.astro`. Tanpa dependensi tambahan.

```astro
---
import type { HTMLAttributes } from "astro/types";

const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control = "relative";
const field =
  "h-10 w-full rounded-md border border-line bg-surface ps-3 pe-9 text-sm text-ink transition-colors duration-150 ease-out placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
const chevron =
  "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
const panel =
  "inset-auto m-0 max-h-60 overflow-y-auto rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const optionClass =
  "flex cursor-pointer items-center justify-between gap-2 rounded-md px-3 py-2 text-sm text-ink hover:bg-subtle aria-selected:bg-subtle";
const check = "size-4 shrink-0 text-primary";
const emptyClass = "px-3 py-2 text-sm text-muted";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";

export type ComboboxOption = { value: string; label: string };

type Props = Omit<
  HTMLAttributes<"input">,
  "value" | "type" | "role" | "name"
> & {
  options: ComboboxOption[];
  label?: string;
  hint?: string;
  error?: string;
  name?: string;
  value?: string;
  emptyLabel?: string;
};

const {
  options,
  label,
  hint,
  error,
  name,
  value = "",
  emptyLabel = "No results",
  id,
  class: className,
  ...rest
} = Astro.props;
const inputId = id ?? `markas-combobox-${crypto.randomUUID().slice(0, 8)}`;
const listId = `${inputId}-listbox`;
const text = options.find((option) => option.value === value)?.label ?? "";
const describedBy = error
  ? `${inputId}-error`
  : hint
    ? `${inputId}-hint`
    : undefined;
const isChecked = (option: ComboboxOption) =>
  value !== "" && option.value === value;
---

<markas-combobox class="contents">
  <div class={wrapper}>
    {
      label && (
        <label id={`${inputId}-label`} for={inputId} class={labelClass}>
          {label}
        </label>
      )
    }
    <div class={control}>
      <input
        id={inputId}
        type="text"
        role="combobox"
        autocomplete="off"
        aria-autocomplete="list"
        aria-expanded="false"
        aria-controls={listId}
        aria-invalid={error ? "true" : undefined}
        aria-describedby={describedBy}
        data-state="closed"
        class:list={[field, className]}
        {...rest}
        value={text}
        data-markas-combobox-input
      />
      <svg
        class={chevron}
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path d="m6 9 6 6 6-6"></path>
      </svg>
    </div>
    {
      name && (
        <input
          type="hidden"
          name={name}
          value={value}
          data-markas-combobox-value
        />
      )
    }
    <div
      id={`${inputId}-popup`}
      popover="manual"
      data-state="closed"
      class={panel}
      data-markas-combobox-panel
    >
      <ul
        id={listId}
        role="listbox"
        aria-labelledby={label ? `${inputId}-label` : undefined}
      >
        {
          options.map((option, index) => (
            <li
              id={`${inputId}-option-${index}`}
              role="option"
              aria-selected="false"
              data-state={isChecked(option) ? "checked" : "unchecked"}
              data-value={option.value}
              data-label={option.label}
              class={optionClass}
            >
              {option.label}
              <svg
                class={check}
                style={isChecked(option) ? undefined : "display: none"}
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="1.5"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="m5 12 5 5L20 7" />
              </svg>
            </li>
          ))
        }
      </ul>
      <p class={emptyClass} hidden={options.length > 0} data-markas-combobox-empty>
        {emptyLabel}
      </p>
    </div>
    {
      error ? (
        <p id={`${inputId}-error`} class={errorClass}>
          {error}
        </p>
      ) : hint ? (
        <p id={`${inputId}-hint`} class={hintClass}>
          {hint}
        </p>
      ) : null
    }
  </div>
</markas-combobox>

<script>
  const GAP = 4;

  /**
   * One instance per combobox. Options are rendered on the server; the script only filters,
   * highlights, and positions them. Changing the selection dispatches a bubbling
   * `markas-change` event with the value in `detail` ("" when cleared).
   */
  class MarkasCombobox extends HTMLElement {
    private input!: HTMLInputElement;
    private panel!: HTMLElement;
    private valueInput: HTMLInputElement | null = null;
    private items: HTMLLIElement[] = [];
    private empty: HTMLElement | null = null;
    private value = "";
    private active = -1;
    private open = false;
    private unfollow: (() => void) | null = null;

    connectedCallback() {
      if (this.input) return;
      this.input = this.querySelector("[data-markas-combobox-input]")!;
      this.panel = this.querySelector("[data-markas-combobox-panel]")!;
      this.valueInput = this.querySelector("[data-markas-combobox-value]");
      this.empty = this.querySelector("[data-markas-combobox-empty]");
      this.items = [...this.panel.querySelectorAll("li")];
      this.value =
        this.items.find((item) => item.dataset.state === "checked")?.dataset
          .value ?? "";

      this.input.addEventListener("input", () => this.onInput());
      this.input.addEventListener("keydown", (event) => this.onKeydown(event));
      this.input.addEventListener("blur", () => this.hide());
      this.input.addEventListener("click", () => this.show());
      this.panel.addEventListener("mousedown", (event) =>
        event.preventDefault(),
      );
      this.panel.addEventListener("click", (event) => {
        const item = (event.target as Element).closest("li");
        if (item) this.select(this.items.indexOf(item));
      });
      // beforetoggle runs synchronously, so the state is current for the next key press.
      this.panel.addEventListener("beforetoggle", (event) =>
        this.setOpen((event as ToggleEvent).newState === "open"),
      );
      this.panel.addEventListener("toggle", (event) => {
        if ((event as ToggleEvent).newState !== "open") return this.unfollow?.();
        this.place();
        this.follow();
      });
    }

    disconnectedCallback() {
      this.unfollow?.();
    }

    /** Indexes of options whose label contains the filter text. */
    private visible() {
      return this.items.flatMap((item, index) => (item.hidden ? [] : [index]));
    }

    private filter(text: string) {
      const query = text.trim().toLowerCase();
      for (const item of this.items)
        item.hidden = !(item.dataset.label ?? "").toLowerCase().includes(query);
      if (this.empty) this.empty.hidden = this.visible().length > 0;
    }

    private setOpen(open: boolean) {
      this.open = open;
      const state = open ? "open" : "closed";
      this.input.setAttribute("aria-expanded", String(open));
      this.input.dataset.state = state;
      this.panel.dataset.state = state;
    }

    private setActive(index: number) {
      this.active = index;
      this.items.forEach((item, i) =>
        item.setAttribute("aria-selected", String(i === index)),
      );
      const item = this.items[index];
      if (!item) return this.input.removeAttribute("aria-activedescendant");
      this.input.setAttribute("aria-activedescendant", item.id);
      item.scrollIntoView({ block: "nearest" });
    }

    private commit(next: string) {
      if (next === this.value) return;
      this.value = next;
      if (this.valueInput) this.valueInput.value = next;
      this.items.forEach((item) => {
        const checked = next !== "" && item.dataset.value === next;
        item.dataset.state = checked ? "checked" : "unchecked";
        item.querySelector("svg")!.style.display = checked ? "" : "none";
      });
      this.dispatchEvent(
        new CustomEvent("markas-change", { detail: next, bubbles: true }),
      );
    }

    private show() {
      if (!this.open) this.panel.showPopover();
    }

    private hide() {
      this.setActive(-1);
      if (this.open) this.panel.hidePopover();
    }

    private select(index: number) {
      const item = this.items[index];
      if (!item) return;
      this.commit(item.dataset.value ?? "");
      this.input.value = item.dataset.label ?? "";
      this.filter("");
      this.hide();
    }

    private move(step: 1 | -1) {
      const list = this.visible();
      if (list.length === 0) return;
      const position = list.indexOf(this.active);
      const next =
        position === -1
          ? step === 1
            ? 0
            : list.length - 1
          : (position + step + list.length) % list.length;
      this.setActive(list[next] ?? -1);
    }

    private onInput() {
      this.filter(this.input.value);
      this.setActive(-1);
      this.commit("");
      this.show();
    }

    private onKeydown(event: KeyboardEvent) {
      if (event.key === "ArrowDown" || event.key === "ArrowUp") {
        event.preventDefault();
        const step = event.key === "ArrowDown" ? 1 : -1;
        if (this.open) return this.move(step);
        this.show();
        const list = this.visible();
        return this.setActive(
          (step === 1 ? list[0] : list[list.length - 1]) ?? -1,
        );
      }
      if (event.key === "Enter" && this.open && this.active >= 0) {
        event.preventDefault();
        return this.select(this.active);
      }
      if (event.key !== "Escape") return;
      event.preventDefault();
      if (this.open) return this.hide();
      this.input.value = "";
      this.filter("");
      this.commit("");
    }

    /** Place the list below the input at its width, flip above when it does not fit. */
    private place() {
      const anchor = this.input.getBoundingClientRect();
      this.panel.style.width = `${anchor.width}px`;
      const { height } = this.panel.getBoundingClientRect();
      const below = anchor.bottom + GAP;
      const above = anchor.top - GAP - height;
      const fitsBelow = below + height <= window.innerHeight;
      this.panel.style.top = `${fitsBelow || above < 0 ? below : above}px`;
      this.panel.style.left = `${anchor.left}px`;
    }

    /** Re-place the list while the page scrolls or the window resizes. */
    private follow() {
      this.unfollow?.();
      const update = () => this.place();
      const scrollOptions = { capture: true, passive: true };
      window.addEventListener("scroll", update, scrollOptions);
      window.addEventListener("resize", update, { passive: true });
      this.unfollow = () => {
        window.removeEventListener("scroll", update, scrollOptions);
        window.removeEventListener("resize", update);
        this.unfollow = null;
      };
    }
  }

  if (!customElements.get("markas-combobox"))
    customElements.define("markas-combobox", MarkasCombobox);
</script>
```

```astro
---
import Combobox from "@/components/markas/Combobox.astro";

const countries = [
  { value: "au", label: "Australia" },
  { value: "id", label: "Indonesia" },
  { value: "jp", label: "Jepang" },
];
---

<Combobox
  name="country"
  label="Negara"
  placeholder="Cari negara"
  emptyLabel="Tidak ada hasil"
  value="id"
  options={countries}
/>
```

Opsi dirender di server. Script kecil yang dibundel (satu custom element per combobox) memfilter, menyorot, dan menempatkan daftar. Mengganti pilihan memancarkan event `markas-change` yang menggelembung dengan value di `event.detail`.

### Angular

Simpan di `src/app/markas/combobox.component.ts`. Tanpa dependensi tambahan.

```ts
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  DestroyRef,
  effect,
  type ElementRef,
  inject,
  input,
  model,
  signal,
  viewChild,
} from "@angular/core";

const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control = "relative";
const field =
  "h-10 w-full rounded-md border border-line bg-surface ps-3 pe-9 text-sm text-ink transition-colors duration-150 ease-out placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
const chevron =
  "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
const panel =
  "inset-auto m-0 max-h-60 overflow-y-auto rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const optionClass =
  "flex cursor-pointer items-center justify-between gap-2 rounded-md px-3 py-2 text-sm text-ink hover:bg-subtle aria-selected:bg-subtle";
const check = "size-4 shrink-0 text-primary";
const emptyClass = "px-3 py-2 text-sm text-muted";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";

const GAP = 4;

export type ComboboxOption = { value: string; label: string };

const labelOf = (options: ComboboxOption[], value: string) =>
  options.find((option) => option.value === value)?.label ?? "";

let nextId = 0;

/**
 * Host stays out of layout (display: contents). id, aria-label, placeholder, and class move to
 * the text input; name goes to the hidden input that holds the selected value.
 */
@Component({
  selector: "markas-combobox",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: "contents",
    "[attr.id]": "null",
    "[attr.name]": "null",
    "[attr.aria-label]": "null",
    "[attr.placeholder]": "null",
  },
  template: `
    <div [class]="wrapper">
      @if (label()) {
        <label
          [id]="inputId() + '-label'"
          [for]="inputId()"
          [class]="labelClass"
          >{{ label() }}</label
        >
      }
      <div [class]="control">
        <input
          #field
          [id]="inputId()"
          type="text"
          role="combobox"
          autocomplete="off"
          aria-autocomplete="list"
          [attr.aria-expanded]="open()"
          [attr.aria-controls]="inputId() + '-listbox'"
          [attr.aria-activedescendant]="
            active() >= 0 ? optionId(active()) : null
          "
          [attr.aria-invalid]="error() ? 'true' : null"
          [attr.aria-describedby]="describedBy()"
          [attr.aria-label]="ariaLabel() ?? null"
          [attr.placeholder]="placeholder() ?? null"
          [attr.data-state]="open() ? 'open' : 'closed'"
          [disabled]="disabled()"
          [required]="required()"
          [class]="fieldClass()"
          [value]="text()"
          (input)="handleInput(field.value)"
          (keydown)="handleKeydown($event)"
          (blur)="hide()"
          (click)="show()"
        />
        <svg
          [attr.class]="chevron"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </div>
      @if (name()) {
        <input type="hidden" [attr.name]="name()" [value]="value()" />
      }
      <div
        #popup
        [id]="inputId() + '-popup'"
        popover="manual"
        [attr.data-state]="open() ? 'open' : 'closed'"
        [class]="panel"
        (beforetoggle)="handleBeforeToggle($event)"
        (toggle)="handleToggle($event)"
        (mousedown)="$event.preventDefault()"
      >
        <ul
          [id]="inputId() + '-listbox'"
          role="listbox"
          [attr.aria-labelledby]="label() ? inputId() + '-label' : null"
        >
          @for (index of visible(); track index) {
            @let option = options()[index]!;
            @let checked = option.value === value() && value() !== "";
            <li
              [id]="optionId(index)"
              role="option"
              [attr.aria-selected]="index === active()"
              [attr.data-state]="checked ? 'checked' : 'unchecked'"
              [class]="optionClass"
              (click)="select(index)"
            >
              {{ option.label }}
              @if (checked) {
                <svg
                  [attr.class]="check"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="1.5"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m5 12 5 5L20 7" />
                </svg>
              }
            </li>
          }
        </ul>
        @if (visible().length === 0) {
          <p [class]="emptyClass">{{ emptyLabel() }}</p>
        }
      </div>
      @if (error()) {
        <p [id]="inputId() + '-error'" [class]="errorClass">{{ error() }}</p>
      } @else if (hint()) {
        <p [id]="inputId() + '-hint'" [class]="hintClass">{{ hint() }}</p>
      }
    </div>
  `,
})
export class Combobox {
  readonly options = input.required<ComboboxOption[]>();
  readonly label = input<string>();
  readonly hint = input<string>();
  readonly error = input<string>();
  readonly name = input<string>();
  readonly emptyLabel = input("No results");
  readonly id = input<string>();
  readonly placeholder = input<string>();
  readonly disabled = input(false, { transform: booleanAttribute });
  readonly required = input(false, { transform: booleanAttribute });
  readonly ariaLabel = input<string | undefined>(undefined, {
    alias: "aria-label",
  });
  readonly userClass = input("", { alias: "class" });
  /** Selected option value, "" when cleared. Two-way bindable with [(value)]. */
  readonly value = model("");

  protected readonly wrapper = wrapper;
  protected readonly labelClass = labelClass;
  protected readonly control = control;
  protected readonly chevron = chevron;
  protected readonly panel = panel;
  protected readonly optionClass = optionClass;
  protected readonly check = check;
  protected readonly emptyClass = emptyClass;
  protected readonly hintClass = hintClass;
  protected readonly errorClass = errorClass;

  protected readonly text = signal("");
  protected readonly active = signal(-1);
  protected readonly open = signal(false);
  private readonly filter = signal("");
  private lastValue: string | undefined;
  private unfollow: (() => void) | null = null;
  private readonly field =
    viewChild.required<ElementRef<HTMLInputElement>>("field");
  private readonly panelRef =
    viewChild.required<ElementRef<HTMLElement>>("popup");

  private readonly generatedId = `markas-combobox-${nextId++}`;
  protected readonly inputId = computed(() => this.id() ?? this.generatedId);
  protected readonly describedBy = computed(() =>
    this.error()
      ? `${this.inputId()}-error`
      : this.hint()
        ? `${this.inputId()}-hint`
        : null,
  );
  protected readonly fieldClass = computed(() =>
    [field, this.userClass()].filter(Boolean).join(" "),
  );
  /** Indexes (in the original list) of options whose label contains the filter text. */
  protected readonly visible = computed(() => {
    const query = this.filter().trim().toLowerCase();
    return this.options().flatMap((option, index) =>
      option.label.toLowerCase().includes(query) ? [index] : [],
    );
  });

  constructor() {
    // A value changed from outside (or the first value) syncs the input text.
    effect(() => {
      const value = this.value();
      if (value === this.lastValue) return;
      this.lastValue = value;
      this.text.set(labelOf(this.options(), value));
    });
    inject(DestroyRef).onDestroy(() => this.unfollow?.());
  }

  protected optionId(index: number) {
    return `${this.inputId()}-option-${index}`;
  }

  private setActive(index: number) {
    this.active.set(index);
    if (index < 0) return;
    document
      .getElementById(this.optionId(index))
      ?.scrollIntoView?.({ block: "nearest" });
  }

  private commit(next: string) {
    if (next === this.value()) return;
    this.lastValue = next;
    this.value.set(next);
  }

  protected show() {
    if (!this.open()) this.panelRef().nativeElement.showPopover();
  }

  protected hide() {
    this.active.set(-1);
    if (this.open()) this.panelRef().nativeElement.hidePopover();
  }

  protected select(index: number) {
    const option = this.options()[index];
    if (!option) return;
    this.commit(option.value);
    this.text.set(option.label);
    // The DOM value may differ from the signal after typing, so set it directly.
    this.field().nativeElement.value = option.label;
    this.filter.set("");
    this.hide();
  }

  private move(step: 1 | -1) {
    const list = this.visible();
    if (list.length === 0) return;
    const position = list.indexOf(this.active());
    const next =
      position === -1
        ? step === 1
          ? 0
          : list.length - 1
        : (position + step + list.length) % list.length;
    this.setActive(list[next] ?? -1);
  }

  protected handleInput(text: string) {
    this.text.set(text);
    this.filter.set(text);
    this.active.set(-1);
    this.commit("");
    this.show();
  }

  protected handleKeydown(event: KeyboardEvent) {
    if (event.key === "ArrowDown" || event.key === "ArrowUp") {
      event.preventDefault();
      const step = event.key === "ArrowDown" ? 1 : -1;
      if (this.open()) return this.move(step);
      this.show();
      const list = this.visible();
      return this.setActive(
        (step === 1 ? list[0] : list[list.length - 1]) ?? -1,
      );
    }
    if (event.key === "Enter" && this.open() && this.active() >= 0) {
      event.preventDefault();
      return this.select(this.active());
    }
    if (event.key !== "Escape") return;
    event.preventDefault();
    if (this.open()) return this.hide();
    this.text.set("");
    this.field().nativeElement.value = "";
    this.filter.set("");
    this.commit("");
  }

  // beforetoggle runs synchronously, so the state is current for the next key press.
  protected handleBeforeToggle(event: Event) {
    this.open.set((event as ToggleEvent).newState === "open");
  }

  protected handleToggle(event: Event) {
    if ((event as ToggleEvent).newState !== "open") return this.unfollow?.();
    this.place();
    this.follow();
  }

  /** Place the list below the input at its width, flip above when it does not fit. */
  private place() {
    const panelEl = this.panelRef().nativeElement;
    const anchor = this.field().nativeElement.getBoundingClientRect();
    panelEl.style.width = `${anchor.width}px`;
    const { height } = panelEl.getBoundingClientRect();
    const below = anchor.bottom + GAP;
    const above = anchor.top - GAP - height;
    const fitsBelow = below + height <= window.innerHeight;
    panelEl.style.top = `${fitsBelow || above < 0 ? below : above}px`;
    panelEl.style.left = `${anchor.left}px`;
  }

  /** Re-place the list while the page scrolls or the window resizes. */
  private follow() {
    this.unfollow?.();
    const update = () => this.place();
    const scrollOptions = { capture: true, passive: true };
    window.addEventListener("scroll", update, scrollOptions);
    window.addEventListener("resize", update, { passive: true });
    this.unfollow = () => {
      window.removeEventListener("scroll", update, scrollOptions);
      window.removeEventListener("resize", update);
      this.unfollow = null;
    };
  }
}
```

```ts
import { Component, signal } from "@angular/core";
import { Combobox } from "./markas/combobox.component";

@Component({
  selector: "app-address",
  imports: [Combobox],
  template: `
    <markas-combobox
      [(value)]="country"
      name="country"
      label="Negara"
      placeholder="Cari negara"
      emptyLabel="Tidak ada hasil"
      [options]="countries"
    />
  `,
})
export class Address {
  readonly country = signal("id");
  readonly countries = [
    { value: "au", label: "Australia" },
    { value: "id", label: "Indonesia" },
    { value: "jp", label: "Jepang" },
  ];
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `options` | `{ value: string, label: string }[]` | [] | Daftar saran. Mengetik memfilter berdasarkan label, tanpa membedakan huruf besar kecil. |
| `label` | `string` | - | Teks label, terhubung ke input dan dipakai sebagai nama listbox. |
| `hint` | `string` | - | Teks petunjuk di bawah input. Disembunyikan saat ada error. |
| `error` | `string` | - | Pesan error. Mengaktifkan aria-invalid dan border danger. |
| `name` | `string` | - | Nama input tersembunyi yang berisi value terpilih untuk submit form. |
| `value / defaultValue / v-model / bind:value` | `string` | "" | Value opsi terpilih. React menerima value dengan onValueChange atau defaultValue; Vue memakai v-model; Svelte bind:value; Angular value atau [(value)]; Blade dan Astro memakai value. |
| `onValueChange / onvaluechange / markas-change` | `(value: string) => void` | - | Dipanggil saat value terpilih berubah, berisi string kosong saat dikosongkan (React onValueChange, Svelte onvaluechange). Blade dan Astro memancarkan event markas-change yang menggelembung; Angular memancarkan valueChange. |
| `emptyLabel` | `string` | No results | Teks saat tidak ada opsi yang cocok. Isi misalnya "Tidak ada hasil". |
| `id` | `string` | auto | Id input. Listbox dan opsi memakainya sebagai awalan. |

## Aksesibilitas

- Input memakai role=combobox, aria-autocomplete=list, aria-expanded, dan aria-controls ke role=listbox.
- Panah bawah dan atas membuka daftar dan berpindah di antara opsi yang cocok (berputar di ujung); aria-activedescendant mengikuti opsi yang disorot sehingga fokus tetap di input.
- Enter memilih opsi yang disorot dan menutup daftar. Escape menutup daftar; Escape kedua mengosongkan input.
- Klik opsi memilihnya. Meninggalkan input menutup daftar.

## Catatan

- Atribut tambahan (`placeholder`, `required`, `disabled`, `class`) jatuh ke input teks yang terlihat. `name` dipasang di input tersembunyi berisi value terpilih, jadi form mengirim `country=id`, bukan labelnya.
- Mengetik memfilter opsi berdasarkan label dan mengosongkan value terpilih sampai opsi dipilih lagi.
- Daftar dirender di top layer lewat Popover API, jadi parent dengan `overflow: hidden` tidak memotongnya.
- Teks daftar kosong bawaan berbahasa Inggris ("No results"). Terjemahkan lewat `emptyLabel`.
