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

ExpandedImageDialog.tsx

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