cmdk README

The project's README from github.com/dip/cmdk. As one markdown file: README.md.

⌘K cmdk minzip package size cmdk package version

⌘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?, so you can wrap items in other components or even as static JSX.

Install

pnpm install cmdk

Use

import { Command } from 'cmdk'

const CommandMenu = () => {
  return (
    <Command label="Command Menu">
      <Command.Input />
      <Command.List>
        <Command.Empty>No results found.</Command.Empty>

        <Command.Group heading="Letters">
          <Command.Item>a</Command.Item>
          <Command.Item>b</Command.Item>
          <Command.Separator />
          <Command.Item>c</Command.Item>
        </Command.Group>

        <Command.Item>Apple</Command.Item>
      </Command.List>
    </Command>
  )
}

Or in a dialog:

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 (
    <Command.Dialog open={open} onOpenChange={setOpen} label="Global Command Menu">
      <Command.Input />
      <Command.List>
        <Command.Empty>No results found.</Command.Empty>

        <Command.Group heading="Letters">
          <Command.Item>a</Command.Item>
          <Command.Item>b</Command.Item>
          <Command.Separator />
          <Command.Item>c</Command.Item>
        </Command.Group>

        <Command.Item>Apple</Command.Item>
      </Command.List>
    </Command.Dialog>
  )
}

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 to render in a elevated context. Can be controlled with the value and onValueChange props.

Note

Values are always trimmed with the trim() method.

const [value, setValue] = React.useState('apple')

return (
  <Command value={value} onValueChange={setValue}>
    <Command.Input />
    <Command.List>
      <Command.Item>Orange</Command.Item>
      <Command.Item>Apple</Command.Item>
    </Command.List>
  </Command>
)

You can provide a custom filter function that is called to rank each item. Note that the value will be trimmed.

<Command
  filter={(value, search) => {
    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.

<Command
  filter={(value, search, keywords) => {
    const extendValue = value + ' ' + keywords.join(' ')
    if (extendValue.includes(search)) return 1
    return 0
  }}
/>

Or disable filtering and sorting entirely:

<Command shouldFilter={false}>
  <Command.List>
    {filteredItems.map((item) => {
      return (
        <Command.Item key={item} value={item}>
          {item}
        </Command.Item>
      )
    })}
  </Command.List>
</Command>

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:

<Command loop />

Dialog [cmdk-dialog] [cmdk-overlay]

Props are forwarded to Command. Composes Radix UI's Dialog component. The overlay is always rendered. See the Radix Documentation for more information. Can be controlled with the open and onOpenChange props.

const [open, setOpen] = React.useState(false)

return (
  <Command.Dialog open={open} onOpenChange={setOpen}>
    ...
  </Command.Dialog>
)

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 for more information.

const containerElement = React.useRef(null)

return (
  <>
    <Command.Dialog container={containerElement.current} />
    <div ref={containerElement} />
  </>
)

Input [cmdk-input]

All props are forwarded to the underlying input element. Can be controlled with the value and onValueChange props.

const [search, setSearch] = React.useState('')

return <Command.Input value={search} onValueChange={setSearch} />

List [cmdk-list]

Contains items and groups. Animate height using the --cmdk-list-height CSS variable.

[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:

[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.

<Command.Item
  onSelect={(value) => console.log('Selected', value)}
  // Value is implicity "apple" because of the provided text content
>
  Apple
</Command.Item>

You can also provide a keywords prop to help with filtering. Keywords are trimmed.

<Command.Item keywords={['fruit', 'apple']}>Apple</Command.Item>
<Command.Item
  onSelect={(value) => console.log('Selected', value)}
  // Value is implicity "apple" because of the provided text content
>
  Apple
</Command.Item>

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]).

<Command.Group heading="Fruit">
  <Command.Item>Apple</Command.Item>
</Command.Group>

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.

const [loading, setLoading] = React.useState(false)

return <Command.List>{loading && <Command.Loading>Hang on…</Command.Loading>}</Command.List>

useCommandState(state => state.selectedField)

Hook that composes 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:

const search = useCommandState((state) => state.search)
return <Command.Empty>No results found for "{search}".</Command.Empty>

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:

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 (
  <Command
    onKeyDown={(e) => {
      // 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))
      }
    }}
  >
    <Command.Input value={search} onValueChange={setSearch} />
    <Command.List>
      {!page && (
        <>
          <Command.Item onSelect={() => setPages([...pages, 'projects'])}>Search projects…</Command.Item>
          <Command.Item onSelect={() => setPages([...pages, 'teams'])}>Join a team…</Command.Item>
        </>
      )}

      {page === 'projects' && (
        <>
          <Command.Item>Project A</Command.Item>
          <Command.Item>Project B</Command.Item>
        </>
      )}

      {page === 'teams' && (
        <>
          <Command.Item>Team 1</Command.Item>
          <Command.Item>Team 2</Command.Item>
        </>
      )}
    </Command.List>
  </Command>
)

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:

const SubItem = (props) => {
  const search = useCommandState((state) => state.search)
  if (!search) return null
  return <Command.Item {...props} />
}

return (
  <Command>
    <Command.Input />
    <Command.List>
      <Command.Item>Change theme…</Command.Item>
      <SubItem>Change theme to dark</SubItem>
      <SubItem>Change theme to light</SubItem>
    </Command.List>
  </Command>
)

Asynchronous results

Render the items as they become available. Filtering and sorting will happen automatically.

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 (
  <Command>
    <Command.Input />
    <Command.List>
      {loading && <Command.Loading>Fetching words…</Command.Loading>}
      {items.map((item) => {
        return (
          <Command.Item key={`word-${item}`} value={item}>
            {item}
          </Command.Item>
        )
      })}
    </Command.List>
  </Command>
)

Use inside Popover

We recommend using the Radix UI popover component. ⌘K relies on the Radix UI Dialog component, so this will reduce your bundle size a bit due to shared dependencies.

$ pnpm install @radix-ui/react-popover

Render Command inside of the popover content:

import * as Popover from '@radix-ui/react-popover'

return (
  <Popover.Root>
    <Popover.Trigger>Toggle popover</Popover.Trigger>

    <Popover.Content>
      <Command>
        <Command.Input />
        <Command.List>
          <Command.Item>Apple</Command.Item>
        </Command.List>
      </Command>
    </Popover.Content>
  </Popover.Root>
)

Drop in stylesheets

You can find global stylesheets to drop in as a starting point for styling. See website/styles/cmdk for examples.

FAQ

Accessible? Yes. Labeling, aria attributes, and DOM ordering tested with Voice Over and Chrome DevTools. Dialog 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. 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) to see if a composable combobox API was possible. Used for the Vercel command menu and autocomplete by Rauno (@raunofreiberg) in 2020. Re-written independently in 2022 with a simpler and more performant approach. Ideas and help from Shu (@shuding_).

use-descendants was extracted from the 2019 version.

Testing

First, install dependencies and Playwright browsers:

pnpm install
pnpm playwright install

Then ensure you've built the library:

pnpm build

Then run the tests using your local build against real browser engines:

pnpm test

cmdk (dip/cmdk)

Searching Database…

13K ·GitHub
这是什么?cmdk(⌘K)是一个快速、无样式的 React 组件,用于构建命令菜单,也可以作为无障碍组合框(combobox)使用。你把条目交给它,它会自动进行过滤和排序。
它是带样式的组件库,还是需要我自己设计样式?它没有预设样式。每个部分都会暴露一个以 cmdk- 为前缀的特定 data 属性,你可以用自己的 CSS 来定制样式;如果需要一个基础样式,项目也提供了可直接套用的入门样式表链接。
如何将它添加到项目中?安装 cmdk 包,然后根据需要使用 Items、Groups、Input、List 渲染 Command 组件。可以直接内嵌,也可以包裹在 Command.Dialog 中,做成弹出的模态框。
是否还需要安装其他 UI 库?Dialog 部分在底层组合了 Radix UI 的 Dialog 组件,因此使用 Command.Dialog 时会将 Radix 作为依赖一并引入。由于它依赖 useId、useSyncExternalStore 等 Hook,因此需要 React 18。
面对大量条目时,它能流畅处理吗?它没有内置虚拟化,但在大约 2,000–3,000 个条目以内,性能表现良好;超过这个数量,你就需要关闭自动过滤和排序,并自行实现虚拟化。
它是服务端组件,可以在 Next.js 的服务端组件中使用吗?不可以,它只能作为客户端组件使用。
我可以在 React Native 中使用它吗?不可以。它仅适用于 Web,并且没有支持 React Native 的计划。
它对屏幕阅读器用户是否无障碍友好?是的。标签、ARIA 属性和 DOM 顺序已经用 Voice Over 和 Chrome DevTools 进行过测试,而且 Dialog 组合的是一个无障碍的 Radix UI Dialog 实现。
我能自己过滤或排序条目,而不使用自动处理吗?可以。向 Command 传入 shouldFilter={false},即可完全关闭内置的过滤和排序,从而获得更好的内存占用和更多的控制权。
条目可以设置影响搜索排序的别名吗?可以。每个 Item 都接受一个 keywords 属性,它的作用是作为条目 value 的别名,并能影响该条目在搜索结果中的排序。
cmdk 是怎么来的?它最初由 Paco Coursey 于 2019 年编写。2020 年,Rauno Freiberg 将它用于 Vercel 的命令菜单。2022 年,它又以更简洁、性能更好的方式被重写。
Creator
dip
Size
0.8 MB
Stars
13K
Age
4y
Commits · 90 Days