260127_01_ENH: 커스텀 컴포넌트들 1차 완성 및 일부페이지에 SampleData 적용

This commit is contained in:
2026-01-27 16:59:24 +09:00
parent 76c2626507
commit 8bfa8fa7c4
33 changed files with 3035 additions and 35 deletions

View File

@@ -1,3 +1,5 @@
'use client'
const AirSolutionPage = () => {
return (
<div>AirSolutionPage</div>

View File

@@ -1,6 +1,10 @@
'use client'
const HAKitchenPage = () => {
return (
<div>HAKitchenPage</div>
<div>
<div>HAKitchenPage</div>
</div>
);
}

View File

@@ -1,3 +1,5 @@
'use client'
const HALivingPage = () => {
return (
<div>HALivingPage</div>

View File

@@ -1,3 +1,5 @@
'use client'
const MSDigitalPage = () => {
return (
<div>MSDigitalPage</div>

View File

@@ -1,6 +1,76 @@
'use client'
import {Button} from "@/components/ui/button";
import TopChartTable from "../../../../../components/lge-dashboard/combo/TopChartTable";
import {
GroupedOverlayBar, GroupedOverlayBarData,
signStyleGapRow, TopChartTableRow
} from "@/components/lge-dashboard";
import {PRODUCT_KEYS, PRODUCTS, YEARS} from "@/const/lgConst";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {useEffect} from "react";
import {apiOwnShareOfTotalPenetration, apiTrendCategories} from "@/config/sample.data";
const LGPenetrationPage = () => {
const displayRowLabel = (i:number, rowLabel: string) => {
if (rowLabel === "gap") return "전년 대비 GAP(%)";
return rowLabel;
};
const productTableRows: TopChartTableRow[] = apiOwnShareOfTotalPenetration.map((row, i) => ({
label: displayRowLabel(i, row.rowLabel),
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
}));
const total: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const yearIndexMap = new Map<number, number>(YEARS.map((y, i) => [y, i]));
const totalRows = apiTrendCategories.filter((r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년"));
const lgRows = apiOwnShareOfTotalPenetration.filter((r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년"));
lgRows.forEach((r, ri) => {
const yi = yearIndexMap.get(r.year);
if (yi == null) return;
for (let ci = 0; ci < PRODUCT_KEYS.length; ci++) {
const k = PRODUCT_KEYS[ci];
const t = (totalRows[ri] as any)[k];
const v = (r as any)[k];
// total/focus 모두 같은 값(“전체 보급률 중 자사제품 비율”이므로)
total[yi][ci] = typeof v === "number" ? t : 0;
focus[yi][ci] = typeof v === "number" ? v : 0;
}
})
const productChartData: GroupedOverlayBarData = {
categories: PRODUCTS,
years: YEARS,
totalName: "전체",
focusName: "LG",
total: total,
focus: focus,
}
return (
<div>LGPenetrationPage</div>
<div>
<TopChartTable
title={"LG제품 보급률"}
categories={[...PRODUCTS]}
rows={productTableRows}
chart={
<GroupedOverlayBar
data={productChartData}
yearTotalColor={{ "24": "--chart-total-1", "25": "--chart-total-2", "26": "--chart-total-3" }}
yearFocusColor={{ "24": "--chart-lg-1", "25": "--chart-lg-2", "26": "--chart-lg-3" }}
showFocusLabel={"last"}
/>
}
signStyle={signStyleGapRow}
/>
</div>
);
}

View File

@@ -1,6 +1,69 @@
'use client'
import TopChartTable from "../../../../../components/lge-dashboard/combo/TopChartTable";
import {PRODUCT_KEYS, PRODUCTS, YEARS} from "@/const/lgConst";
import {GroupedOverlayBar, GroupedOverlayBarData, signStyleGapRow, TopChartTableRow} from "@/components/lge-dashboard";
import { apiOwnShareOfTotalPurchase, apiTrendBuy} from "@/config/sample.data";
const LGPurchasePage = () => {
const displayRowLabel = (i:number, rowLabel: string) => {
if (rowLabel === "gap") return "전년 대비 GAP(%)";
return rowLabel;
};
const purchaseTableRows: TopChartTableRow[] = apiOwnShareOfTotalPurchase.map((row, i) => ({
label: displayRowLabel(i, row.rowLabel),
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
}));
const total: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const yearIndexMap = new Map<number, number>(YEARS.map((y, i) => [y, i]));
const totalRows = apiTrendBuy.filter((r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년"));
const lgRows = apiOwnShareOfTotalPurchase.filter((r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년"));
lgRows.forEach((r, ri) => {
const yi = yearIndexMap.get(r.year);
if (yi == null) return;
for (let ci = 0; ci < PRODUCT_KEYS.length; ci++) {
const k = PRODUCT_KEYS[ci];
const t = (totalRows[ri] as any)[k];
const v = (r as any)[k];
// total/focus 모두 같은 값(“전체 보급률 중 자사제품 비율”이므로)
total[yi][ci] = typeof v === "number" ? t : 0;
focus[yi][ci] = typeof v === "number" ? v : 0;
}
})
const purchaseChartData: GroupedOverlayBarData = {
categories: PRODUCTS,
years: YEARS,
totalName: "전체",
focusName: "LG",
total: total,
focus: focus,
}
return (
<div>LGPurchasePage</div>
<div>
<TopChartTable
title={"LG제품 구매율"}
categories={[...PRODUCTS]}
rows={purchaseTableRows}
chart={
<GroupedOverlayBar
data={purchaseChartData}
yearTotalColor={{ "24": "--chart-total-1", "25": "--chart-total-2", "26": "--chart-total-3" }}
yearFocusColor={{ "24": "--chart-lg-1", "25": "--chart-lg-2", "26": "--chart-lg-3" }}
showFocusLabel={"last"}
/>
}
signStyle={signStyleGapRow}
/>
</div>
);
}

View File

@@ -1,6 +1,122 @@
'use client'
import {useEffect, useState} from "react";
import TopChartTable from "@/components/lge-dashboard/combo/TopChartTable";
import VerticalBar from "@/components/lge-dashboard/chart/VerticalBar";
import {
AXIS_HIDE_STYLE, ChartData,
GRID_X_NOT_PADDING,
GroupedStackBar, signStyleGapRow, TopChartTableRow, GroupedStackBarData
} from "@/components/lge-dashboard";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {apiBrandByYearCategories, apiTrendCategories} from "@/config/sample.data";
import {Button} from "@/components/ui/button";
import {BRAND_LIST, PRODUCT_KEYS, PRODUCTS, YEARS} from "@/const/lgConst";
const PenetrationPage = () => {
const { totalValue, registerExcelExporter } = useLayoutFilter();
const [isBrandShare, setIsBrandShare] = useState<boolean>(false);
const displayRowLabel = (i:number, rowLabel: string) => {
if (rowLabel === "gap") return "전년 대비 GAP(%)";
return rowLabel;
};
const productTableRows: TopChartTableRow[] = apiTrendCategories.map((row, i) => ({
label: displayRowLabel(i, row.rowLabel),
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
}));
const productChartData: ChartData = {
categories: [...PRODUCTS], // 한글 라벨(세탁기/냉장고/...)
series: apiTrendCategories
.filter((r) => r.rowLabel.endsWith("년")) // 24년/25년/26년만 차트에 사용
.map((r) => ({
name: r.rowLabel, // legend: 24년/25년/26년
data: PRODUCT_KEYS.map((k) => (r as any)[k] ?? null),
})),
}
const rowMap = new Map<string, (typeof apiBrandByYearCategories)[number]>();
for (const r of apiBrandByYearCategories) {
rowMap.set(`${r.year}__${r.rowLabel}`, r);
}
const brandShareChartData: GroupedStackBarData = (() => {
const values: number[][][] = YEARS.map(() =>
BRAND_LIST.map(() => new Array(PRODUCTS.length).fill(0))
);
YEARS.forEach((year, yi) =>{
BRAND_LIST.forEach((brand, bi) => {
PRODUCT_KEYS.forEach((k, ci) => {
const row = rowMap.get(`${year}__${brand}`);
const v = (row as any)?.[k];
values[yi][bi][ci] = typeof v === "number" ? v : 0;
});
});
})
return { categories: PRODUCTS, years: YEARS, brands: BRAND_LIST, values };
})();
useEffect(() => {
registerExcelExporter(async (payload) => {
// payload.isTotal / payload.totalValue / payload.categoryValue 사용 가능
// 여기서 데이터 수집 -> 엑셀 생성 -> 다운로드 수행
// TODO: 실제 export 로직
// await exportToExcel(payload);
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>PenetrationPage</div>
<div>
<div className="flex py-4">
<Button
className="h-8 px-3 text-sm font-semibold content-text-sm"
variant={isBrandShare?"default":"secondary"}
onClick={() => setIsBrandShare(!isBrandShare)}
>
{"브랜드별 점유율"}
</Button>
</div>
<TopChartTable
title={isBrandShare?"브랜드별 점유율":"전체 보급률"}
categories={[...PRODUCTS]}
rows={productTableRows}
chart={
isBrandShare?
<GroupedStackBar
data={brandShareChartData}
grid={{...GRID_X_NOT_PADDING, top:60}}
xAxis={{ type: "category", data: PRODUCTS, ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
showFocusLabel={"none"}
// 연도(24/25/26)별로 브랜드 3개 색상 지정 (브랜드 순서는 data.brands 순서)
yearBrandPalette={{
"24": ["--chart-cbrand-1", "--chart-samsung-1", "--chart-lg-1"],
"25": ["--chart-cbrand-2", "--chart-samsung-2", "--chart-lg-2"],
"26": ["--chart-cbrand-3", "--chart-samsung-3", "--chart-lg-3"],
}}
/>
:
<VerticalBar
data={productChartData}
paletteVarNames={["--chart-3", "--chart-2", "--chart-1"]}
grid={GRID_X_NOT_PADDING}
xAxis={{ type: "category", data: [...PRODUCTS], ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
</div>
);
}

View File

@@ -1,6 +1,58 @@
'use client'
import {Button} from "@/components/ui/button";
import TopChartTable from "../../../../../components/lge-dashboard/combo/TopChartTable";
import {PRODUCT_KEYS, PRODUCTS} from "@/const/lgConst";
import {
AXIS_HIDE_STYLE, ChartData,
GRID_X_NOT_PADDING,
signStyleGapRow,
TopChartTableRow
} from "@/components/lge-dashboard";
import VerticalBar from "../../../../../components/lge-dashboard/chart/VerticalBar";
import {apiTrendBuy} from "@/config/sample.data";
const PurchasePage = () => {
const displayRowLabel = (i:number, rowLabel: string) => {
if (rowLabel === "gap") return "전년 대비 GAP(%)";
return rowLabel;
};
const purchaseTableRows: TopChartTableRow[] = apiTrendBuy.map((row, i) => ({
label: displayRowLabel(i, row.rowLabel),
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
}));
const purchaseChartData: ChartData = {
categories: [...PRODUCTS], // 한글 라벨(세탁기/냉장고/...)
series: apiTrendBuy
.filter((r) => r.rowLabel.endsWith("년")) // 24년/25년/26년만 차트에 사용
.map((r) => ({
name: r.rowLabel, // legend: 24년/25년/26년
data: PRODUCT_KEYS.map((k) => (r as any)[k] ?? null),
})),
}
return (
<div>PurchasePage</div>
<div>
<TopChartTable
title={"전체 구매율"}
categories={[...PRODUCTS]}
rows={purchaseTableRows}
chart={
<VerticalBar
data={purchaseChartData}
paletteVarNames={["--chart-3", "--chart-2", "--chart-1"]}
grid={GRID_X_NOT_PADDING}
xAxis={{ type: "category", data: [...PRODUCTS], ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
</div>
);
}

View File

@@ -129,6 +129,10 @@
--lg-orange-400: 29.6 85% 68.0%;
--lg-orange-300: 29.6 75% 78.0%;
--samsung-blue-600: 218.93 53.91% 52.35%; /* #4472C7 */
--samsung-blue-500: 218.93 48.0% 56.0%; /* #597FC5 */
--samsung-blue-400: 218.93 40.0% 66.0%; /* #869ECB */
--samsung-blue-300: 218.93 33.0% 76.0%; /* #AEBCD6 */
/* =============================
Brand Core
(semantic은 "실제 색"으로 정의)
@@ -166,16 +170,30 @@
/* =============================
Chart Colors
============================= */
--chart-1: hsl(var(--lg-red-600));
--chart-2: hsl(var(--lg-red-300));
--chart-3: hsl(var(--lg-pink-300));
--chart-4: hsl(var(--lg-pink-400));
--chart-5: hsl(var(--lg-pink-600));
--chart-6: hsl(var(--lg-gray-900));
--chart-7: hsl(var(--lg-gray-800));
--chart-8: hsl(var(--lg-gray-700));
--chart-9: hsl(var(--lg-gray-600));
--chart-10: hsl(var(--lg-gray-500));
--chart-1: var(--lg-red-600);
--chart-2: var(--lg-red-300);
--chart-3: var(--lg-pink-300);
--chart-4: var(--lg-pink-400);
--chart-5: var(--lg-pink-600);
--chart-6: var(--lg-gray-900);
--chart-7: var(--lg-gray-800);
--chart-8: var(--lg-gray-700);
--chart-9: var(--lg-gray-600);
--chart-10: var(--lg-gray-500);
--chart-lg-1: var(--lg-pink-300);
--chart-lg-2: var(--lg-red-300);
--chart-lg-3: var(--lg-red-600);
--chart-total-1: var(--lg-gray-300);
--chart-total-2: var(--lg-gray-400);
--chart-total-3: var(--lg-gray-700);
--chart-cbrand-1: var(--lg-gray-300);
--chart-cbrand-2: var(--lg-gray-400);
--chart-cbrand-3: var(--lg-gray-700);
--chart-samsung-1: var(--samsung-blue-400);
--chart-samsung-2: var(--samsung-blue-500);
--chart-samsung-3: var(--samsung-blue-600);
--chart-border: hsl(0 0% 95%);
/* =============================

View File

@@ -0,0 +1,20 @@
"use client";
import { Button } from "@/components/ui/button";
import { useLayoutFilter } from "./LayoutFilterContext";
const ExcelDownloadButton = () => {
const { requestExcelExport } = useLayoutFilter();
return (
<Button
variant="excel"
className="h-8 px-3 text-sm font-semibold content-text-sm"
onClick={requestExcelExport}
>
Excel 다운로드
</Button>
);
};
export default ExcelDownloadButton;

View File

@@ -0,0 +1,60 @@
"use client";
import React, { createContext, useCallback, useContext, useMemo, useRef } from "react";
import type { SelectedMap } from "@/types/common";
import type { CategoryFilterValue } from "@/components/layout/CategoryFilter";
export type ExcelExportContext = {
isTotal: boolean;
totalValue: SelectedMap;
categoryValue: CategoryFilterValue;
};
type ExcelExporter = (ctx: ExcelExportContext) => void | Promise<void>;
type LayoutFilterContextValue = ExcelExportContext & {
registerExcelExporter: (exporter: ExcelExporter | null) => void;
requestExcelExport: () => Promise<void>;
};
const LayoutFilterContext = createContext<LayoutFilterContextValue | null>(null);
export const LayoutFilterProvider = ({
value,
children,
}: {
value: ExcelExportContext;
children: React.ReactNode;
}) => {
const exporterRef = useRef<ExcelExporter | null>(null);
const registerExcelExporter = useCallback((exporter: ExcelExporter | null) => {
exporterRef.current = exporter;
}, []);
const requestExcelExport = useCallback(async () => {
const exporter = exporterRef.current;
if (!exporter) {
console.warn("Excel exporter is not registered.");
return;
}
await exporter(value);
}, [value]);
const ctxValue = useMemo<LayoutFilterContextValue>(
() => ({
...value,
registerExcelExporter,
requestExcelExport,
}),
[value, registerExcelExporter, requestExcelExport]
);
return <LayoutFilterContext.Provider value={ctxValue}>{children}</LayoutFilterContext.Provider>;
};
export const useLayoutFilter = () => {
const ctx = useContext(LayoutFilterContext);
if (!ctx) throw new Error("useLayoutFilter must be used within LayoutFilterProvider");
return ctx;
};

View File

@@ -2,16 +2,17 @@
import {ReactNode, useState} from "react";
import { usePathname, useRouter } from "next/navigation";
import {topMenus, totalSubMenus, categorySubMenus} from "@/config/menu.data";
import Header from "./Header";
import SubMenu from "./SubMenu";
import TotalFilter from "@/components/layout/TotalFilter";
import CategoryFilter, {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {cn} from "@/lib/utils";
import {Button} from "@/components/ui/button";
import {SelectedMap} from "@/types/common";
import {topMenus, totalSubMenus, categorySubMenus} from "@/config/menu.data";
import {categoryTarget, totalFilters} from "@/config/filter.data";
import {CategoryTargetData, CategoryTargetType} from "@/config/filter.types";
import Header from "./Header";
import SubMenu from "./SubMenu";
import TotalFilter from "./TotalFilter";
import CategoryFilter, {CategoryFilterValue} from "./CategoryFilter";
import ExcelDownloadButton from "./ExcelDownloadButton";
import {LayoutFilterProvider} from "./LayoutFilterContext";
type MainLayoutProps = {
children: ReactNode;
@@ -64,13 +65,15 @@ const MainLayout = ({ children }: MainLayoutProps) => {
else setIsCategoryFilterOpen((v) => !v);
};
const handleExcelDownload = async () => {
// TODO: 다운로드 구현 필요
console.log("Excel download:", { pathname, top: activeTop.id, sub: activeSub.id });
};
return (
<div className="min-h-screen flex flex-col bg-transparent">
<LayoutFilterProvider
value={{
isTotal,
totalValue,
categoryValue,
}}
>
<Header
activeTopId={activeTop.id}
onNavigate={movePage}
@@ -95,12 +98,7 @@ const MainLayout = ({ children }: MainLayoutProps) => {
필터 <span className="text-sm leading-none">{isFilterOpen ? "▲" : "▼"}</span>
</button>
<Button
variant="excel"
className="h-8 px-3 text-sm font-semibold content-text-sm"
onClick={handleExcelDownload}>
Excel 다운로드
</Button>
<ExcelDownloadButton/>
</div>
{isFilterOpen && (
@@ -113,13 +111,15 @@ const MainLayout = ({ children }: MainLayoutProps) => {
</div>
)}
{/* ✅ 실제 콘텐츠만 스크롤 */}
<div className="flex-1 min-h-0 overflow-auto">
<div className="p-3">{children}</div>
<div className="p-3">
{children}
</div>
</div>
</div>
</div>
</div>
</LayoutFilterProvider>
</div>
);
}

View File

@@ -29,7 +29,7 @@ const SubMenu = ({
"border border-gray-200",
"-ml-px first:ml-0 rounded-tl-lg rounded-tr-lg cursor-pointer", // 탭이 서로 '붙어' 보이게
active
? "bg-primary text-primary-foreground z-40"
? "bg-primary text-primary-foreground z-10"
: "bg-white-hover text-secondary"
)}
style={active ? {

View File

@@ -0,0 +1,38 @@
"use client";
import {bannerType} from "@/components/lge-dashboard/types";
type BannerButtonsProps = {
banners: bannerType[];
selectedBanner: bannerType;
onSelectBanner: (banner: bannerType) => void;
};
const BannerButtons = ({
banners,
selectedBanner,
onSelectBanner
}: BannerButtonsProps) => {
return (
<div className="flex flex-col gap-2">
{banners.map((banner) => (
<button
key={banner.variable}
onClick={() => onSelectBanner(banner)}
className={`
px-4 py-2 text-sm font-medium rounded-lg transition-colors
${
selectedBanner === banner
? "bg-primary text-primary-foreground"
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
}
`}
>
{banner.variableName}
</button>
))}
</div>
);
}
export default BannerButtons;

View File

@@ -0,0 +1,37 @@
"use client";
import dynamic from "next/dynamic";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
const ReactECharts = dynamic(() => import("echarts-for-react"), { ssr: false });
type BaseEChartProps = {
option: EChartsOption;
height?: number | string;
className?: string;
/** echarts-for-react의 notMerge/lazyUpdate 옵션 필요 시 */
notMerge?: boolean;
lazyUpdate?: boolean;
/** echarts-for-react 이벤트 바인딩(예: legendselectchanged) */
onEvents?: Record<string, (params: unknown) => void>;
};
const BaseEChart = ({
option,
height = 260,
className,
notMerge = true,
lazyUpdate = true,
onEvents,
}: BaseEChartProps) => {
const style = useMemo(() => ({ height }), [height]);
return (
<div className={className}>
<ReactECharts option={option} style={style} notMerge={notMerge} lazyUpdate={lazyUpdate} onEvents={onEvents} />
</div>
);
}
export default BaseEChart;

View File

@@ -0,0 +1,37 @@
"use client";
import type React from "react";
import { cn } from "@/lib/utils";
type Props = {
label?: string;
title?: string;
rightSlot?: React.ReactNode;
className?: string;
children: React.ReactNode;
};
export const Card = ({
label,
title,
rightSlot,
className,
children }: Props) =>
{
return (
<div className={cn("lg-category-card", className)}>
{label && <div className="lg-category-card__label">{label}</div>}
{(title || rightSlot) && (
<div className="flex items-start justify-between gap-3 pt-2">
{title && <div className="content-text-base font-semibold">{title}</div>}
{rightSlot && <div className="shrink-0">{rightSlot}</div>}
</div>
)}
<div className="pt-3">{children}</div>
</div>
);
}
export default Card;

View File

@@ -0,0 +1,282 @@
"use client";
import React, { useMemo, useState } from "react";
import type {
GridComponentOption,
LegendComponentOption,
TooltipComponentOption,
XAXisComponentOption,
YAXisComponentOption,
SeriesOption, EChartsOption,
} from "echarts";
import BaseEChart from "../BaseEChart";
import { buildLgPalette } from "../color";
import {AXIS_HIDE_STYLE, GroupedOverlayBarData, ShowLabel} from "../types";
import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill";
type Props = {
data: GroupedOverlayBarData;
height?: number;
tooltip?: TooltipComponentOption;
grid?: GridComponentOption;
xAxis?: XAXisComponentOption;
yAxis?: YAXisComponentOption;
legend?: LegendComponentOption;
barMaxWidth?: number;
showFocusLabel?: ShowLabel;
// 연도 legend(좌측)
showYearLegend?: boolean;
yearTotalColor?: Record<string, string>;
yearFocusColor?: Record<string, string>;
};
const GroupedOverlayBar = ({
data,
height = 260,
tooltip,
grid,
xAxis,
yAxis,
showYearLegend = true,
legend,
yearTotalColor,
yearFocusColor,
barMaxWidth,
showFocusLabel = "all",
}: Props) => {
const years = data.years;
const totalName = data.totalName ?? "전체";
const focusName = data.focusName ?? "LG";
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: 40, bottom: 10, containLabel: true};
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_STYLE };
const expandedCategories: string[] = [];
data.categories.forEach((cat, catIdx) => {
years.forEach(year => {
expandedCategories.push(`${year}년 ${cat}`);
});
// 카테고리 사이에 빈 공간 추가 (마지막 제외)
if (catIdx < data.categories.length - 1) {
expandedCategories.push(''); // 빈 항목
}
});
const defaultXAxis: EChartsOption["xAxis"] = {
type: "category",
data: expandedCategories,
...AXIS_HIDE_STYLE
};
// 연도별 색: 없으면 기본값(전체=회색, LG=빨강 계열)
const totalTokens = years.map((y, i) => {
const t = yearTotalColor?.[String(y)];
return t ?? (["--lg-gray-200", "--lg-gray-300", "--lg-gray-400", "--lg-gray-500"][i] ?? "--lg-gray-300");
});
const focusTokens = years.map((y, i) => {
const t = yearFocusColor?.[String(y)];
return t ?? (["--lg-red-300", "--lg-red-400", "--lg-red-500", "--lg-red-600"][i] ?? "--lg-red-500");
});
const totalColors = buildLgPalette(totalTokens);
const focusColors = buildLgPalette(focusTokens);
// 연도 legend가 실제로 렌더되려면 "name=24년" series가 있어야 함 (bar가 아닌 line으로)
const yearLegendSeries: SeriesOption[] = showYearLegend
? years.map((y, yi) => ({
id: `__year__|${y}`,
name: `${y}년`,
type: "line",
data: [],
showSymbol: false,
silent: true,
tooltip: { show: false },
emphasis: { disabled: true },
lineStyle: { color: focusColors[yi], width: 6 },
itemStyle: { color: focusColors[yi] },
}))
: [];
const series: SeriesOption[] = [];
for (let yi = 0; yi < years.length; yi++) {
const year = years[yi];
const yearLabel = `${year}년`;
const isOn = yearSelected[yearLabel] !== false;
const totalRow = data.total?.[yi] ?? [];
const focusRow = data.focus?.[yi] ?? [];
// 각 카테고리별로 데이터 배치
const totalData: (number | null)[] = [];
const focusData: (number | null)[] = [];
data.categories.forEach((cat, ci) => {
years.forEach((y, yIdx) => {
if (yIdx === yi) {
totalData.push(isOn ? (totalRow[ci] ?? null) : null);
focusData.push(isOn ? (focusRow[ci] ?? null) : null);
} else {
totalData.push(null);
focusData.push(null);
}
});
// 카테고리 사이에 null 추가 (마지막 제외)
if (ci < data.categories.length - 1) {
totalData.push(null);
focusData.push(null);
}
});
// (1) 전체(회색)
series.push({
id: `total|${year}`,
name: `${year}년-${totalName}`,
type: "bar",
z: 1,
barMaxWidth: 42,
emphasis: { disabled: true },
itemStyle: { color: totalColors[yi] },
data: totalData,
});
const showLabel = getIsShowLabel(showFocusLabel, yi, years.length);
// (2) LG(빨강) - 같은 위치에 겹침
series.push({
id: `focus|${year}`,
name: `${year}년-${focusName}`,
type: "bar",
z: 2,
barMaxWidth: 42,
barGap: "-100%",
emphasis: { disabled: true },
itemStyle: { color: focusColors[yi] },
label: showLabel
? ({
show: true,
position: "top",
formatter: (p: any) => (p?.value ?? "") as any,
} as any)
: undefined,
data: focusData,
});
}
const YEAR_ITEM_W = 25;
const YEAR_ITEM_H = 14;
const YEAR_RADIUS = 4;
let yearLegendOpt: LegendComponentOption | undefined = showYearLegend
? ({
top: 0,
left: "center",
orient: "horizontal",
data: yearLabels,
selected: yearSelected,
icon: roundedRectIcon(YEAR_ITEM_W, YEAR_ITEM_H, YEAR_RADIUS),
itemWidth: YEAR_ITEM_W,
itemHeight: YEAR_ITEM_H,
itemGap: 8,
...legend,
} as LegendComponentOption)
: undefined;
if(yearLegendOpt === undefined && legend !== undefined){
yearLegendOpt = legend;
}
return {
tooltip:
tooltip ??
({
trigger: "axis",
axisPointer: { type: "shadow" },
formatter: (params: any) => {
const arr = Array.isArray(params) ? params : [params];
const header = arr?.[0]?.axisValueLabel ?? "";
// bar만
const barItems = arr
.filter((p: any) => p?.seriesType === "bar")
.filter((p: any) => p?.value !== null && p?.value !== undefined);
// year -> {total, focus}
const map = new Map<number, { total?: number; focus?: number }>();
for (const p of barItems) {
const sid = String(p.seriesId ?? ""); // total|24, focus|24
const [kind, yStr] = sid.split("|");
const y = Number(yStr);
const e = map.get(y) ?? {};
if (kind === "total") e.total = Number(p.value);
if (kind === "focus") e.focus = Number(p.value);
map.set(y, e);
}
const lines = [...map.keys()]
.sort((a, b) => a - b)
.map((y) => {
const v = map.get(y)!;
const t = v.total ?? 0;
const f = v.focus ?? 0;
const pct = t > 0 ? ` (${Math.round((f / t) * 100)}%)` : "";
return `${totalName} ${t} 중 ${focusName} ${f}${pct}`;
});
return [header, ...lines].join("<br/>");
},
} as TooltipComponentOption),
legend: yearLegendOpt ?? undefined,
grid: grid ?? defaultGrid,
xAxis: xAxis ?? defaultXAxis,
yAxis: yAxis ?? defaultYAxis,
series: [...yearLegendSeries, ...series],
};
}, [
years,
data.categories,
data.total,
data.focus,
totalName,
focusName,
tooltip,
grid,
xAxis,
yAxis,
showYearLegend,
legend,
yearTotalColor,
yearFocusColor,
barMaxWidth,
showFocusLabel,
yearLabels,
yearSelected,
]);
const onEvents = useMemo(
() => ({
legendselectchanged: (e: any) => {
const name = String(e?.name ?? "");
if (!yearLabels.includes(name)) return;
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 GroupedOverlayBar;

View File

@@ -0,0 +1,259 @@
"use client";
import React, { useMemo, useState } from "react";
import type {
GridComponentOption,
LegendComponentOption,
TooltipComponentOption,
XAXisComponentOption,
YAXisComponentOption,
SeriesOption, EChartsOption,
} from "echarts";
import BaseEChart from "../BaseEChart";
import {AXIS_HIDE_STYLE, GroupedStackBarData, ShowLabel} from "../types";
import { buildLgPalette } from "@/components/lge-dashboard/color";
import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill";
type Props = {
data: GroupedStackBarData;
height?: number;
tooltip?: TooltipComponentOption;
grid?: GridComponentOption;
xAxis?: XAXisComponentOption;
yAxis?: YAXisComponentOption;
legend?: LegendComponentOption;
barMaxWidth?: number;
showFocusLabel?: ShowLabel;
showYearLegend?: boolean;
yearBrandPalette?: Record<string, string[]>;
};
const GroupedStackBar = ({
data,
height = 260,
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);
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] !== false;
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)),
});
}
}
const YEAR_ITEM_W = 25;
const YEAR_ITEM_H = 14;
const YEAR_RADIUS = 4;
// 3) legend 2개: (좌)연도, (우)브랜드
let yearLegendOpt: LegendComponentOption | undefined = showYearLegend
? ({
top: 0,
left: "center",
orient: "horizontal",
data: yearLabels, // yearLegendSeries name과 일치
selected: yearSelected,
icon: roundedRectIcon(YEAR_ITEM_W, YEAR_ITEM_H, YEAR_RADIUS),
itemWidth: YEAR_ITEM_W,
itemHeight: YEAR_ITEM_H,
itemGap: 8,
...legend,
} as LegendComponentOption)
: undefined;
if(yearLegendOpt === undefined && legend !== undefined){
yearLegendOpt = legend;
}
const brandLegendOpt: LegendComponentOption = ({
top: 25,
right: "center",
orient: "horizontal",
data: brands,
icon: roundedRectIcon(YEAR_ITEM_W, YEAR_ITEM_H, YEAR_RADIUS),
itemWidth: YEAR_ITEM_W,
itemHeight: YEAR_ITEM_H,
itemGap: 8,
...legend,
} 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;

View File

@@ -0,0 +1,86 @@
"use client";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
import BaseEChart from "../BaseEChart";
import {ChartData, ShowLabel, ValueFormatter} from "../types";
import { buildLgPalette } from "../color";
import {getIsShowLabel} from "@/components/lge-dashboard/chart/utill";
type Props = {
data: ChartData;
height?: number | string;
className?: string;
paletteVarNames?: string[];
valueFormatter?: ValueFormatter;
tooltip?: EChartsOption["tooltip"];
legend?: EChartsOption["legend"];
grid?: EChartsOption["grid"];
xAxis?: EChartsOption["xAxis"];
yAxis?: EChartsOption["yAxis"];
barMaxWidth?: number;
showFocusLabel?:ShowLabel;
};
const HorizontalBar = ({
data,
height,
className,
paletteVarNames,
valueFormatter,
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
showFocusLabel = "all",
}: Props) => {
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
const defaultTooltip: EChartsOption["tooltip"] = {
trigger: "axis",
axisPointer: { type: "shadow" },
valueFormatter: (v: unknown) => (typeof v === "number" ? fmt(v) : String(v)),
};
const defaultLegend: EChartsOption["legend"] = { top: 0 };
const defaultGrid: EChartsOption["grid"] = { left: 16, right: 16, top: 36, bottom: 12, containLabel: true };
const defaultXAxis: EChartsOption["xAxis"] = { type: "value" };
const defaultYAxis: EChartsOption["yAxis"] = { type: "category", data: data.categories };
return {
color: palette,
tooltip: tooltip ?? defaultTooltip,
legend: legend ?? defaultLegend,
grid: grid ?? defaultGrid,
xAxis: xAxis ?? defaultXAxis,
yAxis: yAxis ?? defaultYAxis,
series: data.series.map((s, index) => {
const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length);
return {
name: s.name,
type: "bar",
data: s.data,
emphasis: { disabled: true },
barMaxWidth: barMaxWidth ?? 42,
label: showLabel
? {
show: true,
position: "right",
formatter: (p: any) => (p?.value ?? "") as any,
}
: undefined,
};
}),
};
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel]);
return <BaseEChart option={option} height={height} className={className} />;
}
export default HorizontalBar;

View File

@@ -0,0 +1,78 @@
"use client";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
import BaseEChart from "../BaseEChart";
import type { ChartData, ValueFormatter } from "../types";
import { buildLgPalette } from "../color";
type Props = {
data: ChartData;
height?: number | string;
className?: string;
paletteVarNames?: string[];
valueFormatter?: ValueFormatter;
orientation?: "vertical" | "horizontal";
/** series.stack이 없을 때 기본 stack key */
defaultStackKey?: string;
tooltip?: EChartsOption["tooltip"];
legend?: EChartsOption["legend"];
grid?: EChartsOption["grid"];
xAxis?: EChartsOption["xAxis"];
yAxis?: EChartsOption["yAxis"];
barMaxWidth?: number;
};
const StackBar = ({
data,
height,
className,
paletteVarNames,
valueFormatter,
orientation = "vertical",
defaultStackKey = "total",
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
}: Props) => {
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
const isV = orientation === "vertical";
const defaultTooltip: EChartsOption["tooltip"] = {
trigger: "axis",
axisPointer: { type: "shadow" },
valueFormatter: (v: unknown) => (typeof v === "number" ? fmt(v) : String(v)),
};
const defaultLegend: EChartsOption["legend"] = { top: 0 };
const defaultGrid: EChartsOption["grid"] = { left: 16, right: 16, top: 36, bottom: 12, containLabel: true };
const defaultXAxis: EChartsOption["xAxis"] = isV ? { type: "category", data: data.categories } : { type: "value" };
const defaultYAxis: EChartsOption["yAxis"] = isV ? { type: "value" } : { type: "category", data: data.categories };
return {
color: palette,
tooltip: tooltip ?? defaultTooltip,
legend: legend ?? defaultLegend,
grid: grid ?? defaultGrid,
xAxis: xAxis ?? defaultXAxis,
yAxis: yAxis ?? defaultYAxis,
series: data.series.map((s) => ({
name: s.name,
type: "bar",
stack: s.stack ?? defaultStackKey,
data: s.data,
emphasis: { disabled: true },
barMaxWidth: barMaxWidth ?? 42,
})),
};
}, [data, palette, valueFormatter, orientation, defaultStackKey, tooltip, legend, grid, xAxis, yAxis, barMaxWidth]);
return <BaseEChart option={option} height={height} className={className} />;
}
export default StackBar;

View File

@@ -0,0 +1,87 @@
"use client";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
import BaseEChart from "../BaseEChart";
import {ChartData, ShowLabel, ValueFormatter} from "../types";
import { buildLgPalette } from "../color";
import {getIsShowLabel} from "@/components/lge-dashboard/chart/utill";
type Props = {
data: ChartData;
height?: number | string;
className?: string;
paletteVarNames?: string[];
valueFormatter?: ValueFormatter;
tooltip?: EChartsOption["tooltip"];
legend?: EChartsOption["legend"];
grid?: EChartsOption["grid"];
xAxis?: EChartsOption["xAxis"];
yAxis?: EChartsOption["yAxis"];
barMaxWidth?: number;
showFocusLabel?:ShowLabel;
};
const VerticalBar = ({
data,
height,
className,
paletteVarNames,
valueFormatter,
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
showFocusLabel = "all",
}: Props) => {
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
const defaultTooltip: EChartsOption["tooltip"] = {
trigger: "axis",
axisPointer: { type: "shadow" },
valueFormatter: (v: unknown) => (typeof v === "number" ? fmt(v) : String(v)),
};
const defaultLegend: EChartsOption["legend"] = { top: 0 };
const defaultGrid: EChartsOption["grid"] = { left: 16, right: 16, top: 36, bottom: 12, containLabel: true };
const defaultXAxis: EChartsOption["xAxis"] = { type: "category", data: data.categories, axisTick: { alignWithLabel: true } };
const defaultYAxis: EChartsOption["yAxis"] = { type: "value" };
return {
color: palette,
tooltip: tooltip ?? defaultTooltip,
legend: legend ?? defaultLegend,
grid: grid ?? defaultGrid,
xAxis: xAxis ?? defaultXAxis,
yAxis: yAxis ?? defaultYAxis,
series: data.series.map((s, index) => {
const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length);
return {
name: s.name,
type: "bar",
data: s.data,
emphasis: { disabled: true },
barMaxWidth: barMaxWidth ?? 42,
label: showLabel
? {
show: true,
position: "top",
formatter: (p: any) => (p?.value ?? "") as any,
}
: undefined,
}
}),
};
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel]);
return <BaseEChart option={option} height={height} className={className} />;
}
export default VerticalBar;

View File

@@ -0,0 +1,21 @@
import {ShowLabel} from "@/components/lge-dashboard";
export const roundedRectIcon = (w: number, h: number, r: number) => {
const rr = Math.max(0, Math.min(r, Math.min(w, h) / 2));
// ECharts legend icon은 'path://' 지원
return `path://M${rr},0 H${w - rr} Q${w},0 ${w},${rr} V${h - rr} Q${w},${h} ${w - rr},${h} H${rr} Q0,${h} 0,${h - rr} V${rr} Q0,0 ${rr},0 Z`;
};
export const getIsShowLabel = (showFocusLabel:ShowLabel, i:number, arrayLength: number ):boolean => {
let isShowLabel = false;
if (showFocusLabel === "all") {
isShowLabel = true;
} else if (showFocusLabel === "last") {
isShowLabel = i === arrayLength - 1;
} else if (showFocusLabel === "first") {
isShowLabel = i === 0;
}
return isShowLabel;
}

View File

@@ -0,0 +1,58 @@
type Hsl = { h: number; s: number; l: number };
const parseHslTriplet = (raw: string): Hsl | null => {
// 예: "341.1 100% 32.4%" / "0 0% 85%"
const m = raw.trim().match(/^(-?\d+(\.\d+)?)\s+(\d+(\.\d+)?)%\s+(\d+(\.\d+)?)%$/);
if (!m) return null;
return { h: Number(m[1]), s: Number(m[3]), l: Number(m[5]) };
};
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
export const resolveHslVar = (varName: string): Hsl | null => {
if (typeof window === "undefined") return null;
const raw = getComputedStyle(document.documentElement).getPropertyValue(varName);
return parseHslTriplet(raw);
};
export const hslCss = (hsl: Hsl, alpha = 1) =>
`hsl(${hsl.h} ${hsl.s}% ${hsl.l}% / ${alpha})`;
export const buildLgPalette = (varNames?: string[]): string[] => {
// globals.css에 정의된 스케일을 직접 참조(중첩 var(--chart-1) 회피)
const defaults = varNames ?? [
"--chart-1",
"--chart-2",
"--chart-3",
"--chart-4",
"--chart-5",
"--chart-6",
"--chart-7",
"--chart-8",
"--chart-9",
"--chart-10",
];
return defaults.map((v) => {
const hsl = resolveHslVar(v);
return hsl ? hslCss(hsl, 1) : v;
});
};
/** Row 기준 heatmap 배경색: 같은 row 안에서 min~max 상대비율로 칠함 */
export const rowHeatColor = (
value: number,
rowMin: number,
rowMax: number,
low: Hsl,
high: Hsl,
alpha = 0.18
) => {
const t = rowMax === rowMin ? 0.5 : (value - rowMin) / (rowMax - rowMin);
const h: Hsl = {
h: lerp(low.h, high.h, t),
s: lerp(low.s, high.s, t),
l: lerp(low.l, high.l, t),
};
return hslCss(h, alpha);
};

View File

@@ -0,0 +1,65 @@
import {bannerType, type ChartData, type DataColumn, DataTable, StackBar} from "@/components/lge-dashboard";
import BannerButtons from "@/components/lge-dashboard/BannerButtons";
import {totalFilters} from "@/config/filter.data";
import {useEffect, useState} from "react";
type CategoryByDataProps<T extends Record<string, unknown>> = {
chartData:ChartData;
tableColumns: DataColumn<T>[];
allTableData: T[];
}
const banners: bannerType[] = totalFilters.map((filter) => {
return {variable: filter.variable, variableName: filter.variableName}
})
const CategoryByData = <T extends Record<string, unknown>>({
chartData,
tableColumns,
allTableData,
}: CategoryByDataProps<T>) => {
const [selectedBanner, setSelectedBanner] = useState<bannerType>(banners[0]);
const [tableData, setTableData] = useState<T[]>([]);
useEffect(() => {
const filteredTableData = allTableData.filter((row) => row[selectedBanner.variable] === selectedBanner.variableName);
setTableData(filteredTableData);
}, [selectedBanner, allTableData]);
return (
<div className="flex gap-6 p-6">
{/* 좌측: 차트 */}
<div className="flex-shrink-0" style={{ width: "300px" }}>
<StackBar
data={chartData}
height={300}
paletteVarNames={[
"--lg-red-300",
"--lg-red-400",
"--lg-red-500",
]}
/>
</div>
{/* 중앙: 버튼 */}
<div className="flex items-center">
<BannerButtons
banners={banners}
selectedBanner={selectedBanner}
onSelectBanner={setSelectedBanner}
/>
</div>
{/* 우측: 테이블 */}
<div className="flex-1">
<DataTable
columns={tableColumns}
rows={tableData}
wrapperClassName="border rounded-lg"
/>
</div>
</div>
);
};
export default CategoryByData;

View File

@@ -0,0 +1,266 @@
"use client";
import React, { useMemo } from "react";
import { cn } from "@/lib/utils";
import type { DataColumn, SignStyle } from "../types";
type MergedChartCell<T> = {
/** 차트를 삽입할 컬럼 key(해당 컬럼 td는 startRow에서만 렌더되고 rowSpan 적용) */
key: keyof T;
/** rowSpan 시작 row index (기본 0) */
startRowIndex?: number;
/** rowSpan 수 (기본: rows.length - startRowIndex) */
rowSpan?: number;
/** chart td 클래스 (예: lg-table__sep-r) */
className?: string;
};
type Props<T extends Record<string, unknown>> = {
title?: string;
columns: DataColumn<T>[];
rows: T[];
/** 머지된 셀 안에 렌더할 차트 */
chart: React.ReactNode;
/** 어떤 컬럼을 머지-차트 셀로 교체할지 */
chartCell: MergedChartCell<T>;
/** +/-/0 표기/색상 옵션(선택) */
signStyle?: SignStyle<T>;
wrapperClassName?: string;
tableClassName?: string;
minWidthPx?: number;
};
function toNumber(v: unknown): number | null {
if (v === null || v === undefined) return null;
if (typeof v === "number") return Number.isFinite(v) ? v : null;
if (typeof v === "string") {
const s = v.trim();
if (s === "" || s === "-") return null;
const n = Number(s.replaceAll(",", ""));
return Number.isFinite(n) ? n : null;
}
return null;
}
function renderSigned(
n: number,
opts: {
display: "number" | "arrow";
showPlus: boolean;
arrowWithNumber: boolean;
zeroText: string;
}
) {
if (n === 0) return opts.zeroText;
if (opts.display === "arrow") {
const arrow = n > 0 ? "▲" : "▼";
const num = Math.abs(n);
return opts.arrowWithNumber ? `${arrow} ${num}` : arrow;
}
if (n > 0) return opts.showPlus ? `+${n}` : `${n}`;
return `${n}`;
}
export default function LeftChartTable<T extends Record<string, unknown>>({
title,
columns,
rows,
chart,
chartCell,
signStyle,
wrapperClassName,
tableClassName,
minWidthPx = 1200,
}: Props<T>) {
const hasGroupHeader = useMemo(
() => columns.some((c) => c.group) || columns.some((c) => c.headRowSpan === 2),
[columns]
);
const groupCells = useMemo(() => {
if (!hasGroupHeader) return [] as Array<
| { kind: "rowspan"; label: string; colSpan: 1; rowSpan: 2; className?: string }
| { kind: "group"; label: string; colSpan: number; rowSpan: 1; className?: string }
| { kind: "blank"; label: string; colSpan: 1; rowSpan: 1; className?: string }
>;
type Cell =
| { kind: "rowspan"; label: string; colSpan: 1; rowSpan: 2; className?: string }
| { kind: "group"; label: string; colSpan: number; rowSpan: 1; className?: string }
| { kind: "blank"; label: string; colSpan: 1; rowSpan: 1; className?: string };
const out: Cell[] = [];
let i = 0;
while (i < columns.length) {
const c = columns[i];
if (c.headRowSpan === 2) {
out.push({
kind: "rowspan",
label: c.header,
colSpan: 1,
rowSpan: 2,
className: c.headerClassName,
});
i += 1;
continue;
}
const g = c.group ?? "";
if (!g) {
out.push({ kind: "blank", label: "", colSpan: 1, rowSpan: 1, className: c.headerClassName });
i += 1;
continue;
}
let span = 1;
while (
i + span < columns.length &&
(columns[i + span].headRowSpan ?? 1) !== 2 &&
(columns[i + span].group ?? "") === g
) {
span += 1;
}
out.push({ kind: "group", label: g, colSpan: span, rowSpan: 1, className: columns[i + span -1].headerClassName });
i += span;
}
return out;
}, [columns, hasGroupHeader]);
const display = signStyle?.display ?? "number";
const arrowWithNumber = signStyle?.arrowWithNumber ?? true;
const showPlus = signStyle?.showPlus ?? true;
const zeroText = signStyle?.zeroText ?? "-";
const posCls = signStyle?.positiveTextClassName ?? "lg-num-pos";
const negCls = signStyle?.negativeTextClassName ?? "lg-num-neg";
const zeroCls = signStyle?.zeroTextClassName ?? "";
const start = chartCell.startRowIndex ?? 0;
const rowSpan = chartCell.rowSpan ?? Math.max(0, rows.length - start);
return (
<div className={cn("w-full", wrapperClassName)}>
{title && (
<div className="mb-2 font-semibold flex items-center gap-2">
<span className="w-3 h-3 bg-primary"></span>
{title}
</div>
)}
<div className="overflow-x-auto">
<table className={cn("lg-table", tableClassName)} style={{ minWidth: `${minWidthPx}px` }}>
<thead>
{hasGroupHeader ? (
<tr className="lg-table__group">
{groupCells.map((g, idx) => (
<th
key={`${g.kind}-${idx}`}
className={cn(g.className)}
colSpan={g.colSpan}
rowSpan={g.rowSpan}
>
{g.label}
</th>
))}
</tr>
) : null}
<tr className={hasGroupHeader ? "lg-table__subhead" : undefined}>
{columns
.filter((c) => (c.headRowSpan ?? 1) !== 2)
.map((c) => (
<th key={String(c.key)} className={cn(c.headerClassName)} style={c.width ? { width: c.width } : undefined}>
{c.header}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, ri) => {
const isSignRow = signStyle?.rowSelector ? signStyle.rowSelector(row, ri) : false;
return (
<tr key={ri}>
{columns.map((c) => {
// 머지-차트 셀
if (c.key === chartCell.key) {
if (ri !== start) return null;
return (
<td
key={String(c.key)}
rowSpan={rowSpan}
className={cn(c.cellClassName, chartCell.className)}
style={{ padding: 0, verticalAlign: "middle" }}
>
{chart}
</td>
);
}
// 일반 셀
const raw = c.key in row ? row[c.key] : undefined;
const content = c.render
? c.render(row)
: raw === null || raw === undefined
? ""
: typeof raw === "string" || typeof raw === "number"
? raw
: String(raw);
const n = isSignRow ? toNumber(raw) : null;
const shouldSign = isSignRow && (signStyle?.keys ? signStyle.keys.includes(c.key) : !!c.numeric);
if (c.rowHead) {
return (
<th
key={String(c.key)}
scope="row"
className={cn("lg-table__rowhead", c.cellClassName)}
style={c.width ? { width: c.width } : undefined}
>
{content}
</th>
);
}
if (!shouldSign) {
return (
<td
key={String(c.key)}
className={cn(c.cellClassName)}
style={c.width ? { width: c.width } : undefined}
>
{content}
</td>
);
}
// sign row: 값이 없으면 "-" 유지
if (n === null) {
return (
<td key={String(c.key)} className={cn(c.cellClassName)}>
-
</td>
);
}
const cls = n > 0 ? posCls : n < 0 ? negCls : zeroCls;
const txt = renderSigned(n, { display, showPlus, arrowWithNumber, zeroText });
return (
<td key={String(c.key)} className={cn(c.cellClassName, cls)}>
{txt}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,219 @@
"use client";
import React, { useMemo } from "react";
import { cn } from "@/lib/utils";
import type { ChartData, SignStyle, TopChartTableRow } from "../types";
type BaseProps = {
title?: string;
/** 테이블 상단(헤더 1행) 콜스팬 셀 내부에 렌더될 차트 */
chart?:
| React.ReactNode
| ((ctx: {
/** 테이블 컬럼(=x축) 기준으로 구성된 ChartData */
chartData: ChartData;
tableCategories: string[];
tableRows: TopChartTableRow[];
}) => React.ReactNode);
/** chart 셀 높이(px) */
chartHeight?: number;
/** 가로 스크롤 min-width */
minWidthPx?: number;
tableClassName?: string;
wrapperClassName?: string;
/** +/-/0 색상/표기 옵션(선택) */
signStyle?: SignStyle<TopChartTableRow>;
};
/**
* 1) (신규) HTML 형태: columns=categories, rows=TopChartTableRow
*/
type HtmlModeProps = BaseProps & {
categories: string[];
rows: TopChartTableRow[];
};
/**
* 2) (호환) 기존 형태: ChartData 기반으로 rows/columns 자동 생성
* - rows = data.categories
* - cols = data.series.name
*/
type ChartDataModeProps = BaseProps & {
data: ChartData;
/** 좌측 rowhead 컬럼 헤더 */
categoryHeader?: string;
/** 값 표기 포맷터 */
valueFormatter?: (v: number) => string;
};
export type TopChartTableProps = HtmlModeProps | ChartDataModeProps;
function toNumber(v: unknown): number | null {
if (v === null || v === undefined) return null;
if (typeof v === "number") return Number.isFinite(v) ? v : null;
if (typeof v === "string") {
const s = v.trim();
if (s === "" || s === "-") return null;
const n = Number(s.replaceAll(",", ""));
return Number.isFinite(n) ? n : null;
}
return null;
}
function formatSignedNumber(n: number, zeroText: string, showPlus: boolean) {
if (n === 0) return zeroText;
if (n > 0) return showPlus ? `+${n}` : `${n}`;
return `${n}`;
}
type CellValue = TopChartTableRow["values"][number];
function toCellValue(v: unknown): CellValue {
if (v === null || v === undefined) return v;
if (typeof v === "number" || typeof v === "string") return v;
return String(v);
}
export default function TopChartTable(props: TopChartTableProps) {
const {
title,
chart,
chartHeight = 260,
minWidthPx = 1600,
tableClassName,
wrapperClassName,
signStyle,
} = props;
const display = signStyle?.display ?? "number";
const arrowWithNumber = signStyle?.arrowWithNumber ?? true;
const showPlus = signStyle?.showPlus ?? true;
const posCls = signStyle?.positiveTextClassName ?? "lg-num-pos";
const negCls = signStyle?.negativeTextClassName ?? "lg-num-neg";
const zeroText = signStyle?.zeroText ?? "-";
const { categories, rows, rowHeadHeader, valueFormatter } = useMemo(() => {
if ("data" in props) {
const d = props.data;
const tableRows: TopChartTableRow[] = d.categories.map((cat, i) => ({
label: String(cat ?? ""),
values: d.series.map((s) => toCellValue(s.data[i] ?? null)),
}));
return {
categories: d.series.map((s) => s.name),
rows: tableRows,
rowHeadHeader: props.categoryHeader ?? "",
valueFormatter: props.valueFormatter,
};
}
return {
categories: props.categories,
rows: props.rows,
rowHeadHeader: "",
valueFormatter: undefined,
};
}, [props]);
// 테이블 컬럼(=categories)을 x축으로 사용하는 chartData를 항상 제공
const chartData: ChartData = useMemo(
() => ({
categories,
series: rows.map((r) => ({
name: r.label,
data: r.values.map((v) => toNumber(v) ?? null),
})),
}),
[categories, rows]
);
const chartNode = useMemo(() => {
if (!chart) return null;
return typeof chart === "function" ? chart({ chartData, tableCategories: categories, tableRows: rows }) : chart;
}, [chart, chartData, categories, rows]);
return (
<div className={cn("w-full", wrapperClassName)}>
{title && (
<div className="mb-2 font-semibold flex items-center gap-2">
<span className="w-3 h-3 bg-primary"></span>
{title}
</div>
)}
<div className="overflow-x-auto">
<table
className={cn("lg-table", tableClassName)}
style={{ minWidth: `${minWidthPx}px` }}
>
<thead>
<tr>
{/* 좌상단: rowhead 헤더(필요 시 표시). HTML과 동일하게 2행 rowspan */}
<th rowSpan={2} className="lg-table__sep-r w-15" style={{ whiteSpace: "nowrap" }}>
{rowHeadHeader}
</th>
<td colSpan={categories.length} style={{ padding: 0, height: chartNode ? chartHeight : 0 }}>
{chartNode ? <div style={{ width: "100%", height: "100%" }}>{chartNode}</div> : null}
</td>
</tr>
<tr className="lg-table__subhead">
{categories.map((c) => (
<th key={c} className={"content-text-xs"}>{c}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((r, ri) => {
const isSignRow = !!(signStyle?.rowSelector && signStyle.rowSelector(r, ri));
return (
<tr key={`${r.label}-${ri}`}>
<th scope="row" className="lg-table__rowhead lg-table__sep-r content-text-sm">
{r.label}
</th>
{categories.map((_, ci) => {
const raw = r.values?.[ci];
const n = toNumber(raw);
// 일반 행
if (!isSignRow) {
if (n === null) return <td key={ci}>-</td>;
const txt = valueFormatter ? valueFormatter(n) : n.toLocaleString();
return <td key={ci}>{txt}</td>;
}
// sign row
if (n === null) return <td key={ci}>-</td>;
if (n === 0) return <td key={ci}>{zeroText}</td>;
const cls = n > 0 ? posCls : negCls;
if (display === "arrow") {
const arrow = n > 0 ? "▲" : "▼";
const num = Math.abs(n);
return (
<td key={ci} className={cls}>
{arrow}
{arrowWithNumber ? ` ${num}` : ""}
</td>
);
}
return (
<td key={ci} className={cls}>
{formatSignedNumber(n, zeroText, showPlus)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,17 @@
export * from "./types";
export { default as BaseEChart } from "./BaseEChart";
export { default as VerticalBar } from "./chart/VerticalBar";
export { default as HorizontalBar } from "./chart/HorizontalBar";
export { default as StackBar } from "./chart/StackBar";
export { default as GroupedStackBar} from "./chart/GroupedStackBar";
export { default as GroupedOverlayBar} from "./chart/GroupedOverlayBar";
export { default as DataTable } from "./table/DataTable";
export { default as GaugeTable } from "./table/GaugeTable";
export { default as TopChartTable } from "./combo/TopChartTable";
export { default as LeftChartTable } from "./combo/LeftChartTable";
export { default as CardDefault } from "./card/Card";

View File

@@ -0,0 +1,248 @@
"use client";
import { useMemo } from "react";
import type React from "react";
import { cn } from "@/lib/utils";
import type { DataColumn, SignDisplayMode, SignStyle } from "../types";
type Props<T extends Record<string, unknown>> = {
columns: DataColumn<T>[];
rows: T[];
className?: string;
wrapperClassName?: string;
signStyle?: SignStyle<T>;
};
const parseSignedNumber = (raw: unknown): number | null => {
if (raw === null || raw === undefined) return null;
if (typeof raw === "number") return Number.isFinite(raw) ? raw : null;
if (typeof raw === "string") {
const s = raw
.trim()
.replaceAll(",", "")
.replaceAll("−", "-") // 유니코드 마이너스
.replaceAll("%", "");
if (s === "" || s === "-") return null;
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
return null;
};
const defaultFmt = (v: number) =>
Number.isInteger(v) ? String(v) : v.toLocaleString();
const signText = (
v: number,
display: SignDisplayMode,
showPlus: boolean,
arrowWithNumber: boolean,
fmt: (n: number) => string,
zeroText: string
) => {
if (display === "arrow") {
if (v > 0) return arrowWithNumber ? `▲ ${fmt(Math.abs(v))}` : "▲";
if (v < 0) return arrowWithNumber ? `▼ ${fmt(Math.abs(v))}` : "▼";
return zeroText;
}
// number
if (v > 0) return showPlus ? `+${fmt(v)}` : fmt(v);
if (v < 0) return fmt(v); // 음수는 기본적으로 - 포함
return zeroText;
};
const DataTable = <T extends Record<string, unknown>>({
columns,
rows,
className,
wrapperClassName,
signStyle,
}: Props<T>) => {
const hasGroup = columns.some((c) => !!c.group) || columns.some((c) => c.headRowSpan === 2);
// group header(1행): rowspan=2 컬럼(th) + group label(colspan)
const groupCells = useMemo(() => {
type GroupCell =
| { kind: "rowspan"; label: string; colSpan: 1; rowSpan: 2; className?: string }
| { kind: "group"; label: string; colSpan: number; rowSpan: 1; className?: string }
| { kind: "blank"; label: string; colSpan: 1; rowSpan: 1; className?: string };
if (!hasGroup) return [] as GroupCell[];
const res: GroupCell[] = [];
let i = 0;
while (i < columns.length) {
const c = columns[i];
if (c.headRowSpan === 2) {
res.push({ kind: "rowspan", label: c.header, colSpan: 1, rowSpan: 2, className: c.headerClassName });
i++;
continue;
}
const g = c.group;
if (!g) {
// group 미지정: 1칸짜리 blank group 셀
res.push({ kind: "blank", label: "", colSpan: 1, rowSpan: 1, className: c.headerClassName });
i++;
continue;
}
// 같은 group 연속 구간 colSpan
let span = 1;
let j = i + 1;
while (j < columns.length && columns[j].headRowSpan !== 2 && columns[j].group === g) {
span++;
j++;
}
res.push({ kind: "group", label: g, colSpan: span, rowSpan: 1, className: c.headerClassName });
i = j;
}
return res;
}, [columns, hasGroup]);
const {
rowSelector,
keys,
paint = "text",
display = "number",
showPlus = true,
arrowWithNumber = false,
zeroText = "-",
valueFormatter,
positiveTextClassName = "text-primary font-semibold",
negativeTextClassName = "text-info font-semibold",
zeroTextClassName = "text-gray-600",
positiveCellBg = "hsl(var(--primary) / 0.08)",
negativeCellBg = "hsl(var(--info) / 0.08)",
zeroCellBg = "hsl(var(--lg-gray-200) / 0.6)",
} = signStyle ?? ({} as SignStyle<T>);
const fmt = valueFormatter ?? defaultFmt;
const isSignRow = (row: T, rowIndex: number) =>
!!signStyle && !!rowSelector?.(row, rowIndex);
const isTargetKey = (k: keyof T) => {
if (!signStyle) return false;
if (keys && keys.length) return keys.includes(k);
// keys 미지정이면 numeric 컬럼 전체
const col = columns.find((c) => c.key === k);
return !!col?.numeric;
};
const signClass = (v: number) => {
if (v > 0) return positiveTextClassName;
if (v < 0) return negativeTextClassName;
return zeroTextClassName;
};
const signBg = (v: number) => {
if (v > 0) return positiveCellBg;
if (v < 0) return negativeCellBg;
return zeroCellBg;
};
return (
<div className={cn("w-full overflow-x-auto", wrapperClassName)}>
<table className={cn("lg-table", className)}>
<thead>
{hasGroup && (
<tr className="lg-table__group">
{groupCells.map((g, idx) => (
<th
key={`${g.kind}-${g.label}-${idx}`}
colSpan={g.colSpan}
rowSpan={g.rowSpan}
className={g.className}
>
{g.label}
</th>
))}
</tr>
)}
<tr className={hasGroup ? "lg-table__subhead" : undefined}>
{columns
.filter((c) => c.headRowSpan !== 2)
.map((c) => (
<th key={String(c.key)} style={{ width: c.width }} className={c.headerClassName}>
{c.header}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, rIdx) => {
const signRow = isSignRow(row, rIdx);
return (
<tr key={rIdx}>
{columns.map((c) => {
const raw = row[c.key];
const align = c.align ?? (c.numeric ? "right" : "center");
// headRowSpan=2 컬럼은 thead 2행에서 제외되므로, tbody는 항상 렌더
// sign row + target column이면 색상/표기 적용
const applySign = signRow && isTargetKey(c.key) && !c.rowHead;
if (applySign) {
const n = parseSignedNumber(raw);
const displayText =
n === null ? "-" : signText(n, display, showPlus, arrowWithNumber, fmt, zeroText);
const style: React.CSSProperties =
paint === "cell"
? { textAlign: align, background: signBg(n ?? 0) }
: { textAlign: align };
return (
<td key={String(c.key)} style={style} className={c.cellClassName}>
<span className={cn(n === null ? "text-gray-500" : signClass(n))}>
{displayText}
</span>
</td>
);
}
// 일반 셀
const content = c.render
? c.render(row)
: raw === null || raw === undefined
? ""
: typeof raw === "string" || typeof raw === "number"
? raw
: String(raw);
if (c.rowHead) {
return (
<th
key={String(c.key)}
className={cn("lg-table__rowhead", c.cellClassName)}
style={{ textAlign: align }}
>
{content}
</th>
);
}
return (
<td key={String(c.key)} style={{ textAlign: align }} className={c.cellClassName}>
{content}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
);
}
export default DataTable;

View File

@@ -0,0 +1,162 @@
"use client";
import { useMemo } from "react";
import { cn } from "@/lib/utils";
import {GaugeColumn} from "../types";
type Props<T extends Record<string, unknown>> = {
columns: GaugeColumn<T>[];
rows: T[];
className?: string;
wrapperClassName?: string;
/** value가 0~100이 아니라 0~1이면 scale=100 */
scale?: number; // 기본 1
/** 색상(기본: primary 채움 + gray 트랙) */
fillColor?: string; // ex) "hsl(var(--primary) / 0.9)"
trackColor?: string; // ex) "hsl(var(--lg-gray-200) / 0.9)"
/** 셀 높이 */
cellHeight?: number; // 기본 26
/** 숫자 표시 여부/포맷 */
showValue?: boolean; // 기본 true
valueFormatter?: (v: number) => string;
};
const num = (v: unknown) => {
if (typeof v === "number" && Number.isFinite(v)) return v;
if (typeof v === "string") {
const n = Number(v.replaceAll(",", "").replaceAll("%", "").trim());
return Number.isFinite(n) ? n : null;
}
return null;
};
const GaugeTable = <T extends Record<string, unknown>>({
columns,
rows,
className,
wrapperClassName,
scale = 1,
fillColor = "hsl(var(--primary) / 0.85)",
trackColor = "hsl(var(--lg-gray-200) / 0.85)",
cellHeight = 26,
showValue = true,
valueFormatter,
}: Props<T>) => {
const hasGroup = columns.some((c) => !!c.group);
const groupCells = useMemo(() => {
if (!hasGroup) return [];
const res: { label: string; span: number }[] = [];
let i = 0;
while (i < columns.length) {
const g = columns[i].group ?? "";
let span = 1;
let j = i + 1;
while (j < columns.length && (columns[j].group ?? "") === g) {
span++;
j++;
}
res.push({ label: g, span });
i = j;
}
return res;
}, [columns, hasGroup]);
const fmt = valueFormatter ?? ((v: number) => String(Math.round(v)));
return (
<div className={cn("w-full overflow-x-auto", wrapperClassName)}>
<table className={cn("lg-table", className)}>
<thead>
{hasGroup && (
<tr className="lg-table__group">
{groupCells.map((g, idx) => (
<th key={`${g.label}-${idx}`} colSpan={g.span}>
{g.label}
</th>
))}
</tr>
)}
<tr className={hasGroup ? "lg-table__subhead" : undefined}>
{columns.map((c) => (
<th key={String(c.key)} style={{ width: c.width }}>
{c.header}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, rIdx) => (
<tr key={rIdx}>
{columns.map((c) => {
const align = c.align ?? (c.rowHead ? "left" : "center");
if (c.rowHead) {
const raw = row[c.key];
const label = c.renderLabel
? c.renderLabel(row)
: raw === null || raw === undefined
? ""
: typeof raw === "string" || typeof raw === "number"
? raw
: String(raw);
return (
<th
key={String(c.key)}
className="lg-table__rowhead"
style={{ textAlign: align }}
>
{label}
</th>
);
}
const raw = row[c.key];
const v = num(raw);
const max = c.max ?? 100;
const ratio = v === null ? 0 : Math.max(0, Math.min(1, (v * scale) / max));
const pct = ratio * 100;
return (
<td key={String(c.key)} style={{ textAlign: align }}>
<div
className="relative overflow-hidden rounded-md"
style={{
height: cellHeight,
background: trackColor,
border: "1px solid hsl(var(--border))",
}}
>
<div
className="absolute inset-y-0 left-0"
style={{
width: `${pct}%`,
background: fillColor,
}}
/>
{showValue && (
<div
className="relative z-10 flex h-full items-center justify-center content-text-sm"
style={{ color: "hsl(var(--lg-gray-900))" }}
>
{v === null ? "-" : fmt(v)}
</div>
)}
</div>
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
);
}
export default GaugeTable;

View File

@@ -0,0 +1,249 @@
import type React from "react";
export type NewNumber = number | null | undefined;
export const PRODUCT_KEY_MAP = {
washingMachine: "세탁기",
refrigerator: "냉장고",
airConditioner: "에어컨",
tv: "TV",
microwave: "전자 레인지",
vacuumCleaner: "청소기",
laptop: "노트북",
kimchiRefrigerator: "김치 냉장고",
airFryer: "에어 프라이어",
tablet: "태블릿",
waterPurifier: "정수기",
monitor: "모니터",
airPurifier: "공기 청정기",
dryer: "건조기",
electricRange: "전기 레인지",
humidifier: "가습기",
dehumidifier: "제습기",
oven: "오븐",
robotVacuum: "로봇 청소기",
dishwasher: "식기 세척기",
massageChair: "안마 의자",
clothingCareSystem: "의류 관리기",
foodWasteDisposer: "음식물처리기",
projector: "빔프로젝터",
comboAirCareProduct: "복합 에어케어 제품",
ventilationSystem: "환기 시스템",
wineCellar: "와인 셀러",
premiumBathroomVentFan: "프리미엄 욕실 환풍기",
shoeCareSystem: "신발 관리기",
} as const;
export const BANNER_KEY_MAP = {
// 라이프 스테이지
single: "미혼",
noKids: "무자녀",
preschoolKids: "미취학",
schoolKids: "취학자녀",
adultKids: "성인자녀",
independentSenior: "독립시니어",
// 가구원수
hh1: "1인 가구",
hh2: "2인 가구",
hh3: "3인 가구",
hh4Plus: "4인 이상 가구",
// 연령
age20s: "20대",
age30s: "30대",
age40s: "40대",
age50s: "50대",
age60s: "60대",
// 점유형태
ownerOccupied: "자가",
jeonse: "전세",
depositAndMonthly: "전+월세 (보증금有)",
monthlyNoDeposit: "월세 (보증금無)",
otherTenure: "기타",
// 주거형태
apartment: "아파트",
house: "주택",
officetel: "오피스텔",
villa: "(연립)빌라",
studio: "원룸",
otherHousingType: "기타",
// 평형
under19Pyeong: "19평 이하",
pyeong20s: "20평형 대",
pyeong30s: "30평형 대",
pyeong40s: "40평형 대",
pyeong50Plus: "50평형 대 이상",
// 권역
regionCapital: "서울, 인천, 경기도",
regionGyeongnamBusanUlsan: "경남, 부산, 울산",
regionGyeongbukDaegu: "경북, 대구",
regionJeollaGwangju: "전라도, 광주",
regionChungcheongDaejeonSejong: "충청, 대전, 세종",
regionGangwonJeju: "강원, 제주",
// 소득
incomeUnder299: "299만원 이하",
income300to599: "300~599만원 이하",
income600to899: "600~899만원 이하",
income900Plus: "900만원 이상",
} as const;
export type ProductKey = keyof typeof PRODUCT_KEY_MAP;
export type BannerKey = keyof typeof BANNER_KEY_MAP;
export type ServerBaseRow = {
year: number;
rowLabel: string;
total: number;
};
// { year, rowLabel, total, ...category }
export type ServerProductRow = ServerBaseRow & Partial<Record<ProductKey, number>>;
// { year, rowLabel, total, ...banner }
// (배너는 기본 41개 키 + 차트별 추가 키가 생길 수 있으니 확장 허용)
export type ServerBannerRow = ServerBaseRow &
Partial<Record<BannerKey, number>> & {
[k: string]: number | string;
};
export type ChartSeries = {
/** legend에 노출될 이름 */
name: string;
/** categories와 동일 길이 */
data: NewNumber[];
/** stacked bar 용 */
stack?: string; // 같은 stack 값끼리 누적
};
export type ChartData = {
/** x(세로바)/y(가로바) 카테고리 */
categories: string[];
/** 시리즈(막대/스택 등) */
series: ChartSeries[];
};
/**
* (GroupedStackBar)
* - categories: x축 카테고리(예: 제품)
* - years: 그룹(예: 24/25/26)
* - brands: 스택 구성요소(예: LG/SS/C브랜드)
* - values: [yearIndex][brandIndex][categoryIndex]
*/
export type GroupedStackBarData = {
categories: string[];
years: Array<string | number>;
brands: string[];
values: Array<Array<Array<number | null | undefined>>>;
};
export type GroupedOverlayBarData = {
categories: string[]; // 제품
years: number[]; // 예: [24,25,26]
totalName?: string; // default: "전체"
focusName?: string; // default: "LG"
total: Array<Array<number | null>>; // [yearIndex][categoryIndex]
focus: Array<Array<number | null>>; // [yearIndex][categoryIndex]
};
/** (TopChartTable) HTML 테이블용 row (columns=categories) */
export type TopChartTableRow = {
/** 좌측 rowhead 라벨 */
label: string;
/** categories 순서대로 값 */
values: Array<number | string | null | undefined>;
};
export type ValueFormatter = (v: number) => string;
export type DataColumn<T> = {
key: keyof T;
header: string;
width?: number | string;
align?: "left" | "center" | "right";
group?: string; // 2단 헤더 그룹
groupKey?:string;// 2단 헤더 그룹
/** group header에서 해당 컬럼 헤더를 rowspan=2로 올릴 때 사용(HTML 테이블과 동일한 구조 지원) */
headRowSpan?: 1 | 2;
rowHead?: boolean; // 첫 컬럼 등 row header
numeric?: boolean; // 숫자열(정렬 기본값/색상 타겟 기본값에 사용)
/** th 클래스(필요 시 lg-table__sep-r 등 주입) */
headerClassName?: string;
/** td 클래스(필요 시 lg-table__sep-l, lg-table__sep-r 등 주입) */
cellClassName?: string;
render?: (row: T) => React.ReactNode;
};
export type GaugeColumn<T> = {
key: keyof T;
header: string;
width?: number | string;
align?: "left" | "center" | "right";
group?: string;
rowHead?: boolean;
/** 게이지 최대값 기준(기본 100) */
max?: number;
renderLabel?: (row: T) => React.ReactNode; // rowHead에 쓰기 좋음
};
export type SignDisplayMode = "number" | "arrow";
export type SignStyle<T> = {
/** 어떤 row에 +/ -/ 0 색상표기를 적용할지 선택 */
rowSelector: (row: T, rowIndex: number) => boolean;
/** 어떤 컬럼에 적용할지(미지정 시 numeric 컬럼 전체) */
keys?: (keyof T)[];
/** 색상 적용 방식 */
paint?: "text" | "cell"; // 기본 text
/** 표기 방식 */
display?: SignDisplayMode; // 기본 number
showPlus?: boolean; // number 모드에서 + 표시(기본 true)
/** 0 값 표기(기본 "-") */
zeroText?: string;
/** arrow 모드 옵션 */
arrowWithNumber?: boolean; // ▲ 2 처럼 (기본 false)
/** 값 포맷(기본: 정수면 그대로/그 외 toLocaleString) */
valueFormatter?: (v: number) => string;
/** 색상 커스터마이즈(기본: + primary, - info, 0 gray) */
positiveTextClassName?: string; // 기본 "text-primary font-semibold"
negativeTextClassName?: string; // 기본 "text-info font-semibold"
zeroTextClassName?: string; // 기본 "text-gray-600"
positiveCellBg?: string; // ex) "hsl(var(--primary) / 0.08)"
negativeCellBg?: string; // ex) "hsl(var(--info) / 0.08)"
zeroCellBg?: string; // ex) "hsl(var(--lg-gray-200) / 0.6)"
};
export const signStyleGapRow: SignStyle<TopChartTableRow> = {
rowSelector: (row) => row.label === "전년 대비 GAP(%)",
display: "arrow",
arrowWithNumber: true,
paint: "text",
};
/** X 축 패딩 없앤 GridOption*/
export const GRID_X_NOT_PADDING = { left: 0, right: 0, top: 50, bottom: 10, containLabel: false } as const;
/** T 축 패딩 없앤 GridOption*/
export const GRID_Y_NOT_PADDING = { left: 10, right: 10, top: 0, bottom: 0, containLabel: false } as const;
/** 축 스타일 감춤 */
export const AXIS_HIDE_STYLE = { axisLabel: { show: false }, axisTick: { show: false }, axisLine: { show: false }} as const;
/** ChartLabel 보여지는 옵션 */
export type ShowLabel = "none" | "all" | "last" | "first";
export type bannerType = {
variable:string;
variableName:string;
}

368
src/config/sample.data.ts Normal file
View File

@@ -0,0 +1,368 @@
// sample.data.ts
import {
ProductKey,
BannerKey,
ServerBannerRow,
ServerProductRow,
} from "@/components/lge-dashboard";
import {PRODUCT_KEY_MAP} from "@/components/lge-dashboard";
const PRODUCT_KEYS = Object.keys(PRODUCT_KEY_MAP) as ProductKey[];
const randInt = (min: number, max: number) =>
Math.floor(Math.random() * (max - min + 1)) + min;
type RandRange = { min: number | null; max: number | null };
const makeProductDist = (range?: RandRange): Record<ProductKey, number> => {
const min = range?.min ?? 1;
const max = range?.max ?? 60;
const out = {} as Record<ProductKey, number>;
for (const k of PRODUCT_KEYS) out[k] = randInt(min, max);
return out;
};
const productRow = (
year: number,
rowLabel: string,
total: number,
range: RandRange = { min: null, max: null },
extra?: Partial<Record<ProductKey, number>>,
): ServerProductRow => ({
year,
rowLabel,
total,
...makeProductDist(range),
...(extra ?? {}),
});
const round1 = (n: number) => Math.round(n * 10) / 10;
const calcGapRow = (row26: ServerProductRow, row25: ServerProductRow): ServerProductRow => {
const out: ServerProductRow = {
year: row26.year,
rowLabel: "gap",
total: row26.total - row25.total,
};
for (const k of PRODUCT_KEYS) {
const a = row26[k] ?? 0;
const b = row25[k] ?? 0;
out[k] = a - b;
}
return out;
};
const calcCagrRow = (row24: ServerProductRow, row26: ServerProductRow): ServerProductRow => {
const years = 2; // 24 -> 26
const out: ServerProductRow = { year: row26.year, rowLabel: "CAGR", total: 0 };
// total은 참고용으로만: (26/24) CAGR %
out.total =
row24.total > 0 ? round1((Math.pow(row26.total / row24.total, 1 / years) - 1) * 100) : 0;
for (const k of PRODUCT_KEYS) {
const v24 = row24[k] ?? 0;
const v26 = row26[k] ?? 0;
out[k] = v24 > 0 ? round1((Math.pow(v26 / v24, 1 / years) - 1) * 100) : 0;
}
return out;
};
// 배너(41키) 그룹별 합이 100 되도록 고정 분포
const BANNER_DIST_DEFAULT: Record<BannerKey, number> = {
// 라이프스테이지(6)
single: 20,
noKids: 20,
preschoolKids: 20,
schoolKids: 20,
adultKids: 10,
independentSenior: 10,
// 가구원수(4)
hh1: 25,
hh2: 35,
hh3: 20,
hh4Plus: 20,
// 연령(5)
age20s: 15,
age30s: 25,
age40s: 30,
age50s: 20,
age60s: 10,
// 점유형태(5)
ownerOccupied: 50,
jeonse: 25,
depositAndMonthly: 10,
monthlyNoDeposit: 10,
otherTenure: 5,
// 주거형태(6)
apartment: 60,
house: 15,
officetel: 10,
villa: 10,
studio: 3,
otherHousingType: 2,
// 평형(5)
under19Pyeong: 10,
pyeong20s: 20,
pyeong30s: 35,
pyeong40s: 20,
pyeong50Plus: 15,
// 권역(6)
regionCapital: 45,
regionGyeongnamBusanUlsan: 15,
regionGyeongbukDaegu: 10,
regionJeollaGwangju: 10,
regionChungcheongDaejeonSejong: 10,
regionGangwonJeju: 10,
// 소득(4)
incomeUnder299: 20,
income300to599: 40,
income600to899: 25,
income900Plus: 15,
};
const bannerRow = (year: number, rowLabel: string, total: number, extra?: Record<string, number>): ServerBannerRow => ({
year,
rowLabel,
total,
...BANNER_DIST_DEFAULT,
...(extra ?? {}),
});
const TREND_24: ServerProductRow = productRow(24, "24년", 45, {min:70, max:99});
const TREND_25: ServerProductRow = productRow(25, "25년", 46, {min:70, max:99});
const TREND_26: ServerProductRow = productRow(26, "26년", 48, {min:70, max:99});
export const apiTrendCategories: ServerProductRow[] = [
calcGapRow(TREND_26, TREND_25),
TREND_24,
TREND_25,
TREND_26,
calcCagrRow(TREND_24, TREND_26),
];
export const apiBrandByYearCategories: ServerProductRow[] = [
productRow(24, "LG", 1200),
productRow(24, "Samsung", 1300),
productRow(24, "Cbrand", 600),
productRow(25, "LG", 1250),
productRow(25, "Samsung", 1320),
productRow(25, "Cbrand", 620),
productRow(26, "LG", 1280),
productRow(26, "Samsung", 1340),
productRow(26, "Cbrand", 640),
];
const OWN_PEN_24: ServerProductRow = productRow(24, "24년", 45);
const OWN_PEN_25: ServerProductRow = productRow(25, "25년", 46);
const OWN_PEN_26: ServerProductRow = productRow(26, "26년", 48);
export const apiOwnShareOfTotalPenetration: ServerProductRow[] = [
calcGapRow(OWN_PEN_26, OWN_PEN_25),
OWN_PEN_24,
OWN_PEN_25,
OWN_PEN_26,
];
const BUY_24: ServerProductRow = productRow(24, "24년", 45, {min:20, max:40});
const BUY_25: ServerProductRow = productRow(25, "25년", 46, {min:20, max:40});
const BUY_26: ServerProductRow = productRow(26, "26년", 48, {min:20, max:40});
export const apiTrendBuy: ServerProductRow[] = [
calcGapRow(TREND_26, TREND_25),
BUY_24,
BUY_25,
BUY_26,
];
const OWN_BUY_24: ServerProductRow = productRow(24, "24년", 41, {min:5, max:20});
const OWN_BUY_25: ServerProductRow = productRow(25, "25년", 42, {min:5, max:20});
const OWN_BUY_26: ServerProductRow = productRow(26, "26년", 43, {min:5, max:20});
export const apiOwnShareOfTotalPurchase: ServerProductRow[] = [
calcGapRow(OWN_BUY_26, OWN_BUY_25),
productRow(26, "전체 구입율 중 자사제품 비율", 46),
OWN_BUY_24,
OWN_BUY_25,
OWN_BUY_26,
];
export const apiLifeStageByProduct: ServerBannerRow[] = [
bannerRow(26, "냉장고", 1200, { single: 18, noKids: 22, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "세탁기", 1100, { single: 18, noKids: 22, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "에어컨", 900, { single: 22, noKids: 18, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "TV", 950, { single: 18, noKids: 22, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "청소기", 1000, { single: 22, noKids: 18, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "김치 냉장고", 700, { single: 22, noKids: 18, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "공기 청정기", 800, { single: 22, noKids: 18, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "가습기", 650, { single: 22, noKids: 18, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "제습기", 600, { single: 18, noKids: 22, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "건조기", 500, { single: 18, noKids: 22, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "식기세척기", 450, { single: 22, noKids: 18, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "의류 관리기", 320, { single: 18, noKids: 22, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
bannerRow(26, "로봇 청소기", 420, { single: 22, noKids: 18, preschoolKids: 20, schoolKids: 20, adultKids: 10, independentSenior: 10 }),
];
/** ---------------------------
* API #6
* year rowLabel total banner
* 26 사례수 / 보유율 / gap / 보유대수
* -------------------------- */
export const apiOwnershipSummary: ServerBannerRow[] = [
bannerRow(26, "사례수", 2000),
bannerRow(26, "보유율", 85),
bannerRow(26, "gap", 1), // 26-25
bannerRow(26, "보유대수", 1.2),
];
/** ---------------------------
* API #7
* year rowLabel total banner
* 26 사례수
* 26 26
* 25 25
* 24 24
* -------------------------- */
export const apiYearIndex: ServerBannerRow[] = [
bannerRow(26, "사례수", 2000),
bannerRow(26, "26", 100),
bannerRow(25, "25", 100),
bannerRow(24, "24", 100),
];
/** ---------------------------
* API #8
* year rowLabel total banner
* 25/26 사례수 + 브랜드
* -------------------------- */
export const apiBrandShareByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 500),
bannerRow(25, "lg", 48),
bannerRow(25, "삼성", 40),
bannerRow(25, "위니아", 4),
bannerRow(25, "캐리어", 3),
bannerRow(25, "하이얼", 1),
bannerRow(25, "기타", 4),
bannerRow(26, "사례수", 520),
bannerRow(26, "lg", 47),
bannerRow(26, "삼성", 40),
bannerRow(26, "위니아", 5),
bannerRow(26, "캐리어", 3),
bannerRow(26, "하이얼", 1),
bannerRow(26, "기타", 4),
];
/** ---------------------------
* API #9
* year rowLabel total banner
* 25/26 사례수 + 도어 타입
* -------------------------- */
export const apiFridgeDoorTypeByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 480),
bannerRow(25, "1도어", 5),
bannerRow(25, "2도어 상 냉동+하 냉장", 22),
bannerRow(25, "2도어 상 냉장+하 냉동", 8),
bannerRow(25, "2도어 양문형", 36),
bannerRow(25, "4도어", 28),
bannerRow(25, "기타", 1),
bannerRow(26, "사례수", 500),
bannerRow(26, "1도어", 5),
bannerRow(26, "2도어 상 냉동+하 냉장", 23),
bannerRow(26, "2도어 상 냉장+하 냉동", 12),
bannerRow(26, "2도어 양문형", 35),
bannerRow(26, "4도어", 25),
bannerRow(26, "기타", 0),
];
/** ---------------------------
* API #10
* year rowLabel total banner
* 25/26 사례수 + 보유 경로(구매 경로)
* -------------------------- */
export const apiPurchasePathByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 520),
bannerRow(25, "신규 구입", 8),
bannerRow(25, "기존 제품 작동하나 신규 구입", 4),
bannerRow(25, "기존 제품 고장으로 신규 구입", 40),
bannerRow(25, "추가 구입", 48),
bannerRow(26, "사례수", 540),
bannerRow(26, "신규 구입", 8),
bannerRow(26, "기존 제품 작동하나 신규 구입", 4),
bannerRow(26, "기존 제품 고장으로 신규 구입", 40),
bannerRow(26, "추가 구입", 48),
];
/** ---------------------------
* API #11
* year rowLabel total banner
* 25/26 결제수단
* -------------------------- */
export const apiPaymentMethodByYear: ServerBannerRow[] = [
bannerRow(25, "일시불", 60),
bannerRow(25, "할부", 30),
bannerRow(25, "렌탈", 10),
bannerRow(26, "일시불", 58),
bannerRow(26, "할부", 32),
bannerRow(26, "렌탈", 10),
];
/** ---------------------------
* API #12
* year rowLabel total banner
* 26 사례수 / 구매율 / gap
* -------------------------- */
export const apiPurchaseRateKpis: ServerBannerRow[] = [
bannerRow(26, "사례수", 700),
bannerRow(26, "구매율", 35),
bannerRow(26, "gap", 2), // 26-25
];
/** ---------------------------
* API #13
* year rowLabel total banner
* 25/26 사례수 + 유통채널
* -------------------------- */
export const apiPurchaseChannelByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 650),
bannerRow(25, "오프라인 단독 매장", 25),
bannerRow(25, "전자제품 양판점", 20),
bannerRow(25, "대형할인점", 10),
bannerRow(25, "백화점", 5),
bannerRow(25, "오픈마켓", 15),
bannerRow(25, "제조사 공식 홈페이지", 8),
bannerRow(25, "포털 쇼핑채널 입점몰", 4),
bannerRow(25, "백화점 기반 쇼핑몰", 2),
bannerRow(25, "TV 홈쇼핑", 3),
bannerRow(25, "유통사 온라인 쇼핑몰", 4),
bannerRow(25, "라이프스타일 쇼핑몰", 2),
bannerRow(25, "해외 직구/대행 사이트", 1),
bannerRow(25, "중고거래 사이트", 1),
bannerRow(26, "사례수", 680),
bannerRow(26, "오프라인 단독 매장", 24),
bannerRow(26, "전자제품 양판점", 20),
bannerRow(26, "대형할인점", 10),
bannerRow(26, "백화점", 5),
bannerRow(26, "오픈마켓", 16),
bannerRow(26, "제조사 공식 홈페이지", 9),
bannerRow(26, "포털 쇼핑채널 입점몰", 4),
bannerRow(26, "백화점 기반 쇼핑몰", 2),
bannerRow(26, "TV 홈쇼핑", 3),
bannerRow(26, "유통사 온라인 쇼핑몰", 3),
bannerRow(26, "라이프스타일 쇼핑몰", 2),
bannerRow(26, "해외 직구/대행 사이트", 1),
bannerRow(26, "중고거래 사이트", 1),
];

6
src/const/lgConst.ts Normal file
View File

@@ -0,0 +1,6 @@
import {PRODUCT_KEY_MAP} from "@/components/lge-dashboard";
export const PRODUCT_KEYS = Object.keys(PRODUCT_KEY_MAP) as Array<keyof typeof PRODUCT_KEY_MAP>;
export const PRODUCTS = Object.values(PRODUCT_KEY_MAP) as Array<string>;
export const YEARS = [24, 25, 26];
export const BRAND_LIST = ['Cbrand', 'Samsung', 'LG'];