The best way to control Claude Code, Codex and more from any computer or phone

main
ts 149 lines 6.41 KB
Raw
1 import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2 import { useEffect, useEffectEvent } from "react";
3 import { isCommandPaletteOpen } from "../../commandPaletteBus";
4 import { resolveChatShortcutCommand, type ShortcutMatchContext } from "../../keybindings";
5 import { isTerminalCloseConfirmPending } from "../../lib/terminalCloseConfirm";
6 import {
7 preventRepeatedTerminalCloseShortcut,
8 preventTerminalCloseShortcut,
9 } from "../../lib/terminalCloseShortcut";
10 import { isInSideChatPane } from "../../lib/sideChatPane";
11 import { getTerminalFocusOwner, type TerminalFocusOwner } from "../../lib/terminalFocus";
12 import type { ComposerHandleRef } from "../../composerHandleContext";
13 import type { BranchToolbarHandle } from "../BranchToolbar";
14 import { shouldTypeToFocusComposer } from "./composerFocusRedirect";
15 import { composerShortcutCommands } from "./composerShortcuts";
16
17 /** Returning false lets the key event through untouched. */
18 type ChatShortcutHandler = (context: {
19 readonly event: KeyboardEvent;
20 readonly terminalFocusOwner: TerminalFocusOwner | null;
21 }) => boolean | void;
22
23 export type ChatShortcutCommands = Partial<Record<KeybindingCommand, ChatShortcutHandler>>;
24
25 /** Window-level commands the main chat still runs while focus is in its side chat pane. */
26 const SIDE_CHAT_PANE_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
27 "rightPanel.toggle",
28 "rightPanel.close",
29 "rightPanel.toggleMaximized",
30 ]);
31
32 interface ChatShortcutsInput {
33 readonly enabled: boolean;
34 /**
35 * A side chat inside another chat leaves the window to the outer chat. It runs only
36 * composer chords, for keys pressed inside `composerElement`.
37 */
38 readonly embedded?: boolean;
39 readonly composerElement?: HTMLElement | null;
40 readonly keybindings: ResolvedKeybindingsConfig;
41 readonly scriptKeybindings: ResolvedKeybindingsConfig;
42 readonly getShortcutContext: (target: EventTarget | null) => ShortcutMatchContext & {
43 readonly modelPickerOpen: boolean;
44 };
45 readonly threadFindActive: boolean;
46 /** Takes type-to-focus keys and the composer and branch toolbar chords. */
47 readonly composerRef: ComposerHandleRef;
48 readonly branchToolbarRef: { readonly current: BranchToolbarHandle | null };
49 readonly closeThreadFind: () => void;
50 readonly commands: ChatShortcutCommands;
51 /** Handles commands not in `commands`, such as project scripts. */
52 readonly fallback: (command: KeybindingCommand) => ChatShortcutHandler | undefined;
53 }
54
55 /**
56 * The chat's window keyboard shortcuts, plus Escape closing thread find.
57 * Listeners attach once; the effect events read the latest input, so handlers
58 * act on the current render without re-registering on every change.
59 */
60 export function useChatShortcuts(input: ChatShortcutsInput) {
61 const embedded = input.embedded === true;
62 const composerElement = embedded ? (input.composerElement ?? null) : null;
63 const handleShortcut = useEffectEvent((event: KeyboardEvent) => {
64 const { keybindings } = input;
65 if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {
66 event.stopPropagation();
67 return;
68 }
69 if (input.threadFindActive && event.key === "Escape") return;
70 if (isTerminalCloseConfirmPending() && preventTerminalCloseShortcut(event, keybindings)) {
71 event.stopPropagation();
72 return;
73 }
74 if (!input.enabled || isCommandPaletteOpen()) return;
75 const inSideChatPane = isInSideChatPane(event.target);
76 const terminalFocusOwner = getTerminalFocusOwner();
77 if (event.defaultPrevented && terminalFocusOwner === null) return;
78 const shortcutContext = input.getShortcutContext(event.target);
79
80 if (
81 !inSideChatPane &&
82 !shortcutContext.terminalFocus &&
83 !shortcutContext.modelPickerOpen &&
84 shouldTypeToFocusComposer(event) &&
85 input.composerRef.current?.insertTextAtEnd(event.key) === true
86 ) {
87 event.preventDefault();
88 event.stopPropagation();
89 return;
90 }
91
92 const command = resolveChatShortcutCommand(event, keybindings, input.scriptKeybindings, {
93 context: shortcutContext,
94 });
95 if (!command || (inSideChatPane && !SIDE_CHAT_PANE_COMMANDS.has(command))) return;
96 const run =
97 input.commands[command] ??
98 composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command] ??
99 input.fallback(command);
100 if (!run || run({ event, terminalFocusOwner }) === false) return;
101 event.preventDefault();
102 event.stopPropagation();
103 });
104 const dismissFind = useEffectEvent((event: KeyboardEvent) => {
105 if (
106 event.key !== "Escape" ||
107 !input.threadFindActive ||
108 event.defaultPrevented ||
109 event.isComposing ||
110 event.keyCode === 229 ||
111 isCommandPaletteOpen() ||
112 isInSideChatPane(event.target)
113 )
114 return;
115 const context = input.getShortcutContext(event.target);
116 if (context.terminalFocus || context.previewFocus || context.modelPickerOpen) return;
117 event.preventDefault();
118 input.closeThreadFind();
119 });
120 const handleComposerShortcut = useEffectEvent((event: KeyboardEvent) => {
121 if (event.defaultPrevented || isCommandPaletteOpen()) return;
122 const command = resolveChatShortcutCommand(event, input.keybindings, input.scriptKeybindings, {
123 context: input.getShortcutContext(event.target),
124 });
125 const run = command
126 ? composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command]
127 : undefined;
128 if (!run || run({ event, terminalFocusOwner: null }) === false) return;
129 event.preventDefault();
130 event.stopPropagation();
131 });
132 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches keydown listeners for chat shortcuts and find dismissal: on the window, or on an embedded chat's composer
133 useEffect(() => {
134 if (embedded) {
135 if (composerElement === null) return;
136 const onComposerKeyDown = (event: KeyboardEvent) => handleComposerShortcut(event);
137 composerElement.addEventListener("keydown", onComposerKeyDown, true);
138 return () => composerElement.removeEventListener("keydown", onComposerKeyDown, true);
139 }
140 const onKeyDownCapture = (event: KeyboardEvent) => handleShortcut(event);
141 const onKeyDown = (event: KeyboardEvent) => dismissFind(event);
142 window.addEventListener("keydown", onKeyDownCapture, true);
143 window.addEventListener("keydown", onKeyDown);
144 return () => {
145 window.removeEventListener("keydown", onKeyDownCapture, true);
146 window.removeEventListener("keydown", onKeyDown);
147 };
148 }, [composerElement, embedded]);
149 }