Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve graph layout and drag animations https://github.com/siyuan-note/siyuan/issues/18667

Daniel896f511c0b14
diff --git a/app/src/layout/dock/graph/GraphEngine.ts b/app/src/layout/dock/graph/GraphEngine.ts
index bec4c90dbf..4b874d7b6a 100644
--- a/app/src/layout/dock/graph/GraphEngine.ts
+++ b/app/src/layout/dock/graph/GraphEngine.ts
@@ -72,6 +72,7 @@ export class GraphEngine {
private options: IGraphOptions;
private palette: IGraphPalette;
private pendingFocusId = "";
+ private readonly pendingNodeReleases = new Map<number, number>();
private readonly pinnedNodes = new Map<number, [number, number]>();
private pinchAction: IPinchAction;
private pointerAction: IPointerAction;
@@ -80,6 +81,7 @@ export class GraphEngine {
private positions = new Float32Array();
private renderFrame = 0;
private renderer: IGraphRenderer;
+ private releaseToken = 0;
private selected = -1;
private selectionVersion = 0;
private styleVersion = 0;
@@ -138,6 +140,7 @@ export class GraphEngine {
this.cameraTouched = false;
this.focusAnimation++;
this.resetInteraction();
+ this.pendingNodeReleases.clear();
this.pinnedNodes.clear();
this.hideTooltip();
this.fit(false);
@@ -194,6 +197,7 @@ export class GraphEngine {
this.focusAnimation++;
this.autoFitPending = false;
this.pendingFocusId = "";
+ this.pendingNodeReleases.clear();
this.pinnedNodes.clear();
this.data = undefined;
this.positions = new Float32Array();
@@ -336,6 +340,8 @@ export class GraphEngine {
private startLayout() {
this.stopLayout();
+ this.pendingNodeReleases.forEach((_token, index) => this.pinnedNodes.delete(index));
+ this.pendingNodeReleases.clear();
if (!this.data || this.data.nodes.length < 2) {
if (this.pendingFocusId) {
this.focusNode(this.pendingFocusId);
@@ -351,8 +357,17 @@ export class GraphEngine {
this.layoutWorker = worker;
worker.onmessage = (event: MessageEvent<TGraphLayoutResponse>) => {
const message = event.data;
- if (message.type !== "positions" || message.generation !== this.generation ||
- message.positions.length !== this.positions.length) {
+ if (message.generation !== this.generation) {
+ return;
+ }
+ if (message.type === "released") {
+ if (this.pendingNodeReleases.get(message.index) === message.token) {
+ this.pendingNodeReleases.delete(message.index);
+ this.pinnedNodes.delete(message.index);
+ }
+ return;
+ }
+ if (message.positions.length !== this.positions.length) {
return;
}
this.pinnedNodes.forEach((position, index) => {
@@ -616,6 +631,7 @@ export class GraphEngine {
const y = graph.y;
this.positions[action.node * 2] = x;
this.positions[action.node * 2 + 1] = y;
+ this.pendingNodeReleases.delete(action.node);
this.pinnedNodes.set(action.node, [x, y]);
this.positionVersion++;
this.postLayoutMessage({
@@ -756,6 +772,18 @@ export class GraphEngine {
}
const offset = action.node * 2;
this.pinnedNodes.set(action.node, [this.positions[offset], this.positions[offset + 1]]);
+ if (!this.layoutWorker) {
+ this.pinnedNodes.delete(action.node);
+ return;
+ }
+ const token = ++this.releaseToken;
+ this.pendingNodeReleases.set(action.node, token);
+ this.postLayoutMessage({
+ type: "release",
+ generation: this.generation,
+ index: action.node,
+ token,
+ });
}
private setHovered(index: number) {
diff --git a/app/src/layout/dock/graph/core.test.ts b/app/src/layout/dock/graph/core.test.ts
index fc5c754f32..4e29466954 100644
--- a/app/src/layout/dock/graph/core.test.ts
+++ b/app/src/layout/dock/graph/core.test.ts
@@ -30,6 +30,7 @@ describe("graph data normalization", () => {
assert.deepEqual(Array.from(data.sources), [0]);
assert.deepEqual(Array.from(data.targets), [1]);
assert.deepEqual(Array.from(data.degrees), [1, 1]);
+ assert.deepEqual(data.components.map((component) => component.nodeIndices), [[0, 1]]);
assert.equal(data.sizes[0], 10);
assert.equal(data.sizes[1], 30);
});
@@ -53,6 +54,51 @@ describe("graph data normalization", () => {
assert.deepEqual(createInitialPositions(second, 400), createInitialPositions(first, 400));
});
+ it("packs disconnected components without overlap", () => {
+ const data = normalizeGraphData([
+ ...nodes,
+ {id: "c", box: "box", path: "/c.sy", type: "NodeDocument", size: 15, defs: 0},
+ {id: "d", box: "box", path: "/d.sy", type: "NodeDocument", size: 15, defs: 0},
+ ], [
+ {from: "a", to: "b", ref: true},
+ {from: "c", to: "d", ref: true},
+ ], 15);
+ const positions = createInitialPositions(data, 400);
+ assert.equal(data.components.length, 2);
+ const firstBounds = {
+ minX: Math.min(positions[0], positions[2]) - 15,
+ maxX: Math.max(positions[0], positions[2]) + 15,
+ minY: Math.min(positions[1], positions[3]) - 15,
+ maxY: Math.max(positions[1], positions[3]) + 15,
+ };
+ const secondBounds = {
+ minX: Math.min(positions[4], positions[6]) - 15,
+ maxX: Math.max(positions[4], positions[6]) + 15,
+ minY: Math.min(positions[5], positions[7]) - 15,
+ maxY: Math.max(positions[5], positions[7]) + 15,
+ };
+ assert.ok(firstBounds.maxX < secondBounds.minX || secondBounds.maxX < firstBounds.minX ||
+ firstBounds.maxY < secondBounds.minY || secondBounds.maxY < firstBounds.minY);
+ });
+
+ it("scatters isolated nodes radially without forming rows", () => {
+ const isolatedNodes = Array.from({length: 128}, (_item, index) => ({
+ id: `isolated-${index.toString().padStart(3, "0")}`,
+ box: "box",
+ path: `/${index}.sy`,
+ type: "NodeDocument",
+ size: 15,
+ defs: 0,
+ }));
+ const data = normalizeGraphData(isolatedNodes, [], 15);
+ const positions = createInitialPositions(data, 100);
+ const uniqueY = new Set<number>();
+ for (let index = 0; index < isolatedNodes.length; index++) {
+ uniqueY.add(positions[index * 2 + 1]);
+ }
+ assert.ok(uniqueY.size > isolatedNodes.length / 2);
+ });
+
it("fits positions into the available viewport", () => {
const camera = fitGraphCamera(new Float32Array([-100, 0, 100, 0]), new Float32Array([10, 10]), 400, 200);
assert.ok(camera.scale > 0);
@@ -66,7 +112,7 @@ describe("graph data normalization", () => {
});
it("emphasizes highlighted edges without exceeding valid opacity", () => {
- assert.ok(Math.abs(getGraphEdgeOpacity(0.36, false) - 0.45) < Number.EPSILON);
+ assert.equal(getGraphEdgeOpacity(0.36, false), 0.36);
assert.ok(Math.abs(getGraphEdgeOpacity(0.36, true) - 0.9) < Number.EPSILON);
assert.equal(getGraphEdgeOpacity(0.8, true), 1);
assert.equal(getGraphEdgeOpacity(-0.5, false), 0);
diff --git a/app/src/layout/dock/graph/core.ts b/app/src/layout/dock/graph/core.ts
index db22919ed9..683fbb865a 100644
--- a/app/src/layout/dock/graph/core.ts
+++ b/app/src/layout/dock/graph/core.ts
@@ -8,12 +8,11 @@ import {
} from "./types";
const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
-const EDGE_OPACITY_FACTOR = 1.25;
const HIGHLIGHT_EDGE_OPACITY_FACTOR = 2.5;
-export const MIN_GRAPH_EDGE_WIDTH = 1.5;
+export const MIN_GRAPH_EDGE_WIDTH = 1;
export const getGraphEdgeOpacity = (lineOpacity: number, highlighted: boolean) =>
- Math.max(0, Math.min(1, lineOpacity * (highlighted ? HIGHLIGHT_EDGE_OPACITY_FACTOR : EDGE_OPACITY_FACTOR)));
+ Math.max(0, Math.min(1, lineOpacity * (highlighted ? HIGHLIGHT_EDGE_OPACITY_FACTOR : 1)));
export const getGraphNodeSize = (baseSize: number, definitions: number) => {
if (definitions < 1) {
@@ -64,6 +63,48 @@ export const normalizeGraphData = (
}
links.sort((left, right) => left.source - right.source || left.target - right.target ||
Number(left.ref) - Number(right.ref));
+ const parents = new Uint32Array(nodes.length);
+ const ranks = new Uint8Array(nodes.length);
+ nodes.forEach((_node, index) => {
+ parents[index] = index;
+ });
+ const findRoot = (index: number) => {
+ let root = index;
+ while (parents[root] !== root) {
+ root = parents[root];
+ }
+ while (parents[index] !== index) {
+ const parent = parents[index];
+ parents[index] = root;
+ index = parent;
+ }
+ return root;
+ };
+ links.forEach((link) => {
+ let sourceRoot = findRoot(link.source);
+ let targetRoot = findRoot(link.target);
+ if (sourceRoot === targetRoot) {
+ return;
+ }
+ if (ranks[sourceRoot] < ranks[targetRoot]) {
+ [sourceRoot, targetRoot] = [targetRoot, sourceRoot];
+ }
+ parents[targetRoot] = sourceRoot;
+ if (ranks[sourceRoot] === ranks[targetRoot]) {
+ ranks[sourceRoot]++;
+ }
+ });
+ const nodesByRoot = new Map<number, number[]>();
+ nodes.forEach((_node, index) => {
+ const root = findRoot(index);
+ const nodeIndices = nodesByRoot.get(root) || [];
+ nodeIndices.push(index);
+ nodesByRoot.set(root, nodeIndices);
+ });
+ const components = Array.from(nodesByRoot.values()).map((nodeIndices) => ({
+ key: nodes[nodeIndices[0]].id,
+ nodeIndices,
+ })).sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0);
const sources = new Uint32Array(links.length);
const targets = new Uint32Array(links.length);
@@ -83,6 +124,7 @@ export const normalizeGraphData = (
return {
nodes,
links,
+ components,
indexById,
sources,
targets,
@@ -101,22 +143,249 @@ const hashString = (value: string) => {
return hash >>> 0;
};
-export const createInitialPositions = (data: IGraphData, linkDistance: number, previous?: Map<string, [number, number]>) => {
+const pseudoRandom = (value: number) => {
+ let hash = value + 0x6d2b79f5;
+ hash = Math.imul(hash ^ hash >>> 15, hash | 1);
+ hash ^= hash + Math.imul(hash ^ hash >>> 7, hash | 61);
+ return ((hash ^ hash >>> 14) >>> 0) / 4294967296;
+};
+
+interface IGraphBounds {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+}
+
+interface IGraphComponentPlacement extends IGraphBounds {
+ fixed: boolean;
+ key: string;
+ nodeIndices: number[];
+ packingMaxX: number;
+ packingMaxY: number;
+ packingMinX: number;
+ packingMinY: number;
+}
+
+interface IGraphPackingIndex {
+ bounds: IGraphBounds[];
+ cells: Map<string, number[]>;
+ cellSize: number;
+}
+
+const getGraphBounds = (nodeIndices: number[], positions: Float32Array, sizes: Float32Array): IGraphBounds => {
+ let minX = Number.POSITIVE_INFINITY;
+ let minY = Number.POSITIVE_INFINITY;
+ let maxX = Number.NEGATIVE_INFINITY;
+ let maxY = Number.NEGATIVE_INFINITY;
+ nodeIndices.forEach((nodeIndex) => {
+ const offset = nodeIndex * 2;
+ const radius = sizes[nodeIndex];
+ minX = Math.min(minX, positions[offset] - radius);
+ minY = Math.min(minY, positions[offset + 1] - radius);
+ maxX = Math.max(maxX, positions[offset] + radius);
+ maxY = Math.max(maxY, positions[offset + 1] + radius);
+ });
+ return {minX, minY, maxX, maxY};
+};
+
+const translateGraphNodes = (
+ nodeIndices: number[],
+ positions: Float32Array,
+ deltaX: number,
+ deltaY: number,
+) => {
+ nodeIndices.forEach((nodeIndex) => {
+ const offset = nodeIndex * 2;
+ positions[offset] += deltaX;
+ positions[offset + 1] += deltaY;
+ });
+};
+
+const getPackingCellKey = (x: number, y: number) => `${x}:${y}`;
+
+const addPackingBounds = (index: IGraphPackingIndex, bounds: IGraphBounds) => {
+ const boundsIndex = index.bounds.length;
+ index.bounds.push(bounds);
+ const minCellX = Math.floor(bounds.minX / index.cellSize);
+ const minCellY = Math.floor(bounds.minY / index.cellSize);
+ const maxCellX = Math.floor(bounds.maxX / index.cellSize);
+ const maxCellY = Math.floor(bounds.maxY / index.cellSize);
+ for (let cellX = minCellX; cellX <= maxCellX; cellX++) {
+ for (let cellY = minCellY; cellY <= maxCellY; cellY++) {
+ const key = getPackingCellKey(cellX, cellY);
+ const cell = index.cells.get(key) || [];
+ cell.push(boundsIndex);
+ index.cells.set(key, cell);
+ }
+ }
+};
+
+const hasPackingOverlap = (index: IGraphPackingIndex, bounds: IGraphBounds) => {
+ const minCellX = Math.floor(bounds.minX / index.cellSize);
+ const minCellY = Math.floor(bounds.minY / index.cellSize);
+ const maxCellX = Math.floor(bounds.maxX / index.cellSize);
+ const maxCellY = Math.floor(bounds.maxY / index.cellSize);
+ const checked = new Set<number>();
+ for (let cellX = minCellX; cellX <= maxCellX; cellX++) {
+ for (let cellY = minCellY; cellY <= maxCellY; cellY++) {
+ const cell = index.cells.get(getPackingCellKey(cellX, cellY));
+ if (!cell) {
+ continue;
+ }
+ for (const boundsIndex of cell) {
+ if (checked.has(boundsIndex)) {
+ continue;
+ }
+ checked.add(boundsIndex);
+ const placed = index.bounds[boundsIndex];
+ if (bounds.minX < placed.maxX && bounds.maxX > placed.minX &&
+ bounds.minY < placed.maxY && bounds.maxY > placed.minY) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+};
+
+export const createInitialPositions = (
+ data: IGraphData,
+ linkDistance: number,
+ previous?: Map<string, [number, number]>,
+) => {
const positions = new Float32Array(data.nodes.length * 2);
const spacing = Math.max(24, linkDistance * 0.35);
- data.nodes.forEach((node, index) => {
- const saved = previous?.get(node.id);
- if (saved) {
- positions[index * 2] = saved[0];
- positions[index * 2 + 1] = saved[1];
- return;
+ const placements: IGraphComponentPlacement[] = data.components.map((component) => {
+ const savedNodes: number[] = [];
+ let centerX = 0;
+ let centerY = 0;
+ component.nodeIndices.forEach((nodeIndex) => {
+ const saved = previous?.get(data.nodes[nodeIndex].id);
+ if (!saved || !Number.isFinite(saved[0]) || !Number.isFinite(saved[1])) {
+ return;
+ }
+ const offset = nodeIndex * 2;
+ positions[offset] = saved[0];
+ positions[offset + 1] = saved[1];
+ centerX += saved[0];
+ centerY += saved[1];
+ savedNodes.push(nodeIndex);
+ });
+ const fixed = savedNodes.length > 0;
+ const savedSet = new Set(savedNodes);
+ if (fixed) {
+ centerX /= savedNodes.length;
+ centerY /= savedNodes.length;
+ let savedRadius = spacing;
+ savedNodes.forEach((nodeIndex) => {
+ const offset = nodeIndex * 2;
+ savedRadius = Math.max(savedRadius, Math.hypot(
+ positions[offset] - centerX,
+ positions[offset + 1] - centerY,
+ ) + data.sizes[nodeIndex]);
+ });
+ let added = 0;
+ component.nodeIndices.forEach((nodeIndex) => {
+ if (savedSet.has(nodeIndex)) {
+ return;
+ }
+ const hash = hashString(data.nodes[nodeIndex].id);
+ const angle = added * GOLDEN_ANGLE + (hash % 1024) / 1024;
+ const radius = savedRadius + Math.sqrt(++added) * spacing;
+ positions[nodeIndex * 2] = centerX + Math.cos(angle) * radius;
+ positions[nodeIndex * 2 + 1] = centerY + Math.sin(angle) * radius;
+ });
+ } else {
+ const orderedNodes = component.nodeIndices.slice().sort((left, right) =>
+ data.degrees[right] - data.degrees[left] || left - right);
+ orderedNodes.forEach((nodeIndex, localIndex) => {
+ if (localIndex === 0) {
+ return;
+ }
+ const hash = hashString(data.nodes[nodeIndex].id);
+ const angle = (localIndex - 1) * GOLDEN_ANGLE + (hash % 1024) / 1024;
+ const radius = Math.sqrt(localIndex) * spacing;
+ positions[nodeIndex * 2] = Math.cos(angle) * radius;
+ positions[nodeIndex * 2 + 1] = Math.sin(angle) * radius;
+ });
+ const bounds = getGraphBounds(component.nodeIndices, positions, data.sizes);
+ const centerX = (bounds.minX + bounds.maxX) / 2;
+ const centerY = (bounds.minY + bounds.maxY) / 2;
+ translateGraphNodes(component.nodeIndices, positions, -centerX, -centerY);
}
- const hash = hashString(node.id);
- const angle = index * GOLDEN_ANGLE + (hash % 1024) / 1024;
- const radius = Math.sqrt(index + 1) * spacing;
- positions[index * 2] = Math.cos(angle) * radius;
- positions[index * 2 + 1] = Math.sin(angle) * radius;
+ const bounds = getGraphBounds(component.nodeIndices, positions, data.sizes);
+ const padding = component.nodeIndices.length > 1 ? Math.max(48, linkDistance * 0.75) :
+ Math.max(12, data.sizes[component.nodeIndices[0]] * 1.5);
+ return {
+ ...bounds,
+ fixed,
+ key: component.key,
+ nodeIndices: component.nodeIndices,
+ packingMaxX: bounds.maxX + padding,
+ packingMaxY: bounds.maxY + padding,
+ packingMinX: bounds.minX - padding,
+ packingMinY: bounds.minY - padding,
+ };
});
+
+ const fixedPlacements = placements.filter((placement) => placement.fixed);
+ const movablePlacements = placements.filter((placement) => !placement.fixed).sort((left, right) => {
+ const leftArea = (left.packingMaxX - left.packingMinX) * (left.packingMaxY - left.packingMinY);
+ const rightArea = (right.packingMaxX - right.packingMinX) * (right.packingMaxY - right.packingMinY);
+ return rightArea - leftArea || (left.key < right.key ? -1 : left.key > right.key ? 1 : 0);
+ });
+ const fixedBounds = fixedPlacements.length > 0 ? getGraphBounds(
+ fixedPlacements.flatMap((placement) => placement.nodeIndices), positions, data.sizes,
+ ) : undefined;
+ const packingCenterX = fixedBounds ? (fixedBounds.minX + fixedBounds.maxX) / 2 : 0;
+ const packingCenterY = fixedBounds ? (fixedBounds.minY + fixedBounds.maxY) / 2 : 0;
+ const packingIndex: IGraphPackingIndex = {
+ bounds: [],
+ cells: new Map(),
+ cellSize: Math.max(64, linkDistance * 0.5),
+ };
+ fixedPlacements.forEach((placement) => {
+ addPackingBounds(packingIndex, {
+ minX: placement.packingMinX,
+ minY: placement.packingMinY,
+ maxX: placement.packingMaxX,
+ maxY: placement.packingMaxY,
+ });
+ });
+ let packingSequence = 0;
+ movablePlacements.forEach((placement) => {
+ const width = placement.packingMaxX - placement.packingMinX;
+ const height = placement.packingMaxY - placement.packingMinY;
+ let packedBounds: IGraphBounds;
+ while (true) {
+ const sequence = packingSequence++;
+ const angle = pseudoRandom(sequence * 2) * Math.PI * 2;
+ const radius = sequence === 0 ? 0 : spacing * Math.sqrt(sequence + pseudoRandom(sequence * 2 + 1));
+ const centerX = packingCenterX + Math.cos(angle) * radius;
+ const centerY = packingCenterY + Math.sin(angle) * radius;
+ packedBounds = {
+ minX: centerX - width / 2,
+ minY: centerY - height / 2,
+ maxX: centerX + width / 2,
+ maxY: centerY + height / 2,
+ };
+ if (!hasPackingOverlap(packingIndex, packedBounds)) {
+ break;
+ }
+ }
+ const deltaX = packedBounds.minX - placement.packingMinX;
+ const deltaY = packedBounds.minY - placement.packingMinY;
+ translateGraphNodes(placement.nodeIndices, positions, deltaX, deltaY);
+ addPackingBounds(packingIndex, packedBounds);
+ });
+ if (fixedPlacements.length === 0 && data.nodes.length > 0) {
+ const nodeIndices = data.nodes.map((_node, index) => index);
+ const bounds = getGraphBounds(nodeIndices, positions, data.sizes);
+ const deltaX = -(bounds.minX + bounds.maxX) / 2;
+ const deltaY = -(bounds.minY + bounds.maxY) / 2;
+ translateGraphNodes(nodeIndices, positions, deltaX, deltaY);
+ }
return positions;
};
diff --git a/app/src/layout/dock/graph/layoutCore.test.ts b/app/src/layout/dock/graph/layoutCore.test.ts
index 868c423c71..c40825abc9 100644
--- a/app/src/layout/dock/graph/layoutCore.test.ts
+++ b/app/src/layout/dock/graph/layoutCore.test.ts
@@ -1,5 +1,6 @@
import * as assert from "node:assert/strict";
import {describe, it} from "node:test";
+import {createInitialPositions, normalizeGraphData} from "./core";
import {GraphForceLayout} from "./layoutCore";
const createLayout = () => new GraphForceLayout({
@@ -37,6 +38,20 @@ describe("graph force layout", () => {
assert.notDeepEqual(Array.from(layout.positions.subarray(2, 4)), [25, 35]);
});
+ it("restarts a settled layout while dragging a node", () => {
+ const layout = createLayout();
+ assert.equal(layout.step(400), true);
+ const neighborBefore = Array.from(layout.positions.subarray(2, 4));
+ layout.pin(0, -400, 100);
+ assert.equal(layout.step(), false);
+ layout.step(20);
+ assert.deepEqual(Array.from(layout.positions.subarray(0, 2)), [-400, 100]);
+ assert.notDeepEqual(Array.from(layout.positions.subarray(2, 4)), neighborBefore);
+ layout.release(0);
+ layout.step(20);
+ assert.notDeepEqual(Array.from(layout.positions.subarray(0, 2)), [-400, 100]);
+ });
+
it("accepts updated physics options", () => {
const layout = createLayout();
layout.step(10);
@@ -50,7 +65,7 @@ describe("graph force layout", () => {
layout.positions.forEach((value) => assert.ok(Number.isFinite(value)));
});
- it("balances repulsion across different node masses", () => {
+ it("applies ForceAtlas2 degree weighting to repulsion", () => {
const layout = new GraphForceLayout({
degrees: new Uint32Array([0, 8]),
layout: {
@@ -65,14 +80,14 @@ describe("graph force layout", () => {
targets: new Uint32Array(),
});
layout.step();
- const lightDisplacement = -100 - layout.positions[0];
- const heavyDisplacement = layout.positions[2] - 100;
- assert.ok(Math.abs(lightDisplacement - heavyDisplacement * (1 + Math.sqrt(8))) < 0.0001);
+ const lowDegreeDisplacement = -100 - layout.positions[0];
+ const highDegreeDisplacement = layout.positions[2] - 100;
+ assert.ok(Math.abs(highDegreeDisplacement - lowDegreeDisplacement * 9) < 0.0001);
});
- it("pulls isolated nodes inward more strongly", () => {
+ it("pulls high-degree nodes toward the graph center more strongly", () => {
const layout = new GraphForceLayout({
- degrees: new Uint32Array([0, 1]),
+ degrees: new Uint32Array([0, 8]),
layout: {
centerStrength: 0.01,
linkDistance: 100,
@@ -87,6 +102,167 @@ describe("graph force layout", () => {
layout.step();
const isolatedDisplacement = 100 - layout.positions[0];
const connectedDisplacement = layout.positions[2] + 100;
- assert.ok(isolatedDisplacement > connectedDisplacement * 4);
+ assert.ok(Math.abs(connectedDisplacement - isolatedDisplacement * 9) < 0.0001);
+ });
+
+ it("uses the legacy straight-edge spring distance", () => {
+ const layout = new GraphForceLayout({
+ degrees: new Uint32Array([1, 1]),
+ layout: {
+ centerStrength: 0,
+ linkDistance: 100,
+ repulsion: 0,
+ springStrength: 0.08,
+ },
+ positions: new Float32Array([-75, 0, 75, 0]),
+ sizes: new Float32Array([15, 15]),
+ sources: new Uint32Array([0]),
+ targets: new Uint32Array([1]),
+ });
+ layout.step();
+ assert.deepEqual(Array.from(layout.positions), [-75, 0, 75, 0]);
+ });
+
+ it("keeps disconnected subgraphs in separate regions after settling", () => {
+ const nodes = Array.from({length: 12}, (_item, index) => ({
+ id: `node-${index.toString().padStart(2, "0")}`,
+ box: "box",
+ path: `/${index}.sy`,
+ type: "NodeDocument",
+ size: 15,
+ defs: 0,
+ }));
+ const links = [1, 2, 3, 4, 5].flatMap((target) => [
+ {from: nodes[0].id, to: nodes[target].id, ref: true},
+ {from: nodes[6].id, to: nodes[target + 6].id, ref: true},
+ ]);
+ const data = normalizeGraphData(nodes, links, 15);
+ const positions = createInitialPositions(data, 100);
+ const layout = new GraphForceLayout({
+ degrees: data.degrees,
+ layout: {
+ centerStrength: 0.01,
+ linkDistance: 100,
+ repulsion: 600,
+ springStrength: 0.08,
+ },
+ positions,
+ sizes: data.sizes,
+ sources: data.sources,
+ targets: data.targets,
+ });
+ layout.step(320);
+ const bounds = data.components.map((component) => {
+ const xs = component.nodeIndices.map((index) => layout.positions[index * 2]);
+ const ys = component.nodeIndices.map((index) => layout.positions[index * 2 + 1]);
+ return {
+ minX: Math.min(...xs) - 15,
+ maxX: Math.max(...xs) + 15,
+ minY: Math.min(...ys) - 15,
+ maxY: Math.max(...ys) + 15,
+ };
+ });
+ assert.ok(bounds[0].maxX < bounds[1].minX || bounds[1].maxX < bounds[0].minX ||
+ bounds[0].maxY < bounds[1].minY || bounds[1].maxY < bounds[0].minY);
+ });
+
+ it("keeps isolated nodes around connected clusters", () => {
+ const connectedCount = 20;
+ const nodes = Array.from({length: 100}, (_item, index) => ({
+ id: `node-${index.toString().padStart(3, "0")}`,
+ box: "box",
+ path: `/${index}.sy`,
+ type: "NodeDocument",
+ size: 15,
+ defs: 0,
+ }));
+ const links = Array.from({length: connectedCount - 1}, (_item, index) => ({
+ from: nodes[0].id,
+ to: nodes[index + 1].id,
+ ref: true,
+ }));
+ const data = normalizeGraphData(nodes, links, 15);
+ const layout = new GraphForceLayout({
+ degrees: data.degrees,
+ layout: {
+ centerStrength: 0.01,
+ linkDistance: 100,
+ repulsion: 600,
+ springStrength: 0.08,
+ },
+ positions: createInitialPositions(data, 100),
+ sizes: data.sizes,
+ sources: data.sources,
+ targets: data.targets,
+ });
+ layout.step(320);
+ const averageRadius = (start: number, end: number) => {
+ let radius = 0;
+ for (let index = start; index < end; index++) {
+ radius += Math.hypot(layout.positions[index * 2], layout.positions[index * 2 + 1]);
+ }
+ return radius / (end - start);
+ };
+ const connectedRadius = averageRadius(0, connectedCount);
+ const isolatedRadius = averageRadius(connectedCount, nodes.length);
+ assert.ok(isolatedRadius > connectedRadius * 1.5, JSON.stringify({connectedRadius, isolatedRadius}));
+ });
+
+ it("separates dense communities connected by a single edge", () => {
+ const nodes = Array.from({length: 10}, (_item, index) => ({
+ id: `community-${index.toString().padStart(2, "0")}`,
+ box: "box",
+ path: `/${index}.sy`,
+ type: "NodeDocument",
+ size: 15,
+ defs: 0,
+ }));
+ const links: {from: string, to: string, ref: boolean}[] = [];
+ for (const start of [0, 5]) {
+ for (let source = start; source < start + 5; source++) {
+ for (let target = source + 1; target < start + 5; target++) {
+ links.push({from: nodes[source].id, to: nodes[target].id, ref: true});
+ }
+ }
+ }
+ links.push({from: nodes[0].id, to: nodes[5].id, ref: true});
+ const data = normalizeGraphData(nodes, links, 15);
+ const positions = createInitialPositions(data, 100);
+ const layout = new GraphForceLayout({
+ degrees: data.degrees,
+ layout: {
+ centerStrength: 0.01,
+ linkDistance: 100,
+ repulsion: 600,
+ springStrength: 0.08,
+ },
+ positions,
+ sizes: data.sizes,
+ sources: data.sources,
+ targets: data.targets,
+ });
+ layout.step(320);
+ const getCommunity = (start: number) => {
+ let centerX = 0;
+ let centerY = 0;
+ for (let index = start; index < start + 5; index++) {
+ centerX += layout.positions[index * 2];
+ centerY += layout.positions[index * 2 + 1];
+ }
+ centerX /= 5;
+ centerY /= 5;
+ let radius = 0;
+ for (let index = start; index < start + 5; index++) {
+ radius = Math.max(radius, Math.hypot(
+ layout.positions[index * 2] - centerX,
+ layout.positions[index * 2 + 1] - centerY,
+ ));
+ }
+ return {centerX, centerY, radius};
+ };
+ const first = getCommunity(0);
+ const second = getCommunity(5);
+ const centerDistance = Math.hypot(first.centerX - second.centerX, first.centerY - second.centerY);
+ assert.ok(centerDistance > first.radius + second.radius, JSON.stringify({centerDistance, first, second}));
});
});
diff --git a/app/src/layout/dock/graph/layoutCore.ts b/app/src/layout/dock/graph/layoutCore.ts
index 3c4b8bac26..a3353b34e8 100644
--- a/app/src/layout/dock/graph/layoutCore.ts
+++ b/app/src/layout/dock/graph/layoutCore.ts
@@ -3,13 +3,12 @@ import {IGraphLayoutOptions} from "./types";
const TREE_THETA_SQUARED = 0.25;
const MAX_TREE_DEPTH = 32;
const STABLE_TICKS = 12;
-const ISOLATED_CENTER_STRENGTH_FACTOR = 3;
+const LEGACY_LINK_DISTANCE_FACTOR = 1.5;
export class GraphForceLayout {
public readonly positions: Float32Array;
private readonly degrees: Uint32Array;
private readonly forces: Float32Array;
- private readonly masses: Float32Array;
private readonly pinned: Uint8Array;
private readonly pinnedPositions: Float32Array;
private readonly sizes: Float32Array;
@@ -46,12 +45,8 @@ export class GraphForceLayout {
this.targets = options.targets;
this.forces = new Float32Array(this.positions.length);
this.velocities = new Float32Array(this.positions.length);
- this.masses = new Float32Array(this.sizes.length);
this.pinned = new Uint8Array(this.sizes.length);
this.pinnedPositions = new Float32Array(this.positions.length);
- for (let index = 0; index < this.masses.length; index++) {
- this.masses[index] = 1 + Math.sqrt(this.degrees[index]);
- }
const treeCapacity = Math.max(16, this.sizes.length * 4 + 1);
this.treeBodies = new Int32Array(treeCapacity);
this.treeCentersX = new Float64Array(treeCapacity);
@@ -83,6 +78,7 @@ export class GraphForceLayout {
this.positions[index * 2 + 1] = y;
this.velocities[index * 2] = 0;
this.velocities[index * 2 + 1] = 0;
+ this.restart();
}
public release(index: number) {
@@ -119,7 +115,7 @@ export class GraphForceLayout {
this.applySprings();
const nodeCount = this.sizes.length;
const timestep = nodeCount > 2048 ? 0.12 : nodeCount > 256 ? 0.18 : 0.25;
- const damping = 0.6;
+ const damping = 0.4;
const maxVelocity = Math.max(24, this.options.linkDistance * 0.25);
let velocityTotal = 0;
for (let index = 0; index < nodeCount; index++) {
@@ -131,12 +127,14 @@ export class GraphForceLayout {
this.velocities[offset + 1] = 0;
continue;
}
- const centerStrength = this.options.centerStrength *
- (this.degrees[index] === 0 ? ISOLATED_CENTER_STRENGTH_FACTOR : 1);
+ const degreeWeight = this.degrees[index] + 1;
+ const centerStrength = this.options.centerStrength * degreeWeight;
this.forces[offset] -= this.positions[offset] * centerStrength;
this.forces[offset + 1] -= this.positions[offset + 1] * centerStrength;
- let velocityX = (this.velocities[offset] + this.forces[offset] / this.masses[index] * timestep) * damping;
- let velocityY = (this.velocities[offset + 1] + this.forces[offset + 1] / this.masses[index] * timestep) * damping;
+ let velocityX = this.velocities[offset] +
+ (this.forces[offset] - damping * this.velocities[offset]) * timestep;
+ let velocityY = this.velocities[offset + 1] +
+ (this.forces[offset + 1] - damping * this.velocities[offset + 1]) * timestep;
const velocity = Math.hypot(velocityX, velocityY);
if (velocity > maxVelocity) {
const ratio = maxVelocity / velocity;
@@ -160,6 +158,7 @@ export class GraphForceLayout {
}
private applySprings() {
+ const linkDistance = this.options.linkDistance * LEGACY_LINK_DISTANCE_FACTOR;
for (let index = 0; index < this.sources.length; index++) {
const source = this.sources[index];
const target = this.targets[index];
@@ -168,7 +167,7 @@ export class GraphForceLayout {
const deltaX = this.positions[targetOffset] - this.positions[sourceOffset];
const deltaY = this.positions[targetOffset + 1] - this.positions[sourceOffset + 1];
const distance = Math.max(0.001, Math.hypot(deltaX, deltaY));
- const force = (distance - this.options.linkDistance) * this.options.springStrength;
+ const force = (distance - linkDistance) * this.options.springStrength;
const forceX = deltaX / distance * force;
const forceY = deltaY / distance * force;
this.forces[sourceOffset] += forceX;
@@ -181,7 +180,7 @@ export class GraphForceLayout {
private applyRepulsion() {
for (let body = 0; body < this.sizes.length; body++) {
const bodyOffset = body * 2;
- const bodyMass = this.masses[body];
+ const degreeWeight = this.degrees[body] + 1;
const bodyX = this.positions[bodyOffset];
const bodyY = this.positions[bodyOffset + 1];
let stackLength = 1;
@@ -202,11 +201,11 @@ export class GraphForceLayout {
const width = this.treeHalves[cell] * 2;
if (cellBody >= 0 || width * width / distanceSquared < TREE_THETA_SQUARED) {
const distance = Math.sqrt(distanceSquared);
- let force = this.options.repulsion * bodyMass * mass / distanceSquared;
+ let force = this.options.repulsion * degreeWeight * mass / distanceSquared;
if (cellBody >= 0) {
const minimumDistance = (this.sizes[body] + this.sizes[cellBody]) * 1.2;
if (distance < minimumDistance) {
- force += (minimumDistance - distance) * 0.5 * bodyMass * this.masses[cellBody] / distance;
+ force += (minimumDistance - distance) * 0.5 * degreeWeight / distance;
}
}
this.forces[bodyOffset] += deltaX * force;
@@ -244,7 +243,7 @@ export class GraphForceLayout {
for (let cell = this.treeCount - 1; cell >= 0; cell--) {
const body = this.treeBodies[cell];
if (body >= 0) {
- this.treeMasses[cell] = this.masses[body];
+ this.treeMasses[cell] = 1;
this.treePointsX[cell] = this.positions[body * 2];
this.treePointsY[cell] = this.positions[body * 2 + 1];
continue;
diff --git a/app/src/layout/dock/graph/layoutWorker.ts b/app/src/layout/dock/graph/layoutWorker.ts
index feab8baf04..465482ce4b 100644
--- a/app/src/layout/dock/graph/layoutWorker.ts
+++ b/app/src/layout/dock/graph/layoutWorker.ts
@@ -8,6 +8,7 @@ type TWorkerScope = {
const workerScope = globalThis as unknown as TWorkerScope;
let generation = 0;
+let interactive = false;
let layout: GraphForceLayout;
let paused = false;
let scheduled = false;
@@ -43,10 +44,11 @@ const run = () => {
do {
settled = layout.step();
} while (!settled && performance.now() - start < 12);
- if (settled || performance.now() - lastPosted >= 32) {
+ if (settled || performance.now() - lastPosted >= (interactive ? 16 : 32)) {
postPositions(settled);
}
if (settled) {
+ interactive = false;
stopped = true;
return;
}
@@ -70,6 +72,7 @@ workerScope.onmessage = (event) => {
sources: message.sources,
targets: message.targets,
});
+ interactive = false;
paused = false;
lastPosted = 0;
restart();
@@ -83,8 +86,17 @@ workerScope.onmessage = (event) => {
restart();
} else if (message.type === "pin") {
layout.pin(message.index, message.x, message.y);
+ interactive = true;
+ restart();
} else if (message.type === "release") {
layout.release(message.index);
+ interactive = true;
+ workerScope.postMessage({
+ type: "released",
+ generation,
+ index: message.index,
+ token: message.token,
+ }, []);
restart();
} else if (message.type === "pause") {
paused = true;
diff --git a/app/src/layout/dock/graph/types.ts b/app/src/layout/dock/graph/types.ts
index 60d1d38568..e7cb6245bb 100644
--- a/app/src/layout/dock/graph/types.ts
+++ b/app/src/layout/dock/graph/types.ts
@@ -27,9 +27,15 @@ export interface IGraphLink {
ref: boolean;
}
+export interface IGraphComponent {
+ key: string;
+ nodeIndices: number[];
+}
+
export interface IGraphData {
nodes: IGraphNode[];
links: IGraphLink[];
+ components: IGraphComponent[];
indexById: Map<string, number>;
sources: Uint32Array;
targets: Uint32Array;
@@ -116,6 +122,7 @@ export type TGraphLayoutRequest = {
type: "release";
generation: number;
index: number;
+ token: number;
} | {
type: "pause" | "resume" | "stop";
generation: number;
@@ -126,4 +133,9 @@ export type TGraphLayoutResponse = {
generation: number;
positions: Float32Array;
settled: boolean;
+} | {
+ type: "released";
+ generation: number;
+ index: number;
+ token: number;
};