Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): draw note map nodes as note badges

Elian Doranee02931e7693
diff --git a/apps/client/src/widgets/note_map/NoteMap.css b/apps/client/src/widgets/note_map/NoteMap.css
index 28da932c7d..c34617dc05 100644
--- a/apps/client/src/widgets/note_map/NoteMap.css
+++ b/apps/client/src/widgets/note_map/NoteMap.css
@@ -56,9 +56,28 @@
/* End of styling the slider */
+/*
+ * What the map asks the theme for what it is drawn in, each one wearing the colour it stands for so
+ * that it can be read back off it. The map draws on a canvas, which knows nothing of a stylesheet.
+ */
.style-resolver {
color: var(--muted-text-color);
display: none;
+
+ .style-resolver-background {
+ color: var(--main-background-color);
+ }
+
+ /* What a note's icon is drawn on and in wherever else it is shown at a size — beside the title of
+ the note being read, above all, which is the very note the map is drawn around. The themes that
+ do not name them are answered with what the map drew that note in before they existed. */
+ .style-resolver-anchor {
+ color: var(--note-icon-background-color, var(--link-color));
+ }
+
+ .style-resolver-anchor-icon {
+ 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
diff --git a/apps/client/src/widgets/note_map/NoteMap.tsx b/apps/client/src/widgets/note_map/NoteMap.tsx
index 730ef80781..603bf3eee9 100644
--- a/apps/client/src/widgets/note_map/NoteMap.tsx
+++ b/apps/client/src/widgets/note_map/NoteMap.tsx
@@ -106,7 +106,7 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {
// Configure rendering properties.
teardownRendering = setupRendering(graph, {
note,
- noteId: note.noteId,
+ mapRootId,
noteIdToSizeMap: notesAndRelations.noteIdToSizeMap,
cssData,
notesAndRelations,
@@ -225,19 +225,34 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {
</div>
)}
- <div ref={styleResolverRef} class="style-resolver" />
+ {/* What the map is drawn in, asked of the theme — see getCssData. */}
+ <div ref={styleResolverRef} class="style-resolver">
+ <span class="style-resolver-background" />
+ <span class="style-resolver-anchor" />
+ <span class="style-resolver-anchor-icon" />
+ </div>
<div ref={containerRef} className="note-map-container" />
</div>
);
}
+/**
+ * What the map is drawn in, asked of the theme through elements wearing the colours it is after: a
+ * canvas knows nothing of a stylesheet, and a theme is free to have its own idea of any of them.
+ */
function getCssData(container: HTMLElement, styleResolver: HTMLElement): CssData {
const containerStyle = window.getComputedStyle(container);
- const styleResolverStyle = window.getComputedStyle(styleResolver);
+ const colorOf = (selector: string) => {
+ const element = styleResolver.querySelector(selector);
+ return element ? rgb2hex(window.getComputedStyle(element).color) : "";
+ };
return {
fontFamily: containerStyle.fontFamily,
textColor: rgb2hex(containerStyle.color),
- mutedTextColor: rgb2hex(styleResolverStyle.color)
+ mutedTextColor: rgb2hex(window.getComputedStyle(styleResolver).color),
+ backgroundColor: colorOf(".style-resolver-background"),
+ anchorColor: colorOf(".style-resolver-anchor"),
+ anchorIconColor: colorOf(".style-resolver-anchor-icon")
};
}
diff --git a/apps/client/src/widgets/note_map/rendering.ts b/apps/client/src/widgets/note_map/rendering.ts
index 2ae9629d62..12faf50f82 100644
--- a/apps/client/src/widgets/note_map/rendering.ts
+++ b/apps/client/src/widgets/note_map/rendering.ts
@@ -1,10 +1,10 @@
import type ForceGraph from "force-graph";
+
+import FNote from "../../entities/fnote";
+import { escapeHtml } from "../../services/utils";
import { NoteMapLinkObject, NoteMapNodeObject, NotesAndRelationsData } from "./data";
-import { LinkObject, NodeObject } from "force-graph";
import { ICON_FONT_FAMILY } from "./icons";
-import { generateColorFromString, getFitPadding, isLightColor, isRootedAtCurrentNote, mixColors, NoteMapWidgetMode, withAlpha } from "./utils";
-import { escapeHtml } from "../../services/utils";
-import FNote from "../../entities/fnote";
+import { getFitPadding, getHopDistances, isRootedAtCurrentNote, mixColors, NoteMapWidgetMode, withAlpha } from "./utils";
/** Roughly a second of simulation at 60 fps — see {@link setupFraming}. */
const TICKS_UNTIL_DAMPED = 60;
@@ -15,6 +15,9 @@ 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 thick the ring around the note the map is drawn around is on screen. */
+const ANCHOR_RING_PX = 2;
+
/** How much is left of what the pointer is not resting on, while it rests on a note of the map. */
const DIMMED_ALPHA = 0.15;
@@ -71,13 +74,30 @@ export interface CssData {
fontFamily: string;
textColor: string;
mutedTextColor: string;
+ /**
+ * What the map is drawn on: the notes are faded towards it the further they are from the one the
+ * map is rooted at, and their icons are cut out of them in it.
+ */
+ backgroundColor: string;
+ /**
+ * What a note's icon is drawn on and in beside the title of the note being read, which the map
+ * draws the very same note in — so that the middle of the map and the note it is about are
+ * plainly one thing. The second doubles as the ring that picks it out: on a dark theme the badge
+ * is a dark circle, which a map of light notes would otherwise swallow.
+ */
+ anchorColor: string;
+ anchorIconColor: string;
}
interface RenderData {
note: FNote;
noteIdToSizeMap: Record<string, number>;
cssData: CssData;
- noteId: string;
+ /**
+ * The note the map is drawn around — the one being read, where the map follows it, and otherwise
+ * the one it has been pointed at. Everything else is coloured by how far it is from this one.
+ */
+ mapRootId: string;
themeStyle: "light" | "dark";
widgetMode: NoteMapWidgetMode;
notesAndRelations: NotesAndRelationsData;
@@ -88,7 +108,7 @@ interface RenderData {
}
/** @returns a teardown function to call when the graph is discarded. */
-export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, { note, noteId, themeStyle, widgetMode, noteIdToSizeMap, notesAndRelations, cssData, container, iconGlyphs }: RenderData) {
+export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, { note, mapRootId, themeStyle, widgetMode, noteIdToSizeMap, notesAndRelations, cssData, container, iconGlyphs }: RenderData) {
// What the map is showing of the note under the pointer: the note itself, the notes a relation
// 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.
@@ -98,6 +118,8 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO
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>();
+ /** How many relations lie between each note and the one the map is rooted at — see {@link setupFraming}. */
+ const hopDistances = getHopDistances(mapRootId, notesAndRelations.links);
/**
* What the hovered note's own relations are drawn in. Remembered rather than asked of the hovered
* note as it is drawn, so that they have a colour to fade back from once the pointer has left.
@@ -210,14 +232,16 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO
fadeTimer = 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) {
- if (node.color) {
- return node.color;
- } else if (isRootedAtCurrentNote(widgetMode) && node.id === noteId) {
- return "red"; // subtree root mark as red
- } else {
- return generateColorFromString(node.type, themeStyle);
- }
+ return node.color || cssData.anchorColor;
}
/**
@@ -265,15 +289,28 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO
}
const size = noteIdToSizeMap[node.id];
+ const radius = size * 0.8;
+
ctx.fillStyle = color;
- // Read back rather than kept: a canvas resolves whatever colour it is given — a name, a
- // function, a shorthand — to one form, which is the one worth asking anything about.
- const dotColor = typeof ctx.fillStyle === "string" ? ctx.fillStyle : color;
ctx.beginPath();
- ctx.arc(x, y, size * 0.8, 0, 2 * Math.PI, false);
+ ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
ctx.fill();
- paintNodeIcon(node, size, dotColor, x, y, ctx);
+ // The note the map is drawn around wears a ring, which is what picks it out of the notes
+ // around it: it is drawn as its icon is drawn beside its title, and on a dark theme that is a
+ // dark circle — the quietest thing on a map whose notes are the light ones. The ring is in
+ // the colour of the icon within it, so it is of the badge rather than something laid over it.
+ if (node.id === mapRootId) {
+ const width = ANCHOR_RING_PX / zoomLevel;
+
+ ctx.strokeStyle = cssData.anchorIconColor;
+ ctx.lineWidth = width;
+ ctx.beginPath();
+ ctx.arc(x, y, radius + width / 2, 0, 2 * Math.PI, false);
+ ctx.stroke();
+ }
+
+ paintNodeIcon(node, size, x, y, ctx);
if (!isLabelDrawn(size)) {
return;
@@ -334,20 +371,26 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO
/**
- * The note's own icon, over 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.
+ * 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.
+ *
+ * Drawn as it is drawn beside a title, in the colour that goes with the badge under it.
+ *
+ * A note that asks for a colour of its own has no such pairing to draw on, so its 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.
*
* Only where the dot is drawn large enough on screen to hold it: below that the glyph is a smudge
* over the colour, and the colour alone says more.
*/
- function paintNodeIcon(node: NoteMapNodeObject, size: number, dotColor: string, x: number, y: number, ctx: CanvasRenderingContext2D) {
+ function 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)) {
return;
}
- ctx.fillStyle = isLightColor(dotColor) ? "#000" : "#fff";
+ ctx.fillStyle = node.color ? cssData.backgroundColor : cssData.anchorIconColor;
ctx.font = `${size}px ${ICON_FONT_FAMILY}`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
@@ -467,6 +510,8 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO
// Every note keeps its own colour while one of them is hovered; what tells the note's
// own from the rest of the map is that the rest of it is faded back behind them.
ctx.save();
+ // 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);
ctx.restore();
@@ -514,7 +559,7 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkO
graph.d3Force("charge")?.strength(boundedCharge);
graph.d3Force("charge")?.distanceMax(1000);
- const stopFraming = setupFraming(graph, container, { note, noteId, widgetMode, notesAndRelations });
+ const stopFraming = setupFraming(graph, container, { note, widgetMode, notesAndRelations, hopDistances });
return () => {
clearTimeout(fadeTimer);
@@ -593,9 +638,11 @@ 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, noteId, widgetMode, notesAndRelations }: Pick<RenderData, "note" | "noteId" | "widgetMode" | "notesAndRelations">) {
+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")
- ? getSubGraphConnectedToCurrentNote(noteId, notesAndRelations)
+ ? 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
@@ -662,51 +709,3 @@ function getNoteIdsWithLinks(data: NotesAndRelationsData) {
return noteIds;
}
-
-function getSubGraphConnectedToCurrentNote(noteId: string, data: NotesAndRelationsData) {
- function getGroupedLinks(links: LinkObject<NodeObject>[], type: "source" | "target") {
- const map: Record<string | number, LinkObject<NodeObject>[]> = {};
-
- for (const link of links) {
- if (typeof link[type] !== "object") {
- continue;
- }
-
- const key = link[type].id;
- if (key) {
- map[key] = map[key] || [];
- map[key].push(link);
- }
- }
-
- return map;
- }
-
- const linksBySource = getGroupedLinks(data.links, "source");
- const linksByTarget = getGroupedLinks(data.links, "target");
-
- const subGraphNoteIds = new Set<string | number>();
-
- function traverseGraph(noteId?: string | number) {
- if (!noteId || subGraphNoteIds.has(noteId)) {
- return;
- }
-
- subGraphNoteIds.add(noteId);
-
- for (const link of linksBySource[noteId] || []) {
- if (typeof link.target === "object") {
- traverseGraph(link.target?.id);
- }
- }
-
- for (const link of linksByTarget[noteId] || []) {
- if (typeof link.source === "object") {
- traverseGraph(link.source?.id);
- }
- }
- }
-
- traverseGraph(noteId);
- return subGraphNoteIds;
-}
diff --git a/apps/client/src/widgets/note_map/utils.spec.ts b/apps/client/src/widgets/note_map/utils.spec.ts
index f2379b427b..cf92977152 100644
--- a/apps/client/src/widgets/note_map/utils.spec.ts
+++ b/apps/client/src/widgets/note_map/utils.spec.ts
@@ -1,6 +1,40 @@
import { describe, expect, it } from "vitest";
-import { getFitPadding, isLightColor, mixColors, toMapType, withAlpha } from "./utils";
+import { getFitPadding, getHopDistances, mixColors, toMapType, withAlpha } from "./utils";
+
+describe("getHopDistances", () => {
+ const link = (source: string, target: string) => ({ source, target });
+
+ it("counts the relations between each note and the one the map is rooted at, whichever way they run", () => {
+ // root → near → far, and a relation pointing back at the root rather than away from it.
+ const distances = getHopDistances("root", [ link("root", "near"), link("near", "far"), link("pointsAtRoot", "root") ]);
+
+ expect(distances.get("root")).toBe(0);
+ expect(distances.get("near")).toBe(1);
+ expect(distances.get("far")).toBe(2);
+ // Being pointed at is as near as pointing to.
+ expect(distances.get("pointsAtRoot")).toBe(1);
+ });
+
+ it("keeps the shortest way to a note, and leaves out what cannot be reached at all", () => {
+ // "far" is two hops one way round and one the other.
+ const distances = getHopDistances("root", [ link("root", "near"), link("near", "far"), link("root", "far") ]);
+ expect(distances.get("far")).toBe(1);
+
+ expect(getHopDistances("root", [ link("root", "near"), link("alone", "elsewhere") ]).has("alone")).toBe(false);
+ });
+
+ 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);
+ });
+
+ it("reads the ends of a relation once the graph has looked them up", () => {
+ // The graph swaps each end for the note it stands for, in place, once it has the data.
+ const distances = getHopDistances("root", [ { source: { id: "root" }, target: { id: "near" } } ]);
+ expect(distances.get("near")).toBe(1);
+ });
+});
describe("mixColors", () => {
it("takes a colour the given part of the way to another, and gives up on what it cannot read", () => {
@@ -39,26 +73,6 @@ describe("toMapType", () => {
});
});
-describe("isLightColor", () => {
- it("tells the colours a note's icon wants drawing dark over from the ones it wants light", () => {
- expect(isLightColor("#ffffff")).toBe(true);
- expect(isLightColor("#ffff00")).toBe(true);
- expect(isLightColor("#fff")).toBe(true);
- expect(isLightColor("rgb(255, 255, 255)")).toBe(true);
-
- expect(isLightColor("#000000")).toBe(false);
- // Red reads as dark despite being a bright colour: the eye takes little of its brightness
- // from the red channel, which is what the icon over it has to stand out against.
- expect(isLightColor("#ff0000")).toBe(false);
- expect(isLightColor("#2c4f3d")).toBe(false);
- expect(isLightColor("rgba(0, 0, 0, 0.5)")).toBe(false);
-
- // Nothing to go on falls back to the light icon drawn over the darker half of the colours.
- expect(isLightColor("nonsense")).toBe(false);
- expect(isLightColor("")).toBe(false);
- });
-});
-
describe("getFitPadding", () => {
it("crops the sidebar's map the more of it there is to crop, and leaves the others alone", () => {
// A handful of notes is mostly its labels, which the fit does not measure: given a margin.
diff --git a/apps/client/src/widgets/note_map/utils.ts b/apps/client/src/widgets/note_map/utils.ts
index 7703392a9a..e855029ad6 100644
--- a/apps/client/src/widgets/note_map/utils.ts
+++ b/apps/client/src/widgets/note_map/utils.ts
@@ -56,30 +56,6 @@ export function rgb2hex(rgb: string) {
.join("")}`;
}
-/**
- * Whether the given colour is light enough to want something dark drawn over it — a note's icon, over
- * the dot standing for it. The dots are coloured by the note itself, by its type, or by what the map
- * makes of it, so nothing but the colour at hand says which way round it should be.
- *
- * @param color as a canvas hands it back once assigned, which is to say `#rrggbb` or `rgb(…)`.
- */
-export function isLightColor(color: string) {
- const hex = color.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i)?.[1];
- const channels = hex
- ? (hex.length === 3 ? [ ...hex ].map((c) => c + c) : hex.match(/../g) ?? []).map((c) => parseInt(c, 16))
- : (color.match(/\d+(\.\d+)?/g) ?? []).slice(0, 3).map(Number);
-
- if (channels.length < 3) {
- // Nothing to go on: what is drawn over the dots elsewhere is light, so light it stays.
- return false;
- }
-
- // Perceived brightness rather than the plain average, green counting for most of it and blue for
- // least, as the eye has it.
- const [ red, green, blue ] = channels;
- return (red * 0.299 + green * 0.587 + blue * 0.114) > 150;
-}
-
/**
* The colour a given part of the way from one to the other, for fading between two of them.
*
@@ -120,22 +96,61 @@ function toChannels(color: string) {
return channels ? channels.slice(1, 4).map((channel) => parseInt(channel, 16)) : null;
}
-export function generateColorFromString(str: string, themeStyle: "light" | "dark") {
- if (themeStyle === "dark") {
- str = `0${str}`; // magic lightning modifier
- }
+/** A relation as the map holds it, its ends being note ids until the graph has looked them up. */
+interface TraversableLink {
+ source: string | { id?: string | number };
+ target: string | { id?: string | number };
+}
- let hash = 0;
- for (let i = 0; i < str.length; i++) {
- hash = str.charCodeAt(i) + ((hash << 5) - hash);
+/**
+ * How many relations away from the given note each note of the map is, the note itself being none at
+ * all. Notes it cannot be reached from are left out, as is every note where it is not in the map to
+ * be reached from — a search note is not part of its own results.
+ *
+ * Which way round a relation runs is not what this asks: a note reached only by being pointed at is
+ * as near as one pointed to.
+ */
+export function getHopDistances(anchorNoteId: string, links: TraversableLink[]) {
+ const neighbours = new Map<string, string[]>();
+
+ const endOf = (end: TraversableLink["source"]) => (typeof end === "object" ? end.id : end);
+ const join = (from?: string | number, to?: string | number) => {
+ if (typeof from !== "string" || typeof to !== "string") {
+ return;
+ }
+
+ neighbours.set(from, [ ...(neighbours.get(from) ?? []), to ]);
+ };
+
+ for (const link of links) {
+ const source = endOf(link.source);
+ const target = endOf(link.target);
+ join(source, target);
+ join(target, source);
}
- let color = "#";
- for (let i = 0; i < 3; i++) {
- const value = (hash >> (i * 8)) & 0xff;
+ const distances = new Map<string, number>();
+ if (!neighbours.has(anchorNoteId)) {
+ return distances;
+ }
- color += `00${value.toString(16)}`.substr(-2);
+ // Breadth first, so that a note is reached by the shortest way to it before any longer one.
+ distances.set(anchorNoteId, 0);
+ for (let frontier = [ anchorNoteId ], distance = 1; frontier.length > 0; distance++) {
+ const next: string[] = [];
+
+ for (const noteId of frontier) {
+ for (const neighbour of neighbours.get(noteId) ?? []) {
+ if (!distances.has(neighbour)) {
+ distances.set(neighbour, distance);
+ next.push(neighbour);
+ }
+ }
+ }
+
+ frontier = next;
}
- return color;
+
+ return distances;
}