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(relation_map): color relations like the note map
Elian Dorana1f4562f9abb
diff --git a/apps/client/src/widgets/type_widgets/relation_map/NoteBox.tsx b/apps/client/src/widgets/type_widgets/relation_map/NoteBox.tsxindex cf62933220..c0f0ac0f63 100644--- a/apps/client/src/widgets/type_widgets/relation_map/NoteBox.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/NoteBox.tsx@@ -17,7 +17,7 @@ import { idToNoteId, noteIdToId } from "./utils";const NOTE_BOX_SOURCE_CONFIG = {filter: ".endpoint",anchor: "Continuous",- connectorStyle: { stroke: "#000", strokeWidth: 1 },+ connectorStyle: { strokeWidth: 1 },connectionType: "basic",extract: {action: "the-action"diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.css b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.cssindex 8a7c8041c5..1abd26b9d1 100644--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.css+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.css@@ -3,6 +3,9 @@}.note-detail-relation-map {+ --relation-map-line-color: var(--muted-text-color);+ --relation-map-highlight-color: var(--note-icon-background-color, var(--link-color));+height: 100%;overflow: hidden !important;position: relative;@@ -41,7 +44,26 @@cursor: crosshair;}-.note-detail-relation-map .relation-map-arrow {- stroke-width: 1.2px;- stroke-linejoin: round;+.note-detail-relation-map .jtk-connector {+ transition: opacity 0.2s ease;++ path {+ stroke: var(--relation-map-line-color);+ transition: stroke 0.2s ease, fill 0.2s ease;+ }++ .relation-map-arrow {+ fill: var(--relation-map-line-color);+ stroke-width: 1.2px;+ stroke-linejoin: round;+ }++ &.jtk-hover,+ &.relation-map-lit {+ --relation-map-line-color: var(--relation-map-lit-color, var(--relation-map-highlight-color));+ }+}++.relation-map-note-hovered :is(.jtk-connector, .connection-label):not(.relation-map-lit) {+ opacity: 0.15;}diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsxindex ef9e89e954..ea2d8e29d3 100644--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.tsx@@ -1,10 +1,12 @@+import type { Connection, jsPlumbInstance } from "jsplumb";import type { PanZoom } from "panzoom";import { render } from "preact";import { useRef } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { useCanvasClicks, useRevealSelectedBox } from "./RelationMap";+import { buildNote } from "../../../test/easy-froca";+import { useCanvasClicks, useHoveredNoteRelations, useRevealSelectedBox } from "./RelationMap";import { noteIdToId } from "./utils";describe("relation map canvas clicks", () => {@@ -197,3 +199,77 @@ describe("relation map revealing the selected box", () => {mount(noteId);}});++describe("relation map highlighting the relations of the hovered box", () => {+ let container: HTMLElement | undefined;++ afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ /** Renders a canvas with boxes `a`, `b` and `c`, a relation from `a` to `b` and one from `b` to `c`. */+ function mount() {+ buildNote({ id: "a", title: "A", "#color": "red" });+ buildNote({ id: "b", title: "B" });+ container = document.createElement("div");+ document.body.appendChild(container);++ const relations = [ fakeConnection("a", "b"), fakeConnection("b", "c") ];+ function Harness() {+ const canvasRef = useRef<HTMLDivElement>(null);+ const jsPlumbApiRef = useRef<jsPlumbInstance>({ getAllConnections: () => relations.map((r) => r.connection) } as unknown as jsPlumbInstance);+ useHoveredNoteRelations({ containerRef: canvasRef, jsPlumbApiRef });+ return (+ <div ref={canvasRef} className="canvas">+ {[ "a", "b", "c" ].map((noteId) => (+ <div id={noteIdToId(noteId)} className="note-box"><span className="title" /></div>+ ))}+ </div>+ );+ }+ act(() => render(<Harness />, container as HTMLElement));++ const canvas = container.querySelector(".canvas");+ if (!canvas) throw new Error("canvas not rendered");+ for (const { line, label } of relations) canvas.append(line, label);+ return { canvas, relations };+ }++ function fakeConnection(sourceNoteId: string, targetNoteId: string) {+ const line = document.createElement("div");+ const label = document.createElement("div");+ const connection = {+ sourceId: noteIdToId(sourceNoteId),+ targetId: noteIdToId(targetNoteId),+ canvas: line,+ getOverlay: (id: string) => (id === "label" ? { getElement: () => label } : undefined)+ } as unknown as Connection;+ return { connection, line, label };+ }++ function hover(element: Element | null | undefined) {+ act(() => { element?.dispatchEvent(new MouseEvent("mouseover", { bubbles: true })); });+ }++ it("lights the relations of the hovered box in its color and clears them when the pointer leaves", () => {+ const { canvas, relations: [ ab, bc ] } = mount();++ hover(canvas.querySelector(`#${noteIdToId("a")} .title`));+ expect(canvas.classList.contains("relation-map-note-hovered")).toBe(true);+ expect([ ab.line, ab.label ].map((e) => e.classList.contains("relation-map-lit"))).toEqual([ true, true ]);+ expect(ab.line.style.getPropertyValue("--relation-map-lit-color")).toBe("red");+ expect(bc.line.classList.contains("relation-map-lit")).toBe(false);++ hover(canvas.querySelector(`#${noteIdToId("b")}`));+ expect([ ab.line, bc.line ].map((e) => e.classList.contains("relation-map-lit"))).toEqual([ true, true ]);+ expect(ab.line.style.getPropertyValue("--relation-map-lit-color")).toBe("");++ act(() => { canvas.dispatchEvent(new MouseEvent("mouseleave")); });+ expect(canvas.classList.contains("relation-map-note-hovered")).toBe(false);+ expect([ ab.line, bc.line ].map((e) => e.classList.contains("relation-map-lit"))).toEqual([ false, false ]);+ });+});diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsxindex 1677f61d58..eb457c6a57 100644--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.tsx@@ -2,7 +2,7 @@ import "./RelationMap.css";import { RelationMapPostResponse } from "@triliumnext/commons";import clsx from "clsx";-import { jsPlumbInstance, OnConnectionBindInfo } from "jsplumb";+import { jsPlumbInstance, OnConnectionBindInfo, Overlay } from "jsplumb";// The library's own types rather than the hand-written `PanZoom` in types.d.ts, which stops at the// handful of calls the map made when it was written and knows nothing of the rest — the ends of the// zoom range, or unsubscribing from a report.@@ -41,6 +41,8 @@ declare module "jsplumb" {interface Overlay {setLabel(label: string): void;+ /** The element of a label overlay. */+ getElement(): HTMLElement;}interface ConnectParams {@@ -156,6 +158,7 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent});useRevealSelectedBox({ wrapperRef, containerRef, panZoom, noteId: selection?.noteId });+ useHoveredNoteRelations({ containerRef, jsPlumbApiRef: pbApiRef });useRelationData(note.noteId, data, mapApiRef, pbApiRef);return (@@ -175,7 +178,6 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponentEndpoint: ["Dot", { radius: 2 }],Connector: "StateMachine",ConnectionOverlays: uniDirectionalOverlays,- HoverPaintStyle: { stroke: "#777", strokeWidth: 1 },}}onInstanceCreated={setupOverlays}onConnection={connectionCallback}@@ -559,6 +561,74 @@ export function useRevealSelectedBox({ wrapperRef, containerRef, panZoom, noteId}, [ wrapperRef, containerRef, panZoom, noteId ]);}+/**+ * Highlights the relations of the hovered box and fades the other relations, as the note map does.+ * The relations take the note's `color` label, or `--relation-map-highlight-color` without one.+ */+export function useHoveredNoteRelations({ containerRef, jsPlumbApiRef }: {+ containerRef: RefObject<HTMLDivElement | null>;+ jsPlumbApiRef: RefObject<jsPlumbInstance | null>;+}) {+ useEffect(() => {+ const container = containerRef.current;+ if (!container) return;++ let hoveredBox: Element | null = null;+ let litElements: HTMLElement[] = [];++ const clear = () => {+ container.classList.remove("relation-map-note-hovered");+ for (const element of litElements) {+ element.classList.remove("relation-map-lit");+ element.style.removeProperty("--relation-map-lit-color");+ }+ litElements = [];+ };++ const onMouseOver = (e: MouseEvent) => {+ const box = e.target instanceof Element+ ? e.target.closest(".note-box:not(.relation-map-ghost-note)")+ : null;+ if (box === hoveredBox) return;++ clear();+ hoveredBox = box;+ const connections = jsPlumbApiRef.current?.getAllConnections();+ if (!box || !connections) return;++ const color = froca.getNoteFromCache(idToNoteId(box.id))?.getLabelValue("color");+ for (const connection of connections) {+ if (connection.sourceId !== box.id && connection.targetId !== box.id) continue;++ const labels = LABEL_OVERLAY_IDS+ .map((id) => connection.getOverlay(id) as Overlay | undefined)+ .filter((overlay) => overlay !== undefined)+ .map((overlay) => overlay.getElement());+ for (const element of [ connection.canvas, ...labels ]) {+ element.classList.add("relation-map-lit");+ if (color) element.style.setProperty("--relation-map-lit-color", color);+ litElements.push(element);+ }+ }+ container.classList.add("relation-map-note-hovered");+ };+ const onMouseLeave = () => {+ hoveredBox = null;+ clear();+ };++ container.addEventListener("mouseover", onMouseOver);+ container.addEventListener("mouseleave", onMouseLeave);+ return () => {+ container.removeEventListener("mouseover", onMouseOver);+ container.removeEventListener("mouseleave", onMouseLeave);+ clear();+ };+ }, [ containerRef, jsPlumbApiRef ]);+}++const LABEL_OVERLAY_IDS = [ "label", "label-source", "label-target" ];+/** Offset of the pointer from the top-left corner of a box being placed, near the box's top center. */const PLACEMENT_OFFSET = { x: 80, y: 15 };diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.htmlindex e51f8348d9..08ac57d72d 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Relation Map.html@@ -39,6 +39,8 @@</li><li>Each note is shown as a card with its icon and title, colored in the note'scolor the same way as the cards of a <a class="reference-link" href="#root/_help_CtBQqbwXDx1w">Kanban Board</a>.</li>+ <li>Hovering a note highlights its relationships, in the note's color if it+ has one, and fades the other relationships.</li><li>To view or edit a note, click it on the map. This opens the note panel(see below).<ul>diff --git a/docs/User Guide/User Guide/Note Types/Relation Map.md b/docs/User Guide/User Guide/Note Types/Relation Map.mdindex 4bb1ed05e5..f57c4fe289 100644--- a/docs/User Guide/User Guide/Note Types/Relation Map.md+++ b/docs/User Guide/User Guide/Note Types/Relation Map.md@@ -14,6 +14,7 @@ Relation map is a type of note which visualizes notes and their [relations](..* Drag over the same note to create a self-referencing relationship (represented as a loop).* Once dragged, a popover next to the relationship asks for its name. Type a new name and press <kbd>Enter</kbd>, or pick a relation name already in use from the suggestions. To cancel, press <kbd>Esc</kbd>, close the popover or click elsewhere on the map.* Each note is shown as a card with its icon and title, colored in the note's color the same way as the cards of a <a class="reference-link" href="../Collections/Kanban%20Board.md">Kanban Board</a>.+* Hovering a note highlights its relationships, in the note's color if it has one, and fades the other relationships.* To view or edit a note, click it on the map. This opens the note panel (see below).* To open the note in a new tab instead, <kbd>Ctrl</kbd>+click it or click it with the middle mouse button. <kbd>Shift</kbd>+click opens it in a new window. The right click menu offers the same options.* To edit the title of a note, change its color or delete it (either from the map, or delete it completely), right click the note. The color picker is not shown if the map is read-only.