The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 17:00 UTC
refactor(web): composer editor stops mirroring props into refs with effects (#25079)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 17:23 UTC
65822d8e17428eb870f62cce16e0f9cb08a2ab33
4 files changed
+90
-101
apps/web/src/components/ComposerPromptEditorTiptap.tsx
+27
-42
@@ -7,6 +7,7 @@ import {
7
Node,
8
wrappingInputRule,
9
type JSONContent,
10
+ type TiptapEditorHTMLElement,
11
} from "@tiptap/core";
12
import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
13
import StarterKit from "@tiptap/starter-kit";
@@ -976,36 +977,15 @@ function ComposerPromptEditorTiptapInner(
977
const expandEditorCursor = (text: string, position: number) =>
978
literalText ? position : expandCollapsedComposerCursor(text, position);
979
979
- const onChangeRef = useRef(onChange);
980
- const onVisibleSelectionChangeRef = useRef(onVisibleSelectionChange);
981
- const onCommandKeyDownRef = useRef(onCommandKeyDown);
982
- const isPathQueryActiveRef = useRef(isPathQueryActive);
983
- const buildFragmentRef = useRef(buildContextClipboardFragment);
984
- const importFragmentRef = useRef(importContextFragment);
980
const latestValueRef = useRef(value);
986
- const editorHolder = useRef<TiptapEditor | null>(null);
987
-
988
- useEffect(() => {
989
- onChangeRef.current = onChange;
990
- }, [onChange]);
991
- useEffect(() => {
992
- onVisibleSelectionChangeRef.current = onVisibleSelectionChange;
993
- }, [onVisibleSelectionChange]);
994
- useEffect(() => {
995
- onCommandKeyDownRef.current = onCommandKeyDown;
996
- }, [onCommandKeyDown]);
997
- useEffect(() => {
998
- isPathQueryActiveRef.current = isPathQueryActive;
999
- }, [isPathQueryActive]);
1000
- useEffect(() => {
1001
- buildFragmentRef.current = buildContextClipboardFragment;
1002
- }, [buildContextClipboardFragment]);
1003
- useEffect(() => {
1004
- importFragmentRef.current = importContextFragment;
1005
- }, [importContextFragment]);
1006
- useLayoutEffect(() => {
1007
- latestValueRef.current = value;
1008
- }, [value]);
981
+ // The editor config is built once, so its handlers reach the current callbacks through here.
982
+ const readCallbacks = useStableCallback(() => ({
983
+ onChange,
984
+ onVisibleSelectionChange,
985
+ onCommandKeyDown,
986
+ isPathQueryActive,
987
+ importContextFragment,
988
+ }));
989
990
// Stable so a skills refresh does not rerun the controlled-value effect.
991
const skillLabelFor = useStableCallback((name: string) => composerSkillMeta(skills, name));
@@ -1074,7 +1054,7 @@ function ComposerPromptEditorTiptapInner(
1054
if (isApplyingControlledUpdateRef.current) return;
1055
if (!snapshotChanged) {
1056
if (didComposerSelectionChangeVisibly(previousSelectionRange, nextSelectionRange)) {
1077
- onVisibleSelectionChangeRef.current?.();
1057
+ readCallbacks().onVisibleSelectionChange?.();
1058
}
1059
return;
1060
}
@@ -1096,7 +1076,13 @@ function ComposerPromptEditorTiptapInner(
1076
[updated.state.selection.$from.nodeBefore, updated.state.selection.$from.nodeAfter].some(
1077
(node) => node?.isInline && node.isAtom && !node.isText && node.type.name !== "hardBreak",
1078
);
1099
- onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, suppressTrigger, contextIds);
1079
+ readCallbacks().onChange(
1080
+ nextValue,
1081
+ nextCursor,
1082
+ nextExpandedCursor,
1083
+ suppressTrigger,
1084
+ contextIds,
1085
+ );
1086
};
1087
1088
const editorAttributes = {
@@ -1301,9 +1287,9 @@ function ComposerPromptEditorTiptapInner(
1287
return true;
1288
}
1289
}
1304
- const handler = onCommandKeyDownRef.current;
1290
+ const handler = readCallbacks().onCommandKeyDown;
1291
if (event.key === "Enter") {
1306
- const instance = editorHolder.current;
1292
+ const instance = (view.dom as TiptapEditorHTMLElement).editor;
1293
const isTaskItem = richText && (instance?.isActive("taskItem") ?? false);
1294
const isListItem = richText && (instance?.isActive("listItem") ?? false);
1295
const handled = handler?.("Enter", event, isTaskItem || isListItem) ?? false;
@@ -1390,7 +1376,7 @@ function ComposerPromptEditorTiptapInner(
1376
);
1377
return true;
1378
}
1393
- const importFragment = importFragmentRef.current;
1379
+ const importFragment = readCallbacks().importContextFragment;
1380
let text =
1381
!literalText && importFragment
1382
? importPastedComposerText(clipboardData, importFragment)
@@ -1412,8 +1398,8 @@ function ComposerPromptEditorTiptapInner(
1398
const lineBefore = $from.parent.textBetween(0, $from.parentOffset, undefined, "\uFFFC");
1399
const literalLength = literalText
1400
? 0
1415
- : pastedPathQueryLength(lineBefore, text, isPathQueryActiveRef.current?.());
1416
- const editorInstance = editorHolder.current;
1401
+ : pastedPathQueryLength(lineBefore, text, readCallbacks().isPathQueryActive?.());
1402
+ const editorInstance = (view.dom as TiptapEditorHTMLElement).editor;
1403
if (editorInstance) {
1404
const $paste = view.state.selection.$from;
1405
const nested = ["listItem", "taskItem", "blockquote"].some((name) =>
@@ -1476,10 +1462,6 @@ function ComposerPromptEditorTiptapInner(
1462
editor?.setEditable(!disabled);
1463
}, [disabled, editor]);
1464
1479
- useEffect(() => {
1480
- editorHolder.current = editor;
1481
- }, [editor]);
1482
-
1465
// Push attributes before layout measurements; Tiptap updates them later in a passive effect.
1466
useLayoutEffect(() => {
1467
if (!editor?.isInitialized) return;
@@ -1539,7 +1521,10 @@ function ComposerPromptEditorTiptapInner(
1521
onCitationDraftSave(replacedValue, serializeEditorDoc(current.state.doc).value);
1522
});
1523
1524
+ // The one place the controlled value reaches the editor. Imperative handlers compare against
1525
+ // the committed value, so it is recorded here even before the editor exists.
1526
useLayoutEffect(() => {
1527
+ latestValueRef.current = value;
1528
if (!editor) return;
1529
const initialSelection = !hasAppliedControlledSelectionRef.current;
1530
hasAppliedControlledSelectionRef.current = true;
@@ -1665,7 +1650,7 @@ function ComposerPromptEditorTiptapInner(
1650
start: snapshotRef.current.expandedCursor,
1651
end: snapshotRef.current.expandedCursor,
1652
};
1668
- onChangeRef.current(
1653
+ readCallbacks().onChange(
1654
snapshotRef.current.value,
1655
boundedCursor,
1656
snapshotRef.current.expandedCursor,
@@ -1756,7 +1741,7 @@ function ComposerPromptEditorTiptapInner(
1741
);
1742
1743
const handleCopyCut = (event: React.ClipboardEvent, cut: boolean) => {
1759
- const build = buildFragmentRef.current;
1744
+ const build = buildContextClipboardFragment;
1745
if (!editor || (cut && !editor.isEditable)) return;
1746
const clipboardData = event.clipboardData;
1747
const { from, to } = editor.state.selection;
apps/web/src/components/chat/ChatComposer.tsx
+48
-40
@@ -295,7 +295,7 @@ import {
295
usePreparingComposerImages,
296
} from "./preparingComposerImages";
297
import { ComposerControlsBar } from "./ComposerControlsBar";
298
-import { useComposerCommandKey } from "./useComposerCommandKey";
298
+import { composerCommandKeyHandler } from "./composerCommandKey";
299
300
function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
301
const armed = Date.now() <= deadline.current;
@@ -1096,7 +1096,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1096
null,
1097
);
1098
const [composerMenuAnchor, setComposerMenuAnchor] = useState<HTMLDivElement | null>(null);
1099
- const hasWrappedPrompt = useComposerMultilinePrompt(composerMenuAnchor);
1099
+ const [hasWrappedPrompt, observeWrappedPrompt] = useComposerMultilinePrompt();
1100
const hasMultilinePrompt = prompt.includes("\n") || hasWrappedPrompt;
1101
const [isTasksDrawerOpen, setIsTasksDrawerOpen] = useState(false);
1102
// A pending question stays expanded: its card moves into the banner dock,
@@ -2234,43 +2234,44 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2234
};
2235
const expandMobileComposerStable = useStableCallback(expandMobileComposer);
2236
2237
- const { onComposerCommandKey } = useComposerCommandKey({
2238
- keybindings,
2239
- sendShortcut: settings.sendShortcut,
2240
- routeKind,
2241
- phase,
2242
- isCompacting,
2243
- followUpBehavior,
2244
- isSoftwareKeyboardOpen,
2245
- planModeUiEnabled,
2246
- isLiteralPendingAnswer,
2247
- pendingUserInputs,
2248
- promptHistoryMessages,
2249
- promptHistoryPositionRef,
2250
- composerDraftTarget,
2251
- promptRef,
2252
- composerImagesRef,
2253
- composerFilesRef,
2254
- composerTerminalContextsRef,
2255
- composerPreviewAnnotations,
2256
- composerReviewComments,
2257
- composerEditorRef,
2258
- composerMenuOpenRef,
2259
- composerMenuItemsRef,
2260
- activeComposerMenuItemRef,
2261
- setComposerDraftPrompt,
2262
- setComposerCursor,
2263
- setComposerTrigger,
2264
- setComposerHighlightedItemId,
2265
- dismissComposerTrigger,
2266
- toggleInteractionMode,
2267
- nudgeComposerMenuHighlight,
2268
- onSelectComposerItem,
2269
- resolveActiveComposerTrigger,
2270
- readComposerSnapshot,
2271
- applyPromptReplacement,
2272
- submitComposer,
2273
- });
2237
+ const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) =>
2238
+ composerCommandKeyHandler({
2239
+ keybindings,
2240
+ sendShortcut: settings.sendShortcut,
2241
+ routeKind,
2242
+ phase,
2243
+ isCompacting,
2244
+ followUpBehavior,
2245
+ isSoftwareKeyboardOpen,
2246
+ planModeUiEnabled,
2247
+ isLiteralPendingAnswer,
2248
+ pendingUserInputs,
2249
+ promptHistoryMessages,
2250
+ promptHistoryPositionRef,
2251
+ composerDraftTarget,
2252
+ promptRef,
2253
+ composerImagesRef,
2254
+ composerFilesRef,
2255
+ composerTerminalContextsRef,
2256
+ composerPreviewAnnotations,
2257
+ composerReviewComments,
2258
+ composerEditorRef,
2259
+ composerMenuOpenRef,
2260
+ composerMenuItemsRef,
2261
+ activeComposerMenuItemRef,
2262
+ setComposerDraftPrompt,
2263
+ setComposerCursor,
2264
+ setComposerTrigger,
2265
+ setComposerHighlightedItemId,
2266
+ dismissComposerTrigger,
2267
+ toggleInteractionMode,
2268
+ nudgeComposerMenuHighlight,
2269
+ onSelectComposerItem,
2270
+ resolveActiveComposerTrigger,
2271
+ readComposerSnapshot,
2272
+ applyPromptReplacement,
2273
+ submitComposer,
2274
+ })(key, event, isTaskItem);
2275
2276
const {
2277
stashQueue,
@@ -3653,7 +3654,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3654
) : null}
3655
3656
<div
3656
- ref={setComposerMenuAnchor}
3657
+ ref={(node) => {
3658
+ setComposerMenuAnchor(node);
3659
+ const stopObserving = observeWrappedPrompt(node);
3660
+ return () => {
3661
+ setComposerMenuAnchor(null);
3662
+ stopObserving?.();
3663
+ };
3664
+ }}
3665
data-chat-composer-body="true"
3666
className={cn(
3667
"relative px-3 pb-2 sm:px-4",
apps/web/src/components/chat/composerCommandKey.ts
renamed
+6
-12
@@ -21,13 +21,14 @@ import { type PreviewAnnotationPayload } from "@t3tools/contracts";
21
import { type ReviewCommentContext } from "../../reviewCommentContext";
22
import { composerTargetKey } from "../../composerDraftStore";
23
import { listContinuationForEnter, listIndentForTab } from "../../composer-list-continuation";
24
-import { type Dispatch, type RefObject, type SetStateAction, useLayoutEffect, useRef } from "react";
24
+import type { Dispatch, RefObject, SetStateAction } from "react";
25
26
/**
27
* The composer's key handling inside the editor: send shortcuts, the slash/mention menu,
28
* prompt history on ArrowUp/ArrowDown, plan-mode toggle, and list continuation.
29
+ * Returns the editor's key handler; it reads the inputs captured by the render that built it.
30
*/
30
-export function useComposerCommandKey(input: {
31
+export function composerCommandKeyHandler(input: {
32
readonly keybindings: ChatComposerProps["keybindings"];
33
readonly sendShortcut: ChatComposerProps["settings"]["sendShortcut"];
34
readonly routeKind: ChatComposerProps["routeKind"];
@@ -116,12 +117,6 @@ export function useComposerCommandKey(input: {
117
applyPromptReplacement,
118
submitComposer,
119
} = input;
119
- // Entries are built on the keypress, not per render: the timeline changes
120
- // on every streamed delta and ArrowUp is rare.
121
- const promptHistoryMessagesRef = useRef(promptHistoryMessages);
122
- useLayoutEffect(() => {
123
- promptHistoryMessagesRef.current = promptHistoryMessages;
124
- });
120
121
// The composer persists across threads. A recall from thread A must not
122
// be treated as active in thread B, where the text-match fallback could
@@ -164,7 +159,8 @@ export function useComposerCommandKey(input: {
159
}
160
const step = stepComposerPromptHistory({
161
direction,
167
- entries: buildComposerPromptHistoryEntries(promptHistoryMessagesRef.current),
162
+ // Built on the keypress, not per render: the timeline changes on every streamed delta.
163
+ entries: buildComposerPromptHistoryEntries(promptHistoryMessages),
164
position,
165
currentPrompt: promptRef.current,
166
});
@@ -258,7 +254,5 @@ export function useComposerCommandKey(input: {
254
return false;
255
};
256
261
- return {
262
- onComposerCommandKey,
263
- };
257
+ return onComposerCommandKey;
258
}
apps/web/src/components/chat/useComposerMultilinePrompt.ts
+9
-7
@@ -1,4 +1,4 @@
1
-import { useLayoutEffect, useState } from "react";
1
+import { useState } from "react";
2
import { observeResize } from "../../lib/observeResize";
3
4
function measureComposerMultilinePrompt(body: HTMLElement): boolean | null {
@@ -19,10 +19,13 @@ function measureComposerMultilinePrompt(body: HTMLElement): boolean | null {
19
return bounds.height > lineHeight + 1 || bounds.width > expandedWidth + 1;
20
}
21
22
-export function useComposerMultilinePrompt(body: HTMLElement | null): boolean {
22
+/** Whether the prompt wraps, and the ref callback that measures it on the composer body. */
23
+export function useComposerMultilinePrompt(): readonly [
24
+ boolean,
25
+ (body: HTMLElement | null) => (() => void) | undefined,
26
+] {
27
const [isMultiline, setIsMultiline] = useState(false);
24
-
25
- useLayoutEffect(() => {
28
+ const observeBody = (body: HTMLElement | null) => {
29
if (!body) return;
30
const measure = () => {
31
const next = measureComposerMultilinePrompt(body);
@@ -37,7 +40,6 @@ export function useComposerMultilinePrompt(body: HTMLElement | null): boolean {
40
stopObserving();
41
mutationObserver.disconnect();
42
};
40
- }, [body]);
41
-
42
- return isMultiline;
43
+ };
44
+ return [isMultiline, observeBody] as const;
45
}