'use client' import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import type { OnChangeFn, PaginationState, Row, RowPinningState, RowSelectionState, SortingState } from '@tanstack/react-table' import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table' import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react' import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' import { TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table' import { cn } from '@/lib/utils' import type { DataTableColumn, DataTableProps } from './DataTable.type' import { DataTablePagination } from './DataTablePagination' import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag' const EMPTY_PINNED_ROWS: never[] = [] export function DataTable({ columns, data, getRowId, highlightRowIds, isClient = true, pageCount: serverPageCount, totalCount: serverTotalCount, pagination: externalPagination, onPaginationChange: onServerPaginationChange, onSortingChange: onServerSortingChange, selectMode = 'none', onRowClick, onRowSelectionChange, defaultPageSize = 10, pageSizeOptions = [5, 10, 25, 50], paginationItemsToDisplay = 5, emptyText = '데이터가 없습니다.', className, maxBodyHeight, disablePagination = false, topPinnedRows = EMPTY_PINNED_ROWS, bottomPinnedRows = EMPTY_PINNED_ROWS, }: Readonly>) { const [internalPagination, setInternalPagination] = useState({ pageIndex: 0, pageSize: defaultPageSize }) const [sorting, setSorting] = useState([]) const [rowSelection, setRowSelection] = useState({}) const drag = usePreventClickOnDrag() const selectionEnabled = selectMode === 'single' || selectMode === 'multi' const enhancedColumns = useMemo[]>(() => { if (!selectionEnabled) return columns const selectionColumn = { id: 'select', header: ({ table }) => selectMode === 'multi' ? ( table.toggleAllPageRowsSelected(Boolean(value))} aria-label="전체 선택" /> ) : null, cell: ({ row }) => row.getIsPinned() ? null : ( { if (selectMode === 'single') table.resetRowSelection() row.toggleSelected(Boolean(value)) }} aria-label="행 선택" onClick={(event) => event.stopPropagation()} /> ), size: 28, enableSorting: false, } as DataTableColumn return [selectionColumn, ...columns] }, [columns, selectMode, selectionEnabled]) const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination) useEffect(() => { setRowSelection({}) }, [pagination.pageIndex, pagination.pageSize, sorting]) const handlePaginationChange = useCallback>( (updater) => { if (isClient) { setInternalPagination(updater) return } if (onServerPaginationChange) { onServerPaginationChange(updater) return } setInternalPagination(updater) }, [isClient, onServerPaginationChange], ) const combinedData = useMemo( () => [...topPinnedRows, ...data, ...bottomPinnedRows], [topPinnedRows, data, bottomPinnedRows], ) const internalGetRowId = useCallback((row: TData, index: number) => { if (index < topPinnedRows.length) return `__top-pinned-${index}` if (index >= topPinnedRows.length + data.length) { return `__bottom-pinned-${index - topPinnedRows.length - data.length}` } const originalIndex = index - topPinnedRows.length return getRowId ? getRowId(data[originalIndex], originalIndex) : String(originalIndex) }, [topPinnedRows.length, data, getRowId]) const rowPinning = useMemo(() => ({ top: topPinnedRows.map((_, i) => `__top-pinned-${i}`), bottom: bottomPinnedRows.map((_, i) => `__bottom-pinned-${i}`), }), [topPinnedRows, bottomPinnedRows]) const table = useReactTable({ data: combinedData, columns: enhancedColumns, pageCount: isClient ? undefined : serverPageCount, state: { sorting, pagination, rowSelection, rowPinning }, enableRowSelection: (row) => selectionEnabled && !row.getIsPinned(), enableRowPinning: true, keepPinnedRows: true, onRowSelectionChange: setRowSelection, onSortingChange: setSorting, onPaginationChange: handlePaginationChange, getCoreRowModel: getCoreRowModel(), getSortedRowModel: isClient ? getSortedRowModel() : undefined, getPaginationRowModel: isClient && !disablePagination ? getPaginationRowModel() : undefined, manualPagination: !isClient, manualSorting: !isClient, enableSortingRemoval: false, getRowId: internalGetRowId, }) useEffect(() => { if (!isClient) onServerSortingChange?.(sorting) }, [isClient, onServerSortingChange, sorting]) useEffect(() => { if (!selectionEnabled) return onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original)) }, [onRowSelectionChange, rowSelection, selectionEnabled, table]) const handleRowClick = (row: Row) => { if (selectMode === 'none') return if (selectMode === 'click-event') { onRowClick?.(row.original) return } if (selectMode === 'single') { table.resetRowSelection() row.toggleSelected(true) return } row.toggleSelected(!row.getIsSelected()) } const totalCount = isClient ? data.length : (serverTotalCount ?? 0) const topRows = table.getTopRows() const centerRows = table.getCenterRows() const bottomRows = table.getBottomRows() const scrollContainerRef = useRef(null) const [topOffsets, setTopOffsets] = useState([]) const [bottomOffsets, setBottomOffsets] = useState([]) useLayoutEffect(() => { if (!maxBodyHeight) return const container = scrollContainerRef.current if (!container) return const headerHeight = container.querySelector('thead')?.getBoundingClientRect().height ?? 0 const bodyRows = Array.from(container.querySelectorAll('tbody > tr')) const topRowEls = bodyRows.slice(0, topRows.length) const bottomRowEls = bottomRows.length ? bodyRows.slice(-bottomRows.length) : [] let topAcc = headerHeight setTopOffsets(topRowEls.map((element) => { const offset = topAcc topAcc += element.getBoundingClientRect().height return offset })) let bottomAcc = 0 const offsets: number[] = [] for (let index = bottomRowEls.length - 1; index >= 0; index -= 1) { offsets[index] = bottomAcc bottomAcc += bottomRowEls[index].getBoundingClientRect().height } setBottomOffsets(offsets) }, [maxBodyHeight, topRows.length, bottomRows.length, centerRows.length]) return (
{table.getHeaderGroups().map((headerGroup) => ( {headerGroup.headers.map((header) => { const column = header.column const sorted = column.getIsSorted() const content = header.isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext()) return ( {!header.isPlaceholder && column.getCanSort() ? ( ) : content} ) })} ))} {topRows.map((row, index) => ( td]:px-2 [&>td]:py-1.5', maxBodyHeight && 'sticky z-10', )} style={maxBodyHeight ? { top: topOffsets[index] ?? 0 } : undefined} > {row.getVisibleCells().map((cell) => {flexRender(cell.column.columnDef.cell, cell.getContext())})} ))} {centerRows.length ? centerRows.map((row) => ( handleRowClick(row))} className={cn( 'text-sm [&>td]:px-2 [&>td]:py-0', selectMode !== 'none' && 'cursor-pointer', 'data-[state=selected]:bg-muted data-[state=selected]:font-semibold', highlightRowIds?.includes(row.id) && 'bg-emerald-50', )} > {row.getVisibleCells().map((cell) => {flexRender(cell.column.columnDef.cell, cell.getContext())})} )) : ( {emptyText} )} {bottomRows.map((row, index) => ( td]:px-2 [&>td]:py-1.5', maxBodyHeight && 'sticky z-10', )} style={maxBodyHeight ? { bottom: bottomOffsets[index] ?? 0 } : undefined} > {row.getVisibleCells().map((cell) => {flexRender(cell.column.columnDef.cell, cell.getContext())})} ))}
{!disablePagination && ( )}
) }