base-cmdk 0.1.0 → 0.1.1

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.
package/dist/index.js CHANGED
@@ -1,16 +1,915 @@
1
1
  "use client";
2
- import { CommandRoot } from "./root.js";
3
- import { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandLoading, CommandSeparator, } from "./parts.js";
4
- export const Command = Object.assign(CommandRoot, {
5
- Dialog: CommandDialog,
6
- Empty: CommandEmpty,
7
- Group: CommandGroup,
8
- Input: CommandInput,
9
- Item: CommandItem,
10
- List: CommandList,
11
- Loading: CommandLoading,
12
- Separator: CommandSeparator,
13
- });
14
- export { CommandRoot, defaultFilter } from "./root.js";
15
- export { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandLoading, CommandSeparator, } from "./parts.js";
16
- export { useCommandState } from "./context.js";
2
+ import * as React from "react";
3
+ import { useRefWithInit } from "@base-ui/utils/useRefWithInit";
4
+ import { useValueAsRef } from "@base-ui/utils/useValueAsRef";
5
+ import { useIsoLayoutEffect } from "@base-ui/utils/useIsoLayoutEffect";
6
+ import { Dialog } from "@base-ui/react/dialog";
7
+ import { useMergedRefs } from "@base-ui/utils/useMergedRefs";
8
+ import { jsx, jsxs } from "react/jsx-runtime";
9
+ // src/context.ts
10
+ const GROUP_SELECTOR = `[cmdk-group=""]`;
11
+ const GROUP_HEADING_SELECTOR = `[cmdk-group-heading=""]`;
12
+ const VALID_ITEM_SELECTOR = `[cmdk-item=""]:not([aria-disabled="true"])`;
13
+ const SELECT_EVENT = `cmdk-item-select`;
14
+ const VALUE_ATTR = `data-value`;
15
+ const CommandContext = React.createContext(null);
16
+ const StoreContext = React.createContext(null);
17
+ const GroupContext = React.createContext(null);
18
+ function useCommand() {
19
+ const context = React.useContext(CommandContext);
20
+ if (!context) throw new Error("Command parts must be rendered inside a Command.");
21
+ return context;
22
+ }
23
+ function useStore() {
24
+ const store = React.useContext(StoreContext);
25
+ if (!store) throw new Error("Command state must be read inside a Command.");
26
+ return store;
27
+ }
28
+ /** Run a selector against the store state. */
29
+ function useCommandState(selector) {
30
+ const store = useStore();
31
+ const [read, readServer] = React.useMemo(() => {
32
+ function memoize(getSnapshot) {
33
+ let previous;
34
+ let selection;
35
+ return () => {
36
+ const snapshot = getSnapshot();
37
+ if (previous !== snapshot) {
38
+ selection = selector(snapshot);
39
+ previous = snapshot;
40
+ }
41
+ return selection;
42
+ };
43
+ }
44
+ return [memoize(store.snapshot), memoize(() => store.initialSnapshot)];
45
+ }, [store, selector]);
46
+ return React.useSyncExternalStore(store.subscribe, read, readServer);
47
+ }
48
+ function wrapChildren({ asChild, children }, render) {
49
+ if (asChild && React.isValidElement(children)) return React.cloneElement(children, void 0, render(children.props.children));
50
+ return render(children);
51
+ }
52
+ // src/command-score.ts
53
+ const SCORE_CONTINUE_MATCH = 1;
54
+ const SCORE_SPACE_WORD_JUMP = .9;
55
+ const SCORE_NON_SPACE_WORD_JUMP = .8;
56
+ const SCORE_CHARACTER_JUMP = .17;
57
+ const SCORE_TRANSPOSITION = .1;
58
+ const PENALTY_SKIPPED = .999;
59
+ const PENALTY_CASE_MISMATCH = .9999;
60
+ const PENALTY_NOT_COMPLETE = .99;
61
+ const IS_GAP_REGEXP = /[\\/_+.#"@[({&]/;
62
+ const COUNT_GAPS_REGEXP = /[\\/_+.#"@[({&]/g;
63
+ const IS_SPACE_REGEXP = /[\s-]/;
64
+ const COUNT_SPACE_REGEXP = /[\s-]/g;
65
+ function commandScoreInner(value, abbreviation, lowerString, lowerAbbreviation, stringIndex, abbreviationIndex, memoizedResults) {
66
+ if (abbreviationIndex === abbreviation.length) {
67
+ if (stringIndex === value.length) return SCORE_CONTINUE_MATCH;
68
+ return PENALTY_NOT_COMPLETE;
69
+ }
70
+ const memoizeKey = `${stringIndex},${abbreviationIndex}`;
71
+ if (memoizedResults[memoizeKey] !== void 0) return memoizedResults[memoizeKey];
72
+ const abbreviationChar = lowerAbbreviation.charAt(abbreviationIndex);
73
+ let index = lowerString.indexOf(abbreviationChar, stringIndex);
74
+ let highScore = 0;
75
+ let score, transposedScore, wordBreaks, spaceBreaks;
76
+ while (index >= 0) {
77
+ score = commandScoreInner(value, abbreviation, lowerString, lowerAbbreviation, index + 1, abbreviationIndex + 1, memoizedResults);
78
+ if (score > highScore) {
79
+ if (index === stringIndex) score *= SCORE_CONTINUE_MATCH;
80
+ else if (IS_GAP_REGEXP.test(value.charAt(index - 1))) {
81
+ score *= SCORE_NON_SPACE_WORD_JUMP;
82
+ wordBreaks = value.slice(stringIndex, index - 1).match(COUNT_GAPS_REGEXP);
83
+ if (wordBreaks && stringIndex > 0) score *= Math.pow(PENALTY_SKIPPED, wordBreaks.length);
84
+ } else if (IS_SPACE_REGEXP.test(value.charAt(index - 1))) {
85
+ score *= SCORE_SPACE_WORD_JUMP;
86
+ spaceBreaks = value.slice(stringIndex, index - 1).match(COUNT_SPACE_REGEXP);
87
+ if (spaceBreaks && stringIndex > 0) score *= Math.pow(PENALTY_SKIPPED, spaceBreaks.length);
88
+ } else {
89
+ score *= SCORE_CHARACTER_JUMP;
90
+ if (stringIndex > 0) score *= Math.pow(PENALTY_SKIPPED, index - stringIndex);
91
+ }
92
+ if (value.charAt(index) !== abbreviation.charAt(abbreviationIndex)) score *= PENALTY_CASE_MISMATCH;
93
+ }
94
+ if (score < SCORE_TRANSPOSITION && lowerString.charAt(index - 1) === lowerAbbreviation.charAt(abbreviationIndex + 1) || lowerAbbreviation.charAt(abbreviationIndex + 1) === lowerAbbreviation.charAt(abbreviationIndex) && lowerString.charAt(index - 1) !== lowerAbbreviation.charAt(abbreviationIndex)) {
95
+ transposedScore = commandScoreInner(value, abbreviation, lowerString, lowerAbbreviation, index + 1, abbreviationIndex + 2, memoizedResults);
96
+ if (transposedScore * SCORE_TRANSPOSITION > score) score = transposedScore * SCORE_TRANSPOSITION;
97
+ }
98
+ if (score > highScore) highScore = score;
99
+ index = lowerString.indexOf(abbreviationChar, index + 1);
100
+ }
101
+ memoizedResults[memoizeKey] = highScore;
102
+ return highScore;
103
+ }
104
+ function formatInput(value) {
105
+ return value.toLowerCase().replace(COUNT_SPACE_REGEXP, " ");
106
+ }
107
+ function commandScore(string, abbreviation, aliases) {
108
+ string = aliases && aliases.length > 0 ? `${string + " " + aliases.join(" ")}` : string;
109
+ return commandScoreInner(string, abbreviation, formatInput(string), formatInput(abbreviation), 0, 0, {});
110
+ }
111
+ // src/collection.ts
112
+ const defaultFilter = (value, search, keywords = []) => commandScore(value, search, keywords);
113
+ function createCollection(invalidate) {
114
+ const items = /* @__PURE__ */ new Map();
115
+ const groups = /* @__PURE__ */ new Map();
116
+ let dirty = true;
117
+ let filter = defaultFilter;
118
+ let automatic = true;
119
+ function markDirty() {
120
+ if (!dirty) {
121
+ dirty = true;
122
+ invalidate();
123
+ }
124
+ }
125
+ function filterItems(search) {
126
+ const ranked = automatic && Boolean(search);
127
+ const scores = /* @__PURE__ */ new Map();
128
+ const visibleGroups = /* @__PURE__ */ new Set();
129
+ const unavailable = /* @__PURE__ */ new Set();
130
+ function groupHidden(groupId) {
131
+ while (groupId) {
132
+ const group = groups.get(groupId);
133
+ if (group?.hidden) return true;
134
+ groupId = group?.parentId;
135
+ }
136
+ return false;
137
+ }
138
+ function showGroup(groupId) {
139
+ while (groupId && !visibleGroups.has(groupId)) {
140
+ visibleGroups.add(groupId);
141
+ groupId = groups.get(groupId)?.parentId;
142
+ }
143
+ }
144
+ for (const [id, group] of groups) if ((group.forced || !ranked) && !groupHidden(id)) showGroup(id);
145
+ for (const [id, item] of items) {
146
+ const hidden = item.hidden || groupHidden(item.groupId) || item.parent?.closest("[hidden]:not([cmdk-group]), [inert]");
147
+ if (hidden) unavailable.add(id);
148
+ const rank = hidden ? 0 : ranked ? filter(item.value, search, item.keywords) : 1;
149
+ scores.set(id, rank);
150
+ if (rank > 0) showGroup(item.groupId);
151
+ }
152
+ let count = 0;
153
+ for (const [id, item] of items) {
154
+ if (unavailable.has(id) || item.groupId && !visibleGroups.has(item.groupId)) continue;
155
+ if (item.forced || (scores.get(id) ?? 0) > 0) count++;
156
+ }
157
+ return {
158
+ ranked,
159
+ count,
160
+ items: scores,
161
+ groups: visibleGroups
162
+ };
163
+ }
164
+ return {
165
+ refresh(nextFilter = defaultFilter, shouldFilter = true) {
166
+ const changed = dirty || filter !== nextFilter || automatic !== shouldFilter;
167
+ filter = nextFilter;
168
+ automatic = shouldFilter;
169
+ dirty = false;
170
+ return changed;
171
+ },
172
+ filterItems,
173
+ markDirty,
174
+ updateItem(id, item) {
175
+ const last = items.get(id);
176
+ if (last && last.value === item.value && last.groupId === item.groupId && last.parent === item.parent && last.forced === item.forced && last.disabled === item.disabled && last.hidden === item.hidden && last.keywords.length === item.keywords.length && last.keywords.every((word, index) => word === item.keywords[index])) return;
177
+ items.set(id, item);
178
+ markDirty();
179
+ },
180
+ removeItem(id) {
181
+ if (items.delete(id)) markDirty();
182
+ },
183
+ updateGroup(id, forced, hidden, parentId) {
184
+ const last = groups.get(id);
185
+ if (last && last.forced === forced && last.hidden === hidden && last.parentId === parentId) return;
186
+ groups.set(id, {
187
+ forced,
188
+ hidden,
189
+ parentId
190
+ });
191
+ markDirty();
192
+ },
193
+ removeGroup(id) {
194
+ if (groups.delete(id)) markDirty();
195
+ }
196
+ };
197
+ }
198
+ // src/order.ts
199
+ function trackOrder(list, onChange) {
200
+ const movable = /* @__PURE__ */ new WeakSet();
201
+ const authored = /* @__PURE__ */ new Map();
202
+ function record(changes) {
203
+ for (const change of changes) {
204
+ const siblings = authored.get(change.target);
205
+ if (!siblings) continue;
206
+ for (const node of [...change.removedNodes, ...change.addedNodes]) {
207
+ const index = siblings.indexOf(node);
208
+ if (index !== -1) siblings.splice(index, 1);
209
+ }
210
+ const before = change.nextSibling ? siblings.indexOf(change.nextSibling) : -1;
211
+ siblings.splice(before < 0 ? siblings.length : before, 0, ...change.addedNodes);
212
+ }
213
+ }
214
+ const observer = new MutationObserver((changes) => {
215
+ record(changes);
216
+ onChange();
217
+ });
218
+ observer.observe(list, {
219
+ childList: true,
220
+ subtree: true
221
+ });
222
+ function arrange(filtered) {
223
+ record(observer.takeRecords());
224
+ const scores = /* @__PURE__ */ new Map();
225
+ for (const item of list.querySelectorAll("[cmdk-item], [cmdk-group]")) {
226
+ if (item.closest("[cmdk-list-sizer]") !== list) continue;
227
+ const score = filtered?.items.get(item.id) ?? 0;
228
+ let node = item;
229
+ while (node && node !== list) {
230
+ movable.add(node);
231
+ scores.set(node, Math.max(scores.get(node) ?? 0, score));
232
+ const parent = node.parentElement;
233
+ if (parent && !authored.has(parent)) authored.set(parent, Array.from(parent.childNodes));
234
+ node = parent;
235
+ }
236
+ }
237
+ for (const [parent, siblings] of authored) {
238
+ if (!list.contains(parent)) {
239
+ authored.delete(parent);
240
+ continue;
241
+ }
242
+ const results = siblings.filter((node) => movable.has(node));
243
+ if (filtered) results.sort((a, b) => (scores.get(b) ?? 0) - (scores.get(a) ?? 0));
244
+ let i = results.length;
245
+ let anchor = null;
246
+ for (let j = siblings.length - 1; j >= 0; j--) {
247
+ let node = siblings[j];
248
+ if (movable.has(node)) {
249
+ node = results[--i];
250
+ if (node.nextSibling !== anchor) parent.insertBefore(node, anchor);
251
+ }
252
+ anchor = node;
253
+ }
254
+ }
255
+ observer.takeRecords();
256
+ }
257
+ return {
258
+ list,
259
+ arrange,
260
+ disconnect: () => observer.disconnect()
261
+ };
262
+ }
263
+ // src/parts.tsx
264
+ function declaredText(children) {
265
+ return React.Children.toArray(children).map((child) => {
266
+ if (typeof child === "string" || typeof child === "number") return String(child);
267
+ if (React.isValidElement(child) && (typeof child.type === "string" || child.type === React.Fragment)) return declaredText(child.props.children);
268
+ return "";
269
+ }).join("");
270
+ }
271
+ /**
272
+ * Command menu item. Becomes active on pointer enter or through keyboard navigation.
273
+ * Preferably pass a `value`, otherwise the value will be inferred from `children` or
274
+ * the rendered item's `textContent`.
275
+ */
276
+ const CommandItem = React.forwardRef((props, forwardedRef) => {
277
+ const generatedId = React.useId();
278
+ const id = props.id ?? generatedId;
279
+ const ref = React.useRef(null);
280
+ const mergedRef = useMergedRefs(ref, forwardedRef);
281
+ const groupContext = React.useContext(GroupContext);
282
+ const parent = React.useRef(null);
283
+ const context = useCommand();
284
+ const propsRef = useValueAsRef(props);
285
+ const forceMount = props.forceMount ?? groupContext?.forceMount;
286
+ const value = React.useRef("");
287
+ const initialValue = React.useMemo(() => props.value ?? declaredText(props.children), [props.value, props.children]);
288
+ useIsoLayoutEffect(() => {
289
+ const text = props.value ?? (typeof props.children === "string" ? props.children : ref.current?.textContent);
290
+ value.current = (text ?? (value.current || initialValue)).trim();
291
+ if (ref.current) parent.current = ref.current.parentElement;
292
+ ref.current?.setAttribute("data-value", value.current);
293
+ context.updateItem(id, {
294
+ value: value.current,
295
+ keywords: props.keywords?.map((word) => word.trim()) ?? [],
296
+ groupId: groupContext?.id,
297
+ parent: parent.current,
298
+ forced: Boolean(forceMount),
299
+ disabled: Boolean(props.disabled),
300
+ hidden: Boolean(props.hidden || props.inert)
301
+ });
302
+ });
303
+ const { removeItem } = context;
304
+ useIsoLayoutEffect(() => () => removeItem(id), [id, removeItem]);
305
+ const store = useStore();
306
+ const selected = useCommandState((state) => state.selectedItemId === id);
307
+ const render = useCommandState((state) => !state.filtered.ranked || forceMount || (state.filtered.items.has(id) ? (state.filtered.items.get(id) ?? 0) > 0 : state.ready || !initialValue || context.initialScore(initialValue.trim(), props.keywords) > 0));
308
+ useIsoLayoutEffect(() => {
309
+ const element = ref.current;
310
+ if (!element || props.disabled) return;
311
+ element.addEventListener(SELECT_EVENT, onSelect);
312
+ return () => element.removeEventListener(SELECT_EVENT, onSelect);
313
+ }, [
314
+ render,
315
+ props.onSelect,
316
+ props.disabled
317
+ ]);
318
+ function onSelect() {
319
+ if (!ref.current || ref.current.closest("[hidden], [inert]") || propsRef.current.disabled) return;
320
+ select();
321
+ propsRef.current.onSelect?.(value.current);
322
+ }
323
+ function select() {
324
+ store.setState("value", value.current, true);
325
+ }
326
+ const { disabled, value: _, onSelect: __, forceMount: ___, keywords: ____, ...etc } = props;
327
+ if (!render) return null;
328
+ return /* @__PURE__ */ jsx("div", {
329
+ ref: mergedRef,
330
+ ...etc,
331
+ id,
332
+ "cmdk-item": "",
333
+ role: "option",
334
+ "aria-disabled": Boolean(disabled),
335
+ "aria-selected": Boolean(selected),
336
+ "data-disabled": Boolean(disabled),
337
+ "data-selected": Boolean(selected),
338
+ onPointerMove: (event) => {
339
+ etc.onPointerMove?.(event);
340
+ if (!disabled && !context.disablePointerSelection && !event.defaultPrevented) select();
341
+ },
342
+ onMouseDown: (event) => {
343
+ etc.onMouseDown?.(event);
344
+ const item = event.currentTarget;
345
+ const active = item.getRootNode().activeElement;
346
+ const control = event.target.closest("a[href], button, input, select, textarea, [contenteditable]:not([contenteditable=false]), [tabindex]");
347
+ if (!event.defaultPrevented && event.button === 0 && !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey && active?.matches("[cmdk-input]") && active.closest("[cmdk-root]") === item.closest("[cmdk-root]") && !(control && item.contains(control))) event.preventDefault();
348
+ },
349
+ onClick: (event) => {
350
+ etc.onClick?.(event);
351
+ if (!disabled && !event.defaultPrevented) onSelect();
352
+ },
353
+ children: props.children
354
+ });
355
+ });
356
+ /**
357
+ * Group command menu items together with a heading.
358
+ * Grouped items are always shown together.
359
+ */
360
+ const CommandGroup = React.forwardRef((props, forwardedRef) => {
361
+ const { heading, children: _children, forceMount, value, hidden, ...etc } = props;
362
+ const id = React.useId();
363
+ const ref = React.useRef(null);
364
+ const mergedRef = useMergedRefs(ref, forwardedRef);
365
+ const headingRef = React.useRef(null);
366
+ const headingId = React.useId();
367
+ const parentId = React.useContext(GroupContext)?.id;
368
+ const context = useCommand();
369
+ const render = useCommandState((state) => !state.ready || !state.filtered.ranked || state.filtered.groups.has(id));
370
+ const { updateGroup, removeGroup } = context;
371
+ useIsoLayoutEffect(() => updateGroup(id, Boolean(forceMount), Boolean(hidden), parentId), [
372
+ id,
373
+ forceMount,
374
+ hidden,
375
+ parentId,
376
+ updateGroup
377
+ ]);
378
+ useIsoLayoutEffect(() => () => removeGroup(id), [id, removeGroup]);
379
+ useIsoLayoutEffect(() => {
380
+ const name = value ?? headingRef.current?.textContent;
381
+ if (name != null) ref.current?.setAttribute("data-value", name.trim());
382
+ });
383
+ const contextValue = React.useMemo(() => ({
384
+ id,
385
+ forceMount
386
+ }), [id, forceMount]);
387
+ return /* @__PURE__ */ jsxs("div", {
388
+ ref: mergedRef,
389
+ ...etc,
390
+ "cmdk-group": "",
391
+ "data-cmdk-group-id": id,
392
+ role: "presentation",
393
+ hidden: hidden || !render,
394
+ children: [heading && /* @__PURE__ */ jsx("div", {
395
+ ref: headingRef,
396
+ "cmdk-group-heading": "",
397
+ "aria-hidden": true,
398
+ id: headingId,
399
+ children: heading
400
+ }), wrapChildren(props, (child) => /* @__PURE__ */ jsx("div", {
401
+ "cmdk-group-items": "",
402
+ role: "group",
403
+ "aria-labelledby": heading ? headingId : void 0,
404
+ children: /* @__PURE__ */ jsx(GroupContext.Provider, {
405
+ value: contextValue,
406
+ children: child
407
+ })
408
+ }))]
409
+ });
410
+ });
411
+ /**
412
+ * A visual and semantic separator between items or groups.
413
+ * Visible when the search query is empty or `alwaysRender` is true, hidden otherwise.
414
+ */
415
+ const CommandSeparator = React.forwardRef((props, forwardedRef) => {
416
+ const { alwaysRender, ...etc } = props;
417
+ const ref = React.useRef(null);
418
+ const mergedRef = useMergedRefs(ref, forwardedRef);
419
+ const render = useCommandState((state) => !state.search);
420
+ if (!alwaysRender && !render) return null;
421
+ return /* @__PURE__ */ jsx("div", {
422
+ ref: mergedRef,
423
+ ...etc,
424
+ "cmdk-separator": "",
425
+ role: "separator"
426
+ });
427
+ });
428
+ /**
429
+ * Command menu input.
430
+ * All props are forwarded to the underyling `input` element.
431
+ */
432
+ const CommandInput = React.forwardRef((props, forwardedRef) => {
433
+ const { onValueChange, defaultValue, ...etc } = props;
434
+ const isControlled = props.value != null;
435
+ const store = useStore();
436
+ const search = useCommandState((state) => state.search);
437
+ const selectedItemId = useCommandState((state) => state.selectedItemId);
438
+ const context = useCommand();
439
+ const initialDefault = React.useRef(defaultValue);
440
+ const { setInputId } = context;
441
+ useIsoLayoutEffect(() => {
442
+ setInputId(props.id);
443
+ return () => setInputId(void 0);
444
+ }, [props.id, setInputId]);
445
+ useIsoLayoutEffect(() => {
446
+ if (initialDefault.current != null) store.setState("search", String(initialDefault.current));
447
+ }, [store]);
448
+ useIsoLayoutEffect(() => {
449
+ if (props.value != null) store.setState("search", props.value);
450
+ }, [props.value]);
451
+ return /* @__PURE__ */ jsx("input", {
452
+ ref: forwardedRef,
453
+ ...etc,
454
+ "cmdk-input": "",
455
+ autoComplete: "off",
456
+ autoCorrect: "off",
457
+ spellCheck: false,
458
+ "aria-autocomplete": "list",
459
+ role: "combobox",
460
+ "aria-expanded": true,
461
+ "aria-controls": context.listId,
462
+ "aria-labelledby": etc["aria-labelledby"] ?? (etc["aria-label"] ? void 0 : context.labelledBy),
463
+ "aria-activedescendant": selectedItemId,
464
+ id: props.id ?? context.inputId,
465
+ type: "text",
466
+ value: isControlled ? props.value : search,
467
+ onChange: (e) => {
468
+ if (!isControlled) store.setState("search", e.target.value);
469
+ onValueChange?.(e.target.value);
470
+ }
471
+ });
472
+ });
473
+ /**
474
+ * Contains `Item`, `Group`, and `Separator`.
475
+ * Use the `--cmdk-list-height` CSS variable to animate height based on the number of results.
476
+ */
477
+ const CommandList = React.forwardRef((props, forwardedRef) => {
478
+ const { children: _children, label = "Suggestions", ...etc } = props;
479
+ const ref = React.useRef(null);
480
+ const mergedRef = useMergedRefs(ref, forwardedRef);
481
+ const height = React.useRef(null);
482
+ const selectedItemId = useCommandState((state) => state.selectedItemId);
483
+ const context = useCommand();
484
+ const innerRef = useMergedRefs(height, context.listInnerRef);
485
+ const { setListId, markDirty } = context;
486
+ useIsoLayoutEffect(() => {
487
+ const list = height.current;
488
+ if (!list) return;
489
+ const observer = new MutationObserver((changes) => {
490
+ if (changes.some(({ target, attributeName }) => attributeName === "inert" || !target.matches("[cmdk-group]"))) markDirty();
491
+ });
492
+ const options = {
493
+ attributes: true,
494
+ attributeFilter: ["hidden", "inert"]
495
+ };
496
+ observer.observe(list, {
497
+ ...options,
498
+ subtree: true
499
+ });
500
+ for (let parent = list.parentElement; parent; parent = parent.parentElement) observer.observe(parent, options);
501
+ return () => observer.disconnect();
502
+ }, [markDirty]);
503
+ useIsoLayoutEffect(() => {
504
+ setListId(props.id);
505
+ return () => setListId(void 0);
506
+ }, [props.id, setListId]);
507
+ React.useEffect(() => {
508
+ if (height.current && ref.current) {
509
+ const el = height.current;
510
+ const wrapper = ref.current;
511
+ let animationFrame;
512
+ const observer = new ResizeObserver(() => {
513
+ animationFrame = requestAnimationFrame(() => {
514
+ const height = el.offsetHeight;
515
+ wrapper.style.setProperty(`--cmdk-list-height`, height.toFixed(1) + "px");
516
+ });
517
+ });
518
+ observer.observe(el);
519
+ return () => {
520
+ if (animationFrame !== void 0) cancelAnimationFrame(animationFrame);
521
+ observer.unobserve(el);
522
+ };
523
+ }
524
+ }, []);
525
+ return /* @__PURE__ */ jsx("div", {
526
+ ref: mergedRef,
527
+ ...etc,
528
+ "cmdk-list": "",
529
+ role: "listbox",
530
+ tabIndex: -1,
531
+ "aria-activedescendant": selectedItemId,
532
+ "aria-label": etc["aria-label"] ?? label,
533
+ id: props.id ?? context.listId,
534
+ children: wrapChildren(props, (child) => /* @__PURE__ */ jsx("div", {
535
+ ref: innerRef,
536
+ "cmdk-list-sizer": "",
537
+ children: child
538
+ }))
539
+ });
540
+ });
541
+ /**
542
+ * Renders the command menu in a Base UI Dialog.
543
+ */
544
+ const CommandDialog = React.forwardRef((props, forwardedRef) => {
545
+ const { open, defaultOpen, modal, onOpenChange, onOpenChangeComplete, disablePointerDismissal, actionsRef, handle, triggerId, defaultTriggerId, overlayClassName, contentClassName, container, ...etc } = props;
546
+ return /* @__PURE__ */ jsx(Dialog.Root, {
547
+ open,
548
+ defaultOpen,
549
+ modal,
550
+ onOpenChange,
551
+ onOpenChangeComplete,
552
+ disablePointerDismissal,
553
+ actionsRef,
554
+ handle,
555
+ triggerId,
556
+ defaultTriggerId,
557
+ children: /* @__PURE__ */ jsxs(Dialog.Portal, {
558
+ container,
559
+ children: [/* @__PURE__ */ jsx(Dialog.Backdrop, {
560
+ "cmdk-overlay": "",
561
+ className: overlayClassName
562
+ }), /* @__PURE__ */ jsx(Dialog.Popup, {
563
+ "aria-labelledby": props["aria-labelledby"],
564
+ "aria-label": props.label ?? props["aria-label"],
565
+ "cmdk-dialog": "",
566
+ className: contentClassName,
567
+ children: /* @__PURE__ */ jsx(CommandRoot, {
568
+ ref: forwardedRef,
569
+ ...etc
570
+ })
571
+ })]
572
+ })
573
+ });
574
+ });
575
+ /**
576
+ * Automatically renders when there are no results for the search query.
577
+ */
578
+ const CommandEmpty = React.forwardRef((props, forwardedRef) => {
579
+ if (!useCommandState((state) => state.ready && state.filtered.count === 0)) return null;
580
+ return /* @__PURE__ */ jsx("div", {
581
+ ref: forwardedRef,
582
+ ...props,
583
+ "cmdk-empty": "",
584
+ role: "presentation"
585
+ });
586
+ });
587
+ /**
588
+ * You should conditionally render this with `progress` while loading asynchronous items.
589
+ */
590
+ const CommandLoading = React.forwardRef((props, forwardedRef) => {
591
+ const { progress, children: _children, label = "Loading...", ...etc } = props;
592
+ return /* @__PURE__ */ jsx("div", {
593
+ ref: forwardedRef,
594
+ ...etc,
595
+ "cmdk-loading": "",
596
+ role: "progressbar",
597
+ "aria-valuenow": progress,
598
+ "aria-valuemin": 0,
599
+ "aria-valuemax": 100,
600
+ "aria-label": label,
601
+ children: wrapChildren(props, (child) => /* @__PURE__ */ jsx("div", {
602
+ "aria-hidden": true,
603
+ children: child
604
+ }))
605
+ });
606
+ });
607
+ // src/root.tsx
608
+ function readParts(children) {
609
+ let input;
610
+ let list;
611
+ function visit(nodes) {
612
+ React.Children.forEach(nodes, (node) => {
613
+ if (input && list || !React.isValidElement(node)) return;
614
+ if (node.type === CommandInput) input ??= node.props;
615
+ else if (node.type === CommandList) list ??= node.props;
616
+ else if (typeof node.type === "string" || node.type === React.Fragment || node.type === React.Suspense) visit(node.props.children);
617
+ });
618
+ }
619
+ visit(children);
620
+ return {
621
+ input,
622
+ list
623
+ };
624
+ }
625
+ const CommandRoot = React.forwardRef((props, forwardedRef) => {
626
+ const { label, children: _children, value, defaultValue, defaultSearch, onValueChange: _onValueChange, filter, shouldFilter, loop: _loop, tabToGroup = false, disablePointerSelection, vimBindings = true, ...etc } = props;
627
+ const propsRef = useValueAsRef(props);
628
+ const declared = React.useMemo(() => readParts(props.children), [props.children]);
629
+ const generatedListId = React.useId();
630
+ const [mountedListId, setListId] = React.useState();
631
+ const listId = declared.list?.id ?? mountedListId ?? generatedListId;
632
+ const labelId = React.useId();
633
+ const generatedInputId = React.useId();
634
+ const [mountedInputId, setInputId] = React.useState();
635
+ const inputId = declared.input?.id ?? mountedInputId ?? generatedInputId;
636
+ const listInnerRef = React.useRef(null);
637
+ const [, invalidate] = React.useReducer((n) => n + 1, 0);
638
+ const collection = useRefWithInit(() => createCollection(invalidate)).current;
639
+ const listeners = useRefWithInit(() => /* @__PURE__ */ new Set()).current;
640
+ const state = useRefWithInit(() => {
641
+ const search = String(declared.input?.value ?? declared.input?.defaultValue ?? defaultSearch ?? "");
642
+ return {
643
+ search,
644
+ value: (value ?? defaultValue ?? "").trim(),
645
+ ready: false,
646
+ filtered: {
647
+ ...collection.filterItems(search),
648
+ ranked: shouldFilter !== false && Boolean(search)
649
+ }
650
+ };
651
+ });
652
+ const ordering = React.useRef(null);
653
+ const resetSelection = React.useRef(false);
654
+ const accessibleName = label ?? props["aria-label"];
655
+ const labelledBy = props["aria-labelledby"] ?? (accessibleName ? labelId : void 0);
656
+ function publish(change) {
657
+ state.current = {
658
+ ...state.current,
659
+ ...change
660
+ };
661
+ listeners.forEach((listener) => listener());
662
+ }
663
+ function restoreOrder() {
664
+ ordering.current?.arrange();
665
+ ordering.current?.disconnect();
666
+ ordering.current = null;
667
+ }
668
+ const store = useRefWithInit(() => ({
669
+ initialSnapshot: state.current,
670
+ snapshot: () => state.current,
671
+ subscribe(cb) {
672
+ listeners.add(cb);
673
+ return () => listeners.delete(cb);
674
+ },
675
+ setState(key, next, skipScroll) {
676
+ if (state.current[key] === next) return;
677
+ if (key === "search") {
678
+ if (!next) restoreOrder();
679
+ resetSelection.current = true;
680
+ publish({
681
+ search: next,
682
+ filtered: collection.filterItems(next)
683
+ });
684
+ invalidate();
685
+ return;
686
+ }
687
+ if (propsRef.current.value === void 0) {
688
+ publish({
689
+ value: next,
690
+ selectedItemId: getItemByValue(next)?.id
691
+ });
692
+ const focused = focusedMenuElement();
693
+ if (focused?.matches("[cmdk-root]")) focused.querySelector("[cmdk-input]")?.focus();
694
+ }
695
+ propsRef.current.onValueChange?.(next);
696
+ if (!skipScroll) scrollSelectedIntoView();
697
+ }
698
+ })).current;
699
+ const context = React.useMemo(() => ({
700
+ ...collection,
701
+ disablePointerSelection,
702
+ initialScore: (item, keywords) => (filter ?? defaultFilter)(item, store.initialSnapshot.search, keywords?.map((word) => word.trim())),
703
+ setInputId,
704
+ setListId,
705
+ labelledBy,
706
+ listId,
707
+ labelId,
708
+ inputId,
709
+ listInnerRef
710
+ }), [
711
+ collection,
712
+ disablePointerSelection,
713
+ labelledBy,
714
+ listId,
715
+ labelId,
716
+ inputId,
717
+ filter,
718
+ store
719
+ ]);
720
+ useIsoLayoutEffect(() => {
721
+ if (collection.refresh(filter, shouldFilter)) {
722
+ if (shouldFilter === false) restoreOrder();
723
+ publish({
724
+ filtered: collection.filterItems(state.current.search),
725
+ ready: true
726
+ });
727
+ invalidate();
728
+ return;
729
+ }
730
+ const list = listInnerRef.current;
731
+ if (list && state.current.filtered.ranked) {
732
+ if (ordering.current?.list !== list) {
733
+ ordering.current?.disconnect();
734
+ ordering.current = trackOrder(list, () => ordering.current?.arrange(state.current.filtered));
735
+ }
736
+ ordering.current.arrange(state.current.filtered);
737
+ } else if (ordering.current) restoreOrder();
738
+ const selectedValue = value?.trim() ?? state.current.value;
739
+ let selected = getItemByValue(selectedValue);
740
+ if (value !== void 0 && state.current.value !== selectedValue) publish({
741
+ value: selectedValue,
742
+ selectedItemId: selected?.id
743
+ });
744
+ const selectFirst = value === void 0 && (resetSelection.current || !selected);
745
+ resetSelection.current = false;
746
+ if (selectFirst) {
747
+ const first = getValidItems()[0];
748
+ store.setState("value", first?.getAttribute("data-value") ?? "");
749
+ selected = first;
750
+ }
751
+ if (state.current.selectedItemId !== selected?.id) publish({ selectedItemId: selected?.id });
752
+ });
753
+ useIsoLayoutEffect(() => () => {
754
+ ordering.current?.disconnect();
755
+ ordering.current = null;
756
+ }, []);
757
+ function focusedMenuElement() {
758
+ const list = listInnerRef.current;
759
+ const focused = (list?.getRootNode())?.activeElement;
760
+ return focused && focused.closest("[cmdk-root]") === list?.closest("[cmdk-root]") ? focused : null;
761
+ }
762
+ function isAvailable(item) {
763
+ return !item.closest("[hidden], [inert]") && item.closest("[cmdk-list-sizer]") === listInnerRef.current;
764
+ }
765
+ function getValidItems() {
766
+ return Array.from(listInnerRef.current?.querySelectorAll("[cmdk-item=\"\"]:not([aria-disabled=\"true\"])") ?? []).filter(isAvailable);
767
+ }
768
+ function getItemByValue(value) {
769
+ if (!value) return;
770
+ const query = VALID_ITEM_SELECTOR + `[${VALUE_ATTR}="${CSS.escape(value)}"]`;
771
+ return Array.from(listInnerRef.current?.querySelectorAll(query) ?? []).find(isAvailable);
772
+ }
773
+ function getSelectedItem() {
774
+ return getItemByValue(state.current.value);
775
+ }
776
+ function scrollSelectedIntoView() {
777
+ requestAnimationFrame(() => {
778
+ if (!focusedMenuElement()?.matches("[cmdk-input], [cmdk-root], [cmdk-list]")) return;
779
+ const item = getSelectedItem();
780
+ if (item) {
781
+ if (item.parentElement?.firstElementChild === item) item.closest(GROUP_SELECTOR)?.querySelector(GROUP_HEADING_SELECTOR)?.scrollIntoView({ block: "nearest" });
782
+ item.scrollIntoView({ block: "nearest" });
783
+ }
784
+ });
785
+ }
786
+ /** Setters */
787
+ function updateSelectedToIndex(index) {
788
+ const item = getValidItems()[index];
789
+ if (item) store.setState("value", item.getAttribute("data-value") ?? "");
790
+ }
791
+ function updateSelectedByItem(change) {
792
+ const selected = getSelectedItem();
793
+ const items = getValidItems();
794
+ const index = items.findIndex((item) => item === selected);
795
+ let newSelected = items[index + change];
796
+ if (propsRef.current?.loop) newSelected = index + change < 0 ? items[items.length - 1] : index + change === items.length ? items[0] : items[index + change];
797
+ if (newSelected) store.setState("value", newSelected.getAttribute("data-value") ?? "");
798
+ }
799
+ function updateSelectedByGroup(change, cycle = false) {
800
+ const currentGroup = getSelectedItem()?.closest(GROUP_SELECTOR);
801
+ const groups = /* @__PURE__ */ new Map();
802
+ for (const option of getValidItems()) {
803
+ const group = option.closest(GROUP_SELECTOR);
804
+ if (group && !groups.has(group)) groups.set(group, option);
805
+ }
806
+ const index = currentGroup ? [...groups.keys()].indexOf(currentGroup) : -1;
807
+ const items = [...groups.values()];
808
+ if (cycle && items.length < 2) return;
809
+ const nextIndex = cycle ? (index + change + items.length) % items.length : index + change;
810
+ const item = index < 0 ? void 0 : items[nextIndex];
811
+ if (item) store.setState("value", item.getAttribute("data-value") ?? "");
812
+ else updateSelectedByItem(change);
813
+ }
814
+ const last = () => updateSelectedToIndex(getValidItems().length - 1);
815
+ const next = (e) => {
816
+ e.preventDefault();
817
+ if (e.metaKey) last();
818
+ else if (e.altKey) updateSelectedByGroup(1);
819
+ else updateSelectedByItem(1);
820
+ };
821
+ const prev = (e) => {
822
+ e.preventDefault();
823
+ if (e.metaKey) updateSelectedToIndex(0);
824
+ else if (e.altKey) updateSelectedByGroup(-1);
825
+ else updateSelectedByItem(-1);
826
+ };
827
+ return /* @__PURE__ */ jsxs("div", {
828
+ ref: forwardedRef,
829
+ tabIndex: -1,
830
+ ...etc,
831
+ "cmdk-root": "",
832
+ onKeyDown: (e) => {
833
+ etc.onKeyDown?.(e);
834
+ const isComposing = e.nativeEvent.isComposing || e.keyCode === 229;
835
+ if (e.defaultPrevented || isComposing || e.target !== e.currentTarget && (!(e.target instanceof Element) || !e.target.matches("[cmdk-input], [cmdk-list]") || e.target.closest("[cmdk-root]") !== e.currentTarget)) return;
836
+ switch (e.key) {
837
+ case "Tab":
838
+ if (tabToGroup && !e.ctrlKey && !e.metaKey && !e.altKey) {
839
+ e.preventDefault();
840
+ updateSelectedByGroup(e.shiftKey ? -1 : 1, true);
841
+ }
842
+ break;
843
+ case "n":
844
+ case "j":
845
+ if (vimBindings && e.ctrlKey) next(e);
846
+ break;
847
+ case "ArrowDown":
848
+ next(e);
849
+ break;
850
+ case "p":
851
+ case "k":
852
+ if (vimBindings && e.ctrlKey) prev(e);
853
+ break;
854
+ case "ArrowUp":
855
+ prev(e);
856
+ break;
857
+ case "Home":
858
+ e.preventDefault();
859
+ updateSelectedToIndex(0);
860
+ break;
861
+ case "End":
862
+ e.preventDefault();
863
+ last();
864
+ break;
865
+ case "Enter": {
866
+ e.preventDefault();
867
+ const item = getSelectedItem();
868
+ if (item) {
869
+ const event = new Event(SELECT_EVENT);
870
+ item.dispatchEvent(event);
871
+ }
872
+ }
873
+ }
874
+ },
875
+ children: [accessibleName && /* @__PURE__ */ jsx("label", {
876
+ "cmdk-label": "",
877
+ htmlFor: context.inputId,
878
+ id: context.labelId,
879
+ style: srOnlyStyles,
880
+ children: accessibleName
881
+ }), wrapChildren(props, (child) => /* @__PURE__ */ jsx(StoreContext.Provider, {
882
+ value: store,
883
+ children: /* @__PURE__ */ jsx(CommandContext.Provider, {
884
+ value: context,
885
+ children: /* @__PURE__ */ jsx(GroupContext.Provider, {
886
+ value: null,
887
+ children: child
888
+ })
889
+ })
890
+ }))]
891
+ });
892
+ });
893
+ const srOnlyStyles = {
894
+ position: "absolute",
895
+ width: "1px",
896
+ height: "1px",
897
+ padding: "0",
898
+ margin: "-1px",
899
+ overflow: "hidden",
900
+ clip: "rect(0, 0, 0, 0)",
901
+ whiteSpace: "nowrap",
902
+ borderWidth: "0"
903
+ };
904
+ // src/index.ts
905
+ const Command = Object.assign(CommandRoot, {
906
+ Dialog: CommandDialog,
907
+ Empty: CommandEmpty,
908
+ Group: CommandGroup,
909
+ Input: CommandInput,
910
+ Item: CommandItem,
911
+ List: CommandList,
912
+ Loading: CommandLoading,
913
+ Separator: CommandSeparator
914
+ });
915
+ export { Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandLoading, CommandRoot, CommandSeparator, defaultFilter, useCommandState };