258 lines
7.4 KiB
TypeScript
258 lines
7.4 KiB
TypeScript
"use client";
|
|
|
|
import React, { useEffect, useRef } from "react";
|
|
import * as d3 from "d3";
|
|
import { ChartConfig, ChartData } from "../types";
|
|
|
|
interface LineChartProps {
|
|
data: ChartData;
|
|
config: ChartConfig;
|
|
width?: number;
|
|
height?: number;
|
|
}
|
|
|
|
/**
|
|
* D3 선 차트 컴포넌트
|
|
*/
|
|
export function LineChart({ data, config, width = 600, height = 400 }: LineChartProps) {
|
|
const svgRef = useRef<SVGSVGElement>(null);
|
|
|
|
useEffect(() => {
|
|
if (!svgRef.current || !data.labels.length || !data.datasets.length) return;
|
|
|
|
const svg = d3.select(svgRef.current);
|
|
svg.selectAll("*").remove();
|
|
|
|
const margin = { top: 40, right: 80, bottom: 80, left: 60 };
|
|
const chartWidth = width - margin.left - margin.right;
|
|
const chartHeight = height - margin.top - margin.bottom;
|
|
|
|
const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);
|
|
|
|
// X축 스케일 (카테고리 → 연속형으로 변환)
|
|
const xScale = d3.scalePoint().domain(data.labels).range([0, chartWidth]).padding(0.5);
|
|
|
|
// Y축 스케일
|
|
const maxValue = d3.max(data.datasets.flatMap((ds) => ds.data)) || 0;
|
|
const yScale = d3
|
|
.scaleLinear()
|
|
.domain([0, maxValue * 1.1])
|
|
.range([chartHeight, 0])
|
|
.nice();
|
|
|
|
// X축 그리기
|
|
g.append("g")
|
|
.attr("transform", `translate(0,${chartHeight})`)
|
|
.call(d3.axisBottom(xScale))
|
|
.selectAll("text")
|
|
.attr("transform", "rotate(-45)")
|
|
.style("text-anchor", "end")
|
|
.style("font-size", "12px");
|
|
|
|
// Y축 그리기
|
|
g.append("g").call(d3.axisLeft(yScale)).style("font-size", "12px");
|
|
|
|
// 그리드 라인
|
|
if (config.showGrid !== false) {
|
|
g.append("g")
|
|
.attr("class", "grid")
|
|
.call(
|
|
d3
|
|
.axisLeft(yScale)
|
|
.tickSize(-chartWidth)
|
|
.tickFormat(() => ""),
|
|
)
|
|
.style("stroke-dasharray", "3,3")
|
|
.style("stroke", "#e0e0e0")
|
|
.style("opacity", 0.5);
|
|
}
|
|
|
|
// 색상 팔레트
|
|
const colors = config.colors || ["#3B82F6", "#EF4444", "#10B981", "#F59E0B"];
|
|
|
|
// 선 생성기
|
|
const lineGenerator = d3
|
|
.line<number>()
|
|
.x((_, i) => xScale(data.labels[i]) || 0)
|
|
.y((d) => yScale(d));
|
|
|
|
// 부드러운 곡선 적용
|
|
if (config.lineStyle === "smooth") {
|
|
lineGenerator.curve(d3.curveMonotoneX);
|
|
}
|
|
|
|
// 각 데이터셋에 대해 선 그리기
|
|
data.datasets.forEach((dataset, i) => {
|
|
const color = dataset.color || colors[i % colors.length];
|
|
|
|
// 선 그리기
|
|
const path = g
|
|
.append("path")
|
|
.datum(dataset.data)
|
|
.attr("fill", "none")
|
|
.attr("stroke", color)
|
|
.attr("stroke-width", 2.5)
|
|
.attr("d", lineGenerator);
|
|
|
|
// 애니메이션
|
|
if (config.enableAnimation !== false) {
|
|
const totalLength = path.node()?.getTotalLength() || 0;
|
|
path
|
|
.attr("stroke-dasharray", `${totalLength} ${totalLength}`)
|
|
.attr("stroke-dashoffset", totalLength)
|
|
.transition()
|
|
.duration(config.animationDuration || 750)
|
|
.attr("stroke-dashoffset", 0);
|
|
}
|
|
|
|
// 데이터 포인트 (점) 그리기
|
|
const circles = g
|
|
.selectAll(`.circle-${i}`)
|
|
.data(dataset.data)
|
|
.enter()
|
|
.append("circle")
|
|
.attr("class", `circle-${i}`)
|
|
.attr("cx", (_, j) => xScale(data.labels[j]) || 0)
|
|
.attr("cy", (d) => yScale(d))
|
|
.attr("r", 0)
|
|
.attr("fill", color)
|
|
.attr("stroke", "white")
|
|
.attr("stroke-width", 2);
|
|
|
|
// 애니메이션
|
|
if (config.enableAnimation !== false) {
|
|
circles
|
|
.transition()
|
|
.delay((_, j) => j * 50)
|
|
.duration(300)
|
|
.attr("r", 4);
|
|
} else {
|
|
circles.attr("r", 4);
|
|
}
|
|
|
|
// 툴팁
|
|
if (config.showTooltip !== false) {
|
|
circles
|
|
.on("mouseover", function (event, d) {
|
|
d3.select(this).attr("r", 6);
|
|
|
|
const [mouseX, mouseY] = d3.pointer(event, g.node());
|
|
const tooltipText = `${dataset.label}: ${d}`;
|
|
|
|
const tooltip = g
|
|
.append("g")
|
|
.attr("class", "tooltip")
|
|
.attr("transform", `translate(${mouseX},${mouseY - 10})`);
|
|
|
|
const text = tooltip
|
|
.append("text")
|
|
.attr("text-anchor", "middle")
|
|
.attr("fill", "white")
|
|
.attr("font-size", "12px")
|
|
.attr("dy", "-0.5em")
|
|
.text(tooltipText);
|
|
|
|
const bbox = (text.node() as SVGTextElement).getBBox();
|
|
const padding = 8;
|
|
|
|
tooltip
|
|
.insert("rect", "text")
|
|
.attr("x", bbox.x - padding)
|
|
.attr("y", bbox.y - padding)
|
|
.attr("width", bbox.width + padding * 2)
|
|
.attr("height", bbox.height + padding * 2)
|
|
.attr("fill", "rgba(0,0,0,0.85)")
|
|
.attr("rx", 6);
|
|
})
|
|
.on("mouseout", function () {
|
|
d3.select(this).attr("r", 4);
|
|
g.selectAll(".tooltip").remove();
|
|
});
|
|
}
|
|
});
|
|
|
|
// 차트 제목
|
|
if (config.title) {
|
|
svg
|
|
.append("text")
|
|
.attr("x", width / 2)
|
|
.attr("y", 20)
|
|
.attr("text-anchor", "middle")
|
|
.style("font-size", "16px")
|
|
.style("font-weight", "bold")
|
|
.text(config.title);
|
|
}
|
|
|
|
// X축 라벨
|
|
if (config.xAxisLabel) {
|
|
svg
|
|
.append("text")
|
|
.attr("x", width / 2)
|
|
.attr("y", height - 5)
|
|
.attr("text-anchor", "middle")
|
|
.style("font-size", "12px")
|
|
.style("fill", "#666")
|
|
.text(config.xAxisLabel);
|
|
}
|
|
|
|
// Y축 라벨
|
|
if (config.yAxisLabel) {
|
|
svg
|
|
.append("text")
|
|
.attr("transform", "rotate(-90)")
|
|
.attr("x", -height / 2)
|
|
.attr("y", 15)
|
|
.attr("text-anchor", "middle")
|
|
.style("font-size", "12px")
|
|
.style("fill", "#666")
|
|
.text(config.yAxisLabel);
|
|
}
|
|
|
|
// 범례 (차트 하단 중앙)
|
|
if (config.showLegend !== false && data.datasets.length > 0) {
|
|
const legendItemWidth = 120;
|
|
const totalLegendWidth = data.datasets.length * legendItemWidth;
|
|
const legendStartX = (width - totalLegendWidth) / 2;
|
|
|
|
const legend = svg
|
|
.append("g")
|
|
.attr("class", "legend")
|
|
.attr("transform", `translate(${legendStartX}, ${height - 20})`);
|
|
|
|
data.datasets.forEach((dataset, i) => {
|
|
const legendItem = legend
|
|
.append("g")
|
|
.attr("transform", `translate(${i * legendItemWidth}, 0)`);
|
|
|
|
legendItem
|
|
.append("line")
|
|
.attr("x1", 0)
|
|
.attr("y1", 7)
|
|
.attr("x2", 15)
|
|
.attr("y2", 7)
|
|
.attr("stroke", dataset.color || colors[i % colors.length])
|
|
.attr("stroke-width", 3);
|
|
|
|
legendItem
|
|
.append("circle")
|
|
.attr("cx", 7.5)
|
|
.attr("cy", 7)
|
|
.attr("r", 4)
|
|
.attr("fill", dataset.color || colors[i % colors.length])
|
|
.attr("stroke", "white")
|
|
.attr("stroke-width", 2);
|
|
|
|
legendItem
|
|
.append("text")
|
|
.attr("x", 20)
|
|
.attr("y", 12)
|
|
.style("font-size", "12px")
|
|
.style("fill", "#333")
|
|
.text(dataset.label);
|
|
});
|
|
}
|
|
}, [data, config, width, height]);
|
|
|
|
return <svg ref={svgRef} width={width} height={height} style={{ fontFamily: "sans-serif" }} />;
|
|
}
|