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

ExpandedImageDialog.tsx

274 lines10.1 KB

1import { memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";
2import { createPortal } from "react-dom";
3import { ChevronLeftIcon, ChevronRightIcon, ImageIcon, TextIcon, XIcon } from "lucide-react";
4import { Button } from "../ui/button";
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 { composerFloatingLayerProps } from "./composerEventScope";
19import { ZoomableImage, type ZoomableImageHandle } from "./ZoomableImage";
20​
21interface ExpandedImageDialogProps {
22 preview: ExpandedImagePreview;
23 onClose: () => void;
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 );
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 );
61​
62export const ExpandedImageDialog = memo(function ExpandedImageDialog({
63 preview,
64 onClose,
65}: ExpandedImageDialogProps) {
66 const [imageOffset, setImageOffset] = useState(0);
67 const zoomableImageRef = useRef<ZoomableImageHandle>(null);
68 const [failedImageSrc, setFailedImageSrc] = useState<string | null>(null);
69 const [accessibilityDetailsSrc, setAccessibilityDetailsSrc] = useState<string | null>(null);
70 const index = (preview.index + imageOffset + preview.images.length) % preview.images.length;
71 const item = preview.images[index];
72 const source: MediaActionSource = item?.actionsSource ?? {
73 kind: item?.type === "video" ? "video" : "image",
74 name: item?.name ?? "Media",
75 src: item?.src ?? null,
76 };
77 const openFile = source.onOpenFile;
78 const actionsSource: MediaActionSource = openFile
79 ? {
80 ...source,
81 onOpenFile: () => {
82 openFile();
83 onClose();
84 },
85 }
86 : source;
87​
88 const navigateImage = useCallback(
89 (direction: -1 | 1) => {
90 setImageOffset(
91 (current) => (current + direction + preview.images.length) % preview.images.length,
92 );
93 },
94 [preview.images.length],
95 );
96​
97 // The element that opened the preview gets focus back on close. Without
98 // this a close button click leaves focus on the unmounted dialog, and the
99 // composer that owned the opener reads that as a blur and rests.
100 const openerRef = useRef<Element | null>(null);
101 useEffect(() => {
102 openerRef.current = document.activeElement;
103 return () => {
104 const opener = openerRef.current;
105 if (opener instanceof HTMLElement && opener.isConnected) {
106 opener.focus({ preventScroll: true });
107 }
108 };
109 }, []);
110​
111 useEffect(() => {
112 const onKeyDown = (event: globalThis.KeyboardEvent) => {
113 if (event.defaultPrevented || isContextMenuOpen()) {
114 return;
115 }
116 if (event.key === "Escape") {
117 event.preventDefault();
118 event.stopPropagation();
119 onClose();
120 return;
121 }
122 if (zoomableImageRef.current?.pan(event.key)) {
123 event.preventDefault();
124 event.stopPropagation();
125 return;
126 }
127 if (preview.images.length <= 1) return;
128 if (event.key === "ArrowLeft") {
129 event.preventDefault();
130 event.stopPropagation();
131 navigateImage(-1);
132 return;
133 }
134 if (event.key !== "ArrowRight") return;
135 event.preventDefault();
136 event.stopPropagation();
137 navigateImage(1);
138 };
139 window.addEventListener("keydown", onKeyDown);
140 return () => window.removeEventListener("keydown", onKeyDown);
141 }, [navigateImage, onClose, preview.images.length]);
142​
143 if (!item) return null;
144 const mediaLabel = item.type === "video" ? "video" : "image";
145 const openOriginalLink =
146 item.originalUrl && resolveExternalWebLinkHost(item.originalUrl) !== null ? (
147 <OpenMediaLink originalUrl={item.originalUrl} />
148 ) : null;
149 const accessibilityDetails = item.source ? snapShotAccessibilityDetails(item.source) : undefined;
150 const showingAccessibilityDetails =
151 Boolean(accessibilityDetails) && accessibilityDetailsSrc === item.src;
152 const contentsLabel = showingAccessibilityDetails
153 ? "Show screenshot"
154 : accessibilityDetails?.format === "json"
155 ? "Show accessibility JSON"
156 : "Show extracted text";
157 const ContentsIcon = showingAccessibilityDetails ? ImageIcon : TextIcon;
158​
159 return createPortal(
160 <div
161 {...composerFloatingLayerProps}
162 className="fixed inset-0 z-[60] flex items-center justify-center bg-black/75 px-4 py-6 [-webkit-app-region:no-drag]"
163 role="dialog"
164 aria-modal="true"
165 aria-label={`Expanded ${mediaLabel} preview`}
166 >
167 <button
168 type="button"
169 className="absolute inset-0 z-0 cursor-zoom-out"
170 aria-label={`Close ${mediaLabel} preview`}
171 onClick={onClose}
172 />
173 {preview.images.length > 1 && (
174 <Button
175 type="button"
176 size="icon-xl"
177 variant="overlay"
178 className="absolute left-2 top-1/2 z-20 -translate-y-1/2 sm:left-6"
179 aria-label="Previous image"
180 onClick={() => navigateImage(-1)}
181 >
182 <ChevronLeftIcon className="size-7" />
183 </Button>
184 )}
185 <MediaActions source={actionsSource}>
186 <div className="relative isolate z-10 max-h-[92vh] max-w-[92vw]">
187 <Button
188 type="button"
189 size="icon-xs"
190 variant="ghost"
191 className="absolute right-2 top-2 z-20"
192 onClick={onClose}
193 aria-label={`Close ${mediaLabel} preview`}
194 >
195 <XIcon />
196 </Button>
197 {item.type === "video" ? (
198 <ExpandedVideo key={index} item={item} />
199 ) : showingAccessibilityDetails ? (
200 accessibilityDetails ? (
201 <SnapShotAccessibilityData
202 details={accessibilityDetails}
203 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"
204 />
205 ) : null
206 ) : item.src === null || failedImageSrc === item.src ? (
207 <ExpandedMediaFailure>
208 <p>
209 {openOriginalLink
210 ? "This image could not be loaded."
211 : "Image unavailable. The file may have been moved or deleted."}
212 </p>
213 {openOriginalLink}
214 </ExpandedMediaFailure>
215 ) : (
216 <ZoomableImage
217 ref={zoomableImageRef}
218 key={`${index}:${item.src}`}
219 src={item.src}
220 name={item.name}
221 onError={() => setFailedImageSrc(item.src)}
222 />
223 )}
224 <div className="mt-2 flex max-w-[92vw] items-center justify-center gap-1.5 text-xs text-white/80">
225 <span className="truncate">
226 {item.name}
227 {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
228 </span>
229 {accessibilityDetails && item.source ? (
230 <Tooltip>
231 <TooltipTrigger
232 render={
233 <Button
234 aria-label={contentsLabel}
235 aria-pressed={showingAccessibilityDetails}
236 className="[--control-icon-color:currentColor] hover:bg-white/10 hover:text-white"
237 onClick={() =>
238 setAccessibilityDetailsSrc(showingAccessibilityDetails ? null : item.src)
239 }
240 size="icon-micro"
241 variant="ghost-muted"
242 />
243 }
244 >
245 <ContentsIcon className="size-3" aria-hidden="true" />
246 </TooltipTrigger>
247 <TooltipPopup side="top">{contentsLabel}</TooltipPopup>
248 </Tooltip>
249 ) : item.source ? (
250 <SnapShotContentsButton
251 source={item.source}
252 side="top"
253 className="hover:bg-white/10 hover:text-white"
254 />
255 ) : null}
256 </div>
257 </div>
258 </MediaActions>
259 {preview.images.length > 1 && (
260 <Button
261 type="button"
262 size="icon-xl"
263 variant="overlay"
264 className="absolute right-2 top-1/2 z-20 -translate-y-1/2 sm:right-6"
265 aria-label="Next image"
266 onClick={() => navigateImage(1)}
267 >
268 <ChevronRightIcon className="size-7" />
269 </Button>
270 )}
271 </div>,
272 document.body,
273 );
274});