Skip to content

Build your personal knowledge base with Trilium Notes

refactor(relation_map): draw relations without jsPlumb

Elian Doran208dac377ad2
diff --git a/README.md b/README.md
index 80b39d4443..28aeb4475e 100644
--- a/README.md
+++ b/README.md
@@ -246,7 +246,6 @@ Trilium would not be possible without the technologies behind it:
* [Leaflet](https://github.com/Leaflet/Leaflet) - for rendering geographical maps.
* [Tabulator](https://github.com/olifolkerd/tabulator) - for the interactive table used in collections.
* [FancyTree](https://github.com/mar10/fancytree) - feature-rich tree library without real competition.
-* [jsPlumb](https://github.com/jsplumb/jsplumb) - visual connectivity library. Used in [relation maps](https://docs.triliumnotes.org/user-guide/note-types/relation-map) and [link maps](https://docs.triliumnotes.org/user-guide/advanced-usage/note-map#link-map)
## 🤝 Support
diff --git a/apps/client/package.json b/apps/client/package.json
index a193282460..c5957e1b54 100644
--- a/apps/client/package.json
+++ b/apps/client/package.json
@@ -53,7 +53,6 @@
"i18next-http-backend": "4.0.2",
"jquery": "4.0.0",
"jquery.fancytree": "2.38.5",
- "jsplumb": "2.15.6",
"katex": "0.19.0",
"maplibre-gl": "6.12.0",
"mark.js": "8.11.1",
diff --git a/apps/client/src/widgets/type_widgets/relation_map/Connections.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/Connections.spec.tsx
new file mode 100644
index 0000000000..081a1cbc72
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/Connections.spec.tsx
@@ -0,0 +1,114 @@
+import { render } from "preact";
+import { useRef } from "preact/hooks";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { buildNote } from "../../../test/easy-froca";
+import type { ClientRelation } from "./api";
+import Connections, { type PendingRelation } from "./Connections";
+import type { Box } from "./geometry";
+import { useHoveredBox } from "./RelationMap";
+import { noteIdToId } from "./utils";
+
+describe("relation map Connections", () => {
+ let container: HTMLElement | undefined;
+ const onContextMenu = vi.fn();
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ const boxes = new Map<string, Box>([
+ [ "a", { x: 0, y: 0, width: 100, height: 40 } ],
+ [ "b", { x: 300, y: 0, width: 100, height: 40 } ],
+ [ "c", { x: 300, y: 300, width: 100, height: 40 } ]
+ ]);
+ const relations: ClientRelation[] = [
+ relation("ab", "a", "b", "uniDirectional", "author"),
+ relation("bc", "b", "c", "inverse", "parentOf"),
+ relation("ca", "c", "a", "biDirectional", "sibling")
+ ];
+
+ /** Renders boxes `a`, `b` and `c` with the relations above, highlighting those of the hovered box. */
+ function mount(pending: PendingRelation | null = null) {
+ buildNote({ id: "a", title: "A", "#color": "red" });
+ buildNote({ id: "b", title: "B" });
+ container = document.createElement("div");
+ document.body.appendChild(container);
+
+ function Harness() {
+ const canvasRef = useRef<HTMLDivElement>(null);
+ const hoveredNoteId = useHoveredBox(canvasRef);
+ return (
+ <div ref={canvasRef} className="canvas">
+ <Connections
+ relations={relations}
+ inverseRelations={{ parentOf: "childOf", sibling: "sibling" }}
+ boxes={boxes}
+ hoveredNoteId={hoveredNoteId}
+ hoveredRelationId={null}
+ pending={pending}
+ onHoverRelation={() => {}}
+ onContextMenu={onContextMenu}
+ />
+ {[ "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");
+ return canvas;
+ }
+
+ const connection = (id: string) => container?.querySelector<SVGGElement>(`[data-connection-id="${id}"]`);
+ const labels = () => [ ...container?.querySelectorAll<HTMLElement>(".connection-label") ?? [] ];
+
+ it("draws each relation with its arrowheads and labels, and opens its context menu", () => {
+ mount();
+
+ expect([ "ab", "bc", "ca" ].map((id) => connection(id)?.querySelectorAll(".relation-map-arrow").length))
+ .toEqual([ 1, 2, 2 ]);
+ expect(labels().map((label) => label.textContent)).toEqual([ "author", "parentOf", "childOf", "sibling" ]);
+
+ act(() => { labels()[0].dispatchEvent(new MouseEvent("contextmenu", { bubbles: true })); });
+ expect(onContextMenu.mock.calls.at(-1)?.[0]).toBe(relations[0]);
+ });
+
+ it("lights the relations of the hovered box in its color and fades the others", () => {
+ const canvas = mount();
+ const classesOf = (id: string) => [ ...connection(id)?.classList ?? [] ].filter((name) => name !== "relation-map-connection");
+ const hover = (element: Element | null | undefined) => act(() => {
+ element?.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
+ });
+
+ hover(canvas.querySelector(`#${noteIdToId("a")} .title`));
+ expect([ classesOf("ab"), classesOf("bc"), classesOf("ca") ]).toEqual([ [ "lit" ], [ "faded" ], [ "lit" ] ]);
+ expect(connection("ab")?.style.getPropertyValue("--relation-map-lit-color")).toBe("red");
+ expect(labels()[0].classList.contains("lit")).toBe(true);
+
+ hover(canvas.querySelector(`#${noteIdToId("b")}`));
+ expect(classesOf("ab")).toEqual([ "lit" ]);
+ expect(connection("ab")?.style.getPropertyValue("--relation-map-lit-color")).toBe("");
+
+ act(() => { canvas.dispatchEvent(new MouseEvent("mouseleave")); });
+ expect([ classesOf("ab"), classesOf("bc") ]).toEqual([ [], [] ]);
+ });
+
+ it("draws a relation being created toward the pointer", () => {
+ mount({ sourceNoteId: "a", pointer: { x: 250, y: 20 } });
+
+ expect(connection("pending")?.querySelector("path")?.getAttribute("d")).toBe("M 103 20 Q 150 20 250 20");
+ });
+});
+
+function relation(attributeId: string, sourceNoteId: string, targetNoteId: string, type: ClientRelation["type"], name: string): ClientRelation {
+ return { attributeId, sourceNoteId, targetNoteId, type, name, render: true };
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/Connections.tsx b/apps/client/src/widgets/type_widgets/relation_map/Connections.tsx
new file mode 100644
index 0000000000..73136b9c3b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/Connections.tsx
@@ -0,0 +1,140 @@
+import clsx from "clsx";
+import { useMemo } from "preact/hooks";
+
+import froca from "../../../services/froca";
+import type { ClientRelation } from "./api";
+import { type Box, type ConnectionLayout, type ConnectionShape, layoutConnections, layoutLine, type Point } from "./geometry";
+
+/** A relation being drawn from the endpoint of a box, toward the pointer or onto a target box. */
+export interface PendingRelation {
+ sourceNoteId: string;
+ /** The box under the pointer, or the box the relation was dropped on. */
+ targetNoteId?: string;
+ /** The pointer, in unzoomed map pixels. */
+ pointer: Point;
+}
+
+/** `data-connection-id` of the relation being drawn, which the relation name popover anchors to. */
+export const PENDING_CONNECTION_ID = "pending";
+
+/**
+ * Draws the relations between the boxes of a relation map: an SVG layer under the boxes for the
+ * lines and arrowheads, and HTML labels over the lines.
+ *
+ * While a box is hovered, its relations take the note's `color` label (or
+ * `--relation-map-highlight-color`) and the other relations fade, as on the note map.
+ */
+export default function Connections({ relations, inverseRelations, boxes, hoveredNoteId, hoveredRelationId, pending, onHoverRelation, onContextMenu }: {
+ /** The relations to draw. A relation that pairs with an inverse is passed once, with its `type`. */
+ relations: ClientRelation[];
+ inverseRelations: Record<string, string> | undefined;
+ /** The boxes on the map, by note ID. */
+ boxes: Map<string, Box>;
+ hoveredNoteId: string | null;
+ hoveredRelationId: string | null;
+ pending: PendingRelation | null;
+ onHoverRelation(attributeId: string | null): void;
+ onContextMenu(relation: ClientRelation, e: MouseEvent): void;
+}) {
+ const layouts = useMemo(
+ () => layoutConnections(relations.map(toShape), boxes),
+ [ relations, boxes ]);
+ const pendingLayout = useMemo(() => pending && layoutPending(pending, boxes), [ pending, boxes ]);
+ const litColor = hoveredNoteId ? froca.getNoteFromCache(hoveredNoteId)?.getLabelValue("color") : null;
+
+ const drawn = relations
+ .map((relation) => ({ relation, layout: layouts.get(relation.attributeId) }))
+ .filter((entry): entry is { relation: ClientRelation; layout: ConnectionLayout } => !!entry.layout);
+ const stateOf = (relation: ClientRelation) => {
+ const isLit = !!hoveredNoteId && (relation.sourceNoteId === hoveredNoteId || relation.targetNoteId === hoveredNoteId);
+ return {
+ className: clsx(
+ isLit && "lit",
+ hoveredNoteId && !isLit && "faded",
+ hoveredRelationId === relation.attributeId && "hovered"
+ ),
+ style: isLit && litColor ? { "--relation-map-lit-color": litColor } : undefined
+ };
+ };
+ const hoverProps = (relation: ClientRelation) => ({
+ onMouseEnter: () => onHoverRelation(relation.attributeId),
+ onMouseLeave: () => onHoverRelation(null),
+ onContextMenu: (e: MouseEvent) => onContextMenu(relation, e)
+ });
+
+ return (
+ <>
+ <svg className="relation-map-connections">
+ {drawn.map(({ relation, layout }) => {
+ const { className, style } = stateOf(relation);
+ return (
+ <g
+ key={relation.attributeId}
+ className={clsx("relation-map-connection", className)}
+ style={style}
+ data-connection-id={relation.attributeId}
+ {...hoverProps(relation)}
+ >
+ <path className="relation-map-connection-hit" d={layout.path} />
+ <ConnectionLine layout={layout} />
+ </g>
+ );
+ })}
+ {pendingLayout && (
+ <g className="relation-map-connection pending" data-connection-id={PENDING_CONNECTION_ID}>
+ <ConnectionLine layout={pendingLayout} />
+ </g>
+ )}
+ </svg>
+
+ {drawn.flatMap(({ relation, layout }) => {
+ const { className, style } = stateOf(relation);
+ return labelsOf(relation, inverseRelations).map((text, index) => text ? (
+ <div
+ key={`${relation.attributeId}-${index}`}
+ className={clsx("connection-label", className)}
+ style={{ ...style, left: layout.labels[index].x, top: layout.labels[index].y }}
+ {...hoverProps(relation)}
+ >
+ {text}
+ </div>
+ ) : null);
+ })}
+ </>
+ );
+}
+
+function ConnectionLine({ layout }: { layout: ConnectionLayout }) {
+ return (
+ <>
+ <path className="relation-map-connection-line" d={layout.path} />
+ {layout.arrows.map((points) => <polygon className="relation-map-arrow" points={points} />)}
+ </>
+ );
+}
+
+function toShape(relation: ClientRelation): ConnectionShape {
+ return {
+ id: relation.attributeId,
+ sourceId: relation.sourceNoteId,
+ targetId: relation.targetNoteId,
+ arrowAtSource: relation.type !== "uniDirectional",
+ labelAt: relation.type === "inverse" ? [ 0.2, 0.8 ] : [ 0.5 ]
+ };
+}
+
+/** The relation's name, and for an `inverse` relation the name of its inverse as well. */
+function labelsOf(relation: ClientRelation, inverseRelations: Record<string, string> | undefined) {
+ return relation.type === "inverse"
+ ? [ relation.name, inverseRelations?.[relation.name] ?? "" ]
+ : [ relation.name ];
+}
+
+function layoutPending({ sourceNoteId, targetNoteId, pointer }: PendingRelation, boxes: Map<string, Box>) {
+ const source = boxes.get(sourceNoteId);
+ if (!source) return null;
+ if (!targetNoteId) return layoutLine(source, pointer);
+
+ const shape = { id: PENDING_CONNECTION_ID, sourceId: sourceNoteId, targetId: targetNoteId, arrowAtSource: false, labelAt: [] };
+ return layoutConnections([ shape ], boxes).get(PENDING_CONNECTION_ID) ?? null;
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/NoteBox.css b/apps/client/src/widgets/type_widgets/relation_map/NoteBox.css
index 75da44f1b1..4dc2d9568d 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/NoteBox.css
+++ b/apps/client/src/widgets/type_widgets/relation_map/NoteBox.css
@@ -17,6 +17,7 @@
line-height: 1.2;
cursor: pointer;
user-select: none;
+ touch-action: none;
> .note-box-icon {
flex-shrink: 0;
@@ -56,7 +57,7 @@
var(--board-item-hover-shadow);
}
- &.dragHover {
+ &.drop-target {
outline: 2px solid var(--board-selected-ring-color);
}
@@ -71,8 +72,7 @@
}
}
-/* jsPlumb adds these classes to both boxes of the hovered relation. */
-.note-detail-relation-map .note-box:is(.jtk-source-hover, .jtk-target-hover) {
+.note-detail-relation-map .note-box.highlighted {
background-color: var(--note-card-hover-background);
box-shadow: var(--board-item-hover-shadow);
}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/NoteBox.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/NoteBox.spec.tsx
index 7069c1ade3..a67915066c 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/NoteBox.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/NoteBox.spec.tsx
@@ -1,7 +1,7 @@
import { render } from "preact";
import { useRef } from "preact/hooks";
import { act } from "preact/test-utils";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import Component from "../../../components/component";
import FAttribute from "../../../entities/fattribute";
@@ -34,9 +34,11 @@ describe("relation map NoteBox", () => {
}
});
+ const onResize = vi.fn();
+
function Harness({ selected }: { selected: boolean }) {
const mapApiRef = useRef<RelationMapApi>(null);
- return <NoteBox noteId="boxnote" x={10} y={20} mapApiRef={mapApiRef} selected={selected} isReadOnly={false} />;
+ return <NoteBox noteId="boxnote" x={10} y={20} mapApiRef={mapApiRef} selected={selected} isReadOnly={false} onPointerDown={() => {}} onResize={onResize} />;
}
async function mount(selected = false) {
@@ -59,19 +61,19 @@ describe("relation map NoteBox", () => {
const box = () => container?.querySelector<HTMLElement>(".note-box") ?? null;
- it("shows the note's icon and title as a card, not as a link", async () => {
+ it("shows the note's icon and title as a card, not as a link, and reports its size", async () => {
await mount();
expect(box()?.classList.contains("tn-note-card")).toBe(true);
expect(box()?.querySelector(".note-box-icon")?.classList.contains("bx-bug")).toBe(true);
expect(box()?.querySelector(".note-box-title")?.textContent).toBe("Specification");
expect(box()?.querySelector("a")).toBeNull();
+ expect(onResize).toHaveBeenCalledWith("boxnote", { width: 0, height: 0 });
});
- it("follows the note's colour and the selection without dropping the classes jsPlumb added", async () => {
+ it("follows the note's colour and the selection", async () => {
await mount();
const coloured = cssClassManager.createClassForColor("#ff0000");
- box()?.classList.add("jtk-draggable");
expect(box()?.className).not.toContain(coloured);
await addColor("#ff0000");
@@ -80,7 +82,6 @@ describe("relation map NoteBox", () => {
expect(box()?.className).toContain(coloured);
expect(box()?.classList.contains("with-hue")).toBe(true);
expect(box()?.classList.contains("selected")).toBe(true);
- expect(box()?.classList.contains("jtk-draggable")).toBe(true);
await mount(false);
expect(box()?.classList.contains("selected")).toBe(false);
diff --git a/apps/client/src/widgets/type_widgets/relation_map/NoteBox.tsx b/apps/client/src/widgets/type_widgets/relation_map/NoteBox.tsx
index c0f0ac0f63..6c2b365d57 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/NoteBox.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/NoteBox.tsx
@@ -3,7 +3,7 @@ import "./NoteBox.css";
import clsx from "clsx";
import { RefObject } from "preact";
-import { useEffect, useMemo, useState } from "preact/hooks";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import FNote from "../../../entities/fnote";
import froca from "../../../services/froca";
@@ -11,38 +11,30 @@ import { t } from "../../../services/i18n";
import { useNoteColorClass, useNoteIcon, useNoteProperty } from "../../react/hooks";
import RelationMapApi, { MapDataNoteEntry } from "./api";
import { buildNoteContextMenuHandler } from "./context_menu";
-import { JsPlumbItem } from "./jsplumb";
-import { idToNoteId, noteIdToId } from "./utils";
-
-const NOTE_BOX_SOURCE_CONFIG = {
- filter: ".endpoint",
- anchor: "Continuous",
- connectorStyle: { strokeWidth: 1 },
- connectionType: "basic",
- extract: {
- action: "the-action"
- }
-};
-
-const NOTE_BOX_TARGET_CONFIG = {
- dropOptions: { hoverClass: "dragHover" },
- anchor: "Continuous",
- allowLoopback: true
-};
+import { noteIdToId } from "./utils";
interface NoteBoxProps extends MapDataNoteEntry {
mapApiRef: RefObject<RelationMapApi | null>;
/** The note is open in the note pane. */
selected?: boolean;
+ /** A relation of the note is hovered. */
+ highlighted?: boolean;
+ /** A relation being drawn would end on this box. */
+ dropTarget?: boolean;
/** The map cannot be edited, so the context menu offers no color picker. */
isReadOnly: boolean;
+ /** Starts dragging the box, or drawing a relation from its `.endpoint`. */
+ onPointerDown(e: PointerEvent): void;
+ /** Reports the box's size, which the relations need to end on its border. */
+ onResize(noteId: string, size: { width: number; height: number }): void;
}
-export function NoteBox({ noteId, x, y, mapApiRef, selected, isReadOnly }: NoteBoxProps) {
+export function NoteBox({ noteId, x, y, mapApiRef, selected, highlighted, dropTarget, isReadOnly, onPointerDown, onResize }: NoteBoxProps) {
const [ note, setNote ] = useState<FNote | null>();
const title = useNoteProperty(note, "title");
const icon = useNoteIcon(note);
const colorClass = useNoteColorClass(note);
+ const boxRef = useRef<HTMLDivElement>(null);
useEffect(() => {
froca.getNote(noteId).then(setNote);
}, [ noteId ]);
@@ -51,30 +43,37 @@ export function NoteBox({ noteId, x, y, mapApiRef, selected, isReadOnly }: NoteB
return buildNoteContextMenuHandler(note, mapApiRef, isReadOnly);
}, [ note, isReadOnly ]);
+ useLayoutEffect(() => {
+ const box = boxRef.current;
+ if (!box) return;
+
+ const report = () => onResize(noteId, { width: box.offsetWidth, height: box.offsetHeight });
+ report();
+ const observer = new ResizeObserver(report);
+ observer.observe(box);
+ return () => observer.disconnect();
+ }, [ note, noteId, onResize ]);
+
return note && (
- <JsPlumbItem
+ <div
+ ref={boxRef}
id={noteIdToId(noteId)}
- className="note-box tn-note-card"
- dynamicClassName={clsx(colorClass, note.getCssClass(), selected && "selected")}
+ className={clsx(
+ "note-box tn-note-card", colorClass, note.getCssClass(),
+ selected && "selected", highlighted && "highlighted", dropTarget && "drop-target"
+ )}
+ style={{ left: `${x}px`, top: `${y}px` }}
onContextMenu={contextMenuHandler}
- x={x} y={y}
- draggable={{
- start() {},
- drag() {},
- stop(params) {
- const noteId = idToNoteId(params.el.id);
- const [ x, y ] = params.pos;
- mapApiRef.current?.moveNote(noteId, x, y);
- },
- }}
- sourceConfig={NOTE_BOX_SOURCE_CONFIG}
- targetConfig={NOTE_BOX_TARGET_CONFIG}
+ onPointerDown={onPointerDown}
+ // Keeps `panzoom` from panning the map while the box is dragged.
+ onMouseDown={stopPropagation}
+ onTouchStart={stopPropagation}
>
<span className={clsx("note-box-icon", icon)} />
<span className="note-box-title">{title}</span>
<div className="endpoint" title={t("relation_map.start_dragging_relations")} />
- </JsPlumbItem>
- )
+ </div>
+ );
}
/**
@@ -89,3 +88,7 @@ export function GhostNoteBox({ elementRef }: { elementRef: RefObject<HTMLDivElem
</div>
);
}
+
+function stopPropagation(e: Event) {
+ e.stopPropagation();
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.css b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.css
index 1abd26b9d1..520ee4e423 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.css
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.css
@@ -17,11 +17,53 @@
outline: none; /* remove dotted outline on click */
}
-.note-detail-relation-map .connection-label.jtk-hover {
- background-color: var(--more-accented-background-color);
+.note-detail-relation-map .relation-map-connections {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 1;
+ width: 1px;
+ height: 1px;
+ overflow: visible;
+ pointer-events: none;
+}
+
+.note-detail-relation-map .relation-map-connection {
+ transition: opacity 0.2s ease;
+
+ .relation-map-connection-hit {
+ fill: none;
+ stroke: transparent;
+ stroke-width: 12px;
+ pointer-events: stroke;
+ cursor: pointer;
+ }
+
+ .relation-map-connection-line {
+ fill: none;
+ stroke: var(--relation-map-line-color);
+ stroke-width: 1px;
+ transition: stroke 0.2s ease;
+ }
+
+ .relation-map-arrow {
+ fill: var(--relation-map-line-color);
+ stroke: var(--relation-map-line-color);
+ stroke-width: 1.2px;
+ stroke-linejoin: round;
+ transition: stroke 0.2s ease, fill 0.2s ease;
+ }
+
+ &:is(.hovered, .lit, .pending) {
+ --relation-map-line-color: var(--relation-map-lit-color, var(--relation-map-highlight-color));
+ }
}
.note-detail-relation-map .connection-label {
+ position: absolute;
+ z-index: 2;
+ translate: -50% -50%;
+ white-space: nowrap;
background-color: var(--accented-background-color);
color: var(--main-text-color);
opacity: 0.8;
@@ -29,11 +71,15 @@
border-radius: 0.5em;
border: 1px solid #666;
cursor: pointer;
+ transition: opacity 0.2s ease;
+
+ &.hovered {
+ background-color: var(--more-accented-background-color);
+ }
}
-.note-detail-relation-map path,
-.note-detail-relation-map .jtk-endpoint {
- cursor: pointer;
+.note-detail-relation-map :is(.relation-map-connection, .connection-label).faded {
+ opacity: 0.15;
}
.note-detail-relation-map .ui-contextmenu {
@@ -43,27 +89,3 @@
.relation-map-wrapper.placing-note {
cursor: crosshair;
}
-
-.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.tsx
index ea2d8e29d3..ef9e89e954 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,12 +1,10 @@
-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 { buildNote } from "../../../test/easy-froca";
-import { useCanvasClicks, useHoveredNoteRelations, useRevealSelectedBox } from "./RelationMap";
+import { useCanvasClicks, useRevealSelectedBox } from "./RelationMap";
import { noteIdToId } from "./utils";
describe("relation map canvas clicks", () => {
@@ -199,77 +197,3 @@ 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.tsx
index eb457c6a57..9dab6d4f1f 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,6 @@ import "./RelationMap.css";
import { RelationMapPostResponse } from "@triliumnext/commons";
import clsx from "clsx";
-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.
@@ -21,34 +20,16 @@ import toast from "../../../services/toast";
import { isMobile } from "../../../services/utils";
import { useEditorSpacedUpdate, useNoteLabelBoolean, useTriliumEvent, useTriliumEvents } from "../../react/hooks";
import { TypeWidgetProps } from "../type_widget";
-import RelationMapApi, { ClientRelation, MapData, MapDataNoteEntry, RelationType } from "./api";
-import { buildRelationContextMenuHandler } from "./context_menu";
-import { JsPlumb } from "./jsplumb";
+import RelationMapApi, { ClientRelation, MapData, MapDataNoteEntry } from "./api";
+import Connections from "./Connections";
+import { showRelationContextMenu } from "./context_menu";
+import { useBoxDragging, useRelationDrawing } from "./drags";
+import type { Box } from "./geometry";
import MapToolbar, { EditToolbar } from "./MapToolbar";
import { GhostNoteBox, NoteBox } from "./NoteBox";
import NotePane, { type NotePaneHandle, type PaneSelection } from "./NotePane";
-import setupOverlays, { uniDirectionalOverlays } from "./overlays";
-import RelationNamePopover, { type AskRelationName, useRelationNamePrompt } from "./RelationNamePopover";
-import { getMousePosition, getZoom, idToNoteId, noteIdToId, revealOffset } from "./utils";
-
-declare module "jsplumb" {
-
- interface Connection {
- canvas: HTMLCanvasElement;
- getType(): string;
- bind(event: string, callback: (obj: unknown, event: MouseEvent) => void): void;
- }
-
- interface Overlay {
- setLabel(label: string): void;
- /** The element of a label overlay. */
- getElement(): HTMLElement;
- }
-
- interface ConnectParams {
- type: RelationType;
- }
-}
+import RelationNamePopover, { useRelationNamePrompt } from "./RelationNamePopover";
+import { CLICK_TOLERANCE, getMousePosition, getZoom, idToNoteId, noteIdToId, revealOffset } from "./utils";
export default function RelationMap({ note, noteContext, ntxId, parentComponent }: TypeWidgetProps) {
const [ data, setData ] = useState<MapData>();
@@ -57,7 +38,6 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
const wrapperRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const mapApiRef = useRef<RelationMapApi>(null);
- const pbApiRef = useRef<jsPlumbInstance>(null);
const spacedUpdate = useEditorSpacedUpdate({
note,
@@ -108,10 +88,8 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
});
const onTransform = useCallback((pzInstance: PanZoom) => {
- if (!containerRef.current || !mapApiRef.current || !pbApiRef.current || !data) return;
- const zoom = getZoom(containerRef.current);
+ if (!mapApiRef.current || !data) return;
mapApiRef.current.setTransform(pzInstance.getTransform());
- pbApiRef.current.setZoom(zoom);
}, [ data ]);
const [ selection, setSelection ] = useState<PaneSelection | null>(null);
@@ -137,7 +115,9 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
const dragProps = useNoteDragging({ containerRef, mapApiRef });
const relationNamePrompt = useRelationNamePrompt();
- const connectionCallback = useRelationCreation({ mapApiRef, jsPlumbApiRef: pbApiRef, askRelationName: relationNamePrompt.ask });
+ const { dragged, startDrag } = useBoxDragging({ containerRef, mapApiRef });
+ const { pending, startDrawing } = useRelationDrawing({ containerRef, mapApiRef, askRelationName: relationNamePrompt.ask });
+ const { boxes, onBoxResize } = useBoxes(data?.notes, dragged);
const panZoom = usePanZoom({
ntxId,
@@ -158,8 +138,16 @@ 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);
+ const hoveredNoteId = useHoveredBox(containerRef);
+ const [ hoveredRelationId, setHoveredRelationId ] = useState<string | null>(null);
+ const { relations, inverseRelations } = useRelationData(note.noteId, data, mapApiRef);
+ const drawnRelations = useMemo(() => relations?.filter((relation) => relation.render) ?? [], [ relations ]);
+ const hoveredRelation = drawnRelations.find((relation) => relation.attributeId === hoveredRelationId);
+
+ const onRelationContextMenu = useCallback((relation: ClientRelation, e: MouseEvent) => {
+ const anchor = () => containerRef.current?.querySelector(`[data-connection-id="${CSS.escape(relation.attributeId)}"]`);
+ showRelationContextMenu(e, relation, mapApiRef, (defaultValue) => relationNamePrompt.ask(anchor, defaultValue));
+ }, [ relationNamePrompt.ask ]);
return (
<div
@@ -170,23 +158,41 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
{...clickProps}
{...dragProps}
>
- <JsPlumb
- apiRef={pbApiRef}
- containerRef={containerRef}
- className="relation-map-container"
- props={{
- Endpoint: ["Dot", { radius: 2 }],
- Connector: "StateMachine",
- ConnectionOverlays: uniDirectionalOverlays,
- }}
- onInstanceCreated={setupOverlays}
- onConnection={connectionCallback}
- >
- {data?.notes.map(note => (
- <NoteBox {...note} mapApiRef={mapApiRef} selected={note.noteId === selection?.noteId} isReadOnly={isReadOnly} />
- ))}
+ <div ref={containerRef} className="relation-map-container">
+ <Connections
+ relations={drawnRelations}
+ inverseRelations={inverseRelations}
+ boxes={boxes}
+ hoveredNoteId={hoveredNoteId}
+ hoveredRelationId={hoveredRelationId}
+ pending={pending}
+ onHoverRelation={setHoveredRelationId}
+ onContextMenu={onRelationContextMenu}
+ />
+ {data?.notes.map((entry) => {
+ const position = dragged?.noteId === entry.noteId ? dragged : entry;
+ return (
+ <NoteBox
+ key={entry.noteId}
+ {...position}
+ mapApiRef={mapApiRef}
+ selected={entry.noteId === selection?.noteId}
+ highlighted={entry.noteId === hoveredRelation?.sourceNoteId || entry.noteId === hoveredRelation?.targetNoteId}
+ dropTarget={entry.noteId === pending?.targetNoteId}
+ isReadOnly={isReadOnly}
+ onPointerDown={(e) => {
+ if (e.target instanceof Element && e.target.closest(".endpoint")) {
+ startDrawing(e, entry.noteId);
+ } else {
+ startDrag(e, position);
+ }
+ }}
+ onResize={onBoxResize}
+ />
+ );
+ })}
{placement.placing && <GhostNoteBox elementRef={placement.ghostRef} />}
- </JsPlumb>
+ </div>
{/* Both groups stand on the map whatever layout the note is read in: what is done to a
canvas belongs on the canvas, and the bar of buttons above the note is not where the
@@ -214,7 +220,7 @@ export default function RelationMap({ note, noteContext, ntxId, parentComponent
{relationNamePrompt.request && (
<RelationNamePopover
key={relationNamePrompt.request.id}
- connection={relationNamePrompt.request.connection}
+ anchor={relationNamePrompt.request.anchor}
defaultValue={relationNamePrompt.request.defaultValue}
onAnswer={relationNamePrompt.answer}
/>
@@ -280,89 +286,89 @@ function usePanZoom({ ntxId, containerRef, options, transformData, onTransform }
return panZoom;
}
-async function useRelationData(noteId: string, mapData: MapData | undefined, mapApiRef: RefObject<RelationMapApi | null>, jsPlumbRef: RefObject<jsPlumbInstance | null>) {
- const noteIds = mapData?.notes.map((note) => note.noteId);
+function useRelationData(noteId: string, mapData: MapData | undefined, mapApiRef: RefObject<RelationMapApi | null>) {
const [ relations, setRelations ] = useState<ClientRelation[]>();
const [ inverseRelations, setInverseRelations ] = useState<RelationMapPostResponse["inverseRelations"]>();
- async function refresh() {
+ useEffect(() => {
const api = mapApiRef.current;
+ const noteIds = mapData?.notes.map((note) => note.noteId);
if (!noteIds || !api) return;
- const data = await server.post<RelationMapPostResponse>("relation-map", { noteIds, relationMapNoteId: noteId });
- const relations: ClientRelation[] = [];
-
- for (const _relation of data.relations) {
- const relation = _relation as ClientRelation; // we inject a few variables.
- const match = relations.find(
- (rel) =>
- rel.name === data.inverseRelations[relation.name] &&
- ((rel.sourceNoteId === relation.sourceNoteId && rel.targetNoteId === relation.targetNoteId) ||
- (rel.sourceNoteId === relation.targetNoteId && rel.targetNoteId === relation.sourceNoteId))
- );
-
- if (match) {
- match.type = relation.type = relation.name === data.inverseRelations[relation.name] ? "biDirectional" : "inverse";
- relation.render = false; // don't render second relation
- } else {
- relation.type = "uniDirectional";
- relation.render = true;
- }
+ let isCurrent = true;
+ server.post<RelationMapPostResponse>("relation-map", { noteIds, relationMapNoteId: noteId }).then((data) => {
+ if (!isCurrent) return;
- relations.push(relation);
+ const relations = pairInverseRelations(data.relations, data.inverseRelations);
+ setRelations(relations);
setInverseRelations(data.inverseRelations);
- }
-
- setRelations(relations);
- api.loadRelations(relations);
- api.cleanupOtherNotes(Object.keys(data.noteTitles));
- }
-
- useEffect(() => {
- refresh();
- }, [ noteId, mapData, jsPlumbInstance ]);
-
- // Refresh on the canvas.
- useEffect(() => {
- const jsPlumbInstance = jsPlumbRef.current;
- if (!jsPlumbInstance) return;
-
- jsPlumbInstance.batch(async () => {
- if (!mapData || !relations) {
- return;
- }
-
- jsPlumbInstance.deleteEveryEndpoint();
+ api.loadRelations(relations);
+ api.cleanupOtherNotes(Object.keys(data.noteTitles));
+ });
+ return () => {
+ isCurrent = false;
+ };
+ }, [ noteId, mapData, mapApiRef ]);
- for (const relation of relations) {
- if (!relation.render) {
- continue;
- }
+ return { relations, inverseRelations };
+}
- const connection = jsPlumbInstance.connect({
- source: noteIdToId(relation.sourceNoteId),
- target: noteIdToId(relation.targetNoteId),
- type: relation.type
- });
- if (!connection) return;
+/**
+ * Gives each relation its `type`. A relation whose inverse also runs between the same two notes is
+ * drawn once, as `biDirectional` when it is its own inverse and as `inverse` otherwise; the second
+ * of the pair gets `render: false`.
+ */
+function pairInverseRelations(serverRelations: RelationMapPostResponse["relations"], inverseRelations: Record<string, string>) {
+ const relations: ClientRelation[] = [];
+
+ for (const serverRelation of serverRelations) {
+ const relation: ClientRelation = { ...serverRelation, type: "uniDirectional", render: true };
+ const match = relations.find(
+ (rel) =>
+ rel.name === inverseRelations[relation.name] &&
+ ((rel.sourceNoteId === relation.sourceNoteId && rel.targetNoteId === relation.targetNoteId) ||
+ (rel.sourceNoteId === relation.targetNoteId && rel.targetNoteId === relation.sourceNoteId))
+ );
+
+ if (match) {
+ match.type = relation.type = relation.name === inverseRelations[relation.name] ? "biDirectional" : "inverse";
+ relation.render = false;
+ }
- // Stash the attributeId on the connection so api.ts can map a clicked connection
- // back to its relation (see the `rel.attributeId === connection.id` lookups there),
- // and so it can be exposed as data-connection-id below.
- //@ts-expect-error jsPlumb's Connection type has no writable `id` property.
- connection.id = relation.attributeId;
+ relations.push(relation);
+ }
- if (relation.type === "inverse") {
- connection.getOverlay("label-source").setLabel(relation.name);
- connection.getOverlay("label-target").setLabel(inverseRelations?.[relation.name] ?? "");
- } else {
- connection.getOverlay("label").setLabel(relation.name);
- }
+ return relations;
+}
- connection.canvas.setAttribute("data-connection-id", connection.id);
- }
+/**
+ * The boxes on the map by note ID, for drawing the relations: each note's position, with `dragged`
+ * overriding the saved one, and the size its `NoteBox` reports through `onBoxResize`. A box that
+ * has not reported its size yet is left out.
+ */
+function useBoxes(notes: MapDataNoteEntry[] | undefined, dragged: MapDataNoteEntry | null) {
+ const [ sizes, setSizes ] = useState<Record<string, { width: number; height: number }>>({});
+
+ const onBoxResize = useCallback((noteId: string, size: { width: number; height: number }) => {
+ setSizes((sizes) => {
+ const current = sizes[noteId];
+ if (current?.width === size.width && current.height === size.height) return sizes;
+ return { ...sizes, [noteId]: size };
});
- }, [ relations, mapData ]);
+ }, []);
+
+ const boxes = useMemo(() => {
+ const boxes = new Map<string, Box>();
+ for (const entry of notes ?? []) {
+ const size = sizes[entry.noteId];
+ if (!size) continue;
+ const { x, y } = dragged?.noteId === entry.noteId ? dragged : entry;
+ boxes.set(entry.noteId, { x, y, ...size });
+ }
+ return boxes;
+ }, [ notes, sizes, dragged ]);
+
+ return { boxes, onBoxResize };
}
/**
@@ -561,80 +567,36 @@ 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>;
-}) {
+/** The note of the box under the pointer, or `null` while the pointer is over no box. */
+export function useHoveredBox(containerRef: RefObject<HTMLDivElement | null>) {
+ const [ hoveredNoteId, setHoveredNoteId ] = useState<string | null>(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();
+ setHoveredNoteId(box ? idToNoteId(box.id) : null);
};
+ const onMouseLeave = () => setHoveredNoteId(null);
container.addEventListener("mouseover", onMouseOver);
container.addEventListener("mouseleave", onMouseLeave);
return () => {
container.removeEventListener("mouseover", onMouseOver);
container.removeEventListener("mouseleave", onMouseLeave);
- clear();
};
- }, [ containerRef, jsPlumbApiRef ]);
-}
+ }, [ containerRef ]);
-const LABEL_OVERLAY_IDS = [ "label", "label-source", "label-target" ];
+ return hoveredNoteId;
+}
/** 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 };
-/** How far, in pixels, the pointer can move between press and release for the click to count. */
-const CLICK_TOLERANCE = 4;
-
/**
* Opens the note of a box the way a link to it opens: Ctrl or the middle button in a new tab, Shift
* in a new window (see `goToLinkExt`).
@@ -695,39 +657,3 @@ function useNoteDragging({ containerRef, mapApiRef }: {
return dragProps;
}
-
-function useRelationCreation({ mapApiRef, jsPlumbApiRef, askRelationName }: {
- mapApiRef: RefObject<RelationMapApi | null>,
- jsPlumbApiRef: RefObject<jsPlumbInstance | null>,
- askRelationName: AskRelationName
-}) {
- const connectionCallback = useCallback(async (info: OnConnectionBindInfo, originalEvent: Event) => {
- const connection = info.connection;
-
- // Called whenever a connection is created, either initially or manually when added by the user.
- const handler = buildRelationContextMenuHandler(connection, mapApiRef, askRelationName);
- connection.bind("contextmenu", handler);
-
- // if there's no event, then this has been triggered programmatically
- if (!originalEvent || !mapApiRef.current) return;
-
- const name = await askRelationName(connection);
-
- // Delete the newly created connection if the dialog was dismissed.
- if (!name || !name.trim()) {
- jsPlumbApiRef.current?.deleteConnection(connection);
- return;
- }
-
- const targetNoteId = idToNoteId(connection.target.id);
- const sourceNoteId = idToNoteId(connection.source.id);
- const result = await mapApiRef.current.connect(name, sourceNoteId, targetNoteId);
- if (!result) {
- toast.showError(t("relation_map.connection_exists", { name }));
- jsPlumbApiRef.current?.deleteConnection(connection);
- }
- }, [ askRelationName ]);
-
- return connectionCallback;
-}
-
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.spec.tsx
index 4c54e869cc..298a801144 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.spec.tsx
@@ -1,4 +1,3 @@
-import type { Connection } from "jsplumb";
import { act } from "preact/test-utils";
import { describe, expect, it, vi } from "vitest";
@@ -86,8 +85,8 @@ describe("useRelationNamePrompt", () => {
await act(async () => { renderInto(<Probe />); });
const ask = prompt?.ask as AskRelationName;
- const first = ask(fakeConnection());
- const second = ask(fakeConnection(), "author");
+ const first = ask(fakeAnchor());
+ const second = ask(fakeAnchor(), "author");
await act(async () => undefined);
expect(await first).toBeNull();
expect(prompt?.request?.defaultValue).toBe("author");
@@ -102,7 +101,7 @@ async function mount(defaultValue = "") {
const onAnswer = vi.fn();
await act(async () => {
renderInto(
- <RelationNamePopover connection={fakeConnection()} defaultValue={defaultValue} onAnswer={onAnswer} />);
+ <RelationNamePopover anchor={fakeAnchor()} defaultValue={defaultValue} onAnswer={onAnswer} />);
});
// Lets `placeFloating()` resolve, which is when the popover focuses its field.
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
@@ -112,10 +111,10 @@ async function mount(defaultValue = "") {
return { input, onAnswer };
}
-function fakeConnection() {
- const canvas = document.createElement("div");
- document.body.appendChild(canvas);
- return { canvas } as unknown as Connection;
+function fakeAnchor() {
+ const drawing = document.createElement("div");
+ document.body.appendChild(drawing);
+ return () => drawing;
}
async function type(input: HTMLInputElement, value: string) {
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx
index d3316b874e..0fa7eb9db1 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx
+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx
@@ -1,6 +1,5 @@
import "./RelationNamePopover.css";
-import type { Connection } from "jsplumb";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
@@ -14,19 +13,19 @@ import Popover from "../../react/Popover";
interface RelationNameRequest {
/** Tells requests apart, so a new one opens a fresh popover. */
id: number;
- connection: Connection;
+ anchor: RelationNameAnchor;
/** The name the field opens with: the current one when renaming, empty for a new relation. */
defaultValue: string;
resolve(name: string | null): void;
}
/**
- * Asks for the name of the relation drawn by `connection`, next to the connection itself. Resolves
+ * Asks for the name of a relation, next to the relation's drawing (`anchor`). Resolves
* with the name, or `null` when the request is canceled with Escape, the close button or a press
* outside the popover.
*/
-export default function RelationNamePopover({ connection, defaultValue, onAnswer }: {
- connection: Connection;
+export default function RelationNamePopover({ anchor, defaultValue, onAnswer }: {
+ anchor: RelationNameAnchor;
defaultValue: string;
onAnswer(name: string | null): void;
}) {
@@ -54,7 +53,7 @@ export default function RelationNamePopover({ connection, defaultValue, onAnswer
<Popover
className="relation-name-popover"
placement="bottom"
- getAnchorRect={() => connectionAnchorRect(connection)}
+ getAnchorRect={() => anchorRect(anchor)}
onDismiss={cancel}
onPlaced={() => inputRef.current?.focus()}
>
@@ -104,12 +103,15 @@ export default function RelationNamePopover({ connection, defaultValue, onAnswer
);
}
-/** Asks for a relation name next to `connection`; see {@link useRelationNamePrompt}. */
-export type AskRelationName = (connection: Connection, defaultValue?: string) => Promise<string | null>;
+/** Finds the drawing of the relation the popover asks about. */
+export type RelationNameAnchor = () => Element | null | undefined;
+
+/** Asks for a relation name next to `anchor`; see {@link useRelationNamePrompt}. */
+export type AskRelationName = (anchor: RelationNameAnchor, defaultValue?: string) => Promise<string | null>;
/**
* Holds the pending request for a relation name, for {@link RelationNamePopover} to answer. `ask`
- * keeps its identity across renders, so a jsPlumb handler bound once can call it; a new request
+ * keeps its identity across renders, so a handler bound once can call it; a new request
* cancels the one still pending.
*/
export function useRelationNamePrompt() {
@@ -118,9 +120,9 @@ export function useRelationNamePrompt() {
requestRef.current = request;
const nextId = useRef(0);
- const ask: AskRelationName = useCallback((connection, defaultValue = "") => new Promise<string | null>((resolve) => {
+ const ask: AskRelationName = useCallback((anchor, defaultValue = "") => new Promise<string | null>((resolve) => {
requestRef.current?.resolve(null);
- requestRef.current = { id: nextId.current++, connection, defaultValue, resolve };
+ requestRef.current = { id: nextId.current++, anchor, defaultValue, resolve };
setRequest(requestRef.current);
}), []);
@@ -133,9 +135,9 @@ export function useRelationNamePrompt() {
return { request, ask, answer };
}
-/** The middle of the connection's drawing, read afresh so the popover follows the map's pan and zoom. */
-function connectionAnchorRect(connection: Connection) {
- const rect = connection.canvas?.getBoundingClientRect();
+/** The middle of the relation's drawing, read afresh so the popover follows the map's pan and zoom. */
+function anchorRect(anchor: RelationNameAnchor) {
+ const rect = anchor()?.getBoundingClientRect();
if (!rect) {
return new DOMRect();
}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/api.ts b/apps/client/src/widgets/type_widgets/relation_map/api.ts
index 8962991365..681c1c0b6d 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/api.ts
+++ b/apps/client/src/widgets/type_widgets/relation_map/api.ts
@@ -1,4 +1,3 @@
-import { Connection } from "jsplumb";
import FNote from "../../../entities/fnote";
import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
@@ -88,8 +87,8 @@ export default class RelationMapApi {
this.onDataChange(true);
}
- async removeRelation(connection: Connection) {
- const relation = this.relations.find((rel) => rel.attributeId === connection.id);
+ async removeRelation(attributeId: string) {
+ const relation = this.relations.find((rel) => rel.attributeId === attributeId);
if (relation) {
await server.remove(`notes/${relation.sourceNoteId}/relations/${relation.name}/to/${relation.targetNoteId}`);
@@ -98,9 +97,9 @@ export default class RelationMapApi {
this.onDataChange(true);
}
- async renameRelation(connection: Connection, newName: string) {
+ async renameRelation(attributeId: string, newName: string) {
newName = utils.filterAttributeName(newName);
- const relation = this.relations.find((rel) => rel.attributeId === connection.id);
+ const relation = this.relations.find((rel) => rel.attributeId === attributeId);
if (!relation) return false;
@@ -116,8 +115,8 @@ export default class RelationMapApi {
return true;
}
- getRelationName(connection: Connection): string | undefined {
- const relation = this.relations.find((rel) => rel.attributeId === connection.id);
+ getRelationName(attributeId: string): string | undefined {
+ const relation = this.relations.find((rel) => rel.attributeId === attributeId);
return relation?.name;
}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts b/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts
index 8b2a5976ef..2d71562f96 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts
+++ b/apps/client/src/widgets/type_widgets/relation_map/context_menu.ts
@@ -1,4 +1,3 @@
-import { Connection } from "jsplumb";
import { RefObject } from "preact";
import appContext from "../../../components/app_context";
@@ -10,8 +9,7 @@ import dialog from "../../../services/dialog";
import toast from "../../../services/toast";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
-import RelationMapApi from "./api";
-import type { AskRelationName } from "./RelationNamePopover";
+import RelationMapApi, { type ClientRelation } from "./api";
export function buildNoteContextMenuHandler(note: FNote | null | undefined, mapApiRef: RefObject<RelationMapApi | null>, isReadOnly: boolean) {
return (e: MouseEvent) => {
@@ -77,46 +75,42 @@ export async function confirmRemoveFromMap(note: FNote, mapApiRef: RefObject<Rel
await mapApiRef.current?.removeItem(note.noteId, result.isDeleteNoteChecked);
}
-export function buildRelationContextMenuHandler(connection: Connection, mapApiRef: RefObject<RelationMapApi | null>, askRelationName: AskRelationName) {
- return (_, event: MouseEvent) => {
- if (connection.getType().includes("link")) {
- // don't create context menu if it's a link since there's nothing to do with link from relation map
- // (don't open browser menu either)
- event.preventDefault();
- } else {
- event.preventDefault();
- event.stopPropagation();
-
- contextMenu.show({
- x: event.pageX,
- y: event.pageY,
- items: [
- { title: t("relation_map.rename_relation"), command: "rename", uiIcon: "bx bx-pencil" },
- { kind: "separator" },
- { title: t("relation_map.remove_relation"), command: "remove", uiIcon: "bx bx-trash" }
- ],
- selectMenuItemHandler: async ({ command }) => {
- if (command === "rename") {
- const currentName = mapApiRef.current?.getRelationName(connection) ?? "";
- const newName = await askRelationName(connection, currentName);
+/**
+ * Shows the context menu of a relation, which renames or removes it. `askRelationName` asks for the
+ * new name next to the relation.
+ */
+export function showRelationContextMenu(event: MouseEvent, relation: ClientRelation, mapApiRef: RefObject<RelationMapApi | null>, askRelationName: (defaultValue: string) => Promise<string | null>) {
+ event.preventDefault();
+ event.stopPropagation();
- if (!newName?.trim() || newName === currentName) {
- return;
- }
+ contextMenu.show({
+ x: event.pageX,
+ y: event.pageY,
+ items: [
+ { title: t("relation_map.rename_relation"), command: "rename", uiIcon: "bx bx-pencil" },
+ { kind: "separator" },
+ { title: t("relation_map.remove_relation"), command: "remove", uiIcon: "bx bx-trash" }
+ ],
+ selectMenuItemHandler: async ({ command }) => {
+ if (command === "rename") {
+ const currentName = mapApiRef.current?.getRelationName(relation.attributeId) ?? "";
+ const newName = await askRelationName(currentName);
- const result = await mapApiRef.current?.renameRelation(connection, newName);
- if (!result) {
- toast.showError(t("relation_map.connection_exists", { name: newName }));
- }
- } else if (command === "remove") {
- if (!(await dialog.confirm(t("relation_map.confirm_remove_relation")))) {
- return;
- }
+ if (!newName?.trim() || newName === currentName) {
+ return;
+ }
- mapApiRef.current?.removeRelation(connection);
- }
+ const result = await mapApiRef.current?.renameRelation(relation.attributeId, newName);
+ if (!result) {
+ toast.showError(t("relation_map.connection_exists", { name: newName }));
}
- });
+ } else if (command === "remove") {
+ if (!(await dialog.confirm(t("relation_map.confirm_remove_relation")))) {
+ return;
+ }
+
+ mapApiRef.current?.removeRelation(relation.attributeId);
+ }
}
- };
+ });
}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/drags.spec.tsx b/apps/client/src/widgets/type_widgets/relation_map/drags.spec.tsx
new file mode 100644
index 0000000000..f4e2f3eacb
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/drags.spec.tsx
@@ -0,0 +1,137 @@
+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 toast from "../../../services/toast";
+import type RelationMapApi from "./api";
+import { useBoxDragging, useRelationDrawing } from "./drags";
+import type { RelationNameAnchor } from "./RelationNamePopover";
+import { noteIdToId } from "./utils";
+
+describe("relation map pointer drags", () => {
+ let container: HTMLElement | undefined;
+ const moveNote = vi.fn();
+ const connect = vi.fn(async () => true);
+ const askRelationName = vi.fn<(anchor: RelationNameAnchor) => Promise<string | null>>();
+ let state: { dragged: unknown; pending: unknown } = { dragged: null, pending: null };
+ let startDrag: ReturnType<typeof useBoxDragging>["startDrag"] | undefined;
+ let startDrawing: ReturnType<typeof useRelationDrawing>["startDrawing"] | undefined;
+
+ beforeEach(() => {
+ for (const mock of [ moveNote, connect, askRelationName ]) mock.mockClear();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ act(() => render(<Harness />, container as HTMLElement));
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ vi.restoreAllMocks();
+ });
+
+ function Harness() {
+ const canvasRef = useRef<HTMLDivElement>(null);
+ const mapApiRef = useRef({ moveNote, connect } as unknown as RelationMapApi);
+ const dragging = useBoxDragging({ containerRef: canvasRef, mapApiRef });
+ const drawing = useRelationDrawing({ containerRef: canvasRef, mapApiRef, askRelationName });
+ state = { dragged: dragging.dragged, pending: drawing.pending };
+ startDrag = dragging.startDrag;
+ startDrawing = drawing.startDrawing;
+
+ // Zoomed to 2x, as `panzoom` would transform it.
+ return (
+ <div ref={canvasRef} className="canvas" style={{ transform: "matrix(2, 0, 0, 2, 0, 0)" }}>
+ <div id={noteIdToId("target")} className="note-box" />
+ </div>
+ );
+ }
+
+ function pointer(type: string, clientX: number, clientY: number) {
+ return new PointerEvent(type, { clientX, clientY, button: 0, isPrimary: true });
+ }
+
+ /** Releases the pointer, and waits for the name to be asked and the relation created. */
+ async function release(clientX: number, clientY: number) {
+ await act(async () => {
+ window.dispatchEvent(pointer("pointerup", clientX, clientY));
+ await new Promise((resolve) => setTimeout(resolve));
+ });
+ }
+
+ function dispatch(type: string, clientX: number, clientY: number) {
+ act(() => { window.dispatchEvent(pointer(type, clientX, clientY)); });
+ }
+
+ it("moves a box once the pointer leaves the click tolerance, and saves it on release", () => {
+ act(() => startDrag?.(pointer("pointerdown", 100, 100), { noteId: "box", x: 10, y: 20 }));
+
+ dispatch("pointermove", 102, 101);
+ expect(state.dragged).toBeNull();
+
+ dispatch("pointermove", 140, 160);
+ expect(state.dragged).toEqual({ noteId: "box", x: 30, y: 50 });
+
+ dispatch("pointerup", 140, 160);
+ expect(moveNote).toHaveBeenCalledWith("box", 30, 50);
+ expect(state.dragged).toBeNull();
+ });
+
+ it("puts a box back when the drag is canceled", () => {
+ act(() => startDrag?.(pointer("pointerdown", 100, 100), { noteId: "box", x: 10, y: 20 }));
+ dispatch("pointermove", 140, 160);
+ dispatch("pointercancel", 140, 160);
+
+ expect(moveNote).not.toHaveBeenCalled();
+ expect(state.dragged).toBeNull();
+ });
+
+ it("draws a relation onto the box under the pointer and creates it with the name asked for", async () => {
+ const target = container?.querySelector(".note-box") ?? null;
+ vi.spyOn(document, "elementFromPoint").mockImplementation((x) => (x > 200 ? target : null));
+ askRelationName.mockResolvedValue("author");
+
+ act(() => startDrawing?.(pointer("pointerdown", 100, 100), "source"));
+ dispatch("pointermove", 150, 100);
+ expect(state.pending).toEqual({ sourceNoteId: "source", targetNoteId: undefined, pointer: { x: 75, y: 50 } });
+
+ dispatch("pointermove", 250, 100);
+ expect(state.pending).toMatchObject({ targetNoteId: "target" });
+
+ await release(250, 100);
+ expect(askRelationName).toHaveBeenCalledTimes(1);
+ expect(connect).toHaveBeenCalledWith("author", "source", "target");
+ expect(state.pending).toBeNull();
+ });
+
+ it("creates nothing on a click, off a box, when the name is dismissed or when the relation exists", async () => {
+ const target = container?.querySelector(".note-box") ?? null;
+ const elementFromPoint = vi.spyOn(document, "elementFromPoint").mockReturnValue(null);
+ const showError = vi.spyOn(toast, "showError").mockImplementation(() => {});
+
+ act(() => startDrawing?.(pointer("pointerdown", 100, 100), "source"));
+ await release(250, 100);
+ expect(askRelationName).not.toHaveBeenCalled();
+ expect(state.pending).toBeNull();
+
+ elementFromPoint.mockReturnValue(target);
+ act(() => startDrawing?.(pointer("pointerdown", 100, 100), "source"));
+ await release(101, 101);
+ expect(askRelationName).not.toHaveBeenCalled();
+
+ askRelationName.mockResolvedValue(null);
+ act(() => startDrawing?.(pointer("pointerdown", 100, 100), "source"));
+ await release(250, 100);
+ expect(connect).not.toHaveBeenCalled();
+
+ askRelationName.mockResolvedValue("author");
+ connect.mockResolvedValueOnce(false);
+ act(() => startDrawing?.(pointer("pointerdown", 100, 100), "source"));
+ await release(250, 100);
+ expect(showError).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/relation_map/drags.ts b/apps/client/src/widgets/type_widgets/relation_map/drags.ts
new file mode 100644
index 0000000000..12b75da2b5
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/drags.ts
@@ -0,0 +1,140 @@
+import { RefObject } from "preact";
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import toast from "../../../services/toast";
+import RelationMapApi, { MapDataNoteEntry } from "./api";
+import { type PendingRelation, PENDING_CONNECTION_ID } from "./Connections";
+import type { AskRelationName } from "./RelationNamePopover";
+import { CLICK_TOLERANCE, getMousePosition, getZoom, idToNoteId } from "./utils";
+
+/**
+ * Moves a box with the pointer. The box follows the pointer once it has moved more than
+ * `CLICK_TOLERANCE`, so a click still selects it, and the map saves the position on release.
+ * `dragged` is the box's position while it is dragged, which overrides the saved one.
+ */
+export function useBoxDragging({ containerRef, mapApiRef }: {
+ containerRef: RefObject<HTMLDivElement | null>;
+ mapApiRef: RefObject<RelationMapApi | null>;
+}) {
+ const [ dragged, setDragged ] = useState<MapDataNoteEntry | null>(null);
+ const track = usePointerTracking();
+
+ const startDrag = useCallback((e: PointerEvent, entry: MapDataNoteEntry) => {
+ const container = containerRef.current;
+ if (!container || e.button !== 0 || !e.isPrimary) return;
+
+ const zoom = getZoom(container);
+ let position: MapDataNoteEntry | null = null;
+ track({
+ onMove(moveEvent) {
+ const dx = moveEvent.clientX - e.clientX;
+ const dy = moveEvent.clientY - e.clientY;
+ if (!position && Math.hypot(dx, dy) <= CLICK_TOLERANCE) return;
+
+ position = { noteId: entry.noteId, x: entry.x + dx / zoom, y: entry.y + dy / zoom };
+ setDragged(position);
+ },
+ onEnd(endEvent) {
+ if (position && endEvent.type === "pointerup") {
+ mapApiRef.current?.moveNote(position.noteId, position.x, position.y);
+ }
+ setDragged(null);
+ }
+ });
+ }, [ containerRef, mapApiRef, track ]);
+
+ return { dragged, startDrag };
+}
+
+/**
+ * Draws a new relation from the endpoint of a box. The relation follows the pointer and snaps to the
+ * box under it; on release over a box, it stays drawn while `askRelationName` asks for its name, and
+ * the relation is created with that name. A release within `CLICK_TOLERANCE` of the press creates
+ * nothing, so a click on the endpoint does not start a relation from the box to itself.
+ */
+export function useRelationDrawing({ containerRef, mapApiRef, askRelationName }: {
+ containerRef: RefObject<HTMLDivElement | null>;
+ mapApiRef: RefObject<RelationMapApi | null>;
+ askRelationName: AskRelationName;
+}) {
+ const [ pending, setPending ] = useState<PendingRelation | null>(null);
+ const track = usePointerTracking();
+
+ const startDrawing = useCallback((e: PointerEvent, sourceNoteId: string) => {
+ const container = containerRef.current;
+ if (!container || e.button !== 0 || !e.isPrimary) return;
+
+ const zoom = getZoom(container);
+ const pendingAt = (event: PointerEvent): PendingRelation => ({
+ sourceNoteId,
+ targetNoteId: boxNoteIdAt(event, container),
+ pointer: getMousePosition(event, container, zoom)
+ });
+ setPending(pendingAt(e));
+
+ track({
+ onMove: (moveEvent) => setPending(pendingAt(moveEvent)),
+ async onEnd(endEvent) {
+ const dropped = pendingAt(endEvent);
+ const { targetNoteId } = dropped;
+ const isClick = Math.hypot(endEvent.clientX - e.clientX, endEvent.clientY - e.clientY) <= CLICK_TOLERANCE;
+ if (endEvent.type !== "pointerup" || !targetNoteId || isClick) {
+ setPending(null);
+ return;
+ }
+
+ setPending(dropped);
+ const name = await askRelationName(
+ () => container.querySelector(`[data-connection-id="${PENDING_CONNECTION_ID}"]`));
+ if (name?.trim() && mapApiRef.current
+ && !await mapApiRef.current.connect(name, sourceNoteId, targetNoteId)) {
+ toast.showError(t("relation_map.connection_exists", { name }));
+ }
+ setPending(null);
+ }
+ });
+ }, [ containerRef, mapApiRef, askRelationName, track ]);
+
+ return { pending, startDrawing };
+}
+
+/**
+ * Follows the pointer on the window until it is released or the gesture is canceled, so the gesture
+ * continues outside the box it started on. Stops following on unmount.
+ */
+function usePointerTracking() {
+ const stopRef = useRef<() => void>(null);
+ useEffect(() => () => stopRef.current?.(), []);
+
+ return useCallback(({ onMove, onEnd }: {
+ onMove(e: PointerEvent): void;
+ onEnd(e: PointerEvent): void;
+ }) => {
+ stopRef.current?.();
+ const end = (e: PointerEvent) => {
+ stop();
+ onEnd(e);
+ };
+ const stop = () => {
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", end);
+ window.removeEventListener("pointercancel", end);
+ stopRef.current = null;
+ };
+
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", end);
+ window.addEventListener("pointercancel", end);
+ stopRef.current = stop;
+ }, []);
+}
+
+/**
+ * The note of the box under the pointer. Read from the point rather than from the event's target,
+ * because a touch keeps sending events to the element it started on.
+ */
+function boxNoteIdAt(e: PointerEvent, container: HTMLElement) {
+ const box = document.elementFromPoint(e.clientX, e.clientY)?.closest(".note-box:not(.relation-map-ghost-note)");
+ return box && container.contains(box) ? idToNoteId(box.id) : undefined;
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/geometry.spec.ts b/apps/client/src/widgets/type_widgets/relation_map/geometry.spec.ts
new file mode 100644
index 0000000000..1aa155b401
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/geometry.spec.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+
+import { type Box, type ConnectionShape, layoutConnections, layoutLine } from "./geometry";
+
+const boxA: Box = { x: 0, y: 0, width: 100, height: 40 };
+const boxB: Box = { x: 300, y: 0, width: 100, height: 40 };
+
+describe("relation map geometry", () => {
+ it("runs a line between the facing borders, with an arrowhead at the target only", () => {
+ const layout = layoutLine(boxA, boxB, { labelAt: [ 0.5 ] });
+
+ expect(layout?.path).toBe("M 103 20 Q 200 20 297 20");
+ expect(layout?.arrows).toHaveLength(1);
+ expect(arrowTip(layout?.arrows[0])).toEqual({ x: 297, y: 20 });
+ expect(layout?.labels).toEqual([ { x: 200, y: 20 } ]);
+
+ const both = layoutLine(boxA, boxB, { arrowAtSource: true });
+ expect(both?.arrows.map(arrowTip)).toEqual([ { x: 297, y: 20 }, { x: 103, y: 20 } ]);
+ });
+
+ it("draws a relation being created up to the pointer, and nothing from inside its own box", () => {
+ expect(layoutLine(boxA, { x: 250, y: 20 })?.path).toBe("M 103 20 Q 150 20 250 20");
+ expect(layoutLine(boxA, { x: 60, y: 30 })).toBeNull();
+ });
+
+ it("bows relations between the same two boxes apart, whichever way they run", () => {
+ const layouts = layoutConnections([
+ shape("ab", "a", "b"),
+ shape("ba", "b", "a"),
+ shape("single", "a", "c")
+ ], new Map([ [ "a", boxA ], [ "b", boxB ], [ "c", { ...boxB, y: 300 } ] ]));
+
+ const offset = (id: string) => (layouts.get(id)?.labels[0].y ?? 20) - 20;
+ expect(offset("ab") * offset("ba")).toBeLessThan(0);
+ expect(Math.abs(offset("ab") - offset("ba"))).toBeGreaterThan(20);
+ expect(layouts.get("single")?.path).toMatch(/^M [\d.]+ [\d.]+ Q 200 170 /);
+ });
+
+ it("loops a relation to its own box around the top-right corner, each further loop wider", () => {
+ const layouts = layoutConnections([
+ { ...shape("first", "a", "a"), labelAt: [ 0.5 ] },
+ shape("second", "a", "a")
+ ], new Map([ [ "a", boxA ] ]));
+
+ expect(layouts.get("first")?.path).toBe("M 82 0 A 18 18 0 1 1 100 18");
+ expect(layouts.get("second")?.path).toBe("M 72 0 A 28 28 0 1 1 100 28");
+ expect(arrowTip(layouts.get("first")?.arrows[0])).toEqual({ x: 100, y: 18 });
+ const label = layouts.get("first")?.labels[0];
+ expect([ label?.x, label?.y ].map((value) => Math.round(value ?? 0))).toEqual([ 113, -13 ]);
+ });
+
+ it("leaves out a relation whose box is not measured yet", () => {
+ expect(layoutConnections([ shape("ab", "a", "b") ], new Map([ [ "a", boxA ] ])).size).toBe(0);
+ });
+});
+
+function shape(id: string, sourceId: string, targetId: string): ConnectionShape {
+ return { id, sourceId, targetId, arrowAtSource: false, labelAt: [ 0.5 ] };
+}
+
+/** The first point of an arrowhead outline, which is its tip. */
+function arrowTip(points: string | undefined) {
+ const [ x, y ] = (points ?? "").split(" ")[0].split(",").map(Number);
+ return { x, y };
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/geometry.ts b/apps/client/src/widgets/type_widgets/relation_map/geometry.ts
new file mode 100644
index 0000000000..18a2a37643
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/relation_map/geometry.ts
@@ -0,0 +1,185 @@
+import { getArrowOutline } from "../../note_map/rendering";
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+/** A note box, in unzoomed map pixels. */
+export interface Box extends Point {
+ width: number;
+ height: number;
+}
+
+/** A relation to lay out, between two boxes or from a box to itself. */
+export interface ConnectionShape {
+ id: string;
+ sourceId: string;
+ targetId: string;
+ /** Draws an arrowhead at the source end as well as at the target end. */
+ arrowAtSource: boolean;
+ /** Positions of the labels along the line, from 0 at the source to 1 at the target. */
+ labelAt: number[];
+}
+
+export interface ConnectionLayout {
+ /** SVG path data of the line. */
+ path: string;
+ /** Outlines of the arrowheads, as SVG `points`. */
+ arrows: string[];
+ /** Centers of the labels, in the order of `ConnectionShape.labelAt`. */
+ labels: Point[];
+}
+
+/** Length of an arrowhead. The rounded stroke of `.relation-map-arrow` adds about half a pixel on every side. */
+const ARROW_LENGTH_PX = 9;
+/** Gap between a box and the end of a line. */
+const BOX_GAP = 3;
+/** Distance between the middles of relations that run between the same two boxes. */
+const PARALLEL_SPACING = 30;
+/** Radius of a box's first loop; each further loop is `LOOP_SPACING` wider. */
+const LOOP_RADIUS = 18;
+const LOOP_SPACING = 10;
+
+/**
+ * Lays out the relations between the boxes in `boxes`, keyed by note ID. A relation whose box has
+ * not been measured yet, or whose boxes overlap too much for a line, is left out.
+ *
+ * Relations between the same two boxes bow apart, so that their lines and labels do not overlap,
+ * and the loops of a box grow one around the other.
+ */
+export function layoutConnections(shapes: ConnectionShape[], boxes: Map<string, Box>) {
+ const layouts = new Map<string, ConnectionLayout>();
+
+ for (const group of groupByBoxPair(shapes)) {
+ for (const [ index, shape ] of group.entries()) {
+ const source = boxes.get(shape.sourceId);
+ const target = boxes.get(shape.targetId);
+ if (!source || !target) continue;
+
+ const layout = shape.sourceId === shape.targetId
+ ? layoutLoop(source, index, shape)
+ : layoutLine(source, target, {
+ ...shape,
+ // Measured from the box with the lower ID, so that relations in both directions fan out.
+ bend: (index - (group.length - 1) / 2) * PARALLEL_SPACING * (shape.sourceId < shape.targetId ? 1 : -1)
+ });
+ if (layout) layouts.set(shape.id, layout);
+ }
+ }
+
+ return layouts;
+}
+
+/**
+ * Lays out a line from the border of `source` to the border of `target`, or to a point while a
+ * relation is being drawn. The line is a quadratic curve whose middle lies `bend` pixels to the left
+ * of the straight line, looking from `source`. Returns `null` when there is no room for a line.
+ */
+export function layoutLine(source: Box, target: Box | Point, { bend = 0, arrowAtSource = false, labelAt = [] }: {
+ bend?: number;
+ arrowAtSource?: boolean;
+ labelAt?: number[];
+} = {}): ConnectionLayout | null {
+ const from = centerOf(source);
+ const to = "width" in target ? centerOf(target) : target;
+ const dx = to.x - from.x;
+ const dy = to.y - from.y;
+ const distance = Math.hypot(dx, dy);
+ if (!distance) return null;
+
+ // The curve passes halfway between the middle of the straight line and its control point.
+ const control = {
+ x: (from.x + to.x) / 2 + (dy / distance) * bend * 2,
+ y: (from.y + to.y) / 2 - (dx / distance) * bend * 2
+ };
+ const start = exitPoint(source, control);
+ const end = "width" in target ? exitPoint(target, control) : target;
+ if (!start || !end) return null;
+
+ return {
+ path: `M ${round(start.x)} ${round(start.y)} Q ${round(control.x)} ${round(control.y)} ${round(end.x)} ${round(end.y)}`,
+ arrows: arrowsAt([ [ control, end ], ...(arrowAtSource ? [ [ control, start ] as const ] : []) ]),
+ labels: labelAt.map((t) => quadraticAt(start, control, end, t))
+ };
+}
+
+/**
+ * Lays out a relation from a box to itself: an arc around the box's top-right corner, from its top
+ * edge to its right edge. `index` makes each further loop of the box wider than the one before.
+ */
+function layoutLoop(box: Box, index: number, { arrowAtSource, labelAt }: ConnectionShape): ConnectionLayout {
+ const radius = LOOP_RADIUS + index * LOOP_SPACING;
+ const corner = { x: box.x + box.width, y: box.y };
+ const start = { x: corner.x - radius, y: corner.y };
+ const end = { x: corner.x, y: corner.y + radius };
+ // The arc runs three quarters of a circle clockwise, from the left of the corner to below it.
+ const pointAt = (t: number) => {
+ const angle = Math.PI + t * 1.5 * Math.PI;
+ return { x: corner.x + radius * Math.cos(angle), y: corner.y + radius * Math.sin(angle) };
+ };
+
+ return {
+ path: `M ${round(start.x)} ${round(start.y)} A ${radius} ${radius} 0 1 1 ${round(end.x)} ${round(end.y)}`,
+ arrows: arrowsAt([
+ [ { x: end.x + radius, y: end.y }, end ],
+ ...(arrowAtSource ? [ [ { x: start.x, y: start.y - radius }, start ] as const ] : [])
+ ]),
+ labels: labelAt.map(pointAt)
+ };
+}
+
+/** Groups the relations by the pair of boxes they run between, in either direction. */
+function groupByBoxPair(shapes: ConnectionShape[]) {
+ const groups = new Map<string, ConnectionShape[]>();
+ for (const shape of shapes) {
+ const key = [ shape.sourceId, shape.targetId ].sort().join("\n");
+ groups.set(key, [ ...(groups.get(key) ?? []), shape ]);
+ }
+ return groups.values();
+}
+
+/**
+ * Where the ray from the center of `box` toward `point` leaves the box, plus `BOX_GAP`, or `null`
+ * when `point` is inside the box.
+ */
+function exitPoint(box: Box, point: Point): Point | null {
+ const center = centerOf(box);
+ const dx = point.x - center.x;
+ const dy = point.y - center.y;
+ const scale = Math.min(
+ dx ? box.width / 2 / Math.abs(dx) : Infinity,
+ dy ? box.height / 2 / Math.abs(dy) : Infinity
+ );
+ if (scale >= 1) return null;
+
+ const distance = Math.hypot(dx, dy);
+ return {
+ x: center.x + dx * scale + (dx / distance) * BOX_GAP,
+ y: center.y + dy * scale + (dy / distance) * BOX_GAP
+ };
+}
+
+/** The outlines of arrowheads pointing along each `[from, tip]` pair, as SVG `points`. */
+function arrowsAt(directions: (readonly [ Point, Point ])[]) {
+ return directions
+ .map(([ from, tip ]) => getArrowOutline(from, tip, 0, ARROW_LENGTH_PX))
+ .filter((outline) => outline !== null)
+ .map((outline) => outline.map(([ x, y ]) => `${round(x)},${round(y)}`).join(" "));
+}
+
+function quadraticAt(start: Point, control: Point, end: Point, t: number): Point {
+ const u = 1 - t;
+ return {
+ x: u * u * start.x + 2 * u * t * control.x + t * t * end.x,
+ y: u * u * start.y + 2 * u * t * control.y + t * t * end.y
+ };
+}
+
+function centerOf(box: Box): Point {
+ return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
+}
+
+function round(value: number) {
+ return Math.round(value * 100) / 100;
+}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/jsplumb.tsx b/apps/client/src/widgets/type_widgets/relation_map/jsplumb.tsx
deleted file mode 100644
index 0f72917480..0000000000
--- a/apps/client/src/widgets/type_widgets/relation_map/jsplumb.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import { jsPlumb, Defaults, jsPlumbInstance, DragOptions, OnConnectionBindInfo } from "jsplumb";
-import { ComponentChildren, createContext, HTMLAttributes, RefObject } from "preact";
-import { useContext, useEffect, useRef } from "preact/hooks";
-
-const JsPlumbInstance = createContext<RefObject<jsPlumbInstance | null> | undefined>(undefined);
-
-export function JsPlumb({ className, props, children, containerRef: externalContainerRef, apiRef, onInstanceCreated, onConnection }: {
- className?: string;
- props: Omit<Defaults, "container">;
- children: ComponentChildren;
- containerRef?: RefObject<HTMLElement | null>;
- apiRef?: RefObject<jsPlumbInstance | null>;
- onInstanceCreated?: (jsPlumbInstance: jsPlumbInstance) => void;
- onConnection?: (info: OnConnectionBindInfo, originalEvent: Event) => void;
-}) {
- const containerRef = useRef<HTMLDivElement>(null);
- const jsPlumbRef = useRef<jsPlumbInstance | undefined>(undefined);
-
- useEffect(() => {
- if (!containerRef.current) return;
- if (externalContainerRef) {
- externalContainerRef.current = containerRef.current;
- }
-
- const jsPlumbInstance = jsPlumb.getInstance({
- Container: containerRef.current,
- ...props
- });
- if (apiRef) {
- apiRef.current = jsPlumbInstance;
- }
- jsPlumbRef.current = jsPlumbInstance;
-
- onInstanceCreated?.(jsPlumbInstance);
- return () => {
- jsPlumbInstance.deleteEveryEndpoint();
- jsPlumbInstance.cleanupListeners()
- };
- }, [ apiRef ]);
-
- useEffect(() => {
- const jsPlumbInstance = jsPlumbRef.current;
- if (!jsPlumbInstance || !onConnection) return;
-
- jsPlumbInstance.bind("connection", onConnection);
- return () => jsPlumbInstance.unbind("connection", onConnection);
- }, [ onConnection ]);
-
- return (
- <div ref={containerRef} className={className}>
- <JsPlumbInstance.Provider value={apiRef}>
- {children}
- </JsPlumbInstance.Provider>
- </div>
- )
-}
-
-export function JsPlumbItem({ x, y, children, draggable, sourceConfig, targetConfig, dynamicClassName, ...restProps }: {
- x: number;
- y: number;
- children: ComponentChildren;
- draggable?: DragOptions;
- sourceConfig?: object;
- targetConfig?: object;
- /** Classes that change while the item is on the map. Added to the element directly rather than
- * through `className`, whose changes would drop the classes jsPlumb adds to it. */
- dynamicClassName?: string;
-} & Pick<HTMLAttributes<HTMLDivElement>, "id" | "className" | "onContextMenu">) {
- const containerRef = useRef<HTMLDivElement>(null);
- const apiRef = useContext(JsPlumbInstance);
-
- useEffect(() => {
- if (!draggable || !apiRef?.current || !containerRef.current) return;
- apiRef.current.draggable(containerRef.current, draggable);
- }, [ draggable ]);
-
- useEffect(() => {
- if (!sourceConfig || !apiRef?.current || !containerRef.current) return;
- apiRef.current.makeSource(containerRef.current, sourceConfig);
- }, [ sourceConfig ]);
-
- useEffect(() => {
- if (!targetConfig || !apiRef?.current || !containerRef.current) return;
- apiRef.current.makeTarget(containerRef.current, targetConfig);
- }, [ targetConfig ]);
-
- useEffect(() => {
- const element = containerRef.current;
- const classes = dynamicClassName?.split(" ").filter(Boolean) ?? [];
- if (!element || !classes.length) return;
-
- element.classList.add(...classes);
- return () => element.classList.remove(...classes);
- }, [ dynamicClassName ]);
-
- return (
- <div
- ref={containerRef}
- {...restProps}
- style={{ left: `${x}px`, top: `${y}px` }}
- >
- {children}
- </div>
- )
-}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/overlays.ts b/apps/client/src/widgets/type_widgets/relation_map/overlays.ts
deleted file mode 100644
index 9b740c2b79..0000000000
--- a/apps/client/src/widgets/type_widgets/relation_map/overlays.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { jsPlumbInstance, OverlaySpec } from "jsplumb";
-
-const ARROW_LENGTH_PX = 9;
-
-export const uniDirectionalOverlays: OverlaySpec[] = [
- arrow({ location: 1, id: "arrow" }),
- ["Label", { label: "", id: "label", cssClass: "connection-label" }]
-];
-
-const biDirectionalOverlays: OverlaySpec[] = [
- arrow({ location: 1, id: "arrow" }),
- ["Label", { label: "", id: "label", cssClass: "connection-label" }],
- arrow({ location: 0, id: "arrow2", direction: -1 })
-];
-
-const inverseRelationsOverlays: OverlaySpec[] = [
- arrow({ location: 1, id: "arrow" }),
- ["Label", { label: "", location: 0.2, id: "label-source", cssClass: "connection-label" }],
- ["Label", { label: "", location: 0.8, id: "label-target", cssClass: "connection-label" }],
- arrow({ location: 0, id: "arrow2", direction: -1 })
-];
-
-const linkOverlays: OverlaySpec[] = [
- arrow({ location: 1, id: "arrow" })
-];
-
-export default function setupOverlays(jsPlumbInstance: jsPlumbInstance) {
- jsPlumbInstance.registerConnectionType("uniDirectional", {
- anchor: "Continuous",
- connector: "StateMachine",
- overlays: uniDirectionalOverlays
- });
-
- jsPlumbInstance.registerConnectionType("biDirectional", {
- anchor: "Continuous",
- connector: "StateMachine",
- overlays: biDirectionalOverlays
- });
-
- jsPlumbInstance.registerConnectionType("inverse", {
- anchor: "Continuous",
- connector: "StateMachine",
- overlays: inverseRelationsOverlays
- });
-
- jsPlumbInstance.registerConnectionType("link", {
- anchor: "Continuous",
- connector: "StateMachine",
- overlays: linkOverlays
- });
-}
-
-/**
- * The arrowhead of the note map (`note_map/rendering.ts`): as wide as 0.72 of its length, with the
- * tail swept back to 0.72 of the length from the tip. It is a pixel shorter, because the rounded
- * stroke of `.relation-map-arrow` adds about half a pixel on every side.
- */
-function arrow(options: { location: number, id: string, direction?: number }): OverlaySpec {
- return [ "Arrow", {
- ...options,
- length: ARROW_LENGTH_PX,
- width: ARROW_LENGTH_PX * 0.72,
- foldback: 0.72,
- cssClass: "relation-map-arrow"
- } ];
-}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/utils.ts b/apps/client/src/widgets/type_widgets/relation_map/utils.ts
index c4d634a4ef..a3eea9dc31 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/utils.ts
+++ b/apps/client/src/widgets/type_widgets/relation_map/utils.ts
@@ -9,6 +9,9 @@ export function idToNoteId(id: string) {
return id.substr(13);
}
+/** How far, in pixels, the pointer can move between press and release for the click to count. */
+export const CLICK_TOLERANCE = 4;
+
export function getZoom(container: HTMLDivElement) {
const transform = window.getComputedStyle(container).transform;
if (transform === "none") {
diff --git a/apps/standalone/package.json b/apps/standalone/package.json
index cfcdc08e51..43be4ad639 100644
--- a/apps/standalone/package.json
+++ b/apps/standalone/package.json
@@ -46,7 +46,6 @@
"js-sha256": "1.0.0",
"js-sha512": "0.9.0",
"scrypt-js": "3.0.1",
- "jsplumb": "2.15.6",
"katex": "0.19.0",
"maplibre-gl": "6.12.0",
"mark.js": "8.11.1",
diff --git a/docs/Developer Guide/Developer Guide/Dependencies/Per-dependency checks.md b/docs/Developer Guide/Developer Guide/Dependencies/Per-dependency checks.md
index 0640925536..bdd0cbdb2f 100644
--- a/docs/Developer Guide/Developer Guide/Dependencies/Per-dependency checks.md
+++ b/docs/Developer Guide/Developer Guide/Dependencies/Per-dependency checks.md
@@ -101,13 +101,6 @@
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
- <tr>
- <td><code>jsplumb</code></td>
- <td><code>RELATION_MAP</code></td>
- <td><ul><li>Relation map note type</li></ul></td>
- <td>&nbsp;</td>
- <td>&nbsp;</td>
- </tr>
<tr>
<td><code>jquery.mark.es6</code></td>
<td><code>MARKJS</code></td>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c14327bd40..9c3f758805 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -313,9 +313,6 @@ importers:
jquery.fancytree:
specifier: 2.38.5
version: 2.38.5([email protected])
- jsplumb:
- specifier: 2.15.6
- version: 2.15.6
katex:
specifier: 0.19.0
version: 0.19.0
@@ -945,9 +942,6 @@ importers:
js-sha512:
specifier: 0.9.0
version: 0.9.0
- jsplumb:
- specifier: 2.15.6
- version: 2.15.6
katex:
specifier: 0.19.0
version: 0.19.0
@@ -8305,9 +8299,6 @@ packages:
resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-sIpbpz5eMVM+vV+MQzFCidlaa1RsknrQs6LOTKYDjYUDdTAi2AN2bFi94TxB33TifcIsRNV1jebcaxg0tCoPzg==}
-
resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==}
engines: {node: '>=4.0'}
@@ -19967,8 +19958,6 @@ snapshots:
optional: true
-
dependencies:
array-includes: 3.2.0