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