392 lines
15 KiB
TypeScript
392 lines
15 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect, useState } from 'react'
|
|
import {
|
|
ChevronsLeftIcon,
|
|
ChevronLeftIcon,
|
|
ChevronRightIcon,
|
|
ChevronsRightIcon,
|
|
ArrowUp,
|
|
ArrowDown,
|
|
ArrowUpDown
|
|
} from 'lucide-react'
|
|
|
|
import type { PaginationState, SortingState, RowSelectionState } from '@tanstack/react-table'
|
|
import {
|
|
flexRender,
|
|
getCoreRowModel,
|
|
getPaginationRowModel,
|
|
getSortedRowModel,
|
|
useReactTable
|
|
} from '@tanstack/react-table'
|
|
|
|
import { Button } from '@/components/ui/button'
|
|
import { Checkbox } from '@/components/ui/checkbox'
|
|
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/components/ui/pagination'
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
|
|
|
import { usePagination } from './hooks/usePagination'
|
|
import { DataTableProps, DataTableColumn } from './DataTable.type'
|
|
|
|
import { cn } from '@/lib/utils'
|
|
import {usePreventClickOnDrag} from "@/components/data-table/hooks/usePreventClickOnDrag";
|
|
|
|
export function DataTable<TData>({
|
|
columns,
|
|
data,
|
|
getRowId,
|
|
highlightRowIds,
|
|
isClient = true,
|
|
pageCount: serverPageCount,
|
|
totalCount: serverTotalCount,
|
|
onPaginationChange: onServerPaginationChange,
|
|
onSortingChange: onServerSortingChange,
|
|
selectMode = 'none',
|
|
onRowClick,
|
|
onRowSelectionChange,
|
|
defaultPageSize = 10,
|
|
pageSizeOptions = [5, 10, 25, 50],
|
|
showPagination = true,
|
|
paginationItemsToDisplay = 5,
|
|
headerFontClass = 'content-text-lg',
|
|
cellFontClass = 'content-text-base',
|
|
}: Readonly<DataTableProps<TData>>) {
|
|
// Pagination state
|
|
const [pagination, setPagination] = useState<PaginationState>({
|
|
pageIndex: 0,
|
|
pageSize: defaultPageSize
|
|
})
|
|
|
|
// Sorting state
|
|
const [sorting, setSorting] = useState<SortingState>([])
|
|
|
|
// Row selection state
|
|
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
|
|
|
const drag = usePreventClickOnDrag(6);
|
|
|
|
const isNotSelection = !['none', 'click-event'].includes(selectMode);
|
|
|
|
// 서버 페이지네이션일 때 부모에게 알림
|
|
useEffect(() => {
|
|
if (!isClient && onServerPaginationChange) {
|
|
onServerPaginationChange(pagination)
|
|
}
|
|
}, [pagination, isClient, onServerPaginationChange])
|
|
|
|
// 서버 정렬일 때 부모에게 알림
|
|
useEffect(() => {
|
|
if (!isClient && onServerSortingChange) {
|
|
onServerSortingChange(sorting)
|
|
}
|
|
}, [sorting, isClient, onServerSortingChange])
|
|
|
|
// Row selection 변경 시 부모에게 알림
|
|
useEffect(() => {
|
|
if (isNotSelection && onRowSelectionChange) {
|
|
const selectedRows = table
|
|
.getSelectedRowModel()
|
|
.rows.map(row => row.original)
|
|
onRowSelectionChange(selectedRows)
|
|
}
|
|
}, [rowSelection, selectMode])
|
|
|
|
// selectMode에 따라 select column 추가
|
|
const enhancedColumns: DataTableColumn<TData, any>[] = [
|
|
...(isNotSelection
|
|
? [
|
|
{
|
|
id: 'select',
|
|
header: ({ table }) =>
|
|
selectMode === 'multi' ? (
|
|
<Checkbox
|
|
checked={
|
|
table.getIsAllPageRowsSelected() ||
|
|
(table.getIsSomePageRowsSelected() && 'indeterminate')
|
|
}
|
|
onCheckedChange={value => table.toggleAllPageRowsSelected(!!value)}
|
|
aria-label='KriSelect all'
|
|
/>
|
|
) : null,
|
|
cell: ({ row }) => (
|
|
<Checkbox
|
|
checked={row.getIsSelected()}
|
|
onCheckedChange={value => {
|
|
if (selectMode === 'single') {
|
|
// single mode: 다른 것 모두 해제
|
|
table.resetRowSelection()
|
|
}
|
|
row.toggleSelected(!!value)
|
|
}}
|
|
aria-label='KriSelect row'
|
|
onClick={e => e.stopPropagation()} // row 클릭 이벤트 전파 방지
|
|
/>
|
|
),
|
|
size: 28,
|
|
enableSorting: false
|
|
} as DataTableColumn<TData, any>
|
|
]
|
|
: []),
|
|
...columns
|
|
]
|
|
|
|
// Row 클릭 핸들러
|
|
const handleRowClick = (row: any) => {
|
|
switch (selectMode) {
|
|
case 'none':
|
|
return
|
|
|
|
case 'click-event':
|
|
if (!onRowClick) return
|
|
onRowClick(row.original)
|
|
return
|
|
|
|
case 'single':
|
|
table.resetRowSelection()
|
|
row.toggleSelected(true)
|
|
return
|
|
|
|
default: // 'multi' 등
|
|
row.toggleSelected(!row.getIsSelected())
|
|
return
|
|
}
|
|
}
|
|
|
|
const table = useReactTable({
|
|
data,
|
|
columns: enhancedColumns,
|
|
pageCount: isClient ? undefined : serverPageCount,
|
|
state: {
|
|
sorting,
|
|
pagination,
|
|
rowSelection
|
|
},
|
|
enableRowSelection: isNotSelection,
|
|
onRowSelectionChange: setRowSelection,
|
|
onSortingChange: setSorting,
|
|
onPaginationChange: setPagination,
|
|
getCoreRowModel: getCoreRowModel(),
|
|
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
|
|
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined,
|
|
manualPagination: !isClient,
|
|
manualSorting: !isClient,
|
|
enableSortingRemoval: false,
|
|
...(getRowId && { getRowId }), //있으면만 적용
|
|
})
|
|
|
|
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
|
|
currentPage: table.getState().pagination.pageIndex + 1,
|
|
totalPages: table.getPageCount(),
|
|
paginationItemsToDisplay
|
|
})
|
|
|
|
const totalCount = isClient ? data.length : (serverTotalCount || 0)
|
|
|
|
return (
|
|
<div className='w-full space-y-4'>
|
|
<div className='rounded-md border'>
|
|
<Table>
|
|
<TableHeader>
|
|
{table.getHeaderGroups().map(headerGroup => (
|
|
<TableRow key={headerGroup.id} className='hover:bg-transparent'>
|
|
{headerGroup.headers.map(header => {
|
|
const column = header.column
|
|
const canSort = column.getCanSort()
|
|
const sorted = column.getIsSorted() as false | 'asc' | 'desc'
|
|
const headerContent = header.isPlaceholder
|
|
? null
|
|
: flexRender(column.columnDef.header, header.getContext())
|
|
|
|
return (
|
|
<TableHead
|
|
key={header.id}
|
|
className={cn(
|
|
'font-semibold text-gray-900',
|
|
headerFontClass,
|
|
column.id === 'actions' && 'w-[140px] text-center'
|
|
)}
|
|
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
|
|
>
|
|
{header.isPlaceholder ? null : canSort ? (
|
|
<Button
|
|
type='button'
|
|
variant='ghost'
|
|
className={cn('px-0 font-semibold flex items-center gap-1', headerFontClass)}
|
|
onClick={column.getToggleSortingHandler()}
|
|
>
|
|
<span>{headerContent}</span>
|
|
{sorted === 'asc' && <ArrowUp className='w-3 h-3' />}
|
|
{sorted === 'desc' && <ArrowDown className='w-3 h-3' />}
|
|
{!sorted && <ArrowUpDown className='w-3 h-3 text-muted-foreground' />}
|
|
</Button>
|
|
) : (
|
|
headerContent
|
|
)}
|
|
</TableHead>
|
|
)
|
|
})}
|
|
</TableRow>
|
|
))}
|
|
</TableHeader>
|
|
<TableBody>
|
|
{table.getRowModel().rows?.length ? (
|
|
table.getRowModel().rows.map(row => {
|
|
const shouldHighlight = highlightRowIds && highlightRowIds.includes(row.id)
|
|
return (
|
|
<TableRow
|
|
key={row.id}
|
|
data-state={row.getIsSelected() && 'selected'}
|
|
onPointerDown={drag.onPointerDown}
|
|
onPointerMove={drag.onPointerMove}
|
|
onPointerUp={drag.onPointerUp}
|
|
onPointerCancel={drag.onPointerCancel}
|
|
onClick={drag.wrapClick(() => handleRowClick(row))}
|
|
className={cn(
|
|
cellFontClass,
|
|
'[&>td]:py-3 [&>td]:px-3',
|
|
selectMode !== 'none' && 'cursor-pointer',
|
|
'data-[state=selected]:bg-slate-100 data-[state=selected]:font-semibold',
|
|
shouldHighlight && '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'>
|
|
데이터가 없습니다.
|
|
</TableCell>
|
|
</TableRow>
|
|
)}
|
|
</TableBody>
|
|
</Table>
|
|
</div>
|
|
|
|
{showPagination && (
|
|
<div className='flex items-center justify-between gap-3 max-sm:flex-col p-2 pt-0'>
|
|
<p className='text-muted-foreground flex-1 text-sm whitespace-nowrap' aria-live='polite'>
|
|
Page <span className='text-foreground'>{table.getState().pagination.pageIndex + 1}</span> of{' '}
|
|
<span className='text-foreground'>{table.getPageCount()}</span>
|
|
{!isClient && totalCount > 0 && (
|
|
<span className='ml-2'>
|
|
(총 <span className='text-foreground'>{totalCount}</span>건)
|
|
</span>
|
|
)}
|
|
</p>
|
|
|
|
<div className='grow'>
|
|
<Pagination>
|
|
<PaginationContent>
|
|
<PaginationItem>
|
|
<Button
|
|
size='icon'
|
|
variant='outline'
|
|
className='disabled:pointer-events-none disabled:opacity-50'
|
|
onClick={() => table.firstPage()}
|
|
disabled={!table.getCanPreviousPage()}
|
|
aria-label='Go to first page'
|
|
>
|
|
<ChevronsLeftIcon aria-hidden='true' />
|
|
</Button>
|
|
</PaginationItem>
|
|
<PaginationItem>
|
|
<Button
|
|
size='icon'
|
|
variant='outline'
|
|
className='disabled:pointer-events-none disabled:opacity-50'
|
|
onClick={() => table.previousPage()}
|
|
disabled={!table.getCanPreviousPage()}
|
|
aria-label='Go to previous page'
|
|
>
|
|
<ChevronLeftIcon aria-hidden='true' />
|
|
</Button>
|
|
</PaginationItem>
|
|
|
|
{showLeftEllipsis && (
|
|
<PaginationItem>
|
|
<PaginationEllipsis />
|
|
</PaginationItem>
|
|
)}
|
|
|
|
{pages.map(page => {
|
|
const isActive = page === table.getState().pagination.pageIndex + 1
|
|
|
|
return (
|
|
<PaginationItem key={page}>
|
|
<Button
|
|
size='icon'
|
|
variant={isActive ? 'default' : 'ghost'}
|
|
onClick={() => table.setPageIndex(page - 1)}
|
|
aria-current={isActive ? 'page' : undefined}
|
|
>
|
|
{page}
|
|
</Button>
|
|
</PaginationItem>
|
|
)
|
|
})}
|
|
|
|
{showRightEllipsis && (
|
|
<PaginationItem>
|
|
<PaginationEllipsis />
|
|
</PaginationItem>
|
|
)}
|
|
|
|
<PaginationItem>
|
|
<Button
|
|
size='icon'
|
|
variant='outline'
|
|
className='disabled:pointer-events-none disabled:opacity-50'
|
|
onClick={() => table.nextPage()}
|
|
disabled={!table.getCanNextPage()}
|
|
aria-label='Go to next page'
|
|
>
|
|
<ChevronRightIcon aria-hidden='true' />
|
|
</Button>
|
|
</PaginationItem>
|
|
<PaginationItem>
|
|
<Button
|
|
size='icon'
|
|
variant='outline'
|
|
className='disabled:pointer-events-none disabled:opacity-50'
|
|
onClick={() => table.lastPage()}
|
|
disabled={!table.getCanNextPage()}
|
|
aria-label='Go to last page'
|
|
>
|
|
<ChevronsRightIcon aria-hidden='true' />
|
|
</Button>
|
|
</PaginationItem>
|
|
</PaginationContent>
|
|
</Pagination>
|
|
</div>
|
|
|
|
<div className='flex flex-1 justify-end'>
|
|
<Select
|
|
value={table.getState().pagination.pageSize.toString()}
|
|
onValueChange={value => {
|
|
table.setPageSize(Number(value))
|
|
}}
|
|
>
|
|
<SelectTrigger id='results-per-page' className='w-fit whitespace-nowrap' aria-label='Results per page'>
|
|
<SelectValue placeholder='페이지당 개수' />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{pageSizeOptions.map(size => (
|
|
<SelectItem key={size} value={size.toString()}>
|
|
{size} / page
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|