summaryrefslogtreecommitdiff
path: root/components/client-table-v2/client-virtual-table.tsx
blob: 1713369f93c5b0f652ed09a016d5ca10c6831b22 (plain)
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
"use client"

import * as React from "react"
import { rankItem } from "@tanstack/match-sorter-utils"
import {
  useReactTable,
  getCoreRowModel,
  getSortedRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getGroupedRowModel,
  getExpandedRowModel,
  getFacetedRowModel,
  getFacetedUniqueValues,
  getFacetedMinMaxValues,
  ColumnDef,
  SortingState,
  ColumnFiltersState,
  flexRender,
  PaginationState,
  OnChangeFn,
  ColumnOrderState,
  VisibilityState,
  ColumnPinningState,
  FilterFn,
  Table,
  RowSelectionState,
  Row,
  Column,
  GroupingState,
  ExpandedState,
} from "@tanstack/react-table"
import { useVirtualizer } from "@tanstack/react-virtual"
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from "@dnd-kit/core"
import {
  arrayMove,
  SortableContext,
  horizontalListSortingStrategy,
} from "@dnd-kit/sortable"
import { cn } from "@/lib/utils"
import { Loader2, ChevronRight, ChevronDown } from "lucide-react"

import { ClientTableToolbar } from "../client-table/client-table-toolbar"
import { exportToExcel } from "../client-table/export-utils"
import { ClientDataTablePagination } from "@/components/client-data-table/data-table-pagination"
import { ClientTableColumnHeader } from "./client-table-column-header"
import { ClientTableViewOptions } from "../client-table/client-table-view-options"
import { ClientTablePreset } from "./client-table-preset"

// Moved outside for stability (Performance Optimization)
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
  const itemRank = rankItem(row.getValue(columnId), value)
  addMeta({ itemRank })
  return itemRank.passed
}

export interface ClientVirtualTableProps<TData, TValue> {
  data: TData[]
  columns: ColumnDef<TData, TValue>[]
  height?: string | number
  estimateRowHeight?: number
  className?: string
  actions?: React.ReactNode
  customToolbar?: React.ReactNode
  enableExport?: boolean
  onExport?: (data: TData[]) => void
  isLoading?: boolean

  /**
   * 데이터 페칭 모드
   * - client: 모든 데이터를 한번에 받아 클라이언트에서 처리 (기본값)
   * - server: 서버에서 필터링/정렬/페이지네이션 된 데이터를 받음
   */
  fetchMode?: "client" | "server"

  // --- User Preset Saving ---
  enableUserPreset?: boolean
  tableKey?: string

  // --- State Control (Controlled or Uncontrolled) ---

  // Pagination
  enablePagination?: boolean
  manualPagination?: boolean
  pageCount?: number
  rowCount?: number
  pagination?: PaginationState
  onPaginationChange?: OnChangeFn<PaginationState>

  // Sorting
  sorting?: SortingState
  onSortingChange?: OnChangeFn<SortingState>

  // Filtering
  columnFilters?: ColumnFiltersState
  onColumnFiltersChange?: OnChangeFn<ColumnFiltersState>
  globalFilter?: string
  onGlobalFilterChange?: OnChangeFn<string>

  // Visibility
  columnVisibility?: VisibilityState
  onColumnVisibilityChange?: OnChangeFn<VisibilityState>

  // Pinning
  columnPinning?: ColumnPinningState
  onColumnPinningChange?: OnChangeFn<ColumnPinningState>

  // Order
  columnOrder?: ColumnOrderState
  onColumnOrderChange?: OnChangeFn<ColumnOrderState>

  // Selection
  enableRowSelection?: boolean | ((row: Row<TData>) => boolean)
  enableMultiRowSelection?: boolean | ((row: Row<TData>) => boolean)
  rowSelection?: RowSelectionState
  onRowSelectionChange?: OnChangeFn<RowSelectionState>

  // Grouping
  enableGrouping?: boolean
  grouping?: GroupingState
  onGroupingChange?: OnChangeFn<GroupingState>
  expanded?: ExpandedState
  onExpandedChange?: OnChangeFn<ExpandedState>

  // --- Event Handlers ---
  onRowClick?: (row: Row<TData>, event: React.MouseEvent) => void

  // --- Styling ---
  getRowClassName?: (originalRow: TData, index: number) => string

  // --- Advanced ---
  meta?: Record<string, any>
  getRowId?: (originalRow: TData, index: number, parent?: any) => string

  // Custom Header Visual Feedback
  renderHeaderVisualFeedback?: (props: {
    column: Column<TData, TValue>
    isPinned: boolean | string
    isSorted: boolean | string
    isFiltered: boolean
    isGrouped: boolean
  }) => React.ReactNode
}

function ClientVirtualTableInner<TData, TValue>(
  {
    data,
    columns,
    height = "100%",
    estimateRowHeight = 40,
    className,
    actions,
    customToolbar,
    enableExport = true,
    onExport,
    isLoading = false,
    fetchMode = "client",

    // User Preset Saving
    enableUserPreset = false,
    tableKey,

    // Pagination
    enablePagination = false,
    manualPagination: propManualPagination,
    pageCount,
    rowCount,
    pagination: propPagination,
    onPaginationChange,

    // Sorting
    sorting: propSorting,
    onSortingChange,

    // Filtering
    columnFilters: propColumnFilters,
    onColumnFiltersChange,
    globalFilter: propGlobalFilter,
    onGlobalFilterChange,

    // Visibility
    columnVisibility: propColumnVisibility,
    onColumnVisibilityChange,

    // Pinning
    columnPinning: propColumnPinning,
    onColumnPinningChange,

    // Order
    columnOrder: propColumnOrder,
    onColumnOrderChange,

    // Selection
    enableRowSelection,
    enableMultiRowSelection,
    rowSelection: propRowSelection,
    onRowSelectionChange,

    // Grouping
    enableGrouping = false,
    grouping: propGrouping,
    onGroupingChange,
    expanded: propExpanded,
    onExpandedChange,

    // Style defaults
    getRowClassName,

    // Meta & RowID
    meta,
    getRowId,

    // Event Handlers
    onRowClick,

    // Custom Header Visual Feedback
    renderHeaderVisualFeedback,
  }: ClientVirtualTableProps<TData, TValue>,
  ref: React.Ref<Table<TData>>
) {
  // Internal States (used when props are undefined)
  const [internalSorting, setInternalSorting] = React.useState<SortingState>([])
  const [internalColumnFilters, setInternalColumnFilters] = React.useState<ColumnFiltersState>([])
  const [internalGlobalFilter, setInternalGlobalFilter] = React.useState("")
  const [internalColumnVisibility, setInternalColumnVisibility] = React.useState<VisibilityState>({})
  const [internalColumnPinning, setInternalColumnPinning] = React.useState<ColumnPinningState>({ left: [], right: [] })
  const [internalColumnOrder, setInternalColumnOrder] = React.useState<ColumnOrderState>(
    () => columns.map((c) => c.id || (c as any).accessorKey) as string[]
  )
  const [internalPagination, setInternalPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  })
  const [internalRowSelection, setInternalRowSelection] = React.useState<RowSelectionState>({})
  const [internalGrouping, setInternalGrouping] = React.useState<GroupingState>([])
  const [internalExpanded, setInternalExpanded] = React.useState<ExpandedState>({})

  // Effective States
  const sorting = propSorting ?? internalSorting
  const setSorting = onSortingChange ?? setInternalSorting

  const columnFilters = propColumnFilters ?? internalColumnFilters
  const setColumnFilters = onColumnFiltersChange ?? setInternalColumnFilters

  const globalFilter = propGlobalFilter ?? internalGlobalFilter
  const setGlobalFilter = onGlobalFilterChange ?? setInternalGlobalFilter

  const columnVisibility = propColumnVisibility ?? internalColumnVisibility
  const setColumnVisibility = onColumnVisibilityChange ?? setInternalColumnVisibility

  const columnPinning = propColumnPinning ?? internalColumnPinning
  const setColumnPinning = onColumnPinningChange ?? setInternalColumnPinning

  const columnOrder = propColumnOrder ?? internalColumnOrder
  const setColumnOrder = onColumnOrderChange ?? setInternalColumnOrder

  const pagination = propPagination ?? internalPagination
  const setPagination = onPaginationChange ?? setInternalPagination

  const rowSelection = propRowSelection ?? internalRowSelection
  const setRowSelection = onRowSelectionChange ?? setInternalRowSelection

  const grouping = propGrouping ?? internalGrouping
  const setGrouping = onGroupingChange ?? setInternalGrouping

  const expanded = propExpanded ?? internalExpanded
  const setExpanded = onExpandedChange ?? setInternalExpanded

  // Server Mode Logic
  const isServer = fetchMode === "server"
  // If server mode is enabled, we default manual flags to true unless explicitly overridden
  const manualPagination = propManualPagination ?? isServer
  const manualSorting = isServer
  const manualFiltering = isServer
  const manualGrouping = isServer

  // Table Instance
  const table = useReactTable({
    data,
    columns,
    state: {
      sorting,
      columnFilters,
      globalFilter,
      pagination,
      columnVisibility,
      columnPinning,
      columnOrder,
      rowSelection,
      grouping,
      expanded,
    },
    manualPagination,
    manualSorting,
    manualFiltering,
    manualGrouping,
    pageCount: manualPagination ? pageCount : undefined,
    rowCount: manualPagination ? rowCount : undefined,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    onPaginationChange: setPagination,
    onColumnVisibilityChange: setColumnVisibility,
    onColumnPinningChange: setColumnPinning,
    onColumnOrderChange: setColumnOrder,
    onRowSelectionChange: setRowSelection,
    onGroupingChange: setGrouping,
    onExpandedChange: setExpanded,
    enableRowSelection,
    enableMultiRowSelection,
    enableGrouping,
    getCoreRowModel: getCoreRowModel(),

    // Systematic Order of Operations:
    // If server-side, we skip client-side processing models to avoid double processing
    // and to ensure the table reflects exactly what the server returned.
    getFilteredRowModel: !isServer ? getFilteredRowModel() : undefined,
    getFacetedRowModel: !isServer ? getFacetedRowModel() : undefined,
    getFacetedUniqueValues: !isServer ? getFacetedUniqueValues() : undefined,
    getFacetedMinMaxValues: !isServer ? getFacetedMinMaxValues() : undefined,

    getSortedRowModel: !isServer ? getSortedRowModel() : undefined,

    getGroupedRowModel: (!isServer && enableGrouping) ? getGroupedRowModel() : undefined,
    getExpandedRowModel: (!isServer && enableGrouping) ? getExpandedRowModel() : undefined,

    getPaginationRowModel: (!isServer && enablePagination) ? getPaginationRowModel() : undefined,
    columnResizeMode: "onChange",
    filterFns: {
      fuzzy: fuzzyFilter,
    },
    globalFilterFn: fuzzyFilter,
    meta,
    getRowId,
  })

  // Expose table instance via ref
  React.useImperativeHandle(ref, () => table, [table])

  // DnD Sensors
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8,
      },
    }),
    useSensor(KeyboardSensor)
  )

  // Handle Drag End
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event
    if (active && over && active.id !== over.id) {
      const activeId = active.id as string
      const overId = over.id as string

      const activeColumn = table.getColumn(activeId)
      const overColumn = table.getColumn(overId)

      if (activeColumn && overColumn) {
        const activePinState = activeColumn.getIsPinned()
        const overPinState = overColumn.getIsPinned()

        // If dragging between different pin states, update the pin state of the active column
        if (activePinState !== overPinState) {
          activeColumn.pin(overPinState)
        }

        // Reorder the columns
        setColumnOrder((items) => {
          const currentItems = Array.isArray(items) ? items : []
          const oldIndex = items.indexOf(activeId)
          const newIndex = items.indexOf(overId)
          return arrayMove(items, oldIndex, newIndex)
        })
      }
    }
  }

  // Virtualization
  const tableContainerRef = React.useRef<HTMLDivElement>(null)
  const { rows } = table.getRowModel()

  const rowVirtualizer = useVirtualizer({
    count: rows.length,
    getScrollElement: () => tableContainerRef.current,
    estimateSize: () => estimateRowHeight,
    overscan: 10,
  })

  const virtualRows = rowVirtualizer.getVirtualItems()
  const totalSize = rowVirtualizer.getTotalSize()

  const paddingTop = virtualRows.length > 0 ? virtualRows?.[0]?.start || 0 : 0
  const paddingBottom =
    virtualRows.length > 0
      ? totalSize - (virtualRows?.[virtualRows.length - 1]?.end || 0)
      : 0

  // Export Handler
  const handleExport = async () => {
    if (onExport) {
      onExport(data)
      return
    }
    const currentData = table.getFilteredRowModel().rows.map((row) => row.original)
    await exportToExcel(currentData, columns, `export-${new Date().toISOString().slice(0, 10)}.xlsx`)
  }

  return (
    <div
      className={`flex flex-col gap-4 ${className || ""}`}
      style={{ height }}
    >
      <ClientTableToolbar
        globalFilter={globalFilter}
        setGlobalFilter={setGlobalFilter}
        totalRows={manualPagination ? (rowCount ?? data.length) : data.length}
        visibleRows={rows.length}
        onExport={enableExport ? handleExport : undefined}
        viewOptions={
          <>
            <ClientTableViewOptions table={table} />
            {enableUserPreset && tableKey && (
              <ClientTablePreset table={table} tableKey={tableKey} />
            )}
          </>
        }
        customToolbar={customToolbar}
        actions={actions}
      />

      <div
        ref={tableContainerRef}
        className="relative border rounded-md overflow-auto bg-background flex-1 min-h-0"
      >
        {isLoading && (
          <div className="absolute inset-0 z-50 flex items-center justify-center bg-background/50 backdrop-blur-sm">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        )}

        <DndContext
          sensors={sensors}
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
        >
          <table
            className="table-fixed border-collapse w-full min-w-full"
            style={{ width: table.getTotalSize() }}
          >
            <thead className="sticky top-0 z-40 bg-muted">
              {table.getHeaderGroups().map((headerGroup) => (
                <tr key={headerGroup.id}>
                  <SortableContext
                    items={headerGroup.headers.map((h) => h.id)}
                    strategy={horizontalListSortingStrategy}
                  >
                    {headerGroup.headers.map((header) => (
                      <ClientTableColumnHeader
                        key={header.id}
                        header={header}
                        enableReordering={true}
                        renderHeaderVisualFeedback={renderHeaderVisualFeedback}
                      />
                    ))}
                  </SortableContext>
                </tr>
              ))}
            </thead>
            <tbody>
              {paddingTop > 0 && (
                <tr>
                  <td style={{ height: `${paddingTop}px` }} />
                </tr>
              )}
              {virtualRows.length === 0 && !isLoading ? (
                <tr>
                  <td colSpan={columns.length} className="h-24 text-center">
                    No results.
                  </td>
                </tr>
              ) : (
                virtualRows.map((virtualRow) => {
                  const row = rows[virtualRow.index]

                  // --- Group Header Rendering ---
                  if (row.getIsGrouped()) {
                    const groupingColumnId = row.groupingColumnId ?? "";
                    const groupingValue = row.getGroupingValue(groupingColumnId);

                    return (
                      <tr
                        key={row.id}
                        className="hover:bg-muted/50 border-b bg-muted/30"
                        style={{ height: `${virtualRow.size}px` }}
                      >
                        <td
                          colSpan={columns.length}
                          className="px-4 py-2 text-left font-medium cursor-pointer"
                          onClick={row.getToggleExpandedHandler()}
                        >
                          <div className="flex items-center gap-2">
                            {row.getIsExpanded() ? (
                              <ChevronDown className="h-4 w-4" />
                            ) : (
                              <ChevronRight className="h-4 w-4" />
                            )}
                            <span className="flex items-center gap-2">
                              <span className="font-bold capitalize">
                                {groupingColumnId}:
                              </span>
                              <span>
                                {String(groupingValue)}
                              </span>
                              <span className="text-muted-foreground text-sm font-normal">
                                ({row.subRows.length})
                              </span>
                            </span>
                          </div>
                        </td>
                      </tr>
                    )
                  }

                  // --- Normal Row Rendering ---
                  return (
                    <tr
                      key={row.id}
                      className={cn(
                        "hover:bg-muted/50 border-b last:border-0",
                        getRowClassName ? getRowClassName(row.original, row.index) : "",
                        onRowClick ? "cursor-pointer" : ""
                      )}
                      style={{ height: `${virtualRow.size}px` }}
                      onClick={(e) => onRowClick?.(row, e)}
                    >
                      {row.getVisibleCells().map((cell) => {
                        // Handle pinned cells
                        const isPinned = cell.column.getIsPinned()
                        const isGrouped = cell.column.getIsGrouped()

                        const style: React.CSSProperties = {
                          width: cell.column.getSize(),
                        }
                        if (isPinned === "left") {
                          style.position = "sticky"
                          style.left = `${cell.column.getStart("left")}px`
                          style.zIndex = 20
                        } else if (isPinned === "right") {
                          style.position = "sticky"
                          style.right = `${cell.column.getAfter("right")}px`
                          style.zIndex = 20
                        }

                        return (
                          <td
                            key={cell.id}
                            className={cn(
                              "px-2 py-0 text-sm truncate border-b bg-background",
                              isGrouped ? "bg-muted/20" : ""
                            )}
                            style={style}
                          >
                            {cell.getIsGrouped() ? (
                              // If this cell is grouped, usually we don't render it here if we have a group header row,
                              // but if we keep it, it acts as the expander for the next level (if multi-level grouping).
                              // Since we used a full-width row for the group header, this branch might not be hit for the group row itself,
                              // but for nested groups it might?
                              // Wait, row.getIsGrouped() is true for the group row.
                              // The cells inside the group row are not rendered because we return early above.
                              // The cells inside the "leaf" rows (normal rows) are rendered here.
                              // So cell.getIsGrouped() checks if the COLUMN is currently grouped.
                              // If the column is grouped, the cell value is usually redundant or hidden in normal rows.
                              // Standard practice: hide the cell content or dim it.
                              null
                            ) : cell.getIsAggregated() ? (
                              // If this cell is an aggregation of the group
                              flexRender(
                                cell.column.columnDef.aggregatedCell ??
                                cell.column.columnDef.cell,
                                cell.getContext()
                              )
                            ) : (
                              // Normal cell
                              cell.getIsPlaceholder()
                                ? null
                                : flexRender(cell.column.columnDef.cell, cell.getContext())
                            )}
                          </td>
                        )
                      })}
                    </tr>
                  )
                })
              )}
              {paddingBottom > 0 && (
                <tr>
                  <td style={{ height: `${paddingBottom}px` }} />
                </tr>
              )}
            </tbody>
          </table>
        </DndContext>
      </div>

      {enablePagination && (
        <ClientDataTablePagination table={table} />
      )}
    </div>
  )
}

export const ClientVirtualTable = React.memo(
  React.forwardRef(ClientVirtualTableInner)
) as <TData, TValue>(
  props: ClientVirtualTableProps<TData, TValue> & { ref?: React.Ref<Table<TData>> }
) => React.ReactElement