Fixed Tab content lost on reload

This commit is contained in:
2025-11-16 16:17:42 +01:00
parent ca238303b8
commit edcd3ae1a8
3 changed files with 56 additions and 26 deletions

View File

@@ -3,48 +3,72 @@ import logging
from fasthtml.components import Script, Div
from myfasthtml.controls.helpers import Ids
from myfasthtml.core.dbmanager import DbObject
from myfasthtml.core.instances import MultipleInstance
logger = logging.getLogger("VisNetwork")
class VisNetworkState(DbObject):
def __init__(self, owner):
super().__init__(owner.get_session(), owner.get_id())
with self.initializing():
# persisted in DB
self.nodes: list = []
self.edges: list = []
self.options: dict = {
"autoResize": True,
"interaction": {
"dragNodes": True,
"zoomView": True,
"dragView": True,
},
"physics": {"enabled": True}
}
class VisNetwork(MultipleInstance):
def __init__(self, session, _id=None, nodes=None, edges=None, options=None):
super().__init__(session, Ids.VisNetwork, _id=_id)
logger.debug(f"VisNetwork created with id: {self._id}")
# Default values
self.nodes = nodes or []
self.edges = edges or []
self.options = options or {
"autoResize": True,
"interaction": {
"dragNodes": True,
"zoomView": True,
"dragView": True,
},
"physics": {"enabled": True}
}
self._state = VisNetworkState(self)
self._update_state(nodes, edges, options)
def _update_state(self, nodes, edges, options):
logger.debug(f"Updating VisNetwork state with {nodes=}, {edges=}, {options=}")
if not nodes and not edges and not options:
return
state = self._state.copy()
if nodes is not None:
state.nodes = nodes
if edges is not None:
state.edges = edges
if options is not None:
state.options = options
self._state.update(state)
def render(self):
# Prepare JS arrays (no JSON library needed)
js_nodes = ",\n ".join(
f'{{ id: {n["id"]}, label: "{n.get("label", "")}" }}'
for n in self.nodes
for n in self._state.nodes
)
js_edges = ",\n ".join(
f'{{ from: {e["from"]}, to: {e["to"]} }}'
for e in self.edges
for e in self._state.edges
)
# Convert Python options to JS
import json
js_options = json.dumps(self.options, indent=2)
js_options = json.dumps(self._state.options, indent=2)
return (
Div(
id=self._id,
cls="mf-vis",
#style="width:100%; height:100%;", # Let parent control the layout
),
# The script initializing Vis.js