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
test(client): cover what the note map decides before it draws
Elian Doranf95a7ab2bd7c
diff --git a/apps/client/src/widgets/note_map/data.spec.ts b/apps/client/src/widgets/note_map/data.spec.tsindex 2d5c693d6e..5721c0fe38 100644--- a/apps/client/src/widgets/note_map/data.spec.ts+++ b/apps/client/src/widgets/note_map/data.spec.ts@@ -1,6 +1,61 @@-import { describe, expect, it } from "vitest";+import { NoteMapPostResponse } from "@triliumnext/commons";+import { afterEach, describe, expect, it, vi } from "vitest";-import { dropUnlinkedNotes } from "./data";+import server from "../../services/server";+import { dropUnlinkedNotes, loadNotesAndRelations } from "./data";++describe("loadNotesAndRelations", () => {+ afterEach(() => vi.restoreAllMocks());++ /** Two notes pointed at from the root, one of them by two relations at once, and a loose note. */+ const response: NoteMapPostResponse = {+ notes: [+ [ "root", "Root", "text", null, "bx bx-home" ],+ [ "linked", "Linked", "code", "#ff0000", "bx bx-code" ],+ [ "loose", "Loose", "text", null, "bx bx-file" ]+ ],+ links: [+ { key: "1", sourceNoteId: "root", targetNoteId: "linked", name: "relates" },+ { key: "2", sourceNoteId: "root", targetNoteId: "linked", name: "mentions" },+ // The same relation twice over — a note can carry two of a name pointing the same way.+ { key: "3", sourceNoteId: "root", targetNoteId: "linked", name: "relates" }+ ],+ noteIdToDescendantCountMap: { root: 4, linked: 0 }+ };+ const answerWith = (resp: NoteMapPostResponse) => vi.spyOn(server, "post").mockResolvedValue(resp);++ it("reads the notes and gathers the relations running between each pair into one", async () => {+ answerWith(response);+ const { nodes, links, noteIdToSizeMap } = await loadNotesAndRelations("root", [], [], "link");++ expect(nodes).toEqual([+ { id: "root", name: "Root", type: "text", color: null, icon: "bx bx-home" },+ { id: "linked", name: "Linked", type: "code", color: "#ff0000", icon: "bx bx-code" },+ { id: "loose", name: "Loose", type: "text", color: null, icon: "bx bx-file" }+ ]);++ // One relation drawn for the pair, named for each of the ways they are related, and a name+ // carried twice named once.+ expect(links).toEqual([ { id: "root-linked", source: "root", target: "linked", name: "relates, mentions" } ]);++ // A note of a link map is drawn the larger the more is pointed at it, counting every relation+ // rather than the one drawn for them.+ expect(noteIdToSizeMap).toEqual({ root: 4, linked: 4 + Math.sqrt(3), loose: 4 });+ });++ it("drops the notes nothing links to only where it is asked to, and only from a link map", async () => {+ answerWith(response);+ const linkMap = await loadNotesAndRelations("root", [], [], "link", true);+ expect(linkMap.nodes.map((node) => node.id)).toEqual([ "root", "linked" ]);++ // A tree map links every note to its parent, so it has no unlinked notes to speak of — and is+ // sized by what hangs off each note rather than by what points at it.+ answerWith(response);+ const treeMap = await loadNotesAndRelations("root", [], [], "tree", true);+ expect(treeMap.nodes.map((node) => node.id)).toEqual([ "root", "linked", "loose" ]);+ expect(treeMap.noteIdToSizeMap).toEqual({ root: 4 + 1 + Math.round(Math.log(4) / Math.log(1.5)), linked: 4 });+ });+});describe("dropUnlinkedNotes", () => {const nodes = [ { id: "root" }, { id: "source" }, { id: "target" }, { id: "loose" } ];diff --git a/apps/client/src/widgets/note_map/icons.spec.ts b/apps/client/src/widgets/note_map/icons.spec.tsnew file mode 100644index 0000000000..59f54be127--- /dev/null+++ b/apps/client/src/widgets/note_map/icons.spec.ts@@ -0,0 +1,72 @@+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/rendering.spec.ts b/apps/client/src/widgets/note_map/rendering.spec.tsnew file mode 100644index 0000000000..fdc28e8047--- /dev/null+++ b/apps/client/src/widgets/note_map/rendering.spec.ts@@ -0,0 +1,295 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { NoteMapNodeObject, NotesAndRelationsData } from "./data";+import {+ createFade,+ CssData,+ getArrowOutline,+ getFadedAlpha,+ getHoveredNeighbourhood,+ getLabelFontSize,+ getNodeColors,+ isIconDrawn,+ isLabelDrawn,+ planFraming,+ traceRoundedPath,+ truncateLabel+} from "./rendering";++describe("getHoveredNeighbourhood", () => {+ const node = (id: string) => ({ id, name: id, type: "text", color: null, icon: "bx bx-file" });+ const [ hovered, pointedAt, pointingAt, elsewhere ] = [ node("hovered"), node("pointedAt"), node("pointingAt"), node("elsewhere") ];+ const link = (source: NoteMapNodeObject | string, target: NoteMapNodeObject | string) => ({ id: `${source}-${target}`, source, target, name: "relates" });++ it("gathers what the hovered note is related to, whichever way each relation runs", () => {+ const own = [ link(hovered, pointedAt), link(pointingAt, hovered) ];+ const { neighbours, highlightLinks } = getHoveredNeighbourhood(hovered, [+ ...own,+ link(pointedAt, elsewhere),+ // A relation whose ends the graph has yet to look up, which it is drawn without.+ link("hovered", "elsewhere")+ ]);++ expect([ ...neighbours ]).toEqual([ pointedAt, pointingAt ]);+ expect([ ...highlightLinks ]).toEqual(own);+ });++ it("has nothing to gather for a note nothing is related to", () => {+ const { neighbours, highlightLinks } = getHoveredNeighbourhood(elsewhere, [ link(hovered, pointedAt) ]);++ expect(neighbours.size).toBe(0);+ expect(highlightLinks.size).toBe(0);+ });+});++describe("getFadedAlpha", () => {+ it("draws whole what a hover leaves alone, and steps back what it does not", () => {+ // Nothing hovered at all, and the notes a hover is about: both drawn whole.+ expect(getFadedAlpha(0)).toBe(1);+ expect(getFadedAlpha(1)).toBe(1);++ // The rest of the map, and the way there.+ expect(getFadedAlpha(-1)).toBeCloseTo(0.15);+ expect(getFadedAlpha(-0.5)).toBeCloseTo(0.575);+ });+});++describe("getNodeColors", () => {+ it("draws a note as the badge it wears elsewhere, unless it asks for a colour of its own", () => {+ expect(getNodeColors({ color: null }, cssData)).toEqual({ fill: "#eeeeee", icon: "#333333" });++ // Its own colour is the reader's doing and stands; the icon is then cut out of it in what the+ // map is laid on, there being no badge pairing to draw on.+ expect(getNodeColors({ color: "#ff0000" }, cssData)).toEqual({ fill: "#ff0000", icon: "#ffffff" });++ // A note is free to ask for a colour CSS knows by name rather than by number.+ expect(getNodeColors({ color: "rebeccapurple" }, cssData).fill).toBe("rebeccapurple");+ });+});++describe("getLabelFontSize", () => {+ const onScreen = (screenPx: number, zoomLevel: number) => getLabelFontSize(screenPx, zoomLevel) * zoomLevel;++ it("carries a label part of the way with the zoom, rather than all of it or none", () => {+ // The canvas is scaled by the zoom, so the size asked for is divided back out of it.+ expect(getLabelFontSize(11, 1)).toBe(11);+ expect(getLabelFontSize(11, 4)).toBeCloseTo(11 * 4 ** 0.25 / 4);++ // Across the whole range of zooms the map allows, 11px comes out between 8 and 18 — the+ // titles come closer as the map is zoomed into without taking it over.+ expect(onScreen(11, 0.1)).toBeGreaterThan(5);+ expect(onScreen(11, 1)).toBe(11);+ expect(onScreen(11, 7)).toBeCloseTo(17.9, 1);+ });+});++describe("isLabelDrawn", () => {+ it("asks more of a small note than a large one before its name is worth the clutter", () => {+ // Zoomed well in, every note is named.+ expect(isLabelDrawn(1, 3)).toBe(true);++ expect(isLabelDrawn(6, 1.5)).toBe(false);+ expect(isLabelDrawn(7, 1.5)).toBe(true);++ expect(isLabelDrawn(10, 0.5)).toBe(false);+ expect(isLabelDrawn(11, 0.5)).toBe(true);++ // Zoomed far enough out, nothing is named however large.+ expect(isLabelDrawn(100, 0.2)).toBe(false);+ });+});++describe("isIconDrawn", () => {+ it("waits until the dot is drawn large enough on screen to hold a glyph", () => {+ // The dot is drawn a little inside the size the graph holds the note at, and that is what has+ // to come out at 7px on screen.+ expect(isIconDrawn(8.75, 1)).toBe(true);+ expect(isIconDrawn(8.74, 1)).toBe(false);++ // What a note too small at one zoom is drawn with at another.+ expect(isIconDrawn(5, 1)).toBe(false);+ expect(isIconDrawn(5, 2)).toBe(true);+ });+});++describe("truncateLabel", () => {+ /** A font of even, 5-unit-wide characters, so that a width is a count of them. */+ const measureWidth = (text: string) => text.length * 5;++ it("cuts a title to the width allowed, the ellipsis included in what has to fit", () => {+ // 12 ems of a 10px font is 120 units, which is 24 of these characters.+ expect(truncateLabel("x".repeat(24), 10, measureWidth)).toBe("x".repeat(24));++ const cut = truncateLabel("x".repeat(40), 10, measureWidth);+ expect(cut).toBe(`${"x".repeat(23)}…`);+ expect(measureWidth(cut)).toBeLessThanOrEqual(120);++ // A font wide enough that nothing fits still leaves a character to hang the ellipsis on,+ // rather than cutting the title away to nothing.+ expect(truncateLabel("abc", 10, () => 1000)).toBe("a…");+ });+});++describe("getArrowOutline", () => {+ it("points the arrowhead along the relation and stops it at the dot it points at", () => {+ const outline = getArrowOutline({ x: 0, y: 0 }, { x: 100, y: 0 }, 10, 10);+ expect(outline).not.toBeNull();+ const [ tip, leftFlank, notch, rightFlank ] = outline ?? [];++ // Stopped a note's radius short of the middle of the note it points at.+ expect(tip).toEqual([ 90, 0 ]);++ // The tail is as far across as the width the arrowhead is drawn at, evenly either side of the+ // line, and swept in towards the tip in the middle — an arrowhead rather than a triangle.+ expect(leftFlank[0]).toBeCloseTo(80);+ expect(rightFlank[0]).toBeCloseTo(80);+ expect(leftFlank[1]).toBeCloseTo(3.6);+ expect(rightFlank[1]).toBeCloseTo(-3.6);+ expect(notch[0]).toBeGreaterThan(leftFlank[0]);+ expect(notch[0]).toBeLessThan(tip[0]);+ expect(notch[1]).toBeCloseTo(0);+ });++ it("turns with the relation, and gives up where there is nowhere to be drawn but inside a note", () => {+ // The same relation the other way up: the tip is a radius short of the note at the bottom.+ const outline = getArrowOutline({ x: 0, y: 0 }, { x: 0, y: 100 }, 10, 10) ?? [];+ expect(outline[0][0]).toBeCloseTo(0);+ expect(outline[0][1]).toBeCloseTo(90);++ // Two notes all but on top of one another: an arrowhead there would be drawn inside one of+ // them, pointing back the way it came.+ expect(getArrowOutline({ x: 0, y: 0 }, { x: 19, y: 0 }, 10, 10)).toBeNull();+ expect(getArrowOutline({ x: 0, y: 0 }, { x: 21, y: 0 }, 10, 10)).not.toBeNull();+ });+});++describe("traceRoundedPath", () => {+ it("rounds every corner by drawing an arc between the middles of the edges meeting at it", () => {+ const ctx = { beginPath: vi.fn(), moveTo: vi.fn(), arcTo: vi.fn(), closePath: vi.fn() };+ const square: [ number, number ][] = [ [ 0, 0 ], [ 10, 0 ], [ 10, 10 ], [ 0, 10 ] ];++ traceRoundedPath(ctx as unknown as CanvasRenderingContext2D, square, 2);++ // Started at the middle of an edge rather than at a corner, which is what leaves every corner+ // to be rounded — the first one included.+ expect(ctx.moveTo).toHaveBeenCalledWith(0, 5);+ expect(ctx.arcTo).toHaveBeenCalledTimes(4);+ expect(ctx.arcTo).toHaveBeenNthCalledWith(1, 0, 0, 5, 0, 2);+ // The last corner is rounded towards the point the path started from.+ expect(ctx.arcTo).toHaveBeenNthCalledWith(4, 0, 10, 0, 5, 2);+ expect(ctx.closePath).toHaveBeenCalled();+ });+});++describe("createFade", () => {+ afterEach(() => vi.restoreAllMocks());++ /** The clock the fade is run against, which is the one the animation frames are drawn on. */+ const atTime = (ms: number) => vi.spyOn(performance, "now").mockReturnValue(ms);++ it("takes a value to where a change puts it over the fade, and clamps it there", () => {+ atTime(0);+ let hovered = false;+ const fade = createFade([ "hovered", "other" ], (element) => (hovered && element !== "hovered" ? -1 : 0));++ // Nothing has been changed yet, so there is nothing on its way anywhere.+ expect(fade.get("other")).toBe(0);++ // Where everything stands is taken down before the change is made, that being what the fade+ // about to start reads from.+ fade.restart();+ hovered = true;+ expect(fade.get("other")).toBe(0);++ // Half of the fade's 160ms.+ atTime(80);+ expect(fade.get("other")).toBeCloseTo(-0.5);+ // What the hover is about does not move at all.+ expect(fade.get("hovered")).toBe(0);++ atTime(10_000);+ expect(fade.get("other")).toBe(-1);+ });++ it("starts a fade from wherever the last one had got to", () => {+ atTime(0);+ let hovered = false;+ const fade = createFade([ "other" ], () => (hovered ? -1 : 0));+ fade.restart();+ hovered = true;++ // The pointer leaves the note halfway through the fade its arrival started.+ atTime(80);+ fade.restart();+ hovered = false;++ // Which is where the way back begins, rather than from the map as it stands with nothing+ // hovered — half of the way back from half faded is a quarter.+ atTime(160);+ expect(fade.get("other")).toBeCloseTo(-0.25);+ });+});++describe("planFraming", () => {+ const node = (id: string) => ({ id, name: id, type: "text", color: null, icon: "bx bx-file" });+ const notesAndRelations: NotesAndRelationsData = {+ nodes: [ node("root"), node("linked"), node("loose") ],+ links: [ { id: "l", source: node("root"), target: node("linked"), name: "relates" } ],+ noteIdToSizeMap: {}+ };+ // A note two relations out, which the walk of the map reaches and the relation above does not+ // mention — so which of the two the framing was measured on can be told apart.+ const hopDistances = new Map([ [ "root", 0 ], [ "linked", 1 ], [ "loose", 2 ] ]);++ it("frames the notes reached from the one the map is rooted at, where it is rooted at one", () => {+ const plan = planFraming({ widgetMode: "sidebar", noteType: "text", notesAndRelations, hopDistances });++ expect([ ...plan.framedNoteIds ]).toEqual([ "root", "linked", "loose" ]);+ expect(plan.framesSubset).toBe(true);+ expect(plan.fittedNoteCount).toBe(3);+ expect(plan.padding).toBe(20);+ });++ it("frames what the relations touch where there is no note to walk out from", () => {+ // A search note is not among its own results, and the maps that are not rooted at the note+ // being read have nowhere to walk out from either.+ for (const plan of [+ planFraming({ widgetMode: "sidebar", noteType: "search", notesAndRelations, hopDistances }),+ planFraming({ widgetMode: "type", noteType: "text", notesAndRelations, hopDistances })+ ]) {+ expect([ ...plan.framedNoteIds ]).toEqual([ "root", "linked" ]);+ expect(plan.fittedNoteCount).toBe(2);+ }++ // The maps with room of their own keep their own margins.+ expect(planFraming({ widgetMode: "type", noteType: "text", notesAndRelations, hopDistances }).padding).toBe(30);+ });++ it("falls back to the whole graph where there is no more than a note to frame", () => {+ // A note whose map is only itself has no extent to fit: fitting it alone asks for a zoom of+ // hundreds and fills the card with a single circle.+ const lone = planFraming({ widgetMode: "sidebar", noteType: "text", notesAndRelations, hopDistances: new Map([ [ "root", 0 ] ]) });+ expect(lone.framesSubset).toBe(false);+ expect(lone.fittedNoteCount).toBe(3);++ // The same where the graph has not yet looked the ends of its relations up, which leaves+ // nothing to be framed at all.+ const unresolved = planFraming({+ widgetMode: "type",+ noteType: "text",+ notesAndRelations: { ...notesAndRelations, links: [ { id: "l", source: "root", target: "linked", name: "relates" } ] },+ hopDistances+ });+ expect(unresolved.framedNoteIds.size).toBe(0);+ expect(unresolved.fittedNoteCount).toBe(3);+ });+});++const cssData: CssData = {+ fontFamily: "sans-serif",+ textColor: "#000000",+ mutedTextColor: "#888888",+ backgroundColor: "#ffffff",+ anchorColor: "#eeeeee",+ anchorIconColor: "#333333"+};diff --git a/apps/client/src/widgets/note_map/rendering.ts b/apps/client/src/widgets/note_map/rendering.tsindex 12faf50f82..53b2cd8fe0 100644--- a/apps/client/src/widgets/note_map/rendering.ts+++ b/apps/client/src/widgets/note_map/rendering.ts@@ -1,6 +1,6 @@import type ForceGraph from "force-graph";-import FNote from "../../entities/fnote";+import type FNote from "../../entities/fnote";import { escapeHtml } from "../../services/utils";import { NoteMapLinkObject, NoteMapNodeObject, NotesAndRelationsData } from "./data";import { ICON_FONT_FAMILY } from "./icons";@@ -15,6 +15,16 @@ const LONE_NOTE_ZOOM = 4;/** How large a note's dot has to come out on screen, in pixels, before its icon is drawn inside it. */const MIN_ICON_RADIUS = 7;+/**+ * How wide a note's dot is drawn, as a part of the size the graph holds it at. The graph measures the+ * room a note takes up by that size, and the dot is drawn a little inside it so that the notes of a+ * crowded map are not laid edge to edge.+ */+const NODE_RADIUS_RATIO = 0.8;++/** Above how many framed notes a map is left to settle at its own pace — see {@link setupFraming}. */+const DAMPING_MAX_NOTES = 30;+/** How thick the ring around the note the map is drawn around is on screen. */const ANCHOR_RING_PX = 2;@@ -113,8 +123,8 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO// runs between it and, and those relations. Worked out once when the hover changes rather than// while painting, so that every note of a frame is painted knowing the same thing.let hoverNode: NoteMapNodeObject | null = null;- const neighbours = new Set<NoteMapNodeObject>();- const highlightLinks = new Set<NoteMapLinkObject>();+ let neighbours = new Set<NoteMapNodeObject>();+ let highlightLinks = new Set<NoteMapLinkObject>();let zoomLevel: number;/** Titles as they are drawn, cut to the width a label is allowed — see {@link getLabel}. */const labelsByNoteId = new Map<string, string>();@@ -152,31 +162,15 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOkeepPaintingThroughFade();hoverNode = node;- neighbours.clear();- highlightLinks.clear();if (!hoverNode) {+ neighbours = new Set();+ highlightLinks = new Set();return;}- highlightColor = normalizeColor(getColorForNode(hoverNode));-- for (const link of notesAndRelations.links) {- const { source, target } = link;- // Both ends are notes of the map by the time it is drawn, the graph having looked up what- // the data carries as ids.- if (typeof source !== "object" || typeof target !== "object") {- continue;- }-- if (source.id === hoverNode.id) {- neighbours.add(target);- highlightLinks.add(link);- } else if (target.id === hoverNode.id) {- neighbours.add(source);- highlightLinks.add(link);- }- }+ highlightColor = normalizeColor(getNodeColors(hoverNode, cssData).fill);+ ({ neighbours, highlightLinks } = getHoveredNeighbourhood(hoverNode, notesAndRelations.links));}/** Whether the note is the hovered one or one a relation runs between it and — all of them, while nothing is hovered. */@@ -203,11 +197,6 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOreturn withAlpha(color, getFadedAlpha(focus));}- /** How much of a note or a relation is drawn, from all of it to {@link DIMMED_ALPHA} faded back. */- function getFadedAlpha(focus: number) {- return DIMMED_ALPHA + (1 - DIMMED_ALPHA) * Math.min(1, 1 + focus);- }-/*** The colour as a canvas keeps it — `#rrggbb` — whatever it was written as, a note being free to* ask for any colour CSS knows by name. Only that form can be faded or mixed with another.@@ -232,38 +221,6 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOfadeTimer = setTimeout(() => graph.autoPauseRedraw(true), HOVER_FADE_MS + 100);}- /**- * What a note is drawn in: the badge its icon is shown in beside a title, wherever a note is shown- * at a size. Every note of the map wears it, whole — which of them the map is drawn around is said- * by the ring, and what kind of note each is by the icon within it.- *- * A note that asks for a colour of its own is given it — that is the reader's own doing, and it- * says something no map should talk over.- */- function getColorForNode(node: NoteMapNodeObject) {- return node.color || cssData.anchorColor;- }-- /**- * The size to draw text at in the graph's own units, for a size on screen.- *- * The canvas is scaled by the zoom, so text measured in the graph's units is drawn as large as- * the map is zoomed in — which is how a title once came to stand taller than the note it belonged- * to. Dividing the size on screen back out by the zoom holds it to a size of its own, and the- * share of the zoom it is given back (see {@link LABEL_ZOOM_SHARE}) is what still lets it grow.- */- function getFontSize(screenPx: number) {- return screenPx * zoomLevel ** LABEL_ZOOM_SHARE / zoomLevel;- }-- /**- * Whether a note of the given size has its label drawn under it as the map stands: the smaller the- * note, the further in the map has to be zoomed before its name is worth the clutter.- */- function isLabelDrawn(size: number) {- return zoomLevel > 2 || (zoomLevel > 1 && size > 6) || (zoomLevel > 0.3 && size > 10);- }-/*** The note's title, for the tooltip that stands over it while it is hovered — or nothing at all* where the map is already showing the title in full under the note, the tooltip then being a@@ -274,7 +231,7 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO* entry in the map has never had its label drawn, and cannot have it in full.*/function getTooltip(node: NoteMapNodeObject) {- const shownInFull = isLabelDrawn(noteIdToSizeMap[node.id]) && labelsByNoteId.get(node.id) === node.name;+ const shownInFull = isLabelDrawn(noteIdToSizeMap[node.id], zoomLevel) && labelsByNoteId.get(node.id) === node.name;return shownInFull ? "" : escapeHtml(node.name);}@@ -289,7 +246,7 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO}const size = noteIdToSizeMap[node.id];- const radius = size * 0.8;+ const radius = size * NODE_RADIUS_RATIO;ctx.fillStyle = color;ctx.beginPath();@@ -312,11 +269,11 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOpaintNodeIcon(node, size, x, y, ctx);- if (!isLabelDrawn(size)) {+ if (!isLabelDrawn(size, zoomLevel)) {return;}- const fontSize = getFontSize(LABEL_FONT_PX);+ const fontSize = getLabelFontSize(LABEL_FONT_PX, zoomLevel);ctx.save();castLabelShadow(ctx);@@ -324,7 +281,7 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOctx.font = `${fontSize}px ${cssData.fontFamily}`;ctx.textAlign = "center";ctx.textBaseline = "middle";- ctx.fillText(getLabel(node, ctx, fontSize), x, y + size * 0.8 + fontSize);+ ctx.fillText(getLabel(node, ctx, fontSize), x, y + radius + fontSize);ctx.restore();}@@ -355,21 +312,12 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOreturn cached;}- const maxWidth = MAX_LABEL_WIDTH_EMS * fontSize;- let label = node.name;-- if (ctx.measureText(label).width > maxWidth) {- while (label.length > 1 && ctx.measureText(`${label}…`).width > maxWidth) {- label = label.slice(0, -1);- }- label = `${label}…`;- }+ const label = truncateLabel(node.name, fontSize, (text) => ctx.measureText(text).width);labelsByNoteId.set(node.id, label);return label;}-/*** The note's own icon, cut out of the dot standing for it — the same one the tree and the tabs* draw it with, so a note is recognised in the map by what it is recognised by everywhere else.@@ -386,11 +334,11 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOfunction paintNodeIcon(node: NoteMapNodeObject, size: number, x: number, y: number, ctx: CanvasRenderingContext2D) {const glyph = iconGlyphs.get(node.icon);- if (!glyph || !(size * 0.8 * zoomLevel >= MIN_ICON_RADIUS)) {+ if (!glyph || !isIconDrawn(size, zoomLevel)) {return;}- ctx.fillStyle = node.color ? cssData.backgroundColor : cssData.anchorIconColor;+ ctx.fillStyle = getNodeColors(node, cssData).icon;ctx.font = `${size}px ${ICON_FONT_FAMILY}`;ctx.textAlign = "center";ctx.textBaseline = "middle";@@ -408,40 +356,23 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO* inside the larger ones.*/function paintArrow(link: NoteMapLinkObject, source: NoteMapNodeObject, target: NoteMapNodeObject, ctx: CanvasRenderingContext2D) {- const { x: sourceX = 0, y: sourceY = 0 } = source;- const { x: targetX = 0, y: targetY = 0 } = target;- const length = getFontSize(ARROW_LENGTH_PX);- const lineLength = Math.hypot(targetX - sourceX, targetY - sourceY);- const targetRadius = noteIdToSizeMap[target.id] * 0.8;-- // Two notes all but on top of one another leave nowhere to put it that is not inside one of- // them, where it would be drawn pointing back the way it came.- if (lineLength < targetRadius + length) {+ const length = getLabelFontSize(ARROW_LENGTH_PX, zoomLevel);+ const outline = getArrowOutline(+ { x: source.x ?? 0, y: source.y ?? 0 },+ { x: target.x ?? 0, y: target.y ?? 0 },+ noteIdToSizeMap[target.id] * NODE_RADIUS_RATIO,+ length+ );++ if (!outline) {return;}- const alongX = (targetX - sourceX) / lineLength;- const alongY = (targetY - sourceY) / lineLength;- const tipX = targetX - alongX * targetRadius;- const tipY = targetY - alongY * targetRadius;- const baseX = tipX - alongX * length;- const baseY = tipY - alongY * length;- const halfWidth = length * ARROW_WIDTH_RATIO / 2;- // The notch the tail is swept back to, which is what keeps it an arrowhead rather than a- // triangle sitting on the line.- const notchX = baseX + alongX * length * ARROW_SWEEP;- const notchY = baseY + alongY * length * ARROW_SWEEP;-ctx.save();// The corners are rounded into the outline itself rather than stroked round afterwards: a// stroke over a fill is drawn twice where the two meet, which tells on an arrowhead faded// back behind a hover as a rim darker than the rest of it.- traceRoundedPath(ctx, [- [ tipX, tipY ],- [ baseX - alongY * halfWidth, baseY + alongX * halfWidth ],- [ notchX, notchY ],- [ baseX + alongY * halfWidth, baseY - alongX * halfWidth ]- ], length * ARROW_ROUNDING);+ traceRoundedPath(ctx, outline, length * ARROW_ROUNDING);ctx.fillStyle = getLinkColor(link);ctx.fill();@@ -465,7 +396,7 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO// Held to a size the same way a note's label is, from a smaller one: the name of a relation// is there to be read of a map already zoomed into, not to stand alongside the names of the// notes it runs between.- const fontSize = getFontSize(LINK_LABEL_FONT_PX);+ const fontSize = getLabelFontSize(LINK_LABEL_FONT_PX, zoomLevel);ctx.font = `${fontSize}px ${cssData.fontFamily}`;ctx.textAlign = "center";@@ -513,7 +444,7 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO// Every note is drawn whole; the only thing that steps one back is the pointer resting on// another note than it.ctx.globalAlpha = getFadedAlpha(nodeFocus.get(node));- paintNode(node, getColorForNode(node), ctx);+ paintNode(node, getNodeColors(node, cssData).fill, ctx);ctx.restore();}).onNodeHover((node) => setHoveredNode(node ?? null))@@ -567,6 +498,155 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO};}+/**+ * What the map is to show of the note under the pointer: the notes a relation runs between it and,+ * and the relations themselves. Which way round a relation runs is not what this asks — a note is as+ * much a neighbour for being pointed at as for pointing.+ *+ * Worked out once when the hover changes rather than while painting, so that every note of a frame is+ * painted knowing the same thing.+ */+export function getHoveredNeighbourhood(hoverNode: NoteMapNodeObject, links: NoteMapLinkObject[]) {+ const neighbours = new Set<NoteMapNodeObject>();+ const highlightLinks = new Set<NoteMapLinkObject>();++ for (const link of links) {+ const { source, target } = link;+ // Both ends are notes of the map by the time it is drawn, the graph having looked up what the+ // data carries as ids.+ if (typeof source !== "object" || typeof target !== "object") {+ continue;+ }++ if (source.id === hoverNode.id) {+ neighbours.add(target);+ highlightLinks.add(link);+ } else if (target.id === hoverNode.id) {+ neighbours.add(source);+ highlightLinks.add(link);+ }+ }++ return { neighbours, highlightLinks };+}++/** How much of a note or a relation is drawn, from all of it to {@link DIMMED_ALPHA} faded back. */+export function getFadedAlpha(focus: number) {+ return DIMMED_ALPHA + (1 - DIMMED_ALPHA) * Math.min(1, 1 + focus);+}++/**+ * What a note is drawn in, and what its icon is cut out of it in.+ *+ * The badge its icon is shown in beside a title, wherever a note is shown at a size. Every note of the+ * map wears it, whole — which of them the map is drawn around is said by the ring, and what kind of+ * note each is by the icon within it.+ *+ * A note that asks for a colour of its own is given it: that is the reader's own doing, and it says+ * something no map should talk over. It has no badge pairing to draw its icon in, though, so the icon+ * is cut out of it in the colour of what the map is laid on — whatever the note asks to be drawn in,+ * the page behind it is something else.+ */+export function getNodeColors(node: Pick<NoteMapNodeObject, "color">, cssData: CssData) {+ return {+ fill: node.color || cssData.anchorColor,+ icon: node.color ? cssData.backgroundColor : cssData.anchorIconColor+ };+}++/**+ * The size to draw text at in the graph's own units, for a size on screen.+ *+ * The canvas is scaled by the zoom, so text measured in the graph's units is drawn as large as the map+ * is zoomed in — which is how a title once came to stand taller than the note it belonged to. Dividing+ * the size on screen back out by the zoom holds it to a size of its own, and the share of the zoom it+ * is given back (see {@link LABEL_ZOOM_SHARE}) is what still lets it grow.+ */+export function getLabelFontSize(screenPx: number, zoomLevel: number) {+ return screenPx * zoomLevel ** LABEL_ZOOM_SHARE / zoomLevel;+}++/**+ * Whether a note of the given size has its label drawn under it as the map stands: the smaller the+ * note, the further in the map has to be zoomed before its name is worth the clutter.+ */+export function isLabelDrawn(size: number, zoomLevel: number) {+ return zoomLevel > 2 || (zoomLevel > 1 && size > 6) || (zoomLevel > 0.3 && size > 10);+}++/**+ * Whether the note's dot comes out large enough on screen to hold its icon. Below that the glyph is a+ * smudge over the colour, and the colour alone says more.+ */+export function isIconDrawn(size: number, zoomLevel: number) {+ return size * NODE_RADIUS_RATIO * zoomLevel >= MIN_ICON_RADIUS;+}++/**+ * The title cut down to what a label is allowed to be wide, with an ellipsis for what is left off.+ *+ * Measured rather than counted: a count of characters cuts a title of wide ones halfway across the map+ * and one of narrow ones long before it had to. The width allowed is in multiples of the font size and+ * the measuring is in the graph's units, so the zoom is on both sides of the comparison and cancels+ * out — what fits at one zoom fits at every other.+ *+ * @param measureWidth how wide the text comes out, as the canvas it is to be drawn on measures it.+ */+export function truncateLabel(title: string, fontSize: number, measureWidth: (text: string) => number) {+ const maxWidth = MAX_LABEL_WIDTH_EMS * fontSize;++ if (measureWidth(title) <= maxWidth) {+ return title;+ }++ let label = title;+ // The ellipsis is part of what has to fit, so it is measured along with what is left of the title.+ while (label.length > 1 && measureWidth(`${label}…`) > maxWidth) {+ label = label.slice(0, -1);+ }++ return `${label}…`;+}++/**+ * The corners of the arrowhead that says which way a relation runs — a swept chevron, drawn where the+ * line meets the note it points at, rather than the hard little wedge the graph draws of its own+ * accord. Rounded off by whoever traces it (see {@link traceRoundedPath}).+ *+ * Nothing at all where the two notes are so close together that there is nowhere to put it that is not+ * inside one of them, where it would be drawn pointing back the way it came.+ *+ * @param targetRadius the dot the arrowhead stops at, as the map actually draws it: the graph sizes+ * every note the same for this, which buries the arrowhead inside the larger ones.+ * @param length how long the arrowhead is, in the graph's units.+ */+export function getArrowOutline(source: { x: number, y: number }, target: { x: number, y: number }, targetRadius: number, length: number) {+ const lineLength = Math.hypot(target.x - source.x, target.y - source.y);++ if (lineLength < targetRadius + length) {+ return null;+ }++ const alongX = (target.x - source.x) / lineLength;+ const alongY = (target.y - source.y) / lineLength;+ const tipX = target.x - alongX * targetRadius;+ const tipY = target.y - alongY * targetRadius;+ const baseX = tipX - alongX * length;+ const baseY = tipY - alongY * length;+ const halfWidth = length * ARROW_WIDTH_RATIO / 2;+ // The notch the tail is swept back to, which is what keeps it an arrowhead rather than a triangle+ // sitting on the line.+ const notchX = baseX + alongX * length * ARROW_SWEEP;+ const notchY = baseY + alongY * length * ARROW_SWEEP;++ return [+ [ tipX, tipY ],+ [ baseX - alongY * halfWidth, baseY + alongX * halfWidth ],+ [ notchX, notchY ],+ [ baseX + alongY * halfWidth, baseY - alongX * halfWidth ]+ ] satisfies [ number, number ][];+}+/*** Lays out a shape whose every corner is rounded off, ready to be filled.*@@ -576,7 +656,7 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO** @param radius how much of each corner to round off, in the units the points are given in.*/-function traceRoundedPath(ctx: CanvasRenderingContext2D, points: [ number, number ][], radius: number) {+export function traceRoundedPath(ctx: CanvasRenderingContext2D, points: [ number, number ][], radius: number) {const middleOf = (from: [ number, number ], to: [ number, number ]) => [ (from[0] + to[0]) / 2, (from[1] + to[1]) / 2 ] as const;const [ startX, startY ] = middleOf(points[points.length - 1], points[0]);@@ -602,7 +682,7 @@ function traceRoundedPath(ctx: CanvasRenderingContext2D, points: [ number, numbe** @param getTarget where the value should end up, as things stand now.*/-function createFade<T>(elements: T[], getTarget: (element: T) => number) {+export function createFade<T>(elements: T[], getTarget: (element: T) => number) {const startingPoints = new Map<T, number>();let startedAt = 0;@@ -639,23 +719,10 @@ function createFade<T>(elements: T[], getTarget: (element: T) => number) {* @returns a teardown function to call when the graph is discarded.*/function setupFraming(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, container: HTMLElement, { note, widgetMode, notesAndRelations, hopDistances }: Pick<RenderData, "note" | "widgetMode" | "notesAndRelations"> & { hopDistances: Map<string, number> }) {- // The notes that can be reached from the one the map is rooted at, which is what the distances- // drawn on are a walk of already.- const framedNoteIds = (isRootedAtCurrentNote(widgetMode) && note?.type !== "search")- ? new Set(hopDistances.keys())- : getNoteIdsWithLinks(notesAndRelations);-- // A lone note has no extent to fit and would just be blown up to the maximum zoom, hiding the- // rest of the map; the whole graph is the more useful thing to look at then.- const nodeFilter = framedNoteIds.size > 1+ const { framedNoteIds, framesSubset, padding, fittedNoteCount } = planFraming({ widgetMode, noteType: note?.type, notesAndRelations, hopDistances });+ const nodeFilter = framesSubset? (node: NoteMapNodeObject) => framedNoteIds.has(node.id): undefined;- const padding = getFitPadding(widgetMode, framedNoteIds.size);- // What the fit is measured on: the framed notes, or the whole graph where those are no more than- // the one note. A note whose map is only itself has no extent to fit at all — the fit then asks- // for a zoom of hundreds and gets the highest allowed, which fills the card with a single circle- // and the beginning of a title. It is shown at a size it can be read at instead.- const fittedNoteCount = nodeFilter ? framedNoteIds.size : notesAndRelations.nodes.length;// Panning or zooming hands the view over to the user for good — re-fitting under their fingers// would make the map impossible to explore while it is still settling.@@ -684,7 +751,7 @@ function setupFraming(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, c// Damping, once the graph has had the room to spread out, so that a small map comes to rest// instead of drifting for the whole cooldown.- if (++ticks === TICKS_UNTIL_DAMPED && framedNoteIds.size < 30) {+ if (++ticks === TICKS_UNTIL_DAMPED && framedNoteIds.size < DAMPING_MAX_NOTES) {graph.d3VelocityDecay(0.4);}});@@ -695,6 +762,41 @@ function setupFraming(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, c};}+/**+ * What the view is to be framed on, worked out once from the map's data — see {@link setupFraming} for+ * what is done with it.+ */+export function planFraming({ widgetMode, noteType, notesAndRelations, hopDistances }: {+ widgetMode: NoteMapWidgetMode;+ /** Of the note the map is drawn for, a search note being no part of its own results. */+ noteType: string | undefined;+ notesAndRelations: NotesAndRelationsData;+ hopDistances: Map<string, number>;+}) {+ // The notes that can be reached from the one the map is rooted at, which is what the distances+ // drawn on are a walk of already.+ const framedNoteIds: Set<string | number> = (isRootedAtCurrentNote(widgetMode) && noteType !== "search")+ ? new Set(hopDistances.keys())+ : getNoteIdsWithLinks(notesAndRelations);++ // A lone note has no extent to fit and would just be blown up to the maximum zoom, hiding the+ // rest of the map; the whole graph is the more useful thing to look at then.+ const framesSubset = framedNoteIds.size > 1;++ return {+ framedNoteIds,+ framesSubset,+ padding: getFitPadding(widgetMode, framedNoteIds.size),+ /**+ * What the fit is measured on: the framed notes, or the whole graph where those are no more+ * than the one note. A note whose map is only itself has no extent to fit at all — the fit+ * then asks for a zoom of hundreds and gets the highest allowed, which fills the card with a+ * single circle and the beginning of a title. It is shown at a size it can be read at instead.+ */+ fittedNoteCount: framesSubset ? framedNoteIds.size : notesAndRelations.nodes.length+ };+}+function getNoteIdsWithLinks(data: NotesAndRelationsData) {const noteIds = new Set<string | number>();diff --git a/apps/client/src/widgets/note_map/utils.spec.ts b/apps/client/src/widgets/note_map/utils.spec.tsindex cf92977152..ec1811e737 100644--- a/apps/client/src/widgets/note_map/utils.spec.ts+++ b/apps/client/src/widgets/note_map/utils.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { getFitPadding, getHopDistances, mixColors, toMapType, withAlpha } from "./utils";+import { getFitPadding, getHopDistances, mixColors, rgb2hex, toMapType, withAlpha } from "./utils";describe("getHopDistances", () => {const link = (source: string, target: string) => ({ source, target });@@ -27,6 +27,9 @@ describe("getHopDistances", () => {it("has nothing to measure where the map is not rooted at one of its own notes", () => {// A search note is not among its own results, so its map has no note to be rooted at.expect(getHopDistances("search", [ link("result", "other") ]).size).toBe(0);++ // A relation with an end the graph has looked up and found nothing for is no way anywhere.+ expect(getHopDistances("root", [ link("root", "near"), { source: {}, target: "root" } ]).get("near")).toBe(1);});it("reads the ends of a relation once the graph has looked them up", () => {@@ -36,6 +39,18 @@ describe("getHopDistances", () => {});});+describe("rgb2hex", () => {+ it("takes the colour a browser hands back and gives it as a canvas takes it", () => {+ // Which is the form every colour is asked of the theme in — see getCssData.+ expect(rgb2hex("rgb(0, 0, 0)")).toBe("#000000");+ expect(rgb2hex("rgb(255, 128, 7)")).toBe("#ff8007");+ expect(rgb2hex("rgb(1,2,3)")).toBe("#010203");++ // Anything else — a colour with an opacity, above all — is past reading.+ expect(rgb2hex("rgba(0, 0, 0, 0.5)")).toBe("#");+ });+});+describe("mixColors", () => {it("takes a colour the given part of the way to another, and gives up on what it cannot read", () => {expect(mixColors("#000000", "#ffffff", 0)).toBe("#000000");