Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(file): preview font files in themselves
Elian Doran4026ab6fad37
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex f8493e80a9..8b74588d74 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1610,6 +1610,14 @@"unit_kmh": "{{value}} km/h","unit_mph": "{{value}} mph"},+ "font_preview": {+ "pangram": "The quick brown fox jumps over the lazy dog",+ "specimen_placeholder": "Type to preview your own text…",+ "size": "Preview size",+ "size_pixels": "{{size}} px",+ "sizes": "Sizes",+ "characters": "Characters"+ },"media": {"play": "Play","activate": "Play {{- title}}",diff --git a/apps/client/src/widgets/type_widgets/File.css b/apps/client/src/widgets/type_widgets/File.cssindex c3303032cb..cc2033b5c3 100644--- a/apps/client/src/widgets/type_widgets/File.css+++ b/apps/client/src/widgets/type_widgets/File.css@@ -44,8 +44,10 @@ pre.file-preview-content:not(.hljs) {/* base .office-preview-body / .office-preview-loading styles live in content_renderer.css.The unpadded wrapper is the scroll host (like .scrolling-container for text notes):the scrollbar hugs the split edge and the body's padding scrolls with the document.- The GPX preview needs the same: a file note is full-height, so nothing above scrolls for it. */+ The GPX and font previews need the same: a file note is full-height, so nothing above scrolls+ for them. */.note-detail-file:has(> .office-preview-body),+.note-detail-file:has(> .font-preview),.note-detail-file:has(> .gpx-preview) {overflow: auto;padding: 0;diff --git a/apps/client/src/widgets/type_widgets/File.spec.tsx b/apps/client/src/widgets/type_widgets/File.spec.tsxindex 486cead826..c52c261588 100644--- a/apps/client/src/widgets/type_widgets/File.spec.tsx+++ b/apps/client/src/widgets/type_widgets/File.spec.tsx@@ -18,6 +18,12 @@ vi.mock("../react/ActionButton", () => ({ default: () => <button class="code-blo// the module graph; the markers let FileTypeWidget's mime routing be asserted without rendering them.vi.mock("../react/hooks", () => ({ useNoteBlob: vi.fn(() => null) }));vi.mock("./file/MediaPreview", () => ({ default: () => <div class="media-preview-stub" /> }));+// Only the rendered preview is stubbed here — `isFontMimeType`, which the routing below is+// asserted on, stays the real one.+vi.mock("./file/FontPreview", async () => ({+ ...await vi.importActual<typeof import("./file/FontPreview")>("./file/FontPreview"),+ default: () => <div class="font-preview-stub" />+}));vi.mock("./file/Office", () => ({ default: () => <div class="office-preview-stub" /> }));vi.mock("./file/Pdf", () => ({ default: () => <div class="pdf-preview-stub" /> }));@@ -56,7 +62,7 @@ describe("FileTypeWidget", () => {expect(applySingleBlockSyntaxHighlight.mock.calls[0][1]).toBe("text-xml");});- it("routes non-text blobs by mime: PDF, media, and a no-preview fallback", () => {+ it("routes non-text blobs by mime: PDF, media, fonts, and a no-preview fallback", () => {// mockReturnValue outlives clearAllMocks, so drop the previous test's text blob explicitly.vi.mocked(useNoteBlob).mockReturnValue(null);@@ -69,6 +75,13 @@ describe("FileTypeWidget", () => {mount("audio/mpeg");expect(container.querySelector(".media-preview-stub")).not.toBeNull();+ mount("font/woff2");+ expect(container.querySelector(".font-preview-stub")).not.toBeNull();+ // EOT is a font the engine will not load, so it keeps the fallback.+ mount("application/vnd.ms-fontobject");+ expect(container.querySelector(".font-preview-stub")).toBeNull();+ expect(container.querySelector(".alert")).not.toBeNull();+mount("application/octet-stream");expect(container.querySelector(".media-preview-stub")).toBeNull();expect(container.querySelector(".alert")).not.toBeNull();diff --git a/apps/client/src/widgets/type_widgets/File.tsx b/apps/client/src/widgets/type_widgets/File.tsxindex 0f1737e35f..d1c78a22d1 100644--- a/apps/client/src/widgets/type_widgets/File.tsx+++ b/apps/client/src/widgets/type_widgets/File.tsx@@ -7,6 +7,7 @@ import { t } from "../../services/i18n";import Alert from "../react/Alert";import CodeBlock from "../react/CodeBlock";import { useNoteBlob } from "../react/hooks";+import FontPreview, { isFontMimeType } from "./file/FontPreview";import GpxPreview from "./file/GpxPreview";import MediaPreview from "./file/MediaPreview";import OfficePreview from "./file/Office";@@ -33,6 +34,8 @@ export default function FileTypeWidget({ note, parentComponent, noteContext, isVreturn noteContext && <PdfPreview blob={blob} note={note} componentId={parentComponent?.componentId} noteContext={noteContext} />;} else if (note.mime.startsWith("video/") || note.mime.startsWith("audio/")) {return <MediaPreview entity={note} environment="standalone" noteContext={noteContext} isVisible={isVisible} />;+ } else if (isFontMimeType(note.mime)) {+ return <FontPreview note={note} blob={blob} />;}return <NoPreview />;diff --git a/apps/client/src/widgets/type_widgets/file/FontPreview.css b/apps/client/src/widgets/type_widgets/file/FontPreview.cssnew file mode 100644index 0000000000..3afb0e4cd2--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/FontPreview.css@@ -0,0 +1,77 @@+.font-preview {+ max-width: 1000px;+ /* Its own padding rather than the wrapper's: the wrapper is the unpadded scroll host (see+ File.css), so the scrollbar hugs the split edge and this padding scrolls with the content. */+ padding: 10px;++ .font-preview-controls {+ display: flex;+ align-items: center;+ gap: 16px;+ margin-bottom: 20px;+ }++ .font-preview-specimen-input {+ flex: 1 1 auto;+ min-width: 0;+ }++ .font-preview-size {+ flex: 0 0 auto;+ display: flex;+ align-items: center;+ gap: 8px;+ }++ .font-preview-size-value {+ color: var(--muted-text-color);+ font-variant-numeric: tabular-nums;+ /* Room for the widest reading, so the slider does not shift as the value grows. */+ min-width: 5ch;+ }++ .font-preview-specimen {+ font-family: var(--font-preview-family);+ font-size: var(--font-preview-specimen-size);+ line-height: 1.15;+ overflow-wrap: anywhere;+ margin-bottom: 24px;+ }++ .font-preview-heading {+ color: var(--muted-text-color);+ font-size: 0.85em;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ margin-bottom: 10px;+ }++ .font-preview-ladder {+ display: grid;+ grid-template-columns: auto 1fr;+ gap: 12px 16px;+ align-items: baseline;+ margin-bottom: 24px;+ }++ .font-preview-ladder-size {+ color: var(--muted-text-color);+ font-size: 0.85em;+ font-variant-numeric: tabular-nums;+ text-align: right;+ }++ .font-preview-ladder-line {+ font-family: var(--font-preview-family);+ font-size: var(--font-preview-ladder-size);+ line-height: 1.3;+ overflow-wrap: anywhere;+ }++ .font-preview-characters {+ font-family: var(--font-preview-family);+ font-size: 22px;+ line-height: 1.7;+ overflow-wrap: anywhere;+ }+}diff --git a/apps/client/src/widgets/type_widgets/file/FontPreview.spec.tsx b/apps/client/src/widgets/type_widgets/file/FontPreview.spec.tsxnew file mode 100644index 0000000000..f0b6183803--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/FontPreview.spec.tsx@@ -0,0 +1,172 @@+import { render } from "preact";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// i18next is never initialized under test, so t() is rendered deterministic instead: the key with+// the interpolated values appended, e.g. "font_preview.size_pixels|36".+vi.mock("../../../services/i18n", () => ({+ t: (key: string, opts?: Record<string, unknown>) => [ key, ...Object.values(opts ?? {}) ].join("|")+}));++const { default: FontPreview, isFontMimeType } = await import("./FontPreview");++/** The faces `document.fonts` currently holds, as the stubbed registry below sees them. */+let registeredFonts: Set<FontStub>;+let fetchMock: ReturnType<typeof vi.fn>;+let container: HTMLDivElement;++/** Stands in for `FontFace`: records what it was constructed with and resolves unless the source+ * bytes say otherwise, so an undecodable file can be tested without one. */+class FontStub {+ constructor(public family: string, public source: ArrayBuffer | string) {}++ load() {+ const isUndecodable = typeof this.source !== "string" && new Uint8Array(this.source)[0] === 0xff;+ return isUndecodable ? Promise.reject(new Error("Failed to decode downloaded font.")) : Promise.resolve(this);+ }+}++beforeEach(() => {+ registeredFonts = new Set();+ fetchMock = vi.fn(async () => new Response(new Uint8Array([ 0x00, 0x01, 0x00, 0x00 ])));++ vi.stubGlobal("FontFace", FontStub);+ vi.stubGlobal("fetch", fetchMock);+ Object.defineProperty(document, "fonts", {+ configurable: true,+ value: {+ add: (font: FontStub) => registeredFonts.add(font),+ delete: (font: FontStub) => registeredFonts.delete(font)+ }+ });++ container = document.createElement("div");+ document.body.appendChild(container);+});++afterEach(() => {+ render(null, container);+ container.remove();+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++function mount({ noteId = "font1", blobId = "blobA" as string | null, isContentAvailable = true } = {}) {+ const note = { noteId, isContentAvailable: () => isContentAvailable };+ const blob = blobId ? { blobId } : null;+ const props = { note, blob } as unknown as Parameters<typeof FontPreview>[0];+ render(<FontPreview {...props} />, container);+}++/** The rendered specimen line, once the font has loaded and the preview has replaced its blank. */+async function waitForSpecimen() {+ return await vi.waitFor(() => {+ const specimen = container.querySelector<HTMLElement>(".font-preview-specimen");+ expect(specimen).not.toBeNull();+ return specimen as HTMLElement;+ });+}++describe("FontPreview", () => {+ it("renders the file in itself: the font is registered under a note-private family the specimen and ladder are drawn in", async () => {+ mount();+ const specimen = await waitForSpecimen();++ // Fetched from the note's own endpoint, versioned by blobId so a replaced file is not+ // served from the cache of the one it replaced.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(String(fetchMock.mock.calls[0][0])).toContain("api/notes/font1/open?v=blobA");++ const [ font ] = registeredFonts;+ expect(font.family).toBe("trilium-font-preview-font1");+ expect(container.querySelector<HTMLElement>(".font-preview")?.style.getPropertyValue("--font-preview-family"))+ .toBe(`"trilium-font-preview-font1"`);++ // Nothing was typed yet, so the pangram stands in — in the specimen and every ladder line.+ expect(specimen.textContent).toBe("font_preview.pangram");+ const ladderLines = container.querySelectorAll<HTMLElement>(".font-preview-ladder-line");+ expect(ladderLines).toHaveLength(5);+ expect([ ...ladderLines ].map((line) => line.style.getPropertyValue("--font-preview-ladder-size")))+ .toEqual([ "36px", "24px", "18px", "14px", "12px" ]);+ expect(ladderLines[0].textContent).toBe("font_preview.pangram");+ });++ it("draws the typed specimen text at the size the slider is set to", async () => {+ mount();+ const specimen = await waitForSpecimen();+ expect(specimen.style.getPropertyValue("--font-preview-specimen-size")).toBe("56px");++ const input = container.querySelector<HTMLInputElement>(".font-preview-specimen-input");+ if (!input) throw new Error("specimen box not rendered");+ input.value = "Hamburgefonstiv";+ input.dispatchEvent(new Event("input", { bubbles: true }));++ const slider = container.querySelector<HTMLInputElement>("input.slider");+ if (!slider) throw new Error("size slider not rendered");+ slider.value = "72";+ slider.dispatchEvent(new Event("input", { bubbles: true }));++ await vi.waitFor(() => {+ expect(container.querySelector(".font-preview-specimen")?.textContent).toBe("Hamburgefonstiv");+ expect(container.querySelector<HTMLElement>(".font-preview-specimen")?.style.getPropertyValue("--font-preview-specimen-size")).toBe("72px");+ });+ // The ladder shows the same text, at its own fixed sizes.+ expect(container.querySelector(".font-preview-ladder-line")?.textContent).toBe("Hamburgefonstiv");+ });++ it("unregisters the font when the preview goes away", async () => {+ mount();+ await waitForSpecimen();+ expect(registeredFonts.size).toBe(1);++ render(null, container);+ expect(registeredFonts.size).toBe(0);+ });++ it("falls back to the no-preview notice for a file the engine will not rasterize, and registers nothing", async () => {+ fetchMock.mockResolvedValue(new Response(new Uint8Array([ 0xff, 0xff ])));+ mount();++ await vi.waitFor(() => expect(container.querySelector(".file-preview-not-available")).not.toBeNull());+ expect(container.querySelector(".font-preview")).toBeNull();+ expect(registeredFonts.size).toBe(0);+ });++ it("falls back to the no-preview notice when the file cannot be fetched", async () => {+ fetchMock.mockResolvedValue(new Response("nope", { status: 404 }));+ mount();++ await vi.waitFor(() => expect(container.querySelector(".file-preview-not-available")).not.toBeNull());+ expect(registeredFonts.size).toBe(0);+ });++ it("does not reach for the content of a protected note outside a protected session", async () => {+ mount({ isContentAvailable: false });++ await vi.waitFor(() => expect(container.querySelector(".file-preview-not-available")).not.toBeNull());+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("stays blank until the blob that versions the request arrives", () => {+ mount({ blobId: null });++ expect(container.innerHTML).toBe("");+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe("isFontMimeType", () => {+ it("accepts the formats FontFace rasterizes, including the legacy aliases", () => {+ for (const mime of [ "font/woff2", "font/woff", "font/ttf", "font/otf", "font/sfnt", "application/font-woff", "application/x-font-ttf", "application/x-font-truetype", "application/x-font-otf", "application/x-font-opentype" ]) {+ expect(isFontMimeType(mime), mime).toBe(true);+ }+ expect(isFontMimeType("FONT/WOFF2")).toBe(true);+ });++ it("rejects font formats no engine loads this way, and non-fonts", () => {+ // EOT and TrueType collections keep the generic no-preview notice rather than a preview+ // that could only fail.+ for (const mime of [ "application/vnd.ms-fontobject", "font/collection", "application/octet-stream", "image/png", "" ]) {+ expect(isFontMimeType(mime), mime).toBe(false);+ }+ });+});diff --git a/apps/client/src/widgets/type_widgets/file/FontPreview.tsx b/apps/client/src/widgets/type_widgets/file/FontPreview.tsxnew file mode 100644index 0000000000..238577af39--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/FontPreview.tsx@@ -0,0 +1,172 @@+import "./FontPreview.css";++import { Fragment } from "preact";+import { useEffect, useState } from "preact/hooks";++import type FBlob from "../../../entities/fblob";+import type FNote from "../../../entities/fnote";+import { t } from "../../../services/i18n";+import Alert from "../../react/Alert";+import FormTextBox from "../../react/FormTextBox";+import Slider from "../../react/Slider";++/** The sizes the specimen is laddered at, from a display line down to body copy. */+const LADDER_SIZES = [ 36, 24, 18, 14, 12 ];++const MIN_SPECIMEN_SIZE = 12;+const MAX_SPECIMEN_SIZE = 96;+const DEFAULT_SPECIMEN_SIZE = 56;++/** The Latin repertoire, shown as a fixed sample of what the file draws. Any other script can be+ * typed into the specimen box instead. */+const UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";+const LOWERCASE = "abcdefghijklmnopqrstuvwxyz";+const DIGITS_AND_PUNCTUATION = "0123456789 & @ $ # % () [] {} / \\ ? ! . , ; : “ ” – —";++interface FontPreviewProps {+ note: FNote;+ /** The note's blob, fetched by the file widget. A font blob arrives contentless — the bytes are+ * fetched below — but it is watched, so a replaced file re-reads. */+ blob: FBlob | null | undefined;+}++/**+ * Main-view preview for font files: the file rendered in itself, where "no preview available" used+ * to be — an editable specimen line whose size the slider drives, the same text laddered down to+ * body sizes, and the Latin repertoire.+ */+export default function FontPreview({ note, blob }: FontPreviewProps) {+ const family = useLoadedFont(note, blob);+ const [ specimen, setSpecimen ] = useState("");+ const [ size, setSize ] = useState(DEFAULT_SPECIMEN_SIZE);++ if (family === undefined) {+ return null;+ }+ if (family === null) {+ // A file the engine will not rasterize gets the notice any other unpreviewable file gets.+ return (+ <Alert className="file-preview-not-available" type="info">+ {t("file.file_preview_not_available")}+ </Alert>+ );+ }++ const text = specimen.trim() ? specimen : t("font_preview.pangram");++ return (+ <div className="font-preview selectable-text" style={{ "--font-preview-family": `"${family}"` }}>+ <div className="font-preview-controls">+ <FormTextBox+ className="font-preview-specimen-input"+ currentValue={specimen}+ onChange={(newValue) => setSpecimen(newValue)}+ placeholder={t("font_preview.specimen_placeholder")}+ />+ <div className="font-preview-size">+ <Slider+ value={size}+ min={MIN_SPECIMEN_SIZE}+ max={MAX_SPECIMEN_SIZE}+ onChange={setSize}+ title={t("font_preview.size")}+ />+ <span className="font-preview-size-value">{t("font_preview.size_pixels", { size })}</span>+ </div>+ </div>++ <div className="font-preview-specimen" style={{ "--font-preview-specimen-size": `${size}px` }}>{text}</div>++ <div className="font-preview-heading">{t("font_preview.sizes")}</div>+ <div className="font-preview-ladder">+ {LADDER_SIZES.map((ladderSize) => (+ <Fragment key={ladderSize}>+ <div className="font-preview-ladder-size">{t("font_preview.size_pixels", { size: ladderSize })}</div>+ <div className="font-preview-ladder-line" style={{ "--font-preview-ladder-size": `${ladderSize}px` }}>{text}</div>+ </Fragment>+ ))}+ </div>++ <div className="font-preview-heading">{t("font_preview.characters")}</div>+ <div className="font-preview-characters">+ <div>{UPPERCASE}</div>+ <div>{LOWERCASE}</div>+ <div>{DIGITS_AND_PUNCTUATION}</div>+ </div>+ </div>+ );+}++/** Font formats `FontFace` rasterizes. EOT and TrueType collections are left out: no engine loads+ * them this way, so a preview of one could only fail. */+const PREVIEWABLE_MIME_TYPES = new Set([+ "font/otf",+ "font/sfnt",+ "font/ttf",+ "font/woff",+ "font/woff2",+ "application/font-woff",+ "application/font-woff2",+ "application/x-font-opentype",+ "application/x-font-otf",+ "application/x-font-truetype",+ "application/x-font-ttf"+]);++export function isFontMimeType(mime: string) {+ return PREVIEWABLE_MIME_TYPES.has(mime.toLowerCase());+}++/**+ * Registers the note's font with the document for as long as the preview is mounted, and returns+ * the family name to render it with — `undefined` while it loads, `null` if the file is not a font+ * the engine accepts.+ */+function useLoadedFont(note: FNote, blob: FBlob | null | undefined) {+ const [ family, setFamily ] = useState<string | null>();++ useEffect(() => {+ if (!blob) return;+ if (!note.isContentAvailable()) {+ setFamily(null);+ return;+ }++ let cancelled = false;+ let registered: FontFace | undefined;+ // Private to this note, so a preview can never shadow the font the app itself renders in.+ const previewFamily = `trilium-font-preview-${note.noteId}`;+ setFamily(undefined);++ // The bytes are fetched and handed to `FontFace` directly rather than referenced by their+ // API URL: a `url()` source is loaded by the engine itself, outside the host document's+ // service worker and Capacitor request interceptors, which is where standalone and iOS+ // answer an API request from (see loadIconPackFont in IconPackPreview.tsx). Versioned by+ // blobId so a replaced file is not served from the cache of the one it replaced.+ const url = new URL(`api/notes/${note.noteId}/open?v=${encodeURIComponent(blob.blobId)}`, document.baseURI).href;++ (async () => {+ try {+ const response = await fetch(url);+ if (!response.ok) {+ throw new Error(`Font request failed with HTTP ${response.status}.`);+ }+ const face = await new FontFace(previewFamily, await response.arrayBuffer()).load();+ if (cancelled) return;++ document.fonts.add(face);+ registered = face;+ setFamily(previewFamily);+ } catch {+ if (!cancelled) setFamily(null);+ }+ })();++ return () => {+ cancelled = true;+ if (registered) document.fonts.delete(registered);+ };+ }, [ note, blob ]);++ return family;+}