@underpin/ui 2.1.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/components/data-table.d.ts +16 -14
- package/components/data-table.js +19 -9
- package/components/data-table.js.map +1 -1
- package/components/menu.d.ts +16 -1
- package/components/menu.js +23 -2
- package/components/menu.js.map +1 -1
- package/components/nav.d.ts +33 -2
- package/components/nav.js +37 -2
- package/components/nav.js.map +1 -1
- package/components/range-picker.d.ts +59 -0
- package/components/range-picker.js +107 -0
- package/components/range-picker.js.map +1 -0
- package/components/router.d.ts +20 -0
- package/components/router.js +48 -0
- package/components/router.js.map +1 -0
- package/components/section-header.d.ts +13 -2
- package/components/section-header.js +15 -1
- package/components/section-header.js.map +1 -1
- package/components/shell.d.ts +54 -0
- package/components/shell.js +152 -0
- package/components/shell.js.map +1 -0
- package/components/table.d.ts +18 -1
- package/components/table.js +23 -4
- package/components/table.js.map +1 -1
- package/lib/data-table-search.d.ts +91 -0
- package/lib/data-table-search.js +115 -0
- package/lib/data-table-search.js.map +1 -0
- package/lib/data-table-state.d.ts +3 -18
- package/lib/data-table-state.js.map +1 -1
- package/lib/data-table-types.d.ts +29 -0
- package/lib/data-table-types.js +0 -0
- package/lib/href.d.ts +11 -0
- package/lib/href.js +15 -0
- package/lib/href.js.map +1 -0
- package/lib/icons.d.ts +15 -1
- package/lib/icons.js +40 -2
- package/lib/icons.js.map +1 -1
- package/package.json +14 -2
- package/styles.css +11 -1
package/components/table.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { rowPressClasses } from "../lib/classes.js";
|
|
3
|
-
import { AlertIcon, ArrowDownIcon, ArrowUpIcon, FilterIcon } from "../lib/icons.js";
|
|
3
|
+
import { AlertIcon, ArrowDownIcon, ArrowUpIcon, FilterIcon, RefreshIcon } from "../lib/icons.js";
|
|
4
4
|
import { cn, variants } from "../lib/variants.js";
|
|
5
|
+
import { Button } from "./button.js";
|
|
5
6
|
import { Checkbox } from "./checkbox.js";
|
|
6
7
|
import { CopyButton } from "./copy-button.js";
|
|
7
8
|
import { EmptyState } from "./empty-state.js";
|
|
9
|
+
import { ActionsMenu } from "./menu.js";
|
|
8
10
|
import { Skeleton } from "./skeleton.js";
|
|
9
11
|
import { Sparkline } from "./sparkline.js";
|
|
10
12
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
@@ -460,6 +462,16 @@ function TableActionsCell({ align, className, children, ...props }) {
|
|
|
460
462
|
})
|
|
461
463
|
});
|
|
462
464
|
}
|
|
465
|
+
/**
|
|
466
|
+
* The row's "…" menu, for a `TableActionsCell`: `ActionsMenu` at its `row` placement, a quiet
|
|
467
|
+
* ghost trigger that grows to finger size on a touch screen, and a menu aligned to the row's end.
|
|
468
|
+
*/
|
|
469
|
+
function TableActionsMenu(props) {
|
|
470
|
+
return /* @__PURE__ */ jsx(ActionsMenu, {
|
|
471
|
+
placement: "row",
|
|
472
|
+
...props
|
|
473
|
+
});
|
|
474
|
+
}
|
|
463
475
|
/** Selects the row, or every row on the page in the header. */
|
|
464
476
|
function TableCheckboxCell({ label, header: headerProp, checked, indeterminate, disabled, onCheckedChange, className, ...props }) {
|
|
465
477
|
const { layout } = use(TableContext);
|
|
@@ -544,11 +556,18 @@ function TableSkeletonRow({ size, index = 0 }) {
|
|
|
544
556
|
* Stands in for the rows: the small empty state across every column, under the header, which
|
|
545
557
|
* keeps its line. Put it inside `TableBody`.
|
|
546
558
|
*/
|
|
547
|
-
function TableMessage({ kind, icon, title, description, action }) {
|
|
559
|
+
function TableMessage({ kind, icon, title, description, action, onRetry, retryLabel = "Try again" }) {
|
|
548
560
|
const { layout } = use(TableContext);
|
|
549
561
|
const list = layout === "list";
|
|
550
562
|
const Row = list ? "div" : "tr";
|
|
551
563
|
const Cell = list ? "div" : "td";
|
|
564
|
+
const retry = kind === "error" && onRetry && /* @__PURE__ */ jsx(Button, {
|
|
565
|
+
variant: "secondary",
|
|
566
|
+
size: "sm",
|
|
567
|
+
prefix: /* @__PURE__ */ jsx(RefreshIcon, {}),
|
|
568
|
+
onClick: onRetry,
|
|
569
|
+
children: retryLabel
|
|
570
|
+
});
|
|
552
571
|
return /* @__PURE__ */ jsx(Row, {
|
|
553
572
|
role: list ? "listitem" : "row",
|
|
554
573
|
"data-kind": kind,
|
|
@@ -562,11 +581,11 @@ function TableMessage({ kind, icon, title, description, action }) {
|
|
|
562
581
|
icon: icon ?? (kind === "empty" ? void 0 : MESSAGE_ICONS[kind]),
|
|
563
582
|
title,
|
|
564
583
|
description,
|
|
565
|
-
action
|
|
584
|
+
action: action ?? retry
|
|
566
585
|
})
|
|
567
586
|
})
|
|
568
587
|
});
|
|
569
588
|
}
|
|
570
|
-
export { Table, TableActionsCell, TableBadgeCell, TableBody, TableCell, TableCheckboxCell, TableColumnScope, TableCountryCell, TableDateCell, TableGroupHeader, TableHead, TableHeader, TableIdentityCell, TableMessage, TableMeterCell, TableMonoCell, TableNumberCell, TablePersonCell, TableRow, TableRowLink, TableSkeletonRow, TableSparklineCell, TableTagsCell, tableColumnPriorityClasses };
|
|
589
|
+
export { Table, TableActionsCell, TableActionsMenu, TableBadgeCell, TableBody, TableCell, TableCheckboxCell, TableColumnScope, TableCountryCell, TableDateCell, TableGroupHeader, TableHead, TableHeader, TableIdentityCell, TableMessage, TableMeterCell, TableMonoCell, TableNumberCell, TablePersonCell, TableRow, TableRowLink, TableSkeletonRow, TableSparklineCell, TableTagsCell, tableColumnPriorityClasses };
|
|
571
590
|
|
|
572
591
|
//# sourceMappingURL=table.js.map
|
package/components/table.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table.js","names":[],"sources":["../../src/components/table.tsx"],"sourcesContent":["\"use client\"\n\nimport { useRender } from \"@base-ui/react/use-render\"\nimport {\n Children,\n type ComponentProps,\n createContext,\n type CSSProperties,\n type ReactNode,\n use,\n} from \"react\"\nimport { rowPressClasses } from \"../lib/classes\"\nimport { AlertIcon, ArrowDownIcon, ArrowUpIcon, FilterIcon } from \"../lib/icons\"\nimport { cn, variants, type VariantProps } from \"../lib/variants\"\nimport { Checkbox } from \"./checkbox\"\nimport { CopyButton } from \"./copy-button\"\nimport { EmptyState } from \"./empty-state\"\nimport { Skeleton } from \"./skeleton\"\nimport { Sparkline } from \"./sparkline\"\n\n// The parts are table elements laid out as a CSS grid, so they carry their table roles\n// explicitly: a browser that sees `display: grid` on a `<table>` may stop exposing it as one.\n/* oxlint-disable jsx-a11y/no-redundant-roles */\n\n/**\n * Which columns give way as the table's box narrows: a `medium` column hides below the `@2xl`\n * container width (672px), a `low` one below `@4xl` (896px) and a `lowest` one below `@6xl`\n * (1152px), for a table with more columns than a laptop's content column holds. A column with\n * none always shows.\n */\nexport type TableColumnPriority = \"medium\" | \"low\" | \"lowest\"\n\nexport interface TableColumn {\n /** The column's grid track: `minmax(0,1fr)` for the name, a fixed `6rem` for a figure. */\n width: string\n priority?: TableColumnPriority\n /** Where a skeleton row puts its stand-in. */\n align?: \"start\" | \"end\"\n /** Whether a skeleton row draws a stand-in here. Off for a checkbox or actions column. */\n skeleton?: boolean\n}\n\ntype TableLayout = \"table\" | \"list\"\n\ninterface TableContextValue {\n layout: TableLayout\n columns: TableColumn[]\n}\n\nconst TableContext = createContext<TableContextValue>({ layout: \"table\", columns: [] })\n\ninterface TableColumnScopeValue {\n align?: \"start\" | \"end\"\n priority?: TableColumnPriority\n}\n\nconst TableColumnScopeContext = createContext<TableColumnScopeValue>({})\n\n/**\n * The classes that hide a cell of a column with a priority, on its head and on every cell, so\n * the column drops out whole. `Table` drops its track from the grid at the same widths.\n */\nexport const tableColumnPriorityClasses: Record<TableColumnPriority, string> = {\n medium: \"@max-2xl:hidden\",\n low: \"@max-4xl:hidden\",\n lowest: \"@max-6xl:hidden\",\n}\n\nfunction formatColumnTemplate(columns: TableColumn[], hidden: TableColumnPriority[]) {\n return columns\n .filter(column => !column.priority || !hidden.includes(column.priority))\n .map(column => column.width)\n .join(\" \")\n}\n\nconst ROW_GRID_CLASSES = \"col-span-full grid grid-cols-subgrid\"\n\nconst tableVariants = variants({\n slots: {\n container: \"@container relative\",\n table: [\n \"grid w-full text-control text-ink\",\n \"grid-cols-(--table-columns) @2xl:grid-cols-(--table-columns-md) @4xl:grid-cols-(--table-columns-lg) @6xl:grid-cols-(--table-columns-xl)\",\n // A sticky header pushes the sticky group headings down by its own height.\n \"has-[>[data-sticky]]:[--table-header-height:--spacing(10)]\",\n ],\n },\n\n variants: {\n variant: {\n // The card surface, its edge drawn by the wrapper so the rows' fills stay inside it.\n card: { container: \"overflow-clip rounded-lg border bg-surface shadow-card\" },\n // No surface, for a table inside another card or a dialog.\n flush: {},\n },\n },\n\n defaultVariants: {\n variant: \"card\",\n },\n})\n\nconst tableRowVariants = variants({\n base: [\n ROW_GRID_CLASSES,\n \"group/row relative items-center border-t border-edge-subtle\",\n // Only a row that opens something answers the pointer. The hover and focus fills leave out a\n // pressed link: they match with the same weight as the press fill and come later in the\n // stylesheet, so they would hide it.\n \"has-[[data-row-link]:not(:active)]:hover:bg-canvas has-[[data-row-link]:focus-visible:not(:active)]:bg-canvas\",\n rowPressClasses,\n \"data-selected:bg-fill-subtle data-selected:hover:bg-fill-subtle\",\n // The cell holding the row link sits on a layer above its neighbours. A faded cell is a\n // stacking context of its own, and a later one would otherwise paint over the link's box.\n // A grid item takes `z-index` without being positioned, so the link still fills the row.\n \"*:has-[[data-row-link]]:z-1\",\n // An archived or blocked record fades, all but its menu. A cell holding a control above the\n // row link (the checkbox, a copy button) fades its content instead: faded whole, it would be\n // a stacking context under the link's layer, and the control could not be clicked.\n \"data-inactive:*:not-data-[slot=actions]:not-data-[slot=checkbox]:not-data-[slot=mono]:opacity-50\",\n ],\n\n variants: {\n size: {\n /** 32px, for a feed or a dense list. */\n compact: \"h-8\",\n /** 44px, a one-line row. */\n default: \"h-11\",\n /** 52px, for a two-line name cell. */\n identity: \"h-13\",\n },\n },\n\n defaultVariants: {\n size: \"default\",\n },\n})\n\nconst tableCellVariants = variants({\n base: [\n \"flex min-w-0 items-center gap-2 px-2 first:pl-5 last:pr-5\",\n // The trailing inset goes to the last cell still shown: a hidden cell after it stays the\n // `:last-child`. Below 1152px that is a cell followed only by `lowest` ones, below 896px one\n // followed only by `low` and `lowest` ones, below 672px one followed only by cells with a\n // priority.\n \"@max-6xl:[&:not(:has(~:not([data-priority=lowest])))]:pr-5\",\n \"@max-4xl:[&:not(:has(~:not([data-priority=low]):not([data-priority=lowest])))]:pr-5\",\n \"@max-2xl:[&:not(:has(~:not([data-priority])))]:pr-5\",\n ],\n\n variants: {\n align: {\n start: \"justify-start text-left\",\n end: \"justify-end text-right\",\n },\n priority: tableColumnPriorityClasses,\n },\n\n defaultVariants: {\n align: \"start\",\n },\n})\n\ntype TableCellVariantProps = VariantProps<typeof tableCellVariants>\n\n/** Varied widths for a skeleton row's first line, so a stack of them does not read as stripes. */\nconst SKELETON_NAME_WIDTHS = [\"w-36\", \"w-28\", \"w-40\", \"w-32\", \"w-24\"]\n\nconst MESSAGE_ICONS = {\n filtered: <FilterIcon />,\n error: <AlertIcon />,\n}\n\nexport interface TableProps\n extends Omit<ComponentProps<\"table\">, \"children\">, VariantProps<typeof tableVariants> {\n /** Every column in order, the same list the head and the cells of each row follow. */\n columns: TableColumn[]\n /**\n * `list` draws the same rows with no column names, for a list of records (members, API keys):\n * the rows are list items rather than table rows.\n */\n layout?: TableLayout\n /** The band under the rows: `Pagination` or `PaginationInfinite`. */\n footer?: ReactNode\n /** Classes for the box around the table: the card, or the bare wrapper of a flush table. */\n containerClassName?: string\n children?: ReactNode\n}\n\n/**\n * A table on a CSS grid. The root sets one grid template from `columns`, and the header and\n * every row take it as a subgrid, so the columns line up however the rows are grouped. A row\n * stays a positioned box, which a real table row is not in Safari, so a stretched link can\n * fill it (`TableRowLink`). Columns with a `priority` drop out as the table's own box narrows.\n * Set `--table-sticky-top` on it when a sticky header must clear a bar pinned above it.\n */\nexport function Table({\n columns,\n layout = \"table\",\n variant,\n footer,\n className,\n containerClassName,\n style,\n children,\n ...props\n}: TableProps) {\n const styles = tableVariants({ variant })\n const template = {\n \"--table-columns\": formatColumnTemplate(columns, [\"medium\", \"low\", \"lowest\"]),\n \"--table-columns-md\": formatColumnTemplate(columns, [\"low\", \"lowest\"]),\n \"--table-columns-lg\": formatColumnTemplate(columns, [\"lowest\"]),\n \"--table-columns-xl\": formatColumnTemplate(columns, []),\n ...style,\n } as CSSProperties\n const Root = layout === \"list\" ? \"div\" : \"table\"\n\n return (\n <TableContext value={{ layout, columns }}>\n <div className={styles.container({ className: containerClassName })}>\n <Root\n role={layout === \"list\" ? \"list\" : \"table\"}\n className={styles.table({ className })}\n style={template}\n {...props}\n >\n {children}\n </Root>\n {footer}\n </div>\n </TableContext>\n )\n}\n\ninterface TableHeaderProps extends ComponentProps<\"thead\"> {\n /** Keeps the column names in view while the rows scroll under them. */\n sticky?: boolean\n}\n\n/**\n * The row of column names: 40px, on the surface, with one line under it in the card's edge\n * colour. The first row draws no line of its own, so the two never stack. A list has none, and\n * renders nothing for one.\n */\nexport function TableHeader({ sticky, className, children, ...props }: TableHeaderProps) {\n if (use(TableContext).layout === \"list\") return null\n\n return (\n <thead\n role=\"rowgroup\"\n data-sticky={sticky ? \"\" : undefined}\n className={cn(\n ROW_GRID_CLASSES,\n \"border-b bg-surface\",\n sticky && \"sticky top-(--table-sticky-top,0px) z-20\",\n className,\n )}\n {...props}\n >\n {/* The rule reads a header row as interactive; the role restores what `display: grid` drops. */}\n {/* oxlint-disable-next-line jsx-a11y/no-interactive-element-to-noninteractive-role */}\n <tr role=\"row\" className={cn(ROW_GRID_CLASSES, \"h-10 items-center\")}>\n {children}\n </tr>\n </thead>\n )\n}\n\n/**\n * The rows. A table cut into runs (days, workspaces) takes one body per run, each opening with\n * its `TableGroupHeader`, so the heading sticks while its own rows are in view.\n */\nexport function TableBody({ className, ...props }: ComponentProps<\"tbody\">) {\n const { layout } = use(TableContext)\n const Body = layout === \"list\" ? \"div\" : \"tbody\"\n\n return (\n <Body\n role={layout === \"list\" ? \"presentation\" : \"rowgroup\"}\n className={cn(\n ROW_GRID_CLASSES,\n // The first row of the table sits under the header's line, or the card's edge.\n \"[&:first-of-type>:first-child]:border-t-0\",\n className,\n )}\n {...props}\n />\n )\n}\n\nexport interface TableRowProps extends ComponentProps<\"tr\">, VariantProps<typeof tableRowVariants> {\n selected?: boolean\n /** Dims the row's cells, for a record that is archived or blocked. */\n inactive?: boolean\n}\n\n/**\n * One record. A row whose name is a `TableRowLink` opens it from anywhere on the row and takes\n * the hover fill; a row without one keeps its background under the pointer.\n */\nexport function TableRow({ size, selected, inactive, className, ...props }: TableRowProps) {\n const { layout } = use(TableContext)\n const Row = layout === \"list\" ? \"div\" : \"tr\"\n\n return (\n <Row\n role={layout === \"list\" ? \"listitem\" : \"row\"}\n data-selected={selected ? \"\" : undefined}\n data-inactive={inactive ? \"\" : undefined}\n className={tableRowVariants({ size, className })}\n {...props}\n />\n )\n}\n\nexport interface TableHeadProps extends Omit<ComponentProps<\"th\">, \"align\">, TableCellVariantProps {\n /** The order the table is in by this column. Left out for a column that does not sort. */\n sort?: \"ascending\" | \"descending\" | \"none\"\n /** Turns the name into a button that sorts by the column. */\n onSort?: () => void\n}\n\n/**\n * A column name, in the control weight. A sortable column is a button, with the arrow of its\n * order while the table is sorted by it; unsorted, it looks like any other name.\n */\nexport function TableHead({\n align,\n priority,\n sort,\n onSort,\n className,\n children,\n ...props\n}: TableHeadProps) {\n const sorted = sort === \"ascending\" || sort === \"descending\"\n const Arrow = sort === \"ascending\" ? ArrowUpIcon : ArrowDownIcon\n\n return (\n <th\n role=\"columnheader\"\n scope=\"col\"\n data-priority={priority}\n aria-sort={sort}\n className={tableCellVariants({\n align,\n priority,\n className: cn(\"gap-1 font-medium text-control text-ink\", className),\n })}\n {...props}\n >\n {onSort ? (\n <button\n type=\"button\"\n className=\"inline-flex min-w-0 cursor-pointer items-center gap-1 rounded-xs hover:text-ink-secondary\"\n onClick={onSort}\n >\n <span className=\"truncate\">{children}</span>\n {sorted && <Arrow className=\"size-3 shrink-0\" />}\n </button>\n ) : (\n children\n )}\n </th>\n )\n}\n\nexport interface TableCellProps\n extends Omit<ComponentProps<\"td\">, \"align\">, TableCellVariantProps {}\n\n/**\n * One cell, the Text type: a line of ink that ends in an ellipsis. Every other cell type is\n * built on it. Give it the `align` and `priority` of its column's head.\n */\nexport function TableCell({ align, priority, className, children, ...props }: TableCellProps) {\n const { layout } = use(TableContext)\n const scope = use(TableColumnScopeContext)\n const columnPriority = priority ?? scope.priority\n const Cell = layout === \"list\" ? \"div\" : \"td\"\n const text = typeof children === \"string\" || typeof children === \"number\"\n\n return (\n <Cell\n role={layout === \"list\" ? undefined : \"cell\"}\n data-priority={columnPriority}\n className={tableCellVariants({\n align: align ?? scope.align,\n priority: columnPriority,\n className,\n })}\n {...props}\n >\n {text ? <span className=\"truncate\">{children}</span> : children}\n </Cell>\n )\n}\n\ninterface TableColumnScopeProps extends TableColumnScopeValue {\n children?: ReactNode\n}\n\n/**\n * Hands the cells inside it their column's `align` and `priority`, for a cell rendered by code\n * that knows nothing of its column (a `DataTable` column's `cell`). A cell's own props win.\n */\nexport function TableColumnScope({ align, priority, children }: TableColumnScopeProps) {\n return <TableColumnScopeContext value={{ align, priority }}>{children}</TableColumnScopeContext>\n}\n\n/**\n * The record's name as a link that covers the whole row: its box stretches over the row, and\n * the focus ring is drawn round the row. The checkbox, the menu and any other link in the row\n * sit above it (`relative z-10`, as the checkbox and actions cells do), so each keeps its own\n * click. Pass `render` for a router's link.\n */\nexport function TableRowLink({ render, className, ...props }: useRender.ComponentProps<\"a\">) {\n return useRender({\n render,\n defaultTagName: \"a\",\n props: {\n \"data-row-link\": \"\",\n \"data-press-target\": \"\",\n className: cn(\n \"truncate outline-none after:absolute after:inset-0\",\n \"focus-visible:after:outline-2 focus-visible:after:-outline-offset-2 focus-visible:after:outline-focus\",\n className,\n ),\n ...props,\n },\n })\n}\n\ninterface TableIdentityCellProps extends Omit<TableCellProps, \"title\"> {\n /** A favicon, an avatar or a letter tile, sized 28px (`size-7`) by the caller. */\n leading?: ReactNode\n /** The record's name, usually a `TableRowLink`. */\n title: ReactNode\n /** One muted line under the name: a domain, an email. */\n detail?: ReactNode\n /** A flag or a badge after the name. */\n extras?: ReactNode\n}\n\n/** The name column: the leading mark, the name in the control weight and a muted line. */\nexport function TableIdentityCell({\n leading,\n title,\n detail,\n extras,\n className,\n ...props\n}: TableIdentityCellProps) {\n return (\n <TableCell className={cn(\"gap-3\", className)} {...props}>\n {leading && <span className=\"flex shrink-0\">{leading}</span>}\n <span className=\"flex min-w-0 flex-col gap-0.5\">\n <span className=\"flex min-w-0 items-center gap-1.5\">\n <span className=\"min-w-0 truncate font-medium\">{title}</span>\n {extras && <span className=\"flex shrink-0 items-center gap-1.5\">{extras}</span>}\n </span>\n {detail && <span className=\"truncate text-ink-muted text-xs\">{detail}</span>}\n </span>\n </TableCell>\n )\n}\n\n/**\n * A figure, Number or Money: end-aligned in tabular figures. The caller formats the value, a\n * sum of money with its currency.\n */\nexport function TableNumberCell({ align, className, ...props }: TableCellProps) {\n const scope = use(TableColumnScopeContext)\n\n return (\n <TableCell\n align={align ?? scope.align ?? \"end\"}\n className={cn(\"tabular-nums\", className)}\n {...props}\n />\n )\n}\n\n/** A date, muted: pass a `RelativeTime`, which keeps the exact moment for its tooltip. */\nexport function TableDateCell({ className, ...props }: TableCellProps) {\n return <TableCell className={cn(\"text-ink-muted tabular-nums\", className)} {...props} />\n}\n\n/** A status: pass one `Badge`. */\nexport function TableBadgeCell(props: TableCellProps) {\n return <TableCell {...props} />\n}\n\ninterface TableTagsCellProps extends Omit<TableCellProps, \"children\"> {\n /** One `Badge` per tag. */\n tags: ReactNode[]\n /** How many show before the rest fold into \"+N\". */\n max?: number\n}\n\n/** Tags: the first two, then a count of the rest. */\nexport function TableTagsCell({ tags, max = 2, className, ...props }: TableTagsCellProps) {\n const rest = tags.length - max\n\n return (\n <TableCell className={cn(\"gap-1\", className)} {...props}>\n {Children.toArray(tags.slice(0, max))}\n {rest > 0 && <span className=\"shrink-0 text-ink-muted text-xs tabular-nums\">+{rest}</span>}\n </TableCell>\n )\n}\n\ninterface TableSparklineCellProps extends Omit<TableCellProps, \"children\"> {\n data: number[]\n}\n\n/** A trend: a `Sparkline` across the cell, 32px tall. */\nexport function TableSparklineCell({ data, ...props }: TableSparklineCellProps) {\n return (\n <TableCell {...props}>\n <Sparkline data={data} className=\"h-8 w-full\" />\n </TableCell>\n )\n}\n\nconst METER_TONES = {\n neutral: { bar: \"bg-ink\", ring: \"stroke-ink\" },\n brand: { bar: \"bg-brand\", ring: \"stroke-brand\" },\n warning: { bar: \"bg-warning\", ring: \"stroke-warning\" },\n danger: { bar: \"bg-danger\", ring: \"stroke-danger\" },\n}\n\n/** The ring's radius in its 16px box, and the length of its circle. */\nconst RING_RADIUS = 6\nconst RING_LENGTH = 2 * Math.PI * RING_RADIUS\n\ninterface TableMeterCellProps extends Omit<TableCellProps, \"children\"> {\n value: number\n max: number\n /** The usage as text, formatted by the caller: \"8,240 of 10,000\". */\n label?: ReactNode\n /**\n * The meter's colour, for a meter whose state the app knows better than the share does (a\n * usage lock, a failed job). Left out, it is ink and turns warning past 90%.\n */\n tone?: keyof typeof METER_TONES\n /**\n * `bar` puts a 48px bar before a muted figure. `ring` puts a 14px ring before the figure in the\n * cell's own text, for a narrow column whose figure needs the room (\"35.5k of 657.2k rows\").\n */\n layout?: \"bar\" | \"ring\"\n}\n\n/** Usage against a limit: a bar or a ring, then the figure. It turns warning past 90%. */\nexport function TableMeterCell({\n value,\n max,\n label,\n tone,\n layout = \"bar\",\n className,\n ...props\n}: TableMeterCellProps) {\n const share = max > 0 ? Math.min(value / max, 1) : 0\n const tones = METER_TONES[tone ?? (share > 0.9 ? \"warning\" : \"neutral\")]\n const ring = layout === \"ring\"\n\n return (\n <TableCell className={cn(ring ? \"gap-1.5\" : \"gap-2\", className)} {...props}>\n <span\n // A native `<meter>` draws its own bar, which the theme's tokens cannot reach.\n // oxlint-disable-next-line jsx-a11y/prefer-tag-over-role\n role=\"meter\"\n aria-valuenow={value}\n aria-valuemin={0}\n aria-valuemax={max}\n aria-label={typeof label === \"string\" ? label : undefined}\n className={cn(\n \"shrink-0\",\n ring ? \"flex size-3.5\" : \"h-1 w-12 overflow-hidden rounded-full bg-fill\",\n )}\n >\n {ring ? (\n <svg aria-hidden viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-full -rotate-90\">\n <circle\n cx=\"8\"\n cy=\"8\"\n r={RING_RADIUS}\n strokeWidth=\"2.5\"\n className=\"stroke-fill-strong\"\n />\n {share > 0 && (\n <circle\n cx=\"8\"\n cy=\"8\"\n r={RING_RADIUS}\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeDasharray={`${share * RING_LENGTH} ${RING_LENGTH}`}\n className={tones.ring}\n />\n )}\n </svg>\n ) : (\n <span\n className={cn(\"block h-full rounded-full\", tones.bar)}\n style={{ width: `${share * 100}%` }}\n />\n )}\n </span>\n {label && (\n <span className={cn(\"truncate tabular-nums\", !ring && \"text-ink-muted text-xs\")}>\n {label}\n </span>\n )}\n </TableCell>\n )\n}\n\ninterface TableCountryCellProps extends Omit<TableCellProps, \"children\"> {\n /** The country's flag. */\n flag: ReactNode\n name: ReactNode\n}\n\n/** A country: its flag and its name. */\nexport function TableCountryCell({ flag, name, ...props }: TableCountryCellProps) {\n return (\n <TableCell {...props}>\n <span className=\"flex shrink-0\">{flag}</span>\n <span className=\"truncate\">{name}</span>\n </TableCell>\n )\n}\n\ninterface TableMonoCellProps extends Omit<TableCellProps, \"children\"> {\n value: string\n /** Adds a copy button after the value. */\n copy?: boolean\n}\n\n/** A machine string (a key, an id) in mono, with a copy button that sits above the row link. */\nexport function TableMonoCell({ value, copy, className, ...props }: TableMonoCellProps) {\n return (\n <TableCell data-slot=\"mono\" className={cn(\"gap-1\", className)} {...props}>\n <span className=\"truncate font-mono text-ink-secondary text-xs in-data-inactive:opacity-50\">\n {value}\n </span>\n {copy && (\n <CopyButton\n value={value}\n variant=\"ghost\"\n size=\"xs\"\n className=\"relative z-10 in-data-inactive:opacity-50\"\n />\n )}\n </TableCell>\n )\n}\n\ninterface TablePersonCellProps extends Omit<TableCellProps, \"children\"> {\n /** An avatar, sized 20px (`size-5`) by the caller. */\n avatar?: ReactNode\n name: ReactNode\n}\n\n/** A person on one line: a 20px avatar and the name. */\nexport function TablePersonCell({ avatar, name, ...props }: TablePersonCellProps) {\n return (\n <TableCell {...props}>\n {avatar && <span className=\"flex shrink-0\">{avatar}</span>}\n <span className=\"truncate\">{name}</span>\n </TableCell>\n )\n}\n\n/**\n * The row's menu, end-aligned above the row link. It shows on hover, on keyboard focus, while\n * open, and always on a touch screen, which has no hover to give.\n */\nexport function TableActionsCell({ align, className, children, ...props }: TableCellProps) {\n const scope = use(TableColumnScopeContext)\n\n return (\n <TableCell\n data-slot=\"actions\"\n align={align ?? scope.align ?? \"end\"}\n className={className}\n {...props}\n >\n <span\n className={cn(\n \"relative z-10 flex\",\n \"opacity-0 group-hover/row:opacity-100 focus-within:opacity-100 has-data-popup-open:opacity-100 pointer-coarse:opacity-100\",\n )}\n >\n {children}\n </span>\n </TableCell>\n )\n}\n\ninterface TableCheckboxCellProps\n extends\n Omit<TableCellProps, \"children\" | \"onChange\">,\n Pick<\n ComponentProps<typeof Checkbox>,\n \"checked\" | \"indeterminate\" | \"disabled\" | \"onCheckedChange\"\n > {\n /** Names the checkbox: \"Select openalternative.com\", \"Select all\". */\n label: string\n /** Renders a head cell for the header row: the select-all box. Ignored in a list. */\n header?: boolean\n}\n\n/** Selects the row, or every row on the page in the header. */\nexport function TableCheckboxCell({\n label,\n header: headerProp,\n checked,\n indeterminate,\n disabled,\n onCheckedChange,\n className,\n ...props\n}: TableCheckboxCellProps) {\n // A list has no header row, so a header box there renders as a plain cell.\n const { layout } = use(TableContext)\n const header = headerProp && layout === \"table\"\n const box = (\n <Checkbox\n aria-label={label}\n checked={checked}\n indeterminate={indeterminate}\n disabled={disabled}\n className=\"relative z-10 in-data-inactive:opacity-50\"\n onCheckedChange={onCheckedChange}\n />\n )\n const classes = cn(\"pr-0 first:pl-4\", className)\n\n if (header) {\n const { align, priority, ...headProps } = props\n return (\n <th\n role=\"columnheader\"\n scope=\"col\"\n data-slot=\"checkbox\"\n className={tableCellVariants({ align, priority, className: classes })}\n {...headProps}\n >\n {box}\n </th>\n )\n }\n\n return (\n <TableCell data-slot=\"checkbox\" className={classes} {...props}>\n {box}\n </TableCell>\n )\n}\n\ninterface TableGroupHeaderProps extends ComponentProps<\"tr\"> {}\n\n/**\n * A heading row for the run of rows under it: a day of a feed, a workspace of a list. It sticks\n * under the header while its own body is in view, and the next one pushes it out. Opaque, so the\n * rows slide under it.\n */\nexport function TableGroupHeader({ className, children, ...props }: TableGroupHeaderProps) {\n const { layout } = use(TableContext)\n const list = layout === \"list\"\n const Row = list ? \"div\" : \"tr\"\n const Heading = list ? \"div\" : \"th\"\n\n return (\n <Row\n role={list ? \"listitem\" : \"row\"}\n className={cn(\n ROW_GRID_CLASSES,\n // Above the controls of the rows sliding under it (`z-10`), below a sticky header (`z-20`).\n \"sticky top-[calc(var(--table-sticky-top,0px)+var(--table-header-height,0px))] z-15\",\n \"h-7 border-t border-edge-subtle bg-fill-subtle\",\n className,\n )}\n {...props}\n >\n <Heading\n role={list ? \"heading\" : \"rowheader\"}\n aria-level={list ? 3 : undefined}\n scope={list ? undefined : \"rowgroup\"}\n className=\"col-span-full flex items-center px-5 text-left font-medium text-ink-secondary text-xs\"\n >\n {children}\n </Heading>\n </Row>\n )\n}\n\ninterface TableSkeletonRowProps extends VariantProps<typeof tableRowVariants> {\n /** The row's place in the stack, which picks the width of its first line. */\n index?: number\n}\n\n/**\n * A loading row the size of the rows it stands in for, one stand-in per column of the table.\n * Put five in the body on a first load; while a later page loads, keep the old rows and dim them.\n */\nexport function TableSkeletonRow({ size, index = 0 }: TableSkeletonRowProps) {\n const { columns } = use(TableContext)\n const nameWidth = SKELETON_NAME_WIDTHS[index % SKELETON_NAME_WIDTHS.length]\n // The first column that draws a stand-in, past a leading checkbox.\n const nameColumn = columns.findIndex(column => column.skeleton !== false)\n\n return (\n <TableRow size={size} aria-hidden>\n {columns.map((column, position) => (\n <TableCell\n // oxlint-disable-next-line react/no-array-index-key\n key={position}\n align={column.align}\n priority={column.priority}\n className=\"gap-2\"\n >\n {column.skeleton === false ? null : position === nameColumn && size === \"identity\" ? (\n <>\n <Skeleton className=\"size-7 shrink-0 rounded-md\" />\n <span className=\"flex flex-col gap-1.5\">\n <Skeleton className={cn(\"h-3\", nameWidth)} />\n <Skeleton className=\"h-2.5 w-24\" />\n </span>\n </>\n ) : (\n <Skeleton className={cn(\"h-3\", position === nameColumn ? nameWidth : \"w-16\")} />\n )}\n </TableCell>\n ))}\n </TableRow>\n )\n}\n\ninterface TableMessageProps {\n /**\n * `empty`: nothing exists yet, with the create action. `filtered`: nothing matches, with a way\n * to clear the filters. `error`: the load failed, with a retry.\n */\n kind: \"empty\" | \"filtered\" | \"error\"\n /** Required for `empty`; `filtered` and `error` draw a filter and an alert by default. */\n icon?: ReactNode\n title: ReactNode\n description?: ReactNode\n action?: ReactNode\n}\n\n/**\n * Stands in for the rows: the small empty state across every column, under the header, which\n * keeps its line. Put it inside `TableBody`.\n */\nexport function TableMessage({ kind, icon, title, description, action }: TableMessageProps) {\n const { layout } = use(TableContext)\n const list = layout === \"list\"\n const Row = list ? \"div\" : \"tr\"\n const Cell = list ? \"div\" : \"td\"\n\n return (\n <Row\n role={list ? \"listitem\" : \"row\"}\n data-kind={kind}\n className={cn(ROW_GRID_CLASSES, \"border-t border-edge-subtle\")}\n >\n <Cell role={list ? undefined : \"cell\"} className=\"col-span-full py-5\">\n <EmptyState\n size=\"sm\"\n role={kind === \"error\" ? \"alert\" : undefined}\n icon={icon ?? (kind === \"empty\" ? undefined : MESSAGE_ICONS[kind])}\n title={title}\n description={description}\n action={action}\n />\n </Cell>\n </Row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ACE,oBAAC,KAAD;EACE,MAAM,OAAO,aAAa;EAC1B,aAAW;EACX,WAAW,GAAG,kBAAkB,6BAA6B;EAE7D,UAAA,oBAAC,MAAD;GAAM,MAAM,OAAO,KAAA,IAAY;GAAQ,WAAU;GAC/C,UAAA,oBAAC,YAAD;IACE,MAAK;IACL,MAAM,SAAS,UAAU,UAAU,KAAA;IACnC,MAAM,SAAS,SAAS,UAAU,KAAA,IAAY,cAAc;IACrD;IACM;IACL;GACT,CAAA;EACG,CAAA;CACH,CAAA;AAET"}
|
|
1
|
+
{"version":3,"file":"table.js","names":[],"sources":["../../src/components/table.tsx"],"sourcesContent":["\"use client\"\n\nimport { useRender } from \"@base-ui/react/use-render\"\nimport {\n Children,\n type ComponentProps,\n createContext,\n type CSSProperties,\n type ReactNode,\n use,\n} from \"react\"\nimport { rowPressClasses } from \"../lib/classes\"\nimport { AlertIcon, ArrowDownIcon, ArrowUpIcon, FilterIcon, RefreshIcon } from \"../lib/icons\"\nimport { cn, variants, type VariantProps } from \"../lib/variants\"\nimport { Button } from \"./button\"\nimport { Checkbox } from \"./checkbox\"\nimport { CopyButton } from \"./copy-button\"\nimport { EmptyState } from \"./empty-state\"\nimport { ActionsMenu } from \"./menu\"\nimport { Skeleton } from \"./skeleton\"\nimport { Sparkline } from \"./sparkline\"\n\n// The parts are table elements laid out as a CSS grid, so they carry their table roles\n// explicitly: a browser that sees `display: grid` on a `<table>` may stop exposing it as one.\n/* oxlint-disable jsx-a11y/no-redundant-roles */\n\n/**\n * Which columns give way as the table's box narrows: a `medium` column hides below the `@2xl`\n * container width (672px), a `low` one below `@4xl` (896px) and a `lowest` one below `@6xl`\n * (1152px), for a table with more columns than a laptop's content column holds. A column with\n * none always shows.\n */\nexport type TableColumnPriority = \"medium\" | \"low\" | \"lowest\"\n\nexport interface TableColumn {\n /** The column's grid track: `minmax(0,1fr)` for the name, a fixed `6rem` for a figure. */\n width: string\n priority?: TableColumnPriority\n /** Where a skeleton row puts its stand-in. */\n align?: \"start\" | \"end\"\n /** Whether a skeleton row draws a stand-in here. Off for a checkbox or actions column. */\n skeleton?: boolean\n}\n\ntype TableLayout = \"table\" | \"list\"\n\ninterface TableContextValue {\n layout: TableLayout\n columns: TableColumn[]\n}\n\nconst TableContext = createContext<TableContextValue>({ layout: \"table\", columns: [] })\n\ninterface TableColumnScopeValue {\n align?: \"start\" | \"end\"\n priority?: TableColumnPriority\n}\n\nconst TableColumnScopeContext = createContext<TableColumnScopeValue>({})\n\n/**\n * The classes that hide a cell of a column with a priority, on its head and on every cell, so\n * the column drops out whole. `Table` drops its track from the grid at the same widths.\n */\nexport const tableColumnPriorityClasses: Record<TableColumnPriority, string> = {\n medium: \"@max-2xl:hidden\",\n low: \"@max-4xl:hidden\",\n lowest: \"@max-6xl:hidden\",\n}\n\nfunction formatColumnTemplate(columns: TableColumn[], hidden: TableColumnPriority[]) {\n return columns\n .filter(column => !column.priority || !hidden.includes(column.priority))\n .map(column => column.width)\n .join(\" \")\n}\n\nconst ROW_GRID_CLASSES = \"col-span-full grid grid-cols-subgrid\"\n\nconst tableVariants = variants({\n slots: {\n container: \"@container relative\",\n table: [\n \"grid w-full text-control text-ink\",\n \"grid-cols-(--table-columns) @2xl:grid-cols-(--table-columns-md) @4xl:grid-cols-(--table-columns-lg) @6xl:grid-cols-(--table-columns-xl)\",\n // A sticky header pushes the sticky group headings down by its own height.\n \"has-[>[data-sticky]]:[--table-header-height:--spacing(10)]\",\n ],\n },\n\n variants: {\n variant: {\n // The card surface, its edge drawn by the wrapper so the rows' fills stay inside it.\n card: { container: \"overflow-clip rounded-lg border bg-surface shadow-card\" },\n // No surface, for a table inside another card or a dialog.\n flush: {},\n },\n },\n\n defaultVariants: {\n variant: \"card\",\n },\n})\n\nconst tableRowVariants = variants({\n base: [\n ROW_GRID_CLASSES,\n \"group/row relative items-center border-t border-edge-subtle\",\n // Only a row that opens something answers the pointer. The hover and focus fills leave out a\n // pressed link: they match with the same weight as the press fill and come later in the\n // stylesheet, so they would hide it.\n \"has-[[data-row-link]:not(:active)]:hover:bg-canvas has-[[data-row-link]:focus-visible:not(:active)]:bg-canvas\",\n rowPressClasses,\n \"data-selected:bg-fill-subtle data-selected:hover:bg-fill-subtle\",\n // The cell holding the row link sits on a layer above its neighbours. A faded cell is a\n // stacking context of its own, and a later one would otherwise paint over the link's box.\n // A grid item takes `z-index` without being positioned, so the link still fills the row.\n \"*:has-[[data-row-link]]:z-1\",\n // An archived or blocked record fades, all but its menu. A cell holding a control above the\n // row link (the checkbox, a copy button) fades its content instead: faded whole, it would be\n // a stacking context under the link's layer, and the control could not be clicked.\n \"data-inactive:*:not-data-[slot=actions]:not-data-[slot=checkbox]:not-data-[slot=mono]:opacity-50\",\n ],\n\n variants: {\n size: {\n /** 32px, for a feed or a dense list. */\n compact: \"h-8\",\n /** 44px, a one-line row. */\n default: \"h-11\",\n /** 52px, for a two-line name cell. */\n identity: \"h-13\",\n },\n },\n\n defaultVariants: {\n size: \"default\",\n },\n})\n\nconst tableCellVariants = variants({\n base: [\n \"flex min-w-0 items-center gap-2 px-2 first:pl-5 last:pr-5\",\n // The trailing inset goes to the last cell still shown: a hidden cell after it stays the\n // `:last-child`. Below 1152px that is a cell followed only by `lowest` ones, below 896px one\n // followed only by `low` and `lowest` ones, below 672px one followed only by cells with a\n // priority.\n \"@max-6xl:[&:not(:has(~:not([data-priority=lowest])))]:pr-5\",\n \"@max-4xl:[&:not(:has(~:not([data-priority=low]):not([data-priority=lowest])))]:pr-5\",\n \"@max-2xl:[&:not(:has(~:not([data-priority])))]:pr-5\",\n ],\n\n variants: {\n align: {\n start: \"justify-start text-left\",\n end: \"justify-end text-right\",\n },\n priority: tableColumnPriorityClasses,\n },\n\n defaultVariants: {\n align: \"start\",\n },\n})\n\ntype TableCellVariantProps = VariantProps<typeof tableCellVariants>\n\n/** Varied widths for a skeleton row's first line, so a stack of them does not read as stripes. */\nconst SKELETON_NAME_WIDTHS = [\"w-36\", \"w-28\", \"w-40\", \"w-32\", \"w-24\"]\n\nconst MESSAGE_ICONS = {\n filtered: <FilterIcon />,\n error: <AlertIcon />,\n}\n\nexport interface TableProps\n extends Omit<ComponentProps<\"table\">, \"children\">, VariantProps<typeof tableVariants> {\n /** Every column in order, the same list the head and the cells of each row follow. */\n columns: TableColumn[]\n /**\n * `list` draws the same rows with no column names, for a list of records (members, API keys):\n * the rows are list items rather than table rows.\n */\n layout?: TableLayout\n /** The band under the rows: `Pagination` or `PaginationInfinite`. */\n footer?: ReactNode\n /** Classes for the box around the table: the card, or the bare wrapper of a flush table. */\n containerClassName?: string\n children?: ReactNode\n}\n\n/**\n * A table on a CSS grid. The root sets one grid template from `columns`, and the header and\n * every row take it as a subgrid, so the columns line up however the rows are grouped. A row\n * stays a positioned box, which a real table row is not in Safari, so a stretched link can\n * fill it (`TableRowLink`). Columns with a `priority` drop out as the table's own box narrows.\n * Set `--table-sticky-top` on it when a sticky header must clear a bar pinned above it.\n */\nexport function Table({\n columns,\n layout = \"table\",\n variant,\n footer,\n className,\n containerClassName,\n style,\n children,\n ...props\n}: TableProps) {\n const styles = tableVariants({ variant })\n const template = {\n \"--table-columns\": formatColumnTemplate(columns, [\"medium\", \"low\", \"lowest\"]),\n \"--table-columns-md\": formatColumnTemplate(columns, [\"low\", \"lowest\"]),\n \"--table-columns-lg\": formatColumnTemplate(columns, [\"lowest\"]),\n \"--table-columns-xl\": formatColumnTemplate(columns, []),\n ...style,\n } as CSSProperties\n const Root = layout === \"list\" ? \"div\" : \"table\"\n\n return (\n <TableContext value={{ layout, columns }}>\n <div className={styles.container({ className: containerClassName })}>\n <Root\n role={layout === \"list\" ? \"list\" : \"table\"}\n className={styles.table({ className })}\n style={template}\n {...props}\n >\n {children}\n </Root>\n {footer}\n </div>\n </TableContext>\n )\n}\n\ninterface TableHeaderProps extends ComponentProps<\"thead\"> {\n /** Keeps the column names in view while the rows scroll under them. */\n sticky?: boolean\n}\n\n/**\n * The row of column names: 40px, on the surface, with one line under it in the card's edge\n * colour. The first row draws no line of its own, so the two never stack. A list has none, and\n * renders nothing for one.\n */\nexport function TableHeader({ sticky, className, children, ...props }: TableHeaderProps) {\n if (use(TableContext).layout === \"list\") return null\n\n return (\n <thead\n role=\"rowgroup\"\n data-sticky={sticky ? \"\" : undefined}\n className={cn(\n ROW_GRID_CLASSES,\n \"border-b bg-surface\",\n sticky && \"sticky top-(--table-sticky-top,0px) z-20\",\n className,\n )}\n {...props}\n >\n {/* The rule reads a header row as interactive; the role restores what `display: grid` drops. */}\n {/* oxlint-disable-next-line jsx-a11y/no-interactive-element-to-noninteractive-role */}\n <tr role=\"row\" className={cn(ROW_GRID_CLASSES, \"h-10 items-center\")}>\n {children}\n </tr>\n </thead>\n )\n}\n\n/**\n * The rows. A table cut into runs (days, workspaces) takes one body per run, each opening with\n * its `TableGroupHeader`, so the heading sticks while its own rows are in view.\n */\nexport function TableBody({ className, ...props }: ComponentProps<\"tbody\">) {\n const { layout } = use(TableContext)\n const Body = layout === \"list\" ? \"div\" : \"tbody\"\n\n return (\n <Body\n role={layout === \"list\" ? \"presentation\" : \"rowgroup\"}\n className={cn(\n ROW_GRID_CLASSES,\n // The first row of the table sits under the header's line, or the card's edge.\n \"[&:first-of-type>:first-child]:border-t-0\",\n className,\n )}\n {...props}\n />\n )\n}\n\nexport interface TableRowProps extends ComponentProps<\"tr\">, VariantProps<typeof tableRowVariants> {\n selected?: boolean\n /** Dims the row's cells, for a record that is archived or blocked. */\n inactive?: boolean\n}\n\n/**\n * One record. A row whose name is a `TableRowLink` opens it from anywhere on the row and takes\n * the hover fill; a row without one keeps its background under the pointer.\n */\nexport function TableRow({ size, selected, inactive, className, ...props }: TableRowProps) {\n const { layout } = use(TableContext)\n const Row = layout === \"list\" ? \"div\" : \"tr\"\n\n return (\n <Row\n role={layout === \"list\" ? \"listitem\" : \"row\"}\n data-selected={selected ? \"\" : undefined}\n data-inactive={inactive ? \"\" : undefined}\n className={tableRowVariants({ size, className })}\n {...props}\n />\n )\n}\n\nexport interface TableHeadProps extends Omit<ComponentProps<\"th\">, \"align\">, TableCellVariantProps {\n /** The order the table is in by this column. Left out for a column that does not sort. */\n sort?: \"ascending\" | \"descending\" | \"none\"\n /** Turns the name into a button that sorts by the column. */\n onSort?: () => void\n}\n\n/**\n * A column name, in the control weight. A sortable column is a button, with the arrow of its\n * order while the table is sorted by it; unsorted, it looks like any other name.\n */\nexport function TableHead({\n align,\n priority,\n sort,\n onSort,\n className,\n children,\n ...props\n}: TableHeadProps) {\n const sorted = sort === \"ascending\" || sort === \"descending\"\n const Arrow = sort === \"ascending\" ? ArrowUpIcon : ArrowDownIcon\n\n return (\n <th\n role=\"columnheader\"\n scope=\"col\"\n data-priority={priority}\n aria-sort={sort}\n className={tableCellVariants({\n align,\n priority,\n className: cn(\"gap-1 font-medium text-control text-ink\", className),\n })}\n {...props}\n >\n {onSort ? (\n <button\n type=\"button\"\n className=\"inline-flex min-w-0 cursor-pointer items-center gap-1 rounded-xs hover:text-ink-secondary\"\n onClick={onSort}\n >\n <span className=\"truncate\">{children}</span>\n {sorted && <Arrow className=\"size-3 shrink-0\" />}\n </button>\n ) : (\n children\n )}\n </th>\n )\n}\n\nexport interface TableCellProps\n extends Omit<ComponentProps<\"td\">, \"align\">, TableCellVariantProps {}\n\n/**\n * One cell, the Text type: a line of ink that ends in an ellipsis. Every other cell type is\n * built on it. Give it the `align` and `priority` of its column's head.\n */\nexport function TableCell({ align, priority, className, children, ...props }: TableCellProps) {\n const { layout } = use(TableContext)\n const scope = use(TableColumnScopeContext)\n const columnPriority = priority ?? scope.priority\n const Cell = layout === \"list\" ? \"div\" : \"td\"\n const text = typeof children === \"string\" || typeof children === \"number\"\n\n return (\n <Cell\n role={layout === \"list\" ? undefined : \"cell\"}\n data-priority={columnPriority}\n className={tableCellVariants({\n align: align ?? scope.align,\n priority: columnPriority,\n className,\n })}\n {...props}\n >\n {text ? <span className=\"truncate\">{children}</span> : children}\n </Cell>\n )\n}\n\ninterface TableColumnScopeProps extends TableColumnScopeValue {\n children?: ReactNode\n}\n\n/**\n * Hands the cells inside it their column's `align` and `priority`, for a cell rendered by code\n * that knows nothing of its column (a `DataTable` column's `cell`). A cell's own props win.\n */\nexport function TableColumnScope({ align, priority, children }: TableColumnScopeProps) {\n return <TableColumnScopeContext value={{ align, priority }}>{children}</TableColumnScopeContext>\n}\n\n/**\n * The record's name as a link that covers the whole row: its box stretches over the row, and\n * the focus ring is drawn round the row. The checkbox, the menu and any other link in the row\n * sit above it (`relative z-10`, as the checkbox and actions cells do), so each keeps its own\n * click. Pass `render` for a router's link.\n */\nexport function TableRowLink({ render, className, ...props }: useRender.ComponentProps<\"a\">) {\n return useRender({\n render,\n defaultTagName: \"a\",\n props: {\n \"data-row-link\": \"\",\n \"data-press-target\": \"\",\n className: cn(\n \"truncate outline-none after:absolute after:inset-0\",\n \"focus-visible:after:outline-2 focus-visible:after:-outline-offset-2 focus-visible:after:outline-focus\",\n className,\n ),\n ...props,\n },\n })\n}\n\ninterface TableIdentityCellProps extends Omit<TableCellProps, \"title\"> {\n /** A favicon, an avatar or a letter tile, sized 28px (`size-7`) by the caller. */\n leading?: ReactNode\n /** The record's name, usually a `TableRowLink`. */\n title: ReactNode\n /** One muted line under the name: a domain, an email. */\n detail?: ReactNode\n /** A flag or a badge after the name. */\n extras?: ReactNode\n}\n\n/** The name column: the leading mark, the name in the control weight and a muted line. */\nexport function TableIdentityCell({\n leading,\n title,\n detail,\n extras,\n className,\n ...props\n}: TableIdentityCellProps) {\n return (\n <TableCell className={cn(\"gap-3\", className)} {...props}>\n {leading && <span className=\"flex shrink-0\">{leading}</span>}\n <span className=\"flex min-w-0 flex-col gap-0.5\">\n <span className=\"flex min-w-0 items-center gap-1.5\">\n <span className=\"min-w-0 truncate font-medium\">{title}</span>\n {extras && <span className=\"flex shrink-0 items-center gap-1.5\">{extras}</span>}\n </span>\n {detail && <span className=\"truncate text-ink-muted text-xs\">{detail}</span>}\n </span>\n </TableCell>\n )\n}\n\n/**\n * A figure, Number or Money: end-aligned in tabular figures. The caller formats the value, a\n * sum of money with its currency.\n */\nexport function TableNumberCell({ align, className, ...props }: TableCellProps) {\n const scope = use(TableColumnScopeContext)\n\n return (\n <TableCell\n align={align ?? scope.align ?? \"end\"}\n className={cn(\"tabular-nums\", className)}\n {...props}\n />\n )\n}\n\n/** A date, muted: pass a `RelativeTime`, which keeps the exact moment for its tooltip. */\nexport function TableDateCell({ className, ...props }: TableCellProps) {\n return <TableCell className={cn(\"text-ink-muted tabular-nums\", className)} {...props} />\n}\n\n/** A status: pass one `Badge`. */\nexport function TableBadgeCell(props: TableCellProps) {\n return <TableCell {...props} />\n}\n\ninterface TableTagsCellProps extends Omit<TableCellProps, \"children\"> {\n /** One `Badge` per tag. */\n tags: ReactNode[]\n /** How many show before the rest fold into \"+N\". */\n max?: number\n}\n\n/** Tags: the first two, then a count of the rest. */\nexport function TableTagsCell({ tags, max = 2, className, ...props }: TableTagsCellProps) {\n const rest = tags.length - max\n\n return (\n <TableCell className={cn(\"gap-1\", className)} {...props}>\n {Children.toArray(tags.slice(0, max))}\n {rest > 0 && <span className=\"shrink-0 text-ink-muted text-xs tabular-nums\">+{rest}</span>}\n </TableCell>\n )\n}\n\ninterface TableSparklineCellProps extends Omit<TableCellProps, \"children\"> {\n data: number[]\n}\n\n/** A trend: a `Sparkline` across the cell, 32px tall. */\nexport function TableSparklineCell({ data, ...props }: TableSparklineCellProps) {\n return (\n <TableCell {...props}>\n <Sparkline data={data} className=\"h-8 w-full\" />\n </TableCell>\n )\n}\n\nconst METER_TONES = {\n neutral: { bar: \"bg-ink\", ring: \"stroke-ink\" },\n brand: { bar: \"bg-brand\", ring: \"stroke-brand\" },\n warning: { bar: \"bg-warning\", ring: \"stroke-warning\" },\n danger: { bar: \"bg-danger\", ring: \"stroke-danger\" },\n}\n\n/** The ring's radius in its 16px box, and the length of its circle. */\nconst RING_RADIUS = 6\nconst RING_LENGTH = 2 * Math.PI * RING_RADIUS\n\ninterface TableMeterCellProps extends Omit<TableCellProps, \"children\"> {\n value: number\n max: number\n /** The usage as text, formatted by the caller: \"8,240 of 10,000\". */\n label?: ReactNode\n /**\n * The meter's colour, for a meter whose state the app knows better than the share does (a\n * usage lock, a failed job). Left out, it is ink and turns warning past 90%.\n */\n tone?: keyof typeof METER_TONES\n /**\n * `bar` puts a 48px bar before a muted figure. `ring` puts a 14px ring before the figure in the\n * cell's own text, for a narrow column whose figure needs the room (\"35.5k of 657.2k rows\").\n */\n layout?: \"bar\" | \"ring\"\n}\n\n/** Usage against a limit: a bar or a ring, then the figure. It turns warning past 90%. */\nexport function TableMeterCell({\n value,\n max,\n label,\n tone,\n layout = \"bar\",\n className,\n ...props\n}: TableMeterCellProps) {\n const share = max > 0 ? Math.min(value / max, 1) : 0\n const tones = METER_TONES[tone ?? (share > 0.9 ? \"warning\" : \"neutral\")]\n const ring = layout === \"ring\"\n\n return (\n <TableCell className={cn(ring ? \"gap-1.5\" : \"gap-2\", className)} {...props}>\n <span\n // A native `<meter>` draws its own bar, which the theme's tokens cannot reach.\n // oxlint-disable-next-line jsx-a11y/prefer-tag-over-role\n role=\"meter\"\n aria-valuenow={value}\n aria-valuemin={0}\n aria-valuemax={max}\n aria-label={typeof label === \"string\" ? label : undefined}\n className={cn(\n \"shrink-0\",\n ring ? \"flex size-3.5\" : \"h-1 w-12 overflow-hidden rounded-full bg-fill\",\n )}\n >\n {ring ? (\n <svg aria-hidden viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-full -rotate-90\">\n <circle\n cx=\"8\"\n cy=\"8\"\n r={RING_RADIUS}\n strokeWidth=\"2.5\"\n className=\"stroke-fill-strong\"\n />\n {share > 0 && (\n <circle\n cx=\"8\"\n cy=\"8\"\n r={RING_RADIUS}\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeDasharray={`${share * RING_LENGTH} ${RING_LENGTH}`}\n className={tones.ring}\n />\n )}\n </svg>\n ) : (\n <span\n className={cn(\"block h-full rounded-full\", tones.bar)}\n style={{ width: `${share * 100}%` }}\n />\n )}\n </span>\n {label && (\n <span className={cn(\"truncate tabular-nums\", !ring && \"text-ink-muted text-xs\")}>\n {label}\n </span>\n )}\n </TableCell>\n )\n}\n\ninterface TableCountryCellProps extends Omit<TableCellProps, \"children\"> {\n /** The country's flag. */\n flag: ReactNode\n name: ReactNode\n}\n\n/** A country: its flag and its name. */\nexport function TableCountryCell({ flag, name, ...props }: TableCountryCellProps) {\n return (\n <TableCell {...props}>\n <span className=\"flex shrink-0\">{flag}</span>\n <span className=\"truncate\">{name}</span>\n </TableCell>\n )\n}\n\ninterface TableMonoCellProps extends Omit<TableCellProps, \"children\"> {\n value: string\n /** Adds a copy button after the value. */\n copy?: boolean\n}\n\n/** A machine string (a key, an id) in mono, with a copy button that sits above the row link. */\nexport function TableMonoCell({ value, copy, className, ...props }: TableMonoCellProps) {\n return (\n <TableCell data-slot=\"mono\" className={cn(\"gap-1\", className)} {...props}>\n <span className=\"truncate font-mono text-ink-secondary text-xs in-data-inactive:opacity-50\">\n {value}\n </span>\n {copy && (\n <CopyButton\n value={value}\n variant=\"ghost\"\n size=\"xs\"\n className=\"relative z-10 in-data-inactive:opacity-50\"\n />\n )}\n </TableCell>\n )\n}\n\ninterface TablePersonCellProps extends Omit<TableCellProps, \"children\"> {\n /** An avatar, sized 20px (`size-5`) by the caller. */\n avatar?: ReactNode\n name: ReactNode\n}\n\n/** A person on one line: a 20px avatar and the name. */\nexport function TablePersonCell({ avatar, name, ...props }: TablePersonCellProps) {\n return (\n <TableCell {...props}>\n {avatar && <span className=\"flex shrink-0\">{avatar}</span>}\n <span className=\"truncate\">{name}</span>\n </TableCell>\n )\n}\n\n/**\n * The row's menu, end-aligned above the row link. It shows on hover, on keyboard focus, while\n * open, and always on a touch screen, which has no hover to give.\n */\nexport function TableActionsCell({ align, className, children, ...props }: TableCellProps) {\n const scope = use(TableColumnScopeContext)\n\n return (\n <TableCell\n data-slot=\"actions\"\n align={align ?? scope.align ?? \"end\"}\n className={className}\n {...props}\n >\n <span\n className={cn(\n \"relative z-10 flex\",\n \"opacity-0 group-hover/row:opacity-100 focus-within:opacity-100 has-data-popup-open:opacity-100 pointer-coarse:opacity-100\",\n )}\n >\n {children}\n </span>\n </TableCell>\n )\n}\n\ninterface TableActionsMenuProps {\n /** Names the menu and its trigger for a screen reader: \"Actions for figma.com\". */\n label: string\n /** Classes for the trigger, e.g. its place on a card. */\n className?: string\n children: ReactNode\n}\n\n/**\n * The row's \"…\" menu, for a `TableActionsCell`: `ActionsMenu` at its `row` placement, a quiet\n * ghost trigger that grows to finger size on a touch screen, and a menu aligned to the row's end.\n */\nexport function TableActionsMenu(props: TableActionsMenuProps) {\n return <ActionsMenu placement=\"row\" {...props} />\n}\n\ninterface TableCheckboxCellProps\n extends\n Omit<TableCellProps, \"children\" | \"onChange\">,\n Pick<\n ComponentProps<typeof Checkbox>,\n \"checked\" | \"indeterminate\" | \"disabled\" | \"onCheckedChange\"\n > {\n /** Names the checkbox: \"Select openalternative.com\", \"Select all\". */\n label: string\n /** Renders a head cell for the header row: the select-all box. Ignored in a list. */\n header?: boolean\n}\n\n/** Selects the row, or every row on the page in the header. */\nexport function TableCheckboxCell({\n label,\n header: headerProp,\n checked,\n indeterminate,\n disabled,\n onCheckedChange,\n className,\n ...props\n}: TableCheckboxCellProps) {\n // A list has no header row, so a header box there renders as a plain cell.\n const { layout } = use(TableContext)\n const header = headerProp && layout === \"table\"\n const box = (\n <Checkbox\n aria-label={label}\n checked={checked}\n indeterminate={indeterminate}\n disabled={disabled}\n className=\"relative z-10 in-data-inactive:opacity-50\"\n onCheckedChange={onCheckedChange}\n />\n )\n const classes = cn(\"pr-0 first:pl-4\", className)\n\n if (header) {\n const { align, priority, ...headProps } = props\n return (\n <th\n role=\"columnheader\"\n scope=\"col\"\n data-slot=\"checkbox\"\n className={tableCellVariants({ align, priority, className: classes })}\n {...headProps}\n >\n {box}\n </th>\n )\n }\n\n return (\n <TableCell data-slot=\"checkbox\" className={classes} {...props}>\n {box}\n </TableCell>\n )\n}\n\ninterface TableGroupHeaderProps extends ComponentProps<\"tr\"> {}\n\n/**\n * A heading row for the run of rows under it: a day of a feed, a workspace of a list. It sticks\n * under the header while its own body is in view, and the next one pushes it out. Opaque, so the\n * rows slide under it.\n */\nexport function TableGroupHeader({ className, children, ...props }: TableGroupHeaderProps) {\n const { layout } = use(TableContext)\n const list = layout === \"list\"\n const Row = list ? \"div\" : \"tr\"\n const Heading = list ? \"div\" : \"th\"\n\n return (\n <Row\n role={list ? \"listitem\" : \"row\"}\n className={cn(\n ROW_GRID_CLASSES,\n // Above the controls of the rows sliding under it (`z-10`), below a sticky header (`z-20`).\n \"sticky top-[calc(var(--table-sticky-top,0px)+var(--table-header-height,0px))] z-15\",\n \"h-7 border-t border-edge-subtle bg-fill-subtle\",\n className,\n )}\n {...props}\n >\n <Heading\n role={list ? \"heading\" : \"rowheader\"}\n aria-level={list ? 3 : undefined}\n scope={list ? undefined : \"rowgroup\"}\n className=\"col-span-full flex items-center px-5 text-left font-medium text-ink-secondary text-xs\"\n >\n {children}\n </Heading>\n </Row>\n )\n}\n\ninterface TableSkeletonRowProps extends VariantProps<typeof tableRowVariants> {\n /** The row's place in the stack, which picks the width of its first line. */\n index?: number\n}\n\n/**\n * A loading row the size of the rows it stands in for, one stand-in per column of the table.\n * Put five in the body on a first load; while a later page loads, keep the old rows and dim them.\n */\nexport function TableSkeletonRow({ size, index = 0 }: TableSkeletonRowProps) {\n const { columns } = use(TableContext)\n const nameWidth = SKELETON_NAME_WIDTHS[index % SKELETON_NAME_WIDTHS.length]\n // The first column that draws a stand-in, past a leading checkbox.\n const nameColumn = columns.findIndex(column => column.skeleton !== false)\n\n return (\n <TableRow size={size} aria-hidden>\n {columns.map((column, position) => (\n <TableCell\n // oxlint-disable-next-line react/no-array-index-key\n key={position}\n align={column.align}\n priority={column.priority}\n className=\"gap-2\"\n >\n {column.skeleton === false ? null : position === nameColumn && size === \"identity\" ? (\n <>\n <Skeleton className=\"size-7 shrink-0 rounded-md\" />\n <span className=\"flex flex-col gap-1.5\">\n <Skeleton className={cn(\"h-3\", nameWidth)} />\n <Skeleton className=\"h-2.5 w-24\" />\n </span>\n </>\n ) : (\n <Skeleton className={cn(\"h-3\", position === nameColumn ? nameWidth : \"w-16\")} />\n )}\n </TableCell>\n ))}\n </TableRow>\n )\n}\n\ninterface TableMessageProps {\n /**\n * `empty`: nothing exists yet, with the create action. `filtered`: nothing matches, with a way\n * to clear the filters. `error`: the load failed, with a retry.\n */\n kind: \"empty\" | \"filtered\" | \"error\"\n /** Required for `empty`; `filtered` and `error` draw a filter and an alert by default. */\n icon?: ReactNode\n title: ReactNode\n description?: ReactNode\n /** The message's button. Left out, an `error` with `onRetry` draws the retry button. */\n action?: ReactNode\n /** Loads the rows again, from the \"Try again\" button of an `error`. */\n onRetry?: () => void\n /** The retry button's label. */\n retryLabel?: ReactNode\n}\n\n/**\n * Stands in for the rows: the small empty state across every column, under the header, which\n * keeps its line. Put it inside `TableBody`.\n */\nexport function TableMessage({\n kind,\n icon,\n title,\n description,\n action,\n onRetry,\n retryLabel = \"Try again\",\n}: TableMessageProps) {\n const { layout } = use(TableContext)\n const list = layout === \"list\"\n const Row = list ? \"div\" : \"tr\"\n const Cell = list ? \"div\" : \"td\"\n const retry = kind === \"error\" && onRetry && (\n <Button variant=\"secondary\" size=\"sm\" prefix={<RefreshIcon />} onClick={onRetry}>\n {retryLabel}\n </Button>\n )\n\n return (\n <Row\n role={list ? \"listitem\" : \"row\"}\n data-kind={kind}\n className={cn(ROW_GRID_CLASSES, \"border-t border-edge-subtle\")}\n >\n <Cell role={list ? undefined : \"cell\"} className=\"col-span-full py-5\">\n <EmptyState\n size=\"sm\"\n role={kind === \"error\" ? \"alert\" : undefined}\n icon={icon ?? (kind === \"empty\" ? undefined : MESSAGE_ICONS[kind])}\n title={title}\n description={description}\n action={action ?? retry}\n />\n </Cell>\n </Row>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmDA,MAAM,eAAe,cAAiC;CAAE,QAA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CAC3B,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,QAAQ,SAAS,WAAW,WAChC,oBAAC,QAAD;EAAQ,SAAQ;EAAY,MAAK;EAAK,QAAQ,oBAAC,aAAD,CAAc,CAAA;EAAG,SAAS;EACrE,UAAA;CACK,CAAA;CAGV,OACE,oBAAC,KAAD;EACE,MAAM,OAAO,aAAa;EAC1B,aAAW;EACX,WAAW,GAAG,kBAAkB,6BAA6B;EAE7D,UAAA,oBAAC,MAAD;GAAM,MAAM,OAAO,KAAA,IAAY;GAAQ,WAAU;GAC/C,UAAA,oBAAC,YAAD;IACE,MAAK;IACL,MAAM,SAAS,UAAU,UAAU,KAAA;IACnC,MAAM,SAAS,SAAS,UAAU,KAAA,IAAY,cAAc;IACrD;IACM;IACb,QAAQ,UAAU;GACnB,CAAA;EACG,CAAA;CACH,CAAA;AAET"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { DataTableChangeOptions, DataTableSort, DataTableState } from "./data-table-types.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
/**
|
|
4
|
+
* The bridge between a `DataTable`'s state and the URL's search params, with plain objects in
|
|
5
|
+
* and out, so any router can carry it: `@underpin/ui/router` wires it to TanStack Router, and a
|
|
6
|
+
* Next.js app hands the same objects to nuqs. One `createDataTableSearch` call holds the param
|
|
7
|
+
* names, the page sizes and the defaults, so the schema, the read and the write never disagree.
|
|
8
|
+
* The URL holds only what differs from the default: page 1, the default page size and sort, and
|
|
9
|
+
* an empty search stay out of it.
|
|
10
|
+
*/
|
|
11
|
+
/** The table fields the URL carries, each under a param named after it unless `keys` renames it. */
|
|
12
|
+
type DataTableSearchField = "page" | "perPage" | "sort" | "order" | "query";
|
|
13
|
+
/** New names for the params, e.g. `{ query: "search" }` for a list whose links use `?search=`. */
|
|
14
|
+
export type DataTableSearchKeys = Partial<Record<DataTableSearchField, string>>;
|
|
15
|
+
/** The name a field's param takes under `Keys`. */
|
|
16
|
+
type DataTableSearchKey<Keys extends DataTableSearchKeys, Field extends DataTableSearchField> = Keys[Field] extends string ? Keys[Field] : Field;
|
|
17
|
+
/** A route's search params as the helpers take them: the table's, under any names, and more. */
|
|
18
|
+
type SearchParams = Record<string, unknown>;
|
|
19
|
+
declare function createFieldShape(perPageOptions: readonly number[]): {
|
|
20
|
+
page: z.ZodCatch<z.ZodOptional<z.ZodCoercedNumber<unknown>>>;
|
|
21
|
+
perPage: z.ZodCatch<z.ZodOptional<z.ZodCoercedNumber<unknown>>>;
|
|
22
|
+
sort: z.ZodCatch<z.ZodPreprocess<z.ZodOptional<z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>, z.ZodTransform<string, string | number | boolean>>>, unknown>>;
|
|
23
|
+
order: z.ZodCatch<z.ZodOptional<z.ZodEnum<{
|
|
24
|
+
asc: "asc";
|
|
25
|
+
desc: "desc";
|
|
26
|
+
}>>>;
|
|
27
|
+
query: z.ZodCatch<z.ZodPreprocess<z.ZodOptional<z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>, z.ZodTransform<string, string | number | boolean>>>, unknown>>;
|
|
28
|
+
};
|
|
29
|
+
type DataTableSearchShape<Keys extends DataTableSearchKeys> = { [Field in DataTableSearchField as DataTableSearchKey<Keys, Field>]: ReturnType<typeof createFieldShape>[Field]; };
|
|
30
|
+
export interface DataTableSearchOptions<Keys extends DataTableSearchKeys> {
|
|
31
|
+
/** New names for the params. */
|
|
32
|
+
keys?: Keys;
|
|
33
|
+
/** The page sizes the reader may pick. Left out, the URL carries no page size. */
|
|
34
|
+
perPageOptions?: readonly number[];
|
|
35
|
+
/** Rows on a page while the URL names no page size. */
|
|
36
|
+
perPage?: number;
|
|
37
|
+
/** The sort while the URL names none. Left out, the server's own order applies. */
|
|
38
|
+
sort?: DataTableSort;
|
|
39
|
+
/**
|
|
40
|
+
* What `write` puts in a param to remove it from the URL: `undefined` (the default) for
|
|
41
|
+
* TanStack Router, which drops an undefined param, and `null` for nuqs, which skips an
|
|
42
|
+
* undefined one and clears a param only on `null`.
|
|
43
|
+
*/
|
|
44
|
+
clearValue?: null;
|
|
45
|
+
/** The chosen values of each filtered field, read from the table's own params. */
|
|
46
|
+
readFilters?: (search: SearchParams) => DataTableState["filters"];
|
|
47
|
+
/**
|
|
48
|
+
* The table's own params for its filters, every one of them present and undefined when it is
|
|
49
|
+
* empty, so the write clears a filter the reader removed. An undefined value becomes
|
|
50
|
+
* `clearValue`.
|
|
51
|
+
*/
|
|
52
|
+
writeFilters?: (filters: NonNullable<DataTableState["filters"]>) => SearchParams;
|
|
53
|
+
}
|
|
54
|
+
/** What `getProps` hands a `DataTable`. */
|
|
55
|
+
export interface DataTableSearchProps {
|
|
56
|
+
state: DataTableState;
|
|
57
|
+
onStateChange: (state: DataTableState, options: DataTableChangeOptions) => void;
|
|
58
|
+
}
|
|
59
|
+
export interface DataTableSearchPropsOptions {
|
|
60
|
+
/** The route's search params. */
|
|
61
|
+
search: SearchParams;
|
|
62
|
+
/** Writes the new search params to the URL. */
|
|
63
|
+
onSearchChange: (search: SearchParams, navigation: DataTableChangeOptions) => void;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* A table's search params, with everything that shapes them given once:
|
|
67
|
+
*
|
|
68
|
+
* - `schema` reads them. Each one the URL leaves out, or names in a form the table cannot read,
|
|
69
|
+
* is the default, so a stale or edited link never fails the route. A number reads from a
|
|
70
|
+
* number or a string. A table's own params (a view, a facet filter) go in with
|
|
71
|
+
* `schema.extend()`.
|
|
72
|
+
* - `read` turns search params, parsed or raw, into the table's state.
|
|
73
|
+
* - `write` turns the state into search params, every key present and `clearValue` when it is
|
|
74
|
+
* the default, so merging the result into the current params clears them. A page size the
|
|
75
|
+
* table does not offer is never written.
|
|
76
|
+
* - `hasUnreadablePage` says when the URL names a page the table cannot read (`?page=1`,
|
|
77
|
+
* `?page=0`, `?page=abc`), so the route redirects and the address shows what the table shows.
|
|
78
|
+
* - `getProps` returns a `DataTable`'s `state` and `onStateChange`. A new page, page size, sort
|
|
79
|
+
* or filter adds a history entry, so Back returns to it. A page the table corrected past the
|
|
80
|
+
* end, and a search typed a key at a time, replace the entry instead.
|
|
81
|
+
*/
|
|
82
|
+
export declare function createDataTableSearch<const Keys extends DataTableSearchKeys = {}>({ keys, perPageOptions, perPage: defaultPerPage, sort: defaultSort, clearValue, readFilters, writeFilters }?: DataTableSearchOptions<Keys>): {
|
|
83
|
+
schema: z.ZodObject<DataTableSearchShape<Keys> extends (infer T) ? { -readonly [P in keyof T]: T[P]; } : never, z.core.$strip>;
|
|
84
|
+
read: (search: SearchParams) => DataTableState;
|
|
85
|
+
write: (state: DataTableState) => SearchParams;
|
|
86
|
+
hasUnreadablePage: (raw: SearchParams) => boolean;
|
|
87
|
+
getProps: ({ search, onSearchChange }: DataTableSearchPropsOptions) => DataTableSearchProps;
|
|
88
|
+
};
|
|
89
|
+
/** What `createDataTableSearch` returns for a table whose params go under `Keys`. */
|
|
90
|
+
export type DataTableSearch<Keys extends DataTableSearchKeys = {}> = ReturnType<typeof createDataTableSearch<Keys>>;
|
|
91
|
+
export {};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// src/lib/data-table-search.ts
|
|
3
|
+
/**
|
|
4
|
+
* A text param. A router that parses search params as JSON (TanStack Router's default) hands a
|
|
5
|
+
* hand-typed `?query=123` or `?query=true` over as a number or a boolean, so each reads back as
|
|
6
|
+
* text. Null is an absent param, as nuqs reports one, so a hand-typed `?query=null` reads as no
|
|
7
|
+
* search. Such a parser also rewrites some text on the way in (`1e3` becomes `1000`); the links
|
|
8
|
+
* the table writes come back exact, since the router quotes text that would parse as JSON.
|
|
9
|
+
*/
|
|
10
|
+
const textParam = z.preprocess((value) => value ?? void 0, z.union([
|
|
11
|
+
z.string(),
|
|
12
|
+
z.number(),
|
|
13
|
+
z.boolean()
|
|
14
|
+
]).transform((value) => String(value)).optional()).catch(void 0);
|
|
15
|
+
function createFieldShape(perPageOptions) {
|
|
16
|
+
return {
|
|
17
|
+
page: z.coerce.number().int().min(2).optional().catch(void 0),
|
|
18
|
+
perPage: z.coerce.number().refine((value) => perPageOptions.includes(value)).optional().catch(void 0),
|
|
19
|
+
sort: textParam,
|
|
20
|
+
order: z.enum(["asc", "desc"]).optional().catch(void 0),
|
|
21
|
+
query: textParam
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The direction the URL names, or the default sort's. A column the reader chose without a
|
|
26
|
+
* direction reads in the default's direction too, so a written sort needs no order beside it.
|
|
27
|
+
*/
|
|
28
|
+
function isDescending(order, sort) {
|
|
29
|
+
if (order) return order === "desc";
|
|
30
|
+
return sort?.desc ?? false;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A table's search params, with everything that shapes them given once:
|
|
34
|
+
*
|
|
35
|
+
* - `schema` reads them. Each one the URL leaves out, or names in a form the table cannot read,
|
|
36
|
+
* is the default, so a stale or edited link never fails the route. A number reads from a
|
|
37
|
+
* number or a string. A table's own params (a view, a facet filter) go in with
|
|
38
|
+
* `schema.extend()`.
|
|
39
|
+
* - `read` turns search params, parsed or raw, into the table's state.
|
|
40
|
+
* - `write` turns the state into search params, every key present and `clearValue` when it is
|
|
41
|
+
* the default, so merging the result into the current params clears them. A page size the
|
|
42
|
+
* table does not offer is never written.
|
|
43
|
+
* - `hasUnreadablePage` says when the URL names a page the table cannot read (`?page=1`,
|
|
44
|
+
* `?page=0`, `?page=abc`), so the route redirects and the address shows what the table shows.
|
|
45
|
+
* - `getProps` returns a `DataTable`'s `state` and `onStateChange`. A new page, page size, sort
|
|
46
|
+
* or filter adds a history entry, so Back returns to it. A page the table corrected past the
|
|
47
|
+
* end, and a search typed a key at a time, replace the entry instead.
|
|
48
|
+
*/
|
|
49
|
+
function createDataTableSearch({ keys, perPageOptions = [], perPage: defaultPerPage, sort: defaultSort, clearValue, readFilters, writeFilters } = {}) {
|
|
50
|
+
const fields = createFieldShape(perPageOptions);
|
|
51
|
+
const fieldSchema = z.object(fields);
|
|
52
|
+
function key(field) {
|
|
53
|
+
return keys?.[field] ?? field;
|
|
54
|
+
}
|
|
55
|
+
const names = Object.keys(fields).map((field) => key(field));
|
|
56
|
+
const repeated = names.find((name, index) => names.indexOf(name) !== index);
|
|
57
|
+
if (repeated) throw new Error(`Two table fields share the search param "${repeated}"`);
|
|
58
|
+
const schema = z.object(Object.fromEntries(Object.entries(fields).map(([field, value]) => [key(field), value])));
|
|
59
|
+
function read(search) {
|
|
60
|
+
const fieldValues = fieldSchema.parse({
|
|
61
|
+
page: search[key("page")],
|
|
62
|
+
perPage: search[key("perPage")],
|
|
63
|
+
sort: search[key("sort")],
|
|
64
|
+
order: search[key("order")],
|
|
65
|
+
query: search[key("query")]
|
|
66
|
+
});
|
|
67
|
+
const id = fieldValues.sort ?? defaultSort?.id;
|
|
68
|
+
return {
|
|
69
|
+
page: fieldValues.page ?? 1,
|
|
70
|
+
perPage: fieldValues.perPage ?? defaultPerPage,
|
|
71
|
+
sort: id === void 0 ? void 0 : {
|
|
72
|
+
id,
|
|
73
|
+
desc: isDescending(fieldValues.order, defaultSort)
|
|
74
|
+
},
|
|
75
|
+
search: fieldValues.query,
|
|
76
|
+
filters: readFilters?.(search)
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function write(state) {
|
|
80
|
+
const { page = 1, perPage, sort, search, filters } = state;
|
|
81
|
+
const defaultDesc = defaultSort?.desc ?? false;
|
|
82
|
+
const direction = sort?.desc ? "desc" : "asc";
|
|
83
|
+
const offered = perPage !== void 0 && perPageOptions.includes(perPage);
|
|
84
|
+
const params = {
|
|
85
|
+
[key("page")]: page > 1 ? page : void 0,
|
|
86
|
+
[key("perPage")]: offered && perPage !== defaultPerPage ? perPage : void 0,
|
|
87
|
+
[key("sort")]: sort && sort.id !== defaultSort?.id ? sort.id : void 0,
|
|
88
|
+
[key("order")]: sort && sort.desc !== defaultDesc ? direction : void 0,
|
|
89
|
+
[key("query")]: search?.trim() ? search : void 0,
|
|
90
|
+
...writeFilters?.(filters ?? {})
|
|
91
|
+
};
|
|
92
|
+
return Object.fromEntries(Object.entries(params).map(([name, value]) => [name, value ?? clearValue]));
|
|
93
|
+
}
|
|
94
|
+
function hasUnreadablePage(raw) {
|
|
95
|
+
const value = raw[key("page")];
|
|
96
|
+
return value !== void 0 && value !== null && fields.page.parse(value) === void 0;
|
|
97
|
+
}
|
|
98
|
+
function getProps({ search, onSearchChange }) {
|
|
99
|
+
const state = read(search);
|
|
100
|
+
return {
|
|
101
|
+
state,
|
|
102
|
+
onStateChange: (next, { replace }) => onSearchChange(write(next), { replace: replace || (next.search ?? "") !== (state.search ?? "") })
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
schema,
|
|
107
|
+
read,
|
|
108
|
+
write,
|
|
109
|
+
hasUnreadablePage,
|
|
110
|
+
getProps
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
export { createDataTableSearch };
|
|
114
|
+
|
|
115
|
+
//# sourceMappingURL=data-table-search.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-table-search.js","names":[],"sources":["../../src/lib/data-table-search.ts"],"sourcesContent":["import { z } from \"zod\"\nimport type { DataTableChangeOptions, DataTableSort, DataTableState } from \"./data-table-types\"\n\n/**\n * The bridge between a `DataTable`'s state and the URL's search params, with plain objects in\n * and out, so any router can carry it: `@underpin/ui/router` wires it to TanStack Router, and a\n * Next.js app hands the same objects to nuqs. One `createDataTableSearch` call holds the param\n * names, the page sizes and the defaults, so the schema, the read and the write never disagree.\n * The URL holds only what differs from the default: page 1, the default page size and sort, and\n * an empty search stay out of it.\n */\n\n/** The table fields the URL carries, each under a param named after it unless `keys` renames it. */\ntype DataTableSearchField = \"page\" | \"perPage\" | \"sort\" | \"order\" | \"query\"\n\n/** New names for the params, e.g. `{ query: \"search\" }` for a list whose links use `?search=`. */\nexport type DataTableSearchKeys = Partial<Record<DataTableSearchField, string>>\n\n/** The name a field's param takes under `Keys`. */\ntype DataTableSearchKey<\n Keys extends DataTableSearchKeys,\n Field extends DataTableSearchField,\n> = Keys[Field] extends string ? Keys[Field] : Field\n\n/** A route's search params as the helpers take them: the table's, under any names, and more. */\ntype SearchParams = Record<string, unknown>\n\n/**\n * A text param. A router that parses search params as JSON (TanStack Router's default) hands a\n * hand-typed `?query=123` or `?query=true` over as a number or a boolean, so each reads back as\n * text. Null is an absent param, as nuqs reports one, so a hand-typed `?query=null` reads as no\n * search. Such a parser also rewrites some text on the way in (`1e3` becomes `1000`); the links\n * the table writes come back exact, since the router quotes text that would parse as JSON.\n */\nconst textParam = z\n .preprocess(\n value => value ?? undefined,\n z\n .union([z.string(), z.number(), z.boolean()])\n .transform(value => String(value))\n .optional(),\n )\n .catch(undefined)\n\nfunction createFieldShape(perPageOptions: readonly number[]) {\n return {\n page: z.coerce.number().int().min(2).optional().catch(undefined),\n perPage: z.coerce\n .number()\n .refine(value => perPageOptions.includes(value))\n .optional()\n .catch(undefined),\n sort: textParam,\n order: z.enum([\"asc\", \"desc\"]).optional().catch(undefined),\n query: textParam,\n }\n}\n\ntype DataTableSearchShape<Keys extends DataTableSearchKeys> = {\n [Field in DataTableSearchField as DataTableSearchKey<Keys, Field>]: ReturnType<\n typeof createFieldShape\n >[Field]\n}\n\nexport interface DataTableSearchOptions<Keys extends DataTableSearchKeys> {\n /** New names for the params. */\n keys?: Keys\n /** The page sizes the reader may pick. Left out, the URL carries no page size. */\n perPageOptions?: readonly number[]\n /** Rows on a page while the URL names no page size. */\n perPage?: number\n /** The sort while the URL names none. Left out, the server's own order applies. */\n sort?: DataTableSort\n /**\n * What `write` puts in a param to remove it from the URL: `undefined` (the default) for\n * TanStack Router, which drops an undefined param, and `null` for nuqs, which skips an\n * undefined one and clears a param only on `null`.\n */\n clearValue?: null\n /** The chosen values of each filtered field, read from the table's own params. */\n readFilters?: (search: SearchParams) => DataTableState[\"filters\"]\n /**\n * The table's own params for its filters, every one of them present and undefined when it is\n * empty, so the write clears a filter the reader removed. An undefined value becomes\n * `clearValue`.\n */\n writeFilters?: (filters: NonNullable<DataTableState[\"filters\"]>) => SearchParams\n}\n\n/** What `getProps` hands a `DataTable`. */\nexport interface DataTableSearchProps {\n state: DataTableState\n onStateChange: (state: DataTableState, options: DataTableChangeOptions) => void\n}\n\nexport interface DataTableSearchPropsOptions {\n /** The route's search params. */\n search: SearchParams\n /** Writes the new search params to the URL. */\n onSearchChange: (search: SearchParams, navigation: DataTableChangeOptions) => void\n}\n\n/**\n * The direction the URL names, or the default sort's. A column the reader chose without a\n * direction reads in the default's direction too, so a written sort needs no order beside it.\n */\nfunction isDescending(order: \"asc\" | \"desc\" | undefined, sort: DataTableSort | undefined) {\n if (order) return order === \"desc\"\n return sort?.desc ?? false\n}\n\n/**\n * A table's search params, with everything that shapes them given once:\n *\n * - `schema` reads them. Each one the URL leaves out, or names in a form the table cannot read,\n * is the default, so a stale or edited link never fails the route. A number reads from a\n * number or a string. A table's own params (a view, a facet filter) go in with\n * `schema.extend()`.\n * - `read` turns search params, parsed or raw, into the table's state.\n * - `write` turns the state into search params, every key present and `clearValue` when it is\n * the default, so merging the result into the current params clears them. A page size the\n * table does not offer is never written.\n * - `hasUnreadablePage` says when the URL names a page the table cannot read (`?page=1`,\n * `?page=0`, `?page=abc`), so the route redirects and the address shows what the table shows.\n * - `getProps` returns a `DataTable`'s `state` and `onStateChange`. A new page, page size, sort\n * or filter adds a history entry, so Back returns to it. A page the table corrected past the\n * end, and a search typed a key at a time, replace the entry instead.\n */\nexport function createDataTableSearch<const Keys extends DataTableSearchKeys = {}>({\n keys,\n perPageOptions = [],\n perPage: defaultPerPage,\n sort: defaultSort,\n clearValue,\n readFilters,\n writeFilters,\n}: DataTableSearchOptions<Keys> = {}) {\n const fields = createFieldShape(perPageOptions)\n const fieldSchema = z.object(fields)\n\n function key(field: DataTableSearchField) {\n return keys?.[field] ?? field\n }\n\n const names = Object.keys(fields).map(field => key(field as DataTableSearchField))\n const repeated = names.find((name, index) => names.indexOf(name) !== index)\n if (repeated) throw new Error(`Two table fields share the search param \"${repeated}\"`)\n\n const schema = z.object(\n Object.fromEntries(\n Object.entries(fields).map(([field, value]) => [key(field as DataTableSearchField), value]),\n ) as DataTableSearchShape<Keys>,\n )\n\n function read(search: SearchParams): DataTableState {\n const fieldValues = fieldSchema.parse({\n page: search[key(\"page\")],\n perPage: search[key(\"perPage\")],\n sort: search[key(\"sort\")],\n order: search[key(\"order\")],\n query: search[key(\"query\")],\n })\n const id = fieldValues.sort ?? defaultSort?.id\n\n return {\n page: fieldValues.page ?? 1,\n perPage: fieldValues.perPage ?? defaultPerPage,\n sort:\n id === undefined ? undefined : { id, desc: isDescending(fieldValues.order, defaultSort) },\n search: fieldValues.query,\n filters: readFilters?.(search),\n }\n }\n\n function write(state: DataTableState): SearchParams {\n const { page = 1, perPage, sort, search, filters } = state\n const defaultDesc = defaultSort?.desc ?? false\n const direction = sort?.desc ? \"desc\" : \"asc\"\n const offered = perPage !== undefined && perPageOptions.includes(perPage)\n const params: SearchParams = {\n [key(\"page\")]: page > 1 ? page : undefined,\n [key(\"perPage\")]: offered && perPage !== defaultPerPage ? perPage : undefined,\n [key(\"sort\")]: sort && sort.id !== defaultSort?.id ? sort.id : undefined,\n [key(\"order\")]: sort && sort.desc !== defaultDesc ? direction : undefined,\n [key(\"query\")]: search?.trim() ? search : undefined,\n ...writeFilters?.(filters ?? {}),\n }\n\n return Object.fromEntries(\n Object.entries(params).map(([name, value]) => [name, value ?? clearValue]),\n )\n }\n\n function hasUnreadablePage(raw: SearchParams) {\n const value = raw[key(\"page\")]\n return value !== undefined && value !== null && fields.page.parse(value) === undefined\n }\n\n function getProps({ search, onSearchChange }: DataTableSearchPropsOptions): DataTableSearchProps {\n const state = read(search)\n\n return {\n state,\n onStateChange: (next, { replace }) =>\n onSearchChange(write(next), {\n replace: replace || (next.search ?? \"\") !== (state.search ?? \"\"),\n }),\n }\n }\n\n return { schema, read, write, hasUnreadablePage, getProps }\n}\n\n/** What `createDataTableSearch` returns for a table whose params go under `Keys`. */\nexport type DataTableSearch<Keys extends DataTableSearchKeys = {}> = ReturnType<\n typeof createDataTableSearch<Keys>\n>\n"],"mappings":";;;;;;;;;AAkCA,MAAM,YAAY,EACf,YACC,UAAS,SAAS,KAAA,GAClB,EACG,MAAM;CAAC,EAAE,OAAO;CAAG,EAAE,OAAO;CAAG,EAAE,QAAQ;AAAC,CAAC,CAAC,CAC5C,WAAU,UAAS,OAAO,KAAK,CAAC,CAAC,CACjC,SAAS,CACd,CAAC,CACA,MAAM,KAAA,CAAS;AAElB,SAAS,iBAAiB,gBAAmC;CAC3D,OAAO;EACL,MAAM,EAAE,OAAO,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,KAAA,CAAS;EAC/D,SAAS,EAAE,OACR,OAAO,CAAC,CACR,QAAO,UAAS,eAAe,SAAS,KAAK,CAAC,CAAC,CAC/C,SAAS,CAAC,CACV,MAAM,KAAA,CAAS;EAClB,MAAM;EACN,OAAO,EAAE,KAAK,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,KAAA,CAAS;EACzD,OAAO;CACT;AACF;;;;;AAkDA,SAAS,aAAa,OAAmC,MAAiC;CACxF,IAAI,OAAO,OAAO,UAAU;CAC5B,OAAO,MAAM,QAAQ;AACvB;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,sBAAmE,EACjF,MACA,iBAAiB,CAAC,GAClB,SAAS,gBACT,MAAM,aACN,YACA,aACA,iBACgC,CAAC,GAAG;CACpC,MAAM,SAAS,iBAAiB,cAAc;CAC9C,MAAM,cAAc,EAAE,OAAO,MAAM;CAEnC,SAAS,IAAI,OAA6B;EACxC,OAAO,OAAO,UAAU;CAC1B;CAEA,MAAM,QAAQ,OAAO,KAAK,MAAM,CAAC,CAAC,KAAI,UAAS,IAA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OAAO,IAAI,QAAQ,KAAK,IAAI,SAAS,KAAA;GAC1C,GAAG,eAAe,WAAW,CAAC,CAAC;EACjC;EAEA,OAAO,OAAO,YACZ,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,MAAM,SAAS,UAAU,CAAC,CAC3E;CACF;CAEA,SAAS,kBAAkB,KAAmB;EAC5C,MAAM,QAAQ,IAAI,IAAI,MAAM;EAC5B,OAAO,UAAU,KAAA,KAAa,UAAU,QAAQ,OAAO,KAAK,MAAM,KAAK,MAAM,KAAA;CAC/E;CAEA,SAAS,SAAS,EAAE,QAAQ,kBAAqE;EAC/F,MAAM,QAAQ,KAAK,MAAM;EAEzB,OAAO;GACL;GACA,gBAAgB,MAAM,EAAE,cACtB,eAAe,MAAM,IAAI,GAAG,EAC1B,SAAS,YAAY,KAAK,UAAU,SAAS,MAAM,UAAU,IAC/D,CAAC;EACL;CACF;CAEA,OAAO;EAAE;EAAQ;EAAM;EAAO;EAAmB;CAAS;AAC5D"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { TableColumnPriority } from "../components/table.js";
|
|
2
|
+
import { DataTableSort, DataTableState } from "./data-table-types.js";
|
|
2
3
|
import { ColumnVisibilityState, RowData } from "@tanstack/react-table";
|
|
3
4
|
/**
|
|
4
5
|
* The model behind `DataTable`: its react-table features, the meta a column carries, and the
|
|
@@ -45,23 +46,6 @@ export declare function createDataTableColumnHelper<TData extends RowData>(): im
|
|
|
45
46
|
columnVisibilityFeature: import("@tanstack/react-table").TableFeature;
|
|
46
47
|
columnMeta: DataTableColumnMeta;
|
|
47
48
|
}, TData>;
|
|
48
|
-
export interface DataTableSort {
|
|
49
|
-
/** The column's id. */
|
|
50
|
-
id: string;
|
|
51
|
-
desc: boolean;
|
|
52
|
-
}
|
|
53
|
-
/** What a table shows, owned by the app. */
|
|
54
|
-
export interface DataTableState {
|
|
55
|
-
/** 1-based. Read by a paged table, left out by one that loads as it scrolls. */
|
|
56
|
-
page?: number;
|
|
57
|
-
/** Rows on a page. Read by a paged table. */
|
|
58
|
-
perPage?: number;
|
|
59
|
-
/** Left out while the server's own order applies, so no column shows an arrow. */
|
|
60
|
-
sort?: DataTableSort;
|
|
61
|
-
search?: string;
|
|
62
|
-
/** The chosen values of each filtered field, by field. */
|
|
63
|
-
filters?: Record<string, string[]>;
|
|
64
|
-
}
|
|
65
49
|
/** The page size of a paged table whose state names none. */
|
|
66
50
|
export declare const DEFAULT_PER_PAGE = 25;
|
|
67
51
|
/**
|
|
@@ -84,4 +68,5 @@ export declare function formatRowSetKey({ page, perPage, sort, search, filters }
|
|
|
84
68
|
/** The columns the reader hid on this table, saved in this browser. Empty when none are. */
|
|
85
69
|
export declare function readColumnVisibility(storageKey: string): ColumnVisibilityState;
|
|
86
70
|
/** Saves the columns the reader hid. A browser that blocks storage keeps them for the visit. */
|
|
87
|
-
export declare function writeColumnVisibility(storageKey: string, visibility: ColumnVisibilityState): void;
|
|
71
|
+
export declare function writeColumnVisibility(storageKey: string, visibility: ColumnVisibilityState): void;
|
|
72
|
+
export type { DataTableSort, DataTableState };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-table-state.js","names":[],"sources":["../../src/lib/data-table-state.ts"],"sourcesContent":["import {\n type ColumnVisibilityState,\n columnVisibilityFeature,\n createColumnHelper,\n metaHelper,\n type RowData,\n rowSelectionFeature,\n rowSortingFeature,\n tableFeatures,\n} from \"@tanstack/react-table\"\nimport type { TableColumnPriority } from \"../components/table\"\n\n/**\n * The model behind `DataTable`: its react-table features, the meta a column carries, and the\n * state the app owns. The package never reads the URL: an app keeps `DataTableState` in its\n * router's search params (TanStack Router, nuqs) and hands it back on every change.\n */\n\n/** What a column tells the table about its own head and cells. */\nexport interface DataTableColumnMeta {\n /** Figures read from the end. */\n align?: \"start\" | \"end\"\n /** The column's grid track: `minmax(0,1fr)` (the default) for the name, `6rem` for a figure. */\n width?: string\n /**\n * Where the column gives way as the table narrows: `medium` below 672px, `low` below 896px,\n * `lowest` below 1152px.\n */\n priority?: TableColumnPriority\n /**\n * Turns the column's name into a button that sorts by it. The first click sorts ascending, or\n * descending for `\"descending\"` (a figure, a date read newest first); the next flips it.\n */\n sortable?: boolean | \"ascending\" | \"descending\"\n /** Whether a skeleton row draws a stand-in here. Off for an actions column. */\n skeleton?: boolean\n /** The column's name in the column picker, for a column whose header is not a string. */\n label?: string\n}\n\n/** The react-table features every `DataTable` registers. */\nexport const DATA_TABLE_FEATURES = tableFeatures({\n rowSortingFeature,\n rowSelectionFeature,\n columnVisibilityFeature,\n columnMeta: metaHelper<DataTableColumnMeta>(),\n})\n\nexport type DataTableFeatures = typeof DATA_TABLE_FEATURES\n\n/**\n * The column helper for a `DataTable` of `TData` rows. A column's `cell` returns one of the\n * table's cell parts (`TableCell`, `TableIdentityCell`, `TableNumberCell`…), which take the\n * column's `align` and `priority` from its meta.\n */\nexport function createDataTableColumnHelper<TData extends RowData>() {\n return createColumnHelper<DataTableFeatures, TData>()\n}\n\
|
|
1
|
+
{"version":3,"file":"data-table-state.js","names":[],"sources":["../../src/lib/data-table-state.ts"],"sourcesContent":["import {\n type ColumnVisibilityState,\n columnVisibilityFeature,\n createColumnHelper,\n metaHelper,\n type RowData,\n rowSelectionFeature,\n rowSortingFeature,\n tableFeatures,\n} from \"@tanstack/react-table\"\nimport type { TableColumnPriority } from \"../components/table\"\nimport type { DataTableSort, DataTableState } from \"./data-table-types\"\n\nexport type { DataTableSort, DataTableState } from \"./data-table-types\"\n\n/**\n * The model behind `DataTable`: its react-table features, the meta a column carries, and the\n * state the app owns. The package never reads the URL: an app keeps `DataTableState` in its\n * router's search params (TanStack Router, nuqs) and hands it back on every change.\n */\n\n/** What a column tells the table about its own head and cells. */\nexport interface DataTableColumnMeta {\n /** Figures read from the end. */\n align?: \"start\" | \"end\"\n /** The column's grid track: `minmax(0,1fr)` (the default) for the name, `6rem` for a figure. */\n width?: string\n /**\n * Where the column gives way as the table narrows: `medium` below 672px, `low` below 896px,\n * `lowest` below 1152px.\n */\n priority?: TableColumnPriority\n /**\n * Turns the column's name into a button that sorts by it. The first click sorts ascending, or\n * descending for `\"descending\"` (a figure, a date read newest first); the next flips it.\n */\n sortable?: boolean | \"ascending\" | \"descending\"\n /** Whether a skeleton row draws a stand-in here. Off for an actions column. */\n skeleton?: boolean\n /** The column's name in the column picker, for a column whose header is not a string. */\n label?: string\n}\n\n/** The react-table features every `DataTable` registers. */\nexport const DATA_TABLE_FEATURES = tableFeatures({\n rowSortingFeature,\n rowSelectionFeature,\n columnVisibilityFeature,\n columnMeta: metaHelper<DataTableColumnMeta>(),\n})\n\nexport type DataTableFeatures = typeof DATA_TABLE_FEATURES\n\n/**\n * The column helper for a `DataTable` of `TData` rows. A column's `cell` returns one of the\n * table's cell parts (`TableCell`, `TableIdentityCell`, `TableNumberCell`…), which take the\n * column's `align` and `priority` from its meta.\n */\nexport function createDataTableColumnHelper<TData extends RowData>() {\n return createColumnHelper<DataTableFeatures, TData>()\n}\n\n/** The page size of a paged table whose state names none. */\nexport const DEFAULT_PER_PAGE = 25\n\nfunction isSameSort(one: DataTableSort | undefined, other: DataTableSort | undefined) {\n return one?.id === other?.id && one?.desc === other?.desc\n}\n\nfunction isSameFilters(one: DataTableState[\"filters\"], other: DataTableState[\"filters\"]) {\n const keys = new Set([...Object.keys(one ?? {}), ...Object.keys(other ?? {})])\n\n return [...keys].every(key => {\n const left = one?.[key] ?? []\n const right = other?.[key] ?? []\n return left.length === right.length && left.every(value => right.includes(value))\n })\n}\n\n/**\n * The state after a change, under the paging rules: a new sort, search, filter or page size\n * starts over on page 1, since the page the reader was on no longer holds the same rows.\n */\nexport function changeDataTableState(\n state: DataTableState,\n change: Partial<DataTableState>,\n): DataTableState {\n const next = { ...state, ...change }\n const restarts =\n (\"sort\" in change && !isSameSort(state.sort, change.sort)) ||\n (\"search\" in change && (state.search ?? \"\") !== (change.search ?? \"\")) ||\n (\"filters\" in change && !isSameFilters(state.filters, change.filters)) ||\n (\"perPage\" in change && state.perPage !== change.perPage)\n\n return restarts ? { ...next, page: 1 } : next\n}\n\n/** How many pages `total` rows fill. An empty table still has its one page. */\nexport function getPageCount(total: number, perPage: number) {\n return Math.max(1, Math.ceil(total / perPage))\n}\n\n/**\n * The page a table shows for the one its state asks for: page 1 for a page before it, the last\n * page for one past the end (a stale link, rows deleted since).\n */\nexport function clampPage(page: number, pageCount: number) {\n return Math.min(Math.max(1, Math.floor(page)), pageCount)\n}\n\n/**\n * A key that changes whenever the rows a table holds stop being the same set: a new page, sort,\n * search or filter. A selection covers one such set.\n */\nexport function formatRowSetKey({ page, perPage, sort, search, filters }: DataTableState) {\n // Sorted, so the same filters in another order make the same key, as `isSameFilters` reads them.\n const filterKey = Object.entries(filters ?? {})\n .filter(([, values]) => values.length > 0)\n .map(([field, values]) => [field, values.toSorted()])\n .toSorted(([one], [other]) => String(one).localeCompare(String(other)))\n\n return JSON.stringify([page, perPage, sort?.id, sort?.desc, search ?? \"\", filterKey])\n}\n\nfunction formatStorageKey(storageKey: string) {\n return `underpin:data-table:${storageKey}:columns`\n}\n\n/** The columns the reader hid on this table, saved in this browser. Empty when none are. */\nexport function readColumnVisibility(storageKey: string): ColumnVisibilityState {\n try {\n const stored: unknown = JSON.parse(localStorage.getItem(formatStorageKey(storageKey)) ?? \"{}\")\n if (typeof stored !== \"object\" || stored === null || Array.isArray(stored)) return {}\n\n return Object.fromEntries(\n Object.entries(stored).filter((entry): entry is [string, boolean] => entry[1] === false),\n )\n } catch {\n return {}\n }\n}\n\n/** Saves the columns the reader hid. A browser that blocks storage keeps them for the visit. */\nexport function writeColumnVisibility(storageKey: string, visibility: ColumnVisibilityState) {\n const hidden = Object.fromEntries(Object.entries(visibility).filter(([, shown]) => !shown))\n\n try {\n localStorage.setItem(formatStorageKey(storageKey), JSON.stringify(hidden))\n } catch {}\n}\n"],"mappings":";;;AA4CA,MAAa,sBAAsB,cAAc;CAC/C;CACA;CACA;CACA,YAAY,WAAgC;AAC9C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5C,QAAQ,GAAG,YAAY,OAAO,SAAS,CAAC,CAAC,CACzC,KAAK,CAAC,OAAO,YAAY,CAAC,OAAO,OAAO,SAAS,CAAC,CAAC,CAAC,CACpD,UAAU,CAAC,MAAM,CAAC,WAAW,OAAO,GAAG,CAAC,CAAC,cAAc,OAAO,KAAK,CAAC,CAAC;CAExE,OAAO,KAAK,UAAU;EAAC;EAAM;EAAS,MAAM;EAAI,MAAM;EAAM,UAAU;EAAI;CAAS,CAAC;AACtF;AAEA,SAAS,iBAAiB,YAAoB;CAC5C,OAAO,uBAAuB,WAAW;AAC3C;;AAGA,SAAgB,qBAAqB,YAA2C;CAC9E,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,aAAa,QAAQ,iBAAiB,UAAU,CAAC,KAAK,IAAI;EAC7F,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,GAAG,OAAO,CAAC;EAEpF,OAAO,OAAO,YACZ,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,UAAsC,MAAM,OAAO,KAAK,CACzF;CACF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;AAGA,SAAgB,sBAAsB,YAAoB,YAAmC;CAC3F,MAAM,SAAS,OAAO,YAAY,OAAO,QAAQ,UAAU,CAAC,CAAC,QAAQ,GAAG,WAAW,CAAC,KAAK,CAAC;CAE1F,IAAI;EACF,aAAa,QAAQ,iBAAiB,UAAU,GAAG,KAAK,UAAU,MAAM,CAAC;CAC3E,QAAQ,CAAC;AACX"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The types a table's state is made of, with no import, so a router adapter that reads only
|
|
3
|
+
* these (`data-table-search`) never pulls in react-table's types.
|
|
4
|
+
*/
|
|
5
|
+
export interface DataTableSort {
|
|
6
|
+
/** The column's id. */
|
|
7
|
+
id: string;
|
|
8
|
+
desc: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** What a table shows, owned by the app. */
|
|
11
|
+
export interface DataTableState {
|
|
12
|
+
/** 1-based. Read by a paged table, left out by one that loads as it scrolls. */
|
|
13
|
+
page?: number;
|
|
14
|
+
/** Rows on a page. Read by a paged table. */
|
|
15
|
+
perPage?: number;
|
|
16
|
+
/** Left out while the server's own order applies, so no column shows an arrow. */
|
|
17
|
+
sort?: DataTableSort;
|
|
18
|
+
search?: string;
|
|
19
|
+
/** The chosen values of each filtered field, by field. */
|
|
20
|
+
filters?: Record<string, string[]>;
|
|
21
|
+
}
|
|
22
|
+
/** How the table hands over a change of its state. */
|
|
23
|
+
export interface DataTableChangeOptions {
|
|
24
|
+
/**
|
|
25
|
+
* True when the table corrects the state itself (a page past the end), so a router adapter
|
|
26
|
+
* replaces the history entry rather than adding one the reader would land back on.
|
|
27
|
+
*/
|
|
28
|
+
replace: boolean;
|
|
29
|
+
}
|
|
File without changes
|