Skip to content

Commit f279070

Browse files
fix(web): Escape and copy work in chat media and markdown widgets, which attach through ref callbacks (pingdotgg#25246)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent d487078 commit f279070

17 files changed

Lines changed: 536 additions & 387 deletions

‎apps/web/src/appInit.tsx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1+
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
12
import type { ClientSettings } from "@t3tools/contracts/settings";
23
import { createBrowserHistory, createHashHistory } from "@tanstack/react-router";
34

45
import { applyAppearanceContrast } from "./appearanceContrast";
56
import { applyAppearanceFontVariables } from "./appearanceFonts";
7+
import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
68
import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
79
import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
810
import { resolveServerBackedAppDisplayName } from "./branding.logic";
911
import { isElectron } from "./env";
12+
import { useComposerDraftStore } from "./composerDraftStore";
1013
import { getClientSettings, subscribeClientSettings } from "./hooks/useSettings";
1114
import {
1215
syncDocumentElectronPlatformClasses,
@@ -16,6 +19,7 @@ import { prepareProviderAuthDelivery } from "./providerAuthDelivery";
1619
import { getRouter, type AppRouter } from "./router";
1720
import { appAtomRegistry } from "./rpc/atomRegistry";
1821
import { primaryServerConfigAtom } from "./state/server";
22+
import { resolveThreadRouteTarget } from "./threadRoutes";
1923

2024
/** Writes appearance settings onto the document, touching only the groups that changed. */
2125
function startClientAppearance(): void {
@@ -84,6 +88,24 @@ function startDocumentTitle(): void {
8488
);
8589
}
8690

91+
/** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
92+
function startThreadOverlayRetention(router: AppRouter): void {
93+
router.subscribe("onResolved", () => {
94+
const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
95+
const draftSession =
96+
target?.kind === "draft"
97+
? useComposerDraftStore.getState().getDraftSession(target.draftId)
98+
: null;
99+
const threadRef =
100+
target?.kind === "server"
101+
? target.threadRef
102+
: draftSession
103+
? scopeThreadRef(draftSession.environmentId, draftSession.threadId)
104+
: null;
105+
retainThreadOverlaysForThread(threadRef ? scopedThreadKey(threadRef) : null);
106+
});
107+
}
108+
87109
/**
88110
* Starts every app-lifetime service once, before the first render, and returns the router.
89111
* They run for the life of the page, so their disposers are dropped here.
@@ -103,6 +125,7 @@ export function startAppServices(): AppRouter {
103125
startClientAppearance();
104126
startDocumentTitle();
105127
startAgentOpenedPreviews();
128+
startThreadOverlayRetention(router);
106129

107130
return router;
108131
}

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

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import type {
77
} from "@t3tools/contracts";
88
import { useAtomValue } from "@effect/atom-react";
99
import { Atom } from "effect/reactivity";
10-
import { useEffect } from "react";
1110

1211
import { appAtomRegistry } from "~/rpc/atomRegistry";
1312
import { useRightPanelStore } from "~/rightPanelStore";
@@ -25,15 +24,26 @@ import {
2524
import { Button } from "../ui/button";
2625
import { Dialog } from "../ui/dialog";
2726
import { WizardPopup } from "../ui/wizard";
28-
29-
// Atoms isolate overlay renders. Thread keys prevent overlays following thread switches.
27+
import { registerThreadOverlay } from "./threadOverlayRetention";
28+
29+
/**
30+
* Open state for overlays the chat view hosts. It lives in atoms rather than
31+
* ChatView state so opening or closing one renders only its host, not the
32+
* whole chat chrome. Each entry carries the thread it was opened for; a host
33+
* shows only its own thread's entry, and leaving that thread's route drops it.
34+
*/
3035
type ThreadOverlayAtom<T> = Atom.Writable<{ readonly threadKey: string; readonly value: T } | null>;
3136

3237
function makeThreadOverlayAtom<T>(label: string): ThreadOverlayAtom<T> {
33-
return Atom.make<{ readonly threadKey: string; readonly value: T } | null>(null).pipe(
38+
const atom = Atom.make<{ readonly threadKey: string; readonly value: T } | null>(null).pipe(
3439
Atom.keepAlive,
3540
Atom.withLabel(`chat:${label}`),
3641
);
42+
registerThreadOverlay((threadKey) => {
43+
const entry = appAtomRegistry.get(atom);
44+
if (entry !== null && entry.threadKey !== threadKey) closeThreadOverlay(atom);
45+
});
46+
return atom;
3747
}
3848

3949
function closeThreadOverlay<T>(atom: ThreadOverlayAtom<T>): void {
@@ -42,12 +52,6 @@ function closeThreadOverlay<T>(atom: ThreadOverlayAtom<T>): void {
4252

4353
function useThreadOverlay<T>(atom: ThreadOverlayAtom<T>, threadKey: string | null): T | null {
4454
const entry = useAtomValue(atom);
45-
useEffect(
46-
() => () => {
47-
if (appAtomRegistry.get(atom)?.threadKey === threadKey) closeThreadOverlay(atom);
48-
},
49-
[atom, threadKey],
50-
);
5155
return threadKey !== null && entry?.threadKey === threadKey ? entry.value : null;
5256
}
5357

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import type { SnapShotSource } from "@t3tools/contracts";
2+
import { describe, expect, it, vi } from "vite-plus/test";
3+
import { userEvent } from "vite-plus/test/browser";
4+
5+
import "~/index.css";
6+
import { render } from "../../../test/render";
7+
import { ExpandedImageDialog } from "./ExpandedImageDialog";
8+
9+
const PIXEL =
10+
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
11+
12+
const snapShotSource: SnapShotSource = {
13+
kind: "snap-shot",
14+
capturedAt: "2026-01-01T00:00:00.000Z",
15+
appName: "Finder",
16+
windowTitle: "Downloads",
17+
};
18+
19+
describe("ExpandedImageDialog", () => {
20+
it("Escape closes a popup opened inside the dialog before the dialog", async () => {
21+
const onClose = vi.fn();
22+
await using screen = await render(
23+
<ExpandedImageDialog
24+
preview={{ images: [{ src: PIXEL, name: "shot.png", source: snapShotSource }], index: 0 }}
25+
onClose={onClose}
26+
/>,
27+
// The dialog renders no links and reads no route.
28+
{ router: false },
29+
);
30+
31+
await userEvent.click(screen.getByRole("button", { name: "No accessibility data" }));
32+
await expect.element(screen.getByText("Accessibility data")).toBeVisible();
33+
34+
await userEvent.keyboard("{Escape}");
35+
await expect.element(screen.getByText("Accessibility data")).not.toBeInTheDocument();
36+
expect(onClose).not.toHaveBeenCalled();
37+
38+
// Focus returns to the popup's trigger and opens its tooltip; leave it for a plain control.
39+
(screen.getByRole("button", { name: "Close image preview" }).element() as HTMLElement).focus();
40+
await userEvent.keyboard("{Escape}");
41+
await vi.waitFor(() => expect(onClose).toHaveBeenCalledOnce());
42+
});
43+
});

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

Lines changed: 47 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { memo, useEffect, useRef, useState, type ReactNode, type KeyboardEvent } from "react";
1+
import { memo, useRef, useState, type ReactNode, type KeyboardEvent } from "react";
2+
import { flushSync } from "react-dom";
23
import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "lucide-react";
34
import { Image as ImageGlyph, Text as TextGlyph } from "lucide";
45
import { Button } from "../ui/button";
@@ -23,6 +24,7 @@ import { useAtomValue } from "@effect/atom-react";
2324
import { Atom } from "effect/reactivity";
2425
import { appAtomRegistry } from "~/rpc/atomRegistry";
2526
import { expandedImageKey } from "./ExpandedImagePreview";
27+
import { registerThreadOverlay } from "./threadOverlayRetention";
2628

2729
interface ExpandedImageDialogProps {
2830
preview: ExpandedImagePreview;
@@ -76,6 +78,13 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
7678
const [returnFocusTarget] = useState(() =>
7779
document.activeElement instanceof HTMLElement ? document.activeElement : null,
7880
);
81+
// The host unmounts the dialog outright, so Base UI never runs finalFocus. Without
82+
// this, focus stays on the removed dialog, and the composer that owned the opener
83+
// reads that as a blur and rests.
84+
const close = () => {
85+
flushSync(onClose);
86+
if (returnFocusTarget?.isConnected) returnFocusTarget.focus({ preventScroll: true });
87+
};
7988
const closeButtonRef = useRef<HTMLButtonElement>(null);
8089
const imageCount = preview.images.length;
8190
const index =
@@ -92,7 +101,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
92101
...source,
93102
onOpenFile: () => {
94103
openFile();
95-
onClose();
104+
close();
96105
},
97106
}
98107
: source;
@@ -101,18 +110,6 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
101110
setImageOffset((current) => current + direction);
102111
};
103112

104-
// Restore opener focus to prevent composer collapse.
105-
const openerRef = useRef<Element | null>(null);
106-
useEffect(() => {
107-
openerRef.current = document.activeElement;
108-
return () => {
109-
const opener = openerRef.current;
110-
if (opener instanceof HTMLElement && opener.isConnected) {
111-
opener.focus({ preventScroll: true });
112-
}
113-
};
114-
}, []);
115-
116113
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
117114
if (event.defaultPrevented || isContextMenuOpen() || event.target instanceof HTMLVideoElement)
118115
return;
@@ -134,17 +131,6 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
134131
navigateImage(1);
135132
};
136133

137-
useEffect(() => {
138-
const onEscape = (event: globalThis.KeyboardEvent) => {
139-
if (event.key !== "Escape" || isContextMenuOpen()) return;
140-
event.preventDefault();
141-
event.stopPropagation();
142-
onClose();
143-
};
144-
window.addEventListener("keydown", onEscape, { capture: true });
145-
return () => window.removeEventListener("keydown", onEscape, { capture: true });
146-
}, [onClose]);
147-
148134
if (!item) return null;
149135
const mediaLabel = item.type === "video" ? "video" : "image";
150136
const openOriginalLink =
@@ -163,8 +149,14 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
163149
return (
164150
<Dialog
165151
open
166-
onOpenChange={(open) => {
167-
if (!open) onClose();
152+
onOpenChange={(open, eventDetails) => {
153+
if (open) return;
154+
// Escape belongs to an open context menu first.
155+
if (eventDetails.reason === "escape-key" && isContextMenuOpen()) {
156+
eventDetails.cancel();
157+
return;
158+
}
159+
close();
168160
}}
169161
>
170162
<DialogPopup
@@ -177,7 +169,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
177169
initialFocus={closeButtonRef}
178170
finalFocus={() => returnFocusTarget}
179171
onClick={(event) => {
180-
if (event.target === event.currentTarget) onClose();
172+
if (event.target === event.currentTarget) close();
181173
}}
182174
>
183175
<DialogTitle className="sr-only">Expanded {mediaLabel} preview</DialogTitle>
@@ -187,7 +179,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
187179
size="icon-sm"
188180
variant="media-close"
189181
className="absolute right-0 top-0 z-20"
190-
onClick={onClose}
182+
onClick={close}
191183
aria-label={`Close ${mediaLabel} preview`}
192184
>
193185
<XIcon />
@@ -286,35 +278,45 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({
286278
});
287279

288280
// Keep preview state outside ChatView to isolate dialog renders.
289-
const expandedImagePreviewAtom = Atom.make<{
281+
type ExpandedImagePreviewState = {
290282
readonly threadKey: string;
291283
readonly preview: ExpandedImagePreview;
292-
} | null>(null).pipe(Atom.keepAlive, Atom.withLabel("chat:expanded-image-preview"));
284+
} | null;
285+
286+
const expandedImagePreviewAtom = Atom.make<ExpandedImagePreviewState>(null).pipe(
287+
Atom.keepAlive,
288+
Atom.withLabel("chat:expanded-image-preview"),
289+
);
290+
291+
function ownedSrc(state: ExpandedImagePreviewState): string | null {
292+
const item = state?.preview.images[state.preview.index];
293+
return item?.ownsSrc === true ? item.src : null;
294+
}
295+
296+
// The preview owns a blob URL made for it, so whatever replaces it releases that URL.
297+
function setExpandedImagePreview(next: ExpandedImagePreviewState): void {
298+
const previous = ownedSrc(appAtomRegistry.get(expandedImagePreviewAtom));
299+
appAtomRegistry.set(expandedImagePreviewAtom, next);
300+
if (previous !== null && previous !== ownedSrc(next)) URL.revokeObjectURL(previous);
301+
}
293302

294303
export function openExpandedImagePreview(threadKey: string, preview: ExpandedImagePreview): void {
295-
appAtomRegistry.set(expandedImagePreviewAtom, { threadKey, preview });
304+
setExpandedImagePreview({ threadKey, preview });
296305
}
297306

298307
function closeExpandedImagePreview(): void {
299-
appAtomRegistry.set(expandedImagePreviewAtom, null);
308+
setExpandedImagePreview(null);
300309
}
301310

302-
function closeExpandedImagePreviewFor(threadKey: string): void {
303-
if (appAtomRegistry.get(expandedImagePreviewAtom)?.threadKey === threadKey) {
304-
closeExpandedImagePreview();
305-
}
306-
}
311+
// Leaving the thread's route (or the chat view) drops its preview.
312+
registerThreadOverlay((threadKey) => {
313+
const current = appAtomRegistry.get(expandedImagePreviewAtom);
314+
if (current !== null && current.threadKey !== threadKey) closeExpandedImagePreview();
315+
});
307316

308317
export function ExpandedImageDialogHost({ threadKey }: { readonly threadKey: string }) {
309318
const state = useAtomValue(expandedImagePreviewAtom);
310319
const preview = state?.threadKey === threadKey ? state.preview : null;
311-
const item = preview?.images[preview.index];
312-
const ownedSrc = item?.ownsSrc === true ? item.src : null;
313-
useEffect(() => {
314-
if (ownedSrc === null) return;
315-
return () => URL.revokeObjectURL(ownedSrc);
316-
}, [ownedSrc]);
317-
useEffect(() => () => closeExpandedImagePreviewFor(threadKey), [threadKey]);
318320
if (preview === null) return null;
319321
return (
320322
<ExpandedImageDialog
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { EnvironmentId } from "@t3tools/contracts";
2+
import { describe, expect, it, vi } from "vite-plus/test";
3+
import { userEvent } from "vite-plus/test/browser";
4+
5+
import "~/index.css";
6+
import { render } from "../../../test/render";
7+
8+
vi.mock(import("~/assets/longLivedAssetUrls"), () => ({
9+
useLongLivedAssetUrl: () => ({
10+
_tag: "Success",
11+
url: "about:blank",
12+
expiresAt: Date.now() + 60 * 60_000,
13+
}),
14+
}));
15+
vi.mock(import("~/assets/assetUrls"), async (importOriginal) => ({
16+
...(await importOriginal()),
17+
useAssetUrlRefresh: () => async () => "about:blank",
18+
}));
19+
20+
import { HtmlRenderFrame } from "./HtmlRenderFrame";
21+
22+
describe("HtmlRenderFrame", () => {
23+
it("reports leaving full screen when it unmounts while expanded", async () => {
24+
const onFullscreenChange = vi.fn();
25+
await using screen = await render(
26+
<HtmlRenderFrame
27+
environmentId={EnvironmentId.make("environment")}
28+
htmlRender={{ attachmentId: "attachment", title: "Report", height: 200 }}
29+
threadRef={undefined}
30+
onFullscreenChange={onFullscreenChange}
31+
/>,
32+
);
33+
34+
await userEvent.click(screen.getByRole("button", { name: "Open full screen" }));
35+
await expect.element(screen.getByRole("dialog")).toBeVisible();
36+
expect(onFullscreenChange).toHaveBeenLastCalledWith(true);
37+
38+
await screen.unmount();
39+
expect(onFullscreenChange).toHaveBeenLastCalledWith(false);
40+
});
41+
});

0 commit comments

Comments
 (0)