@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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