@aiquants/select-box
v0.22.4
Published
High-performance select box component for React with virtual scrolling and fuzzy search
Readme
@aiquants/select-box
A high-performance React select box component with virtual scrolling, fuzzy search, multi-selection, and advanced multi-directional cross-script text normalization.
Features
- Virtual Scrolling: Built with
@aiquants/virtualscrollto handle 1,000+ options smoothly - Fuzzy Search: Drives the
FuzzySearchManagerof@aiquants/fuzzy-searchdirectly (Web Workers, non-blocking); the fuzzy rows of a query are listed only for that very query — see Search behavior while typing - Multi-Directional & Cross-Script Normalization: Supports full-width ↔ half-width, Hiragana ↔ Katakana, Romaji ↔ Kana (romaji runs inside mixed text included), case-insensitive, Japanese variant and optional vowel-length cross-matching; every option gets up to five comparison forms and the query is read through the same stages
- Fail-Safe Match Classification: exact and substring matches are classified synchronously, never through the fuzzy worker — a fuzzy-engine failure or debounce delay can only affect the fuzzy bucket, not deterministic matches
- Responsive Typing: The input renders immediately and the list follows through
useDeferredValue; rows are memoized, options are never copied, and large datasets are prepared in time slices between frames, with matches listed while the rest is still being prepared - Viewport Placement:
dropdownStrategy="fixed"promotes the popup to the top layer (Popover API) so no ancestoroverflowclips it, and follows the input through scrolling, resizing and every update of the component; width, min/max width, the input–popup gap and stacking order are CSS variables on the component root — see Sizing and placement - Single & Multi Select: Unified API for both modes via the
multipleprop - Clearable: Optional clear button in both single- and multi-select mode; clearing emits
null(single) or[](multiple), and in single modeBackspaceon an empty input clears as well - Chip Line Limit:
maxTagLineskeeps amultipleinput area a fixed number of lines tall whatever the selection — the chips that fit, invalueorder, then one marker (+3/ほか 3 件) whose tooltip and screen-reader text name the rest — fitted with the chips' real widths before anything is painted; see Sizing model - New Values: with
createOption, a typed value that names no option is offered in one more row (Use "<text>"), committed byEnteror a press like any row; a value that differs from an option only by width or case (undernormalizeOptions) selects that option instead — see New values - Resizable Dropdown: Drag the handle in the scrollbar's corner (the top corner when the popup opens above) with a mouse, pen or finger to resize within
minDropdownHeight/maxDropdownHeight, or click it to expand or shrink the list (the next click puts it back); the height survives closing and reopening — see Sizing model - Search Highlighting & Score Gradient: Highlights what answers the query as typed (emerald green) and what is only a guess — a stand-in for what the end of the query may still become, a word-wise or subsequence match, a fuzzy row (amber, a gradient scaled by the similarity score on a fuzzy row, and a dotted underline, so the two differ in more than colour, in forced colors too) — using exactly the normalization the search matched with
- Search/Display Decoupling:
searchText/searchFieldssearch decorated labels correctly;renderOptiontakes over row rendering and receives the compiled highlighter ascontext.highlight - Themeable & Dark Mode: Every color routes through
--sb-*CSS variables; the dark palette keys off a.darkclass on an ancestor —<html>on a plain page, the shadow host (:host(.dark)) or an element inside the shadow tree in a shadow root - Density & Row Height:
density="compact"text preset for dense screens, or a talleroptionHeight; under every pointer rows and the input area are at least 44 px tall and the input area's buttons are 44 × 44 px targets (WCAG 2.2 SC 2.5.5) - Worker Isolation:
workerIdgives each instance its own fuzzy-search index (required when multiple SelectBoxes share a screen; use a fixed set of ids) - Full Keyboard Navigation: Arrow / Page / Home / End / Enter / Escape / Alt+Arrow, with scroll-follow that works at 1,500+ options — DOM focus stays in the input while you navigate
- IME-Safe: Every key handler stands down while a composition is in flight, so Japanese conversion (candidate window, Enter to confirm) is never intercepted
- WAI-ARIA Combobox:
role="combobox"+aria-expanded/aria-controls/aria-activedescendant(present only while the row it names is mounted), a chevron toggle that carriesaria-expanded/aria-controlstoo, a namedrole="listbox"popup, per-row ids andaria-posinset/aria-setsizethat report the whole listed (filtered) set rather than the rendered virtual window, an accessible description on every guess row, plus a polite live region for the result count - Disabled Options:
option.disabledrendersaria-disabled, ignores clicks and is skipped by every navigation key - Localizable: built-in English (
"en", default) and Japanese ("ja") throughlocale; every built-in string (button names, empty and searching messages, the description of a guess row, live-region and selection texts, default placeholder, the resize-handle tooltip, the create row's text, the popup's scroll chrome) is overridable throughlabels— see Localization - Shadow DOM & Quirks Mode: works inside an open shadow root (with the standalone CSS injected into it) and on pages without a doctype — see CSS Setup and
dropdownStrategy - Fail-Fast Configuration: a prop whose wrong value would otherwise fail later, far from its cause (in a time slice, a worker or an event handler), is validated as the component renders, and an invalid value throws a
RangeErrornaming the prop — see Fail-fast - TypeScript: Complete type definitions included (the published declaration files carry no doc comments, so this README and the behavior contracts under
docs/behavior/are the host-facing contract);SelectBoxis generic in your option type, soonChange,renderOption,searchTextandonActiveIndexChangereceive your own model without a cast — see Types
Installation
pnpm add @aiquants/select-boxPeer Dependencies
@aiquants/fuzzy-search and @aiquants/virtualscroll are mandatory — SelectBox renders its
list through virtualscroll and filters through fuzzy-search, so neither is optional. Install all
four:
pnpm add @aiquants/fuzzy-search @aiquants/virtualscroll react react-domselect-box requires @aiquants/virtualscroll 3.22.1 or later (^3.22.1) — every host, whether or not it
passes locale / labels: the package imports the engine's label catalog and resolvers when the module
loads, and the release is built and tested with 3.22.1 (the popup scroll bar has been a named role="scrollbar"
track between its two arrow buttons since 3.20.0). It requires @aiquants/fuzzy-search 3.2.1 or later
(^3.2.1, the version the release is built and tested with): a box searches with the manager's search and prebuildIndex — from 3.1.0 on, prebuildIndex also
prepares the Levenshtein Worker's copy of the dataset, which the first fuzzy answer after the box opens depends on
to arrive without building every record inside the user's wait — reads the engine's worker status store
(FuzzySearchManager.getWorkerStatus / subscribeWorkerStatus: idle, loading, ready or failed per worker
kind) and takes the text normalizer from @aiquants/fuzzy-search/normalize. Both floors are the versions the
release is built and tested with. select-box 0.15.x and earlier stay on fuzzy-search 2.x.
Browser floors are those of the @aiquants/fuzzy-search version installed (its README, "Browser Support"):
select-box imports the engine and @aiquants/fuzzy-search/normalize when its module loads, and its text pipeline
(normalization, grapheme clusters, highlighting) runs on that normalizer. For fuzzy-search 3.1 that is Chrome / Edge
93+, Firefox 125+ and Safari 16.4+ (iOS Safari 16.4+): the normalizer builds a RegExp with lookbehind when it is
imported, so on an older Safari the bundle throws a SyntaxError as it loads, and it splits text with
Intl.Segmenter, which it requires rather than detects. select-box's own code needs nothing newer (Object.hasOwn:
Chrome 93, Firefox 92, Safari 15.4; Node 16.9 for server rendering and tests), and @aiquants/virtualscroll's floors
are lower. dropdownStrategy="fixed" also needs the Popover API, IntersectionObserver and ResizeObserver
(Popover API: Chrome / Edge 114, Firefox 125, Safari 17); without them use the default "absolute".
Quick Start
import { useState, useMemo } from "react"
import { SelectBox, type Option } from "@aiquants/select-box"
// Required: Vite environments need explicit Worker URLs
import indexWorkerUrl from "@aiquants/fuzzy-search/worker/indexWorker?url"
import levenshteinWorkerUrl from "@aiquants/fuzzy-search/worker/levenshteinWorker?url"
const options: Option[] = [
{ label: "Apple", value: "apple" },
{ label: "Banana", value: "banana" },
{ label: "Cherry", value: "cherry" },
]
function SingleSelect() {
const [value, setValue] = useState<Option | null>(null)
const workerUrls = useMemo(() => ({
indexWorker: indexWorkerUrl,
levenshteinWorker: levenshteinWorkerUrl,
}), [])
return (
<SelectBox
options={options}
value={value}
onChange={setValue}
placeholder="Select a fruit..."
workerUrls={workerUrls}
/>
)
}
function MultiSelect() {
const [values, setValues] = useState<Option[]>([])
const workerUrls = useMemo(() => ({
indexWorker: indexWorkerUrl,
levenshteinWorker: levenshteinWorkerUrl,
}), [])
return (
<SelectBox
options={options}
value={values}
onChange={setValues}
multiple
placeholder="Select multiple..."
workerUrls={workerUrls}
/>
)
}Multi-Directional & Cross-Script Normalization
Queries match option data across scripts and width styles: full-width ↔ half-width, hiragana ↔
katakana, romaji ↔ kana, case and Japanese variants. Every option text yields up to five comparison
forms, and the query is read through the same stages into tiered readings. normalizeOptions takes
eight boolean keys — convertCase, convertWidth, convertKana and normalizeVariants on by default;
convertRomaji (requires convertKana), ignoreSpaces, ignoreSymbols and ignoreLongVowels off —
and is compared by value. Exact rows come first, then partial rows, then fuzzy rows. Under ignoreLongVowels, a
match that only the long-vowel fold finds (ト for tou, which also reads トウ) ranks after every match that needs
no fold, so the exact, the answer and the stand-in rows each start with the rows ignoreLongVowels: false lists
there, in its order. Korean matches composed (NFC) syllables. The normalizer is the engine's (@aiquants/fuzzy-search/normalize): the normalization
exports re-export it unchanged, so their argument errors read [fuzzy-search] …. The options, the
comparison forms, matching and ranking, romaji and long vowels are specified in
docs/behavior/normalization.md.
Search behavior while typing
Results only narrow as you type characters at the end of the query. The input renders on every
keystroke and the list follows through useDeferredValue; navigation and Enter act on exactly the
list the typed query will show. Exact and partial matches are computed synchronously; the fuzzy rows
come once the dataset is prepared and typing pauses for fuzzyDebounceMs (default 300 ms), and are
listed only for the query, options and settings they were computed for — every match at or above
threshold, with no cap. A box runs one fuzzy search at a time, and a failed search empties only the
fuzzy part, so the direct rows stay. Only an answer row — exact, or partial for the query as typed — is
ever the best match that autoHighlight highlights and Enter commits, or, when no answer row is
selectable, the create row of createOption; a deferred Enter waits for its query's answer
or failure and never starts a search of its own. Large, growing, relabelled and
replaced datasets, the guesses shown while options stream in, the scroll position, the spinner, the live
region and prepare follow the rules in docs/behavior/search-while-typing.md.
New values
createOption lets the user commit a value that is not among options, for a field where the user
mostly picks an existing value and sometimes types a new one (a category, a tag, a group). Given it, the
list of a typed query offers the text in one more row, the create row (Use "<text>" /
「<text>」を使う, named by labels.create):
- When: once every current row is classified under the query (a large dataset still being prepared
lists it once its preparation reaches every row), when the query without its surrounding whitespace is
not empty, and when no row is an exact match of it. An exact row is the option the query names,
compared exactly as the search compares — under
normalizeOptions, and throughsearchTextwhen given — so a value that differs from an option only by width or case (APPLEorappleforApple) lists that option, not a create row; a disabled exact row suppresses it too. GivenormalizeOptionsthe variants your values must not be duplicated by (ignoreSpaces: truemakesA BandABone value). - Where: right after the rows found directly (exact, partial and stand-in rows) and before the fuzzy rows, so it is the first row when nothing matches directly, and the fuzzy rows arriving later never move it.
- Committing:
Enteron the highlighted create row, or a press on it, callscreateOption(text)once with that text and treats the option it returns like a picked row. Single selection reports it throughonChangeand closes;multipleappends it to the selection (a chip), clears the query and keeps the popup open, and reports nothing when an entry with itsvalueis already selected. The function must return an enabled option of your typeT—valuekeeps its type (T | nullin single mode) —; anything else throws aRangeErrornaming the call, and nothing is reported. - Keys: the create row is a row like any other for the arrow, page and
Home/Endkeys.Enterwith nothing highlighted is still left to the browser (an enclosing form submits). UnderautoHighlightthe create row is the best match when no answer row is selectable, so "type,Enter" creates the value, while an answer row (Appleforapp) stays the best match.Tab,Escapeand a press outside close without creating. The rules are in The create row.
const [group, setGroup] = useState<Option | null>(null)
<SelectBox
options={groups}
value={group}
onChange={setGroup}
createOption={(text) => ({ label: text, value: text })}
autoHighlight
/>The created option is yours to keep: add it to options when it should be offered next time. The create
row is a role="option" with the id <base>-create and the hook data-sb-create-option;
onActiveIndexChange reports it with a null option, and the live region names its text after the
count (No options found, new value "Mango").
Rendering performance
A keystroke commits the input urgently, and the list work follows in a deferred render React may
interrupt. A query that narrows the previous one rescans only the rows that query matched, a dataset
is prepared in time slices of 8 ms between frames (a rebuild copies the rows the last complete build
holds), and rows are memoized in two layers. Pass a stable renderOption (useCallback); options is
compared element by element, workerUrls, searchFields and normalizeOptions by value, and the
prepared search follows the content of the options, not their objects. The costs, the memory and the
fuzzy engine's preparation of the dataset (its index build and the Levenshtein Worker's records) are in
docs/behavior/rendering-performance.md.
Sizing and placement
Height is set through props (dropdownHeight, minDropdownHeight, maxDropdownHeight,
optionHeight, density); width, minimum and maximum width, the gap and the stacking order are
--sb-* CSS variables on .sb-container. The resize handle is the scrollbar's corner, with a click as
its single-pointer alternative, and the root's position belongs to the host. Under every pointer (mouse, pen,
finger) rows and the input area are at least 44 px tall and the clear, toggle and chip remove buttons are
44 × 44 px; under multiple, maxTagLines holds the input area to a number of lines (one line is 44 px) and
folds the chips that do not fit into one marker. dropdownStrategy="absolute"
(the default) positions the popup inside the component, where an ancestor's overflow clips it;
"fixed" promotes it to the top layer through the Popover API. The
Sizing model (Hostile resets included),
dropdownStrategy and its
Limitations are in docs/behavior/sizing-and-placement.md.
CSS Setup
The package ships two CSS artifacts; pick one per host. SelectBox builds on @aiquants/virtualscroll (and @aiquants/fuzzy-search), so the virtualscroll stylesheet is a peer CSS dependency — import it once alongside select-box.
A reset that unsets everything with all (all: unset, e.g. the-new-css-reset) belongs in the base
layer (@import "the-new-css-reset" layer(base);): unlayered, it outranks every layered declaration of
both sheets and collapses the popup, the rows and the input area
(Sizing model).
Tailwind v4 host — import the components-only build in
layer(components), after@import "tailwindcss", and do the same for the virtualscroll peer build:/* app tailwind.css */ @import "tailwindcss"; @import "@aiquants/virtualscroll/styles/virtualscroll.css" layer(components); @import "@aiquants/select-box/styles/select-box.css" layer(components);The package imports must come after
@import "tailwindcss"(or after an explicit@layer theme, base, components, utilities;): imported first, they makecomponentsthe first layer, and preflight (base) then outranks every non-important.sb-*declaration — the input area loses its padding (6 px → 0) and shrinks from 42 to 38 px.Every class the component itself renders is an
.sb-*or.aqvs-*class, the loading spinner's and the list window's included, and the hand-written rules of the two sheets style them (every size and opacity the component depends on, the icons' included), so a Tailwind host needs no@sourcefor the package: there is no utility to generate.select-box.css(Artifact A) carries only the hand-written.sb-*classes (every theme value they read — the@applyrules and the root's colour defaults — resolved to avar(--token, fallback)reference, so your theme flows in) — no:roottheme variables, no Tailwind utilities, no preflight — and it does not embed the virtualscroll stylesheet. Do not also@importthe standalone build here: it repeats the.sb-*rules with Tailwind's default theme values written into them, so those rules would not follow your theme.Under
prefix()(@import "tailwindcss" prefix(tw);) your build renames its theme variables (--tw-*), soselect-box.csssees none of them and renders Tailwind's defaults (the default palette, spacing step, radii and type scale). Map what you customise on.sb-container— the--sb-*palette,--spacing,--radius-md/-sm/-xs,--sb-font-size/--sb-line-height— and again in its dark block, as Theming shows, or use the standalone build instead ofselect-box.css.Non-Tailwind or Tailwind v3 host — import the single self-contained standalone build. It bundles the
.sb-*classes with Tailwind's default theme values written into them and the virtualscroll peer CSS, and nothing else: it registers no custom property (@property), and every rule is scoped to the component's own elements (.sb-*,.aqvs-*,[data-sb-*]), so no class of the host page (.collapse,.container,.hidden…) is restyled. A Tailwind v4 host built withprefix()may use it instead ofselect-box.css. A Tailwind v3 page is such a host:select-box.csstargets Tailwind v4's@layerand theme variables, while this sheet reads none of the--tw-*variables a Tailwind v3 base declares and writes the borders v3's preflight removes as layered!importantdeclarations. The theme values are local to the component (it reads no variable but its own, not even--tw-*), so a host's own--spacingor--color-*variables leave it unchanged (Standalone build):@import "@aiquants/select-box/styles/select-box.standalone.css";It ships no preflight: the
.sb-*rules reset what they rely on themselves (the buttons' chrome, the icons' sizes, the input's margin and font, its placeholder's opacity), so a page with only this file renders the same geometry as a Tailwind page with preflight.Dark styles key off a
.darkclass on an ancestor of the component —<html>on a plain page (for a shadow root, see the next item).Inside an open shadow root (a web component, a micro-frontend, an extension UI) — a document stylesheet does not reach into the shadow tree, so inject the standalone build into the shadow root itself. The document needs nothing else: the sheet registers no
@property(which Chromium would ignore inside a shadow root). For example:// Under Vite: import standaloneCss from "@aiquants/select-box/styles/select-box.standalone.css?inline" const shadowRoot = host.attachShadow({ mode: "open" }) const style = document.createElement("style") style.textContent = standaloneCss shadowRoot.append(style)Interaction then works as on a plain page (Keyboard), and the fixed strategy follows scrolls inside the shadow tree. Closed shadow roots are not supported.
The dark theme does not:
<html class="dark">does not reach inside the shadow tree. Put.darkon the shadow host (the stylesheet matches it as:host(.dark)) or on an element inside the shadow tree above the component.:host-context()is deliberately not used, since only Chromium supports it.
Localization
SelectBox renders thirteen strings of its own plus the scroll chrome of the dropdown's VirtualScroll,
all from the frozen per-locale catalog SELECT_BOX_LABEL_CATALOGS in English ("en", the default)
and Japanese ("ja"). Pick the language with locale and override single keys with labels; both
are resolved at the top of every render, so an invalid value throws a RangeError in the render that
receives it. The keys, the label functions and the live region's
Status phrases are in
docs/behavior/localization.md.
API Reference
SelectBox Props
T is your option type: SelectBox infers it from options, and every option it hands back is a T
(see Types). It defaults to Option.
| Prop | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| options | readonly T[] | Yes | - | Array of selectable options, never mutated: objects (plain objects, class instances, objects with getters) with a string label, a string or finite-number value and an optional boolean disabled (validated once per array). An option object's label, its searchText result and its searchFields values must not change while the same object stays in options: the box reads them once per object, so pass a new object to change them |
| value | single: T \| null; multiple: readonly T[] \| null | No | undefined | Current selection (controlled): null / undefined for none, one option in single mode, an array of options under multiple; null round-trips from onChange. The type follows multiple, and a mismatched shape from untyped code throws a RangeError. Commit it synchronously — see Controlled selection |
| onChange | single: (value: T \| null) => void; multiple: (value: T[]) => void | No | undefined | Selection change callback: the picked option (null on clear) in single mode, the whole next array ([] on clear) under multiple; receives the host's own option objects, typed T, so a typed useState setter (useState<Fruit \| null>, useState<Fruit[]>) fits as it is. Each change is computed from the current value |
| placeholder | string | No | the placeholder label of locale ("Select..." / "選択...") | Per-instance placeholder shown when nothing is selected; takes precedence over the catalog default (an explicit "" is kept). Only this prop — never the catalog default — names the listbox when neither ariaLabel nor ariaLabelledBy is given, and only when it is a non-blank string. Not validated |
| multiple | boolean | No | false | Enable multi-select mode; it selects the types of value and onChange (see Types). Like every boolean prop, read by truthiness (null as omitted; not validated) |
| maxTagLines | single: undefined; multiple: number | No | undefined | Fit the chips into this many lines: an integer greater than 0, given only with multiple (otherwise a RangeError). The input area is that many lines tall whatever the selection (one line is 44 px with the default theme); it shows the first chips of value that fit, in order, and one marker, labels.moreTags(hidden) (+3 / ほか 3 件), for the rest, whose tooltip and off-screen text are labels.hiddenTags(hidden) (3 more: … / ほか 3 件: …), also while disabled. The last line keeps room for the marker, the input's minimum width (60 px) and the clear and toggle buttons; lines are never added: a first chip wider than its room is cut with an ellipsis (its title holds the label), and with less room than a chip cut to the ellipsis the marker stands alone. The fit is measured with the chips' real widths before paint — no frame shows every chip first — and again when the box's width, a chip's width, the fonts, the selection or labels.moreTags change. The selection works as without the limit: hidden entries stay selected and Backspace removes the last entry even while it is hidden. Omitted, every chip is shown, wrapping onto as many lines as it takes. See Sizing model |
| className | string | No | undefined | Additional CSS classes for the component root — the place to override --sb-* variables, and to position the component: the root's position belongs to the host (sticky top-0 z-10, absolute … work under both strategies; a sticky root is a stacking context, so give it a z-index or use dropdownStrategy="fixed" — see Sizing model). Written after sb-container, one space apart, as given ("" adds nothing). Not validated |
| disabled | boolean | No | false | Disable the component. Disabling an open popup closes it (the query is cleared); re-enabling leaves it closed |
| clearable | boolean | No | false | Show a clear button whenever at least one value is selected and the component is not disabled; clicking emits null (single) or [] (multiple), resets the query and closes the popup. In single mode Backspace on an empty input does the same, so the button is left out of the Tab order like the toggle (a click still clears); under multiple, where Backspace removes only the last chip, the button stays a tab stop |
| createOption | (text: string) => T | No | undefined (no create row) | Lets the user commit a value that is not among options: the list of a typed query that no row matches exactly (under normalizeOptions, through searchText when given; a disabled exact row included) offers the query without its surrounding whitespace in one more row, the create row (labels.create), placed after the rows found directly and before the fuzzy rows. Enter on it or a press on it calls createOption(text) once and commits the option it returns like a picked row: onChange with it and close in single mode; under multiple it is appended (nothing is reported when an entry with its value is already selected) and the query is cleared, the popup kept open. Under autoHighlight the create row is the best match when no answer row is selectable. It must return an enabled option of your type T; anything else throws a RangeError naming the call when the row is committed. A function or undefined. See New values |
| autoFocus | boolean | No | false | Auto-focus the input on mount |
| enableHighlight | boolean | No | true | Enable/disable search result highlighting and score gradients in the default row renderer (no effect with renderOption) |
| normalizeOptions | NormalizeOptions | No | DEFAULT_NORMALIZE_OPTIONS (exported) | Normalization settings applied identically to the query, every option, the fuzzy engine and the highlighter; compared by value. See Normalization |
| workerUrls | WorkerUrls ({ indexWorker?, levenshteinWorker? }) | No | undefined (the engine's defaults) | Explicit Web Worker URLs, compared by value and forwarded to the engine as given; the engine checks them when the box creates its manager (a plain object with only these keys, each a non-blank string, else its [fuzzy-search] RangeError). The first URLs of a workerId win for the page (see Web Worker URLs) |
| workerId | string | No | undefined (the shared "default" workers) | Isolation key (a non-blank string, checked by the engine) for the fuzzy-search workers and index. Give every SelectBox on the same screen a distinct value — instances sharing the default workers evict each other's index on every dataset switch. The engine keeps the two workers of an id alive for the rest of the page's life, so use a fixed set of ids, never one generated per mount — see Web Worker URLs |
| searchText | (option: T) => string | No | undefined | Derives the search-target string per option, decoupling search from label decoration (padding, separators, units). Unset searches label. A pure function of the option, compared by what it derives (an inline function is safe; a changed derivation re-prepares the search) — see Rendering performance. A value that is not a function throws a RangeError in the render that receives it; a result that is not a string throws a RangeError when the search is prepared (see prepare) |
| searchFields | readonly string[] | No | undefined | Additional option fields handed (normalized) to the fuzzy engine besides the base target; exact and partial matching reads the base target only. An array of field names, compared by value (a repeated name, and label while searchText is unset, index and weigh that field twice); each field's value must be a string, number, boolean, null or undefined |
| threshold | number | No | 0.3 | Fuzzy-match similarity threshold, a finite number in [0, 1]. Only affects the fuzzy bucket — exact and substring matches are classified directly and never filtered by it |
| sortBy | SortBy ("score" \| "relevance") | No | "score" | Scoring mode of the fuzzy engine for the fuzzy bucket; "relevance" adds matched-field-count weighting |
| fuzzyDebounceMs | number | No | 300 | The typing pause in ms — how long a typed query must stay unchanged — for both the fuzzy search and the live region: the fuzzy search runs, and the settled list of a typed query is announced (isTyping in SelectBoxStatusInfo is true until then), once the pause has passed. One prop on purpose: the pause is one threshold of user behaviour, the typing cadence (the default is one keystroke interval of a 40 WPM typist), and both wait for the user to stop typing. The trade-off follows: 0 (or a small value) gives instant fuzzy rows but also announces each list that settles between keystrokes — at 0 no pause is recorded, isTyping is never true and a keystroke costs no extra render — and a large value spares fuzzy searches but delays every announcement of a typed query by as much. Exact and partial matches never wait; a query set by a single-select pick, a clear or closing the popup is announced at once; the pause belongs to the typed query, so a change of the options or of the engine settings never restarts it, and a navigation key or Enter queued on a list still searching ends the pause of its query (typing restarts it; see Search behavior while typing). A finite number in [0, 2147483647] |
| prepare | SearchPreparation ("interaction" \| "mount") | No | "interaction" | When the search (the normalized text of every option and the fuzzy engine's index) is prepared: "interaction" at the first pointer entry or focus, so a box nobody uses never derives its corpus nor sends its options to the engine (the engine's two workers of a worker id start when the first box of that id mounts); "mount" starts the sliced preparation right after mount. The trade-off: when typing starts right at focus, the first fuzzy rows wait for the whole dataset to be prepared and indexed under "interaction", while under "mount" a page open for a while before typing has that done — use "mount" for a large box the user is expected to type into first (see Rendering performance) |
| renderOption | RenderOption<T> ((option: T, context: RenderOptionContext) => ReactNode) | No | undefined | Custom row renderer; replaces the default label/highlight rendering entirely. context is { query, score, category, highlight } (category is the row's MatchCategory, the value of data-match-category). Pass a stable function — see Rendering performance |
| showMatchScore | boolean | No | false | Show each row's match category (MatchCategory) as a subtle badge — exact / partial for an answer, stand-in for a row reached only through a stand-in reading, or fuzzy 0.87 with the engine score (search-tuning aid); only rendered while a query is active. The badge sits at the row's inline end, right before the single-select check mark of a selected row |
| optionHeight | number | No | POINTER_TARGET_SIZE (44) | Dropdown row height in px, applied to both the virtual-scroll math and the row elements, in both densities. A finite number greater than 0; a value below POINTER_TARGET_SIZE (44 px) is raised to it, a taller one is kept. It does not follow the root font size; the default label's line height is capped to it (Sizing and placement) |
| density | Density ("comfortable" \| "compact") | No | "comfortable" | Text density preset; compact sets the text to the body step of control text (--sb-font-size-body / --sb-line-height-body, 13 / 20 px by default), one step denser than the default 14 px (see Text size). Rows and the input area keep POINTER_TARGET_SIZE (44 px) in both densities. The root carries the resolved value as data-density |
| id | string | No | undefined (the input has no id, and the generated ids take a useId prefix, sb-…) | DOM id of the text input, and the prefix of every generated id (<base>-listbox, <base>-option-<generation>-<origin>, <base>-selection; a row keeps its id until a change of options alters a value at an existing index — see Accessibility notes), so give a valid HTML id: non-empty, no ASCII whitespace (written as given, not validated). When omitted the input has no id and the generated ids use sb-<useId>. Supply it for deterministic ids in tests and to wire a <label htmlFor> |
| name | string | No | undefined | Form field name of the selection: hidden inputs of this name submit the selected values — one per selected option, a single empty one when nothing is selected; they render whenever name is given. The search input itself has no name, so the typed query is never submitted. Written as given (not validated; an empty name submits nothing) |
| ariaLabel | string | No | undefined | Accessible name applied to both the combobox and its listbox popup, unless ariaLabelledBy is given. ARIA requires each to be named independently — a <label> attached to the input does not name the popup. When omitted, the placeholder prop (never the catalog default) names the listbox if it is not blank. Written as given (not validated; give it non-whitespace content, since a blank name names nothing) |
| ariaLabelledBy | string | No | undefined | Same as ariaLabel, by id reference — an IDREF list, one or more ids separated by ASCII whitespace — for both the combobox and the listbox. Takes precedence: when it is given, no aria-label is written. Written as given (not validated) |
| autoHighlight | boolean | No | false | Activate the best match while typing so Enter accepts it — the first selectable answer row (an exact row, or a partial row reached through the query as typed) of the list ranked for the typed query, followed as the list grows or re-ranks; a list of guesses alone (stand-in or fuzzy rows) is not highlighted (see Search behavior while typing); turned on while a query is shown, it takes effect from the next keystroke. Default false follows the APG (typing returns visual focus to the textbox) and keeps Enter available for form submission |
| loopNavigation | boolean | No | true | Wrap Arrow navigation at the list ends |
| dropdownHeight | number | No | 300 | Initial list height in px — the most the list shows; a list with fewer rows is as tall as its rows — read once at mount (later values are not read) and clamped into [minDropdownHeight, maxDropdownHeight]; a finite number greater than 0. A drag-resize survives closing and reopening; the held height is kept within the bounds when they change; under dropdownStrategy="fixed" the height is capped to the room the popup has |
| minDropdownHeight | number | No | 100 | Lower bound of the resize drag; a finite number greater than 0. When it exceeds maxDropdownHeight (600 when omitted), the upper bound is raised to it |
| maxDropdownHeight | number | No | 600 | Upper bound of the resize drag; a finite number greater than 0. A value below minDropdownHeight (100 when omitted) is raised to it |
| dropdownStrategy | DropdownStrategy ("absolute" \| "fixed") | No | "absolute" | "fixed" positions the popup against the viewport in the top layer (requires the Popover API (showPopover / hidePopover), IntersectionObserver and ResizeObserver, checked at render where a document exists, so server rendering is exempt; in a browser without them, use "absolute"). See Sizing and placement |
| locale | SelectBoxLocale ("en" \| "ja") | No | "en" | UI chrome language of every built-in string, including the scroll chrome of the popup's VirtualScroll. See Localization |
| labels | SelectBoxLabelOverrides<T> | No | undefined | Per-key overrides laid over the catalog of locale; removeTag receives the host's own option of a chip, typed T, moreTags and hiddenTags the options a maxTagLines marker stands for and selection the selected options, typed readonly T[]. Resolved on every render (an object mutated in place is read again) and compared key by key, so an inline literal with the same values re-renders nothing. See Localization |
| onActiveIndexChange | (index: number, option: T \| null) => void | No | undefined | Fires whenever the keyboard-highlighted row changes, with your own object (typed T), or -1 and null when nothing is highlighted (also while a "fixed" popup is hidden with its field); the create row of createOption is reported with its index and null. It fires when the active index or the active row's id (see id) changes, not for re-created options with the same value or a changed label or disabled, so storing the option in state never loops; it is called in a passive effect after the commit, after onOpenChange (details in Accessibility notes). A function or undefined |
| onOpenChange | (isOpen: boolean) => void | No | undefined | Fires whenever the popup is shown or hidden on screen (a popup that never became visible is not reported). Called in a passive effect after the commit that changes it (never inside the commit; after paint unless a discrete input such as a key press or a click caused the commit, whose passive effects React runs before paint), before onActiveIndexChange when both change in one commit (an autoHighlight open reports true, then the best match). A function or undefined |
Controlled selection
valueis the selection; the component stores none of its own. Every change — picking or deselecting a row undermultiple, removing a chip,Backspaceon an empty input (the last entry undermultiple, the value of aclearablesingle select), clearing, committing a row in single mode, committing the create row ofcreateOption— is computed from the currentvalueprop and reported throughonChange, so a change the host does not commit leaves no trace. An optioncreateOptionreturned is selected only through thatonChange: whether it joinsoptionsis the host's choice.- Commit
valuesynchronously inonChange, as React requires for any controlled input — not insidestartTransitionor after an asynchronous step (a router navigation that waits for its loaders). A second pick made before such a transition commits is computed from the oldvalue, and the first pick is lost. - A row is selected and deselected by
value. A chip stands for one selection entry: removing it (its remove button, orBackspacefor the last chip) removes exactly that entry, by its position, even when another entry shares itsvalue. UndermaxTagLinesthe entries past the shown chips have no chip and stay selected all the same:Backspaceremoves the last entry even while the marker stands for it.
Fail-fast
A prop is checked as the component renders only when its wrong value would otherwise throw or silently
disable a feature later, far from its cause (in a time slice, a worker, an event handler or a table lookup).
Such a value throws a RangeError — a wrong type included, so the package throws no TypeError for
configuration — in the render that receives it (the mount included), where an error boundary catches it,
never later inside a callback. The one prop read only at mount is dropdownHeight. Every configuration
error reads [select-box] <setting> must be …; got …; workerId and workerUrls are checked by the engine
([fuzzy-search] …). The strings React only writes to the DOM and the boolean props are not checked. The
rule for each setting, and the worker failures (reported, never thrown), are in
docs/behavior/fail-fast.md.
Exports
| Export | Description |
| --- | --- |
| SelectBox | The component |
| createHighlighter(query, options?) | Compiles a query once and returns a Highlighter, (text, category?) => HighlightSegment[], that splits any text into highlight segments with the same readings the search matches with. Given a row's MatchCategory, the category decides the paint (see Matching and ranking); without one, the paint is inferred from the text. A category that is neither undefined nor a MatchCategory throws a RangeError (see Fail-fast). renderOption receives the one for the listed query (under the component's normalizeOptions), bound to the row's category, as context.highlight |
| getHighlightSegments(text, query, options?) | One-shot createHighlighter(query, options)(text). For many texts of one query, create one highlighter instead; inside renderOption, use context.highlight |
| normalizeText(text, options?) | The most normalized form of a finished text (see Comparison forms): a whole-text key, compared for equality with the same call on the other side. It is stable under neither prefixes nor substrings, under the default options too (normalizeText("ア-1") is アー1, which does not contain -1; under convertRomaji, normalizeText("kanwa-st") is カンワーst, not a prefix of カンワーsタrch), so to search compare the spellings of getNormalizedVariants or let the component search |
| getNormalizedVariants(text, options?) | The spellings a matcher may meet: the original as written, trimmed like every form (only whole whitespace clusters, so " " keeps the space the U+0600 joins), its case-folded spelling (under convertCase, the fold every form uses: İstanbul → istanbul, no dangling dot, each letter the fold changed recomposed with its marks, like the forms), its NFKC form (case-folded under convertCase), every comparison form with its hiragana and katakana counterparts, and the full-width alphanumeric spelling of the (folded) text (Straße → strasse). Under convertCase: false no case-changed spelling is listed (Straße gives Straße), except the romaji readings of convertRomaji, which ignore case (IPHONE gives イpホネ) |
| normalizeJapaneseVariants(text) | The variant map alone (tildes, dashes, apostrophes, ‖, ヶ / ヵ / ゖ / ゕ, NFC) |
| romajiToKatakana(text) | Hepburn transliteration of a finished text (the rules of Romaji); letters that form no syllable and every other character pass through |
| hiraganaToKatakana(text) / katakanaToHiragana(text) | Script conversion, iteration marks and the Small Kana Extension's four pairs included |
| DEFAULT_NORMALIZE_OPTIONS | The frozen default options, a ResolvedNormalizeOptions |
| SORT_BY_VALUES, DENSITY_VALUES, DROPDOWN_STRATEGY_VALUES, SEARCH_PREPARATION_VALUES, SELECT_BOX_LOCALE_VALUES, MATCH_CATEGORY_VALUES | The frozen closed sets of sortBy, density, dropdownStrategy, prepare and locale, and of a row's category (["exact", "partial", "stand-in", "fuzzy", "none"], in ranking order), each in the order error messages list them; SortBy, Density, DropdownStrategy, SearchPreparation, SelectBoxLocale and MatchCategory are derived from them, and the render-time checks — the highlighter's category check included — read the same sets |
| isGuessCategory(category) | Whether a row's MatchCategory is a guess ("stand-in" or "fuzzy") rather than an answer ("exact" or "partial"; "none" is neither) — the one partition the package's highlight and guess description (the row's accessible description) read. A type predicate (category is "stand-in" \| "fuzzy"), so both branches narrow; a value that is not a MatchCategory throws a RangeError, like the highlighter. In a renderOption, test isGuessCategory(context.category) rather than the literals |
| DEFAULT_SORT_BY, DEFAULT_DENSITY, DEFAULT_DROPDOWN_STRATEGY, DEFAULT_SEARCH_PREPARATION, DEFAULT_SELECT_BOX_LOCALE | What an omitted sortBy ("score"), density ("comfortable"), dropdownStrategy ("absolute"), prepare ("interaction") and locale ("en") resolve to — each a member of its set, typed by its member type, so a settings UI never re-types a default |
| DEFAULT_THRESHOLD, DEFAULT_FUZZY_DEBOUNCE_MS, DEFAULT_DROPDOWN_HEIGHT, DEFAULT_MIN_DROPDOWN_HEIGHT, DEFAULT_MAX_DROPDOWN_HEIGHT | What an omitted threshold (0.3), fuzzyDebounceMs (300), dropdownHeight (300, clamped into the bounds), minDropdownHeight (100) and maxDropdownHeight (600) resolve to — so a threshold slider or a debounce field starts from the package's own number |
| POINTER_TARGET_SIZE | The side in CSS px (44, WCAG 2.2 SC 2.5.5) of the targets under every pointer: what an omitted optionHeight resolves to and the floor of an explicit one (in both densities), and the size the stylesheet gives the input area and its clear, toggle and chip remove buttons. Not adjustable: lowering it would break the criterion |
| DEFAULT_FLAGS | What each omitted boolean prop resolves to, one frozen BehaviorFlags object: multiple, disabled, clearable, autoFocus, showMatchScore and autoHighlight are false, enableHighlight and loopNavigation are true |
| SELECT_BOX_LABEL_KEYS, SELECT_BOX_LABEL_CATALOGS, resolveSelectBoxLabels | See Localization |
Every default a prop resolves to is exported by one rule, whatever the kind of prop: the enumerated
defaults next to their sets, the scalar defaults, the boolean defaults (DEFAULT_FLAGS) and
DEFAULT_NORMALIZE_OPTIONS. The numbers in the props table are their values.
Every exported set is frozen and named by one rule: the members of a type are <TYPE>_VALUES
(SORT_BY_VALUES holds the members of SortBy), the keys of an object type <TYPE>_KEYS
(SELECT_BOX_LABEL_KEYS holds the keys of SelectBoxLabels).
Types
The package ships two declaration sets of 6 files each (index, components/SelectBox, types/index,
utils/{config, highlight, labels}), .d.ts for the exports map's import condition and .d.cts for
its require condition; import only from @aiquants/select-box. The normalization types resolve through
the required peer @aiquants/fuzzy-search.
SelectBox is generic in your option type T, and SelectBoxProps<T> is
SelectBoxCommonProps<T> & SelectBoxModeProps<T>. The declaration files, the generic props and the
recipes for wrappers and for a mode chosen at run time are in docs/behavior/types.md.
DOM hooks
The data-testid and data-* attributes listed in docs/behavior/dom-hooks.md
are the component's supported hooks for tests, scripts and host CSS, part of the contract like the
props. Locate elements by them or by role, never by class name or by a generated id; any other
data-* attribute is internal.
Keyboard
The component never moves DOM focus off the text input; the highlighted row is published through
aria-activedescendant (the WAI-ARIA APG "combobox with list autocomplete" pattern). The row sets the
attribute itself while it is mounted, so it never names a row that is not in the DOM: a row scrolled
out of the rendered virtual window drops it until it comes back. Every handler stands down while an IME
composition is in flight.
| Key | Popup closed | Popup open |
| --- | --- | --- |
| ArrowDown | Opens, highlighting the current selection if it is in the list | Next option (wraps unless loopNavigation={false}); while other steps are queued, or on a list still searching that cannot take it (nothing highlighted and no row it can reach), queued and replayed once the list can (see below) |
| ArrowUp | Opens, highlighting the current selection | Previous option (wraps); queued as ArrowDown is (see below) |
| Alt+ArrowDown | Opens without highlighting anything | – |
| Alt+ArrowUp | – | Closes |
| PageDown / PageUp | (browser default) | ± one viewport of rows, clamped at the ends; queued as ArrowDown is; on a settled empty list left to the browser |
| Home / End | (caret) | First / last option when the query is empty (queued as ArrowDown is); otherwise the native caret move is preserved (APG's editable-combobox behavior) |
| Ctrl/Cmd+Home / End | (browser default) | First / last option, regardless of the query; queued as ArrowDown is; on a settled empty list left to the browser |
| Enter | (browser default — form submit still works) | Commits the highlighted row — on the create row of createOption, the option createOption returns for its text (New values). With nothing highlighted on a settled or ranked list — or on any list without autoHighlight — the key is not intercepted, so an enclosing form submits, also while a create row is listed. Under autoHighlight, while the highlight is provisional — the list is still searching with its answer rows to come (the dataset's first preparation, or a rebuild after a change of the options that has not completed) — it is consumed and waits: it ends its query's typing pause, never starts a search of its own, and lands once its query's fuzzy answer or failure arrives or no fuzzy row can come (bounded by the engine's timeouts), committing the best match — an answer row, or the create row when no answer row is selectable — or nothing (and submitting nothing) when the list holds neither; never a guess. An Enter pressed while steps are queued is queued with them (see below). The rules are in the Enter item of Search behavior while typing |
| Escape | Not intercepted, so a parent dialog still receives it — also while a dropdownStrategy="fixed" popup is hidden because its field is out of view, which it then closes | Closes without committing |
| Tab | – | Closes without committing, focus moves on |
| Backspace | On an empty query with something selected: under multiple, removes the last selection entry (its chip, or the last entry a maxTagLines marker stands for) — exactly that entry, even when another entry has the same value; in single mode under clearable, clears the value (onChange(null), as the clear button does). With a query typed it only deletes characters, and in single mode without clearable it does nothing | Same — the branch is not gated on the popup state; a single-mode clear closes the popup, as the clear button does |
Tab stops at the input, at each chip's remove button and, under multiple, at the clear button. A button
the input has a key for is left out of the Tab order: the toggle (Alt+ArrowDown) and, in single mode,
the clear button (Backspace on an empty input), so Tab and Shift+Tab from the input of a single
select leave the widget. Both still respond to a click.
Focus handling, wrap-around and the queue that holds keys pressed while the list is still searching are specified in docs/behavior/keyboard.md.
Testing your integration
A deferred Enter — pressed on the provisional automatic highlight while the list is still searching —
is applied only while the input itself holds focus (see the Enter item of Search behavior while
typing). Under jsdom, give the input
real focus before pressing keys: call input.focus(), or drive it with Testing Library's userEvent,
which focuses what it clicks and types into. fireEvent.focus(input) only dispatches the event and
leaves focus on the body, so a deferred Enter is refused without an error and onChange is never
called. A test that presses Enter while the highlight is provisional and then drives the preparation
must await its act (await act(async () => …)) to see onChange.
The component runs under jsdom and under happy-dom. Pointer events need no shim in either: the resize
handle captures the pointer only where setPointerCapture exists, and the list's scroll pane detects the
Pointer Capture API too (jsdom has none). The component calls no matchMedia: rows are at least
POINTER_TARGET_SIZE (44 px) tall in both environments, as in a browser under every pointer.
The default "absolute" strategy runs without IntersectionObserver: without one (jsdom) keys waiting
on a list still searching land as on a settled list. dropdownStrategy="fixed" calls the Popover API
(HTMLElement.prototype.showPopover and hidePopover), IntersectionObserver and ResizeObserver: jsdom
has none of them; happy-dom 20 defines the two observers (which never report) but not the Popover API.
Shim what your environment lacks, or the first render that receives the prop throws a [select-box] Error
naming what is missing. Neither environment lays anything out, so the placement is skipped (no position,
data-placement or height cap; the list renders at its own height), nothing non-finite reaches a style or
React state, and aria-activedescendant stays on the notified row. Test the placement itself (side, flip,
width clamp) in a real browser, or stub the popup's computed width, height, borders and margins.
Server rendering needs no shim: the check runs only where a document exists, also when a server's DOM shim
defines a global HTMLElement. The package's own suite runs these scenarios in both, with exactly these
shims.
Without Worker (jsdom and happy-dom by default) a box calls nothing of @aiquants/fuzzy-search and lists
direct matches, so a stand-in of the module needs only what your own code uses. Where a test defines Worker
and replaces the module, FuzzySearchManager needs only the constructor, search, prebuildIndex, dispose
and the statics. prebuildIndex(items, fields, options) must return a Promise (the box ignores its value and its
rejection), and the box calls it from an effect, never during render. The statics are
getWorkerStatus(workerId) (a frozen { workerId, index, levenshtein }, each kind { state, failure } with
state one of "idle", "loading", "ready", "failed" and failure set exactly while it is "failed",
the same object while nothing changes) and subscribeWorkerStatus(workerId, listener) (returning an
unsubscribe). search receives the box's raw rows — arrays of strings — and must resolve with results whose
originalIndex is the row's index in that array and whose score is finite (other fields are not read), or
reject. A test that defines Worker and keeps the real engine stands in for the worker scripts instead: from
@aiquants/fuzzy-search 3.1.0 on, the pre-build also posts levenshteinInstall to the Levenshtein Worker, which
must answer levenshteinReady — on an error answer the engine drops that worker's copy of the dataset, and the
first fuzzy search after the preparation, already queued behind the install, rejects. The box reads getWorkerStatus during render, creates and disposes its manager in effects, and never
imports WorkerFailureError.
Mouse wheel
The list scrolls by wheel, touch drag and its scrollbar, and nothing floats over the rows. A vertical wheel over a list taller than the popup stays inside the popup even at its edges; a list that fits, the message box and the resize corner are not scroll targets, so a wheel there reaches the page. The details are in docs/behavior/mouse-wheel.md.
Accessibility notes
Give every instance an ariaLabel (or ariaLabelledBy). DOM focus stays in the input: option rows are
not focusable, and aria-activedescendant names a row only while it is mounted. aria-posinset /
aria-setsize report the whole listed (filtered) set, the listbox is aria-busy while the list is not
settled, every guess row carries an accessible description, the palette's contrast is specified and
forced colors are handled. Under every pointer the clear and toggle buttons and every chip's remove button are
44 × 44 px targets and the rows and the input area at least 44 px tall (SC 2.5.5); under a coarse primary pointer
((pointer: coarse)) the typed text is also at least 16 px, so iOS Safari does not zoom into the field. The full
notes are in
docs/behavior/accessibility.md.
Option Type
An option is any object that is not an array, with a string label (the default search target), a
value that is a string or a finite number (the identity used for selection and form submission; it
may repeat) and an optional boolean disabled. Your own type T is inferred from options, and every
callback receives your options exactly as you passed them — never copied. The interface, the rules for
duplicate values, RenderOptionContext and the decorated-label recipe (searchText with
renderOption) are in docs/behavior/types.md.
Theming
Every color and the component font size resolve through --sb-* CSS custom properties declared on .sb-container, defaulting to the light palette (each default chains to the host's Tailwind token, e.g. var(--color-gray-300, oklch(…))).
Two exceptions are never declared by the package: the optional --sb-highlight-fuzzy-bg (while it is unset, the fuzzy highlight is an amber whose lightness follows the row's score, and setting it, on the root or on any ancestor since it is inherited, replaces that amber with one colour) and the three text steps --sb-font-size-body, --sb-line-height-body and --sb-font-size-caption, which are read with rem fallbacks (see Text size).
The root declares its own values, so override any subset with a rule that matches .sb-container itself — a descendant selector or a class passed through className:
.my-app .sb-container {
--sb-bg: #101828;
--sb-fg: #f3f4f6;
--sb-border: #364153;
--sb-font-size: 1rem;
}Key variables: --sb-bg, --sb-fg, --sb-border, --sb-border-hover, --sb-focus, --sb-placeholder, --sb-icon, --sb-icon-hover, --sb-disabled-bg, --sb-tag-bg, --sb-tag-fg, --sb-tag-border, --sb-tag-remove, --sb-tag-remove-hover, --sb-option-hover-bg,
--sb-option-focused-bg, --sb-option-focused-accent, --sb-option-focused-accent-width, --sb-option-selected-bg, --sb-option-selected-fg, --sb-checkbox-border, --sb-checkbox-bg, --sb-checkbox-fg, --sb-check-fg, --sb-no-options-fg,
--sb-score-fg, --sb-highlight-exact-bg, --sb-highlight-exact-fg, --sb-highlight-fuzzy-bg (optional, see above), --sb-highlight-fuzzy-fg, --sb-font-size, --sb-line-height, the text steps (see Text size), and the border and spacing variables below (full inventory in src/styles/select-box.css).
A default written --spacing × n is your theme's spacing step under select-box.css
(calc(var(--spacing, 0.25rem) * n)) and Tailwind's default step (0.25rem) written in under the
standalone build, where a host --spacing changes nothing.
| Variable | Default | Controls |
| --- | --- | --- |
| --sb-border-width | 1px | The border width of the input area, the chips, the popup and the checkboxes |
| --sb-border-style | solid | The border style of the same four |
| --sb-input-padding-inline | --spacing × 1 (4 px) | The inline padding of the input and of the single-select value over it, so both texts start at the same point |
| --sb-input-padding-block | --spacing × 1 (4 px) | The input's block padding (the input is its line height plus twice this) |
| --sb-option-padding-inline | --spacing × 3 (12 px) | The rows' inline padding; keep it wider than --sb-option-focused-accent-width (3 px) so the active row's accent bar never covers the text |
Where a variable reaches, the pinned values, the checkbox, scrollbar and layout variables, dark mode and forced colors are specified in docs/behavior/theming.md.
Text size
The default density's text is `--sb
