Open History to see the last commit
1import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import { useEffect } from "react";
3
4export type HardwareKeyboardCommand =
5 | "newTask"
6 | "focusSearch"
7 | "back"
8 | "files"
9 | "terminal"
10 | "review"
11 | "copyThreadReference"
12 | "toggleSidebar";
13
14type CommandHandler = () => boolean | void;
15
16const handlers = new Map<HardwareKeyboardCommand, Set<CommandHandler>>();
17const registrationListeners = new Set<() => void>();
18let registrationVersion = 0;
19
20/**
21 * Registers a context-specific hardware-keyboard action. The most recently mounted handler gets
22 * the first chance to consume the command, allowing focused screens to override app defaults.
23 */
24export function useHardwareKeyboardCommand(
25 command: HardwareKeyboardCommand,
26 handler: CommandHandler,
27): void {
28 useEffect(() => {
29 const commandHandlers = handlers.get(command) ?? new Set<CommandHandler>();
30 commandHandlers.add(handler);
31 handlers.set(command, commandHandlers);
32 registrationVersion += 1;
33 registrationListeners.forEach((listener) => listener());
34 return () => {
35 commandHandlers.delete(handler);
36 if (commandHandlers.size === 0) handlers.delete(command);
37 registrationVersion += 1;
38 registrationListeners.forEach((listener) => listener());
39 };
40 }, [command, handler]);
41}
42
43export function getRegisteredHardwareKeyboardCommands(): ReadonlySet<HardwareKeyboardCommand> {
44 return new Set(handlers.keys());
45}
46
47export function getHardwareKeyboardCommandRegistrationVersion(): number {
48 return registrationVersion;
49}
50
51export function subscribeToHardwareKeyboardCommandRegistrations(listener: () => void): () => void {
52 registrationListeners.add(listener);
53 return () => registrationListeners.delete(listener);
54}
55
56export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
57 const commandHandlers = handlers.get(command);
58 if (!commandHandlers) return false;
59 // `.reverse()` on a copy, not `.toReversed()`: Hermes has no ES2023 array methods.
60 for (const handler of [...commandHandlers].reverse()) {
61 if (handler() !== false) return true;
62 }
63 return false;
64}
65
66export function parseActiveThreadPath(pathname: string): {
67 readonly environmentId: EnvironmentId;
68 readonly threadId: ThreadId;
69} | null {
70 const match = /^\/threads\/([^/]+)\/([^/]+)(?:\/|$)/.exec(pathname);
71 if (!match?.[1] || !match[2]) return null;
72 try {
73 return {
74 environmentId: EnvironmentId.make(decodeURIComponent(match[1])),
75 threadId: ThreadId.make(decodeURIComponent(match[2])),
76 };
77 } catch {
78 return null;
79 }
80}