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

useChatShortcuts.ts

261 lines11.0 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 { getTerminalFocusOwner, type TerminalFocusOwner } from "../../lib/terminalFocus";
11import type { ComposerHandleRef } from "../../composerHandleContext";
12import { isRightPanelShortcutBlockedByContextMenu } from "../../shortcuts/rightPanelShortcuts";
13import type { BranchToolbarHandle } from "../BranchToolbar";
14import { isInsideComposerFloatingLayer } from "./composerEventScope";
15import {
16 shouldTypeToFocusComposer,
17 TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,
18} from "./composerFocusRedirect";
19import { composerShortcutCommands } from "./composerShortcuts";
20​
21/** Returning false lets the key through, except for cycling while a terminal owns focus. */
22type ChatShortcutHandler = (context: {
23 readonly event: KeyboardEvent;
24 readonly terminalFocusOwner: TerminalFocusOwner | null;
25}) => boolean | void;
26​
27export type ChatShortcutCommands = Partial<Record<KeybindingCommand, ChatShortcutHandler>>;
28​
29/** Window-level commands the main chat still runs while focus is in its side chat pane. */
30const SIDE_CHAT_PANE_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
31 "rightPanel.toggle",
32 "rightPanel.close",
33 "rightPanel.toggleMaximized",
34]);
35/** A side chat's own commands, run from anywhere in its pane: its find and its queue. */
36const SIDE_CHAT_OWN_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
37 "chat.find",
38 "thread.steerQueuedMessage",
39 "thread.editQueuedMessage",
40]);
41// The narrow right panel renders as a sheet-popup, so it must not block closing itself.
42const OPEN_LAYER = `:is(${TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR}):not([data-slot="sheet-popup"])`;
43​
44// The mobile sidebar is a layer of the app, not a popup a chat opened.
45const PORTALLED_POPUP = `${OPEN_LAYER}:not([data-slot="sidebar"])`;
46​
47// Popups portal out of the side chat pane, so DOM ancestry cannot name their chat;
48// the embedded pane that last took focus or a pointer press owns them instead.
49let popupOwner: Element | null = null;
50const embeddedPanes = new Set<Element>();
51​
52function isInsidePortalledPopup(target: Element): boolean {
53 return isInsideComposerFloatingLayer(target) || target.closest(PORTALLED_POPUP) !== null;
55​
56function trackPopupOwner(target: EventTarget | null) {
57 if (!(target instanceof Element) || target.hasAttribute("data-base-ui-focus-guard")) return;
58 const pane = target.closest("[data-side-chat-pane]");
59 if (pane === null && isInsidePortalledPopup(target)) return;
60 popupOwner = pane && embeddedPanes.has(pane) ? pane : null;
62​
63const onPopupOwnerEvent = (event: Event) => trackPopupOwner(event.target);
64​
65/** Whether a key event belongs to a side chat: pressed in its pane or in a popup it opened. */
66export function isSideChatShortcutTarget(target: EventTarget | null): boolean {
67 return sideChatOwnerFor(target) !== null;
69​
70/**
71 * Whether a side chat's key was pressed in its pane or a composer popup. Its other popups,
72 * such as a message menu, keep their keys: neither chat acts on them.
73 */
74export function isSideChatCommandTarget(target: EventTarget | null): boolean {
75 return (
76 target instanceof Element &&
77 (target.closest("[data-side-chat-pane]") !== null || isInsideComposerFloatingLayer(target))
78 );
80​
81function sideChatOwnerFor(target: EventTarget | null): Element | null {
82 if (!(target instanceof Element)) return null;
83 const pane = target.closest("[data-side-chat-pane]");
84 if (pane) return pane;
85 return isInsidePortalledPopup(target) &&
86 popupOwner?.isConnected &&
87 popupOwner.closest("[inert]") === null
88 ? popupOwner
89 : null;
91​
92interface ChatShortcutsInput {
93 readonly enabled: boolean;
94 /**
95 * A side chat inside another chat handles its pane's find and queue, composer chords, and
96 * the popups it portals out via a capture listener on `window`, while keeping Escape find
97 * dismissal on its pane and leaving non-composer window shortcuts to the outer chat.
98 */
99 readonly embedded?: boolean;
100 readonly composerElement?: HTMLElement | null;
101 readonly keybindings: ResolvedKeybindingsConfig;
102 readonly scriptKeybindings: ResolvedKeybindingsConfig;
103 readonly getShortcutContext: (target: EventTarget | null) => ShortcutMatchContext & {
104 readonly modelPickerOpen: boolean;
105 };
106 readonly threadFindActive: boolean;
107 /** Takes type-to-focus keys and the composer and branch toolbar chords. */
108 readonly composerRef: ComposerHandleRef;
109 readonly branchToolbarRef: { readonly current: BranchToolbarHandle | null };
110 readonly closeThreadFind: () => void;
111 readonly commands: ChatShortcutCommands;
112 /** Handles commands not in `commands`, such as project scripts. */
113 readonly fallback: (command: KeybindingCommand) => ChatShortcutHandler | undefined;
115​
116/**
117 * The chat's window keyboard shortcuts, plus Escape closing thread find.
118 * Listeners attach once; the effect events read the latest input, so handlers
119 * act on the current render without re-registering on every change.
120 */
121export function useChatShortcuts(input: ChatShortcutsInput) {
122 const embedded = input.embedded === true;
123 const composerElement = embedded ? (input.composerElement ?? null) : null;
124 const handleShortcut = useEffectEvent((event: KeyboardEvent) => {
125 if (event.target instanceof Element && event.target.closest("[data-keybinding-capture]")) {
126 return;
127 }
128 const { keybindings } = input;
129 if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {
130 event.stopPropagation();
131 return;
132 }
133 if (input.threadFindActive && event.key === "Escape") return;
134 if (isTerminalCloseConfirmPending() && preventTerminalCloseShortcut(event, keybindings)) {
135 event.stopPropagation();
136 return;
137 }
138 if (!input.enabled || isCommandPaletteOpen()) return;
139 const inSideChatPane = sideChatOwnerFor(event.target) !== null;
140 const terminalFocusOwner = getTerminalFocusOwner();
141 if (event.defaultPrevented && terminalFocusOwner === null) return;
142 const shortcutContext = input.getShortcutContext(event.target);
143​
144 if (
145 !inSideChatPane &&
146 !shortcutContext.terminalFocus &&
147 !shortcutContext.modelPickerOpen &&
148 shouldTypeToFocusComposer(event) &&
149 input.composerRef.current?.insertTextAtEnd(event.key) === true
150 ) {
151 event.preventDefault();
152 event.stopPropagation();
153 return;
154 }
155​
156 const command = resolveChatShortcutCommand(event, keybindings, input.scriptKeybindings, {
157 context: shortcutContext,
158 });
159 if (!command || (inSideChatPane && !SIDE_CHAT_PANE_COMMANDS.has(command))) return;
160 if (isRightPanelShortcutBlockedByContextMenu(command)) return;
161 const isBlockedByOpenLayer =
162 command === "rightPanel.close" ||
163 command === "rightPanel.toggle" ||
164 command === "terminal.toggle";
165 if (isBlockedByOpenLayer && document.querySelector(OPEN_LAYER) !== null) return;
166 // Escape dismisses any open layer, the narrow right panel sheet included, before it stops.
167 if (
168 command === "thread.stop" &&
169 event.key === "Escape" &&
170 document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR) !== null
171 )
172 return;
173 const run =
174 input.commands[command] ??
175 composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command] ??
176 input.fallback(command);
177 if (!run) return;
178 if (!inSideChatPane) popupOwner = null;
179 const handled = run({ event, terminalFocusOwner });
180 if (
181 handled === false &&
182 (terminalFocusOwner === null ||
183 (command !== "terminal.previous" && command !== "terminal.next"))
184 )
185 return;
186 event.preventDefault();
187 event.stopPropagation();
188 });
189 const dismissFind = useEffectEvent((event: KeyboardEvent) => {
190 if (
191 event.key !== "Escape" ||
192 !input.threadFindActive ||
193 event.defaultPrevented ||
194 event.isComposing ||
195 event.keyCode === 229 ||
196 isCommandPaletteOpen() ||
197 (sideChatOwnerFor(event.target) !== null) !== embedded
198 )
199 return;
200 const context = input.getShortcutContext(event.target);
201 if (context.terminalFocus || context.previewFocus || context.modelPickerOpen) return;
202 // The narrow right panel sheet closes on Escape and ignores defaultPrevented.
203 event.preventDefault();
204 event.stopPropagation();
205 input.closeThreadFind();
206 });
207 const handleSideChatShortcut = useEffectEvent((event: KeyboardEvent, pane: HTMLElement) => {
208 if (event.defaultPrevented || isCommandPaletteOpen()) return;
209 if (sideChatOwnerFor(event.target) !== pane || !isSideChatCommandTarget(event.target)) return;
210 const command = resolveChatShortcutCommand(event, input.keybindings, input.scriptKeybindings, {
211 context: input.getShortcutContext(event.target),
212 });
213 let run: ChatShortcutHandler | undefined;
214 if (command && SIDE_CHAT_OWN_COMMANDS.has(command)) run = input.commands[command];
215 else if (
216 command &&
217 (isInsideComposerFloatingLayer(event.target) ||
218 (event.target instanceof Node && composerElement?.contains(event.target)))
219 ) {
220 run = composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command];
221 }
222 if (!run || run({ event, terminalFocusOwner: null }) === false) return;
223 event.preventDefault();
224 event.stopPropagation();
225 });
226 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches window capture shortcut/popup-owner listeners and pane/window bubble find-dismissal listeners
227 useEffect(() => {
228 const pane = embedded
229 ? (composerElement?.closest<HTMLElement>("[data-side-chat-pane]") ?? null)
230 : null;
231 const target: Pick<HTMLElement, "addEventListener" | "removeEventListener"> | null = embedded
232 ? pane
233 : window;
234 if (!target) return;
235 if (pane) {
236 if (embeddedPanes.size === 0) {
237 window.addEventListener("focusin", onPopupOwnerEvent, true);
238 window.addEventListener("pointerdown", onPopupOwnerEvent, true);
239 }
240 embeddedPanes.add(pane);
241 trackPopupOwner(document.activeElement);
242 }
243 const onKeyDownCapture = (event: KeyboardEvent) =>
244 pane ? handleSideChatShortcut(event, pane) : handleShortcut(event);
245 const onKeyDown = (event: KeyboardEvent) => dismissFind(event);
246 window.addEventListener("keydown", onKeyDownCapture, true);
247 target.addEventListener("keydown", onKeyDown);
248 return () => {
249 window.removeEventListener("keydown", onKeyDownCapture, true);
250 target.removeEventListener("keydown", onKeyDown);
251 if (pane) {
252 embeddedPanes.delete(pane);
253 if (popupOwner === pane) popupOwner = null;
254 if (embeddedPanes.size === 0) {
255 window.removeEventListener("focusin", onPopupOwnerEvent, true);
256 window.removeEventListener("pointerdown", onPopupOwnerEvent, true);
257 }
258 }
259 };
260 }, [composerElement, embedded]);