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, ImageIcon, TextIcon, XIcon } from "lucide-react";
11import { Button } from "../ui/button";
12import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
13import type { ExpandedImageItem, ExpandedImagePreview } from "./ExpandedImagePreview";
14import { resolveExternalWebLinkHost } from "./externalLinkContextMenu";
15import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls";
16import { OpenMediaLink } from "../media/OpenMediaLink";
17import { MediaActions, type MediaActionSource } from "../media/MediaActions";
18import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
19import { isContextMenuOpen } from "../../contextMenuFallback";
20import {
21 SnapShotAccessibilityData,
22 SnapShotContentsButton,
23 snapShotAccessibilityDetails,
24} from "./SnapShotAttachmentDetails";
25import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
26import { ZoomableImage, type ZoomableImageHandle } from "./ZoomableImage";
27import { composerFloatingLayerProps } from "./composerEventScope";
28
29interface ExpandedImageDialogProps {
30 preview: ExpandedImagePreview;
31 onClose: () => void;
32}
33
34const EXPANDED_MEDIA_STATE_CLASS_NAME =
35 "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";
36
37function ExpandedMediaFailure({ children }: { children: ReactNode }) {
38 return (
39 <div role="alert" className={EXPANDED_MEDIA_STATE_CLASS_NAME}>
40 {children}
41 </div>
42 );
43}
44
45function ExpandedVideo({ item }: { readonly item: ExpandedImageItem }) {
46 const asset = item.actionsSource?.asset;
47 const assetUrl = useAssetUrlState(asset?.environmentId ?? null, asset?.resource ?? null);
48 const refreshAssetUrl = useAssetUrlRefresh(asset?.environmentId ?? null, asset?.resource ?? null);
49 const src = asset
50 ? assetUrl._tag === "Success"
51 ? assetUrl.url + (item.srcFragment ?? "")
52 : null
53 : item.src;
54 return (
55 <MediaVideoPlayer
56 src={src}
57 label={item.name}
58 sourceFailed={assetUrl._tag === "Failure"}
59 originalUrl={item.originalUrl}
60 preload="metadata"
61 autoPlay={item.autoPlay ?? true}
62 className="block max-h-[var(--media-height)] max-w-[var(--media-width)] text-center"
63 videoClassName="aspect-auto max-h-[var(--media-height)] w-auto max-w-[var(--media-width)] rounded-lg border border-border/70 shadow-2xl"
64 stateClassName={EXPANDED_MEDIA_STATE_CLASS_NAME}
65 onRetry={asset ? refreshAssetUrl : undefined}
66 />
67 );
68}
69
70export const ExpandedImageDialog = memo(function ExpandedImageDialog({
71 preview,
72 onClose,
73}: ExpandedImageDialogProps) {
74 const [imageOffset, setImageOffset] = useState(0);
75 const [failedImageSrc, setFailedImageSrc] = useState<string | null>(null);
76 const [accessibilityDetailsSrc, setAccessibilityDetailsSrc] = useState<string | null>(null);
77 const zoomableImageRef = useRef<ZoomableImageHandle>(null);
78 const [returnFocusTarget] = useState(() =>
79 document.activeElement instanceof HTMLElement ? document.activeElement : null,
80 );
81 const closeButtonRef = useRef<HTMLButtonElement>(null);
82 // The offset accumulates without bound, so wrap it into range in both directions:
83 // JavaScript `%` keeps the sign of the dividend, and a negative index blanks the dialog.
84 const imageCount = preview.images.length;
85 const index =
86 imageCount > 0 ? (((preview.index + imageOffset) % imageCount) + imageCount) % imageCount : 0;
87 const item = preview.images[index];
88 const source: MediaActionSource = item?.actionsSource ?? {
89 kind: item?.type === "video" ? "video" : "image",
90 name: item?.name ?? "Media",
91 src: item?.src ?? null,
92 };
93 const openFile = source.onOpenFile;
94 const actionsSource: MediaActionSource = openFile
95 ? {
96 ...source,
97 onOpenFile: () => {
98 openFile();
99 onClose();
100 },
101 }
102 : source;
103
104 const navigateImage = useCallback((direction: -1 | 1) => {
105 setImageOffset((current) => current + direction);
106 }, []);
107
108 // The element that opened the preview gets focus back on close. Without
109 // this a close button click leaves focus on the unmounted dialog, and the
110 // composer that owned the opener reads that as a blur and rests.
111 const openerRef = useRef<Element | null>(null);
112 useEffect(() => {
113 openerRef.current = document.activeElement;
114 return () => {
115 const opener = openerRef.current;
116 if (opener instanceof HTMLElement && opener.isConnected) {
117 opener.focus({ preventScroll: true });
118 }
119 };
120 }, []);
121
122 const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
123 if (event.defaultPrevented || isContextMenuOpen() || event.target instanceof HTMLVideoElement)
124 return;
125 if (zoomableImageRef.current?.pan(event.key)) {
126 event.preventDefault();
127 event.stopPropagation();
128 return;
129 }
130 if (preview.images.length <= 1) return;
131 if (event.key === "ArrowLeft") {
132 event.preventDefault();
133 event.stopPropagation();
134 navigateImage(-1);
135 return;
136 }
137 if (event.key !== "ArrowRight") return;
138 event.preventDefault();
139 event.stopPropagation();
140 navigateImage(1);
141 };
142
143 useEffect(() => {
144 const onEscape = (event: globalThis.KeyboardEvent) => {
145 if (event.key !== "Escape" || isContextMenuOpen()) return;
146 event.preventDefault();
147 event.stopPropagation();
148 onClose();
149 };
150 window.addEventListener("keydown", onEscape, { capture: true });
151 return () => window.removeEventListener("keydown", onEscape, { capture: true });
152 }, [onClose]);
153
154 if (!item) return null;
155 const mediaLabel = item.type === "video" ? "video" : "image";
156 const openOriginalLink =
157 item.originalUrl && resolveExternalWebLinkHost(item.originalUrl) !== null ? (
158 <OpenMediaLink originalUrl={item.originalUrl} />
159 ) : null;
160 const accessibilityDetails = item.source ? snapShotAccessibilityDetails(item.source) : undefined;
161 const showingAccessibilityDetails =
162 Boolean(accessibilityDetails) && accessibilityDetailsSrc === item.src;
163 const contentsLabel = showingAccessibilityDetails
164 ? "Show screenshot"
165 : accessibilityDetails?.format === "json"
166 ? "Show accessibility JSON"
167 : "Show extracted text";
168 const ContentsIcon = showingAccessibilityDetails ? ImageIcon : TextIcon;
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 max-h-[92vh] w-[92vw] max-w-[92vw] items-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 {preview.images.length > 1 && (
192 <Button
193 type="button"
194 size="icon"
195 variant="media-navigation"
196 className="left-0 top-auto -bottom-12 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
197 aria-label="Previous media"
198 onClick={() => navigateImage(-1)}
199 >
200 <ChevronLeftIcon className="size-5" />
201 </Button>
202 )}
203 <MediaActions source={actionsSource}>
204 <div className="relative isolate z-10 max-h-[92vh] max-w-[var(--media-width)]">
205 <Button
206 type="button"
207 ref={closeButtonRef}
208 size="icon-xs"
209 variant="media-close"
210 className="absolute right-0 -top-10 z-20"
211 onClick={onClose}
212 aria-label={`Close ${mediaLabel} preview`}
213 >
214 <XIcon />
215 </Button>
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)] 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"
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">
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 <ContentsIcon className="size-3" aria-hidden="true" />
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-12 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});