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
feat(client): draw each note's icon inside its dot on the note map
Elian Doran09e32e027c5c
diff --git a/apps/client/src/widgets/note_map/NoteMap.css b/apps/client/src/widgets/note_map/NoteMap.cssindex 15955713a8..28da932c7d 100644--- a/apps/client/src/widgets/note_map/NoteMap.css+++ b/apps/client/src/widgets/note_map/NoteMap.css@@ -60,3 +60,11 @@color: var(--muted-text-color);display: none;}++/* 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.tsxindex 7a9f1ad39e..a079cfe54b 100644--- a/apps/client/src/widgets/note_map/NoteMap.tsx+++ b/apps/client/src/widgets/note_map/NoteMap.tsx@@ -16,6 +16,7 @@ import { useElementSize, useNoteLabel } from "../react/hooks";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, NoteMapWidgetMode, rgb2hex, toMapType } from "./utils";@@ -79,7 +80,13 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {const labelValues = (name: string) => note.getLabels(name).map(l => l.value) ?? [];const excludeRelations = labelValues("mapExcludeRelation");const includeRelations = labelValues("mapIncludeRelation");- loadNotesAndRelations(mapRootId, excludeRelations, includeRelations, mapType, widgetMode === "sidebar").then((notesAndRelations) => {+ Promise.all([+ 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()+ ]).then(([ notesAndRelations ]) => {if (disposed || !containerRef.current || !styleResolverRef.current) return;// Guard against rendering too many notes which would freeze the browser.@@ -90,6 +97,7 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {setTooManyNotes(null);const cssData = getCssData(containerRef.current, styleResolverRef.current);+ const iconGlyphs = resolveIconGlyphs(notesAndRelations.nodes.map((node) => node.icon), containerRef.current);// Configure rendering properties.teardownRendering = setupRendering(graph, {@@ -101,7 +109,8 @@ export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {themeStyle: getEffectiveThemeStyle(),widgetMode,mapType,- container+ container,+ iconGlyphs});// Interactiondiff --git a/apps/client/src/widgets/note_map/data.ts b/apps/client/src/widgets/note_map/data.tsindex 3fd27d3565..c7dcf79b76 100644--- a/apps/client/src/widgets/note_map/data.ts+++ b/apps/client/src/widgets/note_map/data.ts@@ -15,7 +15,10 @@ export interface NoteMapNodeObject extends NodeObject {id: string;name: string;type: string;- color: string;+ /** What the note asks to be drawn in through its `color` label, if it asks at all. */+ color: string | null;+ /** The note's icon, as the classes it is drawn with everywhere else (e.g. `tn-icon bx bx-file`). */+ icon: string;}export interface NoteMapLinkObject extends LinkObject<NoteMapNodeObject> {@@ -51,11 +54,12 @@ export async function loadNotesAndRelations(mapRootNoteId: string, excludeRelaticonst noteIdToSizeMap = calculateNodeSizes(resp, mapType);const links = getGroupedLinks(resp.links);- let nodes = resp.notes.map(([noteId, title, type, color]) => ({+ let nodes = resp.notes.map(([noteId, title, type, color, icon]) => ({id: noteId,name: title,- type: type,- color: color+ type,+ color,+ icon}));// A tree map links every node to its parent, so it has no unlinked notes to speak of.diff --git a/apps/client/src/widgets/note_map/icons.ts b/apps/client/src/widgets/note_map/icons.tsnew file mode 100644index 0000000000..eb622cc0e8--- /dev/null+++ b/apps/client/src/widgets/note_map/icons.ts@@ -0,0 +1,52 @@+/** 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.tsindex 289dbb0e9c..0ab318a243 100644--- a/apps/client/src/widgets/note_map/rendering.ts+++ b/apps/client/src/widgets/note_map/rendering.ts@@ -1,7 +1,8 @@import type ForceGraph from "force-graph";import { NoteMapLinkObject, NoteMapNodeObject, NotesAndRelationsData } from "./data";import { LinkObject, NodeObject } from "force-graph";-import { generateColorFromString, getFitPadding, isRootedAtCurrentNote, MapType, NoteMapWidgetMode } from "./utils";+import { ICON_FONT_FAMILY } from "./icons";+import { generateColorFromString, getFitPadding, isLightColor, isRootedAtCurrentNote, MapType, NoteMapWidgetMode } from "./utils";import { escapeHtml } from "../../services/utils";import FNote from "../../entities/fnote";@@ -11,6 +12,9 @@ const TICKS_UNTIL_DAMPED = 60;/** What a map of a single note is shown at, there being no extent to fit — see {@link setupFraming}. */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;+export interface CssData {fontFamily: string;textColor: string;@@ -28,10 +32,12 @@ interface RenderData {mapType: MapType;/** 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>;}/** @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, mapType, container }: RenderData) {+export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkObject>, { note, noteId, themeStyle, widgetMode, noteIdToSizeMap, notesAndRelations, cssData, mapType, container, iconGlyphs }: RenderData) {// variables for the hover effect. We have to save the neighbours of a hovered node in a set. Also we need to save the links as well as the hovered node itselfconst neighbours = new Set();const highlightLinks = new Set();@@ -59,10 +65,15 @@ export function setupRendering(graph: ForceGraph<NoteMapNodeObject, NoteMapLinkOconst size = noteIdToSizeMap[node.id];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.fill();+ paintNodeIcon(node, size, dotColor, x, y, ctx);+const toRender = zoomLevel > 2 || (zoomLevel > 1 && size > 6) || (zoomLevel > 0.3 && size > 10);if (!toRender) {@@ -84,6 +95,27 @@ 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.+ *+ * 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) {+ const glyph = iconGlyphs.get(node.icon);++ if (!glyph || !(size * 0.8 * zoomLevel >= MIN_ICON_RADIUS)) {+ return;+ }++ ctx.fillStyle = isLightColor(dotColor) ? "#000" : "#fff";+ ctx.font = `${size}px ${ICON_FONT_FAMILY}`;+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ ctx.fillText(glyph, x, y);+ }+function paintLink(link: NoteMapLinkObject, ctx: CanvasRenderingContext2D) {if (zoomLevel < 5) {return;diff --git a/apps/client/src/widgets/note_map/utils.spec.ts b/apps/client/src/widgets/note_map/utils.spec.tsindex bd3ae50dd7..698d19c892 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, toMapType } from "./utils";+import { getFitPadding, isLightColor, toMapType } from "./utils";describe("toMapType", () => {it("only reads the tree map out of the label, the link map standing for anything else", () => {@@ -12,6 +12,26 @@ 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.tsindex a624b5f1fe..1ce84a7826 100644--- a/apps/client/src/widgets/note_map/utils.ts+++ b/apps/client/src/widgets/note_map/utils.ts@@ -56,6 +56,30 @@ 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;+}+export function generateColorFromString(str: string, themeStyle: "light" | "dark") {if (themeStyle === "dark") {str = `0${str}`; // magic lightning modifierdiff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex e6f174600a..b85e3e4620 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -509,8 +509,11 @@ export interface NoteMapLink {name: string;}+/** A note of a map, kept as a tuple rather than an object: a map carries thousands of them. */+export type NoteMapNote = [ noteId: string, title: string, type: string, color: string | null, icon: string ];+export interface NoteMapPostResponse {- notes: string[];+ notes: NoteMapNote[];links: NoteMapLink[];noteIdToDescendantCountMap: Record<string, number>;}diff --git a/packages/trilium-core/src/routes/api/note_map.spec.ts b/packages/trilium-core/src/routes/api/note_map.spec.tsindex f1717dd0be..8b5b89a5be 100644--- a/packages/trilium-core/src/routes/api/note_map.spec.ts+++ b/packages/trilium-core/src/routes/api/note_map.spec.ts@@ -1,4 +1,4 @@-import { trimIndentation } from "@triliumnext/commons";+import { NoteMapNote, trimIndentation } from "@triliumnext/commons";import { beforeAll, describe, expect, it, vi } from "vitest";import becca from "../../becca/becca";@@ -8,13 +8,13 @@ import { buildNote, buildNotes } from "../../test/becca_easy_mocking";import note_map from "./note_map";interface LinkMapResponse {- notes: [string, string, string, string | null][];+ notes: NoteMapNote[];noteIdToDescendantCountMap: Record<string, number>;links: { id: string; sourceNoteId: string; targetNoteId: string; name: string }[];}interface TreeMapResponse {- notes: [string, string, string, string | null][];+ notes: NoteMapNote[];noteIdToDescendantCountMap: Record<string, number>;links: { sourceNoteId: string; targetNoteId: string }[];}diff --git a/packages/trilium-core/src/routes/api/note_map.ts b/packages/trilium-core/src/routes/api/note_map.tsindex 534e5058e7..c0d5d3b57b 100644--- a/packages/trilium-core/src/routes/api/note_map.ts+++ b/packages/trilium-core/src/routes/api/note_map.ts@@ -1,7 +1,7 @@import BAttribute from "../../becca/entities/battribute";import BNote from "../../becca/entities/bnote";import becca from "../../becca/becca";-import type { BacklinkCountResponse, BacklinksResponse } from "@triliumnext/commons";+import type { BacklinkCountResponse, BacklinksResponse, NoteMapNote } from "@triliumnext/commons";import type { Request } from "express";import { findExcerpts, findLlmChatExcerpts } from "../../services/backlink_excerpts";@@ -139,10 +139,10 @@ function getLinkMap(req: Request<{ noteId: string }>) {const noteIdsArray = Array.from(noteIds);- const notes = noteIdsArray.map((noteId) => {+ const notes: NoteMapNote[] = noteIdsArray.map((noteId) => {const note = becca.getNoteOrThrow(noteId);- return [note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color")];+ return [ note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color"), note.getIcon() ];});const links = Object.values(becca.attributes)@@ -208,7 +208,7 @@ function getTreeMap(req: Request<{ noteId: string }>) {return !note.getParentNotes().find((parentNote) => parentNote.noteId === imageLinkRelation.noteId);})- .map((note) => [note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color")]);+ .map((note): NoteMapNote => [ note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color"), note.getIcon() ]);const noteIds = new Set<string>();notes.forEach(([noteId]) => noteId && noteIds.add(noteId));