259 lines
8.3 KiB
TypeScript
259 lines
8.3 KiB
TypeScript
"use client";
|
||
|
||
import React, { useMemo, useState } from "react";
|
||
import type {
|
||
GridComponentOption,
|
||
LegendComponentOption,
|
||
TooltipComponentOption,
|
||
XAXisComponentOption,
|
||
YAXisComponentOption,
|
||
SeriesOption, EChartsOption,
|
||
} from "echarts";
|
||
import BaseEChart from "../BaseEChart";
|
||
import { GroupedStackBarData, ShowLabel} from "../types";
|
||
import { buildLgPalette } from "@/components/lge-dashboard/color";
|
||
import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill";
|
||
import {AXIS_HIDE_STYLE} from "@/const/lgConst";
|
||
import { LEGEND_ITEM_SIZE } from "@/const/chartConst";
|
||
|
||
type Props = {
|
||
data: GroupedStackBarData;
|
||
height?: number | string;
|
||
|
||
tooltip?: TooltipComponentOption;
|
||
grid?: GridComponentOption;
|
||
xAxis?: XAXisComponentOption;
|
||
yAxis?: YAXisComponentOption;
|
||
legend?: LegendComponentOption;
|
||
barMaxWidth?: number;
|
||
showFocusLabel?: ShowLabel;
|
||
|
||
showYearLegend?: boolean;
|
||
yearBrandPalette?: Record<string, string[]>;
|
||
};
|
||
|
||
const GroupedStackBar = ({
|
||
data,
|
||
height,
|
||
tooltip,
|
||
grid,
|
||
xAxis,
|
||
yAxis,
|
||
legend,
|
||
barMaxWidth,
|
||
showFocusLabel = "all",
|
||
showYearLegend = true,
|
||
yearBrandPalette,
|
||
}: Props) => {
|
||
const years = data.years;
|
||
const brands = data.brands;
|
||
|
||
|
||
const yearLabels = useMemo(() => years.map((y) => `${y}년`), [years]);
|
||
|
||
const [yearSelected, setYearSelected] = useState<Record<string, boolean>>(() =>
|
||
Object.fromEntries(yearLabels.map((yl) => [yl, true]))
|
||
);
|
||
|
||
const option = useMemo(() => {
|
||
const defaultGrid: EChartsOption["grid"] = {left: 10, right: 10, top: 60, bottom: 10, containLabel: true};
|
||
const defaultXAxis: EChartsOption["xAxis"] = { type: "category", data: data.categories, ...AXIS_HIDE_STYLE };
|
||
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_STYLE };
|
||
|
||
const latestYear = years.at(-1);
|
||
console.log(yearBrandPalette, String(latestYear), yearBrandPalette?.[String(latestYear)])
|
||
const latestPalette = buildLgPalette(yearBrandPalette?.[String(latestYear)]);
|
||
|
||
const yearLegendTokens = years.map((y) => {
|
||
const tokens = yearBrandPalette?.[String(y)];
|
||
const last = tokens?.[tokens.length - 1];
|
||
return last ?? "--lg-gray-500";
|
||
});
|
||
|
||
const yearLegendColors = buildLgPalette(yearLegendTokens);
|
||
|
||
const yearLegendSeries: SeriesOption[] = showYearLegend
|
||
? years.map((y, yi) => ({
|
||
id: `__year__|${y}`,
|
||
name: `${y}년`,
|
||
type: "line",
|
||
data: [], // 렌더링 없음(legend만)
|
||
showSymbol: false,
|
||
silent: true,
|
||
tooltip: { show: false },
|
||
emphasis: { disabled: true },
|
||
lineStyle: { color: yearLegendColors[yi], width: 6 },
|
||
itemStyle: { color: yearLegendColors[yi] },
|
||
}))
|
||
: [];
|
||
|
||
const brandLegendSeries: SeriesOption[] = brands.map((brand, bi) => ({
|
||
id: `__legend__|${brand}`,
|
||
name: brand,
|
||
type: "line",
|
||
data: [], // 렌더링 없음(legend만)
|
||
showSymbol: false,
|
||
silent: true,
|
||
tooltip: { show: false },
|
||
emphasis: { disabled: true },
|
||
lineStyle: { color: latestPalette[bi], width: 6 },
|
||
itemStyle: { color: latestPalette[bi] },
|
||
}));
|
||
|
||
// 2) 실제 bar series (연도 스택 3개) × (브랜드 N개)
|
||
const realSeries: SeriesOption[] = [];
|
||
for (let yi = 0; yi < years.length; yi++) {
|
||
const year = years[yi];
|
||
const yearLabel = `${year}년`;
|
||
|
||
const palette = buildLgPalette(yearBrandPalette?.[String(year)]);
|
||
|
||
for (let bi = 0; bi < brands.length; bi++) {
|
||
const brand = brands[bi];
|
||
const row = data.values?.[yi]?.[bi] ?? [];
|
||
|
||
const isYearOn = yearSelected[yearLabel];
|
||
const showLabel = getIsShowLabel(showFocusLabel, yi, years.length);
|
||
|
||
realSeries.push({
|
||
id: `${year}|${brand}`,
|
||
name: brand,
|
||
type: "bar",
|
||
stack: `Y${year}`,
|
||
emphasis: { disabled: true },
|
||
barMaxWidth: barMaxWidth ?? 42,
|
||
itemStyle: { color: palette?.[bi] },
|
||
label: showLabel
|
||
? ({
|
||
show: true,
|
||
position: "top",
|
||
formatter: (p: any) => (p?.value ?? "") as any,
|
||
} as any)
|
||
: undefined,
|
||
data: data.categories.map((_, ci) => (isYearOn ? (row[ci] ?? null) : null)),
|
||
});
|
||
}
|
||
}
|
||
|
||
// 3) legend 2개: (좌)연도, (우)브랜드
|
||
let yearLegendOpt: LegendComponentOption | undefined = showYearLegend
|
||
? ({
|
||
top: 0,
|
||
left: "center",
|
||
orient: "horizontal",
|
||
data: yearLabels, // yearLegendSeries name과 일치
|
||
selected: yearSelected,
|
||
icon: roundedRectIcon(LEGEND_ITEM_SIZE.WIDTH, LEGEND_ITEM_SIZE.HEIGHT, LEGEND_ITEM_SIZE.RADIUS),
|
||
itemWidth: LEGEND_ITEM_SIZE.WIDTH,
|
||
itemHeight: LEGEND_ITEM_SIZE.HEIGHT,
|
||
itemGap: 8,
|
||
...legend,
|
||
} as LegendComponentOption)
|
||
: undefined;
|
||
|
||
if(yearLegendOpt === undefined && legend !== undefined){
|
||
yearLegendOpt = legend;
|
||
}
|
||
|
||
const brandLegendOpt: LegendComponentOption = ({
|
||
top: 25,
|
||
right: "center",
|
||
orient: "horizontal",
|
||
icon: roundedRectIcon(LEGEND_ITEM_SIZE.WIDTH, LEGEND_ITEM_SIZE.HEIGHT, LEGEND_ITEM_SIZE.RADIUS),
|
||
itemWidth: LEGEND_ITEM_SIZE.WIDTH,
|
||
itemHeight: LEGEND_ITEM_SIZE.HEIGHT,
|
||
itemGap: 8,
|
||
...legend,
|
||
data: [...brands].reverse(),
|
||
} as LegendComponentOption);
|
||
|
||
const legends = yearLegendOpt ? [yearLegendOpt, brandLegendOpt] : brandLegendOpt;
|
||
|
||
return {
|
||
tooltip:
|
||
tooltip ??
|
||
({
|
||
trigger: "axis",
|
||
axisPointer: { type: "shadow" },
|
||
formatter: (params: any) => {
|
||
const arr = Array.isArray(params) ? params : [params];
|
||
const header = arr?.[0]?.axisValueLabel ?? "";
|
||
|
||
const yearMap = new Map<number, Array<{ brand: string; value: number }>>();
|
||
|
||
// bar series만 + 값 있는 것만
|
||
const barItems = arr
|
||
.filter((p: any) => p?.seriesType === "bar")
|
||
.filter((p: any) => p?.value !== null && p?.value !== undefined);
|
||
|
||
barItems.forEach((p: any) => {
|
||
const sid = String(p.seriesId ?? "");
|
||
const [y, brand] = sid.split("|");
|
||
const year = Number(y);
|
||
|
||
if (!yearMap.has(year)) {
|
||
yearMap.set(year, []);
|
||
}
|
||
yearMap.get(year)!.push({ brand, value: p.value });
|
||
});
|
||
|
||
const lines = Array.from(yearMap.entries())
|
||
.sort((a, b) => a[0] - b[0])
|
||
.map(([year, brands]) => {
|
||
const brandTexts = brands
|
||
.toReversed() // 브랜드 역순
|
||
.map(item => `${item.brand}: ${item.value}`)
|
||
.join(", ");
|
||
return `${year}년- ${brandTexts}`;
|
||
});
|
||
|
||
return [header, ...lines].join("<br/>");
|
||
},
|
||
} as TooltipComponentOption),
|
||
|
||
legend: legends,
|
||
grid: grid ?? defaultGrid,
|
||
xAxis: xAxis ?? defaultXAxis,
|
||
yAxis: yAxis ?? defaultYAxis,
|
||
|
||
series: [...yearLegendSeries, ...brandLegendSeries, ...realSeries],
|
||
};
|
||
}, [
|
||
years,
|
||
brands,
|
||
data.categories,
|
||
data.values,
|
||
tooltip,
|
||
grid,
|
||
xAxis,
|
||
yAxis,
|
||
legend,
|
||
showFocusLabel,
|
||
showYearLegend,
|
||
yearBrandPalette,
|
||
yearLabels,
|
||
yearSelected,
|
||
barMaxWidth,
|
||
]);
|
||
|
||
// 연도 legend 토글 이벤트만 가로채서 yearSelected에 반영
|
||
const onEvents = useMemo(
|
||
() => ({
|
||
legendselectchanged: (e: any) => {
|
||
const name = String(e?.name ?? "");
|
||
if (!yearLabels.includes(name)) return; // 브랜드 토글은 ECharts 기본 동작 사용
|
||
const selected = e?.selected as Record<string, boolean>;
|
||
setYearSelected((prev) => ({
|
||
...prev,
|
||
[name]: selected?.[name] ?? true,
|
||
}));
|
||
},
|
||
}),
|
||
[yearLabels]
|
||
);
|
||
|
||
return <BaseEChart option={option} height={height} onEvents={onEvents} />;
|
||
};
|
||
|
||
export default GroupedStackBar;
|