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

ExpandedImageDialog.tsx

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