248 lines
8.1 KiB
TypeScript
248 lines
8.1 KiB
TypeScript
"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; |