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