260917_01_ENH: 테이블에서 학당명 핸들러 부여하고 사용자가 가변처리 할수 있도록 수정

This commit is contained in:
2026-09-17 14:02:06 +09:00
parent c12fd7133e
commit cfc88018aa
3 changed files with 115 additions and 16 deletions

View File

@@ -42,9 +42,12 @@ export default function ProgressPage() {
}, [reportQuery.data, admin, selectedCenterCds]);
const centerNameWidth = useAutoFitCenterNameWidth(content);
// 사용자가 핸들로 폭을 조절하면 그 값을 우선 사용하고, 그 이후엔 자동 맞춤을 멈춘다(새로고침 시 초기화).
const [manualCenterNameWidth, setManualCenterNameWidth] = useState<number | null>(null);
const effectiveCenterNameWidth = manualCenterNameWidth ?? centerNameWidth;
const leadingColumns = useMemo(
() => LEADING_COLUMNS.map((column) => column.key === "centerName" ? { ...column, width: centerNameWidth } : column),
[centerNameWidth],
() => LEADING_COLUMNS.map((column) => column.key === "centerName" ? { ...column, width: effectiveCenterNameWidth, resizable: true } : column),
[effectiveCenterNameWidth],
);
const handleDownload = () => {
@@ -81,6 +84,9 @@ export default function ProgressPage() {
scale="current"
leadingColumns={leadingColumns}
mergeLeadingColumnsWhen={(row) => row.centerCd === 0}
onColumnResize={(key, width) => {
if (key === "centerName") setManualCenterNameWidth(width);
}}
/>
)}
</div>

View File

@@ -40,9 +40,12 @@ export default function ReportPage() {
}, [reportQuery.data, admin, selectedCenterCds]);
const centerNameWidth = useAutoFitCenterNameWidth(content);
const [manualCenterNameWidth, setManualCenterNameWidth] = useState<number | null>(null);
const effectiveCenterNameWidth = manualCenterNameWidth ?? centerNameWidth;
const leadingColumns = useMemo(
() => LEADING_COLUMNS.map((column) => column.key === "centerName" ? { ...column, width: centerNameWidth } : column),
[centerNameWidth],
() => LEADING_COLUMNS.map((column) => column.key === "centerName" ? { ...column, width: effectiveCenterNameWidth, resizable: true } : column),
[effectiveCenterNameWidth],
);
const handleDownload = () => {
@@ -73,7 +76,15 @@ export default function ReportPage() {
{reportQuery.isLoading ? (
<p className="text-sm text-muted-foreground">불러오는 중...</p>
) : (
<ReportTable headers={reportQuery.data?.headers ?? []} content={content} scale="final" leadingColumns={leadingColumns} />
<ReportTable
headers={reportQuery.data?.headers ?? []}
content={content}
scale="final"
leadingColumns={leadingColumns}
onColumnResize={(key, width) => {
if (key === "centerName") setManualCenterNameWidth(width);
}}
/>
)}
</div>
);

View File

@@ -1,6 +1,6 @@
"use client";
import { useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent, type ReactNode } from "react";
import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { cn } from "@/lib/utils";
import type { ReportContent, ReportHeader } from "@/types/report";
@@ -11,6 +11,8 @@ export interface ReportLeadingColumn {
label: string;
width: number;
sticky?: boolean;
// true면 헤더 우측 경계에 드래그 핸들을 표시해 사용자가 폭을 조절할 수 있다(onColumnResize와 함께 사용).
resizable?: boolean;
render: (row: ReportContent) => ReactNode;
}
@@ -25,8 +27,13 @@ export interface ReportTableProps {
leafColumnWidth?: number;
// 0을 "-"로 표시할지(기본값), "0.00"/"0.0"처럼 반올림된 값 그대로 표시할지 선택한다.
zeroAsDash?: boolean;
// resizable 컬럼의 드래그 핸들로 폭이 바뀔 때 호출된다. 실제 폭 상태는 상위에서 관리한다.
onColumnResize?: (key: string, width: number) => void;
}
// 드래그로 줄일 수 있는 최소 폭(px). sticky 컬럼이 뭉개지지 않도록 하한을 둔다.
const MIN_RESIZE_WIDTH = 80;
const BODY_CELL_TEXT_CLASS = "truncate";
const CENTER_NAME_CELL_CLASS = "whitespace-pre-line break-keep";
@@ -44,6 +51,10 @@ const formatReportValue = (raw: string | null, field: "value7" | "value100", zer
// 공백이 없으면 단어 중간(한글 글자 사이)도 끊어버려서, 한국어에 맞는 break-keep(word-break: keep-all)을 쓴다.
const HEADER_CELL_TEXT_CLASS = "whitespace-normal break-keep";
// 마지막 sticky(고정) 컬럼 우측에 주는 강조 경계선. 가로 스크롤 시 고정 영역이 어디까지인지
// 시각적으로 분명히 보여준다. 옅은 기본 border 대신 2px muted-foreground를 사용한다.
const STICKY_EDGE_BORDER_CLASS = "border-r-2 border-r-muted-foreground/40";
export function ReportTable({
headers,
content,
@@ -53,6 +64,7 @@ export function ReportTable({
maxBodyHeight = "70vh",
leafColumnWidth = 120,
zeroAsDash = true,
onColumnResize,
}: ReportTableProps) {
const layout = useMemo(() => buildReportHeaderLayout(headers, scale), [headers, scale]);
const totalColumns = leadingColumns.length + layout.leafColumns.length;
@@ -72,6 +84,12 @@ export function ReportTable({
const theadRef = useRef<HTMLTableSectionElement>(null);
const [rowTopOffsets, setRowTopOffsets] = useState<number[]>([]);
// 리사이즈 가능한 컬럼의 <col>과 헤더 <th>. 드래그 중에는 이 요소들의 폭만 직접 갱신해
// 표 전체 리렌더 없이 부드럽게 리사이즈하고, 최종 폭만 mouseup에서 state로 커밋한다.
const resizableColRef = useRef<HTMLTableColElement>(null);
const resizableHeadRef = useRef<HTMLTableCellElement>(null);
const resizeRafRef = useRef<number | null>(null);
useLayoutEffect(() => {
const thead = theadRef.current;
if (!thead) return;
@@ -79,12 +97,15 @@ export function ReportTable({
const measure = () => {
const rows = Array.from(thead.querySelectorAll("tr"));
let acc = 0;
setRowTopOffsets(
rows.map((tr) => {
const offset = acc;
acc += tr.getBoundingClientRect().height;
return offset;
}),
const next = rows.map((tr) => {
const offset = acc;
acc += tr.getBoundingClientRect().height;
return offset;
});
// 가로 리사이즈처럼 높이가 그대로면 오프셋 값도 동일하다. 값이 같으면 배열 참조를 유지해
// 불필요한 리렌더(리사이즈 중 ResizeObserver 발동으로 인한 이중 렌더)를 막는다.
setRowTopOffsets((prev) =>
prev.length === next.length && prev.every((value, index) => value === next[index]) ? prev : next,
);
};
@@ -94,6 +115,52 @@ export function ReportTable({
return () => observer.disconnect();
}, [layout]);
// 헤더 우측 핸들을 누른 지점을 기준으로 마우스 이동량만큼 폭을 조절한다.
// 드래그 중에는 setState 대신 <col>/<th>의 폭만 직접 갱신(rAF로 프레임당 1회)해서 표 바디의
// 리렌더/reconciliation을 피하고, 최종 폭만 mouseup에서 state로 커밋한다.
// (리사이즈 대상은 항상 마지막 sticky 컬럼이라 이후 sticky 컬럼의 left 오프셋을 다시 계산할 필요가 없다.)
// document 리스너로 처리해 커서가 셀 밖으로 나가도 드래그가 유지되게 한다.
const handleResizeStart = (key: string, startWidth: number) => (event: ReactMouseEvent) => {
event.preventDefault();
event.stopPropagation();
const startX = event.clientX;
let latestWidth = startWidth;
const applyWidth = () => {
resizeRafRef.current = null;
const col = resizableColRef.current;
if (col) col.style.width = `${latestWidth}px`;
const head = resizableHeadRef.current;
if (head) {
head.style.width = `${latestWidth}px`;
head.style.minWidth = `${latestWidth}px`;
head.style.maxWidth = `${latestWidth}px`;
}
};
const onMouseMove = (moveEvent: MouseEvent) => {
latestWidth = Math.max(MIN_RESIZE_WIDTH, startWidth + (moveEvent.clientX - startX));
if (resizeRafRef.current === null) resizeRafRef.current = requestAnimationFrame(applyWidth);
};
const onMouseUp = () => {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
document.body.style.userSelect = "";
document.body.style.cursor = "";
if (resizeRafRef.current !== null) {
cancelAnimationFrame(resizeRafRef.current);
resizeRafRef.current = null;
}
// 최종 폭만 state로 커밋 → 자동 맞춤/새로고침/후속 렌더와 일관되게 동기화한다.
onColumnResize?.(key, latestWidth);
};
document.body.style.userSelect = "none";
document.body.style.cursor = "col-resize";
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
};
return (
<div className="rounded-md border">
{/* DataTable.tsx와 동일하게 x/y 스크롤을 하나의 컨테이너에서 처리해야 sticky의 기준 컨테이너가 어긋나지 않는다.
@@ -103,7 +170,11 @@ export function ReportTable({
<table className="w-full table-fixed caption-bottom text-sm">
<colgroup>
{leadingColumns.map((column) => (
<col key={column.key} style={{ width: column.width }} />
<col
key={column.key}
ref={column.resizable ? resizableColRef : undefined}
style={{ width: column.width }}
/>
))}
{layout.leafColumns.map((leaf, index) => (
<col key={`${leaf.headerId}-${leaf.field}-${index}`} style={{ width: leafColumnWidth }} />
@@ -125,14 +196,25 @@ export function ReportTable({
maxWidth: column.width,
};
if (column.sticky) style.left = leftOffsets[columnIndex];
const isStickyEdge = columnIndex === stickyCount - 1;
return (
<TableHead
key={column.key}
ref={column.resizable ? resizableHeadRef : undefined}
rowSpan={layout.rowCount}
style={style}
className={cn("h-auto bg-muted py-2 text-center align-middle font-semibold text-foreground", HEADER_CELL_TEXT_CLASS)}
className={cn("h-auto bg-muted py-2 text-center align-middle font-semibold text-foreground", HEADER_CELL_TEXT_CLASS, isStickyEdge && STICKY_EDGE_BORDER_CLASS)}
>
{column.label}
{column.resizable && onColumnResize ? (
// sticky 셀은 position이 static이 아니므로 이 핸들의 absolute 기준이 된다.
<span
role="separator"
aria-orientation="vertical"
onMouseDown={handleResizeStart(column.key, column.width)}
className="absolute inset-y-0 right-0 z-10 w-1.5 cursor-col-resize select-none hover:bg-primary/40"
/>
) : null}
</TableHead>
);
})
@@ -167,12 +249,12 @@ export function ReportTable({
return (
<TableRow key={row.centerCd}>
{merged ? (
<TableCell colSpan={stickyCount} style={{ position: "sticky", left: 0, zIndex: 10 }} className={cn("bg-background text-center font-medium", leadingColumns[stickyCount - 1].key === "centerName" ? CENTER_NAME_CELL_CLASS : BODY_CELL_TEXT_CLASS)}>
<TableCell colSpan={stickyCount} style={{ position: "sticky", left: 0, zIndex: 10 }} className={cn("bg-background text-center font-medium", leadingColumns[stickyCount - 1].key === "centerName" ? CENTER_NAME_CELL_CLASS : BODY_CELL_TEXT_CLASS, STICKY_EDGE_BORDER_CLASS)}>
{leadingColumns[stickyCount - 1].render(row)}
</TableCell>
) : (
leadingColumns.slice(0, stickyCount).map((column, columnIndex) => (
<TableCell key={column.key} style={{ position: "sticky", left: leftOffsets[columnIndex], zIndex: 10 }} className={cn("bg-background text-center", column.key === "centerName" ? CENTER_NAME_CELL_CLASS : BODY_CELL_TEXT_CLASS)}>
<TableCell key={column.key} style={{ position: "sticky", left: leftOffsets[columnIndex], zIndex: 10 }} className={cn("bg-background text-center", column.key === "centerName" ? CENTER_NAME_CELL_CLASS : BODY_CELL_TEXT_CLASS, columnIndex === stickyCount - 1 && STICKY_EDGE_BORDER_CLASS)}>
{column.render(row)}
</TableCell>
))