Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | 5x 13x 13x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 135x 135x 135x 12x 9x 9x 9x 1x 1x 8x 8x 8x 8x 9x 12x 7x 7x 3x 3x 4x 4x 4x 4x 7x 3x 4x 4x 4x 12x 12x 12x 38x 38x 38x 23x 38x 38x 38x 12x 16x 9x 9x 9x 16x 16x 16x 16x 16x 2x 1x 1x 3x 5x 4x 4x 12x 8x 6x 12x 8x 12x 12x 12x 12x 72x 34x 12x 12x 7x 1x 7x 1x 12x 6x 6x 1x 6x 6x 6x 6x 6x 3x 12x 12x 12x 12x 12x 12x 12x 12x 13x 12x 12x 12x 12x 12x 6x 4x 4x 4x 3x 2x 2x 7x 6x 1x 1x 5x 2x 5x 4x 3x 3x 4x 3x 3x 3x 3x | import { fuzzyScore } from '../collections/collection';
import { createControllerHost } from '../core/host';
import type { ChangeDetails, RuntimeController, RuntimeEventSource } from '../core/types';
import { isAbortError, isHTMLInputElement } from '../dom/dom';
import type { FloatingPositionOptions, PositionResult } from '../positioning/positioning';
import { createControllableValue } from '../state/controllable';
import {
createListbox,
type ListboxChangeReason,
type ListboxOption,
type ListboxSelectEvent,
} from './listbox';
import {
createOpenController,
type OpenChangeEvent,
type OpenLifecycleEvents,
type OverlayElements,
} from './openable';
/** Causes of editable Combobox input changes. @public */
export type ComboboxInputReason = 'programmatic' | 'input' | 'selection' | 'clear';
/** Causes of Combobox option selection without exposing the internal Listbox engine. @public */
export type ComboboxSelectReason = 'programmatic' | 'pointer' | 'keyboard';
const normalizeSelectionDetails = (
details: ChangeDetails<ListboxChangeReason>,
): ChangeDetails<ComboboxSelectReason> => {
const reason: ComboboxSelectReason = details.reason === 'typeahead' ? 'keyboard' : details.reason;
return details.event ? { reason, event: details.event } : { reason };
};
/** Combobox option with a required consumer value. @public */
export interface ComboboxOption extends ListboxOption {
/** Consumer value committed on selection. */
readonly value: string;
}
/** Immutable Combobox snapshot. @public */
export interface ComboboxSnapshot {
/** Current popup state. */
readonly open: boolean;
/** Current editable input value. */
readonly inputValue: string;
/** Query used for local or async filtering. */
readonly query: string;
/** Selected consumer value, if any. */
readonly selectedValue: string | null;
/** Keyboard-active option ID. */
readonly activeId: string | null;
/** Whether an async suggestion request is active. */
readonly loading: boolean;
/** Whether an IME composition transaction is active. */
readonly composing: boolean;
/** Whether no visible option matches a settled query. */
readonly empty: boolean;
/** Whether input value is consumer-owned. */
readonly inputControlled: boolean;
/** Whether selected value is consumer-owned. */
readonly selectionControlled: boolean;
/** Filtered option metadata used by the popup listbox. */
readonly options: readonly ComboboxOption[];
/** Stable listbox ID for `aria-controls`. */
readonly listboxId: string;
/** Latest collision-aware popup position. */
readonly position: PositionResult | null;
}
/** Combobox query change payload. @public */
export interface ComboboxQueryEvent {
/** Next query. */
readonly query: string;
/** Typed cause and optional native event. */
readonly details: ChangeDetails<ComboboxInputReason>;
}
/** Combobox selection payload. @public */
export interface ComboboxSelectEvent {
/** Selected option. */
readonly option: Readonly<ComboboxOption>;
/** Typed selection cause and optional native event. */
readonly details: ChangeDetails<ComboboxSelectReason>;
}
/** Combobox lifecycle event map. @public */
export interface ComboboxEvents extends Omit<OpenLifecycleEvents, 'stateChange'> {
/** Cancellable event emitted before option selection. */
readonly beforeSelect: ComboboxSelectEvent;
/** Event emitted after option selection. */
readonly select: ComboboxSelectEvent;
/** Event emitted whenever the search query changes. */
readonly queryChange: ComboboxQueryEvent;
/** Event emitted for accepted open, query, or selection changes. */
readonly stateChange: OpenChangeEvent | ComboboxQueryEvent | ComboboxSelectEvent;
}
/** Combobox options for two controlled values, filtering, async suggestions, and positioning. @public */
export interface ComboboxOptions {
/** Initial editable input value in uncontrolled mode. */
readonly defaultInputValue?: string;
/** Reads consumer-owned input value. */
readonly getInputValue?: () => string;
/** Receives accepted input requests. */
readonly onInputValueChange?: (
value: string,
details: ChangeDetails<ComboboxInputReason>,
) => void;
/** Subscribes to external input changes. */
readonly subscribeInputValue?: (listener: () => void) => () => void;
/** Initial selected value in uncontrolled mode. */
readonly defaultSelectedValue?: string | null;
/** Reads consumer-owned selected value. */
readonly getSelectedValue?: () => string | null;
/** Receives accepted selection requests. */
readonly onSelectedValueChange?: (
value: string | null,
details: ChangeDetails<ComboboxSelectReason>,
) => void;
/** Subscribes to external selection changes. */
readonly subscribeSelectedValue?: (listener: () => void) => () => void;
/** Replaces the default fuzzy local matcher. */
readonly filter?: (option: Readonly<ComboboxOption>, query: string) => boolean;
/** Loads query-specific options; stale responses are ignored by request generation. */
readonly loadOptions?: (query: string, signal: AbortSignal) => Promise<readonly ComboboxOption[]>;
/** Popup positioning options shared with other anchored components. */
readonly positioning?: FloatingPositionOptions;
/** Deterministic ID prefix. */
readonly id?: string;
}
/** Headless editable Combobox controller. @public */
export interface ComboboxController
extends RuntimeController<ComboboxSnapshot>, RuntimeEventSource<ComboboxEvents> {
/** Registers a local option and returns cleanup scoped to that option. */
registerOption(option: ComboboxOption): () => void;
/** Binds input/popup DOM through the shared overlay layer. */
bind(elements: OverlayElements): () => void;
/** Updates editable text, filtering and async suggestions. */
setInputValue(value: string, details?: ChangeDetails<ComboboxInputReason>): void;
/** Handles a native input event without reading during module evaluation. */
handleInput(event: InputEvent): void;
/** Handles popup navigation, selection, and Escape. */
handleKeyDown(event: KeyboardEvent): void;
/** Marks the start of an IME composition transaction. */
handleCompositionStart(): void;
/** Commits the final IME value and resumes filtering. */
handleCompositionEnd(event: CompositionEvent): void;
/** Selects a visible enabled option. */
select(id: string, details?: ChangeDetails<ComboboxSelectReason>): void;
/** Re-runs async suggestions for the current query. */
refresh(): Promise<void>;
}
/** Creates an editable Combobox with stale-response protection and shared Listbox behavior. @public */
export function createCombobox(options: ComboboxOptions = {}): ComboboxController {
const listbox = createListbox(options.id ? { id: `${options.id}-listbox` } : {});
const overlay = createOpenController({
role: 'listbox',
closeOnFocusOutside: true,
...(options.positioning ? { positioning: options.positioning } : {}),
});
const localOptions = new Map<string, ComboboxOption>();
let asyncOptions: readonly ComboboxOption[] = [];
let visibleOptions: readonly ComboboxOption[] = [];
let visibleCleanups: (() => void)[] = [];
const initialInputValue = options.getInputValue?.() ?? options.defaultInputValue ?? '';
const initialSelectedValue = options.getSelectedValue?.() ?? options.defaultSelectedValue ?? null;
let query = initialInputValue;
let loading = false;
let composing = false;
let requestId = 0;
let abortController: AbortController | undefined;
const initialListbox = listbox.getSnapshot();
const initialOverlay = overlay.getSnapshot();
const host = createControllerHost<ComboboxSnapshot, ComboboxEvents>({
open: initialOverlay.open,
inputValue: initialInputValue,
query,
selectedValue: initialSelectedValue,
activeId: initialListbox.activeId,
loading,
composing,
empty: true,
inputControlled: options.getInputValue !== undefined,
selectionControlled: options.getSelectedValue !== undefined,
options: [],
listboxId: initialListbox.id,
position: initialOverlay.position,
});
const sync = (): void => {
const listboxSnapshot = listbox.getSnapshot();
const overlaySnapshot = overlay.getSnapshot();
host.update({
open: overlaySnapshot.open,
inputValue: inputState.get(),
query,
selectedValue: selectedState.get(),
activeId: listboxSnapshot.activeId,
loading,
composing,
empty: !loading && visibleOptions.length === 0,
inputControlled: inputState.controlled,
selectionControlled: selectedState.controlled,
options: visibleOptions,
listboxId: listboxSnapshot.id,
position: overlaySnapshot.position,
});
};
let pendingSelection: ComboboxSelectEvent | undefined;
const commitInput = (value: string, changeDetails?: ChangeDetails<ComboboxInputReason>): void => {
query = value;
rebuildVisible();
if (!changeDetails) {
void refresh();
return;
}
const payload = { query, details: changeDetails };
host.emit('queryChange', payload);
host.emit('stateChange', payload);
overlay.open({
reason: changeDetails.reason === 'input' ? 'trigger' : 'programmatic',
...(changeDetails.event ? { event: changeDetails.event } : {}),
});
void refresh();
};
const commitSelection = (
_value: string | null,
changeDetails?: ChangeDetails<ComboboxSelectReason>,
): void => {
sync();
if (!changeDetails) {
pendingSelection = undefined;
return;
}
Iif (!pendingSelection) return;
const payload = { ...pendingSelection, details: changeDetails };
pendingSelection = undefined;
const inputDetails: ChangeDetails<ComboboxInputReason> = {
reason: 'selection',
...(changeDetails.event ? { event: changeDetails.event } : {}),
};
if (inputState.set(payload.option.text, inputDetails))
commitInput(payload.option.text, inputDetails);
host.emit('select', payload);
host.emit('stateChange', payload);
overlay.close({
reason: 'selection',
...(changeDetails.event ? { event: changeDetails.event } : {}),
});
};
const inputState = createControllableValue<string, ComboboxInputReason>(
{
defaultValue: options.defaultInputValue ?? '',
...(options.getInputValue ? { getValue: options.getInputValue } : {}),
...(options.onInputValueChange ? { onValueChange: options.onInputValueChange } : {}),
...(options.subscribeInputValue ? { subscribeValue: options.subscribeInputValue } : {}),
},
commitInput,
);
const selectedState = createControllableValue<string | null, ComboboxSelectReason>(
{
defaultValue: options.defaultSelectedValue ?? null,
...(options.getSelectedValue ? { getValue: options.getSelectedValue } : {}),
...(options.onSelectedValueChange ? { onValueChange: options.onSelectedValueChange } : {}),
...(options.subscribeSelectedValue ? { subscribeValue: options.subscribeSelectedValue } : {}),
},
commitSelection,
);
const rebuildVisible = (): void => {
visibleCleanups.splice(0).forEach((cleanup) => cleanup());
const all = [...localOptions.values(), ...asyncOptions];
const filter =
options.filter ??
((option: Readonly<ComboboxOption>, value: string) =>
fuzzyScore(option.text, value) > Number.NEGATIVE_INFINITY);
visibleOptions = Object.freeze(all.filter((option) => filter(option, query)));
visibleCleanups = visibleOptions.map((option) => listbox.registerOption(option));
sync();
};
const refresh = async (): Promise<void> => {
if (!host.alive() || !options.loadOptions || composing) return;
requestId += 1;
const currentRequest = requestId;
abortController?.abort();
abortController = new AbortController();
loading = true;
sync();
try {
const result = await options.loadOptions(query, abortController.signal);
if (currentRequest !== requestId || abortController.signal.aborted || !host.alive()) return;
asyncOptions = Object.freeze([...result]);
rebuildVisible();
} catch (error) {
if (!isAbortError(error)) throw error;
} finally {
if (currentRequest === requestId) {
loading = false;
sync();
}
}
};
const setInputValue = (
value: string,
changeDetails: ChangeDetails<ComboboxInputReason> = { reason: 'programmatic' },
): void => {
if (!host.alive() || inputState.get() === value) return;
if (inputState.set(value, changeDetails)) commitInput(value, changeDetails);
};
const selectOption = (
id: string,
changeDetails: ChangeDetails<ComboboxSelectReason> = { reason: 'programmatic' },
): void => listbox.select(id, changeDetails);
host.resources.add(listbox.subscribe(sync));
host.resources.add(overlay.subscribe(sync));
const openEvents = [
'beforeOpen',
'open',
'afterOpen',
'beforeClose',
'close',
'afterClose',
] as const;
for (const name of openEvents) {
host.resources.add(
overlay.on(name, (event) => {
if (!host.emit(name, event.detail)) event.preventDefault();
}),
);
}
host.resources.add(overlay.on('stateChange', (event) => host.emit('stateChange', event.detail)));
host.resources.add(
listbox.on('beforeSelect', (event) => {
const option =
localOptions.get(event.detail.option.id) ??
asyncOptions.find((item) => item.id === event.detail.option.id);
if (
!option ||
!host.emit('beforeSelect', {
option,
details: normalizeSelectionDetails(event.detail.details),
})
)
event.preventDefault();
}),
);
host.resources.add(
listbox.on('select', (event) => {
const selection = event.detail as ListboxSelectEvent;
const option =
localOptions.get(selection.option.id) ??
asyncOptions.find((item) => item.id === selection.option.id);
Iif (!option) return;
const selectionDetails = normalizeSelectionDetails(selection.details);
const payload = { option, details: selectionDetails };
pendingSelection = payload;
if (selectedState.set(option.value, selectionDetails))
commitSelection(option.value, selectionDetails);
}),
);
host.resources.add(() => inputState.destroy());
host.resources.add(() => selectedState.destroy());
host.resources.add(() => listbox.destroy());
host.resources.add(() => overlay.destroy());
host.resources.add(() => abortController?.abort());
host.resources.add(() => visibleCleanups.splice(0).forEach((cleanup) => cleanup()));
rebuildVisible();
return {
getSnapshot: host.getSnapshot,
subscribe: host.subscribe,
on: host.on,
off: host.off,
once: host.once,
registerOption(option) {
if (!host.alive()) return () => undefined;
const registration = Object.freeze({ ...option });
localOptions.set(option.id, registration);
rebuildVisible();
let active = true;
return () => {
if (!active) return;
active = false;
if (localOptions.get(option.id) === registration) localOptions.delete(option.id);
rebuildVisible();
};
},
bind: overlay.bind,
setInputValue,
handleInput(event) {
if (composing) return;
const target = event.target;
if (isHTMLInputElement(target)) setInputValue(target.value, { reason: 'input', event });
},
handleKeyDown(event) {
if (!host.alive()) return;
if (event.key === 'Escape') {
overlay.close({ reason: 'escape-key', event });
return;
}
if (event.key === 'ArrowDown' && !overlay.getSnapshot().open)
overlay.open({ reason: 'keyboard', event });
listbox.handleKeyDown(event);
},
handleCompositionStart() {
if (!host.alive()) return;
composing = true;
sync();
},
handleCompositionEnd(event) {
if (!host.alive()) return;
composing = false;
const target = event.target;
sync();
if (isHTMLInputElement(target)) setInputValue(target.value, { reason: 'input', event });
},
select: selectOption,
refresh,
destroy: host.destroy,
};
}
|