Skip to content

Build your personal knowledge base with Trilium Notes

feat(mind-map): carry the node icons into the SVG and PNG exports

Elian Doran15bfeb642daf
diff --git a/apps/client/src/widgets/type_widgets/mind_map/export.spec.ts b/apps/client/src/widgets/type_widgets/mind_map/export.spec.ts
index 9a4ec4cb0b..68d2417e64 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/export.spec.ts
+++ b/apps/client/src/widgets/type_widgets/mind_map/export.spec.ts
@@ -160,6 +160,71 @@ describe("postProcessExportedSvg", () => {
expect(doc.querySelector("image")?.hasAttribute("preserveAspectRatio")).toBe(false);
});
+ it("writes each icon drawing once and stamps it out wherever it is worn", () => {
+ // The same icon on two nodes and another on a third: a drawing carried as text is the
+ // heaviest thing in the file, so it is written once and pointed at twice.
+ const star = "data:image/png;base64,STAR";
+ const icons = [
+ { x: 10, y: 20, size: 16, color: "rgb(20, 20, 20)", image: star },
+ { x: 30, y: 40, size: 16, color: "rgb(20, 20, 20)", image: star },
+ { x: 50, y: 60, size: 12, color: "rgb(20, 20, 20)", image: "data:image/png;base64,CUBE" }
+ ];
+
+ const result = postProcessExportedSvg(buildMind(), buildExportedSvg(), icons);
+
+ const doc = new DOMParser().parseFromString(result, "image/svg+xml");
+ const innerSvg = doc.documentElement.querySelector(":scope > svg");
+ const symbols = Array.from(innerSvg?.querySelectorAll("defs > symbol") ?? []);
+ expect(symbols.map((symbol) => symbol.querySelector("image")?.getAttribute("href")))
+ .toEqual([ star, "data:image/png;base64,CUBE" ]);
+
+ const uses = Array.from(innerSvg?.querySelectorAll(":scope > use") ?? []);
+ expect(uses.map((use) => [ use.getAttribute("href"), use.getAttribute("x"), use.getAttribute("width") ]))
+ .toEqual([
+ [ `#${symbols[0].id}`, "10", "16" ],
+ [ `#${symbols[0].id}`, "30", "16" ],
+ [ `#${symbols[1].id}`, "50", "12" ]
+ ]);
+ // The older spelling of the reference alongside the newer one, for whatever needs it.
+ expect(uses[0].getAttributeNS("http://www.w3.org/1999/xlink", "href")).toBe(`#${symbols[0].id}`);
+ // Only the drawings go in the defs, and every drawing is written inside the map layers.
+ expect(doc.documentElement.querySelectorAll(":scope > use, :scope > defs")).toHaveLength(0);
+ });
+
+ it("writes an icon that is a character as the character, centred on its square", () => {
+ const icons = [ { x: 10, y: 20, size: 16, color: "rgb(20, 20, 20)", text: "⭐" } ];
+
+ const result = postProcessExportedSvg(buildMind(), buildExportedSvg(), icons);
+
+ const doc = new DOMParser().parseFromString(result, "image/svg+xml");
+ const text = doc.querySelector("text");
+ expect(text?.textContent).toBe("⭐");
+ expect([ text?.getAttribute("x"), text?.getAttribute("y"), text?.getAttribute("dy") ])
+ .toEqual([ "18", "28", "0.35em" ]);
+ expect(text?.getAttribute("text-anchor")).toBe("middle");
+ expect(text?.getAttribute("fill")).toBe("rgb(20, 20, 20)");
+ // Nothing is drawn for it, so it costs the file no drawing.
+ expect(doc.querySelectorAll("defs")).toHaveLength(0);
+ });
+
+ it("leaves the pictures of the map paired with those of the export when it writes icons in", () => {
+ // The fit is carried over by counting the two against each other, which an icon written in
+ // beforehand would throw off — and quietly, the pairing simply being abandoned.
+ const mind = buildMind();
+ const drawn = document.createElement("img");
+ drawn.style.objectFit = "cover";
+ mind.nodes.appendChild(drawn);
+
+ const exportedSvg = `<svg xmlns="http://www.w3.org/2000/svg"><svg>` +
+ `<image width="240px" height="240px" href="a.png"/></svg></svg>`;
+ const icons = [ { x: 1, y: 2, size: 16, color: "black", image: "data:image/png;base64,STAR" } ];
+ const result = postProcessExportedSvg(mind, exportedSvg, icons);
+
+ const doc = new DOMParser().parseFromString(result, "image/svg+xml");
+ const picture = Array.from(doc.querySelectorAll("image")).find((image) => image.getAttribute("href") === "a.png");
+ expect(picture?.getAttribute("preserveAspectRatio")).toBe("xMidYMid slice");
+ });
+
it("adds no labels when the map has none, and returns unparseable input unchanged", () => {
const noLabels = postProcessExportedSvg(buildMind(), buildExportedSvg());
const doc = new DOMParser().parseFromString(noLabels, "image/svg+xml");
diff --git a/apps/client/src/widgets/type_widgets/mind_map/export.ts b/apps/client/src/widgets/type_widgets/mind_map/export.ts
index ba0f7cb5ae..e108dde602 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/export.ts
+++ b/apps/client/src/widgets/type_widgets/mind_map/export.ts
@@ -1,10 +1,12 @@
import type { MindElixirInstance } from "mind-elixir";
import { sanitizeNoteContentHtml } from "../../../services/sanitize_content";
+import { type ExportedIcon, renderExportedIcons } from "./icons";
import { loadImageData } from "./images";
const SVG_NS = "http://www.w3.org/2000/svg";
const XHTML_NS = "http://www.w3.org/1999/xhtml";
+const XLINK_NS = "http://www.w3.org/1999/xlink";
/**
* Renders the mind map to an SVG string for the preview attachment (share pages,
@@ -16,7 +18,8 @@ const XHTML_NS = "http://www.w3.org/1999/xhtml";
* and summaries live in an HTML overlay (`.label-container`) rather than in the SVG
* layers it clones, so they are missing from its output (the reason the preview was
* previously generated with snapdom). {@link postProcessExportedSvg} re-adds them and
- * relaxes the exporter's exact-fit text boxes so rasterization cannot clip them.
+ * relaxes the exporter's exact-fit text boxes so rasterization cannot clip them. It also
+ * carries in the node icons, which are a font the export is given none of (see icons.ts).
*
* Note that upstream considers `exportSvg()` deprecated in favor of DOM screenshot
* libraries and will not fix the label gap (see
@@ -28,8 +31,13 @@ const XHTML_NS = "http://www.w3.org/1999/xhtml";
* switching back to a screenshot library.
*/
export async function renderMindMapPreviewSvg(mind: MindElixirInstance): Promise<string> {
- const svgText = await mind.exportSvg().text();
- return inlineExportedImages(postProcessExportedSvg(mind, svgText));
+ const [ svgText, icons ] = await Promise.all([
+ mind.exportSvg().text(),
+ // Drawn alongside the export rather than after it: each is a drawing of its own, and the
+ // first of them may have a font to wait on before there is anything to draw with.
+ renderExportedIcons(mind.nodes)
+ ]);
+ return inlineExportedImages(postProcessExportedSvg(mind, svgText, icons));
}
/**
@@ -98,12 +106,14 @@ const SIZE_SLACK_PX = 2;
* - Adds slack to every `<foreignObject>`'s exact-fit size so text is not clipped when
* the SVG is rasterized with slightly different font metrics (see the slack constants).
* - Backs translucent node boxes with the canvas color (see {@link backTranslucentNodeBoxes}).
+ * - Writes in the node icons the exporter cannot draw (see {@link placeExportedIcons}).
*
* @param mind the live mind map instance the SVG was exported from.
* @param svgText the output of `mind.exportSvg().text()`.
+ * @param icons the drawings of the map's icons, as `renderExportedIcons` made them.
* @returns the post-processed SVG, or the input unchanged if it cannot be parsed.
*/
-export function postProcessExportedSvg(mind: MindElixirInstance, svgText: string): string {
+export function postProcessExportedSvg(mind: MindElixirInstance, svgText: string, icons: ExportedIcon[] = []): string {
const doc = new DOMParser().parseFromString(svgText, "image/svg+xml");
// The exporter produces <svg> [ <rect background>, <svg map layers> ] — label
// coordinates are relative to the inner svg.
@@ -117,7 +127,10 @@ export function postProcessExportedSvg(mind: MindElixirInstance, svgText: string
backTranslucentNodeBoxes(contentSvg, canvasColor);
}
+ // Before the icons are written in: the fit is carried over by pairing the pictures of the map
+ // with those of the export in the order they were written, which any picture added here breaks.
carryImageFit(contentSvg, mind);
+ placeExportedIcons(contentSvg, icons);
const labels = mind.nodes.querySelectorAll<HTMLElement>(".svg-label");
for (const label of Array.from(labels)) {
@@ -190,6 +203,87 @@ const FIT_ALIGNMENTS: Record<string, string> = {
cover: "xMidYMid slice"
};
+/**
+ * Writes the node icons into the exported map (see `renderExportedIcons` for why they are drawn).
+ *
+ * Each drawing is written once however many nodes wear it and stamped out of that one copy: a map is
+ * commonly a handful of icons over a great many nodes, and a drawing carried as text inside the SVG
+ * is far and away the heaviest thing in it. An icon that is a character rather than a drawing is
+ * written as the character, which the export needs nothing of its own to draw.
+ */
+function placeExportedIcons(contentSvg: Element, icons: ExportedIcon[]) {
+ const doc = contentSvg.ownerDocument;
+ /** The icons already written, by the drawing each of them is. */
+ const stamps = new Map<string, string>();
+ let defs: Element | undefined;
+
+ for (const icon of icons) {
+ if (icon.image) {
+ let id = stamps.get(icon.image);
+ if (!id) {
+ id = `mind-map-icon-${stamps.size}`;
+ stamps.set(icon.image, id);
+
+ defs ??= contentSvg.appendChild(doc.createElementNS(SVG_NS, "defs"));
+ defs.appendChild(buildIconStamp(doc, id, icon.image));
+ }
+ contentSvg.appendChild(buildIconUse(doc, id, icon));
+ } else if (icon.text) {
+ contentSvg.appendChild(buildIconText(doc, icon));
+ }
+ }
+}
+
+/**
+ * The one copy of a drawing, held in a square of its own so that every use of it can be given a size
+ * — which is what a `<symbol>` carries over a bare `<image>`, whose own size a `<use>` cannot change.
+ */
+function buildIconStamp(doc: Document, id: string, image: string) {
+ const symbol = doc.createElementNS(SVG_NS, "symbol");
+ symbol.setAttribute("id", id);
+ symbol.setAttribute("viewBox", "0 0 1 1");
+
+ const picture = doc.createElementNS(SVG_NS, "image");
+ picture.setAttribute("href", image);
+ picture.setAttribute("width", "1");
+ picture.setAttribute("height", "1");
+ symbol.appendChild(picture);
+
+ return symbol;
+}
+
+function buildIconUse(doc: Document, id: string, { x, y, size }: ExportedIcon) {
+ const use = doc.createElementNS(SVG_NS, "use");
+ use.setAttribute("href", `#${id}`);
+ // The older spelling alongside it, for whatever reads the file that has not caught up with the
+ // newer one — a rasterizer of its own, a drawing program.
+ use.setAttributeNS(XLINK_NS, "xlink:href", `#${id}`);
+ use.setAttribute("x", String(x));
+ use.setAttribute("y", String(y));
+ use.setAttribute("width", String(size));
+ use.setAttribute("height", String(size));
+
+ return use;
+}
+
+/**
+ * An icon that is a character, written on the middle line of its square and nudged down by the part
+ * of a character that hangs below that line — the plain way of centring text in SVG, rather than the
+ * `dominant-baseline` that says so outright and that not everything reading the file honours.
+ */
+function buildIconText(doc: Document, { x, y, size, color, text }: ExportedIcon) {
+ const element = doc.createElementNS(SVG_NS, "text");
+ element.setAttribute("x", String(x + size / 2));
+ element.setAttribute("y", String(y + size / 2));
+ element.setAttribute("dy", "0.35em");
+ element.setAttribute("text-anchor", "middle");
+ element.setAttribute("font-size", String(size));
+ element.setAttribute("fill", color);
+ element.textContent = text ?? "";
+
+ return element;
+}
+
/**
* The alpha of a fill the exporter took from a computed style, or `null` when it carries none.
* Computed sRGB colors are always serialized as `rgb()`/`rgba()`, so a translucent one arrives in
diff --git a/apps/client/src/widgets/type_widgets/mind_map/icons.spec.ts b/apps/client/src/widgets/type_widgets/mind_map/icons.spec.ts
index 9d4f5c89be..a6a9fab8f2 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/icons.spec.ts
+++ b/apps/client/src/widgets/type_widgets/mind_map/icons.spec.ts
@@ -1,6 +1,11 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { LEAD_ICON_CLASS, renderIconClasses } from "./icons";
+import { renderIconImage } from "../../../services/icon_glyphs";
+import { LEAD_ICON_CLASS, renderExportedIcons, renderIconClasses } from "./icons";
+
+// The drawing of a glyph needs a canvas and the browser's own style resolution, neither of which
+// this environment has; the service has its own tests for that.
+vi.mock("../../../services/icon_glyphs", () => ({ renderIconImage: vi.fn() }));
const uncheckedWindow = window as unknown as { glob: { iconRegistry?: unknown } };
@@ -122,3 +127,85 @@ describe("renderIconClasses", () => {
expect(icons(container)[0]?.textContent).toBe("bx bx-star");
});
});
+
+describe("renderExportedIcons", () => {
+ beforeEach(() => {
+ uncheckedWindow.glob.iconRegistry = { sources: [ { prefix: "bx" } ] };
+ vi.mocked(renderIconImage).mockReset();
+ vi.mocked(renderIconImage).mockImplementation(async (iconClass) => `data:image/png;drawn-${iconClass}`);
+ });
+
+ afterEach(() => {
+ delete uncheckedWindow.glob.iconRegistry;
+ vi.restoreAllMocks();
+ });
+
+ /**
+ * A node dressed as the map dresses it, laid out as the browser would lay it out — neither of
+ * which the test environment does of its own accord.
+ */
+ function buildLaidOutNode(...iconTexts: string[]) {
+ const nodes = document.createElement("me-nodes");
+ const container = buildNode(...iconTexts);
+ nodes.appendChild(container);
+ renderIconClasses(container);
+
+ // Each icon 12 wide on a line of 20, the node itself 100 across the map and 40 down it. The
+ // walk out to the map adds the two up, so the icons hang off the node and the node off the
+ // map, as they would be laid out.
+ const topic = container.querySelector("me-tpc");
+ lay(topic, nodes, { offsetLeft: 100, offsetTop: 40 });
+ for (const [ index, icon ] of icons(container).entries()) {
+ lay(icon, topic, { offsetLeft: index * 12, offsetTop: 0, offsetWidth: 12, offsetHeight: 20 });
+ }
+
+ // The size and the colour are read off the styles, which resolve to nothing here.
+ vi.spyOn(window, "getComputedStyle")
+ .mockReturnValue({ fontSize: "16px", color: "rgb(20, 20, 20)" } as CSSStyleDeclaration);
+
+ return nodes;
+ }
+
+ /** Puts an element where it would have been laid out, and off the element it was laid out in. */
+ function lay(element: Element | null, offsetParent: Element | null, offsets: Record<string, number>) {
+ for (const [ name, value ] of Object.entries({ ...offsets, offsetParent })) {
+ Object.defineProperty(element, name, { configurable: true, value });
+ }
+ }
+
+ it("draws every icon a pack draws, centred in the room the text left it", async () => {
+ const nodes = buildLaidOutNode("bx bx-star", "bx bx-cube");
+
+ const drawn = await renderExportedIcons(nodes);
+
+ expect(drawn).toEqual([
+ // The node sits at (100, 40) and each icon within it, so the two are added up; the icon
+ // is drawn at the size of the text, centred in the 12 by 20 it was given.
+ { x: 100 + (12 - 16) / 2, y: 40 + (20 - 16) / 2, size: 16, color: "rgb(20, 20, 20)", image: "data:image/png;drawn-bx bx-star" },
+ { x: 112 + (12 - 16) / 2, y: 40 + (20 - 16) / 2, size: 16, color: "rgb(20, 20, 20)", image: "data:image/png;drawn-bx bx-cube" }
+ ]);
+ // Drawn at one size whatever size it is shown at, the drawing being scaled to each place it
+ // is stamped — so the same icon on a large node and a small one is drawn once between them.
+ expect(renderIconImage).toHaveBeenCalledWith("bx bx-star", { size: 48, color: "rgb(20, 20, 20)", scale: 1 });
+ });
+
+ it("draws only the leading one of the icons that are characters, the rest being drawn already", async () => {
+ // An emoji leads the text, where the exporter no longer finds it; the one that follows it
+ // stays in the wrapper the exporter reads, and is left to it.
+ const nodes = buildLaidOutNode("⭐", "\u{1f9ca}");
+
+ const drawn = await renderExportedIcons(nodes);
+
+ expect(drawn).toEqual([
+ { x: 100 + (12 - 16) / 2, y: 40 + (20 - 16) / 2, size: 16, color: "rgb(20, 20, 20)", text: "⭐" }
+ ]);
+ expect(renderIconImage).not.toHaveBeenCalled();
+ });
+
+ it("passes over an icon that could not be drawn at all", async () => {
+ vi.mocked(renderIconImage).mockResolvedValue(null);
+ const nodes = buildLaidOutNode("bx bx-star");
+
+ await expect(renderExportedIcons(nodes)).resolves.toEqual([]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/mind_map/icons.ts b/apps/client/src/widgets/type_widgets/mind_map/icons.ts
index cb9f32852b..db62b4d340 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/icons.ts
+++ b/apps/client/src/widgets/type_widgets/mind_map/icons.ts
@@ -1,3 +1,5 @@
+import { renderIconImage } from "../../../services/icon_glyphs";
+
/** Marks the icon moved ahead of a node's text, both to dress it and to know it has been moved. */
export const LEAD_ICON_CLASS = "mind-map-lead-icon";
@@ -75,3 +77,113 @@ function isIconClass(text: string) {
const [ prefix, name, ...rest ] = text.split(" ");
return !rest.length && !!name && (glob.iconRegistry?.sources ?? []).some((source) => source.prefix === prefix);
}
+
+/** An icon of the map as the exported SVG has to carry it. See {@link renderExportedIcons}. */
+export interface ExportedIcon {
+ /** Where it sits and how large, in the coordinates the exported map layers are drawn in. */
+ x: number;
+ y: number;
+ size: number;
+ /** What it is drawn in, which is the colour of the text it sits beside. */
+ color: string;
+ /** A drawing of the icon, as a `data:` URL — for an icon a pack draws out of a font. */
+ image?: string;
+ /** The character itself — for an icon that is one, an emoji off a map made elsewhere. */
+ text?: string;
+}
+
+/**
+ * Every icon the map wears, drawn as the exported SVG has to carry it.
+ *
+ * An icon is a class and a font, and an exported map is read as a picture: it may fetch nothing and
+ * is given none of the page's fonts, so the class that draws the icon everywhere else draws nothing
+ * at all there. Each is therefore drawn here into a picture of its own, which the SVG carries inside
+ * it (see `export.ts`). The drawings are kept between exports, an icon being asked for again at every
+ * pause in the editing.
+ *
+ * Note that the exporter itself already writes out the icons that follow a node's text, which are
+ * left where they are: it finds them by their wrapper, and reads each as the text it holds. That
+ * leaves two it cannot draw — an icon a pack draws, whose text is a class and whose class means
+ * nothing to a picture, and the first icon of every node, which {@link renderIconClasses} moves out
+ * of the wrapper the exporter looks in. Both are drawn afresh here; the exporter's own empty boxes
+ * are left behind it, being invisible.
+ */
+export async function renderExportedIcons(nodes: HTMLElement): Promise<ExportedIcon[]> {
+ const worn = nodes.querySelectorAll<HTMLElement>(`me-tpc > .${LEAD_ICON_CLASS}, me-tpc > .icons > span`);
+
+ const drawn = await Promise.all(Array.from(worn, async (element) => {
+ const placement = measureIcon(element, nodes);
+ const iconClass = getIconClass(element);
+
+ if (iconClass) {
+ const image = await renderIconImage(iconClass, {
+ size: ICON_RASTER_SIZE,
+ color: placement.color,
+ scale: 1
+ });
+ return (image ? { ...placement, image } : null);
+ }
+
+ // An icon that is a character of its own is already drawn wherever the exporter found it,
+ // and the only one it did not find is the one moved ahead of the text.
+ const text = element.textContent?.trim();
+ return (text && element.classList.contains(LEAD_ICON_CLASS) ? { ...placement, text } : null);
+ }));
+
+ return drawn.filter((icon) => icon !== null);
+}
+
+/**
+ * How large an icon is drawn, whatever size it is shown at: the drawing is carried in a square of
+ * its own and scaled to each place it is stamped (see `export.ts`), so one drawing serves a node
+ * whose text is small and another whose text is large. Comfortably larger than any icon is shown
+ * at, so that it holds up both on a dense display and in a PNG export, which rasterizes the SVG at
+ * a scale of its own — and a fixed size rather than the display's, so that the same map exports the
+ * same picture wherever it is exported from.
+ */
+const ICON_RASTER_SIZE = 48;
+
+/** The icon class an element was dressed with, or `null` for one carrying an icon of its own. */
+function getIconClass(element: HTMLElement) {
+ const iconClass = element.className.split(/\s+/)
+ .filter((name) => name && name !== LEAD_ICON_CLASS)
+ .join(" ");
+ return iconClass || null;
+}
+
+/**
+ * The square an icon is drawn in, in the coordinates the exported layers use.
+ *
+ * The icon is a character on a line of text, so the room it takes up is a line's — taller than it is
+ * wide, and neither of them the size of the icon. What it is drawn at is the size of the text it is
+ * set in, centred in the room it was given.
+ */
+function measureIcon(element: HTMLElement, nodes: HTMLElement) {
+ const style = getComputedStyle(element);
+ const size = Number.parseFloat(style.fontSize) || element.offsetHeight;
+ const { offsetLeft, offsetTop } = offsetWithin(element, nodes);
+
+ return {
+ x: offsetLeft + (element.offsetWidth - size) / 2,
+ y: offsetTop + (element.offsetHeight - size) / 2,
+ size,
+ color: style.color
+ };
+}
+
+/**
+ * Where an element sits within an ancestor, walked up the chain of offset parents as the exporter
+ * walks it for everything else it writes out — so that what is measured here lands in the same
+ * coordinates as the layers it is written into.
+ */
+function offsetWithin(element: HTMLElement, ancestor: HTMLElement) {
+ let offsetLeft = 0;
+ let offsetTop = 0;
+
+ for (let node: HTMLElement | null = element; node && node !== ancestor; node = node.offsetParent as HTMLElement | null) {
+ offsetLeft += node.offsetLeft;
+ offsetTop += node.offsetTop;
+ }
+
+ return { offsetLeft, offsetTop };
+}