trust-module-frontend/src/Components/TreeChart.jsx

122 lines
3.9 KiB
JavaScript

import React, { useRef, useEffect } from "react";
import * as d3 from "d3";
const TreeChart = ({ data, onNodeClick }) => {
const chartRef = useRef();
useEffect(() => {
if (!data) return;
// Очищаем старый граф перед отрисовкой
d3.select(chartRef.current).selectAll("*").remove();
const width = 928;
const height = 600;
const root = d3.hierarchy(data, (d) => d.items);
const links = root.links();
const nodes = root.descendants();
const simulation = d3
.forceSimulation(nodes)
.force("link", d3.forceLink(links).id((d) => d.data.title).distance(80).strength(1)) // Увеличил дистанцию
.force("charge", d3.forceManyBody().strength(-500)) // Увеличил отталкивание узлов
.force("x", d3.forceX())
.force("y", d3.forceY());
const svg = d3
.select(chartRef.current)
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-width / 2, -height / 2, width, height])
.attr("style", "max-width: 100%; height: auto;");
const link = svg
.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(links)
.join("line");
const node = svg
.append("g")
.attr("stroke", "#000")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("fill", (d) => (d.children ? "#555" : "#000"))
.attr("stroke", "#fff")
.attr("r", 7) // Немного увеличил размер узлов для удобства клика
.call(drag(simulation));
// Добавляем текстовые подписи
const text = svg
.append("g")
.attr("fill", "#000")
.attr("font-family", "Arial")
.attr("font-size", 12)
.attr("pointer-events", "none") // Отключаем обработку событий текста
.selectAll("text")
.data(nodes)
.join("text")
.text((d) => d.data.title)
.attr("dx", 12) // Отодвигаем текст дальше от узла
.attr("dy", 4) // Немного поднимаем текст
node.append("title").text((d) => d.data.title);
node.on("click", (event, d) => {
if (onNodeClick) {
onNodeClick(d.data.id, d.data.title); // Передаем id и title
}
});
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);
text
.attr("x", (d) => d.x + 12) // Смещаем текст правее узла
.attr("y", (d) => d.y + 4);
});
return () => {
simulation.stop();
};
}, [data, onNodeClick]);
const drag = (simulation) => {
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
return d3.drag().on("start", dragstarted).on("drag", dragged).on("end", dragended);
};
return <svg ref={chartRef}></svg>;
};
export default TreeChart;