251201_01_ENH : datatable, autocomplete, user관리 완성

This commit is contained in:
2025-12-02 13:45:35 +09:00
parent 74de3d58f7
commit 310506d9ef
45 changed files with 5313 additions and 368 deletions

View File

@@ -0,0 +1,366 @@
'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'
export function DataTable<TData>({
columns,
data,
getRowId,
highlightRowIds,
isClient = true,
pageCount: serverPageCount,
totalCount: serverTotalCount,
onPaginationChange: onServerPaginationChange,
onSortingChange: onServerSortingChange,
selectMode = 'none',
onRowSelectionChange,
enableRowClickSelection = false,
defaultPageSize = 10,
pageSizeOptions = [5, 10, 25, 50],
paginationItemsToDisplay = 5
}: 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>({})
// 서버 페이지네이션일 때 부모에게 알림
useEffect(() => {
if (!isClient && onServerPaginationChange) {
onServerPaginationChange(pagination)
}
}, [pagination, isClient, onServerPaginationChange])
// 서버 정렬일 때 부모에게 알림
useEffect(() => {
if (!isClient && onServerSortingChange) {
onServerSortingChange(sorting)
}
}, [sorting, isClient, onServerSortingChange])
// Row selection 변경 시 부모에게 알림
useEffect(() => {
if (selectMode !== 'none' && onRowSelectionChange) {
const selectedRows = table
.getSelectedRowModel()
.rows.map(row => row.original)
onRowSelectionChange(selectedRows)
}
}, [rowSelection, selectMode])
// selectMode에 따라 select column 추가
const enhancedColumns: DataTableColumn<TData, any>[] = [
...(selectMode !== 'none'
? [
{
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) => {
if (!enableRowClickSelection || selectMode === 'none') return
if (selectMode === 'single') {
table.resetRowSelection()
row.toggleSelected(true)
} else {
row.toggleSelected(!row.getIsSelected())
}
}
const table = useReactTable({
data,
columns: enhancedColumns,
pageCount: isClient ? undefined : serverPageCount,
state: {
sorting,
pagination,
rowSelection
},
enableRowSelection: selectMode !== 'none',
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(
'content-text-lg font-semibold text-gray-900',
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 content-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' />}
</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'}
onClick={() => handleRowClick(row)}
className={cn(
'content-text-base',
'[&>td]:py-0 [&>td]:px-2',
enableRowClickSelection && 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>
<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>
)
}

View File

@@ -0,0 +1,47 @@
import { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table'
export type SelectMode = 'none' | 'single' | 'multi'
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue> & {
enableSorting?: boolean // 정렬 가능 여부 (기본값: false)
}
export interface ServerPaginationParams {
pageIndex: number
pageSize: number
sorting?: SortingState
}
export interface ServerPaginationResponse<TData> {
data: TData[]
totalCount: number
pageCount: number
}
export interface DataTableProps<TData> {
// 필수 props
columns: DataTableColumn<TData, any>[]
data: TData[]
getRowId?: (row: TData, index: number) => string //id 지정
highlightRowIds?: string[]
// 페이지네이션 모드
isClient?: boolean // true: 클라이언트, false: 서버 (기본값: true)
// 서버 페이지네이션 (isClient=false일 때 필요)
pageCount?: number
totalCount?: number
onPaginationChange?: (pagination: PaginationState) => void
onSortingChange?: (sorting: SortingState) => void
// 선택 모드
selectMode?: SelectMode // 'none' | 'single' | 'multi' (기본값: 'none')
onRowSelectionChange?: (selectedRows: TData[]) => void
enableRowClickSelection?: boolean // row 클릭 시 select 여부 (기본값: false)
// 페이지네이션 설정
defaultPageSize?: number
pageSizeOptions?: number[]
// 기타 설정
paginationItemsToDisplay?: number
}

View File

@@ -0,0 +1,38 @@
import { useMemo } from 'react'
interface UsePaginationProps {
currentPage: number
totalPages: number
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)
}
if (currentPage > totalPages - halfDisplay) {
startPage = Math.max(1, totalPages - paginationItemsToDisplay + 1)
}
const pages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i)
return {
pages,
showLeftEllipsis: startPage > 1,
showRightEllipsis: endPage < totalPages
}
}, [currentPage, totalPages, paginationItemsToDisplay])
return { pages, showLeftEllipsis, showRightEllipsis }
}