Skip to content

Commit cb5f6ac

Browse files
fix(web): composer banners, menus and pickers act in their handlers
Dismissing a composer notice and switching threads within its 220ms exit transition lost the dismissal: the stack is keyed by thread, so the unmount cleared the pending timer and the notice came back. Most composer parts also mirrored state through effects that their handlers or element refs could own. - ComposerBannerStack: the dismissal timer is no longer cancelled on unmount; focus moves in the expand/collapse handlers via flushSync; notice overflow is observed from a ref callback. - useComposerStash: the stash shortcut registers through the shortcut dispatcher (capture phase) while the composer dock is mounted, reading terminal and picker state when the key arrives; the badge pulse is a CSS animation replayed per stash key instead of a 1.2s timer (absorbs the ComposerStashBadge change and its keyframes in index.css). - ComposerStashMenu, ComposerAttachmentStrip, ComposerCommandMenu, DraftHeroProjectHeading, useRestingComposerControlsLayout: listeners, scroll-into-view and measurement live in element ref callbacks. - ProviderModelPicker / ModelPickerContent: the popup's initialFocus focuses search, its ref callback holds the background scroll lock, picker shortcuts run from onKeyDownCapture, and list fades re-measure on content resize. - ComposerImageThumbnail suspends on the thumbnail promise. - DraftHeroHeadline compares the draft session in the store instead of a mirrored ref; composerContextUndo drops its clear-on-switch effect (the old maps are unreachable). Effects: 19 -> 0 across the touched files; ChatComposer unchanged at 26. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3de45c6 commit cb5f6ac

16 files changed

Lines changed: 351 additions & 396 deletions

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

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2277,34 +2277,34 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
22772277
stashQueue,
22782278
isStashMenuOpen,
22792279
setIsStashMenuOpen,
2280-
stashPulse,
2280+
stashPulseKey,
2281+
stashShortcutScopeRef,
22812282
restoreStashEntryStable,
22822283
deleteStashEntryStable,
22832284
toggleStashMenuStable,
22842285
} = useComposerStash({
22852286
environmentId,
22862287
composerDraftTarget,
2287-
promptRef,
2288-
composerImagesRef,
2289-
composerFilesRef,
2290-
composerTerminalContextsRef,
2291-
keybindings,
2292-
terminalOpen,
2288+
readPrompt: () => promptRef.current,
2289+
readAttachmentDraft: () => ({
2290+
images: composerImagesRef.current,
2291+
files: composerFilesRef.current,
2292+
}),
2293+
readTerminalContexts: () => composerTerminalContextsRef.current,
2294+
routeThreadRef,
22932295
projectSelectionRequired,
2294-
isRevertingCheckpoint,
22952296
pendingUserInputs,
22962297
activePendingProgress,
22972298
prompt,
22982299
composerMenuOpen,
2299-
isComposerModelPickerOpen,
23002300
isComposerCollapsedMobile,
23012301
composerPreviewAnnotations,
23022302
composerReviewComments,
23032303
composerThreadContexts,
2304-
attachmentTargetKeyRef,
2305-
composerDraftTargetKeyRef,
2304+
attachmentTargetKey,
2305+
isComposerDraftTargetOpen: (key) => composerDraftTargetKeyRef.current === key,
23062306
composerEditorRef,
2307-
isRevertingCheckpointRef,
2307+
isRevertingCheckpoint: () => isRevertingCheckpointRef.current,
23082308
pendingThreadImportsRef,
23092309
setComposerCursor,
23102310
setComposerTrigger,
@@ -3478,7 +3478,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
34783478
restingControlsHost,
34793479
)
34803480
: null}
3481-
<ComposerBanner.Dock>
3481+
<ComposerBanner.Dock ref={stashShortcutScopeRef}>
34823482
<ComposerBanner.Column>
34833483
<ComposerBannerStack
34843484
key={activeThreadId}
@@ -3578,8 +3578,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
35783578
<ComposerStashBadge
35793579
count={stashQueue.length}
35803580
menuOpen={isStashMenuOpen}
3581-
pulseKey={stashPulse.key}
3582-
pulsing={stashPulse.active}
3581+
pulseKey={stashPulseKey}
35833582
onToggleMenu={toggleStashMenuStable}
35843583
/>
35853584
</ComposerBanner.Dock>

‎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 &&
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { InfoIcon } from "lucide-react";
2+
import { expect, it, vi } from "vite-plus/test";
3+
import { userEvent } from "vite-plus/test/browser";
4+
5+
import { render } from "../../../test/render";
6+
import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack";
7+
8+
it("commits a dismissal when the thread switches during the exit transition", async () => {
9+
const onDismiss = vi.fn();
10+
const item: ComposerBannerStackItem = {
11+
id: "notice",
12+
variant: "info",
13+
icon: <InfoIcon />,
14+
title: "Thread A notice",
15+
dismissLabel: "Dismiss notice",
16+
onDismiss,
17+
};
18+
await using screen = await render(<ComposerBannerStack key="thread-a" items={[item]} />);
19+
20+
await userEvent.click(screen.getByRole("button", { name: "Dismiss notice" }));
21+
// The composer keys the stack by thread, so switching threads remounts it mid-exit.
22+
await screen.rerender(<ComposerBannerStack key="thread-b" items={[]} />);
23+
24+
await vi.waitFor(() => expect(onDismiss).toHaveBeenCalledTimes(1));
25+
});

‎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);
Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,24 @@
1-
import { memo, useEffect, useState, type ReactNode } from "react";
1+
import { memo, Suspense, use, type ReactNode } from "react";
22

33
import {
44
createComposerImageThumbnail,
55
readComposerImageThumbnail,
66
} from "../../lib/imageCompression";
77

8-
export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({
8+
export const ComposerImageThumbnail = memo(function ComposerImageThumbnail(props: {
9+
file: File;
10+
alt: string;
11+
className: string;
12+
fallback: ReactNode;
13+
}) {
14+
return (
15+
<Suspense fallback={props.fallback}>
16+
<ThumbnailImage {...props} />
17+
</Suspense>
18+
);
19+
});
20+
21+
function ThumbnailImage({
922
file,
1023
alt,
1124
className,
@@ -16,16 +29,8 @@ export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({
1629
className: string;
1730
fallback: ReactNode;
1831
}) {
19-
const [preview, setPreview] = useState<{ file: File; src: string | null } | null>(null);
20-
useEffect(() => {
21-
let active = true;
22-
void createComposerImageThumbnail(file).then((src) => {
23-
if (active) setPreview({ file, src });
24-
});
25-
return () => {
26-
active = false;
27-
};
28-
}, [file]);
29-
const src = preview?.file === file ? preview.src : (readComposerImageThumbnail(file) ?? null);
32+
// A settled thumbnail paints synchronously instead of suspending for a tick.
33+
const settled = readComposerImageThumbnail(file);
34+
const src = settled === undefined ? use(createComposerImageThumbnail(file)) : settled;
3035
return src ? <img src={src} alt={alt} className={className} /> : fallback;
31-
});
36+
}

0 commit comments

Comments
 (0)