})}
>
```
We didn't want to provide a render prop:
```tsx
// No
onItemRender={({ item }) => {
return
{item}
}}
```
Instead, we wanted to render components:
```tsx
// Yes
My item
```
Especially, we wanted full component composition:
```tsx
// YES
<>
{staticItems}
>
```
Compound components are natural and easy to write. A few months after exploring this library, we were pleased to see [Radix UI](https://www.radix-ui.com) released using this exact approach of component structure – setting the standard for ease of use and composability.
However, for a combobox, it is a terrible, terrible constraint that we've spent 2 years fighting.
## Approach
⌘K always keeps every item and group rendered in the React tree. Each item and group adds or removes itself from the DOM based on the search input. The DOM is authoritative. Item selection order is based on the DOM order, which is based on the React render order, which the consumer provides.
### Discarded approach
We did not use `React.Children` iteration because it will not support component composition. There is no way to "peek inside" the items contained within ``, so those items cannot be filtered.
We did not use an object-based data array for each item, like `{ name: "Logout", action: () => logout() }` because this is strict and limiting. In reality, the interface of those objects grows with edge-cases, like `image`, `detailedSubTitle`, `hideWhenRootSearch`, etc. We prefer that you have full control of item rendering, including icons, keyboard shortcuts, and styling. Don't want an item shown? Don't render it. Only want to show an item under condition xyz? Render it.
We did not use a render prop because they are an inelegant pattern and quickly fall to long, centralised if-else logic chains. For example, if you want a fancy sparkle rainbow item, you need a new if statement to render that item specially.
The original approach for tracking which item was selected was to keep an index 0..n. But it's impossible to know which Item is in which position within the React tree when React Strict Mode is enabled, because `useEffect` runs twice and `useRef` cannot be used for stable IDs. This may be possible with `useId`, now. We created [use-descendants](https://github.com/pacocoursey/use-descendants) to track relative component indeces, but abandoned it because it could not work in Strict Mode, and will be incompatible with upcoming concurrent mode. Now, we track the selected item with its value, because it is stable across item mounts and unmounts.
## Example
```tsx
AB
```
The "A" item should not be shown! But we cannot remove it from the React tree, because the user controls it. In most cases, this is easy because the rendered items is sourced from a backing data array:
```tsx
<>
{['A', 'B'].map((item) => {
if (matches(item, search)) {
return {item}
}
})}
>
```
But in our case, the item will remain in the React tree and just be removed from the DOM:
```tsx
{/* returns `null`, no DOM created */}
AB
```
## Performance
This is more expensive memory wise, because if there are 2,000 items but the list is filtered to only 2 items, we still allocate memory for 2,000 instances of the Item component. But it's our only option! Thankfully we can still keep the DOM size to 2 items.
## Groups
Item mount informs both the root and the parent group, which keeps track of items within it. Each group informs the root.
================================================
FILE: LICENSE.md
================================================
MIT License
Copyright (c) 2022 Paco Coursey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# ⌘K [](https://www.npmjs.com/package/cmdk?activeTab=code) [](https://www.npmjs.com/package/cmdk)
⌘K is a command menu React component that can also be used as an accessible combobox. You render items, it filters and sorts them automatically. ⌘K supports a fully composable API [How?](/ARCHITECTURE.md), so you can wrap items in other components or even as static JSX.
## Install
```bash
pnpm install cmdk
```
## Use
```tsx
import { Command } from 'cmdk'
const CommandMenu = () => {
return (
No results found.abcApple
)
}
```
Or in a dialog:
```tsx
import { Command } from 'cmdk'
const CommandMenu = () => {
const [open, setOpen] = React.useState(false)
// Toggle the menu when ⌘K is pressed
React.useEffect(() => {
const down = (e) => {
if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
setOpen((open) => !open)
}
}
document.addEventListener('keydown', down)
return () => document.removeEventListener('keydown', down)
}, [])
return (
No results found.abcApple
)
}
```
## Parts and styling
All parts forward props, including `ref`, to an appropriate element. Each part has a specific data-attribute (starting with `cmdk-`) that can be used for styling.
### Command `[cmdk-root]`
Render this to show the command menu inline, or use [Dialog](#dialog-cmdk-dialog-cmdk-overlay) to render in a elevated context. Can be controlled with the `value` and `onValueChange` props.
> **Note**
>
> Values are always trimmed with the [trim()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim) method.
```tsx
const [value, setValue] = React.useState('apple')
return (
OrangeApple
)
```
You can provide a custom `filter` function that is called to rank each item. Note that the value will be trimmed.
```tsx
{
if (value.includes(search)) return 1
return 0
}}
/>
```
A third argument, `keywords`, can also be provided to the filter function. Keywords act as aliases for the item value, and can also affect the rank of the item. Keywords are trimmed.
```tsx
{
const extendValue = value + ' ' + keywords.join(' ')
if (extendValue.includes(search)) return 1
return 0
}}
/>
```
Or disable filtering and sorting entirely:
```tsx
{filteredItems.map((item) => {
return (
{item}
)
})}
```
You can make the arrow keys wrap around the list (when you reach the end, it goes back to the first item) by setting the `loop` prop:
```tsx
```
### Dialog `[cmdk-dialog]` `[cmdk-overlay]`
Props are forwarded to [Command](#command-cmdk-root). Composes Radix UI's Dialog component. The overlay is always rendered. See the [Radix Documentation](https://www.radix-ui.com/docs/primitives/components/dialog) for more information. Can be controlled with the `open` and `onOpenChange` props.
```tsx
const [open, setOpen] = React.useState(false)
return (
...
)
```
You can provide a `container` prop that accepts an HTML element that is forwarded to Radix UI's Dialog Portal component to specify which element the Dialog should portal into (defaults to `body`). See the [Radix Documentation](https://www.radix-ui.com/docs/primitives/components/dialog#portal) for more information.
```tsx
const containerElement = React.useRef(null)
return (
<>
>
)
```
### Input `[cmdk-input]`
All props are forwarded to the underlying `input` element. Can be controlled with the `value` and `onValueChange` props.
```tsx
const [search, setSearch] = React.useState('')
return
```
### List `[cmdk-list]`
Contains items and groups. Animate height using the `--cmdk-list-height` CSS variable.
```css
[cmdk-list] {
min-height: 300px;
height: var(--cmdk-list-height);
max-height: 500px;
transition: height 100ms ease;
}
```
To scroll item into view earlier near the edges of the viewport, use scroll-padding:
```css
[cmdk-list] {
scroll-padding-block-start: 8px;
scroll-padding-block-end: 8px;
}
```
### Item `[cmdk-item]` `[data-disabled?]` `[data-selected?]`
Item that becomes active on pointer enter. You should provide a unique `value` for each item, but it will be automatically inferred from the `.textContent`.
```tsx
console.log('Selected', value)}
// Value is implicity "apple" because of the provided text content
>
Apple
```
You can also provide a `keywords` prop to help with filtering. Keywords are trimmed.
```tsx
Apple
```
```tsx
console.log('Selected', value)}
// Value is implicity "apple" because of the provided text content
>
Apple
```
You can force an item to always render, regardless of filtering, by passing the `forceMount` prop.
### Group `[cmdk-group]` `[hidden?]`
Groups items together with the given `heading` (`[cmdk-group-heading]`).
```tsx
Apple
```
Groups will not unmount from the DOM, rather the `hidden` attribute is applied to hide it from view. This may be relevant in your styling.
You can force a group to always render, regardless of filtering, by passing the `forceMount` prop.
### Separator `[cmdk-separator]`
Visible when the search query is empty or `alwaysRender` is true, hidden otherwise.
### Empty `[cmdk-empty]`
Automatically renders when there are no results for the search query.
### Loading `[cmdk-loading]`
You should conditionally render this with `progress` while loading asynchronous items.
```tsx
const [loading, setLoading] = React.useState(false)
return {loading && Hang on…}
```
### `useCommandState(state => state.selectedField)`
Hook that composes [`useSyncExternalStore`](https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore). Pass a function that returns a slice of the command menu state to re-render when that slice changes. This hook is provided for advanced use cases and should not be commonly used.
A good use case would be to render a more detailed empty state, like so:
```tsx
const search = useCommandState((state) => state.search)
return No results found for "{search}".
```
## Examples
Code snippets for common use cases.
### Nested items
Often selecting one item should navigate deeper, with a more refined set of items. For example selecting "Change theme…" should show new items "Dark theme" and "Light theme". We call these sets of items "pages", and they can be implemented with simple state:
```tsx
const ref = React.useRef(null)
const [open, setOpen] = React.useState(false)
const [search, setSearch] = React.useState('')
const [pages, setPages] = React.useState([])
const page = pages[pages.length - 1]
return (
{
// Escape goes to previous page
// Backspace goes to previous page when search is empty
if (e.key === 'Escape' || (e.key === 'Backspace' && !search)) {
e.preventDefault()
setPages((pages) => pages.slice(0, -1))
}
}}
>
{!page && (
<>
setPages([...pages, 'projects'])}>Search projects… setPages([...pages, 'teams'])}>Join a team…
>
)}
{page === 'projects' && (
<>
Project AProject B
>
)}
{page === 'teams' && (
<>
Team 1Team 2
>
)}
)
```
### Show sub-items when searching
If your items have nested sub-items that you only want to reveal when searching, render based on the search state:
```tsx
const SubItem = (props) => {
const search = useCommandState((state) => state.search)
if (!search) return null
return
}
return (
Change theme…Change theme to darkChange theme to light
)
```
### Asynchronous results
Render the items as they become available. Filtering and sorting will happen automatically.
```tsx
const [loading, setLoading] = React.useState(false)
const [items, setItems] = React.useState([])
React.useEffect(() => {
async function getItems() {
setLoading(true)
const res = await api.get('/dictionary')
setItems(res)
setLoading(false)
}
getItems()
}, [])
return (
{loading && Fetching words…}
{items.map((item) => {
return (
{item}
)
})}
)
```
### Use inside Popover
We recommend using the [Radix UI popover](https://www.radix-ui.com/docs/primitives/components/popover) component. ⌘K relies on the Radix UI Dialog component, so this will reduce your bundle size a bit due to shared dependencies.
```bash
$ pnpm install @radix-ui/react-popover
```
Render `Command` inside of the popover content:
```tsx
import * as Popover from '@radix-ui/react-popover'
return (
Toggle popoverApple
)
```
### Drop in stylesheets
You can find global stylesheets to drop in as a starting point for styling. See [website/styles/cmdk](website/styles/cmdk) for examples.
## FAQ
**Accessible?** Yes. Labeling, aria attributes, and DOM ordering tested with Voice Over and Chrome DevTools. [Dialog](#dialog-cmdk-dialog-cmdk-overlay) composes an accessible Dialog implementation.
**Virtualization?** No. Good performance up to 2,000-3,000 items, though. Read below to bring your own.
**Filter/sort items manually?** Yes. Pass `shouldFilter={false}` to [Command](#command-cmdk-root). Better memory usage and performance. Bring your own virtualization this way.
**React 18 safe?** Yes, required. Uses React 18 hooks like `useId` and `useSyncExternalStore`.
**Unstyled?** Yes, use the listed CSS selectors.
**Hydration mismatch?** No, likely a bug in your code. Ensure the `open` prop to `Command.Dialog` is `false` on the server.
**React strict mode safe?** Yes. Open an issue if you notice an issue.
**Weird/wrong behavior?** Make sure your `Command.Item` has a `key` and unique `value`.
**Concurrent mode safe?** Maybe, but concurrent mode is not yet real. Uses risky approaches like manual DOM ordering.
**React server component?** No, it's a client component.
**Listen for ⌘K automatically?** No, do it yourself to have full control over keybind context.
**React Native?** No, and no plans to support it. If you build a React Native version, let us know and we'll link your repository here.
## History
Written in 2019 by Paco ([@pacocoursey](https://twitter.com/pacocoursey)) to see if a composable combobox API was possible. Used for the Vercel command menu and autocomplete by Rauno ([@raunofreiberg](https://twitter.com/raunofreiberg)) in 2020. Re-written independently in 2022 with a simpler and more performant approach. Ideas and help from Shu ([@shuding\_](https://twitter.com/shuding_)).
[use-descendants](https://github.com/pacocoursey/use-descendants) was extracted from the 2019 version.
## Testing
First, install dependencies and Playwright browsers:
```bash
pnpm install
pnpm playwright install
```
Then ensure you've built the library:
```bash
pnpm build
```
Then run the tests using your local build against real browser engines:
```bash
pnpm test
```
================================================
FILE: cmdk/package.json
================================================
{
"name": "cmdk",
"version": "1.1.1",
"license": "MIT",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
}
},
"scripts": {
"prepublishOnly": "cp ../README.md . && pnpm build",
"postpublish": "rm README.md",
"build": "tsup src",
"dev": "tsup src --watch"
},
"peerDependencies": {
"react": "^18 || ^19 || ^19.0.0-rc",
"react-dom": "^18 || ^19 || ^19.0.0-rc"
},
"dependencies": {
"@radix-ui/react-compose-refs": "^1.1.1",
"@radix-ui/react-dialog": "^1.1.6",
"@radix-ui/react-id": "^1.1.0",
"@radix-ui/react-primitive": "^2.0.2"
},
"devDependencies": {
"@types/react": "18.0.15"
},
"sideEffects": false,
"repository": {
"type": "git",
"url": "git+https://github.com/pacocoursey/cmdk.git",
"directory": "cmdk"
},
"bugs": {
"url": "https://github.com/pacocoursey/cmdk/issues"
},
"homepage": "https://github.com/pacocoursey/cmdk#readme",
"author": {
"name": "Paco",
"url": "https://github.com/pacocoursey"
}
}
================================================
FILE: cmdk/src/command-score.ts
================================================
// The scores are arranged so that a continuous match of characters will
// result in a total score of 1.
//
// The best case, this character is a match, and either this is the start
// of the string, or the previous character was also a match.
var SCORE_CONTINUE_MATCH = 1,
// A new match at the start of a word scores better than a new match
// elsewhere as it's more likely that the user will type the starts
// of fragments.
// NOTE: We score word jumps between spaces slightly higher than slashes, brackets
// hyphens, etc.
SCORE_SPACE_WORD_JUMP = 0.9,
SCORE_NON_SPACE_WORD_JUMP = 0.8,
// Any other match isn't ideal, but we include it for completeness.
SCORE_CHARACTER_JUMP = 0.17,
// If the user transposed two letters, it should be significantly penalized.
//
// i.e. "ouch" is more likely than "curtain" when "uc" is typed.
SCORE_TRANSPOSITION = 0.1,
// The goodness of a match should decay slightly with each missing
// character.
//
// i.e. "bad" is more likely than "bard" when "bd" is typed.
//
// This will not change the order of suggestions based on SCORE_* until
// 100 characters are inserted between matches.
PENALTY_SKIPPED = 0.999,
// The goodness of an exact-case match should be higher than a
// case-insensitive match by a small amount.
//
// i.e. "HTML" is more likely than "haml" when "HM" is typed.
//
// This will not change the order of suggestions based on SCORE_* until
// 1000 characters are inserted between matches.
PENALTY_CASE_MISMATCH = 0.9999,
// Match higher for letters closer to the beginning of the word
PENALTY_DISTANCE_FROM_START = 0.9,
// If the word has more characters than the user typed, it should
// be penalised slightly.
//
// i.e. "html" is more likely than "html5" if I type "html".
//
// However, it may well be the case that there's a sensible secondary
// ordering (like alphabetical) that it makes sense to rely on when
// there are many prefix matches, so we don't make the penalty increase
// with the number of tokens.
PENALTY_NOT_COMPLETE = 0.99
var IS_GAP_REGEXP = /[\\\/_+.#"@\[\(\{&]/,
COUNT_GAPS_REGEXP = /[\\\/_+.#"@\[\(\{&]/g,
IS_SPACE_REGEXP = /[\s-]/,
COUNT_SPACE_REGEXP = /[\s-]/g
function commandScoreInner(
string,
abbreviation,
lowerString,
lowerAbbreviation,
stringIndex,
abbreviationIndex,
memoizedResults,
) {
if (abbreviationIndex === abbreviation.length) {
if (stringIndex === string.length) {
return SCORE_CONTINUE_MATCH
}
return PENALTY_NOT_COMPLETE
}
var memoizeKey = `${stringIndex},${abbreviationIndex}`
if (memoizedResults[memoizeKey] !== undefined) {
return memoizedResults[memoizeKey]
}
var abbreviationChar = lowerAbbreviation.charAt(abbreviationIndex)
var index = lowerString.indexOf(abbreviationChar, stringIndex)
var highScore = 0
var score, transposedScore, wordBreaks, spaceBreaks
while (index >= 0) {
score = commandScoreInner(
string,
abbreviation,
lowerString,
lowerAbbreviation,
index + 1,
abbreviationIndex + 1,
memoizedResults,
)
if (score > highScore) {
if (index === stringIndex) {
score *= SCORE_CONTINUE_MATCH
} else if (IS_GAP_REGEXP.test(string.charAt(index - 1))) {
score *= SCORE_NON_SPACE_WORD_JUMP
wordBreaks = string.slice(stringIndex, index - 1).match(COUNT_GAPS_REGEXP)
if (wordBreaks && stringIndex > 0) {
score *= Math.pow(PENALTY_SKIPPED, wordBreaks.length)
}
} else if (IS_SPACE_REGEXP.test(string.charAt(index - 1))) {
score *= SCORE_SPACE_WORD_JUMP
spaceBreaks = string.slice(stringIndex, index - 1).match(COUNT_SPACE_REGEXP)
if (spaceBreaks && stringIndex > 0) {
score *= Math.pow(PENALTY_SKIPPED, spaceBreaks.length)
}
} else {
score *= SCORE_CHARACTER_JUMP
if (stringIndex > 0) {
score *= Math.pow(PENALTY_SKIPPED, index - stringIndex)
}
}
if (string.charAt(index) !== abbreviation.charAt(abbreviationIndex)) {
score *= PENALTY_CASE_MISMATCH
}
}
if (
(score < SCORE_TRANSPOSITION &&
lowerString.charAt(index - 1) === lowerAbbreviation.charAt(abbreviationIndex + 1)) ||
(lowerAbbreviation.charAt(abbreviationIndex + 1) === lowerAbbreviation.charAt(abbreviationIndex) && // allow duplicate letters. Ref #7428
lowerString.charAt(index - 1) !== lowerAbbreviation.charAt(abbreviationIndex))
) {
transposedScore = commandScoreInner(
string,
abbreviation,
lowerString,
lowerAbbreviation,
index + 1,
abbreviationIndex + 2,
memoizedResults,
)
if (transposedScore * SCORE_TRANSPOSITION > score) {
score = transposedScore * SCORE_TRANSPOSITION
}
}
if (score > highScore) {
highScore = score
}
index = lowerString.indexOf(abbreviationChar, index + 1)
}
memoizedResults[memoizeKey] = highScore
return highScore
}
function formatInput(string) {
// convert all valid space characters to space so they match each other
return string.toLowerCase().replace(COUNT_SPACE_REGEXP, ' ')
}
export function commandScore(string: string, abbreviation: string, aliases: string[]): number {
/* NOTE:
* in the original, we used to do the lower-casing on each recursive call, but this meant that toLowerCase()
* was the dominating cost in the algorithm, passing both is a little ugly, but considerably faster.
*/
string = aliases && aliases.length > 0 ? `${string + ' ' + aliases.join(' ')}` : string
return commandScoreInner(string, abbreviation, formatInput(string), formatInput(abbreviation), 0, 0, {})
}
================================================
FILE: cmdk/src/index.tsx
================================================
'use client'
import * as RadixDialog from '@radix-ui/react-dialog'
import * as React from 'react'
import { commandScore } from './command-score'
import { Primitive } from '@radix-ui/react-primitive'
import { useId } from '@radix-ui/react-id'
import { composeRefs } from '@radix-ui/react-compose-refs'
type Children = { children?: React.ReactNode }
type DivProps = React.ComponentPropsWithoutRef
type LoadingProps = Children &
DivProps & {
/** Estimated progress of loading asynchronous options. */
progress?: number
/**
* Accessible label for this loading progressbar. Not shown visibly.
*/
label?: string
}
type EmptyProps = Children & DivProps & {}
type SeparatorProps = DivProps & {
/** Whether this separator should always be rendered. Useful if you disable automatic filtering. */
alwaysRender?: boolean
}
type DialogProps = RadixDialog.DialogProps &
CommandProps & {
/** Provide a className to the Dialog overlay. */
overlayClassName?: string
/** Provide a className to the Dialog content. */
contentClassName?: string
/** Provide a custom element the Dialog should portal into. */
container?: HTMLElement
}
type ListProps = Children &
DivProps & {
/**
* Accessible label for this List of suggestions. Not shown visibly.
*/
label?: string
}
type ItemProps = Children &
Omit & {
/** Whether this item is currently disabled. */
disabled?: boolean
/** Event handler for when this item is selected, either via click or keyboard selection. */
onSelect?: (value: string) => void
/**
* A unique value for this item.
* If no value is provided, it will be inferred from `children` or the rendered `textContent`. If your `textContent` changes between renders, you _must_ provide a stable, unique `value`.
*/
value?: string
/** Optional keywords to match against when filtering. */
keywords?: string[]
/** Whether this item is forcibly rendered regardless of filtering. */
forceMount?: boolean
}
type GroupProps = Children &
Omit & {
/** Optional heading to render for this group. */
heading?: React.ReactNode
/** If no heading is provided, you must provide a value that is unique for this group. */
value?: string
/** Whether this group is forcibly rendered regardless of filtering. */
forceMount?: boolean
}
type InputProps = Omit, 'value' | 'onChange' | 'type'> & {
/**
* Optional controlled state for the value of the search input.
*/
value?: string
/**
* Event handler called when the search value changes.
*/
onValueChange?: (search: string) => void
}
type CommandFilter = (value: string, search: string, keywords?: string[]) => number
type CommandProps = Children &
DivProps & {
/**
* Accessible label for this command menu. Not shown visibly.
*/
label?: string
/**
* Optionally set to `false` to turn off the automatic filtering and sorting.
* If `false`, you must conditionally render valid items based on the search query yourself.
*/
shouldFilter?: boolean
/**
* Custom filter function for whether each command menu item should matches the given search query.
* It should return a number between 0 and 1, with 1 being the best match and 0 being hidden entirely.
* By default, uses the `command-score` library.
*/
filter?: CommandFilter
/**
* Optional default item value when it is initially rendered.
*/
defaultValue?: string
/**
* Optional controlled state of the selected command menu item.
*/
value?: string
/**
* Event handler called when the selected item of the menu changes.
*/
onValueChange?: (value: string) => void
/**
* Optionally set to `true` to turn on looping around when using the arrow keys.
*/
loop?: boolean
/**
* Optionally set to `true` to disable selection via pointer events.
*/
disablePointerSelection?: boolean
/**
* Set to `false` to disable ctrl+n/j/p/k shortcuts. Defaults to `true`.
*/
vimBindings?: boolean
}
type Context = {
value: (id: string, value: string, keywords?: string[]) => void
item: (id: string, groupId: string) => () => void
group: (id: string) => () => void
filter: () => boolean
label: string
getDisablePointerSelection: () => boolean
// Ids
listId: string
labelId: string
inputId: string
// Refs
listInnerRef: React.RefObject
}
type State = {
search: string
value: string
selectedItemId?: string
filtered: { count: number; items: Map; groups: Set }
}
type Store = {
subscribe: (callback: () => void) => () => void
snapshot: () => State
setState: (key: K, value: State[K], opts?: any) => void
emit: () => void
}
type Group = {
id: string
forceMount?: boolean
}
const GROUP_SELECTOR = `[cmdk-group=""]`
const GROUP_ITEMS_SELECTOR = `[cmdk-group-items=""]`
const GROUP_HEADING_SELECTOR = `[cmdk-group-heading=""]`
const ITEM_SELECTOR = `[cmdk-item=""]`
const VALID_ITEM_SELECTOR = `${ITEM_SELECTOR}:not([aria-disabled="true"])`
const SELECT_EVENT = `cmdk-item-select`
const VALUE_ATTR = `data-value`
const defaultFilter: CommandFilter = (value, search, keywords) => commandScore(value, search, keywords)
const CommandContext = React.createContext(undefined)
const useCommand = () => React.useContext(CommandContext)
const StoreContext = React.createContext(undefined)
const useStore = () => React.useContext(StoreContext)
const GroupContext = React.createContext(undefined)
const Command = React.forwardRef((props, forwardedRef) => {
const state = useLazyRef(() => ({
/** Value of the search query. */
search: '',
/** Currently selected item value. */
value: props.value ?? props.defaultValue ?? '',
/** Currently selected item id. */
selectedItemId: undefined,
filtered: {
/** The count of all visible items. */
count: 0,
/** Map from visible item id to its search score. */
items: new Map(),
/** Set of groups with at least one visible item. */
groups: new Set(),
},
}))
const allItems = useLazyRef>(() => new Set()) // [...itemIds]
const allGroups = useLazyRef