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

useChatShortcuts.ts

140 lines6.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 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​
25interface ChatShortcutsInput {
26 readonly enabled: boolean;
27 /**
28 * A side chat inside another chat leaves the window to the outer chat. It runs only
29 * composer chords, for keys pressed inside `composerElement`.
30 */
31 readonly embedded?: boolean;
32 readonly composerElement?: HTMLElement | null;
33 readonly keybindings: ResolvedKeybindingsConfig;
34 readonly scriptKeybindings: ResolvedKeybindingsConfig;
35 readonly getShortcutContext: (target: EventTarget | null) => ShortcutMatchContext & {
36 readonly modelPickerOpen: boolean;
37 };
38 readonly threadFindActive: boolean;
39 /** Takes type-to-focus keys and the composer and branch toolbar chords. */
40 readonly composerRef: ComposerHandleRef;
41 readonly branchToolbarRef: { readonly current: BranchToolbarHandle | null };
42 readonly closeThreadFind: () => void;
43 readonly commands: ChatShortcutCommands;
44 /** Handles commands not in `commands`, such as project scripts. */
45 readonly fallback: (command: KeybindingCommand) => ChatShortcutHandler | undefined;
47​
48/**
49 * The chat's window keyboard shortcuts, plus Escape closing thread find.
50 * Listeners attach once; the effect events read the latest input, so handlers
51 * act on the current render without re-registering on every change.
52 */
53export function useChatShortcuts(input: ChatShortcutsInput) {
54 const embedded = input.embedded === true;
55 const composerElement = embedded ? (input.composerElement ?? null) : null;
56 const handleShortcut = useEffectEvent((event: KeyboardEvent) => {
57 const { keybindings } = input;
58 if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {
59 event.stopPropagation();
60 return;
61 }
62 if (input.threadFindActive && event.key === "Escape") return;
63 if (isTerminalCloseConfirmPending() && preventTerminalCloseShortcut(event, keybindings)) {
64 event.stopPropagation();
65 return;
66 }
67 if (!input.enabled || isCommandPaletteOpen() || isInSideChatPane(event.target)) return;
68 const terminalFocusOwner = getTerminalFocusOwner();
69 if (event.defaultPrevented && terminalFocusOwner === null) return;
70 const shortcutContext = input.getShortcutContext(event.target);
71​
72 if (
73 !shortcutContext.terminalFocus &&
74 !shortcutContext.modelPickerOpen &&
75 shouldTypeToFocusComposer(event) &&
76 input.composerRef.current?.insertTextAtEnd(event.key) === true
77 ) {
78 event.preventDefault();
79 event.stopPropagation();
80 return;
81 }
82​
83 const command = resolveChatShortcutCommand(event, keybindings, input.scriptKeybindings, {
84 context: shortcutContext,
85 });
86 if (!command) return;
87 const run =
88 input.commands[command] ??
89 composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command] ??
90 input.fallback(command);
91 if (!run || run({ event, terminalFocusOwner }) === false) return;
92 event.preventDefault();
93 event.stopPropagation();
94 });
95 const dismissFind = useEffectEvent((event: KeyboardEvent) => {
96 if (
97 event.key !== "Escape" ||
98 !input.threadFindActive ||
99 event.defaultPrevented ||
100 event.isComposing ||
101 event.keyCode === 229 ||
102 isCommandPaletteOpen() ||
103 isInSideChatPane(event.target)
104 )
105 return;
106 const context = input.getShortcutContext(event.target);
107 if (context.terminalFocus || context.previewFocus || context.modelPickerOpen) return;
108 event.preventDefault();
109 input.closeThreadFind();
110 });
111 const handleComposerShortcut = useEffectEvent((event: KeyboardEvent) => {
112 if (event.defaultPrevented || isCommandPaletteOpen()) return;
113 const command = resolveChatShortcutCommand(event, input.keybindings, input.scriptKeybindings, {
114 context: input.getShortcutContext(event.target),
115 });
116 const run = command
117 ? composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command]
118 : undefined;
119 if (!run || run({ event, terminalFocusOwner: null }) === false) return;
120 event.preventDefault();
121 event.stopPropagation();
122 });
123 // 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
124 useEffect(() => {
125 if (embedded) {
126 if (composerElement === null) return;
127 const onComposerKeyDown = (event: KeyboardEvent) => handleComposerShortcut(event);
128 composerElement.addEventListener("keydown", onComposerKeyDown, true);
129 return () => composerElement.removeEventListener("keydown", onComposerKeyDown, true);
130 }
131 const onKeyDownCapture = (event: KeyboardEvent) => handleShortcut(event);
132 const onKeyDown = (event: KeyboardEvent) => dismissFind(event);
133 window.addEventListener("keydown", onKeyDownCapture, true);
134 window.addEventListener("keydown", onKeyDown);
135 return () => {
136 window.removeEventListener("keydown", onKeyDownCapture, true);
137 window.removeEventListener("keydown", onKeyDown);
138 };
139 }, [composerElement, embedded]);