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(fonts): offer only the stock families this device can render
Elian Doranecfbdcd68505
diff --git a/apps/client/src/services/font.spec.ts b/apps/client/src/services/font.spec.tsindex d8029caaee..6b27ab61f2 100644--- a/apps/client/src/services/font.spec.ts+++ b/apps/client/src/services/font.spec.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { applyFontsFromOptions, createFontStylesheetLink, listSystemFonts } from "./font.js";+import { applyFontsFromOptions, createFontStylesheetLink, filterAvailableFamilies, listSystemFonts } from "./font.js";function fontLinkHrefs() {return Array.from(document.head.querySelectorAll<HTMLLinkElement>("link[data-font-stylesheet]"))@@ -187,3 +187,57 @@ describe("listSystemFonts", () => {]);});});++describe("filterAvailableFamilies", () => {+ /**+ * Stands in for the canvas the measurement runs on. `installed` decides which families the+ * device has; anything else falls back, and measures exactly as the generic it fell back to.+ */+ function stubMeasuring(installed: Record<string, number>) {+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation((() => {+ const generics = { monospace: 100, serif: 110, "sans-serif": 120 };+ let font = "";++ return {+ canvas: { width: 40, height: 40 },+ measureText: () => {+ const family = font.match(/"(.+?)"/)?.[1];+ const fallback = font.replace(/^\d+px\s*/, "").split(", ").pop() ?? "";+ // Without a family named, the width is the generic's own.+ return { width: family && family in installed ? installed[family] : generics[fallback as keyof typeof generics] };+ },+ get font() {+ return font;+ },+ set font(value: string) {+ font = value;+ }+ };+ }) as never);+ }++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("keeps the families the device has and drops the ones it falls back from", () => {+ stubMeasuring({ Georgia: 130, "Comic Sans MS": 140 });++ expect(filterAvailableFamilies([ "Georgia", "Garamond", "Comic Sans MS", "Luminari" ]))+ .toEqual([ "Georgia", "Comic Sans MS" ]);+ });++ it("keeps a family that measures as one generic but not the others", () => {+ // Arial resolves to the same face as the default sans-serif, so it is told apart only by+ // the other two. A single fallback would report it missing.+ stubMeasuring({ Arial: 120 });++ expect(filterAvailableFamilies([ "Arial" ])).toEqual([ "Arial" ]);+ });++ it("keeps everything where there is no canvas to measure on", () => {+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);++ expect(filterAvailableFamilies([ "Garamond", "Luminari" ])).toEqual([ "Garamond", "Luminari" ]);+ });+});diff --git a/apps/client/src/services/font.ts b/apps/client/src/services/font.tsindex a7e0e69797..cfd087fb9f 100644--- a/apps/client/src/services/font.ts+++ b/apps/client/src/services/font.ts@@ -89,6 +89,48 @@ const PROBE_CHARACTERS = [ "A", "日" ];/** Big enough that a light glyph still covers a pixel once it is rasterized. */const PROBE_FONT_SIZE = 20;+/**+ * The families of `candidates` this device can render, for a list of guesses to be narrowed to what+ * is actually there. Everything is kept where there is no canvas to measure on.+ *+ * Used where the fonts cannot be enumerated outright — that is, everywhere but the desktop app, so+ * the stock list stops offering families the browser would only fall back from.+ */+export function filterAvailableFamilies(candidates: string[]): string[] {+ const context = createProbeContext();+ if (!context) {+ return candidates;+ }++ return candidates.filter((family) => isAvailable(context, family));+}++/**+ * Whether naming `family` changes how text is laid out. Asked of each generic in turn, because a+ * family can share its metrics with one of them and still be present: Arial resolves to the same+ * face as the default sans-serif on a Linux box, so it measures identically against that one while+ * differing from serif and monospace.+ */+function isAvailable(context: CanvasRenderingContext2D, family: string): boolean {+ for (const fallback of FALLBACK_FAMILIES) {+ context.font = `${PROBE_FONT_SIZE}px ${fallback}`;+ const fellBack = context.measureText(AVAILABILITY_TEXT).width;++ context.font = `${PROBE_FONT_SIZE}px "${family}", ${fallback}`;+ if (context.measureText(AVAILABILITY_TEXT).width !== fellBack) {+ return true;+ }+ }++ return false;+}++/** The generics a candidate is measured against, one of which every fallback lands on. */+const FALLBACK_FAMILIES = [ "monospace", "serif", "sans-serif" ];++/** Wide and narrow letters together, so a family carrying its own metrics shifts the advance. */+const AVAILABILITY_TEXT = "mmmmmmmmmmlli";+/** The surface every family is drawn on, or `null` where the runtime offers no canvas. */function createProbeContext() {const canvas = document.createElement("canvas");diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 1bae34176b..8ffd68f91f 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1826,7 +1826,7 @@"monospace_ligatures": "Programming ligatures","monospace_ligatures_description": "Renders character pairs such as != and -> as single symbols (≠, →), if the monospace font supports it. The text itself is unchanged.","size_relative_to_general": "Size is relative to the general font size",- "custom_fonts_description": "Replaces the theme's fonts. Not all listed fonts are available on every device; a font uploaded into Trilium can be added from its own note.",+ "custom_fonts_description": "Replaces the theme's fonts. A font uploaded into Trilium can be added from its own note.","apply_changes": "Reload to apply changes","generic-fonts": "Generic fonts","user-fonts": "Custom fonts",diff --git a/apps/client/src/widgets/type_widgets/options/appearance_fonts.spec.tsx b/apps/client/src/widgets/type_widgets/options/appearance_fonts.spec.tsxindex daca8bf1bc..7fae16706c 100644--- a/apps/client/src/widgets/type_widgets/options/appearance_fonts.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/appearance_fonts.spec.tsx@@ -6,7 +6,9 @@ const mocks = vi.hoisted(() => ({electron: true,stored: {} as Record<string, string | boolean>,userFonts: [] as { noteId: string; title: string; blobId: string }[],- systemFonts: [] as { family: string; monospace: boolean }[]+ systemFonts: [] as { family: string; monospace: boolean }[],+ /** The stock families this device can render, or `null` to let every one of them through. */+ availableFamilies: null as string[] | null}));// Only the desktop app can be asked what fonts the device has.@@ -27,7 +29,8 @@ vi.mock("../../../services/custom_fonts", () => ({// happy-dom exposes no `queryLocalFonts`, so what the desktop app would find is stood in for.vi.mock("../../../services/font", async (importOriginal) => ({...(await importOriginal<typeof import("../../../services/font")>()),- listSystemFonts: async () => mocks.systemFonts+ listSystemFonts: async () => mocks.systemFonts,+ filterAvailableFamilies: (families: string[]) => mocks.availableFamilies ?? families}));// useNoteTitle names the font a font option points at; the listing above is what the picker lists.@@ -47,6 +50,7 @@ beforeEach(() => {mocks.stored = {};mocks.userFonts = [];mocks.systemFonts = [];+ mocks.availableFamilies = null;Object.defineProperty(document, "fonts", {configurable: true,value: { add: vi.fn(), delete: vi.fn() }@@ -86,6 +90,9 @@ async function openPicker() {await act(async () => (fontRows()[0] as HTMLElement).click());}+/** The generic entries, which head every list and are never measured against the device. */+const GENERIC_LABELS = [ "fonts.theme_defined", "fonts.system-default", "fonts.serif", "fonts.sans-serif", "fonts.monospace" ];+/** Types into the picker's search box, as the user would. */function searchFonts(query: string) {const search = document.querySelector<HTMLInputElement>(".font-picker-modal .settings-search input");@@ -209,6 +216,24 @@ describe("the font settings", () => {expect(headers).toContain("fonts.sans-serif-system-fonts");});+ it("narrows the named families to the ones the device can render", async () => {+ mocks.electron = false;+ mocks.stored = { overrideThemeFonts: true };+ // Nothing from the serif or handwriting groups, so both go entirely.+ mocks.availableFamilies = [ "Arial", "Verdana", "Courier New" ];+ open();+ await act(async () => {});+ await act(async () => (fontRows()[0] as HTMLElement).click());++ expect(listedFonts()).toEqual([ ...GENERIC_LABELS, "Arial", "Verdana", "Courier New" ]);+ // A group left with nothing goes, its header with it; the generics are never measured.+ expect(listedHeaders()).toEqual([+ "fonts.generic-fonts",+ "fonts.sans-serif-system-fonts",+ "fonts.monospace-system-fonts"+ ]);+ });+it("narrows the list to the fonts matching what is searched for", async () => {await openPicker();await act(async () => searchFonts("georgia"));diff --git a/apps/client/src/widgets/type_widgets/options/appearance_fonts.tsx b/apps/client/src/widgets/type_widgets/options/appearance_fonts.tsxindex 6d11ffbf26..d600f33d63 100644--- a/apps/client/src/widgets/type_widgets/options/appearance_fonts.tsx+++ b/apps/client/src/widgets/type_widgets/options/appearance_fonts.tsx@@ -7,7 +7,7 @@ import { createPortal } from "preact/compat";import { useEffect, useMemo, useRef, useState } from "preact/hooks";import { getCustomFonts, registerFontNote } from "../../../services/custom_fonts";-import { listSystemFonts, type SystemFont } from "../../../services/font";+import { filterAvailableFamilies, listSystemFonts, type SystemFont } from "../../../services/font";import { t } from "../../../services/i18n";import { isElectron } from "../../../services/utils";import { Card, OptionCardSection } from "../../react/Card";@@ -160,7 +160,7 @@ function useFontGroups(): FontGroup[] {}, []);return useMemo(() => {- const stockGroups = systemFonts.length ? installedFontGroups(systemFonts) : FONT_FAMILIES;+ const stockGroups = systemFonts.length ? installedFontGroups(systemFonts) : availableStockGroups();// Ahead of the rest: a font the user went and added is the one they are looking for.return customFonts.length@@ -172,6 +172,28 @@ function useFontGroups(): FontGroup[] {}, [ customFonts, systemFonts ]);}+/**+ * The stock groups, with the families this device cannot render left out and any group they empty+ * left out with them. The generic families always stay: the browser resolves those itself.+ *+ * The list is a guess at what a device holds, which is why every runtime that cannot enumerate its+ * fonts has to be told which of the guesses landed.+ */+function availableStockGroups(): FontGroup[] {+ const named = FONT_FAMILIES.filter((group) => group !== GENERIC_FONTS);+ const available = new Set(filterAvailableFamilies(named.flatMap((group) => group.items.map(({ value }) => value))));++ const groups = [ GENERIC_FONTS ];+ for (const group of named) {+ const items = group.items.filter(({ value }) => available.has(value));+ if (items.length) {+ groups.push({ ...group, items });+ }+ }++ return groups;+}+/*** The generic families, then the installed ones split by advance width. Serif and sans-serif cannot* be told apart from a browser — nothing reports a face's style — so this is as far as the grouping