260724_01_ENH: 테이블 스타일 통일, 일부 버그 수정
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { OnChangeFn, PaginationState, Row, RowSelectionState, SortingState } from '@tanstack/react-table'
|
||||
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'
|
||||
@@ -12,6 +12,8 @@ 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,
|
||||
@@ -34,11 +36,14 @@ export function DataTable<TData, TValue = unknown>({
|
||||
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 containerRef = useRef<HTMLDivElement>(null)
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null)
|
||||
const drag = usePreventClickOnDrag()
|
||||
const selectionEnabled = selectMode === 'single' || selectMode === 'multi'
|
||||
|
||||
@@ -54,7 +59,7 @@ export function DataTable<TData, TValue = unknown>({
|
||||
aria-label="전체 선택"
|
||||
/>
|
||||
) : null,
|
||||
cell: ({ row }) => (
|
||||
cell: ({ row }) => row.getIsPinned() ? null : (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
onCheckedChange={(value) => {
|
||||
@@ -95,22 +100,43 @@ export function DataTable<TData, TValue = unknown>({
|
||||
[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,
|
||||
data: combinedData,
|
||||
columns: enhancedColumns,
|
||||
pageCount: isClient ? undefined : serverPageCount,
|
||||
state: { sorting, pagination, rowSelection },
|
||||
enableRowSelection: selectionEnabled,
|
||||
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 ? getPaginationRowModel() : undefined,
|
||||
getPaginationRowModel: isClient && !disablePagination ? getPaginationRowModel() : undefined,
|
||||
manualPagination: !isClient,
|
||||
manualSorting: !isClient,
|
||||
enableSortingRemoval: false,
|
||||
...(getRowId ? { getRowId } : {}),
|
||||
getRowId: internalGetRowId,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
@@ -124,7 +150,7 @@ export function DataTable<TData, TValue = unknown>({
|
||||
|
||||
useEffect(() => {
|
||||
if (!focusRowId) return
|
||||
const target = containerRef.current?.querySelector<HTMLElement>(`[data-row-id="${CSS.escape(focusRowId)}"]`)
|
||||
const target = scrollContainerRef.current?.querySelector<HTMLElement>(`[data-row-id="${CSS.escape(focusRowId)}"]`)
|
||||
target?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}, [focusRowId, data])
|
||||
|
||||
@@ -150,15 +176,48 @@ export function DataTable<TData, TValue = unknown>({
|
||||
|
||||
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={containerRef}
|
||||
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-10 bg-background')}>
|
||||
<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) => {
|
||||
@@ -171,7 +230,7 @@ export function DataTable<TData, TValue = unknown>({
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className={cn(
|
||||
'text-base font-semibold text-foreground',
|
||||
'text-base font-semibold bg-primary text-primary-foreground',
|
||||
column.id === 'actions' && 'w-[140px] text-center',
|
||||
maxWidth && 'overflow-hidden text-ellipsis',
|
||||
)}
|
||||
@@ -181,9 +240,16 @@ export function DataTable<TData, TValue = unknown>({
|
||||
}}
|
||||
>
|
||||
{!header.isPlaceholder && column.getCanSort() ? (
|
||||
<Button type="button" variant="ghost" className="flex gap-1 px-0 text-base font-semibold" onClick={column.getToggleSortingHandler()}>
|
||||
<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="text-muted-foreground size-3" />}
|
||||
{sorted === 'asc' ? <ArrowUp className="size-3" /> : sorted === 'desc' ? <ArrowDown className="size-3" /> : <ArrowUpDown className="size-3" />}
|
||||
</Button>
|
||||
) : content}
|
||||
</TableHead>
|
||||
@@ -193,7 +259,19 @@ export function DataTable<TData, TValue = unknown>({
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows.length ? table.getRowModel().rows.map((row) => (
|
||||
{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}
|
||||
@@ -228,17 +306,31 @@ export function DataTable<TData, TValue = unknown>({
|
||||
)) : (
|
||||
<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>
|
||||
|
||||
<DataTablePagination
|
||||
table={table}
|
||||
isClient={isClient}
|
||||
totalCount={totalCount}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
paginationItemsToDisplay={paginationItemsToDisplay}
|
||||
/>
|
||||
{!disablePagination && (
|
||||
<DataTablePagination
|
||||
table={table}
|
||||
isClient={isClient}
|
||||
totalCount={totalCount}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
paginationItemsToDisplay={paginationItemsToDisplay}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user