Files

296 lines
13 KiB
TypeScript

'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<TData, TValue = unknown>({
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<DataTableProps<TData, TValue>>) {
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
const [sorting, setSorting] = useState<SortingState>([])
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
const drag = usePreventClickOnDrag()
const selectionEnabled = selectMode === 'single' || selectMode === 'multi'
const enhancedColumns = useMemo<DataTableColumn<TData, TValue>[]>(() => {
if (!selectionEnabled) return columns
const selectionColumn = {
id: 'select',
header: ({ table }) => selectMode === 'multi' ? (
<Checkbox
checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && 'indeterminate')}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(Boolean(value))}
aria-label="전체 선택"
/>
) : null,
cell: ({ row }) => row.getIsPinned() ? null : (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => {
if (selectMode === 'single') table.resetRowSelection()
row.toggleSelected(Boolean(value))
}}
aria-label="행 선택"
onClick={(event) => event.stopPropagation()}
/>
),
size: 28,
enableSorting: false,
} as DataTableColumn<TData, TValue>
return [selectionColumn, ...columns]
}, [columns, selectMode, selectionEnabled])
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
useEffect(() => {
setRowSelection({})
}, [pagination.pageIndex, pagination.pageSize, sorting])
const handlePaginationChange = useCallback<OnChangeFn<PaginationState>>(
(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<RowPinningState>(() => ({
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<TData>) => {
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<HTMLDivElement>(null)
const [topOffsets, setTopOffsets] = useState<number[]>([])
const [bottomOffsets, setBottomOffsets] = useState<number[]>([])
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 (
<div className={cn('w-full space-y-4', className)}>
<div className="rounded-md border">
<div
ref={scrollContainerRef}
className={cn('relative w-full overflow-x-auto', maxBodyHeight && 'overflow-y-auto')}
style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined}
>
<table className="w-full caption-bottom text-sm">
<TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-20 bg-background')}>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent">
{headerGroup.headers.map((header) => {
const column = header.column
const sorted = column.getIsSorted()
const content = header.isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext())
return (
<TableHead
key={header.id}
className={cn('text-base font-semibold text-foreground', column.id === 'actions' && 'w-[140px] text-center')}
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
>
{!header.isPlaceholder && column.getCanSort() ? (
<Button type="button" variant="ghost" className="flex gap-1 px-0 text-base font-semibold" onClick={column.getToggleSortingHandler()}>
<span>{content}</span>
{sorted === 'asc' ? <ArrowUp className="size-3" /> : sorted === 'desc' ? <ArrowDown className="size-3" /> : <ArrowUpDown className="text-muted-foreground size-3" />}
</Button>
) : content}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{topRows.map((row, index) => (
<TableRow
key={row.id}
className={cn(
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
maxBodyHeight && 'sticky z-10',
)}
style={maxBodyHeight ? { top: topOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
{centerRows.length ? centerRows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() ? 'selected' : undefined}
onPointerDown={drag.onPointerDown}
onPointerMove={drag.onPointerMove}
onPointerUp={drag.onPointerUp}
onPointerCancel={drag.onPointerCancel}
onClick={drag.wrapClick(() => 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) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
)) : (
<TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow>
)}
{bottomRows.map((row, index) => (
<TableRow
key={row.id}
className={cn(
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
maxBodyHeight && 'sticky z-10',
)}
style={maxBodyHeight ? { bottom: bottomOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
</TableBody>
</table>
</div>
</div>
{!disablePagination && (
<DataTablePagination
table={table}
isClient={isClient}
totalCount={totalCount}
pageSizeOptions={pageSizeOptions}
paginationItemsToDisplay={paginationItemsToDisplay}
/>
)}
</div>
)
}