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 the fonts installed on this device on the desktop app
Elian Dorane70bbe6c6496
diff --git a/apps/client/src/services/font.spec.ts b/apps/client/src/services/font.spec.tsindex bb13defa52..843e7eab50 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 } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { applyFontsFromOptions, createFontStylesheetLink } from "./font.js";+import { applyFontsFromOptions, createFontStylesheetLink, listSystemFontFamilies } from "./font.js";function fontLinkHrefs() {return Array.from(document.head.querySelectorAll<HTMLLinkElement>("link[data-font-stylesheet]"))@@ -87,3 +87,38 @@ describe("font service", () => {expect(hrefs[1]).toBe("style.css");});});++describe("listSystemFontFamilies", () => {+ /** 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}` };+ }++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("returns nothing where the runtime does not expose the API", async () => {+ expect(window.queryLocalFonts).toBeUndefined();+ expect(await listSystemFontFamilies()).toEqual([]);+ });++ it("reduces the faces to sorted, deduplicated families", async () => {+ vi.stubGlobal("queryLocalFonts", async () => [+ face("Inter", "Regular"),+ face("Inter", "Bold"),+ face("Adwaita Mono", "Regular"),+ face("Inter", "Italic")+ ]);++ expect(await listSystemFontFamilies()).toEqual([ "Adwaita Mono", "Inter" ]);+ });++ it("returns nothing when the query is refused, so the picker keeps the stock list", async () => {+ vi.stubGlobal("queryLocalFonts", async () => {+ throw new DOMException("denied", "NotAllowedError");+ });++ expect(await listSystemFontFamilies()).toEqual([]);+ });+});diff --git a/apps/client/src/services/font.ts b/apps/client/src/services/font.tsindex b42427117d..874f3fbd08 100644--- a/apps/client/src/services/font.ts+++ b/apps/client/src/services/font.ts@@ -39,3 +39,25 @@ export function applyFontsFromOptions() {// If the new stylesheet fails to load, keep the previous one rather than dropping fonts entirely.newLink.addEventListener("error", () => newLink.remove(), { once: true });}++/**+ * 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.+ *+ * 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[]> {+ if (typeof window.queryLocalFonts !== "function") {+ return [];+ }++ try {+ const faces = await window.queryLocalFonts();+ return [ ...new Set(faces.map(({ family }) => family)) ].sort((a, b) => a.localeCompare(b));+ } catch {+ return [];+ }+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a8065405b0..5a3ecaf11c 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1830,6 +1830,7 @@"apply_changes": "Reload to apply changes","generic-fonts": "Generic fonts","user-fonts": "Custom fonts",+ "system-fonts": "System fonts","sans-serif-system-fonts": "Sans-serif system fonts","serif-system-fonts": "Serif system fonts","monospace-system-fonts": "Monospace system fonts",diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.tsindex 133f3009cc..e3df790d09 100644--- a/apps/client/src/types.d.ts+++ b/apps/client/src/types.d.ts@@ -64,6 +64,21 @@ declare global {electronApi?: ElectronApi;/** Present only in the standalone build, where the stack runs in this browser. */standaloneApi?: StandaloneApi;++ /**+ * Chromium's Local Font Access API, absent from the DOM typings. Defined only in a secure+ * context on Chromium, and it rejects unless the `local-fonts` permission is granted — see+ * `listSystemFontFamilies`, which is the only caller.+ */+ queryLocalFonts?: () => Promise<FontData[]>;+ }++ /** One installed font face, as {@link Window.queryLocalFonts} reports it. */+ interface FontData {+ family: string;+ fullName: string;+ postscriptName: string;+ style: string;}diff --git a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsxindex a03659d771..c8eb97fc6f 100644--- a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx@@ -6,7 +6,8 @@ const mocks = vi.hoisted(() => ({electron: true,mobile: false,stored: {} as Record<string, string | boolean>,- userFonts: [] as { noteId: string; title: string; blobId: string }[]+ userFonts: [] as { noteId: string; title: string; blobId: string }[],+ systemFonts: [] as string[]}));// Both the desktop card and the illustrated layout choices turn on which kind of client this is.@@ -40,6 +41,12 @@ vi.mock("../../../services/custom_fonts", () => ({registerFontNote: async (_noteId: string, family: string) => ({ family })}));+// 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+}));+// useNoteTitle names the font a font option points at; the listing above is what the picker lists.vi.mock("../../react/hooks", async (importOriginal) => ({...(await importOriginal<typeof import("../../react/hooks")>()),@@ -57,6 +64,7 @@ beforeEach(() => {mocks.mobile = false;mocks.stored = {};mocks.userFonts = [];+ mocks.systemFonts = [];Object.defineProperty(document, "fonts", {configurable: true,value: { add: vi.fn(), delete: vi.fn() }@@ -148,6 +156,37 @@ describe("the font settings", () => {expect(headers).toContain("fonts.generic-fonts");});+ it("offers the fonts installed on the device in place of the guessed families", async () => {+ mocks.stored = { overrideThemeFonts: true };+ mocks.systemFonts = [ "Adwaita Mono", "Inter" ];+ 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");+ // 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.+ expect(headers).toContain("fonts.generic-fonts");++ const listed = [ ...document.querySelectorAll(".font-picker-list .dropdown-item") ].map((item) => item.textContent?.trim());+ expect(listed).toEqual(expect.arrayContaining([ "Adwaita Mono", "Inter" ]));+ });++ 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" ];+ 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).toContain("fonts.sans-serif-system-fonts");+ });+it("leaves ligatures alone, since they come from the theme's own font", () => {open();diff --git a/apps/client/src/widgets/type_widgets/options/appearance.tsx b/apps/client/src/widgets/type_widgets/options/appearance.tsxindex 14f204e5b4..a0932ec9b0 100644--- a/apps/client/src/widgets/type_widgets/options/appearance.tsx+++ b/apps/client/src/widgets/type_widgets/options/appearance.tsx@@ -9,6 +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 { t } from "../../../services/i18n";import server from "../../../services/server";import { isElectron, isMobile, reloadFrontendApp } from "../../../services/utils";@@ -83,17 +84,21 @@ interface FontGroup {items: FontFamilyEntry[];}+/** Families the browser resolves for itself, so they hold wherever Trilium runs. */+const GENERIC_FONTS: FontGroup = {+ title: t("fonts.generic-fonts"),+ items: [+ { value: "theme", label: t("fonts.theme_defined") },+ { value: "system", label: t("fonts.system-default") },+ { value: "serif", label: t("fonts.serif") },+ { value: "sans-serif", label: t("fonts.sans-serif") },+ { value: "monospace", label: t("fonts.monospace") }+ ]+};++/** Named families, offered where the device's own fonts cannot be listed (see {@link useFontGroups}). */const FONT_FAMILIES: FontGroup[] = [- {- title: t("fonts.generic-fonts"),- items: [- { value: "theme", label: t("fonts.theme_defined") },- { value: "system", label: t("fonts.system-default") },- { value: "serif", label: t("fonts.serif") },- { value: "sans-serif", label: t("fonts.sans-serif") },- { value: "monospace", label: t("fonts.monospace") }- ]- },+ GENERIC_FONTS,{title: t("fonts.sans-serif-system-fonts"),items: [{ value: "Arial" }, { value: "Verdana" }, { value: "Helvetica" }, { value: "Tahoma" }, { value: "Trebuchet MS" }, { value: "Microsoft YaHei" }]@@ -494,9 +499,13 @@ function Fonts() {* The picker's groups, with the fonts the user labelled `#customFont` appended. Those are also* registered with the document for as long as the page is open, so the picker draws each specimen* in the font it names.+ *+ * Where the device's own fonts can be listed, they stand in for the named families: the stock list+ * is a guess at what a device has, and half of it does not resolve on any given one.*/function useFontGroups(): FontGroup[] {const [ customFonts, setCustomFonts ] = useState<UserFont[]>([]);+ const systemFonts = useSystemFontFamilies();useEffect(() => {let cancelled = false;@@ -530,13 +539,45 @@ function useFontGroups(): FontGroup[] {};}, []);- // Ahead of the stock families: a font the user went and added is the one they are looking for.- return useMemo(() => (customFonts.length- ? [ {- title: t("fonts.user-fonts"),- items: customFonts.map(({ noteId, title }) => ({ value: customFontOption(noteId), label: title }))- }, ...FONT_FAMILIES ]- : FONT_FAMILIES), [ customFonts ]);+ return useMemo(() => {+ const stockGroups = systemFonts.length+ ? [ GENERIC_FONTS, { title: t("fonts.system-fonts"), items: systemFonts.map((value) => ({ value })) } ]+ : FONT_FAMILIES;++ // Ahead of the rest: a font the user went and added is the one they are looking for.+ return customFonts.length+ ? [ {+ title: t("fonts.user-fonts"),+ items: customFonts.map(({ noteId, title }) => ({ value: customFontOption(noteId), label: title }))+ }, ...stockGroups ]+ : stockGroups;+ }, [ customFonts, systemFonts ]);+}++/**+ * 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`).+ */+function useSystemFontFamilies(): string[] {+ const [ families, setFamilies ] = useState<string[]>([]);++ useEffect(() => {+ if (!isElectron()) return;++ let cancelled = false;+ void listSystemFontFamilies().then((found) => {+ if (!cancelled) setFamilies(found);+ });++ return () => {+ cancelled = true;+ };+ }, []);++ return families;}interface FontProps {diff --git a/apps/desktop/src/services/web_contents_security.spec.ts b/apps/desktop/src/services/web_contents_security.spec.tsindex 048efd7e1d..36f3b6b64c 100644--- a/apps/desktop/src/services/web_contents_security.spec.ts+++ b/apps/desktop/src/services/web_contents_security.spec.ts@@ -293,6 +293,8 @@ describe("isPermissionAllowed", () => {// The Excalidraw canvas opens and saves files through the File System// Access API instead of `electronApi`.expect(isPermissionAllowed("app", "fileSystem")).toBe(true);+ // Lets the appearance settings list the fonts installed on this device.+ expect(isPermissionAllowed("app", "local-fonts")).toBe(true);// Guest session: only fullscreen (embedded video players). Remote// pages must not show OS notifications appearing to come from Trilium.@@ -300,6 +302,7 @@ describe("isPermissionAllowed", () => {expect(isPermissionAllowed("guest", "clipboard-sanitized-write")).toBe(false);expect(isPermissionAllowed("guest", "notifications")).toBe(false);expect(isPermissionAllowed("guest", "fileSystem")).toBe(false);+ expect(isPermissionAllowed("guest", "local-fonts")).toBe(false);// Everything else is denied everywhere.for (const permission of ["media", "geolocation", "midi", "hid", "serial", "usb", "pointerLock", "clipboard-read", "openExternal"]) {@@ -320,6 +323,8 @@ describe("isPermissionAllowedForOrigin", () => {expect(isPermissionAllowedForOrigin("app", "notifications", "https://www.youtube-nocookie.com/embed/x")).toBe(false);expect(isPermissionAllowedForOrigin("app", "clipboard-sanitized-write", "https://evil.example")).toBe(false);expect(isPermissionAllowedForOrigin("app", "fileSystem", "https://evil.example")).toBe(false);+ // The installed font list is a fingerprinting surface, so an embed does not get to read it.+ expect(isPermissionAllowedForOrigin("app", "local-fonts", "https://evil.example")).toBe(false);// Another host under our own scheme is not the app shell.expect(isPermissionAllowedForOrigin("app", "notifications", "trilium-app://evil")).toBe(false);// A missing / unparseable origin is treated as untrusted.diff --git a/apps/desktop/src/services/web_contents_security.ts b/apps/desktop/src/services/web_contents_security.tsindex 27a7b3efd6..d6dd5d2d84 100644--- a/apps/desktop/src/services/web_contents_security.ts+++ b/apps/desktop/src/services/web_contents_security.ts@@ -144,6 +144,10 @@ export function hardenWebviewPreferences(webPreferences: Electron.WebPreferences* `browser-fs-access` to insert an image or export a drawing. Chromium only* 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+ * *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* Web View notes. Fullscreen only (embedded video players) — a remote page* must not show OS notifications that appear to come from Trilium.@@ -154,7 +158,7 @@ export function hardenWebviewPreferences(webPreferences: Electron.WebPreferences* the default session. Fullscreen is the exception — granted for any origin.*/const PERMISSION_ALLOWLIST = {- app: new Set(["clipboard-sanitized-write", "fileSystem", "fullscreen", "notifications"]),+ app: new Set(["clipboard-sanitized-write", "fileSystem", "fullscreen", "local-fonts", "notifications"]),guest: new Set(["fullscreen"])} as const;