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