Skip to content
  1. Examples

Expand with pinning

In this example you can see how you can take advantage of the pinning option when adding elements to the graph and running the force layout. The "pinned" nodes are taken into account by the layout but not moved by it.

ts
import Ogma, { NodeId, RawGraph, RawNode, Node } from '@linkurious/ogma';
import { GUI } from 'dat.gui';
import './styles.css';

const ogma = new Ogma({
  container: 'graph-container'
});

const settings = {
  async expandSelectedNode() {
    const selected = ogma.getSelectedNodes();
    if (selected.size === 0) return;
    await expandNode(selected.get(0));
  },
  async addRandomSubgraph() {
    await addSubgraph();
  },
  async runLayout() {
    await ogma.layouts.force({
      autoStop: true,
      locate: true
    });
  }
};
const gui = new GUI();
gui.add(settings, 'expandSelectedNode').name('Expand selected node');
gui.add(settings, 'addRandomSubgraph').name('Add random subgraph');
gui.add(settings, 'runLayout').name('Re-layout');

let nodesMap: Map<NodeId, RawNode> = new Map();
const initialGraph = await Ogma.parse.jsonFromUrl('files/paris.json');
const graph = cacheGraph(adjustIds(initialGraph));
ogma.addNode(nodesMap.get(16)!);
await ogma.view.locateGraph();
ogma.getNodes().setSelected(true);

ogma.styles.addNodeRule({
  text: {
    font: 'IBM Plex Sans'
  },
  badges: {
    bottomRight: node => {
      const degree = node.getData('degree');
      if (degree > 1 && degree !== node.getDegree())
        return {
          text: { content: degree, font: 'IBM Plex Sans' },
          scale: 0.15,
          minVisibleSize: 0
        };
    }
  }
});

ogma.events.on('doubleclick', ({ target }) => {
  if (target && target.isNode) {
    expandNode(target);
  }
});

async function expandNode(target: Node) {
  const subgraph = expand(target.getId());
  ogma.getNodes().setAttribute('layoutable', false);
  // do not lock the expanding node
  target.setAttribute('layoutable', true);

  // do not lock existing endpoints of the newly added edges
  const endPoints: NodeId[] = subgraph.edges.reduce((acc, edge) => {
    acc.push(edge.source, edge.target);
    return acc;
  }, [] as NodeId[]);
  ogma.getNodes(endPoints).dedupe().setAttribute('layoutable', true);
  const { x, y } = target.getPosition();
  subgraph.nodes.forEach(node => {
    node.attributes!.x = x;
    node.attributes!.y = y;
  });
  await ogma.addGraph(subgraph);
  await ogma.layouts.force({ locate: true });
  await ogma.getNodes().setAttribute('layoutable', true);
}

async function addSubgraph() {
  ogma.getNodes().setAttribute('layoutable', false);
  const graph = adjustIds(await ogma.generate.barabasiAlbert({ nodes: 50 }));
  await ogma.addGraph(graph);
  await ogma.layouts.force({ autoStop: true });
  await ogma.getNodes().setAttribute('layoutable', true);
}

function cacheGraph({ nodes, edges }: RawGraph) {
  const graph = { nodes, edges };
  nodesMap = nodes.reduce((acc, node) => {
    acc.set(node.id as NodeId, node);
    return acc;
  }, new Map<NodeId, RawNode>());
  return graph;
}

function expand(nodeId: NodeId): RawGraph {
  const dedupe = new Set(ogma.getNodes().getId());
  return graph.edges.reduce(
    (acc, edge) => {
      if (
        edge.source === nodeId ||
        (edge.target === nodeId && !ogma.getEdge(edge.id!))
      ) {
        acc.edges.push(edge);
        const other = edge.source === nodeId ? edge.target : edge.source;
        if (!dedupe.has(other)) {
          acc.nodes.push(nodesMap.get(other)!);
          dedupe.add(other);
        }
      }
      return acc;
    },
    { nodes: [], edges: [] } as RawGraph
  );
}

// avoid index clashing
function adjustIds({ nodes, edges }: RawGraph) {
  const offset = ogma.getNodes().size + 1;
  const nodesMap = new Map<NodeId, RawNode>();

  nodes.forEach((node, i) => {
    const id = node.id!;
    const newId = offset + i;
    node.id = newId;
    (node.data = node.data || {}).degree = 0;
    nodesMap.set(id, node);
  });

  edges.forEach((edge, i) => {
    const source = nodesMap.get(edge.source)!;
    const target = nodesMap.get(edge.target)!;

    source.data.degree++;
    target.data.degree++;

    edge.source = source.id!;
    edge.target = target.id!;
    edge.id = i;
  });

  return { nodes, edges };
}
html
<!doctype html>
<html>
  <head>
    <title>Rectangle select</title>
    <meta charset="utf-8" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap"
      rel="stylesheet"
    />
  </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;
}


#controls {
  position: absolute;
  right: 20px;
  top: 20px;
  padding: 15px;
  border-radius: 5px;
  background: white;
  box-shadow: 0 0 5px rgba(0,0,0,0.5);
  z-index: 999;
}