Hi, i want to use d3.js and use it for making a tree binding model.
d3_graph.py:
import reflex as rx
from reflex.components.component import NoSSRComponent
from typing import Any, Dict, List
class D3Graph(NoSSRComponent):
library = "d3@7"
tag = "ForceGraph"
# Define the props
nodes: rx.Var[List[Dict[str, Any]]]
links: rx.Var[List[Dict[str, Any]]]
def add_custom_code(self) -> str:
return """
import React, { useRef, useEffect } from 'react';
import * as d3 from 'd3';
function ForceGraph({nodes, links, ...props}) {
const svgRef = useRef();
const width = 800;
const height = 600;
useEffect(() => {
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove(); // Clear previous render
const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
const link = svg.append("g")
.selectAll("line")
.data(links)
.join("line")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6);
const node = svg.append("g")
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 5)
.attr("fill", "#69b3a2")
.call(drag(simulation));
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});
return () => simulation.stop();
}, [nodes, links]);
return <svg ref={svgRef} width={width} height={height} {...props} />;
}
function drag(simulation) {
function dragstarted(event) {
if (!event.active) simulation.alphaTarget(0.3).restart();
event.subject.fx = event.subject.x;
event.subject.fy = event.subject.y;
}
function dragged(event) {
event.subject.fx = event.x;
event.subject.fy = event.y;
}
function dragended(event) {
if (!event.active) simulation.alphaTarget(0);
event.subject.fx = null;
event.subject.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
"""
d3_graph = D3Graph.create
page.py:
from ..templates import template
import reflex as rx
from ..components.d3_graph import d3_graph
import random
from collections import defaultdict
from typing import Any, Dict, List
class State(rx.State):
nodes: List[Dict[str, Any]] = [
{"id": "1", "name": "Node 1"},
{"id": "2", "name": "Node 2"},
{"id": "3", "name": "Node 3"},
]
links: List[Dict[str, Any]] = [
{"source": "1", "target": "2"},
{"source": "2", "target": "3"},
]
@template(route="/accounts", title="Accounts")
def accounts() -> rx.Component:
return rx.vstack(
d3_graph(
nodes=State.nodes,
links=State.links,
),
width="100%",
height="600px",
)
I get this error:
Error:
x Expression expected
56 | }
57 | 5
58 | j
59 | ]
: ^
60 | o
61 | /
61 | p
`----
Caused by:
Syntax Error
Import trace for requested module: