{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"shadcn-studio/data-table-11","type":"registry:component","title":"Data Table 11","description":"data table with sorting, row selection, and pagination - styled with Origin UI and powered by @tanstack/react-table","dependencies":["lucide-react","@tanstack/react-table"],"registryDependencies":["badge","button","checkbox","pagination","select","table"],"files":[{"path":"src/registry/new-york/components/data-table/data-table-11.tsx","content":"'use client'\n\nimport { useEffect, useState } from 'react'\n\nimport { ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, ChevronUpIcon } from 'lucide-react'\n\nimport type { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table'\nimport {\n  flexRender,\n  getCoreRowModel,\n  getPaginationRowModel,\n  getSortedRowModel,\n  useReactTable\n} from '@tanstack/react-table'\n\nimport { Badge } from '@/registry/new-york/ui/badge'\nimport { Button } from '@/registry/new-york/ui/button'\nimport { Checkbox } from '@/registry/new-york/ui/checkbox'\nimport { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/registry/new-york/ui/pagination'\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/registry/new-york/ui/select'\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/registry/new-york/ui/table'\n\nimport { usePagination } from '@/registry/new-york/hooks/use-pagination'\n\nimport { cn } from '@/registry/new-york/lib/utils'\n\ntype Item = {\n  product_name: string\n  price: string\n  availability: 'In Stock' | 'Out of Stock' | 'Limited'\n}\n\nconst columns: ColumnDef<Item>[] = [\n  {\n    id: 'select',\n    header: ({ table }) => (\n      <Checkbox\n        checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && 'indeterminate')}\n        onCheckedChange={value => table.toggleAllPageRowsSelected(!!value)}\n        aria-label='Select all'\n      />\n    ),\n    cell: ({ row }) => (\n      <Checkbox\n        checked={row.getIsSelected()}\n        onCheckedChange={value => row.toggleSelected(!!value)}\n        aria-label='Select row'\n      />\n    ),\n    size: 28,\n    enableSorting: false\n  },\n  {\n    header: 'Product Name',\n    accessorKey: 'product_name',\n    cell: ({ row }) => <div className='font-medium'>{row.getValue('product_name')}</div>\n  },\n  {\n    header: 'Price',\n    accessorKey: 'price',\n    cell: ({ row }) => <div className='font-medium'>{row.getValue('price')}</div>\n  },\n  {\n    header: 'Availability',\n    accessorKey: 'availability',\n    cell: ({ row }) => {\n      const availability = row.getValue('availability') as string\n\n      const styles = {\n        'In Stock':\n          'bg-green-600/10 text-green-600 focus-visible:ring-green-600/20 dark:bg-green-400/10 dark:text-green-400 dark:focus-visible:ring-green-400/40 [a&]:hover:bg-green-600/5 dark:[a&]:hover:bg-green-400/5',\n        'Out of Stock':\n          'bg-destructive/10 [a&]:hover:bg-destructive/5 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 text-destructive',\n        Limited:\n          'bg-amber-600/10 text-amber-600 focus-visible:ring-amber-600/20 dark:bg-amber-400/10 dark:text-amber-400 dark:focus-visible:ring-amber-400/40 [a&]:hover:bg-amber-600/5 dark:[a&]:hover:bg-amber-400/5'\n      }[availability]\n\n      return <Badge className={styles}>{row.getValue('availability')}</Badge>\n    }\n  }\n]\n\nconst DataTableWithPaginationDemo = () => {\n  const pageSize = 5\n\n  const [pagination, setPagination] = useState<PaginationState>({\n    pageIndex: 0,\n    pageSize: pageSize\n  })\n\n  const [sorting, setSorting] = useState<SortingState>([\n    {\n      id: 'product_name',\n      desc: false\n    }\n  ])\n\n  const [data, setData] = useState<Item[]>([])\n\n  useEffect(() => {\n    async function fetchPosts() {\n      const res = await fetch('https://cdn.jsdelivr.net/gh/themeselection/fy-assets/assets/json/mobile-stock.json')\n\n      if (!res.ok) {\n        throw new Error('Failed to fetch data')\n      }\n\n      const items = await res.json()\n\n      const data = await items.data\n\n      setData([...data, ...data])\n    }\n\n    fetchPosts()\n  }, [])\n\n  const table = useReactTable({\n    data,\n    columns,\n    getCoreRowModel: getCoreRowModel(),\n    getSortedRowModel: getSortedRowModel(),\n    onSortingChange: setSorting,\n    enableSortingRemoval: false,\n    getPaginationRowModel: getPaginationRowModel(),\n    onPaginationChange: setPagination,\n    state: {\n      sorting,\n      pagination\n    }\n  })\n\n  const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({\n    currentPage: table.getState().pagination.pageIndex + 1,\n    totalPages: table.getPageCount(),\n    paginationItemsToDisplay: 5\n  })\n\n  return (\n    <div className='w-full space-y-4'>\n      <div className='rounded-md border'>\n        <Table>\n          <TableHeader>\n            {table.getHeaderGroups().map(headerGroup => (\n              <TableRow key={headerGroup.id} className='hover:bg-transparent'>\n                {headerGroup.headers.map(header => {\n                  return (\n                    <TableHead key={header.id} style={{ width: `${header.getSize()}px` }} className='h-11'>\n                      {header.isPlaceholder ? null : header.column.getCanSort() ? (\n                        <div\n                          className={cn(\n                            header.column.getCanSort() &&\n                              'flex h-full cursor-pointer items-center justify-between gap-2 select-none'\n                          )}\n                          onClick={header.column.getToggleSortingHandler()}\n                          onKeyDown={e => {\n                            if (header.column.getCanSort() && (e.key === 'Enter' || e.key === ' ')) {\n                              e.preventDefault()\n                              header.column.getToggleSortingHandler()?.(e)\n                            }\n                          }}\n                          tabIndex={header.column.getCanSort() ? 0 : undefined}\n                        >\n                          {flexRender(header.column.columnDef.header, header.getContext())}\n                          {{\n                            asc: <ChevronUpIcon className='shrink-0 opacity-60' size={16} aria-hidden='true' />,\n                            desc: <ChevronDownIcon className='shrink-0 opacity-60' size={16} aria-hidden='true' />\n                          }[header.column.getIsSorted() as string] ?? null}\n                        </div>\n                      ) : (\n                        flexRender(header.column.columnDef.header, header.getContext())\n                      )}\n                    </TableHead>\n                  )\n                })}\n              </TableRow>\n            ))}\n          </TableHeader>\n          <TableBody>\n            {table.getRowModel().rows?.length ? (\n              table.getRowModel().rows.map(row => (\n                <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>\n                  {row.getVisibleCells().map(cell => (\n                    <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>\n                  ))}\n                </TableRow>\n              ))\n            ) : (\n              <TableRow>\n                <TableCell colSpan={columns.length} className='h-24 text-center'>\n                  No results.\n                </TableCell>\n              </TableRow>\n            )}\n          </TableBody>\n        </Table>\n      </div>\n\n      <div className='flex items-center justify-between gap-3 max-sm:flex-col'>\n        <p className='text-muted-foreground flex-1 text-sm whitespace-nowrap' aria-live='polite'>\n          Page <span className='text-foreground'>{table.getState().pagination.pageIndex + 1}</span> of{' '}\n          <span className='text-foreground'>{table.getPageCount()}</span>\n        </p>\n\n        <div className='grow'>\n          <Pagination>\n            <PaginationContent>\n              <PaginationItem>\n                <Button\n                  size='icon'\n                  variant='outline'\n                  className='disabled:pointer-events-none disabled:opacity-50'\n                  onClick={() => table.previousPage()}\n                  disabled={!table.getCanPreviousPage()}\n                  aria-label='Go to previous page'\n                >\n                  <ChevronLeftIcon aria-hidden='true' />\n                </Button>\n              </PaginationItem>\n\n              {showLeftEllipsis && (\n                <PaginationItem>\n                  <PaginationEllipsis />\n                </PaginationItem>\n              )}\n\n              {pages.map(page => {\n                const isActive = page === table.getState().pagination.pageIndex + 1\n\n                return (\n                  <PaginationItem key={page}>\n                    <Button\n                      size='icon'\n                      variant={`${isActive ? 'outline' : 'ghost'}`}\n                      onClick={() => table.setPageIndex(page - 1)}\n                      aria-current={isActive ? 'page' : undefined}\n                    >\n                      {page}\n                    </Button>\n                  </PaginationItem>\n                )\n              })}\n\n              {showRightEllipsis && (\n                <PaginationItem>\n                  <PaginationEllipsis />\n                </PaginationItem>\n              )}\n\n              <PaginationItem>\n                <Button\n                  size='icon'\n                  variant='outline'\n                  className='disabled:pointer-events-none disabled:opacity-50'\n                  onClick={() => table.nextPage()}\n                  disabled={!table.getCanNextPage()}\n                  aria-label='Go to next page'\n                >\n                  <ChevronRightIcon aria-hidden='true' />\n                </Button>\n              </PaginationItem>\n            </PaginationContent>\n          </Pagination>\n        </div>\n\n        <div className='flex flex-1 justify-end'>\n          <Select\n            value={table.getState().pagination.pageSize.toString()}\n            onValueChange={value => {\n              table.setPageSize(Number(value))\n            }}\n          >\n            <SelectTrigger id='results-per-page' className='w-fit whitespace-nowrap' aria-label='Results per page'>\n              <SelectValue placeholder='Select number of results' />\n            </SelectTrigger>\n            <SelectContent>\n              {[5, 10, 25, 50].map(pageSize => (\n                <SelectItem key={pageSize} value={pageSize.toString()}>\n                  {pageSize} / page\n                </SelectItem>\n              ))}\n            </SelectContent>\n          </Select>\n        </div>\n      </div>\n      <p className='text-muted-foreground mt-4 text-center text-sm'>\n        Data table with pagination{' '}\n        <a href='https://originui.com/table' className='hover:text-primary underline' target='_blank'>\n          Origin UI\n        </a>\n      </p>\n    </div>\n  )\n}\n\nexport default DataTableWithPaginationDemo\n","type":"registry:component","target":"components/shadcn-studio/data-table/data-table-11.tsx"},{"path":"src/registry/new-york/hooks/use-pagination.ts","content":"type UsePaginationProps = {\n  currentPage: number\n  totalPages: number\n  paginationItemsToDisplay: number\n}\n\ntype UsePaginationReturn = {\n  pages: number[]\n  showLeftEllipsis: boolean\n  showRightEllipsis: boolean\n}\n\nexport function usePagination({\n  currentPage,\n  totalPages,\n  paginationItemsToDisplay\n}: UsePaginationProps): UsePaginationReturn {\n  function calculatePaginationRange(): number[] {\n    if (totalPages <= paginationItemsToDisplay) {\n      return Array.from({ length: totalPages }, (_, i) => i + 1)\n    }\n\n    const halfDisplay = Math.floor(paginationItemsToDisplay / 2)\n\n    const initialRange = {\n      start: currentPage - halfDisplay,\n      end: currentPage + halfDisplay\n    }\n\n    const adjustedRange = {\n      start: Math.max(1, initialRange.start),\n      end: Math.min(totalPages, initialRange.end)\n    }\n\n    if (adjustedRange.start === 1) {\n      adjustedRange.end = Math.min(paginationItemsToDisplay, totalPages)\n    }\n\n    if (adjustedRange.end === totalPages) {\n      adjustedRange.start = Math.max(1, totalPages - paginationItemsToDisplay + 1)\n    }\n\n    return Array.from({ length: adjustedRange.end - adjustedRange.start + 1 }, (_, i) => adjustedRange.start + i)\n  }\n\n  const pages = calculatePaginationRange()\n\n  // Determine ellipsis display based on the actual pages shown\n  const showLeftEllipsis = pages.length > 0 && pages[0] > 1 && pages[0] > 2\n\n  const showRightEllipsis =\n    pages.length > 0 && pages[pages.length - 1] < totalPages && pages[pages.length - 1] < totalPages - 1\n\n  return {\n    pages,\n    showLeftEllipsis,\n    showRightEllipsis\n  }\n}\n","type":"registry:hook","target":"hooks/use-pagination.ts"}]}