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

AttachmentFilePreview.tsx

354 lines13.6 KB

1import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
2import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
3import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
4import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
5import { settlePromise } from "@t3tools/client-runtime/state/runtime";
6import * as AsyncResult from "effect/reactivity/AsyncResult";
7import * as Cause from "effect/Cause";
8import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
9import { ChevronRightIcon, DownloadIcon, Trash2Icon, WrapTextIcon, XIcon } from "lucide-react";
10import { Check, Code2, Copy, Eye, Table2 } from "lucide";
11import { lazy, Suspense, useEffect, useRef, useState } from "react";
12​
13import { useAssetUrlRefresh } from "~/assets/assetUrls";
14import ChatMarkdown from "~/components/ChatMarkdown";
15import { MorphIcon } from "~/components/MorphIcon";
16import { ScrollArea } from "~/components/ui/scroll-area";
17import { toastManager } from "~/components/ui/toast";
18import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
19import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
20import { cn } from "~/lib/utils";
21​
22import { AudioPreview } from "./AudioPreview";
23import { BrowserDocumentFrame } from "./BrowserDocumentFrame";
24import { DelimitedTablePreview } from "./DelimitedTablePreview";
25import {
26 FILE_SURFACE_SUBHEADER_CLASS,
27 FileSurfaceAction,
28 FileSurfaceFailure,
29 FileSurfaceLoading,
30 FileSurfaceNotice,
31} from "./fileSurfaceChrome";
32​
33const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
34​
35const STALE_URL_MS = 5 * 60_000;
36​
37export function ReadOnlySourcePreview(props: { name: string; text: string }) {
38 return (
39 <Suspense fallback={<FileSurfaceLoading className="p-4" />}>
40 <SourcePreview {...props} />
41 </Suspense>
42 );
44​
45function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {
46 if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";
47 if (mode === "table") return rendered ? "Show source" : "Show table";
48 return rendered ? "Show HTML source" : "Show rendered page";
50​
51// useAssetUrlRefresh keys its callback on these objects, so they must stay cached.
52function useAttachmentResources(
53 attachmentId: string | undefined,
54 fileName: string,
55 mimeType: string,
56) {
57 "use memo";
58 const resource = attachmentId
59 ? {
60 _tag: "attachment" as const,
61 attachmentId,
62 fileName,
63 mimeType,
64 disposition: "inline" as const,
65 }
66 : null;
67 const downloadResource = resource ? { ...resource, disposition: "attachment" as const } : null;
68 return { resource, downloadResource };
70​
71export function AttachmentFilePreview(props: {
72 name: string;
73 mimeType: string;
74 sizeBytes: number;
75 file?: Blob | null;
76 asset?: { environmentId: EnvironmentId; attachmentId: string };
77 htmlRender?: boolean;
78 threadRef?: ScopedThreadRef;
79 origin?: string;
80 onRemove?: () => void;
81 onClose?: () => void;
82}) {
83 const kind = filePreviewKind(props);
84 const delimiter = filePreviewDelimiter(props);
85 const renderedMode =
86 kind === "markdown" ? "markdown" : kind === "html" ? "html" : delimiter ? "table" : null;
87 const attachmentId = props.asset?.attachmentId;
88 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: props.name });
89 const { resource, downloadResource } = useAttachmentResources(
90 attachmentId,
91 props.name,
92 props.mimeType,
93 );
94 const refresh = useAssetUrlRefresh(
95 props.file ? null : (props.asset?.environmentId ?? null),
96 props.file ? null : resource,
97 );
98 const prepareDownload = useAssetUrlRefresh(props.asset?.environmentId ?? null, downloadResource);
99 const [saving, setSaving] = useState(false);
100 const [localUrl, setLocalUrl] = useState<string | null>(null);
101 const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
102 const [rendered, setRendered] = useState(true);
103 const [revision, setRevision] = useState(0);
104 const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
105 const [error, setError] = useState<string | null>(null);
106 const [contentError, setContentError] = useState<string | null>(null);
107 const authorizedAt = useRef(0);
108 useEffect(() => {
109 if (!props.file) return;
110 const url = URL.createObjectURL(props.file);
111 // oxlint-disable-next-line react/set-state-in-effect -- Publish an object URL only after its cleanup is registered for this Blob.
112 setLocalUrl(url);
113 return () => URL.revokeObjectURL(url);
114 }, [props.file]);
115 useEffect(() => {
116 if (props.file) return;
117 let cancelled = false;
118 // oxlint-disable-next-line react/set-state-in-effect -- A new preview request clears its previous URL and error.
119 setRemoteUrl(null);
120 setError(null);
121 void refresh()
122 .then((url) => {
123 if (cancelled) return;
124 if (!url) throw new Error("Reconnect to the environment and try again.");
125 authorizedAt.current = Date.now();
126 setRemoteUrl(url);
127 })
128 .catch((cause: unknown) => {
129 if (!cancelled)
130 setError(cause instanceof Error ? cause.message : "The attachment is unavailable.");
131 });
132 return () => {
133 cancelled = true;
134 };
135 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
136 }, [props.file, refresh, revision]);
137 const url = props.file ? localUrl : remoteUrl;
138 const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
139 useEffect(() => {
140 if (!needsText || !url) return;
141 const controller = new AbortController();
142 // oxlint-disable-next-line react/set-state-in-effect -- A new external resource must clear the previous response before loading.
143 setContent(null);
144 setContentError(null);
145 const file = props.file;
146 void (async () => {
147 if (!file && Date.now() - authorizedAt.current > STALE_URL_MS) {
148 const target = await refresh();
149 if (controller.signal.aborted) return;
150 if (!target) throw new Error("Reconnect to the environment and try again.");
151 authorizedAt.current = Date.now();
152 if (target !== url) {
153 setRemoteUrl(target);
154 return;
155 }
156 }
157 const response = file
158 ? { ok: true, body: file.stream() }
159 : await fetch(url, {
160 signal: controller.signal,
161 ...(props.sizeBytes > 0
162 ? { headers: { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } }
163 : {}),
164 cache: revision === 0 ? "default" : "reload",
165 });
166 const result = await readFilePreviewResponse(response, controller.signal);
167 if (!controller.signal.aborted) setContent(result);
168 })().catch((cause: unknown) => {
169 if (!controller.signal.aborted)
170 setContentError(cause instanceof Error ? cause.message : "Could not load this file.");
171 });
172 return () => controller.abort();
173 }, [url, needsText, revision, props.sizeBytes, props.file, refresh]);
174 const failure = error ?? (needsText ? contentError : null);
175 const wordWrap = useClientSettings((settings) => settings.wordWrap);
176 const updateClientSettings = useUpdateClientSettings();
177 const showsRawText =
178 failure === null &&
179 needsText &&
180 content !== null &&
181 !(delimiter && rendered) &&
182 !(kind === "markdown" && rendered);
183​
184 const save = () => {
185 setSaving(true);
186 void settlePromise(async () => {
187 let file = props.file;
188 if (!file) {
189 const target = await prepareDownload();
190 if (!target) throw new Error("Reconnect to the environment and try again.");
191 const response = await fetch(target);
192 if (!response.ok) throw new Error("The file could not be loaded. Try again.");
193 file = await response.blob();
194 }
195 // A Blob keeps cross-origin downloads inside the desktop client instead of
196 // navigating its custom app scheme to an external browser.
197 const downloadUrl = URL.createObjectURL(file);
198 // Scheduled before the click so the URL is revoked even if the click throws.
199 setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000);
200 const anchor = document.createElement("a");
201 anchor.href = downloadUrl;
202 anchor.download = props.name;
203 anchor.click();
204 }).then((result) => {
205 if (!AsyncResult.isSuccess(result)) {
206 const cause = Cause.squash(result.cause);
207 toastManager.add({
208 type: "error",
209 title: "Could not save file",
210 description: cause instanceof Error ? cause.message : "Please try again.",
211 });
212 }
213 setSaving(false);
214 });
215 };
216​
217 const body = failure ? (
218 <FileSurfaceFailure
219 message={failure}
220 onRetry={() => {
221 setError(null);
222 setRevision((value) => value + 1);
223 }}
224 />
225 ) : !url || (needsText && !content) ? (
226 <FileSurfaceLoading />
227 ) : needsText && content ? (
228 delimiter && rendered ? (
229 <DelimitedTablePreview name={props.name} text={content.text} delimiter={delimiter} />
230 ) : kind === "markdown" && rendered ? (
231 <ScrollArea className="min-h-0 flex-1">
232 <ChatMarkdown text={content.text} cwd={undefined} className="mx-auto max-w-4xl px-6 py-5" />
233 </ScrollArea>
234 ) : (
235 <ReadOnlySourcePreview name={props.name} text={content.text} />
236 )
237 ) : kind === "pdf" || kind === "html" ? (
238 <BrowserDocumentFrame
239 src={url}
240 title={props.name}
241 pdf={kind === "pdf"}
242 htmlRender={props.htmlRender === true}
243 threadRef={props.threadRef}
244 />
245 ) : kind === "audio" ? (
246 <AudioPreview src={url} name={props.name} onError={() => setError("Unable to load audio.")} />
247 ) : kind === "video" ? (
248 <div className="flex min-h-0 flex-1 items-center justify-center bg-black">
249 <video
250 controls
251 playsInline
252 src={url}
253 aria-label={props.name}
254 className="max-h-full max-w-full"
255 onError={() => setError("Unable to load video.")}
256 />
257 </div>
258 ) : kind === "image" ? (
259 // oxlint-disable-next-line t3code/require-centered-scroll-gutter -- The image is capped at max-h-full max-w-full, so this never scrolls.
260 <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
261 <img
262 src={url}
263 alt={props.name}
264 className="max-h-full max-w-full object-contain"
265 onError={() => setError("Unable to load image.")}
266 />
267 </div>
268 ) : (
269 <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center">
270 <p className="text-sm font-medium">No preview for this file</p>
271 <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
272 Save it to open in an app that supports {props.name.split(".").at(-1) || "this format"}{" "}
273 files.
274 </p>
275 </div>
276 );
277​
278 return (
279 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
280 <div className={cn(FILE_SURFACE_SUBHEADER_CLASS)} data-surface-subheader>
281 <div className="flex min-w-0 flex-1 items-center text-xs">
282 <span className="shrink-0 px-0.5 text-muted-foreground">
283 {props.origin ?? "Attachment"}
284 </span>
285 <ChevronRightIcon className="mx-1 size-3.5 shrink-0 text-muted-foreground/60" />
286 <span aria-current="page" className="min-w-0 truncate px-0.5 font-medium text-foreground">
287 {props.name}
288 </span>
289 {props.sizeBytes > 0 ? (
290 <span className="ml-2 shrink-0 text-muted-foreground">
291 {formatAttachmentSize(props.sizeBytes)}
292 </span>
293 ) : null}
294 </div>
295 {renderedMode ? (
296 <FileSurfaceAction
297 label={renderedToggleLabel(renderedMode, rendered)}
298 pressed={rendered}
299 onPress={() => setRendered((value) => !value)}
300 >
301 <MorphIcon
302 className="size-3.5"
303 icon={rendered ? Code2 : renderedMode === "table" ? Table2 : Eye}
304 />
305 </FileSurfaceAction>
306 ) : null}
307 {showsRawText ? (
308 <FileSurfaceAction
309 label={wordWrap ? "Disable word wrap" : "Enable word wrap"}
310 pressed={wordWrap}
311 onPress={() => updateClientSettings({ wordWrap: !wordWrap })}
312 >
313 <WrapTextIcon className="size-3.5" />
314 </FileSurfaceAction>
315 ) : null}
316 {content ? (
317 <FileSurfaceAction
318 label={isCopied ? "Copied" : content.truncated ? "Copy preview" : "Copy contents"}
319 onPress={() => copyToClipboard(content.text, undefined)}
320 >
321 <MorphIcon className="size-3.5" icon={isCopied ? Check : Copy} />
322 </FileSurfaceAction>
323 ) : null}
324 {url ? (
325 <FileSurfaceAction
326 label={saving ? "Preparing file…" : "Save file"}
327 disabled={saving}
328 onPress={save}
329 >
330 <DownloadIcon className="size-3.5" />
331 </FileSurfaceAction>
332 ) : null}
333 {props.onRemove ? (
334 <FileSurfaceAction label="Remove from draft" onPress={props.onRemove}>
335 <Trash2Icon className="size-3.5" />
336 </FileSurfaceAction>
337 ) : null}
338 {props.onClose ? (
339 <FileSurfaceAction label="Close" onPress={props.onClose}>
340 <XIcon className="size-3.5" />
341 </FileSurfaceAction>
342 ) : null}
343 </div>
344 {content?.truncated ? (
345 <FileSurfaceNotice>
346 Preview limited to the first 1 MB
347 {props.sizeBytes > 0 ? ` of a ${props.sizeBytes.toLocaleString()} byte file` : ""}. Save
348 the file to read it in full.
349 </FileSurfaceNotice>
350 ) : null}
351 {body}
352 </div>
353 );