@platned/ui 0.9.2 → 0.9.4

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.
@@ -0,0 +1,832 @@
1
+ import {
2
+ Button,
3
+ Checkbox,
4
+ DropdownMenu,
5
+ DropdownMenuCheckboxItem,
6
+ DropdownMenuContent,
7
+ DropdownMenuLabel,
8
+ DropdownMenuTrigger,
9
+ EmptyState,
10
+ FOCUS_RING,
11
+ FOCUS_RING_INSET,
12
+ PaginationBar,
13
+ SCROLLBAR_CLASSES,
14
+ SearchInput,
15
+ Skeleton,
16
+ TableCellBadge,
17
+ TableCellLeadText,
18
+ TableCellProgress,
19
+ TableCellText,
20
+ TableRow,
21
+ cn,
22
+ devWarn,
23
+ useElementWidth
24
+ } from "./chunk-OGQIGGVB.js";
25
+
26
+ // src/components/lists/data-table.tsx
27
+ import {
28
+ useCallback,
29
+ useEffect,
30
+ useLayoutEffect,
31
+ useMemo,
32
+ useRef,
33
+ useState
34
+ } from "react";
35
+ import clsx from "clsx";
36
+ import {
37
+ flexRender,
38
+ getCoreRowModel,
39
+ getFilteredRowModel,
40
+ getPaginationRowModel,
41
+ getSortedRowModel,
42
+ useReactTable
43
+ } from "@tanstack/react-table";
44
+
45
+ // src/components/lists/data-table-layout.ts
46
+ var DEFAULT_CARD_BREAKPOINT_PX = 560;
47
+ var LAYOUT_HYSTERESIS_PX = 24;
48
+ var FALLBACK_COLUMN_WIDTH_PX = 160;
49
+ function widthToPx(width) {
50
+ if (!width) return FALLBACK_COLUMN_WIDTH_PX;
51
+ const px = /^(\d+(?:\.\d+)?)px$/.exec(width);
52
+ if (px) return Number(px[1]);
53
+ const rem = /^(\d+(?:\.\d+)?)rem$/.exec(width);
54
+ if (rem) return Number(rem[1]) * 16;
55
+ return FALLBACK_COLUMN_WIDTH_PX;
56
+ }
57
+ function nextLayoutMode(current, widthPx, breakpointPx = DEFAULT_CARD_BREAKPOINT_PX) {
58
+ if (widthPx === void 0 || !Number.isFinite(widthPx) || widthPx <= 0) return current;
59
+ if (breakpointPx <= 0) return "table";
60
+ if (current === "table") return widthPx < breakpointPx - LAYOUT_HYSTERESIS_PX ? "cards" : "table";
61
+ return widthPx >= breakpointPx + LAYOUT_HYSTERESIS_PX ? "table" : "cards";
62
+ }
63
+ function cardSlots(columns) {
64
+ const title = columns.find((c) => c.mobile === "title") ?? columns[0];
65
+ const status = columns.find((c) => c.mobile === "status" && c !== title);
66
+ const actions = columns.find((c) => c.mobile === "actions" && c !== title);
67
+ const fields = columns.filter(
68
+ (c) => c !== title && c !== status && c !== actions && c.mobile !== "hidden"
69
+ );
70
+ return { title, status, actions, fields };
71
+ }
72
+
73
+ // src/components/lists/data-table-parts.tsx
74
+ import { ChevronDownIcon, ChevronUpIcon, ChevronsUpDownIcon, Columns3Icon } from "lucide-react";
75
+ import { jsx, jsxs } from "react/jsx-runtime";
76
+ var SELECT_COLUMN_ID = "select";
77
+ function columnLabel(column) {
78
+ const meta = column.columnDef.meta;
79
+ if (meta?.label) return meta.label;
80
+ const header = column.columnDef.header;
81
+ return typeof header === "string" ? header : column.id;
82
+ }
83
+ function DataTableColumnHeader({
84
+ column,
85
+ title,
86
+ className
87
+ }) {
88
+ const text = title ?? columnLabel(column);
89
+ const hidden = column.columnDef.meta?.hideHeader;
90
+ if (!column.getCanSort()) {
91
+ return /* @__PURE__ */ jsx("span", { className: cn(hidden ? "sr-only" : "inline-block w-max whitespace-nowrap", className), children: text });
92
+ }
93
+ const sorted = column.getIsSorted();
94
+ const Icon = sorted === "asc" ? ChevronUpIcon : sorted === "desc" ? ChevronDownIcon : ChevronsUpDownIcon;
95
+ return /* @__PURE__ */ jsxs(
96
+ "button",
97
+ {
98
+ type: "button",
99
+ onClick: column.getToggleSortingHandler(),
100
+ "data-sorted": sorted || void 0,
101
+ className: cn(
102
+ // w-max + nowrap: a header is never truncated; its column widens to fit it instead.
103
+ "inline-flex w-max items-center gap-1 whitespace-nowrap rounded-sm transition-colors hover:text-default",
104
+ "data-[sorted]:text-default",
105
+ FOCUS_RING,
106
+ className
107
+ ),
108
+ children: [
109
+ /* @__PURE__ */ jsx("span", { className: cn(hidden && "sr-only"), children: text }),
110
+ /* @__PURE__ */ jsx(
111
+ Icon,
112
+ {
113
+ "aria-hidden": true,
114
+ "data-sorted": sorted || void 0,
115
+ className: "size-3.5 shrink-0 text-icon-default-secondary data-[sorted]:text-icon-brand"
116
+ }
117
+ )
118
+ ]
119
+ }
120
+ );
121
+ }
122
+ function createSelectColumn(options = {}) {
123
+ const { getRowLabel, selectAllLabel = "Select all rows on this page" } = options;
124
+ return {
125
+ id: SELECT_COLUMN_ID,
126
+ header: ({ table }) => /* @__PURE__ */ jsx(
127
+ Checkbox,
128
+ {
129
+ "aria-label": selectAllLabel,
130
+ checked: table.getIsAllPageRowsSelected(),
131
+ indeterminate: table.getIsSomePageRowsSelected() && !table.getIsAllPageRowsSelected(),
132
+ onCheckedChange: (checked) => table.toggleAllPageRowsSelected(checked)
133
+ }
134
+ ),
135
+ cell: ({ row }) => /* @__PURE__ */ jsx(
136
+ Checkbox,
137
+ {
138
+ "aria-label": getRowLabel ? getRowLabel(row.original) : "Select row",
139
+ checked: row.getIsSelected(),
140
+ disabled: !row.getCanSelect(),
141
+ onCheckedChange: (checked) => row.toggleSelected(checked)
142
+ }
143
+ ),
144
+ enableSorting: false,
145
+ enableHiding: false,
146
+ enableGlobalFilter: false,
147
+ meta: { width: "48px", interactive: true, mobile: "hidden", label: "Select" }
148
+ };
149
+ }
150
+ function DataTableViewOptions({ table, label = "Columns" }) {
151
+ const columns = table.getAllLeafColumns().filter((column) => column.getCanHide());
152
+ if (columns.length === 0) return null;
153
+ return /* @__PURE__ */ jsxs(DropdownMenu, { children: [
154
+ /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "neutral", size: "md", leadingIcon: /* @__PURE__ */ jsx(Columns3Icon, { "aria-hidden": true }), children: label }) }),
155
+ /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", children: [
156
+ /* @__PURE__ */ jsx(DropdownMenuLabel, { children: "Show columns" }),
157
+ columns.map((column) => /* @__PURE__ */ jsx(
158
+ DropdownMenuCheckboxItem,
159
+ {
160
+ checked: column.getIsVisible(),
161
+ onCheckedChange: (visible) => column.toggleVisibility(visible),
162
+ children: columnLabel(column)
163
+ },
164
+ column.id
165
+ ))
166
+ ] })
167
+ ] });
168
+ }
169
+ function DataTablePagination({
170
+ table,
171
+ pageSizeOptions = [10, 20, 50],
172
+ summary
173
+ }) {
174
+ const { pageIndex, pageSize } = table.getState().pagination;
175
+ return /* @__PURE__ */ jsx(
176
+ PaginationBar,
177
+ {
178
+ page: pageIndex + 1,
179
+ pageSize,
180
+ total: table.getRowCount(),
181
+ onPageChange: (page) => table.setPageIndex(page - 1),
182
+ onPageSizeChange: (size) => table.setPageSize(size),
183
+ pageSizeOptions,
184
+ summary,
185
+ label: "Table pages"
186
+ }
187
+ );
188
+ }
189
+
190
+ // src/components/lists/data-table.tsx
191
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
192
+ var DENSITY = {
193
+ default: {
194
+ headerCell: "px-4 py-3",
195
+ headerText: "text-body-xs font-medium text-default-secondary",
196
+ bodyCell: "px-4 py-[14px]"
197
+ },
198
+ compact: {
199
+ headerCell: "px-3 py-2",
200
+ headerText: "text-body-tiny font-semibold uppercase tracking-[0.4px] text-default-secondary",
201
+ bodyCell: "px-3 py-2 text-body-xs text-default"
202
+ }
203
+ };
204
+ var VERTICAL = {
205
+ center: "align-middle",
206
+ top: "align-top"
207
+ };
208
+ var TEXT_ALIGN = {
209
+ start: "text-left",
210
+ center: "text-center",
211
+ end: "text-right"
212
+ };
213
+ var ROW_LINK_ATTR = "data-row-link";
214
+ function resolve(updater, previous) {
215
+ return typeof updater === "function" ? updater(previous) : updater;
216
+ }
217
+ function useTableState(controlled, initial, onChange) {
218
+ const [inner, setInner] = useState(initial);
219
+ const value = controlled ?? inner;
220
+ const latest = useRef(value);
221
+ latest.current = value;
222
+ const isControlled = controlled !== void 0;
223
+ const onChangeRef = useRef(onChange);
224
+ onChangeRef.current = onChange;
225
+ const set = useCallback(
226
+ (updater) => {
227
+ const next = resolve(updater, latest.current);
228
+ if (!isControlled) setInner(next);
229
+ onChangeRef.current?.(next);
230
+ },
231
+ [isControlled]
232
+ );
233
+ return [value, set];
234
+ }
235
+ function CellInteractionGuard({ children }) {
236
+ return (
237
+ // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
238
+ /* @__PURE__ */ jsx2(
239
+ "div",
240
+ {
241
+ className: "contents",
242
+ onClick: (event) => event.stopPropagation(),
243
+ onKeyDown: (event) => event.stopPropagation(),
244
+ onKeyUp: (event) => event.stopPropagation(),
245
+ children
246
+ }
247
+ )
248
+ );
249
+ }
250
+ var HEADER_PADDING_PX = { default: 32, compact: 24 };
251
+ function useHeaderWidths(padding, deps) {
252
+ const nodes = useRef(/* @__PURE__ */ new Map());
253
+ const [widths, setWidths] = useState({});
254
+ const measure = useCallback(() => {
255
+ const next = {};
256
+ nodes.current.forEach((node, id) => {
257
+ next[id] = Math.ceil(node.getBoundingClientRect().width) + padding;
258
+ });
259
+ setWidths((previous) => {
260
+ const keys = Object.keys(next);
261
+ const same = keys.length === Object.keys(previous).length && keys.every((key) => previous[key] === next[key]);
262
+ return same ? previous : next;
263
+ });
264
+ }, [padding]);
265
+ useLayoutEffect(measure, [measure, deps]);
266
+ useLayoutEffect(() => {
267
+ let live = true;
268
+ void document.fonts?.ready.then(() => live && measure());
269
+ return () => {
270
+ live = false;
271
+ };
272
+ }, [measure]);
273
+ const register = useCallback(
274
+ (id) => (node) => {
275
+ if (node) nodes.current.set(id, node);
276
+ else nodes.current.delete(id);
277
+ },
278
+ []
279
+ );
280
+ return { widths, register };
281
+ }
282
+ function useScrollEdges() {
283
+ const [node, setNode] = useState(null);
284
+ const [edges, setEdges] = useState({ overflowing: false, atStart: true, atEnd: true, overflowingY: false, atTop: true });
285
+ const measure = useCallback(() => {
286
+ if (!node) return;
287
+ const { scrollLeft, scrollWidth, clientWidth, scrollTop, scrollHeight, clientHeight } = node;
288
+ const next = {
289
+ overflowing: scrollWidth > clientWidth + 1,
290
+ atStart: scrollLeft <= 1,
291
+ atEnd: scrollLeft + clientWidth >= scrollWidth - 1,
292
+ overflowingY: scrollHeight > clientHeight + 1,
293
+ atTop: scrollTop <= 1
294
+ };
295
+ setEdges(
296
+ (previous) => previous.overflowing === next.overflowing && previous.atStart === next.atStart && previous.atEnd === next.atEnd && previous.overflowingY === next.overflowingY && previous.atTop === next.atTop ? previous : next
297
+ );
298
+ }, [node]);
299
+ useLayoutEffect(() => {
300
+ if (!node) return;
301
+ measure();
302
+ if (typeof ResizeObserver === "undefined") return;
303
+ const observer = new ResizeObserver(measure);
304
+ observer.observe(node);
305
+ if (node.firstElementChild) observer.observe(node.firstElementChild);
306
+ return () => observer.disconnect();
307
+ }, [node, measure]);
308
+ return { ref: setNode, onScroll: measure, ...edges };
309
+ }
310
+ var serverSortedValue = () => void 0;
311
+ function defaultRowLink({ children, ...props }) {
312
+ return /* @__PURE__ */ jsx2("a", { ...props, children });
313
+ }
314
+ function DataTable({
315
+ columns,
316
+ data,
317
+ getRowId,
318
+ label,
319
+ caption,
320
+ searchable = false,
321
+ columnVisibility: showColumnMenu = false,
322
+ pagination: paginated = true,
323
+ pageSize = 10,
324
+ pageSizeOptions = [10, 20, 50],
325
+ enableRowSelection,
326
+ onSelectionChange,
327
+ getRowLabel,
328
+ onRowClick,
329
+ getRowHref,
330
+ renderRowLink = defaultRowLink,
331
+ getRowTone,
332
+ getRowDimmed,
333
+ loading = false,
334
+ loadingRows = 5,
335
+ error,
336
+ onRetry,
337
+ empty = "No results found.",
338
+ toolbar,
339
+ footer,
340
+ density = "default",
341
+ align = "center",
342
+ responsive = true,
343
+ maxHeight,
344
+ manual = {},
345
+ state = {},
346
+ onSortingChange,
347
+ onGlobalFilterChange,
348
+ onColumnFiltersChange,
349
+ onPaginationChange,
350
+ onColumnVisibilityChange,
351
+ onRowSelectionChange,
352
+ tableOptions,
353
+ className
354
+ }) {
355
+ if (!label && !caption) {
356
+ devWarn('DataTable needs `label` or `caption`: an unnamed table is announced as just "table".');
357
+ }
358
+ if (manual.pagination && manual.rowCount === void 0) {
359
+ devWarn("DataTable `manual.pagination` needs `manual.rowCount` to know how many pages there are.");
360
+ }
361
+ const [sorting, setSorting] = useTableState(state.sorting, [], onSortingChange);
362
+ const [globalFilter, setGlobalFilter] = useTableState(state.globalFilter, "", onGlobalFilterChange);
363
+ const [columnFilters, setColumnFilters] = useTableState(state.columnFilters, [], onColumnFiltersChange);
364
+ const [pagination, setPagination] = useTableState(
365
+ state.pagination,
366
+ { pageIndex: 0, pageSize },
367
+ onPaginationChange
368
+ );
369
+ const [columnVisibility, setColumnVisibility] = useTableState(
370
+ state.columnVisibility,
371
+ {},
372
+ onColumnVisibilityChange
373
+ );
374
+ const [rowSelection, setRowSelection] = useTableState(state.rowSelection, {}, onRowSelectionChange);
375
+ const allColumns = useMemo(() => {
376
+ let cols = columns;
377
+ if (manual.sorting) {
378
+ cols = cols.map(
379
+ (column) => column.enableSorting === true && !("accessorFn" in column) && !("accessorKey" in column) ? { ...column, accessorFn: serverSortedValue } : column
380
+ );
381
+ }
382
+ if (!enableRowSelection || cols.some((column) => column.id === SELECT_COLUMN_ID)) return cols;
383
+ return [createSelectColumn({ getRowLabel: getRowLabel && ((row) => `Select ${getRowLabel(row)}`) }), ...cols];
384
+ }, [columns, enableRowSelection, getRowLabel, manual.sorting]);
385
+ const table = useReactTable({
386
+ data,
387
+ columns: allColumns,
388
+ getRowId,
389
+ state: { sorting, globalFilter, columnFilters, pagination, columnVisibility, rowSelection },
390
+ onSortingChange: setSorting,
391
+ onGlobalFilterChange: setGlobalFilter,
392
+ onColumnFiltersChange: setColumnFilters,
393
+ onPaginationChange: setPagination,
394
+ onColumnVisibilityChange: setColumnVisibility,
395
+ onRowSelectionChange: setRowSelection,
396
+ enableRowSelection: typeof enableRowSelection === "function" ? (row) => enableRowSelection(row.original) : Boolean(enableRowSelection),
397
+ getCoreRowModel: getCoreRowModel(),
398
+ getSortedRowModel: manual.sorting ? void 0 : getSortedRowModel(),
399
+ getFilteredRowModel: manual.filtering ? void 0 : getFilteredRowModel(),
400
+ getPaginationRowModel: paginated && !manual.pagination ? getPaginationRowModel() : void 0,
401
+ manualSorting: manual.sorting,
402
+ manualFiltering: manual.filtering,
403
+ manualPagination: !paginated || manual.pagination,
404
+ rowCount: manual.rowCount,
405
+ // Two states from 0.9.4: a third click no longer clears the sort. "Off" is not a direction a
406
+ // person can see or ask for, and it silently reverted to an order nobody chose. Pass
407
+ // `tableOptions={{ enableSortingRemoval: true }}` for the three-state cycle.
408
+ enableSortingRemoval: false,
409
+ ...tableOptions
410
+ });
411
+ const selectionReported = useRef(false);
412
+ useEffect(() => {
413
+ if (!onSelectionChange) return;
414
+ if (!selectionReported.current) {
415
+ selectionReported.current = true;
416
+ return;
417
+ }
418
+ onSelectionChange(table.getSelectedRowModel().rows.map((row) => row.original));
419
+ }, [rowSelection]);
420
+ const [wrapRef, containerWidth] = useElementWidth();
421
+ const breakpoint = responsive === false ? 0 : typeof responsive === "object" ? responsive.breakpoint ?? DEFAULT_CARD_BREAKPOINT_PX : DEFAULT_CARD_BREAKPOINT_PX;
422
+ const modeRef = useRef("table");
423
+ const mode = nextLayoutMode(modeRef.current, containerWidth, breakpoint);
424
+ modeRef.current = mode;
425
+ const search = searchable === true ? {} : searchable || void 0;
426
+ const searchColumn = search?.columnId ? table.getColumn(search.columnId) : void 0;
427
+ const searchValue = searchColumn ? String(searchColumn.getFilterValue() ?? "") : globalFilter;
428
+ const setSearchValue = (value) => {
429
+ if (searchColumn) searchColumn.setFilterValue(value || void 0);
430
+ else table.setGlobalFilter(value);
431
+ };
432
+ const filtering = Boolean(globalFilter) || columnFilters.length > 0;
433
+ const rows = table.getRowModel().rows;
434
+ const isEmpty = !loading && !error && rows.length === 0;
435
+ const placeholder = error ? /* @__PURE__ */ jsx2(
436
+ EmptyState,
437
+ {
438
+ message: typeof error === "string" ? error : "Something went wrong loading this data.",
439
+ variant: "error",
440
+ size: "md",
441
+ action: onRetry ? /* @__PURE__ */ jsx2(Button, { variant: "neutral", size: "sm", onClick: onRetry, children: "Retry" }) : void 0,
442
+ className: "mx-auto max-w-[520px]"
443
+ }
444
+ ) : isEmpty ? typeof empty === "string" ? /* @__PURE__ */ jsx2(EmptyState, { message: empty, size: "md", className: "mx-auto max-w-[520px]" }) : empty : null;
445
+ const resultCount = manual.filtering ? table.getRowCount() : table.getFilteredRowModel().rows.length;
446
+ const showToolbar = Boolean(search || toolbar || showColumnMenu);
447
+ const showPager = paginated && !error && table.getRowCount() > 0;
448
+ const view = {
449
+ table,
450
+ label,
451
+ caption,
452
+ density,
453
+ align,
454
+ loading,
455
+ loadingRows,
456
+ placeholder,
457
+ onRowClick,
458
+ getRowHref,
459
+ renderRowLink,
460
+ getRowTone,
461
+ getRowDimmed,
462
+ getRowLabel,
463
+ maxHeight
464
+ };
465
+ return /* @__PURE__ */ jsxs2("div", { "data-slot": "data-table", className: cn("relative flex flex-col gap-3", className), children: [
466
+ showToolbar && /* @__PURE__ */ jsxs2("div", { className: "flex flex-wrap items-center gap-2", children: [
467
+ search && /* @__PURE__ */ jsx2(
468
+ SearchInput,
469
+ {
470
+ size: "md",
471
+ label: search.label ?? "Search",
472
+ placeholder: search.placeholder ?? "Search\u2026",
473
+ value: searchValue,
474
+ onChange: (event) => setSearchValue(event.target.value),
475
+ onClear: () => setSearchValue(""),
476
+ className: "w-full max-w-[280px]"
477
+ }
478
+ ),
479
+ toolbar,
480
+ showColumnMenu && /* @__PURE__ */ jsx2("div", { className: "ml-auto", children: /* @__PURE__ */ jsx2(DataTableViewOptions, { table }) })
481
+ ] }),
482
+ /* @__PURE__ */ jsx2("p", { role: "status", "aria-live": "polite", className: "sr-only", children: filtering && !loading ? `${resultCount} ${resultCount === 1 ? "result" : "results"}` : "" }),
483
+ /* @__PURE__ */ jsxs2("div", { ref: wrapRef, className: "overflow-hidden rounded-xl border border-default bg-default", children: [
484
+ mode === "cards" ? maxHeight ? /* @__PURE__ */ jsx2(CardScroll, { label, maxHeight, children: /* @__PURE__ */ jsx2(CardList, { ...view }) }) : /* @__PURE__ */ jsx2(CardList, { ...view }) : /* @__PURE__ */ jsx2(TableView, { ...view }),
485
+ showPager && /* @__PURE__ */ jsx2("div", { className: "border-t border-default px-4 py-3", children: /* @__PURE__ */ jsx2(DataTablePagination, { table, pageSizeOptions }) }),
486
+ footer && /* @__PURE__ */ jsx2("div", { className: "border-t border-default px-4 py-3", children: footer })
487
+ ] })
488
+ ] });
489
+ }
490
+ function titleColumnId(columns) {
491
+ const content = columns.filter((column) => column.id !== SELECT_COLUMN_ID);
492
+ return (content.find((column) => column.columnDef.meta?.mobile === "title") ?? content[0])?.id;
493
+ }
494
+ function TableView({
495
+ table,
496
+ label,
497
+ caption,
498
+ density,
499
+ align,
500
+ loading,
501
+ loadingRows,
502
+ placeholder,
503
+ onRowClick,
504
+ getRowHref,
505
+ renderRowLink,
506
+ getRowTone,
507
+ getRowDimmed,
508
+ maxHeight
509
+ }) {
510
+ const d = DENSITY[density];
511
+ const columns = table.getVisibleLeafColumns();
512
+ const scroll = useScrollEdges();
513
+ const headers = useHeaderWidths(HEADER_PADDING_PX[density], columns.map((column) => column.id).join());
514
+ const columnPx = (column) => Math.max(widthToPx(column.columnDef.meta?.width), headers.widths[column.id] ?? 0);
515
+ const minWidth = columns.reduce((sum, column) => sum + columnPx(column), 0);
516
+ const showPlaceholder = loading || placeholder !== null;
517
+ const first = columns[0];
518
+ const last = columns[columns.length - 1];
519
+ const stickyStart = scroll.overflowing && first?.columnDef.meta?.sticky === "start" ? first.id : void 0;
520
+ const stickyEnd = scroll.overflowing && last?.columnDef.meta?.sticky === "end" && last !== first ? last.id : void 0;
521
+ const hasSticky = Boolean(stickyStart || stickyEnd);
522
+ const titleId = titleColumnId(columns);
523
+ const rowAction = getRowHref ? "link" : onRowClick ? "click" : null;
524
+ const stickyClass = (id, header) => clsx(
525
+ id === stickyStart && [
526
+ "sticky left-0 z-raised",
527
+ // A hairline where content slides under the pinned column, once it has scrolled.
528
+ !scroll.atStart && "shadow-[inset_-1px_0_0_var(--color-border-default-default)]"
529
+ ],
530
+ id === stickyEnd && [
531
+ "sticky right-0 z-raised",
532
+ !scroll.atEnd && "shadow-[inset_1px_0_0_var(--color-border-default-default)]"
533
+ ],
534
+ (id === stickyStart || id === stickyEnd) && (header ? "bg-default-secondary" : ["bg-default", rowAction && "group-hover:bg-default-secondary"])
535
+ );
536
+ const scrolls = scroll.overflowing || Boolean(maxHeight) && scroll.overflowingY;
537
+ const direction = scroll.overflowing && maxHeight && scroll.overflowingY ? "scrolls" : scroll.overflowing ? "scrolls horizontally" : "scrolls vertically";
538
+ const regionLabel = `${label ?? "Table"} (${direction})`;
539
+ const pinnedHeader = maxHeight ? clsx("sticky top-0 z-sticky bg-default-secondary", !scroll.atTop && "shadow-[inset_0_-1px_0_var(--color-border-default-default)]") : void 0;
540
+ return /* @__PURE__ */ jsxs2("div", { className: "relative", children: [
541
+ /* @__PURE__ */ jsx2(
542
+ "div",
543
+ {
544
+ ref: scroll.ref,
545
+ onScroll: scroll.onScroll,
546
+ className: cn(
547
+ maxHeight ? "overflow-auto overscroll-contain" : "overflow-x-auto overscroll-x-contain",
548
+ SCROLLBAR_CLASSES,
549
+ scrolls && FOCUS_RING_INSET
550
+ ),
551
+ style: maxHeight ? { maxHeight } : void 0,
552
+ ...scrolls ? { role: "region", tabIndex: 0, "aria-label": regionLabel } : {},
553
+ children: /* @__PURE__ */ jsxs2(
554
+ "table",
555
+ {
556
+ className: "w-full table-fixed border-collapse text-left",
557
+ style: showPlaceholder ? void 0 : { minWidth },
558
+ "aria-busy": loading || void 0,
559
+ children: [
560
+ caption ? /* @__PURE__ */ jsx2("caption", { className: "px-4 pt-3 text-left text-body-sm text-default-secondary", children: caption }) : label && /* @__PURE__ */ jsx2("caption", { className: "sr-only", children: label }),
561
+ /* @__PURE__ */ jsx2("colgroup", { children: columns.map((column) => {
562
+ const meta = column.columnDef.meta;
563
+ const floor = headers.widths[column.id] ?? 0;
564
+ return /* @__PURE__ */ jsx2(
565
+ "col",
566
+ {
567
+ style: meta?.grow || !meta?.width ? void 0 : { width: floor > widthToPx(meta.width) ? floor : meta.width }
568
+ },
569
+ column.id
570
+ );
571
+ }) }),
572
+ /* @__PURE__ */ jsx2("thead", { children: table.getHeaderGroups().map((group) => /* @__PURE__ */ jsx2("tr", { className: "bg-default-secondary", children: group.headers.map((header) => {
573
+ const meta = header.column.columnDef.meta;
574
+ const sortable = header.column.getCanSort();
575
+ const sorted = header.column.getIsSorted();
576
+ const definition = header.column.columnDef.header;
577
+ return /* @__PURE__ */ jsx2(
578
+ "th",
579
+ {
580
+ scope: "col",
581
+ colSpan: header.colSpan,
582
+ "aria-sort": sortable ? sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : "none" : void 0,
583
+ className: cn(
584
+ d.headerCell,
585
+ d.headerText,
586
+ TEXT_ALIGN[meta?.align ?? "start"],
587
+ !meta?.interactive && "overflow-hidden",
588
+ stickyClass(header.column.id, true),
589
+ pinnedHeader,
590
+ meta?.headerClassName
591
+ ),
592
+ children: header.isPlaceholder ? null : typeof definition === "string" || definition === void 0 ? /* @__PURE__ */ jsx2("span", { ref: meta?.hideHeader ? void 0 : headers.register(header.column.id), className: "inline-block", children: /* @__PURE__ */ jsx2(DataTableColumnHeader, { column: header.column }) }) : flexRender(definition, header.getContext())
593
+ },
594
+ header.id
595
+ );
596
+ }) }, group.id)) }),
597
+ /* @__PURE__ */ jsx2("tbody", { children: loading && !placeholder ? Array.from({ length: loadingRows }, (_, index) => /* @__PURE__ */ jsx2("tr", { className: clsx(index > 0 && "border-t border-default"), children: columns.map((column) => /* @__PURE__ */ jsx2("td", { className: clsx(d.bodyCell, "align-middle"), children: /* @__PURE__ */ jsx2(Skeleton, { className: column.columnDef.meta?.grow ? "w-[70%]" : "w-[55%]" }) }, column.id)) }, `skeleton-${index}`)) : placeholder ? /* @__PURE__ */ jsx2("tr", { children: /* @__PURE__ */ jsx2("td", { colSpan: columns.length, className: "px-4", children: placeholder }) }) : table.getRowModel().rows.map((row) => /* @__PURE__ */ jsx2(
598
+ BodyRow,
599
+ {
600
+ row,
601
+ density,
602
+ align,
603
+ titleId,
604
+ rowAction,
605
+ hasSticky,
606
+ stickyClass,
607
+ onRowClick,
608
+ getRowHref,
609
+ renderRowLink,
610
+ getRowTone,
611
+ getRowDimmed
612
+ },
613
+ row.id
614
+ )) })
615
+ ]
616
+ }
617
+ )
618
+ }
619
+ ),
620
+ scroll.overflowing && !scroll.atStart && !stickyStart && /* @__PURE__ */ jsx2("span", { "aria-hidden": true, className: "pointer-events-none absolute inset-y-0 left-0 w-6 bg-gradient-to-r from-default-secondary to-transparent" }),
621
+ scroll.overflowing && !scroll.atEnd && !stickyEnd && /* @__PURE__ */ jsx2("span", { "aria-hidden": true, className: "pointer-events-none absolute inset-y-0 right-0 w-6 bg-gradient-to-l from-default-secondary to-transparent" })
622
+ ] });
623
+ }
624
+ function BodyRow({
625
+ row,
626
+ density,
627
+ align,
628
+ titleId,
629
+ rowAction,
630
+ hasSticky,
631
+ stickyClass,
632
+ onRowClick,
633
+ getRowHref,
634
+ renderRowLink,
635
+ getRowTone,
636
+ getRowDimmed
637
+ }) {
638
+ const d = DENSITY[density];
639
+ const href = getRowHref?.(row.original);
640
+ return /* @__PURE__ */ jsx2(
641
+ TableRow,
642
+ {
643
+ selected: row.getIsSelected() || void 0,
644
+ tone: getRowTone?.(row.original),
645
+ dimmed: getRowDimmed?.(row.original),
646
+ className: cn(
647
+ "group",
648
+ rowAction && ["cursor-pointer", hasSticky && "hover:bg-default-secondary"],
649
+ // outline, not ring: `ring-*` is box-shadow, which browsers do not paint on a <tr>
650
+ // under border-collapse.
651
+ rowAction === "click" && "outline-none focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-brand"
652
+ ),
653
+ tabIndex: rowAction === "click" ? 0 : void 0,
654
+ onClick: rowAction === "link" ? (event) => {
655
+ if (event.target.closest("a")) return;
656
+ event.currentTarget.querySelector(`[${ROW_LINK_ATTR}]`)?.click();
657
+ } : rowAction === "click" ? () => onRowClick(row.original) : void 0,
658
+ onKeyDown: rowAction === "click" ? (event) => {
659
+ if (event.target !== event.currentTarget) return;
660
+ if (event.key === "Enter" || event.key === " ") {
661
+ event.preventDefault();
662
+ onRowClick(row.original);
663
+ }
664
+ } : void 0,
665
+ children: row.getVisibleCells().map((cell) => /* @__PURE__ */ jsx2(
666
+ BodyCell,
667
+ {
668
+ cell,
669
+ className: cn(d.bodyCell, VERTICAL[align], stickyClass(cell.column.id, false)),
670
+ link: href && cell.column.id === titleId ? href : void 0,
671
+ renderRowLink
672
+ },
673
+ cell.id
674
+ ))
675
+ }
676
+ );
677
+ }
678
+ function BodyCell({
679
+ cell,
680
+ className,
681
+ link,
682
+ renderRowLink
683
+ }) {
684
+ const meta = cell.column.columnDef.meta;
685
+ let content = flexRender(cell.column.columnDef.cell, cell.getContext());
686
+ if (link) {
687
+ content = renderRowLink({
688
+ href: link,
689
+ [ROW_LINK_ATTR]: "",
690
+ className: cn("block min-w-0 rounded-sm", FOCUS_RING_INSET),
691
+ children: content
692
+ }, cell.row.original);
693
+ }
694
+ return /* @__PURE__ */ jsx2(
695
+ "td",
696
+ {
697
+ className: cn(
698
+ className,
699
+ TEXT_ALIGN[meta?.align ?? "start"],
700
+ // Guards against a bespoke cell bleeding into the next column. Interactive cells opt
701
+ // out so focus rings are not clipped.
702
+ !meta?.interactive && "overflow-hidden",
703
+ meta?.cellClassName
704
+ ),
705
+ children: meta?.interactive ? /* @__PURE__ */ jsx2(CellInteractionGuard, { children: content }) : content
706
+ }
707
+ );
708
+ }
709
+ function CardScroll({ label, maxHeight, children }) {
710
+ const scroll = useScrollEdges();
711
+ return /* @__PURE__ */ jsx2(
712
+ "div",
713
+ {
714
+ ref: scroll.ref,
715
+ onScroll: scroll.onScroll,
716
+ style: { maxHeight },
717
+ className: cn("overflow-y-auto overscroll-contain", SCROLLBAR_CLASSES, scroll.overflowingY && FOCUS_RING_INSET),
718
+ ...scroll.overflowingY ? { role: "region", tabIndex: 0, "aria-label": `${label ?? "Table"} (scrolls vertically)` } : {},
719
+ children
720
+ }
721
+ );
722
+ }
723
+ function CardList({
724
+ table,
725
+ label,
726
+ loading,
727
+ loadingRows,
728
+ placeholder,
729
+ onRowClick,
730
+ getRowHref,
731
+ renderRowLink,
732
+ getRowTone,
733
+ getRowDimmed,
734
+ getRowLabel
735
+ }) {
736
+ if (placeholder) return /* @__PURE__ */ jsx2("div", { className: "px-4", children: placeholder });
737
+ if (loading) {
738
+ return /* @__PURE__ */ jsx2("ul", { "aria-label": label, "aria-busy": "true", className: "divide-y divide-default", children: Array.from({ length: loadingRows }, (_, index) => /* @__PURE__ */ jsxs2("li", { className: "flex flex-col gap-3 p-4", children: [
739
+ /* @__PURE__ */ jsx2(Skeleton, { className: "w-2/3" }),
740
+ /* @__PURE__ */ jsx2(Skeleton, { className: "w-1/2" }),
741
+ /* @__PURE__ */ jsx2(Skeleton, { className: "w-5/6" })
742
+ ] }, index)) });
743
+ }
744
+ const columns = table.getVisibleLeafColumns();
745
+ const selectable = columns.some((column) => column.id === SELECT_COLUMN_ID);
746
+ const slots = cardSlots(
747
+ columns.filter((column) => column.id !== SELECT_COLUMN_ID).map((column) => ({ id: column.id, mobile: column.columnDef.meta?.mobile, column }))
748
+ );
749
+ const trigger = clsx(
750
+ "block w-full min-w-0 text-left focus-visible:outline-none",
751
+ "after:absolute after:inset-0 after:content-['']",
752
+ "focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-brand"
753
+ );
754
+ return (
755
+ // Card mode un-truncates: on touch there is no hover tooltip, so a clipped value would be
756
+ // unreadable. `.truncate` cell renderers wrap here instead.
757
+ /* @__PURE__ */ jsx2(
758
+ "ul",
759
+ {
760
+ "aria-label": label,
761
+ className: "divide-y divide-default [&_.truncate]:whitespace-normal [&_.truncate]:[overflow-wrap:anywhere]",
762
+ children: table.getRowModel().rows.map((row) => {
763
+ const cells = new Map(row.getVisibleCells().map((cell) => [cell.column.id, cell]));
764
+ const render = (id) => {
765
+ const cell = id ? cells.get(id) : void 0;
766
+ return cell ? flexRender(cell.column.columnDef.cell, cell.getContext()) : null;
767
+ };
768
+ const href = getRowHref?.(row.original);
769
+ const titleContent = render(slots.title?.id);
770
+ const tone = getRowTone?.(row.original);
771
+ return /* @__PURE__ */ jsxs2(
772
+ "li",
773
+ {
774
+ "data-state": row.getIsSelected() ? "selected" : void 0,
775
+ "data-tone": tone && tone !== "default" ? tone : void 0,
776
+ "data-dimmed": getRowDimmed?.(row.original) || void 0,
777
+ className: cn(
778
+ "relative flex flex-col gap-3 p-4 transition-colors",
779
+ (href || onRowClick) && "hover:bg-default-secondary/50",
780
+ "data-[tone=muted]:bg-default-secondary data-[tone=brand]:bg-brand-tertiary",
781
+ "data-[tone=positive]:bg-positive-tertiary data-[tone=warning]:bg-warning-tertiary",
782
+ "data-[tone=danger]:bg-danger-tertiary data-[dimmed]:opacity-60",
783
+ "data-[state=selected]:bg-brand-tertiary"
784
+ ),
785
+ children: [
786
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-start gap-3", children: [
787
+ selectable && /* @__PURE__ */ jsx2("div", { className: "relative z-raised shrink-0 pt-0.5", children: render(SELECT_COLUMN_ID) }),
788
+ /* @__PURE__ */ jsx2("div", { className: "min-w-0 flex-1", children: href ? renderRowLink({ href, [ROW_LINK_ATTR]: "", className: trigger, children: titleContent }, row.original) : onRowClick ? /* @__PURE__ */ jsx2(
789
+ "button",
790
+ {
791
+ type: "button",
792
+ className: trigger,
793
+ "aria-label": getRowLabel?.(row.original),
794
+ onClick: () => onRowClick(row.original),
795
+ children: titleContent
796
+ }
797
+ ) : titleContent }),
798
+ slots.status && // A status pill is `nowrap`, so a long label would spill off the card. Let it
799
+ // wrap inside the cap instead.
800
+ /* @__PURE__ */ jsx2("div", { className: "flex max-w-[45%] shrink-0 justify-end [&_.whitespace-nowrap]:whitespace-normal", children: render(slots.status.id) }),
801
+ slots.actions && /* @__PURE__ */ jsx2("div", { className: "relative z-raised shrink-0", children: /* @__PURE__ */ jsx2(CellInteractionGuard, { children: render(slots.actions.id) }) })
802
+ ] }),
803
+ slots.fields.length > 0 && /* @__PURE__ */ jsx2("dl", { className: "grid grid-cols-[repeat(auto-fit,minmax(min(100%,8.5rem),1fr))] gap-x-4 gap-y-2.5", children: slots.fields.map(({ id, column }) => /* @__PURE__ */ jsxs2("div", { className: clsx("min-w-0", column.columnDef.meta?.interactive && "relative z-raised"), children: [
804
+ /* @__PURE__ */ jsx2("dt", { className: "text-body-tiny text-default-secondary", children: columnLabel(column) }),
805
+ /* @__PURE__ */ jsx2("dd", { className: "mt-0.5 min-w-0 text-body-xs text-default", children: column.columnDef.meta?.interactive ? /* @__PURE__ */ jsx2(CellInteractionGuard, { children: render(id) }) : render(id) })
806
+ ] }, id)) })
807
+ ]
808
+ },
809
+ row.id
810
+ );
811
+ })
812
+ }
813
+ )
814
+ );
815
+ }
816
+
817
+ // src/data-table.tsx
818
+ import { createColumnHelper } from "@tanstack/react-table";
819
+ export {
820
+ DataTable,
821
+ DataTableColumnHeader,
822
+ DataTablePagination,
823
+ DataTableViewOptions,
824
+ SELECT_COLUMN_ID,
825
+ TableCellBadge,
826
+ TableCellLeadText,
827
+ TableCellProgress,
828
+ TableCellText,
829
+ createColumnHelper,
830
+ createSelectColumn
831
+ };
832
+ //# sourceMappingURL=data-table.js.map