diff options
| author | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-05-29 05:17:13 +0000 |
|---|---|---|
| committer | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-05-29 05:17:13 +0000 |
| commit | 37f55540833c2d5894513eca9fc8f7c6233fc2d2 (patch) | |
| tree | 6807978e7150358b3444c33b825c83e2c9cda8e8 /components/data-table | |
| parent | 4b9bdb29e637f67761beb2db7f75dab0432d6712 (diff) | |
(대표님) 0529 14시 16분 변경사항 저장 (Vendor Data, Docu)
Diffstat (limited to 'components/data-table')
| -rw-r--r-- | components/data-table/data-table-pagination.tsx | 219 | ||||
| -rw-r--r-- | components/data-table/infinite-data-table.tsx | 294 |
2 files changed, 443 insertions, 70 deletions
diff --git a/components/data-table/data-table-pagination.tsx b/components/data-table/data-table-pagination.tsx index 4ed63a1b..922dacf1 100644 --- a/components/data-table/data-table-pagination.tsx +++ b/components/data-table/data-table-pagination.tsx @@ -7,6 +7,7 @@ import { ChevronRight, ChevronsLeft, ChevronsRight, + Infinity, } from "lucide-react" import { Button } from "@/components/ui/button" @@ -21,57 +22,99 @@ import { interface DataTablePaginationProps<TData> { table: Table<TData> pageSizeOptions?: Array<number | "All"> + // 무한 스크롤 관련 props + infiniteScroll?: { + enabled: boolean + hasNextPage: boolean + isLoadingMore: boolean + totalCount?: number | null + onLoadMore?: () => void + } + // 페이지 크기 변경 콜백 (필수!) + onPageSizeChange?: (pageSize: number) => void } export function DataTablePagination<TData>({ table, pageSizeOptions = [10, 20, 30, 40, 50, "All"], + infiniteScroll, + onPageSizeChange, }: DataTablePaginationProps<TData>) { // 현재 테이블 pageSize const currentPageSize = table.getState().pagination.pageSize + const isInfiniteMode = infiniteScroll?.enabled || currentPageSize >= 1_000_000 - // "All"을 1,000,000으로 처리할 것이므로, - // 만약 현재 pageSize가 1,000,000이면 화면상 "All"로 표시 - const selectValue = - currentPageSize === 1_000_000 - ? "All" - : String(currentPageSize) + // "All"을 1,000,000으로 처리하고, 무한 스크롤 모드 표시 + const selectValue = isInfiniteMode ? "All" : String(currentPageSize) + + const handlePageSizeChange = (value: string) => { + if (!onPageSizeChange) { + console.warn('DataTablePagination: onPageSizeChange prop is required for page size changes to work') + return + } + + if (value === "All") { + // "All" 선택 시 무한 스크롤 모드로 전환 + onPageSizeChange(1_000_000) // URL 상태 업데이트만 수행 + } else { + const newSize = Number(value) + onPageSizeChange(newSize) // URL 상태 업데이트만 수행 + } + + // table.setPageSize()는 호출하지 않음! + // URL 상태 변경이 테이블 상태로 자동 반영됨 + } return ( <div className="flex w-full flex-col-reverse items-center justify-between gap-4 overflow-auto p-1 sm:flex-row sm:gap-8"> + {/* 선택된 행 및 총 개수 정보 */} <div className="flex-1 whitespace-nowrap text-sm text-muted-foreground"> {table.getFilteredSelectedRowModel().rows.length} of{" "} - {table.getFilteredRowModel().rows.length} row(s) selected. - <span className="ml-4">Total: {table.getRowCount()} records</span> + {isInfiniteMode ? ( + // 무한 스크롤 모드일 때 + <> + {table.getRowModel().rows.length} row(s) selected. + {infiniteScroll?.totalCount !== null && ( + <span className="ml-4"> + Total: {infiniteScroll.totalCount?.toLocaleString()} records + <span className="ml-2 text-xs"> + ({table.getRowModel().rows.length.toLocaleString()} loaded) + </span> + </span> + )} + </> + ) : ( + // 페이지네이션 모드일 때 + <> + {table.getFilteredRowModel().rows.length} row(s) selected. + <span className="ml-4">Total: {table.getRowCount()} records</span> + </> + )} </div> + <div className="flex flex-col-reverse items-center gap-4 sm:flex-row sm:gap-6 lg:gap-8"> {/* Rows per page Select */} <div className="flex items-center space-x-2"> - <p className="whitespace-nowrap text-sm font-medium">Rows per page</p> - <Select - value={selectValue} - onValueChange={(value) => { - if (value === "All") { - // "All"을 1,000,000으로 치환 - table.setPageSize(1_000_000) - } else { - table.setPageSize(Number(value)) - } - }} - > + <p className="whitespace-nowrap text-sm font-medium"> + {isInfiniteMode ? "View mode" : "Rows per page"} + </p> + <Select value={selectValue} onValueChange={handlePageSizeChange}> <SelectTrigger className="h-8 w-[4.5rem]"> <SelectValue placeholder={selectValue} /> </SelectTrigger> <SelectContent side="top"> {pageSizeOptions.map((option) => { - // 화면에 표시할 라벨 const label = option === "All" ? "All" : String(option) - // value도 문자열화 const val = option === "All" ? "All" : String(option) return ( <SelectItem key={val} value={val}> - {label} + <div className="flex items-center space-x-2"> + {option === "All" && ( + <Infinity className="h-3 w-3 text-muted-foreground" /> + )} + <span>{label}</span> + </div> </SelectItem> ) })} @@ -79,54 +122,90 @@ export function DataTablePagination<TData>({ </Select> </div> - {/* 현재 페이지 / 전체 페이지 */} - <div className="flex items-center justify-center text-sm font-medium"> - Page {table.getState().pagination.pageIndex + 1} of{" "} - {table.getPageCount()} - </div> + {/* 페이지네이션 모드일 때만 페이지 정보 표시 */} + {!isInfiniteMode && ( + <> + {/* 현재 페이지 / 전체 페이지 */} + <div className="flex items-center justify-center text-sm font-medium"> + Page {table.getState().pagination.pageIndex + 1} of{" "} + {table.getPageCount()} + </div> - {/* 페이지 이동 버튼 */} - <div className="flex items-center space-x-2"> - <Button - aria-label="Go to first page" - variant="outline" - className="hidden size-8 p-0 lg:flex" - onClick={() => table.setPageIndex(0)} - disabled={!table.getCanPreviousPage()} - > - <ChevronsLeft className="size-4" aria-hidden="true" /> - </Button> - <Button - aria-label="Go to previous page" - variant="outline" - size="icon" - className="size-8" - onClick={() => table.previousPage()} - disabled={!table.getCanPreviousPage()} - > - <ChevronLeft className="size-4" aria-hidden="true" /> - </Button> - <Button - aria-label="Go to next page" - variant="outline" - size="icon" - className="size-8" - onClick={() => table.nextPage()} - disabled={!table.getCanNextPage()} - > - <ChevronRight className="size-4" aria-hidden="true" /> - </Button> - <Button - aria-label="Go to last page" - variant="outline" - size="icon" - className="hidden size-8 lg:flex" - onClick={() => table.setPageIndex(table.getPageCount() - 1)} - disabled={!table.getCanNextPage()} - > - <ChevronsRight className="size-4" aria-hidden="true" /> - </Button> - </div> + {/* 페이지 이동 버튼 */} + <div className="flex items-center space-x-2"> + <Button + aria-label="Go to first page" + variant="outline" + className="hidden size-8 p-0 lg:flex" + onClick={() => table.setPageIndex(0)} + disabled={!table.getCanPreviousPage()} + > + <ChevronsLeft className="size-4" aria-hidden="true" /> + </Button> + <Button + aria-label="Go to previous page" + variant="outline" + size="icon" + className="size-8" + onClick={() => table.previousPage()} + disabled={!table.getCanPreviousPage()} + > + <ChevronLeft className="size-4" aria-hidden="true" /> + </Button> + <Button + aria-label="Go to next page" + variant="outline" + size="icon" + className="size-8" + onClick={() => table.nextPage()} + disabled={!table.getCanNextPage()} + > + <ChevronRight className="size-4" aria-hidden="true" /> + </Button> + <Button + aria-label="Go to last page" + variant="outline" + size="icon" + className="hidden size-8 lg:flex" + onClick={() => table.setPageIndex(table.getPageCount() - 1)} + disabled={!table.getCanNextPage()} + > + <ChevronsRight className="size-4" aria-hidden="true" /> + </Button> + </div> + </> + )} + + {/* 무한 스크롤 모드일 때 로드 더 버튼 */} + {isInfiniteMode && infiniteScroll && ( + <div className="flex items-center space-x-2"> + {infiniteScroll.hasNextPage && ( + <Button + variant="outline" + size="sm" + onClick={infiniteScroll.onLoadMore} + disabled={infiniteScroll.isLoadingMore} + > + {infiniteScroll.isLoadingMore ? ( + <> + <div className="mr-2 h-3 w-3 animate-spin rounded-full border-2 border-current border-t-transparent" /> + Loading... + </> + ) : ( + <> + <ChevronRight className="mr-2 h-3 w-3" /> + Load More + </> + )} + </Button> + )} + {!infiniteScroll.hasNextPage && table.getRowModel().rows.length > 0 && ( + <span className="text-xs text-muted-foreground"> + All data loaded + </span> + )} + </div> + )} </div> </div> ) diff --git a/components/data-table/infinite-data-table.tsx b/components/data-table/infinite-data-table.tsx new file mode 100644 index 00000000..fcac56ee --- /dev/null +++ b/components/data-table/infinite-data-table.tsx @@ -0,0 +1,294 @@ +"use client" + +import * as React from "react" +import { flexRender, type Table as TanstackTable } from "@tanstack/react-table" +import { ChevronRight, ChevronUp, Loader2 } from "lucide-react" +import { useIntersection } from "@mantine/hooks" + +import { cn } from "@/lib/utils" +import { getCommonPinningStyles } from "@/lib/data-table" +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table" +import { Button } from "@/components/ui/button" +import { DataTableResizer } from "@/components/data-table/data-table-resizer" +import { useAutoSizeColumns } from "@/hooks/useAutoSizeColumns" + +interface InfiniteDataTableProps<TData> extends React.HTMLAttributes<HTMLDivElement> { + table: TanstackTable<TData> + floatingBar?: React.ReactNode | null + autoSizeColumns?: boolean + compact?: boolean + // 무한 스크롤 관련 props + hasNextPage?: boolean + isLoadingMore?: boolean + onLoadMore?: () => void + totalCount?: number | null + isEmpty?: boolean +} + +/** + * 무한 스크롤 지원 DataTable + */ +export function InfiniteDataTable<TData>({ + table, + floatingBar = null, + autoSizeColumns = true, + compact = false, + hasNextPage = false, + isLoadingMore = false, + onLoadMore, + totalCount = null, + isEmpty = false, + children, + className, + maxHeight, + ...props +}: InfiniteDataTableProps<TData> & { maxHeight?: string | number }) { + + useAutoSizeColumns(table, autoSizeColumns) + + // Intersection Observer for infinite scroll + const { ref: loadMoreRef, entry } = useIntersection({ + threshold: 0.1, + }) + + // 자동 로딩 트리거 + React.useEffect(() => { + if (entry?.isIntersecting && hasNextPage && !isLoadingMore && onLoadMore) { + onLoadMore() + } + }, [entry?.isIntersecting, hasNextPage, isLoadingMore, onLoadMore]) + + // 컴팩트 모드를 위한 클래스 정의 + const compactStyles = compact ? { + row: "h-7", + cell: "py-1 px-2 text-sm", + groupRow: "py-1 bg-muted/20 text-sm", + emptyRow: "h-16", + } : { + row: "", + cell: "", + groupRow: "bg-muted/20", + emptyRow: "h-24", + } + + return ( + <div className={cn("w-full space-y-2.5 overflow-auto", className)} {...props}> + {children} + + {/* 총 개수 표시 */} + {totalCount !== null && ( + <div className="text-sm text-muted-foreground"> + 총 {totalCount.toLocaleString()}개 항목 + {table.getRowModel().rows.length > 0 && ( + <span className="ml-2"> + (현재 {table.getRowModel().rows.length.toLocaleString()}개 로드됨) + </span> + )} + </div> + )} + + <div + className="max-w-[100vw] overflow-auto" + style={{ maxHeight: maxHeight || '35rem' }} + > + <Table className="[&>thead]:sticky [&>thead]:top-0 [&>thead]:z-10 table-fixed"> + {/* 테이블 헤더 */} + <TableHeader> + {table.getHeaderGroups().map((headerGroup) => ( + <TableRow key={headerGroup.id} className={compact ? "h-8" : ""}> + {headerGroup.headers.map((header) => { + if (header.column.getIsGrouped()) { + return null + } + + return ( + <TableHead + key={header.id} + colSpan={header.colSpan} + data-column-id={header.column.id} + className={compact ? "py-1 px-2 text-sm" : ""} + style={{ + ...getCommonPinningStyles({ column: header.column }), + width: header.getSize(), + }} + > + <div style={{ position: "relative" }}> + {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext() + )} + + {header.column.getCanResize() && ( + <DataTableResizer header={header} /> + )} + </div> + </TableHead> + ) + })} + </TableRow> + ))} + </TableHeader> + + {/* 테이블 바디 */} + <TableBody> + {table.getRowModel().rows?.length ? ( + <> + {table.getRowModel().rows.map((row) => { + // 그룹핑 헤더 Row + if (row.getIsGrouped()) { + const groupingColumnId = row.groupingColumnId ?? "" + const groupingColumn = table.getColumn(groupingColumnId) + + let columnLabel = groupingColumnId + if (groupingColumn) { + const headerDef = groupingColumn.columnDef.meta?.excelHeader + if (typeof headerDef === "string") { + columnLabel = headerDef + } + } + + return ( + <TableRow + key={row.id} + className={compactStyles.groupRow} + data-state={row.getIsExpanded() && "expanded"} + > + <TableCell + colSpan={table.getVisibleFlatColumns().length} + className={compact ? "py-1 px-2" : ""} + > + {row.getCanExpand() && ( + <button + onClick={row.getToggleExpandedHandler()} + className="inline-flex items-center justify-center mr-2 w-5 h-5" + style={{ + marginLeft: `${row.depth * 1.5}rem`, + }} + > + {row.getIsExpanded() ? ( + <ChevronUp size={compact ? 14 : 16} /> + ) : ( + <ChevronRight size={compact ? 14 : 16} /> + )} + </button> + )} + + <span className="font-semibold"> + {columnLabel}: {row.getValue(groupingColumnId)} + </span> + <span className="ml-2 text-xs text-muted-foreground"> + ({row.subRows.length} rows) + </span> + </TableCell> + </TableRow> + ) + } + + // 일반 Row + return ( + <TableRow + key={row.id} + className={compactStyles.row} + data-state={row.getIsSelected() && "selected"} + > + {row.getVisibleCells().map((cell) => { + if (cell.column.getIsGrouped()) { + return null + } + + return ( + <TableCell + key={cell.id} + data-column-id={cell.column.id} + className={compactStyles.cell} + style={{ + ...getCommonPinningStyles({ column: cell.column }), + width: cell.column.getSize(), + }} + > + {flexRender( + cell.column.columnDef.cell, + cell.getContext() + )} + </TableCell> + ) + })} + </TableRow> + ) + })} + </> + ) : isEmpty ? ( + // 데이터가 없을 때 + <TableRow> + <TableCell + colSpan={table.getAllColumns().length} + className={compactStyles.emptyRow + " text-center"} + > + No results. + </TableCell> + </TableRow> + ) : null} + </TableBody> + </Table> + </div> + + {/* 무한 스크롤 로딩 영역 */} + <div className="flex flex-col items-center space-y-4 py-4"> + {hasNextPage && ( + <> + {/* Intersection Observer 타겟 */} + <div ref={loadMoreRef} className="h-1" /> + + {isLoadingMore && ( + <div className="flex items-center space-x-2"> + <Loader2 className="h-4 w-4 animate-spin" /> + <span className="text-sm text-muted-foreground"> + 로딩 중... + </span> + </div> + )} + + {/* 수동 로드 버튼 (자동 로딩 실패 시 대안) */} + {!isLoadingMore && onLoadMore && ( + <Button + variant="outline" + onClick={onLoadMore} + className="w-full max-w-md" + > + 더 보기 + </Button> + )} + </> + )} + + {!hasNextPage && table.getRowModel().rows.length > 0 && ( + <p className="text-sm text-muted-foreground"> + 모든 데이터를 불러왔습니다. + </p> + )} + </div> + + <div className="flex flex-col gap-2.5"> + {/* 선택된 행 정보 */} + {table.getFilteredSelectedRowModel().rows.length > 0 && ( + <div className="text-sm text-muted-foreground"> + {table.getFilteredSelectedRowModel().rows.length} of{" "} + {table.getRowModel().rows.length} row(s) selected. + </div> + )} + + {/* Floating Bar (선택된 행 있을 때) */} + {table.getFilteredSelectedRowModel().rows.length > 0 && floatingBar} + </div> + </div> + ) +}
\ No newline at end of file |
