{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "casework-shortcuts",
  "title": "Casework keyboard shortcuts",
  "description": "Single-key shortcuts for the work shell and the dialog that lists them; a key fires only while no field has focus.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/casework-content",
    "@registrystack/lib-content",
    "@registrystack/lib-format",
    "@registrystack/ui-dialog",
    "@registrystack/ui-kbd"
  ],
  "files": [
    {
      "path": "casework/shortcuts.tsx",
      "content": "import {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ReactNode,\n} from \"react\";\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogHeader,\n  DialogTitle,\n} from \"@/components/ui/dialog\";\nimport { Kbd } from \"@/components/ui/kbd\";\nimport {\n  useRememberedState,\n  type BrowserMemory,\n} from \"@registrystack/app-runtime/react\";\nimport {\n  useCaseworkContent,\n  type CaseworkContent,\n} from \"@/blocks/casework/casework-content\";\nimport { useLocale } from \"@/blocks/lib/content\";\nimport { fill } from \"@/blocks/lib/format\";\n\n/**\n * Keyboard shortcuts for the work shell. A single key fires only while no\n * text field, dialog or menu has focus and only while the officer has left\n * them on: WCAG 2.1.4 asks that single-character shortcuts can be switched\n * off, and the switch lives in the account menu. A chord with the platform\n * modifier (Cmd on macOS, Ctrl elsewhere) fires everywhere, like a browser\n * shortcut does.\n */\n\nexport interface Shortcut {\n  /** The key as `KeyboardEvent.key` reports it, such as `j` or `?`. */\n  key: string;\n  /** What the key does, for the shortcuts list. */\n  label: string;\n  /** Whether the platform modifier is part of the shortcut. */\n  chord?: \"mod\";\n}\n\ninterface Registered extends Shortcut {\n  handler: () => void;\n}\n\ninterface ShortcutsState {\n  enabled: boolean;\n  setEnabled: (enabled: boolean) => void;\n  register: (shortcut: Registered) => () => void;\n  shortcuts: Shortcut[];\n}\n\nconst ShortcutsContext = createContext<ShortcutsState | null>(null);\n\n/** Where the switch is kept between sessions: \"off\" is the only value read. */\nconst settingKey = \"appkit.shortcuts\";\nconst setting: BrowserMemory<boolean> = {\n  decode: (raw) => raw !== \"off\",\n  encode: (on) => (on ? \"on\" : \"off\"),\n};\n\n/** An element that takes typed text, where a single key must stay a character. */\nfunction takesText(target: EventTarget | null): boolean {\n  if (!(target instanceof HTMLElement)) return false;\n  if (target.isContentEditable) return true;\n  const tag = target.tagName;\n  return tag === \"INPUT\" || tag === \"TEXTAREA\" || tag === \"SELECT\";\n}\n\n/** An element inside a popup, where a single key belongs to that popup. */\nfunction inPopup(target: EventTarget | null): boolean {\n  return (\n    target instanceof Element &&\n    target.closest('[role=\"dialog\"], [role=\"menu\"], [role=\"listbox\"]') !== null\n  );\n}\n\nexport function ShortcutsProvider({ children }: { children: ReactNode }) {\n  // Storage the browser refuses reads as on, and a refused write keeps the\n  // setting for the session only; the switch still works.\n  const [enabled, setEnabled] = useRememberedState(settingKey, true, setting);\n  const registry = useRef(new Map<symbol, Registered>());\n  const [shortcuts, setShortcuts] = useState<Shortcut[]>([]);\n  const register = useCallback((shortcut: Registered) => {\n    const id = Symbol(shortcut.key);\n    registry.current.set(id, shortcut);\n    const list = () =>\n      setShortcuts(\n        [...registry.current.values()].map(({ handler: _, ...rest }) => rest),\n      );\n    list();\n    return () => {\n      registry.current.delete(id);\n      list();\n    };\n  }, []);\n  useEffect(() => {\n    const onKeyDown = (event: KeyboardEvent) => {\n      if (event.defaultPrevented || event.altKey || event.repeat) return;\n      const mod = event.metaKey || event.ctrlKey;\n      const single = !mod;\n      if (\n        single &&\n        (!enabled || takesText(event.target) || inPopup(event.target))\n      )\n        return;\n      for (const shortcut of registry.current.values()) {\n        const wantsMod = shortcut.chord === \"mod\";\n        if (wantsMod !== mod) continue;\n        if (event.key.toLowerCase() !== shortcut.key.toLowerCase()) continue;\n        event.preventDefault();\n        shortcut.handler();\n        return;\n      }\n    };\n    window.addEventListener(\"keydown\", onKeyDown);\n    return () => window.removeEventListener(\"keydown\", onKeyDown);\n  }, [enabled]);\n  const value = useMemo(\n    () => ({ enabled, setEnabled, register, shortcuts }),\n    [enabled, setEnabled, register, shortcuts],\n  );\n  return (\n    <ShortcutsContext.Provider value={value}>\n      {children}\n    </ShortcutsContext.Provider>\n  );\n}\n\nfunction useShortcutsContext(): ShortcutsState {\n  const context = useContext(ShortcutsContext);\n  if (!context) throw new Error(\"ShortcutsProvider is required.\");\n  return context;\n}\n\n/** The officer's switch for single-key shortcuts. */\nexport function useShortcutsSetting(): [boolean, (enabled: boolean) => void] {\n  const { enabled, setEnabled } = useShortcutsContext();\n  return [enabled, setEnabled];\n}\n\n/**\n * Binds a key for as long as the calling screen is mounted. The handler may\n * change every render; the binding does not.\n */\nexport function useShortcut(\n  shortcut: Shortcut,\n  handler: () => void,\n  active = true,\n) {\n  const { register } = useShortcutsContext();\n  const latest = useRef(handler);\n  latest.current = handler;\n  const { key, label, chord } = shortcut;\n  useEffect(() => {\n    if (!active) return;\n    return register({\n      key,\n      label,\n      ...(chord ? { chord } : {}),\n      handler: () => latest.current(),\n    });\n  }, [register, key, label, chord, active]);\n}\n\n/** The modifier key as this platform names it; the Mac symbol is a symbol, the other is `shortcutControl`. */\nexport function modifierLabel(\n  c: Pick<CaseworkContent, \"shortcutControl\">,\n): string {\n  return typeof navigator !== \"undefined\" &&\n    /Mac|iPhone|iPad/.test(navigator.platform)\n    ? \"⌘\"\n    : c.shortcutControl;\n}\n\n/** A shortcut's keys as the help list shows them: the key, with the modifier before it for a chord. */\nexport function keyLabel(\n  shortcut: Shortcut,\n  c: CaseworkContent,\n  locale: string,\n): string {\n  const key =\n    shortcut.key === \" \"\n      ? c.shortcutSpace\n      : shortcut.key.length === 1\n        ? shortcut.key.toUpperCase()\n        : shortcut.key;\n  return shortcut.chord === \"mod\"\n    ? fill(c.shortcutChord, { modifier: modifierLabel(c), key }, locale)\n    : key;\n}\n\n/** The list of every shortcut bound right now, opened with `?`. */\nexport function ShortcutsHelp({\n  open,\n  onOpenChange,\n}: {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n}) {\n  const c = useCaseworkContent();\n  const locale = useLocale();\n  const { shortcuts } = useShortcutsContext();\n  return (\n    <Dialog open={open} onOpenChange={onOpenChange}>\n      <DialogContent closeLabel={c.close} className=\"shortcuts-help\">\n        <DialogHeader>\n          <DialogTitle>{c.shortcutsTitle}</DialogTitle>\n          <DialogDescription>{c.shortcutsDescription}</DialogDescription>\n        </DialogHeader>\n        <table>\n          <thead>\n            <tr>\n              <th scope=\"col\">{c.shortcutKey}</th>\n              <th scope=\"col\">{c.shortcutDoes}</th>\n            </tr>\n          </thead>\n          <tbody>\n            {shortcuts.map((shortcut) => (\n              <tr key={`${shortcut.chord ?? \"\"}${shortcut.key}`}>\n                <td>\n                  <Kbd>{keyLabel(shortcut, c, locale)}</Kbd>\n                </td>\n                <td>{shortcut.label}</td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      </DialogContent>\n    </Dialog>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/casework/shortcuts.tsx"
    }
  ],
  "type": "registry:block"
}