Files
lg-cxdash-front/src/components/lge-dashboard/combo/LeftChartTable.tsx

275 lines
9.0 KiB
TypeScript

"use client";
import React, { useMemo } from "react";
import { cn, parseNumber } from "@/lib/utils";
import type { DataColumn, SignStyle } from "../types";
import SectionTitle from "../SectionTitle";
import { TABLE_DIMENSIONS } from "@/const/chartConst";
import {isSampleRow} from "@/lib/lg-dashboard";
import {SAMPLE_SIZE_NOTICE, UNIT_TEXT} from "@/const/lgConst";
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;
starUnder30Sample?: boolean;
unitText?: string;
};
// toNumber는 utils.ts의 parseNumber로 통합됨
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 = TABLE_DIMENSIONS.MIN_WIDTH.COMPACT,
starUnder30Sample = true,
unitText = UNIT_TEXT,
}: 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)}>
<div className="mb-2 flex items-center justify-between">
{ title && <SectionTitle title={title} />}
{
(unitText || starUnder30Sample) &&
<div className="ml-auto text-gray-500 content-text-xs font-semibold text-right">
{unitText}
{starUnder30Sample && <><br/>{SAMPLE_SIZE_NOTICE}</>}
</div>
}
</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 sampleRow = isSampleRow(row.rowLabel as string ?? "");
const isSignRow = signStyle?.rowSelector ? signStyle.rowSelector(row, ri) : false;
return (
<tr key={ri}>
{columns.map((c) => {
// 머지-차트 셀
if (c.key === chartCell.key && ri >= start) {
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 = c.numeric ? parseNumber(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) {
const numContent = c.numeric ? parseNumber(content) ?? 0 : 0;
const isStar = starUnder30Sample && sampleRow && numContent < 30;
return (
<td
key={String(c.key)}
className={cn(c.cellClassName)}
style={c.width ? { width: c.width } : undefined}
>
{isStar?`${content}*`: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>
);
}