Create a reusable Vis graph component

This commit is contained in:
Maciej Pędzich 2024-03-07 21:57:07 +01:00
parent f9f424bc4c
commit 650490e91d
3 changed files with 97 additions and 14 deletions

View File

@ -0,0 +1,58 @@
---
import type { Node, Edge, Options } from 'vis-network/esnext';
export interface Props {
nodes: Node[];
edges: Edge[];
options?: Options;
}
const { nodes, edges, options = {} } = Astro.props;
---
<vis-graph
data-nodes={JSON.stringify(nodes)}
data-edges={JSON.stringify(edges)}
data-options={JSON.stringify(options)}
>
<div></div>
</vis-graph>
<script>
import type { Node, Data, Edge, Options } from 'vis-network/esnext';
import { DataSet } from 'vis-data/esnext';
import { Network } from 'vis-network/esnext';
class VisGraph extends HTMLElement {
constructor() {
super();
const nodes = new DataSet(
JSON.parse(this.dataset.nodes as string) as Node[]
);
const edges = new DataSet<Edge>(
JSON.parse(this.dataset.edges as string) as Edge[]
);
const container = this.querySelector('div')!;
const data: Data = {
nodes,
edges
};
const options: Options = {
...(JSON.parse(this.dataset.options as string) as Options)
};
new Network(container, data, options);
}
}
customElements.define('vis-graph', VisGraph);
</script>
<style>
div {
width: 100vw;
height: 100vh;
}
</style>

View File

@ -0,0 +1,18 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>Astro</title>
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<slot />
</body>
</html>

View File

@ -1,16 +1,23 @@
---
import BaseLayout from '../layouts/BaseLayout.astro';
import VisGraph from '../components/VisGraph.astro';
const nodes = [
{ id: 1, label: 'Node 1' },
{ id: 2, label: 'Node 2' },
{ id: 3, label: 'Node 3' },
{ id: 4, label: 'Node 4' },
{ id: 5, label: 'Node 5' }
];
const edges = [
{ from: 1, to: 3 },
{ from: 1, to: 2 },
{ from: 2, to: 4 },
{ from: 2, to: 5 },
{ from: 3, to: 3 }
];
---
---
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>Astro</title>
</head>
<body>
<h1>Astro</h1>
</body>
</html>
<BaseLayout>
<VisGraph nodes={nodes} edges={edges} />
</BaseLayout>