Appearance
Neighborhood highlight
This example shows how to retrieve nodes and edges neighbors, ei connected elements. It uses getAdjacentNodes and getAdjacentEdges methods. Hover a node with your cursor, its direct neighbors will be highlighted in red and its neighbors' neighbors in orange.
ts
import Ogma from '@linkurious/ogma';
const ogma = new Ogma({
container: 'graph-container'
});
ogma.styles.createClass({ name: 'sourceNode' });
// Create a class for 1st step neighbors
ogma.styles.createClass({
name: 'neighbor1',
nodeAttributes: {
color: 'red',
radius: 7,
icon: {
color: 'white',
content: '1'
},
layer: 5
},
edgeAttributes: {
color: 'red'
}
});
// Create a class for 1st step neighbors
ogma.styles.createClass({
name: 'neighbor2',
nodeAttributes: {
color: 'orange',
radius: 4,
icon: {
color: 'white',
content: '2'
},
layer: 5
},
edgeAttributes: {
color: 'orange'
}
});
ogma.generate
.erdosRenyi({ nodes: 20, p: 0.1 })
.then(graph => ogma.setGraph(graph))
.then(() => ogma.view.locateGraph());
ogma.events.on('mouseover', async ({ target }) => {
if (!target || !target.isNode) return;
const node = target;
await node.addClass('sourceNode');
await node.getAdjacentNodes().addClass('neighbor1');
await node.getAdjacentEdges().addClass('neighbor1');
await node
.getAdjacentNodes()
.getAdjacentNodes()
.filter(n => n !== node)
.addClass('neighbor2');
await node.getAdjacentNodes().getAdjacentEdges().addClass('neighbor2');
console.log(
'nodes with a distance 1 ',
ogma.getNodesByClassName('neighbor1')
);
});
ogma.events.on('mouseout', async ref => {
if (!ref.target || !ref.target.isNode) return;
const node = ref.target;
node.removeClass('sourceNode');
await node.getAdjacentNodes().removeClass('neighbor1');
await node.getAdjacentEdges().removeClass('neighbor1');
// recreate the traversal to remove the class
await node.getAdjacentNodes().getAdjacentNodes().removeClass('neighbor2');
await node.getAdjacentNodes().getAdjacentEdges().removeClass('neighbor2');
// We can also remove the class to all nodes who belong to it
// ogma.getNodesByClassName('neighbor2').removeClass('neighbor2');
// ogma.getEdgesByClassName('neighbor2').removeClass('neighbor2');
});
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;
}