Skip to content

Build your personal knowledge base with Trilium Notes

fix(fonts): rebuild a custom font's face when its file is replaced

Elian Doran8e3113b0f553
diff --git a/apps/client/src/services/custom_fonts.spec.ts b/apps/client/src/services/custom_fonts.spec.ts
index 15a93d1020..d3cc92da80 100644
--- a/apps/client/src/services/custom_fonts.spec.ts
+++ b/apps/client/src/services/custom_fonts.spec.ts
@@ -10,7 +10,8 @@ vi.mock("./froca.js", () => ({ default: { getNote: async (noteId: string) => moc
vi.mock("./ws.js", () => ({ logError: vi.fn() }));
vi.mock("./server.js", () => ({ default: { get: vi.fn() } }));
-const { applyCustomFontsFromOptions, registerFontNote } = await import("./custom_fonts.js");
+const { applyCustomFontsFromOptions, hasCustomFontContentChanged, registerFontNote } = await import("./custom_fonts.js");
+const { default: LoadResults } = await import("./load_results.js");
/** The faces `document.fonts` holds, as the stub below sees them. */
let registeredFaces: Set<FontFace>;
@@ -102,6 +103,21 @@ describe("applyCustomFontsFromOptions", () => {
expect(families()).toEqual([ "trilium-font-fontNoteE5" ]);
});
+ it("loads the file again once a new revision replaces it, dropping the face built from the old one", async () => {
+ mocks.options = { mainFontFamily: "customFont:fontNoteF6" };
+ mocks.notes = { fontNoteF6: { blobId: "blobF" } };
+ await applyCustomFontsFromOptions();
+ const staleFace = [ ...registeredFaces ][0];
+
+ mocks.notes = { fontNoteF6: { blobId: "blobF2" } };
+ await applyCustomFontsFromOptions();
+
+ expect(String(fetchMock.mock.calls.at(-1)?.[0])).toContain("v=blobF2");
+ // One face under the family the stylesheet names, built from the file the note holds now.
+ expect(families()).toEqual([ "trilium-font-fontNoteF6" ]);
+ expect(registeredFaces.has(staleFace)).toBe(false);
+ });
+
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();
@@ -113,3 +129,26 @@ describe("applyCustomFontsFromOptions", () => {
expect(families()).toEqual([]);
});
});
+
+describe("hasCustomFontContentChanged", () => {
+ /** A reload carrying a content change for each of `noteIds`. */
+ function reloadOf(...noteIds: string[]) {
+ const loadResults = new LoadResults([]);
+ for (const noteId of noteIds) {
+ loadResults.addNoteContent(noteId, "someComponent");
+ }
+
+ return loadResults;
+ }
+
+ it("answers only for the notes whose fonts the app is rendering with", async () => {
+ mocks.options = { mainFontFamily: "customFont:fontNoteH8" };
+ mocks.notes = { fontNoteH8: { blobId: "blobH" } };
+ await applyCustomFontsFromOptions();
+
+ expect(hasCustomFontContentChanged(reloadOf("fontNoteH8"))).toBe(true);
+ // A note holding no font the options name, and a reload that changed no content at all.
+ expect(hasCustomFontContentChanged(reloadOf("someOtherNote"))).toBe(false);
+ expect(hasCustomFontContentChanged(reloadOf())).toBe(false);
+ });
+});
diff --git a/apps/client/src/services/custom_fonts.ts b/apps/client/src/services/custom_fonts.ts
index a715d128b8..dd03fd73ae 100644
--- a/apps/client/src/services/custom_fonts.ts
+++ b/apps/client/src/services/custom_fonts.ts
@@ -1,6 +1,7 @@
import { customFontFamily, customFontNoteId, type UserFont } from "@triliumnext/commons";
import froca from "./froca.js";
+import type LoadResults from "./load_results.js";
import options from "./options.js";
import server from "./server.js";
import { logError } from "./ws.js";
@@ -8,8 +9,14 @@ 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;
+/** A face registered with the document, and the file it was built from. */
+interface RegisteredFont {
+ face: FontFace;
+ blobId: string;
+}
+
/** The faces registered for the fonts the options currently name, by the note each is stored in. */
-const registeredFonts = new Map<string, FontFace>();
+const registeredFonts = new Map<string, RegisteredFont>();
/**
* Registers the user's own fonts that the font options name, so the families the fonts stylesheet
@@ -21,11 +28,9 @@ const registeredFonts = new Map<string, FontFace>();
* 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));
+ const wanted = namedFontNoteIds();
- for (const [ noteId, face ] of registeredFonts) {
+ for (const [ noteId, { face } ] of registeredFonts) {
if (!wanted.has(noteId)) {
document.fonts.delete(face);
registeredFonts.delete(noteId);
@@ -33,26 +38,51 @@ export async function applyCustomFontsFromOptions() {
}
await Promise.all([ ...wanted ].map(async (noteId) => {
- if (registeredFonts.has(noteId)) return;
-
const note = await froca.getNote(noteId);
if (!note) return;
+ // What is already registered is checked by blob, not by note: a file replaced through a new
+ // revision has to be fetched again, under the same family the stylesheet already names.
+ const blobId = note.blobId ?? "";
+ if (registeredFonts.get(noteId)?.blobId === blobId) 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)) {
+ const face = await registerFontNote(noteId, customFontFamily(noteId), blobId);
+ const current = registeredFonts.get(noteId);
+ // A concurrent call might have registered this same file while the bytes were being
+ // fetched, in which case this face is one too many.
+ if (current?.blobId === blobId) {
document.fonts.delete(face);
- } else {
- registeredFonts.set(noteId, face);
+ return;
+ }
+
+ // The face built from the file this note held before goes only now that its replacement
+ // is registered, so nothing renders in the fallback family in between.
+ if (current) {
+ document.fonts.delete(current.face);
}
+ registeredFonts.set(noteId, { face, blobId });
} catch (e) {
logError(`Could not load the font stored in note '${noteId}': ${e}`);
}
}));
}
+/**
+ * Whether a reload touched the file of a font the options name. Replacing that file leaves the
+ * options themselves untouched, so nothing else in the reload says that the faces have to be built
+ * again.
+ */
+export function hasCustomFontContentChanged(loadResults: LoadResults) {
+ for (const noteId of namedFontNoteIds()) {
+ if (loadResults.isNoteContentReloaded(noteId)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
/** The fonts the user offers to the font picker: the file notes labelled `#customFont`. */
export async function getCustomFonts() {
return await server.get<UserFont[]>("options/user-fonts");
@@ -83,3 +113,10 @@ export async function registerFontNote(noteId: string, family: string, version:
return face;
}
+
+/** The notes the font options name, without the families the browser resolves for itself. */
+function namedFontNoteIds() {
+ return new Set(FONT_FAMILY_OPTIONS
+ .map((optionName) => customFontNoteId(options.get(optionName)))
+ .filter((noteId) => noteId !== null));
+}
diff --git a/apps/client/src/widgets/containers/root_container.ts b/apps/client/src/widgets/containers/root_container.ts
index 6dbbffe568..00da4e3eb0 100644
--- a/apps/client/src/widgets/containers/root_container.ts
+++ b/apps/client/src/widgets/containers/root_container.ts
@@ -2,7 +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 { applyCustomFontsFromOptions, hasCustomFontContentChanged } 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";
@@ -76,6 +76,10 @@ export default class RootContainer extends FlexContainer<BasicWidget> {
if (FONT_OPTIONS.some((optionName) => loadResults.isOptionReloaded(optionName))) {
applyFontsFromOptions();
void applyCustomFontsFromOptions();
+ } else if (hasCustomFontContentChanged(loadResults)) {
+ // The options still name the same fonts, so the stylesheet they are served as holds; only
+ // the faces their files were loaded into have to be built again.
+ void applyCustomFontsFromOptions();
}
if (loadResults.isOptionReloaded("motionEnabled")) {
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
index bc5a81a35f..a03659d771 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
@@ -109,7 +109,7 @@ describe("the font settings", () => {
mocks.userFonts = [
{ noteId: "fontNoteA1", title: "Iosevka", blobId: "b1" },
{ noteId: "fontNoteB2", title: "Inter", blobId: "b2" },
- // Two notes may well carry the same name; each is its own entry, told apart by its note.
+ // Two notes can carry the same name; each is its own entry, told apart by its note.
{ noteId: "fontNoteC3", title: "Inter", blobId: "b3" }
];
open();