{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-table-example-infinite",
  "title": "Example: infinite table",
  "description": "A complete /example route to see the table running before wiring your own data: a table schema, a mock API that filters, computes facets and cursor-paginates in memory with the same semantics as the Drizzle handler, and the infinite table with a timeline chart, URL state, command palette, row sheet and a hand-written timing phases column. Delete app/example when you have your own.",
  "registryDependencies": [
    "https://data-table.openstatus.dev/r/data-table.json",
    "https://data-table.openstatus.dev/r/data-table-schema.json",
    "https://data-table.openstatus.dev/r/data-table-query.json",
    "https://data-table.openstatus.dev/r/data-table-nuqs.json",
    "https://data-table.openstatus.dev/r/data-table-sheet.json",
    "https://data-table.openstatus.dev/r/data-table-cell.json",
    "https://data-table.openstatus.dev/r/data-table-filter-command.json",
    "https://data-table.openstatus.dev/r/data-table-chart.json",
    "hover-card",
    "dropdown-menu",
    "button"
  ],
  "files": [
    {
      "path": "src/examples/infinite/layout.tsx",
      "content": "\"use client\";\n\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport { NuqsAdapter } from \"nuqs/adapters/next/app\";\nimport * as React from \"react\";\n\n/**\n * The two providers the table needs, scoped to this route so nothing in the\n * root layout has to change. Move them up to `app/layout.tsx` once more than\n * one route uses them.\n */\nexport default function Layout({ children }: { children: React.ReactNode }) {\n  const [queryClient] = React.useState(() => new QueryClient());\n\n  return (\n    <QueryClientProvider client={queryClient}>\n      <NuqsAdapter>{children}</NuqsAdapter>\n    </QueryClientProvider>\n  );\n}\n",
      "type": "registry:page",
      "target": "app/example/layout.tsx"
    },
    {
      "path": "src/examples/infinite/page.tsx",
      "content": "import type { SearchParams as RawSearchParams } from \"nuqs\";\nimport { Client } from \"./client\";\nimport { searchParamsCache } from \"./schema\";\n\n/**\n * Parses the URL on the server so the first render already has the filters,\n * the sort and the cursor — no flash of an unfiltered table.\n */\nexport default async function Page({\n  searchParams,\n}: {\n  searchParams: Promise<RawSearchParams>;\n}) {\n  const search = await searchParamsCache.parse(searchParams);\n  return <Client initialState={search} />;\n}\n",
      "type": "registry:page",
      "target": "app/example/page.tsx"
    },
    {
      "path": "src/examples/infinite/client.tsx",
      "content": "\"use client\";\n\nimport {\n  TimelineChart,\n  type TimelineChartSeries,\n} from \"@/components/data-table/data-table-chart/timeline-chart\";\nimport { DataTableFilterCommand } from \"@/components/data-table/data-table-filter-command\";\nimport { DataTableInfinite } from \"@/components/data-table/data-table-infinite\";\nimport { useDataTable } from \"@/components/data-table/data-table-provider\";\nimport { DataTableRefreshButton } from \"@/components/data-table/data-table-refresh-button\";\nimport { MemoizedDataTableSheetContent } from \"@/components/data-table/data-table-sheet/data-table-sheet-content\";\nimport { DataTableSheetDetails } from \"@/components/data-table/data-table-sheet/data-table-sheet-details\";\nimport type { SheetField } from \"@/components/data-table/types\";\nimport {\n  applyFacets,\n  getFacetedMinMaxValues,\n  getFacetedUniqueValues,\n  getMetaPage,\n  refreshDataTableQuery,\n} from \"@/lib/data-table\";\nimport { isActive } from \"@/lib/filters\";\nimport { useNuqsAdapter } from \"@/lib/store/adapters/nuqs\";\nimport { useFilterState } from \"@/lib/store/hooks/useFilterState\";\nimport { DataTableStoreProvider } from \"@/lib/store/provider/DataTableStoreProvider\";\nimport {\n  generateColumns,\n  generateFilterFields,\n  generateSheetFields,\n  getDefaultColumnVisibility,\n} from \"@/lib/table-schema\";\nimport { useInfiniteQuery, useQueryClient } from \"@tanstack/react-query\";\nimport * as React from \"react\";\nimport { Footer } from \"./footer\";\nimport { dataOptions } from \"./query-options\";\nimport { filterSchema, type FilterState, type SearchParams } from \"./schema\";\nimport {\n  getLevelRowClassName,\n  tableSchema,\n  type ColumnSchema,\n} from \"./table-schema\";\nimport { timingPhasesColumn } from \"./timing-phases\";\n\n// Everything the table renders is generated from the schema, once. The one\n// exception is the timing bar, which spans five columns and is appended by hand.\nconst columns = [\n  ...generateColumns<ColumnSchema>(tableSchema.definition),\n  timingPhasesColumn<ColumnSchema>(),\n];\nconst filterFields = generateFilterFields<ColumnSchema>(tableSchema.definition);\nconst sheetFields = generateSheetFields<ColumnSchema>(tableSchema.definition);\nconst defaultColumnVisibility = getDefaultColumnVisibility(\n  tableSchema.definition,\n);\n\n/** The chart's stacked series, bottom-up. Colours come from the core block's CSS variables. */\nconst CHART_SERIES: TimelineChartSeries[] = [\n  { key: \"error\", label: \"Error\" },\n  { key: \"warning\", label: \"Warning\" },\n  { key: \"info\", label: \"Info\" },\n];\n\n// Module-level so its identity is stable: the memoized rows compare it.\nconst getRowClassName = (row: { original: ColumnSchema }) =>\n  getLevelRowClassName(row.original.level);\n\n/** URL state that is not a column filter. */\nconst STATE_KEYS = new Set([\"sort\", \"uuid\", \"size\", \"direction\", \"cursor\"]);\n\nexport function Client({ initialState }: { initialState: SearchParams }) {\n  const adapter = useNuqsAdapter(filterSchema.definition, {\n    id: \"example\",\n    initialState,\n  });\n\n  return (\n    <DataTableStoreProvider adapter={adapter}>\n      <Table />\n    </DataTableStoreProvider>\n  );\n}\n\nfunction Table() {\n  const search = useFilterState<FilterState>();\n  const queryClient = useQueryClient();\n  const { data, isFetching, isLoading, fetchNextPage, hasNextPage } =\n    useInfiniteQuery(dataOptions(search));\n\n  // Not the bare `refetch`: that would restart from the first cached page\n  // param. The helper resets the cache to a fresh first page (now, with meta).\n  const refresh = React.useCallback(\n    () => refreshDataTableQuery(queryClient, dataOptions(search)),\n    [queryClient, search],\n  );\n\n  const flatData = React.useMemo(\n    () => data?.pages?.flatMap((page) => page.data ?? []) ?? [],\n    [data?.pages],\n  );\n\n  // Facets and counts come from the page that carries meta — the first one,\n  // since pagination requests skip it.\n  const meta = getMetaPage(data)?.meta;\n  const facets = meta?.facets;\n\n  const defaultColumnFilters = Object.entries(search)\n    .filter(([key, value]) => !STATE_KEYS.has(key) && isActive(value))\n    .map(([id, value]) => ({ id, value }));\n\n  const dynamicFilterFields = React.useMemo(\n    () => applyFacets(filterFields, facets),\n    [facets],\n  );\n\n  return (\n    <DataTableInfinite\n      columns={columns}\n      data={flatData}\n      totalRows={meta?.totalRowCount}\n      filterRows={meta?.filterRowCount}\n      totalRowsFetched={flatData.length}\n      defaultColumnFilters={defaultColumnFilters}\n      defaultColumnSorting={search.sort ? [search.sort] : undefined}\n      defaultRowSelection={search.uuid ? { [search.uuid]: true } : undefined}\n      defaultColumnVisibility={defaultColumnVisibility}\n      filterFields={dynamicFilterFields}\n      isFetching={isFetching}\n      isLoading={isLoading}\n      fetchNextPage={fetchNextPage}\n      hasNextPage={hasNextPage}\n      getRowId={(row) => row.uuid}\n      getRowClassName={getRowClassName}\n      getFacetedUniqueValues={getFacetedUniqueValues(facets)}\n      getFacetedMinMaxValues={getFacetedMinMaxValues(facets)}\n      chartSlot={\n        <TimelineChart\n          data={meta?.chartData ?? []}\n          columnId=\"date\"\n          series={CHART_SERIES}\n          className=\"-mb-2\"\n        />\n      }\n      toolbarActions={<DataTableRefreshButton onClick={refresh} />}\n      footerSlot={<Footer />}\n      commandSlot={\n        <DataTableFilterCommand\n          schema={filterSchema.definition}\n          tableId=\"example\"\n        />\n      }\n      sheetSlot={\n        <SheetSlot\n          sheetFields={sheetFields}\n          totalRows={meta?.totalRowCount ?? 0}\n          filterRows={meta?.filterRowCount ?? 0}\n          totalRowsFetched={flatData.length}\n        />\n      }\n      tableId=\"example\"\n    />\n  );\n}\n\nfunction SheetSlot({\n  sheetFields: fields,\n  totalRows,\n  filterRows,\n  totalRowsFetched,\n}: {\n  sheetFields: SheetField<ColumnSchema>[];\n  totalRows: number;\n  filterRows: number;\n  totalRowsFetched: number;\n}) {\n  const { table, rowSelection, isLoading, filterFields } = useDataTable<\n    ColumnSchema,\n    unknown\n  >();\n  const selectedRowKey = Object.keys(rowSelection)?.[0];\n  const selectedRow = React.useMemo(() => {\n    if (isLoading && !selectedRowKey) return undefined;\n    return table\n      .getCoreRowModel()\n      .flatRows.find((row) => row.id === selectedRowKey);\n  }, [selectedRowKey, isLoading, table]);\n\n  return (\n    <DataTableSheetDetails\n      title={\n        selectedRow\n          ? `${selectedRow.original.method} ${selectedRow.original.pathname}`\n          : undefined\n      }\n      titleClassName=\"font-mono\"\n    >\n      <MemoizedDataTableSheetContent\n        table={table}\n        data={selectedRow?.original}\n        filterFields={filterFields}\n        fields={fields}\n        metadata={{ totalRows, filterRows, totalRowsFetched }}\n      />\n    </DataTableSheetDetails>\n  );\n}\n",
      "type": "registry:file",
      "target": "app/example/client.tsx"
    },
    {
      "path": "src/examples/infinite/schema.ts",
      "content": "import {\n  createNuqsSearchParams,\n  type inferParserType,\n} from \"@/lib/store/adapters/nuqs/server\";\nimport { field } from \"@/lib/store/schema\";\nimport { generateFilterSchema } from \"@/lib/table-schema\";\nimport { tableSchema } from \"./table-schema\";\n\nconst DIRECTIONS = [\"prev\", \"next\"] as const;\n\n/**\n * Everything that lives in the URL: one filter field per filterable column,\n * generated from the table schema, plus the state that is not a filter —\n * the sort, the selected row, and the cursor pagination.\n */\nexport const filterSchema = generateFilterSchema(tableSchema.definition, {\n  sort: field.sort(),\n  uuid: field.string(),\n  size: field.number().default(40),\n  direction: field.stringLiteral(DIRECTIONS).default(\"next\"),\n  cursor: field.timestamp(),\n});\n\nexport type FilterState = typeof filterSchema._type;\n\nexport const { searchParamsCache, searchParamsSerializer, searchParamsParser } =\n  createNuqsSearchParams(filterSchema.definition);\n\nexport type SearchParams = inferParserType<typeof searchParamsParser>;\n",
      "type": "registry:file",
      "target": "app/example/schema.ts"
    },
    {
      "path": "src/examples/infinite/table-schema.ts",
      "content": "import {\n  col,\n  createTableSchema,\n  type InferTableType,\n} from \"@/lib/table-schema\";\nimport { SheetTimingPhases } from \"./timing-phases\";\n\nexport const LEVELS = [\"error\", \"warning\", \"info\"] as const;\nexport const METHODS = [\"GET\", \"POST\", \"PUT\", \"DELETE\"] as const;\nexport const REGIONS = [\"ams\", \"fra\", \"iad\", \"syd\"] as const;\nexport const STATUS_CODES = [200, 201, 400, 404, 500];\n\n/**\n * A faint tint of the level's colour on the rows worth noticing, stepping up\n * on hover, focus, and for the row that is open in the sheet or checked — the\n * table marks that row `data-[state=selected]` without a select column, and\n * `data-detail` / `data-checked` with one. `info` is nearly every row, so it\n * stays plain.\n */\nexport function getLevelRowClassName(level: string): string {\n  switch (level) {\n    case \"warning\":\n      return [\n        \"bg-warning/5 hover:bg-warning/10 focus-visible:bg-warning/10 data-[state=selected]:bg-warning/20 data-detail:bg-warning/20 data-checked:bg-warning/20\",\n        \"dark:bg-warning/10 dark:hover:bg-warning/20 dark:focus-visible:bg-warning/20 dark:data-[state=selected]:bg-warning/30 dark:data-detail:bg-warning/30 dark:data-checked:bg-warning/30\",\n      ].join(\" \");\n    case \"error\":\n      return [\n        \"bg-error/5 hover:bg-error/10 focus-visible:bg-error/10 data-[state=selected]:bg-error/20 data-detail:bg-error/20 data-checked:bg-error/20\",\n        \"dark:bg-error/10 dark:hover:bg-error/20 dark:focus-visible:bg-error/20 dark:data-[state=selected]:bg-error/30 dark:data-detail:bg-error/30 dark:data-checked:bg-error/30\",\n      ].join(\" \");\n    default:\n      return \"\";\n  }\n}\n\n/**\n * The one definition the whole example reads from. The columns, the filter\n * sidebar, the command palette, the row sheet and the mock API's filter\n * semantics are all generated from it, so a column added here shows up on\n * every surface.\n */\nexport const tableSchema = createTableSchema({\n  level: col.presets\n    .logLevel(LEVELS)\n    .display(\"level-indicator\")\n    .hideHeader()\n    .size(37)\n    .sheet(),\n  date: col.presets\n    .timestamp()\n    .label(\"Date\")\n    // The mock API returns rows newest-first and does not sort; the header\n    // must not promise what the endpoint cannot deliver.\n    .sortable(false)\n    .defaultOpen()\n    .commandDisabled()\n    // The one unsized column: it absorbs the table's leftover width.\n    .minSize(200)\n    .sheet(),\n  status: col.presets.httpStatus(STATUS_CODES).size(70).sheet(),\n  method: col.presets.httpMethod(METHODS).size(80).sheet(),\n  pathname: col.presets.pathname().size(220).sheet(),\n  region: col\n    .enum(REGIONS)\n    .label(\"Region\")\n    .display(\"badge\")\n    .filterable(\"checkbox\", {\n      options: REGIONS.map((region) => ({ label: region, value: region })),\n    })\n    .size(90)\n    .sheet(),\n  latency: col.presets\n    .latency(\"ms\")\n    .label(\"Latency\")\n    .sortable(false)\n    .size(110)\n    .sheet(),\n\n  // The five phases behind `timingPhasesColumn`: hidden from the table by\n  // default (toggle them in the column settings), each filterable by range,\n  // and shown together as one sheet section hung off the first.\n  \"timing.dns\": col.presets\n    .duration(\"ms\")\n    .label(\"DNS\")\n    .size(110)\n    .hidden()\n    .sheet({\n      label: \"Timing Phases\",\n      component: SheetTimingPhases,\n      className: \"flex-col items-start w-full gap-1\",\n    }),\n  \"timing.connection\": col.presets\n    .duration(\"ms\")\n    .label(\"Connection\")\n    .size(110)\n    .hidden(),\n  \"timing.tls\": col.presets.duration(\"ms\").label(\"TLS\").size(110).hidden(),\n  \"timing.ttfb\": col.presets.duration(\"ms\").label(\"TTFB\").size(110).hidden(),\n  \"timing.transfer\": col.presets\n    .duration(\"ms\")\n    .label(\"Transfer\")\n    .size(110)\n    .hidden(),\n  uuid: col.presets.traceId().label(\"Request ID\").hidden().sheet(),\n});\n\nexport type ColumnSchema = InferTableType<typeof tableSchema.definition>;\n",
      "type": "registry:file",
      "target": "app/example/table-schema.ts"
    },
    {
      "path": "src/examples/infinite/timing.ts",
      "content": "/**\n * The request's timing phases, in the order they happen. Each is a flat,\n * dotted column on the row (`\"timing.dns\"`), the shape the table schema,\n * the filters and the mock API all read.\n */\nexport const TIMING_PHASES = [\n  \"timing.dns\",\n  \"timing.connection\",\n  \"timing.tls\",\n  \"timing.ttfb\",\n  \"timing.transfer\",\n] as const;\n\nexport type TimingPhase = (typeof TIMING_PHASES)[number];\n\nexport type Timing = Record<TimingPhase, number>;\n\n/**\n * What `timingPhasesColumn` and `SheetTimingPhases` read off a row: the\n * total, and whichever phases the row carries. Any row type with these keys\n * fits, which is how the docs site's own demos share the components.\n */\nexport type TimingRow = { latency: number } & Partial<\n  Record<TimingPhase, number>\n>;\n\nconst PHASES: Record<TimingPhase, { label: string; color: string }> = {\n  \"timing.dns\": { label: \"DNS\", color: \"bg-emerald-500\" },\n  \"timing.connection\": { label: \"Connection\", color: \"bg-cyan-500\" },\n  \"timing.tls\": { label: \"TLS\", color: \"bg-blue-500\" },\n  \"timing.ttfb\": { label: \"TTFB\", color: \"bg-violet-500\" },\n  \"timing.transfer\": { label: \"Transfer\", color: \"bg-purple-500\" },\n};\n\nexport function getTimingLabel(phase: TimingPhase): string {\n  return PHASES[phase].label;\n}\n\nexport function getTimingColor(phase: TimingPhase): string {\n  return PHASES[phase].color;\n}\n\n/**\n * One phase's share of the latency, as a percentage for a bar's `width`.\n * A row with no latency has no shares, not `NaN` ones.\n */\nexport function getTimingShare(\n  timing: Timing,\n  phase: TimingPhase,\n  latency: number,\n): number {\n  return latency > 0 ? (timing[phase] / latency) * 100 : 0;\n}\n\n/** Each phase's share of the latency, formatted for display (`\"12.5%\"`, `\"<1%\"`). */\nexport function getTimingPercentage(\n  timing: Timing,\n  latency: number,\n): Record<TimingPhase, string> {\n  const out = {} as Record<TimingPhase, string>;\n  for (const phase of TIMING_PHASES) {\n    const share = getTimingShare(timing, phase, latency);\n    out[phase] = share > 0 && share < 1 ? \"<1%\" : `${share.toFixed(1)}%`;\n  }\n  return out;\n}\n\n/** The phases of a row, read off its flat dotted keys. */\nexport function pickTiming(row: Partial<Record<TimingPhase, number>>): Timing {\n  const out = {} as Timing;\n  for (const phase of TIMING_PHASES) out[phase] = row[phase] ?? 0;\n  return out;\n}\n",
      "type": "registry:file",
      "target": "app/example/timing.ts"
    },
    {
      "path": "src/examples/infinite/timing-phases.tsx",
      "content": "\"use client\";\n\nimport { HOVER_CARD_DELAY } from \"@/components/data-table/ui-compat\";\nimport {\n  HoverCard,\n  HoverCardContent,\n  HoverCardTrigger,\n} from \"@/components/ui/hover-card\";\nimport { formatMilliseconds } from \"@/lib/format\";\nimport type { DataTableFeatures } from \"@/lib/table/features\";\nimport { cn } from \"@/lib/utils\";\nimport type { ColumnDef } from \"@tanstack/react-table\";\nimport {\n  getTimingColor,\n  getTimingLabel,\n  getTimingPercentage,\n  getTimingShare,\n  pickTiming,\n  TIMING_PHASES,\n  type Timing,\n  type TimingRow,\n} from \"./timing\";\n\n/** One stacked bar, each phase as wide as its share of the latency. */\nfunction TimingBar({\n  timing,\n  latency,\n  className,\n}: {\n  timing: Timing;\n  latency: number;\n  className?: string;\n}) {\n  return (\n    <div className={cn(\"flex\", className)}>\n      {TIMING_PHASES.map((phase) => (\n        <div\n          key={phase}\n          className={cn(getTimingColor(phase), \"h-4\")}\n          style={{ width: `${getTimingShare(timing, phase, latency)}%` }}\n        />\n      ))}\n    </div>\n  );\n}\n\n/**\n * A column that spans five schema columns, so it cannot be generated from\n * one of them: append `timingPhasesColumn<ColumnSchema>()` to\n * `generateColumns(...)` by hand. The bar reads the phases off `row.original`,\n * whose flat dotted keys are the schema's.\n *\n * A factory rather than one def so the column takes the table's own row type:\n * any row carrying `latency` and the phases fits, which is how the docs site's\n * demos share it.\n */\nexport function timingPhasesColumn<TData extends TimingRow>(): ColumnDef<\n  DataTableFeatures,\n  TData\n> {\n  return {\n    id: \"timing\",\n    header: () => <div className=\"whitespace-nowrap\">Timing Phases</div>,\n    cell: ({ row }) => {\n      const timing = pickTiming(row.original);\n      const latency = row.original.latency;\n      const percentage = getTimingPercentage(timing, latency);\n      return (\n        // The props are spread, and the trigger has no `asChild`, on purpose:\n        // this file ships as `registry:file`, which the shadcn CLI copies\n        // verbatim — its Base UI codemod (`asChild` → `render`) never runs on\n        // it, and a literal `openDelay` fails to typecheck on Base UI's\n        // preview card. So the trigger renders its own element, with the\n        // open-state class in both libraries' spelling.\n        <HoverCard {...HOVER_CARD_DELAY}>\n          <HoverCardTrigger className=\"block opacity-70 hover:opacity-100 data-open:opacity-100 data-[state=open]:opacity-100\">\n            <TimingBar timing={timing} latency={latency} />\n          </HoverCardTrigger>\n          <HoverCardContent\n            side=\"bottom\"\n            align=\"end\"\n            className=\"z-10 w-auto p-2\"\n          >\n            <div className=\"flex flex-col gap-1\">\n              {TIMING_PHASES.map((phase) => (\n                <div key={phase} className=\"grid grid-cols-2 gap-4 text-xs\">\n                  <div className=\"flex items-center gap-2\">\n                    <div\n                      className={cn(\n                        getTimingColor(phase),\n                        \"h-2 w-2 rounded-full\",\n                      )}\n                    />\n                    <div className=\"text-accent-foreground font-mono uppercase\">\n                      {getTimingLabel(phase)}\n                    </div>\n                  </div>\n                  <div className=\"flex items-center justify-between gap-4\">\n                    <div className=\"text-muted-foreground font-mono\">\n                      {percentage[phase]}\n                    </div>\n                    <div className=\"font-mono\">\n                      {formatMilliseconds(timing[phase])}\n                      <span className=\"text-muted-foreground\">ms</span>\n                    </div>\n                  </div>\n                </div>\n              ))}\n            </div>\n          </HoverCardContent>\n        </HoverCard>\n      );\n    },\n    enableResizing: false,\n    size: 130,\n    minSize: 130,\n    // Pins the width: the bars have no intrinsic size, so without a fixed width\n    // the column would collapse once another column claims the leftover width.\n    maxSize: 130,\n    meta: { label: \"Timing Phases\" },\n  };\n}\n\n/**\n * The row sheet's \"Timing Phases\" section. The sheet renders a field's\n * `component` with the whole row as props, hence the loose parameter type:\n * `SheetConfig.component` is typed `(row: unknown) => …`.\n */\nexport function SheetTimingPhases(props: unknown) {\n  const row = props as TimingRow;\n  const timing = pickTiming(row);\n  const percentage = getTimingPercentage(timing, row.latency);\n  return (\n    <div className=\"w-full space-y-1 text-left\">\n      {TIMING_PHASES.map((phase) => (\n        <div\n          key={phase}\n          className=\"grid grid-cols-3 items-center justify-between gap-2 text-xs\"\n        >\n          <div className=\"text-foreground truncate font-mono uppercase\">\n            {getTimingLabel(phase)}\n          </div>\n          <div className=\"col-span-2 flex gap-2\">\n            <div className=\"text-muted-foreground mr-8 font-mono\">\n              {percentage[phase]}\n            </div>\n            <div className=\"flex flex-1 items-center justify-end gap-2\">\n              <div className=\"font-mono\">\n                {formatMilliseconds(timing[phase])}\n                <span className=\"text-muted-foreground\">ms</span>\n              </div>\n            </div>\n            <div\n              className={cn(getTimingColor(phase), \"h-4\")}\n              style={{\n                width: `${getTimingShare(timing, phase, row.latency)}%`,\n              }}\n            />\n          </div>\n        </div>\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:file",
      "target": "app/example/timing-phases.tsx"
    },
    {
      "path": "src/examples/infinite/footer.tsx",
      "content": "\"use client\";\n\nimport { buttonVariants } from \"@/components/ui/button\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuGroup,\n  DropdownMenuItem,\n  DropdownMenuLabel,\n  DropdownMenuSeparator,\n  DropdownMenuShortcut,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport { Github, Keyboard } from \"lucide-react\";\n\n/**\n * The chords `useHotKey` registers for the example. The hook only fires with\n * `⌘`/`Ctrl` held — that includes `Escape` — so every one of these is a chord\n * and can be replayed from the menu.\n */\nexport const SHORTCUTS = [\n  { key: \"k\", label: \"Toggle command input\" },\n  { key: \"b\", label: \"Toggle filter controls\" },\n  { key: \"u\", label: \"Reset column order and visibility\" },\n  { key: \"Escape\", label: \"Reset table filters\" },\n] as const;\n\nexport type Shortcut = (typeof SHORTCUTS)[number];\n\n/** Plain keys the table and the row sheet respond to. Listed, not replayed. */\nexport const NAVIGATION = [\n  { keys: \"↑ ↓\", label: \"Previous / next row (sheet open)\" },\n  { keys: \"Enter\", label: \"Open the focused row\" },\n  { keys: \"Esc\", label: \"Close the row sheet\" },\n] as const;\n\n/**\n * Replays a chord as the keydown `useHotKey` listens for, so picking it from\n * the menu does the same thing as pressing it.\n */\nexport function triggerShortcut(key: Shortcut[\"key\"]) {\n  document.dispatchEvent(\n    new KeyboardEvent(\"keydown\", { key, metaKey: true, bubbles: true }),\n  );\n}\n\nexport function formatShortcut(key: Shortcut[\"key\"]) {\n  return `⌘${key === \"Escape\" ? \"Esc\" : key.toUpperCase()}`;\n}\n\n/**\n * The sidebar footer: a GitHub link and the shortcuts list, with a\n * \"Powered by openstatus\" line. Delete it along with the rest of\n * `app/example` — or keep whatever is useful in your own footer slot.\n */\nexport function Footer() {\n  return (\n    <div className=\"flex flex-wrap items-center justify-between gap-2\">\n      <p className=\"text-muted-foreground text-xs\">\n        Powered by{\" \"}\n        <a\n          href=\"https://openstatus.dev\"\n          target=\"_blank\"\n          rel=\"noreferrer\"\n          className=\"text-foreground decoration-border hover:decoration-foreground underline underline-offset-4\"\n        >\n          openstatus\n        </a>\n      </p>\n      <div className=\"flex items-center gap-1\">\n        {/* No `asChild` here, on purpose: this file ships as `registry:file`,\n            which the shadcn CLI copies verbatim, so its Base UI codemod\n            (`asChild` → `render`) never runs on it. The link and the menu\n            trigger take the button styles directly instead. */}\n        <a\n          href=\"https://github.com/openstatusHQ/data-table-filters\"\n          target=\"_blank\"\n          rel=\"noreferrer\"\n          className={buttonVariants({ variant: \"ghost\", size: \"icon-xs\" })}\n        >\n          <Github />\n          <span className=\"sr-only\">View on GitHub</span>\n        </a>\n        <ShortcutsMenu />\n      </div>\n    </div>\n  );\n}\n\nfunction ShortcutsMenu() {\n  return (\n    <DropdownMenu>\n      <DropdownMenuTrigger\n        className={buttonVariants({ variant: \"ghost\", size: \"icon-xs\" })}\n      >\n        <Keyboard />\n        <span className=\"sr-only\">Keyboard shortcuts</span>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent className=\"w-72\" align=\"end\">\n        <DropdownMenuGroup>\n          <DropdownMenuLabel>Shortcuts</DropdownMenuLabel>\n          {SHORTCUTS.map((shortcut) => (\n            <DropdownMenuItem\n              key={shortcut.key}\n              onClick={() => triggerShortcut(shortcut.key)}\n            >\n              {shortcut.label}\n              <DropdownMenuShortcut>\n                {formatShortcut(shortcut.key)}\n              </DropdownMenuShortcut>\n            </DropdownMenuItem>\n          ))}\n        </DropdownMenuGroup>\n        <DropdownMenuSeparator />\n        <DropdownMenuGroup>\n          <DropdownMenuLabel>Navigation</DropdownMenuLabel>\n          {NAVIGATION.map((item) => (\n            <DropdownMenuItem key={item.keys} disabled>\n              {item.label}\n              <DropdownMenuShortcut>{item.keys}</DropdownMenuShortcut>\n            </DropdownMenuItem>\n          ))}\n        </DropdownMenuGroup>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n",
      "type": "registry:file",
      "target": "app/example/footer.tsx"
    },
    {
      "path": "src/examples/infinite/data.ts",
      "content": "import { LEVELS, METHODS, REGIONS, type ColumnSchema } from \"./table-schema\";\nimport { TIMING_PHASES, type Timing } from \"./timing\";\n\nconst ROWS = 5000;\nconst DAYS = 7;\n\nconst PATHNAMES = [\n  \"/api/v1/orders\",\n  \"/api/v1/products\",\n  \"/api/v1/customers\",\n  \"/checkout\",\n  \"/cart\",\n  \"/search\",\n  \"/account/settings\",\n  \"/health\",\n];\n\n/** A small seeded generator, so every server process serves the same rows. */\nfunction mulberry32(seed: number): () => number {\n  let state = seed >>> 0;\n  return () => {\n    state = (state + 0x6d2b79f5) >>> 0;\n    let t = state;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\nfunction pick<T>(random: () => number, values: readonly T[]): T {\n  return values[Math.floor(random() * values.length)];\n}\n\nfunction hex(random: () => number, length: number): string {\n  let out = \"\";\n  for (let index = 0; index < length; index++) {\n    out += Math.floor(random() * 16).toString(16);\n  }\n  return out;\n}\n\nfunction statusFor(random: () => number): number {\n  const roll = random();\n  if (roll < 0.85) return 200;\n  if (roll < 0.9) return 201;\n  if (roll < 0.94) return 400;\n  if (roll < 0.97) return 404;\n  return 500;\n}\n\n/** Rough share of a request each phase takes; jittered per row below. */\nconst TIMING_WEIGHTS = [0.05, 0.1, 0.15, 0.5, 0.2] as const;\n\n/**\n * Split the latency over the phases so they add up to it exactly: every\n * phase but the last is rounded, and the last takes whatever is left.\n */\nfunction timingFor(random: () => number, latency: number): Timing {\n  const weights = TIMING_WEIGHTS.map(\n    (weight) => weight * (0.6 + random() * 0.8),\n  );\n  const total = weights.reduce((sum, weight) => sum + weight, 0);\n  const timing = {} as Timing;\n  let remaining = latency;\n  TIMING_PHASES.forEach((phase, index) => {\n    const last = index === TIMING_PHASES.length - 1;\n    const value = last\n      ? remaining\n      : Math.round((latency * weights[index]) / total);\n    timing[phase] = Math.max(0, value);\n    remaining -= value;\n  });\n  return timing;\n}\n\nfunction levelFor(status: number): (typeof LEVELS)[number] {\n  if (status >= 500) return \"error\";\n  if (status >= 400) return \"warning\";\n  return \"info\";\n}\n\n/**\n * Rows spread over the last `DAYS` days, newest first — the order a timestamp\n * cursor expects. The values are seeded, so a refresh shows the same table;\n * only the timestamps move with the clock.\n */\nexport function createRows(now: number = Date.now()): ColumnSchema[] {\n  const random = mulberry32(42);\n  const span = DAYS * 24 * 60 * 60 * 1000;\n  const step = span / ROWS;\n  const rows: ColumnSchema[] = [];\n\n  for (let index = 0; index < ROWS; index++) {\n    const status = statusFor(random);\n    const base = 40 + random() * 200;\n    const slow = random() < 0.05 ? random() * 3000 : 0;\n    const latency = Math.round(base + slow);\n    rows.push({\n      uuid: hex(random, 32),\n      // Jitter stays under one step, so the order is strictly descending.\n      date: new Date(now - Math.floor(index * step + random() * step * 0.4)),\n      level: levelFor(status),\n      status,\n      method: pick(random, METHODS),\n      pathname: pick(random, PATHNAMES),\n      region: pick(random, REGIONS),\n      latency,\n      ...timingFor(random, latency),\n    });\n  }\n\n  return rows;\n}\n\nexport const rows = createRows();\n",
      "type": "registry:file",
      "target": "app/example/data.ts"
    },
    {
      "path": "src/examples/infinite/query-options.ts",
      "content": "import { createDataTableQueryOptions } from \"@/lib/data-table\";\nimport { searchParamsSerializer, type SearchParams } from \"./schema\";\nimport type { ColumnSchema } from \"./table-schema\";\n\nconst options = createDataTableQueryOptions<\n  ColumnSchema[],\n  Record<string, unknown>\n>({\n  queryKeyPrefix: \"example\",\n  apiEndpoint: \"/example/api\",\n  searchParamsSerializer: searchParamsSerializer as (\n    search: Record<string, unknown>,\n  ) => string,\n  // The route honours `_meta=false`; the client reads meta via `getMetaPage`.\n  skipMetaOnPagination: true,\n});\n\nexport const dataOptions = (search: SearchParams) =>\n  options(search as unknown as Record<string, unknown>);\n",
      "type": "registry:file",
      "target": "app/example/query-options.ts"
    },
    {
      "path": "src/examples/infinite/api/route.ts",
      "content": "import type {\n  FacetMetadataSchema,\n  InfiniteQueryResponse,\n} from \"@/lib/data-table\";\nimport { bucketChartData } from \"@/lib/data-table/chart-data\";\nimport { defineFilters } from \"@/lib/filters\";\nimport SuperJSON from \"superjson\";\nimport { rows } from \"../data\";\nimport { searchParamsCache, type SearchParams } from \"../schema\";\nimport { LEVELS, tableSchema, type ColumnSchema } from \"../table-schema\";\n\nexport const dynamic = \"force-dynamic\";\n\n/**\n * The same filter semantics the sidebar, the command palette and the Drizzle\n * handler use, applied to an array. When the rows move to Postgres, replace\n * this file with `createDrizzleHandler` from the drizzle block — the client\n * does not change.\n */\nconst filters = defineFilters(tableSchema.definition);\n\nconst sliderKeys = filters.specs\n  .filter((spec) => spec.type === \"slider\")\n  .map((spec) => spec.key);\nconst dateKeys = filters.specs\n  .filter((spec) => spec.type === \"timerange\")\n  .map((spec) => spec.key);\nconst facetKeys = filters.specs\n  .filter((spec) => spec.type !== \"timerange\" && spec.type !== \"slider\")\n  .map((spec) => spec.key);\n\nexport async function GET(request: Request): Promise<Response> {\n  const url = new URL(request.url);\n  const search = searchParamsCache.parse(Object.fromEntries(url.searchParams));\n  const values = search as Record<string, unknown>;\n\n  // Three passes, matching the Drizzle handler: the date range first, then\n  // every filter except the sliders, then the sliders. A slider's min and max\n  // facet is computed over the second pass, so the range stays visible after\n  // the user narrows it.\n  const ranged = filters.apply(rows, values, { only: dateKeys });\n  const withoutSliders = filters.apply(ranged, values, {\n    exclude: [...sliderKeys, ...dateKeys],\n  });\n  const filtered = filters.apply(withoutSliders, values, { only: sliderKeys });\n\n  const page = pageRows(sortRows(filtered, search.sort), search);\n\n  // Pagination requests send `_meta=false`: the client keeps the meta from the\n  // first page, and it cannot change while the filters are fixed.\n  const skipMeta = url.searchParams.get(\"_meta\") === \"false\";\n  const facets = skipMeta\n    ? {}\n    : {\n        ...facetsOf(withoutSliders, sliderKeys),\n        ...facetsOf(filtered, facetKeys),\n      };\n  // One point per time bucket with a count per level, over the date filter\n  // when one is set and the rows' own span otherwise.\n  const chartData = skipMeta\n    ? []\n    : bucketChartData(filtered, {\n        timestamp: (row) => row.date,\n        series: (row) => row.level,\n        keys: LEVELS,\n        range: search.date,\n      });\n\n  const response: InfiniteQueryResponse<ColumnSchema[]> = {\n    data: page,\n    meta: {\n      totalRowCount: rows.length,\n      filterRowCount: filtered.length,\n      chartData,\n      facets,\n    },\n    prevCursor: page.length > 0 ? page[0].date.getTime() : null,\n    nextCursor: page.length > 0 ? page[page.length - 1].date.getTime() : null,\n  };\n\n  return Response.json(SuperJSON.stringify(response));\n}\n\nfunction compare(left: unknown, right: unknown): number {\n  const a = left instanceof Date ? left.getTime() : left;\n  const b = right instanceof Date ? right.getTime() : right;\n  if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n  return String(a).localeCompare(String(b));\n}\n\n/**\n * Newest first, the order a timestamp cursor addresses. The caller's sort\n * only decides between rows sharing a timestamp, and `uuid` descending\n * settles the rest — the same composition and directions as the Drizzle\n * handler (cursor desc, sort, tiebreak desc), so swapping it in does not\n * reshuffle tied rows.\n * Sorting by the requested column alone would make every page after the\n * first re-read or skip rows, because the cursor is still a timestamp.\n */\nfunction sortRows(\n  data: ColumnSchema[],\n  sort: SearchParams[\"sort\"],\n): ColumnSchema[] {\n  const key = sort?.id as keyof ColumnSchema | undefined;\n  const direction = sort?.desc ? -1 : 1;\n  return [...data].sort(\n    (a, b) =>\n      compare(b.date, a.date) ||\n      (key ? compare(a[key], b[key]) * direction : 0) ||\n      compare(b.uuid, a.uuid),\n  );\n}\n\n/**\n * One page, addressed by a timestamp cursor. `next` reads rows older than the\n * cursor; `prev` reads everything newer, which is what a live refresh asks\n * for. Rows sharing the last timestamp travel together so none are skipped.\n */\nfunction pageRows(\n  data: ColumnSchema[],\n  search: Pick<SearchParams, \"cursor\" | \"size\" | \"direction\">,\n): ColumnSchema[] {\n  const cursor = search.cursor?.getTime() ?? Date.now();\n  // A `size` of zero or less would send back an empty first page forever.\n  const size = search.size && search.size > 0 ? search.size : 40;\n\n  if (search.direction === \"prev\") {\n    return data.filter((row) => row.date.getTime() > cursor);\n  }\n\n  const page: ColumnSchema[] = [];\n  for (const row of data) {\n    const time = row.date.getTime();\n    if (time >= cursor) continue;\n    const last = page[page.length - 1];\n    if (page.length < size || (last && last.date.getTime() === time)) {\n      page.push(row);\n    } else {\n      break;\n    }\n  }\n  return page;\n}\n\n/** Value counts per key, plus min and max for the numeric ones. */\nfunction facetsOf(\n  data: ColumnSchema[],\n  keys: string[],\n): Record<string, FacetMetadataSchema> {\n  const facets: Record<string, FacetMetadataSchema> = {};\n\n  for (const key of keys) {\n    const counts = new Map<unknown, number>();\n    let min: number | undefined;\n    let max: number | undefined;\n\n    for (const row of data) {\n      const value = row[key as keyof ColumnSchema];\n      if (value === null || value === undefined) continue;\n      counts.set(value, (counts.get(value) ?? 0) + 1);\n      if (typeof value === \"number\") {\n        min = min === undefined ? value : Math.min(min, value);\n        max = max === undefined ? value : Math.max(max, value);\n      }\n    }\n\n    facets[key] = {\n      rows: [...counts].map(([value, total]) => ({ value, total })),\n      total: data.length,\n      min,\n      max,\n    };\n  }\n\n  return facets;\n}\n",
      "type": "registry:page",
      "target": "app/example/api/route.ts"
    }
  ],
  "docs": "Start the dev server and open http://localhost:3000/example. The example lives in app/example — edit table-schema.ts to change the columns, or delete the folder once you have your own table.",
  "type": "registry:block"
}
