Skip to content

Build your personal knowledge base with Trilium Notes

feat(fonts): render the app in the font the options name

Elian Doranf29d06e32c72
diff --git a/apps/client/src/services/custom_fonts.spec.ts b/apps/client/src/services/custom_fonts.spec.ts
new file mode 100644
index 0000000000..15a93d1020
--- /dev/null
+++ b/apps/client/src/services/custom_fonts.spec.ts
@@ -0,0 +1,115 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ options: {} as Record<string, string>,
+ notes: {} as Record<string, { blobId: string } | null>
+}));
+
+vi.mock("./options.js", () => ({ default: { get: (name: string) => mocks.options[name] ?? "" } }));
+vi.mock("./froca.js", () => ({ default: { getNote: async (noteId: string) => mocks.notes[noteId] ?? null } }));
+vi.mock("./ws.js", () => ({ logError: vi.fn() }));
+vi.mock("./server.js", () => ({ default: { get: vi.fn() } }));
+
+const { applyCustomFontsFromOptions, registerFontNote } = await import("./custom_fonts.js");
+
+/** The faces `document.fonts` holds, as the stub below sees them. */
+let registeredFaces: Set<FontFace>;
+let fetchMock: ReturnType<typeof vi.fn>;
+
+/** Stands in for `FontFace`, resolving unless the source bytes say the file is undecodable. */
+class FontStub {
+ constructor(public family: string, public source: ArrayBuffer | string) {}
+
+ load() {
+ const undecodable = typeof this.source !== "string" && new Uint8Array(this.source)[0] === 0xff;
+ return undecodable ? Promise.reject(new Error("Failed to decode downloaded font.")) : Promise.resolve(this);
+ }
+}
+
+beforeEach(() => {
+ mocks.options = {};
+ mocks.notes = {};
+ registeredFaces = 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: (face: FontFace) => registeredFaces.add(face),
+ delete: (face: FontFace) => registeredFaces.delete(face)
+ }
+ });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+});
+
+const families = () => [ ...registeredFaces ].map((face) => face.family);
+
+describe("registerFontNote", () => {
+ it("loads a note's file and registers it under the given family, versioned by blob", async () => {
+ await registerFontNote("fontNoteA1", "some-family", "blobA");
+
+ expect(String(fetchMock.mock.calls[0][0])).toContain("api/notes/fontNoteA1/open?v=blobA");
+ expect(families()).toEqual([ "some-family" ]);
+ });
+
+ it("throws rather than registering anything when the file cannot be fetched", async () => {
+ fetchMock.mockResolvedValue(new Response("nope", { status: 404 }));
+
+ await expect(registerFontNote("fontNoteA1", "some-family", "blobA")).rejects.toThrow("404");
+ expect(families()).toEqual([]);
+ });
+});
+
+// Each case names notes of its own: what has been registered is module state, as it is for the page
+// these run in, and outlives the test that put it there.
+describe("applyCustomFontsFromOptions", () => {
+ it("registers the note a font option names, under the family the stylesheet declares", async () => {
+ mocks.options = { mainFontFamily: "customFont:fontNoteB2", treeFontFamily: "Arial" };
+ mocks.notes = { fontNoteB2: { blobId: "blobB" } };
+
+ await applyCustomFontsFromOptions();
+
+ // "Arial" names a family the browser resolves for itself; nothing is loaded for it.
+ expect(families()).toEqual([ "trilium-font-fontNoteB2" ]);
+ });
+
+ it("registers each named font once, however many options name it", async () => {
+ mocks.options = { mainFontFamily: "customFont:fontNoteC3", detailFontFamily: "customFont:fontNoteC3" };
+ mocks.notes = { fontNoteC3: { blobId: "blobC" } };
+
+ await applyCustomFontsFromOptions();
+ // A second pass over unchanged options loads nothing again either.
+ await applyCustomFontsFromOptions();
+
+ expect(families()).toEqual([ "trilium-font-fontNoteC3" ]);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("drops a font once no option names it any more", async () => {
+ mocks.options = { mainFontFamily: "customFont:fontNoteD4" };
+ mocks.notes = { fontNoteD4: { blobId: "blobD" }, fontNoteE5: { blobId: "blobE" } };
+ await applyCustomFontsFromOptions();
+
+ mocks.options = { mainFontFamily: "customFont:fontNoteE5" };
+ await applyCustomFontsFromOptions();
+
+ expect(families()).toEqual([ "trilium-font-fontNoteE5" ]);
+ });
+
+ it("carries on where the note is gone or its file will not load", async () => {
+ mocks.options = { mainFontFamily: "customFont:goneNote001" };
+ await expect(applyCustomFontsFromOptions()).resolves.toBeUndefined();
+ expect(families()).toEqual([]);
+
+ mocks.notes = { goneNote001: { blobId: "blobG" } };
+ fetchMock.mockResolvedValue(new Response(new Uint8Array([ 0xff, 0xff ])));
+ await expect(applyCustomFontsFromOptions()).resolves.toBeUndefined();
+ expect(families()).toEqual([]);
+ });
+});
diff --git a/apps/client/src/services/custom_fonts.ts b/apps/client/src/services/custom_fonts.ts
index 70bb75f8ea..a715d128b8 100644
--- a/apps/client/src/services/custom_fonts.ts
+++ b/apps/client/src/services/custom_fonts.ts
@@ -1,6 +1,57 @@
-import type { UserFont } from "@triliumnext/commons";
+import { customFontFamily, customFontNoteId, type UserFont } from "@triliumnext/commons";
+import froca from "./froca.js";
+import options from "./options.js";
import server from "./server.js";
+import { logError } from "./ws.js";
+
+/** The font options that can name one of the user's own fonts. */
+const FONT_FAMILY_OPTIONS = [ "mainFontFamily", "treeFontFamily", "detailFontFamily", "monospaceFontFamily" ] as const;
+
+/** The faces registered for the fonts the options currently name, by the note each is stored in. */
+const registeredFonts = new Map<string, FontFace>();
+
+/**
+ * Registers the user's own fonts that the font options name, so the families the fonts stylesheet
+ * declares (see `getFontCss`) resolve to the files those notes hold. Fonts no longer named by any
+ * option are unregistered.
+ *
+ * Lives here rather than beside the stylesheet in `font.ts` because that module is loaded by
+ * `index.ts` before jQuery is: froca and the options reach i18next through their imports, which
+ * touches `$` as it loads.
+ */
+export async function applyCustomFontsFromOptions() {
+ const wanted = new Set(FONT_FAMILY_OPTIONS
+ .map((optionName) => customFontNoteId(options.get(optionName)))
+ .filter((noteId) => noteId !== null));
+
+ for (const [ noteId, face ] of registeredFonts) {
+ if (!wanted.has(noteId)) {
+ document.fonts.delete(face);
+ registeredFonts.delete(noteId);
+ }
+ }
+
+ await Promise.all([ ...wanted ].map(async (noteId) => {
+ if (registeredFonts.has(noteId)) return;
+
+ const note = await froca.getNote(noteId);
+ if (!note) return;
+
+ try {
+ const face = await registerFontNote(noteId, customFontFamily(noteId), note.blobId ?? "");
+ // A concurrent call may have registered the same note, or the option may have moved on
+ // while the bytes were being fetched; either way this face is one too many.
+ if (registeredFonts.has(noteId)) {
+ document.fonts.delete(face);
+ } else {
+ registeredFonts.set(noteId, face);
+ }
+ } catch (e) {
+ logError(`Could not load the font stored in note '${noteId}': ${e}`);
+ }
+ }));
+}
/** The fonts the user offers to the font picker: the file notes labelled `#customFont`. */
export async function getCustomFonts() {
diff --git a/apps/client/src/widgets/containers/root_container.ts b/apps/client/src/widgets/containers/root_container.ts
index 37cabc0766..6dbbffe568 100644
--- a/apps/client/src/widgets/containers/root_container.ts
+++ b/apps/client/src/widgets/containers/root_container.ts
@@ -2,6 +2,7 @@ import { LOCALES, OptionNames } from "@triliumnext/commons";
import { EventData } from "../../components/app_context.js";
import { getEnabledExperimentalFeatureIds } from "../../services/experimental_features.js";
+import { applyCustomFontsFromOptions } from "../../services/custom_fonts.js";
import { applyFontsFromOptions } from "../../services/font.js";
import options from "../../services/options.js";
import { applyThemeFromOptions, updateColorSchemeClasses, updateThemeCapabilities } from "../../services/theme.js";
@@ -58,6 +59,9 @@ export default class RootContainer extends FlexContainer<BasicWidget> {
this.#setMonospaceLigatures();
updateThemeCapabilities();
this.#setLocaleAndDirection(options.get("locale"));
+ // The fonts stylesheet went out with the page; the files the user's own fonts are stored in
+ // are fetched here, once froca can be asked which notes hold them.
+ void applyCustomFontsFromOptions();
this.#setExperimentalFeatures();
this.#initPWATopbarColor();
@@ -71,6 +75,7 @@ export default class RootContainer extends FlexContainer<BasicWidget> {
if (FONT_OPTIONS.some((optionName) => loadResults.isOptionReloaded(optionName))) {
applyFontsFromOptions();
+ void applyCustomFontsFromOptions();
}
if (loadResults.isOptionReloaded("motionEnabled")) {
diff --git a/packages/trilium-core/src/routes/api/fonts.spec.ts b/packages/trilium-core/src/routes/api/fonts.spec.ts
index 6dff4d7ebf..f84abdac97 100644
--- a/packages/trilium-core/src/routes/api/fonts.spec.ts
+++ b/packages/trilium-core/src/routes/api/fonts.spec.ts
@@ -68,4 +68,20 @@ describe("Fonts API", () => {
expect(body).toContain(v);
}
});
+
+ it("names one of the user's own fonts by the family its file is registered under", () => {
+ cls.init(() => {
+ optionService.setOption("overrideThemeFonts", "true");
+ optionService.setOption("mainFontFamily", "customFont:abc123XYZ");
+ // A reference to no note Trilium could have minted is left as it stands rather than
+ // built into a declaration.
+ optionService.setOption("treeFontFamily", "customFont:not a note id");
+ optionService.setOption("detailFontFamily", "Arial");
+ });
+
+ const { body } = getCss();
+ expect(body).toContain('--main-font-family: "trilium-font-abc123XYZ";');
+ expect(body).toContain("--tree-font-family: customFont:not a note id;");
+ expect(body).toContain("--detail-font-family: Arial;");
+ });
});
diff --git a/packages/trilium-core/src/routes/api/fonts.ts b/packages/trilium-core/src/routes/api/fonts.ts
index 99aaf143db..a9d17baf88 100644
--- a/packages/trilium-core/src/routes/api/fonts.ts
+++ b/packages/trilium-core/src/routes/api/fonts.ts
@@ -1,4 +1,4 @@
-import { SYSTEM_MONOSPACE_FONT_STACK, SYSTEM_SANS_SERIF_FONT_STACK, type OptionMap } from "@triliumnext/commons";
+import { customFontFamily, customFontNoteId, SYSTEM_MONOSPACE_FONT_STACK, SYSTEM_SANS_SERIF_FONT_STACK, type OptionMap } from "@triliumnext/commons";
import type { Request, Response } from "express";
import optionService from "../../services/options.js";
@@ -46,24 +46,37 @@ function getFontFamily({ mainFontFamily, treeFontFamily, detailFontFamily, monos
// Apply the font override if not using theme fonts.
if (mainFontFamily !== "theme") {
- style += `--main-font-family: ${mainFontFamily};`;
+ style += `--main-font-family: ${resolveFamily(mainFontFamily)};`;
}
if (treeFontFamily !== "theme") {
- style += `--tree-font-family: ${treeFontFamily};`;
+ style += `--tree-font-family: ${resolveFamily(treeFontFamily)};`;
}
if (detailFontFamily !== "theme") {
- style += `--detail-font-family: ${detailFontFamily};`;
+ style += `--detail-font-family: ${resolveFamily(detailFontFamily)};`;
}
if (monospaceFontFamily !== "theme") {
- style += `--monospace-font-family: ${monospaceFontFamily};`;
+ style += `--monospace-font-family: ${resolveFamily(monospaceFontFamily)};`;
}
return style;
}
+/**
+ * The family a font option names. One of the user's own fonts names the note holding it, and is
+ * drawn under the family the client registers that note's file as; anything else already names a
+ * family the browser resolves for itself.
+ *
+ * A reference the client would not register — one naming no note Trilium could have minted — is
+ * left as it stands rather than built into a declaration.
+ */
+function resolveFamily(optionValue: string) {
+ const noteId = customFontNoteId(optionValue);
+ return noteId ? `"${customFontFamily(noteId)}"` : optionValue;
+}
+
function getFontSize(optionsMap: OptionMap) {
let style = "";
style += `--main-font-size: ${optionsMap.mainFontSize}%;`;