Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

hardwareKeyboardCommands.ts

82 lines2.6 KB

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]);
42​
43export function getRegisteredHardwareKeyboardCommands(): ReadonlySet<HardwareKeyboardCommand> {
44 return new Set(handlers.keys());
46​
47export function getHardwareKeyboardCommandRegistrationVersion(): number {
48 return registrationVersion;
50​
51export function subscribeToHardwareKeyboardCommandRegistrations(listener: () => void): () => void {
52 registrationListeners.add(listener);
53 return () => registrationListeners.delete(listener);
55​
56export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
57 const commandHandlers = handlers.get(command);
58 if (!commandHandlers) return false;
59 const handlersInRegistrationOrder = Array.from(commandHandlers);
60 for (let index = handlersInRegistrationOrder.length - 1; index >= 0; index -= 1) {
61 const handler = handlersInRegistrationOrder[index];
62 if (!handler) continue;
63 if (handler() !== false) return true;
64 }
65 return false;
67​
68export function parseActiveThreadPath(pathname: string): {
69 readonly environmentId: EnvironmentId;
70 readonly threadId: ThreadId;
71} | null {
72 const match = /^\/threads\/([^/]+)\/([^/]+)(?:\/|$)/.exec(pathname);
73 if (!match?.[1] || !match[2]) return null;
74 try {
75 return {
76 environmentId: EnvironmentId.make(decodeURIComponent(match[1])),
77 threadId: ThreadId.make(decodeURIComponent(match[2])),
78 };
79 } catch {
80 return null;
81 }