Files
frontend/apps/sn/app/(map-layout)/map/components/pipeAnalysis/PipeAnalysisSummaryTable.tsx
T

253 lines
8.2 KiB
TypeScript

"use client";
import { Fragment, useMemo, type CSSProperties, type ReactNode } from "react";
import {
getCoreRowModel,
useReactTable,
type ColumnDef,
} from "@tanstack/react-table";
import {
StandardDataTable,
type UiHeadProps,
} from "@common/business_components";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@common/components";
import type {
PipeAnalysisSummaryViewRow,
PipeAnalysisYearMaterialGroup,
PipeAnalysisYearMaterialGroupRow,
} from "./pipeAnalysisUtils";
import "./pipe-analysis-summary-table.css";
type SummaryRow = PipeAnalysisSummaryViewRow | PipeAnalysisYearMaterialGroup;
type Props = {
rows: PipeAnalysisSummaryViewRow[];
groups: PipeAnalysisYearMaterialGroup[];
grouped: boolean;
heads: UiHeadProps[];
title: string;
total: number;
page: number;
pageSize: number;
actions: ReactNode;
onPageChange: (page: number) => void;
onCellClick: (row: PipeAnalysisSummaryViewRow, columnId: string) => void;
onGroupedCellClick: (
group: PipeAnalysisYearMaterialGroup,
row: PipeAnalysisYearMaterialGroupRow,
columnId: string,
) => void;
};
/** 지역 식별 열은 가로 스크롤해도 남겨 두고, 모든 집계 방식에 같은 너비를 사용한다. */
const FIXED_WIDTHS: Record<string, number> = {
rowNo: 56,
ctpvNm: 120,
sggNm: 120,
swtrmtZoneNm: 160,
totalLengthKm: 100,
};
/** 기존 집계와 같은 천 단위 구분 및 소수점 세 자리 표시를 유지한다. */
const formatValue = (value: unknown) => {
if (value === null || value === undefined || value === "") return "-";
return typeof value === "number"
? value.toLocaleString("ko-KR", { maximumFractionDigits: 3 })
: String(value);
};
/** 표준 카드·페이징 안에서 관로 집계의 병합 셀과 고정 열을 렌더링한다. */
export default function PipeAnalysisSummaryTable({
rows,
groups,
grouped,
heads,
title,
total,
page,
pageSize,
actions,
onPageChange,
onCellClick,
onGroupedCellClick,
}: Props) {
// 표준 페이징이 기존 행 또는 처리구역 그룹 수를 기준으로 동작하도록 연결한다.
const data = useMemo<SummaryRow[]>(
() => (grouped ? groups : rows),
[grouped, groups, rows],
);
// 실제 셀은 renderTable에서 그리며 표준 테이블에는 열 식별자를 등록한다.
const columns = useMemo<ColumnDef<SummaryRow>[]>(
() => heads.map((head) => ({ id: head.id })),
[heads],
);
// 페이지 단위는 기존과 동일하게 일반 표는 행, 병합 표는 처리구역 그룹이다.
const pagination = { pageIndex: Math.max(0, page - 1), pageSize };
const table = useReactTable({
data,
columns,
state: { pagination },
rowCount: total,
manualPagination: true,
getCoreRowModel: getCoreRowModel(),
onPaginationChange: (updater) => {
const next =
typeof updater === "function" ? updater(pagination) : updater;
if (next.pageIndex !== pagination.pageIndex)
onPageChange(next.pageIndex + 1);
},
});
// 열별 픽셀 너비와 왼쪽 고정 위치를 한곳에서 계산해 헤더·본문을 일치시킨다.
const layout = useMemo(() => {
let left = 0;
return heads.map((head) => {
const width =
FIXED_WIDTHS[head.id] ??
(head.id === "elapsedYearLabel"
? 112
: String(head.title).length > 10
? 160
: 120);
const fixed = head.id in FIXED_WIDTHS;
const style: CSSProperties = fixed ? { left } : {};
if (fixed) left += width;
return { ...head, width, fixed, style };
});
}, [heads]);
// 모든 재질 열의 너비 합계를 최소 폭으로 사용해 좁은 팝업에서 열 압축을 막는다.
const tableWidth = layout.reduce((sum, head) => sum + head.width, 0);
/** 실제 결과가 있는 수치만 기존 상세 조회 핸들러로 연결한다. */
const cell = (
head: (typeof layout)[number],
value: unknown,
onClick?: () => void,
rowSpan?: number,
) => (
<TableCell
key={head.id}
rowSpan={rowSpan}
style={head.style}
className={`${head.fixed ? "pipe-summary-fixed" : ""} ${head.id === "totalLengthKm" ? "pipe-summary-fixed-end" : ""}`}
align={head.align === "right" ? "right" : "center"}
>
{onClick ? (
<button type="button" className="pipe-summary-value" onClick={onClick}>
{formatValue(value)}
</button>
) : (
<span className="pipe-summary-text" title={formatValue(value)}>
{formatValue(value)}
</span>
)}
</TableCell>
);
return (
<StandardDataTable
key={`${title}-${page}`}
table={table}
title={title}
flushOuterMargin
className="sn-pipe-summary-grid"
scrollMode="both"
maxHeight="calc(100dvh - 34rem)"
minTableWidth={`${tableWidth}px`}
actions={actions}
renderTable={() => (
<Table
variant="default"
style={{
width: `max(100%, ${tableWidth}px)`,
minWidth: tableWidth,
tableLayout: "fixed",
}}
>
<colgroup>
{layout.map((head) => (
<col key={head.id} style={{ width: head.width }} />
))}
</colgroup>
<TableHeader>
<TableRow>
{layout.map((head) => (
<TableHead
key={head.id}
scope="col"
style={head.style}
className={`${head.fixed ? "pipe-summary-fixed" : ""} ${head.id === "totalLengthKm" ? "pipe-summary-fixed-end" : ""}`}
>
<span title={String(head.title)}>{head.title}</span>
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{grouped
? groups.map((group, groupIndex) => (
<Fragment
key={`${group.base.ctpvCd}-${group.base.sggCd}-${group.base.swtrmtZoneNm}-${groupIndex}`}
>
{group.rows.map((row, rowIndex) => (
<TableRow
key={row.elapsedYearBucket}
className={
rowIndex === 0 ? "pipe-summary-group-start" : ""
}
>
{layout.map((head) => {
if (head.fixed) {
if (rowIndex !== 0) return null;
return cell(
head,
group[
head.id as keyof PipeAnalysisYearMaterialGroup
],
undefined,
group.rows.length,
);
}
if (head.id === "elapsedYearLabel")
return cell(head, row.elapsedYearLabel);
const value = Number(row.metrics[head.id] ?? 0);
return cell(
head,
value,
value > 0 && row.cellFilters[head.id]
? () => onGroupedCellClick(group, row, head.id)
: undefined,
);
})}
</TableRow>
))}
</Fragment>
))
: rows.map((row, index) => (
<TableRow
key={`${row.__base.ctpvCd}-${row.__base.sggCd}-${row.__base.swtrmtZoneNm}-${index}`}
>
{layout.map((head) =>
cell(
head,
head.id === "rowNo"
? total - ((page - 1) * pageSize + index)
: row[head.id],
row.__cellFilters[head.id] && Number(row[head.id]) > 0
? () => onCellClick(row, head.id)
: undefined,
),
)}
</TableRow>
))}
</TableBody>
</Table>
)}
/>
);
}