How to use sigma.js with svelte

Viewed 96

I've been trying load sigma.js with Svelte / Sveltekit but there seems to be no component integration nor any guidance on how to do this. I tried loading it as client-only code in Sveltekit unsuccessfully but I have no idea if this a legit approach. Is there any working example of a simple graph in Sigma.js running with Sveltekit?

2 Answers

I created a simple svelte-sigma app like this:

npm init vite svelte-sigma -- --template svelte
cd my-app
npm install
npm run dev

after I installed sigma.js:

npm install graphology sigma

Now I changed App.svelte like this:

App.svelte

<script>
  import Sigma from 'sigma';
  import Graph from 'graphology';
  import { onMount } from 'svelte';

  onMount(() => {
    const container1 =  document.getElementById("sigma-container");
    

      const graph = new Graph();

      graph.addNode("John", { x: 0, y: 10, size: 15, label: "John", color: "blue" });
      graph.addNode("Mary", { x: 10, y: 0, size: 10, label: "Mary", color: "green" });
      graph.addNode("Thomas", { x: 7, y: 9, size: 20, label: "Thomas", color: "red" });
      graph.addNode("Hannah", { x: -7, y: -6, size: 25, label: "Hannah", color: "teal" });

      graph.addEdge("John", "Mary");
      graph.addEdge("John", "Thomas");
      graph.addEdge("John", "Hannah");
      graph.addEdge("Hannah", "Thomas");
      graph.addEdge("Hannah", "Mary");

      const renderer = new Sigma(graph, container1);

  });

  
</script>
<h1> Sigma graph exemple</h1>
<div id="sigma-container" />

<style>
  #sigma-container {
      width: 550px;
      height: 450px;
  }
</style>

and I have this render on my localhost: graph exemple

You can see this exemple

Example for parsing a gexf file:

<script lang="ts">
    import Sigma from 'sigma';
    import Graph from 'graphology';
    import { onMount } from 'svelte';

    let container: HTMLElement;

    onMount(async () => {
        const res = await fetch('/arctic.gexf');
        const gexf = await res.text();
        const { parse } = await import('graphology-gexf/browser');

        const graph = parse(Graph, gexf);

        const renderer = new Sigma(graph, container, {
            minCameraRatio: 0.1,
            maxCameraRatio: 10,
        });
    })
</script>

<div bind:this={container} class="container" />

<style>
    .container {
        width: 800px;
        height: 600px;
    }
</style>

Required packages:

  • sigma
  • graphology
  • graphology-gexf (for reading .gexf files)

graphology-gexf has two modes, one for Node, one for the Browser. To prevent errors in SSR, the browser part can be dynamically imported.

In Svelte you get access to the DOM elements via bind:this instead of querying the DOM, most other things are not that different. Elements bound this way are available in onMount.

arctic.gexf is placed in the static directory. Code is adapted from this example (without all the additional functionality).

Related