"use client";import * as React from "react";import { Check, Keyboard, Search, X } from "lucide-react";import { INTERACTION_FOCUS, INTERACTION_PRESS, useInteractionReducedMotion,} from "./ui-interaction-motion";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * SHORTCUT SHEET: searchable keyboard map & live key trainer * * live while the sheet is open or active, pressing real * keys on your keyboard physically depresses and * illuminates matching <kbd> keycaps across the grid; * completing a chord or two-key sequence (e.g. G then I) * highlights that exact command row in real time * * format shares ShortcutRecorder's canonical syntax ("mod+k", * "mod+shift+p", "g then i", "/") with automatic macOS * (⌘ ⌥ ⇧ ⌃) vs Windows/Linux (Ctrl Alt Shift) glyphs * * modes renders either inline inside Settings/Help screens * or as a hairline modal overlay toggled by global "?" * ───────────────────────────────────────────────────────── */export type ShortcutSheetPlatform = "auto" | "mac" | "other";export interface ShortcutEntry { /** Stable identifier for the command (e.g. "open-command-menu"). */ id: string; /** Human-readable command label (e.g. "Open command menu"). */ label: string; /** Canonical shortcut string: chord ("mod+k", "mod+shift+p") or sequence ("g then i", "g then p"). */ keys: string; /** Optional subtle secondary note or category hint. */ description?: string; /** Optional custom search keywords. */ keywords?: string[];}export interface ShortcutGroup { /** Section heading (e.g. "Navigation", "Editor", "Actions"). */ title: string; /** Shortcuts inside this section. */ items: ShortcutEntry[];}export interface ShortcutSheetProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "onSelect"> { /** Grouped keyboard shortcuts to display. */ groups: ShortcutGroup[]; /** Presentation mode: embedded hairline card or global-hotkey dialog overlay. */ variant?: "inline" | "dialog"; /** Controlled open state (dialog variant only). */ open?: boolean; /** Initial uncontrolled open state (dialog variant, default false). */ defaultOpen?: boolean; /** Called when dialog opens or closes. */ onOpenChange?: (open: boolean) => void; /** Global single key that toggles the dialog when not typing in an input (default "?"; pass null to disable). */ hotkey?: string | null; /** Enable real-time physical keyboard keycap lighting & chord matching (default true). */ liveKeys?: boolean; /** Called when a user clicks a shortcut row or completes its chord in liveKeys mode. */ onTrigger?: (entry: ShortcutEntry) => void; /** OS glyph rendering mode (default "auto"). */ platform?: ShortcutSheetPlatform; /** Show quick search bar (default true). */ searchable?: boolean; /** Sheet title (default "Keyboard shortcuts"). */ title?: string; /** Opt-in quiet Web Audio ticks when live keys match (from ui-sounds.ts). */ sound?: boolean;}const noopSubscribe = () => () => {};function useDetectedPlatform(): "mac" | "other" { return React.useSyncExternalStore( noopSubscribe, () => { if (typeof navigator === "undefined") return "mac"; const nav = navigator as Navigator & { userAgentData?: { platform?: string } }; const plat = (nav.userAgentData?.platform ?? navigator.platform ?? navigator.userAgent ?? "").toLowerCase(); return plat.includes("mac") || plat.includes("iphone") || plat.includes("ipad") ? "mac" : "other"; }, () => "mac", );}interface ParsedStep { /** Normalized tokens like ["mod", "shift", "p"] or ["g"]. */ tokens: string[];}/** Parse "mod+shift+p" or "g then i" into steps of normalized lowercase tokens. */export function parseShortcutSpec(spec: string): ParsedStep[] { return spec .trim() .toLowerCase() .split(/\s+then\s+/i) .map((step) => ({ tokens: step .split("+") .map((t) => normalizeToken(t.trim())) .filter(Boolean), })) .filter((s) => s.tokens.length > 0);}function normalizeToken(raw: string): string { switch (raw) { case "cmd": case "command": case "meta": case "cmdorctrl": case "commandorcontrol": return "mod"; case "control": return "ctrl"; case "option": case "opt": return "alt"; case "escape": return "esc"; case "return": return "enter"; case "arrowup": case "up": return "up"; case "arrowdown": case "down": return "down"; case "arrowleft": case "left": return "left"; case "arrowright": case "right": return "right"; case " ": return "space"; default: return raw; }}function eventToPrimaryToken(e: KeyboardEvent): string | null { const k = e.key.toLowerCase(); if (k === "meta" || k === "control" || k === "alt" || k === "shift") return null; if (k === " ") return "space"; if (k === "escape") return "esc"; if (k === "enter") return "enter"; if (k === "backspace") return "backspace"; if (k === "tab") return "tab"; if (k === "arrowup") return "up"; if (k === "arrowdown") return "down"; if (k === "arrowleft") return "left"; if (k === "arrowright") return "right"; if (k.length === 1) return k; return k;}function formatKeyToken(token: string, resolvedPlatform: "mac" | "other"): string { const isMac = resolvedPlatform === "mac"; switch (token) { case "mod": return isMac ? "⌘" : "Ctrl"; case "ctrl": return isMac ? "⌃" : "Ctrl"; case "alt": return isMac ? "⌥" : "Alt"; case "shift": return isMac ? "⇧" : "Shift"; case "enter": return "↵"; case "esc": return "Esc"; case "space": return "Space"; case "backspace": return "⌫"; case "tab": return "⇥"; case "up": return "↑"; case "down": return "↓"; case "left": return "←"; case "right": return "→"; default: return token.length === 1 ? token.toUpperCase() : token[0].toUpperCase() + token.slice(1); }}function isEditableElement(target: EventTarget | null): boolean { if (!(target instanceof HTMLElement)) return false; const tag = target.tagName; if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return true; return target.isContentEditable;}function Keycap({ label, pressed, matched, reduced,}: { label: string; pressed: boolean; matched: boolean; reduced: boolean;}) { return ( <kbd data-pressed={pressed ? "true" : "false"} className={`inline-flex h-6 min-w-[24px] select-none items-center justify-center rounded-[6px] border px-1.5 font-mono text-[11px] font-medium leading-none ${ reduced ? "" : "transition-[transform,background-color,border-color,color,box-shadow] duration-100" } ${ matched ? "translate-y-[1px] border-emerald-500/50 bg-emerald-500/15 text-emerald-700 shadow-none dark:text-emerald-300" : pressed ? "translate-y-[1px] border-foreground/45 bg-foreground text-background shadow-none" : "border-border bg-background text-foreground shadow-[0_1.5px_0_var(--border),inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[0_1.5px_0_rgb(0_0_0/0.65),inset_0_0.5px_0_rgb(255_255_255/0.07)]" }`} > {label} </kbd> );}interface SheetContentProps { groups: ShortcutGroup[]; title: string; searchable: boolean; liveKeys: boolean; resolvedPlatform: "mac" | "other"; reduced: boolean; isDialog: boolean; sound: boolean; onClose?: () => void; onTrigger?: (entry: ShortcutEntry) => void;}function SheetSurface({ groups, title, searchable, liveKeys, resolvedPlatform, reduced, isDialog, sound, onClose, onTrigger,}: SheetContentProps) { const [query, setQuery] = React.useState(""); const [pressedTokens, setPressedTokens] = React.useState<Set<string>>(() => new Set()); const [matchedId, setMatchedId] = React.useState<string | null>(null); const [liveStatus, setLiveStatus] = React.useState(""); const searchRef = React.useRef<HTMLInputElement | null>(null); const seqPrefixRef = React.useRef<{ token: string; ts: number } | null>(null); const matchTimerRef = React.useRef(0); React.useEffect( () => () => { window.clearTimeout(matchTimerRef.current); }, [], ); // Pre-parse every shortcut spec once per groups update const parsedGroups = React.useMemo( () => groups.map((g) => ({ ...g, entries: g.items.map((item) => ({ item, steps: parseShortcutSpec(item.keys), })), })), [groups], ); const flatEntries = React.useMemo(() => parsedGroups.flatMap((g) => g.entries), [parsedGroups]); const filteredGroups = React.useMemo(() => { const q = query.trim().toLowerCase(); if (!q) return parsedGroups; return parsedGroups .map((g) => ({ ...g, entries: g.entries.filter(({ item }) => { const hay = [g.title, item.label, item.description ?? "", item.keys, ...(item.keywords ?? [])] .join(" ") .toLowerCase(); return hay.includes(q); }), })) .filter((g) => g.entries.length > 0); }, [parsedGroups, query]); const fireMatch = React.useCallback( (entry: ShortcutEntry) => { setMatchedId(entry.id); setLiveStatus(`Matched shortcut: ${entry.label}`); if (sound) playSound("tick", 0.3); onTrigger?.(entry); window.clearTimeout(matchTimerRef.current); matchTimerRef.current = window.setTimeout(() => setMatchedId(null), 1100); }, [onTrigger, sound], ); // Real-time physical keycap lighting & chord / sequence matching React.useEffect(() => { if (!liveKeys) return; const getActiveMods = (e: KeyboardEvent) => { const next = new Set<string>(); const modDown = resolvedPlatform === "mac" ? e.metaKey : e.ctrlKey; if (modDown) next.add("mod"); if (resolvedPlatform === "mac" && e.ctrlKey) next.add("ctrl"); if (e.altKey) next.add("alt"); if (e.shiftKey) next.add("shift"); return next; }; const onKeyDown = (e: KeyboardEvent) => { if (isDialog && e.key === "Escape") { e.preventDefault(); onClose?.(); return; } // Skip live keycap lighting while typing inside the search input (except Escape clearing search) if (isEditableElement(e.target)) { if (e.key === "Escape" && query) { setQuery(""); } return; } const active = getActiveMods(e); const primary = eventToPrimaryToken(e); if (primary) active.add(primary); setPressedTokens(active); if (!primary) return; const now = Date.now(); const hasMods = active.has("mod") || active.has("ctrl") || active.has("alt") || active.has("shift"); // Check two-key sequence match first (e.g. "g then i") const prev = seqPrefixRef.current; if (!hasMods && prev && now - prev.ts < 900) { const seqHit = flatEntries.find( ({ steps }) => steps.length === 2 && steps[0].tokens.length === 1 && steps[0].tokens[0] === prev.token && steps[1].tokens.length === 1 && steps[1].tokens[0] === primary, ); if (seqHit) { e.preventDefault(); seqPrefixRef.current = null; fireMatch(seqHit.item); return; } } // Check single-step chord match (e.g. "mod+k", "mod+shift+p", "/", "c") const chordHit = flatEntries.find(({ steps }) => { if (steps.length !== 1) return false; const req = steps[0].tokens; if (req.length !== active.size) return false; return req.every((t) => active.has(t)); }); if (chordHit) { // Prevent browser hijacking chords like Cmd+K when practicing in the sheet if (hasMods || primary === "/") e.preventDefault(); seqPrefixRef.current = null; fireMatch(chordHit.item); return; } // Record potential sequence prefix (e.g. pressing "g") if (!hasMods) { const isPrefix = flatEntries.some( ({ steps }) => steps.length === 2 && steps[0].tokens.length === 1 && steps[0].tokens[0] === primary, ); seqPrefixRef.current = isPrefix ? { token: primary, ts: now } : null; } else { seqPrefixRef.current = null; } }; const onKeyUp = (e: KeyboardEvent) => { if (isEditableElement(e.target)) return; setPressedTokens(getActiveMods(e)); }; const onBlur = () => setPressedTokens(new Set()); window.addEventListener("keydown", onKeyDown); window.addEventListener("keyup", onKeyUp); window.addEventListener("blur", onBlur); return () => { window.removeEventListener("keydown", onKeyDown); window.removeEventListener("keyup", onKeyUp); window.removeEventListener("blur", onBlur); }; }, [liveKeys, isDialog, onClose, resolvedPlatform, flatEntries, fireMatch, query]); const visibleCount = filteredGroups.reduce((acc, g) => acc + g.entries.length, 0); const liveKeyText = pressedTokens.size > 0 ? Array.from(pressedTokens) .map((t) => formatKeyToken(t, resolvedPlatform)) .join(" + ") : "Press any key to test"; return ( <div role="region" aria-label={title} data-live-keys={liveKeys ? "true" : "false"} data-matched-id={matchedId ?? ""} className="@container flex w-full flex-col overflow-hidden rounded-[16px] border border-border bg-card text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)]" > {/* Header */} <div className="flex flex-wrap items-center justify-between gap-2 border-b border-border/80 bg-muted/20 px-4 py-3"> <div className="flex items-center gap-2"> <Keyboard className="size-4 text-muted-foreground" strokeWidth={1.9} /> <span className="text-[13px] font-medium tracking-[-0.01em] text-foreground">{title}</span> <span className="font-mono text-[11px] tabular-nums text-muted-foreground"> <NumberRoll value={visibleCount} duration={420} /> </span> </div> <div className="flex items-center gap-2"> {liveKeys && ( <span className="hidden items-center gap-1.5 rounded-full border border-border/80 bg-background px-2 py-0.5 text-[10.5px] text-muted-foreground @[440px]:inline-flex"> <span className={`size-1.5 rounded-full transition-colors ${ pressedTokens.size > 0 || matchedId ? "bg-emerald-500" : "bg-muted-foreground/45" }`} /> <TextMorph duration={320}>{liveKeyText}</TextMorph> </span> )} {isDialog && onClose && ( <button type="button" aria-label="Close shortcuts" onClick={onClose} className={`inline-flex size-7 cursor-pointer items-center justify-center rounded-[8px] text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <X className="size-4" strokeWidth={2} /> </button> )} </div> </div> {/* Optional live search filter */} {searchable && ( <div className="flex items-center gap-2 border-b border-border/80 px-3.5 py-2"> <Search className="size-3.5 shrink-0 text-muted-foreground" strokeWidth={2} /> <input ref={searchRef} type="text" aria-label="Filter keyboard shortcuts" placeholder="Filter commands or keys…" value={query} onChange={(e) => setQuery(e.currentTarget.value)} className="h-6 min-w-0 flex-1 bg-transparent text-[12.5px] text-foreground placeholder:text-muted-foreground/55 focus:outline-none" /> {query && ( <button type="button" aria-label="Clear filter" onClick={() => { setQuery(""); searchRef.current?.focus(); }} className="inline-flex size-5 cursor-pointer items-center justify-center rounded-[5px] text-muted-foreground hover:bg-accent hover:text-foreground" > <X className="size-3" strokeWidth={2} /> </button> )} </div> )} {/* Two-column grouped hairline shortcut grid */} <div className="max-h-[420px] overflow-y-auto p-4"> {filteredGroups.length === 0 ? ( <div className="py-8 text-center text-[12.5px] text-muted-foreground"> No shortcuts matching “{query}” </div> ) : ( <div className="grid grid-cols-1 gap-x-5 gap-y-5 md:grid-cols-2"> {filteredGroups.map((group) => ( <div key={group.title} className="flex flex-col gap-1.5"> <h3 className="px-2 text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground"> {group.title} </h3> <div className="flex flex-col divide-y divide-border/50 rounded-[12px] border border-border/80 bg-background/50"> {group.entries.map(({ item, steps }) => { const isMatched = matchedId === item.id; return ( <button key={item.id} type="button" data-shortcut-row={item.id} data-matched={isMatched ? "true" : "false"} onClick={() => fireMatch(item)} className={`flex w-full cursor-pointer items-center justify-between gap-3 px-2.5 py-2 text-left transition-colors first:rounded-t-[11px] last:rounded-b-[11px] ${ isMatched ? "bg-emerald-500/[0.09]" : "hover:bg-accent/55" } ${INTERACTION_FOCUS}`} > <span className="min-w-0"> <span className="flex items-center gap-1.5 text-[12.5px] text-foreground"> <span className="truncate">{item.label}</span> {isMatched && ( <span className="inline-flex shrink-0 items-center gap-0.5 rounded-full bg-emerald-500/15 px-1.5 py-0 text-[10px] font-medium text-emerald-700 dark:text-emerald-300"> <Check className="size-2.5" strokeWidth={2.5} /> Ready </span> )} </span> {item.description && ( <span className="block truncate text-[11px] text-muted-foreground">{item.description}</span> )} </span> <span className="flex shrink-0 items-center gap-1"> {steps.map((step, sIdx) => ( <React.Fragment key={sIdx}> {sIdx > 0 && ( <span className="px-0.5 text-[10px] text-muted-foreground/70">then</span> )} <span className="flex items-center gap-0.5"> {step.tokens.map((tok, tIdx) => ( <Keycap key={`${tok}-${tIdx}`} label={formatKeyToken(tok, resolvedPlatform)} pressed={pressedTokens.has(tok)} matched={isMatched} reduced={reduced} /> ))} </span> </React.Fragment> ))} </span> </button> ); })} </div> </div> ))} </div> )} </div> {/* Subtle footer hint */} <div className="flex items-center justify-between border-t border-border/80 bg-muted/15 px-4 py-2 text-[11px] text-muted-foreground"> <span> Showing {resolvedPlatform === "mac" ? "macOS" : "Windows / Linux"} glyphs </span> {isDialog && <span>Press Esc to close</span>} </div> <span className="sr-only" role="status" aria-live="polite"> {liveStatus} </span> </div> );}export function ShortcutSheet({ groups, variant = "inline", open: controlledOpen, defaultOpen = false, onOpenChange, hotkey = "?", liveKeys = true, onTrigger, platform = "auto", searchable = true, title = "Keyboard shortcuts", sound = false, className = "", ...props}: ShortcutSheetProps) { const reduced = useInteractionReducedMotion(); const detected = useDetectedPlatform(); const resolvedPlatform: "mac" | "other" = platform === "auto" ? detected : platform; const [ownOpen, setOwnOpen] = React.useState(defaultOpen); const isOpen = controlledOpen !== undefined ? controlledOpen : ownOpen; const setOpen = React.useCallback( (next: boolean) => { if (controlledOpen === undefined) setOwnOpen(next); onOpenChange?.(next); }, [controlledOpen, onOpenChange], ); // Global `?` toggle for dialog variant React.useEffect(() => { if (variant !== "dialog" || !hotkey) return; const onKey = (e: KeyboardEvent) => { if (isEditableElement(e.target)) return; if (e.metaKey || e.ctrlKey || e.altKey) return; if (e.key === hotkey) { e.preventDefault(); setOpen(!isOpen); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [variant, hotkey, isOpen, setOpen]); if (variant === "inline") { return ( <div className={`w-full max-w-[720px] ${className}`} {...props}> <SheetSurface groups={groups} title={title} searchable={searchable} liveKeys={liveKeys} resolvedPlatform={resolvedPlatform} reduced={reduced} isDialog={false} sound={sound} onTrigger={onTrigger} /> </div> ); } if (!isOpen) return null; return ( <div role="dialog" aria-modal="true" aria-label={title} className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 backdrop-blur-[2px]" onMouseDown={(e) => { if (e.target === e.currentTarget) setOpen(false); }} > <div className={`w-full max-w-[720px] ${className}`} {...props}> <SheetSurface groups={groups} title={title} searchable={searchable} liveKeys={liveKeys} resolvedPlatform={resolvedPlatform} reduced={reduced} isDialog sound={sound} onClose={() => setOpen(false)} onTrigger={onTrigger} /> </div> </div> );}export default ShortcutSheet;