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

ExpandedImageDialog.tsx

293 lines11.2 KB

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;
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 );
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 );
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 // The offset accumulates without bound, so wrap it into range in both directions:
85 // JavaScript `%` keeps the sign of the dividend, and a negative index blanks the dialog.
86 const imageCount = preview.images.length;
87 const index =
88 imageCount > 0 ? (((preview.index + imageOffset) % imageCount) + imageCount) % imageCount : 0;
89 const item = preview.images[index];
90 const source: MediaActionSource = item?.actionsSource ?? {
91 kind: item?.type === "video" ? "video" : "image",
92 name: item?.name ?? "Media",
93 src: item?.src ?? null,
94 };
95 const openFile = source.onOpenFile;
96 const actionsSource: MediaActionSource = openFile
97 ? {
98 ...source,
99 onOpenFile: () => {
100 openFile();
101 onClose();
102 },
103 }
104 : source;
105​
106 const navigateImage = useCallback((direction: -1 | 1) => {
107 setImageOffset((current) => current + direction);
108 }, []);
109​
110 // The element that opened the preview gets focus back on close. Without
111 // this a close button click leaves focus on the unmounted dialog, and the
112 // composer that owned the opener reads that as a blur and rests.
113 const openerRef = useRef<Element | null>(null);
114 useEffect(() => {
115 openerRef.current = document.activeElement;
116 return () => {
117 const opener = openerRef.current;
118 if (opener instanceof HTMLElement && opener.isConnected) {
119 opener.focus({ preventScroll: true });
120 }
121 };
122 }, []);
123​
124 const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
125 if (event.defaultPrevented || isContextMenuOpen() || event.target instanceof HTMLVideoElement)
126 return;
127 if (zoomableImageRef.current?.pan(event.key)) {
128 event.preventDefault();
129 event.stopPropagation();
130 return;
131 }
132 if (preview.images.length <= 1) return;
133 if (event.key === "ArrowLeft") {
134 event.preventDefault();
135 event.stopPropagation();
136 navigateImage(-1);
137 return;
138 }
139 if (event.key !== "ArrowRight") return;
140 event.preventDefault();
141 event.stopPropagation();
142 navigateImage(1);
143 };
144​
145 useEffect(() => {
146 const onEscape = (event: globalThis.KeyboardEvent) => {
147 if (event.key !== "Escape" || isContextMenuOpen()) return;
148 event.preventDefault();
149 event.stopPropagation();
150 onClose();
151 };
152 window.addEventListener("keydown", onEscape, { capture: true });
153 return () => window.removeEventListener("keydown", onEscape, { capture: true });
154 }, [onClose]);
155​
156 if (!item) return null;
157 const mediaLabel = item.type === "video" ? "video" : "image";
158 const openOriginalLink =
159 item.originalUrl && resolveExternalWebLinkHost(item.originalUrl) !== null ? (
160 <OpenMediaLink originalUrl={item.originalUrl} />
161 ) : null;
162 const accessibilityDetails = item.source ? snapShotAccessibilityDetails(item.source) : undefined;
163 const showingAccessibilityDetails =
164 Boolean(accessibilityDetails) && accessibilityDetailsSrc === item.src;
165 const contentsLabel = showingAccessibilityDetails
166 ? "Show screenshot"
167 : accessibilityDetails?.format === "json"
168 ? "Show accessibility JSON"
169 : "Show extracted text";
170​
171 return (
172 <Dialog
173 open
174 onOpenChange={(open) => {
175 if (!open) onClose();
176 }}
177 >
178 <DialogPopup
179 {...composerFloatingLayerProps}
180 variant="media"
181 showCloseButton={false}
182 bottomStickOnMobile={false}
183 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)]"
184 onKeyDown={onKeyDown}
185 initialFocus={closeButtonRef}
186 finalFocus={() => returnFocusTarget}
187 onClick={(event) => {
188 if (event.target === event.currentTarget) onClose();
189 }}
190 >
191 <DialogTitle className="sr-only">Expanded {mediaLabel} preview</DialogTitle>
192 {preview.images.length > 1 && (
193 <Button
194 type="button"
195 size="icon"
196 variant="media-navigation"
197 className="left-0 top-auto -bottom-12 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
198 aria-label="Previous media"
199 onClick={() => navigateImage(-1)}
200 >
201 <ChevronLeftIcon className="size-5" />
202 </Button>
203 )}
204 <MediaActions source={actionsSource}>
205 <div className="relative isolate z-10 max-h-[92vh] max-w-[var(--media-width)]">
206 <Button
207 type="button"
208 ref={closeButtonRef}
209 size="icon-xs"
210 variant="media-close"
211 className="absolute right-0 -top-10 z-20"
212 onClick={onClose}
213 aria-label={`Close ${mediaLabel} preview`}
214 >
215 <XIcon />
216 </Button>
217 {item.type === "video" ? (
218 <ExpandedVideo key={index} item={item} />
219 ) : showingAccessibilityDetails ? (
220 accessibilityDetails ? (
221 <SnapShotAccessibilityData
222 details={accessibilityDetails}
223 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"
224 />
225 ) : null
226 ) : item.src === null || failedImageSrc === item.src ? (
227 <ExpandedMediaFailure>
228 <p>
229 {openOriginalLink
230 ? "This image could not be loaded."
231 : "Image unavailable. The file may have been moved or deleted."}
232 </p>
233 {openOriginalLink}
234 </ExpandedMediaFailure>
235 ) : (
236 <ZoomableImage
237 ref={zoomableImageRef}
238 key={`${index}:${item.src}`}
239 src={item.src}
240 name={item.name}
241 onError={() => setFailedImageSrc(item.src)}
242 />
243 )}
244 <div className="mt-2 flex max-w-[var(--media-width)] items-center justify-center gap-1.5 text-xs text-white/80">
245 <span className="truncate" aria-live="polite" aria-atomic="true">
246 {item.name}
247 {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
248 </span>
249 {accessibilityDetails && item.source ? (
250 <Tooltip>
251 <TooltipTrigger
252 render={
253 <Button
254 aria-label={contentsLabel}
255 aria-pressed={showingAccessibilityDetails}
256 onClick={() =>
257 setAccessibilityDetailsSrc(showingAccessibilityDetails ? null : item.src)
258 }
259 size="icon-micro"
260 variant="overlay"
261 />
262 }
263 >
264 <MorphIcon
265 className="size-3"
266 aria-hidden="true"
267 icon={showingAccessibilityDetails ? ImageGlyph : TextGlyph}
268 />
269 </TooltipTrigger>
270 <TooltipPopup side="top">{contentsLabel}</TooltipPopup>
271 </Tooltip>
272 ) : item.source ? (
273 <SnapShotContentsButton source={item.source} side="top" />
274 ) : null}
275 </div>
276 </div>
277 </MediaActions>
278 {preview.images.length > 1 && (
279 <Button
280 type="button"
281 size="icon"
282 variant="media-navigation"
283 className="right-0 top-auto -bottom-12 translate-y-0 sm:top-1/2 sm:bottom-auto sm:-translate-y-1/2"
284 aria-label="Next media"
285 onClick={() => navigateImage(1)}
286 >
287 <ChevronRightIcon className="size-5" />
288 </Button>
289 )}
290 </DialogPopup>
291 </Dialog>
292 );
293});