260703_01_FST: First Commit

This commit is contained in:
2026-07-03 10:40:45 +09:00
commit b11d47b14e
65 changed files with 11002 additions and 0 deletions

View File

@@ -0,0 +1,182 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import type { 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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { cn } from '@/lib/utils'
import type { DataTableColumn, DataTableProps } from './DataTable.type'
import { DataTablePagination } from './DataTablePagination'
import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag'
export function DataTable<TData, TValue = unknown>({
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,
emptyText = '데이터가 없습니다.',
className,
}: Readonly<DataTableProps<TData, TValue>>) {
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
const [sorting, setSorting] = useState<SortingState>([])
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
const drag = usePreventClickOnDrag()
const selectionEnabled = selectMode === 'single' || selectMode === 'multi'
const enhancedColumns = useMemo<DataTableColumn<TData, TValue>[]>(() => {
if (!selectionEnabled) return columns
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>
return [selectionColumn, ...columns]
}, [columns, selectMode, selectionEnabled])
const table = useReactTable({
data,
columns: enhancedColumns,
pageCount: isClient ? undefined : serverPageCount,
state: { sorting, pagination, rowSelection },
enableRowSelection: selectionEnabled,
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
onPaginationChange: setPagination,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined,
manualPagination: !isClient,
manualSorting: !isClient,
enableSortingRemoval: false,
...(getRowId ? { getRowId } : {}),
})
useEffect(() => {
if (!isClient) onServerPaginationChange?.(pagination)
}, [isClient, onServerPaginationChange, pagination])
useEffect(() => {
if (!isClient) onServerSortingChange?.(sorting)
}, [isClient, onServerSortingChange, sorting])
useEffect(() => {
if (!selectionEnabled) return
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
}, [onRowSelectionChange, rowSelection, selectionEnabled, table])
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)
return
}
row.toggleSelected(!row.getIsSelected())
}
const totalCount = isClient ? data.length : (serverTotalCount ?? 0)
return (
<div className={cn('w-full space-y-4', className)}>
<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 sorted = column.getIsSorted()
const content = header.isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext())
return (
<TableHead
key={header.id}
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 && 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>
) : content}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.length ? table.getRowModel().rows.map((row) => (
<TableRow
key={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))}
className={cn(
'text-sm [&>td]:px-2 [&>td]:py-0',
selectMode !== 'none' && 'cursor-pointer',
'data-[state=selected]:bg-muted data-[state=selected]:font-semibold',
highlightRowIds?.includes(row.id) && '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">{emptyText}</TableCell></TableRow>
)}
</TableBody>
</Table>
</div>
<DataTablePagination
table={table}
isClient={isClient}
totalCount={totalCount}
pageSizeOptions={pageSizeOptions}
paginationItemsToDisplay={paginationItemsToDisplay}
/>
</div>
)
}

View File

@@ -0,0 +1,36 @@
import type { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table'
export type SelectMode = 'none' | 'click-event' | 'single' | 'multi'
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue>
export interface ServerPaginationParams {
pageIndex: number
pageSize: number
sorting?: SortingState
}
export interface ServerPaginationResponse<TData> {
data: TData[]
totalCount: number
pageCount: number
}
export interface DataTableProps<TData, TValue = unknown> {
columns: DataTableColumn<TData, TValue>[]
data: TData[]
getRowId?: (row: TData, index: number) => string
highlightRowIds?: string[]
isClient?: boolean
pageCount?: number
totalCount?: number
onPaginationChange?: (pagination: PaginationState) => void
onSortingChange?: (sorting: SortingState) => void
selectMode?: SelectMode
onRowClick?: (row: TData) => void
onRowSelectionChange?: (rows: TData[]) => void
defaultPageSize?: number
pageSizeOptions?: number[]
paginationItemsToDisplay?: number
emptyText?: string
className?: string
}

View File

@@ -0,0 +1,96 @@
'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>) {
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>
)
}

View File

@@ -0,0 +1,30 @@
import { useMemo } from 'react'
interface UsePaginationProps {
currentPage: number
totalPages: number
paginationItemsToDisplay?: number
}
export function usePagination({ currentPage, totalPages, paginationItemsToDisplay = 5 }: UsePaginationProps) {
return useMemo(() => {
if (totalPages <= 0) {
return { pages: [] as number[], showLeftEllipsis: false, showRightEllipsis: false }
}
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)
if (endPage - startPage + 1 < visibleCount) {
startPage = Math.max(1, endPage - visibleCount + 1)
}
return {
pages: Array.from({ length: endPage - startPage + 1 }, (_, index) => startPage + index),
showLeftEllipsis: startPage > 1,
showRightEllipsis: endPage < totalPages,
}
}, [currentPage, paginationItemsToDisplay, totalPages])
}

View File

@@ -0,0 +1,37 @@
import * as React from 'react'
export function usePreventClickOnDrag(thresholdPx = 6) {
const state = React.useRef({ x: 0, y: 0, 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((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(() => {
setTimeout(() => {
state.current.dragging = false
}, 0)
}, [])
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 }
}

View File

@@ -0,0 +1,30 @@
import { useMemo } from 'react'
interface UsePaginationProps {
currentPage: number
totalPages: number
paginationItemsToDisplay?: number
}
export function usePagination({ currentPage, totalPages, paginationItemsToDisplay = 5 }: UsePaginationProps) {
return useMemo(() => {
if (totalPages <= 0) {
return { pages: [] as number[], showLeftEllipsis: false, showRightEllipsis: false }
}
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)
if (endPage - startPage + 1 < visibleCount) {
startPage = Math.max(1, endPage - visibleCount + 1)
}
return {
pages: Array.from({ length: endPage - startPage + 1 }, (_, index) => startPage + index),
showLeftEllipsis: startPage > 1,
showRightEllipsis: endPage < totalPages,
}
}, [currentPage, paginationItemsToDisplay, totalPages])
}

View File

@@ -0,0 +1,37 @@
import * as React from 'react'
export function usePreventClickOnDrag(thresholdPx = 6) {
const state = React.useRef({ x: 0, y: 0, 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((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(() => {
setTimeout(() => {
state.current.dragging = false
}, 0)
}, [])
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 }
}

View File

@@ -0,0 +1,8 @@
export { DataTable } from './DataTable'
export type {
DataTableColumn,
DataTableProps,
SelectMode,
ServerPaginationParams,
ServerPaginationResponse,
} from './DataTable.type'