@platned/ui 0.9.3 → 0.9.5

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