260714_01_ENH: 테스트 서버에서 기동 후 중간 테스트를 위한 커밋
This commit is contained in:
@@ -1,224 +1,179 @@
|
||||
'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 { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { OnChangeFn, PaginationState, Row, 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 { 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 { TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {usePreventClickOnDrag} from "@/components/data-table/hooks/usePreventClickOnDrag";
|
||||
import type { DataTableColumn, DataTableProps } from './DataTable.type'
|
||||
import { DataTablePagination } from './DataTablePagination'
|
||||
import { usePreventClickOnDrag } from './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],
|
||||
paginationItemsToDisplay = 5
|
||||
}: Readonly<DataTableProps<TData>>) {
|
||||
// Pagination state
|
||||
const [pagination, setPagination] = useState<PaginationState>({
|
||||
pageIndex: 0,
|
||||
pageSize: defaultPageSize
|
||||
})
|
||||
|
||||
// Sorting state
|
||||
export function DataTable<TData, TValue = unknown>({
|
||||
columns,
|
||||
data,
|
||||
getRowId,
|
||||
highlightRowIds,
|
||||
focusRowId,
|
||||
isClient = true,
|
||||
pageCount: serverPageCount,
|
||||
totalCount: serverTotalCount,
|
||||
pagination: externalPagination,
|
||||
onPaginationChange: onServerPaginationChange,
|
||||
onSortingChange: onServerSortingChange,
|
||||
selectMode = 'none',
|
||||
onRowClick,
|
||||
onRowDoubleClick,
|
||||
onRowSelectionChange,
|
||||
defaultPageSize = 10,
|
||||
pageSizeOptions = [5, 10, 25, 50],
|
||||
paginationItemsToDisplay = 5,
|
||||
emptyText = '데이터가 없습니다.',
|
||||
className,
|
||||
maxBodyHeight,
|
||||
}: Readonly<DataTableProps<TData, TValue>>) {
|
||||
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
|
||||
// Row selection state
|
||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const drag = usePreventClickOnDrag()
|
||||
const selectionEnabled = selectMode === 'single' || selectMode === 'multi'
|
||||
|
||||
const drag = usePreventClickOnDrag(6);
|
||||
const enhancedColumns = useMemo<DataTableColumn<TData, TValue>[]>(() => {
|
||||
if (!selectionEnabled) return columns
|
||||
|
||||
const isNotSelection = !['none', 'click-event'].includes(selectMode);
|
||||
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 }) => (
|
||||
<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>
|
||||
|
||||
// 서버 페이지네이션일 때 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (!isClient && onServerPaginationChange) {
|
||||
onServerPaginationChange(pagination)
|
||||
}
|
||||
}, [pagination, isClient, onServerPaginationChange])
|
||||
return [selectionColumn, ...columns]
|
||||
}, [columns, selectMode, selectionEnabled])
|
||||
|
||||
// 서버 정렬일 때 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (!isClient && onServerSortingChange) {
|
||||
onServerSortingChange(sorting)
|
||||
}
|
||||
}, [sorting, isClient, onServerSortingChange])
|
||||
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
|
||||
|
||||
// Row selection 변경 시 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (isNotSelection && onRowSelectionChange) {
|
||||
const selectedRows = table
|
||||
.getSelectedRowModel()
|
||||
.rows.map(row => row.original)
|
||||
onRowSelectionChange(selectedRows)
|
||||
}
|
||||
}, [rowSelection, selectMode])
|
||||
const handlePaginationChange = useCallback<OnChangeFn<PaginationState>>(
|
||||
(updater) => {
|
||||
if (isClient) {
|
||||
setInternalPagination(updater)
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
]
|
||||
if (onServerPaginationChange) {
|
||||
onServerPaginationChange(updater)
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
setInternalPagination(updater)
|
||||
},
|
||||
[isClient, onServerPaginationChange],
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns: enhancedColumns,
|
||||
pageCount: isClient ? undefined : serverPageCount,
|
||||
state: {
|
||||
sorting,
|
||||
pagination,
|
||||
rowSelection
|
||||
},
|
||||
enableRowSelection: isNotSelection,
|
||||
state: { sorting, pagination, rowSelection },
|
||||
enableRowSelection: selectionEnabled,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onPaginationChange: setPagination,
|
||||
onPaginationChange: handlePaginationChange,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
|
||||
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined,
|
||||
manualPagination: !isClient,
|
||||
manualSorting: !isClient,
|
||||
enableSortingRemoval: false,
|
||||
...(getRowId && { getRowId }), //있으면만 적용
|
||||
...(getRowId ? { getRowId } : {}),
|
||||
})
|
||||
|
||||
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
|
||||
currentPage: table.getState().pagination.pageIndex + 1,
|
||||
totalPages: table.getPageCount(),
|
||||
paginationItemsToDisplay
|
||||
})
|
||||
useEffect(() => {
|
||||
if (!isClient) onServerSortingChange?.(sorting)
|
||||
}, [isClient, onServerSortingChange, sorting])
|
||||
|
||||
const totalCount = isClient ? data.length : (serverTotalCount || 0)
|
||||
useEffect(() => {
|
||||
if (!selectionEnabled) return
|
||||
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
|
||||
}, [onRowSelectionChange, rowSelection, selectionEnabled, table])
|
||||
|
||||
useEffect(() => {
|
||||
if (!focusRowId) return
|
||||
const target = containerRef.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)
|
||||
|
||||
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 => {
|
||||
<div className={cn('w-full space-y-4', className)}>
|
||||
<div
|
||||
ref={containerRef}
|
||||
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')}>
|
||||
{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())
|
||||
const sorted = column.getIsSorted()
|
||||
const content = header.isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext())
|
||||
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className={cn(
|
||||
'text-lg font-semibold text-gray-900',
|
||||
column.id === 'actions' && 'w-[140px] text-center'
|
||||
)}
|
||||
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 ? null : canSort ? (
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
className='px-0 font-semibold text-lg flex items-center gap-1'
|
||||
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' />}
|
||||
{!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>
|
||||
) : (
|
||||
headerContent
|
||||
)}
|
||||
) : content}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
@@ -226,160 +181,41 @@ export function DataTable<TData>({
|
||||
))}
|
||||
</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(
|
||||
'text-base',
|
||||
'[&>td]:py-0 [&>td]:px-2',
|
||||
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>
|
||||
{table.getRowModel().rows.length ? table.getRowModel().rows.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-0',
|
||||
(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) => <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>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
<DataTablePagination
|
||||
table={table}
|
||||
isClient={isClient}
|
||||
totalCount={totalCount}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
paginationItemsToDisplay={paginationItemsToDisplay}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table'
|
||||
import type { ColumnDef, PaginationState, SortingState, Updater } from '@tanstack/react-table'
|
||||
|
||||
export type SelectMode = 'none' | 'click-event' | 'single' | 'multi'
|
||||
|
||||
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue> & {
|
||||
enableSorting?: boolean // 정렬 가능 여부 (기본값: false)
|
||||
}
|
||||
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue>
|
||||
|
||||
export interface ServerPaginationParams {
|
||||
pageIndex: number
|
||||
@@ -18,30 +15,26 @@ export interface ServerPaginationResponse<TData> {
|
||||
pageCount: number
|
||||
}
|
||||
|
||||
export interface DataTableProps<TData> {
|
||||
// 필수 props
|
||||
columns: DataTableColumn<TData, any>[]
|
||||
export interface DataTableProps<TData, TValue = unknown> {
|
||||
columns: DataTableColumn<TData, TValue>[]
|
||||
data: TData[]
|
||||
getRowId?: (row: TData, index: number) => string //id 지정
|
||||
getRowId?: (row: TData, index: number) => string
|
||||
highlightRowIds?: string[]
|
||||
// 페이지네이션 모드
|
||||
isClient?: boolean // true: 클라이언트, false: 서버 (기본값: true)
|
||||
|
||||
// 서버 페이지네이션 (isClient=false일 때 필요)
|
||||
focusRowId?: string
|
||||
isClient?: boolean
|
||||
pageCount?: number
|
||||
totalCount?: number
|
||||
onPaginationChange?: (pagination: PaginationState) => void
|
||||
pagination?: PaginationState
|
||||
onPaginationChange?: (updater: Updater<PaginationState>) => void
|
||||
onSortingChange?: (sorting: SortingState) => void
|
||||
|
||||
// 선택 모드
|
||||
selectMode?: SelectMode // 'none' | 'click-event' | 'single' | 'multi' (기본값: 'none')
|
||||
onRowClick?: (selectedRows: TData) => void
|
||||
onRowSelectionChange?: (selectedRows: TData[]) => void
|
||||
|
||||
// 페이지네이션 설정
|
||||
selectMode?: SelectMode
|
||||
onRowClick?: (row: TData) => void
|
||||
onRowDoubleClick?: (row: TData) => void
|
||||
onRowSelectionChange?: (rows: TData[]) => void
|
||||
defaultPageSize?: number
|
||||
pageSizeOptions?: number[]
|
||||
|
||||
// 기타 설정
|
||||
paginationItemsToDisplay?: number
|
||||
}
|
||||
emptyText?: string
|
||||
className?: string
|
||||
maxBodyHeight?: string
|
||||
}
|
||||
|
||||
98
src/components/data-table/DataTablePagination.tsx
Normal file
98
src/components/data-table/DataTablePagination.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
'use client'
|
||||
|
||||
import type { Table } from '@tanstack/react-table'
|
||||
import { ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/components/ui/pagination'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { usePagination } from './hooks/usePagination'
|
||||
|
||||
interface DataTablePaginationProps<TData> {
|
||||
table: Table<TData>
|
||||
isClient: boolean
|
||||
totalCount: number
|
||||
pageSizeOptions: number[]
|
||||
paginationItemsToDisplay: number
|
||||
}
|
||||
|
||||
export function DataTablePagination<TData>({
|
||||
table,
|
||||
isClient,
|
||||
totalCount,
|
||||
pageSizeOptions,
|
||||
paginationItemsToDisplay,
|
||||
}: DataTablePaginationProps<TData>) {
|
||||
'use no memo'
|
||||
|
||||
const currentPage = table.getState().pagination.pageIndex + 1
|
||||
const pageCount = table.getPageCount()
|
||||
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
|
||||
currentPage,
|
||||
totalPages: pageCount,
|
||||
paginationItemsToDisplay,
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-3 p-2 pt-0 max-sm:flex-col">
|
||||
<p className="text-muted-foreground flex-1 whitespace-nowrap text-sm" aria-live="polite">
|
||||
Page <span className="text-foreground">{currentPage}</span> of{' '}
|
||||
<span className="text-foreground">{pageCount}</span>
|
||||
{!isClient && totalCount > 0 ? (
|
||||
<span className="ml-2">(총 <span className="text-foreground">{totalCount}</span>건)</span>
|
||||
) : null}
|
||||
</p>
|
||||
|
||||
<div className="grow">
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<Button size="icon" variant="outline" onClick={() => table.firstPage()} disabled={!table.getCanPreviousPage()} aria-label="첫 페이지">
|
||||
<ChevronsLeftIcon aria-hidden="true" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button size="icon" variant="outline" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} aria-label="이전 페이지">
|
||||
<ChevronLeftIcon aria-hidden="true" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
{showLeftEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
|
||||
{pages.map((page) => (
|
||||
<PaginationItem key={page}>
|
||||
<Button
|
||||
size="icon"
|
||||
variant={page === currentPage ? 'default' : 'ghost'}
|
||||
onClick={() => table.setPageIndex(page - 1)}
|
||||
aria-current={page === currentPage ? 'page' : undefined}
|
||||
>
|
||||
{page}
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
))}
|
||||
{showRightEllipsis ? <PaginationItem><PaginationEllipsis /></PaginationItem> : null}
|
||||
<PaginationItem>
|
||||
<Button size="icon" variant="outline" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} aria-label="다음 페이지">
|
||||
<ChevronRightIcon aria-hidden="true" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button size="icon" variant="outline" onClick={() => table.lastPage()} disabled={!table.getCanNextPage()} aria-label="마지막 페이지">
|
||||
<ChevronsRightIcon aria-hidden="true" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 justify-end">
|
||||
<Select value={String(table.getState().pagination.pageSize)} onValueChange={(value) => table.setPageSize(Number(value))}>
|
||||
<SelectTrigger className="w-fit whitespace-nowrap" aria-label="페이지당 개수">
|
||||
<SelectValue placeholder="페이지당 개수" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{pageSizeOptions.map((size) => <SelectItem key={size} value={String(size)}>{size} / page</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,33 +6,25 @@ interface UsePaginationProps {
|
||||
paginationItemsToDisplay?: number
|
||||
}
|
||||
|
||||
export function usePagination({
|
||||
currentPage,
|
||||
totalPages,
|
||||
paginationItemsToDisplay = 5
|
||||
}: UsePaginationProps) {
|
||||
const { pages, showLeftEllipsis, showRightEllipsis } = useMemo(() => {
|
||||
const halfDisplay = Math.floor(paginationItemsToDisplay / 2)
|
||||
|
||||
let startPage = Math.max(1, currentPage - halfDisplay)
|
||||
let endPage = Math.min(totalPages, currentPage + halfDisplay)
|
||||
|
||||
if (currentPage <= halfDisplay) {
|
||||
endPage = Math.min(paginationItemsToDisplay, totalPages)
|
||||
export function usePagination({ currentPage, totalPages, paginationItemsToDisplay = 5 }: UsePaginationProps) {
|
||||
return useMemo(() => {
|
||||
if (totalPages <= 0) {
|
||||
return { pages: [] as number[], showLeftEllipsis: false, showRightEllipsis: false }
|
||||
}
|
||||
|
||||
if (currentPage > totalPages - halfDisplay) {
|
||||
startPage = Math.max(1, totalPages - paginationItemsToDisplay + 1)
|
||||
}
|
||||
const visibleCount = Math.max(1, paginationItemsToDisplay)
|
||||
const half = Math.floor(visibleCount / 2)
|
||||
let startPage = Math.max(1, currentPage - half)
|
||||
let endPage = Math.min(totalPages, startPage + visibleCount - 1)
|
||||
|
||||
const pages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i)
|
||||
if (endPage - startPage + 1 < visibleCount) {
|
||||
startPage = Math.max(1, endPage - visibleCount + 1)
|
||||
}
|
||||
|
||||
return {
|
||||
pages,
|
||||
pages: Array.from({ length: endPage - startPage + 1 }, (_, index) => startPage + index),
|
||||
showLeftEllipsis: startPage > 1,
|
||||
showRightEllipsis: endPage < totalPages
|
||||
showRightEllipsis: endPage < totalPages,
|
||||
}
|
||||
}, [currentPage, totalPages, paginationItemsToDisplay])
|
||||
|
||||
return { pages, showLeftEllipsis, showRightEllipsis }
|
||||
}
|
||||
}, [currentPage, paginationItemsToDisplay, totalPages])
|
||||
}
|
||||
|
||||
@@ -1,48 +1,37 @@
|
||||
import * as React from "react";
|
||||
import * as React from 'react'
|
||||
|
||||
export const usePreventClickOnDrag = (thresholdPx = 6) => {
|
||||
const s = React.useRef({ x: 0, y: 0, dragging: false });
|
||||
export function usePreventClickOnDrag(thresholdPx = 6) {
|
||||
const state = React.useRef({ x: 0, y: 0, dragging: false })
|
||||
|
||||
const onPointerDown = React.useCallback((e: React.PointerEvent) => {
|
||||
// 좌클릭만
|
||||
if (e.button !== 0) return;
|
||||
s.current.x = e.clientX;
|
||||
s.current.y = e.clientY;
|
||||
s.current.dragging = false;
|
||||
}, []);
|
||||
const onPointerDown = React.useCallback((event: React.PointerEvent) => {
|
||||
if (event.button !== 0) return
|
||||
state.current = { x: event.clientX, y: event.clientY, dragging: false }
|
||||
}, [])
|
||||
|
||||
const onPointerMove = React.useCallback(
|
||||
(e: React.PointerEvent) => {
|
||||
// 누르고 있을 때만
|
||||
if (e.buttons === 0) return;
|
||||
|
||||
const dx = e.clientX - s.current.x;
|
||||
const dy = e.clientY - s.current.y;
|
||||
|
||||
if (dx * dx + dy * dy >= thresholdPx * thresholdPx) {
|
||||
s.current.dragging = true;
|
||||
}
|
||||
},
|
||||
[thresholdPx]
|
||||
);
|
||||
const onPointerMove = React.useCallback((event: React.PointerEvent) => {
|
||||
if (event.buttons === 0) return
|
||||
const dx = event.clientX - state.current.x
|
||||
const dy = event.clientY - state.current.y
|
||||
if (dx * dx + dy * dy >= thresholdPx * thresholdPx) state.current.dragging = true
|
||||
}, [thresholdPx])
|
||||
|
||||
const onPointerUp = React.useCallback(() => {
|
||||
// click은 pointerup 다음에 발생하므로 "다음 tick"에 false로 복구
|
||||
setTimeout(() => {
|
||||
s.current.dragging = false;
|
||||
}, 0);
|
||||
}, []);
|
||||
state.current.dragging = false
|
||||
}, 0)
|
||||
}, [])
|
||||
|
||||
const wrapClick =
|
||||
(fn: () => void) =>
|
||||
(e: React.MouseEvent) => {
|
||||
if (s.current.dragging) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
fn();
|
||||
};
|
||||
const wrapClick = React.useCallback(
|
||||
(callback: () => void) => (event: React.MouseEvent) => {
|
||||
if (state.current.dragging) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
callback()
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp, wrapClick };
|
||||
}
|
||||
return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp, wrapClick }
|
||||
}
|
||||
|
||||
8
src/components/data-table/index.ts
Normal file
8
src/components/data-table/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export { DataTable } from './DataTable'
|
||||
export type {
|
||||
DataTableColumn,
|
||||
DataTableProps,
|
||||
SelectMode,
|
||||
ServerPaginationParams,
|
||||
ServerPaginationResponse,
|
||||
} from './DataTable.type'
|
||||
Reference in New Issue
Block a user