Files
kfpa-cx-dash-front/src/components/combo/TopChartTable.tsx

302 lines
9.9 KiB
TypeScript

"use client";
import React, { useMemo } from "react";
import { cn, parseNumber } from "@/lib/utils";
import BaseTableHeader from "../table/core/BaseTableHeader";
import {
formatSignedValue, getSignTextClass,
resolveSignStyle,
toCssSize,
toRoundedNumber
} from "../table/core/table-core.helpers";
import {
TopChartTablePreAppendCell,
TopChartTablePreAppendCellConfig,
TopChartTableRow,
TopChartTableSectionRow
} from "./types";
import {ChartData} from "../chart/types";
import {CHART_HEIGHTS, TABLE_DIMENSIONS} from "../chart/chart.config";
import type {DataColumn, SignStyle} from "@/components/table/types";
import { KFPA_DECIMAL_POINT } from "@/config/kfpa.config";
export type TopChartTableProps = {
title?: string;
columns: DataColumn<Record<string, unknown>>[];
rows: TopChartTableRow[];
sectionRows?: TopChartTableSectionRow[];
chart?:
| React.ReactNode
| ((ctx: {
chartData: ChartData;
}) => React.ReactNode);
chartHeight?: number | string;
minWidthPx?: number;
minWidth?: number;
maxWidth?: number;
subLabelHeader?: string;
rowHeaderWidth?: number | string;
categoryColumnWidth?: number | string;
categoryColumnWidths?: Array<number | string | undefined>;
tableClassName?: string;
wrapperClassName?: string;
signStyle?: SignStyle<TopChartTableRow>;
};
const isPreAppendCellConfig = (
cell: TopChartTablePreAppendCell
): cell is TopChartTablePreAppendCellConfig =>
typeof cell === "object" &&
cell !== null &&
!Array.isArray(cell) &&
"content" in cell;
const renderPreAppendCell = (cell: TopChartTablePreAppendCell, index: number) => {
if (!isPreAppendCellConfig(cell)) {
return <td key={`pre-append-${index}`}>{cell}</td>;
}
return (
<td
key={`pre-append-${index}`}
className={cell.className}
colSpan={cell.colSpan}
rowSpan={cell.rowSpan}
style={{ width: toCssSize(cell.width), minWidth: toCssSize(cell.width) }}
>
{cell.content}
</td>
);
};
const getLeadingColumnWidths = (rows: TopChartTableRow[], preAppendColumnCount: number) => {
const widths = Array<string | undefined>(preAppendColumnCount).fill(undefined);
rows.forEach((row) => {
let columnIndex = 0;
row.preAppendCells?.forEach((cell) => {
const colSpan = isPreAppendCellConfig(cell) ? cell.colSpan ?? 1 : 1;
const width = isPreAppendCellConfig(cell) ? toCssSize(cell.width) : undefined;
if (width && colSpan === 1 && !widths[columnIndex]) {
widths[columnIndex] = width;
}
columnIndex += colSpan;
});
});
return widths;
};
const getLabelColumnWidth = (rows: TopChartTableRow[]) =>
rows.map((row) => toCssSize(row.labelWidth)).find(Boolean);
const getColumnKey = (column: DataColumn<Record<string, unknown>>) =>
String(column.id ?? ("key" in column ? column.key : column.header));
const getColumnLabel = (column: DataColumn<Record<string, unknown>>) =>
typeof column.header === "string" ? column.header : getColumnKey(column);
export default function TopChartTable({
title,
rows,
sectionRows = [],
columns,
chart,
chartHeight = CHART_HEIGHTS.DEFAULT,
minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.STANDARD,
minWidth,
maxWidth,
subLabelHeader = "",
rowHeaderWidth,
categoryColumnWidth,
categoryColumnWidths,
tableClassName,
wrapperClassName,
signStyle,
}: Readonly<TopChartTableProps>) {
const resolvedSignStyle = resolveSignStyle(signStyle, {
positiveTextClassName: "kfpa-num-pos",
negativeTextClassName: "kfpa-num-neg",
zeroTextClassName: "text-zero",
arrowWithNumber: true,
valueFormatter: (value) => value.toFixed(KFPA_DECIMAL_POINT),
});
const maxPreAppendCellCount = useMemo(
() => Math.max(0, ...rows.map((row) => row.preAppendCells?.length ?? 0)),
[rows]
);
const leadingColumnCount = maxPreAppendCellCount + 1;
const leadingColumnWidths = useMemo(
() => [...getLeadingColumnWidths(rows, maxPreAppendCellCount), getLabelColumnWidth(rows)],
[maxPreAppendCellCount, rows]
);
const columnLabels = useMemo(() => columns.map(getColumnLabel), [columns]);
const chartData: ChartData = useMemo(
() => ({
categories: columnLabels,
series: rows.map((row) => ({
name: row.label,
data: row.values.map((value) => parseNumber(value) ?? null),
})),
}),
[columnLabels, rows]
);
const chartNode = useMemo(() => {
if (!chart) {
return null;
}
return typeof chart === "function" ? chart({ chartData }) : chart;
}, [chart, chartData]);
const rowHeaderStyle = useMemo(() => {
const width = toCssSize(rowHeaderWidth);
return width ? { width, minWidth: width } : undefined;
}, [rowHeaderWidth]);
const hasCategoryHeaderRow = useMemo(
() => subLabelHeader.trim().length > 0 || columns.some((column) => getColumnLabel(column).trim().length > 0),
[columns, subLabelHeader]
);
return (
<div className={cn("w-full", wrapperClassName)}>
<BaseTableHeader title={title} />
<div className="overflow-x-auto">
<table className={cn("kfpa-table kfpa-table", tableClassName)} style={{ minWidth: `${minWidth ?? minWidthPx}px` , maxWidth: maxWidth ? `${maxWidth}px` : undefined}}>
<colgroup>
{leadingColumnWidths.map((width, index) => (
<col key={`leading-col-${index}`} style={width ? { width, minWidth: width } : undefined} />
))}
{columns.map((column, index) => {
const width = toCssSize(categoryColumnWidths?.[index] ?? column.width ?? categoryColumnWidth);
return (
<col
key={`category-col-${getColumnKey(column)}`}
style={width ? { width, minWidth: width } : undefined}
/>
);
})}
</colgroup>
<thead>
<tr className="kfpa-table__chart-row border-none">
<th
colSpan={leadingColumnCount}
className={cn(rowHeaderWidth ? undefined : "w-44", "border-none")}
style={{ whiteSpace: "nowrap", ...rowHeaderStyle }}
/>
<td colSpan={columns.length} style={{ padding: 0, height: chartNode ? chartHeight : 0 }}>
{chartNode ? <div style={{ width: "100%", height: "100%" }}>{chartNode}</div> : null}
</td>
</tr>
{hasCategoryHeaderRow && (
<tr className="kfpa-table__subhead kfpa-table__subhead kfpa-table__after-chart-row">
<th
colSpan={leadingColumnCount}
className={"kfpa-table-border-none content-text-base bg-transparent"}
style={rowHeaderStyle}
>
{subLabelHeader}
</th>
{columns.map((column) => {
return (
<th
key={getColumnKey(column)}
className={cn(column.headerClassName, "content-text-base")}
style={{ textAlign: column.align }}
>
{column.header}
</th>
)
})}
</tr>
)}
</thead>
<tbody>
{rows.map((row, rowIndex) => {
const signRow = !!signStyle?.rowSelector?.(row, rowIndex);
const preAppendCells = row.preAppendCells ?? [];
const sectionRowsAfterCurrentRow = sectionRows.filter(
(sectionRow) => sectionRow.afterRowIndex === rowIndex
);
return (
<React.Fragment key={`${row.label}-${rowIndex}`}>
<tr>
{preAppendCells.map(renderPreAppendCell)}
<th
scope="row"
className={cn(
"kfpa-table__rowhead kfpa-table__sep-r kfpa-table__sep-r content-text-base",
row.labelClassName
)}
style={{
width: toCssSize(row.labelWidth),
minWidth: toCssSize(row.labelWidth),
}}
>
{row.label}
</th>
{columns.map((column, categoryIndex) => {
const rawValue = row.values?.[categoryIndex];
const decimalPlaces = row.decimalPlaces ?? KFPA_DECIMAL_POINT;
const roundedValue = toRoundedNumber(rawValue, decimalPlaces);
if (roundedValue === null) {
return <td key={getColumnKey(column)} className={cn(column.cellClassName, row.cellClassName)} style={{ textAlign: column.align }}>-</td>;
}
if(!signRow) {
return (
<td key={getColumnKey(column)} className={cn(column.cellClassName, row.cellClassName)} style={{ textAlign: column.align }}>
{roundedValue.toFixed(decimalPlaces)}
</td>
);
}
return (
<td
key={getColumnKey(column)}
className={cn(column.cellClassName, row.cellClassName, getSignTextClass(roundedValue, resolvedSignStyle))}
style={{ textAlign: column.align }}
>
{formatSignedValue(roundedValue, resolvedSignStyle)}
</td>
);
})}
</tr>
{sectionRowsAfterCurrentRow.map((sectionRow, sectionRowIndex) => (
<tr key={`section-row-${rowIndex}-${sectionRowIndex}`}>
<td
colSpan={leadingColumnCount}
className={cn("kfpa-table__section-row content-text-base", sectionRow.className)}
>
{sectionRow.content}
</td>
<td
colSpan={columns.length}
className={cn("kfpa-table__section-row content-text-base", sectionRow.bodyClassName)}
/>
</tr>
))}
</React.Fragment>
);
})}
</tbody>
</table>
</div>
</div>
);
}