All files / react-base/src/components data-table.tsx

0% Statements 0/656
0% Branches 0/1
0% Functions 0/1
0% Lines 0/656

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 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import {
  type Column,
  type ColumnDef,
  type ColumnFiltersState,
  type ExpandedState,
  type Row,
  type SortingState,
  type Table as TanstackTable,
  type VisibilityState,
  flexRender,
  getCoreRowModel,
  getExpandedRowModel,
  getFacetedRowModel,
  getFacetedUniqueValues,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import {
  ArrowDown,
  ArrowUp,
  ArrowUpDown,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  Download,
  ListFilter,
  RefreshCw,
  Search,
  SlidersHorizontal,
  UserPlus,
  X,
} from "lucide-react";
import * as React from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
 
declare module "@tanstack/react-table" {
  interface ColumnMeta<TData, TValue> {
    title?: string;
  }
}
 
export type DataTableFilterOption = {
  label: string;
  value: string;
};
 
export type DataTableFilterableColumn = {
  id: string;
  title: string;
  options: DataTableFilterOption[];
};
 
export type DataTableSearchAction = {
  label: string;
  onClick: () => void;
  backgroundColor?: string;
  hoverBackgroundColor?: string;
  textColor?: string;
  icon?: React.ReactNode;
  ariaLabel?: string;
};
 
type DataTableProps<TData, TValue> = {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  pageSize?: number;
  pageSizeOptions?: number[];
  searchPlaceholder?: string;
  filterableColumns?: DataTableFilterableColumn[];
  onRefresh?: () => void | Promise<void>;
  isRefreshing?: boolean;
  onExport?: () => void;
  enableSearch?: boolean;
  enableRowSelection?: boolean;
  enableColumnVisibility?: boolean;
  searchAction?: DataTableSearchAction;
  searchActions?: React.ReactNode;
  toolbarActions?: React.ReactNode;
  bulkActions?: React.ReactNode;
  onSelectionChange?: (rows: TData[]) => void;
  /** Renders a full-width panel below the row when expanded. */
  renderExpandedRow?: (row: TData) => React.ReactNode;
  /** Stable row id for expansion state (recommended when data can reorder). */
  getRowId?: (row: TData, index: number) => string;
  /** Toggle expand when clicking the row (default: true when renderExpandedRow is set). */
  expandOnRowClick?: boolean;
  /** Keep multiple rows expanded at once (default: false). */
  allowMultipleExpanded?: boolean;
};
 
function getColumnLabel<TData>(column: Column<TData, unknown>) {
  return column.columnDef.meta?.title ?? column.id;
}
 
const DataTableIconButton = React.forwardRef<
  HTMLButtonElement,
  React.ComponentProps<typeof Button> & { tooltip: string; badge?: number | string }
>(({ tooltip, badge, children, className, ...props }, ref) => (
  <Tooltip>
    <TooltipTrigger asChild>
      <Button
        ref={ref}
        type="button"
        variant="outline"
        size="sm"
        className={cn("relative h-8 w-8 shrink-0 border-dashed bg-background p-0 shadow-sm", className)}
        aria-label={tooltip}
        {...props}
      >
        {children}
        {badge !== undefined && Number(badge) > 0 ? (
          <Badge
            variant="secondary"
            className="absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-normal"
          >
            {badge}
          </Badge>
        ) : null}
      </Button>
    </TooltipTrigger>
    <TooltipContent side="bottom">{tooltip}</TooltipContent>
  </Tooltip>
));
DataTableIconButton.displayName = "DataTableIconButton";
 
export type DataTableRowAction = {
  tooltip: string;
  icon: React.ReactNode;
  onClick: () => void;
  variant?: React.ComponentProps<typeof Button>["variant"];
  disabled?: boolean;
};
 
export function DataTableRowActions({
  actions,
  className,
  align = "center",
}: {
  actions: DataTableRowAction[];
  className?: string;
  align?: "center" | "end";
}) {
  return (
    <div
      className={cn(
        "flex w-full items-center gap-1",
        align === "center" ? "justify-center" : "justify-end",
        className,
      )}
    >
      {actions.map((action, index) => (
        <Tooltip key={`${action.tooltip}-${index}`}>
          <TooltipTrigger asChild>
            <Button
              type="button"
              variant={action.variant ?? "outline"}
              size="sm"
              className="h-8 w-8 shrink-0 p-0"
              aria-label={action.tooltip}
              onClick={(event) => {
                event.stopPropagation();
                action.onClick();
              }}
              disabled={action.disabled}
            >
              {action.icon}
            </Button>
          </TooltipTrigger>
          <TooltipContent side="bottom">{action.tooltip}</TooltipContent>
        </Tooltip>
      ))}
    </div>
  );
}
 
/** Standard actions column with icon-only update/delete (extend via getActions). */
export function dataTableActionsColumn<TData>({
  getActions,
}: {
  getActions: (row: TData) => DataTableRowAction[];
}): ColumnDef<TData> {
  return {
    id: "actions",
    meta: { title: "Actions" },
    enableSorting: false,
    enableHiding: false,
    header: () => (
      <div className="flex w-full justify-center">
        <span className="text-sm font-medium">Actions</span>
      </div>
    ),
    cell: ({ row }) => <DataTableRowActions actions={getActions(row.original)} align="center" />,
  };
}
 
/** Leading expand/collapse affordance — auto-prepended when renderExpandedRow is used. */
export function dataTableExpandColumn<TData>(): ColumnDef<TData> {
  return {
    id: "expand",
    meta: { title: "Expand" },
    header: () => <span className="sr-only">Expand</span>,
    cell: ({ row }) =>
      row.getCanExpand() ? (
        <ChevronDown
          className={cn(
            "h-4 w-4 text-muted-foreground transition-transform",
            row.getIsExpanded() && "rotate-180",
          )}
          aria-hidden
        />
      ) : null,
    enableSorting: false,
    enableHiding: false,
    size: 40,
  };
}
 
export function dataTableSelectColumn<TData>({
  shape = "square",
}: {
  shape?: "rounded" | "square";
} = {}): ColumnDef<TData> {
  return {
    id: "select",
    header: ({ table }) => (
      <Checkbox
        shape={shape}
        checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label="Select all rows on this page"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        shape={shape}
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="Select row"
      />
    ),
    enableSorting: false,
    enableHiding: false,
  };
}
 
export function DataTableColumnHeader<TData, TValue>({
  column,
  title,
  className,
}: {
  column: {
    getCanSort: () => boolean;
    getIsSorted: () => false | "asc" | "desc";
    toggleSorting: (desc?: boolean) => void;
  };
  title: string;
  className?: string;
}) {
  if (!column.getCanSort()) {
    return <span className={cn("text-sm font-medium", className)}>{title}</span>;
  }
 
  const sorted = column.getIsSorted();
 
  return (
    <button
      type="button"
      className={cn(
        "-ml-2 inline-flex h-8 items-center gap-1.5 rounded-md px-2 text-sm font-medium transition-colors",
        "hover:bg-muted/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
        sorted ? "text-foreground" : "text-muted-foreground",
        className,
      )}
      onClick={() => column.toggleSorting(sorted === "asc")}
    >
      <span>{title}</span>
      {sorted === "desc" ? (
        <ArrowDown className="h-3.5 w-3.5" />
      ) : sorted === "asc" ? (
        <ArrowUp className="h-3.5 w-3.5" />
      ) : (
        <ArrowUpDown className="h-3.5 w-3.5 opacity-50" />
      )}
    </button>
  );
}
 
function DataTableFacetedFilterGroup<TData>({
  column,
  title,
  options,
}: {
  column: Column<TData, unknown> | undefined;
  title: string;
  options: DataTableFilterOption[];
}) {
  const filterValues = (column?.getFilterValue() as string[] | undefined) ?? [];
 
  const toggleOption = (optionValue: string, checked: boolean | "indeterminate") => {
    if (!column) {
      return;
    }
 
    const next = new Set(filterValues);
    if (checked === true) {
      next.add(optionValue);
    } else {
      next.delete(optionValue);
    }
 
    const values = Array.from(next);
    column.setFilterValue(values.length ? values : undefined);
  };
 
  return (
    <div className="space-y-2">
      <p className="text-sm font-medium">{title}</p>
      <div className="space-y-1">
        {options.map((option) => {
          const isSelected = filterValues.includes(option.value);
          return (
            <div
              key={option.value}
              className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/60"
              onClick={() => toggleOption(option.value, !isSelected)}
              onKeyDown={(event) => {
                if (event.key === "Enter" || event.key === " ") {
                  event.preventDefault();
                  toggleOption(option.value, !isSelected);
                }
              }}
              role="button"
              tabIndex={0}
            >
              <Checkbox
                shape="square"
                checked={isSelected}
                onCheckedChange={(checked) => toggleOption(option.value, checked)}
                onClick={(event) => event.stopPropagation()}
              />
              <span>{option.label}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}
 
function DataTableSearch<TData>({
  table,
  searchPlaceholder,
  className,
}: {
  table: TanstackTable<TData>;
  searchPlaceholder: string;
  className?: string;
}) {
  const query = (table.getState().globalFilter as string) ?? "";
 
  return (
    <div className={cn("relative min-w-0 flex-1", className)}>
      <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
      <Input
        placeholder={searchPlaceholder}
        value={query}
        onChange={(event) => table.setGlobalFilter(event.target.value)}
        className="h-9 bg-background pl-8 pr-8 shadow-sm"
      />
      {query ? (
        <button
          type="button"
          aria-label="Clear search"
          className="absolute right-2.5 top-2.5 rounded-sm text-muted-foreground hover:text-foreground"
          onClick={() => table.setGlobalFilter("")}
        >
          <X className="h-4 w-4" />
        </button>
      ) : null}
    </div>
  );
}
 
function DataTableSearchActionButton({ action }: { action: DataTableSearchAction }) {
  const { label, onClick, backgroundColor, hoverBackgroundColor, textColor, icon, ariaLabel } = action;
  const tooltip = ariaLabel ?? label;
  const hasCustomColors = Boolean(backgroundColor || textColor || hoverBackgroundColor);
 
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          variant={hasCustomColors ? "default" : "brand"}
          size="sm"
          className={cn(
            "h-8 w-8 shrink-0 border-0 p-0 shadow-sm",
            hasCustomColors && "bg-primary text-primary-foreground hover:bg-primary/90",
          )}
          style={
            hasCustomColors
              ? {
                  backgroundColor,
                  color: textColor,
                }
              : undefined
          }
          aria-label={tooltip}
          onClick={onClick}
          onMouseEnter={(event) => {
            if (hoverBackgroundColor) {
              event.currentTarget.style.backgroundColor = hoverBackgroundColor;
            }
          }}
          onMouseLeave={(event) => {
            if (backgroundColor) {
              event.currentTarget.style.backgroundColor = backgroundColor;
            }
          }}
        >
          {icon ?? <UserPlus className="h-4 w-4" />}
        </Button>
      </TooltipTrigger>
      <TooltipContent side="bottom">{tooltip}</TooltipContent>
    </Tooltip>
  );
}
 
function DataTableFiltersPopover<TData>({
  table,
  filterableColumns,
}: {
  table: TanstackTable<TData>;
  filterableColumns?: DataTableFilterableColumn[];
}) {
  const activeFilterCount = table.getState().columnFilters.length;
 
  if (!filterableColumns?.length) {
    return null;
  }
 
  return (
    <Popover modal>
      <PopoverTrigger asChild>
        <DataTableIconButton tooltip="Filters" badge={activeFilterCount || undefined}>
          <ListFilter className="h-4 w-4" />
        </DataTableIconButton>
      </PopoverTrigger>
      <PopoverContent align="start" className="z-[100] w-80 p-0">
        <div className="border-b px-4 py-3">
          <p className="text-sm font-semibold">Filters</p>
          <p className="text-xs text-muted-foreground">Filter rows by column values.</p>
        </div>
        <ScrollArea className="max-h-80">
          <div className="space-y-4 p-4">
            {filterableColumns.map((filterColumn) => (
              <DataTableFacetedFilterGroup
                key={filterColumn.id}
                column={table.getColumn(filterColumn.id)}
                title={filterColumn.title}
                options={filterColumn.options}
              />
            ))}
          </div>
        </ScrollArea>
        {activeFilterCount > 0 && (
          <div className="border-t p-2">
            <Button
              variant="outline"
              size="sm"
              className="h-8 w-full"
              onClick={() => table.resetColumnFilters()}
            >
              Reset filters
            </Button>
          </div>
        )}
      </PopoverContent>
    </Popover>
  );
}
 
function DataTableSortDropdown<TData>({ table }: { table: TanstackTable<TData> }) {
  const sortableColumns = table.getAllLeafColumns().filter((column) => column.getCanSort());
  const sorting = table.getState().sorting;
 
  return (
    <DropdownMenu modal={false}>
      <DropdownMenuTrigger asChild>
        <DataTableIconButton tooltip="Sort" badge={sorting.length || undefined}>
          <ArrowUpDown className="h-4 w-4" />
        </DataTableIconButton>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="z-[100] w-52">
        <DropdownMenuLabel>Sort by</DropdownMenuLabel>
        <DropdownMenuSeparator />
        {sortableColumns.length === 0 ? (
          <p className="px-2 py-3 text-sm text-muted-foreground">No sortable columns.</p>
        ) : (
          sortableColumns.map((column) => {
            const sorted = column.getIsSorted();
            return (
              <DropdownMenuItem
                key={column.id}
                onSelect={(event) => {
                  event.preventDefault();
                  column.toggleSorting(sorted === "asc");
                }}
              >
                <span className="flex-1">{getColumnLabel(column)}</span>
                {sorted === "asc" ? (
                  <ArrowUp className="h-4 w-4 text-muted-foreground" />
                ) : sorted === "desc" ? (
                  <ArrowDown className="h-4 w-4 text-muted-foreground" />
                ) : (
                  <ArrowUpDown className="h-4 w-4 opacity-30" />
                )}
              </DropdownMenuItem>
            );
          })
        )}
        {sorting.length > 0 && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onSelect={(event) => {
                event.preventDefault();
                table.resetSorting();
              }}
              className="text-muted-foreground"
            >
              Clear sorting
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
 
function DataTableViewDropdown<TData>({ table }: { table: TanstackTable<TData> }) {
  const hideableColumns = table.getAllLeafColumns().filter((column) => column.getCanHide());
  const hiddenCount = hideableColumns.filter((column) => !column.getIsVisible()).length;
 
  return (
    <DropdownMenu modal={false}>
      <DropdownMenuTrigger asChild>
        <DataTableIconButton tooltip="View columns" badge={hiddenCount || undefined}>
          <SlidersHorizontal className="h-4 w-4" />
        </DataTableIconButton>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="z-[100] w-52">
        <DropdownMenuLabel>Toggle columns</DropdownMenuLabel>
        <DropdownMenuSeparator />
        {hideableColumns.length === 0 ? (
          <p className="px-2 py-3 text-sm text-muted-foreground">No hideable columns.</p>
        ) : (
          hideableColumns.map((column) => (
            <DropdownMenuCheckboxItem
              key={column.id}
              checked={column.getIsVisible()}
              onCheckedChange={(checked) => column.toggleVisibility(checked === true)}
              onSelect={(event) => event.preventDefault()}
            >
              {getColumnLabel(column)}
            </DropdownMenuCheckboxItem>
          ))
        )}
        {hiddenCount > 0 && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onSelect={(event) => {
                event.preventDefault();
                table.resetColumnVisibility();
              }}
            >
              Show all columns
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
 
type DataTableToolbarProps<TData> = {
  table: TanstackTable<TData>;
  searchPlaceholder: string;
  filterableColumns?: DataTableFilterableColumn[];
  onRefresh?: () => void | Promise<void>;
  isRefreshing?: boolean;
  onExport?: () => void;
  enableSearch?: boolean;
  enableColumnVisibility?: boolean;
  searchAction?: DataTableSearchAction;
  searchActions?: React.ReactNode;
  toolbarActions?: React.ReactNode;
};
 
function DataTableToolbar<TData>({
  table,
  searchPlaceholder,
  filterableColumns,
  onRefresh,
  isRefreshing,
  onExport,
  enableSearch = true,
  enableColumnVisibility = true,
  searchAction,
  searchActions,
  toolbarActions,
}: DataTableToolbarProps<TData>) {
  const searchRowActions = (
    <>
      {searchAction ? <DataTableSearchActionButton action={searchAction} /> : null}
      {searchActions}
    </>
  );
  const hasSearchRowActions = Boolean(searchAction || searchActions);
 
  return (
    <div className="flex flex-col gap-2 border-b bg-muted/20 px-3 py-2">
      <div className="flex flex-wrap items-center gap-2">
        {enableSearch ? <DataTableSearch table={table} searchPlaceholder={searchPlaceholder} /> : null}
        <div className="ml-auto flex shrink-0 flex-wrap items-center gap-1">
          <DataTableFiltersPopover table={table} filterableColumns={filterableColumns} />
          <DataTableSortDropdown table={table} />
          {onExport ? (
            <DataTableIconButton tooltip="Export" onClick={onExport}>
              <Download className="h-4 w-4" />
            </DataTableIconButton>
          ) : null}
          {enableColumnVisibility ? <DataTableViewDropdown table={table} /> : null}
          {toolbarActions}
          {onRefresh ? (
            <DataTableIconButton
              tooltip="Refresh"
              onClick={() => onRefresh()}
              disabled={isRefreshing}
            >
              <RefreshCw className={cn("h-4 w-4", isRefreshing && "animate-spin")} />
            </DataTableIconButton>
          ) : null}
          {hasSearchRowActions ? searchRowActions : null}
        </div>
      </div>
    </div>
  );
}
 
function DataTableBulkBar<TData>({
  table,
  bulkActions,
}: {
  table: TanstackTable<TData>;
  bulkActions?: React.ReactNode;
}) {
  const selectedCount = table.getFilteredSelectedRowModel().rows.length;
 
  if (selectedCount === 0) {
    return null;
  }
 
  return (
    <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-dashed bg-muted/30 px-3 py-2">
      <p className="text-sm text-muted-foreground">
        {selectedCount} row{selectedCount === 1 ? "" : "s"} selected
      </p>
      <div className="flex flex-wrap items-center gap-2">
        {bulkActions}
        <Button variant="outline" size="sm" className="h-8" onClick={() => table.resetRowSelection()}>
          Clear selection
        </Button>
      </div>
    </div>
  );
}
 
function DataTablePagination<TData>({
  table,
  pageSizeOptions,
  enableRowSelection,
}: {
  table: TanstackTable<TData>;
  pageSizeOptions: number[];
  enableRowSelection: boolean;
}) {
  const selectedCount = table.getFilteredSelectedRowModel().rows.length;
  const totalCount = table.getFilteredRowModel().rows.length;
 
  return (
    <div className="flex flex-col gap-4 px-1 sm:flex-row sm:items-center sm:justify-between">
      <p className="text-sm text-muted-foreground">
        {enableRowSelection ? (
          <>
            {selectedCount} of {totalCount} row(s) selected.
          </>
        ) : (
          <>{totalCount} row(s) total.</>
        )}
      </p>
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:gap-6">
        <div className="flex items-center gap-2">
          <span className="whitespace-nowrap text-sm text-muted-foreground">Rows per page</span>
          <Select
            value={`${table.getState().pagination.pageSize}`}
            onValueChange={(value) => table.setPageSize(Number(value))}
          >
            <SelectTrigger className="h-8 w-[4.5rem]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent side="top">
              {pageSizeOptions.map((size) => (
                <SelectItem key={size} value={`${size}`}>
                  {size}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="flex items-center justify-between gap-4 sm:justify-end">
          <span className="whitespace-nowrap text-sm font-medium">
            Page {table.getState().pagination.pageIndex + 1} of {table.getPageCount() || 1}
          </span>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="sm"
              className="h-8 w-8 p-0"
              onClick={() => table.setPageIndex(0)}
              disabled={!table.getCanPreviousPage()}
              aria-label="First page"
            >
              <ChevronsLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="h-8 w-8 p-0"
              onClick={() => table.previousPage()}
              disabled={!table.getCanPreviousPage()}
              aria-label="Previous page"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="h-8 w-8 p-0"
              onClick={() => table.nextPage()}
              disabled={!table.getCanNextPage()}
              aria-label="Next page"
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="h-8 w-8 p-0"
              onClick={() => table.setPageIndex(table.getPageCount() - 1)}
              disabled={!table.getCanNextPage()}
              aria-label="Last page"
            >
              <ChevronsRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
 
function globalUserSearchFilter<TData>(row: Row<TData>, _columnId: string, filterValue: string) {
  const query = filterValue.trim().toLowerCase();
  if (!query) {
    return true;
  }
 
  const record = row.original as Record<string, unknown>;
  const name = String(record.name ?? "").toLowerCase();
  const email = String(record.email ?? "").toLowerCase();
  const role = String(record.role ?? "").toLowerCase();
 
  return name.includes(query) || email.includes(query) || role.includes(query);
}
 
export function DataTable<TData, TValue>({
  columns,
  data,
  pageSize = 10,
  pageSizeOptions = [5, 10, 20, 30, 50],
  searchPlaceholder = "Search rows...",
  filterableColumns,
  onRefresh,
  isRefreshing = false,
  onExport,
  enableSearch = true,
  enableRowSelection = false,
  enableColumnVisibility = true,
  searchAction,
  searchActions,
  toolbarActions,
  bulkActions,
  onSelectionChange,
  renderExpandedRow,
  getRowId,
  expandOnRowClick,
  allowMultipleExpanded = false,
}: DataTableProps<TData, TValue>) {
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]);
  const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({});
  const [rowSelection, setRowSelection] = React.useState({});
  const [globalFilter, setGlobalFilter] = React.useState("");
  const [expanded, setExpanded] = React.useState<ExpandedState>({});
  const canExpandRows = Boolean(renderExpandedRow);
  const shouldExpandOnRowClick = canExpandRows && expandOnRowClick !== false;
 
  const tableColumns = React.useMemo(() => {
    const next: ColumnDef<TData, TValue>[] = [];
    if (canExpandRows) {
      next.push(dataTableExpandColumn<TData>());
    }
    if (enableRowSelection) {
      next.push(dataTableSelectColumn<TData>());
    }
    next.push(...columns);
    return next;
  }, [canExpandRows, columns, enableRowSelection]);
 
  const handleExpandedChange = React.useCallback(
    (updater: ExpandedState | ((old: ExpandedState) => ExpandedState)) => {
      setExpanded((current) => {
        const next = typeof updater === "function" ? updater(current) : updater;
        if (allowMultipleExpanded) {
          return next;
        }
        const expandedIds = Object.entries(next)
          .filter(([, isExpanded]) => isExpanded)
          .map(([key]) => key);
        if (expandedIds.length <= 1) {
          return next;
        }
        const latestId = expandedIds[expandedIds.length - 1];
        return { [latestId]: true };
      });
    },
    [allowMultipleExpanded],
  );
 
  const table = useReactTable({
    data,
    columns: tableColumns,
    ...(getRowId ? { getRowId: (row: TData, index: number) => getRowId(row, index) } : {}),
    state: {
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
      globalFilter,
      expanded,
    },
    enableRowSelection,
    enableSorting: true,
    enableColumnFilters: true,
    enableHiding: true,
    enableExpanding: canExpandRows,
    paginateExpandedRows: false,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    onGlobalFilterChange: setGlobalFilter,
    onExpandedChange: handleExpandedChange,
    getRowCanExpand: () => canExpandRows,
    globalFilterFn: globalUserSearchFilter,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getExpandedRowModel: getExpandedRowModel(),
    getFacetedRowModel: getFacetedRowModel(),
    getFacetedUniqueValues: getFacetedUniqueValues(),
    initialState: {
      pagination: { pageSize },
    },
  });
 
  React.useEffect(() => {
    if (!onSelectionChange) {
      return;
    }
    const selected = table.getFilteredSelectedRowModel().rows.map((row) => row.original);
    onSelectionChange(selected);
  }, [rowSelection, data, onSelectionChange, table]);
 
  return (
    <div className="space-y-4">
      <div className="overflow-hidden rounded-lg border bg-card shadow-sm">
        <DataTableToolbar
          table={table}
          searchPlaceholder={searchPlaceholder}
          filterableColumns={filterableColumns}
          onRefresh={onRefresh}
          isRefreshing={isRefreshing}
          onExport={onExport}
          enableSearch={enableSearch}
          enableColumnVisibility={enableColumnVisibility}
          searchAction={searchAction}
          searchActions={searchActions}
          toolbarActions={toolbarActions}
        />
 
        {enableRowSelection ? (
          <div className="border-b px-3 py-2">
            <DataTableBulkBar table={table} bulkActions={bulkActions} />
          </div>
        ) : null}
 
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id} className="border-b bg-muted/30 hover:bg-muted/30">
                {headerGroup.headers.map((header) => (
                  <TableHead
                    key={header.id}
                    className={cn(
                      "h-11",
                      header.column.id === "actions" && "text-center",
                      header.column.id === "expand" && "w-10",
                    )}
                  >
                    {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <React.Fragment key={row.id}>
                  <TableRow
                    data-state={row.getIsSelected() && "selected"}
                    className={cn(
                      shouldExpandOnRowClick && row.getCanExpand() && "cursor-pointer",
                      row.getIsExpanded() && "bg-muted/30",
                    )}
                    onClick={
                      shouldExpandOnRowClick && row.getCanExpand()
                        ? () => row.toggleExpanded()
                        : undefined
                    }
                  >
                    {row.getVisibleCells().map((cell) => (
                      <TableCell
                        key={cell.id}
                        className={cn(
                          "h-12",
                          cell.column.id === "actions" && "text-center",
                          cell.column.id === "expand" && "w-10",
                        )}
                        onClick={
                          cell.column.id === "select" || cell.column.id === "actions"
                            ? (event) => event.stopPropagation()
                            : undefined
                        }
                      >
                        {flexRender(cell.column.columnDef.cell, cell.getContext())}
                      </TableCell>
                    ))}
                  </TableRow>
                  {row.getIsExpanded() && renderExpandedRow ? (
                    <TableRow className="bg-muted/20 hover:bg-muted/20">
                      <TableCell colSpan={row.getVisibleCells().length} className="p-4">
                        {renderExpandedRow(row.original)}
                      </TableCell>
                    </TableRow>
                  ) : null}
                </React.Fragment>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={table.getVisibleLeafColumns().length} className="h-24 text-center">
                  No results.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
 
      <DataTablePagination
        table={table}
        pageSizeOptions={pageSizeOptions}
        enableRowSelection={enableRowSelection}
      />
    </div>
  );
}