The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { ChatComposerProps } from "./ChatComposer"; |
| 2 | import { type ComposerCommandItem } from "./ComposerCommandMenu"; |
| 3 | import { |
| 4 | type ComposerDispatchMode, |
| 5 | resolveComposerDispatchMode, |
| 6 | } from "@t3tools/client-runtime/state/composer-dispatch"; |
| 7 | import { type ComposerPromptEditorHandle } from "../ComposerPromptEditorTiptap"; |
| 8 | import { |
| 9 | type ComposerPromptHistoryMentions, |
| 10 | type ComposerPromptHistoryPosition, |
| 11 | buildComposerPromptHistoryEntries, |
| 12 | stepComposerPromptHistory, |
| 13 | } from "./composerPromptHistory"; |
| 14 | import { |
| 15 | type ComposerSubmissionIntent, |
| 16 | type ComposerTrigger, |
| 17 | collapseExpandedComposerCursor, |
| 18 | composerSubmissionIntentForKey, |
| 19 | } from "../../composer-logic"; |
| 20 | import { type PendingUserInput } from "../../session-logic"; |
| 21 | import { |
| 22 | type EnvironmentContextRecord, |
| 23 | type PreviewAnnotationPayload, |
| 24 | type ThreadContextRecord, |
| 25 | } from "@t3tools/contracts"; |
| 26 | import { type ReviewCommentContext } from "../../reviewCommentContext"; |
| 27 | import { composerTargetKey } from "../../composerDraftStore"; |
| 28 | import { |
| 29 | type ComposerListEdit, |
| 30 | listContinuationForEnter, |
| 31 | listIndentForTab, |
| 32 | listOutdentForTab, |
| 33 | } from "../../composer-list-continuation"; |
| 34 | import type { Dispatch, RefObject, SetStateAction } from "react"; |
| 35 | |
| 36 | /** |
| 37 | * The composer's key handling inside the editor: send shortcuts, the slash/mention menu, |
| 38 | * prompt history on ArrowUp/ArrowDown, plan-mode toggle, prompt suggestions on Tab, and list continuation. |
| 39 | * Returns the editor's key handler; it reads the inputs captured by the render that built it. |
| 40 | */ |
| 41 | export function composerCommandKeyHandler(input: { |
| 42 | readonly keybindings: ChatComposerProps["keybindings"]; |
| 43 | readonly getShortcutContext: ChatComposerProps["getShortcutContext"]; |
| 44 | readonly sendShortcut: ChatComposerProps["settings"]["sendShortcut"]; |
| 45 | readonly routeKind: ChatComposerProps["routeKind"]; |
| 46 | readonly phase: ChatComposerProps["phase"]; |
| 47 | readonly canSteer: boolean; |
| 48 | readonly followUpBehavior: ChatComposerProps["settings"]["followUpBehavior"]; |
| 49 | readonly isSoftwareKeyboardOpen: boolean; |
| 50 | readonly isLiteralPendingAnswer: boolean; |
| 51 | readonly pendingUserInputs: ReadonlyArray<PendingUserInput>; |
| 52 | readonly promptHistoryEntries: ChatComposerProps["promptHistoryEntries"]; |
| 53 | readonly promptHistoryPositionRef: RefObject<{ |
| 54 | targetKey: string; |
| 55 | position: ComposerPromptHistoryPosition; |
| 56 | } | null>; |
| 57 | readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"]; |
| 58 | readonly promptRef: ChatComposerProps["promptRef"]; |
| 59 | readonly composerImagesRef: ChatComposerProps["composerImagesRef"]; |
| 60 | readonly composerFilesRef: ChatComposerProps["composerFilesRef"]; |
| 61 | readonly composerTerminalContextsRef: ChatComposerProps["composerTerminalContextsRef"]; |
| 62 | readonly composerPreviewAnnotations: ReadonlyArray<PreviewAnnotationPayload>; |
| 63 | readonly composerReviewComments: ReadonlyArray<ReviewCommentContext>; |
| 64 | readonly composerEditorRef: RefObject<ComposerPromptEditorHandle | null>; |
| 65 | readonly composerMenuItemsRef: RefObject<ComposerCommandItem[]>; |
| 66 | readonly activeComposerMenuItemRef: RefObject<ComposerCommandItem | null>; |
| 67 | readonly setComposerDraftPrompt: ( |
| 68 | target: ChatComposerProps["composerDraftTarget"], |
| 69 | prompt: string, |
| 70 | ) => void; |
| 71 | readonly setComposerDraftThreadContexts: ( |
| 72 | target: ChatComposerProps["composerDraftTarget"], |
| 73 | records: ReadonlyArray<ThreadContextRecord>, |
| 74 | ) => void; |
| 75 | readonly setComposerDraftEnvironmentContexts: ( |
| 76 | target: ChatComposerProps["composerDraftTarget"], |
| 77 | records: ReadonlyArray<EnvironmentContextRecord>, |
| 78 | ) => void; |
| 79 | readonly setComposerCursor: Dispatch<SetStateAction<number>>; |
| 80 | readonly setComposerTrigger: (trigger: ComposerTrigger | null) => void; |
| 81 | readonly setComposerHighlightedItemId: Dispatch<SetStateAction<string | null>>; |
| 82 | readonly dismissComposerTrigger: (trigger: ComposerTrigger | null) => void; |
| 83 | readonly nudgeComposerMenuHighlight: (key: "ArrowDown" | "ArrowUp") => void; |
| 84 | readonly onSelectComposerItem: (item: ComposerCommandItem) => void; |
| 85 | readonly resolveActiveComposerTrigger: () => { trigger: ComposerTrigger | null }; |
| 86 | readonly readComposerSnapshot: () => { value: string }; |
| 87 | readonly applyPromptReplacement: ( |
| 88 | rangeStart: number, |
| 89 | rangeEnd: number, |
| 90 | replacement: string, |
| 91 | options?: { expandedCursorAfterReplace?: number }, |
| 92 | ) => boolean; |
| 93 | readonly submitComposer: ( |
| 94 | event: undefined, |
| 95 | dispatchMode: ComposerDispatchMode, |
| 96 | submissionIntent: ComposerSubmissionIntent, |
| 97 | ) => void; |
| 98 | /** Predicted next prompt that Tab fills into an empty composer; Escape dismisses it. */ |
| 99 | readonly promptSuggestion: string | null; |
| 100 | readonly dismissPromptSuggestion: () => void; |
| 101 | }) { |
| 102 | const { |
| 103 | keybindings, |
| 104 | getShortcutContext, |
| 105 | sendShortcut, |
| 106 | routeKind, |
| 107 | phase, |
| 108 | canSteer, |
| 109 | followUpBehavior, |
| 110 | isSoftwareKeyboardOpen, |
| 111 | isLiteralPendingAnswer, |
| 112 | pendingUserInputs, |
| 113 | promptHistoryEntries, |
| 114 | promptHistoryPositionRef, |
| 115 | composerDraftTarget, |
| 116 | promptRef, |
| 117 | composerImagesRef, |
| 118 | composerFilesRef, |
| 119 | composerTerminalContextsRef, |
| 120 | composerPreviewAnnotations, |
| 121 | composerReviewComments, |
| 122 | composerEditorRef, |
| 123 | composerMenuItemsRef, |
| 124 | activeComposerMenuItemRef, |
| 125 | setComposerDraftPrompt, |
| 126 | setComposerDraftThreadContexts, |
| 127 | setComposerDraftEnvironmentContexts, |
| 128 | setComposerCursor, |
| 129 | setComposerTrigger, |
| 130 | setComposerHighlightedItemId, |
| 131 | dismissComposerTrigger, |
| 132 | nudgeComposerMenuHighlight, |
| 133 | onSelectComposerItem, |
| 134 | resolveActiveComposerTrigger, |
| 135 | readComposerSnapshot, |
| 136 | applyPromptReplacement, |
| 137 | submitComposer, |
| 138 | promptSuggestion, |
| 139 | dismissPromptSuggestion, |
| 140 | } = input; |
| 141 | |
| 142 | // The composer persists across threads. A recall from thread A must not |
| 143 | // be treated as active in thread B, where the text-match fallback could |
| 144 | // otherwise turn B's own draft into a browsing position. |
| 145 | const promptHistoryTargetKey = composerTargetKey(composerDraftTarget); |
| 146 | |
| 147 | const replacePromptFromHistory = ( |
| 148 | nextPrompt: string, |
| 149 | mentions: ComposerPromptHistoryMentions, |
| 150 | ) => { |
| 151 | promptRef.current = nextPrompt; |
| 152 | setComposerDraftPrompt(composerDraftTarget, nextPrompt); |
| 153 | setComposerDraftThreadContexts(composerDraftTarget, mentions.threadContexts); |
| 154 | setComposerDraftEnvironmentContexts(composerDraftTarget, mentions.environmentContexts); |
| 155 | setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); |
| 156 | setComposerTrigger(null); |
| 157 | setComposerHighlightedItemId(null); |
| 158 | }; |
| 159 | |
| 160 | const navigatePromptHistory = ( |
| 161 | direction: "backward" | "forward", |
| 162 | event: KeyboardEvent, |
| 163 | ): boolean => { |
| 164 | if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) { |
| 165 | return false; |
| 166 | } |
| 167 | if (pendingUserInputs.length > 0) return false; |
| 168 | if ( |
| 169 | composerImagesRef.current.length > 0 || |
| 170 | composerFilesRef.current.length > 0 || |
| 171 | composerTerminalContextsRef.current.length > 0 || |
| 172 | composerPreviewAnnotations.length > 0 || |
| 173 | composerReviewComments.length > 0 |
| 174 | ) { |
| 175 | return false; |
| 176 | } |
| 177 | const recalled = promptHistoryPositionRef.current; |
| 178 | const position = recalled?.targetKey === promptHistoryTargetKey ? recalled.position : null; |
| 179 | if (position === null && promptRef.current.length > 0) { |
| 180 | return false; |
| 181 | } |
| 182 | const editor = composerEditorRef.current; |
| 183 | if (!editor?.isCaretOnVisualEdge(direction === "backward" ? "start" : "end")) { |
| 184 | return false; |
| 185 | } |
| 186 | const step = stepComposerPromptHistory({ |
| 187 | direction, |
| 188 | // Built on the keypress, not per render: the timeline changes on every streamed delta. |
| 189 | entries: buildComposerPromptHistoryEntries( |
| 190 | promptHistoryEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])), |
| 191 | ), |
| 192 | position, |
| 193 | currentPrompt: promptRef.current, |
| 194 | }); |
| 195 | if (!step) return false; |
| 196 | promptHistoryPositionRef.current = step.position |
| 197 | ? { targetKey: promptHistoryTargetKey, position: step.position } |
| 198 | : null; |
| 199 | replacePromptFromHistory(step.prompt, step.mentions); |
| 200 | return true; |
| 201 | }; |
| 202 | |
| 203 | const applyListEdit = ( |
| 204 | event: KeyboardEvent, |
| 205 | listEdit: (value: string, start: number, end: number) => ComposerListEdit | null, |
| 206 | ): boolean => { |
| 207 | if (isLiteralPendingAnswer || event.isComposing) return false; |
| 208 | const selection = composerEditorRef.current?.readSelectionRange(); |
| 209 | const snapshot = readComposerSnapshot(); |
| 210 | if (!selection || selection.start !== selection.end || snapshot.value !== promptRef.current) { |
| 211 | return false; |
| 212 | } |
| 213 | const edit = listEdit(snapshot.value, selection.start, selection.end); |
| 214 | return ( |
| 215 | edit !== null && |
| 216 | applyPromptReplacement(edit.start, edit.end, edit.replacement, { |
| 217 | expandedCursorAfterReplace: edit.cursorAfter, |
| 218 | }) |
| 219 | ); |
| 220 | }; |
| 221 | |
| 222 | const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem = false) => { |
| 223 | const submissionIntent = composerSubmissionIntentForKey({ |
| 224 | event, |
| 225 | keybindings, |
| 226 | context: getShortcutContext(event.target), |
| 227 | isSoftwareKeyboardOpen, |
| 228 | isDraftThread: routeKind === "draft", |
| 229 | isRunning: phase === "running" || phase === "connecting", |
| 230 | sendShortcut, |
| 231 | prompt: promptRef.current, |
| 232 | }); |
| 233 | if (key === "Tab" && event.shiftKey && submissionIntent === null) { |
| 234 | return applyListEdit(event, listOutdentForTab); |
| 235 | } |
| 236 | const { trigger } = resolveActiveComposerTrigger(); |
| 237 | const menuIsActive = !isLiteralPendingAnswer && trigger !== null; |
| 238 | if (key === "Escape") { |
| 239 | if (event.isComposing || event.keyCode === 229) return false; |
| 240 | if (!menuIsActive && promptSuggestion !== null && promptRef.current.length === 0) { |
| 241 | dismissPromptSuggestion(); |
| 242 | return true; |
| 243 | } |
| 244 | if (!menuIsActive) return false; |
| 245 | dismissComposerTrigger(trigger); |
| 246 | return true; |
| 247 | } |
| 248 | if ( |
| 249 | menuIsActive && |
| 250 | !event.shiftKey && |
| 251 | (submissionIntent === null || submissionIntent === "foreground") |
| 252 | ) { |
| 253 | const currentItems = composerMenuItemsRef.current; |
| 254 | const selectedItem = activeComposerMenuItemRef.current ?? currentItems[0]; |
| 255 | if (key === "ArrowDown" && currentItems.length > 0) { |
| 256 | nudgeComposerMenuHighlight("ArrowDown"); |
| 257 | return true; |
| 258 | } |
| 259 | if (key === "ArrowUp" && currentItems.length > 0) { |
| 260 | nudgeComposerMenuHighlight("ArrowUp"); |
| 261 | return true; |
| 262 | } |
| 263 | if ((key === "Enter" || key === "Tab") && selectedItem) { |
| 264 | onSelectComposerItem(selectedItem); |
| 265 | return true; |
| 266 | } |
| 267 | } |
| 268 | if ( |
| 269 | key === "Tab" && |
| 270 | promptSuggestion !== null && |
| 271 | promptRef.current.length === 0 && |
| 272 | !menuIsActive && |
| 273 | !event.shiftKey && |
| 274 | !event.altKey && |
| 275 | !event.metaKey && |
| 276 | !event.ctrlKey && |
| 277 | !event.isComposing && |
| 278 | event.keyCode !== 229 |
| 279 | ) { |
| 280 | // The typing guard must see this draft, so an approval that lands next is not answered with it. |
| 281 | return applyPromptReplacement(0, 0, promptSuggestion); |
| 282 | } |
| 283 | if ((key === "ArrowUp" || key === "ArrowDown") && submissionIntent === null) { |
| 284 | return navigatePromptHistory(key === "ArrowUp" ? "backward" : "forward", event); |
| 285 | } |
| 286 | if (submissionIntent) { |
| 287 | submitComposer( |
| 288 | undefined, |
| 289 | resolveComposerDispatchMode({ |
| 290 | running: phase === "running" || phase === "connecting", |
| 291 | alternateModifier: submissionIntent === "alternate", |
| 292 | activeTurnDefault: followUpBehavior, |
| 293 | canSteer, |
| 294 | }), |
| 295 | submissionIntent, |
| 296 | ); |
| 297 | return true; |
| 298 | } |
| 299 | if (key === "Enter" && isTaskItem) return false; |
| 300 | if (key === "Enter" || (key === "Tab" && !event.shiftKey)) { |
| 301 | return applyListEdit(event, key === "Enter" ? listContinuationForEnter : listIndentForTab); |
| 302 | } |
| 303 | return false; |
| 304 | }; |
| 305 | |
| 306 | return onComposerCommandKey; |
| 307 | } |