1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
|
"use client"
import * as React from "react"
import { flexRender, type Table as TanstackTable } from "@tanstack/react-table"
import { ChevronRight, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
import { getCommonPinningStylesWithBorder } from "@/lib/data-table"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { DataTablePagination } from "@/components/data-table/data-table-pagination"
import { DataTableResizer } from "@/components/data-table/data-table-resizer"
import { useAutoSizeColumns } from "@/hooks/useAutoSizeColumns"
interface DataTableProps<TData> extends React.HTMLAttributes<HTMLDivElement> {
table: TanstackTable<TData>
floatingBar?: React.ReactNode | null
autoSizeColumns?: boolean
compact?: boolean // 컴팩트 모드 옵션 추가
}
// ✅ compactStyles를 정적으로 정의 (매번 새로 생성 방지)
const COMPACT_STYLES = {
row: "h-7", // 행 높이 축소
cell: "py-1 px-2 text-sm", // 셀 패딩 축소 및 폰트 크기 조정
groupRow: "py-1 bg-muted/20 text-sm", // 그룹 행 패딩 축소
emptyRow: "h-16", // 데이터 없을 때 행 높이 조정
header: "py-1 px-2 text-sm", // 헤더 패딩 축소
headerHeight: "h-8", // 헤더 높이 축소
};
const NORMAL_STYLES = {
row: "",
cell: "",
groupRow: "bg-muted/20",
emptyRow: "h-24",
header: "",
headerHeight: "",
};
/**
* 멀티 그룹핑 + 그룹 토글 + 그룹 컬럼/헤더 숨김 + Indent + 리사이징 + 컴팩트 모드
*/
export function DataTable<TData>({
table,
floatingBar = null,
autoSizeColumns = true,
compact = false, // 기본값은 false로 설정
children,
className,
maxHeight,
...props
}: DataTableProps<TData> & { maxHeight?: string | number }) {
useAutoSizeColumns(table, autoSizeColumns)
// nested header 감지: columns 속성을 가진 헤더가 있는지 확인
const hasNestedHeader = React.useMemo(() => {
return table.getHeaderGroups().some(headerGroup =>
headerGroup.headers.some(header => 'columns' in header.column.columnDef)
)
}, [table])
// ✅ compactStyles를 useMemo로 메모이제이션
const compactStyles = React.useMemo(() =>
compact ? COMPACT_STYLES : NORMAL_STYLES,
[compact]
);
const stableChildren = React.useMemo(() => {
console.log("📦 DataTable children 메모이제이션됨");
return children;
}, [children]);
return (
<div className={cn("w-full space-y-2.5 overflow-auto", className)} {...props}>
{stableChildren}
<div className="max-w-[100vw] overflow-auto" style={{ maxHeight: maxHeight || '35rem' }} >
<Table
className={cn(
"[&>thead]:sticky [&>thead]:top-0 [&>thead]:z-10",
!hasNestedHeader && "table-fixed" // nested header가 없으면 table-fixed 적용
)}>
{/* nested header가 있으면 table-fixed 제거, 없으면 적용 */}
{/* 테이블 헤더 */}
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className={compactStyles.headerHeight}>
{headerGroup.headers.map((header) => {
if (header.column.getIsGrouped()) {
return null
}
return (
<TableHead
key={header.id}
colSpan={header.colSpan}
data-column-id={header.column.id}
className={cn(
compactStyles.header,
"whitespace-normal break-words",
// 그룹 헤더(자식 컬럼이 있는 경우)에 스타일 적용 (nested column)
('columns' in header.column.columnDef) && "group-header"
)}
style={{
...getCommonPinningStylesWithBorder({
column: header.column,
isHeader: true
}),
// 부모 그룹 헤더는 colSpan으로 너비가 결정되므로 width 설정하지 않음
// 자식 헤더만 개별 width 설정
...(!('columns' in header.column.columnDef) && {
width: header.getSize()
}),
}}
>
<div style={{ position: "relative" }}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
{/* 부모 그룹 헤더는 리사이즈 불가, 자식 헤더만 리사이즈 가능 */}
{header.column.getCanResize() && !('columns' in header.column.columnDef) && (
<DataTableResizer header={header} />
)}
</div>
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
{/* 테이블 바디 */}
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => {
// 그룹핑 헤더 Row
if (row.getIsGrouped()) {
const groupingColumnId = row.groupingColumnId ?? ""
const groupingColumn = table.getColumn(groupingColumnId)
let columnLabel = groupingColumnId
if (groupingColumn) {
const headerDef = groupingColumn.columnDef.meta?.excelHeader
if (typeof headerDef === "string") {
columnLabel = headerDef
}
}
return (
<TableRow
key={row.id}
className={compactStyles.groupRow}
data-state={row.getIsExpanded() && "expanded"}
>
<TableCell
colSpan={table.getVisibleFlatColumns().length}
className={compact ? "py-1 px-2" : ""}
>
{row.getCanExpand() && (
<button
onClick={row.getToggleExpandedHandler()}
className="inline-flex items-center justify-center mr-2 w-5 h-5"
style={{
marginLeft: `${row.depth * 1.5}rem`,
}}
>
{row.getIsExpanded() ? (
<ChevronUp size={compact ? 14 : 16} />
) : (
<ChevronRight size={compact ? 14 : 16} />
)}
</button>
)}
<span className="font-semibold whitespace-normal break-words">
{columnLabel}: {row.getValue(groupingColumnId)}
</span>
<span className="ml-2 text-xs text-muted-foreground">
({row.subRows.length} rows)
</span>
</TableCell>
</TableRow>
)
}
// 일반 Row
return (
<TableRow
key={row.id}
className={compactStyles.row}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => {
if (cell.column.getIsGrouped()) {
return null
}
return (
<TableCell
key={cell.id}
data-column-id={cell.column.id}
className={cn(compactStyles.cell, "whitespace-normal break-words")}
style={{
...getCommonPinningStylesWithBorder({ column: cell.column }),
width: cell.column.getSize(),
}}
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
)
})}
</TableRow>
)
})
) : (
// 데이터가 없을 때
<TableRow>
<TableCell
colSpan={table.getAllColumns().length}
className={compactStyles.emptyRow + " text-center"}
>
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex flex-col gap-2.5">
{/* Pagination */}
<DataTablePagination table={table} />
{/* Floating Bar (선택된 행 있을 때) */}
{table.getFilteredSelectedRowModel().rows.length > 0 && floatingBar}
</div>
</div>
)
}
|