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.
package/dist/index.mjs ADDED
@@ -0,0 +1,2304 @@
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
+
1033
+ // packages/form/src/FormBuilder.jsx
1034
+ import React2, {
1035
+ useState as useState2,
1036
+ useRef as useRef2,
1037
+ useMemo as useMemo2,
1038
+ useCallback as useCallback2,
1039
+ useEffect as useEffect2,
1040
+ useImperativeHandle,
1041
+ forwardRef
1042
+ } from "react";
1043
+ import {
1044
+ Accordion,
1045
+ Form,
1046
+ Flex as Flex2,
1047
+ Box as Box2,
1048
+ AutoGrid,
1049
+ Tile,
1050
+ Inline,
1051
+ Text as Text2,
1052
+ Link as Link2,
1053
+ Icon as Icon2,
1054
+ Divider,
1055
+ Button as Button2,
1056
+ LoadingButton,
1057
+ Alert,
1058
+ Tooltip,
1059
+ StepIndicator,
1060
+ Input as Input2,
1061
+ TextArea as TextArea2,
1062
+ Select as Select2,
1063
+ MultiSelect as MultiSelect2,
1064
+ NumberInput as NumberInput2,
1065
+ StepperInput as StepperInput2,
1066
+ CurrencyInput as CurrencyInput2,
1067
+ DateInput as DateInput2,
1068
+ TimeInput as TimeInput2,
1069
+ Toggle as Toggle2,
1070
+ Checkbox as Checkbox2,
1071
+ ToggleGroup
1072
+ } from "@hubspot/ui-extensions";
1073
+ import {
1074
+ CrmPropertyList,
1075
+ CrmAssociationPropertyList
1076
+ } from "@hubspot/ui-extensions/crm";
1077
+ var getEmptyValue = (field) => {
1078
+ switch (field.type) {
1079
+ case "toggle":
1080
+ case "checkbox":
1081
+ return false;
1082
+ case "multiselect":
1083
+ case "checkboxGroup":
1084
+ return [];
1085
+ case "number":
1086
+ case "stepper":
1087
+ case "currency":
1088
+ return void 0;
1089
+ case "date":
1090
+ case "time":
1091
+ case "datetime":
1092
+ return void 0;
1093
+ case "display":
1094
+ case "crmPropertyList":
1095
+ case "crmAssociationPropertyList":
1096
+ return void 0;
1097
+ // these field types have no form value
1098
+ case "repeater":
1099
+ return [];
1100
+ default:
1101
+ return "";
1102
+ }
1103
+ };
1104
+ var isValueEmpty = (value, field) => {
1105
+ if (value === void 0 || value === null) return true;
1106
+ if (typeof value === "string" && value.trim() === "") return true;
1107
+ if (Array.isArray(value) && value.length === 0) return true;
1108
+ if ((field.type === "toggle" || field.type === "checkbox") && value === false) return true;
1109
+ return false;
1110
+ };
1111
+ var runValidators = (value, field, allValues, fieldTypes) => {
1112
+ if (field.type === "display" || field.type === "crmPropertyList" || field.type === "crmAssociationPropertyList") return null;
1113
+ const isRequired = resolveRequired(field, allValues);
1114
+ const plugin = fieldTypes && fieldTypes[field.type];
1115
+ const empty = plugin && plugin.isEmpty ? plugin.isEmpty(value) : isValueEmpty(value, field);
1116
+ if (isRequired && empty) {
1117
+ return `${field.label} is required`;
1118
+ }
1119
+ if (empty) return null;
1120
+ if (field.pattern && typeof value === "string") {
1121
+ if (!field.pattern.test(value)) {
1122
+ return field.patternMessage || "Invalid format";
1123
+ }
1124
+ }
1125
+ if (typeof value === "string") {
1126
+ if (field.minLength != null && value.length < field.minLength) {
1127
+ return `Must be at least ${field.minLength} characters`;
1128
+ }
1129
+ if (field.maxLength != null && value.length > field.maxLength) {
1130
+ return `Must be no more than ${field.maxLength} characters`;
1131
+ }
1132
+ }
1133
+ if (typeof value === "number") {
1134
+ if (field.min != null && value < field.min) {
1135
+ return `Must be at least ${field.min}`;
1136
+ }
1137
+ if (field.max != null && value > field.max) {
1138
+ return `Must be no more than ${field.max}`;
1139
+ }
1140
+ }
1141
+ if (field.validate) {
1142
+ const result = field.validate(value, allValues);
1143
+ if (result && typeof result.then === "function") return null;
1144
+ if (result !== true && result) return result;
1145
+ }
1146
+ return null;
1147
+ };
1148
+ var resolveRequired = (field, allValues) => {
1149
+ if (typeof field.required === "function") return field.required(allValues);
1150
+ return !!field.required;
1151
+ };
1152
+ var resolveOptions = (field, allValues) => {
1153
+ if (typeof field.options === "function") return field.options(allValues);
1154
+ return field.options || [];
1155
+ };
1156
+ var useFormPrefill = (properties, mapping) => {
1157
+ return useMemo2(() => {
1158
+ if (!properties) return {};
1159
+ if (!mapping) {
1160
+ const result2 = {};
1161
+ for (const [key, value] of Object.entries(properties)) {
1162
+ if (value !== void 0) result2[key] = value;
1163
+ }
1164
+ return result2;
1165
+ }
1166
+ const result = {};
1167
+ for (const [formField, crmProp] of Object.entries(mapping)) {
1168
+ if (properties[crmProp] !== void 0) {
1169
+ result[formField] = properties[crmProp];
1170
+ }
1171
+ }
1172
+ return result;
1173
+ }, [properties, mapping]);
1174
+ };
1175
+ var FormBuilder = forwardRef(function FormBuilder2(props, ref) {
1176
+ const {
1177
+ fields,
1178
+ // FormBuilderField[] — field definitions
1179
+ onSubmit,
1180
+ // (values, { reset, rawValues }) => void | Promise
1181
+ transformValues,
1182
+ // (values) => values — reshape before submit
1183
+ onBeforeSubmit,
1184
+ // (values) => boolean | Promise<boolean> — intercept submit
1185
+ onSubmitSuccess,
1186
+ // (result, { reset, values }) => void
1187
+ onSubmitError,
1188
+ // (error, { values }) => void
1189
+ resetOnSuccess = false
1190
+ // auto-reset after successful submit
1191
+ } = props;
1192
+ const {
1193
+ initialValues,
1194
+ // Record<string, unknown> — starting values (uncontrolled)
1195
+ values,
1196
+ // Record<string, unknown> — controlled values
1197
+ onChange,
1198
+ // (values) => void — called on any field change (controlled)
1199
+ onFieldChange
1200
+ // (name, value, allValues) => void — per-field change callback
1201
+ } = props;
1202
+ const {
1203
+ validateOnChange = false,
1204
+ // validate on keystroke (onInput)
1205
+ validateOnBlur = true,
1206
+ // validate on blur
1207
+ validateOnSubmit = true,
1208
+ // validate all before onSubmit
1209
+ onValidationChange
1210
+ // (errors) => void
1211
+ } = props;
1212
+ const {
1213
+ steps,
1214
+ // FormBuilderStep[] — enables multi-step mode
1215
+ step: controlledStep,
1216
+ // number — controlled current step (0-based)
1217
+ onStepChange,
1218
+ // (step) => void
1219
+ showStepIndicator = true,
1220
+ // show StepIndicator component
1221
+ validateStepOnNext = true
1222
+ // validate current step fields before Next
1223
+ } = props;
1224
+ const {
1225
+ submitLabel = "Submit",
1226
+ // submit button text
1227
+ submitVariant = "primary",
1228
+ // submit button variant
1229
+ showCancel = false,
1230
+ // show cancel button
1231
+ cancelLabel = "Cancel",
1232
+ // cancel button text
1233
+ onCancel,
1234
+ // () => void
1235
+ submitPosition = "bottom",
1236
+ // "bottom" | "none"
1237
+ loading: controlledLoading,
1238
+ // controlled loading state
1239
+ disabled = false
1240
+ // disable entire form
1241
+ } = props;
1242
+ const {
1243
+ columns = 1,
1244
+ // number of grid columns (1 = full-width stack)
1245
+ columnWidth,
1246
+ // AutoGrid columnWidth — responsive layout (overrides columns)
1247
+ layout,
1248
+ // explicit row layout array (overrides columns + columnWidth)
1249
+ sections,
1250
+ // FormBuilderSection[] — accordion field grouping
1251
+ gap = "sm",
1252
+ // gap between fields
1253
+ showRequiredIndicator = true,
1254
+ // show * on required fields
1255
+ noFormWrapper = false,
1256
+ // skip HubSpot <Form> wrapper
1257
+ fieldTypes
1258
+ // Record<string, FieldTypePlugin> — custom field type registry
1259
+ } = props;
1260
+ const {
1261
+ error: formError,
1262
+ // string | boolean — form-level error alert
1263
+ success: formSuccess,
1264
+ // string — form-level success alert
1265
+ readOnly: formReadOnly = false,
1266
+ // boolean — lock all fields
1267
+ readOnlyMessage
1268
+ // string — warning alert when readOnly
1269
+ } = props;
1270
+ const {
1271
+ onDirtyChange,
1272
+ // (isDirty: boolean) => void
1273
+ autoSave
1274
+ // { debounce: number, onAutoSave: (values) => void }
1275
+ } = props;
1276
+ const computeInitialValues = () => {
1277
+ const vals = {};
1278
+ for (const field of fields) {
1279
+ if (field.type === "display" || field.type === "crmPropertyList" || field.type === "crmAssociationPropertyList") continue;
1280
+ const plugin = fieldTypes && fieldTypes[field.type];
1281
+ const emptyValue = plugin && plugin.getEmptyValue ? plugin.getEmptyValue() : getEmptyValue(field);
1282
+ const init = initialValues && initialValues[field.name] !== void 0 ? initialValues[field.name] : field.defaultValue !== void 0 ? field.defaultValue : emptyValue;
1283
+ vals[field.name] = init;
1284
+ }
1285
+ return vals;
1286
+ };
1287
+ const [internalValues, setInternalValues] = useState2(computeInitialValues);
1288
+ const [internalErrors, setInternalErrors] = useState2({});
1289
+ const [internalStep, setInternalStep] = useState2(0);
1290
+ const [internalLoading, setInternalLoading] = useState2(false);
1291
+ const [touchedFields, setTouchedFields] = useState2({});
1292
+ const [validatingFields, setValidatingFields] = useState2({});
1293
+ const asyncValidationRef = useRef2(/* @__PURE__ */ new Map());
1294
+ const debounceTimersRef = useRef2(/* @__PURE__ */ new Map());
1295
+ const initialSnapshot = useRef2(null);
1296
+ if (initialSnapshot.current === null) {
1297
+ initialSnapshot.current = JSON.stringify(computeInitialValues());
1298
+ }
1299
+ const formValues = values != null ? values : internalValues;
1300
+ const currentStep = controlledStep != null ? controlledStep : internalStep;
1301
+ const isLoading = controlledLoading != null ? controlledLoading : internalLoading;
1302
+ const isMultiStep = Array.isArray(steps) && steps.length > 0;
1303
+ useEffect2(() => {
1304
+ return () => {
1305
+ for (const timer of debounceTimersRef.current.values()) clearTimeout(timer);
1306
+ };
1307
+ }, []);
1308
+ const isDirty = useMemo2(() => {
1309
+ return JSON.stringify(formValues) !== initialSnapshot.current;
1310
+ }, [formValues]);
1311
+ const prevDirtyRef = useRef2(false);
1312
+ useEffect2(() => {
1313
+ if (isDirty !== prevDirtyRef.current) {
1314
+ prevDirtyRef.current = isDirty;
1315
+ if (onDirtyChange) onDirtyChange(isDirty);
1316
+ }
1317
+ }, [isDirty, onDirtyChange]);
1318
+ const autoSaveTimerRef = useRef2(null);
1319
+ useEffect2(() => {
1320
+ if (!autoSave || !autoSave.onAutoSave || !isDirty) return;
1321
+ if (autoSaveTimerRef.current) clearTimeout(autoSaveTimerRef.current);
1322
+ autoSaveTimerRef.current = setTimeout(() => {
1323
+ autoSaveTimerRef.current = null;
1324
+ autoSave.onAutoSave(formValues);
1325
+ }, autoSave.debounce || 1e3);
1326
+ return () => {
1327
+ if (autoSaveTimerRef.current) clearTimeout(autoSaveTimerRef.current);
1328
+ };
1329
+ }, [formValues, isDirty, autoSave]);
1330
+ const visibleFields = useMemo2(() => {
1331
+ let filtered = fields.filter((f) => {
1332
+ if (f.visible && !f.visible(formValues)) return false;
1333
+ return true;
1334
+ });
1335
+ if (isMultiStep && steps[currentStep] && steps[currentStep].fields) {
1336
+ const stepFieldNames = new Set(steps[currentStep].fields);
1337
+ filtered = filtered.filter((f) => stepFieldNames.has(f.name));
1338
+ }
1339
+ return filtered;
1340
+ }, [fields, formValues, isMultiStep, steps, currentStep]);
1341
+ const validateField = useCallback2(
1342
+ (name, value) => {
1343
+ const field = fields.find((f) => f.name === name);
1344
+ if (!field) return null;
1345
+ if (field.visible && !field.visible(formValues)) return null;
1346
+ return runValidators(value != null ? value : formValues[name], field, formValues, fieldTypes);
1347
+ },
1348
+ [fields, formValues, fieldTypes]
1349
+ );
1350
+ const validateVisibleFields = useCallback2(
1351
+ (fieldSubset) => {
1352
+ const toValidate = fieldSubset || visibleFields;
1353
+ const errors = {};
1354
+ let hasErrors = false;
1355
+ for (const field of toValidate) {
1356
+ const err = runValidators(formValues[field.name], field, formValues, fieldTypes);
1357
+ if (err) {
1358
+ errors[field.name] = err;
1359
+ hasErrors = true;
1360
+ }
1361
+ }
1362
+ return { errors, hasErrors };
1363
+ },
1364
+ [visibleFields, formValues]
1365
+ );
1366
+ const updateErrors = useCallback2(
1367
+ (newErrors) => {
1368
+ setInternalErrors((prev) => {
1369
+ const merged = { ...prev, ...newErrors };
1370
+ for (const key of Object.keys(merged)) {
1371
+ if (newErrors[key] === null || newErrors[key] === void 0) {
1372
+ delete merged[key];
1373
+ }
1374
+ }
1375
+ if (onValidationChange) onValidationChange(merged);
1376
+ return merged;
1377
+ });
1378
+ },
1379
+ [onValidationChange]
1380
+ );
1381
+ const runAsyncValidation = useCallback2(
1382
+ (name, value) => {
1383
+ const field = fields.find((f) => f.name === name);
1384
+ if (!field || !field.validate) return;
1385
+ const val = value != null ? value : formValues[name];
1386
+ const syncError = runValidators(val, field, formValues, fieldTypes);
1387
+ if (syncError) return;
1388
+ const result = field.validate(val, formValues);
1389
+ if (!result || typeof result.then !== "function") return;
1390
+ const validationPromise = result.then(
1391
+ (asyncResult) => {
1392
+ if (asyncValidationRef.current.get(name) !== validationPromise) return;
1393
+ asyncValidationRef.current.delete(name);
1394
+ setValidatingFields((prev) => {
1395
+ const next = { ...prev };
1396
+ delete next[name];
1397
+ return next;
1398
+ });
1399
+ const err = asyncResult !== true && asyncResult ? asyncResult : null;
1400
+ updateErrors({ [name]: err });
1401
+ },
1402
+ (rejection) => {
1403
+ if (asyncValidationRef.current.get(name) !== validationPromise) return;
1404
+ asyncValidationRef.current.delete(name);
1405
+ setValidatingFields((prev) => {
1406
+ const next = { ...prev };
1407
+ delete next[name];
1408
+ return next;
1409
+ });
1410
+ updateErrors({ [name]: (rejection == null ? void 0 : rejection.message) || "Validation failed" });
1411
+ }
1412
+ );
1413
+ asyncValidationRef.current.set(name, validationPromise);
1414
+ setValidatingFields((prev) => ({ ...prev, [name]: true }));
1415
+ },
1416
+ [fields, formValues, updateErrors]
1417
+ );
1418
+ const triggerAsyncValidation = useCallback2(
1419
+ (name, value) => {
1420
+ const field = fields.find((f) => f.name === name);
1421
+ if (!field || !field.validate) return;
1422
+ const debounceMs = field.validateDebounce;
1423
+ if (debounceMs && debounceMs > 0) {
1424
+ const existing = debounceTimersRef.current.get(name);
1425
+ if (existing) clearTimeout(existing);
1426
+ const timer = setTimeout(() => {
1427
+ debounceTimersRef.current.delete(name);
1428
+ runAsyncValidation(name, value);
1429
+ }, debounceMs);
1430
+ debounceTimersRef.current.set(name, timer);
1431
+ } else {
1432
+ runAsyncValidation(name, value);
1433
+ }
1434
+ },
1435
+ [fields, runAsyncValidation]
1436
+ );
1437
+ const setFieldValueSilent = useCallback2(
1438
+ (name, value) => {
1439
+ if (values != null) {
1440
+ if (onChange) onChange({ ...formValues, [name]: value });
1441
+ } else {
1442
+ setInternalValues((prev) => ({ ...prev, [name]: value }));
1443
+ }
1444
+ },
1445
+ [values, onChange, formValues]
1446
+ );
1447
+ const handleFieldChange = useCallback2(
1448
+ (name, value) => {
1449
+ const newValues = { ...formValues, [name]: value };
1450
+ if (values != null) {
1451
+ if (onChange) onChange(newValues);
1452
+ } else {
1453
+ setInternalValues(newValues);
1454
+ }
1455
+ if (onFieldChange) onFieldChange(name, value, newValues);
1456
+ if (internalErrors[name]) {
1457
+ updateErrors({ [name]: null });
1458
+ }
1459
+ const field = fields.find((f) => f.name === name);
1460
+ if (field && field.onFieldChange) {
1461
+ field.onFieldChange(value, newValues, {
1462
+ setFieldValue: setFieldValueSilent,
1463
+ setFieldError: (fieldName, message) => updateErrors({ [fieldName]: message })
1464
+ });
1465
+ }
1466
+ },
1467
+ [formValues, values, onChange, onFieldChange, internalErrors, updateErrors, fields, setFieldValueSilent]
1468
+ );
1469
+ const inputDebounceRef = useRef2(/* @__PURE__ */ new Map());
1470
+ const handleDebouncedFieldChange = useCallback2(
1471
+ (name, value) => {
1472
+ const field = fields.find((f) => f.name === name);
1473
+ const debounceMs = field && field.debounce;
1474
+ if (debounceMs && debounceMs > 0) {
1475
+ const existing = inputDebounceRef.current.get(name);
1476
+ if (existing) clearTimeout(existing);
1477
+ const timer = setTimeout(() => {
1478
+ inputDebounceRef.current.delete(name);
1479
+ handleFieldChange(name, value);
1480
+ }, debounceMs);
1481
+ inputDebounceRef.current.set(name, timer);
1482
+ } else {
1483
+ handleFieldChange(name, value);
1484
+ }
1485
+ },
1486
+ [fields, handleFieldChange]
1487
+ );
1488
+ const handleFieldInput = useCallback2(
1489
+ (name, value) => {
1490
+ if (validateOnChange) {
1491
+ const err = validateField(name, value);
1492
+ updateErrors({ [name]: err });
1493
+ }
1494
+ },
1495
+ [validateOnChange, validateField, updateErrors]
1496
+ );
1497
+ const handleFieldBlur = useCallback2(
1498
+ (name, value) => {
1499
+ setTouchedFields((prev) => ({ ...prev, [name]: true }));
1500
+ if (validateOnBlur) {
1501
+ const err = validateField(name, value != null ? value : formValues[name]);
1502
+ updateErrors({ [name]: err });
1503
+ if (!err) {
1504
+ triggerAsyncValidation(name, value != null ? value : formValues[name]);
1505
+ }
1506
+ }
1507
+ },
1508
+ [validateOnBlur, validateField, updateErrors, formValues, triggerAsyncValidation]
1509
+ );
1510
+ const handleSubmit = useCallback2(
1511
+ async (e) => {
1512
+ if (e && e.preventDefault) e.preventDefault();
1513
+ if (validateOnSubmit) {
1514
+ const allVisible = fields.filter((f) => !f.visible || f.visible(formValues));
1515
+ const { errors, hasErrors } = validateVisibleFields(allVisible);
1516
+ if (hasErrors) {
1517
+ setInternalErrors(errors);
1518
+ if (onValidationChange) onValidationChange(errors);
1519
+ return;
1520
+ }
1521
+ if (asyncValidationRef.current.size > 0) {
1522
+ await Promise.all(asyncValidationRef.current.values());
1523
+ const currentErrors = { ...internalErrors };
1524
+ const hasAsyncErrors = Object.keys(currentErrors).length > 0;
1525
+ if (hasAsyncErrors) return;
1526
+ }
1527
+ }
1528
+ const reset = () => {
1529
+ const fresh = computeInitialValues();
1530
+ if (values == null) setInternalValues(fresh);
1531
+ setInternalErrors({});
1532
+ setTouchedFields({});
1533
+ initialSnapshot.current = JSON.stringify(fresh);
1534
+ };
1535
+ const rawValues = {};
1536
+ for (const key of Object.keys(formValues)) {
1537
+ const f = fields.find((fd) => fd.name === key);
1538
+ if (f && (f.type === "display" || f.type === "crmPropertyList" || f.type === "crmAssociationPropertyList")) continue;
1539
+ rawValues[key] = formValues[key];
1540
+ }
1541
+ const submitValues = transformValues ? transformValues(rawValues) : rawValues;
1542
+ if (onBeforeSubmit) {
1543
+ const proceed = await onBeforeSubmit(submitValues);
1544
+ if (proceed === false) return;
1545
+ }
1546
+ if (controlledLoading == null) setInternalLoading(true);
1547
+ try {
1548
+ const result = await onSubmit(submitValues, { reset, rawValues });
1549
+ if (resetOnSuccess) reset();
1550
+ if (onSubmitSuccess) onSubmitSuccess(result, { reset, values: submitValues });
1551
+ } catch (err) {
1552
+ if (onSubmitError) {
1553
+ onSubmitError(err, { values: submitValues });
1554
+ } else {
1555
+ throw err;
1556
+ }
1557
+ } finally {
1558
+ if (controlledLoading == null) setInternalLoading(false);
1559
+ }
1560
+ },
1561
+ [validateOnSubmit, fields, formValues, validateVisibleFields, onValidationChange, onSubmit, values, controlledLoading, internalErrors, transformValues, onBeforeSubmit, onSubmitSuccess, onSubmitError, resetOnSuccess]
1562
+ );
1563
+ const handleNext = useCallback2(() => {
1564
+ if (!isMultiStep) return;
1565
+ if (validateStepOnNext && steps[currentStep] && steps[currentStep].fields) {
1566
+ const stepFields = fields.filter(
1567
+ (f) => steps[currentStep].fields.includes(f.name) && (!f.visible || f.visible(formValues))
1568
+ );
1569
+ const { errors, hasErrors } = validateVisibleFields(stepFields);
1570
+ if (hasErrors) {
1571
+ setInternalErrors((prev) => ({ ...prev, ...errors }));
1572
+ if (onValidationChange) onValidationChange({ ...internalErrors, ...errors });
1573
+ return;
1574
+ }
1575
+ }
1576
+ if (steps[currentStep] && steps[currentStep].validate) {
1577
+ const result = steps[currentStep].validate(formValues);
1578
+ if (result !== true && result) {
1579
+ setInternalErrors((prev) => ({ ...prev, ...result }));
1580
+ return;
1581
+ }
1582
+ }
1583
+ const nextStep = Math.min(currentStep + 1, steps.length - 1);
1584
+ if (controlledStep != null) {
1585
+ if (onStepChange) onStepChange(nextStep);
1586
+ } else {
1587
+ setInternalStep(nextStep);
1588
+ }
1589
+ }, [isMultiStep, validateStepOnNext, steps, currentStep, fields, formValues, validateVisibleFields, onValidationChange, internalErrors, controlledStep, onStepChange]);
1590
+ const handleBack = useCallback2(() => {
1591
+ if (!isMultiStep) return;
1592
+ const prevStep = Math.max(currentStep - 1, 0);
1593
+ if (controlledStep != null) {
1594
+ if (onStepChange) onStepChange(prevStep);
1595
+ } else {
1596
+ setInternalStep(prevStep);
1597
+ }
1598
+ }, [isMultiStep, currentStep, controlledStep, onStepChange]);
1599
+ const handleGoTo = useCallback2(
1600
+ (stepIndex) => {
1601
+ if (!isMultiStep) return;
1602
+ const clamped = Math.max(0, Math.min(stepIndex, steps.length - 1));
1603
+ if (controlledStep != null) {
1604
+ if (onStepChange) onStepChange(clamped);
1605
+ } else {
1606
+ setInternalStep(clamped);
1607
+ }
1608
+ },
1609
+ [isMultiStep, steps, controlledStep, onStepChange]
1610
+ );
1611
+ useImperativeHandle(ref, () => ({
1612
+ submit: handleSubmit,
1613
+ validate: () => {
1614
+ const allVisible = fields.filter((f) => !f.visible || f.visible(formValues));
1615
+ const { errors, hasErrors } = validateVisibleFields(allVisible);
1616
+ setInternalErrors(errors);
1617
+ return { valid: !hasErrors, errors };
1618
+ },
1619
+ reset: () => {
1620
+ const fresh = computeInitialValues();
1621
+ if (values == null) setInternalValues(fresh);
1622
+ setInternalErrors({});
1623
+ setTouchedFields({});
1624
+ initialSnapshot.current = JSON.stringify(fresh);
1625
+ },
1626
+ getValues: () => formValues,
1627
+ isDirty: () => isDirty,
1628
+ setFieldValue: (name, value) => handleFieldChange(name, value),
1629
+ setFieldError: (name, message) => updateErrors({ [name]: message }),
1630
+ setErrors: (errors) => {
1631
+ setInternalErrors(errors);
1632
+ if (onValidationChange) onValidationChange(errors);
1633
+ }
1634
+ }));
1635
+ const renderField = (field) => {
1636
+ const fieldValue = formValues[field.name];
1637
+ const fieldError = internalErrors[field.name] || null;
1638
+ const hasError = !!fieldError;
1639
+ const isRequired = showRequiredIndicator && resolveRequired(field, formValues);
1640
+ const isReadOnly = field.readOnly || disabled || formReadOnly;
1641
+ const fieldOnChange = field.debounce ? (v) => handleDebouncedFieldChange(field.name, v) : (v) => handleFieldChange(field.name, v);
1642
+ if (field.type === "display") {
1643
+ if (field.render) {
1644
+ return field.render({ allValues: formValues });
1645
+ }
1646
+ return null;
1647
+ }
1648
+ if (field.type === "crmPropertyList") {
1649
+ return /* @__PURE__ */ React2.createElement(
1650
+ CrmPropertyList,
1651
+ {
1652
+ properties: field.properties,
1653
+ direction: field.direction,
1654
+ ...field.objectId ? { objectId: field.objectId } : {},
1655
+ ...field.objectTypeId ? { objectTypeId: field.objectTypeId } : {},
1656
+ ...field.fieldProps || {}
1657
+ }
1658
+ );
1659
+ }
1660
+ if (field.type === "crmAssociationPropertyList") {
1661
+ return /* @__PURE__ */ React2.createElement(
1662
+ CrmAssociationPropertyList,
1663
+ {
1664
+ objectTypeId: field.objectTypeId,
1665
+ properties: field.properties,
1666
+ ...field.associationLabels ? { associationLabels: field.associationLabels } : {},
1667
+ ...field.filters ? { filters: field.filters } : {},
1668
+ ...field.sort ? { sort: field.sort } : {},
1669
+ ...field.fieldProps || {}
1670
+ }
1671
+ );
1672
+ }
1673
+ if (field.render) {
1674
+ return field.render({
1675
+ value: fieldValue,
1676
+ onChange: fieldOnChange,
1677
+ error: hasError,
1678
+ allValues: formValues
1679
+ });
1680
+ }
1681
+ const plugin = fieldTypes && fieldTypes[field.type];
1682
+ if (plugin && plugin.render) {
1683
+ return plugin.render({
1684
+ value: fieldValue,
1685
+ onChange: fieldOnChange,
1686
+ error: hasError,
1687
+ field,
1688
+ allValues: formValues
1689
+ });
1690
+ }
1691
+ const commonProps = {
1692
+ name: field.name,
1693
+ label: field.label,
1694
+ description: field.description,
1695
+ placeholder: field.placeholder,
1696
+ tooltip: field.tooltip,
1697
+ required: isRequired,
1698
+ readOnly: isReadOnly,
1699
+ error: hasError,
1700
+ validationMessage: fieldError || void 0,
1701
+ ...field.loading || validatingFields[field.name] ? { loading: true } : {},
1702
+ ...field.fieldProps || {}
1703
+ };
1704
+ const options = resolveOptions(field, formValues);
1705
+ switch (field.type) {
1706
+ case "text":
1707
+ case "password":
1708
+ return /* @__PURE__ */ React2.createElement(
1709
+ Input2,
1710
+ {
1711
+ ...commonProps,
1712
+ type: field.type === "password" ? "password" : "text",
1713
+ value: fieldValue || "",
1714
+ onChange: fieldOnChange,
1715
+ onInput: (v) => handleFieldInput(field.name, v),
1716
+ onBlur: (v) => handleFieldBlur(field.name, v)
1717
+ }
1718
+ );
1719
+ case "textarea":
1720
+ return /* @__PURE__ */ React2.createElement(
1721
+ TextArea2,
1722
+ {
1723
+ ...commonProps,
1724
+ value: fieldValue || "",
1725
+ rows: field.rows,
1726
+ cols: field.cols,
1727
+ resize: field.resize,
1728
+ maxLength: field.maxLength,
1729
+ onChange: fieldOnChange,
1730
+ onInput: (v) => handleFieldInput(field.name, v),
1731
+ onBlur: (v) => handleFieldBlur(field.name, v)
1732
+ }
1733
+ );
1734
+ case "number":
1735
+ return /* @__PURE__ */ React2.createElement(
1736
+ NumberInput2,
1737
+ {
1738
+ ...commonProps,
1739
+ value: fieldValue,
1740
+ min: field.min,
1741
+ max: field.max,
1742
+ precision: field.precision,
1743
+ formatStyle: field.formatStyle,
1744
+ onChange: fieldOnChange,
1745
+ onBlur: (v) => handleFieldBlur(field.name, v)
1746
+ }
1747
+ );
1748
+ case "stepper":
1749
+ return /* @__PURE__ */ React2.createElement(
1750
+ StepperInput2,
1751
+ {
1752
+ ...commonProps,
1753
+ value: fieldValue,
1754
+ min: field.min,
1755
+ max: field.max,
1756
+ precision: field.precision,
1757
+ formatStyle: field.formatStyle,
1758
+ stepSize: field.stepSize,
1759
+ minValueReachedTooltip: field.minValueReachedTooltip,
1760
+ maxValueReachedTooltip: field.maxValueReachedTooltip,
1761
+ onChange: fieldOnChange,
1762
+ onBlur: (v) => handleFieldBlur(field.name, v)
1763
+ }
1764
+ );
1765
+ case "currency":
1766
+ return /* @__PURE__ */ React2.createElement(
1767
+ CurrencyInput2,
1768
+ {
1769
+ ...commonProps,
1770
+ currency: field.currency || "USD",
1771
+ value: fieldValue,
1772
+ min: field.min,
1773
+ max: field.max,
1774
+ precision: field.precision,
1775
+ onChange: fieldOnChange,
1776
+ onBlur: (v) => handleFieldBlur(field.name, v)
1777
+ }
1778
+ );
1779
+ case "date":
1780
+ return /* @__PURE__ */ React2.createElement(
1781
+ DateInput2,
1782
+ {
1783
+ ...commonProps,
1784
+ value: fieldValue,
1785
+ format: field.format,
1786
+ min: field.min,
1787
+ max: field.max,
1788
+ timezone: field.timezone,
1789
+ clearButtonLabel: field.clearButtonLabel,
1790
+ todayButtonLabel: field.todayButtonLabel,
1791
+ minValidationMessage: field.minValidationMessage,
1792
+ maxValidationMessage: field.maxValidationMessage,
1793
+ onChange: fieldOnChange,
1794
+ onBlur: (v) => handleFieldBlur(field.name, v)
1795
+ }
1796
+ );
1797
+ case "time":
1798
+ return /* @__PURE__ */ React2.createElement(
1799
+ TimeInput2,
1800
+ {
1801
+ ...commonProps,
1802
+ value: fieldValue,
1803
+ interval: field.interval,
1804
+ min: field.min,
1805
+ max: field.max,
1806
+ timezone: field.timezone,
1807
+ onChange: fieldOnChange,
1808
+ onBlur: (v) => handleFieldBlur(field.name, v)
1809
+ }
1810
+ );
1811
+ case "datetime": {
1812
+ const dateVal = fieldValue ? fieldValue.date || fieldValue : void 0;
1813
+ const timeVal = fieldValue ? fieldValue.time || void 0 : void 0;
1814
+ return /* @__PURE__ */ React2.createElement(Flex2, { direction: "row", gap: "sm" }, /* @__PURE__ */ React2.createElement(Box2, { flex: 1 }, /* @__PURE__ */ React2.createElement(
1815
+ DateInput2,
1816
+ {
1817
+ ...commonProps,
1818
+ name: `${field.name}-date`,
1819
+ label: field.label,
1820
+ format: field.format,
1821
+ value: dateVal,
1822
+ min: field.min,
1823
+ max: field.max,
1824
+ timezone: field.timezone,
1825
+ clearButtonLabel: field.clearButtonLabel,
1826
+ todayButtonLabel: field.todayButtonLabel,
1827
+ minValidationMessage: field.minValidationMessage,
1828
+ maxValidationMessage: field.maxValidationMessage,
1829
+ onChange: (v) => {
1830
+ handleFieldChange(field.name, { ...fieldValue, date: v, time: timeVal });
1831
+ }
1832
+ }
1833
+ )), /* @__PURE__ */ React2.createElement(Box2, { flex: 1 }, /* @__PURE__ */ React2.createElement(
1834
+ TimeInput2,
1835
+ {
1836
+ name: `${field.name}-time`,
1837
+ label: "Time",
1838
+ description: field.description,
1839
+ tooltip: field.tooltip,
1840
+ readOnly: isReadOnly,
1841
+ error: hasError,
1842
+ value: timeVal,
1843
+ interval: field.interval,
1844
+ timezone: field.timezone,
1845
+ onChange: (v) => {
1846
+ handleFieldChange(field.name, { ...fieldValue, date: dateVal, time: v });
1847
+ }
1848
+ }
1849
+ )));
1850
+ }
1851
+ case "select":
1852
+ return /* @__PURE__ */ React2.createElement(
1853
+ Select2,
1854
+ {
1855
+ ...commonProps,
1856
+ value: fieldValue,
1857
+ options,
1858
+ variant: field.variant,
1859
+ onChange: fieldOnChange
1860
+ }
1861
+ );
1862
+ case "multiselect":
1863
+ return /* @__PURE__ */ React2.createElement(
1864
+ MultiSelect2,
1865
+ {
1866
+ ...commonProps,
1867
+ value: fieldValue || [],
1868
+ options,
1869
+ onChange: fieldOnChange
1870
+ }
1871
+ );
1872
+ case "toggle":
1873
+ return /* @__PURE__ */ React2.createElement(
1874
+ Toggle2,
1875
+ {
1876
+ name: field.name,
1877
+ label: field.label,
1878
+ checked: !!fieldValue,
1879
+ size: field.size || "md",
1880
+ labelDisplay: field.labelDisplay || "top",
1881
+ textChecked: field.textChecked,
1882
+ textUnchecked: field.textUnchecked,
1883
+ readonly: isReadOnly,
1884
+ onChange: fieldOnChange,
1885
+ ...field.fieldProps || {}
1886
+ }
1887
+ );
1888
+ case "checkbox":
1889
+ return /* @__PURE__ */ React2.createElement(
1890
+ Checkbox2,
1891
+ {
1892
+ name: field.name,
1893
+ checked: !!fieldValue,
1894
+ description: field.description,
1895
+ readOnly: isReadOnly,
1896
+ inline: field.inline,
1897
+ variant: field.variant,
1898
+ onChange: fieldOnChange,
1899
+ ...field.fieldProps || {}
1900
+ },
1901
+ field.label
1902
+ );
1903
+ case "checkboxGroup":
1904
+ return /* @__PURE__ */ React2.createElement(
1905
+ ToggleGroup,
1906
+ {
1907
+ ...commonProps,
1908
+ toggleType: "checkboxList",
1909
+ value: fieldValue || [],
1910
+ options,
1911
+ inline: field.inline,
1912
+ variant: field.variant,
1913
+ onChange: fieldOnChange
1914
+ }
1915
+ );
1916
+ case "radioGroup":
1917
+ return /* @__PURE__ */ React2.createElement(
1918
+ ToggleGroup,
1919
+ {
1920
+ ...commonProps,
1921
+ toggleType: "radioButtonList",
1922
+ value: fieldValue,
1923
+ options,
1924
+ inline: field.inline,
1925
+ variant: field.variant,
1926
+ onChange: fieldOnChange
1927
+ }
1928
+ );
1929
+ case "repeater": {
1930
+ const rows = Array.isArray(fieldValue) ? fieldValue : [];
1931
+ const subFields = field.fields || [];
1932
+ const minRows = field.min || 0;
1933
+ const maxRows = field.max || Infinity;
1934
+ const canAdd = rows.length < maxRows && !isReadOnly;
1935
+ const canRemove = rows.length > minRows && !isReadOnly;
1936
+ const addRow = () => {
1937
+ const emptyRow = {};
1938
+ for (const sf of subFields) {
1939
+ emptyRow[sf.name] = sf.defaultValue !== void 0 ? sf.defaultValue : getEmptyValue(sf);
1940
+ }
1941
+ handleFieldChange(field.name, [...rows, emptyRow]);
1942
+ };
1943
+ const removeRow = (idx) => {
1944
+ handleFieldChange(field.name, rows.filter((_, i) => i !== idx));
1945
+ };
1946
+ const updateRow = (idx, subName, subValue) => {
1947
+ const updated = rows.map(
1948
+ (row, i) => i === idx ? { ...row, [subName]: subValue } : row
1949
+ );
1950
+ handleFieldChange(field.name, updated);
1951
+ };
1952
+ return /* @__PURE__ */ React2.createElement(Flex2, { direction: "column", gap: "xs" }, field.label && /* @__PURE__ */ React2.createElement(Text2, { format: { fontWeight: "demibold" } }, field.label, isRequired ? " *" : ""), field.description && /* @__PURE__ */ React2.createElement(Text2, { variant: "microcopy" }, field.description), rows.map((row, rowIdx) => /* @__PURE__ */ React2.createElement(Flex2, { key: rowIdx, direction: "row", gap: "xs", align: "end" }, subFields.map((sf) => {
1953
+ const sfValue = row[sf.name];
1954
+ const sfLabel = rowIdx === 0 ? sf.label : void 0;
1955
+ const sfOptions = resolveOptions(sf, formValues);
1956
+ const sfProps = {
1957
+ name: `${field.name}-${rowIdx}-${sf.name}`,
1958
+ label: sfLabel,
1959
+ placeholder: sf.placeholder,
1960
+ readOnly: isReadOnly,
1961
+ ...sf.fieldProps || {}
1962
+ };
1963
+ let sfElement;
1964
+ switch (sf.type) {
1965
+ case "select":
1966
+ sfElement = /* @__PURE__ */ React2.createElement(Select2, { ...sfProps, value: sfValue, options: sfOptions, onChange: (v) => updateRow(rowIdx, sf.name, v) });
1967
+ break;
1968
+ case "number":
1969
+ sfElement = /* @__PURE__ */ React2.createElement(NumberInput2, { ...sfProps, value: sfValue, onChange: (v) => updateRow(rowIdx, sf.name, v) });
1970
+ break;
1971
+ case "checkbox":
1972
+ sfElement = /* @__PURE__ */ React2.createElement(Checkbox2, { ...sfProps, checked: !!sfValue, onChange: (v) => updateRow(rowIdx, sf.name, v) }, sf.label);
1973
+ break;
1974
+ default:
1975
+ sfElement = /* @__PURE__ */ React2.createElement(Input2, { ...sfProps, value: sfValue || "", onChange: (v) => updateRow(rowIdx, sf.name, v) });
1976
+ }
1977
+ return /* @__PURE__ */ React2.createElement(Box2, { key: sf.name, flex: 1 }, sfElement);
1978
+ }), canRemove && /* @__PURE__ */ React2.createElement(
1979
+ Button2,
1980
+ {
1981
+ variant: "secondary",
1982
+ size: "xs",
1983
+ onClick: () => removeRow(rowIdx)
1984
+ },
1985
+ "Remove"
1986
+ ))), canAdd && /* @__PURE__ */ React2.createElement(Button2, { variant: "secondary", size: "sm", onClick: addRow }, "+ Add"), hasError && /* @__PURE__ */ React2.createElement(Text2, { variant: "microcopy" }, fieldError));
1987
+ }
1988
+ default:
1989
+ return /* @__PURE__ */ React2.createElement(
1990
+ Input2,
1991
+ {
1992
+ ...commonProps,
1993
+ value: fieldValue || "",
1994
+ onChange: fieldOnChange,
1995
+ onInput: (v) => handleFieldInput(field.name, v),
1996
+ onBlur: (v) => handleFieldBlur(field.name, v)
1997
+ }
1998
+ );
1999
+ }
2000
+ };
2001
+ const getFieldColSpan = (field) => {
2002
+ if (field.colSpan != null) return Math.min(field.colSpan, columns);
2003
+ if (field.width === "full" && columns > 1) return columns;
2004
+ return 1;
2005
+ };
2006
+ const getDependents = (parentField) => visibleFields.filter((f) => f.dependsOn === parentField.name && f.name !== parentField.name);
2007
+ const isDependent = (field) => field.dependsOn && visibleFields.some((f) => f.name === field.dependsOn && f.name !== field.name);
2008
+ const renderDependentGroup = (parentField, dependents) => {
2009
+ const firstWithLabel = dependents.find((f) => f.dependsOnLabel) || dependents[0];
2010
+ const firstWithMessage = dependents.find((f) => f.dependsOnMessage) || dependents[0];
2011
+ const groupLabel = firstWithLabel.dependsOnLabel || "Dependent properties";
2012
+ const rawMessage = firstWithMessage.dependsOnMessage;
2013
+ const tooltipMessage = typeof rawMessage === "function" ? rawMessage(parentField.label) : rawMessage || "";
2014
+ return /* @__PURE__ */ React2.createElement(Tile, { key: `dep-${parentField.name}`, compact: true }, /* @__PURE__ */ React2.createElement(Flex2, { direction: "column", gap }, /* @__PURE__ */ React2.createElement(Flex2, { direction: "row", align: "center", gap: "xs" }, /* @__PURE__ */ React2.createElement(Text2, { format: { fontWeight: "demibold" } }, groupLabel, " ", tooltipMessage && /* @__PURE__ */ React2.createElement(Link2, { inline: true, variant: "dark", overlay: /* @__PURE__ */ React2.createElement(Tooltip, null, tooltipMessage) }, /* @__PURE__ */ React2.createElement(Icon2, { name: "info" })))), dependents.map((dep) => /* @__PURE__ */ React2.createElement(React2.Fragment, { key: dep.name }, renderField(dep)))));
2015
+ };
2016
+ const renderGridLayout = (fieldSubset) => {
2017
+ const fieldList = fieldSubset || visibleFields;
2018
+ const elements = [];
2019
+ let currentRow = [];
2020
+ let currentRowSpan = 0;
2021
+ const flushRow = () => {
2022
+ if (currentRow.length === 0) return;
2023
+ const totalSpan = currentRow.reduce((s, f) => s + getFieldColSpan(f), 0);
2024
+ const remainder = columns - totalSpan;
2025
+ elements.push(
2026
+ /* @__PURE__ */ React2.createElement(Flex2, { key: `row-${currentRow[0].name}`, direction: "row", gap }, currentRow.map((f) => /* @__PURE__ */ React2.createElement(Box2, { key: f.name, flex: getFieldColSpan(f) }, renderField(f))), remainder > 0 && /* @__PURE__ */ React2.createElement(Box2, { flex: remainder }))
2027
+ );
2028
+ currentRow = [];
2029
+ currentRowSpan = 0;
2030
+ };
2031
+ for (const field of fieldList) {
2032
+ if (isDependent(field)) continue;
2033
+ const span = getFieldColSpan(field);
2034
+ if (span >= columns) {
2035
+ flushRow();
2036
+ elements.push(
2037
+ /* @__PURE__ */ React2.createElement(React2.Fragment, { key: field.name }, renderField(field))
2038
+ );
2039
+ } else {
2040
+ if (currentRowSpan + span > columns) flushRow();
2041
+ currentRow.push(field);
2042
+ currentRowSpan += span;
2043
+ if (currentRowSpan >= columns) flushRow();
2044
+ }
2045
+ const dependents = getDependents(field);
2046
+ if (dependents.length > 0) {
2047
+ flushRow();
2048
+ elements.push(renderDependentGroup(field, dependents));
2049
+ }
2050
+ }
2051
+ flushRow();
2052
+ return elements;
2053
+ };
2054
+ const renderExplicitLayout = () => {
2055
+ const elements = [];
2056
+ const renderedNames = /* @__PURE__ */ new Set();
2057
+ for (let rowIdx = 0; rowIdx < layout.length; rowIdx++) {
2058
+ const row = layout[rowIdx];
2059
+ const rowFields = [];
2060
+ for (const entry of row) {
2061
+ const fieldName = typeof entry === "string" ? entry : entry.field;
2062
+ const flexValue = typeof entry === "string" ? 1 : entry.flex || 1;
2063
+ const field = visibleFields.find((f) => f.name === fieldName);
2064
+ if (!field) continue;
2065
+ rowFields.push({ field, flex: flexValue });
2066
+ renderedNames.add(fieldName);
2067
+ }
2068
+ if (rowFields.length === 0) continue;
2069
+ if (rowFields.length === 1) {
2070
+ elements.push(
2071
+ /* @__PURE__ */ React2.createElement(React2.Fragment, { key: rowFields[0].field.name }, renderField(rowFields[0].field))
2072
+ );
2073
+ } else {
2074
+ elements.push(
2075
+ /* @__PURE__ */ React2.createElement(Flex2, { key: `layout-row-${rowIdx}`, direction: "row", gap }, rowFields.map(({ field, flex }) => /* @__PURE__ */ React2.createElement(Box2, { key: field.name, flex }, renderField(field))))
2076
+ );
2077
+ }
2078
+ for (const { field } of rowFields) {
2079
+ const dependents = getDependents(field).filter((d) => !renderedNames.has(d.name));
2080
+ if (dependents.length > 0) {
2081
+ elements.push(renderDependentGroup(field, dependents));
2082
+ for (const dep of dependents) renderedNames.add(dep.name);
2083
+ }
2084
+ }
2085
+ }
2086
+ for (const field of visibleFields) {
2087
+ if (renderedNames.has(field.name)) continue;
2088
+ if (isDependent(field)) continue;
2089
+ elements.push(
2090
+ /* @__PURE__ */ React2.createElement(React2.Fragment, { key: field.name }, renderField(field))
2091
+ );
2092
+ renderedNames.add(field.name);
2093
+ const dependents = getDependents(field).filter((d) => !renderedNames.has(d.name));
2094
+ if (dependents.length > 0) {
2095
+ elements.push(renderDependentGroup(field, dependents));
2096
+ for (const dep of dependents) renderedNames.add(dep.name);
2097
+ }
2098
+ }
2099
+ return elements;
2100
+ };
2101
+ const renderLegacyLayout = (fieldSubset) => {
2102
+ const fieldList = fieldSubset || visibleFields;
2103
+ const rows = [];
2104
+ let i = 0;
2105
+ while (i < fieldList.length) {
2106
+ const field = fieldList[i];
2107
+ if (field.width === "half" && i + 1 < fieldList.length && fieldList[i + 1].width === "half" && !field.dependsOn) {
2108
+ rows.push({ type: "pair", fields: [fieldList[i], fieldList[i + 1]] });
2109
+ i += 2;
2110
+ } else {
2111
+ rows.push({ type: "single", field });
2112
+ i++;
2113
+ }
2114
+ }
2115
+ const elements = [];
2116
+ const processedDeps = /* @__PURE__ */ new Set();
2117
+ for (const row of rows) {
2118
+ if (row.type === "pair") {
2119
+ elements.push(
2120
+ /* @__PURE__ */ React2.createElement(Flex2, { key: `pair-${row.fields[0].name}`, direction: "row", gap: "sm" }, /* @__PURE__ */ React2.createElement(Box2, { flex: 1 }, renderField(row.fields[0])), /* @__PURE__ */ React2.createElement(Box2, { flex: 1 }, renderField(row.fields[1])))
2121
+ );
2122
+ } else {
2123
+ const field = row.field;
2124
+ if (processedDeps.has(field.name)) continue;
2125
+ elements.push(
2126
+ /* @__PURE__ */ React2.createElement(React2.Fragment, { key: field.name }, renderField(field))
2127
+ );
2128
+ const dependents = getDependents(field);
2129
+ if (dependents.length > 0) {
2130
+ for (const dep of dependents) processedDeps.add(dep.name);
2131
+ elements.push(renderDependentGroup(field, dependents));
2132
+ }
2133
+ }
2134
+ }
2135
+ return elements;
2136
+ };
2137
+ const renderAutoGridLayout = (fieldSubset) => {
2138
+ const fieldList = fieldSubset || visibleFields;
2139
+ const elements = [];
2140
+ let batch = [];
2141
+ const flushBatch = () => {
2142
+ if (batch.length === 0) return;
2143
+ elements.push(
2144
+ /* @__PURE__ */ React2.createElement(AutoGrid, { key: `ag-${batch[0].name}`, columnWidth, flexible: true, gap }, batch.map((f) => /* @__PURE__ */ React2.createElement(React2.Fragment, { key: f.name }, renderField(f))))
2145
+ );
2146
+ batch = [];
2147
+ };
2148
+ for (const field of fieldList) {
2149
+ if (isDependent(field)) continue;
2150
+ batch.push(field);
2151
+ const dependents = getDependents(field);
2152
+ if (dependents.length > 0) {
2153
+ flushBatch();
2154
+ elements.push(renderDependentGroup(field, dependents));
2155
+ }
2156
+ }
2157
+ flushBatch();
2158
+ return elements;
2159
+ };
2160
+ const wrapWithGroups = (fieldList, renderFn) => {
2161
+ const hasGroups = fieldList.some((f) => f.group);
2162
+ if (!hasGroups) return renderFn(fieldList);
2163
+ const chunks = [];
2164
+ let currentGroup = void 0;
2165
+ let currentChunk = [];
2166
+ for (const field of fieldList) {
2167
+ const fieldGroup = field.group || void 0;
2168
+ if (fieldGroup !== currentGroup && currentChunk.length > 0) {
2169
+ chunks.push({ group: currentGroup, fields: [...currentChunk] });
2170
+ currentChunk = [];
2171
+ }
2172
+ currentGroup = fieldGroup;
2173
+ currentChunk.push(field);
2174
+ }
2175
+ if (currentChunk.length > 0) {
2176
+ chunks.push({ group: currentGroup, fields: currentChunk });
2177
+ }
2178
+ const elements = [];
2179
+ for (let i = 0; i < chunks.length; i++) {
2180
+ const chunk = chunks[i];
2181
+ if (i > 0) {
2182
+ elements.push(/* @__PURE__ */ React2.createElement(Divider, { key: `group-div-${i}` }));
2183
+ }
2184
+ if (chunk.group) {
2185
+ elements.push(
2186
+ /* @__PURE__ */ React2.createElement(Text2, { key: `group-label-${i}`, format: { fontWeight: "demibold" } }, chunk.group)
2187
+ );
2188
+ }
2189
+ const chunkElements = renderFn(chunk.fields);
2190
+ if (Array.isArray(chunkElements)) {
2191
+ elements.push(...chunkElements);
2192
+ } else {
2193
+ elements.push(chunkElements);
2194
+ }
2195
+ }
2196
+ return elements;
2197
+ };
2198
+ const renderFieldSubset = (fieldSubset) => {
2199
+ if (layout && fieldSubset === visibleFields) return renderExplicitLayout();
2200
+ if (columnWidth) return renderAutoGridLayout(fieldSubset);
2201
+ if (columns > 1) return renderGridLayout(fieldSubset);
2202
+ return renderLegacyLayout(fieldSubset);
2203
+ };
2204
+ const renderSections = () => {
2205
+ const hasSections = Array.isArray(sections) && sections.length > 0;
2206
+ if (!hasSections) return null;
2207
+ const sectionFieldNames = /* @__PURE__ */ new Set();
2208
+ for (const sec of sections) {
2209
+ if (sec.fields) for (const name of sec.fields) sectionFieldNames.add(name);
2210
+ }
2211
+ const elements = [];
2212
+ for (const sec of sections) {
2213
+ const sectionFields = sec.fields ? visibleFields.filter((f) => sec.fields.includes(f.name)) : [];
2214
+ if (sectionFields.length === 0) continue;
2215
+ const accordionContent = /* @__PURE__ */ React2.createElement(Flex2, { direction: "column", gap }, renderFieldSubset(sectionFields));
2216
+ const accordion = /* @__PURE__ */ React2.createElement(
2217
+ Accordion,
2218
+ {
2219
+ key: sec.id,
2220
+ title: sec.label,
2221
+ size: "sm",
2222
+ defaultOpen: sec.defaultOpen !== false
2223
+ },
2224
+ accordionContent
2225
+ );
2226
+ if (sec.info) {
2227
+ elements.push(
2228
+ /* @__PURE__ */ React2.createElement(Flex2, { key: sec.id, direction: "row", align: "start", gap: "flush" }, /* @__PURE__ */ React2.createElement(Box2, { flex: 1 }, accordion), /* @__PURE__ */ React2.createElement(Link2, { overlay: /* @__PURE__ */ React2.createElement(Tooltip, null, sec.info) }, /* @__PURE__ */ React2.createElement(Icon2, { name: "info", size: "sm", screenReaderText: sec.info })))
2229
+ );
2230
+ } else {
2231
+ elements.push(accordion);
2232
+ }
2233
+ }
2234
+ const unsectionedFields = visibleFields.filter(
2235
+ (f) => !sectionFieldNames.has(f.name)
2236
+ );
2237
+ if (unsectionedFields.length > 0) {
2238
+ elements.push(...renderFieldSubset(unsectionedFields));
2239
+ }
2240
+ return elements;
2241
+ };
2242
+ const renderFieldLayout = () => {
2243
+ const hasSections = Array.isArray(sections) && sections.length > 0;
2244
+ if (hasSections) return renderSections();
2245
+ const hasGroups = visibleFields.some((f) => f.group);
2246
+ if (hasGroups && !layout) {
2247
+ return wrapWithGroups(visibleFields, renderFieldSubset);
2248
+ }
2249
+ if (layout) return renderExplicitLayout();
2250
+ return renderFieldSubset(visibleFields);
2251
+ };
2252
+ const renderButtons = () => {
2253
+ if (submitPosition === "none" || formReadOnly) return null;
2254
+ const isLastStep = !isMultiStep || currentStep === steps.length - 1;
2255
+ const isFirstStep = !isMultiStep || currentStep === 0;
2256
+ if (isMultiStep) {
2257
+ return /* @__PURE__ */ React2.createElement(Flex2, { direction: "row", justify: "between", align: "center" }, !isFirstStep ? /* @__PURE__ */ React2.createElement(Button2, { variant: "secondary", onClick: handleBack, disabled }, "Back") : showCancel ? /* @__PURE__ */ React2.createElement(Button2, { variant: "secondary", onClick: onCancel, disabled }, cancelLabel) : /* @__PURE__ */ React2.createElement(Text2, null, " "), /* @__PURE__ */ React2.createElement(Inline, { gap: "small" }, /* @__PURE__ */ React2.createElement(Text2, { variant: "microcopy" }, "Step ", currentStep + 1, " of ", steps.length), isLastStep ? /* @__PURE__ */ React2.createElement(
2258
+ LoadingButton,
2259
+ {
2260
+ variant: submitVariant,
2261
+ loading: isLoading,
2262
+ onClick: handleSubmit,
2263
+ disabled
2264
+ },
2265
+ submitLabel
2266
+ ) : /* @__PURE__ */ React2.createElement(Button2, { variant: "primary", onClick: handleNext, disabled }, "Next")));
2267
+ }
2268
+ return /* @__PURE__ */ React2.createElement(Flex2, { direction: "row", justify: showCancel ? "between" : "start", gap: "sm" }, showCancel && /* @__PURE__ */ React2.createElement(Button2, { variant: "secondary", onClick: onCancel, disabled }, cancelLabel), /* @__PURE__ */ React2.createElement(
2269
+ LoadingButton,
2270
+ {
2271
+ variant: submitVariant,
2272
+ type: noFormWrapper ? "button" : "submit",
2273
+ loading: isLoading,
2274
+ onClick: noFormWrapper ? handleSubmit : void 0,
2275
+ disabled
2276
+ },
2277
+ submitLabel
2278
+ ));
2279
+ };
2280
+ const formContent = /* @__PURE__ */ React2.createElement(Flex2, { direction: "column", gap }, isMultiStep && showStepIndicator && /* @__PURE__ */ React2.createElement(
2281
+ StepIndicator,
2282
+ {
2283
+ currentStep,
2284
+ stepNames: steps.map((s) => s.title)
2285
+ }
2286
+ ), formReadOnly && readOnlyMessage && /* @__PURE__ */ React2.createElement(Alert, { title: "Read Only", variant: "warning" }, readOnlyMessage), formError && /* @__PURE__ */ React2.createElement(Alert, { title: "Error", variant: "danger" }, typeof formError === "string" ? formError : void 0), formSuccess && /* @__PURE__ */ React2.createElement(Alert, { title: "Success", variant: "success" }, formSuccess), isMultiStep && steps[currentStep] && steps[currentStep].render ? steps[currentStep].render({
2287
+ values: formValues,
2288
+ goNext: handleNext,
2289
+ goBack: handleBack,
2290
+ goTo: handleGoTo
2291
+ }) : (
2292
+ /* Field layout */
2293
+ renderFieldLayout()
2294
+ ), renderButtons());
2295
+ if (noFormWrapper) {
2296
+ return formContent;
2297
+ }
2298
+ return /* @__PURE__ */ React2.createElement(Form, { onSubmit: handleSubmit, autoComplete: props.autoComplete }, formContent);
2299
+ });
2300
+ export {
2301
+ DataTable,
2302
+ FormBuilder,
2303
+ useFormPrefill
2304
+ };