{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"shortcut-sheet","type":"registry:component","title":"Shortcut sheet","description":"Press ? anywhere to see every shortcut, then press one to watch it light up.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/shortcut-sheet.tsx","type":"registry:component","content":"\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// A power-user surface, opened and closed in quick succession: the panel\n// should arrive rather than blink, and never make anyone wait.\nconst OPEN = { duration: 0.15, ease: EASE_OUT };\nconst CLOSE = { duration: 0.1, ease: EASE_OUT };\n// Long enough to register the row lighting up, short enough to be gone\n// before the next press.\nconst FLASH_MS = 600;\n\nconst FOCUSABLE =\n  'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])';\n\nexport type Shortcut = {\n  id: string;\n  label: string;\n  group: string;\n  /** \"Mod\" is ⌘ on Apple platforms and Ctrl elsewhere; the last key is the trigger. */\n  keys: string[];\n};\n\nconst subscribeNoop = () => () => {};\nfunction useIsMac() {\n  // Server renders \"Ctrl\"; the client corrects it without a hydration mismatch.\n  return useSyncExternalStore(\n    subscribeNoop,\n    () => /Mac|iPhone|iPad/.test(navigator.platform),\n    () => false,\n  );\n}\n\n// The portal needs document.body, which only exists on the client.\nfunction useIsClient() {\n  return useSyncExternalStore(\n    subscribeNoop,\n    () => true,\n    () => false,\n  );\n}\n\nconst MAC_GLYPHS: Record<string, string> = {\n  Mod: \"⌘\",\n  Shift: \"⇧\",\n  Alt: \"⌥\",\n};\nconst SPOKEN: Record<string, string> = {\n  \"[\": \"left bracket\",\n  \"]\": \"right bracket\",\n  \"=\": \"equals\",\n  \"-\": \"minus\",\n  \"?\": \"question mark\",\n};\n\nfunction glyph(key: string, isMac: boolean) {\n  if (key === \"Mod\") return isMac ? \"⌘\" : \"Ctrl\";\n  return (isMac && MAC_GLYPHS[key]) || key;\n}\n\nfunction spoken(keys: string[], isMac: boolean) {\n  return keys\n    .map((k) =>\n      k === \"Mod\" ? (isMac ? \"Command\" : \"Control\") : (SPOKEN[k] ?? k),\n    )\n    .join(\" \");\n}\n\nfunction matches(e: KeyboardEvent, keys: string[], isMac: boolean) {\n  const key = keys[keys.length - 1];\n  const mod = isMac ? e.metaKey : e.ctrlKey;\n  const other = isMac ? e.ctrlKey : e.metaKey;\n  if (other || mod !== keys.includes(\"Mod\") || e.altKey !== keys.includes(\"Alt\"))\n    return false;\n  // \"?\" is itself a shifted key, so Shift isn't listed for it.\n  if (key === \"?\") return e.key === \"?\";\n  if (e.shiftKey !== keys.includes(\"Shift\")) return false;\n  return e.key.toLowerCase() === key.toLowerCase();\n}\n\nfunction isEditable(target: EventTarget | null) {\n  return (\n    target instanceof HTMLElement &&\n    (target.isContentEditable ||\n      target.closest(\"input, textarea, select, [contenteditable]\") !== null)\n  );\n}\n\nlet savedOverflow = \"\";\nlet savedPadding = \"\";\nfunction lockScroll() {\n  const body = document.body;\n  // Padding by the scrollbar's width keeps the page from shifting sideways.\n  const gap = window.innerWidth - document.documentElement.clientWidth;\n  savedOverflow = body.style.overflow;\n  savedPadding = body.style.paddingRight;\n  const padding = parseFloat(getComputedStyle(body).paddingRight) || 0;\n  body.style.overflow = \"hidden\";\n  if (gap > 0) body.style.paddingRight = `${padding + gap}px`;\n}\nfunction unlockScroll() {\n  document.body.style.overflow = savedOverflow;\n  document.body.style.paddingRight = savedPadding;\n}\n\nexport function ShortcutSheet({\n  shortcuts,\n  className,\n}: {\n  shortcuts: Shortcut[];\n  className?: string;\n}) {\n  const isMac = useIsMac();\n  const isClient = useIsClient();\n  const reduceMotion = useReducedMotion();\n  const id = useId();\n  const [open, setOpen] = useState(false);\n  const [query, setQuery] = useState(\"\");\n  const [flash, setFlash] = useState<string | null>(null);\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const panelRef = useRef<HTMLDivElement>(null);\n  const flashTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n  const results = useMemo(() => {\n    const q = query.trim().toLowerCase();\n    const found = shortcuts.filter(\n      (s) =>\n        !q ||\n        s.label.toLowerCase().includes(q) ||\n        s.group.toLowerCase().includes(q),\n    );\n    const groups = [...new Set(found.map((s) => s.group))];\n    return {\n      count: found.length,\n      groups: groups.map((group) => ({\n        group,\n        items: found.filter((s) => s.group === group),\n      })),\n    };\n  }, [shortcuts, query]);\n\n  // Read inside the key handler without re-binding it on every keystroke.\n  const visible = useRef(results);\n  useEffect(() => {\n    visible.current = results;\n  }, [results]);\n\n  const show = useCallback(() => {\n    setQuery(\"\");\n    setFlash(null);\n    setOpen(true);\n  }, []);\n  const close = useCallback(() => setOpen(false), []);\n\n  useEffect(() => () => clearTimeout(flashTimer.current), []);\n\n  // Closed: \"?\" anywhere opens it, unless it's being typed into a field.\n  useEffect(() => {\n    if (open) return;\n    const onKeyDown = (e: KeyboardEvent) => {\n      if (e.key !== \"?\" || e.metaKey || e.ctrlKey || e.altKey || e.repeat)\n        return;\n      if (isEditable(e.target)) return;\n      // Inert copies, like the index preview, stay quiet.\n      if (triggerRef.current?.closest(\"[inert]\")) return;\n      e.preventDefault();\n      show();\n    };\n    window.addEventListener(\"keydown\", onKeyDown);\n    return () => window.removeEventListener(\"keydown\", onKeyDown);\n  }, [open, show]);\n\n  // Open: Escape closes, and any listed shortcut lights up its row.\n  useEffect(() => {\n    if (!open) return;\n    const previous = document.activeElement as HTMLElement | null;\n    lockScroll();\n\n    const onKeyDown = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") {\n        e.preventDefault();\n        close();\n        return;\n      }\n      const typing = isEditable(e.target);\n      if (e.key === \"?\" && !typing && !e.metaKey && !e.ctrlKey) {\n        e.preventDefault();\n        close();\n        return;\n      }\n      const hit = visible.current.groups\n        .flatMap((g) => g.items)\n        .find((s) => matches(e, s.keys, isMac));\n      if (!hit) return;\n      // Plain keys belong to the search field while it has focus; only\n      // modifier shortcuts can be demonstrated from there.\n      if (typing && !hit.keys.includes(\"Mod\")) return;\n      // Undo and redo inside the field keep working natively.\n      const nativeEdit = typing && /^[zZ]$/.test(e.key);\n      if (!nativeEdit) e.preventDefault();\n      setFlash(hit.id);\n      clearTimeout(flashTimer.current);\n      flashTimer.current = setTimeout(() => setFlash(null), FLASH_MS);\n      document\n        .getElementById(`${id}-${hit.id}`)\n        ?.scrollIntoView({ block: \"nearest\" });\n    };\n    document.addEventListener(\"keydown\", onKeyDown);\n    return () => {\n      document.removeEventListener(\"keydown\", onKeyDown);\n      clearTimeout(flashTimer.current);\n      unlockScroll();\n      previous?.focus({ preventScroll: true });\n    };\n  }, [open, close, isMac, id]);\n\n  const onPanelKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    if (e.key !== \"Tab\") return;\n    const items = [\n      ...e.currentTarget.querySelectorAll<HTMLElement>(FOCUSABLE),\n    ].filter((el) => el.getClientRects().length > 0);\n    if (!items.length) return;\n    const first = items[0];\n    const last = items[items.length - 1];\n    if (e.shiftKey && document.activeElement === first) {\n      e.preventDefault();\n      last.focus();\n    } else if (!e.shiftKey && document.activeElement === last) {\n      e.preventDefault();\n      first.focus();\n    }\n  };\n\n  return (\n    <>\n      <button\n        ref={triggerRef}\n        type=\"button\"\n        aria-haspopup=\"dialog\"\n        aria-expanded={open}\n        aria-keyshortcuts=\"?\"\n        onClick={show}\n        className={cn(\n          \"flex h-10 touch-manipulation items-center gap-2.5 rounded-full bg-muted pr-2 pl-4 text-sm font-medium text-foreground shadow-raised outline-hidden transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\",\n          className,\n        )}\n      >\n        Keyboard shortcuts\n        <Kbd>?</Kbd>\n      </button>\n\n      {isClient &&\n        createPortal(\n          <AnimatePresence>\n            {open && (\n              <motion.div\n                key=\"sheet\"\n                className=\"fixed inset-0 z-50 flex items-center justify-center p-4\"\n                initial={{ opacity: 0 }}\n                animate={{ opacity: 1, transition: OPEN }}\n                exit={{ opacity: 0, transition: CLOSE }}\n              >\n                {/* Token-only dim: a grey wash in light, near black in dark. */}\n                <div\n                  aria-hidden\n                  className=\"absolute inset-0 bg-foreground/10 dark:bg-background/70\"\n                  onClick={close}\n                />\n                <motion.div\n                  ref={panelRef}\n                  role=\"dialog\"\n                  aria-modal=\"true\"\n                  aria-labelledby={`${id}-title`}\n                  onKeyDown={onPanelKeyDown}\n                  // Centered like any modal; the barest scale, so it lands\n                  // rather than pops.\n                  initial={reduceMotion ? false : { scale: 0.98 }}\n                  animate={{ scale: 1, transition: OPEN }}\n                  // A fixed height, so filtering never resizes the panel and\n                  // the search field stays exactly where it is.\n                  className=\"relative flex h-[min(480px,calc(100dvh-32px))] w-[520px] max-w-full flex-col overflow-hidden rounded-[20px] bg-background shadow-raised\"\n                >\n                  <div className=\"flex h-14 shrink-0 items-center justify-between pr-2.5 pl-5\">\n                    <h2\n                      id={`${id}-title`}\n                      className=\"text-[15px] font-semibold text-foreground\"\n                    >\n                      Keyboard shortcuts\n                    </h2>\n                    <button\n                      type=\"button\"\n                      aria-label=\"Close\"\n                      onClick={close}\n                      className=\"relative flex size-9 touch-manipulation items-center justify-center rounded-full text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out select-none hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color]\"\n                    >\n                      <svg\n                        viewBox=\"0 0 16 16\"\n                        className=\"size-4\"\n                        fill=\"none\"\n                        stroke=\"currentColor\"\n                        strokeWidth={1.5}\n                        strokeLinecap=\"round\"\n                        aria-hidden\n                      >\n                        <path d=\"m4.5 4.5 7 7M11.5 4.5l-7 7\" />\n                      </svg>\n                    </button>\n                  </div>\n\n                  <div className=\"relative mx-3 shrink-0 text-muted-foreground\">\n                    <svg\n                      viewBox=\"0 0 16 16\"\n                      className=\"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2\"\n                      fill=\"none\"\n                      stroke=\"currentColor\"\n                      strokeWidth={1.5}\n                      strokeLinecap=\"round\"\n                      aria-hidden\n                    >\n                      <circle cx=\"7\" cy=\"7\" r=\"4.25\" />\n                      <path d=\"m10.25 10.25 3 3\" />\n                    </svg>\n                    <input\n                      autoFocus\n                      type=\"search\"\n                      aria-label=\"Search shortcuts\"\n                      aria-controls={`${id}-list`}\n                      placeholder=\"Search shortcuts\"\n                      spellCheck={false}\n                      autoComplete=\"off\"\n                      value={query}\n                      onChange={(e) => setQuery(e.target.value)}\n                      className=\"h-10 w-full rounded-lg bg-muted pr-3 pl-9 text-[15px] text-foreground outline-hidden placeholder:text-muted-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground [&::-webkit-search-cancel-button]:hidden\"\n                    />\n                  </div>\n\n                  <p className=\"sr-only\" aria-live=\"polite\">\n                    {query\n                      ? `${results.count} ${results.count === 1 ? \"shortcut\" : \"shortcuts\"}`\n                      : \"\"}\n                  </p>\n\n                  {/* 12px inset + 8px row radius = the panel's 20px corners. */}\n                  <div\n                    id={`${id}-list`}\n                    role=\"region\"\n                    aria-label=\"Shortcuts\"\n                    // Focusable, so the list can be scrolled from the keyboard.\n                    tabIndex={0}\n                    className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain rounded-b-[20px] px-3 pb-3 outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-foreground\"\n                  >\n                    {results.groups.map(({ group, items }) => (\n                      <section key={group} aria-labelledby={`${id}-g-${group}`}>\n                        <h3\n                          id={`${id}-g-${group}`}\n                          className=\"px-2 pt-4 pb-1 text-xs font-medium text-muted-foreground\"\n                        >\n                          {group}\n                        </h3>\n                        <ul>\n                          {items.map((s) => {\n                            const lit = flash === s.id;\n                            return (\n                              <li\n                                key={s.id}\n                                id={`${id}-${s.id}`}\n                                className={cn(\n                                  \"flex h-10 items-center justify-between gap-4 rounded-lg px-2 text-sm text-foreground transition-[background-color] ease-out\",\n                                  // Lights instantly, then fades like an\n                                  // afterglow; the slow fade is what reads\n                                  // as \"that key worked\".\n                                  lit ? \"bg-muted duration-0\" : \"duration-500\",\n                                )}\n                              >\n                                <span className=\"truncate\">{s.label}</span>\n                                <span className=\"sr-only\">\n                                  {spoken(s.keys, isMac)}\n                                </span>\n                                <span aria-hidden className=\"flex shrink-0 gap-1\">\n                                  {s.keys.map((k) => (\n                                    <Kbd key={k} pressed={lit}>\n                                      {glyph(k, isMac)}\n                                    </Kbd>\n                                  ))}\n                                </span>\n                              </li>\n                            );\n                          })}\n                        </ul>\n                      </section>\n                    ))}\n                    {!results.count && (\n                      <p className=\"px-2 py-10 text-center text-sm text-muted-foreground\">\n                        No shortcuts match &ldquo;{query.trim()}&rdquo;\n                      </p>\n                    )}\n                  </div>\n                </motion.div>\n              </motion.div>\n            )}\n          </AnimatePresence>,\n          document.body,\n        )}\n    </>\n  );\n}\n\nfunction Kbd({\n  pressed = false,\n  children,\n}: {\n  pressed?: boolean;\n  children: React.ReactNode;\n}) {\n  return (\n    <kbd\n      className={cn(\n        // The inset bottom edge gives the keycap its depth; pressing drops\n        // the cap by that edge.\n        \"flex h-6 min-w-6 items-center justify-center rounded-md px-1.5 font-sans text-xs leading-none transition-[background-color,color,translate,box-shadow] ease-out motion-reduce:transition-[background-color,color]\",\n        pressed\n          ? \"translate-y-px bg-foreground text-background shadow-none duration-0\"\n          : \"bg-background text-muted-foreground shadow-[0_0_0_1px_var(--border),inset_0_-1px_0_var(--border)] duration-300\",\n      )}\n    >\n      {children}\n    </kbd>\n  );\n}\n\nconst SHORTCUTS: Shortcut[] = [\n  { id: \"search\", label: \"Search\", group: \"Navigation\", keys: [\"Mod\", \"K\"] },\n  { id: \"back\", label: \"Go back\", group: \"Navigation\", keys: [\"Mod\", \"[\"] },\n  { id: \"forward\", label: \"Go forward\", group: \"Navigation\", keys: [\"Mod\", \"]\"] },\n  { id: \"next\", label: \"Next item\", group: \"Navigation\", keys: [\"J\"] },\n  { id: \"prev\", label: \"Previous item\", group: \"Navigation\", keys: [\"K\"] },\n  { id: \"undo\", label: \"Undo\", group: \"Editing\", keys: [\"Mod\", \"Z\"] },\n  { id: \"redo\", label: \"Redo\", group: \"Editing\", keys: [\"Mod\", \"Shift\", \"Z\"] },\n  { id: \"duplicate\", label: \"Duplicate\", group: \"Editing\", keys: [\"Mod\", \"D\"] },\n  { id: \"save\", label: \"Save\", group: \"Editing\", keys: [\"Mod\", \"S\"] },\n  { id: \"rename\", label: \"Rename\", group: \"Editing\", keys: [\"F2\"] },\n  { id: \"sidebar\", label: \"Toggle sidebar\", group: \"View\", keys: [\"Mod\", \"B\"] },\n  { id: \"zoom-in\", label: \"Zoom in\", group: \"View\", keys: [\"Mod\", \"=\"] },\n  { id: \"zoom-out\", label: \"Zoom out\", group: \"View\", keys: [\"Mod\", \"-\"] },\n  { id: \"theme\", label: \"Toggle theme\", group: \"View\", keys: [\"Mod\", \"Shift\", \"L\"] },\n  { id: \"help\", label: \"Show shortcuts\", group: \"View\", keys: [\"?\"] },\n];\n\nexport default function ShortcutSheetDemo() {\n  return <ShortcutSheet shortcuts={SHORTCUTS} />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["navigation"],"docs":"From ui lab: https://lab.xevrion.dev/lab/shortcut-sheet"}