Skip to content

Build your personal knowledge base with Trilium Notes

refactor(client): share one icon-glyph renderer across the maps

Elian Doran3546284f6a1e
diff --git a/apps/client/src/services/icon_glyphs.css b/apps/client/src/services/icon_glyphs.css
new file mode 100644
index 0000000000..4f740a61d6
--- /dev/null
+++ b/apps/client/src/services/icon_glyphs.css
@@ -0,0 +1,8 @@
+/* What an icon class is asked to resolve to, before it is drawn anywhere but in the page (see
+ icon_glyphs.ts). Out of sight and out of the way, but laid out: a pseudo-element of a
+ `display: none` element has no content to read. */
+.icon-glyph-probe {
+ position: absolute;
+ visibility: hidden;
+ pointer-events: none;
+}
diff --git a/apps/client/src/services/icon_glyphs.spec.ts b/apps/client/src/services/icon_glyphs.spec.ts
new file mode 100644
index 0000000000..81c8e1b1d9
--- /dev/null
+++ b/apps/client/src/services/icon_glyphs.spec.ts
@@ -0,0 +1,252 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ drawIconGlyph, type IconGlyph, loadIconFonts, placeGlyph, renderIconImage, resolveIconGlyphs,
+ warmIconFonts
+} from "./icon_glyphs";
+
+const uncheckedWindow = window as unknown as { glob: { iconRegistry?: unknown } };
+
+/**
+ * Two characters of the private-use block, which is where every icon pack numbers its icons — from
+ * the same run of numbers, which is why a character is only ever half of an answer here.
+ */
+const FILE_GLYPH = "\ue9a1";
+const CUBE_GLYPH = "\uf1c2";
+
+/**
+ * What the stylesheet makes of each icon class, as it is read back off the probe wearing it. Stubbed
+ * rather than written as CSS: this is drawn against a browser's own style resolution, which the test
+ * environment has none of.
+ */
+function answerWith(styles: Record<string, Partial<CSSStyleDeclaration>>) {
+ return vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudo) => {
+ const iconClass = (element as HTMLElement).className.replace("icon-glyph-probe", "").trim();
+ return (pseudo === "::before" ? styles[iconClass] ?? {} : {}) as CSSStyleDeclaration;
+ });
+}
+
+/** A canvas that records what it was asked to draw, there being none to draw on here. */
+function answerWithCanvas(metrics: Partial<TextMetrics> = {}) {
+ const context = {
+ font: "",
+ fillStyle: "",
+ textAlign: "",
+ textBaseline: "",
+ scale: vi.fn(),
+ fillText: vi.fn(),
+ measureText: vi.fn(() => ({
+ actualBoundingBoxLeft: 0,
+ actualBoundingBoxRight: 16,
+ actualBoundingBoxAscent: 14,
+ actualBoundingBoxDescent: 2,
+ ...metrics
+ }))
+ };
+ const canvas = {
+ width: 0,
+ height: 0,
+ getContext: () => context,
+ toDataURL: () => "data:image/png;base64,DRAWN"
+ };
+
+ const createElement = document.createElement.bind(document);
+ vi.spyOn(document, "createElement").mockImplementation((tagName: string, options?: unknown) =>
+ (tagName === "canvas" ? canvas : createElement(tagName, options as ElementCreationOptions)) as HTMLElement);
+
+ return { canvas, context };
+}
+
+/** Stands in for the browser's font set, which the test environment has none of either. */
+function answerWithFonts(load: (font: string, text?: string) => Promise<unknown>) {
+ const spy = vi.fn(load);
+ Object.defineProperty(document, "fonts", { configurable: true, value: { load: spy } });
+ return spy;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ Reflect.deleteProperty(document, "fonts");
+ delete uncheckedWindow.glob.iconRegistry;
+});
+
+describe("resolveIconGlyphs", () => {
+ it("reads the character and the font of each class, however quoted, and asks once per class", () => {
+ const resolve = answerWith({
+ "bx bx-file": { content: `"${FILE_GLYPH}"`, fontFamily: "boxicons" },
+ "mdi mdi-cube": { content: `'${CUBE_GLYPH}'`, fontFamily: "trilium-icon-pack-mdi" },
+ // A class that draws no icon, one the stylesheet says nothing about, and one whose
+ // character has nothing to be looked up in.
+ "bx bx-nothing": { content: "none", fontFamily: "boxicons" },
+ "bx bx-unknown": { content: "", fontFamily: "boxicons" },
+ "bx bx-fontless": { content: `"${FILE_GLYPH}"` }
+ });
+ const host = document.createElement("div");
+
+ const glyphs = resolveIconGlyphs([
+ "bx bx-file", "mdi mdi-cube", "bx bx-nothing", "bx bx-unknown", "bx bx-fontless", "bx bx-file"
+ ], host);
+
+ expect(glyphs.get("bx bx-file")).toEqual({ content: FILE_GLYPH, fontFamily: "boxicons" });
+ // A pack the user brought along, carried with the font that gives its numbering meaning.
+ expect(glyphs.get("mdi mdi-cube")).toEqual({ content: CUBE_GLYPH, fontFamily: "trilium-icon-pack-mdi" });
+ expect(glyphs.has("bx bx-nothing")).toBe(false);
+ expect(glyphs.has("bx bx-unknown")).toBe(false);
+ expect(glyphs.has("bx bx-fontless")).toBe(false);
+
+ // Five classes asked for six times: what a map of thousands of notes is spared.
+ expect(resolve).toHaveBeenCalledTimes(5);
+ // The probe is an element of no consequence, and is not left behind as one.
+ expect(host.childElementCount).toBe(0);
+ });
+
+ it("takes the probe back out, out of the page itself by default, even where styles cannot be read", () => {
+ vi.spyOn(window, "getComputedStyle").mockImplementation(() => {
+ throw new Error("no styles to speak of");
+ });
+
+ expect(() => resolveIconGlyphs([ "bx bx-file" ])).toThrow();
+ expect(document.body.querySelector(".icon-glyph-probe")).toBeNull();
+ });
+});
+
+describe("loadIconFonts", () => {
+ it("asks for each font once, naming a character it has to cover", async () => {
+ const load = answerWithFonts(() => Promise.resolve([]));
+
+ await loadIconFonts([
+ { fontFamily: "boxicons", content: FILE_GLYPH },
+ { fontFamily: "boxicons", content: FILE_GLYPH },
+ { fontFamily: "trilium-icon-pack-mdi", content: CUBE_GLYPH }
+ ]);
+
+ expect(load).toHaveBeenCalledTimes(2);
+ expect(load).toHaveBeenCalledWith("16px boxicons", FILE_GLYPH);
+ expect(load).toHaveBeenCalledWith("16px trilium-icon-pack-mdi", CUBE_GLYPH);
+ });
+
+ it("is done either way, a font that cannot be promised being no reason not to draw", async () => {
+ const glyph: IconGlyph = { fontFamily: "boxicons", content: FILE_GLYPH };
+
+ // Somewhere with no font set to ask at all, which is where these tests themselves run.
+ await expect(loadIconFonts([ glyph ])).resolves.toBeUndefined();
+
+ answerWithFonts(() => Promise.reject(new Error("no such font")));
+ await expect(loadIconFonts([ glyph ])).resolves.toBeUndefined();
+ });
+});
+
+describe("warmIconFonts", () => {
+ it("loads every pack's font, each pack being found by the icon it names itself with", async () => {
+ uncheckedWindow.glob.iconRegistry = {
+ sources: [ { icon: "bx bx-package" }, { icon: "mdi mdi-cube" } ]
+ };
+ answerWith({
+ "bx bx-package": { content: `"${FILE_GLYPH}"`, fontFamily: "boxicons" },
+ "mdi mdi-cube": { content: `"${CUBE_GLYPH}"`, fontFamily: "trilium-icon-pack-mdi" }
+ });
+ const load = answerWithFonts(() => Promise.resolve([]));
+
+ await warmIconFonts();
+
+ expect(load.mock.calls.map(([ font ]) => font))
+ .toEqual([ "16px boxicons", "16px trilium-icon-pack-mdi" ]);
+ });
+
+ it("has nothing to load where the packs are not known yet", async () => {
+ const load = answerWithFonts(() => Promise.resolve([]));
+
+ await expect(warmIconFonts()).resolves.toBeUndefined();
+
+ expect(load).not.toHaveBeenCalled();
+ });
+});
+
+describe("placeGlyph", () => {
+ it("centres the ink of the glyph rather than the line box it was written on", () => {
+ const metrics = {
+ actualBoundingBoxLeft: 0,
+ actualBoundingBoxRight: 16,
+ actualBoundingBoxAscent: 14,
+ actualBoundingBoxDescent: 2
+ } as TextMetrics;
+
+ // 16 wide and 16 tall in a square of 20, so 2 of slack on each side; the baseline sits the
+ // ascent below that.
+ expect(placeGlyph(metrics, 20)).toEqual({
+ x: 2, y: 16, textAlign: "start", textBaseline: "alphabetic"
+ });
+ });
+
+ it("falls back to centring the square where the ink cannot be measured", () => {
+ const unmeasured = [
+ { actualBoundingBoxLeft: 0, actualBoundingBoxRight: 0, actualBoundingBoxAscent: 0, actualBoundingBoxDescent: 0 },
+ // A browser that carries no such measurements at all, and one that carries nonsense.
+ {},
+ { actualBoundingBoxLeft: 0, actualBoundingBoxRight: Infinity, actualBoundingBoxAscent: 8, actualBoundingBoxDescent: 0 }
+ ];
+
+ for (const metrics of unmeasured) {
+ expect(placeGlyph(metrics as TextMetrics, 20)).toEqual({
+ x: 10, y: 10, textAlign: "center", textBaseline: "middle"
+ });
+ }
+ });
+});
+
+describe("drawIconGlyph", () => {
+ const glyph: IconGlyph = { fontFamily: "boxicons", content: FILE_GLYPH };
+
+ it("writes the glyph at the size asked for, into a canvas of the density asked for", () => {
+ const { canvas, context } = answerWithCanvas();
+
+ expect(drawIconGlyph(glyph, { size: 20, color: "red", scale: 3 }))
+ .toBe("data:image/png;base64,DRAWN");
+
+ // The density is applied here and only here: a caller that had also scaled the size would
+ // be paying for a drawing nine times the area it can show.
+ expect([ canvas.width, canvas.height ]).toEqual([ 60, 60 ]);
+ expect(context.scale).toHaveBeenCalledWith(3, 3);
+ expect(context.font).toBe("20px boxicons");
+ expect(context.fillStyle).toBe("red");
+ expect(context.fillText).toHaveBeenCalledWith(FILE_GLYPH, 2, 16);
+ });
+
+ it("says so where there is no canvas to draw on", () => {
+ const createElement = document.createElement.bind(document);
+ vi.spyOn(document, "createElement").mockImplementation((tagName: string) =>
+ (tagName === "canvas" ? { getContext: () => null } : createElement(tagName)) as HTMLElement);
+
+ expect(drawIconGlyph(glyph, { size: 20, color: "black", scale: 1 })).toBeNull();
+ });
+});
+
+describe("renderIconImage", () => {
+ it("draws an icon once and keeps it, on the terms it was drawn on", async () => {
+ const resolve = answerWith({ "bx bx-kept": { content: `"${FILE_GLYPH}"`, fontFamily: "boxicons" } });
+ const { context } = answerWithCanvas();
+ answerWithFonts(() => Promise.resolve([]));
+
+ await expect(renderIconImage("bx bx-kept", { size: 20 }))
+ .resolves.toBe("data:image/png;base64,DRAWN");
+ await expect(renderIconImage("bx bx-kept", { size: 20 })).resolves.toBe("data:image/png;base64,DRAWN");
+ expect(resolve).toHaveBeenCalledTimes(1);
+
+ // Asked for on other terms, it is another drawing: the same icon larger, denser, or in
+ // another colour is not the one already drawn.
+ await renderIconImage("bx bx-kept", { size: 40 });
+ await renderIconImage("bx bx-kept", { size: 20, scale: 4 });
+ await renderIconImage("bx bx-kept", { size: 20, color: "red" });
+ expect(resolve).toHaveBeenCalledTimes(4);
+ expect(context.fillStyle).toBe("red");
+ });
+
+ it("keeps an icon it could not draw, rather than trying it again per frame", async () => {
+ const resolve = answerWith({ "bx bx-missing": { content: "none", fontFamily: "boxicons" } });
+
+ await expect(renderIconImage("bx bx-missing", { size: 20 })).resolves.toBeNull();
+ await expect(renderIconImage("bx bx-missing", { size: 20 })).resolves.toBeNull();
+
+ expect(resolve).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/client/src/services/icon_glyphs.ts b/apps/client/src/services/icon_glyphs.ts
new file mode 100644
index 0000000000..d49ead3969
--- /dev/null
+++ b/apps/client/src/services/icon_glyphs.ts
@@ -0,0 +1,244 @@
+import "./icon_glyphs.css";
+
+/**
+ * Icons, for the places they have to leave the page behind.
+ *
+ * An icon is a class in the page (`bx bx-file`), and only the stylesheet knows what that stands for:
+ * the icon pack's CSS sets a private-use character as the `content` of a pseudo-element and names the
+ * font it is drawn from. Anywhere the browser is not doing the drawing for us — a canvas, an SVG that
+ * will be read as a picture — both of those have to be asked for by hand, which is what this does.
+ *
+ * The font matters as much as the character: every pack numbers its icons from the same private-use
+ * block, so the character alone says nothing about which icon it is. Reading the family back off the
+ * element is what lets a user's own icon pack be drawn beside the built-in one.
+ */
+
+/** What an icon class stands for, once the stylesheet has been asked. */
+export interface IconGlyph {
+ /** The pack's font, as a CSS `font-family` value — ready to be put in a canvas `font`. */
+ fontFamily: string;
+ /** The character the pack draws the icon as. */
+ content: string;
+}
+
+/**
+ * What each of the given icon classes stands for, asked of the browser once per class.
+ *
+ * @param iconClasses the classes to resolve; repeats cost nothing.
+ * @param host an element to hang the probe off, so that it is styled as its surroundings are.
+ * @returns a glyph per class that draws one. A class no pack claims is simply absent.
+ */
+export function resolveIconGlyphs(iconClasses: Iterable<string>, host: HTMLElement = document.body) {
+ const glyphs = new Map<string, IconGlyph>();
+ const probe = document.createElement("span");
+ probe.className = PROBE_CLASS;
+ host.appendChild(probe);
+
+ try {
+ for (const iconClass of new Set(iconClasses)) {
+ probe.className = `${PROBE_CLASS} ${iconClass}`;
+
+ const glyph = readGlyph(probe);
+ if (glyph) {
+ glyphs.set(iconClass, glyph);
+ }
+ }
+ } finally {
+ probe.remove();
+ }
+
+ return glyphs;
+}
+
+/** The same for a single class, `null` where it draws no icon. See {@link resolveIconGlyphs}. */
+export function resolveIconGlyph(iconClass: string, host?: HTMLElement): IconGlyph | null {
+ return resolveIconGlyphs([ iconClass ], host).get(iconClass) ?? null;
+}
+
+/** The class the probe wears, which puts it out of sight while leaving it laid out (see the CSS). */
+const PROBE_CLASS = "icon-glyph-probe";
+
+/** What the stylesheet has made of the class the probe is wearing, or `null` if it draws nothing. */
+function readGlyph(probe: Element): IconGlyph | null {
+ const style = window.getComputedStyle(probe, "::before");
+
+ // Quoted as it is written in the stylesheet — `"\ead5"` — or `none` for a class that draws no
+ // icon at all.
+ const content = style.content?.replace(/^["']|["']$/g, "");
+ if (!content || content === "none") {
+ return null;
+ }
+
+ // Without a font there is nothing to look the character up in, and a canvas told to draw in a
+ // font of no name quietly keeps the one it had.
+ const fontFamily = style.fontFamily;
+ if (!fontFamily) {
+ return null;
+ }
+
+ return { fontFamily, content };
+}
+
+/**
+ * Waits for the fonts the given glyphs are drawn from to be available.
+ *
+ * A canvas asked to draw from a font it does not have yet says nothing about it and draws a row of
+ * tofu instead — unlike the page, which redraws itself once the font arrives. Note that it is the
+ * font's own arrival that is waited on here rather than `document.fonts.ready`, which promises only
+ * that the loads already under way have finished: a pack nothing on screen happens to be wearing has
+ * not begun loading at all, so waiting on the page would let it through undrawn.
+ */
+export async function loadIconFonts(glyphs: Iterable<IconGlyph>) {
+ /** One character per font, which is all the browser needs to know which faces to fetch. */
+ const fonts = new Map<string, string>();
+ for (const { fontFamily, content } of glyphs) {
+ fonts.set(fontFamily, content);
+ }
+
+ await Promise.all(Array.from(fonts, ([ fontFamily, content ]) => loadFont(fontFamily, content)));
+}
+
+/**
+ * Waits for every icon pack's font, for a drawing that cannot say yet which of them it will need.
+ *
+ * Each pack names an icon of its own to be known by, so one class per pack is enough to find the
+ * fonts without knowing how any of them are named.
+ */
+export function warmIconFonts(host?: HTMLElement) {
+ const packIcons = (glob.iconRegistry?.sources ?? []).map((source) => source.icon);
+ return loadIconFonts(resolveIconGlyphs(packIcons, host).values());
+}
+
+/** The size a font is asked for at; any valid one will do, the face being the same at every size. */
+const FONT_LOAD_SIZE = 16;
+
+async function loadFont(fontFamily: string, content: string) {
+ try {
+ await document.fonts?.load(`${FONT_LOAD_SIZE}px ${fontFamily}`, content);
+ } catch {
+ // Not being able to promise a font is no reason not to draw; at worst the icon is missing.
+ }
+}
+
+/** How an icon is drawn. See {@link renderIconImage}. */
+export interface IconImageOptions {
+ /** The side of the square it is drawn in, in CSS pixels. */
+ size: number;
+ /** What it is drawn in — any CSS colour. */
+ color?: string;
+ /**
+ * How many pixels of the drawing go to each CSS pixel. The display's own density by default,
+ * which is what keeps an icon sharp where it is shown; a drawing that will be scaled up again
+ * afterwards — a PNG rasterized from an SVG — asks for more.
+ */
+ scale?: number;
+}
+
+/**
+ * An icon drawn as a picture of its own, as a `data:` URL, or `null` where it cannot be drawn.
+ *
+ * For wherever an icon has to stand without the stylesheet that draws it: a map library that takes a
+ * picture per marker, an exported SVG that will be read as a picture and so may fetch nothing and
+ * resolve no fonts of the page.
+ *
+ * What has been drawn once is kept, since the same handful of icons is asked for over and over — a
+ * map is redrawn as it is panned, an SVG is written afresh at every pause in the editing. Failures
+ * are kept alongside the rest: a class that draws nothing will not draw anything the second time
+ * either, and asking again per frame would cost more than the answer is worth.
+ */
+export function renderIconImage(iconClass: string, options: IconImageOptions): Promise<string | null> {
+ const { size, color = DEFAULT_ICON_COLOR, scale = devicePixelRatio() } = options;
+ const key = `${size}|${scale}|${color}|${iconClass}`;
+
+ let image = renderedIcons.get(key);
+ if (!image) {
+ image = drawIcon(iconClass, { size, color, scale });
+ renderedIcons.set(key, image);
+ }
+ return image;
+}
+
+/** What an icon is drawn in unless it is asked for in something else. */
+const DEFAULT_ICON_COLOR = "black";
+
+/** What has already been drawn, by the icon and the terms it was drawn on. */
+const renderedIcons = new Map<string, Promise<string | null>>();
+
+async function drawIcon(iconClass: string, options: Required<IconImageOptions>) {
+ const glyph = resolveIconGlyph(iconClass);
+ if (!glyph) {
+ return null;
+ }
+
+ await loadIconFonts([ glyph ]);
+ return drawIconGlyph(glyph, options);
+}
+
+/**
+ * Draws a glyph centred in a square, as a `data:` URL — the drawing {@link renderIconImage} keeps.
+ *
+ * The square is `size` CSS pixels across and `size * scale` pixels of actual drawing, the glyph being
+ * written at the former into a canvas of the latter. Note that this is the only place the density is
+ * applied: a caller that also scales the size it asks for pays for it twice over, and a drawing four
+ * times the area it can show is carried in full by whatever ends up holding it.
+ *
+ * @returns the drawing, or `null` where the browser will not give a canvas to draw on.
+ */
+export function drawIconGlyph(glyph: IconGlyph, { size, color, scale }: Required<IconImageOptions>) {
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = Math.max(1, Math.round(size * scale));
+
+ const context = canvas.getContext("2d");
+ if (!context) {
+ return null;
+ }
+
+ context.scale(scale, scale);
+ context.font = `${size}px ${glyph.fontFamily}`;
+ context.fillStyle = color;
+
+ const placement = placeGlyph(context.measureText(glyph.content), size);
+ context.textAlign = placement.textAlign;
+ context.textBaseline = placement.textBaseline;
+ context.fillText(glyph.content, placement.x, placement.y);
+
+ return canvas.toDataURL();
+}
+
+/**
+ * Where a glyph of the given measurements is written for its ink to sit in the middle of the square.
+ *
+ * An icon font fills its own line box as it pleases — the character is a drawing, not a letter, and
+ * nothing holds it to the shape of one — so a glyph written on the middle line of the square lands
+ * wherever the pack happened to draw it. Measuring the ink itself and centring that instead is what
+ * keeps a row of icons from wandering up and down.
+ *
+ * Where the browser will not say how far the ink reaches, the glyph is centred on the square as a
+ * letter would be, which is right often enough and is all there is to go on.
+ */
+export function placeGlyph(metrics: TextMetrics, size: number) {
+ const left = metrics.actualBoundingBoxLeft;
+ const right = metrics.actualBoundingBoxRight;
+ const ascent = metrics.actualBoundingBoxAscent;
+ const descent = metrics.actualBoundingBoxDescent;
+
+ const width = left + right;
+ const height = ascent + descent;
+ if (!(width > 0) || !(height > 0) || !Number.isFinite(width) || !Number.isFinite(height)) {
+ return { x: size / 2, y: size / 2, textAlign: "center", textBaseline: "middle" } as const;
+ }
+
+ // The ink runs from `x - left` to `x + right`, and is centred when the first of those is at half
+ // of what the square has left over. The same holds of the ascent going up from the baseline.
+ return {
+ x: (size - width) / 2 + left,
+ y: (size - height) / 2 + ascent,
+ textAlign: "start",
+ textBaseline: "alphabetic"
+ } as const;
+}
+
+/** The display's density, as a number a drawing can be scaled by even where there is no window. */
+function devicePixelRatio() {
+ return window.devicePixelRatio || 1;
+}
diff --git a/apps/client/src/widgets/note_map/NoteMap.css b/apps/client/src/widgets/note_map/NoteMap.css
index 3e3d1ebf5b..2c9a28e7c2 100644
--- a/apps/client/src/widgets/note_map/NoteMap.css
+++ b/apps/client/src/widgets/note_map/NoteMap.css
@@ -98,11 +98,3 @@
color: var(--note-icon-color, var(--main-background-color));
}
}
-
-/* What an icon class is asked to resolve to before the map is drawn (see icons.ts). Out of sight and
- out of the way, but laid out: a pseudo-element of a `display: none` element has no content to read. */
-.icon-glyph-probe {
- position: absolute;
- visibility: hidden;
- pointer-events: none;
-}
diff --git a/apps/client/src/widgets/note_map/NoteMap.tsx b/apps/client/src/widgets/note_map/NoteMap.tsx
index 3416beaf72..76f3ec9298 100644
--- a/apps/client/src/widgets/note_map/NoteMap.tsx
+++ b/apps/client/src/widgets/note_map/NoteMap.tsx
@@ -8,6 +8,7 @@ import appContext from "../../components/app_context";
import FNote from "../../entities/fnote";
import link_context_menu from "../../menus/link_context_menu";
import hoisted_note from "../../services/hoisted_note";
+import { resolveIconGlyphs, warmIconFonts } from "../../services/icon_glyphs";
import { t } from "../../services/i18n";
import ActionButton from "../react/ActionButton";
import Button from "../react/Button";
@@ -15,7 +16,6 @@ import { useColorScheme, useElementSize, useNoteLabel, useTriliumOption } from "
import NoItems from "../react/NoItems";
import Slider from "../react/Slider";
import { loadNotesAndRelations, NoteMapLinkObject, NoteMapNodeObject, NotesAndRelationsData } from "./data";
-import { loadIconFont, resolveIconGlyphs } from "./icons";
import MapTypeSwitcher from "./MapTypeSwitcher";
import { CssData, setupRendering } from "./rendering";
import { isRootedAtCurrentNote, MapType, NOTE_MAP_TYPE_OPTION, NoteMapWidgetMode, rgb2hex, toMapType, usesReaderPreference } from "./utils";
@@ -87,8 +87,9 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {
loadNotesAndRelations(mapRootId, excludeRelations, includeRelations, mapType, widgetMode === "sidebar"),
// Awaited alongside the notes rather than after them: a canvas asked to draw from a font
// it does not have yet says nothing and draws tofu, and the map is painted the moment its
- // data lands.
- loadIconFont()
+ // data lands. Every pack's font, since which of them the map wears is not known until the
+ // notes are in hand — and by then there is no waiting left to do.
+ warmIconFonts()
]).then(([ notesAndRelations ]) => {
if (disposed || !containerRef.current || !styleResolverRef.current) return;
diff --git a/apps/client/src/widgets/note_map/icons.spec.ts b/apps/client/src/widgets/note_map/icons.spec.ts
deleted file mode 100644
index 59f54be127..0000000000
--- a/apps/client/src/widgets/note_map/icons.spec.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import { loadIconFont, resolveIconGlyphs } from "./icons";
-
-describe("resolveIconGlyphs", () => {
- afterEach(() => vi.restoreAllMocks());
-
- /**
- * What the stylesheet makes of each icon class, as it is read back off the probe wearing it.
- * Stubbed rather than written as CSS: the map is drawn against a browser's own style resolution,
- * which the test environment has none of.
- */
- const answerWith = (contents: Record<string, string>) => vi.spyOn(window, "getComputedStyle")
- .mockImplementation((element, pseudo) => {
- const className = (element as HTMLElement).className.replace("icon-glyph-probe ", "");
- return { content: pseudo === "::before" ? contents[className] : "" } as CSSStyleDeclaration;
- });
-
- it("reads what each class draws, however the stylesheet quotes it, and asks once per class", () => {
- const host = document.createElement("div");
- const resolve = answerWith({
- "bx bx-file": "\"\"",
- "bx bx-code": "''",
- // A class that draws no icon at all, and one the stylesheet says nothing about.
- "bx bx-nothing": "none",
- "bx bx-unknown": ""
- });
-
- const glyphs = resolveIconGlyphs([ "bx bx-file", "bx bx-code", "bx bx-nothing", "bx bx-unknown", "bx bx-file" ], host);
-
- expect(glyphs.get("bx bx-file")).toBe("");
- expect(glyphs.get("bx bx-code")).toBe("");
- expect(glyphs.has("bx bx-nothing")).toBe(false);
- expect(glyphs.has("bx bx-unknown")).toBe(false);
-
- // Four classes asked for five times: what a map of thousands of notes is spared.
- expect(resolve).toHaveBeenCalledTimes(4);
- // The probe is an element of no consequence, and is not left behind as one.
- expect(host.childElementCount).toBe(0);
- });
-
- it("takes the probe back out of the map even where the styles cannot be read", () => {
- const host = document.createElement("div");
- vi.spyOn(window, "getComputedStyle").mockImplementation(() => {
- throw new Error("no styles to speak of");
- });
-
- expect(() => resolveIconGlyphs([ "bx bx-file" ], host)).toThrow();
- expect(host.childElementCount).toBe(0);
- });
-});
-
-describe("loadIconFont", () => {
- afterEach(() => vi.restoreAllMocks());
-
- it("is done either way, a font that cannot be promised being no reason not to draw the map", async () => {
- // Somewhere with no font set to ask at all, which is where these tests themselves run.
- await expect(loadIconFont()).resolves.toBeUndefined();
-
- // And somewhere that has one and cannot promise the font.
- Object.defineProperty(document, "fonts", {
- configurable: true,
- value: { load: () => Promise.reject(new Error("no such font")) }
- });
-
- try {
- await expect(loadIconFont()).resolves.toBeUndefined();
- } finally {
- Reflect.deleteProperty(document, "fonts");
- }
- });
-});
diff --git a/apps/client/src/widgets/note_map/icons.ts b/apps/client/src/widgets/note_map/icons.ts
deleted file mode 100644
index eb622cc0e8..0000000000
--- a/apps/client/src/widgets/note_map/icons.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/** The font the note icons are drawn from, both in the page and on the map's canvas. */
-export const ICON_FONT_FAMILY = "boxicons";
-
-/**
- * The glyphs the given icon classes stand for, ready to be drawn on a canvas.
- *
- * An icon is a class in the page (`bx bx-file`) and a character in a font on the canvas, and only the
- * stylesheet knows which is which — the class sets it as the `content` of a pseudo-element. So each
- * class is asked of the browser once, by wearing it on an element of no consequence and reading back
- * what it resolved to, and the answers are kept for the drawing to look up per frame.
- *
- * @param host an element of the map to hang the probe off, so that it is styled as the map is.
- */
-export function resolveIconGlyphs(iconClasses: Iterable<string>, host: HTMLElement) {
- const glyphs = new Map<string, string>();
- const probe = document.createElement("span");
- // Hidden, but laid out: a pseudo-element of a `display: none` element resolves to no content at
- // all, which is precisely what is being asked for here.
- probe.className = "icon-glyph-probe";
- host.appendChild(probe);
-
- try {
- for (const iconClass of new Set(iconClasses)) {
- probe.className = `icon-glyph-probe ${iconClass}`;
- // Quoted as it is written in the stylesheet — `"\ead5"` — or `none` for a class that
- // draws no icon at all.
- const content = window.getComputedStyle(probe, "::before").content;
- const glyph = content?.replace(/^["']|["']$/g, "");
-
- if (glyph && glyph !== "none") {
- glyphs.set(iconClass, glyph);
- }
- }
- } finally {
- probe.remove();
- }
-
- return glyphs;
-}
-
-/**
- * Waits for the icon font to be available to the canvas, which — unlike the page — falls back to
- * another font without a word when it is not, drawing a row of tofu where the icons should be.
- */
-export async function loadIconFont() {
- try {
- await document.fonts?.load(`16px ${ICON_FONT_FAMILY}`);
- } catch {
- // Not being able to promise the font is no reason not to draw the map; at worst the icons of
- // its first paint are missing.
- }
-}
diff --git a/apps/client/src/widgets/note_map/rendering.ts b/apps/client/src/widgets/note_map/rendering.ts
index 53b2cd8fe0..e5b2eaf393 100644
--- a/apps/client/src/widgets/note_map/rendering.ts
+++ b/apps/client/src/widgets/note_map/rendering.ts
@@ -1,9 +1,9 @@
import type ForceGraph from "force-graph";
import type FNote from "../../entities/fnote";
+import type { IconGlyph } from "../../services/icon_glyphs";
import { escapeHtml } from "../../services/utils";
import { NoteMapLinkObject, NoteMapNodeObject, NotesAndRelationsData } from "./data";
-import { ICON_FONT_FAMILY } from "./icons";
import { getFitPadding, getHopDistances, isRootedAtCurrentNote, mixColors, NoteMapWidgetMode, withAlpha } from "./utils";
/** Roughly a second of simulation at 60 fps — see {@link setupFraming}. */
@@ -113,8 +113,8 @@ interface RenderData {
notesAndRelations: NotesAndRelationsData;
/** The element the graph's canvas lives in, watched for the user taking the view over. */
container: HTMLElement;
- /** What each note's icon classes resolve to as a character of the icon font — see icons.ts. */
- iconGlyphs: Map<string, string>;
+ /** What each note's icon class resolves to, as the icon pack draws it — see icon_glyphs.ts. */
+ iconGlyphs: Map<string, IconGlyph>;
}
/** @returns a teardown function to call when the graph is discarded. */
@@ -339,10 +339,12 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO
}
ctx.fillStyle = getNodeColors(node, cssData).icon;
- ctx.font = `${size}px ${ICON_FONT_FAMILY}`;
+ // The pack's own font rather than one font for the map: a note may wear an icon from a pack
+ // the user brought along, whose characters are numbered as the built-in one's are.
+ ctx.font = `${size}px ${glyph.fontFamily}`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
- ctx.fillText(glyph, x, y);
+ ctx.fillText(glyph.content, x, y);
}
/**