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