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