@tangible/ui 0.2.8 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/components/Combobox/Combobox.d.ts +16 -11
  2. package/components/Combobox/Combobox.js +42 -196
  3. package/components/Combobox/types.d.ts +3 -7
  4. package/components/MultiCombobox/MultiCombobox.d.ts +16 -11
  5. package/components/MultiCombobox/MultiCombobox.js +42 -154
  6. package/components/MultiCombobox/types.d.ts +4 -7
  7. package/components/MultiSelect/MultiSelect.d.ts +16 -11
  8. package/components/MultiSelect/MultiSelect.js +70 -207
  9. package/components/MultiSelect/types.d.ts +5 -8
  10. package/components/SearchSelect/SearchSelect.d.ts +34 -0
  11. package/components/SearchSelect/SearchSelect.js +462 -0
  12. package/components/SearchSelect/SearchSelectContext.d.ts +7 -0
  13. package/components/SearchSelect/SearchSelectContext.js +21 -0
  14. package/components/SearchSelect/index.d.ts +2 -0
  15. package/components/SearchSelect/index.js +1 -0
  16. package/components/SearchSelect/types.d.ts +153 -0
  17. package/components/SearchSelect/types.js +5 -0
  18. package/components/Select/Select.d.ts +16 -11
  19. package/components/Select/Select.js +78 -237
  20. package/components/Select/types.d.ts +5 -8
  21. package/components/index.d.ts +2 -0
  22. package/components/index.js +1 -0
  23. package/package.json +5 -1
  24. package/styles/all.css +1 -1
  25. package/styles/all.expanded.css +180 -0
  26. package/styles/all.expanded.unlayered.css +180 -0
  27. package/styles/all.unlayered.css +1 -1
  28. package/styles/components/_bundle.scss +8 -4
  29. package/styles/components/search-select.scss +244 -0
  30. package/tui-manifest.json +74 -2
  31. package/utils/listbox/blur.d.ts +14 -0
  32. package/utils/listbox/blur.js +51 -0
  33. package/utils/listbox/filter-active-index.d.ts +16 -0
  34. package/utils/listbox/filter-active-index.js +72 -0
  35. package/utils/listbox/floating.d.ts +7 -0
  36. package/utils/listbox/floating.js +34 -0
  37. package/utils/listbox/group.d.ts +26 -0
  38. package/utils/listbox/group.js +40 -0
  39. package/utils/listbox/ids.d.ts +9 -0
  40. package/utils/listbox/ids.js +31 -0
  41. package/utils/listbox/index.d.ts +9 -0
  42. package/utils/listbox/index.js +11 -0
  43. package/utils/listbox/navigation.d.ts +27 -0
  44. package/utils/listbox/navigation.js +53 -0
  45. package/utils/listbox/registry.d.ts +61 -0
  46. package/utils/listbox/registry.js +121 -0
  47. package/utils/listbox/scroll.d.ts +7 -0
  48. package/utils/listbox/scroll.js +15 -0
  49. package/utils/listbox/trigger.d.ts +16 -0
  50. package/utils/listbox/trigger.js +35 -0
@@ -0,0 +1,462 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
3
+ import { FloatingPortal } from '@floating-ui/react';
4
+ import { cx } from '../../utils/cx.js';
5
+ import { toKey } from '../../utils/value-key.js';
6
+ import { getPortalRootFor } from '../../utils/portal.js';
7
+ import { useOptionRegistry, useOptionRegistration, deriveOptionText, useListboxIds, useListboxFloating, useListboxNavigation, useListboxBlurGuard, useTriggerPointerDownFix, useFilterStableActiveIndex, useActiveOptionScroll, optionIdForValue, createListboxGroupComponents, } from '../../utils/listbox/index.js';
8
+ import { Icon } from '../Icon/index.js';
9
+ import { SearchInput } from '../SearchInput/index.js';
10
+ import { SearchSelectContext, SearchSelectContentContext, useSearchSelectContext, useSearchSelectContentContext, } from './SearchSelectContext.js';
11
+ import { defaultSearchSelectLabels, } from './types.js';
12
+ // Default filter: case-insensitive substring on textValue.
13
+ const defaultFilter = (textValue, query) => textValue.toLowerCase().includes(query.trim().toLowerCase());
14
+ // =============================================================================
15
+ // SearchSelect Root
16
+ // =============================================================================
17
+ function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange, open: controlledOpen, defaultOpen, onOpenChange, inputValue: controlledInputValue, onInputChange, filter = defaultFilter, disabled = false, placeholder = '', size = 'md', anchorRef, restoreFocusRef, id: triggerIdProp, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, 'aria-required': ariaRequired, labels: labelsProp, children, }) {
18
+ const labels = { ...defaultSearchSelectLabels, ...labelsProp };
19
+ // Controlled/uncontrolled value — lock decision at mount time (see the
20
+ // controlled→uncontrolled gotcha in CLAUDE.md)
21
+ const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);
22
+ const isValueControlled = useRef(controlledValue !== undefined).current;
23
+ const value = isValueControlled ? controlledValue : uncontrolledValue;
24
+ // Every label ever registered, NEVER pruned. Filtering unregisters options
25
+ // while the panel is open, so the closed-unregister skip alone can't keep
26
+ // the trigger label alive — an abandoned search would degrade the label to
27
+ // the raw value key. Populated from the registry below and at commit time.
28
+ const knownLabelsRef = useRef(new Map());
29
+ // Controlled/uncontrolled open
30
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen ?? false);
31
+ const isOpenControlled = controlledOpen !== undefined;
32
+ const open = isOpenControlled ? controlledOpen : uncontrolledOpen;
33
+ // Render-fresh mirror so setOpen can be idempotent without churning identity
34
+ const openStateRef = useRef(open);
35
+ openStateRef.current = open;
36
+ // The trigger ELEMENT (not the Floating UI domReference — that's the search
37
+ // input, see the floating setup below). Used for focus return, the portal
38
+ // root, the blur-guard extra container, and the dismiss exclusion.
39
+ const triggerElRef = useRef(null);
40
+ // Controlled/uncontrolled search text — TRANSIENT: reset when the panel closes
41
+ const [uncontrolledInputValue, setUncontrolledInputValue] = useState('');
42
+ const isInputControlled = controlledInputValue !== undefined;
43
+ const inputValue = isInputControlled ? controlledInputValue : uncontrolledInputValue;
44
+ const query = inputValue;
45
+ const setOpen = useCallback((nextOpen) => {
46
+ // Idempotent: Floating UI's dismiss and our own Escape/blur handlers can
47
+ // both fire for one interaction — collapse the duplicate onOpenChange.
48
+ // The ref tracks the latest REQUESTED state (assigned below, before any
49
+ // re-render): both handlers run in the same event batch, so comparing
50
+ // against rendered state alone wouldn't catch the duplicate.
51
+ if (nextOpen === openStateRef.current)
52
+ return;
53
+ // disabled blocks OPENING only — a form disabling its controls while
54
+ // the panel is open must still be able to close it.
55
+ if (disabled && nextOpen)
56
+ return;
57
+ openStateRef.current = nextOpen;
58
+ if (!isOpenControlled) {
59
+ setUncontrolledOpen(nextOpen);
60
+ }
61
+ onOpenChange?.(nextOpen);
62
+ }, [disabled, isOpenControlled, onOpenChange]);
63
+ const setInputValue = useCallback((nextValue) => {
64
+ if (!isInputControlled) {
65
+ setUncontrolledInputValue(nextValue);
66
+ }
67
+ onInputChange?.(nextValue);
68
+ }, [isInputControlled, onInputChange]);
69
+ // Shared option registry (listbox engine)
70
+ const { registerOption, unregisterOption, orderedOptions, optionIndexMap } = useOptionRegistry({
71
+ open,
72
+ });
73
+ // Harvest every registered label into the persistent map (see knownLabelsRef)
74
+ useEffect(() => {
75
+ for (const opt of orderedOptions) {
76
+ knownLabelsRef.current.set(toKey(opt.value), opt.textValue);
77
+ }
78
+ }, [orderedOptions]);
79
+ // IDs — the panel is a dialog, so it gets its own id for aria-controls
80
+ const { controlId: triggerId, listboxId } = useListboxIds(triggerIdProp, 'trigger');
81
+ const panelId = `${listboxId}-panel`;
82
+ // Refs
83
+ const inputRef = useRef(null);
84
+ const listRef = useRef([]);
85
+ // Active index for navigation (-1 means no active option)
86
+ const [activeIndex, setActiveIndex] = useState(-1);
87
+ const returnFocus = useCallback(() => {
88
+ ;
89
+ (restoreFocusRef?.current ?? triggerElRef.current)?.focus();
90
+ }, [restoreFocusRef]);
91
+ // Commit a value: capture label, close, reset the query, hand focus back
92
+ const selectValue = useCallback((optionValue, textValue) => {
93
+ knownLabelsRef.current.set(toKey(optionValue), textValue);
94
+ if (!isValueControlled) {
95
+ setUncontrolledValue(optionValue);
96
+ }
97
+ onValueChange?.(optionValue);
98
+ setOpen(false);
99
+ }, [isValueControlled, onValueChange, setOpen]);
100
+ // Trigger label: from the persistent label map (populated by registration —
101
+ // the hidden pre-open render covers defaultValue — and at commit), else the
102
+ // live registry, else the raw value.
103
+ const labelFor = useCallback((optionValue) => {
104
+ const key = toKey(optionValue);
105
+ return (knownLabelsRef.current.get(key) ??
106
+ orderedOptions.find((o) => toKey(o.value) === key)?.textValue ??
107
+ String(optionValue));
108
+ }, [orderedOptions]);
109
+ // Reset the transient query when the panel closes
110
+ const prevOpenRef = useRef(open);
111
+ useEffect(() => {
112
+ if (prevOpenRef.current && !open && inputValue !== '') {
113
+ setInputValue('');
114
+ }
115
+ prevOpenRef.current = open;
116
+ }, [open, inputValue, setInputValue]);
117
+ // Compute disabled indices for keyboard navigation
118
+ const disabledIndices = useMemo(() => orderedOptions.reduce((acc, opt, i) => {
119
+ if (opt.disabled)
120
+ acc.push(i);
121
+ return acc;
122
+ }, []), [orderedOptions]);
123
+ // Floating UI setup. The split: the TRIGGER is the POSITION reference (the
124
+ // panel anchors/sizes to it) while the search input is the DOM reference —
125
+ // Floating UI's isTypeableCombobox() reads role="combobox" off the DOM
126
+ // reference, and only then does useListNavigation leave Home/End to the
127
+ // text caret instead of hijacking them for first/last-option jumps.
128
+ const { refs, floatingStyles, context } = useListboxFloating({
129
+ open,
130
+ onOpenChange: setOpen,
131
+ });
132
+ // Shared interaction stack — no click (the trigger has its own onClick so a
133
+ // click on the open trigger closes rather than re-opening) and no typeahead
134
+ // (typing IS the search). The trigger is excluded from outside-press
135
+ // dismissal: it isn't the domReference, so without the exclusion dismiss
136
+ // would close on pointerdown and the trigger's click would re-open.
137
+ const { getReferenceProps, getFloatingProps, getItemProps } = useListboxNavigation(context, {
138
+ listRef,
139
+ activeIndex: activeIndex >= 0 ? activeIndex : null,
140
+ onNavigate: (index) => setActiveIndex(index ?? -1),
141
+ disabledIndices,
142
+ withClick: false,
143
+ dismissOutsidePress: (event) => {
144
+ const toggleEl = restoreFocusRef?.current ?? triggerElRef.current;
145
+ return !(toggleEl && event.target instanceof Node && toggleEl.contains(event.target));
146
+ },
147
+ });
148
+ // EXTERNAL-TRIGGER MODE: anchor the panel to the provided element instead
149
+ // of the built-in Trigger (re-checked on every open — the anchor can mount
150
+ // late). Focus returns via restoreFocusRef (usually the opening button).
151
+ useEffect(() => {
152
+ if (anchorRef?.current) {
153
+ refs.setPositionReference(anchorRef.current);
154
+ }
155
+ // refs is stable; re-run on open so late-mounted anchors are picked up
156
+ // eslint-disable-next-line react-hooks/exhaustive-deps
157
+ }, [open, anchorRef]);
158
+ // Active option ID for aria-activedescendant (hash-based — filtering shifts indices)
159
+ const activeOptionId = activeIndex >= 0 && orderedOptions[activeIndex]
160
+ ? optionIdForValue(listboxId, orderedOptions[activeIndex].value)
161
+ : undefined;
162
+ // Keep the highlighted OPTION stable as filtering shifts indices (engine)
163
+ useFilterStableActiveIndex({ open, orderedOptions, activeIndex, setActiveIndex, listRef });
164
+ // Scroll active option into view
165
+ useActiveOptionScroll(open, activeIndex, listRef);
166
+ // Focus loss — attached at the PANEL level (blur bubbles as focusout), so it
167
+ // covers every descendant: the input, the search clear button, anything a
168
+ // future panel grows. Moving within the panel stays open; the trigger is the
169
+ // extra container (blurring to it must not close — its own onClick performs
170
+ // the toggle without a close/re-open flicker); anything else closes.
171
+ const handlePanelBlur = useListboxBlurGuard({
172
+ open,
173
+ setOpen,
174
+ floatingRef: refs.floating,
175
+ extraContainerRef: restoreFocusRef ?? triggerElRef,
176
+ });
177
+ const handleInputKeyDown = useCallback((e) => {
178
+ if (e.key === 'Enter') {
179
+ e.preventDefault();
180
+ if (activeIndex >= 0) {
181
+ const option = orderedOptions[activeIndex];
182
+ if (option && !option.disabled) {
183
+ selectValue(option.value, option.textValue);
184
+ returnFocus();
185
+ }
186
+ }
187
+ return;
188
+ }
189
+ if (e.key === 'Escape') {
190
+ // NOTE on ordering: Floating UI composes user handlers LAST, so
191
+ // useDismiss's Escape has already called setOpen(false) by the time
192
+ // this runs — setOpen's idempotence collapses the duplicate. This
193
+ // handler's real jobs are the focus return and stopPropagation
194
+ // (suppresses the document-level dismiss listener).
195
+ e.preventDefault();
196
+ e.stopPropagation();
197
+ setOpen(false);
198
+ returnFocus();
199
+ }
200
+ }, [activeIndex, orderedOptions, selectValue, setOpen, returnFocus]);
201
+ const contextValue = useMemo(() => ({
202
+ disabled,
203
+ placeholder,
204
+ size,
205
+ labels,
206
+ triggerId,
207
+ listboxId,
208
+ panelId,
209
+ ariaLabel,
210
+ ariaLabelledBy,
211
+ ariaDescribedBy,
212
+ ariaInvalid,
213
+ ariaRequired,
214
+ setOpen,
215
+ selectValue,
216
+ setInputValue,
217
+ registerOption,
218
+ unregisterOption,
219
+ labelFor,
220
+ returnFocus,
221
+ handlePanelBlur,
222
+ handleInputKeyDown,
223
+ refs,
224
+ triggerElRef,
225
+ anchorRef,
226
+ inputRef,
227
+ listRef,
228
+ optionIndexMap,
229
+ context,
230
+ getReferenceProps,
231
+ getFloatingProps,
232
+ getItemProps,
233
+ open,
234
+ value,
235
+ inputValue,
236
+ query,
237
+ filter,
238
+ activeIndex,
239
+ activeOptionId,
240
+ orderedOptions,
241
+ floatingStyles,
242
+ }),
243
+ // labels is a fresh object each render but derives from labelsProp
244
+ // eslint-disable-next-line react-hooks/exhaustive-deps
245
+ [
246
+ disabled,
247
+ placeholder,
248
+ size,
249
+ labelsProp,
250
+ triggerId,
251
+ listboxId,
252
+ panelId,
253
+ ariaLabel,
254
+ ariaLabelledBy,
255
+ ariaDescribedBy,
256
+ ariaInvalid,
257
+ ariaRequired,
258
+ setOpen,
259
+ selectValue,
260
+ setInputValue,
261
+ registerOption,
262
+ unregisterOption,
263
+ labelFor,
264
+ returnFocus,
265
+ handlePanelBlur,
266
+ handleInputKeyDown,
267
+ refs,
268
+ optionIndexMap,
269
+ context,
270
+ getReferenceProps,
271
+ getFloatingProps,
272
+ getItemProps,
273
+ open,
274
+ value,
275
+ inputValue,
276
+ query,
277
+ filter,
278
+ activeIndex,
279
+ activeOptionId,
280
+ orderedOptions,
281
+ floatingStyles,
282
+ ]);
283
+ return (_jsx(SearchSelectContext.Provider, { value: contextValue, children: _jsx("div", { className: "tui-search-select", children: children }) }));
284
+ }
285
+ SearchSelectRoot.displayName = 'SearchSelect';
286
+ // =============================================================================
287
+ // SearchSelect.Trigger
288
+ // =============================================================================
289
+ function SearchSelectTriggerComponent({ className, children, onClick: onClickProp, onKeyDown: onKeyDownProp, onPointerDown: onPointerDownProp, ...rest }) {
290
+ const { disabled, placeholder, size, triggerId, panelId, ariaLabel, ariaLabelledBy, ariaDescribedBy, ariaInvalid, ariaRequired, setOpen, labelFor, refs, triggerElRef, open, value, } = useSearchSelectContext();
291
+ const hasValue = value !== undefined;
292
+ const valueId = `${triggerId}-value`;
293
+ // The trigger is the POSITION reference (the panel anchors to it); the
294
+ // search input is the DOM reference. Keep our own element ref for focus
295
+ // return / portal root / dismiss exclusion.
296
+ const handleRef = useCallback((node) => {
297
+ triggerElRef.current = node;
298
+ refs.setPositionReference(node);
299
+ }, [refs, triggerElRef]);
300
+ const handleClick = useCallback((e) => {
301
+ onClickProp?.(e);
302
+ if (e.defaultPrevented)
303
+ return;
304
+ setOpen(!open);
305
+ }, [open, setOpen, onClickProp]);
306
+ const handleKeyDown = useCallback((e) => {
307
+ onKeyDownProp?.(e);
308
+ if (e.defaultPrevented)
309
+ return;
310
+ // Enter/Space activate the button natively (click). ArrowDown also opens.
311
+ if (e.key === 'ArrowDown' && !open) {
312
+ e.preventDefault();
313
+ setOpen(true);
314
+ }
315
+ }, [open, setOpen, onKeyDownProp]);
316
+ // Safari/Firefox on macOS don't focus buttons on click — the search input
317
+ // then blurs with relatedTarget null, the blur guard closes the panel, and
318
+ // this click immediately re-opens it: the trigger appears to never toggle
319
+ // closed. Same fix as Select's trigger: focus it ourselves on pointerdown so
320
+ // the blur lands on the trigger (the guard's stay-open container).
321
+ const pointerDownFix = useTriggerPointerDownFix();
322
+ const handlePointerDown = useCallback((e) => {
323
+ onPointerDownProp?.(e);
324
+ if (e.defaultPrevented)
325
+ return;
326
+ pointerDownFix(e);
327
+ }, [onPointerDownProp, pointerDownFix]);
328
+ return (_jsxs("button", { ...rest, ref: handleRef, type: "button", id: triggerId, className: cx('tui-search-select__trigger', size !== 'md' && `is-size-${size}`, className), disabled: disabled, "aria-haspopup": "dialog", "aria-expanded": open, "aria-controls": open ? panelId : undefined, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy ? `${ariaLabelledBy} ${valueId}` : undefined, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid, "aria-required": ariaRequired, "data-state": open ? 'open' : 'closed', onClick: handleClick, onKeyDown: handleKeyDown, onPointerDown: handlePointerDown, children: [_jsx("span", { id: valueId, className: "tui-search-select__value", children: children ??
329
+ (hasValue ? (labelFor(value)) : (_jsx("span", { className: "tui-search-select__placeholder", children: placeholder }))) }), _jsx(Icon, { name: "system/chevron-down", className: "tui-search-select__icon" })] }));
330
+ }
331
+ SearchSelectTriggerComponent.displayName = 'SearchSelect.Trigger';
332
+ // =============================================================================
333
+ // SearchSelect.Content
334
+ // =============================================================================
335
+ function SearchSelectContentComponent({ className, children }) {
336
+ const { labels, size, triggerId, listboxId, panelId, ariaLabel, setInputValue, handlePanelBlur, handleInputKeyDown, refs, triggerElRef, anchorRef, inputRef, listRef, optionIndexMap, getReferenceProps, getFloatingProps, open, inputValue, activeOptionId, orderedOptions, floatingStyles, } = useSearchSelectContext();
337
+ // Move focus into the search field when the panel opens. Callback ref, not
338
+ // an open-keyed effect: FloatingPortal can attach the subtree after the
339
+ // parent's effects run, so an effect may fire while the input is still
340
+ // unmounted. Gated per open: SearchInput composes refs into a fresh closure
341
+ // each render, so React re-invokes this on EVERY render — an ungated focus()
342
+ // would yank focus back from the clear button on any re-render.
343
+ const focusedThisOpenRef = useRef(false);
344
+ useEffect(() => {
345
+ if (!open)
346
+ focusedThisOpenRef.current = false;
347
+ }, [open]);
348
+ const handleInputRef = useCallback((node) => {
349
+ inputRef.current = node;
350
+ // The input is the Floating UI DOM reference (isTypeableCombobox reads
351
+ // role="combobox" off it — that's what frees Home/End for the caret).
352
+ refs.setReference(node);
353
+ if (node && !focusedThisOpenRef.current) {
354
+ focusedThisOpenRef.current = true;
355
+ node.focus();
356
+ }
357
+ }, [inputRef, refs]);
358
+ const { activeIndex } = useSearchSelectContext();
359
+ const contentContextValue = useMemo(() => ({ listRef, activeIndex, orderedOptions, optionIndexMap }), [listRef, activeIndex, orderedOptions, optionIndexMap]);
360
+ // Hidden pre-first-open render keeps the registry populated while closed so
361
+ // a defaultValue's trigger label resolves (same invariant as the other four
362
+ // listboxes — the listbox id must not exist twice at once).
363
+ const hasEverOpened = useRef(false);
364
+ if (open)
365
+ hasEverOpened.current = true;
366
+ if (!open && !hasEverOpened.current) {
367
+ return (_jsx("div", { style: { display: 'none' }, "aria-hidden": "true", children: _jsx("div", { id: listboxId, role: "listbox", children: _jsx(SearchSelectContentContext.Provider, { value: contentContextValue, children: children }) }) }));
368
+ }
369
+ if (!open)
370
+ return null;
371
+ return (_jsx(FloatingPortal, { root: getPortalRootFor(triggerElRef.current ?? anchorRef?.current ?? null), children: _jsxs("div", { ref: refs.setFloating, className: cx('tui-search-select__panel', className), style: floatingStyles, ...getFloatingProps(),
372
+ // AFTER the spread: useRole stamps role="listbox" and its own id on
373
+ // the floating element — this panel is a NON-MODAL dialog (no focus
374
+ // trap, no aria-modal; focus-out dismisses it via the blur guard
375
+ // below, like a combobox popup) holding a combobox + listbox. The
376
+ // trigger's aria-controls points at panelId.
377
+ id: panelId, role: "dialog", "aria-labelledby": triggerElRef.current ? triggerId : undefined, "aria-label": triggerElRef.current ? undefined : ariaLabel,
378
+ // Panel-level so blur from ANY descendant (input, search clear button,
379
+ // future panel furniture) is evaluated — input-only wiring left the
380
+ // panel orphaned open after Tab past the clear button.
381
+ onBlur: handlePanelBlur, children: [_jsx("div", { className: "tui-search-select__search", children: _jsx(SearchInput, { ref: handleInputRef, size: size === 'lg' ? 'md' : 'sm', value: inputValue, onValueChange: setInputValue, searchLabel: labels.search, clearLabel: labels.clearSearch, placeholder: labels.search, ...getReferenceProps({
382
+ onKeyDown: handleInputKeyDown,
383
+ }),
384
+ // AFTER the spread: correct the reference props for the
385
+ // combobox-in-dialog shape. aria-haspopup is useRole's listbox
386
+ // leftover — a combobox already conveys its popup via
387
+ // aria-expanded/aria-controls.
388
+ role: "combobox", "aria-haspopup": undefined, "aria-label": labels.search, "aria-expanded": "true", "aria-controls": listboxId, "aria-autocomplete": "list", "aria-activedescendant": activeOptionId }) }), _jsx("div", { id: listboxId, role: "listbox", "aria-labelledby": triggerElRef.current ? triggerId : undefined, "aria-label": triggerElRef.current ? undefined : ariaLabel, className: "tui-search-select__listbox", tabIndex: -1, children: _jsx(SearchSelectContentContext.Provider, { value: contentContextValue, children: children }) }), orderedOptions.length === 0 && (_jsx("div", { role: "status", className: "tui-search-select__empty", children: labels.noResults }))] }) }));
389
+ }
390
+ SearchSelectContentComponent.displayName = 'SearchSelect.Content';
391
+ // =============================================================================
392
+ // SearchSelect.Option
393
+ // =============================================================================
394
+ function SearchSelectOptionComponent({ value: optionValue, disabled = false, textValue: explicitTextValue, className, children, }) {
395
+ const { value: selectedValue, selectValue, listboxId, registerOption, unregisterOption, getItemProps, query, filter, returnFocus, } = useSearchSelectContext();
396
+ const { listRef, activeIndex, optionIndexMap } = useSearchSelectContentContext();
397
+ const ref = useRef(null);
398
+ // Built-in filtering: a non-matching option renders null AND leaves the
399
+ // registry (enabled: false) so navigation and the empty state see the
400
+ // filtered list. `filter: false` → consumer owns filtering via children.
401
+ // Empty derived text (rich children without textValue) degrades to
402
+ // UNFILTERABLE, not invisible — ''.includes() would vanish it on the first
403
+ // keystroke. deriveOptionText is the hook's own rule, imported so the two
404
+ // can't drift.
405
+ const derivedText = deriveOptionText(children, explicitTextValue);
406
+ const visible = filter === false || query === '' || derivedText === '' || filter(derivedText, query);
407
+ const textValue = useOptionRegistration({
408
+ value: optionValue,
409
+ disabled,
410
+ textValue: explicitTextValue,
411
+ children,
412
+ componentName: 'SearchSelect.Option',
413
+ elementRef: ref,
414
+ registerOption,
415
+ unregisterOption,
416
+ enabled: visible,
417
+ });
418
+ // O(1) index lookup via the registry's map
419
+ const index = optionIndexMap.get(toKey(optionValue)) ?? -1;
420
+ // Assign ref to listRef for navigation
421
+ useEffect(() => {
422
+ if (index >= 0) {
423
+ listRef.current[index] = ref.current;
424
+ }
425
+ }, [index, listRef]);
426
+ const isSelected = selectedValue !== undefined && toKey(selectedValue) === toKey(optionValue);
427
+ const isHighlighted = index >= 0 && activeIndex === index;
428
+ const handleClick = useCallback(() => {
429
+ if (disabled)
430
+ return;
431
+ selectValue(optionValue, textValue);
432
+ returnFocus();
433
+ }, [disabled, optionValue, textValue, selectValue, returnFocus]);
434
+ // Prevent the input losing focus when clicking an option
435
+ const handlePointerDown = useCallback((e) => {
436
+ e.preventDefault();
437
+ }, []);
438
+ if (!visible)
439
+ return null;
440
+ return (_jsxs("div", { ref: ref, id: optionIdForValue(listboxId, optionValue), role: "option", className: cx('tui-search-select__option', className), "aria-selected": isSelected, "aria-disabled": disabled || undefined, "data-highlighted": isHighlighted || undefined, "data-disabled": disabled || undefined, ...getItemProps({
441
+ onClick: handleClick,
442
+ onPointerDown: handlePointerDown,
443
+ }), children: [_jsx("span", { className: "tui-search-select__option-content", children: children }), isSelected && _jsx(Icon, { name: "system/check", className: "tui-search-select__option-check" })] }));
444
+ }
445
+ SearchSelectOptionComponent.displayName = 'SearchSelect.Option';
446
+ // =============================================================================
447
+ // SearchSelect.Group / SearchSelect.Label (shared engine pair)
448
+ // =============================================================================
449
+ const { Group: SearchSelectGroupComponent, Label: SearchSelectLabelComponent } = createListboxGroupComponents({
450
+ componentName: 'SearchSelect',
451
+ groupClass: 'tui-search-select__group',
452
+ labelClass: 'tui-search-select__label',
453
+ });
454
+ const SearchSelect = SearchSelectRoot;
455
+ SearchSelect.Trigger = SearchSelectTriggerComponent;
456
+ SearchSelect.Content = SearchSelectContentComponent;
457
+ SearchSelect.Option = SearchSelectOptionComponent;
458
+ SearchSelect.Group = SearchSelectGroupComponent;
459
+ SearchSelect.Label = SearchSelectLabelComponent;
460
+ export { SearchSelect, SearchSelectTriggerComponent as SearchSelectTrigger, SearchSelectContentComponent as SearchSelectContent, SearchSelectOptionComponent as SearchSelectOption, SearchSelectGroupComponent as SearchSelectGroup, SearchSelectLabelComponent as SearchSelectLabel, };
461
+ // eslint-disable-next-line react-refresh/only-export-components
462
+ export { useSearchSelect } from './SearchSelectContext.js';
@@ -0,0 +1,7 @@
1
+ import type { SearchSelectContextValue, SearchSelectContentContextValue } from './types';
2
+ export declare const SearchSelectContext: import("react").Context<SearchSelectContextValue | null>;
3
+ export declare function useSearchSelectContext(): SearchSelectContextValue;
4
+ /** Public escape hatch, mirroring useSelect/useCombobox. */
5
+ export declare function useSearchSelect(): SearchSelectContextValue;
6
+ export declare const SearchSelectContentContext: import("react").Context<SearchSelectContentContextValue | null>;
7
+ export declare function useSearchSelectContentContext(): SearchSelectContentContextValue;
@@ -0,0 +1,21 @@
1
+ import { createContext, useContext } from 'react';
2
+ export const SearchSelectContext = createContext(null);
3
+ export function useSearchSelectContext() {
4
+ const context = useContext(SearchSelectContext);
5
+ if (!context) {
6
+ throw new Error('SearchSelect components must be used within <SearchSelect>');
7
+ }
8
+ return context;
9
+ }
10
+ /** Public escape hatch, mirroring useSelect/useCombobox. */
11
+ export function useSearchSelect() {
12
+ return useSearchSelectContext();
13
+ }
14
+ export const SearchSelectContentContext = createContext(null);
15
+ export function useSearchSelectContentContext() {
16
+ const context = useContext(SearchSelectContentContext);
17
+ if (!context) {
18
+ throw new Error('SearchSelect.Option must be used within <SearchSelect.Content>');
19
+ }
20
+ return context;
21
+ }
@@ -0,0 +1,2 @@
1
+ export { SearchSelect, SearchSelectTrigger, SearchSelectContent, SearchSelectOption, SearchSelectGroup, SearchSelectLabel, useSearchSelect, } from './SearchSelect';
2
+ export type { SearchSelectProps, SearchSelectTriggerProps, SearchSelectContentProps, SearchSelectOptionProps, SearchSelectGroupProps, SearchSelectLabelProps, SearchSelectLabels, } from './types';
@@ -0,0 +1 @@
1
+ export { SearchSelect, SearchSelectTrigger, SearchSelectContent, SearchSelectOption, SearchSelectGroup, SearchSelectLabel, useSearchSelect, } from './SearchSelect.js';
@@ -0,0 +1,153 @@
1
+ import type { CSSProperties, MutableRefObject, ReactNode, RefObject } from 'react';
2
+ import type { FloatingContext, ReferenceType } from '@floating-ui/react';
3
+ import type { SizeStandard } from '../../types/sizes';
4
+ import type { OptionValue } from '../../utils/value-key';
5
+ export type SearchSelectLabels = {
6
+ /** Placeholder AND accessible name for the search field. @default 'Search' */
7
+ search?: string;
8
+ /** Clear-search button label (forwarded to the embedded SearchInput). @default 'Clear search' */
9
+ clearSearch?: string;
10
+ /** Empty-state text when no options match. @default 'No results' */
11
+ noResults?: string;
12
+ };
13
+ export declare const defaultSearchSelectLabels: Required<SearchSelectLabels>;
14
+ export type SearchSelectProps = {
15
+ /** Controlled selected value. */
16
+ value?: OptionValue;
17
+ /** Uncontrolled initial value. */
18
+ defaultValue?: OptionValue;
19
+ /** Fires with the committed option value. */
20
+ onValueChange?: (value: OptionValue) => void;
21
+ /** Controlled open state. */
22
+ open?: boolean;
23
+ /** @default false */
24
+ defaultOpen?: boolean;
25
+ onOpenChange?: (open: boolean) => void;
26
+ /**
27
+ * Controlled search text. Usually uncontrolled — the query is transient and
28
+ * resets when the panel closes.
29
+ */
30
+ inputValue?: string;
31
+ /** Fires as the user types (and on the reset-on-close). */
32
+ onInputChange?: (value: string) => void;
33
+ /**
34
+ * Built-in filtering: options whose textValue fails this test against the
35
+ * query unmount. Pass `false` to disable and own the filtering by rendering
36
+ * a different set of Options (async lists).
37
+ * @default case-insensitive substring match on textValue
38
+ */
39
+ filter?: false | ((textValue: string, query: string) => boolean);
40
+ /** @default false */
41
+ disabled?: boolean;
42
+ /** Trigger text when nothing is selected. @default '' */
43
+ placeholder?: string;
44
+ /** Control size for the trigger. @default 'md' */
45
+ size?: SizeStandard;
46
+ /** Trigger id — Field.Control injects this. */
47
+ id?: string;
48
+ /**
49
+ * EXTERNAL-TRIGGER MODE: anchor the panel to this element instead of the
50
+ * built-in Trigger. Use with controlled `open`/`onOpenChange` and no
51
+ * `<SearchSelect.Trigger>` — e.g. an IconButton that opens a picker panel
52
+ * under its host field. Provide `aria-label` (the panel's name — the
53
+ * trigger-labelled path doesn't exist here) and wire the external button's
54
+ * own aria-haspopup/aria-expanded.
55
+ */
56
+ anchorRef?: React.RefObject<HTMLElement | null>;
57
+ /**
58
+ * External-trigger mode: where focus returns on commit/Escape (usually the
59
+ * button that opened the panel). Blur onto this element keeps the panel
60
+ * open, so the button's own click handler can toggle without flicker.
61
+ */
62
+ restoreFocusRef?: React.RefObject<HTMLElement | null>;
63
+ 'aria-label'?: string;
64
+ 'aria-labelledby'?: string;
65
+ 'aria-describedby'?: string;
66
+ 'aria-invalid'?: boolean | 'true' | 'false';
67
+ 'aria-required'?: boolean | 'true' | 'false';
68
+ labels?: SearchSelectLabels;
69
+ children: ReactNode;
70
+ };
71
+ export type SearchSelectTriggerProps = {
72
+ className?: string;
73
+ /**
74
+ * Custom trigger content — replaces the default value/placeholder text
75
+ * (the chevron stays). The fields dynamic-value picker renders its
76
+ * bolt + type + key pill here. NOTE: with an `aria-label` on the Root the
77
+ * accessible name is frozen to that label — custom content is then
78
+ * invisible to AT (family-wide follow-up in the roadmap).
79
+ */
80
+ children?: ReactNode;
81
+ } & Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'className'>;
82
+ export type SearchSelectContentProps = {
83
+ className?: string;
84
+ children?: ReactNode;
85
+ };
86
+ export type SearchSelectOptionProps = {
87
+ value: OptionValue;
88
+ disabled?: boolean;
89
+ /** Required when children is not a plain string. */
90
+ textValue?: string;
91
+ className?: string;
92
+ children?: ReactNode;
93
+ };
94
+ export type { ListboxGroupProps as SearchSelectGroupProps } from '../../utils/listbox';
95
+ export type { ListboxLabelProps as SearchSelectLabelProps } from '../../utils/listbox';
96
+ import type { RegisteredOption } from '../../utils/listbox';
97
+ export type { RegisteredOption };
98
+ export type SearchSelectContextValue = {
99
+ disabled: boolean;
100
+ placeholder: string;
101
+ size: SizeStandard;
102
+ labels: Required<SearchSelectLabels>;
103
+ triggerId: string;
104
+ listboxId: string;
105
+ panelId: string;
106
+ ariaLabel?: string;
107
+ ariaLabelledBy?: string;
108
+ ariaDescribedBy?: string;
109
+ ariaInvalid?: boolean | 'true' | 'false';
110
+ ariaRequired?: boolean | 'true' | 'false';
111
+ setOpen: (open: boolean) => void;
112
+ selectValue: (value: OptionValue, textValue: string) => void;
113
+ setInputValue: (value: string) => void;
114
+ registerOption: (option: RegisteredOption) => void;
115
+ unregisterOption: (optionValue: OptionValue) => void;
116
+ labelFor: (value: OptionValue) => string;
117
+ /** Focus the trigger (or restoreFocusRef in external-trigger mode). */
118
+ returnFocus: () => void;
119
+ handlePanelBlur: (e: React.FocusEvent) => void;
120
+ handleInputKeyDown: (e: React.KeyboardEvent) => void;
121
+ refs: {
122
+ reference: RefObject<ReferenceType | null>;
123
+ floating: RefObject<HTMLElement | null>;
124
+ setReference: (node: ReferenceType | null) => void;
125
+ setPositionReference: (node: ReferenceType | null) => void;
126
+ setFloating: (node: HTMLElement | null) => void;
127
+ };
128
+ triggerElRef: MutableRefObject<HTMLButtonElement | null>;
129
+ /** External-trigger mode anchor (see SearchSelectProps.anchorRef). */
130
+ anchorRef?: React.RefObject<HTMLElement | null>;
131
+ inputRef: MutableRefObject<HTMLInputElement | null>;
132
+ listRef: MutableRefObject<(HTMLElement | null)[]>;
133
+ optionIndexMap: Map<string, number>;
134
+ context: FloatingContext;
135
+ getReferenceProps: (userProps?: React.HTMLProps<Element>) => Record<string, unknown>;
136
+ getFloatingProps: (userProps?: React.HTMLProps<HTMLElement>) => Record<string, unknown>;
137
+ getItemProps: (userProps?: React.HTMLProps<HTMLElement>) => Record<string, unknown>;
138
+ open: boolean;
139
+ value: OptionValue | undefined;
140
+ inputValue: string;
141
+ query: string;
142
+ filter: false | ((textValue: string, query: string) => boolean);
143
+ activeIndex: number;
144
+ activeOptionId: string | undefined;
145
+ orderedOptions: RegisteredOption[];
146
+ floatingStyles: CSSProperties;
147
+ };
148
+ export type SearchSelectContentContextValue = {
149
+ listRef: MutableRefObject<(HTMLElement | null)[]>;
150
+ activeIndex: number;
151
+ orderedOptions: RegisteredOption[];
152
+ optionIndexMap: Map<string, number>;
153
+ };
@@ -0,0 +1,5 @@
1
+ export const defaultSearchSelectLabels = {
2
+ search: 'Search',
3
+ clearSearch: 'Clear search',
4
+ noResults: 'No results',
5
+ };