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

useChatShortcuts.ts

163 lines7.1 KB

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 through, except for cycling while a terminal owns focus. */
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;
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 if (event.target instanceof Element && event.target.closest("[data-keybinding-capture]")) {
66 return;
67 }
68 const { keybindings } = input;
69 if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {
70 event.stopPropagation();
71 return;
72 }
73 if (input.threadFindActive && event.key === "Escape") return;
74 if (isTerminalCloseConfirmPending() && preventTerminalCloseShortcut(event, keybindings)) {
75 event.stopPropagation();
76 return;
77 }
78 if (!input.enabled || isCommandPaletteOpen()) return;
79 const inSideChatPane = isInSideChatPane(event.target);
80 const terminalFocusOwner = getTerminalFocusOwner();
81 if (event.defaultPrevented && terminalFocusOwner === null) return;
82 const shortcutContext = input.getShortcutContext(event.target);
83​
84 if (
85 !inSideChatPane &&
86 !shortcutContext.terminalFocus &&
87 !shortcutContext.modelPickerOpen &&
88 shouldTypeToFocusComposer(event) &&
89 input.composerRef.current?.insertTextAtEnd(event.key) === true
90 ) {
91 event.preventDefault();
92 event.stopPropagation();
93 return;
94 }
95​
96 const command = resolveChatShortcutCommand(event, keybindings, input.scriptKeybindings, {
97 context: shortcutContext,
98 });
99 if (!command || (inSideChatPane && !SIDE_CHAT_PANE_COMMANDS.has(command))) return;
100 const run =
101 input.commands[command] ??
102 composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command] ??
103 input.fallback(command);
104 if (!run) return;
105 const handled = run({ event, terminalFocusOwner });
106 if (
107 handled === false &&
108 (terminalFocusOwner === null ||
109 (command !== "terminal.previous" && command !== "terminal.next"))
110 )
111 return;
112 event.preventDefault();
113 event.stopPropagation();
114 });
115 const dismissFind = useEffectEvent((event: KeyboardEvent) => {
116 if (
117 event.key !== "Escape" ||
118 !input.threadFindActive ||
119 event.defaultPrevented ||
120 event.isComposing ||
121 event.keyCode === 229 ||
122 isCommandPaletteOpen() ||
123 isInSideChatPane(event.target) !== embedded
124 )
125 return;
126 const context = input.getShortcutContext(event.target);
127 if (context.terminalFocus || context.previewFocus || context.modelPickerOpen) return;
128 // The narrow right panel sheet closes on Escape and ignores defaultPrevented.
129 event.preventDefault();
130 event.stopPropagation();
131 input.closeThreadFind();
132 });
133 const handleSideChatShortcut = useEffectEvent((event: KeyboardEvent) => {
134 if (event.defaultPrevented || isCommandPaletteOpen()) return;
135 const command = resolveChatShortcutCommand(event, input.keybindings, input.scriptKeybindings, {
136 context: input.getShortcutContext(event.target),
137 });
138 let run: ChatShortcutHandler | undefined;
139 if (command === "chat.find") run = input.commands[command];
140 else if (command && event.target instanceof Node && composerElement?.contains(event.target)) {
141 run = composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command];
142 }
143 if (!run || run({ event, terminalFocusOwner: null }) === false) return;
144 event.preventDefault();
145 event.stopPropagation();
146 });
147 // 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
148 useEffect(() => {
149 const target: Pick<HTMLElement, "addEventListener" | "removeEventListener"> | null = embedded
150 ? (composerElement?.closest<HTMLElement>("[data-side-chat-pane]") ?? null)
151 : window;
152 if (!target) return;
153 const onKeyDownCapture = (event: KeyboardEvent) =>
154 embedded ? handleSideChatShortcut(event) : handleShortcut(event);
155 const onKeyDown = (event: KeyboardEvent) => dismissFind(event);
156 target.addEventListener("keydown", onKeyDownCapture, true);
157 target.addEventListener("keydown", onKeyDown);
158 return () => {
159 target.removeEventListener("keydown", onKeyDownCapture, true);
160 target.removeEventListener("keydown", onKeyDown);
161 };
162 }, [composerElement, embedded]);