Open History to see the last commit
1import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import { Atom, AsyncResult } from "effect/reactivity";
3import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import * as Dialog from "../components/ui/Dialog";
5import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
6import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
7import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
8import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
9import { fetch } from "expo/fetch";
10import { File } from "expo-file-system";
11import * as Effect from "effect/Effect";
12import * as Option from "effect/Option";
13import { useEffect, useRef, useState } from "react";
14
15import type { FileBackedComposerAttachment } from "./composerImages";
16import { localAttachmentPreviewAtom, localAttachmentPreviewState } from "./localAttachmentPreview";
17import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload";
18import { refreshAssetUrl, useFreshAssetUrl, useRefreshAssetUrl } from "../state/assets";
19import { attachmentDocumentPresentation } from "./attachmentDocumentPresentation";
20
21const isLocalUri = (uri: string) => /^(file|content):/.test(uri);
22
23/** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */
24const STALE_URL_MS = 5 * 60_000;
25
26interface AttachmentTextKey {
27 readonly uri: string;
28 /** When a remote `uri` was signed; null for local files. */
29 readonly authorizedAt: number | null;
30 readonly environmentId: EnvironmentId | null;
31 readonly resource: AssetResource;
32 readonly sizeBytes: number;
33 readonly revision: number;
34}
35
36async function readAttachmentText(key: AttachmentTextKey, signal: AbortSignal) {
37 if (isLocalUri(key.uri)) {
38 return readFilePreviewResponse({ ok: true, body: new File(key.uri).readableStream() }, signal);
39 }
40 // Reauthorize before source reads; the opening URL may have expired.
41 let target = key.uri;
42 if (key.authorizedAt === null || Date.now() - key.authorizedAt > STALE_URL_MS) {
43 const refreshed =
44 key.environmentId === null
45 ? null
46 : await refreshAssetUrl(key.environmentId, key.resource, signal);
47 if (!refreshed) throw new Error("Reconnect to this environment and try again.");
48 target = refreshed;
49 }
50 const response = await fetch(target, {
51 signal,
52 headers: {
53 ...(key.sizeBytes > 0 ? { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } : {}),
54 ...(key.revision > 0 ? { "Cache-Control": "no-cache" } : {}),
55 },
56 });
57 return readFilePreviewResponse(response, signal);
58}
59
60// Plain-object keys compare structurally (Effect `Equal`/`Hash`). Unmounting the
61// last reader interrupts the read, which aborts the fetch.
62const attachmentTextAtom = Atom.family((key: AttachmentTextKey) =>
63 Atom.make(
64 Effect.tryPromise({
65 try: (signal) => readAttachmentText(key, signal),
66 catch: (cause) => (cause instanceof Error ? cause : new Error("Could not read this file.")),
67 }),
68 ).pipe(Atom.withLabel("attachment-text")),
69);
70
71const noAttachmentText = Atom.make(
72 AsyncResult.initial<{ text: string; truncated: boolean }, Error>(),
73).pipe(Atom.withLabel("attachment-text:none"));
74
75/** Captured bytes never resolve against the workspace. */
76export function useAttachmentDocument(input: {
77 readonly name: string;
78 readonly mimeType: string;
79 readonly sizeBytes: number;
80 readonly attachmentId: string;
81 readonly environmentId: EnvironmentId | null;
82 readonly attachment: FileBackedComposerAttachment | null;
83}) {
84 const kind = filePreviewKind(input, { richDocuments: false });
85 const delimiter = filePreviewDelimiter(input);
86 const shareController = useRef<AbortController | null>(null);
87 useEffect(() => () => shareController.current?.abort(), []);
88 const resource = {
89 _tag: "attachment" as const,
90 attachmentId: input.attachmentId,
91 fileName: input.name,
92 mimeType: input.mimeType,
93 disposition: "inline" as const,
94 };
95 const environmentId = input.attachment ? null : input.environmentId;
96 const refresh = useRefreshAssetUrl(environmentId, resource);
97 const [rendered, setRendered] = useState(true);
98 const [revision, setRevision] = useState(0);
99 const [sharing, setSharing] = useState(false);
100 const attachment = input.attachment;
101 const localPreviewAtom = localAttachmentPreviewAtom(attachment);
102 const localPreview = localAttachmentPreviewState(useAtomValue(localPreviewAtom));
103 const refreshLocalPreview = useAtomRefresh(localPreviewAtom);
104 const remote = useFreshAssetUrl(environmentId, attachment ? null : resource, revision);
105 const remoteUrl = AsyncResult.isSuccess(remote) && !remote.waiting ? remote.value : null;
106 const uri = attachment ? localPreview.uri : (remoteUrl?.url ?? null);
107 const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
108 const text = useAtomValue(
109 uri && needsText
110 ? attachmentTextAtom({
111 uri,
112 authorizedAt: remoteUrl?.authorizedAt ?? null,
113 environmentId,
114 resource,
115 sizeBytes: input.sizeBytes,
116 revision,
117 })
118 : noAttachmentText,
119 );
120 const content = AsyncResult.isSuccess(text) ? text.value : null;
121 const contentError = AsyncResult.isFailure(text)
122 ? (Option.getOrNull(AsyncResult.error(text))?.message ?? "Could not read this file.")
123 : null;
124 const table = content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null;
125 const presentation = attachmentDocumentPresentation({
126 kind,
127 hasTable: table !== null,
128 hasEnvironment: input.environmentId !== null,
129 rendered,
130 });
131 const error = attachment
132 ? localPreview.error && (localPreview.error.message || "The local file is unavailable.")
133 : AsyncResult.isFailure(remote)
134 ? (Option.getOrNull(AsyncResult.error(remote))?.message ?? "The attachment is unavailable.")
135 : null;
136 const share = async () => {
137 if (!uri || sharing) return;
138 setSharing(true);
139 const controller = new AbortController();
140 shareController.current = controller;
141 const request = {
142 attachment: { name: input.name, mimeType: input.mimeType },
143 signal: controller.signal,
144 };
145 const result = await settlePromise(async () => {
146 if (isLocalUri(uri)) await shareLocalAttachment({ ...request, uri });
147 else await downloadAndShareAttachment({ ...request, url: (await refresh()) ?? uri });
148 });
149 if (shareController.current === controller) shareController.current = null;
150 if (controller.signal.aborted) return;
151 setSharing(false);
152 if (AsyncResult.isFailure(result)) {
153 const cause = squashAtomCommandFailure(result);
154 Dialog.alert(
155 "Could not share file",
156 cause instanceof Error ? cause.message : "Please try again.",
157 );
158 }
159 };
160 return {
161 kind,
162 ...presentation,
163 uri,
164 /** Native viewers resolve their own fresh URL from this instead of reusing `uri`. */
165 resource,
166 content,
167 table,
168 error: error ?? contentError,
169 needsText,
170 rendered,
171 setRendered,
172 revision,
173 retry: () => {
174 setRevision((value) => value + 1);
175 if (attachment) refreshLocalPreview();
176 },
177 share,
178 sharing,
179 };
180}