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