Skip to content

Build your personal knowledge base with Trilium Notes

feat(fonts): group the installed fonts by advance width

Elian Doran7a0edd2ca7b0
diff --git a/apps/client/src/services/font.spec.ts b/apps/client/src/services/font.spec.ts
index 0503e0ff2f..d8029caaee 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, listSystemFontFamilies } from "./font.js";
+import { applyFontsFromOptions, createFontStylesheetLink, listSystemFonts } from "./font.js";
function fontLinkHrefs() {
return Array.from(document.head.querySelectorAll<HTMLLinkElement>("link[data-font-stylesheet]"))
@@ -88,7 +88,7 @@ describe("font service", () => {
});
});
-describe("listSystemFontFamilies", () => {
+describe("listSystemFonts", () => {
/** One face as `queryLocalFonts()` reports it — a family arrives once per weight and slant. */
function face(family: string, style: string): FontData {
return { family, style, fullName: `${family} ${style}`, postscriptName: `${family}-${style}` };
@@ -100,9 +100,10 @@ describe("listSystemFontFamilies", () => {
* does not cover falls back to one that does and paints, so only a character it claims and
* cannot rasterize comes back blank.
*/
- function stubProbeCanvas(paints: (family: string, character: string) => boolean) {
+ function stubProbeCanvas(paints: (family: string, character: string) => boolean, monospace: (family: string) => boolean = () => false) {
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation((() => {
const drawn = { font: "", character: "" };
+ const familyOf = () => drawn.font.match(/"(.+)"/)?.[1] ?? "";
return {
canvas: { width: 40, height: 40 },
@@ -110,9 +111,10 @@ describe("listSystemFontFamilies", () => {
fillText: (character: string) => {
drawn.character = character;
},
+ // A proportional family advances the widest letter further than the narrowest.
+ measureText: (text: string) => ({ width: monospace(familyOf()) || text === "W" ? 10 : 6 }),
getImageData: () => {
- const family = drawn.font.match(/"(.+)"/)?.[1] ?? "";
- return { data: new Uint8ClampedArray([ 0, 0, 0, paints(family, drawn.character) ? 255 : 0 ]) };
+ return { data: new Uint8ClampedArray([ 0, 0, 0, paints(familyOf(), drawn.character) ? 255 : 0 ]) };
},
get font() {
return drawn.font;
@@ -131,18 +133,22 @@ describe("listSystemFontFamilies", () => {
it("returns nothing where the runtime does not expose the API", async () => {
expect(window.queryLocalFonts).toBeUndefined();
- expect(await listSystemFontFamilies()).toEqual([]);
+ expect(await listSystemFonts()).toEqual([]);
});
- it("reduces the faces to sorted, deduplicated families", async () => {
+ it("reduces the faces to sorted, deduplicated families, told apart by advance width", async () => {
vi.stubGlobal("queryLocalFonts", async () => [
face("Inter", "Regular"),
face("Inter", "Bold"),
face("Adwaita Mono", "Regular"),
face("Inter", "Italic")
]);
+ stubProbeCanvas(() => true, (family) => family.endsWith("Mono"));
- expect(await listSystemFontFamilies()).toEqual([ "Adwaita Mono", "Inter" ]);
+ expect(await listSystemFonts()).toEqual([
+ { family: "Adwaita Mono", monospace: true },
+ { family: "Inter", monospace: false }
+ ]);
});
it("returns nothing when the query is refused, so the picker keeps the stock list", async () => {
@@ -150,7 +156,7 @@ describe("listSystemFontFamilies", () => {
throw new DOMException("denied", "NotAllowedError");
});
- expect(await listSystemFontFamilies()).toEqual([]);
+ expect(await listSystemFonts()).toEqual([]);
});
it("leaves out a family the engine measures but will not draw", async () => {
@@ -158,7 +164,7 @@ describe("listSystemFontFamilies", () => {
stubProbeCanvas((family) => family !== "Unifont");
// Offering it would let the interface be set in a font that renders nothing at all.
- expect(await listSystemFontFamilies()).toEqual([ "Inter" ]);
+ expect(await listSystemFonts()).toEqual([ { family: "Inter", monospace: false } ]);
});
it("leaves out a family that draws one of the two scripts and not the other", async () => {
@@ -167,13 +173,17 @@ describe("listSystemFontFamilies", () => {
// would be enough to pass a family that cannot draw a word of Japanese.
stubProbeCanvas((family, character) => !(family === "Latin Only" && character === "日"));
- expect(await listSystemFontFamilies()).toEqual([ "Inter" ]);
+ expect(await listSystemFonts()).toEqual([ { family: "Inter", monospace: false } ]);
});
it("keeps every family where there is no canvas to judge them on", async () => {
vi.stubGlobal("queryLocalFonts", async () => [ face("Inter", "Regular"), face("Unifont", "Regular") ]);
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
- expect(await listSystemFontFamilies()).toEqual([ "Inter", "Unifont" ]);
+ // Nothing is judged and nothing is told apart, so every family stays and none is monospace.
+ expect(await listSystemFonts()).toEqual([
+ { family: "Inter", monospace: false },
+ { family: "Unifont", monospace: false }
+ ]);
});
});
diff --git a/apps/client/src/services/font.ts b/apps/client/src/services/font.ts
index 96105b34e3..a7e0e69797 100644
--- a/apps/client/src/services/font.ts
+++ b/apps/client/src/services/font.ts
@@ -40,29 +40,39 @@ export function applyFontsFromOptions() {
newLink.addEventListener("error", () => newLink.remove(), { once: true });
}
+/** An installed font family, and whether it advances every character by the same width. */
+export interface SystemFont {
+ family: string;
+ monospace: boolean;
+}
+
/**
- * The font families installed on this device, sorted, for the font picker to offer. Deduplicated by
- * family: `queryLocalFonts()` reports one entry per face, so a family with four weights arrives four
- * times.
+ * The fonts installed on this device, sorted by family, for the font picker to offer. Deduplicated
+ * by family: `queryLocalFonts()` reports one entry per face, so a family with four weights arrives
+ * four times.
*
* Empty wherever the runtime does not answer — the API is Chromium-only, needs a secure context, and
* rejects while the `local-fonts` permission is denied. Callers fall back to the stock list, which is
* what every runtime other than the desktop app gets.
*/
-export async function listSystemFontFamilies(): Promise<string[]> {
+export async function listSystemFonts(): Promise<SystemFont[]> {
if (typeof window.queryLocalFonts !== "function") {
return [];
}
try {
const faces = await window.queryLocalFonts();
- const families = [ ...new Set(faces.map(({ family }) => family)) ];
+ const families = [ ...new Set(faces.map(({ family }) => family)) ].sort((a, b) => a.localeCompare(b));
const context = createProbeContext();
- // Nothing to draw on, so nothing is judged and every family stays on the list.
- const drawable = context ? families.filter((family) => rendersText(context, family)) : families;
+ // Nothing to draw on, so nothing is judged and nothing is told apart.
+ if (!context) {
+ return families.map((family) => ({ family, monospace: false }));
+ }
- return drawable.sort((a, b) => a.localeCompare(b));
+ return families
+ .filter((family) => rendersText(context, family))
+ .map((family) => ({ family, monospace: isMonospace(context, family) }));
} catch {
return [];
}
@@ -113,6 +123,17 @@ function rendersText(context: CanvasRenderingContext2D, family: string): boolean
return true;
}
+/**
+ * Whether the family advances every character by the same width, compared at the narrowest and the
+ * widest Latin letter. It is the one distinction a browser can draw between installed families:
+ * nothing reports whether a face is serif or sans, so the picker groups by this alone.
+ */
+function isMonospace(context: CanvasRenderingContext2D, family: string): boolean {
+ context.font = `${PROBE_FONT_SIZE}px "${family}"`;
+
+ return context.measureText("i").width === context.measureText("W").width;
+}
+
/** Whether any pixel was covered, read from the alpha channel — the colour drawn in does not matter. */
function isAnythingPainted({ data }: ImageData): boolean {
for (let offset = 3; offset < data.length; offset += 4) {
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index dc743aa254..ab441cc7e7 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1830,7 +1830,7 @@
"apply_changes": "Reload to apply changes",
"generic-fonts": "Generic fonts",
"user-fonts": "Custom fonts",
- "system-fonts": "System fonts",
+ "proportional-system-fonts": "Proportional fonts",
"sans-serif-system-fonts": "Sans-serif fonts",
"serif-system-fonts": "Serif fonts",
"monospace-system-fonts": "Monospace fonts",
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 c8eb97fc6f..38843341f1 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
@@ -7,7 +7,7 @@ const mocks = vi.hoisted(() => ({
mobile: false,
stored: {} as Record<string, string | boolean>,
userFonts: [] as { noteId: string; title: string; blobId: string }[],
- systemFonts: [] as string[]
+ systemFonts: [] as { family: string; monospace: boolean }[]
}));
// Both the desktop card and the illustrated layout choices turn on which kind of client this is.
@@ -44,7 +44,7 @@ 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")>()),
- listSystemFontFamilies: async () => mocks.systemFonts
+ listSystemFonts: async () => mocks.systemFonts
}));
// useNoteTitle names the font a font option points at; the listing above is what the picker lists.
@@ -158,13 +158,18 @@ describe("the font settings", () => {
it("offers the fonts installed on the device in place of the guessed families", async () => {
mocks.stored = { overrideThemeFonts: true };
- mocks.systemFonts = [ "Adwaita Mono", "Inter" ];
+ mocks.systemFonts = [
+ { family: "Adwaita Mono", monospace: true },
+ { family: "Inter", monospace: false }
+ ];
open();
await act(async () => {});
await act(async () => (fontRows()[0] as HTMLElement).click());
const headers = [ ...document.querySelectorAll(".font-picker-list .dropdown-header") ].map((header) => header.textContent);
- expect(headers).toContain("fonts.system-fonts");
+ // Split by the one thing a browser can tell about an installed family.
+ expect(headers).toContain("fonts.proportional-system-fonts");
+ expect(headers).toContain("fonts.monospace-system-fonts");
// The named families are a guess at what a device has, and go once there is an answer.
expect(headers).not.toContain("fonts.sans-serif-system-fonts");
// The generics resolve wherever Trilium runs, so they stay.
@@ -177,13 +182,13 @@ describe("the font settings", () => {
it("keeps the named families on a server build, which cannot ask what the device has", async () => {
mocks.electron = false;
mocks.stored = { overrideThemeFonts: true };
- mocks.systemFonts = [ "Inter" ];
+ mocks.systemFonts = [ { family: "Inter", monospace: false } ];
open();
await act(async () => {});
await act(async () => (fontRows()[0] as HTMLElement).click());
const headers = [ ...document.querySelectorAll(".font-picker-list .dropdown-header") ].map((header) => header.textContent);
- expect(headers).not.toContain("fonts.system-fonts");
+ expect(headers).not.toContain("fonts.proportional-system-fonts");
expect(headers).toContain("fonts.sans-serif-system-fonts");
});
@@ -197,6 +202,18 @@ describe("the font settings", () => {
});
});
+ it("heads only the half of the split that has fonts in it", async () => {
+ mocks.stored = { overrideThemeFonts: true };
+ mocks.systemFonts = [ { family: "Inter", monospace: false } ];
+ open();
+ await act(async () => {});
+ await act(async () => (fontRows()[0] as HTMLElement).click());
+
+ const headers = [ ...document.querySelectorAll(".font-picker-list .dropdown-header") ].map((header) => header.textContent);
+ expect(headers).toContain("fonts.proportional-system-fonts");
+ expect(headers).not.toContain("fonts.monospace-system-fonts");
+ });
+
describe("the layout choices", () => {
it("gives each an illustrated card of its own, side by side", () => {
open();
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.tsx b/apps/client/src/widgets/type_widgets/options/appearance.tsx
index b1d65a7675..5a7fa1734d 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.tsx
+++ b/apps/client/src/widgets/type_widgets/options/appearance.tsx
@@ -9,7 +9,7 @@ import { useEffect, useMemo, useState } from "preact/hooks";
import zoomService from "../../../components/zoom";
import { ColorScheme, resolveColorScheme, THEME_FAMILY_SCHEMES } from "../../../services/color_scheme";
import { getCustomFonts, registerFontNote } from "../../../services/custom_fonts";
-import { listSystemFontFamilies } from "../../../services/font";
+import { listSystemFonts, type SystemFont } from "../../../services/font";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import { isElectron, isMobile, reloadFrontendApp } from "../../../services/utils";
@@ -507,7 +507,7 @@ function Fonts() {
*/
function useFontGroups(): FontGroup[] {
const [ customFonts, setCustomFonts ] = useState<UserFont[]>([]);
- const systemFonts = useSystemFontFamilies();
+ const systemFonts = useSystemFonts();
useEffect(() => {
let cancelled = false;
@@ -542,9 +542,7 @@ function useFontGroups(): FontGroup[] {
}, []);
return useMemo(() => {
- const stockGroups = systemFonts.length
- ? [ GENERIC_FONTS, { title: t("fonts.system-fonts"), items: systemFonts.map((value) => ({ value })) } ]
- : FONT_FAMILIES;
+ const stockGroups = systemFonts.length ? installedFontGroups(systemFonts) : FONT_FAMILIES;
// Ahead of the rest: a font the user went and added is the one they are looking for.
return customFonts.length
@@ -557,21 +555,41 @@ function useFontGroups(): FontGroup[] {
}
/**
- * The families installed on this device, empty everywhere but the desktop app. The API behind
- * {@link listSystemFontFamilies} also exists in a browser served over HTTPS, where reading it would
- * cost the user a permission prompt for a list the desktop app can have for free — so the ask is
- * kept to the one runtime that grants it itself (see the `local-fonts` entry in
- * `web_contents_security.ts`).
+ * 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
+ * goes, and an empty half is left out rather than headed.
*/
-function useSystemFontFamilies(): string[] {
- const [ families, setFamilies ] = useState<string[]>([]);
+function installedFontGroups(systemFonts: SystemFont[]): FontGroup[] {
+ const groups = [ GENERIC_FONTS ];
+ const named: [ string, SystemFont[] ][] = [
+ [ t("fonts.proportional-system-fonts"), systemFonts.filter(({ monospace }) => !monospace) ],
+ [ t("fonts.monospace-system-fonts"), systemFonts.filter(({ monospace }) => monospace) ]
+ ];
+
+ for (const [ title, fonts ] of named) {
+ if (fonts.length) {
+ groups.push({ title, items: fonts.map(({ family }) => ({ value: family })) });
+ }
+ }
+
+ return groups;
+}
+
+/**
+ * The fonts installed on this device, empty everywhere but the desktop app. The API behind
+ * {@link listSystemFonts} also exists in a browser served over HTTPS, where reading it would cost
+ * the user a permission prompt for a list the desktop app can have for free — so the ask is kept to
+ * the one runtime that grants it itself (see the `local-fonts` entry in `web_contents_security.ts`).
+ */
+function useSystemFonts(): SystemFont[] {
+ const [ fonts, setFonts ] = useState<SystemFont[]>([]);
useEffect(() => {
if (!isElectron()) return;
let cancelled = false;
- void listSystemFontFamilies().then((found) => {
- if (!cancelled) setFamilies(found);
+ void listSystemFonts().then((found) => {
+ if (!cancelled) setFonts(found);
});
return () => {
@@ -579,7 +597,7 @@ function useSystemFontFamilies(): string[] {
};
}, []);
- return families;
+ return fonts;
}
interface FontProps {
diff --git a/apps/desktop/src/services/web_contents_security.ts b/apps/desktop/src/services/web_contents_security.ts
index d6dd5d2d84..090ff39f0c 100644
--- a/apps/desktop/src/services/web_contents_security.ts
+++ b/apps/desktop/src/services/web_contents_security.ts
@@ -145,7 +145,7 @@ export function hardenWebviewPreferences(webPreferences: Electron.WebPreferences
* hands out a handle for a file the user picked in an OS dialog, so the grant
* cannot reach anything the user did not choose.
* `local-fonts` lets the appearance settings offer the fonts installed on
- * this device (see `listSystemFontFamilies`); Chromium routes it through the
+ * this device (see `listSystemFonts`); Chromium routes it through the
* *check* handler rather than the request handler, so granting it here is
* what keeps the picker from falling back to the stock list.
* - `guest`: the `<webview>` partition hosting arbitrary remote pages from