Open History to see the last commit
1import * as Dialog from "../components/ui/Dialog";
2import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
3import type { EnvironmentId } from "@t3tools/contracts";
4import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
5import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
6import { fetch } from "expo/fetch";
7import { File } from "expo-file-system";
8import { useEffect, useMemo, useRef, useState } from "react";
9
10import type { FileBackedComposerAttachment } from "./composerImages";
11import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
12import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload";
13import { useRefreshAssetUrl } from "../state/assets";
14import { attachmentDocumentPresentation } from "./attachmentDocumentPresentation";
15
16const isLocalUri = (uri: string) => /^(file|content):/.test(uri);
17
18/** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */
19const STALE_URL_MS = 5 * 60_000;
20
21/**
22 * Captured bytes never resolve against the workspace.
23 */
24export function useAttachmentDocument(input: {
25 readonly name: string;
26 readonly mimeType: string;
27 readonly sizeBytes: number;
28 readonly attachmentId: string;
29 readonly environmentId: EnvironmentId | null;
30 readonly attachment: FileBackedComposerAttachment | null;
31}) {
32 const kind = filePreviewKind(input);
33 const delimiter = filePreviewDelimiter(input);
34 const shareController = useRef<AbortController | null>(null);
35 useEffect(() => () => shareController.current?.abort(), []);
36 const resource = useMemo(
37 () => ({
38 _tag: "attachment" as const,
39 attachmentId: input.attachmentId,
40 fileName: input.name,
41 mimeType: input.mimeType,
42 disposition: "inline" as const,
43 }),
44 [input.attachmentId, input.name, input.mimeType],
45 );
46 const environmentId = input.attachment ? null : input.environmentId;
47 const refresh = useRefreshAssetUrl(environmentId, resource);
48 const [localUri, setLocalUri] = useState<string | null>(null);
49 const [remoteUri, setRemoteUri] = useState<string | null>(null);
50 const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
51 const table = useMemo(
52 () => (content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null),
53 [content, delimiter],
54 );
55 const [error, setError] = useState<string | null>(null);
56 const [contentError, setContentError] = useState<string | null>(null);
57 const textReadUrl = useRef<{ uri: string; authorizedAt: number } | null>(null);
58 const [rendered, setRendered] = useState(true);
59 const presentation = attachmentDocumentPresentation({
60 kind,
61 hasTable: table !== null,
62 hasEnvironment: input.environmentId !== null,
63 rendered,
64 });
65 const [revision, setRevision] = useState(0);
66 const [sharing, setSharing] = useState(false);
67 const uri = input.attachment ? localUri : remoteUri;
68 const attachment = input.attachment;
69 useEffect(() => {
70 if (attachment) return;
71 let cancelled = false;
72 // Await a fresh signed URL: cached links can expire while the client is suspended.
73 // oxlint-disable-next-line react/set-state-in-effect -- A new preview request clears its previous URL and error.
74 setRemoteUri(null);
75 setError(null);
76 textReadUrl.current = null;
77 void refresh()
78 .then((url) => {
79 if (cancelled) return;
80 if (!url) throw new Error("Reconnect to this environment and try again.");
81 textReadUrl.current = { uri: url, authorizedAt: Date.now() };
82 setRemoteUri(url);
83 })
84 .catch((cause: unknown) => {
85 if (!cancelled)
86 setError(cause instanceof Error ? cause.message : "The attachment is unavailable.");
87 });
88 return () => {
89 cancelled = true;
90 };
91 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
92 }, [attachment, refresh, revision]);
93 useEffect(() => {
94 if (!attachment) return;
95 // A new attachment must not keep the previous file behind it: `share()` would otherwise
96 // send the old bytes under the new name if this load fails.
97 // oxlint-disable-next-line react/set-state-in-effect -- A new attachment invalidates the last one.
98 setLocalUri(null);
99 setContent(null);
100 setContentError(null);
101 const controller = new AbortController();
102 let release: (() => void) | undefined;
103 void loadLocalAttachmentPreview(attachment, controller.signal)
104 .then((file) => {
105 if (!file) return;
106 if (controller.signal.aborted) return file.dispose();
107 release = file.dispose;
108 setLocalUri(file.uri);
109 setError(null);
110 })
111 .catch((cause: unknown) => {
112 if (!controller.signal.aborted)
113 setError(cause instanceof Error ? cause.message : "The local file is unavailable.");
114 });
115 return () => {
116 controller.abort();
117 release?.();
118 };
119 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reacquire a local file lease after a failed load.
120 }, [attachment, revision]);
121 const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
122 const sizeBytes = input.sizeBytes;
123 useEffect(() => {
124 if (!uri || !needsText) return;
125 const controller = new AbortController();
126 // oxlint-disable-next-line react/set-state-in-effect -- A new external resource must clear the previous response before loading.
127 setContent(null);
128 setContentError(null);
129 const response = isLocalUri(uri)
130 ? Promise.resolve().then(() => ({ ok: true, body: new File(uri).readableStream() }))
131 : (async () => {
132 // A signed URL minted when the file opened may have expired by the time the user
133 // switches to source; reauthorize before fetching instead of reading a stale link.
134 const authorized = textReadUrl.current;
135 let target = authorized?.uri ?? uri;
136 if (!authorized || Date.now() - authorized.authorizedAt > STALE_URL_MS) {
137 const refreshed = await refresh();
138 if (!refreshed) throw new Error("Reconnect to this environment and try again.");
139 target = refreshed;
140 if (!controller.signal.aborted) {
141 // Keep the source-read URL and its age together without restarting active media.
142 textReadUrl.current = { uri: refreshed, authorizedAt: Date.now() };
143 }
144 }
145 return fetch(target, {
146 signal: controller.signal,
147 headers: {
148 ...(sizeBytes > 0 ? { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } : {}),
149 ...(revision > 0 ? { "Cache-Control": "no-cache" } : {}),
150 },
151 });
152 })();
153 void response
154 .then((value) => readFilePreviewResponse(value, controller.signal))
155 .then((value) => {
156 if (!controller.signal.aborted) setContent(value);
157 })
158 .catch((cause: unknown) => {
159 if (!controller.signal.aborted)
160 setContentError(cause instanceof Error ? cause.message : "Could not read this file.");
161 });
162 return () => controller.abort();
163 }, [uri, needsText, revision, sizeBytes, refresh]);
164 const share = async () => {
165 if (!uri || sharing) return;
166 setSharing(true);
167 const controller = new AbortController();
168 shareController.current = controller;
169 const request = {
170 attachment: { name: input.name, mimeType: input.mimeType },
171 signal: controller.signal,
172 };
173 try {
174 if (isLocalUri(uri)) await shareLocalAttachment({ ...request, uri });
175 else await downloadAndShareAttachment({ ...request, url: (await refresh()) ?? uri });
176 } catch (cause) {
177 if (controller.signal.aborted) return;
178 Dialog.alert(
179 "Could not share file",
180 cause instanceof Error ? cause.message : "Please try again.",
181 );
182 } finally {
183 if (shareController.current === controller) shareController.current = null;
184 if (!controller.signal.aborted) setSharing(false);
185 }
186 };
187 return {
188 kind,
189 ...presentation,
190 uri,
191 /** Native viewers resolve their own fresh URL from this instead of reusing `uri`. */
192 resource,
193 content,
194 table,
195 error: error ?? (needsText ? contentError : null),
196 needsText,
197 rendered,
198 setRendered,
199 revision,
200 retry: () => setRevision((value) => value + 1),
201 share,
202 sharing,
203 };
204}