@data-slot/combobox

中文文档
1.1.3发布于 2026/11/05MITTypeScriptESM + CJS构建来源已验证近 30 天下载 5232

A headless, accessible combobox component with autocomplete/typeahead filtering.

原始使用文档
文档目录14 节
  1. Installation
  2. Usage
  3. HTML Structure
  4. JavaScript
  5. API
  6. Initialization
  7. Slots
  8. Options
  9. Controller
  10. Events
  11. Keyboard Navigation
  12. Accessibility
  13. Form Integration
  14. License

@data-slot/combobox

A headless, accessible combobox component with autocomplete/typeahead filtering.

Installation

npm install @data-slot/combobox

Usage

HTML Structure

<div data-slot="combobox" data-placeholder="Search fruits...">
  <input data-slot="combobox-input" />
  <button data-slot="combobox-trigger">▼</button>
  <div data-slot="combobox-content" hidden>
    <div data-slot="combobox-list">
      <div data-slot="combobox-empty">No results found</div>
      <div data-slot="combobox-group">
        <div data-slot="combobox-label">Fruits</div>
        <div data-slot="combobox-item" data-value="apple">
          Apple
          <span data-slot="combobox-item-indicator">✓</span>
        </div>
        <div data-slot="combobox-item" data-value="banana">
          Banana
          <span data-slot="combobox-item-indicator">✓</span>
        </div>
      </div>
      <div data-slot="combobox-separator"></div>
      <div data-slot="combobox-item" data-value="other">Other</div>
    </div>
  </div>
</div>

JavaScript

import { create, createCombobox } from '@data-slot/combobox';

// Auto-discover and bind all comboboxes
const controllers = create();

// Or bind a specific element
const root = document.querySelector('[data-slot="combobox"]');
const controller = createCombobox(root, {
  defaultValue: 'apple',
  onValueChange: (value) => console.log('Selected:', value),
});

// Programmatic control
controller.open();
controller.close();
controller.select('banana');
controller.clear();
console.log(controller.value); // 'banana'

// Cleanup
controller.destroy();

API

Initialization

create(scope?)

Find and bind uninitialized [data-slot="combobox"] descendants of scope (defaults to document). Returns ComboboxController[] for newly bound roots. To initialize the scope element itself, use createCombobox.

import { create } from "@data-slot/combobox";

const controllers = create();

createCombobox(root, options?)

Create a ComboboxController for one root element. JavaScript options take precedence over the corresponding data attributes. Calling this again for a bound root returns its existing controller; destroy it before rebinding with new options.

import { createCombobox } from "@data-slot/combobox";

const controller = createCombobox(element, {});

Slots

Runtime Slots

  • combobox - Root container.
  • combobox-input - Required text input for filtering and keyboard navigation.
  • combobox-trigger - Optional button that toggles the popup.
  • combobox-clear - Optional button that clears the current value and focuses input.
  • combobox-value - Optional selected-value text target (typically inside combobox-trigger).
  • combobox-content - Required popup container for the search results.
  • combobox-list - Optional scrollable listbox wrapper; the content acts as the listbox when omitted.
  • combobox-item - Individual selectable option.
  • combobox-item-indicator - Optional selected-state indicator inside combobox-item; hidden automatically for unselected items.
  • combobox-group - Groups related items.
  • combobox-label - Group label (inside a combobox-group).
  • combobox-separator - Divider between items or groups; its visibility is updated as results are filtered.
  • combobox-empty - Message shown when no items match filter.
  • combobox-positioner - Optional authored positioning wrapper (reused instead of generated wrapper).
  • combobox-portal - Optional authored portal wrapper that can contain combobox-positioner.

Composed Portal Markup (Optional)

<div data-slot="combobox">
  <input data-slot="combobox-input" />
  <button data-slot="combobox-trigger">▼</button>
  <div data-slot="combobox-portal">
    <div data-slot="combobox-positioner">
      <div data-slot="combobox-content" hidden>...</div>
    </div>
  </div>
</div>

Popup-Input Composition (Optional)

Use this when you want a trigger with committed value text and a separate search input inside the popup.

<div data-slot="combobox">
  <button data-slot="combobox-trigger">
    <span data-slot="combobox-value">Select country...</span>
  </button>
  <div data-slot="combobox-content" hidden>
    <input data-slot="combobox-input" placeholder="Search countries..." />
    <div data-slot="combobox-list">...</div>
  </div>
</div>

In popup-input mode (combobox-input inside combobox-content):

  • Selection text is synced to combobox-value.
  • Search input is cleared each time the popup opens.
  • Closing keeps the popup input empty.

Clear Button (Optional)

<div data-slot="combobox">
  <input data-slot="combobox-input" />
  <button data-slot="combobox-clear">Clear</button>
  <div data-slot="combobox-content" hidden>...</div>
</div>

When combobox-clear is clicked:

  • Current value is cleared.
  • Input is focused.
  • If popup is closed, it remains closed.
  • If popup is open, it remains open.
  • By default it is out of keyboard tab order (tabindex="-1" behavior). Set tabindex="0" to make it tabbable.

Keyboard Tab Stops

  • combobox-input is the primary keyboard tab stop.
  • combobox-trigger and combobox-clear are out of tab order by default.
  • To opt into keyboard tabbing for either control, author tabindex="0" on that element.

Native Label Support

Use a standard HTML <label for="..."> element to label the combobox. The for attribute should match the id on the input. Clicking the label focuses the input, and aria-labelledby is set automatically.

<label for="fruit-input">Choose a fruit</label>
<div data-slot="combobox">
  <input data-slot="combobox-input" id="fruit-input" />
  <div data-slot="combobox-content" hidden>
    <div data-slot="combobox-list">
      <div data-slot="combobox-item" data-value="apple">Apple</div>
    </div>
  </div>
</div>

Options

Options can be passed via JavaScript or data attributes (JS takes precedence).

OptionData AttributeTypeDefaultDescription
defaultValuedata-default-valuestringnullInitial selected value
defaultOpendata-default-openbooleanfalseInitial popup open state
placeholderdata-placeholderstring""Input placeholder text
disableddata-disabledbooleanfalseDisable interaction
requireddata-requiredbooleanfalseForm validation required
namedata-namestring-Form field name (creates hidden input)
openOnFocusdata-open-on-focusbooleantrueOpen popup when input is focused
autoHighlightdata-auto-highlightbooleanfalseAuto-highlight first visible item after non-whitespace query input
filter-(inputValue: string, itemValue: string, itemLabel: string) => booleancase-insensitive label substring matchReturn true to show an item
itemToStringValue-(item: HTMLElement | null, value: string | null) => stringitem labelCustom text resolver for committed selected-value text (input in inline mode, combobox-value in popup-input mode)
sidedata-side"top" | "bottom""bottom"Popup placement
aligndata-align"start" | "center" | "end""start"Popup alignment
sideOffsetdata-side-offsetnumber4Distance from input (px)
alignOffsetdata-align-offsetnumber0Offset from alignment edge (px)
avoidCollisionsdata-avoid-collisionsbooleantrueAdjust to stay in viewport
collisionPaddingdata-collision-paddingnumber8Viewport edge padding (px)

Placement attributes (data-side, data-align, data-side-offset, data-align-offset, data-avoid-collisions, data-collision-padding) resolve in this order:

  1. JavaScript option
  2. combobox-content
  3. combobox-positioner
  4. combobox root (fallback)

The positioned element (combobox-positioner, or combobox-content when no positioner is used) receives these CSS variables for styling:

  • --transform-origin
  • --available-width
  • --available-height
  • --anchor-width
  • --anchor-height

When a separate combobox-positioner is present, the same values are also mirrored onto combobox-content so copied style packs can branch from either element.

Mobile Behavior

  • On touch/coarse-pointer environments, outside pointerdown (for example during scroll gestures) does not dismiss the popup.
  • Outside tap/click still dismisses the popup.
  • While open, popup position tracks scroll so the popup stays anchored.
  • On touch/coarse-pointer environments, combobox always positions on the bottom side.
  • On touch/coarse-pointer environments, collision side-flipping is disabled to avoid jumpy repositioning.

Callbacks

CallbackTypeDescription
onValueChange(value: string | null) => voidCalled when selection changes
onOpenChange(open: boolean) => voidCalled when popup opens/closes
onInputValueChange(inputValue: string) => voidCalled when user types in the input

Controller

interface ComboboxController {
  readonly value: string | null;      // Current selected value
  readonly inputValue: string;        // Current input text
  readonly isOpen: boolean;           // Current open state
  select(value: string): void;        // Select a value
  clear(): void;                      // Clear selection
  open(): void;                       // Open the popup
  close(): void;                      // Close the popup
  setItemToStringValue(itemToStringValue: ((item: HTMLElement | null, value: string | null) => string) | null): void;
  destroy(): void;                    // Cleanup
}

Controller Destruction

destroy() permanently disposes the controller and hides any open surface without emitting an additional change event. Repeated destruction is safe; methods on the old controller become no-ops. Create a new controller on the same root to rebind it.

Events

Outbound Events

root.addEventListener('combobox:change', (e) => {
  console.log('Value changed:', e.detail.value);
});

root.addEventListener('combobox:open-change', (e) => {
  console.log('Open state:', e.detail.open);
});

root.addEventListener('combobox:input-change', (e) => {
  console.log('Input changed:', e.detail.inputValue);
});

Inbound Events

combobox:set accepts a partial update with these fields, applied in table order:

FieldTypeDescription
valuestring | nullSelect a value, or clear with null
openbooleanOpen or close the popup; opening is blocked when disabled
inputValuestringReplace the input text without filtering or firing the input-change callback
itemToStringValueComboboxItemToStringValue | nullReplace or clear the selected-value formatter and resync the displayed value

Programmatic selection works while disabled. In inline-input mode, updating the formatter resynchronizes the input, so it can overwrite inputValue supplied in the same event.

// Set value
root.dispatchEvent(new CustomEvent('combobox:set', {
  detail: { value: 'apple' }
}));

// Set open state
root.dispatchEvent(new CustomEvent('combobox:set', {
  detail: { open: true }
}));

// Set runtime selected-value text formatter
root.dispatchEvent(new CustomEvent('combobox:set', {
  detail: { itemToStringValue: (item, value) => value ? value.toUpperCase() : '' }
}));

Keyboard Navigation

KeyAction
ArrowDownOpen popup (when closed); move to next visible item
ArrowUpOpen popup (when closed); move to previous visible item
HomeMove to first visible item
EndMove to last visible item
EnterSelect highlighted item
EscapeClose popup, restore input to committed value
TabClose popup, restore input, allow normal tab flow

Accessibility

  • Input: role="combobox", aria-expanded, aria-controls, aria-activedescendant, aria-autocomplete="list"
  • List: role="listbox", aria-labelledby
  • Item: role="option", aria-selected, aria-disabled
  • Group: role="group", aria-labelledby
  • Disabled items are skipped during keyboard navigation

Form Integration

When name is provided, a hidden input is automatically created for form submission:

<form>
  <div data-slot="combobox" data-name="fruit">
    <input data-slot="combobox-input" />
    <div data-slot="combobox-content" hidden>
      <div data-slot="combobox-list">
        <div data-slot="combobox-item" data-value="apple">Apple</div>
      </div>
    </div>
  </div>
  <button type="submit">Submit</button>
</form>

An authored name on the combobox input is also supported. The generated input submits the selected value; the visible input keeps the search or display text. Destroying the controller removes the generated input and restores the authored name.

Behavior change: earlier releases left an authored name on the visible input, so the form received the displayed or typed text. It now receives the selected value (or an empty string when nothing is selected). To submit free text, keep name off the combobox input and mirror combobox:input-change into a separate field. A disabled combobox does not submit its value.

Resetting the form restores defaultValue and the displayed selection without emitting a value-change event. An open popup also resets its search and highlight. Synchronization happens on the next event-loop task, after the browser resets native controls. Calling preventDefault() on the reset event preserves the current state.

License

MIT

版本与发布记录

@data-slot/combobox 共发布 131 个版本,首次发布于 2026/02/07;过去 12 个月发布了 131 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.3latest2026/11/056 天前
1.1.22026/10/1428 天前
1.1.12026/10/051 个月前
1.1.02026/10/021 个月前
1.0.22026/09/271 个月前
1.0.12026/09/261 个月前

关于 @data-slot/combobox 的常见问题

@data-slot/combobox 是什么?

A headless, accessible combobox component with autocomplete/typeahead filtering.

如何安装 @data-slot/combobox?

在项目目录运行 npm install @data-slot/combobox,或使用 pnpm add / yarn add / bun add。

@data-slot/combobox 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@data-slot/combobox 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@data-slot/combobox 可以商用吗?

@data-slot/combobox 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@data-slot/combobox 的下载量有多少?

根据 npm 官方下载统计,@data-slot/combobox 在 2026/10/12 – 2026/11/10 这 30 天内被下载 5,232 次,日均约 174 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@data-slot/combobox 还在维护吗?

最新版本 1.1.3 发布于 2026/11/05(6 天前);至今共发布 131 个版本,其中过去 12 个月发布了 131 个;首次发布于 2026/02/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。