Skip to content

Commit 92c1992

Browse files
refactor(web): composer menus, pickers and banners act in handlers
The composer's menus, banners, model picker, attachment strip and draft hero measure from ref callbacks and act in their handlers, and the overlay measurer that owns held composer heights is added here. Effect categories removed: - measurement and positioning moved to ref callbacks (command menu layer, active row scroll, banner overflow, hero fit, model picker sidebar and list fades, resting controls) - banner focus, question auto-advance and stash badge pulse moved to handlers and keyed CSS animation - picker key listeners moved to element scopes and onKeyDownCapture - thumbnail loading moved to use() under Suspense - stale scratch checks read the draft store instead of a mirrored ref - command-key handling reads the render's menu state per keypress - search focus and scroll lock follow the popup's own lifecycle Bugs fixed: - Dismissing a banner and switching threads quickly lost the dismissal. - The active command row was not scrolled into view on first open. - The model picker indicator did not move when providers above the selected row were added, removed or reordered. Kept effects: - Draft hero layout transition: needs pre-paint geometry of a derived layout change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 24e141c commit 92c1992

20 files changed

Lines changed: 814 additions & 418 deletions

‎apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ describe("composer context undo lifetime", () => {
333333
});
334334
}
335335

336-
it("restores a deleted chip and its file bytes on same-draft undo, then releases them on unmount", async () => {
336+
it("restores a deleted chip and its file bytes on same-draft undo", async () => {
337337
await using composer = await mountComposer();
338338
await composer.deleteDraft();
339339
expect(composer.draft()).toEqual({ value: "", files: [] });
@@ -345,14 +345,10 @@ describe("composer context undo lifetime", () => {
345345
expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(composer.initialValue);
346346
expect(composer.draft()).toEqual({ value: composer.initialValue, files: [file] });
347347
expect(composer.draft().files[0]?.file).toBe(file.file);
348-
349-
await composer.deleteDraft();
350-
await composer.unmount();
351-
expect(retained.files.size).toBe(0);
352348
});
353349

354350
it.each(["", "Draft B"])(
355-
"releases deleted payloads and prevents undo into the previous draft when switching to %j",
351+
"drops deleted payloads and prevents undo into the previous draft when switching to %j",
356352
async (destinationValue) => {
357353
await using composer = await mountComposer(destinationValue);
358354
await composer.deleteDraft();
@@ -361,7 +357,8 @@ describe("composer context undo lifetime", () => {
361357
expect(retained.files.get(fileContextReference(file).contextId)?.file).toBe(file.file);
362358

363359
await composer.show("b");
364-
expect(retained.files.size).toBe(0);
360+
expect(composer.retained()).not.toBe(retained);
361+
expect(composer.retained().files.size).toBe(0);
365362
await composer.undo();
366363
expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(destinationValue);
367364
expect(composer.draft()).toEqual({ value: destinationValue, files: [] });

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

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type {
77
} from "@t3tools/contracts";
88
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
99
import { CircleAlertIcon, PaperclipIcon, PlayIcon, XIcon } from "lucide-react";
10-
import { type ComponentProps, useLayoutEffect, useRef } from "react";
10+
import { type ComponentProps, useRef } from "react";
1111

1212
import {
1313
type ComposerFileAttachment,
@@ -79,22 +79,16 @@ function SnapShotAttachmentFrame({
7979
readonly arrival?: boolean | undefined;
8080
readonly animateArrival?: boolean | undefined;
8181
}) {
82-
const frameRef = useRef<HTMLDivElement>(null);
83-
84-
useLayoutEffect(() => {
85-
const frame = frameRef.current;
86-
if (!frame || (!animationId && !arrival)) return;
87-
frame.scrollIntoView({ block: "nearest", inline: "nearest" });
88-
if (!animationId) return;
89-
90-
return scheduleSnapShotAnimationDestination(animationId, () =>
91-
setSnapShotAnimationDestination(animationId, frame, animationSource),
92-
);
93-
}, [animationId, animationSource, arrival]);
94-
9582
return (
9683
<div
97-
ref={frameRef}
84+
ref={(frame) => {
85+
if (!frame || (!animationId && !arrival)) return;
86+
frame.scrollIntoView({ block: "nearest", inline: "nearest" });
87+
if (!animationId) return;
88+
return scheduleSnapShotAnimationDestination(animationId, () =>
89+
setSnapShotAnimationDestination(animationId, frame, animationSource),
90+
);
91+
}}
9892
className={cn(
9993
animateArrival &&
10094
!animationId &&

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

Lines changed: 21 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { InfoIcon } from "lucide-react";
2-
import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
2+
import { useId, useRef, useState, type ReactNode } from "react";
3+
import { flushSync } from "react-dom";
34

45
import { cn } from "~/lib/utils";
56
import { Button } from "../ui/button";
@@ -51,39 +52,25 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
5152
const noticesRef = useRef<HTMLDivElement>(null);
5253
const peekRef = useRef<HTMLButtonElement>(null);
5354
const expandedItemsRef = useRef<HTMLDivElement>(null);
54-
const pendingFocusRef = useRef<"peek" | "notice" | null>(null);
5555
const expandedItemsId = useId();
5656
const [requestedExitingItemId, setExitingItemId] = useState<string | null>(null);
57-
const dismissTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
5857
const exitingItemId =
5958
requestedExitingItemId !== null && items.some((item) => item.id === requestedExitingItemId)
6059
? requestedExitingItemId
6160
: null;
6261

63-
useEffect(() => {
64-
return () => {
65-
if (dismissTimeoutRef.current) {
66-
clearTimeout(dismissTimeoutRef.current);
67-
}
68-
};
69-
}, []);
70-
7162
if (items.length < 2 && stackExpanded) {
7263
setStackExpanded(false);
7364
}
7465

75-
useLayoutEffect(() => {
76-
if (stackExpanded && pendingFocusRef.current === "notice") {
77-
pendingFocusRef.current = null;
78-
const firstControl = expandedItemsRef.current?.querySelector<HTMLElement>(
79-
'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
80-
);
81-
(firstControl ?? expandedItemsRef.current)?.focus({ preventScroll: true });
82-
} else if (!stackExpanded && pendingFocusRef.current === "peek") {
83-
pendingFocusRef.current = null;
84-
peekRef.current?.focus({ preventScroll: true });
85-
}
86-
}, [stackExpanded]);
66+
const expandAndFocusNotice = () => {
67+
flushSync(() => setStackExpanded(true));
68+
const container = expandedItemsRef.current;
69+
const firstControl = container?.querySelector<HTMLElement>(
70+
'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
71+
);
72+
(firstControl ?? container)?.focus({ preventScroll: true });
73+
};
8774

8875
const orderedItems = items.toSorted((a, b) => bannerPriority(a) - bannerPriority(b));
8976
const frontItem = orderedItems[0];
@@ -106,13 +93,9 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
10693
return;
10794
}
10895
setExitingItemId(item.id);
109-
if (dismissTimeoutRef.current) {
110-
clearTimeout(dismissTimeoutRef.current);
111-
}
112-
dismissTimeoutRef.current = setTimeout(() => {
113-
dismissTimeoutRef.current = null;
114-
item.onDismiss?.();
115-
}, DISMISS_TRANSITION_MS);
96+
// A timer, not transitionend: the dismissal must commit even when the stack unmounts
97+
// (thread switch) or a collapsed composer hides it mid-exit, and transitionend never fires then.
98+
setTimeout(() => item.onDismiss?.(), DISMISS_TRANSITION_MS);
11699
};
117100

118101
return (
@@ -126,7 +109,8 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
126109
onPointerEnter={(event) => {
127110
if (event.pointerType === "touch") return;
128111
if (document.activeElement === peekRef.current) {
129-
pendingFocusRef.current = "notice";
112+
expandAndFocusNotice();
113+
return;
130114
}
131115
setStackExpanded(true);
132116
}}
@@ -145,8 +129,8 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
145129
if (event.key !== "Escape" || !stackExpanded) return;
146130
event.preventDefault();
147131
event.stopPropagation();
148-
pendingFocusRef.current = "peek";
149-
setStackExpanded(false);
132+
flushSync(() => setStackExpanded(false));
133+
peekRef.current?.focus({ preventScroll: true });
150134
}}
151135
>
152136
{showCollapsedStackCap && firstStackedItem ? (
@@ -160,8 +144,7 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
160144
tabIndex={stackExpanded ? -1 : 0}
161145
onClick={(event) => {
162146
event.currentTarget.focus({ preventScroll: true });
163-
pendingFocusRef.current = "notice";
164-
setStackExpanded(true);
147+
expandAndFocusNotice();
165148
}}
166149
className={cn(stackExpanded && "pointer-events-none invisible opacity-0")}
167150
/>
@@ -257,12 +240,10 @@ function NoticeText({
257240
readonly className: string;
258241
readonly detailsLabel: string;
259242
}) {
260-
const textRef = useRef<HTMLSpanElement>(null);
261243
const detailsRef = useRef<HTMLButtonElement>(null);
262244
const [showDetails, setShowDetails] = useState(false);
263245

264-
useLayoutEffect(() => {
265-
const text = textRef.current;
246+
const observeOverflow = (text: HTMLSpanElement | null) => {
266247
if (!text) return;
267248
const measure = () => {
268249
// Ignore the space taken by the details button itself so it cannot
@@ -284,11 +265,11 @@ function NoticeText({
284265
stopObserving();
285266
mutations.disconnect();
286267
};
287-
}, []);
268+
};
288269

289270
return (
290271
<span className="contents">
291-
<span ref={textRef} className={className}>
272+
<span ref={observeOverflow} className={className}>
292273
{children}
293274
</span>
294275
{showDetails ? (

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

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {
2121
UserRoundIcon,
2222
type LucideIcon,
2323
} from "lucide-react";
24-
import { memo, useLayoutEffect, useRef } from "react";
24+
import { memo } from "react";
2525

2626
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
2727
import { cn } from "~/lib/utils";
@@ -90,16 +90,6 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
9090
onHighlightedItemChange: (itemId: string | null) => void;
9191
onSelect: (item: ComposerCommandItem) => void;
9292
}) {
93-
const listRef = useRef<HTMLDivElement>(null);
94-
95-
useLayoutEffect(() => {
96-
if (!props.activeItemId || !listRef.current) return;
97-
const el = listRef.current.querySelector<HTMLElement>(
98-
`[data-composer-item-id="${CSS.escape(props.activeItemId)}"]`,
99-
);
100-
el?.scrollIntoView({ block: "nearest" });
101-
}, [props.activeItemId]);
102-
10393
return (
10494
<Command
10595
autoHighlight={false}
@@ -111,7 +101,6 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
111101
}}
112102
>
113103
<ComposerBanner.Surface
114-
ref={listRef}
115104
className="flex min-h-0 w-full flex-col overflow-hidden pb-(--chat-composer-attachment-overlap) **:data-[slot=command-item]:rounded-lg **:data-[slot=scroll-area-scrollbar]:data-[orientation=vertical]:my-4"
116105
data-composer-command-drawer="true"
117106
>
@@ -159,6 +148,10 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
159148
);
160149
});
161150

151+
function scrollActiveRowIntoView(row: HTMLElement | null) {
152+
row?.scrollIntoView({ block: "nearest" });
153+
}
154+
162155
const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
163156
optionId: string;
164157
item: ComposerCommandItem;
@@ -181,6 +174,7 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
181174
aria-selected={props.isActive}
182175
value={props.item.id}
183176
data-composer-item-id={props.item.id}
177+
ref={props.isActive ? scrollActiveRowIntoView : undefined}
184178
active={props.isActive}
185179
onMouseMove={() => {
186180
if (!props.isActive) props.onHighlight(props.item.id);

0 commit comments

Comments
 (0)