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