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

FilePreviewSession.tsx

272 lines10.4 KB

1import { AssetWorkspaceAssetNotFoundError } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import * as Dialog from "./Dialog";
4import { useContext, useEffect, useEffectEvent, useState, type ComponentType } from "react";
5​
6import { loadLocalAttachmentPreview } from "../../lib/localAttachmentPreview";
7import {
8 downloadAndShareAttachment,
9 nativeViewerErrorMessage,
10 shareLocalAttachment,
11} from "../../lib/attachmentDownload";
12import { usePreviewPresentation } from "../../lib/previewPresentation";
13import { refreshAssetUrl } from "../../state/assets";
14import {
15 filePreviewGallery,
16 filePreviewKey,
17 filePreviewName,
18 filePreviewSourceIdentifier,
19} from "../../lib/filePreviewGallery";
20import { FilePreviewGallery } from "./FilePreviewGallery";
21import type { MediaActionsSource } from "../../lib/mediaActionsSource";
22import type {
23 FilePreviewItem,
24 FilePreviewModalProps,
25 FilePreviewSource,
26 FilePreviewViewerProps,
27} from "./FilePreviewModal.types";
28​
29interface FilePreviewSessionOptions {
30 /** Opens before every image resolves; the viewer takes later URLs as they arrive. */
31 readonly progressiveGallery: boolean;
32 readonly Viewer: ComponentType<FilePreviewViewerProps>;
34​
35class PreviewResolutionError extends Schema.TaggedError<PreviewResolutionError>()(
36 "PreviewResolutionError",
37 { cause: Schema.Defect(), fallbackMessage: Schema.String },
38) {
39 override get message(): string {
40 return this.fallbackMessage;
41 }
43​
44const isPreviewResolutionError = Schema.is(PreviewResolutionError);
45const isAssetNotFoundError = Schema.is(AssetWorkspaceAssetNotFoundError);
46​
47function remotePreviewFailureMessage(error: unknown): string {
48 if (!isAssetNotFoundError(error)) {
49 return "Reconnect to this environment and try again. The file may have been moved or deleted.";
50 }
51 const path = error.checkedPath ?? ("path" in error.resource ? error.resource.path : undefined);
52 return path ? `The file was not found at ${path}.` : error.message;
54​
55interface ResolvedPreviewUri {
56 readonly uri: string;
57 readonly dispose?: () => void;
59​
60async function resolvePreviewUri(
61 item: FilePreviewItem,
62 signal: AbortSignal,
63): Promise<ResolvedPreviewUri | null> {
64 if ("uri" in item) return { uri: item.uri };
65 if ("attachment" in item) {
66 return loadLocalAttachmentPreview(item.attachment, signal).catch((error: unknown) => {
67 throw new PreviewResolutionError({
68 cause: error,
69 fallbackMessage: "Attach the file again and retry.",
70 });
71 });
72 }
73 // Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.
74 const url = await refreshAssetUrl(item.environmentId, item.resource, signal)
75 .then((value) => {
76 if (!value) throw new Error("Reconnect to this environment and try again.");
77 return value;
78 })
79 .catch((error: unknown) => {
80 throw new PreviewResolutionError({
81 cause: error,
82 fallbackMessage: remotePreviewFailureMessage(error),
83 });
84 });
85 return { uri: url + (item.srcFragment ?? "") };
87​
88// Shares from the unresolved item so remote URLs refresh and draft files take their own lease.
89function pdfActionsSource(item: FilePreviewItem): MediaActionsSource {
90 const metadata = {
91 name: filePreviewName(item),
92 mimeType: item.mimeType ?? "application/pdf",
93 ...(item.sourceIdentifier ? { sourceIdentifier: item.sourceIdentifier } : {}),
94 };
95 if ("uri" in item) return { ...metadata, uri: item.uri };
96 if ("attachment" in item) return { ...metadata, attachment: item.attachment };
97 return { ...metadata, environmentId: item.environmentId, resource: item.resource };
99​
100function ResolvedFilePreview(
101 props: FilePreviewSessionOptions & {
102 readonly source: FilePreviewSource;
103 readonly onRequestClose: () => void;
104 readonly onOpenError?: (error: unknown) => void;
105 readonly onPresent: (isFinished: () => boolean) => void;
106 },
107) {
108 const { progressiveGallery, Viewer } = props;
109 // Freeze the group at opening; streaming messages and URL refreshes must not reopen the viewer.
110 const [items] = useState(() => filePreviewGallery(props.source, []));
111 const selectedKey = filePreviewKey(props.source);
112 const selectedIndex = items.findIndex((item) => filePreviewKey(item) === selectedKey);
113 // Undefined while resolving, null once it cannot be.
114 const [uris, setUris] = useState<readonly (string | null | undefined)[]>(() =>
115 items.map((item) => ("uri" in item ? item.uri : undefined)),
116 );
117 const onResolutionError = useEffectEvent((error: PreviewResolutionError) => {
118 if (props.onOpenError) props.onOpenError(error.cause);
119 else Dialog.alert("Could not open preview", error.fallbackMessage);
120 props.onRequestClose();
121 });
122 // Resolves once per presentation and holds local file leases until it closes.
123 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- resolves preview files and holds their local file leases until the preview closes
124 useEffect(() => {
125 const controller = new AbortController();
126 const leases: (() => void)[] = [];
127 const settle = (index: number, uri: string | null) =>
128 setUris((current) => current.map((value, at) => (at === index ? uri : value)));
129 items.forEach((item, index) => {
130 if ("uri" in item) return;
131 void resolvePreviewUri(item, controller.signal).then(
132 (resolved) => {
133 if (controller.signal.aborted) return resolved?.dispose?.();
134 if (resolved?.dispose) leases.push(resolved.dispose);
135 settle(index, resolved?.uri ?? null);
136 },
137 (error: unknown) => {
138 if (controller.signal.aborted) return;
139 if (progressiveGallery && index !== selectedIndex) return settle(index, null);
140 controller.abort();
141 onResolutionError(
142 isPreviewResolutionError(error)
143 ? error
144 : new PreviewResolutionError({ cause: error, fallbackMessage: "Try again." }),
145 );
146 },
147 );
148 });
149 return () => {
150 controller.abort();
151 for (const dispose of leases) dispose();
152 };
153 }, [items, selectedIndex, progressiveGallery]);
154 const selected = { ...items[selectedIndex]!, name: filePreviewName(items[selectedIndex]!) };
155 if (selected.kind === "image") {
156 // A viewer that resets image gestures when its sources change waits for every image.
157 if (!progressiveGallery && uris.some((uri) => uri === undefined)) return null;
158 const images = items.map((item, index) => {
159 const uri = uris[index];
160 return {
161 ...item,
162 name: filePreviewName(item),
163 sourceIdentifier: filePreviewSourceIdentifier(item),
164 ...(uri ? { uri } : uri === null ? { failed: true } : {}),
165 };
166 });
167 return (
168 <Viewer
169 source={{ kind: "image", images, selectedIndex }}
170 onRequestClose={props.onRequestClose}
171 onPresent={props.onPresent}
172 {...(props.onOpenError ? { onOpenError: props.onOpenError } : {})}
173 />
174 );
175 }
176 const uri = uris[selectedIndex];
177 if (!uri) return null;
178 const onOpenError = (error: unknown) => {
179 if (props.onOpenError) return props.onOpenError(error);
180 Dialog.alert("Could not open preview", nativeViewerErrorMessage(error), [
181 { text: "Cancel", style: "cancel" },
182 ...(selected.kind === "document"
183 ? [
184 {
185 text: "Save or share",
186 onPress: () => {
187 const input = {
188 attachment: {
189 name: selected.name,
190 mimeType: selected.mimeType ?? "application/octet-stream",
191 },
192 signal: new AbortController().signal,
193 };
194 const sharing = /^(file|content):/.test(uri)
195 ? shareLocalAttachment({ ...input, uri })
196 : downloadAndShareAttachment({ ...input, url: uri });
197 void sharing.catch(() => Dialog.alert("Could not share file", "Please try again."));
198 },
199 },
200 ]
201 : []),
202 ]);
203 };
204 const actionsSource =
205 selected.kind === "pdf" ? (selected.actionsSource ?? pdfActionsSource(selected)) : undefined;
206 return (
207 <Viewer
208 source={{
209 ...selected,
210 kind: selected.kind,
211 uri,
212 ...(actionsSource ? { actionsSource } : {}),
213 }}
214 onRequestClose={props.onRequestClose}
215 onOpenError={onOpenError}
216 onPresent={props.onPresent}
217 />
218 );
220​
221/**
222 * The part of FilePreviewModal both platforms share: it resolves sources, freezes the gallery
223 * at opening and closes with its screen. Each platform's FilePreviewModal passes its viewer.
224 */
225export function FilePreviewSession(props: FilePreviewModalProps & FilePreviewSessionOptions) {
226 const group = useContext(FilePreviewGallery);
227 const source =
228 props.source === null
229 ? null
230 : { ...props.source, gallery: filePreviewGallery(props.source, group) };
231 usePreviewPresentation(source && filePreviewKey(source), props.onRequestClose);
232 // A tap can land after the native viewer closed but before its close reached the caller, which
233 // still holds the same item; that tap only opens a new viewer under a new key.
234 // Only a viewer that presented and has since closed reopens; one still resolving never does.
235 const [opening, setOpening] = useState<{
236 readonly source: FilePreviewModalProps["source"];
237 readonly count: number;
238 readonly presented: { readonly isFinished: () => boolean } | null;
239 }>({ source: props.source, count: 0, presented: null });
240 if (opening.source !== props.source) {
241 const sameItem =
242 opening.source !== null &&
243 props.source !== null &&
244 filePreviewKey(opening.source) === filePreviewKey(props.source);
245 const reopened = sameItem && opening.presented?.isFinished() === true;
246 setOpening({
247 source: props.source,
248 count: opening.count + (reopened ? 1 : 0),
249 presented: sameItem && !reopened ? opening.presented : null,
250 });
251 }
252 const { count } = opening;
253 const onPresent = (isFinished: () => boolean) =>
254 setOpening((current) =>
255 current.count === count && current.presented === null
256 ? { ...current, presented: { isFinished } }
257 : current,
258 );
259​
260 if (!source) return null;
261 return (
262 <ResolvedFilePreview
263 key={`${opening.count}:${filePreviewKey(source)}`}
264 source={source}
265 onRequestClose={props.onRequestClose}
266 progressiveGallery={props.progressiveGallery}
267 Viewer={props.Viewer}
268 onPresent={onPresent}
269 {...(props.onOpenError ? { onOpenError: props.onOpenError } : {})}
270 />
271 );