Open History to see the last commit
1import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2
3import { resolveShortcutCommand, type ShortcutMatchContext } from "../keybindings";
4import { isEditableFocused } from "../lib/editableFocus";
5import { isPreviewFocused } from "../lib/previewFocus";
6import { isTerminalFocused } from "../lib/terminalFocus";
7import { isModelPickerOpen } from "../modelPickerVisibility";
8import { appAtomRegistry } from "../rpc/atomRegistry";
9import { primaryServerKeybindingsAtom } from "../state/server";
10
11/** Return `false` to let the next scope handle the event. */
12export type CommandHandler = (event: KeyboardEvent) => boolean | void;
13
14export type CommandHandlers = Partial<Record<KeybindingCommand, CommandHandler>>;
15
16export interface CommandScopeOptions {
17 /** Read at event time; a scope whose guard fails is skipped. */
18 readonly when?: (event: KeyboardEvent) => boolean;
19 /** When-clause context the dispatcher cannot know (terminalOpen, previewOpen), read at event time. */
20 readonly context?: () => Partial<ShortcutMatchContext>;
21 readonly keybindings?: () => ResolvedKeybindingsConfig;
22 /** For shortcuts that are not keybinding commands (Escape, "/"); runs before command lookup. */
23 readonly onKeyDown?: CommandHandler;
24 /**
25 * Run in the capture phase, ahead of focused widgets that consume the key
26 * themselves (the terminal encodes Ctrl+Shift+T and stops propagation).
27 */
28 readonly capture?: boolean;
29 /**
30 * Hear every bubbling keydown after the scopes ran, with whether one of them
31 * (or the page) consumed it. Observers never consume. For listeners that react to keys other
32 * scopes may also handle, such as scroll keys.
33 */
34 readonly observe?: (event: KeyboardEvent, consumed: boolean) => void;
35}
36
37interface CommandScope {
38 readonly commands: CommandHandlers;
39 readonly options: CommandScopeOptions;
40}
41
42// Within each list the newest scope wins.
43const globalScopes: CommandScope[] = [];
44const captureScopes: CommandScope[] = [];
45const observerScopes: CommandScope[] = [];
46
47function readFocusContext(event: KeyboardEvent): Partial<ShortcutMatchContext> {
48 return {
49 terminalFocus: isTerminalFocused(),
50 previewFocus: isPreviewFocused(),
51 editableFocus: isEditableFocused(event.target),
52 modelPickerOpen: isModelPickerOpen(),
53 };
54}
55
56function runScope(scope: CommandScope, event: KeyboardEvent): boolean {
57 const { commands, options } = scope;
58 if (options.when && !options.when(event)) return false;
59 if (options.onKeyDown && options.onKeyDown(event) !== false) return true;
60 const command = resolveShortcutCommand(
61 event,
62 options.keybindings?.() ?? appAtomRegistry.get(primaryServerKeybindingsAtom),
63 { context: { ...readFocusContext(event), ...options.context?.() } },
64 );
65 const handler = command === null ? undefined : commands[command];
66 return handler !== undefined && handler(event) !== false;
67}
68
69function runScopes(scopes: readonly CommandScope[], event: KeyboardEvent): boolean {
70 for (let index = scopes.length - 1; index >= 0; index -= 1) {
71 if (event.defaultPrevented) return true;
72 const scope = scopes[index];
73 if (scope && runScope(scope, event)) return true;
74 }
75 return false;
76}
77
78function dispatchCaptureKeyDown(event: KeyboardEvent): void {
79 runScopes(captureScopes, event);
80}
81
82function dispatchKeyDown(event: KeyboardEvent): void {
83 const consumed = runScopes(globalScopes, event) || event.defaultPrevented;
84 for (const scope of observerScopes.slice()) scope.options.observe?.(event, consumed);
85}
86
87let keydownInstalled = false;
88function ensureKeydownListener() {
89 if (keydownInstalled || typeof window === "undefined") return;
90 keydownInstalled = true;
91 window.addEventListener("keydown", dispatchCaptureKeyDown, true);
92 window.addEventListener("keydown", dispatchKeyDown);
93}
94
95function pushScope(list: CommandScope[], scope: CommandScope): () => void {
96 ensureKeydownListener();
97 list.push(scope);
98 return () => {
99 const index = list.lastIndexOf(scope);
100 if (index !== -1) list.splice(index, 1);
101 };
102}
103
104/** App-global commands, registered once at module level or bootstrap. */
105export function registerCommands(
106 commands: CommandHandlers,
107 options: CommandScopeOptions = {},
108): () => void {
109 const scopes = options.observe ? observerScopes : options.capture ? captureScopes : globalScopes;
110 return pushScope(scopes, { commands, options });
111}
112
113type MenuActionHandler = () => void;
114const menuActionHandlers = new Map<string, MenuActionHandler[]>();
115let menuActionInstalled = false;
116
117export function dispatchMenuAction(action: string): void {
118 const handlers = menuActionHandlers.get(action);
119 handlers?.at(-1)?.();
120}
121
122function ensureMenuActionListener() {
123 if (menuActionInstalled || typeof window === "undefined") return;
124 const bridge = window.desktopBridge;
125 if (typeof bridge?.onMenuAction !== "function") return;
126 menuActionInstalled = true;
127 bridge.onMenuAction(dispatchMenuAction);
128}
129
130/** Desktop menu actions; the newest handler for an action wins. */
131export function registerMenuAction(action: string, handler: MenuActionHandler): () => void {
132 ensureMenuActionListener();
133 const handlers = menuActionHandlers.get(action) ?? [];
134 handlers.push(handler);
135 menuActionHandlers.set(action, handlers);
136 return () => {
137 const index = handlers.lastIndexOf(handler);
138 if (index !== -1) handlers.splice(index, 1);
139 };
140}