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

dispatcher.ts

149 lines5.5 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​
56function isInsideConfirmation(target: EventTarget | null): boolean {
57 return target instanceof Element && target.closest('[role="alertdialog"]') !== null;
59​
60function runScope(scope: CommandScope, event: KeyboardEvent): boolean {
61 const { commands, options } = scope;
62 if (options.when && !options.when(event)) return false;
63 if (options.onKeyDown && options.onKeyDown(event) !== false) return true;
64 const command = resolveShortcutCommand(
65 event,
66 options.keybindings?.() ?? appAtomRegistry.get(primaryServerKeybindingsAtom),
67 { context: { ...readFocusContext(event), ...options.context?.() } },
68 );
69 const handler = command === null ? undefined : commands[command];
70 if (handler === undefined) return false;
71 if (isInsideConfirmation(event.target)) {
72 event.preventDefault();
73 return true;
74 }
75 return handler(event) !== false;
77​
78function runScopes(scopes: readonly CommandScope[], event: KeyboardEvent): boolean {
79 for (let index = scopes.length - 1; index >= 0; index -= 1) {
80 if (event.defaultPrevented) return true;
81 const scope = scopes[index];
82 if (scope && runScope(scope, event)) return true;
83 }
84 return false;
86​
87function dispatchCaptureKeyDown(event: KeyboardEvent): void {
88 runScopes(captureScopes, event);
90​
91function dispatchKeyDown(event: KeyboardEvent): void {
92 const consumed = runScopes(globalScopes, event) || event.defaultPrevented;
93 for (const scope of observerScopes.slice()) scope.options.observe?.(event, consumed);
95​
96let keydownInstalled = false;
97function ensureKeydownListener() {
98 if (keydownInstalled || typeof window === "undefined") return;
99 keydownInstalled = true;
100 window.addEventListener("keydown", dispatchCaptureKeyDown, true);
101 window.addEventListener("keydown", dispatchKeyDown);
103​
104function pushScope(list: CommandScope[], scope: CommandScope): () => void {
105 ensureKeydownListener();
106 list.push(scope);
107 return () => {
108 const index = list.lastIndexOf(scope);
109 if (index !== -1) list.splice(index, 1);
110 };
112​
113/** App-global commands, registered once at module level or bootstrap. */
114export function registerCommands(
115 commands: CommandHandlers,
116 options: CommandScopeOptions = {},
117): () => void {
118 const scopes = options.observe ? observerScopes : options.capture ? captureScopes : globalScopes;
119 return pushScope(scopes, { commands, options });
121​
122type MenuActionHandler = () => void;
123const menuActionHandlers = new Map<string, MenuActionHandler[]>();
124let menuActionInstalled = false;
125​
126export function dispatchMenuAction(action: string): void {
127 const handlers = menuActionHandlers.get(action);
128 handlers?.at(-1)?.();
130​
131function ensureMenuActionListener() {
132 if (menuActionInstalled || typeof window === "undefined") return;
133 const bridge = window.desktopBridge;
134 if (typeof bridge?.onMenuAction !== "function") return;
135 menuActionInstalled = true;
136 bridge.onMenuAction(dispatchMenuAction);
138​
139/** Desktop menu actions; the newest handler for an action wins. */
140export function registerMenuAction(action: string, handler: MenuActionHandler): () => void {
141 ensureMenuActionListener();
142 const handlers = menuActionHandlers.get(action) ?? [];
143 handlers.push(handler);
144 menuActionHandlers.set(action, handlers);
145 return () => {
146 const index = handlers.lastIndexOf(handler);
147 if (index !== -1) handlers.splice(index, 1);
148 };