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
fix(fonts): name a font family to CSS as a string
Elian Doranac3d5db24bf4
diff --git a/apps/client/src/services/font.spec.ts b/apps/client/src/services/font.spec.tsindex 6b27ab61f2..166f90342b 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, filterAvailableFamilies, listSystemFonts } from "./font.js";+import { applyFontsFromOptions, createFontStylesheetLink, filterAvailableFamilies, listSystemFonts, quoteFamily } from "./font.js";function fontLinkHrefs() {return Array.from(document.head.querySelectorAll<HTMLLinkElement>("link[data-font-stylesheet]"))@@ -241,3 +241,29 @@ describe("filterAvailableFamilies", () => {expect(filterAvailableFamilies([ "Garamond", "Luminari" ])).toEqual([ "Garamond", "Luminari" ]);});});++/*+ * Read off the function rather than off anything it is written into: happy-dom drops the quotes as+ * it parses a declaration, so `style.fontFamily` reads the same either way and an assertion made+ * through the DOM would hold with the quoting gone.+ */+describe("quoteFamily", () => {+ it("quotes what could not be read unquoted, and leaves the generics as they are", () => {+ // A name beginning with a digit is no identifier, and unquoted takes the whole declaration+ // with it. Windows ships this one; queryLocalFonts() reports whatever is installed.+ expect(quoteFamily("8514oem")).toBe(`"8514oem"`);+ expect(quoteFamily("Trebuchet MS")).toBe(`"Trebuchet MS"`);++ // A generic names a browser default, which quoting would turn into a request for a font+ // that happens to be called "monospace".+ expect(quoteFamily("monospace")).toBe("monospace");+ expect(quoteFamily("ui-sans-serif")).toBe("ui-sans-serif");++ // The quote would close the string early and leave the rest of it as CSS to be read.+ expect(quoteFamily(`Fo"o`)).toBe(`"Fo\\"o"`);+ expect(quoteFamily("Fo\\o")).toBe(`"Fo\\\\o"`);++ // No family is named, and naming an empty one would be no better.+ expect(quoteFamily("")).toBe("");+ });+});diff --git a/apps/client/src/services/font.ts b/apps/client/src/services/font.tsindex cfd087fb9f..a579cebdf3 100644--- a/apps/client/src/services/font.ts+++ b/apps/client/src/services/font.ts@@ -105,6 +105,29 @@ export function filterAvailableFamilies(candidates: string[]): string[] {return candidates.filter((family) => isAvailable(context, family));}+/**+ * A family name as it is named to CSS, whether in a stylesheet, a `style` attribute or a canvas+ * `font`. Unquoted, a name has to be a sequence of identifiers, so one beginning with a digit —+ * Windows ships `8514oem` — is invalid and takes the whole declaration with it. A name carrying a+ * quote would close the string early and leave the rest of it to be read as CSS.+ *+ * The generics are left alone: quoted, they stop naming a browser default and start asking for a+ * font that happens to be called "monospace".+ */+export function quoteFamily(family: string): string {+ if (!family || GENERIC_FAMILIES.has(family)) {+ return family;+ }++ return `"${family.replace(/[\\"]/g, "\\$&")}"`;+}++/** The keywords that name a browser default instead of a font, which only read as one unquoted. */+const GENERIC_FAMILIES = new Set([+ "serif", "sans-serif", "monospace", "cursive", "fantasy", "math", "emoji", "fangsong",+ "system-ui", "ui-serif", "ui-sans-serif", "ui-monospace", "ui-rounded"+]);+/*** 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@@ -116,7 +139,7 @@ function isAvailable(context: CanvasRenderingContext2D, family: string): booleancontext.font = `${PROBE_FONT_SIZE}px ${fallback}`;const fellBack = context.measureText(AVAILABILITY_TEXT).width;- context.font = `${PROBE_FONT_SIZE}px "${family}", ${fallback}`;+ context.font = `${PROBE_FONT_SIZE}px ${quoteFamily(family)}, ${fallback}`;if (context.measureText(AVAILABILITY_TEXT).width !== fellBack) {return true;}@@ -154,7 +177,7 @@ function rendersText(context: CanvasRenderingContext2D, family: string): booleanfor (const character of PROBE_CHARACTERS) {context.clearRect(0, 0, width, height);- context.font = `${PROBE_FONT_SIZE}px "${family}"`;+ context.font = `${PROBE_FONT_SIZE}px ${quoteFamily(family)}`;context.fillText(character, 0, PROBE_FONT_SIZE * 1.5);if (!isAnythingPainted(context.getImageData(0, 0, width, height))) {@@ -171,7 +194,7 @@ function rendersText(context: CanvasRenderingContext2D, family: string): boolean* 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}"`;+ context.font = `${PROBE_FONT_SIZE}px ${quoteFamily(family)}`;return context.measureText("i").width === context.measureText("W").width;}diff --git a/apps/client/src/widgets/type_widgets/options/appearance_fonts.tsx b/apps/client/src/widgets/type_widgets/options/appearance_fonts.tsxindex d600f33d63..fbdf3566de 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 { filterAvailableFamilies, listSystemFonts, type SystemFont } from "../../../services/font";+import { filterAvailableFamilies, listSystemFonts, quoteFamily, type SystemFont } from "../../../services/font";import { t } from "../../../services/i18n";import { isElectron } from "../../../services/utils";import { Card, OptionCardSection } from "../../react/Card";@@ -288,7 +288,7 @@ function Font({ label, description, sizeDescription, groups, fontFamilyOption, f// One of the user's own fonts names the note it is stored in, not a family the browser// could resolve; the family it was registered under is built from the same id.const noteId = customFontNoteId(value);- return noteId ? customFontFamily(noteId) : value;+ return noteId ? customFontFamily(noteId) : quoteFamily(value);};return (