hs-uix 1.0.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.
@@ -0,0 +1,1034 @@
1
+ // packages/datatable/src/DataTable.jsx
2
+ import React, { useState, useMemo, useEffect, useCallback, useRef } from "react";
3
+ import Fuse from "fuse.js";
4
+ import {
5
+ Box,
6
+ Button,
7
+ Checkbox,
8
+ CurrencyInput,
9
+ DateInput,
10
+ EmptyState,
11
+ ErrorState,
12
+ Flex,
13
+ Icon,
14
+ Input,
15
+ Link,
16
+ LoadingSpinner,
17
+ MultiSelect,
18
+ NumberInput,
19
+ SearchInput,
20
+ Select,
21
+ StepperInput,
22
+ Table,
23
+ TableBody,
24
+ TableCell,
25
+ TableFooter,
26
+ TableHead,
27
+ TableHeader,
28
+ TableRow,
29
+ Tag,
30
+ Text,
31
+ TextArea,
32
+ TimeInput,
33
+ Toggle
34
+ } from "@hubspot/ui-extensions";
35
+ var formatDateChip = (dateObj) => {
36
+ if (!dateObj) return "";
37
+ const { year, month, date } = dateObj;
38
+ return new Intl.DateTimeFormat("en-US", {
39
+ month: "short",
40
+ day: "numeric",
41
+ year: "numeric"
42
+ }).format(new Date(year, month, date));
43
+ };
44
+ var dateToTimestamp = (dateObj) => {
45
+ if (!dateObj) return null;
46
+ return new Date(dateObj.year, dateObj.month, dateObj.date).getTime();
47
+ };
48
+ var NARROW_EDIT_TYPES = /* @__PURE__ */ new Set(["checkbox", "toggle"]);
49
+ var DATE_PATTERN = /^\d{4}[-/]\d{2}[-/]\d{2}/;
50
+ var BOOL_VALUES = /* @__PURE__ */ new Set(["true", "false", "yes", "no", "0", "1"]);
51
+ var SORT_DIRECTIONS = /* @__PURE__ */ new Set(["ascending", "descending", "none"]);
52
+ var normalizeSortState = (columns, sort) => {
53
+ const normalized = {};
54
+ columns.forEach((col) => {
55
+ if (col.sortable) normalized[col.field] = "none";
56
+ });
57
+ if (!sort) return normalized;
58
+ if (sort.field && SORT_DIRECTIONS.has(sort.direction) && sort.field in normalized) {
59
+ normalized[sort.field] = sort.direction;
60
+ return normalized;
61
+ }
62
+ Object.keys(normalized).forEach((field) => {
63
+ const direction = sort[field];
64
+ if (SORT_DIRECTIONS.has(direction)) normalized[field] = direction;
65
+ });
66
+ return normalized;
67
+ };
68
+ var serializeSortState = (sortState) => {
69
+ const activeField = Object.keys(sortState).find((field) => sortState[field] !== "none");
70
+ if (!activeField) return null;
71
+ return { field: activeField, direction: sortState[activeField] };
72
+ };
73
+ var toStableKey = (value) => {
74
+ try {
75
+ return JSON.stringify(value);
76
+ } catch (_error) {
77
+ return String(value);
78
+ }
79
+ };
80
+ var computeAutoWidths = (columns, data) => {
81
+ if (!data || data.length === 0) return {};
82
+ const sample = data.slice(0, 50);
83
+ const results = {};
84
+ columns.forEach((col) => {
85
+ if (col.width && col.cellWidth) return;
86
+ const values = sample.map((row) => row[col.field]).filter((v) => v != null);
87
+ const strings = values.map((v) => String(v));
88
+ let widthHint = null;
89
+ let cellWidthHint = null;
90
+ if (col.editable && col.editType && NARROW_EDIT_TYPES.has(col.editType)) {
91
+ cellWidthHint = "min";
92
+ }
93
+ if (strings.length > 0) {
94
+ const lengths = strings.map((s) => s.length);
95
+ const maxLen = Math.max(...lengths);
96
+ const uniqueCount = new Set(strings).size;
97
+ if (values.every((v) => typeof v === "boolean") || strings.every((s) => BOOL_VALUES.has(s.toLowerCase()))) {
98
+ widthHint = widthHint || "min";
99
+ cellWidthHint = cellWidthHint || "min";
100
+ } else if (strings.every((s) => DATE_PATTERN.test(s))) {
101
+ widthHint = widthHint || "min";
102
+ cellWidthHint = cellWidthHint || "auto";
103
+ } else if (values.every((v) => typeof v === "number")) {
104
+ widthHint = widthHint || "auto";
105
+ cellWidthHint = cellWidthHint || "auto";
106
+ } else if (uniqueCount <= 5 && maxLen <= 15) {
107
+ widthHint = widthHint || "min";
108
+ cellWidthHint = cellWidthHint || "auto";
109
+ } else {
110
+ widthHint = widthHint || "auto";
111
+ cellWidthHint = cellWidthHint || "auto";
112
+ }
113
+ }
114
+ if (col.editable && !NARROW_EDIT_TYPES.has(col.editType) && widthHint === "min") {
115
+ widthHint = "auto";
116
+ }
117
+ results[col.field] = {
118
+ width: widthHint || "auto",
119
+ cellWidth: cellWidthHint || "auto"
120
+ };
121
+ });
122
+ return results;
123
+ };
124
+ var getEmptyFilterValue = (filter) => {
125
+ const type = filter.type || "select";
126
+ if (type === "multiselect") return [];
127
+ if (type === "dateRange") return { from: null, to: null };
128
+ return "";
129
+ };
130
+ var BOOLEAN_SELECT_OPTIONS = [
131
+ { label: "Yes", value: true },
132
+ { label: "No", value: false }
133
+ ];
134
+ var resolveEditOptions = (col, data) => {
135
+ if (col.editOptions && col.editOptions.length > 0) return col.editOptions;
136
+ const sample = data.find((row) => row[col.field] != null);
137
+ if (sample && typeof sample[col.field] === "boolean") return BOOLEAN_SELECT_OPTIONS;
138
+ return [];
139
+ };
140
+ var isFilterActive = (filter, value) => {
141
+ const type = filter.type || "select";
142
+ if (type === "multiselect") return Array.isArray(value) && value.length > 0;
143
+ if (type === "dateRange") return value && (value.from || value.to);
144
+ return !!value;
145
+ };
146
+ var DataTable = ({
147
+ // Data
148
+ data,
149
+ columns,
150
+ renderRow,
151
+ // Search
152
+ searchFields = [],
153
+ searchPlaceholder = "Search...",
154
+ fuzzySearch = false,
155
+ // enable fuzzy matching via Fuse.js
156
+ fuzzyOptions,
157
+ // custom Fuse.js options (threshold, distance, etc.)
158
+ // Filters
159
+ filters = [],
160
+ showFilterBadges = true,
161
+ // show active filter chips/badges
162
+ showClearFiltersButton = true,
163
+ // show "Clear all" filters reset button
164
+ // Pagination
165
+ pageSize = 10,
166
+ maxVisiblePageButtons,
167
+ // max page number buttons to show
168
+ showButtonLabels = true,
169
+ // show First/Prev/Next/Last text labels
170
+ showFirstLastButtons,
171
+ // show First/Last page buttons (default: auto when pageCount > 5)
172
+ // Row count
173
+ showRowCount = true,
174
+ // show "X records" / "X of Y records" text
175
+ rowCountBold = false,
176
+ // bold the row count text
177
+ rowCountText,
178
+ // custom formatter: (shownOnPage, totalMatching) => string
179
+ // Table appearance
180
+ bordered = true,
181
+ // show table borders
182
+ flush = true,
183
+ // remove bottom margin
184
+ scrollable = false,
185
+ // allow horizontal overflow with scrollbar
186
+ // Sorting
187
+ defaultSort = {},
188
+ // Grouping
189
+ groupBy,
190
+ // Footer
191
+ footer,
192
+ // Empty state
193
+ emptyTitle,
194
+ emptyMessage,
195
+ // -----------------------------------------------------------------------
196
+ // Server-side mode
197
+ // -----------------------------------------------------------------------
198
+ serverSide = false,
199
+ loading = false,
200
+ // show loading spinner over the table
201
+ error,
202
+ // error message string or boolean — shows ErrorState
203
+ totalCount,
204
+ // server total (server-side only)
205
+ page: externalPage,
206
+ // controlled page (server-side only)
207
+ searchValue,
208
+ // controlled search term (server-side only)
209
+ filterValues: externalFilterValues,
210
+ // controlled filter values (server-side only)
211
+ sort: externalSort,
212
+ // controlled sort state, e.g. { field: "ascending" }
213
+ searchDebounce = 0,
214
+ // ms to debounce onSearchChange callback
215
+ resetPageOnChange = true,
216
+ // auto-reset to page 1 on search/filter/sort change
217
+ onSearchChange,
218
+ // (searchTerm) => void
219
+ onFilterChange,
220
+ // (filterValues) => void
221
+ onSortChange,
222
+ // (field, direction) => void
223
+ onPageChange,
224
+ // (page) => void
225
+ onParamsChange,
226
+ // ({ search, filters, sort, page }) => void
227
+ // -----------------------------------------------------------------------
228
+ // Row selection
229
+ // -----------------------------------------------------------------------
230
+ selectable = false,
231
+ rowIdField = "id",
232
+ // field name used as unique row identifier
233
+ selectedIds: externalSelectedIds,
234
+ // controlled selection — array of row IDs
235
+ onSelectionChange,
236
+ // (selectedIds[]) => void
237
+ onSelectAllRequest,
238
+ // server-side: ({ selectedIds, pageIds, totalCount }) => void
239
+ selectionActions = [],
240
+ // [{ label, onClick(selectedIds[]), icon?, variant? }]
241
+ selectionResetKey,
242
+ // optional key to force clear uncontrolled selection memory
243
+ resetSelectionOnQueryChange = true,
244
+ // clear uncontrolled selection on search/filter/sort changes
245
+ recordLabel,
246
+ // { singular: "Contact", plural: "Contacts" } — defaults to Record/Records
247
+ // -----------------------------------------------------------------------
248
+ // Row actions
249
+ // -----------------------------------------------------------------------
250
+ rowActions,
251
+ // [{ label, onClick(row), icon?, variant? }] or (row) => actions[]
252
+ hideRowActionsWhenSelectionActive = false,
253
+ // hide row action column while selected-row action bar is visible
254
+ // -----------------------------------------------------------------------
255
+ // Inline editing
256
+ // -----------------------------------------------------------------------
257
+ editMode,
258
+ // "discrete" (click-to-edit) | "inline" (always show inputs)
259
+ editingRowId,
260
+ // controlled — row ID currently in full-row edit mode
261
+ onRowEdit,
262
+ // (row, field, newValue) => void
263
+ onRowEditInput,
264
+ // optional live-input callback: (row, field, inputValue) => void
265
+ // -----------------------------------------------------------------------
266
+ // Auto-width
267
+ // -----------------------------------------------------------------------
268
+ autoWidth = true
269
+ // auto-compute column widths from content analysis
270
+ }) => {
271
+ const initialSortState = useMemo(() => {
272
+ return normalizeSortState(columns, defaultSort);
273
+ }, [columns, defaultSort]);
274
+ const [internalSearchTerm, setInternalSearchTerm] = useState("");
275
+ const [internalFilterValues, setInternalFilterValues] = useState(() => {
276
+ const init = {};
277
+ filters.forEach((f) => {
278
+ init[f.name] = getEmptyFilterValue(f);
279
+ });
280
+ return init;
281
+ });
282
+ const [internalSortState, setInternalSortState] = useState(initialSortState);
283
+ const [currentPage, setCurrentPage] = useState(1);
284
+ const [showMoreFilters, setShowMoreFilters] = useState(false);
285
+ const searchTerm = serverSide && searchValue != null ? searchValue : internalSearchTerm;
286
+ const filterValues = serverSide && externalFilterValues != null ? externalFilterValues : internalFilterValues;
287
+ const externalSortState = useMemo(
288
+ () => normalizeSortState(columns, externalSort),
289
+ [columns, externalSort]
290
+ );
291
+ const sortState = serverSide && externalSort != null ? externalSortState : internalSortState;
292
+ const activePage = serverSide && externalPage != null ? externalPage : currentPage;
293
+ useEffect(() => {
294
+ if (!serverSide) setCurrentPage(1);
295
+ }, [internalSearchTerm, internalFilterValues, internalSortState, serverSide]);
296
+ const debounceRef = useRef(null);
297
+ const fireSearchCallback = useCallback((term) => {
298
+ if (serverSide && onSearchChange) onSearchChange(term);
299
+ }, [serverSide, onSearchChange]);
300
+ const fireParamsChange = useCallback((overrides) => {
301
+ if (!onParamsChange) return;
302
+ const nextSortState = overrides.sort != null ? normalizeSortState(columns, overrides.sort) : sortState;
303
+ onParamsChange({
304
+ search: overrides.search != null ? overrides.search : searchTerm,
305
+ filters: overrides.filters != null ? overrides.filters : filterValues,
306
+ sort: serializeSortState(nextSortState),
307
+ page: overrides.page != null ? overrides.page : activePage
308
+ });
309
+ }, [onParamsChange, columns, searchTerm, filterValues, sortState, activePage]);
310
+ const resetPage = useCallback(() => {
311
+ if (resetPageOnChange) {
312
+ setCurrentPage(1);
313
+ if (serverSide && onPageChange) onPageChange(1);
314
+ }
315
+ }, [resetPageOnChange, serverSide, onPageChange]);
316
+ const handleSearchChange = useCallback((term) => {
317
+ setInternalSearchTerm(term);
318
+ resetPage();
319
+ if (searchDebounce > 0) {
320
+ if (debounceRef.current) clearTimeout(debounceRef.current);
321
+ debounceRef.current = setTimeout(() => {
322
+ fireSearchCallback(term);
323
+ fireParamsChange({ search: term, page: resetPageOnChange ? 1 : void 0 });
324
+ }, searchDebounce);
325
+ } else {
326
+ fireSearchCallback(term);
327
+ fireParamsChange({ search: term, page: resetPageOnChange ? 1 : void 0 });
328
+ }
329
+ }, [searchDebounce, fireSearchCallback, fireParamsChange, resetPage, resetPageOnChange]);
330
+ useEffect(() => () => {
331
+ if (debounceRef.current) clearTimeout(debounceRef.current);
332
+ }, []);
333
+ const handleFilterChange = useCallback((name, value) => {
334
+ const next = { ...filterValues, [name]: value };
335
+ setInternalFilterValues(next);
336
+ if (serverSide && onFilterChange) onFilterChange(next);
337
+ resetPage();
338
+ fireParamsChange({ filters: next, page: resetPageOnChange ? 1 : void 0 });
339
+ }, [filterValues, serverSide, onFilterChange, fireParamsChange, resetPage, resetPageOnChange]);
340
+ const handleSortChange = useCallback((field) => {
341
+ const current = sortState[field] || "none";
342
+ const nextDirection = current === "none" ? "ascending" : current === "ascending" ? "descending" : "none";
343
+ const reset = {};
344
+ columns.forEach((col) => {
345
+ if (col.sortable) reset[col.field] = "none";
346
+ });
347
+ const next = nextDirection === "none" ? reset : { ...reset, [field]: nextDirection };
348
+ setInternalSortState(next);
349
+ if (serverSide && onSortChange) onSortChange(field, nextDirection);
350
+ resetPage();
351
+ fireParamsChange({ sort: next, page: resetPageOnChange ? 1 : void 0 });
352
+ }, [sortState, columns, serverSide, onSortChange, fireParamsChange, resetPage, resetPageOnChange]);
353
+ const handlePageChange = useCallback((page) => {
354
+ setCurrentPage(page);
355
+ if (serverSide && onPageChange) onPageChange(page);
356
+ fireParamsChange({ page });
357
+ }, [serverSide, onPageChange, fireParamsChange]);
358
+ const filteredData = useMemo(() => {
359
+ if (serverSide) return data;
360
+ let result = data;
361
+ filters.forEach((filter) => {
362
+ const value = filterValues[filter.name];
363
+ if (!isFilterActive(filter, value)) return;
364
+ const type = filter.type || "select";
365
+ if (filter.filterFn) {
366
+ result = result.filter((row) => filter.filterFn(row, value));
367
+ } else if (type === "multiselect") {
368
+ result = result.filter((row) => value.includes(row[filter.name]));
369
+ } else if (type === "dateRange") {
370
+ const fromTs = dateToTimestamp(value.from);
371
+ const toTs = value.to ? dateToTimestamp(value.to) + 864e5 - 1 : null;
372
+ result = result.filter((row) => {
373
+ const rowTs = new Date(row[filter.name]).getTime();
374
+ if (Number.isNaN(rowTs)) return false;
375
+ if (fromTs && rowTs < fromTs) return false;
376
+ if (toTs && rowTs > toTs) return false;
377
+ return true;
378
+ });
379
+ } else {
380
+ result = result.filter((row) => row[filter.name] === value);
381
+ }
382
+ });
383
+ if (searchTerm && searchFields.length > 0) {
384
+ if (fuzzySearch) {
385
+ const fuse = new Fuse(result, {
386
+ keys: searchFields,
387
+ threshold: 0.4,
388
+ distance: 100,
389
+ ignoreLocation: true,
390
+ ...fuzzyOptions
391
+ });
392
+ result = fuse.search(searchTerm).map((r) => r.item);
393
+ } else {
394
+ const term = searchTerm.toLowerCase();
395
+ result = result.filter(
396
+ (row) => searchFields.some((field) => {
397
+ const val = row[field];
398
+ return val && String(val).toLowerCase().includes(term);
399
+ })
400
+ );
401
+ }
402
+ }
403
+ return result;
404
+ }, [data, filterValues, searchTerm, filters, searchFields, serverSide, fuzzySearch, fuzzyOptions]);
405
+ const sortedData = useMemo(() => {
406
+ if (serverSide) return filteredData;
407
+ const activeField = Object.keys(sortState).find((k) => sortState[k] !== "none");
408
+ if (!activeField) return filteredData;
409
+ return [...filteredData].sort((a, b) => {
410
+ const dir = sortState[activeField] === "ascending" ? 1 : -1;
411
+ const aVal = a[activeField];
412
+ const bVal = b[activeField];
413
+ if (aVal == null && bVal == null) return 0;
414
+ if (aVal == null) return 1;
415
+ if (bVal == null) return -1;
416
+ if (aVal < bVal) return -dir;
417
+ if (aVal > bVal) return dir;
418
+ return 0;
419
+ });
420
+ }, [filteredData, sortState, serverSide]);
421
+ const groupedData = useMemo(() => {
422
+ if (!groupBy) return null;
423
+ const source = serverSide ? data : sortedData;
424
+ const groups = {};
425
+ source.forEach((row) => {
426
+ const key = row[groupBy.field] ?? "--";
427
+ if (!groups[key]) groups[key] = [];
428
+ groups[key].push(row);
429
+ });
430
+ let groupKeys = Object.keys(groups);
431
+ if (groupBy.sort) {
432
+ if (typeof groupBy.sort === "function") {
433
+ groupKeys.sort(groupBy.sort);
434
+ } else {
435
+ const dir = groupBy.sort === "desc" ? -1 : 1;
436
+ groupKeys.sort((a, b) => a < b ? -dir : a > b ? dir : 0);
437
+ }
438
+ }
439
+ return groupKeys.map((key) => ({
440
+ key,
441
+ label: groupBy.label ? groupBy.label(key, groups[key]) : key,
442
+ rows: groups[key]
443
+ }));
444
+ }, [sortedData, data, groupBy, serverSide]);
445
+ const [expandedGroups, setExpandedGroups] = useState(() => {
446
+ if (!groupBy) return /* @__PURE__ */ new Set();
447
+ const defaultExpanded = groupBy.defaultExpanded !== false;
448
+ if (defaultExpanded && groupedData) {
449
+ return new Set(groupedData.map((g) => g.key));
450
+ }
451
+ return /* @__PURE__ */ new Set();
452
+ });
453
+ useEffect(() => {
454
+ if (!groupedData) return;
455
+ const defaultExpanded = (groupBy == null ? void 0 : groupBy.defaultExpanded) !== false;
456
+ if (defaultExpanded) {
457
+ setExpandedGroups((prev) => {
458
+ const next = new Set(prev);
459
+ groupedData.forEach((g) => next.add(g.key));
460
+ return next;
461
+ });
462
+ }
463
+ }, [groupedData, groupBy]);
464
+ const toggleGroup = useCallback((key) => {
465
+ setExpandedGroups((prev) => {
466
+ const next = new Set(prev);
467
+ if (next.has(key)) next.delete(key);
468
+ else next.add(key);
469
+ return next;
470
+ });
471
+ }, []);
472
+ const flatRows = useMemo(() => {
473
+ if (!groupedData) return (serverSide ? data : sortedData).map((row) => ({ type: "data", row }));
474
+ const flat = [];
475
+ groupedData.forEach((group) => {
476
+ flat.push({ type: "group-header", group });
477
+ if (expandedGroups.has(group.key)) {
478
+ group.rows.forEach((row) => flat.push({ type: "data", row }));
479
+ }
480
+ });
481
+ return flat;
482
+ }, [groupedData, sortedData, data, serverSide, expandedGroups]);
483
+ const totalItems = serverSide ? totalCount || data.length : flatRows.length;
484
+ const pageCount = Math.ceil(totalItems / pageSize);
485
+ let displayRows;
486
+ if (serverSide) {
487
+ displayRows = groupBy ? flatRows : data.map((row) => ({ type: "data", row }));
488
+ } else {
489
+ displayRows = flatRows.slice(
490
+ (activePage - 1) * pageSize,
491
+ activePage * pageSize
492
+ );
493
+ }
494
+ const footerData = serverSide ? data : filteredData;
495
+ const activeChips = useMemo(() => {
496
+ const chips = [];
497
+ filters.forEach((filter) => {
498
+ const value = filterValues[filter.name];
499
+ if (!isFilterActive(filter, value)) return;
500
+ const type = filter.type || "select";
501
+ const prefix = filter.chipLabel || filter.placeholder || filter.name;
502
+ if (type === "multiselect") {
503
+ const labels = value.map((v) => {
504
+ var _a;
505
+ return ((_a = filter.options.find((o) => o.value === v)) == null ? void 0 : _a.label) || v;
506
+ }).join(", ");
507
+ chips.push({ key: filter.name, label: `${prefix}: ${labels}` });
508
+ } else if (type === "dateRange") {
509
+ const parts = [];
510
+ if (value.from) parts.push(`from ${formatDateChip(value.from)}`);
511
+ if (value.to) parts.push(`to ${formatDateChip(value.to)}`);
512
+ chips.push({ key: filter.name, label: `${prefix}: ${parts.join(" ")}` });
513
+ } else {
514
+ const option = filter.options.find((o) => o.value === value);
515
+ chips.push({ key: filter.name, label: `${prefix}: ${(option == null ? void 0 : option.label) || value}` });
516
+ }
517
+ });
518
+ return chips;
519
+ }, [filterValues, filters]);
520
+ const handleFilterRemove = useCallback((key) => {
521
+ if (key === "all") {
522
+ const cleared = {};
523
+ filters.forEach((f) => {
524
+ cleared[f.name] = getEmptyFilterValue(f);
525
+ });
526
+ setInternalFilterValues(cleared);
527
+ if (serverSide && onFilterChange) onFilterChange(cleared);
528
+ resetPage();
529
+ fireParamsChange({ filters: cleared, page: resetPageOnChange ? 1 : void 0 });
530
+ } else {
531
+ const filter = filters.find((f) => f.name === key);
532
+ const emptyVal = filter ? getEmptyFilterValue(filter) : "";
533
+ const next = { ...filterValues, [key]: emptyVal };
534
+ setInternalFilterValues(next);
535
+ if (serverSide && onFilterChange) onFilterChange(next);
536
+ resetPage();
537
+ fireParamsChange({ filters: next, page: resetPageOnChange ? 1 : void 0 });
538
+ }
539
+ }, [filters, filterValues, serverSide, onFilterChange, resetPage, fireParamsChange, resetPageOnChange]);
540
+ const displayCount = serverSide ? totalCount || data.length : filteredData.length;
541
+ const totalDataCount = serverSide ? totalCount || data.length : data.length;
542
+ const shownOnPageCount = displayRows.filter((item) => item.type === "data").length;
543
+ const pluralLabel = ((recordLabel == null ? void 0 : recordLabel.plural) || "records").toLowerCase();
544
+ const singularLabel = ((recordLabel == null ? void 0 : recordLabel.singular) || "record").toLowerCase();
545
+ const countLabel = (n) => n === 1 ? singularLabel : pluralLabel;
546
+ const resolvedEmptyTitle = emptyTitle || "No results found";
547
+ const resolvedEmptyMessage = emptyMessage || `No ${pluralLabel} match your search or filter criteria.`;
548
+ const resolvedLoadingLabel = `Loading ${pluralLabel}...`;
549
+ const recordCountLabel = rowCountText ? rowCountText(shownOnPageCount, displayCount) : displayCount === totalDataCount ? `${totalDataCount} ${countLabel(totalDataCount)}` : `${displayCount} of ${totalDataCount} ${countLabel(totalDataCount)}`;
550
+ const [internalSelectedIds, setInternalSelectedIds] = useState(/* @__PURE__ */ new Set());
551
+ const selectionResetRef = useRef("");
552
+ useEffect(() => {
553
+ if (externalSelectedIds != null) {
554
+ setInternalSelectedIds(new Set(externalSelectedIds));
555
+ }
556
+ }, [externalSelectedIds]);
557
+ const selectionQueryKey = useMemo(() => {
558
+ if (!resetSelectionOnQueryChange) return "";
559
+ return toStableKey({
560
+ search: searchTerm,
561
+ filters: filterValues,
562
+ sort: serializeSortState(sortState)
563
+ });
564
+ }, [searchTerm, filterValues, sortState, resetSelectionOnQueryChange]);
565
+ const combinedSelectionResetKey = useMemo(
566
+ () => `${selectionQueryKey}::${selectionResetKey == null ? "" : toStableKey(selectionResetKey)}`,
567
+ [selectionQueryKey, selectionResetKey]
568
+ );
569
+ useEffect(() => {
570
+ if (!selectable || externalSelectedIds != null) {
571
+ selectionResetRef.current = combinedSelectionResetKey;
572
+ return;
573
+ }
574
+ if (selectionResetRef.current && selectionResetRef.current !== combinedSelectionResetKey) {
575
+ setInternalSelectedIds(/* @__PURE__ */ new Set());
576
+ }
577
+ selectionResetRef.current = combinedSelectionResetKey;
578
+ }, [combinedSelectionResetKey, selectable, externalSelectedIds]);
579
+ const selectedIds = externalSelectedIds != null ? new Set(externalSelectedIds) : internalSelectedIds;
580
+ const showRowActionsColumn = !!rowActions && !(hideRowActionsWhenSelectionActive && selectable && selectedIds.size > 0);
581
+ const applySelection = useCallback((nextSet) => {
582
+ if (externalSelectedIds == null) {
583
+ setInternalSelectedIds(nextSet);
584
+ }
585
+ if (onSelectionChange) onSelectionChange([...nextSet]);
586
+ }, [externalSelectedIds, onSelectionChange]);
587
+ const pageRowIds = useMemo(() => {
588
+ if (serverSide) {
589
+ return data.map((row) => row[rowIdField]).filter((id) => id != null);
590
+ }
591
+ return displayRows.filter((r) => r.type === "data").map((r) => r.row[rowIdField]).filter((id) => id != null);
592
+ }, [serverSide, data, displayRows, rowIdField]);
593
+ const allRowIds = useMemo(
594
+ () => flatRows.filter((r) => r.type === "data").map((r) => r.row[rowIdField]).filter((id) => id != null),
595
+ [flatRows, rowIdField]
596
+ );
597
+ const handleSelectRow = useCallback((rowId, checked) => {
598
+ const next = new Set(selectedIds);
599
+ if (checked) next.add(rowId);
600
+ else next.delete(rowId);
601
+ applySelection(next);
602
+ }, [selectedIds, applySelection]);
603
+ const handleSelectAll = useCallback((checked) => {
604
+ const next = new Set(selectedIds);
605
+ pageRowIds.forEach((id) => {
606
+ if (checked) next.add(id);
607
+ else next.delete(id);
608
+ });
609
+ applySelection(next);
610
+ }, [selectedIds, pageRowIds, applySelection]);
611
+ const allVisibleSelected = useMemo(() => {
612
+ return pageRowIds.length > 0 && pageRowIds.every((id) => selectedIds.has(id));
613
+ }, [pageRowIds, selectedIds]);
614
+ const handleSelectAllRows = useCallback(() => {
615
+ const idsToAdd = serverSide ? pageRowIds : allRowIds;
616
+ const next = new Set(selectedIds);
617
+ idsToAdd.forEach((id) => next.add(id));
618
+ applySelection(next);
619
+ if (serverSide && onSelectAllRequest) {
620
+ onSelectAllRequest({
621
+ selectedIds: [...next],
622
+ pageIds: pageRowIds,
623
+ totalCount: totalCount || data.length
624
+ });
625
+ }
626
+ }, [serverSide, pageRowIds, allRowIds, selectedIds, applySelection, onSelectAllRequest, totalCount, data.length]);
627
+ const handleDeselectAll = useCallback(() => {
628
+ applySelection(/* @__PURE__ */ new Set());
629
+ }, [applySelection]);
630
+ const [editingCell, setEditingCell] = useState(null);
631
+ const [editValue, setEditValue] = useState(null);
632
+ const [editError, setEditError] = useState(null);
633
+ const startEditing = useCallback((rowId, field, currentValue) => {
634
+ setEditingCell({ rowId, field });
635
+ setEditValue(currentValue);
636
+ setEditError(null);
637
+ }, []);
638
+ const commitEdit = useCallback((row, field, value) => {
639
+ const col = columns.find((c) => c.field === field);
640
+ if (col == null ? void 0 : col.editValidate) {
641
+ const result = col.editValidate(value, row);
642
+ if (result !== true && result !== void 0 && result !== null) {
643
+ setEditError(typeof result === "string" ? result : "Invalid value");
644
+ return;
645
+ }
646
+ }
647
+ if (onRowEdit) onRowEdit(row, field, value);
648
+ setEditingCell(null);
649
+ setEditValue(null);
650
+ setEditError(null);
651
+ }, [onRowEdit, columns]);
652
+ const renderEditControl = (col, row) => {
653
+ const type = col.editType || "text";
654
+ const rowId = row[rowIdField];
655
+ const fieldName = `edit-${rowId}-${col.field}`;
656
+ const commit = (val) => commitEdit(row, col.field, val);
657
+ const exitEdit = () => {
658
+ if (editError) return;
659
+ setEditingCell(null);
660
+ setEditValue(null);
661
+ };
662
+ const extra = col.editProps || {};
663
+ const validate = col.editValidate;
664
+ const validationProps = validate && editError ? { error: true, validationMessage: editError } : {};
665
+ const onInputValidate = validate ? (val) => {
666
+ const result = validate(val, row);
667
+ if (result !== true && result !== void 0 && result !== null) {
668
+ setEditError(typeof result === "string" ? result : "Invalid value");
669
+ } else {
670
+ setEditError(null);
671
+ }
672
+ } : void 0;
673
+ const handleInput = (val) => {
674
+ setEditValue(val);
675
+ if (onInputValidate) onInputValidate(val);
676
+ if (onRowEditInput) onRowEditInput(row, col.field, val);
677
+ };
678
+ const maybeExitDatetimeEdit = () => {
679
+ if (typeof document === "undefined") return;
680
+ setTimeout(() => {
681
+ var _a, _b;
682
+ const activeName = (_b = (_a = document.activeElement) == null ? void 0 : _a.getAttribute) == null ? void 0 : _b.call(_a, "name");
683
+ if (activeName !== `${fieldName}-date` && activeName !== `${fieldName}-time`) {
684
+ exitEdit();
685
+ }
686
+ }, 0);
687
+ };
688
+ switch (type) {
689
+ case "textarea":
690
+ return /* @__PURE__ */ React.createElement(TextArea, { ...extra, name: fieldName, label: "", value: editValue ?? "", onChange: commit, onBlur: exitEdit, ...validationProps, onInput: handleInput });
691
+ case "number":
692
+ return /* @__PURE__ */ React.createElement(NumberInput, { ...extra, name: fieldName, label: "", value: editValue, onChange: commit, onBlur: exitEdit, ...validationProps, onInput: handleInput });
693
+ case "currency":
694
+ return /* @__PURE__ */ React.createElement(CurrencyInput, { currencyCode: "USD", ...extra, name: fieldName, label: "", value: editValue, onChange: commit, onBlur: exitEdit, ...validationProps, onInput: handleInput });
695
+ case "stepper":
696
+ return /* @__PURE__ */ React.createElement(StepperInput, { ...extra, name: fieldName, label: "", value: editValue, onChange: commit, onBlur: exitEdit, ...validationProps, onInput: handleInput });
697
+ case "select":
698
+ return /* @__PURE__ */ React.createElement(Select, { variant: "transparent", ...extra, name: fieldName, label: "", value: editValue, onChange: commit, options: resolveEditOptions(col, data) });
699
+ case "multiselect":
700
+ return /* @__PURE__ */ React.createElement(MultiSelect, { ...extra, name: fieldName, label: "", value: editValue || [], onChange: commit, options: resolveEditOptions(col, data) });
701
+ case "date":
702
+ return /* @__PURE__ */ React.createElement(DateInput, { ...extra, name: fieldName, label: "", value: editValue, onChange: commit });
703
+ case "time":
704
+ return /* @__PURE__ */ React.createElement(TimeInput, { ...extra, name: fieldName, label: "", value: editValue, onChange: commit });
705
+ case "datetime":
706
+ return /* @__PURE__ */ React.createElement(Flex, { direction: "row", align: "center", gap: "xs", wrap: "nowrap" }, /* @__PURE__ */ React.createElement(DateInput, { ...extra, name: `${fieldName}-date`, label: "", value: editValue == null ? void 0 : editValue.date, onChange: (val) => {
707
+ const next = { ...editValue, date: val };
708
+ setEditValue(next);
709
+ if (onRowEdit) onRowEdit(row, col.field, next);
710
+ }, onBlur: maybeExitDatetimeEdit }), /* @__PURE__ */ React.createElement(TimeInput, { ...extra.timeProps || {}, name: `${fieldName}-time`, label: "", value: editValue == null ? void 0 : editValue.time, onChange: (val) => {
711
+ const next = { ...editValue, time: val };
712
+ setEditValue(next);
713
+ if (onRowEdit) onRowEdit(row, col.field, next);
714
+ }, onBlur: maybeExitDatetimeEdit }));
715
+ case "toggle":
716
+ return /* @__PURE__ */ React.createElement(Toggle, { ...extra, name: fieldName, label: "", checked: !!editValue, onChange: commit });
717
+ case "checkbox":
718
+ return /* @__PURE__ */ React.createElement(Checkbox, { ...extra, name: fieldName, checked: !!editValue, onChange: commit });
719
+ default:
720
+ return /* @__PURE__ */ React.createElement(Input, { ...extra, name: fieldName, label: "", value: editValue ?? "", onChange: commit, onBlur: exitEdit, ...validationProps, onInput: handleInput });
721
+ }
722
+ };
723
+ const resolvedEditMode = editMode || (columns.some((col) => col.editable) ? "discrete" : null);
724
+ const useColumnRendering = selectable || !!resolvedEditMode || editingRowId != null || showRowActionsColumn || !renderRow;
725
+ const autoWidths = useMemo(
726
+ () => autoWidth ? computeAutoWidths(columns, data) : {},
727
+ [columns, data, autoWidth]
728
+ );
729
+ const defaultWidth = scrollable ? "min" : "auto";
730
+ const getHeaderWidth = (col) => {
731
+ var _a;
732
+ return col.width || ((_a = autoWidths[col.field]) == null ? void 0 : _a.width) || defaultWidth;
733
+ };
734
+ const getCellWidth = (col) => {
735
+ var _a;
736
+ return col.cellWidth || col.width || ((_a = autoWidths[col.field]) == null ? void 0 : _a.cellWidth) || defaultWidth;
737
+ };
738
+ const [inlineErrors, setInlineErrors] = useState({});
739
+ const renderInlineControl = (col, row) => {
740
+ const type = col.editType || "text";
741
+ const rowId = row[rowIdField];
742
+ const fieldName = `inline-${rowId}-${col.field}`;
743
+ const cellKey = `${rowId}-${col.field}`;
744
+ const value = row[col.field];
745
+ const validate = col.editValidate;
746
+ const fire = (val) => {
747
+ if (validate) {
748
+ const result = validate(val, row);
749
+ if (result !== true && result !== void 0 && result !== null) {
750
+ setInlineErrors((prev) => ({ ...prev, [cellKey]: typeof result === "string" ? result : "Invalid value" }));
751
+ return;
752
+ }
753
+ setInlineErrors((prev) => {
754
+ const next = { ...prev };
755
+ delete next[cellKey];
756
+ return next;
757
+ });
758
+ }
759
+ if (onRowEdit) onRowEdit(row, col.field, val);
760
+ };
761
+ const extra = col.editProps || {};
762
+ const cellError = inlineErrors[cellKey];
763
+ const validationProps = cellError ? { error: true, validationMessage: cellError } : {};
764
+ const onInputValidate = validate ? (val) => {
765
+ const result = validate(val, row);
766
+ if (result !== true && result !== void 0 && result !== null) {
767
+ setInlineErrors((prev) => ({ ...prev, [cellKey]: typeof result === "string" ? result : "Invalid value" }));
768
+ } else {
769
+ setInlineErrors((prev) => {
770
+ const next = { ...prev };
771
+ delete next[cellKey];
772
+ return next;
773
+ });
774
+ }
775
+ } : void 0;
776
+ const emitInput = (val) => {
777
+ if (onInputValidate) onInputValidate(val);
778
+ if (onRowEditInput) onRowEditInput(row, col.field, val);
779
+ };
780
+ switch (type) {
781
+ case "textarea":
782
+ return /* @__PURE__ */ React.createElement(TextArea, { ...extra, name: fieldName, label: "", value: value ?? "", onChange: fire, ...validationProps, onInput: emitInput });
783
+ case "number":
784
+ return /* @__PURE__ */ React.createElement(NumberInput, { ...extra, name: fieldName, label: "", value, onChange: fire, ...validationProps, onInput: emitInput });
785
+ case "currency":
786
+ return /* @__PURE__ */ React.createElement(CurrencyInput, { currencyCode: "USD", ...extra, name: fieldName, label: "", value, onChange: fire, ...validationProps, onInput: emitInput });
787
+ case "stepper":
788
+ return /* @__PURE__ */ React.createElement(StepperInput, { ...extra, name: fieldName, label: "", value, onChange: fire, ...validationProps, onInput: emitInput });
789
+ case "select":
790
+ return /* @__PURE__ */ React.createElement(Select, { ...extra, name: fieldName, label: "", value, onChange: fire, options: resolveEditOptions(col, data) });
791
+ case "multiselect":
792
+ return /* @__PURE__ */ React.createElement(MultiSelect, { ...extra, name: fieldName, label: "", value: value || [], onChange: fire, options: resolveEditOptions(col, data) });
793
+ case "date":
794
+ return /* @__PURE__ */ React.createElement(DateInput, { ...extra, name: fieldName, label: "", value, onChange: fire });
795
+ case "time":
796
+ return /* @__PURE__ */ React.createElement(TimeInput, { ...extra, name: fieldName, label: "", value, onChange: fire });
797
+ case "datetime":
798
+ return /* @__PURE__ */ React.createElement(Flex, { direction: "row", align: "center", gap: "xs", wrap: "nowrap" }, /* @__PURE__ */ React.createElement(DateInput, { ...extra, name: `${fieldName}-date`, label: "", value: value == null ? void 0 : value.date, onChange: (val) => {
799
+ fire({ ...value, date: val });
800
+ } }), /* @__PURE__ */ React.createElement(TimeInput, { ...extra.timeProps || {}, name: `${fieldName}-time`, label: "", value: value == null ? void 0 : value.time, onChange: (val) => {
801
+ fire({ ...value, time: val });
802
+ } }));
803
+ case "toggle":
804
+ return /* @__PURE__ */ React.createElement(Toggle, { ...extra, name: fieldName, label: "", checked: !!value, onChange: fire });
805
+ case "checkbox":
806
+ return /* @__PURE__ */ React.createElement(Checkbox, { ...extra, name: fieldName, checked: !!value, onChange: fire });
807
+ default:
808
+ return /* @__PURE__ */ React.createElement(Input, { ...extra, name: fieldName, label: "", value: value ?? "", onChange: fire, ...validationProps, onInput: emitInput });
809
+ }
810
+ };
811
+ const renderCellContent = (row, col) => {
812
+ const rowId = row[rowIdField];
813
+ if (resolvedEditMode === "inline" && col.editable) {
814
+ return renderInlineControl(col, row);
815
+ }
816
+ if (editingRowId != null && rowId === editingRowId && col.editable) {
817
+ return renderInlineControl(col, row);
818
+ }
819
+ const isEditing = (editingCell == null ? void 0 : editingCell.rowId) === rowId && (editingCell == null ? void 0 : editingCell.field) === col.field;
820
+ if (isEditing && col.editable) return renderEditControl(col, row);
821
+ const rawValue = row[col.field];
822
+ const rawStr = String(rawValue ?? "");
823
+ if (col.truncate && rawStr.length > 0) {
824
+ if (col.truncate === true) {
825
+ const content2 = col.renderCell ? col.renderCell(rawValue, row) : rawStr;
826
+ if (col.editable) {
827
+ return /* @__PURE__ */ React.createElement(Text, { truncate: { tooltipText: rawStr } }, /* @__PURE__ */ React.createElement(Link, { variant: "dark", onClick: () => startEditing(rowId, col.field, rawValue) }, content2 || "--"));
828
+ }
829
+ return /* @__PURE__ */ React.createElement(Text, { truncate: { tooltipText: rawStr } }, content2);
830
+ }
831
+ const maxLen = col.truncate.maxLength || 100;
832
+ if (rawStr.length > maxLen) {
833
+ const truncatedStr = rawStr.slice(0, maxLen) + "\u2026";
834
+ const truncatedContent = col.renderCell ? col.renderCell(truncatedStr, row) : truncatedStr;
835
+ if (col.editable) {
836
+ return /* @__PURE__ */ React.createElement(Link, { variant: "dark", onClick: () => startEditing(rowId, col.field, rawValue) }, truncatedContent || "--");
837
+ }
838
+ return /* @__PURE__ */ React.createElement(Text, { truncate: { tooltipText: rawStr } }, truncatedContent || "--");
839
+ }
840
+ }
841
+ const content = col.renderCell ? col.renderCell(rawValue, row) : rawValue;
842
+ const isEmpty = content == null || content === "";
843
+ if (col.editable) {
844
+ return /* @__PURE__ */ React.createElement(
845
+ Link,
846
+ {
847
+ variant: "dark",
848
+ onClick: () => startEditing(rowId, col.field, rawValue)
849
+ },
850
+ isEmpty ? "--" : content
851
+ );
852
+ }
853
+ return isEmpty ? "--" : content;
854
+ };
855
+ const renderFilterControl = (filter) => {
856
+ const type = filter.type || "select";
857
+ if (type === "multiselect") {
858
+ return /* @__PURE__ */ React.createElement(
859
+ MultiSelect,
860
+ {
861
+ key: filter.name,
862
+ name: `filter-${filter.name}`,
863
+ label: "",
864
+ placeholder: filter.placeholder || "All",
865
+ value: filterValues[filter.name] || [],
866
+ onChange: (val) => handleFilterChange(filter.name, val),
867
+ options: filter.options
868
+ }
869
+ );
870
+ }
871
+ if (type === "dateRange") {
872
+ const rangeVal = filterValues[filter.name] || { from: null, to: null };
873
+ return /* @__PURE__ */ React.createElement(Flex, { key: filter.name, direction: "row", align: "center", gap: "xs" }, /* @__PURE__ */ React.createElement(
874
+ DateInput,
875
+ {
876
+ name: `filter-${filter.name}-from`,
877
+ label: "",
878
+ placeholder: "From",
879
+ format: "medium",
880
+ value: rangeVal.from,
881
+ onChange: (val) => handleFilterChange(filter.name, { ...rangeVal, from: val })
882
+ }
883
+ ), /* @__PURE__ */ React.createElement(Icon, { name: "dataSync", size: "sm" }), /* @__PURE__ */ React.createElement(
884
+ DateInput,
885
+ {
886
+ size: "sm",
887
+ name: `filter-${filter.name}-to`,
888
+ label: "",
889
+ placeholder: "To",
890
+ format: "medium",
891
+ value: rangeVal.to,
892
+ onChange: (val) => handleFilterChange(filter.name, { ...rangeVal, to: val })
893
+ }
894
+ ));
895
+ }
896
+ return /* @__PURE__ */ React.createElement(
897
+ Select,
898
+ {
899
+ key: filter.name,
900
+ name: `filter-${filter.name}`,
901
+ variant: "transparent",
902
+ placeholder: filter.placeholder || "All",
903
+ value: filterValues[filter.name],
904
+ onChange: (val) => handleFilterChange(filter.name, val),
905
+ options: [
906
+ { label: filter.placeholder || "All", value: "" },
907
+ ...filter.options
908
+ ]
909
+ }
910
+ );
911
+ };
912
+ return /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "xs" }, /* @__PURE__ */ React.createElement(Flex, { direction: "row", gap: "sm" }, /* @__PURE__ */ React.createElement(Box, { flex: 3 }, /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "sm" }, /* @__PURE__ */ React.createElement(Flex, { direction: "row", align: "center", gap: "sm", wrap: "wrap" }, searchFields.length > 0 && /* @__PURE__ */ React.createElement(
913
+ SearchInput,
914
+ {
915
+ name: "datatable-search",
916
+ placeholder: searchPlaceholder,
917
+ value: searchTerm,
918
+ onChange: handleSearchChange
919
+ }
920
+ ), filters.slice(0, 2).map(renderFilterControl), filters.length > 2 && /* @__PURE__ */ React.createElement(
921
+ Button,
922
+ {
923
+ variant: "transparent",
924
+ size: "small",
925
+ onClick: () => setShowMoreFilters((prev) => !prev)
926
+ },
927
+ /* @__PURE__ */ React.createElement(Icon, { name: "filter", size: "sm" }),
928
+ " Filters"
929
+ )), showMoreFilters && filters.length > 2 && /* @__PURE__ */ React.createElement(Flex, { direction: "row", align: "end", gap: "sm", wrap: "wrap" }, filters.slice(2).map(renderFilterControl)), activeChips.length > 0 && (showFilterBadges || showClearFiltersButton) && /* @__PURE__ */ React.createElement(Flex, { direction: "row", align: "center", gap: "sm", wrap: "wrap" }, showFilterBadges && activeChips.map((chip) => /* @__PURE__ */ React.createElement(Tag, { key: chip.key, variant: "default", onDelete: () => handleFilterRemove(chip.key) }, chip.label)), showClearFiltersButton && /* @__PURE__ */ React.createElement(
930
+ Button,
931
+ {
932
+ variant: "transparent",
933
+ size: "extra-small",
934
+ onClick: () => handleFilterRemove("all")
935
+ },
936
+ "Clear all"
937
+ )))), showRowCount && displayCount > 0 && !(selectable && selectedIds.size > 0) && /* @__PURE__ */ React.createElement(Box, { flex: 1, alignSelf: "end" }, /* @__PURE__ */ React.createElement(Flex, { direction: "row", justify: "end" }, /* @__PURE__ */ React.createElement(Text, { variant: "microcopy", format: rowCountBold ? { fontWeight: "bold" } : void 0 }, recordCountLabel)))), selectable && selectedIds.size > 0 && /* @__PURE__ */ React.createElement(Flex, { direction: "row", gap: "sm" }, /* @__PURE__ */ React.createElement(Box, { flex: 3 }, /* @__PURE__ */ React.createElement(Flex, { direction: "row", align: "center", gap: "sm", wrap: "nowrap" }, /* @__PURE__ */ React.createElement(Text, { inline: true, format: { fontWeight: "demibold" } }, selectedIds.size, "\xA0", countLabel(selectedIds.size), "\xA0selected"), /* @__PURE__ */ React.createElement(Button, { variant: "transparent", size: "extra-small", onClick: handleSelectAllRows }, "Select all ", displayCount, " ", countLabel(displayCount)), /* @__PURE__ */ React.createElement(Button, { variant: "transparent", size: "extra-small", onClick: handleDeselectAll }, "Deselect all"), selectionActions.map((action, i) => /* @__PURE__ */ React.createElement(
938
+ Button,
939
+ {
940
+ key: i,
941
+ variant: action.variant || "transparent",
942
+ size: "extra-small",
943
+ onClick: () => action.onClick([...selectedIds])
944
+ },
945
+ action.icon && /* @__PURE__ */ React.createElement(Icon, { name: action.icon, size: "sm" }),
946
+ " ",
947
+ action.label
948
+ )))), showRowCount && displayCount > 0 && /* @__PURE__ */ React.createElement(Box, { flex: 1, alignSelf: "center" }, /* @__PURE__ */ React.createElement(Flex, { direction: "row", justify: "end" }, /* @__PURE__ */ React.createElement(Text, { variant: "microcopy", format: rowCountBold ? { fontWeight: "bold" } : void 0 }, recordCountLabel)))), loading ? /* @__PURE__ */ React.createElement(LoadingSpinner, { label: resolvedLoadingLabel, layout: "centered" }) : error ? /* @__PURE__ */ React.createElement(ErrorState, { title: typeof error === "string" ? error : "Something went wrong." }, /* @__PURE__ */ React.createElement(Text, null, typeof error === "string" ? "Please try again." : "An error occurred while loading data.")) : displayRows.length === 0 ? /* @__PURE__ */ React.createElement(Flex, { direction: "column", align: "center", justify: "center" }, /* @__PURE__ */ React.createElement(EmptyState, { title: resolvedEmptyTitle, layout: "vertical" }, /* @__PURE__ */ React.createElement(Text, null, resolvedEmptyMessage))) : /* @__PURE__ */ React.createElement(
949
+ Table,
950
+ {
951
+ bordered,
952
+ flush,
953
+ paginated: pageCount > 1,
954
+ page: activePage,
955
+ pageCount,
956
+ onPageChange: handlePageChange,
957
+ showFirstLastButtons: showFirstLastButtons != null ? showFirstLastButtons : pageCount > 5,
958
+ showButtonLabels,
959
+ ...maxVisiblePageButtons != null ? { maxVisiblePageButtons } : {}
960
+ },
961
+ /* @__PURE__ */ React.createElement(TableHead, null, /* @__PURE__ */ React.createElement(TableRow, null, selectable && /* @__PURE__ */ React.createElement(TableHeader, { width: "min" }, /* @__PURE__ */ React.createElement(
962
+ Checkbox,
963
+ {
964
+ name: "datatable-select-all",
965
+ "aria-label": "Select all rows",
966
+ checked: allVisibleSelected,
967
+ onChange: handleSelectAll
968
+ }
969
+ )), columns.map((col) => {
970
+ const headerAlign = resolvedEditMode === "inline" && col.editable ? void 0 : col.align;
971
+ return /* @__PURE__ */ React.createElement(
972
+ TableHeader,
973
+ {
974
+ key: col.field,
975
+ width: getHeaderWidth(col),
976
+ align: headerAlign,
977
+ sortDirection: col.sortable ? sortState[col.field] || "none" : "never",
978
+ onSortChange: col.sortable ? () => handleSortChange(col.field) : void 0
979
+ },
980
+ col.label
981
+ );
982
+ }), showRowActionsColumn && /* @__PURE__ */ React.createElement(TableHeader, { width: "min" }))),
983
+ /* @__PURE__ */ React.createElement(TableBody, null, displayRows.map(
984
+ (item, idx) => item.type === "group-header" ? /* @__PURE__ */ React.createElement(TableRow, { key: `group-${item.group.key}` }, selectable && /* @__PURE__ */ React.createElement(TableCell, { width: "min" }), columns.map((col, colIdx) => {
985
+ var _a, _b, _c;
986
+ return /* @__PURE__ */ React.createElement(TableCell, { key: col.field, width: getCellWidth(col), align: colIdx === 0 ? void 0 : col.align }, colIdx === 0 ? /* @__PURE__ */ React.createElement(
987
+ Link,
988
+ {
989
+ variant: "dark",
990
+ onClick: () => toggleGroup(item.group.key)
991
+ },
992
+ /* @__PURE__ */ React.createElement(Flex, { direction: "row", align: "center", gap: "xs", wrap: "nowrap" }, /* @__PURE__ */ React.createElement(Icon, { name: expandedGroups.has(item.group.key) ? "downCarat" : "right" }), /* @__PURE__ */ React.createElement(Text, { format: { fontWeight: "demibold" } }, item.group.label))
993
+ ) : ((_a = groupBy.aggregations) == null ? void 0 : _a[col.field]) ? groupBy.aggregations[col.field](item.group.rows, item.group.key) : ((_c = (_b = groupBy.groupValues) == null ? void 0 : _b[item.group.key]) == null ? void 0 : _c[col.field]) ?? "");
994
+ }), showRowActionsColumn && /* @__PURE__ */ React.createElement(TableCell, { width: "min" })) : useColumnRendering ? /* @__PURE__ */ React.createElement(TableRow, { key: item.row[rowIdField] ?? idx }, selectable && /* @__PURE__ */ React.createElement(TableCell, { width: "min" }, /* @__PURE__ */ React.createElement(
995
+ Checkbox,
996
+ {
997
+ name: `select-${item.row[rowIdField]}`,
998
+ "aria-label": "Select row",
999
+ checked: selectedIds.has(item.row[rowIdField]),
1000
+ onChange: (checked) => handleSelectRow(item.row[rowIdField], checked)
1001
+ }
1002
+ )), columns.map((col) => {
1003
+ const rowId = item.row[rowIdField];
1004
+ const isDiscreteEditing = resolvedEditMode === "discrete" && (editingCell == null ? void 0 : editingCell.rowId) === rowId && (editingCell == null ? void 0 : editingCell.field) === col.field;
1005
+ const isRowEditing = editingRowId != null && rowId === editingRowId && col.editable;
1006
+ const isShowingInput = isDiscreteEditing || isRowEditing || resolvedEditMode === "inline" && col.editable;
1007
+ const cellAlign = isShowingInput ? void 0 : col.align;
1008
+ return /* @__PURE__ */ React.createElement(TableCell, { key: col.field, width: isDiscreteEditing || isRowEditing ? "auto" : getCellWidth(col), align: cellAlign }, renderCellContent(item.row, col));
1009
+ }), showRowActionsColumn && /* @__PURE__ */ React.createElement(TableCell, { width: "min" }, /* @__PURE__ */ React.createElement(Flex, { direction: "row", align: "center", gap: "xs", wrap: "nowrap" }, (() => {
1010
+ const resolvedRowActions = typeof rowActions === "function" ? rowActions(item.row) : rowActions;
1011
+ const actions = Array.isArray(resolvedRowActions) ? resolvedRowActions : [];
1012
+ return actions.map((action, i) => /* @__PURE__ */ React.createElement(
1013
+ Button,
1014
+ {
1015
+ key: i,
1016
+ variant: action.variant || "transparent",
1017
+ size: "extra-small",
1018
+ onClick: () => action.onClick(item.row)
1019
+ },
1020
+ action.icon && /* @__PURE__ */ React.createElement(Icon, { name: action.icon, size: "sm" }),
1021
+ action.label && ` ${action.label}`
1022
+ ));
1023
+ })()))) : renderRow(item.row)
1024
+ )),
1025
+ (footer || columns.some((col) => col.footer)) && /* @__PURE__ */ React.createElement(TableFooter, null, typeof footer === "function" ? footer(footerData) : /* @__PURE__ */ React.createElement(TableRow, null, selectable && /* @__PURE__ */ React.createElement(TableHeader, { width: "min" }), columns.map((col) => {
1026
+ const footerDef = col.footer;
1027
+ const content = typeof footerDef === "function" ? footerDef(footerData) : footerDef || "";
1028
+ return /* @__PURE__ */ React.createElement(TableHeader, { key: col.field, align: col.align }, content);
1029
+ }), showRowActionsColumn && /* @__PURE__ */ React.createElement(TableHeader, { width: "min" })))
1030
+ ));
1031
+ };
1032
+ export {
1033
+ DataTable
1034
+ };