Appearance
Weakly connected components
This example shows how to use the getConnectedComponents method to compute the weakly-connected components of a graph and use them to style it.
Click on a node to highlight its weakly-connected component.
ts
import Ogma from '@linkurious/ogma';
const ogma = new Ogma({
container: 'graph-container',
options: {
interactions: { selection: { enabled: false } },
backgroundColor: '#f0f0f0'
}
});
const getRandomColor = () => {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
const graph = await ogma.generate.random({
nodes: 100,
edges: 50
});
await ogma.setGraph(graph);
await ogma.removeNodes(ogma.getNodes().filter(n => n.getDegree() === 0));
ogma.getConnectedComponents().forEach(component => {
component.fillData('color', getRandomColor());
});
ogma.styles.addRule({
nodeAttributes: {
color: node => node.getData('color'),
radius: 10
},
nodeDependencies: {
self: { attributes: 'all' }
}
});
await ogma.layouts.force({ locate: true, duration: 0 });
ogma.events.on('click', evt => {
ogma.clearSelection();
if (evt.target && evt.target.isNode) {
evt.target.getConnectedComponent().setSelected(true);
}
});
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>
<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;
}