Open History to see the last commit
1import { memo, useRef, useState, type ReactNode, type KeyboardEvent } from "react";
2import { flushSync } from "react-dom";
3import { useGT } from "gt-react";
4import {
5 ChevronLeftIcon,
6 ChevronRightIcon,
7 ImageIcon,
8 PencilIcon,
9 TextIcon,
10 XIcon,
11} from "lucide-react";
12import { Button } from "../ui/button";
13import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
14import type { ExpandedImageItem, ExpandedImagePreview } from "./ExpandedImagePreview";
15import { resolveExternalWebLinkHost } from "./externalLinkContextMenu";
16import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls";
17import { OpenMediaLink } from "../media/OpenMediaLink";
18import { MediaActions, type MediaActionSource } from "../media/MediaActions";
19import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
20import { isContextMenuOpen } from "../../contextMenuFallback";
21import {
22 SnapShotAccessibilityData,
23 SnapShotCopyButton,
24 SnapShotContentsButton,
25 snapShotAccessibilityDetails,
26} from "./SnapShotAttachmentDetails";
27import { ZoomableImage, type ZoomableImageHandle } from "./ZoomableImage";
28import {
29 type EditedImage,
30 ImageAnnotationOverlay,
31 type ImageAnnotationStatus,
32} from "./ImageAnnotationOverlay";
33import { composerFloatingLayerProps } from "./composerEventScope";
34import { useAtomValue } from "@effect/atom-react";
35import { Atom } from "effect/reactivity";
36import { appAtomRegistry } from "~/rpc/atomRegistry";
37import { expandedImageKey } from "./ExpandedImagePreview";
38import { registerThreadOverlay } from "./threadOverlayRetention";
39import { mediaReferenceFileName } from "@t3tools/client-runtime/media-reference";
40import { mediaMimeType, mediaMimeTypeFromExtension } from "@t3tools/shared/mediaPreview";
41import { SharedTooltipTrigger } from "../ui/shared-tooltip";
42
43interface ExpandedImageDialogProps {
44 preview: ExpandedImagePreview;
45 onClose: () => void;
46}
47
48const EXPANDED_MEDIA_STATE_CLASS_NAME =
49 "flex aspect-auto h-48 min-h-0 w-[min(var(--media-width),32rem)] flex-col items-center justify-center gap-3 rounded-lg border border-border/70 bg-black p-6 text-center text-sm text-white shadow-2xl";
50
51function ExpandedMediaFailure({ children }: { children: ReactNode }) {
52 return (
53 <div role="alert" className={EXPANDED_MEDIA_STATE_CLASS_NAME}>
54 {children}
55 </div>
56 );
57}
58
59function itemMimeType(item: ExpandedImageItem): string | undefined {
60 if (item.mimeType) return item.mimeType;
61 const reference = item.actionsSource?.reference;
62 const fileName = reference && mediaReferenceFileName(reference);
63 if (fileName) {
64 return mediaMimeTypeFromExtension(fileName.slice(fileName.lastIndexOf("."))) ?? undefined;
65 }
66 return mediaMimeType(item.src ?? "") ?? undefined;
67}
68
69function ExpandedVideo({ item }: { readonly item: ExpandedImageItem }) {
70 const asset = item.actionsSource?.asset;
71 const assetUrl = useAssetUrlState(asset?.environmentId ?? null, asset?.resource ?? null);
72 const refreshAssetUrl = useAssetUrlRefresh(asset?.environmentId ?? null, asset?.resource ?? null);
73 const src = asset
74 ? assetUrl._tag === "Success"
75 ? assetUrl.url + (item.srcFragment ?? "")
76 : null
77 : item.src;
78 return (
79 <MediaVideoPlayer
80 src={src}
81 label={item.name}
82 sourceFailed={assetUrl._tag === "Failure"}
83 originalUrl={item.originalUrl}
84 preload="metadata"
85 autoPlay={item.autoPlay ?? true}
86 className="block max-h-[var(--media-height)] max-w-[var(--media-width)] text-center"
87 videoClassName="aspect-auto max-h-[var(--media-height)] w-auto max-w-[var(--media-width)] rounded-lg border border-border/70 shadow-2xl"
88 stateClassName={EXPANDED_MEDIA_STATE_CLASS_NAME}
89 onRetry={asset ? refreshAssetUrl : undefined}
90 />
91 );
92}
93
94export const ExpandedImageDialog = memo(function ExpandedImageDialog({
95 preview,
96 onClose,
97}: ExpandedImageDialogProps) {
98 const gt = useGT();
99 const [imageOffset, setImageOffset] = useState(0);
100 const [failedImageSrc, setFailedImageSrc] = useState<string | null>(null);
101 const [accessibilityDetailsSrc, setAccessibilityDetailsSrc] = useState<string | null>(null);
102 const zoomableImageRef = useRef<ZoomableImageHandle>(null);
103 // Drawing happens in place over the current image, so the preview around it never moves.
104 const [editing, setEditing] = useState(false);
105 const [editStatus, setEditStatus] = useState<ImageAnnotationStatus>({
106 dirty: false,
107 saving: false,
108 });
109 // A saved edit replaces the draft's bytes; show them here without reopening the preview.
110 const [editedImages, setEditedImages] = useState<Readonly<Record<number, EditedImage>>>({});
111 const editButtonRef = useRef<HTMLButtonElement>(null);
112 const [returnFocus] = useState(() => {
113 const target = document.activeElement instanceof HTMLElement ? document.activeElement : null;
114 return { target, focusVisible: target?.matches(":focus-visible") ?? false };
115 });
116 // The host unmounts the dialog outright, so Base UI never runs finalFocus. Without
117 // this, focus stays on the removed dialog, and the composer that owned the opener
118 // reads that as a blur and rests. Preserve mouse focus when Escape closes it.
119 const close = () => {
120 flushSync(onClose);
121 const { target, focusVisible } = returnFocus;
122 if (target?.isConnected) target.focus({ preventScroll: true, focusVisible });
123 };
124 const closeButtonRef = useRef<HTMLButtonElement>(null);
125 // Only a press that starts and ends on the empty area closes; a drag across it does not.
126 const emptyAreaPressRef = useRef(false);
127 const imageCount = preview.images.length;
128 const index =
129 imageCount > 0 ? (((preview.index + imageOffset) % imageCount) + imageCount) % imageCount : 0;
130 const previewItem = preview.images[index];
131 const editedImage = editedImages[index];
132 const item =
133 previewItem && editedImage
134 ? {
135 ...previewItem,
136 src: editedImage.src,
137 name: editedImage.file.name,
138 mimeType: editedImage.file.type,
139 ...(previewItem.edit
140 ? {
141 edit: {
142 ...previewItem.edit,
143 file: editedImage.file,
144 name: editedImage.file.name,
145 mimeType: editedImage.file.type,
146 },
147 }
148 : {}),
149 }
150 : previewItem;
151 const source: MediaActionSource = item?.actionsSource ?? {
152 kind: item?.type === "video" ? "video" : "image",
153 name: item?.name ?? gt("Media"),
154 src: item?.src ?? null,
155 };
156 const openFile = source.onOpenFile;
157 const actionsSource: MediaActionSource = openFile
158 ? {
159 ...source,
160 onOpenFile: () => {
161 openFile();
162 close();
163 },
164 }
165 : source;
166
167 const exitEdit = () => {
168 setEditing(false);
169 setEditStatus({ dirty: false, saving: false });
170 editButtonRef.current?.focus({ preventScroll: true });
171 };
172 const cancelEdit = () => {
173 if (!editStatus.saving) exitEdit();
174 };
175
176 const navigateImage = (direction: -1 | 1) => {
177 if (editing) {
178 if (editStatus.dirty) return;
179 exitEdit();
180 }
181 setImageOffset((current) => current + direction);
182 };
183
184 const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
185 if (event.defaultPrevented || isContextMenuOpen() || event.target instanceof HTMLVideoElement)
186 return;
187 if (!editing && zoomableImageRef.current?.pan(event.key)) {
188 event.preventDefault();
189 event.stopPropagation();
190 return;
191 }
192 if (preview.images.length <= 1) return;
193 if (event.key === "ArrowLeft") {
194 event.preventDefault();
195 event.stopPropagation();
196 navigateImage(-1);
197 return;
198 }
199 if (event.key !== "ArrowRight") return;
200 event.preventDefault();
201 event.stopPropagation();
202 navigateImage(1);
203 };
204
205 if (!item) return null;
206 const isVideo = item.type === "video";
207 const editTarget = editing && !isVideo ? item.edit : undefined;
208 const openOriginalLink =
209 item.originalUrl && resolveExternalWebLinkHost(item.originalUrl) !== null ? (
210 <OpenMediaLink originalUrl={item.originalUrl} />
211 ) : null;
212 const accessibilityDetails = item.source ? snapShotAccessibilityDetails(item.source) : undefined;
213 const showingAccessibilityDetails =
214 Boolean(accessibilityDetails) && accessibilityDetailsSrc === item.src;
215 const contentsLabel = showingAccessibilityDetails
216 ? gt("Show screenshot")
217 : accessibilityDetails?.format === "json"
218 ? gt("Show accessibility JSON")
219 : gt("Show extracted text");
220
221 return (
222 <Dialog
223 open
224 onOpenChange={(open, eventDetails) => {
225 if (open) return;
226 // Escape belongs to an open context menu first.
227 if (eventDetails.reason === "escape-key" && isContextMenuOpen()) {
228 eventDetails.cancel();
229 return;
230 }
231 // While drawing, Escape cancels the drawing and nothing else closes the preview.
232 if (editing) {
233 eventDetails.cancel();
234 if (eventDetails.reason === "escape-key") cancelEdit();
235 return;
236 }
237 close();
238 }}
239 >
240 <DialogPopup
241 {...composerFloatingLayerProps}
242 variant="media"
243 mediaControlsPlacement="inside"
244 showCloseButton={false}
245 bottomStickOnMobile={false}
246 className="row-start-1 h-full max-h-[92vh] w-[92vw] max-w-[92vw] items-center justify-center overflow-visible [--media-width:92vw] [--media-height:min(calc((100vh-var(--native-titlebar-height,0px))*0.86),calc(100vh-var(--native-titlebar-height,0px)-160px))] sm:[--media-width:calc(92vw-96px)]"
247 onKeyDown={onKeyDown}
248 initialFocus={closeButtonRef}
249 finalFocus={() => returnFocus.target}
250 onPointerDown={(event) => {
251 emptyAreaPressRef.current = event.target === event.currentTarget;
252 }}
253 // A press released on the image still clicks the popup, their common ancestor.
254 onPointerUp={(event) => {
255 if (event.target !== event.currentTarget) emptyAreaPressRef.current = false;
256 }}
257 onClick={(event) => {
258 if (emptyAreaPressRef.current && event.target === event.currentTarget && !editing)
259 close();
260 emptyAreaPressRef.current = false;
261 }}
262 >
263 <DialogTitle className="sr-only">
264 {isVideo ? gt("Expanded video preview") : gt("Expanded image preview")}
265 </DialogTitle>
266 <Button
267 type="button"
268 ref={closeButtonRef}
269 size="icon"
270 variant="media-close"
271 className="absolute end-0 top-0 z-20 max-[8rem]:end-auto max-[8rem]:left-1/2 max-[8rem]:-translate-x-1/2"
272 onClick={editing ? cancelEdit : close}
273 aria-label={
274 editing
275 ? gt("Cancel drawing")
276 : isVideo
277 ? gt("Close video preview")
278 : gt("Close image preview")
279 }
280 >
281 <XIcon aria-hidden="true" />
282 </Button>
283 {preview.images.length > 1 && (
284 <Button
285 type="button"
286 size="icon"
287 variant="media-navigation"
288 className="left-0 top-auto bottom-0 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
289 aria-label={gt("Previous media")}
290 disabled={editing && editStatus.dirty}
291 onClick={() => navigateImage(-1)}
292 >
293 <ChevronLeftIcon className="size-5" />
294 </Button>
295 )}
296 <MediaActions source={actionsSource} showTooltip={false}>
297 <div className="relative isolate z-10 flex max-h-full max-w-[var(--media-width)] flex-col items-center">
298 {item.type === "video" ? (
299 <ExpandedVideo key={index} item={item} />
300 ) : showingAccessibilityDetails ? (
301 accessibilityDetails ? (
302 <SnapShotAccessibilityData
303 details={accessibilityDetails}
304 className="h-[min(var(--media-height),40rem)] w-[min(var(--media-width),42rem)] transition-opacity duration-140 ease-out starting:opacity-0 rounded-lg border border-border/70 bg-background p-4 text-xs leading-5 shadow-2xl motion-reduce:transition-none"
305 />
306 ) : null
307 ) : item.src === null || failedImageSrc === item.src ? (
308 <ExpandedMediaFailure>
309 <p>
310 {openOriginalLink
311 ? gt("This image could not be loaded.")
312 : gt("Image unavailable. The file may have been moved or deleted.")}
313 </p>
314 {openOriginalLink}
315 </ExpandedMediaFailure>
316 ) : (
317 <ZoomableImage
318 ref={zoomableImageRef}
319 key={`${index}:${item.src}`}
320 src={item.src}
321 name={item.name}
322 mimeType={itemMimeType(item)}
323 onError={() => setFailedImageSrc(item.src)}
324 overlay={
325 editTarget ? (
326 <ImageAnnotationOverlay
327 target={editTarget}
328 onStatusChange={setEditStatus}
329 onSaved={(edited) => {
330 setEditedImages((current) => ({ ...current, [index]: edited }));
331 exitEdit();
332 }}
333 onExit={exitEdit}
334 />
335 ) : undefined
336 }
337 />
338 )}
339 <div className="mt-2 flex max-w-[var(--media-width)] items-center justify-center gap-1.5 text-xs text-white/80 max-sm:px-10">
340 <span className="truncate" aria-live="polite" aria-atomic="true">
341 {item.name}
342 {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
343 </span>
344 {accessibilityDetails && item.source ? (
345 <SharedTooltipTrigger
346 render={
347 <Button
348 aria-label={contentsLabel}
349 aria-pressed={showingAccessibilityDetails}
350 disabled={editing}
351 onClick={() =>
352 setAccessibilityDetailsSrc(showingAccessibilityDetails ? null : item.src)
353 }
354 size="icon-micro"
355 variant="overlay"
356 />
357 }
358 label={contentsLabel}
359 >
360 {showingAccessibilityDetails ? (
361 <ImageIcon className="size-3" aria-hidden="true" />
362 ) : (
363 <TextIcon className="size-3" aria-hidden="true" />
364 )}
365 </SharedTooltipTrigger>
366 ) : item.source ? (
367 <SnapShotContentsButton source={item.source} side="top" />
368 ) : null}
369 {item.edit && !isVideo ? (
370 <SharedTooltipTrigger
371 render={
372 <Button
373 ref={editButtonRef}
374 aria-label={gt("Draw on image")}
375 aria-pressed={editing}
376 disabled={showingAccessibilityDetails || editStatus.saving}
377 onClick={() => (editing ? cancelEdit() : setEditing(true))}
378 size="icon-micro"
379 variant={editing ? "default" : "overlay"}
380 />
381 }
382 label={gt("Draw on image")}
383 >
384 <PencilIcon className="size-3" aria-hidden="true" />
385 </SharedTooltipTrigger>
386 ) : null}
387 {item.onCopySnapshot && (
388 <div className="-my-1.5">
389 <SnapShotCopyButton onCopy={item.onCopySnapshot} />
390 </div>
391 )}
392 </div>
393 </div>
394 </MediaActions>
395 {preview.images.length > 1 && (
396 <Button
397 type="button"
398 size="icon"
399 variant="media-navigation"
400 className="right-0 top-auto bottom-0 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
401 aria-label={gt("Next media")}
402 disabled={editing && editStatus.dirty}
403 onClick={() => navigateImage(1)}
404 >
405 <ChevronRightIcon className="size-5" />
406 </Button>
407 )}
408 </DialogPopup>
409 </Dialog>
410 );
411});
412
413// Keep preview state outside ChatView to isolate dialog renders.
414type ExpandedImagePreviewState = {
415 readonly threadKey: string;
416 readonly preview: ExpandedImagePreview;
417} | null;
418
419const expandedImagePreviewAtom = Atom.make<ExpandedImagePreviewState>(null).pipe(
420 Atom.keepAlive,
421 Atom.withLabel("chat:expanded-image-preview"),
422);
423
424function ownedSrc(state: ExpandedImagePreviewState): string | null {
425 const item = state?.preview.images[state.preview.index];
426 return item?.ownsSrc === true ? item.src : null;
427}
428
429// The preview owns a blob URL made for it, so whatever replaces it releases that URL.
430function setExpandedImagePreview(next: ExpandedImagePreviewState): void {
431 const previous = ownedSrc(appAtomRegistry.get(expandedImagePreviewAtom));
432 appAtomRegistry.set(expandedImagePreviewAtom, next);
433 if (previous !== null && previous !== ownedSrc(next)) URL.revokeObjectURL(previous);
434}
435
436export function openExpandedImagePreview(threadKey: string, preview: ExpandedImagePreview): void {
437 setExpandedImagePreview({ threadKey, preview });
438}
439
440function closeExpandedImagePreview(): void {
441 setExpandedImagePreview(null);
442}
443
444// Leaving the thread's route (or the chat view) drops its preview.
445registerThreadOverlay((threadKey) => {
446 const current = appAtomRegistry.get(expandedImagePreviewAtom);
447 if (current !== null && current.threadKey !== threadKey) closeExpandedImagePreview();
448});
449
450export function ExpandedImageDialogHost({ threadKey }: { readonly threadKey: string }) {
451 const state = useAtomValue(expandedImagePreviewAtom);
452 const preview = state?.threadKey === threadKey ? state.preview : null;
453 if (preview === null) return null;
454 return (
455 <ExpandedImageDialog
456 key={expandedImageKey(preview)}
457 preview={preview}
458 onClose={closeExpandedImagePreview}
459 />
460 );
461}