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

ExpandedImageDialog.tsx

332 lines12.9 KB

1import { memo, useEffect, useRef, useState, type ReactNode, type KeyboardEvent } from "react";
2import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "lucide-react";
3import { Image as ImageGlyph, Text as TextGlyph } from "lucide";
4import { Button } from "../ui/button";
5import { MorphIcon } from "~/components/MorphIcon";
6import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
7import type { ExpandedImageItem, ExpandedImagePreview } from "./ExpandedImagePreview";
8import { resolveExternalWebLinkHost } from "./externalLinkContextMenu";
9import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls";
10import { OpenMediaLink } from "../media/OpenMediaLink";
11import { MediaActions, type MediaActionSource } from "../media/MediaActions";
12import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
13import { isContextMenuOpen } from "../../contextMenuFallback";
14import {
15 SnapShotAccessibilityData,
16 SnapShotContentsButton,
17 snapShotAccessibilityDetails,
18} from "./SnapShotAttachmentDetails";
19import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
20import { ZoomableImage, type ZoomableImageHandle } from "./ZoomableImage";
21import { composerFloatingLayerProps } from "./composerEventScope";
22import { useAtomValue } from "@effect/atom-react";
23import { Atom } from "effect/reactivity";
24import { appAtomRegistry } from "~/rpc/atomRegistry";
25import { expandedImageKey } from "./ExpandedImagePreview";
26​
27interface ExpandedImageDialogProps {
28 preview: ExpandedImagePreview;
29 onClose: () => void;
31​
32const EXPANDED_MEDIA_STATE_CLASS_NAME =
33 "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";
34​
35function ExpandedMediaFailure({ children }: { children: ReactNode }) {
36 return (
37 <div role="alert" className={EXPANDED_MEDIA_STATE_CLASS_NAME}>
38 {children}
39 </div>
40 );
42​
43function ExpandedVideo({ item }: { readonly item: ExpandedImageItem }) {
44 const asset = item.actionsSource?.asset;
45 const assetUrl = useAssetUrlState(asset?.environmentId ?? null, asset?.resource ?? null);
46 const refreshAssetUrl = useAssetUrlRefresh(asset?.environmentId ?? null, asset?.resource ?? null);
47 const src = asset
48 ? assetUrl._tag === "Success"
49 ? assetUrl.url + (item.srcFragment ?? "")
50 : null
51 : item.src;
52 return (
53 <MediaVideoPlayer
54 src={src}
55 label={item.name}
56 sourceFailed={assetUrl._tag === "Failure"}
57 originalUrl={item.originalUrl}
58 preload="metadata"
59 autoPlay={item.autoPlay ?? true}
60 className="block max-h-[var(--media-height)] max-w-[var(--media-width)] text-center"
61 videoClassName="aspect-auto max-h-[var(--media-height)] w-auto max-w-[var(--media-width)] rounded-lg border border-border/70 shadow-2xl"
62 stateClassName={EXPANDED_MEDIA_STATE_CLASS_NAME}
63 onRetry={asset ? refreshAssetUrl : undefined}
64 />
65 );
67​
68export const ExpandedImageDialog = memo(function ExpandedImageDialog({
69 preview,
70 onClose,
71}: ExpandedImageDialogProps) {
72 const [imageOffset, setImageOffset] = useState(0);
73 const [failedImageSrc, setFailedImageSrc] = useState<string | null>(null);
74 const [accessibilityDetailsSrc, setAccessibilityDetailsSrc] = useState<string | null>(null);
75 const zoomableImageRef = useRef<ZoomableImageHandle>(null);
76 const [returnFocusTarget] = useState(() =>
77 document.activeElement instanceof HTMLElement ? document.activeElement : null,
78 );
79 const closeButtonRef = useRef<HTMLButtonElement>(null);
80 // JavaScript `%` keeps the sign of the dividend, and a negative index blanks the dialog.
81 const imageCount = preview.images.length;
82 const index =
83 imageCount > 0 ? (((preview.index + imageOffset) % imageCount) + imageCount) % imageCount : 0;
84 const item = preview.images[index];
85 const source: MediaActionSource = item?.actionsSource ?? {
86 kind: item?.type === "video" ? "video" : "image",
87 name: item?.name ?? "Media",
88 src: item?.src ?? null,
89 };
90 const openFile = source.onOpenFile;
91 const actionsSource: MediaActionSource = openFile
92 ? {
93 ...source,
94 onOpenFile: () => {
95 openFile();
96 onClose();
97 },
98 }
99 : source;
100​
101 const navigateImage = (direction: -1 | 1) => {
102 setImageOffset((current) => current + direction);
103 };
104​
105 // The element that opened the preview gets focus back on close. Without
106 // this a close button click leaves focus on the unmounted dialog, and the
107 // composer that owned the opener reads that as a blur and rests.
108 const openerRef = useRef<Element | null>(null);
109 useEffect(() => {
110 openerRef.current = document.activeElement;
111 return () => {
112 const opener = openerRef.current;
113 if (opener instanceof HTMLElement && opener.isConnected) {
114 opener.focus({ preventScroll: true });
115 }
116 };
117 }, []);
118​
119 const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
120 if (event.defaultPrevented || isContextMenuOpen() || event.target instanceof HTMLVideoElement)
121 return;
122 if (zoomableImageRef.current?.pan(event.key)) {
123 event.preventDefault();
124 event.stopPropagation();
125 return;
126 }
127 if (preview.images.length <= 1) return;
128 if (event.key === "ArrowLeft") {
129 event.preventDefault();
130 event.stopPropagation();
131 navigateImage(-1);
132 return;
133 }
134 if (event.key !== "ArrowRight") return;
135 event.preventDefault();
136 event.stopPropagation();
137 navigateImage(1);
138 };
139​
140 useEffect(() => {
141 const onEscape = (event: globalThis.KeyboardEvent) => {
142 if (event.key !== "Escape" || isContextMenuOpen()) return;
143 event.preventDefault();
144 event.stopPropagation();
145 onClose();
146 };
147 window.addEventListener("keydown", onEscape, { capture: true });
148 return () => window.removeEventListener("keydown", onEscape, { capture: true });
149 }, [onClose]);
150​
151 if (!item) return null;
152 const mediaLabel = item.type === "video" ? "video" : "image";
153 const openOriginalLink =
154 item.originalUrl && resolveExternalWebLinkHost(item.originalUrl) !== null ? (
155 <OpenMediaLink originalUrl={item.originalUrl} />
156 ) : null;
157 const accessibilityDetails = item.source ? snapShotAccessibilityDetails(item.source) : undefined;
158 const showingAccessibilityDetails =
159 Boolean(accessibilityDetails) && accessibilityDetailsSrc === item.src;
160 const contentsLabel = showingAccessibilityDetails
161 ? "Show screenshot"
162 : accessibilityDetails?.format === "json"
163 ? "Show accessibility JSON"
164 : "Show extracted text";
165​
166 return (
167 <Dialog
168 open
169 onOpenChange={(open) => {
170 if (!open) onClose();
171 }}
172 >
173 <DialogPopup
174 {...composerFloatingLayerProps}
175 variant="media"
176 showCloseButton={false}
177 bottomStickOnMobile={false}
178 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(86vh,calc(100vh-160px))] sm:[--media-width:calc(92vw-96px)]"
179 onKeyDown={onKeyDown}
180 initialFocus={closeButtonRef}
181 finalFocus={() => returnFocusTarget}
182 onClick={(event) => {
183 if (event.target === event.currentTarget) onClose();
184 }}
185 >
186 <DialogTitle className="sr-only">Expanded {mediaLabel} preview</DialogTitle>
187 <Button
188 type="button"
189 ref={closeButtonRef}
190 size="icon-sm"
191 variant="media-close"
192 className="absolute right-0 top-0 z-20"
193 onClick={onClose}
194 aria-label={`Close ${mediaLabel} preview`}
195 >
196 <XIcon />
197 </Button>
198 {preview.images.length > 1 && (
199 <Button
200 type="button"
201 size="icon"
202 variant="media-navigation"
203 className="left-0 top-auto bottom-0 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
204 aria-label="Previous media"
205 onClick={() => navigateImage(-1)}
206 >
207 <ChevronLeftIcon className="size-5" />
208 </Button>
209 )}
210 <MediaActions source={actionsSource}>
211 <div className="relative isolate z-10 flex max-h-full max-w-[var(--media-width)] flex-col items-center">
212 {item.type === "video" ? (
213 <ExpandedVideo key={index} item={item} />
214 ) : showingAccessibilityDetails ? (
215 accessibilityDetails ? (
216 <SnapShotAccessibilityData
217 details={accessibilityDetails}
218 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"
219 />
220 ) : null
221 ) : item.src === null || failedImageSrc === item.src ? (
222 <ExpandedMediaFailure>
223 <p>
224 {openOriginalLink
225 ? "This image could not be loaded."
226 : "Image unavailable. The file may have been moved or deleted."}
227 </p>
228 {openOriginalLink}
229 </ExpandedMediaFailure>
230 ) : (
231 <ZoomableImage
232 ref={zoomableImageRef}
233 key={`${index}:${item.src}`}
234 src={item.src}
235 name={item.name}
236 onError={() => setFailedImageSrc(item.src)}
237 />
238 )}
239 <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">
240 <span className="truncate" aria-live="polite" aria-atomic="true">
241 {item.name}
242 {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
243 </span>
244 {accessibilityDetails && item.source ? (
245 <Tooltip>
246 <TooltipTrigger
247 render={
248 <Button
249 aria-label={contentsLabel}
250 aria-pressed={showingAccessibilityDetails}
251 onClick={() =>
252 setAccessibilityDetailsSrc(showingAccessibilityDetails ? null : item.src)
253 }
254 size="icon-micro"
255 variant="overlay"
256 />
257 }
258 >
259 <MorphIcon
260 className="size-3"
261 aria-hidden="true"
262 icon={showingAccessibilityDetails ? ImageGlyph : TextGlyph}
263 />
264 </TooltipTrigger>
265 <TooltipPopup side="top">{contentsLabel}</TooltipPopup>
266 </Tooltip>
267 ) : item.source ? (
268 <SnapShotContentsButton source={item.source} side="top" />
269 ) : null}
270 </div>
271 </div>
272 </MediaActions>
273 {preview.images.length > 1 && (
274 <Button
275 type="button"
276 size="icon"
277 variant="media-navigation"
278 className="right-0 top-auto bottom-0 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
279 aria-label="Next media"
280 onClick={() => navigateImage(1)}
281 >
282 <ChevronRightIcon className="size-5" />
283 </Button>
284 )}
285 </DialogPopup>
286 </Dialog>
287 );
288});
289​
290/**
291 * The chat view's open media preview. It lives outside ChatView so opening or
292 * closing it renders only the dialog host, not the whole chat chrome.
293 */
294const expandedImagePreviewAtom = Atom.make<{
295 readonly threadKey: string;
296 readonly preview: ExpandedImagePreview;
297} | null>(null).pipe(Atom.keepAlive, Atom.withLabel("chat:expanded-image-preview"));
298​
299export function openExpandedImagePreview(threadKey: string, preview: ExpandedImagePreview): void {
300 appAtomRegistry.set(expandedImagePreviewAtom, { threadKey, preview });
302​
303function closeExpandedImagePreview(): void {
304 appAtomRegistry.set(expandedImagePreviewAtom, null);
306​
307function closeExpandedImagePreviewFor(threadKey: string): void {
308 if (appAtomRegistry.get(expandedImagePreviewAtom)?.threadKey === threadKey) {
309 closeExpandedImagePreview();
310 }
312​
313export function ExpandedImageDialogHost({ threadKey }: { readonly threadKey: string }) {
314 const state = useAtomValue(expandedImagePreviewAtom);
315 const preview = state?.threadKey === threadKey ? state.preview : null;
316 const item = preview?.images[preview.index];
317 const ownedSrc = item?.ownsSrc === true ? item.src : null;
318 useEffect(() => {
319 if (ownedSrc === null) return;
320 return () => URL.revokeObjectURL(ownedSrc);
321 }, [ownedSrc]);
322 // Leaving the thread (or the chat view) drops its preview.
323 useEffect(() => () => closeExpandedImagePreviewFor(threadKey), [threadKey]);
324 if (preview === null) return null;
325 return (
326 <ExpandedImageDialog
327 key={expandedImageKey(preview)}
328 preview={preview}
329 onClose={closeExpandedImagePreview}
330 />
331 );