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