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
fix(standalone): icon pack preview font never reaches the backend
Elian Doran83078750ad53
diff --git a/apps/client/src/widgets/react/IsolatedFrame.tsx b/apps/client/src/widgets/react/IsolatedFrame.tsxindex 4bff36e282..a6fe96dfaf 100644--- a/apps/client/src/widgets/react/IsolatedFrame.tsx+++ b/apps/client/src/widgets/react/IsolatedFrame.tsx@@ -26,6 +26,12 @@ interface IsolatedFrameProps {* Provide the frame's own styling via {@link IsolatedFrameProps.css}; theme values can be forwarded* with {@link IsolatedFrameProps.cssVars}. Because the document has no base URL, any URLs referenced* from that CSS must be absolute.+ *+ * They must also not point at the backend: an `about:blank` document is not controlled by a service+ * worker and inherits none of the host document's request interceptors, so in standalone (and on+ * iOS/Capacitor) an `/api/...` subresource never reaches the local backend — it hits the network and+ * comes back as the SPA fallback HTML. Fetch such content from the host document and reference it+ * here as a `blob:` URL instead (see `loadIconPackFont`).*/export default function IsolatedFrame({ className, title, css, cssVars, bodyClassName, children }: IsolatedFrameProps) {const iframeRef = useRef<HTMLIFrameElement>(null);diff --git a/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.spec.tsx b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.spec.tsxindex fe4348fb5e..f7f8fc65bf 100644--- a/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.spec.tsx+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.spec.tsx@@ -1,6 +1,7 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";-import { parseManifest, resolveGlyph } from "./IconPackPreview";+import FNote from "../../../entities/fnote";+import { loadIconPackFont, parseManifest, resolveGlyph } from "./IconPackPreview";// U+E964 is the code point used across the escape-form assertions below.const E964 = String.fromCodePoint(0xe964);@@ -28,6 +29,55 @@ describe("resolveGlyph", () => {});});+describe("loadIconPackFont", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ /** A note whose `file`-role attachments are the given (mime, attachmentId) pairs. */+ function fakeNote(attachments: { mime: string; attachmentId: string }[]) {+ return { getAttachmentsByRole: () => Promise.resolve(attachments) } as unknown as FNote;+ }++ function stubFetch(response: Partial<Response>) {+ const fetchMock = vi.fn(() => Promise.resolve(response as Response));+ vi.stubGlobal("fetch", fetchMock);+ vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:font");+ return fetchMock;+ }++ it("downloads the preferred font attachment and returns it as a blob URL", async () => {+ // woff2 wins over woff and ttf regardless of the order the attachments come back in.+ const fetchMock = stubFetch({ ok: true, blob: () => Promise.resolve(new Blob([ "font" ])) });+ const note = fakeNote([+ { mime: "font/ttf", attachmentId: "ttfId" },+ { mime: "font/woff2", attachmentId: "woff2Id" },+ { mime: "font/woff", attachmentId: "woffId" }+ ]);++ expect(await loadIconPackFont(note)).toEqual({ url: "blob:font", format: "woff2" });+ // The bytes must be fetched from the host document — the preview's iframe reaches no backend+ // in standalone — and the URL resolved against its base so Electron's protocol is covered.+ expect(fetchMock).toHaveBeenCalledWith(new URL("api/attachments/download/woff2Id", document.baseURI).href);+ });++ it("falls back to the next best mime and yields null when there is no font or the download fails", async () => {+ stubFetch({ ok: true, blob: () => Promise.resolve(new Blob([ "font" ])) });+ expect(await loadIconPackFont(fakeNote([+ { mime: "application/pdf", attachmentId: "pdfId" },+ { mime: "font/woff", attachmentId: "woffId" }+ ]))).toEqual({ url: "blob:font", format: "woff" });++ expect(await loadIconPackFont(fakeNote([ { mime: "application/pdf", attachmentId: "pdfId" } ]))).toBeNull();+ expect(await loadIconPackFont(fakeNote([]))).toBeNull();++ // A failed download (e.g. the attachment vanished) must not produce a broken @font-face.+ stubFetch({ ok: false, status: 404 });+ expect(await loadIconPackFont(fakeNote([ { mime: "font/woff2", attachmentId: "woff2Id" } ]))).toBeNull();+ });+});+describe("parseManifest", () => {it("parses icons, resolving glyphs and defaulting missing or ill-typed fields", () => {const result = parseManifest(JSON.stringify({diff --git a/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsx b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsxindex f6ef7e25ae..2c9f529ea2 100644--- a/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsx+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsx@@ -147,28 +147,60 @@ interface IconPackFont {format: string;}-/** Resolves the best font attachment on the note to an absolute download URL, mirroring the server's selection. */+/** Resolves the best font attachment on the note to a `blob:` URL usable from the isolated frame. */function useIconPackFont(note: FNote): IconPackFont | null {const [ font, setFont ] = useState<IconPackFont | null>(null);useEffect(() => {let cancelled = false;- note.getAttachmentsByRole("file").then((attachments) => {- if (cancelled) return;- const best = Object.keys(FONT_MIME_TO_FORMAT)- .map((mime) => attachments.find((attachment) => attachment.mime === mime))- .find(Boolean);- // Resolve against the host document's base URL since the isolated frame has none.- setFont(best- ? { url: new URL(`api/attachments/download/${best.attachmentId}`, document.baseURI).href, format: FONT_MIME_TO_FORMAT[best.mime] }- : null);- }).catch(() => {- if (!cancelled) setFont(null);- });- return () => { cancelled = true; };+ let objectUrl: string | null = null;+ loadIconPackFont(note)+ .then((loaded) => {+ if (cancelled) {+ if (loaded) URL.revokeObjectURL(loaded.url);+ return;+ }+ objectUrl = loaded?.url ?? null;+ setFont(loaded);+ })+ .catch(() => {+ if (!cancelled) setFont(null);+ });+ return () => {+ cancelled = true;+ if (objectUrl) URL.revokeObjectURL(objectUrl);+ };}, [ note ]);return font;}+/**+ * Picks the best font attachment on the note (mirroring the server's order of preference), downloads+ * it and hands back a `blob:` URL for its bytes.+ *+ * The bytes are fetched here, from the host document, rather than being referenced by their API URL+ * from the preview's `@font-face`: the preview lives in a `src`-less iframe, whose `about:blank`+ * document is *not* controlled by a service worker and carries none of the host's request+ * interceptors. In standalone that means such a request never reaches the SQLite worker — it goes+ * to the real network, where the SPA fallback answers a font request with `index.html`, and the+ * browser reports "Failed to decode downloaded font". The same holds on iOS/Capacitor, whose+ * fetch/stylesheet interceptors are likewise installed on the host document only. A `blob:` URL+ * needs no such routing, so it works on every platform.+ */+export async function loadIconPackFont(note: FNote): Promise<IconPackFont | null> {+ const attachments = await note.getAttachmentsByRole("file");+ const best = Object.keys(FONT_MIME_TO_FORMAT)+ .map((mime) => attachments.find((attachment) => attachment.mime === mime))+ .find(Boolean);+ if (!best) return null;++ // Resolve against the host document's base URL, which also covers Electron's `trilium-app://`.+ const downloadUrl = new URL(`api/attachments/download/${best.attachmentId}`, document.baseURI).href;+ const response = await fetch(downloadUrl);+ if (!response.ok) return null;++ return { url: URL.createObjectURL(await response.blob()), format: FONT_MIME_TO_FORMAT[best.mime] };+}+const PREVIEW_FONT_FAMILY = "tn-icon-pack-preview";function buildPreviewCss(font: IconPackFont | null): string {