| 48 | }); |
| 49 | |
| 50 | export function CommandRegistryProvider({ |
| 51 | children, |
| 52 | }: { |
| 53 | children: React.ReactNode; |
| 54 | }) { |
| 55 | const [commands, setCommands] = useState<Command[]>([]); |
| 56 | const commandsRef = useRef<Command[]>([]); |
| 57 | const [paletteOpen, setPaletteOpen] = useState(false); |
| 58 | const [helpOpen, setHelpOpen] = useState(false); |
| 59 | const [recentCommandIds, setRecentCommandIds] = useState<string[]>(() => { |
| 60 | if (typeof window === "undefined") return []; |
| 61 | try { |
| 62 | return JSON.parse(localStorage.getItem(RECENT_KEY) ?? "[]"); |
| 63 | } catch { |
| 64 | return []; |
| 65 | } |
| 66 | }); |
| 67 | |
| 68 | const registerCommand = useCallback((cmd: Command) => { |
| 69 | setCommands((prev) => { |
| 70 | const next = [...prev.filter((c) => c.id !== cmd.id), cmd]; |
| 71 | commandsRef.current = next; |
| 72 | return next; |
| 73 | }); |
| 74 | return () => { |
| 75 | setCommands((prev) => { |
| 76 | const next = prev.filter((c) => c.id !== cmd.id); |
| 77 | commandsRef.current = next; |
| 78 | return next; |
| 79 | }); |
| 80 | }; |
| 81 | }, []); |
| 82 | |
| 83 | const addToRecent = useCallback((id: string) => { |
| 84 | setRecentCommandIds((prev) => { |
| 85 | const next = [id, ...prev.filter((r) => r !== id)].slice(0, RECENT_MAX); |
| 86 | try { |
| 87 | localStorage.setItem(RECENT_KEY, JSON.stringify(next)); |
| 88 | } catch {} |
| 89 | return next; |
| 90 | }); |
| 91 | }, []); |
| 92 | |
| 93 | const runCommand = useCallback( |
| 94 | (id: string) => { |
| 95 | const cmd = commandsRef.current.find((c) => c.id === id); |
| 96 | if (!cmd) return; |
| 97 | if (cmd.when && !cmd.when()) return; |
| 98 | addToRecent(id); |
| 99 | cmd.action(); |
| 100 | }, |
| 101 | [addToRecent] |
| 102 | ); |
| 103 | |
| 104 | const openPalette = useCallback(() => setPaletteOpen(true), []); |
| 105 | const closePalette = useCallback(() => setPaletteOpen(false), []); |
| 106 | const openHelp = useCallback(() => setHelpOpen(true), []); |
| 107 | const closeHelp = useCallback(() => setHelpOpen(false), []); |