Skip to content

Build your personal knowledge base with Trilium Notes

feat(fonts): leave out installed families the engine will not draw

Elian Doran6d9c8e9268e1
diff --git a/apps/client/src/services/font.spec.ts b/apps/client/src/services/font.spec.ts
index 843e7eab50..0503e0ff2f 100644
--- a/apps/client/src/services/font.spec.ts
+++ b/apps/client/src/services/font.spec.ts
@@ -94,8 +94,39 @@ describe("listSystemFontFamilies", () => {
return { family, style, fullName: `${family} ${style}`, postscriptName: `${family}-${style}` };
}
+ /**
+ * Stands in for the canvas the probe draws on, since happy-dom has none. `paints` decides, per
+ * family and character, whether any pixel ends up covered — in a browser a character the family
+ * 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) {
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation((() => {
+ const drawn = { font: "", character: "" };
+
+ return {
+ canvas: { width: 40, height: 40 },
+ clearRect: () => {},
+ fillText: (character: string) => {
+ drawn.character = character;
+ },
+ getImageData: () => {
+ const family = drawn.font.match(/"(.+)"/)?.[1] ?? "";
+ return { data: new Uint8ClampedArray([ 0, 0, 0, paints(family, drawn.character) ? 255 : 0 ]) };
+ },
+ get font() {
+ return drawn.font;
+ },
+ set font(value: string) {
+ drawn.font = value;
+ }
+ };
+ }) as never);
+ }
+
afterEach(() => {
vi.unstubAllGlobals();
+ vi.restoreAllMocks();
});
it("returns nothing where the runtime does not expose the API", async () => {
@@ -121,4 +152,28 @@ describe("listSystemFontFamilies", () => {
expect(await listSystemFontFamilies()).toEqual([]);
});
+
+ it("leaves out a family the engine measures but will not draw", async () => {
+ vi.stubGlobal("queryLocalFonts", async () => [ face("Inter", "Regular"), face("Unifont", "Regular") ]);
+ 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" ]);
+ });
+
+ it("leaves out a family that draws one of the two scripts and not the other", async () => {
+ vi.stubGlobal("queryLocalFonts", async () => [ face("Inter", "Regular"), face("Latin Only", "Regular") ]);
+ // Each character is drawn on its own for this: probed as one string, the Latin one painting
+ // 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" ]);
+ });
+
+ 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" ]);
+ });
});
diff --git a/apps/client/src/services/font.ts b/apps/client/src/services/font.ts
index 874f3fbd08..96105b34e3 100644
--- a/apps/client/src/services/font.ts
+++ b/apps/client/src/services/font.ts
@@ -56,8 +56,70 @@ export async function listSystemFontFamilies(): Promise<string[]> {
try {
const faces = await window.queryLocalFonts();
- return [ ...new Set(faces.map(({ family }) => family)) ].sort((a, b) => a.localeCompare(b));
+ const families = [ ...new Set(faces.map(({ family }) => family)) ];
+ 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;
+
+ return drawable.sort((a, b) => a.localeCompare(b));
} catch {
return [];
}
}
+
+/**
+ * One Latin and one CJK character, each drawn on its own. A character a family does not cover falls
+ * back to one that does and paints, so a character that paints nothing can only be one the family
+ * claims and cannot draw. Drawing them together would hide that: the covered one paints, and the
+ * count says the family is fine.
+ */
+const PROBE_CHARACTERS = [ "A", "日" ];
+
+/** Big enough that a light glyph still covers a pixel once it is rasterized. */
+const PROBE_FONT_SIZE = 20;
+
+/** The surface every family is drawn on, or `null` where the runtime offers no canvas. */
+function createProbeContext() {
+ const canvas = document.createElement("canvas");
+ canvas.width = PROBE_FONT_SIZE * 2;
+ canvas.height = PROBE_FONT_SIZE * 2;
+
+ return canvas.getContext("2d", { willReadFrequently: true });
+}
+
+/**
+ * Whether text set in `family` appears at all. A family can resolve, lend its metrics to the layout
+ * and still draw nothing — GNU Unifont installs bitmap faces beside its outline one, and the name
+ * matches a bitmap face that the engine measures but will not rasterize. Offering such a family
+ * would let the interface be set in a font that leaves it correctly laid out and invisible.
+ *
+ * One `context` serves every family: each character is cleared before the next is drawn, and the
+ * font is named again for each.
+ */
+function rendersText(context: CanvasRenderingContext2D, family: string): boolean {
+ const { width, height } = context.canvas;
+
+ for (const character of PROBE_CHARACTERS) {
+ context.clearRect(0, 0, width, height);
+ context.font = `${PROBE_FONT_SIZE}px "${family}"`;
+ context.fillText(character, 0, PROBE_FONT_SIZE * 1.5);
+
+ if (!isAnythingPainted(context.getImageData(0, 0, width, height))) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/** 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) {
+ if (data[offset] !== 0) {
+ return true;
+ }
+ }
+
+ return false;
+}