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(options): seamless transition when switching fonts
Elian Doranb0c0754ee501
diff --git a/apps/client/src/index.ts b/apps/client/src/index.tsindex 6cf7e8eead..8abf3992e3 100644--- a/apps/client/src/index.ts+++ b/apps/client/src/index.ts@@ -1,3 +1,4 @@+import { createFontStylesheetLink } from "./services/font";import { buildThemeStylesheetRefs, createStylesheetLink, getThemeStyle, StylesheetRef } from "./services/theme";async function bootstrap() {@@ -87,7 +88,8 @@ function loadStylesheets() {const stylesheetsPath = `${assetPath}/stylesheets`;appendStylesheet({ href: `${stylesheetsPath}/ckeditor-theme.css` });- appendStylesheet({ href: `api/fonts` });+ // Marked so it can be swapped when font options change without reloading.+ document.head.appendChild(createFontStylesheetLink());// The light theme is always loaded as the baseline and acts as the anchor for live theme swapping.appendStylesheet({ href: `${stylesheetsPath}/theme-light.css` }, { base: true });for (const ref of buildThemeStylesheetRefs(theme, customThemeCssUrl, themeBase)) {diff --git a/apps/client/src/services/font.spec.ts b/apps/client/src/services/font.spec.tsnew file mode 100644index 0000000000..bb13defa52--- /dev/null+++ b/apps/client/src/services/font.spec.ts@@ -0,0 +1,89 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { applyFontsFromOptions, createFontStylesheetLink } from "./font.js";++function fontLinkHrefs() {+ return Array.from(document.head.querySelectorAll<HTMLLinkElement>("link[data-font-stylesheet]"))+ .map((link) => link.getAttribute("href"));+}++/** happy-dom does not fetch stylesheets, so emulate the pending links finishing loading. */+function fireLoadOnFontLinks() {+ for (const link of document.head.querySelectorAll<HTMLLinkElement>("link[data-font-stylesheet]")) {+ link.dispatchEvent(new Event("load"));+ }+}++// The fonts service keeps a monotonic cache-busting counter as module state, so the exact `?v=N`+// value carries across tests; assertions therefore check the shape and relative change, not the number.+const VERSIONED_HREF = /^api\/fonts\?v=\d+$/;++describe("font service", () => {+ beforeEach(() => {+ // Prevent happy-dom from actually fetching the stylesheet links (which would hit the network and+ // surface as an unhandled rejection); we only assert on the DOM, not on loaded styles.+ const happyDOM = (window as unknown as { happyDOM?: { settings: { disableCSSFileLoading: boolean } } }).happyDOM;+ if (happyDOM) {+ happyDOM.settings.disableCSSFileLoading = true;+ }+ document.head.innerHTML = "";+ });++ afterEach(() => {+ document.head.innerHTML = "";+ });++ it("creates a marked stylesheet link", () => {+ const link = createFontStylesheetLink();+ expect(link.rel).toBe("stylesheet");+ expect(link.hasAttribute("data-font-stylesheet")).toBe(true);+ expect(link.getAttribute("href")).toMatch(/^api\/fonts(\?v=\d+)?$/);+ });++ it("swaps in a fresh cache-busted stylesheet and removes the old one once it loads", () => {+ document.head.appendChild(createFontStylesheetLink());+ expect(fontLinkHrefs()).toHaveLength(1);++ applyFontsFromOptions();+ // New link added before the old one is removed.+ const afterApply = fontLinkHrefs();+ expect(afterApply).toHaveLength(2);+ expect(afterApply[1]).toMatch(VERSIONED_HREF);++ fireLoadOnFontLinks();+ expect(fontLinkHrefs()).toEqual([afterApply[1]]);+ });++ it("bumps the cache-busting param on every apply", () => {+ document.head.appendChild(createFontStylesheetLink());++ applyFontsFromOptions();+ fireLoadOnFontLinks();+ const first = fontLinkHrefs()[0];++ applyFontsFromOptions();+ fireLoadOnFontLinks();+ const second = fontLinkHrefs()[0];++ expect(first).toMatch(VERSIONED_HREF);+ expect(second).toMatch(VERSIONED_HREF);+ expect(second).not.toBe(first);+ });++ it("inserts the new link right after the previous one, preserving cascade position", () => {+ document.head.appendChild(createFontStylesheetLink());+ // A trailing stylesheet (e.g. style.css) must stay after the fonts stylesheet.+ const trailing = document.createElement("link");+ trailing.rel = "stylesheet";+ trailing.href = "style.css";+ document.head.appendChild(trailing);++ applyFontsFromOptions();+ fireLoadOnFontLinks();++ const hrefs = Array.from(document.head.querySelectorAll("link")).map((l) => l.getAttribute("href"));+ expect(hrefs).toHaveLength(2);+ expect(hrefs[0]).toMatch(VERSIONED_HREF);+ expect(hrefs[1]).toBe("style.css");+ });+});diff --git a/apps/client/src/services/font.ts b/apps/client/src/services/font.tsnew file mode 100644index 0000000000..8071a3fa73--- /dev/null+++ b/apps/client/src/services/font.ts@@ -0,0 +1,41 @@+/** Marks the server-generated fonts stylesheet so it can be replaced when a font option changes. */+const FONT_STYLESHEET_ATTR = "data-font-stylesheet";++let version = 0;++/** Creates the (marked) fonts stylesheet link. Used both at boot and when re-applying fonts live. */+export function createFontStylesheetLink(): HTMLLinkElement {+ const link = document.createElement("link");+ link.rel = "stylesheet";+ // A bumped query param busts the browser cache so the server regenerates the CSS from the latest options.+ link.href = version === 0 ? "api/fonts" : `api/fonts?v=${version}`;+ link.setAttribute(FONT_STYLESHEET_ATTR, "true");+ return link;+}++/**+ * Re-fetches the server-generated fonts stylesheet and swaps it in without reloading. The server returns an empty+ * stylesheet when font overrides are disabled, so this also correctly reverts to the theme defaults. The previous+ * stylesheet is removed only once the new one has loaded, keeping the swap free of a flash of unstyled content.+ */+export function applyFontsFromOptions() {+ version++;++ const oldLinks = Array.from(document.head.querySelectorAll<HTMLLinkElement>(`link[${FONT_STYLESHEET_ATTR}]`));+ const newLink = createFontStylesheetLink();++ const anchor = oldLinks.at(-1);+ if (anchor) {+ anchor.after(newLink);+ } else {+ document.head.appendChild(newLink);+ }++ const removeOldLinks = () => {+ for (const oldLink of oldLinks) {+ oldLink.remove();+ }+ };+ newLink.addEventListener("load", removeOldLinks, { once: true });+ newLink.addEventListener("error", removeOldLinks, { once: true });+}diff --git a/apps/client/src/services/theme.spec.ts b/apps/client/src/services/theme.spec.tsindex e74a0f6341..ec43683f4f 100644--- a/apps/client/src/services/theme.spec.ts+++ b/apps/client/src/services/theme.spec.ts@@ -168,6 +168,11 @@ describe("buildThemeStylesheetRefs", () => {describe("applyTheme", () => {beforeEach(() => {+ // Prevent happy-dom from fetching the stylesheet links over the network; we only assert on the DOM.+ const happyDOM = (window as unknown as { happyDOM?: { settings: { disableCSSFileLoading: boolean } } }).happyDOM;+ if (happyDOM) {+ happyDOM.settings.disableCSSFileLoading = true;+ }win.glob = { ...(win.glob ?? {}), assetPath: "/assets" };document.head.innerHTML = "";document.body.removeAttribute("data-theme-id");diff --git a/apps/client/src/widgets/containers/root_container.ts b/apps/client/src/widgets/containers/root_container.tsindex eb1163c604..5af300419d 100644--- a/apps/client/src/widgets/containers/root_container.ts+++ b/apps/client/src/widgets/containers/root_container.ts@@ -1,7 +1,8 @@-import { LOCALES } from "@triliumnext/commons";+import { LOCALES, OptionNames } from "@triliumnext/commons";import { EventData } from "../../components/app_context.js";import { getEnabledExperimentalFeatureIds } from "../../services/experimental_features.js";+import { applyFontsFromOptions } from "../../services/font.js";import options from "../../services/options.js";import { applyThemeFromOptions, updateColorSchemeClasses } from "../../services/theme.js";import utils, { isIOS, isMobile } from "../../services/utils.js";@@ -9,6 +10,15 @@ import { readCssVar } from "../../utils/css-var.js";import type BasicWidget from "../basic_widget.js";import FlexContainer from "./flex_container.js";+/** Font options whose change requires re-applying the server-generated fonts stylesheet. */+const FONT_OPTIONS: OptionNames[] = [+ "overrideThemeFonts",+ "mainFontFamily", "mainFontSize",+ "treeFontFamily", "treeFontSize",+ "detailFontFamily", "detailFontSize",+ "monospaceFontFamily", "monospaceFontSize"+];+/*** The root container is the top-most widget/container, from which the entire layout derives.*@@ -56,6 +66,10 @@ export default class RootContainer extends FlexContainer<BasicWidget> {void applyThemeFromOptions();}+ if (FONT_OPTIONS.some((optionName) => loadResults.isOptionReloaded(optionName))) {+ applyFontsFromOptions();+ }+if (loadResults.isOptionReloaded("motionEnabled")) {this.#setMotion();}diff --git a/apps/client/src/widgets/type_widgets/options/appearance.tsx b/apps/client/src/widgets/type_widgets/options/appearance.tsxindex 16f3491fad..8d268c1596 100644--- a/apps/client/src/widgets/type_widgets/options/appearance.tsx+++ b/apps/client/src/widgets/type_widgets/options/appearance.tsx@@ -417,12 +417,6 @@ function Fonts() {<Font label={t("fonts.note_tree_font")} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="treeFontFamily" fontSizeOption="treeFontSize" disabled={!isEnabled} /><Font label={t("fonts.note_detail_font")} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="detailFontFamily" fontSizeOption="detailFontSize" disabled={!isEnabled} /><Font label={t("fonts.monospace_font")} description={t("fonts.monospace_font_description")} fontFamilyOption="monospaceFontFamily" fontSizeOption="monospaceFontSize" disabled={!isEnabled} isMonospace />-- <OptionsRowWithButton- label={t("fonts.apply_changes")}- icon="bx bx-refresh"- onClick={reloadFrontendApp}- /></OptionsSection>);}