Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { msg, T, useGT } from "gt-react";
3import { useEffect, useState } from "react";
4
5import { m } from "~/i18n/messages";
6
7import { useTheme } from "~/hooks/useTheme";
8
9import { FileSurfaceLoading } from "./fileSurfaceChrome";
10
11const MAX_FONT_BYTES = 10 * 1024 * 1024;
12
13async function readFont(src: string, signal: AbortSignal) {
14 const response = await fetch(src, { signal });
15 if (!response.ok) throw new Error(m(msg("The font could not be loaded.")));
16 if (Number(response.headers.get("content-length")) > MAX_FONT_BYTES)
17 throw new Error(m(msg("Font previews are limited to 10 MB.")));
18 const reader = response.body?.getReader();
19 if (!reader) throw new Error(m(msg("The font is unavailable.")));
20 const chunks: Uint8Array<ArrayBuffer>[] = [];
21 let length = 0;
22 try {
23 while (true) {
24 const { done, value } = await reader.read();
25 if (done) break;
26 length += value.length;
27 if (length > MAX_FONT_BYTES) throw new Error(m(msg("Font previews are limited to 10 MB.")));
28 chunks.push(value);
29 }
30 } finally {
31 await reader.cancel();
32 }
33 const blob = new Blob(chunks);
34 await new FontFace("file-preview", await blob.arrayBuffer()).load();
35 return await new Promise<string>((resolve, reject) => {
36 const reader = new FileReader();
37 reader.addEventListener("load", () => resolve(String(reader.result)), { once: true });
38 reader.addEventListener(
39 "error",
40 () => reject(new Error(m(msg("The font could not be decoded.")))),
41 { once: true },
42 );
43 reader.readAsDataURL(blob);
44 });
45}
46
47const fontColors = (style = getComputedStyle(document.documentElement)) =>
48 [style.getPropertyValue("--background"), style.getPropertyValue("--foreground")] as const;
49
50export default function FontViewer(props: { readonly src: string; readonly name: string }) {
51 const gt = useGT();
52 const { theme, resolvedTheme, themeHalves } = useTheme();
53 const [[background, foreground], setColors] = useState(fontColors);
54 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Read the host DOM's applied theme tokens so the sandboxed font preview receives the current palette.
55 useEffect(() => {
56 // oxlint-disable-next-line react/set-state-in-effect -- Read tokens after useTheme applies the selected palette.
57 setColors(fontColors());
58 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Theme values invalidate the palette read from the host DOM.
59 }, [theme, resolvedTheme, themeHalves]);
60 const [data, setData] = useState<string | null>(null);
61 const [error, setError] = useState<string | null>(null);
62 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Load the font from its URL and abort the request and timeout when the source changes or unmounts.
63 useEffect(() => {
64 const controller = new AbortController();
65 const timeout = setTimeout(() => {
66 setError(m(msg("The font took too long to load.")));
67 controller.abort();
68 }, 30_000);
69 void readFont(props.src, controller.signal)
70 .then((value) => {
71 if (!controller.signal.aborted) setData(value);
72 })
73 .catch((cause: unknown) => {
74 if (!controller.signal.aborted)
75 setError(thrownErrorMessage(cause, m) ?? m(msg("The font is damaged or unsupported.")));
76 })
77 .finally(() => clearTimeout(timeout));
78 return () => {
79 controller.abort();
80 clearTimeout(timeout);
81 };
82 }, [props.src]);
83 if (error)
84 return (
85 <div
86 role="alert"
87 className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center"
88 >
89 <p className="text-sm font-medium">
90 <T>No preview for this file</T>
91 </p>
92 <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
93 {gt`${{ error }} Save it to open in another app.`}
94 </p>
95 </div>
96 );
97 if (!data) return <FileSurfaceLoading />;
98 const escapeHtml = (text: string) =>
99 text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
100 const heading = escapeHtml(gt`Font preview`);
101 const sample = escapeHtml(gt`The quick brown fox jumps over the lazy dog.`);
102 const srcDoc = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><style>@font-face{font-family:preview;src:url('${data}')}html{color-scheme:${resolvedTheme};background:${background};color:${foreground}}body{margin:0;padding:32px;font-family:preview;overflow-wrap:anywhere}h1{font-size:40px;font-weight:normal}p{line-height:1.4}small{font:12px monospace;display:block;opacity:.6;margin-bottom:8px}</style></head><body><h1>${heading}</h1><p style="font-size:24px">ABCDEFGHIJKLMNOPQRSTUVWXYZ<br>abcdefghijklmnopqrstuvwxyz<br>0123456789 !?&@#%(){}[]</p>${[12, 16, 24, 40, 64].map((size) => `<p style="font-size:${size}px"><small>${size} px</small>${sample}</p>`).join("")}</body></html>`;
103 return (
104 <iframe title={props.name} srcDoc={srcDoc} sandbox="" className="min-h-0 flex-1 border-0" />
105 );
106}