All files / components/common DataTable.tsx

82.85% Statements 58/70
82.9% Branches 97/117
80.76% Functions 21/26
86.15% Lines 56/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452                                                                                                                                                                                                          453x 453x     453x 453x     453x 318x 318x                                 453x   7735x     7735x       453x 7735x         453x 5216x 3437x   1779x 1775x   4x       453x 453x 453x     453x 453x 453x 453x   453x 1x 1x       453x                 2519x                 1x                                                                       1037x   18x       5216x                                                                       1740x                                         1x                                         1x                 290x     290x           290x 11x       290x     290x 11x       290x     290x     290x   290x 312x     290x 312x             312x 312x       1x                       1x                                       1x                                                                                                              
import React from 'react';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Pagination,
    PaginationContent,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationNext,
    PaginationPrevious,
} from '@/components/ui/pagination';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { ArrowUpDown, RefreshCw, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useEffect, useRef } from 'react';
 
export interface Column<T> {
    header: string | React.ReactNode;
    accessorKey?: keyof T;
    render?: (item: T) => React.ReactNode;
    sortable?: boolean;
    className?: string; // For setting width or alignment
    frozen?: 'left' | 'right';      // Sticky column position
    frozenOffset?: number;           // px offset for left-frozen columns (cumulative width of preceding frozen cols)
    frozenBorderRight?: boolean;     // Show right border/shadow on last left-frozen column
    headerSuffix?: React.ReactNode;  // Extra content rendered after header text, outside the sort button
    style?: React.CSSProperties;     // Additional cell styles (e.g. minWidth, maxWidth)
}
 
export interface DispatchPagination {
    page: number;
    pageSize: number;
    onPageChange: (page: number) => void;
    onPageSizeChange: (pageSize: number) => void;
}
 
export interface DispatchSorting {
    sortBy: string;
    sortOrder: 'asc' | 'desc';
    onSort: (column: string) => void;
}
 
interface DataTableProps<T> {
    data: T[];
    columns: Column<T>[];
    keyExtractor: (item: T) => string | number;
    isLoading?: boolean;
    totalItems?: number; // Total items in DB for server-side pagination
    pagination?: DispatchPagination;
    sorting?: DispatchSorting;
    onRowClick?: (item: T) => void;
    noDataMessage?: string;
    // Cursor pagination props
    paginationMode?: 'page' | 'scroll';
    hasMore?: boolean;
    onLoadMore?: () => void;
    isLoadingMore?: boolean;
    onPaginationModeChange?: (mode: 'page' | 'scroll') => void;
    autoLoad?: boolean;
    onAutoLoadChange?: (enabled: boolean) => void;
    showModeToggle?: boolean; // Show Page/Scroll toggle (default: false)
    maxTableHeight?: string; // Max height before scroll kicks in (default: '600px')
    minTableHeight?: string; // Min height when data is empty/sparse (default: '180px')
}
 
export function DataTable<T>({
    data,
    columns,
    keyExtractor,
    isLoading = false,
    totalItems = 0,
    pagination,
    sorting,
    onRowClick,
    noDataMessage = 'No data found',
    paginationMode = 'page',
    hasMore = false,
    onLoadMore,
    isLoadingMore = false,
    onPaginationModeChange,
    autoLoad = false,
    onAutoLoadChange,
    showModeToggle = false,
    maxTableHeight = '600px',
    minTableHeight = '180px',
}: DataTableProps<T>) {
    const sentinelRef = useRef<HTMLDivElement>(null);
    const scrollContainerRef = useRef<HTMLDivElement>(null);
 
    // Stable callback ref so the observer doesn't re-register on every render
    const onLoadMoreRef = useRef(onLoadMore);
    useEffect(() => { onLoadMoreRef.current = onLoadMore; }, [onLoadMore]);
 
    // Infinite scroll IntersectionObserver — sentinel lives inside the scroll container
    useEffect(() => {
        Eif (paginationMode !== 'scroll' || !autoLoad || !hasMore || !sentinelRef.current || !scrollContainerRef.current) {
            return;
        }
 
        const observer = new IntersectionObserver(
            (entries) => {
                if (entries[0].isIntersecting && hasMore && !isLoadingMore && onLoadMoreRef.current) {
                    onLoadMoreRef.current();
                }
            },
            { threshold: 0.1, root: scrollContainerRef.current }
        );
 
        observer.observe(sentinelRef.current);
        return () => observer.disconnect();
    }, [paginationMode, autoLoad, hasMore, isLoadingMore]);
 
    // Compute sticky style for frozen columns
    const getCellStyle = (col: Column<T>): React.CSSProperties => {
        const frozenStyle: React.CSSProperties =
            col.frozen === 'left' ? { position: 'sticky', left: col.frozenOffset ?? 0, zIndex: 10 }
                : col.frozen === 'right' ? { position: 'sticky', right: 0, zIndex: 10 }
                    : {};
        return { ...col.style, ...frozenStyle };
    };
 
    // Background + optional right border for frozen columns
    const getFrozenClass = (col: Column<T>) =>
        col.frozen
            ? cn('bg-background', col.frozenBorderRight && 'border-r shadow-[1px_0_4px_0_hsl(var(--border))]')
            : '';
 
    // Helper to resolve cell content
    const renderCell = (item: T, column: Column<T>) => {
        if (column.render) {
            return column.render(item);
        }
        if (column.accessorKey) {
            return item[column.accessorKey] as React.ReactNode;
        }
        return null;
    };
 
    // Calculate pagination values
    const currentPage = pagination?.page || 1;
    const pageSize = pagination?.pageSize || 10;
    const totalPages = Math.ceil(totalItems / pageSize) || 1;
 
    // Pagination helpers
    const canGoPrevious = currentPage > 1;
    const canGoNext = currentPage < totalPages;
    const showingStart = totalItems === 0 ? 0 : (currentPage - 1) * pageSize + 1;
    const showingEnd = Math.min(currentPage * pageSize, totalItems);
 
    const handleSort = (column: Column<T>) => {
        Eif (sorting && column.sortable && column.accessorKey) {
            sorting.onSort(String(column.accessorKey));
        }
    };
 
    return (
        <div className="space-y-4">
            {/* Table container: grows with content up to maxTableHeight, scrollable beyond that */}
            <div className="rounded-md border overflow-hidden flex flex-col" style={{ minHeight: minTableHeight, maxHeight: maxTableHeight }}>
                <div ref={scrollContainerRef} className="overflow-x-auto overflow-y-auto flex-1">
                    <Table>
                        <TableHeader className="sticky top-0 z-20 bg-background">
                            <TableRow>
                                {columns.map((col, index) => (
                                    <TableHead
                                        key={index}
                                        className={cn(col.className, getFrozenClass(col), 'group')}
                                        style={getCellStyle(col)}
                                    >
                                        <div className="flex items-center">
                                            {sorting && col.sortable ? (
                                                <Button
                                                    variant="ghost"
                                                    onClick={() => handleSort(col)}
                                                    className="-ml-4 h-8 px-4 data-[state=open]:bg-accent hover:bg-transparent hover:text-primary"
                                                >
                                                    {col.header}
                                                    {sorting.sortBy === col.accessorKey ? (
                                                        <ArrowUpDown className={`ml-2 h-4 w-4 transform ${sorting.sortOrder === 'asc' ? 'rotate-180' : ''}`} />
                                                    ) : (
                                                        <ArrowUpDown className="ml-2 h-4 w-4 opacity-50" />
                                                    )}
                                                </Button>
                                            ) : (
                                                col.header
                                            )}
                                            {col.headerSuffix}
                                        </div>
                                    </TableHead>
                                ))}
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {isLoading ? (
                                <TableRow>
                                    <TableCell colSpan={columns.length} className="h-24 text-center">
                                        <div className="flex items-center justify-center py-4">
                                            <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
                                        </div>
                                    </TableCell>
                                </TableRow>
                            ) : data.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={columns.length} className="h-24 text-center text-muted-foreground">
                                        {noDataMessage}
                                    </TableCell>
                                </TableRow>
                            ) : (
                                data.map((item) => (
                                    <TableRow
                                        key={keyExtractor(item)}
                                        onClick={() => onRowClick && onRowClick(item)}
                                        className={onRowClick ? "cursor-pointer hover:bg-muted/50" : ""}
                                    >
                                        {columns.map((col, cIndex) => (
                                            <TableCell
                                                key={cIndex}
                                                className={cn(col.className, getFrozenClass(col))}
                                                style={getCellStyle(col)}
                                            >
                                                {renderCell(item, col)}
                                            </TableCell>
                                        ))}
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                    {/* Infinite scroll sentinel — inside the scroll container so it's observed on table scroll */}
                    {paginationMode === 'scroll' && (
                        <div ref={sentinelRef} className="h-1" />
                    )}
                </div>
            </div>
 
            {/* Pagination Controls */}
            {pagination && totalItems > 0 && paginationMode === 'page' && (
                <div className="flex flex-col-reverse gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="flex items-center space-x-2 text-sm text-muted-foreground">
                        <span>Rows per page</span>
                        <Select
                            value={`${pageSize}`}
                            onValueChange={(value) => {
                                pagination.onPageSizeChange(Number(value));
                            }}
                        >
                            <SelectTrigger className="h-8 w-[70px]">
                                <SelectValue placeholder={pageSize} />
                            </SelectTrigger>
                            <SelectContent side="top">
                                {[10, 20, 30, 40, 50, 100].map((size) => (
                                    <SelectItem key={size} value={`${size}`}>
                                        {size}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
 
                        {/* Pagination Mode Toggle - only show if explicitly enabled */}
                        {showModeToggle && (
                            <div className="flex items-center border rounded-md ml-4">
                                <Button
                                    variant={paginationMode === 'page' ? 'default' : 'ghost'}
                                    size="sm"
                                    onClick={() => onPaginationModeChange?.('page')}
                                    className="rounded-none border-r"
                                >
                                    Page
                                </Button>
                                <Button
                                    variant={paginationMode === 'scroll' ? 'default' : 'ghost'}
                                    size="sm"
                                    onClick={() => onPaginationModeChange?.('scroll')}
                                    className="rounded-none"
                                >
                                    Scroll
                                </Button>
                            </div>
                        )}
 
                        <span className="hidden md:inline-block ml-4">
                            Showing {showingStart} to {showingEnd} of {totalItems} entries
                        </span>
                    </div>
 
                    <div className="flex items-center justify-center sm:justify-end">
                        <div className="md:hidden text-sm text-muted-foreground mr-4">
                            {currentPage} / {totalPages}
                        </div>
                        <Pagination>
                            <PaginationContent>
                                <PaginationItem>
                                    <PaginationPrevious
                                        onClick={() => canGoPrevious && pagination.onPageChange(currentPage - 1)}
                                        className={!canGoPrevious ? 'pointer-events-none opacity-50' : 'cursor-pointer'}
                                    />
                                </PaginationItem>
 
                                {/* Simple logic for now: show surrounding pages */}
                                {(() => {
 
 
                                    const items = [];
 
                                    // Always show first
                                    Eif (totalPages > 0) {
                                        // If many pages, logic needed
                                    }
 
                                    /* Simplified Logic for generic component */
                                    // Always show Page 1
                                    if (totalPages > 1) {
                                        items.push(1);
                                    }
 
                                    // If current is far from 1, ellipsis
                                    Iif (currentPage > 3) items.push('e1');
 
                                    // Surrounding
                                    for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
                                        items.push(i);
                                    }
 
                                    // If current is far from end, ellipsis
                                    Iif (currentPage < totalPages - 2) items.push('e2');
 
                                    // Always show last
                                    items.push(totalPages);
 
                                    // Dedup and single page case
                                    const uniqueItems = Array.from(new Set(items));
                                    // Basic 1..N if totalPages is small
                                    const renderList = totalPages <= 7
                                        ? Array.from({ length: totalPages }, (_, i) => i + 1)
                                        : uniqueItems;
 
                                    return renderList.map((p, idx) => {
                                        Iif (p === 'e1' || p === 'e2') {
                                            return (
                                                <PaginationItem key={`ellipsis-${idx}`}>
                                                    <PaginationEllipsis />
                                                </PaginationItem>
                                            );
                                        }
                                        const pageNum = p as number;
                                        return (
                                            <PaginationItem key={pageNum} className="hidden sm:inline-block">
                                                <PaginationLink
                                                    isActive={currentPage === pageNum}
                                                    onClick={() => pagination.onPageChange(pageNum)}
                                                    className="cursor-pointer"
                                                >
                                                    {pageNum}
                                                </PaginationLink>
                                            </PaginationItem>
                                        );
                                    });
                                })()}
 
                                <PaginationItem>
                                    <PaginationNext
                                        onClick={() => canGoNext && pagination.onPageChange(currentPage + 1)}
                                        className={!canGoNext ? 'pointer-events-none opacity-50' : 'cursor-pointer'}
                                    />
                                </PaginationItem>
                            </PaginationContent>
                        </Pagination>
                    </div>
                </div>
            )}
 
            {/* Scroll Mode Controls */}
            {paginationMode === 'scroll' && data.length > 0 && (
                <div className="flex flex-col-reverse gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="flex items-center space-x-2 text-sm text-muted-foreground">
                        {/* Show Mode Toggle only if explicitly enabled */}
                        {showModeToggle && (
                            <div className="flex items-center border rounded-md">
                                <Button
                                    variant={paginationMode === 'page' ? 'default' : 'ghost'}
                                    size="sm"
                                    onClick={() => onPaginationModeChange?.('page')}
                                    className="rounded-none border-r"
                                >
                                    Page
                                </Button>
                                <Button
                                    variant={paginationMode === 'scroll' ? 'default' : 'ghost'}
                                    size="sm"
                                    onClick={() => onPaginationModeChange?.('scroll')}
                                    className="rounded-none"
                                >
                                    Scroll
                                </Button>
                            </div>
                        )}
 
                        <span className="hidden md:inline-block text-muted-foreground">
                            Loaded {data.length} records{hasMore ? ' (more available)' : ' (all loaded)'}
                        </span>
                    </div>
 
                    <div className="flex items-center gap-3 flex-wrap">
                        <div className="flex items-center gap-2">
                            <span className="text-sm text-muted-foreground">Auto-load</span>
                            <Switch
                                checked={autoLoad}
                                onCheckedChange={onAutoLoadChange}
                                disabled={!hasMore || isLoadingMore}
                            />
                        </div>
                        {hasMore && (
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={onLoadMore}
                                disabled={isLoadingMore}
                                className="gap-2"
                            >
                                {isLoadingMore ? (
                                    <>
                                        <Loader2 className="h-4 w-4 animate-spin" />
                                        Loading...
                                    </>
                                ) : (
                                    'Load More'
                                )}
                            </Button>
                        )}
                    </div>
                </div>
            )}
 
        </div>
    );
}