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