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