260714_01_ENH: 테스트 서버에서 기동 후 중간 테스트를 위한 커밋

This commit is contained in:
2026-07-14 10:59:07 +09:00
parent a8ce35f5bf
commit 192d47bdb1
180 changed files with 11942 additions and 6007 deletions

View File

@@ -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>
)
}
}