@tangible/ui 0.2.41 → 0.2.42

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 (58) hide show
  1. package/components/CommandPalette/CommandPalette.d.ts +30 -0
  2. package/components/CommandPalette/CommandPalette.js +409 -0
  3. package/components/CommandPalette/CommandPaletteContext.d.ts +31 -0
  4. package/components/CommandPalette/CommandPaletteContext.js +8 -0
  5. package/components/CommandPalette/index.d.ts +3 -0
  6. package/components/CommandPalette/index.js +2 -0
  7. package/components/CommandPalette/shortcut.d.ts +15 -0
  8. package/components/CommandPalette/shortcut.js +83 -0
  9. package/components/CommandPalette/types.d.ts +152 -0
  10. package/components/CommandPalette/types.js +16 -0
  11. package/components/IconTile/IconTile.d.ts +16 -0
  12. package/components/IconTile/IconTile.js +17 -0
  13. package/components/IconTile/index.d.ts +2 -0
  14. package/components/IconTile/index.js +1 -0
  15. package/components/IconTile/types.d.ts +29 -0
  16. package/components/IconTile/types.js +1 -0
  17. package/components/SegmentedControl/SegmentedControl.js +2 -2
  18. package/components/SegmentedControl/types.d.ts +10 -0
  19. package/components/Table/DataTable.js +1 -1
  20. package/components/Table/types.d.ts +6 -0
  21. package/components/Table/types.js +3 -0
  22. package/components/index.d.ts +4 -0
  23. package/components/index.js +2 -0
  24. package/figma-tokens.json +101 -3
  25. package/icons/icons.svg +1 -1
  26. package/icons/sprite-version.js +1 -1
  27. package/icons/sprite.php +1 -1
  28. package/package.json +13 -1
  29. package/skills/building-with-tui/SKILL.md +15 -1
  30. package/styles/all.css +1 -1
  31. package/styles/all.expanded.css +514 -63
  32. package/styles/all.expanded.unlayered.css +514 -63
  33. package/styles/all.unlayered.css +1 -1
  34. package/styles/components/_bundle.scss +8 -0
  35. package/styles/components/avatar.scss +6 -23
  36. package/styles/components/button.scss +15 -15
  37. package/styles/components/chip.scss +35 -11
  38. package/styles/components/command-palette.scss +314 -0
  39. package/styles/components/content-indicator.scss +6 -1
  40. package/styles/components/date-picker.scss +1 -1
  41. package/styles/components/icon-button.scss +6 -7
  42. package/styles/components/icon-tile.scss +89 -0
  43. package/styles/components/input/index.scss +4 -0
  44. package/styles/components/multi-select.scss +1 -1
  45. package/styles/components/progress.scss +23 -0
  46. package/styles/components/segmented-control.scss +11 -1
  47. package/styles/components/step-indicator.scss +1 -1
  48. package/styles/components/tabs.scss +1 -1
  49. package/styles/core.css +1 -1
  50. package/styles/core.unlayered.css +1 -1
  51. package/styles/system/_constants.scss +5 -0
  52. package/styles/system/_palettes.scss +1 -0
  53. package/styles/system/_tokens.scss +40 -1
  54. package/tui-manifest.json +166 -2
  55. package/utils/color/theme.d.ts +66 -0
  56. package/utils/color/theme.js +232 -0
  57. package/vanilla/styles.css +1 -1
  58. package/vanilla/styles.unlayered.css +1 -1
@@ -0,0 +1,30 @@
1
+ import React from 'react';
2
+ import { type CommandPaletteItemProps, type CommandPaletteProps } from './types';
3
+ declare function CommandPaletteRoot({ open: controlledOpen, defaultOpen, onOpenChange, inputValue: controlledInputValue, onInputChange, filter, onSelect, status, onRetry, shortcut, showHints, restoreFocusTo, labels: labelsProp, className, children, ...rest }: CommandPaletteProps): import("react/jsx-runtime").JSX.Element;
4
+ declare namespace CommandPaletteRoot {
5
+ var displayName: string;
6
+ }
7
+ declare function CommandPaletteItemComponent({ value, textValue: explicitTextValue, keywords, icon, description, href, keepOpen, disabled, className, children, }: CommandPaletteItemProps): import("react/jsx-runtime").JSX.Element | null;
8
+ declare namespace CommandPaletteItemComponent {
9
+ var displayName: string;
10
+ }
11
+ declare const CommandPaletteGroupComponent: {
12
+ ({ className, children }: import("..").SearchSelectGroupProps): import("react/jsx-runtime").JSX.Element;
13
+ displayName: string;
14
+ }, CommandPaletteLabelComponent: {
15
+ ({ className, children }: import("..").SearchSelectLabelProps): import("react/jsx-runtime").JSX.Element;
16
+ displayName: string;
17
+ };
18
+ declare const CommandPaletteTriggerComponent: React.ForwardRefExoticComponent<Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "children" | "type"> & {
19
+ children?: React.ReactNode;
20
+ shortcut?: string;
21
+ size?: import("..").SizeStandard;
22
+ } & React.RefAttributes<HTMLButtonElement>>;
23
+ type CommandPaletteCompound = typeof CommandPaletteRoot & {
24
+ Item: typeof CommandPaletteItemComponent;
25
+ Group: typeof CommandPaletteGroupComponent;
26
+ Label: typeof CommandPaletteLabelComponent;
27
+ Trigger: typeof CommandPaletteTriggerComponent;
28
+ };
29
+ declare const CommandPalette: CommandPaletteCompound;
30
+ export { CommandPalette, CommandPaletteItemComponent as CommandPaletteItem, CommandPaletteGroupComponent as CommandPaletteGroup, CommandPaletteLabelComponent as CommandPaletteLabel, CommandPaletteTriggerComponent as CommandPaletteTrigger, };
@@ -0,0 +1,409 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, } from 'react';
3
+ import { cx } from '../../utils/cx.js';
4
+ import { isDev } from '../../utils/is-dev.js';
5
+ import { toKey } from '../../utils/value-key.js';
6
+ import { useOptionRegistry, useOptionRegistration, deriveOptionText, useFilterStableActiveIndex, useActiveOptionScroll, optionIdForValue, createListboxGroupComponents, } from '../../utils/listbox/index.js';
7
+ import { Modal } from '../Modal/index.js';
8
+ import { Button } from '../Button/index.js';
9
+ import { Icon } from '../Icon/index.js';
10
+ import { Search as SearchIcon } from '../../icons/system/index.js';
11
+ import { CommandPaletteContext, useCommandPaletteContext, } from './CommandPaletteContext.js';
12
+ import { ariaShortcut, formatShortcut, isApplePlatform, isTypingTarget, matchesShortcut, parseShortcut, } from './shortcut.js';
13
+ import { defaultCommandPaletteLabels, } from './types.js';
14
+ // =============================================================================
15
+ // CommandPalette
16
+ // =============================================================================
17
+ //
18
+ // A modal search: a combobox (the field) controlling a listbox (the results),
19
+ // inside a Modal. APG's combobox-in-dialog shape, the same one SearchSelect's
20
+ // panel uses, minus the floating layer: the Modal owns the focus trap, scroll
21
+ // lock, portal and focus restore, so none of that is re-implemented here.
22
+ //
23
+ // The option registry, filter-stable highlight and Group/Label factory come
24
+ // from the shared listbox engine. Keyboard navigation does NOT: the engine's
25
+ // navigation stack is Floating UI's, and it needs a floating context this
26
+ // component has no use for. The field handles Up/Down/Enter itself and leaves
27
+ // Home/End to the text caret (see the Home/End hijack gotcha in CLAUDE.md).
28
+ //
29
+ // Decisions worth keeping:
30
+ // - The first result is highlighted as soon as there are results, so Enter
31
+ // takes the top hit (APG's "list autocomplete with automatic selection",
32
+ // and every palette users know). Up/Down move from there.
33
+ // - Escape closes at once, typed text or not. The text is transient anyway.
34
+ // - The registry is told the palette is always open. Its closed-state
35
+ // retention exists for Select-style triggers that read labels while closed;
36
+ // here nothing reads it while closed, and retention kept the last session's
37
+ // options alive into a reopen that renders none (stale count, a dangling
38
+ // aria-activedescendant).
39
+ //
40
+ // =============================================================================
41
+ const defaultFilter = (text, query, keywords) => {
42
+ const q = query.trim().toLowerCase();
43
+ return text.toLowerCase().includes(q) || keywords.some((k) => k.toLowerCase().includes(q));
44
+ };
45
+ /** Debounce for result-count announcements, so typing doesn't chatter. */
46
+ const ANNOUNCE_DELAY_MS = 300;
47
+ /** Only these leave the page from an href; anything else (javascript:, data:) is refused. */
48
+ function safeHref(href) {
49
+ try {
50
+ const url = new URL(href, window.location.href);
51
+ if (url.protocol === 'http:' || url.protocol === 'https:')
52
+ return href;
53
+ }
54
+ catch {
55
+ // fall through
56
+ }
57
+ if (isDev()) {
58
+ console.warn(`[TUI CommandPalette] Refusing to navigate to "${href}": only http(s) and relative URLs are followed.`);
59
+ }
60
+ return null;
61
+ }
62
+ function createActiveStore() {
63
+ let key = null;
64
+ const listeners = new Set();
65
+ return {
66
+ get: () => key,
67
+ set: (next) => {
68
+ if (next === key)
69
+ return;
70
+ key = next;
71
+ listeners.forEach((listener) => listener());
72
+ },
73
+ subscribe: (listener) => {
74
+ listeners.add(listener);
75
+ return () => listeners.delete(listener);
76
+ },
77
+ };
78
+ }
79
+ function CommandPaletteRoot({ open: controlledOpen, defaultOpen = false, onOpenChange, inputValue: controlledInputValue, onInputChange, filter = defaultFilter, onSelect, status = 'ready', onRetry, shortcut, showHints = true, restoreFocusTo, labels: labelsProp, className, children, ...rest }) {
80
+ const labels = { ...defaultCommandPaletteLabels, ...labelsProp };
81
+ const baseId = useId();
82
+ const titleId = `${baseId}-title`;
83
+ const inputId = `${baseId}-input`;
84
+ const listboxId = `${baseId}-listbox`;
85
+ const hintId = `${baseId}-hint`;
86
+ // ---- Open state: controlled or not, decided at mount ----------------------
87
+ const isOpenControlled = useRef(controlledOpen !== undefined).current;
88
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
89
+ const open = isOpenControlled ? !!controlledOpen : uncontrolledOpen;
90
+ const openRef = useRef(open);
91
+ openRef.current = open;
92
+ const onOpenChangeRef = useRef(onOpenChange);
93
+ onOpenChangeRef.current = onOpenChange;
94
+ const setOpen = useCallback((next) => {
95
+ if (!isOpenControlled)
96
+ setUncontrolledOpen(next);
97
+ onOpenChangeRef.current?.(next);
98
+ }, [isOpenControlled]);
99
+ // Controlled search text hands filtering to the consumer. Locked at mount
100
+ // (the controlled→uncontrolled gotcha): an `undefined` mid-life must not
101
+ // silently switch who filters.
102
+ const isInputControlled = useRef(controlledInputValue !== undefined).current;
103
+ const [uncontrolledInputValue, setUncontrolledInputValue] = useState('');
104
+ const query = isInputControlled ? (controlledInputValue ?? '') : uncontrolledInputValue;
105
+ const setQuery = useCallback((next) => {
106
+ if (!isInputControlled)
107
+ setUncontrolledInputValue(next);
108
+ onInputChange?.(next);
109
+ }, [isInputControlled, onInputChange]);
110
+ // A fresh palette every time: uncontrolled text resets on close.
111
+ useEffect(() => {
112
+ if (!open && !isInputControlled)
113
+ setUncontrolledInputValue('');
114
+ }, [open, isInputControlled]);
115
+ const warnedRef = useRef({ readOnly: false, filter: false, noop: false });
116
+ useEffect(() => {
117
+ if (!isDev() || !isInputControlled)
118
+ return;
119
+ if (!onInputChange && !warnedRef.current.readOnly) {
120
+ warnedRef.current.readOnly = true;
121
+ console.warn('[TUI CommandPalette] `inputValue` without `onInputChange` makes the field read-only.');
122
+ }
123
+ if (filter !== defaultFilter && !warnedRef.current.filter) {
124
+ warnedRef.current.filter = true;
125
+ console.warn('[TUI CommandPalette] `filter` is ignored while `inputValue` is controlled: filter the items you render.');
126
+ }
127
+ }, [isInputControlled, onInputChange, filter]);
128
+ // ---- Global shortcut ------------------------------------------------------
129
+ useEffect(() => {
130
+ if (!shortcut)
131
+ return;
132
+ const parsed = parseShortcut(shortcut);
133
+ if (!parsed)
134
+ return;
135
+ const apple = isApplePlatform();
136
+ const unmodified = !parsed.mod && !parsed.alt;
137
+ const onKeyDown = (event) => {
138
+ if (event.defaultPrevented || event.repeat)
139
+ return;
140
+ if (!matchesShortcut(event, parsed, apple))
141
+ return;
142
+ // A bare key ("/") is a character while typing, the palette's own field included.
143
+ if (unmodified && isTypingTarget(event.target))
144
+ return;
145
+ // Closed, it stands down while another modal is up rather than stack on it.
146
+ if (!openRef.current && document.querySelector('[aria-modal="true"]'))
147
+ return;
148
+ event.preventDefault();
149
+ setOpen(!openRef.current);
150
+ };
151
+ document.addEventListener('keydown', onKeyDown);
152
+ return () => document.removeEventListener('keydown', onKeyDown);
153
+ }, [shortcut, setOpen]);
154
+ // ---- Registry and highlight -----------------------------------------------
155
+ // `open: true`: see the header — nothing reads the registry while closed.
156
+ const { registerOption, unregisterOption, orderedOptions, optionIndexMap } = useOptionRegistry({
157
+ open: true,
158
+ });
159
+ const [activeIndex, setActiveIndex] = useState(-1);
160
+ const listRef = useRef([]);
161
+ useFilterStableActiveIndex({ open, orderedOptions, activeIndex, setActiveIndex, listRef });
162
+ useActiveOptionScroll(open, activeIndex, listRef);
163
+ // Items subscribe to "is it me?", so moving the highlight re-renders two
164
+ // items, not the list.
165
+ const [activeStore] = useState(createActiveStore);
166
+ const activeOption = activeIndex >= 0 ? orderedOptions[activeIndex] : undefined;
167
+ const activeKey = activeOption ? toKey(activeOption.value) : null;
168
+ useLayoutEffect(() => activeStore.set(activeKey), [activeStore, activeKey]);
169
+ // Items publish how they activate, so Enter can run the highlighted one's.
170
+ const activatorsRef = useRef(new Map());
171
+ // Items with an href, so the new-tab hint is read only when it applies.
172
+ const [hrefCount, setHrefCount] = useState(0);
173
+ const trackHref = useCallback((delta) => setHrefCount((n) => n + delta), []);
174
+ const inputRef = useRef(null);
175
+ const onSelectRef = useRef(onSelect);
176
+ onSelectRef.current = onSelect;
177
+ // Stable: items read it through context, and a new identity per parent
178
+ // render would re-render every item.
179
+ const choose = useCallback((value, options) => {
180
+ const { href, keepOpen, newTab } = options;
181
+ // A new tab is a side trip: the palette stays as it was.
182
+ if (newTab && href) {
183
+ const target = safeHref(href);
184
+ if (target)
185
+ window.open(target, '_blank', 'noopener,noreferrer');
186
+ return;
187
+ }
188
+ if (onSelectRef.current) {
189
+ onSelectRef.current(value, { href });
190
+ }
191
+ else if (href) {
192
+ const target = safeHref(href);
193
+ if (target)
194
+ window.location.assign(target);
195
+ }
196
+ else if (isDev() && !warnedRef.current.noop) {
197
+ warnedRef.current.noop = true;
198
+ console.warn(`[TUI CommandPalette] Item "${value}" was chosen, but there is no \`onSelect\` and the item has no \`href\`.`);
199
+ }
200
+ if (!keepOpen)
201
+ setOpen(false);
202
+ }, [setOpen]);
203
+ const move = (direction) => {
204
+ const count = orderedOptions.length;
205
+ if (count === 0)
206
+ return;
207
+ // From nothing highlighted, Down lands on the first item and Up the last.
208
+ let index = activeIndex < 0 ? (direction === 1 ? -1 : count) : activeIndex;
209
+ for (let step = 0; step < count; step++) {
210
+ index = (index + direction + count) % count;
211
+ if (!orderedOptions[index].disabled) {
212
+ setActiveIndex(index);
213
+ return;
214
+ }
215
+ }
216
+ };
217
+ // WebKit ends composition BEFORE the keydown of the Enter that commits it,
218
+ // so isComposing is already false there; keyCode 229 still marks it.
219
+ const handleKeyDown = (event) => {
220
+ if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229)
221
+ return;
222
+ switch (event.key) {
223
+ case 'ArrowDown':
224
+ event.preventDefault();
225
+ move(1);
226
+ break;
227
+ case 'ArrowUp':
228
+ event.preventDefault();
229
+ move(-1);
230
+ break;
231
+ case 'Enter': {
232
+ if (!activeOption || activeOption.disabled)
233
+ return;
234
+ event.preventDefault();
235
+ activatorsRef.current.get(toKey(activeOption.value))?.(event.metaKey || event.ctrlKey);
236
+ break;
237
+ }
238
+ }
239
+ };
240
+ // ---- Status -----------------------------------------------------------------
241
+ const count = orderedOptions.length;
242
+ const trimmed = query.trim();
243
+ const showEmpty = status === 'ready' && count === 0 && trimmed !== '';
244
+ const message = status === 'loading'
245
+ ? labels.loading
246
+ : status === 'error'
247
+ ? labels.error
248
+ : trimmed === ''
249
+ ? ''
250
+ : count === 0
251
+ ? labels.noResults(trimmed)
252
+ : labels.results(count);
253
+ // The region mounts empty with the dialog and is only ever filled after a
254
+ // delay: a region inserted together with its content is the unreliable path.
255
+ // A trailing no-break space alternates so a repeated message ("3 results"
256
+ // twice) is still a DOM change and is read again.
257
+ const [announcement, setAnnouncement] = useState('');
258
+ const flipRef = useRef(false);
259
+ useEffect(() => {
260
+ if (!open) {
261
+ setAnnouncement('');
262
+ return;
263
+ }
264
+ const timer = window.setTimeout(() => {
265
+ flipRef.current = !flipRef.current;
266
+ setAnnouncement(message ? message + (flipRef.current ? ' ' : '') : '');
267
+ }, ANNOUNCE_DELAY_MS);
268
+ return () => window.clearTimeout(timer);
269
+ }, [open, message, query]);
270
+ const handleRetry = () => {
271
+ onRetry?.();
272
+ // The retry button is about to unmount with the error state.
273
+ inputRef.current?.focus();
274
+ };
275
+ const activeOptionId = activeOption ? optionIdForValue(listboxId, activeOption.value) : undefined;
276
+ const contextValue = useMemo(() => ({
277
+ listboxId,
278
+ query,
279
+ filter: isInputControlled ? false : filter,
280
+ registerOption,
281
+ unregisterOption,
282
+ optionIndexMap,
283
+ listRef,
284
+ activeStore,
285
+ setActiveIndex,
286
+ activatorsRef,
287
+ trackHref,
288
+ choose,
289
+ }), [
290
+ listboxId,
291
+ query,
292
+ isInputControlled,
293
+ filter,
294
+ registerOption,
295
+ unregisterOption,
296
+ optionIndexMap,
297
+ activeStore,
298
+ trackHref,
299
+ choose,
300
+ ]);
301
+ return (_jsxs(Modal, { ...rest, open: open, onClose: () => setOpen(false), "aria-labelledby": titleId,
302
+ // An attribute selector: useId output needs no escaping, and CSS.escape
303
+ // doesn't exist during a server render.
304
+ initialFocusSelector: `[id="${inputId}"]`, restoreFocusTo: restoreFocusTo, className: cx('tui-command-palette', className), children: [_jsx("h2", { id: titleId, className: "tui-visually-hidden", children: labels.title }), _jsxs("div", { className: "tui-command-palette__search", children: [_jsx(Icon, { name: SearchIcon, className: "tui-command-palette__search-icon" }), _jsx("input", { ref: inputRef, id: inputId, type: "text", className: "tui-command-palette__input", value: query, placeholder: labels.placeholder, onChange: (event) => setQuery(event.target.value), onKeyDown: handleKeyDown, autoComplete: "off", autoCorrect: "off", spellCheck: false, role: "combobox", "aria-label": labels.search, "aria-expanded": count > 0, "aria-controls": listboxId, "aria-autocomplete": "list", "aria-activedescendant": activeOptionId, "aria-describedby": hrefCount > 0 ? hintId : undefined }), _jsx("kbd", { className: "tui-command-palette__kbd tui-command-palette__esc", "aria-hidden": "true", children: "Esc" }), _jsx(Button, { variant: "ghost", size: "md", className: "tui-command-palette__cancel", onClick: () => setOpen(false), children: labels.close })] }), _jsx("span", { id: hintId, className: "tui-visually-hidden", children: labels.newTabHint }), _jsx("div", { id: listboxId, role: "listbox", "aria-label": labels.list, "aria-busy": status === 'loading' || undefined, className: "tui-command-palette__list", children: _jsx(CommandPaletteContext.Provider, { value: contextValue, children: children }) }), (status !== 'ready' || showEmpty) && (_jsxs("div", { className: "tui-command-palette__message", "data-status": showEmpty ? 'empty' : status, children: [_jsx("p", { children: status === 'ready' ? labels.noResults(trimmed) : message }), status === 'error' && onRetry && (_jsx(Button, { variant: "outline", theme: "secondary", size: "sm", onClick: handleRetry, children: labels.retry }))] })), _jsx("div", { role: "status", className: "tui-visually-hidden", children: announcement }), showHints && (
305
+ // Hidden from AT: it restates the combobox keys AT already announces.
306
+ // The one key it doesn't (new tab) is in the field's description.
307
+ _jsxs("div", { className: "tui-command-palette__hints", "aria-hidden": "true", children: [_jsxs("span", { className: "tui-command-palette__hint", children: [_jsx("kbd", { className: "tui-command-palette__kbd", children: "\u2191\u2193" }), " ", labels.hintNavigate] }), _jsxs("span", { className: "tui-command-palette__hint", children: [_jsx("kbd", { className: "tui-command-palette__kbd", children: "\u21B5" }), " ", labels.hintOpen] }), _jsxs("span", { className: "tui-command-palette__hint", children: [_jsx("kbd", { className: "tui-command-palette__kbd", children: "Esc" }), " ", labels.hintClose] })] }))] }));
308
+ }
309
+ CommandPaletteRoot.displayName = 'CommandPalette';
310
+ // =============================================================================
311
+ // CommandPalette.Item
312
+ // =============================================================================
313
+ const NO_KEYWORDS = [];
314
+ function CommandPaletteItemComponent({ value, textValue: explicitTextValue, keywords = NO_KEYWORDS, icon, description, href, keepOpen = false, disabled = false, className, children, }) {
315
+ const { listboxId, query, filter, registerOption, unregisterOption, optionIndexMap, listRef, activeStore, setActiveIndex, activatorsRef, trackHref, choose, } = useCommandPaletteContext('CommandPalette.Item');
316
+ const ref = useRef(null);
317
+ const key = toKey(value);
318
+ // Text with no derivable string (rich children, no textValue) stays visible
319
+ // rather than vanishing on the first keystroke; the registry warns about it.
320
+ const text = deriveOptionText(children, explicitTextValue);
321
+ const visible = filter === false || query.trim() === '' || text === '' || filter(text, query, keywords);
322
+ useOptionRegistration({
323
+ value,
324
+ disabled,
325
+ textValue: explicitTextValue,
326
+ children,
327
+ componentName: 'CommandPalette.Item',
328
+ elementRef: ref,
329
+ registerOption,
330
+ unregisterOption,
331
+ enabled: visible,
332
+ });
333
+ const index = optionIndexMap.get(key) ?? -1;
334
+ useEffect(() => {
335
+ if (index >= 0)
336
+ listRef.current[index] = ref.current;
337
+ }, [index, listRef]);
338
+ const isActive = useSyncExternalStore(activeStore.subscribe, () => activeStore.get() === key, () => false);
339
+ const activate = useCallback((newTab) => {
340
+ if (disabled)
341
+ return;
342
+ choose(value, { href, keepOpen, newTab });
343
+ }, [disabled, choose, value, href, keepOpen]);
344
+ useLayoutEffect(() => {
345
+ if (!visible)
346
+ return;
347
+ const activators = activatorsRef.current;
348
+ activators.set(key, activate);
349
+ return () => {
350
+ if (activators.get(key) === activate)
351
+ activators.delete(key);
352
+ };
353
+ }, [visible, key, activate, activatorsRef]);
354
+ const hasHref = visible && !!href && !disabled;
355
+ useLayoutEffect(() => {
356
+ if (!hasHref)
357
+ return;
358
+ trackHref(1);
359
+ return () => trackHref(-1);
360
+ }, [hasHref, trackHref]);
361
+ if (!visible)
362
+ return null;
363
+ return (_jsxs("div", { ref: ref, id: optionIdForValue(listboxId, value), role: "option", "aria-selected": isActive, "aria-disabled": disabled || undefined, "data-highlighted": isActive || undefined, "data-disabled": disabled || undefined, className: cx('tui-command-palette__item', className),
364
+ // Keep focus in the field when an item is pressed.
365
+ onPointerDown: (event) => event.preventDefault(), onPointerMove: () => {
366
+ if (!disabled && index >= 0 && !isActive)
367
+ setActiveIndex(index);
368
+ }, onClick: (event) => activate(event.metaKey || event.ctrlKey), onAuxClick: (event) => {
369
+ if (event.button === 1 && href && !disabled) {
370
+ event.preventDefault();
371
+ choose(value, { href, keepOpen, newTab: true });
372
+ }
373
+ }, children: [icon && _jsx(Icon, { name: icon, className: "tui-command-palette__item-icon" }), _jsxs("span", { className: "tui-command-palette__item-text", children: [_jsx("span", { className: "tui-command-palette__item-label", children: children }), description && (_jsx("span", { className: "tui-command-palette__item-description", children: description }))] })] }));
374
+ }
375
+ CommandPaletteItemComponent.displayName = 'CommandPalette.Item';
376
+ CommandPaletteItemComponent.displayName = 'CommandPalette.Item';
377
+ // =============================================================================
378
+ // CommandPalette.Group / CommandPalette.Label (shared engine pair)
379
+ // =============================================================================
380
+ const { Group: CommandPaletteGroupComponent, Label: CommandPaletteLabelComponent } = createListboxGroupComponents({
381
+ componentName: 'CommandPalette',
382
+ groupClass: 'tui-command-palette__group',
383
+ labelClass: 'tui-command-palette__label',
384
+ });
385
+ // =============================================================================
386
+ // CommandPalette.Trigger
387
+ // =============================================================================
388
+ //
389
+ // A search-field-shaped button for a header. Standalone, not context-bound:
390
+ // the trigger and the palette usually live in different parts of the tree, so
391
+ // the consumer wires `onClick` to the same state as `open`.
392
+ //
393
+ // =============================================================================
394
+ const CommandPaletteTriggerComponent = React.forwardRef(function CommandPaletteTrigger({ shortcut, size = 'md', className, children = defaultCommandPaletteLabels.placeholder, ...rest }, ref) {
395
+ // Platform is read after mount so server and first client render agree.
396
+ const [apple, setApple] = useState(false);
397
+ useEffect(() => setApple(isApplePlatform()), []);
398
+ const parsed = shortcut ? parseShortcut(shortcut) : null;
399
+ return (_jsxs("button", { ref: ref, type: "button", "aria-haspopup": "dialog", "aria-keyshortcuts": parsed ? ariaShortcut(parsed, apple) : undefined, ...rest, className: cx('tui-input-group', 'tui-command-palette-trigger', size !== 'md' && `is-size-${size}`, className), children: [_jsx(Icon, { name: SearchIcon, className: "tui-command-palette-trigger__icon" }), _jsx("span", { className: "tui-command-palette-trigger__text", children: children }), parsed && (
400
+ // aria-keyshortcuts carries it for AT
401
+ _jsx("kbd", { className: "tui-command-palette__kbd", "aria-hidden": "true", children: formatShortcut(parsed, apple) }))] }));
402
+ });
403
+ CommandPaletteTriggerComponent.displayName = 'CommandPalette.Trigger';
404
+ const CommandPalette = CommandPaletteRoot;
405
+ CommandPalette.Item = CommandPaletteItemComponent;
406
+ CommandPalette.Group = CommandPaletteGroupComponent;
407
+ CommandPalette.Label = CommandPaletteLabelComponent;
408
+ CommandPalette.Trigger = CommandPaletteTriggerComponent;
409
+ export { CommandPalette, CommandPaletteItemComponent as CommandPaletteItem, CommandPaletteGroupComponent as CommandPaletteGroup, CommandPaletteLabelComponent as CommandPaletteLabel, CommandPaletteTriggerComponent as CommandPaletteTrigger, };
@@ -0,0 +1,31 @@
1
+ import { type MutableRefObject } from 'react';
2
+ import type { RegisteredOption } from '../../utils/listbox';
3
+ import type { OptionValue } from '../../utils/value-key';
4
+ import type { CommandPaletteFilter } from './types';
5
+ /** The highlighted item's key, subscribed to per item (see useSyncExternalStore in Item). */
6
+ export type ActiveStore = {
7
+ get: () => string | null;
8
+ set: (key: string | null) => void;
9
+ subscribe: (listener: () => void) => () => void;
10
+ };
11
+ export type CommandPaletteContextValue = {
12
+ listboxId: string;
13
+ query: string;
14
+ /** `false` when the consumer filters (controlled `inputValue`, or `filter={false}`). */
15
+ filter: CommandPaletteFilter | false;
16
+ registerOption: (option: RegisteredOption) => void;
17
+ unregisterOption: (value: OptionValue) => void;
18
+ optionIndexMap: Map<string, number>;
19
+ listRef: MutableRefObject<(HTMLElement | null)[]>;
20
+ activeStore: ActiveStore;
21
+ setActiveIndex: (index: number) => void;
22
+ activatorsRef: MutableRefObject<Map<string, (newTab: boolean) => void>>;
23
+ trackHref: (delta: 1 | -1) => void;
24
+ choose: (value: OptionValue, options: {
25
+ href?: string;
26
+ keepOpen?: boolean;
27
+ newTab: boolean;
28
+ }) => void;
29
+ };
30
+ export declare const CommandPaletteContext: import("react").Context<CommandPaletteContextValue | null>;
31
+ export declare function useCommandPaletteContext(component: string): CommandPaletteContextValue;
@@ -0,0 +1,8 @@
1
+ import { createContext, useContext } from 'react';
2
+ export const CommandPaletteContext = createContext(null);
3
+ export function useCommandPaletteContext(component) {
4
+ const context = useContext(CommandPaletteContext);
5
+ if (!context)
6
+ throw new Error(`${component} must be rendered inside a CommandPalette.`);
7
+ return context;
8
+ }
@@ -0,0 +1,3 @@
1
+ export { CommandPalette, CommandPaletteItem, CommandPaletteGroup, CommandPaletteLabel, CommandPaletteTrigger, } from './CommandPalette';
2
+ export { defaultCommandPaletteLabels } from './types';
3
+ export type { CommandPaletteProps, CommandPaletteItemProps, CommandPaletteGroupProps, CommandPaletteLabelProps, CommandPaletteTriggerProps, CommandPaletteLabels, CommandPaletteStatus, CommandPaletteSelectDetail, CommandPaletteFilter, } from './types';
@@ -0,0 +1,2 @@
1
+ export { CommandPalette, CommandPaletteItem, CommandPaletteGroup, CommandPaletteLabel, CommandPaletteTrigger, } from './CommandPalette.js';
2
+ export { defaultCommandPaletteLabels } from './types.js';
@@ -0,0 +1,15 @@
1
+ export type ParsedShortcut = {
2
+ key: string;
3
+ mod: boolean;
4
+ shift: boolean;
5
+ alt: boolean;
6
+ };
7
+ export declare function isApplePlatform(): boolean;
8
+ export declare function parseShortcut(shortcut: string): ParsedShortcut | null;
9
+ export declare function matchesShortcut(event: KeyboardEvent, parsed: ParsedShortcut, apple: boolean): boolean;
10
+ /** The shortcut as a visible hint: "⌘K" on Apple platforms, "Ctrl K" elsewhere. */
11
+ export declare function formatShortcut(parsed: ParsedShortcut, apple: boolean): string;
12
+ /** The shortcut in `aria-keyshortcuts` syntax: "Meta+K", "Control+Shift+P". */
13
+ export declare function ariaShortcut(parsed: ParsedShortcut, apple: boolean): string;
14
+ /** Whether a keystroke here is typing (WCAG 2.1.4: an unmodified shortcut must not fire). */
15
+ export declare function isTypingTarget(target: EventTarget | null): boolean;
@@ -0,0 +1,83 @@
1
+ // =============================================================================
2
+ // Keyboard shortcut strings: "mod+k", "mod+shift+p", "/"
3
+ // =============================================================================
4
+ //
5
+ // `mod` is Cmd on Apple platforms and Ctrl elsewhere, the convention every
6
+ // command palette follows. One parser feeds three consumers: the global
7
+ // listener (matching), the key hint (display) and `aria-keyshortcuts`, so the
8
+ // three can't disagree about what the shortcut is.
9
+ //
10
+ // =============================================================================
11
+ export function isApplePlatform() {
12
+ if (typeof navigator === 'undefined')
13
+ return false;
14
+ const platform = navigator.userAgentData?.platform ??
15
+ navigator.platform ??
16
+ '';
17
+ return /mac|iphone|ipad|ipod/i.test(platform);
18
+ }
19
+ export function parseShortcut(shortcut) {
20
+ const parts = shortcut.toLowerCase().split('+').map((part) => part.trim());
21
+ const key = parts.pop();
22
+ if (!key)
23
+ return null;
24
+ return {
25
+ key,
26
+ mod: parts.includes('mod'),
27
+ shift: parts.includes('shift'),
28
+ alt: parts.includes('alt'),
29
+ };
30
+ }
31
+ export function matchesShortcut(event, parsed, apple) {
32
+ const mod = apple ? event.metaKey : event.ctrlKey;
33
+ // The other platform's modifier must be up, or Ctrl+K on a Mac would match too.
34
+ const other = apple ? event.ctrlKey : event.metaKey;
35
+ // Match the printed key, or the physical one for a letter or digit: on a
36
+ // Cyrillic layout K types "л", and Option+P on a Mac types "π".
37
+ // Only when the printed key isn't ASCII, so a Dvorak user's own K still wins.
38
+ const physical = !/^[\x20-\x7e]$/.test(event.key);
39
+ const keyMatches = event.key.toLowerCase() === parsed.key ||
40
+ (physical && /^[a-z]$/.test(parsed.key) && event.code === `Key${parsed.key.toUpperCase()}`) ||
41
+ (physical && /^[0-9]$/.test(parsed.key) && event.code === `Digit${parsed.key}`);
42
+ return (keyMatches &&
43
+ mod === parsed.mod &&
44
+ !other &&
45
+ event.shiftKey === parsed.shift &&
46
+ event.altKey === parsed.alt);
47
+ }
48
+ function keyLabel(key) {
49
+ return key.length === 1 ? key.toUpperCase() : key[0].toUpperCase() + key.slice(1);
50
+ }
51
+ /** The shortcut as a visible hint: "⌘K" on Apple platforms, "Ctrl K" elsewhere. */
52
+ export function formatShortcut(parsed, apple) {
53
+ if (apple) {
54
+ return `${parsed.alt ? '⌥' : ''}${parsed.shift ? '⇧' : ''}${parsed.mod ? '⌘' : ''}${keyLabel(parsed.key)}`;
55
+ }
56
+ return [parsed.mod && 'Ctrl', parsed.alt && 'Alt', parsed.shift && 'Shift', keyLabel(parsed.key)]
57
+ .filter(Boolean)
58
+ .join(' ');
59
+ }
60
+ /** The shortcut in `aria-keyshortcuts` syntax: "Meta+K", "Control+Shift+P". */
61
+ export function ariaShortcut(parsed, apple) {
62
+ return [
63
+ parsed.mod && (apple ? 'Meta' : 'Control'),
64
+ parsed.alt && 'Alt',
65
+ parsed.shift && 'Shift',
66
+ keyLabel(parsed.key),
67
+ ]
68
+ .filter(Boolean)
69
+ .join('+');
70
+ }
71
+ /** Whether a keystroke here is typing (WCAG 2.1.4: an unmodified shortcut must not fire). */
72
+ export function isTypingTarget(target) {
73
+ if (!(target instanceof Element))
74
+ return false;
75
+ if (target.closest('[contenteditable=""], [contenteditable="true"]'))
76
+ return true;
77
+ if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement)
78
+ return true;
79
+ if (target instanceof HTMLInputElement) {
80
+ return !['button', 'checkbox', 'radio', 'submit', 'reset', 'range', 'color', 'file', 'image'].includes(target.type);
81
+ }
82
+ return false;
83
+ }