"use client"; import React, { useEffect, useRef } from "react"; import * as d3 from "d3"; import { ChartConfig, ChartData } from "../types"; interface HorizontalBarChartProps { data: ChartData; config: ChartConfig; width?: number; height?: number; } /** * D3 수평 막대 차트 컴포넌트 */ export function HorizontalBarChart({ data, config, width = 600, height = 400 }: HorizontalBarChartProps) { const svgRef = useRef(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: 120 }; 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})`); // Y축 스케일 (카테고리) - 수평이므로 Y축이 카테고리 const yScale = d3.scaleBand().domain(data.labels).range([0, chartHeight]).padding(0.2); // X축 스케일 (값) - 수평이므로 X축이 값, 절대값 기준 const allValues = data.datasets.flatMap((ds) => ds.data); const maxAbsValue = d3.max(allValues.map((v) => Math.abs(v))) || 0; const xScale = d3 .scaleLinear() .domain([0, maxAbsValue * 1.1]) .range([0, chartWidth]) .nice(); // Y축 그리기 (카테고리) g.append("g").call(d3.axisLeft(yScale)).style("font-size", "12px").selectAll("text").style("text-anchor", "end"); // X축 그리기 (값 표시 제거) g.append("g") .attr("transform", `translate(0,${chartHeight})`) .call(d3.axisBottom(xScale).tickFormat(() => "")) .style("font-size", "12px"); // 그리드 라인 제거됨 // 색상 팔레트 const colors = config.colors || ["#3B82F6", "#EF4444", "#10B981", "#F59E0B"]; // 막대 그리기 const barHeight = yScale.bandwidth() / data.datasets.length; data.datasets.forEach((dataset, i) => { const bars = g .selectAll(`.bar-${i}`) .data(dataset.data) .enter() .append("rect") .attr("class", `bar-${i}`) .attr("x", 0) .attr("y", (_, j) => (yScale(data.labels[j]) || 0) + barHeight * i) .attr("width", 0) .attr("height", barHeight) .attr("fill", (d) => { // 음수면 빨간색 계열, 양수면 원래 색상 if (d < 0) { return "#EF4444"; } return dataset.color || colors[i % colors.length]; }) .attr("ry", 4); // 애니메이션 - 절대값 기준으로 오른쪽으로만 렌더링 if (config.enableAnimation !== false) { bars .transition() .duration(config.animationDuration || 750) .attr("x", 0) .attr("width", (d) => xScale(Math.abs(d))); } else { bars.attr("x", 0).attr("width", (d) => xScale(Math.abs(d))); } // 막대 끝에 값 표시 (음수는 - 부호 포함) const labels = g .selectAll(`.label-${i}`) .data(dataset.data) .enter() .append("text") .attr("class", `label-${i}`) .attr("x", (d) => xScale(Math.abs(d)) + 5) .attr("y", (_, j) => (yScale(data.labels[j]) || 0) + barHeight * i + barHeight / 2) .attr("text-anchor", "start") .attr("dominant-baseline", "middle") .style("font-size", "11px") .style("font-weight", "500") .style("fill", (d) => (d < 0 ? "#EF4444" : "#333")) .text((d) => (d < 0 ? "-" : "") + Math.abs(d).toLocaleString()); // 애니메이션 (라벨) if (config.enableAnimation !== false) { labels .style("opacity", 0) .transition() .duration(config.animationDuration || 750) .style("opacity", 1); } // 툴팁 if (config.showTooltip !== false) { bars .on("mouseover", function (event, d) { d3.select(this).attr("opacity", 0.7); 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("opacity", 1); 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("rect") .attr("width", 15) .attr("height", 15) .attr("fill", dataset.color || colors[i % colors.length]) .attr("rx", 3); legendItem .append("text") .attr("x", 20) .attr("y", 12) .style("font-size", "11px") .style("fill", "#666") .text(dataset.label); }); } }, [data, config, width, height]); return ; }