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/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "base-cmdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Fast, unstyled React 19 command menu built on Base UI — SSR & hydration safe, source-order preserving, zero Radix.",
5
5
  "license": "MIT",
6
6
  "author": "Zack <heyloyep@gmail.com> (https://github.com/loyep)",
7
- "homepage": "https://github.com/loyep/base-cmdk#readme",
7
+ "homepage": "https://www.npmjs.com/package/base-cmdk",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/loyep/base-cmdk.git"
@@ -45,10 +45,13 @@
45
45
  "node": ">=20"
46
46
  },
47
47
  "scripts": {
48
- "build": "rm -rf dist && tsc -p tsconfig.json",
48
+ "dev": "vite",
49
+ "build": "tsdown",
50
+ "build:playground": "vite build",
49
51
  "typecheck": "tsc -p tsconfig.json --noEmit",
50
52
  "test": "bun run build && bun tests/package.mjs",
51
- "check": "bun run typecheck && bun run build && bun run test",
53
+ "check": "bun run typecheck && bun run build && bun run build:playground && bun run test",
54
+ "release": "node scripts/release.mjs",
52
55
  "prepack": "npm run build"
53
56
  },
54
57
  "dependencies": {
@@ -63,9 +66,12 @@
63
66
  "@types/node": "^22.0.0",
64
67
  "@types/react": "19.3.3",
65
68
  "@types/react-dom": "19.3.0",
69
+ "@vitejs/plugin-react": "6.3.1",
66
70
  "playwright": "1.65.1",
67
71
  "react": "19.3.0",
68
72
  "react-dom": "19.3.0",
69
- "typescript": "7.0.2"
73
+ "tsdown": "0.23.8",
74
+ "typescript": "7.0.2",
75
+ "vite": "8.4.1"
70
76
  }
71
77
  }
@@ -1,11 +0,0 @@
1
- import type { CommandFilter, ItemData, State } from "./types.js";
2
- export declare const defaultFilter: CommandFilter;
3
- export declare function createCollection(invalidate: () => void): {
4
- refresh(nextFilter?: CommandFilter, shouldFilter?: boolean): boolean;
5
- filterItems: (search: string) => State["filtered"];
6
- markDirty: () => void;
7
- updateItem(id: string, item: ItemData): void;
8
- removeItem(id: string): void;
9
- updateGroup(id: string, forced: boolean, hidden: boolean, parentId?: string): void;
10
- removeGroup(id: string): void;
11
- };
@@ -1,100 +0,0 @@
1
- import { commandScore } from "./command-score.js";
2
- export const defaultFilter = (value, search, keywords = []) => commandScore(value, search, keywords);
3
- export function createCollection(invalidate) {
4
- const items = new Map();
5
- const groups = new Map();
6
- let dirty = true;
7
- let filter = defaultFilter;
8
- let automatic = true;
9
- function markDirty() {
10
- if (!dirty) {
11
- dirty = true;
12
- invalidate();
13
- }
14
- }
15
- function filterItems(search) {
16
- const ranked = automatic && Boolean(search);
17
- const scores = new Map();
18
- const visibleGroups = new Set();
19
- const unavailable = new Set();
20
- function groupHidden(groupId) {
21
- while (groupId) {
22
- const group = groups.get(groupId);
23
- if (group?.hidden)
24
- return true;
25
- groupId = group?.parentId;
26
- }
27
- return false;
28
- }
29
- function showGroup(groupId) {
30
- while (groupId && !visibleGroups.has(groupId)) {
31
- visibleGroups.add(groupId);
32
- groupId = groups.get(groupId)?.parentId;
33
- }
34
- }
35
- for (const [id, group] of groups) {
36
- if ((group.forced || !ranked) && !groupHidden(id))
37
- showGroup(id);
38
- }
39
- for (const [id, item] of items) {
40
- const hidden = item.hidden ||
41
- groupHidden(item.groupId) ||
42
- item.parent?.closest("[hidden]:not([cmdk-group]), [inert]");
43
- if (hidden)
44
- unavailable.add(id);
45
- const rank = hidden ? 0 : ranked ? filter(item.value, search, item.keywords) : 1;
46
- scores.set(id, rank);
47
- if (rank > 0)
48
- showGroup(item.groupId);
49
- }
50
- let count = 0;
51
- for (const [id, item] of items) {
52
- if (unavailable.has(id) || (item.groupId && !visibleGroups.has(item.groupId)))
53
- continue;
54
- if (item.forced || (scores.get(id) ?? 0) > 0)
55
- count++;
56
- }
57
- return { ranked, count, items: scores, groups: visibleGroups };
58
- }
59
- return {
60
- refresh(nextFilter = defaultFilter, shouldFilter = true) {
61
- const changed = dirty || filter !== nextFilter || automatic !== shouldFilter;
62
- filter = nextFilter;
63
- automatic = shouldFilter;
64
- dirty = false;
65
- return changed;
66
- },
67
- filterItems,
68
- markDirty,
69
- updateItem(id, item) {
70
- const last = items.get(id);
71
- if (last &&
72
- last.value === item.value &&
73
- last.groupId === item.groupId &&
74
- last.parent === item.parent &&
75
- last.forced === item.forced &&
76
- last.disabled === item.disabled &&
77
- last.hidden === item.hidden &&
78
- last.keywords.length === item.keywords.length &&
79
- last.keywords.every((word, index) => word === item.keywords[index]))
80
- return;
81
- items.set(id, item);
82
- markDirty();
83
- },
84
- removeItem(id) {
85
- if (items.delete(id))
86
- markDirty();
87
- },
88
- updateGroup(id, forced, hidden, parentId) {
89
- const last = groups.get(id);
90
- if (last && last.forced === forced && last.hidden === hidden && last.parentId === parentId)
91
- return;
92
- groups.set(id, { forced, hidden, parentId });
93
- markDirty();
94
- },
95
- removeGroup(id) {
96
- if (groups.delete(id))
97
- markDirty();
98
- },
99
- };
100
- }
@@ -1 +0,0 @@
1
- export declare function commandScore(string: string, abbreviation: string, aliases: string[]): number;
@@ -1,123 +0,0 @@
1
- // This is a fork of https://github.com/pacocoursey/cmdk/blob/main/cmdk/src/command-score.ts
2
- // The scores are arranged so that a continuous match of characters will
3
- // result in a total score of 1.
4
- //
5
- // The best case, this character is a match, and either this is the start
6
- // of the string, or the previous character was also a match.
7
- const SCORE_CONTINUE_MATCH = 1,
8
- // A new match at the start of a word scores better than a new match
9
- // elsewhere as it's more likely that the user will type the starts
10
- // of fragments.
11
- // NOTE: We score word jumps between spaces slightly higher than slashes, brackets
12
- // hyphens, etc.
13
- SCORE_SPACE_WORD_JUMP = 0.9, SCORE_NON_SPACE_WORD_JUMP = 0.8,
14
- // Any other match isn't ideal, but we include it for completeness.
15
- SCORE_CHARACTER_JUMP = 0.17,
16
- // If the user transposed two letters, it should be significantly penalized.
17
- //
18
- // i.e. "ouch" is more likely than "curtain" when "uc" is typed.
19
- SCORE_TRANSPOSITION = 0.1,
20
- // The goodness of a match should decay slightly with each missing
21
- // character.
22
- //
23
- // i.e. "bad" is more likely than "bard" when "bd" is typed.
24
- //
25
- // This will not change the order of suggestions based on SCORE_* until
26
- // 100 characters are inserted between matches.
27
- PENALTY_SKIPPED = 0.999,
28
- // The goodness of an exact-case match should be higher than a
29
- // case-insensitive match by a small amount.
30
- //
31
- // i.e. "HTML" is more likely than "haml" when "HM" is typed.
32
- //
33
- // This will not change the order of suggestions based on SCORE_* until
34
- // 1000 characters are inserted between matches.
35
- PENALTY_CASE_MISMATCH = 0.9999,
36
- // Match higher for letters closer to the beginning of the word
37
- // PENALTY_DISTANCE_FROM_START = 0.9,
38
- // If the word has more characters than the user typed, it should
39
- // be penalised slightly.
40
- //
41
- // i.e. "html" is more likely than "html5" if I type "html".
42
- //
43
- // However, it may well be the case that there's a sensible secondary
44
- // ordering (like alphabetical) that it makes sense to rely on when
45
- // there are many prefix matches, so we don't make the penalty increase
46
- // with the number of tokens.
47
- PENALTY_NOT_COMPLETE = 0.99;
48
- const IS_GAP_REGEXP = /[\\/_+.#"@[({&]/, COUNT_GAPS_REGEXP = /[\\/_+.#"@[({&]/g, IS_SPACE_REGEXP = /[\s-]/, COUNT_SPACE_REGEXP = /[\s-]/g;
49
- function commandScoreInner(value, abbreviation, lowerString, lowerAbbreviation, stringIndex, abbreviationIndex, memoizedResults) {
50
- if (abbreviationIndex === abbreviation.length) {
51
- if (stringIndex === value.length) {
52
- return SCORE_CONTINUE_MATCH;
53
- }
54
- return PENALTY_NOT_COMPLETE;
55
- }
56
- const memoizeKey = `${stringIndex},${abbreviationIndex}`;
57
- if (memoizedResults[memoizeKey] !== undefined) {
58
- return memoizedResults[memoizeKey];
59
- }
60
- const abbreviationChar = lowerAbbreviation.charAt(abbreviationIndex);
61
- let index = lowerString.indexOf(abbreviationChar, stringIndex);
62
- let highScore = 0;
63
- let score, transposedScore, wordBreaks, spaceBreaks;
64
- while (index >= 0) {
65
- score = commandScoreInner(value, abbreviation, lowerString, lowerAbbreviation, index + 1, abbreviationIndex + 1, memoizedResults);
66
- if (score > highScore) {
67
- if (index === stringIndex) {
68
- score *= SCORE_CONTINUE_MATCH;
69
- }
70
- else if (IS_GAP_REGEXP.test(value.charAt(index - 1))) {
71
- score *= SCORE_NON_SPACE_WORD_JUMP;
72
- wordBreaks = value.slice(stringIndex, index - 1).match(COUNT_GAPS_REGEXP);
73
- if (wordBreaks && stringIndex > 0) {
74
- score *= Math.pow(PENALTY_SKIPPED, wordBreaks.length);
75
- }
76
- }
77
- else if (IS_SPACE_REGEXP.test(value.charAt(index - 1))) {
78
- score *= SCORE_SPACE_WORD_JUMP;
79
- spaceBreaks = value.slice(stringIndex, index - 1).match(COUNT_SPACE_REGEXP);
80
- if (spaceBreaks && stringIndex > 0) {
81
- score *= Math.pow(PENALTY_SKIPPED, spaceBreaks.length);
82
- }
83
- }
84
- else {
85
- score *= SCORE_CHARACTER_JUMP;
86
- if (stringIndex > 0) {
87
- score *= Math.pow(PENALTY_SKIPPED, index - stringIndex);
88
- }
89
- }
90
- if (value.charAt(index) !== abbreviation.charAt(abbreviationIndex)) {
91
- score *= PENALTY_CASE_MISMATCH;
92
- }
93
- }
94
- if ((score < SCORE_TRANSPOSITION &&
95
- lowerString.charAt(index - 1) === lowerAbbreviation.charAt(abbreviationIndex + 1)) ||
96
- (lowerAbbreviation.charAt(abbreviationIndex + 1) ===
97
- lowerAbbreviation.charAt(abbreviationIndex) && // allow duplicate letters. Ref #7428
98
- lowerString.charAt(index - 1) !== lowerAbbreviation.charAt(abbreviationIndex))) {
99
- transposedScore = commandScoreInner(value, abbreviation, lowerString, lowerAbbreviation, index + 1, abbreviationIndex + 2, memoizedResults);
100
- if (transposedScore * SCORE_TRANSPOSITION > score) {
101
- score = transposedScore * SCORE_TRANSPOSITION;
102
- }
103
- }
104
- if (score > highScore) {
105
- highScore = score;
106
- }
107
- index = lowerString.indexOf(abbreviationChar, index + 1);
108
- }
109
- memoizedResults[memoizeKey] = highScore;
110
- return highScore;
111
- }
112
- function formatInput(value) {
113
- // convert all valid space characters to space so they match each other
114
- return value.toLowerCase().replace(COUNT_SPACE_REGEXP, " ");
115
- }
116
- export function commandScore(string, abbreviation, aliases) {
117
- /* NOTE:
118
- * in the original, we used to do the lower-casing on each recursive call, but this meant that toLowerCase()
119
- * was the dominating cost in the algorithm, passing both is a little ugly, but considerably faster.
120
- */
121
- string = aliases && aliases.length > 0 ? `${string + " " + aliases.join(" ")}` : string;
122
- return commandScoreInner(string, abbreviation, formatInput(string), formatInput(abbreviation), 0, 0, {});
123
- }
package/dist/context.d.ts DELETED
@@ -1,19 +0,0 @@
1
- import * as React from "react";
2
- import type { Context, Group, State, Store } from "./types.js";
3
- export declare const GROUP_SELECTOR = "[cmdk-group=\"\"]";
4
- export declare const GROUP_HEADING_SELECTOR = "[cmdk-group-heading=\"\"]";
5
- export declare const ITEM_SELECTOR = "[cmdk-item=\"\"]";
6
- export declare const VALID_ITEM_SELECTOR = "[cmdk-item=\"\"]:not([aria-disabled=\"true\"])";
7
- export declare const SELECT_EVENT = "cmdk-item-select";
8
- export declare const VALUE_ATTR = "data-value";
9
- export declare const CommandContext: React.Context<Context | null>;
10
- export declare const StoreContext: React.Context<Store | null>;
11
- export declare const GroupContext: React.Context<Group | null>;
12
- export declare function useCommand(): Context;
13
- export declare function useStore(): Store;
14
- /** Run a selector against the store state. */
15
- export declare function useCommandState<T>(selector: (state: State) => T): T;
16
- export declare function wrapChildren({ asChild, children }: {
17
- asChild?: boolean;
18
- children?: React.ReactNode;
19
- }, render: (children: React.ReactNode) => React.ReactElement): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>;
package/dist/context.js DELETED
@@ -1,48 +0,0 @@
1
- import * as React from "react";
2
- export const GROUP_SELECTOR = `[cmdk-group=""]`;
3
- export const GROUP_HEADING_SELECTOR = `[cmdk-group-heading=""]`;
4
- export const ITEM_SELECTOR = `[cmdk-item=""]`;
5
- export const VALID_ITEM_SELECTOR = `${ITEM_SELECTOR}:not([aria-disabled="true"])`;
6
- export const SELECT_EVENT = `cmdk-item-select`;
7
- export const VALUE_ATTR = `data-value`;
8
- export const CommandContext = React.createContext(null);
9
- export const StoreContext = React.createContext(null);
10
- export const GroupContext = React.createContext(null);
11
- export function useCommand() {
12
- const context = React.useContext(CommandContext);
13
- if (!context)
14
- throw new Error("Command parts must be rendered inside a Command.");
15
- return context;
16
- }
17
- export function useStore() {
18
- const store = React.useContext(StoreContext);
19
- if (!store)
20
- throw new Error("Command state must be read inside a Command.");
21
- return store;
22
- }
23
- /** Run a selector against the store state. */
24
- export function useCommandState(selector) {
25
- const store = useStore();
26
- const [read, readServer] = React.useMemo(() => {
27
- function memoize(getSnapshot) {
28
- let previous;
29
- let selection;
30
- return () => {
31
- const snapshot = getSnapshot();
32
- if (previous !== snapshot) {
33
- selection = selector(snapshot);
34
- previous = snapshot;
35
- }
36
- return selection;
37
- };
38
- }
39
- return [memoize(store.snapshot), memoize(() => store.initialSnapshot)];
40
- }, [store, selector]);
41
- return React.useSyncExternalStore(store.subscribe, read, readServer);
42
- }
43
- export function wrapChildren({ asChild, children }, render) {
44
- if (asChild && React.isValidElement(children)) {
45
- return React.cloneElement(children, undefined, render(children.props.children));
46
- }
47
- return render(children);
48
- }
package/dist/order.d.ts DELETED
@@ -1,6 +0,0 @@
1
- import type { State } from "./types.js";
2
- export declare function trackOrder(list: HTMLElement, onChange: () => void): {
3
- list: HTMLElement;
4
- arrange: (filtered?: State["filtered"]) => void;
5
- disconnect: () => void;
6
- };
package/dist/order.js DELETED
@@ -1,66 +0,0 @@
1
- // React inserts keyed children relative to their next authored sibling. Replay
2
- // those insertions in source order, independently of the current search ranking.
3
- export function trackOrder(list, onChange) {
4
- const movable = new WeakSet();
5
- const authored = new Map();
6
- function record(changes) {
7
- for (const change of changes) {
8
- const siblings = authored.get(change.target);
9
- if (!siblings)
10
- continue;
11
- for (const node of [...change.removedNodes, ...change.addedNodes]) {
12
- const index = siblings.indexOf(node);
13
- if (index !== -1)
14
- siblings.splice(index, 1);
15
- }
16
- const before = change.nextSibling ? siblings.indexOf(change.nextSibling) : -1;
17
- siblings.splice(before < 0 ? siblings.length : before, 0, ...change.addedNodes);
18
- }
19
- }
20
- const observer = new MutationObserver((changes) => {
21
- record(changes);
22
- onChange();
23
- });
24
- observer.observe(list, { childList: true, subtree: true });
25
- function arrange(filtered) {
26
- record(observer.takeRecords());
27
- const scores = new Map();
28
- for (const item of list.querySelectorAll("[cmdk-item], [cmdk-group]")) {
29
- if (item.closest("[cmdk-list-sizer]") !== list)
30
- continue;
31
- const score = filtered?.items.get(item.id) ?? 0;
32
- let node = item;
33
- while (node && node !== list) {
34
- movable.add(node);
35
- scores.set(node, Math.max(scores.get(node) ?? 0, score));
36
- const parent = node.parentElement;
37
- if (parent && !authored.has(parent))
38
- authored.set(parent, Array.from(parent.childNodes));
39
- node = parent;
40
- }
41
- }
42
- for (const [parent, siblings] of authored) {
43
- if (!list.contains(parent)) {
44
- authored.delete(parent);
45
- continue;
46
- }
47
- const results = siblings.filter((node) => movable.has(node));
48
- if (filtered)
49
- results.sort((a, b) => (scores.get(b) ?? 0) - (scores.get(a) ?? 0));
50
- let i = results.length;
51
- let anchor = null;
52
- for (let j = siblings.length - 1; j >= 0; j--) {
53
- let node = siblings[j];
54
- if (movable.has(node)) {
55
- node = results[--i];
56
- if (node.nextSibling !== anchor)
57
- parent.insertBefore(node, anchor);
58
- }
59
- anchor = node;
60
- }
61
- }
62
- // Our own moves are presentation changes, never new source positions.
63
- observer.takeRecords();
64
- }
65
- return { list, arrange, disconnect: () => observer.disconnect() };
66
- }
package/dist/parts.d.ts DELETED
@@ -1,86 +0,0 @@
1
- import * as React from "react";
2
- import { Dialog as BaseDialog } from "@base-ui/react/dialog";
3
- /**
4
- * Command menu item. Becomes active on pointer enter or through keyboard navigation.
5
- * Preferably pass a `value`, otherwise the value will be inferred from `children` or
6
- * the rendered item's `textContent`.
7
- */
8
- export declare const CommandItem: React.ForwardRefExoticComponent<{
9
- children?: React.ReactNode;
10
- } & Omit<Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref">, "disabled" | "onSelect" | "value"> & {
11
- disabled?: boolean;
12
- onSelect?: (value: string) => void;
13
- value?: string;
14
- keywords?: string[];
15
- forceMount?: boolean;
16
- } & React.RefAttributes<HTMLDivElement>>;
17
- /**
18
- * Group command menu items together with a heading.
19
- * Grouped items are always shown together.
20
- */
21
- export declare const CommandGroup: React.ForwardRefExoticComponent<{
22
- children?: React.ReactNode;
23
- } & Omit<Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref">, "heading" | "value"> & {
24
- heading?: React.ReactNode;
25
- value?: string;
26
- forceMount?: boolean;
27
- } & React.RefAttributes<HTMLDivElement>>;
28
- /**
29
- * A visual and semantic separator between items or groups.
30
- * Visible when the search query is empty or `alwaysRender` is true, hidden otherwise.
31
- */
32
- export declare const CommandSeparator: React.ForwardRefExoticComponent<Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref"> & {
33
- alwaysRender?: boolean;
34
- } & React.RefAttributes<HTMLDivElement>>;
35
- /**
36
- * Command menu input.
37
- * All props are forwarded to the underyling `input` element.
38
- */
39
- export declare const CommandInput: React.ForwardRefExoticComponent<Omit<Omit<React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, "ref">, "onChange" | "type" | "value"> & {
40
- value?: string;
41
- onValueChange?: (search: string) => void;
42
- } & React.RefAttributes<HTMLInputElement>>;
43
- /**
44
- * Contains `Item`, `Group`, and `Separator`.
45
- * Use the `--cmdk-list-height` CSS variable to animate height based on the number of results.
46
- */
47
- export declare const CommandList: React.ForwardRefExoticComponent<{
48
- children?: React.ReactNode;
49
- } & Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref"> & {
50
- label?: string;
51
- } & React.RefAttributes<HTMLDivElement>>;
52
- /**
53
- * Renders the command menu in a Base UI Dialog.
54
- */
55
- export declare const CommandDialog: React.ForwardRefExoticComponent<Omit<BaseDialog.Root.Props<unknown>, "children"> & {
56
- children?: React.ReactNode;
57
- } & Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref"> & {
58
- label?: string;
59
- shouldFilter?: boolean;
60
- defaultSearch?: string;
61
- filter?: import("./types.js").CommandFilter;
62
- defaultValue?: string;
63
- value?: string;
64
- onValueChange?: (value: string) => void;
65
- loop?: boolean;
66
- tabToGroup?: boolean;
67
- disablePointerSelection?: boolean;
68
- vimBindings?: boolean;
69
- } & {
70
- overlayClassName?: string;
71
- contentClassName?: string;
72
- container?: HTMLElement | null;
73
- } & React.RefAttributes<HTMLDivElement>>;
74
- /**
75
- * Automatically renders when there are no results for the search query.
76
- */
77
- export declare const CommandEmpty: React.ForwardRefExoticComponent<Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref"> & React.RefAttributes<HTMLDivElement>>;
78
- /**
79
- * You should conditionally render this with `progress` while loading asynchronous items.
80
- */
81
- export declare const CommandLoading: React.ForwardRefExoticComponent<{
82
- children?: React.ReactNode;
83
- } & Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref"> & {
84
- progress?: number;
85
- label?: string;
86
- } & React.RefAttributes<HTMLDivElement>>;