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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
|
"use client"
import * as React from "react"
import {
ColumnDef,
ColumnFiltersState,
SortingState,
VisibilityState,
flexRender,
getCoreRowModel,
getFacetedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
Table,
getGroupedRowModel,
getExpandedRowModel,
ColumnSizingState, ColumnPinningState
} from "@tanstack/react-table"
import {
Table as UiTable,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { getCommonPinningStylesWithBorder } from "@/lib/data-table"
import { cn } from "@/lib/utils"
import { ChevronRight, ChevronUp } from "lucide-react"
import { ClientDataTableAdvancedToolbar } from "./data-table-toolbar"
import { ClientDataTablePagination } from "./data-table-pagination"
import { DataTableResizer } from "./data-table-resizer"
import { useAutoSizeColumns } from "@/hooks/useAutoSizeColumns"
import { globalFilterFn } from "./table-filters"
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]
data: TData[]
advancedFilterFields: any[]
autoSizeColumns?: boolean
compact?: boolean // compact 모드 추가
onSelectedRowsChange?: (selected: TData[]) => void
maxHeight?: string | number
/** 추가로 표시할 버튼/컴포넌트 */
children?: React.ReactNode
/** 선택 상태 초기화 트리거 */
clearSelection?: boolean
initialColumnPinning?: ColumnPinningState
/** Table 인스턴스를 상위 컴포넌트에 전달하는 콜백 */
onTableReady?: (table: Table<TData>) => void
}
export function ClientDataTable<TData, TValue>({
columns,
data,
advancedFilterFields,
autoSizeColumns = true,
compact = true, // 기본값 true
children,
maxHeight,
onSelectedRowsChange,
clearSelection,
initialColumnPinning,
onTableReady
}: DataTableProps<TData, TValue>) {
// (1) React Table 상태
const [rowSelection, setRowSelection] = React.useState({})
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
const [sorting, setSorting] = React.useState<SortingState>([])
const [grouping, setGrouping] = React.useState<string[]>([])
const [columnSizing, setColumnSizing] = React.useState<ColumnSizingState>({})
const [columnPinning, setColumnPinning] = React.useState<ColumnPinningState>(
initialColumnPinning || {
left: ["select","TAG_NO", "TAG_DESC", "status"],
right: ["update", 'actions'],
}
)
// 🎯 스크롤 상태 감지 추가
const [isScrolled, setIsScrolled] = React.useState(false)
const table = useReactTable({
data,
columns,
state: {
sorting,
columnVisibility,
rowSelection,
columnFilters,
grouping,
columnSizing,
columnPinning
},
columnResizeMode: "onChange",
onColumnSizingChange: setColumnSizing,
enableRowSelection: true,
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
onColumnVisibilityChange: setColumnVisibility,
onGroupingChange: setGrouping,
globalFilterFn: globalFilterFn as any,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFacetedRowModel: getFacetedRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
getGroupedRowModel: getGroupedRowModel(),
autoResetPageIndex: false,
getExpandedRowModel: getExpandedRowModel(),
enableColumnPinning: true,
onColumnPinningChange: setColumnPinning
})
useAutoSizeColumns(table, autoSizeColumns)
// 🆕 Table 인스턴스를 상위 컴포넌트에 전달
React.useEffect(() => {
if (onTableReady) {
onTableReady(table)
}
}, [table, onTableReady])
React.useEffect(() => {
if (!onSelectedRowsChange) return
const selectedRows = table
.getSelectedRowModel()
.flatRows.map((row) => row.original)
onSelectedRowsChange(selectedRows)
}, [rowSelection, table, onSelectedRowsChange])
// clearSelection prop이 변경되면 선택 상태 초기화
React.useEffect(() => {
setRowSelection({})
}, [clearSelection])
// 🎯 스크롤 핸들러 추가
const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
const scrollLeft = e.currentTarget.scrollLeft
setIsScrolled(scrollLeft > 0)
}
// 🎯 동적 핀 스타일 함수 (width 중복 제거)
const getPinnedStyle = (column: any, isHeader: boolean = false) => {
const baseStyle = getCommonPinningStylesWithBorder({ column })
const pinnedSide = column.getIsPinned()
// width를 제외한 나머지 스타일만 반환
const { width, ...restBaseStyle } = baseStyle
return {
...restBaseStyle,
// 헤더는 핀 여부와 관계없이 항상 배경 유지 (sticky로 고정되어 있기 때문)
...(isHeader && {
background: "hsl(var(--background))",
transition: "none",
}),
// 바디 셀 처리: 왼쪽과 오른쪽을 구분
...(!isHeader && pinnedSide && {
background:
pinnedSide === "right"
? "hsl(var(--background))" // 오른쪽 고정은 항상 불투명
: isScrolled
? "hsl(var(--background))" // 왼쪽 고정은 스크롤 시에만 불투명
: "transparent",
transition: "background-color 0.15s ease-out",
}),
}
}
// 🎯 테이블 총 너비 계산
const getTableWidth = React.useCallback(() => {
const totalSize = table.getCenterTotalSize() + table.getLeftTotalSize() + table.getRightTotalSize()
return Math.max(totalSize, 800) // 최소 800px 보장
}, [table])
// 컴팩트 모드를 위한 클래스 정의
const compactStyles = compact ? {
row: "h-7", // 행 높이 축소
cell: "py-1 px-2 text-sm", // 셀 패딩 축소 및 폰트 크기 조정
header: "py-1 px-2 text-sm", // 헤더 패딩 축소
headerRow: "h-8", // 헤더 행 높이 축소
groupRow: "py-1 bg-muted/20 text-sm", // 그룹 행 패딩 축소
emptyRow: "h-16", // 데이터 없을 때 행 높이 조정
} : {
row: "",
cell: "",
header: "",
headerRow: "",
groupRow: "bg-muted/20",
emptyRow: "h-24",
}
// nested header 감지: columns 속성을 가진 헤더가 있는지 확인
const hasNestedHeader = React.useMemo(() => {
return table.getHeaderGroups().some(headerGroup =>
headerGroup.headers.some(header => 'columns' in header.column.columnDef)
)
}, [table])
// (2) 렌더
return (
<div className="w-full space-y-2.5 overflow-auto">
{/* 툴바에 children을 넘기기 */}
<ClientDataTableAdvancedToolbar
table={table}
filterFields={advancedFilterFields}
shallow={false}
>
{children}
</ClientDataTableAdvancedToolbar>
<div
className="max-w-[100vw] overflow-auto"
style={{ maxHeight: maxHeight || '34rem' }}
onScroll={handleScroll} // 🎯 스크롤 이벤트 핸들러 추가
>
<UiTable
className={cn(
"[&>thead]:sticky [&>thead]:top-0 [&>thead]:z-10",
!hasNestedHeader && "table-fixed" // nested header가 없으면 table-fixed 적용
)}
style={{ minWidth: hasNestedHeader ? getTableWidth() : undefined }}>
{/* nested header가 있으면 table-fixed 제거, 없으면 적용 */}
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className={compactStyles.headerRow}>
{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={compactStyles.header}
style={{
...getPinnedStyle(header.column, 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) => {
// ---------------------------------------------------
// 1) "그룹핑 헤더" Row인지 확인
// ---------------------------------------------------
if (row.getIsGrouped()) {
// row.groupingColumnId로 어떤 컬럼을 기준으로 그룹화 되었는지 알 수 있음
const groupingColumnId = row.groupingColumnId ?? ""
const groupingColumn = table.getColumn(groupingColumnId) // 해당 column 객체
// 컬럼 라벨 가져오기
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" : ""}
>
{/* 확장/축소 버튼 (아이콘 중앙 정렬 + Indent) */}
{row.getCanExpand() && (
<button
onClick={row.getToggleExpandedHandler()}
className="inline-flex items-center justify-center mr-2 w-5 h-5"
style={{
// row.depth: 0이면 top-level, 1이면 그 하위 등
marginLeft: `${row.depth * 1.5}rem`,
}}
>
{row.getIsExpanded() ? (
<ChevronUp size={compact ? 14 : 16} />
) : (
<ChevronRight size={compact ? 14 : 16} />
)}
</button>
)}
{/* Group Label + 값 */}
<span className="font-semibold">
{columnLabel}: {row.getValue(groupingColumnId)}
</span>
<span className="ml-2 text-xs text-muted-foreground">
({row.subRows.length} rows)
</span>
</TableCell>
</TableRow>
)
}
// ---------------------------------------------------
// 2) 일반 Row
// → "그룹핑된 컬럼"은 숨긴다
// ---------------------------------------------------
return (
<TableRow
key={row.id}
className={compactStyles.row}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => {
// 이 셀의 컬럼이 grouped라면 숨긴다
if (cell.column.getIsGrouped()) {
return null
}
return (
<TableCell
key={cell.id}
data-column-id={cell.column.id}
className={compactStyles.cell}
style={{
...getPinnedStyle(cell.column, false), // 🎯 바디 셀임을 명시
width: cell.column.getSize() // 🎯 width 별도 설정
}}
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
)
})}
</TableRow>
)
})
) : (
// ---------------------------------------------------
// 3) 데이터가 없을 때
// ---------------------------------------------------
<TableRow>
<TableCell
colSpan={table.getAllColumns().length}
className={compactStyles.emptyRow + " text-center"}
>
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</UiTable>
</div>
<ClientDataTablePagination table={table} />
</div>
)
}
|