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 isInsideConfirmation(target: EventTarget | null): boolean {
57 return target instanceof Element && target.closest('[role="alertdialog"]') !== null;
58}
59
60function isInsideKeybindingCapture(target: EventTarget | null): boolean {
61 return target instanceof Element && target.closest("[data-keybinding-capture]") !== null;
62}
63
64function scopeCommandHandler(scope: CommandScope, event: KeyboardEvent) {
65 const { commands, options } = scope;
66 const command = resolveShortcutCommand(
67 event,
68 options.keybindings?.() ?? appAtomRegistry.get(primaryServerKeybindingsAtom),
69 { context: { ...readFocusContext(event), ...options.context?.() } },
70 );
71 return command === null ? undefined : commands[command];
72}
73
74function runScope(scope: CommandScope, event: KeyboardEvent): boolean {
75 const { options } = scope;
76 if (options.when && !options.when(event)) return false;
77 if (options.onKeyDown && options.onKeyDown(event) !== false) return true;
78 const handler = scopeCommandHandler(scope, event);
79 if (handler === undefined) return false;
80 if (isInsideConfirmation(event.target)) {
81 event.preventDefault();
82 return true;
83 }
84 return handler(event) !== false;
85}
86
87/**
88 * Whether a bubble-phase command is bound to this keydown, for widgets that would otherwise
89 * consume it. Capture scopes have already run (and declined) by the time a widget sees it.
90 */
91export function hasCommandForKeyDown(event: KeyboardEvent): boolean {
92 return globalScopes.some(
93 (scope) =>
94 (!scope.options.when || scope.options.when(event)) &&
95 scopeCommandHandler(scope, event) !== undefined,
96 );
97}
98
99function runScopes(scopes: readonly CommandScope[], event: KeyboardEvent): boolean {
100 for (let index = scopes.length - 1; index >= 0; index -= 1) {
101 if (event.defaultPrevented) return true;
102 const scope = scopes[index];
103 if (scope && runScope(scope, event)) return true;
104 }
105 return false;
106}
107
108function dispatchCaptureKeyDown(event: KeyboardEvent): void {
109 if (isInsideKeybindingCapture(event.target)) return;
110 runScopes(captureScopes, event);
111}
112
113function dispatchKeyDown(event: KeyboardEvent): void {
114 const consumed = runScopes(globalScopes, event) || event.defaultPrevented;
115 for (const scope of observerScopes.slice()) scope.options.observe?.(event, consumed);
116}
117
118let keydownInstalled = false;
119function ensureKeydownListener() {
120 if (keydownInstalled || typeof window === "undefined") return;
121 keydownInstalled = true;
122 window.addEventListener("keydown", dispatchCaptureKeyDown, true);
123 window.addEventListener("keydown", dispatchKeyDown);
124}
125
126function pushScope(list: CommandScope[], scope: CommandScope): () => void {
127 ensureKeydownListener();
128 list.push(scope);
129 return () => {
130 const index = list.lastIndexOf(scope);
131 if (index !== -1) list.splice(index, 1);
132 };
133}
134
135/** App-global commands, registered once at module level or bootstrap. */
136export function registerCommands(
137 commands: CommandHandlers,
138 options: CommandScopeOptions = {},
139): () => void {
140 const scopes = options.observe ? observerScopes : options.capture ? captureScopes : globalScopes;
141 return pushScope(scopes, { commands, options });
142}
143
144type MenuActionHandler = () => void;
145const menuActionHandlers = new Map<string, MenuActionHandler[]>();
146let menuActionInstalled = false;
147
148export function dispatchMenuAction(action: string): void {
149 const handlers = menuActionHandlers.get(action);
150 handlers?.at(-1)?.();
151}
152
153function ensureMenuActionListener() {
154 if (menuActionInstalled || typeof window === "undefined") return;
155 const bridge = window.desktopBridge;
156 if (typeof bridge?.onMenuAction !== "function") return;
157 menuActionInstalled = true;
158 bridge.onMenuAction(dispatchMenuAction);
159}
160
161/** Desktop menu actions; the newest handler for an action wins. */
162export function registerMenuAction(action: string, handler: MenuActionHandler): () => void {
163 ensureMenuActionListener();
164 const handlers = menuActionHandlers.get(action) ?? [];
165 handlers.push(handler);
166 menuActionHandlers.set(action, handlers);
167 return () => {
168 const index = handlers.lastIndexOf(handler);
169 if (index !== -1) handlers.splice(index, 1);
170 };
171}