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