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