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

attachmentDocument.ts

181 lines7.3 KB

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;
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);
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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the in-flight attachment share download when the component unmounts
88 useEffect(() => () => shareController.current?.abort(), []);
89 const resource = {
90 _tag: "attachment" as const,
91 attachmentId: input.attachmentId,
92 fileName: input.name,
93 mimeType: input.mimeType,
94 disposition: "inline" as const,
95 };
96 const environmentId = input.attachment ? null : input.environmentId;
97 const refresh = useRefreshAssetUrl(environmentId, resource);
98 const [rendered, setRendered] = useState(true);
99 const [revision, setRevision] = useState(0);
100 const [sharing, setSharing] = useState(false);
101 const attachment = input.attachment;
102 const localPreviewAtom = localAttachmentPreviewAtom(attachment);
103 const localPreview = localAttachmentPreviewState(useAtomValue(localPreviewAtom));
104 const refreshLocalPreview = useAtomRefresh(localPreviewAtom);
105 const remote = useFreshAssetUrl(environmentId, attachment ? null : resource, revision);
106 const remoteUrl = AsyncResult.isSuccess(remote) && !remote.waiting ? remote.value : null;
107 const uri = attachment ? localPreview.uri : (remoteUrl?.url ?? null);
108 const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
109 const text = useAtomValue(
110 uri && needsText
111 ? attachmentTextAtom({
112 uri,
113 authorizedAt: remoteUrl?.authorizedAt ?? null,
114 environmentId,
115 resource,
116 sizeBytes: input.sizeBytes,
117 revision,
118 })
119 : noAttachmentText,
120 );
121 const content = AsyncResult.isSuccess(text) ? text.value : null;
122 const contentError = AsyncResult.isFailure(text)
123 ? (Option.getOrNull(AsyncResult.error(text))?.message ?? "Could not read this file.")
124 : null;
125 const table = content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null;
126 const presentation = attachmentDocumentPresentation({
127 kind,
128 hasTable: table !== null,
129 hasEnvironment: input.environmentId !== null,
130 rendered,
131 });
132 const error = attachment
133 ? localPreview.error && (localPreview.error.message || "The local file is unavailable.")
134 : AsyncResult.isFailure(remote)
135 ? (Option.getOrNull(AsyncResult.error(remote))?.message ?? "The attachment is unavailable.")
136 : null;
137 const share = async () => {
138 if (!uri || sharing) return;
139 setSharing(true);
140 const controller = new AbortController();
141 shareController.current = controller;
142 const request = {
143 attachment: { name: input.name, mimeType: input.mimeType },
144 signal: controller.signal,
145 };
146 const result = await settlePromise(async () => {
147 if (isLocalUri(uri)) await shareLocalAttachment({ ...request, uri });
148 else await downloadAndShareAttachment({ ...request, url: (await refresh()) ?? uri });
149 });
150 if (shareController.current === controller) shareController.current = null;
151 if (controller.signal.aborted) return;
152 setSharing(false);
153 if (AsyncResult.isFailure(result)) {
154 const cause = squashAtomCommandFailure(result);
155 Dialog.alert(
156 "Could not share file",
157 cause instanceof Error ? cause.message : "Please try again.",
158 );
159 }
160 };
161 return {
162 kind,
163 ...presentation,
164 uri,
165 /** Native viewers resolve their own fresh URL from this instead of reusing `uri`. */
166 resource,
167 content,
168 table,
169 error: error ?? contentError,
170 needsText,
171 rendered,
172 setRendered,
173 revision,
174 retry: () => {
175 setRevision((value) => value + 1);
176 if (attachment) refreshLocalPreview();
177 },
178 share,
179 sharing,
180 };