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

ExpandedImageDialog.tsx

333 lines13.0 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(calc((100vh-var(--native-titlebar-height,0px))*0.86),calc(100vh-var(--native-titlebar-height,0px)-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 mimeType={item.mimeType}
237 onError={() => setFailedImageSrc(item.src)}
238 />
239 )}
240 <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">
241 <span className="truncate" aria-live="polite" aria-atomic="true">
242 {item.name}
243 {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
244 </span>
245 {accessibilityDetails && item.source ? (
246 <Tooltip>
247 <TooltipTrigger
248 render={
249 <Button
250 aria-label={contentsLabel}
251 aria-pressed={showingAccessibilityDetails}
252 onClick={() =>
253 setAccessibilityDetailsSrc(showingAccessibilityDetails ? null : item.src)
254 }
255 size="icon-micro"
256 variant="overlay"
257 />
258 }
259 >
260 <MorphIcon
261 className="size-3"
262 aria-hidden="true"
263 icon={showingAccessibilityDetails ? ImageGlyph : TextGlyph}
264 />
265 </TooltipTrigger>
266 <TooltipPopup side="top">{contentsLabel}</TooltipPopup>
267 </Tooltip>
268 ) : item.source ? (
269 <SnapShotContentsButton source={item.source} side="top" />
270 ) : null}
271 </div>
272 </div>
273 </MediaActions>
274 {preview.images.length > 1 && (
275 <Button
276 type="button"
277 size="icon"
278 variant="media-navigation"
279 className="right-0 top-auto bottom-0 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
280 aria-label="Next media"
281 onClick={() => navigateImage(1)}
282 >
283 <ChevronRightIcon className="size-5" />
284 </Button>
285 )}
286 </DialogPopup>
287 </Dialog>
288 );
289});
290​
291/**
292 * The chat view's open media preview. It lives outside ChatView so opening or
293 * closing it renders only the dialog host, not the whole chat chrome.
294 */
295const expandedImagePreviewAtom = Atom.make<{
296 readonly threadKey: string;
297 readonly preview: ExpandedImagePreview;
298} | null>(null).pipe(Atom.keepAlive, Atom.withLabel("chat:expanded-image-preview"));
299​
300export function openExpandedImagePreview(threadKey: string, preview: ExpandedImagePreview): void {
301 appAtomRegistry.set(expandedImagePreviewAtom, { threadKey, preview });
303​
304function closeExpandedImagePreview(): void {
305 appAtomRegistry.set(expandedImagePreviewAtom, null);
307​
308function closeExpandedImagePreviewFor(threadKey: string): void {
309 if (appAtomRegistry.get(expandedImagePreviewAtom)?.threadKey === threadKey) {
310 closeExpandedImagePreview();
311 }
313​
314export function ExpandedImageDialogHost({ threadKey }: { readonly threadKey: string }) {
315 const state = useAtomValue(expandedImagePreviewAtom);
316 const preview = state?.threadKey === threadKey ? state.preview : null;
317 const item = preview?.images[preview.index];
318 const ownedSrc = item?.ownsSrc === true ? item.src : null;
319 useEffect(() => {
320 if (ownedSrc === null) return;
321 return () => URL.revokeObjectURL(ownedSrc);
322 }, [ownedSrc]);
323 // Leaving the thread (or the chat view) drops its preview.
324 useEffect(() => () => closeExpandedImagePreviewFor(threadKey), [threadKey]);
325 if (preview === null) return null;
326 return (
327 <ExpandedImageDialog
328 key={expandedImageKey(preview)}
329 preview={preview}
330 onClose={closeExpandedImagePreview}
331 />
332 );