349 lines
16 KiB
TypeScript
349 lines
16 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,
|
|
focusRowId,
|
|
isClient = true,
|
|
pageCount: serverPageCount,
|
|
totalCount: serverTotalCount,
|
|
pagination: externalPagination,
|
|
onPaginationChange: onServerPaginationChange,
|
|
sorting: externalSorting,
|
|
onSortingChange: onServerSortingChange,
|
|
selectMode = 'none',
|
|
onRowClick,
|
|
onRowDoubleClick,
|
|
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 [internalSorting, setInternalSorting] = useState<SortingState>([])
|
|
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
|
const scrollContainerRef = useRef<HTMLDivElement>(null)
|
|
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)
|
|
const sorting = !isClient && externalSorting ? externalSorting : internalSorting
|
|
|
|
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 handleSortingChange = useCallback<OnChangeFn<SortingState>>(
|
|
(updater) => {
|
|
const nextSorting = typeof updater === 'function' ? updater(sorting) : updater
|
|
|
|
if (!isClient && onServerSortingChange) {
|
|
onServerSortingChange(nextSorting)
|
|
return
|
|
}
|
|
|
|
setInternalSorting(nextSorting)
|
|
},
|
|
[isClient, onServerSortingChange, sorting],
|
|
)
|
|
|
|
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: handleSortingChange,
|
|
onPaginationChange: handlePaginationChange,
|
|
getCoreRowModel: getCoreRowModel(),
|
|
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
|
|
getPaginationRowModel: isClient && !disablePagination ? getPaginationRowModel() : undefined,
|
|
manualPagination: !isClient,
|
|
manualSorting: !isClient,
|
|
enableSortingRemoval: false,
|
|
getRowId: internalGetRowId,
|
|
})
|
|
|
|
useEffect(() => {
|
|
if (!selectionEnabled) return
|
|
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
|
|
}, [onRowSelectionChange, rowSelection, selectionEnabled, table])
|
|
|
|
useEffect(() => {
|
|
if (!focusRowId) return
|
|
const target = scrollContainerRef.current?.querySelector<HTMLElement>(`[data-row-id="${CSS.escape(focusRowId)}"]`)
|
|
target?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
|
}, [focusRowId, data])
|
|
|
|
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)
|
|
onRowClick?.(row.original)
|
|
return
|
|
}
|
|
row.toggleSelected(!row.getIsSelected())
|
|
onRowClick?.(row.original)
|
|
}
|
|
|
|
const handleRowDoubleClick = (row: Row<TData>) => {
|
|
onRowDoubleClick?.(row.original)
|
|
}
|
|
|
|
const totalCount = isClient ? data.length : (serverTotalCount ?? 0)
|
|
|
|
const topRows = table.getTopRows()
|
|
const centerRows = table.getCenterRows()
|
|
const bottomRows = table.getBottomRows()
|
|
|
|
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
|
|
ref={scrollContainerRef}
|
|
className={cn('relative w-full overflow-x-auto rounded-md border', 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())
|
|
const maxWidth = column.columnDef.meta?.maxWidth
|
|
|
|
return (
|
|
<TableHead
|
|
key={header.id}
|
|
className={cn(
|
|
'text-base font-semibold bg-primary text-primary-foreground',
|
|
column.id === 'actions' && 'w-[140px] text-center',
|
|
maxWidth && 'overflow-hidden text-ellipsis',
|
|
)}
|
|
style={{
|
|
width: header.getSize() !== 150 ? header.getSize() : undefined,
|
|
maxWidth,
|
|
}}
|
|
>
|
|
{!header.isPlaceholder && column.getCanSort() ? (
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
className={cn(
|
|
"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="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-row-id={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))}
|
|
onDoubleClick={onRowDoubleClick ? () => handleRowDoubleClick(row) : undefined}
|
|
className={cn(
|
|
'text-base [&>td]:px-2 [&>td]:py-1',
|
|
(selectMode !== 'none' || onRowDoubleClick) && 'cursor-pointer',
|
|
'data-[state=selected]:bg-muted data-[state=selected]:font-semibold',
|
|
highlightRowIds?.includes(row.id) && 'bg-emerald-50',
|
|
row.id === focusRowId && 'bg-accent',
|
|
)}
|
|
>
|
|
{row.getVisibleCells().map((cell) => {
|
|
const maxWidth = cell.column.columnDef.meta?.maxWidth
|
|
return (
|
|
<TableCell
|
|
key={cell.id}
|
|
className={cn(maxWidth && 'overflow-hidden text-ellipsis')}
|
|
style={maxWidth ? { maxWidth } : undefined}
|
|
>
|
|
{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>
|
|
|
|
{!disablePagination && (
|
|
<DataTablePagination
|
|
table={table}
|
|
isClient={isClient}
|
|
totalCount={totalCount}
|
|
pageSizeOptions={pageSizeOptions}
|
|
paginationItemsToDisplay={paginationItemsToDisplay}
|
|
/>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|