{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-table-story",
  "title": "Data Table Story",
  "author": "Lloyd Richards <lloyd.d.richards@gmail.com>",
  "description": "Interactive Storybook stories demonstrating sorting, filtering, pagination, and row selection with TanStack Table",
  "dependencies": [
    "@tanstack/react-table@^9.3.1"
  ],
  "registryDependencies": [
    "table",
    "button",
    "checkbox",
    "input",
    "skeleton"
  ],
  "files": [
    {
      "path": "registry/ui/data-table-story/data-table-radix.stories.tsx",
      "content": "import type { Meta, StoryObj } from \"@storybook/nextjs-vite\";\nimport {\n  columnFilteringFeature,\n  createColumnHelper,\n  createFilteredRowModel,\n  createPaginatedRowModel,\n  createSortedRowModel,\n  filterFn_includesString,\n  rowPaginationFeature,\n  rowSelectionFeature,\n  rowSortingFeature,\n  sortFn_text,\n  tableFeatures,\n  useTable,\n} from \"@tanstack/react-table\";\nimport { expect, userEvent, within } from \"storybook/test\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { Input } from \"@/components/ui/input\";\nimport { Skeleton } from \"@/components/ui/skeleton\";\nimport {\n  Table,\n  TableBody,\n  TableCaption,\n  TableCell,\n  TableHead,\n  TableHeader,\n  TableRow,\n} from \"@/components/ui/table\";\n\nconst features = tableFeatures({\n  columnFilteringFeature,\n  rowPaginationFeature,\n  rowSelectionFeature,\n  rowSortingFeature,\n  filteredRowModel: createFilteredRowModel(),\n  paginatedRowModel: createPaginatedRowModel(),\n  sortedRowModel: createSortedRowModel(),\n  filterFns: { includesString: filterFn_includesString },\n  sortFns: { text: sortFn_text },\n});\n\ntype Payment = {\n  id: string;\n  email: string;\n  status: \"Success\" | \"Pending\" | \"Failed\";\n  amount: number;\n};\n\nconst payments: Payment[] = [\n  { id: \"pay-1\", email: \"dana@example.com\", status: \"Success\", amount: 120 },\n  { id: \"pay-2\", email: \"alex@example.com\", status: \"Pending\", amount: 45 },\n  { id: \"pay-3\", email: \"frank@example.com\", status: \"Failed\", amount: 80 },\n  { id: \"pay-4\", email: \"blair@example.com\", status: \"Success\", amount: 210 },\n  { id: \"pay-5\", email: \"erin@example.com\", status: \"Pending\", amount: 65 },\n  { id: \"pay-6\", email: \"casey@example.com\", status: \"Success\", amount: 150 },\n];\n\nconst columnHelper = createColumnHelper<typeof features, Payment>();\nconst columns = columnHelper.columns([\n  columnHelper.display({\n    id: \"selection\",\n    header: ({ table }) => (\n      <Checkbox\n        aria-label=\"Select all payments on this page\"\n        checked={\n          table.getIsSomePageRowsSelected() && !table.getIsAllPageRowsSelected()\n            ? \"indeterminate\"\n            : table.getIsAllPageRowsSelected()\n        }\n        onCheckedChange={(checked) =>\n          table.toggleAllPageRowsSelected(!!checked)\n        }\n      />\n    ),\n    cell: ({ row }) => (\n      <Checkbox\n        aria-label={`Select payment for ${row.original.email}`}\n        checked={row.getIsSelected()}\n        onCheckedChange={(checked) => row.toggleSelected(!!checked)}\n      />\n    ),\n  }),\n  columnHelper.accessor(\"email\", {\n    filterFn: \"includesString\",\n    sortFn: \"text\",\n    header: ({ column }) => (\n      <Button\n        variant=\"ghost\"\n        size=\"sm\"\n        onClick={() => column.toggleSorting(column.getIsSorted() === \"asc\")}\n      >\n        Email\n        <span aria-hidden=\"true\">\n          {column.getIsSorted() === \"asc\"\n            ? \" ↑\"\n            : column.getIsSorted() === \"desc\"\n              ? \" ↓\"\n              : \" ↕\"}\n        </span>\n      </Button>\n    ),\n  }),\n  columnHelper.accessor(\"status\", { header: \"Status\" }),\n  columnHelper.accessor(\"amount\", {\n    header: \"Amount\",\n    cell: ({ row }) => (\n      <span className=\"font-medium tabular-nums\">\n        {new Intl.NumberFormat(\"en-US\", {\n          style: \"currency\",\n          currency: \"USD\",\n        }).format(row.original.amount)}\n      </span>\n    ),\n  }),\n]);\n\nfunction PaymentsTable({\n  data = payments,\n  loading = false,\n}: {\n  data?: Payment[];\n  loading?: boolean;\n}) {\n  const table = useTable({\n    features,\n    columns,\n    data,\n    getRowId: (payment) => payment.id,\n    initialState: { pagination: { pageIndex: 0, pageSize: 3 } },\n  });\n\n  return (\n    <div className=\"w-full space-y-4\">\n      <Input\n        aria-label=\"Filter payments by email\"\n        placeholder=\"Filter emails...\"\n        className=\"max-w-sm\"\n        value={(table.getColumn(\"email\")?.getFilterValue() as string) ?? \"\"}\n        onChange={(event) => {\n          table.getColumn(\"email\")?.setFilterValue(event.target.value);\n          table.setPageIndex(0);\n        }}\n        disabled={loading}\n      />\n      <div className=\"overflow-hidden rounded-md border\">\n        <Table className=\"min-w-[560px]\" aria-busy={loading}>\n          <TableCaption className=\"sr-only\">Recent payments</TableCaption>\n          <TableHeader>\n            {table.getHeaderGroups().map((group) => (\n              <TableRow key={group.id}>\n                {group.headers.map((header) => (\n                  <TableHead\n                    key={header.id}\n                    aria-sort={\n                      header.column.id === \"email\"\n                        ? header.column.getIsSorted() === \"asc\"\n                          ? \"ascending\"\n                          : header.column.getIsSorted() === \"desc\"\n                            ? \"descending\"\n                            : \"none\"\n                        : undefined\n                    }\n                  >\n                    {header.isPlaceholder ? null : (\n                      <table.FlexRender header={header} />\n                    )}\n                  </TableHead>\n                ))}\n              </TableRow>\n            ))}\n          </TableHeader>\n          <TableBody>\n            {loading ? (\n              <TableRow>\n                <TableCell colSpan={columns.length}>\n                  <span role=\"status\" className=\"sr-only\">\n                    Loading payments\n                  </span>\n                  <div className=\"space-y-3 py-2\" aria-hidden=\"true\">\n                    <Skeleton className=\"h-6 w-full\" />\n                    <Skeleton className=\"h-6 w-full\" />\n                    <Skeleton className=\"h-6 w-full\" />\n                  </div>\n                </TableCell>\n              </TableRow>\n            ) : table.getRowModel().rows.length ? (\n              table.getRowModel().rows.map((row) => (\n                <TableRow\n                  key={row.id}\n                  data-state={row.getIsSelected() ? \"selected\" : undefined}\n                >\n                  {row.getAllCells().map((cell) => (\n                    <TableCell key={cell.id}>\n                      <table.FlexRender cell={cell} />\n                    </TableCell>\n                  ))}\n                </TableRow>\n              ))\n            ) : (\n              <TableRow>\n                <TableCell\n                  colSpan={columns.length}\n                  className=\"h-24 text-center\"\n                >\n                  No payments found.\n                </TableCell>\n              </TableRow>\n            )}\n          </TableBody>\n        </Table>\n      </div>\n      <div className=\"flex flex-wrap items-center justify-between gap-3 text-sm\">\n        <p aria-live=\"polite\">\n          {table.getFilteredSelectedRowModel().rows.length} of{\" \"}\n          {table.getFilteredRowModel().rows.length} payments selected\n        </p>\n        <div className=\"flex items-center gap-2\">\n          <span>\n            Page {table.state.pagination.pageIndex + 1} of{\" \"}\n            {Math.max(1, table.getPageCount())}\n          </span>\n          <Button\n            variant=\"outline\"\n            size=\"sm\"\n            disabled={loading || !table.getCanPreviousPage()}\n            onClick={() => table.previousPage()}\n          >\n            Previous\n          </Button>\n          <Button\n            variant=\"outline\"\n            size=\"sm\"\n            disabled={loading || !table.getCanNextPage()}\n            onClick={() => table.nextPage()}\n          >\n            Next\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n/** Compose the Table primitive with TanStack Table v9 to sort, filter, paginate, and select local payments. */\nconst meta = {\n  id: \"ui-radix-datatable\",\n  title: \"ui/DataTable\",\n  component: PaymentsTable,\n  tags: [\"autodocs\"],\n  parameters: { layout: \"padded\" },\n  args: { data: payments, loading: false },\n  decorators: [\n    (Story) => (\n      <div className=\"mx-auto w-full max-w-3xl\">\n        <Story />\n      </div>\n    ),\n  ],\n} satisfies Meta<typeof PaymentsTable>;\n\nexport default meta;\ntype Story = StoryObj<typeof meta>;\n\n/** Browse six deterministic payments with three rows per page. */\nexport const Default: Story = {};\n\n/** Show a clear message when the data source contains no payments. */\nexport const Empty: Story = { args: { data: [] } };\n\n/** Keep the table structure visible while payments are loading. */\nexport const Loading: Story = { args: { data: [], loading: true } };\n\n/** Keep all columns available through horizontal scrolling on narrow screens. */\nexport const NarrowScreen: Story = {\n  decorators: [\n    (Story) => (\n      <div className=\"w-[320px] max-w-full\">\n        <Story />\n      </div>\n    ),\n  ],\n};\n\n/** Sorting changes the visible row order in both directions. */\nexport const ShouldSortPayments: Story = {\n  tags: [\"!dev\", \"!autodocs\"],\n  play: async ({ canvas }) => {\n    const table = canvas.getByRole(\"table\", { name: \"Recent payments\" });\n    const firstRow = () => within(table).getAllByRole(\"row\")[1];\n    await expect(firstRow()).toHaveTextContent(\"dana@example.com\");\n    await userEvent.click(canvas.getByRole(\"button\", { name: \"Email\" }));\n    await expect(firstRow()).toHaveTextContent(\"alex@example.com\");\n    await expect(\n      canvas.getByRole(\"columnheader\", { name: \"Email\" }),\n    ).toHaveAttribute(\"aria-sort\", \"ascending\");\n    await userEvent.click(canvas.getByRole(\"button\", { name: \"Email\" }));\n    await expect(firstRow()).toHaveTextContent(\"frank@example.com\");\n    await expect(\n      canvas.getByRole(\"columnheader\", { name: \"Email\" }),\n    ).toHaveAttribute(\"aria-sort\", \"descending\");\n  },\n};\n\n/** Filtering searches the full dataset, handles no matches, and restores rows when cleared. */\nexport const ShouldFilterPayments: Story = {\n  tags: [\"!dev\", \"!autodocs\"],\n  play: async ({ canvas }) => {\n    const filter = canvas.getByRole(\"textbox\", {\n      name: \"Filter payments by email\",\n    });\n    await userEvent.type(filter, \"casey\");\n    await expect(\n      canvas.getByRole(\"cell\", { name: \"casey@example.com\" }),\n    ).toBeVisible();\n    await expect(\n      canvas.queryByRole(\"cell\", { name: \"dana@example.com\" }),\n    ).not.toBeInTheDocument();\n    await expect(canvas.getByRole(\"button\", { name: \"Next\" })).toBeDisabled();\n    await userEvent.clear(filter);\n    await userEvent.type(filter, \"missing@example.com\");\n    await expect(canvas.getByText(\"No payments found.\")).toBeVisible();\n    await userEvent.clear(filter);\n    await expect(\n      canvas.getByRole(\"cell\", { name: \"dana@example.com\" }),\n    ).toBeVisible();\n    await expect(canvas.getByRole(\"button\", { name: \"Next\" })).toBeEnabled();\n  },\n};\n\n/** Pagination replaces the visible rows and disables navigation at either boundary. */\nexport const ShouldPaginatePayments: Story = {\n  tags: [\"!dev\", \"!autodocs\"],\n  play: async ({ canvas }) => {\n    await expect(\n      canvas.getByRole(\"button\", { name: \"Previous\" }),\n    ).toBeDisabled();\n    await userEvent.click(canvas.getByRole(\"button\", { name: \"Next\" }));\n    await expect(\n      canvas.getByRole(\"cell\", { name: \"blair@example.com\" }),\n    ).toBeVisible();\n    await expect(\n      canvas.queryByRole(\"cell\", { name: \"dana@example.com\" }),\n    ).not.toBeInTheDocument();\n    await expect(canvas.getByText(\"Page 2 of 2\")).toBeVisible();\n    await expect(canvas.getByRole(\"button\", { name: \"Next\" })).toBeDisabled();\n    await userEvent.click(canvas.getByRole(\"button\", { name: \"Previous\" }));\n    await expect(\n      canvas.getByRole(\"cell\", { name: \"dana@example.com\" }),\n    ).toBeVisible();\n    await expect(canvas.getByText(\"Page 1 of 2\")).toBeVisible();\n  },\n};\n\n/** Select a row or the current page while preserving selections across pagination. */\nexport const ShouldSelectPayments: Story = {\n  tags: [\"!dev\", \"!autodocs\"],\n  play: async ({ canvas }) => {\n    const row = canvas.getByRole(\"checkbox\", {\n      name: \"Select payment for dana@example.com\",\n    });\n    const all = canvas.getByRole(\"checkbox\", {\n      name: \"Select all payments on this page\",\n    });\n    await userEvent.click(row);\n    await expect(row).toBeChecked();\n    await expect(canvas.getByText(\"1 of 6 payments selected\")).toBeVisible();\n    await expect(all).toBePartiallyChecked();\n    await userEvent.click(all);\n    await expect(canvas.getByText(\"3 of 6 payments selected\")).toBeVisible();\n    await userEvent.click(canvas.getByRole(\"button\", { name: \"Next\" }));\n    await expect(\n      canvas.getByRole(\"checkbox\", {\n        name: \"Select payment for blair@example.com\",\n      }),\n    ).not.toBeChecked();\n    await expect(canvas.getByText(\"3 of 6 payments selected\")).toBeVisible();\n    await userEvent.click(canvas.getByRole(\"button\", { name: \"Previous\" }));\n    await expect(\n      canvas.getByRole(\"checkbox\", {\n        name: \"Select payment for dana@example.com\",\n      }),\n    ).toBeChecked();\n    await userEvent.click(\n      canvas.getByRole(\"checkbox\", {\n        name: \"Select all payments on this page\",\n      }),\n    );\n    await expect(canvas.getByText(\"0 of 6 payments selected\")).toBeVisible();\n  },\n};\n",
      "type": "registry:component",
      "target": "@ui/data-table.stories.tsx"
    }
  ],
  "categories": [
    "ui",
    "storybook",
    "data-table",
    "data-display"
  ],
  "type": "registry:component"
}