Skip to content

Commit 65822d8

Browse files
refactor(web): composer editor stops mirroring props into refs with effects (pingdotgg#25079)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 4db2ffc commit 65822d8

4 files changed

Lines changed: 90 additions & 101 deletions

File tree

‎apps/web/src/components/ComposerPromptEditorTiptap.tsx‎

Lines changed: 27 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
Node,
88
wrappingInputRule,
99
type JSONContent,
10+
type TiptapEditorHTMLElement,
1011
} from "@tiptap/core";
1112
import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
1213
import StarterKit from "@tiptap/starter-kit";
@@ -976,36 +977,15 @@ function ComposerPromptEditorTiptapInner(
976977
const expandEditorCursor = (text: string, position: number) =>
977978
literalText ? position : expandCollapsedComposerCursor(text, position);
978979

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);
985980
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+
}));
1009989

1010990
// Stable so a skills refresh does not rerun the controlled-value effect.
1011991
const skillLabelFor = useStableCallback((name: string) => composerSkillMeta(skills, name));
@@ -1074,7 +1054,7 @@ function ComposerPromptEditorTiptapInner(
10741054
if (isApplyingControlledUpdateRef.current) return;
10751055
if (!snapshotChanged) {
10761056
if (didComposerSelectionChangeVisibly(previousSelectionRange, nextSelectionRange)) {
1077-
onVisibleSelectionChangeRef.current?.();
1057+
readCallbacks().onVisibleSelectionChange?.();
10781058
}
10791059
return;
10801060
}
@@ -1096,7 +1076,13 @@ function ComposerPromptEditorTiptapInner(
10961076
[updated.state.selection.$from.nodeBefore, updated.state.selection.$from.nodeAfter].some(
10971077
(node) => node?.isInline && node.isAtom && !node.isText && node.type.name !== "hardBreak",
10981078
);
1099-
onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, suppressTrigger, contextIds);
1079+
readCallbacks().onChange(
1080+
nextValue,
1081+
nextCursor,
1082+
nextExpandedCursor,
1083+
suppressTrigger,
1084+
contextIds,
1085+
);
11001086
};
11011087

11021088
const editorAttributes = {
@@ -1301,9 +1287,9 @@ function ComposerPromptEditorTiptapInner(
13011287
return true;
13021288
}
13031289
}
1304-
const handler = onCommandKeyDownRef.current;
1290+
const handler = readCallbacks().onCommandKeyDown;
13051291
if (event.key === "Enter") {
1306-
const instance = editorHolder.current;
1292+
const instance = (view.dom as TiptapEditorHTMLElement).editor;
13071293
const isTaskItem = richText && (instance?.isActive("taskItem") ?? false);
13081294
const isListItem = richText && (instance?.isActive("listItem") ?? false);
13091295
const handled = handler?.("Enter", event, isTaskItem || isListItem) ?? false;
@@ -1390,7 +1376,7 @@ function ComposerPromptEditorTiptapInner(
13901376
);
13911377
return true;
13921378
}
1393-
const importFragment = importFragmentRef.current;
1379+
const importFragment = readCallbacks().importContextFragment;
13941380
let text =
13951381
!literalText && importFragment
13961382
? importPastedComposerText(clipboardData, importFragment)
@@ -1412,8 +1398,8 @@ function ComposerPromptEditorTiptapInner(
14121398
const lineBefore = $from.parent.textBetween(0, $from.parentOffset, undefined, "\uFFFC");
14131399
const literalLength = literalText
14141400
? 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;
14171403
if (editorInstance) {
14181404
const $paste = view.state.selection.$from;
14191405
const nested = ["listItem", "taskItem", "blockquote"].some((name) =>
@@ -1476,10 +1462,6 @@ function ComposerPromptEditorTiptapInner(
14761462
editor?.setEditable(!disabled);
14771463
}, [disabled, editor]);
14781464

1479-
useEffect(() => {
1480-
editorHolder.current = editor;
1481-
}, [editor]);
1482-
14831465
// Push attributes before layout measurements; Tiptap updates them later in a passive effect.
14841466
useLayoutEffect(() => {
14851467
if (!editor?.isInitialized) return;
@@ -1539,7 +1521,10 @@ function ComposerPromptEditorTiptapInner(
15391521
onCitationDraftSave(replacedValue, serializeEditorDoc(current.state.doc).value);
15401522
});
15411523

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.
15421526
useLayoutEffect(() => {
1527+
latestValueRef.current = value;
15431528
if (!editor) return;
15441529
const initialSelection = !hasAppliedControlledSelectionRef.current;
15451530
hasAppliedControlledSelectionRef.current = true;
@@ -1665,7 +1650,7 @@ function ComposerPromptEditorTiptapInner(
16651650
start: snapshotRef.current.expandedCursor,
16661651
end: snapshotRef.current.expandedCursor,
16671652
};
1668-
onChangeRef.current(
1653+
readCallbacks().onChange(
16691654
snapshotRef.current.value,
16701655
boundedCursor,
16711656
snapshotRef.current.expandedCursor,
@@ -1756,7 +1741,7 @@ function ComposerPromptEditorTiptapInner(
17561741
);
17571742

17581743
const handleCopyCut = (event: React.ClipboardEvent, cut: boolean) => {
1759-
const build = buildFragmentRef.current;
1744+
const build = buildContextClipboardFragment;
17601745
if (!editor || (cut && !editor.isEditable)) return;
17611746
const clipboardData = event.clipboardData;
17621747
const { from, to } = editor.state.selection;

‎apps/web/src/components/chat/ChatComposer.tsx‎

Lines changed: 48 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ import {
295295
usePreparingComposerImages,
296296
} from "./preparingComposerImages";
297297
import { ComposerControlsBar } from "./ComposerControlsBar";
298-
import { useComposerCommandKey } from "./useComposerCommandKey";
298+
import { composerCommandKeyHandler } from "./composerCommandKey";
299299

300300
function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
301301
const armed = Date.now() <= deadline.current;
@@ -1096,7 +1096,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
10961096
null,
10971097
);
10981098
const [composerMenuAnchor, setComposerMenuAnchor] = useState<HTMLDivElement | null>(null);
1099-
const hasWrappedPrompt = useComposerMultilinePrompt(composerMenuAnchor);
1099+
const [hasWrappedPrompt, observeWrappedPrompt] = useComposerMultilinePrompt();
11001100
const hasMultilinePrompt = prompt.includes("\n") || hasWrappedPrompt;
11011101
const [isTasksDrawerOpen, setIsTasksDrawerOpen] = useState(false);
11021102
// A pending question stays expanded: its card moves into the banner dock,
@@ -2234,43 +2234,44 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
22342234
};
22352235
const expandMobileComposerStable = useStableCallback(expandMobileComposer);
22362236

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);
22742275

22752276
const {
22762277
stashQueue,
@@ -3653,7 +3654,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
36533654
) : null}
36543655

36553656
<div
3656-
ref={setComposerMenuAnchor}
3657+
ref={(node) => {
3658+
setComposerMenuAnchor(node);
3659+
const stopObserving = observeWrappedPrompt(node);
3660+
return () => {
3661+
setComposerMenuAnchor(null);
3662+
stopObserving?.();
3663+
};
3664+
}}
36573665
data-chat-composer-body="true"
36583666
className={cn(
36593667
"relative px-3 pb-2 sm:px-4",

apps/web/src/components/chat/useComposerCommandKey.ts renamed to apps/web/src/components/chat/composerCommandKey.ts

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,14 @@ import { type PreviewAnnotationPayload } from "@t3tools/contracts";
2121
import { type ReviewCommentContext } from "../../reviewCommentContext";
2222
import { composerTargetKey } from "../../composerDraftStore";
2323
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";
2525

2626
/**
2727
* The composer's key handling inside the editor: send shortcuts, the slash/mention menu,
2828
* 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.
2930
*/
30-
export function useComposerCommandKey(input: {
31+
export function composerCommandKeyHandler(input: {
3132
readonly keybindings: ChatComposerProps["keybindings"];
3233
readonly sendShortcut: ChatComposerProps["settings"]["sendShortcut"];
3334
readonly routeKind: ChatComposerProps["routeKind"];
@@ -116,12 +117,6 @@ export function useComposerCommandKey(input: {
116117
applyPromptReplacement,
117118
submitComposer,
118119
} = 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-
});
125120

126121
// The composer persists across threads. A recall from thread A must not
127122
// be treated as active in thread B, where the text-match fallback could
@@ -164,7 +159,8 @@ export function useComposerCommandKey(input: {
164159
}
165160
const step = stepComposerPromptHistory({
166161
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),
168164
position,
169165
currentPrompt: promptRef.current,
170166
});
@@ -258,7 +254,5 @@ export function useComposerCommandKey(input: {
258254
return false;
259255
};
260256

261-
return {
262-
onComposerCommandKey,
263-
};
257+
return onComposerCommandKey;
264258
}

‎apps/web/src/components/chat/useComposerMultilinePrompt.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useLayoutEffect, useState } from "react";
1+
import { useState } from "react";
22
import { observeResize } from "../../lib/observeResize";
33

44
function measureComposerMultilinePrompt(body: HTMLElement): boolean | null {
@@ -19,10 +19,13 @@ function measureComposerMultilinePrompt(body: HTMLElement): boolean | null {
1919
return bounds.height > lineHeight + 1 || bounds.width > expandedWidth + 1;
2020
}
2121

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+
] {
2327
const [isMultiline, setIsMultiline] = useState(false);
24-
25-
useLayoutEffect(() => {
28+
const observeBody = (body: HTMLElement | null) => {
2629
if (!body) return;
2730
const measure = () => {
2831
const next = measureComposerMultilinePrompt(body);
@@ -37,7 +40,6 @@ export function useComposerMultilinePrompt(body: HTMLElement | null): boolean {
3740
stopObserving();
3841
mutationObserver.disconnect();
3942
};
40-
}, [body]);
41-
42-
return isMultiline;
43+
};
44+
return [isMultiline, observeBody] as const;
4345
}

0 commit comments

Comments
 (0)