Updated NetworkVis + unit tests

This commit is contained in:
2025-11-16 19:03:56 +01:00
parent e286b60348
commit 66d5169b41
3 changed files with 775 additions and 22 deletions

View File

@@ -1,3 +1,4 @@
import json
import logging
from fasthtml.components import Script, Div
@@ -51,18 +52,17 @@ class VisNetwork(MultipleInstance):
self._state.update(state)
def render(self):
# Prepare JS arrays (no JSON library needed)
# Serialize nodes and edges to JSON
# This preserves all properties (color, shape, size, etc.) that are present
js_nodes = ",\n ".join(
f'{{ id: {n["id"]}, label: "{n.get("label", "")}" }}'
for n in self._state.nodes
json.dumps(node) for node in self._state.nodes
)
js_edges = ",\n ".join(
f'{{ from: {e["from"]}, to: {e["to"]} }}'
for e in self._state.edges
json.dumps(edge) for edge in self._state.edges
)
# Convert Python options to JS
import json
js_options = json.dumps(self._state.options, indent=2)
return (
@@ -73,22 +73,22 @@ class VisNetwork(MultipleInstance):
# The script initializing Vis.js
Script(f"""
(function() {{
const container = document.getElementById("{self._id}");
const nodes = new vis.DataSet([
{js_nodes}
]);
const edges = new vis.DataSet([
{js_edges}
]);
const data = {{
nodes: nodes,
edges: edges
}};
const options = {js_options};
const network = new vis.Network(container, data, options);
}})();
""")
(function() {{
const container = document.getElementById("{self._id}");
const nodes = new vis.DataSet([
{js_nodes}
]);
const edges = new vis.DataSet([
{js_edges}
]);
const data = {{
nodes: nodes,
edges: edges
}};
const options = {js_options};
const network = new vis.Network(container, data, options);
}})();
""")
)
def __ft__(self):