Appearance
Incremental expand
This example shows how to use the incremental
parametter in the force layout. It allows to easilly add nodes to the graph without moving the existing topology.
ts
import Ogma, { NodeId, EdgeId, RawGraph } from '@linkurious/ogma';
const ogma = new Ogma({
container: 'graph-container'
});
const duration = 500;
// Generates graph with high-degree nodes
const generateDenseTree = (
startNodeId: NodeId,
startEdgeId: EdgeId,
N: number,
maxR = 10,
minR = 5
): Promise<RawGraph> => {
return new Promise(resolve => {
const nodes = new Array(N).fill(0).map((_, i) => {
return {
id: +startNodeId + i,
attributes: {
text: 'Node #' + i,
radius: minR + Math.random() * (maxR - minR),
x: -50 + Math.random() * 100,
y: -50 + Math.random() * 100
}
};
});
const edges = new Array(N - 1).fill(0).map((_, i) => {
return {
id: +startEdgeId + i,
source: +startNodeId + Math.floor(Math.sqrt(i) / 2),
target: +startNodeId + i + 1
};
});
resolve({ nodes: nodes, edges: edges });
});
};
document.getElementById('add')!.addEventListener('click', () => {
const nodes = ogma.getNodes();
const root = nodes.get(Math.floor(nodes.size * Math.random()));
const rootPos = root.getPosition();
generateDenseTree(ogma.getNodes().size, ogma.getEdges().size, 20)
.then(g => {
g.edges.push({ source: root.getId(), target: g.nodes[0].id! });
return ogma.addGraph(g);
})
.then(g => g.nodes.setAttributes(rootPos))
.then(nodes =>
ogma.layouts.force({
incremental: true,
nodes: nodes,
duration: duration || 0,
locate: true
})
);
});
// generate graph and collapse the nodes
generateDenseTree(0, 0, 20)
.then(graph => ogma.setGraph(graph))
.then(() => ogma.layouts.force())
.then(() => ogma.view.locateGraph());
html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="graph-container"></div>
<button id="add">Add nodes</button>
<script type="module" src="index.ts"></script>
</body>
</html>
css
#graph-container {
top: 0;
bottom: 0;
left: 0;
right: 0;
position: absolute;
margin: 0;
overflow: hidden;
}
#add {
position: absolute;
top: 20px;
right: 20px;
}