<!-- generated by scripts/gen-docs.mjs from docs/system/keyboard-shortcuts.md. Edit the source and rerun. -->
# Keyboard shortcuts

## Description
Gives a product's keyboard shortcuts one map that binds every key and lists them in a dialog the "?" key opens, so the keys the page answers and the keys it lists never disagree.

`import { ShortcutKeys, ShortcutsDialog } from "@/components/cobalt/ui/shortcuts-dialog"`, source `registry/cobalt/ui/shortcuts-dialog.tsx`, status `ready-with-gaps`.
`import { defineShortcuts, useShortcut, useShortcuts, shortcutText, ariaKeys, type Shortcut } from "@/lib/cobalt/shortcuts"`, source `registry/cobalt/lib/shortcuts.ts`, status `ready-with-gaps`.
Foundation: `hand-rolled (the dialog on Dialog, the keys on Kbd and KbdGroup)`. Traps checked: `trap/overlay-title`, `trap/overlay-focus-return`, `trap/overlay-no-max-height`, `trap/escape-nested`, `trap/touch-autofocus`, `trap/scroll-chain`, `trap/text-measure`, `trap/color-only-status`.

`trap/overlay-title` is answered by the dialog's title, "Keyboard shortcuts". `trap/overlay-focus-return` by Dialog, which returns focus to what opened it. `trap/overlay-no-max-height` by Dialog's cap and its body that scrolls. `trap/escape-nested` by the hook, which binds nothing while a dialog, a menu or a listbox is open, so Escape and the keys belong to the open layer. `trap/touch-autofocus` by focus on the dialog's frame when it opens, so no field and no button lights up. `trap/scroll-chain` by DialogBody's `overscroll-contain`. `trap/text-measure` by labels that wrap beside their keys (Limits). `trap/color-only-status` n/a: nothing here is a status.

### Overview
`defineShortcuts` holds the map: each shortcut's keys, its words and its group. `useShortcuts` binds the map's keys to handlers, `useShortcut` one key. `ShortcutsDialog` lists the map; `ShortcutKeys` draws one shortcut's keys in a menu row or beside a field. `shortcutText` and `ariaKeys` give the keys as text and as `aria-keyshortcuts`.

### Foundation
| Given by the foundation | Added by the team |
|---|---|
| `Dialog` from `registry/cobalt/ui/dialog.tsx`: the window, its title, its body that scrolls, Escape and the scrim | `ShortcutsDialog`: the map in groups, each action beside its keys in 32px rows; "?" opens it from anywhere outside a field, `openWith` changes or removes that; focus goes to the window's frame |
| `Kbd` and `KbdGroup` from `registry/cobalt/ui/kbd.tsx`: a cap per key, a combination as a `kbd` of `kbd`s, "then" in a sequence, the symbol's name for a screen reader | `ShortcutKeys`: the map's keys as caps in the reader's own modifiers, ⌘ on a Mac and Ctrl elsewhere, in the platform's order |
| Not applicable: hand-rolled. The map, the hook and the labels | One plain form for keys (`mod+k`, `?`, `g i`); a match on the key's place too, so Option on a Mac and another layout still work; plain keys never fire in a field, a `mod` key does; nothing fires while a dialog or a menu is open, or on a held key's repeat; two-step sequences within 1000ms |

## Examples
One map of a research tool's keys: the page answers each, "/" reaches the search field, and "?" lists them all in groups with the reader's own modifier.

Real uses, 0 call sites (`rg -n "<ShortcutsDialog\b" app registry --glob '!registry/cobalt/ui/*'`): the part is new. Kbd's page already teaches single keys; the map takes Tag's one list of actions and keys (`~/tag/src/owner-ui/shortcuts.ts`) and Fund Census's "?" panel and its key hook that ignores fields (`~/adv-atlas/web/graph/dock.tsx`, `~/adv-atlas/web/graph/keys.ts`).

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/keyboard-shortcuts/default.tsx` | default | One map of a tool's keys: the page answers each, and ? opens the list of them in groups |
| `docs/system/examples/keyboard-shortcuts/default.tsx` | state:open | The dialog with its groups, each action beside its keys |
| `docs/system/examples/keyboard-shortcuts/default.tsx` | state:sequence | Go to inbox, G then I |
| `docs/system/examples/keyboard-shortcuts/default.tsx` | composition:Input | / reaches the search field, and a key typed in it stays the person's words |

Example: One map of a tool's keys: the page answers each, and ? opens the list of them in groups (`docs/system/examples/keyboard-shortcuts/default.tsx`)

```tsx
import { useRef, useState } from "react";

import { Button } from "@/components/cobalt/ui/button";
import { Input } from "@/components/cobalt/ui/input";
import { ShortcutKeys, ShortcutsDialog } from "@/components/cobalt/ui/shortcuts-dialog";
import { defineShortcuts, useShortcuts } from "@/lib/cobalt/shortcuts";

// One map for the whole product: the dialog lists it and the hook binds it, so the two never disagree.
const shortcuts = defineShortcuts({
  search: { keys: "/", label: "Search funds", group: "General" },
  palette: { keys: "mod+k", label: "Open the command menu", group: "General" },
  help: { keys: "?", label: "Show keyboard shortcuts", group: "General" },
  inbox: { keys: "g i", label: "Go to inbox", group: "Go to" },
  watchlist: { keys: "g w", label: "Go to watchlist", group: "Go to" },
  next: { keys: "j", label: "Next row", group: "Lists" },
  previous: { keys: "k", label: "Previous row", group: "Lists" },
  save: { keys: "mod+shift+s", label: "Save the search", group: "Lists" },
});

export default function Example() {
  const [heard, setHeard] = useState("Press a key from the list, or ? to see them all.");
  const search = useRef<HTMLInputElement>(null);
  useShortcuts(shortcuts, {
    search: () => search.current?.focus(),
    palette: () => setHeard("The command menu would open now."),
    inbox: () => setHeard("The inbox would open now."),
    watchlist: () => setHeard("The watchlist would open now."),
    next: () => setHeard("The next row would be chosen now."),
    previous: () => setHeard("The previous row would be chosen now."),
    save: () => setHeard("The search would be saved now."),
  });
  const [open, setOpen] = useState(false);
  return (
    <div className="flex max-w-sm flex-col gap-4">
      <label className="flex flex-col gap-2 text-sm">
        <span className="flex items-center justify-between gap-2 font-medium">
          Search funds <ShortcutKeys keys={shortcuts.search.keys} />
        </span>
        <Input ref={search} type="search" placeholder="Fund, adviser or ticker" />
      </label>
      <p role="status" className="text-sm text-muted-foreground">
        {heard}
      </p>
      <Button variant="secondary" className="self-start" onClick={() => setOpen(true)}>
        Keyboard shortcuts
      </Button>
      <ShortcutsDialog shortcuts={shortcuts} open={open} onOpenChange={setOpen} />
    </div>
  );
}
```

Example: / reaches the search field, and a key typed in it stays the person's words (`docs/system/examples/keyboard-shortcuts/default.tsx`)

```tsx
import { useRef, useState } from "react";

import { Button } from "@/components/cobalt/ui/button";
import { Input } from "@/components/cobalt/ui/input";
import { ShortcutKeys, ShortcutsDialog } from "@/components/cobalt/ui/shortcuts-dialog";
import { defineShortcuts, useShortcuts } from "@/lib/cobalt/shortcuts";

// One map for the whole product: the dialog lists it and the hook binds it, so the two never disagree.
const shortcuts = defineShortcuts({
  search: { keys: "/", label: "Search funds", group: "General" },
  palette: { keys: "mod+k", label: "Open the command menu", group: "General" },
  help: { keys: "?", label: "Show keyboard shortcuts", group: "General" },
  inbox: { keys: "g i", label: "Go to inbox", group: "Go to" },
  watchlist: { keys: "g w", label: "Go to watchlist", group: "Go to" },
  next: { keys: "j", label: "Next row", group: "Lists" },
  previous: { keys: "k", label: "Previous row", group: "Lists" },
  save: { keys: "mod+shift+s", label: "Save the search", group: "Lists" },
});

export default function Example() {
  const [heard, setHeard] = useState("Press a key from the list, or ? to see them all.");
  const search = useRef<HTMLInputElement>(null);
  useShortcuts(shortcuts, {
    search: () => search.current?.focus(),
    palette: () => setHeard("The command menu would open now."),
    inbox: () => setHeard("The inbox would open now."),
    watchlist: () => setHeard("The watchlist would open now."),
    next: () => setHeard("The next row would be chosen now."),
    previous: () => setHeard("The previous row would be chosen now."),
    save: () => setHeard("The search would be saved now."),
  });
  const [open, setOpen] = useState(false);
  return (
    <div className="flex max-w-sm flex-col gap-4">
      <label className="flex flex-col gap-2 text-sm">
        <span className="flex items-center justify-between gap-2 font-medium">
          Search funds <ShortcutKeys keys={shortcuts.search.keys} />
        </span>
        <Input ref={search} type="search" placeholder="Fund, adviser or ticker" />
      </label>
      <p role="status" className="text-sm text-muted-foreground">
        {heard}
      </p>
      <Button variant="secondary" className="self-start" onClick={() => setOpen(true)}>
        Keyboard shortcuts
      </Button>
      <ShortcutsDialog shortcuts={shortcuts} open={open} onOpenChange={setOpen} />
    </div>
  );
}
```

## Variants
Not applicable: one dialog and one form of keys.

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| closed | the dialog not open | press "?" or the control that opens it | nothing drawn | test |
| open | "?" outside a field, or `open` | read the keys; close with Escape, the button or the scrim | the window with its title and groups | by hand |
| sequence | a shortcut written in two steps, `g i` | press G, then I within 1000ms | the caps with "then" between them | test |
| typing | focus in a text field | type; only `mod` keys reach past the field | the caret; nothing fires | test |
| overlay open | a dialog, a menu or a listbox open | use the open layer's own keys | the open layer | by hand |

Example: The dialog with its groups, each action beside its keys (`docs/system/examples/keyboard-shortcuts/default.tsx`)

```tsx
import { useRef, useState } from "react";

import { Button } from "@/components/cobalt/ui/button";
import { Input } from "@/components/cobalt/ui/input";
import { ShortcutKeys, ShortcutsDialog } from "@/components/cobalt/ui/shortcuts-dialog";
import { defineShortcuts, useShortcuts } from "@/lib/cobalt/shortcuts";

// One map for the whole product: the dialog lists it and the hook binds it, so the two never disagree.
const shortcuts = defineShortcuts({
  search: { keys: "/", label: "Search funds", group: "General" },
  palette: { keys: "mod+k", label: "Open the command menu", group: "General" },
  help: { keys: "?", label: "Show keyboard shortcuts", group: "General" },
  inbox: { keys: "g i", label: "Go to inbox", group: "Go to" },
  watchlist: { keys: "g w", label: "Go to watchlist", group: "Go to" },
  next: { keys: "j", label: "Next row", group: "Lists" },
  previous: { keys: "k", label: "Previous row", group: "Lists" },
  save: { keys: "mod+shift+s", label: "Save the search", group: "Lists" },
});

export default function Example() {
  const [heard, setHeard] = useState("Press a key from the list, or ? to see them all.");
  const search = useRef<HTMLInputElement>(null);
  useShortcuts(shortcuts, {
    search: () => search.current?.focus(),
    palette: () => setHeard("The command menu would open now."),
    inbox: () => setHeard("The inbox would open now."),
    watchlist: () => setHeard("The watchlist would open now."),
    next: () => setHeard("The next row would be chosen now."),
    previous: () => setHeard("The previous row would be chosen now."),
    save: () => setHeard("The search would be saved now."),
  });
  const [open, setOpen] = useState(false);
  return (
    <div className="flex max-w-sm flex-col gap-4">
      <label className="flex flex-col gap-2 text-sm">
        <span className="flex items-center justify-between gap-2 font-medium">
          Search funds <ShortcutKeys keys={shortcuts.search.keys} />
        </span>
        <Input ref={search} type="search" placeholder="Fund, adviser or ticker" />
      </label>
      <p role="status" className="text-sm text-muted-foreground">
        {heard}
      </p>
      <Button variant="secondary" className="self-start" onClick={() => setOpen(true)}>
        Keyboard shortcuts
      </Button>
      <ShortcutsDialog shortcuts={shortcuts} open={open} onOpenChange={setOpen} />
    </div>
  );
}
```

Example: Go to inbox, G then I (`docs/system/examples/keyboard-shortcuts/default.tsx`)

```tsx
import { useRef, useState } from "react";

import { Button } from "@/components/cobalt/ui/button";
import { Input } from "@/components/cobalt/ui/input";
import { ShortcutKeys, ShortcutsDialog } from "@/components/cobalt/ui/shortcuts-dialog";
import { defineShortcuts, useShortcuts } from "@/lib/cobalt/shortcuts";

// One map for the whole product: the dialog lists it and the hook binds it, so the two never disagree.
const shortcuts = defineShortcuts({
  search: { keys: "/", label: "Search funds", group: "General" },
  palette: { keys: "mod+k", label: "Open the command menu", group: "General" },
  help: { keys: "?", label: "Show keyboard shortcuts", group: "General" },
  inbox: { keys: "g i", label: "Go to inbox", group: "Go to" },
  watchlist: { keys: "g w", label: "Go to watchlist", group: "Go to" },
  next: { keys: "j", label: "Next row", group: "Lists" },
  previous: { keys: "k", label: "Previous row", group: "Lists" },
  save: { keys: "mod+shift+s", label: "Save the search", group: "Lists" },
});

export default function Example() {
  const [heard, setHeard] = useState("Press a key from the list, or ? to see them all.");
  const search = useRef<HTMLInputElement>(null);
  useShortcuts(shortcuts, {
    search: () => search.current?.focus(),
    palette: () => setHeard("The command menu would open now."),
    inbox: () => setHeard("The inbox would open now."),
    watchlist: () => setHeard("The watchlist would open now."),
    next: () => setHeard("The next row would be chosen now."),
    previous: () => setHeard("The previous row would be chosen now."),
    save: () => setHeard("The search would be saved now."),
  });
  const [open, setOpen] = useState(false);
  return (
    <div className="flex max-w-sm flex-col gap-4">
      <label className="flex flex-col gap-2 text-sm">
        <span className="flex items-center justify-between gap-2 font-medium">
          Search funds <ShortcutKeys keys={shortcuts.search.keys} />
        </span>
        <Input ref={search} type="search" placeholder="Fund, adviser or ticker" />
      </label>
      <p role="status" className="text-sm text-muted-foreground">
        {heard}
      </p>
      <Button variant="secondary" className="self-start" onClick={() => setOpen(true)}>
        Keyboard shortcuts
      </Button>
      <ShortcutsDialog shortcuts={shortcuts} open={open} onOpenChange={setOpen} />
    </div>
  );
}
```

### State precedence
- Typing and a plain key: typing wins. The key goes into the field.
- Typing and a `mod` key: the shortcut wins, as Command K does in a search field.
- Overlay open and any key: the overlay wins; the map binds nothing until it closes.
- Open and "?": open wins. The dialog does not open twice.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| the dialog opens and closes | input | Dialog's `dialog-motion`, `--t-arrive` on `--curve`, leaving in 70 percent | opacity | the same fade; nothing moves |

## Props

<!-- Props generated from registry/cobalt/ui/shortcuts-dialog.tsx with TypeScript by scripts/props-table.mjs -->
### ShortcutsDialog

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `shortcuts` | `ShortcutMap` |  | The product's map, from `defineShortcuts`. |
| `description?` | `ReactNode` |  | One sentence under the title, such as where the keys work. |
| `onOpenChange?` | `(open: boolean) => void` |  |  |
| `open?` | `boolean` |  |  |
| `openWith?` | `string` | `"?"` | The keys that open the dialog. |
| `then?` | `string` |  | The word between the steps of a sequence. |
| `title?` | `string` | `"Keyboard shortcuts"` |  |

### ShortcutKeys

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `keys` | `string` |  | The keys in the map's form, such as `mod+k` or `g i`. |
| `className?` | `string` |  |  |
| `then?` | `string` | `"then"` | The word between the steps of a sequence. |

`ShortcutsDialog` takes `shortcuts` (the map), `open` and `onOpenChange`, `openWith` ("?" by default, null for none), `title`, `description` and `then`. `ShortcutKeys` takes `keys` and `then`. A `Shortcut` is `keys`, `label` and `group`. `useShortcuts` takes the map, its handlers by id and `enabled`; `useShortcut` takes one shortcut or its keys, a handler and `enabled`.

## Usage

### When to use
- A tool people use all day and learn: a research tool, an inbox, an admin table.
- Any page that answers a key, so the key is listed and named where it is used.

### When not to use
- A single key named beside the one action it runs. Use Kbd instead.
- Searching for a command by name. Use CommandPalette instead.

### Rules
- `rule/shortcuts-one-map`: When a page answers keys, define them once with `defineShortcuts` and pass the same map to `useShortcuts` and `ShortcutsDialog`, instead of a listener per key and a list written by hand, because a key the dialog lists that does nothing teaches the person that the list lies. Evidence: principle heuristic: consistency and standards; single use docs/system/examples/keyboard-shortcuts/default.tsx:11. Check: review.
  - Don't: `window.addEventListener("keydown", (e) => e.key === "/" && focus())` beside a hand-written list
  - Do: `useShortcuts(shortcuts, { search: focus }); <ShortcutsDialog shortcuts={shortcuts} />`
- `rule/shortcuts-plain-keys-skip-fields`: When choosing keys, give a single letter or symbol only to an action that makes no sense while typing, and a `mod` key to one that must work from a field, because a plain key in a field is the person's words and the hook leaves it there. Evidence: principle input: a key typed into a field is text. Check: test `shortcuts.test.ts` and the default example's search field.
  - Don't: `save: { keys: "s", label: "Save the search" }`
  - Do: `save: { keys: "mod+shift+s", label: "Save the search" }`
- `rule/shortcuts-keys-in-words`: When writing a shortcut's `keys`, name the keys in words, `mod`, `shift`, `alt` and the key, such as `mod+shift+s`, instead of the symbols ⌘⇧S, because the hook reads names and a symbol matches no key, and `mod` turns into Command on a Mac and Control elsewhere in the caps and in `aria-keyshortcuts`. Evidence: principle platform: macOS uses Command where Windows and Linux use Control. Check: test `shortcuts.test.ts` reads ⌘K and Ctrl+K from one `mod+k`.
  - Don't: `keys: "⌘⇧S"`
  - Do: `keys: "mod+shift+s"`

### Content
- `rule/shortcuts-label-verb`: When writing a shortcut's `label`, start with the verb and its object, such as "Save the search" or "Go to inbox", in at most 40 characters, instead of a noun, because the list is read to find what a key does. Evidence: principle heuristic: match between system and the real world; measured 32px rows in a 448px dialog, `.design-system/evidence/keyboard-shortcuts/dialog-1440.json`. Check: review.
  - Don't: `label: "Inbox"`
  - Do: `label: "Go to inbox"`

### Anti-slop
- `rule/shortcuts-no-hint-without-key`: When showing `ShortcutKeys` beside an action, bind the same keys with `useShortcuts` on that page, instead of a hint alone, because a hint for a key that does nothing is a promise the page breaks. Evidence: principle heuristic: consistency and standards; person D39. Check: review.
  - Don't: `<ShortcutKeys keys="mod+s" />` with no handler for mod+s
  - Do: `useShortcuts(shortcuts, { save }); <ShortcutKeys keys={shortcuts.save.keys} />`

### Limits
- `rule/shortcuts-dialog-group-size`: When a map passes 24 shortcuts, split it into groups of at most 8, instead of one list, because the 448px window shows 8 rows of 32px in a group the eye can scan, and past about 14 rows its body scrolls on a 900px screen. Evidence: measured 32px rows and a 460px window for 8 shortcuts in 3 groups, `.design-system/evidence/keyboard-shortcuts/dialog-1440.json`. Check: probe docs/system/stress/keyboard-shortcuts.tsx with 40 shortcuts.
  - Don't: 30 shortcuts with no `group`
  - Do: 30 shortcuts in groups of 8: General, Go to, Lists, Editing

## Accessibility
Rests on Dialog, a `dl` per group with each action as a `dt` and its keys as a `dd`, and `kbd` elements with the symbols' names.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Shift and slash, the ? key | anywhere outside a field and an open overlay | opens the dialog | the dialog's frame | test |
| Tab | the dialog | moves to the close button | the close button | by hand |
| Escape | the dialog | closes it | what opened it | by hand |
| the map's keys | anywhere outside a field and an open overlay; `mod` keys inside a field too | run their actions | where the action puts it | test |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| dialog | dialog | its title | modal | "Keyboard shortcuts, dialog" | by hand |
| group | region | its heading | none | "Go to, region" | by hand |
| row | term and definition | the label, then the keys | none | "Go to inbox, G then I" | by hand |
| key with a symbol | none | the symbol's name, from Kbd | none | "Command", read in place of ⌘ | test |
| control a shortcut runs | its own | its own | `aria-keyshortcuts` from `ariaKeys` | "Collapse sidebar, button", with Control and backslash as its keys | test |

## Tokens
| Part | State | Token |
|---|---|---|
| dialog | all | `--popover`, `--r-4xl`, `--shadow-sheet` |
| group heading | all | `--muted-foreground` |
| row | all | `--control-sm` |
| key cap | all | `--muted`, `--muted-foreground`, `--r-xs` |

## Related
- Kbd: one key beside one action.
- CommandPalette: commands by name, opened by Command K.
- Sidebar: its trigger takes a `shortcut` from the map.
- ListDetail: j, k and the arrows through a list, through `useRowKeys`.
