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