Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ExpandedImageDialog.tsx

464 lines17.9 KB

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;
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 );
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;
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 );
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 // Commit saving: false before focusing so the draw button is enabled in the DOM.
169 flushSync(() => {
170 setEditing(false);
171 setEditStatus({ dirty: false, saving: false });
172 });
173 editButtonRef.current?.focus({ preventScroll: true });
174 };
175 const cancelEdit = () => {
176 if (!editStatus.saving) exitEdit();
177 };
178​
179 const navigateImage = (direction: -1 | 1) => {
180 if (editing) {
181 if (editStatus.dirty) return;
182 exitEdit();
183 }
184 setImageOffset((current) => current + direction);
185 };
186​
187 const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
188 if (event.defaultPrevented || isContextMenuOpen() || event.target instanceof HTMLVideoElement)
189 return;
190 if (!editing && zoomableImageRef.current?.pan(event.key)) {
191 event.preventDefault();
192 event.stopPropagation();
193 return;
194 }
195 if (preview.images.length <= 1) return;
196 if (event.key === "ArrowLeft") {
197 event.preventDefault();
198 event.stopPropagation();
199 navigateImage(-1);
200 return;
201 }
202 if (event.key !== "ArrowRight") return;
203 event.preventDefault();
204 event.stopPropagation();
205 navigateImage(1);
206 };
207​
208 if (!item) return null;
209 const isVideo = item.type === "video";
210 const editTarget = editing && !isVideo ? item.edit : undefined;
211 const openOriginalLink =
212 item.originalUrl && resolveExternalWebLinkHost(item.originalUrl) !== null ? (
213 <OpenMediaLink originalUrl={item.originalUrl} />
214 ) : null;
215 const accessibilityDetails = item.source ? snapShotAccessibilityDetails(item.source) : undefined;
216 const showingAccessibilityDetails =
217 Boolean(accessibilityDetails) && accessibilityDetailsSrc === item.src;
218 const contentsLabel = showingAccessibilityDetails
219 ? gt`Show screenshot`
220 : accessibilityDetails?.format === "json"
221 ? gt`Show accessibility JSON`
222 : gt`Show extracted text`;
223​
224 return (
225 <Dialog
226 open
227 onOpenChange={(open, eventDetails) => {
228 if (open) return;
229 // Escape belongs to an open context menu first.
230 if (eventDetails.reason === "escape-key" && isContextMenuOpen()) {
231 eventDetails.cancel();
232 return;
233 }
234 // While drawing, Escape cancels the drawing and nothing else closes the preview.
235 if (editing) {
236 eventDetails.cancel();
237 if (eventDetails.reason === "escape-key") cancelEdit();
238 return;
239 }
240 close();
241 }}
242 >
243 <DialogPopup
244 {...composerFloatingLayerProps}
245 variant="media"
246 mediaControlsPlacement="inside"
247 showCloseButton={false}
248 bottomStickOnMobile={false}
249 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)]"
250 onKeyDown={onKeyDown}
251 initialFocus={closeButtonRef}
252 finalFocus={() => returnFocus.target}
253 onPointerDown={(event) => {
254 emptyAreaPressRef.current = event.target === event.currentTarget;
255 }}
256 // A press released on the image still clicks the popup, their common ancestor.
257 onPointerUp={(event) => {
258 if (event.target !== event.currentTarget) emptyAreaPressRef.current = false;
259 }}
260 onClick={(event) => {
261 if (emptyAreaPressRef.current && event.target === event.currentTarget && !editing)
262 close();
263 emptyAreaPressRef.current = false;
264 }}
265 >
266 <DialogTitle className="sr-only">
267 {isVideo ? gt`Expanded video preview` : gt`Expanded image preview`}
268 </DialogTitle>
269 <Button
270 type="button"
271 ref={closeButtonRef}
272 size="icon"
273 variant="media-close"
274 className="absolute end-0 top-0 z-20 max-[8rem]:end-auto max-[8rem]:left-1/2 max-[8rem]:-translate-x-1/2"
275 onClick={editing ? cancelEdit : close}
276 aria-label={
277 editing
278 ? gt`Cancel drawing`
279 : isVideo
280 ? gt`Close video preview`
281 : gt`Close image preview`
282 }
283 >
284 <XIcon aria-hidden="true" />
285 </Button>
286 {preview.images.length > 1 && (
287 <Button
288 type="button"
289 size="icon"
290 variant="media-navigation"
291 className="left-0 top-auto bottom-0 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
292 aria-label={gt`Previous media`}
293 disabled={editing && editStatus.dirty}
294 onClick={() => navigateImage(-1)}
295 >
296 <ChevronLeftIcon className="size-5" />
297 </Button>
298 )}
299 <MediaActions source={actionsSource} showTooltip={false}>
300 <div className="relative isolate z-10 flex max-h-full max-w-[var(--media-width)] flex-col items-center">
301 {item.type === "video" ? (
302 <ExpandedVideo key={index} item={item} />
303 ) : showingAccessibilityDetails ? (
304 accessibilityDetails ? (
305 <SnapShotAccessibilityData
306 details={accessibilityDetails}
307 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"
308 />
309 ) : null
310 ) : item.src === null || failedImageSrc === item.src ? (
311 <ExpandedMediaFailure>
312 <p>
313 {openOriginalLink
314 ? gt`This image could not be loaded.`
315 : gt`Image unavailable. The file may have been moved or deleted.`}
316 </p>
317 {openOriginalLink}
318 </ExpandedMediaFailure>
319 ) : (
320 <ZoomableImage
321 ref={zoomableImageRef}
322 key={`${index}:${item.src}`}
323 src={item.src}
324 name={item.name}
325 mimeType={itemMimeType(item)}
326 onError={() => setFailedImageSrc(item.src)}
327 overlay={
328 editTarget ? (
329 <ImageAnnotationOverlay
330 target={editTarget}
331 onStatusChange={setEditStatus}
332 onSaved={(edited) => {
333 setEditedImages((current) => ({ ...current, [index]: edited }));
334 exitEdit();
335 }}
336 onExit={exitEdit}
337 />
338 ) : undefined
339 }
340 />
341 )}
342 <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">
343 <span className="truncate" aria-live="polite" aria-atomic="true">
344 {item.name}
345 {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
346 </span>
347 {accessibilityDetails && item.source ? (
348 <SharedTooltipTrigger
349 render={
350 <Button
351 aria-label={contentsLabel}
352 aria-pressed={showingAccessibilityDetails}
353 disabled={editing}
354 onClick={() =>
355 setAccessibilityDetailsSrc(showingAccessibilityDetails ? null : item.src)
356 }
357 size="icon-micro"
358 variant="overlay"
359 />
360 }
361 label={contentsLabel}
362 >
363 {showingAccessibilityDetails ? (
364 <ImageIcon className="size-3" aria-hidden="true" />
365 ) : (
366 <TextIcon className="size-3" aria-hidden="true" />
367 )}
368 </SharedTooltipTrigger>
369 ) : item.source ? (
370 <SnapShotContentsButton source={item.source} side="top" />
371 ) : null}
372 {item.edit && !isVideo ? (
373 <SharedTooltipTrigger
374 render={
375 <Button
376 ref={editButtonRef}
377 aria-label={gt`Draw on image`}
378 aria-pressed={editing}
379 disabled={showingAccessibilityDetails || editStatus.saving}
380 onClick={() => (editing ? cancelEdit() : setEditing(true))}
381 size="icon-micro"
382 variant={editing ? "default" : "overlay"}
383 />
384 }
385 label={gt`Draw on image`}
386 >
387 <PencilIcon className="size-3" aria-hidden="true" />
388 </SharedTooltipTrigger>
389 ) : null}
390 {item.onCopySnapshot && (
391 <div className="-my-1.5">
392 <SnapShotCopyButton onCopy={item.onCopySnapshot} />
393 </div>
394 )}
395 </div>
396 </div>
397 </MediaActions>
398 {preview.images.length > 1 && (
399 <Button
400 type="button"
401 size="icon"
402 variant="media-navigation"
403 className="right-0 top-auto bottom-0 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
404 aria-label={gt`Next media`}
405 disabled={editing && editStatus.dirty}
406 onClick={() => navigateImage(1)}
407 >
408 <ChevronRightIcon className="size-5" />
409 </Button>
410 )}
411 </DialogPopup>
412 </Dialog>
413 );
414});
415​
416// Keep preview state outside ChatView to isolate dialog renders.
417type ExpandedImagePreviewState = {
418 readonly threadKey: string;
419 readonly preview: ExpandedImagePreview;
420} | null;
421​
422const expandedImagePreviewAtom = Atom.make<ExpandedImagePreviewState>(null).pipe(
423 Atom.keepAlive,
424 Atom.withLabel("chat:expanded-image-preview"),
425);
426​
427function ownedSrc(state: ExpandedImagePreviewState): string | null {
428 const item = state?.preview.images[state.preview.index];
429 return item?.ownsSrc === true ? item.src : null;
431​
432// The preview owns a blob URL made for it, so whatever replaces it releases that URL.
433function setExpandedImagePreview(next: ExpandedImagePreviewState): void {
434 const previous = ownedSrc(appAtomRegistry.get(expandedImagePreviewAtom));
435 appAtomRegistry.set(expandedImagePreviewAtom, next);
436 if (previous !== null && previous !== ownedSrc(next)) URL.revokeObjectURL(previous);
438​
439export function openExpandedImagePreview(threadKey: string, preview: ExpandedImagePreview): void {
440 setExpandedImagePreview({ threadKey, preview });
442​
443function closeExpandedImagePreview(): void {
444 setExpandedImagePreview(null);
446​
447// Leaving the thread's route (or the chat view) drops its preview.
448registerThreadOverlay((threadKey) => {
449 const current = appAtomRegistry.get(expandedImagePreviewAtom);
450 if (current !== null && current.threadKey !== threadKey) closeExpandedImagePreview();
451});
452​
453export function ExpandedImageDialogHost({ threadKey }: { readonly threadKey: string }) {
454 const state = useAtomValue(expandedImagePreviewAtom);
455 const preview = state?.threadKey === threadKey ? state.preview : null;
456 if (preview === null) return null;
457 return (
458 <ExpandedImageDialog
459 key={expandedImageKey(preview)}
460 preview={preview}
461 onClose={closeExpandedImagePreview}
462 />
463 );