Combobox core

framework-independent
@pdanpdan/headless-combobox-core

The state machine used by every adapter. It owns selection, filtering, validation, keyboard navigation, popup lifecycle, anchoring, and focus management. It does not render anything and does not import a framework.

Install

pnpm add @pdanpdan/headless-combobox-core

Usage

Create the store, push props with setProps, and call mount() when the DOM is available. The snapshot contains state, actions, ARIA prop bags, and ref setters. Call destroy() when the host unmounts.

import { createCombobox } from '@pdanpdan/headless-combobox-core';

const combobox = createCombobox({
  props: {
    modelValue: null,
    options: [ 'Vue', 'React', 'Svelte', 'Solid', 'Angular' ],
  },
  onChange: (value) => {
    console.log('selection', value);
  },
});

combobox.mount();
const state = combobox.getSnapshot();

state.open();
state.select('Vue');
state.close();

combobox.destroy();

Keyboard

NameTypeDescription
Enter / Space / ArrowDown / ArrowUppopup closedOpen the dropdown.
Backspace / Deletepopup closed, or open without a filter inputRemove the last (or only) selected option. Text inputs keep their native editing behavior.
ArrowDown / ArrowUppopup openMove the highlight; wraps around and skips disabled options.
PageDown / PageUppopup openMove the highlight a full page (visible options), clamped at the ends.
Home / Endpopup openJump to the first or last selectable option (native caret behavior in inputs).
Enterpopup openSelect the highlighted option.
Spacepopup openDoes nothing on the trigger; options and text entries keep their native behavior.
Tab / Shift+Tabpopup openSkip the options list to the next focusable element; closes when focus leaves the widget (selectOnTab selects first).
Escapepopup openClose the popup and return focus to the trigger.

Clicking the trigger toggles the popup. Hovering or focusing an option highlights it, clicking selects it, and clicking outside the container closes the popup. Escape works from anywhere inside the widget.

Factory options

NameTypeDescription
propsHeadlessComboboxProps<O, V, Q>Initial props: options, modelValue, selection mode, filtering, validation, and behavior flags.
onChange(value: V | V[] | null) => voidCalled for every selection change.
runtimeComboboxRuntimeOverridesHost hooks for nextTick, unwrap, createId, and document lookup.

Props

These fields go inside the props object. Reactive adapters call setProps whenever their inputs change.

NameTypeDefaultDescription
modelValueV | V[] | nullundefinedSelected value(s). Omit it to let the store keep the selection internally.
optionsO[]n/aList of options.
multiplebooleanfalseEnable multiple selection.
minLengthnumbern/aMultiple: minimum number of selected options (validation).
maxLengthnumbern/aMultiple: maximum selected. Blocks adding beyond it.
requiredbooleanfalseRequire a selection (single: a value; multiple: at least one).
disabledbooleanfalseDisable the control: not focusable, cannot open or change.
readonlybooleanfalseRead-only: focusable, shows the value, but cannot open or change.
closeOnSelectboolean | null!multipleClose the dropdown after selecting.
closeOnClickOutsidebooleantrueClose when clicking outside the widget boundary.
clickOutsideFilter(target: EventTarget | null) => booleann/aReturn false to keep the dropdown open for an outside target.
selectOnTabbooleanfalseOn Tab, when focus leaves the widget: select the highlighted option and close.
optionValue(option: O) => Voption itselfMaps an option to the value stored in the model.
optionLabel(option: O) => stringString(option)Maps an option to a string for filtering and rendering.
optionFilter(option: O, query: Q) => booleansubstringCustom filter function. Q defaults to string.
idstringgeneratedBase id for accessibility attributes.
alignSelectedbooleanfalseAlign the dropdown so the selected option covers the trigger.
errorMessagesPartial<Record<HeadlessComboboxErrorCode, string>>n/aOverride default validation messages.

Snapshot

State

Values for the current selection and popup.

NameTypeDescription
isOpenbooleanWhether the dropdown is open.
multiplebooleanWhether multiple selection is enabled.
disabledbooleanWhether the control is disabled.
readonlybooleanWhether the control is read-only.
searchQueryQ | undefinedCurrent search query. Q defaults to string.
filteredOptionsT[]Options after applying the filter.
highlightedIndexnumberIndex of the highlighted option (-1 when none).
alignmentOffsetnumberPixel offset used for alignment.
cssAnchorNamestringUnique CSS anchor-name for popover positioning.
popupStyleHeadlessComboboxPopupStyleDefault popup positioning style. Spread or merge it onto the dropdown.
selectedCountnumberNumber of selected options.
selectedListV[]Selected values (single mode: a single-element array).
canSelectMorebooleanFalse when at maxLength (multiple).
isSelected(option: T) => booleanWhether an option is selected.
validbooleanWhether the current selection passes validation.
errorsHeadlessComboboxErrorCode[]Active validation errors ('required' | 'minlength' | 'maxlength').
validationMessagestringHuman-readable message for the first error.

ARIA prop bags

Attributes and handlers for your markup.

NameTypeDescription
triggerPropsHeadlessComboboxTriggerPropsrole=combobox, aria-expanded, aria-activedescendant, toggle and keydown handlers.
inputPropsHeadlessComboboxInputPropsSearch input attributes, aria-activedescendant, and keydown handling.
comboboxInputPropsHeadlessComboboxComboboxInputPropsTypeahead input attributes, open and focus handlers.
listboxPropsHeadlessComboboxListboxPropsrole=listbox and aria-multiselectable.
getOptionProps(option, index) => HeadlessComboboxOptionPropsrole=option, aria-selected, aria-disabled, and select and highlight handlers.

Actions

Methods that drive the state machine.

NameTypeDescription
toggle() => voidToggle the dropdown open or closed.
open() => voidOpen the dropdown.
close(returnFocus?: boolean) => voidClose the dropdown.
select(option: T) => voidSelect (single) or toggle (multiple) an option.
clear() => voidClear the selection (null or []).
setSearchQuery(value: Q | undefined) => voidUpdate the search query.
setHighlightedIndex(index: number) => voidSet the highlighted option. Wire it to hover to match keyboard behavior.
focusInput() => voidFocus the filter input while the popup stays open.
handleKeydown(event: KeyboardEvent) => voidKeyboard navigation handler.

Ref setters

Attach DOM elements to the store.

NameTypeDescription
setContainerRefref fnThe root container element.
setTriggerRefref fnThe trigger button or typeahead input.
setDropdownRefref fnThe dropdown popup element.
setInputRefref fnThe search input element.
setListRefref fnThe options list element.
setOptionRef(option, el) => voidEach option element. Needed for alignSelected and scroll-into-view.

Runtime

Adapters override these hooks so the core can wait for a framework render, unwrap proxies, and use the framework's id generator.

NameTypeDescription
nextTick() => Promise<void>Resolve after the host has committed the DOM. Defaults to Promise.resolve().
unwrap<T>(value: T) => TStrip framework proxies before identity comparisons. Defaults to identity.
createId() => stringStable id source for accessibility attributes.
getDocument() => Document | nullDocument access for listeners. Defaults to the global document when available.