demo_network_visjs/client/db_graph.tsx
2024-01-23 14:30:10 +01:00

48 lines
1.1 KiB
TypeScript

import { Ref, useEffect, useRef } from 'preact/hooks'
import * as vis from 'vis-network'
import { DbEntry } from '../datas.ts'
/**
* Renders a network style graph based on the provided database entries.
* @param db - Datas that will be used to draw the graph.
*/
export function DbGraph({ db }: { db: DbEntry[] }) {
const graph = useRef<HTMLDivElement>(null)
useEffect(() => {
drawDb({ db, graph })
}, [])
return <div class='graph' ref={graph}></div>
}
/**
* Draw db entries as vis network graph.
* @param db - DB Entries.
* @param graph - Container html reference.
*/
function drawDb({ db, graph }: { db: DbEntry[]; graph: Ref<HTMLDivElement> }) {
//Convert db entries to "vis-network" nodes
const nodes = db.map(({ id, title, links }) => ({
id,
label: title,
value: links.length,
}))
//Construct "vis-network" edges from db entries
const edges = db.map(({ id, links }) =>
links.map((link) => ({ from: id, to: link, value: id + link }))
).flat()
//Draw the network graph
return new vis.Network(graph.current!, {
nodes,
edges,
}, {
nodes: {
shape: 'dot',
},
})
}