Skip to content

Build your personal knowledge base with Trilium Notes

chore(react): start rendering nodes in note map

Elian Dorane32237559eef
diff --git a/apps/client/src/widgets/note_map.ts b/apps/client/src/widgets/note_map.ts
index c06e504655..2aa7a94d16 100644
--- a/apps/client/src/widgets/note_map.ts
+++ b/apps/client/src/widgets/note_map.ts
@@ -32,15 +32,7 @@ const TPL = /*html*/`<div class="note-map-widget">
type WidgetMode = "type" | "ribbon";
type Data = GraphData<NodeObject, LinkObject<NodeObject>>;
-interface Link extends LinkObject<NodeObject> {
- id: string;
- name: string;
-
- x: number;
- y: number;
- source: Node;
- target: Node;
-}
+
export default class NoteMapWidget extends NoteContextAwareWidget {
@@ -65,9 +57,6 @@ export default class NoteMapWidget extends NoteContextAwareWidget {
doRender() {
this.$widget = $(TPL);
- const documentStyle = window.getComputedStyle(document.documentElement);
- this.themeStyle = documentStyle.getPropertyValue("--theme-style")?.trim();
-
this.$container = this.$widget.find(".note-map-container");
this.$styleResolver = this.$widget.find(".style-resolver");
this.$fixNodesButton = this.$widget.find(".fixnodes-type-switcher > button");
@@ -90,34 +79,11 @@ export default class NoteMapWidget extends NoteContextAwareWidget {
super.doRender();
}
- setDimensions() {
- if (!this.graph) {
- // no graph has been even rendered
- return;
- }
-
- const $parent = this.$widget.parent();
-
- this.graph
- .height($parent.height() || 0)
- .width($parent.width() || 0);
- }
-
async refreshWithNote(note: FNote) {
this.$widget.show();
- //variables for the hover effekt. 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 itself
-
- let hoverNode: NodeObject | null = null;
- const highlightLinks = new Set();
- const neighbours = new Set();
-
const ForceGraph = (await import("force-graph")).default;
this.graph = new ForceGraph(this.$container[0])
- .onZoom((zoom) => this.setZoomLevel(zoom.k))
- .d3AlphaDecay(0.01)
- .d3VelocityDecay(0.08)
-
//Code to fixate nodes when dragged
.onNodeDragEnd((node) => {
if (this.fixNodes) {
@@ -128,11 +94,6 @@ export default class NoteMapWidget extends NoteContextAwareWidget {
node.fy = undefined;
}
})
- //check if hovered and set the hovernode variable, saving the hovered node object into it. Clear links variable everytime you hover. Without clearing links will stay highlighted
- .onNodeHover((node) => {
- hoverNode = node || null;
- highlightLinks.clear();
- })
// set link width to immitate a highlight effekt. Checking the condition if any links are saved in the previous defined set highlightlinks
.linkWidth((link) => (highlightLinks.has(link) ? 3 : 0.4))
@@ -140,30 +101,7 @@ export default class NoteMapWidget extends NoteContextAwareWidget {
.linkDirectionalArrowLength(4)
.linkDirectionalArrowRelPos(0.95)
- // main code for highlighting hovered nodes and neighbours. here we "style" the nodes. the nodes are rendered several hundred times per second.
- .nodeCanvasObject((_node, ctx) => {
- const node = _node as Node;
- if (hoverNode == node) {
- //paint only hovered node
- this.paintNode(node, "#661822", ctx);
- neighbours.clear(); //clearing neighbours or the effect would be maintained after hovering is over
- for (const _link of data.links) {
- const link = _link as unknown as Link;
- //check if node is part of a link in the canvas, if so add it´s neighbours and related links to the previous defined variables to paint the nodes
- if (link.source.id == node.id || link.target.id == node.id) {
- neighbours.add(link.source);
- neighbours.add(link.target);
- highlightLinks.add(link);
- neighbours.delete(node);
- }
- }
- } else if (neighbours.has(node) && hoverNode != null) {
- //paint neighbours
- this.paintNode(node, "#9d6363", ctx);
- } else {
- this.paintNode(node, this.getColorForNode(node), ctx); //paint rest of nodes in canvas
- }
- })
+ // Rendering code was here
.nodePointerAreaPaint((node, _, ctx) => this.paintNode(node as Node, this.getColorForNode(node as Node), ctx))
.nodePointerAreaPaint((node, color, ctx) => {
@@ -179,8 +117,6 @@ export default class NoteMapWidget extends NoteContextAwareWidget {
ctx.fill();
})
.nodeLabel((node) => esc((node as Node).name))
- .maxZoom(7)
- .warmupTicks(30)
.onNodeClick((node) => {
if (node.id) {
appContext.tabManager.getActiveContext()?.setNote((node as Node).id);
@@ -219,71 +155,10 @@ export default class NoteMapWidget extends NoteContextAwareWidget {
this.renderData(data);
}
- getColorForNode(node: Node) {
- if (node.color) {
- return node.color;
- } else if (this.widgetMode === "ribbon" && node.id === this.noteId) {
- return "red"; // subtree root mark as red
- } else {
- return this.generateColorFromString(node.type);
- }
- }
-
- generateColorFromString(str: string) {
- if (this.themeStyle === "dark") {
- str = `0${str}`; // magic lightning modifier
- }
-
- let hash = 0;
- for (let i = 0; i < str.length; i++) {
- hash = str.charCodeAt(i) + ((hash << 5) - hash);
- }
-
- let color = "#";
- for (let i = 0; i < 3; i++) {
- const value = (hash >> (i * 8)) & 0xff;
-
- color += `00${value.toString(16)}`.substr(-2);
- }
- return color;
- }
-
setZoomLevel(level: number) {
this.zoomLevel = level;
}
- paintNode(node: Node, color: string, ctx: CanvasRenderingContext2D) {
- const { x, y } = node;
- if (!x || !y) {
- return;
- }
- const size = this.noteIdToSizeMap[node.id];
-
- ctx.fillStyle = color;
- ctx.beginPath();
- ctx.arc(x, y, size * 0.8, 0, 2 * Math.PI, false);
- ctx.fill();
-
- const toRender = this.zoomLevel > 2 || (this.zoomLevel > 1 && size > 6) || (this.zoomLevel > 0.3 && size > 10);
-
- if (!toRender) {
- return;
- }
-
- ctx.fillStyle = this.cssData.textColor;
- ctx.font = `${size}px ${this.cssData.fontFamily}`;
- ctx.textAlign = "center";
- ctx.textBaseline = "middle";
-
- let title = node.name;
-
- if (title.length > 15) {
- title = `${title.substr(0, 15)}...`;
- }
-
- ctx.fillText(title, x, y + Math.round(size * 1.5));
- }
-
paintLink(link: Link, ctx: CanvasRenderingContext2D) {
if (this.zoomLevel < 5) {
return;
diff --git a/apps/client/src/widgets/note_map/NoteMap.tsx b/apps/client/src/widgets/note_map/NoteMap.tsx
index bf9e2b7b1e..b54411159d 100644
--- a/apps/client/src/widgets/note_map/NoteMap.tsx
+++ b/apps/client/src/widgets/note_map/NoteMap.tsx
@@ -1,27 +1,22 @@
import { useEffect, useRef, useState } from "preact/hooks";
import "./NoteMap.css";
-import { getMapRootNoteId, NoteMapWidgetMode, rgb2hex } from "./utils";
+import { getMapRootNoteId, getThemeStyle, NoteMapWidgetMode, rgb2hex } from "./utils";
import { RefObject } from "preact";
import FNote from "../../entities/fnote";
-import { useNoteContext, useNoteLabel } from "../react/hooks";
+import { useElementSize, useNoteContext, useNoteLabel } from "../react/hooks";
import ForceGraph, { LinkObject, NodeObject } from "force-graph";
import { loadNotesAndRelations, NotesAndRelationsData } from "./data";
-
-interface CssData {
- fontFamily: string;
- textColor: string;
- mutedTextColor: string;
-}
+import { CssData, setupRendering } from "./rendering";
interface NoteMapProps {
note: FNote;
widgetMode: NoteMapWidgetMode;
+ parentRef: RefObject<HTMLElement>;
}
type MapType = "tree" | "link";
-export default function NoteMap({ note, widgetMode }: NoteMapProps) {
- console.log("Got note", note);
+export default function NoteMap({ note, widgetMode, parentRef }: NoteMapProps) {
const containerRef = useRef<HTMLDivElement>(null);
const styleResolverRef = useRef<HTMLDivElement>(null);
const [ cssData, setCssData ] = useState<CssData>();
@@ -36,50 +31,57 @@ export default function NoteMap({ note, widgetMode }: NoteMapProps) {
return (
<div className="note-map-widget">
<div ref={styleResolverRef} class="style-resolver" />
- <NoteGraph containerRef={containerRef} note={note} widgetMode={widgetMode} mapType={mapType} />
+ <NoteGraph parentRef={parentRef} containerRef={containerRef} note={note} widgetMode={widgetMode} mapType={mapType} cssData={cssData} />
</div>
)
}
-function NoteGraph({ containerRef, note, widgetMode, mapType }: {
+function NoteGraph({ containerRef, parentRef, note, widgetMode, mapType, cssData }: {
containerRef: RefObject<HTMLDivElement>;
+ parentRef: RefObject<HTMLElement>;
note: FNote;
widgetMode: NoteMapWidgetMode;
mapType: MapType;
+ cssData: CssData;
}) {
const graphRef = useRef<ForceGraph<NodeObject, LinkObject<NodeObject>>>();
- const [ data, setData ] = useState<NotesAndRelationsData>();
- console.log("Got data ", data);
+ const containerSize = useElementSize(parentRef);
// Build the note graph instance.
useEffect(() => {
const container = containerRef.current;
if (!container) return;
- const { width, height } = container.getBoundingClientRect();
- const graph = new ForceGraph(container)
- .width(width)
- .height(height);
+ const graph = new ForceGraph(container);
+
graphRef.current = graph;
const mapRootId = getMapRootNoteId(note.noteId, note, widgetMode);
+ console.log("Map root ID ", mapRootId);
if (!mapRootId) return;
const labelValues = (name: string) => note.getLabels(name).map(l => l.value) ?? [];
const excludeRelations = labelValues("mapExcludeRelation");
const includeRelations = labelValues("mapIncludeRelation");
- loadNotesAndRelations(mapRootId, excludeRelations, includeRelations, mapType).then((data) => {
- console.log("Got data ", data);
+ loadNotesAndRelations(mapRootId, excludeRelations, includeRelations, mapType).then((notesAndRelations) => {
+ setupRendering(graph, {
+ cssData,
+ noteId: note.noteId,
+ noteIdToSizeMap: notesAndRelations.noteIdToSizeMap,
+ notesAndRelations,
+ themeStyle: getThemeStyle(),
+ widgetMode
+ });
+ graph.graphData(notesAndRelations);
});
return () => container.replaceChildren();
}, [ note ]);
- // Render the data.
+ // React to container size
useEffect(() => {
- if (!graphRef.current || !data) return;
- graphRef.current.graphData(data);
- }, [ data ]);
-
+ if (!containerSize || !graphRef.current) return;
+ graphRef.current.width(containerSize.width).height(containerSize.height);
+ }, [ containerSize?.width, containerSize?.height ]);
return <div ref={containerRef} className="note-map-container" />;
}
diff --git a/apps/client/src/widgets/note_map/data.ts b/apps/client/src/widgets/note_map/data.ts
index 1909f1d499..dd28bd5bfa 100644
--- a/apps/client/src/widgets/note_map/data.ts
+++ b/apps/client/src/widgets/note_map/data.ts
@@ -1,6 +1,6 @@
import { NoteMapLink, NoteMapPostResponse } from "@triliumnext/commons";
import server from "../../services/server";
-import { NodeObject } from "force-graph";
+import { LinkObject, NodeObject } from "force-graph";
type MapType = "tree" | "link";
@@ -11,13 +11,22 @@ interface GroupedLink {
names: string[];
}
-interface Node extends NodeObject {
+export interface Node extends NodeObject {
id: string;
name: string;
type: string;
color: string;
}
+export interface Link extends LinkObject<NodeObject> {
+ id: string;
+ name: string;
+ x: number;
+ y: number;
+ source: Node;
+ target: Node;
+}
+
export interface NotesAndRelationsData {
nodes: Node[];
links: {
diff --git a/apps/client/src/widgets/note_map/rendering.ts b/apps/client/src/widgets/note_map/rendering.ts
new file mode 100644
index 0000000000..2cea9ea39d
--- /dev/null
+++ b/apps/client/src/widgets/note_map/rendering.ts
@@ -0,0 +1,96 @@
+import type ForceGraph from "force-graph";
+import { Link, Node, NotesAndRelationsData } from "./data";
+import { NodeObject } from "force-graph";
+import { getColorForNode, NoteMapWidgetMode } from "./utils";
+
+export interface CssData {
+ fontFamily: string;
+ textColor: string;
+ mutedTextColor: string;
+}
+
+interface RenderData {
+ noteIdToSizeMap: Record<string, number>;
+ cssData: CssData;
+ noteId: string;
+ themeStyle: "light" | "dark";
+ widgetMode: NoteMapWidgetMode;
+ notesAndRelations: NotesAndRelationsData;
+}
+
+export function setupRendering(graph: ForceGraph, { noteId, themeStyle, widgetMode, noteIdToSizeMap, notesAndRelations, cssData }: 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 itself
+ const neighbours = new Set();
+ const highlightLinks = new Set();
+ let hoverNode: NodeObject | null = null;
+ let zoomLevel: number;
+
+ function paintNode(node: Node, color: string, ctx: CanvasRenderingContext2D) {
+ const { x, y } = node;
+ if (!x || !y) {
+ return;
+ }
+ const size = noteIdToSizeMap[node.id];
+
+ ctx.fillStyle = color;
+ ctx.beginPath();
+ ctx.arc(x, y, size * 0.8, 0, 2 * Math.PI, false);
+ ctx.fill();
+
+ const toRender = zoomLevel > 2 || (zoomLevel > 1 && size > 6) || (zoomLevel > 0.3 && size > 10);
+
+ if (!toRender) {
+ return;
+ }
+
+ ctx.fillStyle = cssData.textColor;
+ ctx.font = `${size}px ${cssData.fontFamily}`;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+
+ let title = node.name;
+
+ if (title.length > 15) {
+ title = `${title.substr(0, 15)}...`;
+ }
+
+ ctx.fillText(title, x, y + Math.round(size * 1.5));
+ }
+
+ // main code for highlighting hovered nodes and neighbours. here we "style" the nodes. the nodes are rendered several hundred times per second.
+ graph
+ .d3AlphaDecay(0.01)
+ .d3VelocityDecay(0.08)
+ .maxZoom(7)
+ .warmupTicks(30)
+ .nodeCanvasObject((_node, ctx) => {
+ const node: Node = _node as Node;
+ if (hoverNode == node) {
+ //paint only hovered node
+ paintNode(node, "#661822", ctx);
+ neighbours.clear(); //clearing neighbours or the effect would be maintained after hovering is over
+ for (const _link of notesAndRelations.links) {
+ const link = _link as unknown as Link;
+ //check if node is part of a link in the canvas, if so add it´s neighbours and related links to the previous defined variables to paint the nodes
+ if (link.source.id == node.id || link.target.id == node.id) {
+ neighbours.add(link.source);
+ neighbours.add(link.target);
+ highlightLinks.add(link);
+ neighbours.delete(node);
+ }
+ }
+ } else if (neighbours.has(node) && hoverNode != null) {
+ //paint neighbours
+ paintNode(node, "#9d6363", ctx);
+ } else {
+ paintNode(node, getColorForNode(node, noteId, themeStyle, widgetMode), ctx); //paint rest of nodes in canvas
+ }
+ })
+ //check if hovered and set the hovernode variable, saving the hovered node object into it. Clear links variable everytime you hover. Without clearing links will stay highlighted
+ .onNodeHover((node) => {
+ hoverNode = node || null;
+ highlightLinks.clear();
+ })
+ .onZoom((zoom) => zoomLevel = zoom.k);
+}
+
diff --git a/apps/client/src/widgets/note_map/utils.ts b/apps/client/src/widgets/note_map/utils.ts
index 8014df4141..1a902cdb82 100644
--- a/apps/client/src/widgets/note_map/utils.ts
+++ b/apps/client/src/widgets/note_map/utils.ts
@@ -1,6 +1,7 @@
import appContext from "../../components/app_context";
import FNote from "../../entities/fnote";
import hoisted_note from "../../services/hoisted_note";
+import { Node } from "./data";
export type NoteMapWidgetMode = "ribbon" | "hoisted";
@@ -26,3 +27,37 @@ export function getMapRootNoteId(noteId: string, note: FNote, widgetMode: NoteMa
return mapRootNoteId;
}
+
+export function getColorForNode(node: Node, noteId: string, themeStyle: "light" | "dark", widgetMode: NoteMapWidgetMode) {
+ if (node.color) {
+ return node.color;
+ } else if (widgetMode === "ribbon" && node.id === noteId) {
+ return "red"; // subtree root mark as red
+ } else {
+ return generateColorFromString(node.type, themeStyle);
+ }
+}
+
+function generateColorFromString(str: string, themeStyle: "light" | "dark") {
+ if (themeStyle === "dark") {
+ str = `0${str}`; // magic lightning modifier
+ }
+
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ hash = str.charCodeAt(i) + ((hash << 5) - hash);
+ }
+
+ let color = "#";
+ for (let i = 0; i < 3; i++) {
+ const value = (hash >> (i * 8)) & 0xff;
+
+ color += `00${value.toString(16)}`.substr(-2);
+ }
+ return color;
+}
+
+export function getThemeStyle() {
+ const documentStyle = window.getComputedStyle(document.documentElement);
+ return documentStyle.getPropertyValue("--theme-style")?.trim() as "light" | "dark";
+}
diff --git a/apps/client/src/widgets/ribbon/NoteMapTab.tsx b/apps/client/src/widgets/ribbon/NoteMapTab.tsx
index 88ee108adf..2c814012ea 100644
--- a/apps/client/src/widgets/ribbon/NoteMapTab.tsx
+++ b/apps/client/src/widgets/ribbon/NoteMapTab.tsx
@@ -26,7 +26,7 @@ export default function NoteMapTab({ note }: TabContext) {
return (
<div className="note-map-ribbon-widget" style={{ height }} ref={containerRef}>
- {note && <NoteMap note={note} widgetMode="ribbon" />}
+ {note && <NoteMap note={note} widgetMode="ribbon" parentRef={containerRef} />}
{!isExpanded ? (
<ActionButton