import { flexRender, Table as TSTable } from "@tanstack/react-table"; import { useResourceTable } from "../../hooks/use_resource_table.js"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "../ui/table.js"; import { ChevronsLeft, ChevronsRight, Search } from "lucide-react"; import { Pagination, PaginationContent, PaginationLink, PaginationItem, PaginationPrevious, PaginationNext, } from "../ui/pagination.js"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "../ui/select.js"; import { RecordProvider } from "../../providers/record.js"; import { ComponentProps, useEffect, useRef } from "react"; import { cn } from "../../utils/cn.js"; import { Input } from "../ui/input.js"; import { useTableNavigation } from "../../hooks/use_table_navigation.js"; import { router } from "@inertiajs/react"; import { useResource } from "../../providers/resource.js"; import { useCommand } from "../../providers/command.js"; export const ResourceTable = ({ options = {}, className, ...props }: ComponentProps<"div"> & { options?: Parameters[0]; }) => { const tableRef = useRef(null); const inputRef = useRef(null); const command = useCommand(); const { resource } = useResource(); const { table, query, setQuery } = useResourceTable(options); const { getRowProps } = useTableNavigation({ table, tableRef, inputRef, onKeyDown: (e, row) => { if (e.key === "Enter") { router.visit(`/admin/resources/${resource.name}/${row.id}/edit`); } }, }); useEffect(() => { command.updateCommands({ icon: Search, label: `Search ${resource.name}`, onSelect: () => { // NOTE: Run on next tick, because i dont know. Dont touch it setTimeout(() => inputRef.current?.focus(), 0); }, group: "page-actions", }); }, []); return (
setQuery(e.target.value)} placeholder="Search..." />
{/* */}
{table.getHeaderGroups().map((headerGroup) => ( {headerGroup.headers.map((header) => { return ( {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext(), )} ); })} ))} {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( {row.getVisibleCells().map((cell) => ( {flexRender( cell.column.columnDef.cell, cell.getContext(), )} ))} )) ) : ( No results. )}
); }; const TablePagination = ({ table }: { table: TSTable }) => { const state = table.getState(); const sizes = [10, 25, 50, 100, 250, 500]; const pageCount = table.getPageCount(); const currentPage = state.pagination.pageIndex; const max = pageCount - 3; const min = 0 + 2; const center = Math.min(Math.max(currentPage, min), max); const pages = Array.from({ length: Math.min(pageCount, 5) }).map((_, i) => { if (pageCount < 5) return i; return i - 2 + center; }); return (
table.setPageIndex(0)} > table.previousPage()} /> {pages.map((i) => { return ( table.setPageIndex(i)} > {i + 1} ); })} table.nextPage()} disabled={!table.getCanNextPage()} /> table.setPageIndex(pageCount - 1)} >
{table.getRowCount()} total rows
); };