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

FilePreviewSession.tsx

226 lines8.5 KB

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