Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 57 additions & 18 deletions modules/graph-layers/src/layouts/d3-force/d3-force-layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,23 +50,30 @@ export class D3ForceLayout extends GraphLayout<D3ForceLayoutOptions> {
}

start() {
this._engageWorker();

this._onLayoutStart();
this._engageWorker();
}

update() {
this._onLayoutStart();
this._engageWorker();
}

_engageWorker() {
_engageWorker(isResume = false) {
// prevent multiple start
if (this._worker) {
this._worker.terminate();
}

this._worker = new Worker(new URL('./worker.js', import.meta.url).href);

const options = isResume
? {
...this.props,
alpha: this.props.resumeAlpha
}
: this.props;

this._worker.postMessage({
nodes: this._graph.getNodes().map((node) => ({
id: node.id,
Expand All @@ -77,30 +84,31 @@ export class D3ForceLayout extends GraphLayout<D3ForceLayoutOptions> {
source: edge.getSourceNodeId(),
target: edge.getTargetNodeId()
})),
options: this.props
options
});

this._worker.onmessage = (event) => {
log.log(0, 'D3ForceLayout: worker message', event.data?.type, event.data);
if (event.data.type !== 'end') {
return;
const {type} = event.data ?? {};
switch (type) {
case 'tick':
this._refreshCachedPositions(event.data.nodes);
this._onLayoutChange();
break;
case 'end':
this._refreshCachedPositions(event.data.nodes);
this._onLayoutChange();
this._onLayoutDone();
break;
default:
break;
}

event.data.nodes.forEach(({id, ...d3}) =>
this._positionsByNodeId.set(id, {
...d3,
// precompute so that when we return the node position we do not need to do the conversion
coordinates: [d3.x, d3.y]
})
);

this._onLayoutChange();
this._onLayoutDone();
};
}

resume() {
throw new Error('Resume unavailable');
this._onLayoutStart();
this._engageWorker(true);
}

stop() {
Expand Down Expand Up @@ -165,6 +173,37 @@ export class D3ForceLayout extends GraphLayout<D3ForceLayoutOptions> {
d3Node.fy = null;
};

private _refreshCachedPositions(nodes?: Array<{id: string | number}>) {
if (!Array.isArray(nodes)) {
return;
}

nodes.forEach((node) => {
if (!node || node.id === undefined) {
return;
}

const {id, ...rest} = node as {id: string | number; x?: number; y?: number};
const existing = this._positionsByNodeId.get(id) ?? {};
const next = {
...existing,
...rest
} as {
x?: number;
y?: number;
coordinates?: [number, number];
};

if (typeof next.x === 'number' && Number.isFinite(next.x) && typeof next.y === 'number' && Number.isFinite(next.y)) {
next.coordinates = [next.x, next.y];
} else if (existing.coordinates) {
next.coordinates = existing.coordinates;
}

this._positionsByNodeId.set(id, next);
});
}

protected override _updateBounds(): void {
const positions = Array.from(
this._positionsByNodeId.values(),
Expand Down
145 changes: 145 additions & 0 deletions modules/graph-layers/test/core/graph-engine-layout-events.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// deck.gl-community
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors

import {describe, it, expect} from 'vitest';

import type {Bounds2D} from '@math.gl/types';

import {GraphEngine} from '../../src/core/graph-engine';
import {GraphLayout, type GraphLayoutEventDetail} from '../../src/core/graph-layout';
import type {Graph, EdgeInterface, NodeInterface} from '../../src/graph/graph';
import type {GraphStyleEngine, GraphStylesheet} from '../../src/style/graph-style-engine';

class TestGraph extends EventTarget implements Graph {
version = 0;

constructor(
private readonly nodes: NodeInterface[] = [],
private readonly edges: EdgeInterface[] = []
) {
super();
}

getNodes(): Iterable<NodeInterface> {
return this.nodes;
}

getEdges(): Iterable<EdgeInterface> {
return this.edges;
}

// eslint-disable-next-line class-methods-use-this
createStylesheetEngine(_style: GraphStylesheet, _options?: {stateUpdateTrigger?: unknown}): GraphStyleEngine {
throw new Error('Not implemented in tests.');
}
}

class LifecycleLayout extends GraphLayout {
public startCalls = 0;
public updateCalls = 0;
public resumeCalls = 0;
public updateGraphCalls = 0;

constructor() {
super({}, {});
}

initializeGraph(): void {}

updateGraph(): void {
this.updateGraphCalls += 1;
}

start(): void {
this.startCalls += 1;
this._emitLifecycleCycle();
}

update(): void {
this.updateCalls += 1;
this._emitLifecycleCycle();
}

resume(): void {
this.resumeCalls += 1;
this._emitLifecycleCycle();
}

stop(): void {}

private _emitLifecycleCycle() {
this._onLayoutStart();
this._onLayoutChange();
this._onLayoutDone();
}
}

type CapturedEvent = {
type: 'start' | 'change' | 'done';
bounds?: Bounds2D | null;
};

function recordEngineEvents(engine: GraphEngine): CapturedEvent[] {
const events: CapturedEvent[] = [];
const handler = (type: CapturedEvent['type']) => (event: Event) => {
const detail = event instanceof CustomEvent ? (event.detail as GraphLayoutEventDetail) : undefined;
events.push({type, bounds: detail?.bounds});
};

engine.addEventListener('onLayoutStart', handler('start'));
engine.addEventListener('onLayoutChange', handler('change'));
engine.addEventListener('onLayoutDone', handler('done'));

return events;
}

describe('GraphEngine layout lifecycle events', () => {
it('emits start/change/done in order on initial run', () => {
const graph = new TestGraph();
const layout = new LifecycleLayout();
const engine = new GraphEngine({graph, layout});

const events = recordEngineEvents(engine);

engine.run();

expect(events.map((event) => event.type)).toEqual(['start', 'change', 'done']);
expect(layout.startCalls).toBe(1);
expect(layout.updateCalls).toBe(0);
expect(layout.resumeCalls).toBe(0);
});

it('emits start/change/done when the graph updates', () => {
const graph = new TestGraph();
const layout = new LifecycleLayout();
const engine = new GraphEngine({graph, layout});

const events = recordEngineEvents(engine);

engine.run();
events.length = 0;

graph.dispatchEvent(new Event('onNodeAdded'));

expect(layout.updateGraphCalls).toBe(1);
expect(layout.updateCalls).toBe(1);
expect(events.map((event) => event.type)).toEqual(['start', 'change', 'done']);
});

it('emits start/change/done when resuming the layout', () => {
const graph = new TestGraph();
const layout = new LifecycleLayout();
const engine = new GraphEngine({graph, layout});

const events = recordEngineEvents(engine);

engine.run();
events.length = 0;

engine.resume();

expect(layout.resumeCalls).toBe(1);
expect(events.map((event) => event.type)).toEqual(['start', 'change', 'done']);
});
});

This file was deleted.