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

dispatcher.ts

176 lines6.6 KB

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