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/form.mjs ADDED
@@ -0,0 +1,1271 @@
1
+ // packages/form/src/FormBuilder.jsx
2
+ import React, {
3
+ useState,
4
+ useRef,
5
+ useMemo,
6
+ useCallback,
7
+ useEffect,
8
+ useImperativeHandle,
9
+ forwardRef
10
+ } from "react";
11
+ import {
12
+ Accordion,
13
+ Form,
14
+ Flex,
15
+ Box,
16
+ AutoGrid,
17
+ Tile,
18
+ Inline,
19
+ Text,
20
+ Link,
21
+ Icon,
22
+ Divider,
23
+ Button,
24
+ LoadingButton,
25
+ Alert,
26
+ Tooltip,
27
+ StepIndicator,
28
+ Input,
29
+ TextArea,
30
+ Select,
31
+ MultiSelect,
32
+ NumberInput,
33
+ StepperInput,
34
+ CurrencyInput,
35
+ DateInput,
36
+ TimeInput,
37
+ Toggle,
38
+ Checkbox,
39
+ ToggleGroup
40
+ } from "@hubspot/ui-extensions";
41
+ import {
42
+ CrmPropertyList,
43
+ CrmAssociationPropertyList
44
+ } from "@hubspot/ui-extensions/crm";
45
+ var getEmptyValue = (field) => {
46
+ switch (field.type) {
47
+ case "toggle":
48
+ case "checkbox":
49
+ return false;
50
+ case "multiselect":
51
+ case "checkboxGroup":
52
+ return [];
53
+ case "number":
54
+ case "stepper":
55
+ case "currency":
56
+ return void 0;
57
+ case "date":
58
+ case "time":
59
+ case "datetime":
60
+ return void 0;
61
+ case "display":
62
+ case "crmPropertyList":
63
+ case "crmAssociationPropertyList":
64
+ return void 0;
65
+ // these field types have no form value
66
+ case "repeater":
67
+ return [];
68
+ default:
69
+ return "";
70
+ }
71
+ };
72
+ var isValueEmpty = (value, field) => {
73
+ if (value === void 0 || value === null) return true;
74
+ if (typeof value === "string" && value.trim() === "") return true;
75
+ if (Array.isArray(value) && value.length === 0) return true;
76
+ if ((field.type === "toggle" || field.type === "checkbox") && value === false) return true;
77
+ return false;
78
+ };
79
+ var runValidators = (value, field, allValues, fieldTypes) => {
80
+ if (field.type === "display" || field.type === "crmPropertyList" || field.type === "crmAssociationPropertyList") return null;
81
+ const isRequired = resolveRequired(field, allValues);
82
+ const plugin = fieldTypes && fieldTypes[field.type];
83
+ const empty = plugin && plugin.isEmpty ? plugin.isEmpty(value) : isValueEmpty(value, field);
84
+ if (isRequired && empty) {
85
+ return `${field.label} is required`;
86
+ }
87
+ if (empty) return null;
88
+ if (field.pattern && typeof value === "string") {
89
+ if (!field.pattern.test(value)) {
90
+ return field.patternMessage || "Invalid format";
91
+ }
92
+ }
93
+ if (typeof value === "string") {
94
+ if (field.minLength != null && value.length < field.minLength) {
95
+ return `Must be at least ${field.minLength} characters`;
96
+ }
97
+ if (field.maxLength != null && value.length > field.maxLength) {
98
+ return `Must be no more than ${field.maxLength} characters`;
99
+ }
100
+ }
101
+ if (typeof value === "number") {
102
+ if (field.min != null && value < field.min) {
103
+ return `Must be at least ${field.min}`;
104
+ }
105
+ if (field.max != null && value > field.max) {
106
+ return `Must be no more than ${field.max}`;
107
+ }
108
+ }
109
+ if (field.validate) {
110
+ const result = field.validate(value, allValues);
111
+ if (result && typeof result.then === "function") return null;
112
+ if (result !== true && result) return result;
113
+ }
114
+ return null;
115
+ };
116
+ var resolveRequired = (field, allValues) => {
117
+ if (typeof field.required === "function") return field.required(allValues);
118
+ return !!field.required;
119
+ };
120
+ var resolveOptions = (field, allValues) => {
121
+ if (typeof field.options === "function") return field.options(allValues);
122
+ return field.options || [];
123
+ };
124
+ var useFormPrefill = (properties, mapping) => {
125
+ return useMemo(() => {
126
+ if (!properties) return {};
127
+ if (!mapping) {
128
+ const result2 = {};
129
+ for (const [key, value] of Object.entries(properties)) {
130
+ if (value !== void 0) result2[key] = value;
131
+ }
132
+ return result2;
133
+ }
134
+ const result = {};
135
+ for (const [formField, crmProp] of Object.entries(mapping)) {
136
+ if (properties[crmProp] !== void 0) {
137
+ result[formField] = properties[crmProp];
138
+ }
139
+ }
140
+ return result;
141
+ }, [properties, mapping]);
142
+ };
143
+ var FormBuilder = forwardRef(function FormBuilder2(props, ref) {
144
+ const {
145
+ fields,
146
+ // FormBuilderField[] — field definitions
147
+ onSubmit,
148
+ // (values, { reset, rawValues }) => void | Promise
149
+ transformValues,
150
+ // (values) => values — reshape before submit
151
+ onBeforeSubmit,
152
+ // (values) => boolean | Promise<boolean> — intercept submit
153
+ onSubmitSuccess,
154
+ // (result, { reset, values }) => void
155
+ onSubmitError,
156
+ // (error, { values }) => void
157
+ resetOnSuccess = false
158
+ // auto-reset after successful submit
159
+ } = props;
160
+ const {
161
+ initialValues,
162
+ // Record<string, unknown> — starting values (uncontrolled)
163
+ values,
164
+ // Record<string, unknown> — controlled values
165
+ onChange,
166
+ // (values) => void — called on any field change (controlled)
167
+ onFieldChange
168
+ // (name, value, allValues) => void — per-field change callback
169
+ } = props;
170
+ const {
171
+ validateOnChange = false,
172
+ // validate on keystroke (onInput)
173
+ validateOnBlur = true,
174
+ // validate on blur
175
+ validateOnSubmit = true,
176
+ // validate all before onSubmit
177
+ onValidationChange
178
+ // (errors) => void
179
+ } = props;
180
+ const {
181
+ steps,
182
+ // FormBuilderStep[] — enables multi-step mode
183
+ step: controlledStep,
184
+ // number — controlled current step (0-based)
185
+ onStepChange,
186
+ // (step) => void
187
+ showStepIndicator = true,
188
+ // show StepIndicator component
189
+ validateStepOnNext = true
190
+ // validate current step fields before Next
191
+ } = props;
192
+ const {
193
+ submitLabel = "Submit",
194
+ // submit button text
195
+ submitVariant = "primary",
196
+ // submit button variant
197
+ showCancel = false,
198
+ // show cancel button
199
+ cancelLabel = "Cancel",
200
+ // cancel button text
201
+ onCancel,
202
+ // () => void
203
+ submitPosition = "bottom",
204
+ // "bottom" | "none"
205
+ loading: controlledLoading,
206
+ // controlled loading state
207
+ disabled = false
208
+ // disable entire form
209
+ } = props;
210
+ const {
211
+ columns = 1,
212
+ // number of grid columns (1 = full-width stack)
213
+ columnWidth,
214
+ // AutoGrid columnWidth — responsive layout (overrides columns)
215
+ layout,
216
+ // explicit row layout array (overrides columns + columnWidth)
217
+ sections,
218
+ // FormBuilderSection[] — accordion field grouping
219
+ gap = "sm",
220
+ // gap between fields
221
+ showRequiredIndicator = true,
222
+ // show * on required fields
223
+ noFormWrapper = false,
224
+ // skip HubSpot <Form> wrapper
225
+ fieldTypes
226
+ // Record<string, FieldTypePlugin> — custom field type registry
227
+ } = props;
228
+ const {
229
+ error: formError,
230
+ // string | boolean — form-level error alert
231
+ success: formSuccess,
232
+ // string — form-level success alert
233
+ readOnly: formReadOnly = false,
234
+ // boolean — lock all fields
235
+ readOnlyMessage
236
+ // string — warning alert when readOnly
237
+ } = props;
238
+ const {
239
+ onDirtyChange,
240
+ // (isDirty: boolean) => void
241
+ autoSave
242
+ // { debounce: number, onAutoSave: (values) => void }
243
+ } = props;
244
+ const computeInitialValues = () => {
245
+ const vals = {};
246
+ for (const field of fields) {
247
+ if (field.type === "display" || field.type === "crmPropertyList" || field.type === "crmAssociationPropertyList") continue;
248
+ const plugin = fieldTypes && fieldTypes[field.type];
249
+ const emptyValue = plugin && plugin.getEmptyValue ? plugin.getEmptyValue() : getEmptyValue(field);
250
+ const init = initialValues && initialValues[field.name] !== void 0 ? initialValues[field.name] : field.defaultValue !== void 0 ? field.defaultValue : emptyValue;
251
+ vals[field.name] = init;
252
+ }
253
+ return vals;
254
+ };
255
+ const [internalValues, setInternalValues] = useState(computeInitialValues);
256
+ const [internalErrors, setInternalErrors] = useState({});
257
+ const [internalStep, setInternalStep] = useState(0);
258
+ const [internalLoading, setInternalLoading] = useState(false);
259
+ const [touchedFields, setTouchedFields] = useState({});
260
+ const [validatingFields, setValidatingFields] = useState({});
261
+ const asyncValidationRef = useRef(/* @__PURE__ */ new Map());
262
+ const debounceTimersRef = useRef(/* @__PURE__ */ new Map());
263
+ const initialSnapshot = useRef(null);
264
+ if (initialSnapshot.current === null) {
265
+ initialSnapshot.current = JSON.stringify(computeInitialValues());
266
+ }
267
+ const formValues = values != null ? values : internalValues;
268
+ const currentStep = controlledStep != null ? controlledStep : internalStep;
269
+ const isLoading = controlledLoading != null ? controlledLoading : internalLoading;
270
+ const isMultiStep = Array.isArray(steps) && steps.length > 0;
271
+ useEffect(() => {
272
+ return () => {
273
+ for (const timer of debounceTimersRef.current.values()) clearTimeout(timer);
274
+ };
275
+ }, []);
276
+ const isDirty = useMemo(() => {
277
+ return JSON.stringify(formValues) !== initialSnapshot.current;
278
+ }, [formValues]);
279
+ const prevDirtyRef = useRef(false);
280
+ useEffect(() => {
281
+ if (isDirty !== prevDirtyRef.current) {
282
+ prevDirtyRef.current = isDirty;
283
+ if (onDirtyChange) onDirtyChange(isDirty);
284
+ }
285
+ }, [isDirty, onDirtyChange]);
286
+ const autoSaveTimerRef = useRef(null);
287
+ useEffect(() => {
288
+ if (!autoSave || !autoSave.onAutoSave || !isDirty) return;
289
+ if (autoSaveTimerRef.current) clearTimeout(autoSaveTimerRef.current);
290
+ autoSaveTimerRef.current = setTimeout(() => {
291
+ autoSaveTimerRef.current = null;
292
+ autoSave.onAutoSave(formValues);
293
+ }, autoSave.debounce || 1e3);
294
+ return () => {
295
+ if (autoSaveTimerRef.current) clearTimeout(autoSaveTimerRef.current);
296
+ };
297
+ }, [formValues, isDirty, autoSave]);
298
+ const visibleFields = useMemo(() => {
299
+ let filtered = fields.filter((f) => {
300
+ if (f.visible && !f.visible(formValues)) return false;
301
+ return true;
302
+ });
303
+ if (isMultiStep && steps[currentStep] && steps[currentStep].fields) {
304
+ const stepFieldNames = new Set(steps[currentStep].fields);
305
+ filtered = filtered.filter((f) => stepFieldNames.has(f.name));
306
+ }
307
+ return filtered;
308
+ }, [fields, formValues, isMultiStep, steps, currentStep]);
309
+ const validateField = useCallback(
310
+ (name, value) => {
311
+ const field = fields.find((f) => f.name === name);
312
+ if (!field) return null;
313
+ if (field.visible && !field.visible(formValues)) return null;
314
+ return runValidators(value != null ? value : formValues[name], field, formValues, fieldTypes);
315
+ },
316
+ [fields, formValues, fieldTypes]
317
+ );
318
+ const validateVisibleFields = useCallback(
319
+ (fieldSubset) => {
320
+ const toValidate = fieldSubset || visibleFields;
321
+ const errors = {};
322
+ let hasErrors = false;
323
+ for (const field of toValidate) {
324
+ const err = runValidators(formValues[field.name], field, formValues, fieldTypes);
325
+ if (err) {
326
+ errors[field.name] = err;
327
+ hasErrors = true;
328
+ }
329
+ }
330
+ return { errors, hasErrors };
331
+ },
332
+ [visibleFields, formValues]
333
+ );
334
+ const updateErrors = useCallback(
335
+ (newErrors) => {
336
+ setInternalErrors((prev) => {
337
+ const merged = { ...prev, ...newErrors };
338
+ for (const key of Object.keys(merged)) {
339
+ if (newErrors[key] === null || newErrors[key] === void 0) {
340
+ delete merged[key];
341
+ }
342
+ }
343
+ if (onValidationChange) onValidationChange(merged);
344
+ return merged;
345
+ });
346
+ },
347
+ [onValidationChange]
348
+ );
349
+ const runAsyncValidation = useCallback(
350
+ (name, value) => {
351
+ const field = fields.find((f) => f.name === name);
352
+ if (!field || !field.validate) return;
353
+ const val = value != null ? value : formValues[name];
354
+ const syncError = runValidators(val, field, formValues, fieldTypes);
355
+ if (syncError) return;
356
+ const result = field.validate(val, formValues);
357
+ if (!result || typeof result.then !== "function") return;
358
+ const validationPromise = result.then(
359
+ (asyncResult) => {
360
+ if (asyncValidationRef.current.get(name) !== validationPromise) return;
361
+ asyncValidationRef.current.delete(name);
362
+ setValidatingFields((prev) => {
363
+ const next = { ...prev };
364
+ delete next[name];
365
+ return next;
366
+ });
367
+ const err = asyncResult !== true && asyncResult ? asyncResult : null;
368
+ updateErrors({ [name]: err });
369
+ },
370
+ (rejection) => {
371
+ if (asyncValidationRef.current.get(name) !== validationPromise) return;
372
+ asyncValidationRef.current.delete(name);
373
+ setValidatingFields((prev) => {
374
+ const next = { ...prev };
375
+ delete next[name];
376
+ return next;
377
+ });
378
+ updateErrors({ [name]: (rejection == null ? void 0 : rejection.message) || "Validation failed" });
379
+ }
380
+ );
381
+ asyncValidationRef.current.set(name, validationPromise);
382
+ setValidatingFields((prev) => ({ ...prev, [name]: true }));
383
+ },
384
+ [fields, formValues, updateErrors]
385
+ );
386
+ const triggerAsyncValidation = useCallback(
387
+ (name, value) => {
388
+ const field = fields.find((f) => f.name === name);
389
+ if (!field || !field.validate) return;
390
+ const debounceMs = field.validateDebounce;
391
+ if (debounceMs && debounceMs > 0) {
392
+ const existing = debounceTimersRef.current.get(name);
393
+ if (existing) clearTimeout(existing);
394
+ const timer = setTimeout(() => {
395
+ debounceTimersRef.current.delete(name);
396
+ runAsyncValidation(name, value);
397
+ }, debounceMs);
398
+ debounceTimersRef.current.set(name, timer);
399
+ } else {
400
+ runAsyncValidation(name, value);
401
+ }
402
+ },
403
+ [fields, runAsyncValidation]
404
+ );
405
+ const setFieldValueSilent = useCallback(
406
+ (name, value) => {
407
+ if (values != null) {
408
+ if (onChange) onChange({ ...formValues, [name]: value });
409
+ } else {
410
+ setInternalValues((prev) => ({ ...prev, [name]: value }));
411
+ }
412
+ },
413
+ [values, onChange, formValues]
414
+ );
415
+ const handleFieldChange = useCallback(
416
+ (name, value) => {
417
+ const newValues = { ...formValues, [name]: value };
418
+ if (values != null) {
419
+ if (onChange) onChange(newValues);
420
+ } else {
421
+ setInternalValues(newValues);
422
+ }
423
+ if (onFieldChange) onFieldChange(name, value, newValues);
424
+ if (internalErrors[name]) {
425
+ updateErrors({ [name]: null });
426
+ }
427
+ const field = fields.find((f) => f.name === name);
428
+ if (field && field.onFieldChange) {
429
+ field.onFieldChange(value, newValues, {
430
+ setFieldValue: setFieldValueSilent,
431
+ setFieldError: (fieldName, message) => updateErrors({ [fieldName]: message })
432
+ });
433
+ }
434
+ },
435
+ [formValues, values, onChange, onFieldChange, internalErrors, updateErrors, fields, setFieldValueSilent]
436
+ );
437
+ const inputDebounceRef = useRef(/* @__PURE__ */ new Map());
438
+ const handleDebouncedFieldChange = useCallback(
439
+ (name, value) => {
440
+ const field = fields.find((f) => f.name === name);
441
+ const debounceMs = field && field.debounce;
442
+ if (debounceMs && debounceMs > 0) {
443
+ const existing = inputDebounceRef.current.get(name);
444
+ if (existing) clearTimeout(existing);
445
+ const timer = setTimeout(() => {
446
+ inputDebounceRef.current.delete(name);
447
+ handleFieldChange(name, value);
448
+ }, debounceMs);
449
+ inputDebounceRef.current.set(name, timer);
450
+ } else {
451
+ handleFieldChange(name, value);
452
+ }
453
+ },
454
+ [fields, handleFieldChange]
455
+ );
456
+ const handleFieldInput = useCallback(
457
+ (name, value) => {
458
+ if (validateOnChange) {
459
+ const err = validateField(name, value);
460
+ updateErrors({ [name]: err });
461
+ }
462
+ },
463
+ [validateOnChange, validateField, updateErrors]
464
+ );
465
+ const handleFieldBlur = useCallback(
466
+ (name, value) => {
467
+ setTouchedFields((prev) => ({ ...prev, [name]: true }));
468
+ if (validateOnBlur) {
469
+ const err = validateField(name, value != null ? value : formValues[name]);
470
+ updateErrors({ [name]: err });
471
+ if (!err) {
472
+ triggerAsyncValidation(name, value != null ? value : formValues[name]);
473
+ }
474
+ }
475
+ },
476
+ [validateOnBlur, validateField, updateErrors, formValues, triggerAsyncValidation]
477
+ );
478
+ const handleSubmit = useCallback(
479
+ async (e) => {
480
+ if (e && e.preventDefault) e.preventDefault();
481
+ if (validateOnSubmit) {
482
+ const allVisible = fields.filter((f) => !f.visible || f.visible(formValues));
483
+ const { errors, hasErrors } = validateVisibleFields(allVisible);
484
+ if (hasErrors) {
485
+ setInternalErrors(errors);
486
+ if (onValidationChange) onValidationChange(errors);
487
+ return;
488
+ }
489
+ if (asyncValidationRef.current.size > 0) {
490
+ await Promise.all(asyncValidationRef.current.values());
491
+ const currentErrors = { ...internalErrors };
492
+ const hasAsyncErrors = Object.keys(currentErrors).length > 0;
493
+ if (hasAsyncErrors) return;
494
+ }
495
+ }
496
+ const reset = () => {
497
+ const fresh = computeInitialValues();
498
+ if (values == null) setInternalValues(fresh);
499
+ setInternalErrors({});
500
+ setTouchedFields({});
501
+ initialSnapshot.current = JSON.stringify(fresh);
502
+ };
503
+ const rawValues = {};
504
+ for (const key of Object.keys(formValues)) {
505
+ const f = fields.find((fd) => fd.name === key);
506
+ if (f && (f.type === "display" || f.type === "crmPropertyList" || f.type === "crmAssociationPropertyList")) continue;
507
+ rawValues[key] = formValues[key];
508
+ }
509
+ const submitValues = transformValues ? transformValues(rawValues) : rawValues;
510
+ if (onBeforeSubmit) {
511
+ const proceed = await onBeforeSubmit(submitValues);
512
+ if (proceed === false) return;
513
+ }
514
+ if (controlledLoading == null) setInternalLoading(true);
515
+ try {
516
+ const result = await onSubmit(submitValues, { reset, rawValues });
517
+ if (resetOnSuccess) reset();
518
+ if (onSubmitSuccess) onSubmitSuccess(result, { reset, values: submitValues });
519
+ } catch (err) {
520
+ if (onSubmitError) {
521
+ onSubmitError(err, { values: submitValues });
522
+ } else {
523
+ throw err;
524
+ }
525
+ } finally {
526
+ if (controlledLoading == null) setInternalLoading(false);
527
+ }
528
+ },
529
+ [validateOnSubmit, fields, formValues, validateVisibleFields, onValidationChange, onSubmit, values, controlledLoading, internalErrors, transformValues, onBeforeSubmit, onSubmitSuccess, onSubmitError, resetOnSuccess]
530
+ );
531
+ const handleNext = useCallback(() => {
532
+ if (!isMultiStep) return;
533
+ if (validateStepOnNext && steps[currentStep] && steps[currentStep].fields) {
534
+ const stepFields = fields.filter(
535
+ (f) => steps[currentStep].fields.includes(f.name) && (!f.visible || f.visible(formValues))
536
+ );
537
+ const { errors, hasErrors } = validateVisibleFields(stepFields);
538
+ if (hasErrors) {
539
+ setInternalErrors((prev) => ({ ...prev, ...errors }));
540
+ if (onValidationChange) onValidationChange({ ...internalErrors, ...errors });
541
+ return;
542
+ }
543
+ }
544
+ if (steps[currentStep] && steps[currentStep].validate) {
545
+ const result = steps[currentStep].validate(formValues);
546
+ if (result !== true && result) {
547
+ setInternalErrors((prev) => ({ ...prev, ...result }));
548
+ return;
549
+ }
550
+ }
551
+ const nextStep = Math.min(currentStep + 1, steps.length - 1);
552
+ if (controlledStep != null) {
553
+ if (onStepChange) onStepChange(nextStep);
554
+ } else {
555
+ setInternalStep(nextStep);
556
+ }
557
+ }, [isMultiStep, validateStepOnNext, steps, currentStep, fields, formValues, validateVisibleFields, onValidationChange, internalErrors, controlledStep, onStepChange]);
558
+ const handleBack = useCallback(() => {
559
+ if (!isMultiStep) return;
560
+ const prevStep = Math.max(currentStep - 1, 0);
561
+ if (controlledStep != null) {
562
+ if (onStepChange) onStepChange(prevStep);
563
+ } else {
564
+ setInternalStep(prevStep);
565
+ }
566
+ }, [isMultiStep, currentStep, controlledStep, onStepChange]);
567
+ const handleGoTo = useCallback(
568
+ (stepIndex) => {
569
+ if (!isMultiStep) return;
570
+ const clamped = Math.max(0, Math.min(stepIndex, steps.length - 1));
571
+ if (controlledStep != null) {
572
+ if (onStepChange) onStepChange(clamped);
573
+ } else {
574
+ setInternalStep(clamped);
575
+ }
576
+ },
577
+ [isMultiStep, steps, controlledStep, onStepChange]
578
+ );
579
+ useImperativeHandle(ref, () => ({
580
+ submit: handleSubmit,
581
+ validate: () => {
582
+ const allVisible = fields.filter((f) => !f.visible || f.visible(formValues));
583
+ const { errors, hasErrors } = validateVisibleFields(allVisible);
584
+ setInternalErrors(errors);
585
+ return { valid: !hasErrors, errors };
586
+ },
587
+ reset: () => {
588
+ const fresh = computeInitialValues();
589
+ if (values == null) setInternalValues(fresh);
590
+ setInternalErrors({});
591
+ setTouchedFields({});
592
+ initialSnapshot.current = JSON.stringify(fresh);
593
+ },
594
+ getValues: () => formValues,
595
+ isDirty: () => isDirty,
596
+ setFieldValue: (name, value) => handleFieldChange(name, value),
597
+ setFieldError: (name, message) => updateErrors({ [name]: message }),
598
+ setErrors: (errors) => {
599
+ setInternalErrors(errors);
600
+ if (onValidationChange) onValidationChange(errors);
601
+ }
602
+ }));
603
+ const renderField = (field) => {
604
+ const fieldValue = formValues[field.name];
605
+ const fieldError = internalErrors[field.name] || null;
606
+ const hasError = !!fieldError;
607
+ const isRequired = showRequiredIndicator && resolveRequired(field, formValues);
608
+ const isReadOnly = field.readOnly || disabled || formReadOnly;
609
+ const fieldOnChange = field.debounce ? (v) => handleDebouncedFieldChange(field.name, v) : (v) => handleFieldChange(field.name, v);
610
+ if (field.type === "display") {
611
+ if (field.render) {
612
+ return field.render({ allValues: formValues });
613
+ }
614
+ return null;
615
+ }
616
+ if (field.type === "crmPropertyList") {
617
+ return /* @__PURE__ */ React.createElement(
618
+ CrmPropertyList,
619
+ {
620
+ properties: field.properties,
621
+ direction: field.direction,
622
+ ...field.objectId ? { objectId: field.objectId } : {},
623
+ ...field.objectTypeId ? { objectTypeId: field.objectTypeId } : {},
624
+ ...field.fieldProps || {}
625
+ }
626
+ );
627
+ }
628
+ if (field.type === "crmAssociationPropertyList") {
629
+ return /* @__PURE__ */ React.createElement(
630
+ CrmAssociationPropertyList,
631
+ {
632
+ objectTypeId: field.objectTypeId,
633
+ properties: field.properties,
634
+ ...field.associationLabels ? { associationLabels: field.associationLabels } : {},
635
+ ...field.filters ? { filters: field.filters } : {},
636
+ ...field.sort ? { sort: field.sort } : {},
637
+ ...field.fieldProps || {}
638
+ }
639
+ );
640
+ }
641
+ if (field.render) {
642
+ return field.render({
643
+ value: fieldValue,
644
+ onChange: fieldOnChange,
645
+ error: hasError,
646
+ allValues: formValues
647
+ });
648
+ }
649
+ const plugin = fieldTypes && fieldTypes[field.type];
650
+ if (plugin && plugin.render) {
651
+ return plugin.render({
652
+ value: fieldValue,
653
+ onChange: fieldOnChange,
654
+ error: hasError,
655
+ field,
656
+ allValues: formValues
657
+ });
658
+ }
659
+ const commonProps = {
660
+ name: field.name,
661
+ label: field.label,
662
+ description: field.description,
663
+ placeholder: field.placeholder,
664
+ tooltip: field.tooltip,
665
+ required: isRequired,
666
+ readOnly: isReadOnly,
667
+ error: hasError,
668
+ validationMessage: fieldError || void 0,
669
+ ...field.loading || validatingFields[field.name] ? { loading: true } : {},
670
+ ...field.fieldProps || {}
671
+ };
672
+ const options = resolveOptions(field, formValues);
673
+ switch (field.type) {
674
+ case "text":
675
+ case "password":
676
+ return /* @__PURE__ */ React.createElement(
677
+ Input,
678
+ {
679
+ ...commonProps,
680
+ type: field.type === "password" ? "password" : "text",
681
+ value: fieldValue || "",
682
+ onChange: fieldOnChange,
683
+ onInput: (v) => handleFieldInput(field.name, v),
684
+ onBlur: (v) => handleFieldBlur(field.name, v)
685
+ }
686
+ );
687
+ case "textarea":
688
+ return /* @__PURE__ */ React.createElement(
689
+ TextArea,
690
+ {
691
+ ...commonProps,
692
+ value: fieldValue || "",
693
+ rows: field.rows,
694
+ cols: field.cols,
695
+ resize: field.resize,
696
+ maxLength: field.maxLength,
697
+ onChange: fieldOnChange,
698
+ onInput: (v) => handleFieldInput(field.name, v),
699
+ onBlur: (v) => handleFieldBlur(field.name, v)
700
+ }
701
+ );
702
+ case "number":
703
+ return /* @__PURE__ */ React.createElement(
704
+ NumberInput,
705
+ {
706
+ ...commonProps,
707
+ value: fieldValue,
708
+ min: field.min,
709
+ max: field.max,
710
+ precision: field.precision,
711
+ formatStyle: field.formatStyle,
712
+ onChange: fieldOnChange,
713
+ onBlur: (v) => handleFieldBlur(field.name, v)
714
+ }
715
+ );
716
+ case "stepper":
717
+ return /* @__PURE__ */ React.createElement(
718
+ StepperInput,
719
+ {
720
+ ...commonProps,
721
+ value: fieldValue,
722
+ min: field.min,
723
+ max: field.max,
724
+ precision: field.precision,
725
+ formatStyle: field.formatStyle,
726
+ stepSize: field.stepSize,
727
+ minValueReachedTooltip: field.minValueReachedTooltip,
728
+ maxValueReachedTooltip: field.maxValueReachedTooltip,
729
+ onChange: fieldOnChange,
730
+ onBlur: (v) => handleFieldBlur(field.name, v)
731
+ }
732
+ );
733
+ case "currency":
734
+ return /* @__PURE__ */ React.createElement(
735
+ CurrencyInput,
736
+ {
737
+ ...commonProps,
738
+ currency: field.currency || "USD",
739
+ value: fieldValue,
740
+ min: field.min,
741
+ max: field.max,
742
+ precision: field.precision,
743
+ onChange: fieldOnChange,
744
+ onBlur: (v) => handleFieldBlur(field.name, v)
745
+ }
746
+ );
747
+ case "date":
748
+ return /* @__PURE__ */ React.createElement(
749
+ DateInput,
750
+ {
751
+ ...commonProps,
752
+ value: fieldValue,
753
+ format: field.format,
754
+ min: field.min,
755
+ max: field.max,
756
+ timezone: field.timezone,
757
+ clearButtonLabel: field.clearButtonLabel,
758
+ todayButtonLabel: field.todayButtonLabel,
759
+ minValidationMessage: field.minValidationMessage,
760
+ maxValidationMessage: field.maxValidationMessage,
761
+ onChange: fieldOnChange,
762
+ onBlur: (v) => handleFieldBlur(field.name, v)
763
+ }
764
+ );
765
+ case "time":
766
+ return /* @__PURE__ */ React.createElement(
767
+ TimeInput,
768
+ {
769
+ ...commonProps,
770
+ value: fieldValue,
771
+ interval: field.interval,
772
+ min: field.min,
773
+ max: field.max,
774
+ timezone: field.timezone,
775
+ onChange: fieldOnChange,
776
+ onBlur: (v) => handleFieldBlur(field.name, v)
777
+ }
778
+ );
779
+ case "datetime": {
780
+ const dateVal = fieldValue ? fieldValue.date || fieldValue : void 0;
781
+ const timeVal = fieldValue ? fieldValue.time || void 0 : void 0;
782
+ return /* @__PURE__ */ React.createElement(Flex, { direction: "row", gap: "sm" }, /* @__PURE__ */ React.createElement(Box, { flex: 1 }, /* @__PURE__ */ React.createElement(
783
+ DateInput,
784
+ {
785
+ ...commonProps,
786
+ name: `${field.name}-date`,
787
+ label: field.label,
788
+ format: field.format,
789
+ value: dateVal,
790
+ min: field.min,
791
+ max: field.max,
792
+ timezone: field.timezone,
793
+ clearButtonLabel: field.clearButtonLabel,
794
+ todayButtonLabel: field.todayButtonLabel,
795
+ minValidationMessage: field.minValidationMessage,
796
+ maxValidationMessage: field.maxValidationMessage,
797
+ onChange: (v) => {
798
+ handleFieldChange(field.name, { ...fieldValue, date: v, time: timeVal });
799
+ }
800
+ }
801
+ )), /* @__PURE__ */ React.createElement(Box, { flex: 1 }, /* @__PURE__ */ React.createElement(
802
+ TimeInput,
803
+ {
804
+ name: `${field.name}-time`,
805
+ label: "Time",
806
+ description: field.description,
807
+ tooltip: field.tooltip,
808
+ readOnly: isReadOnly,
809
+ error: hasError,
810
+ value: timeVal,
811
+ interval: field.interval,
812
+ timezone: field.timezone,
813
+ onChange: (v) => {
814
+ handleFieldChange(field.name, { ...fieldValue, date: dateVal, time: v });
815
+ }
816
+ }
817
+ )));
818
+ }
819
+ case "select":
820
+ return /* @__PURE__ */ React.createElement(
821
+ Select,
822
+ {
823
+ ...commonProps,
824
+ value: fieldValue,
825
+ options,
826
+ variant: field.variant,
827
+ onChange: fieldOnChange
828
+ }
829
+ );
830
+ case "multiselect":
831
+ return /* @__PURE__ */ React.createElement(
832
+ MultiSelect,
833
+ {
834
+ ...commonProps,
835
+ value: fieldValue || [],
836
+ options,
837
+ onChange: fieldOnChange
838
+ }
839
+ );
840
+ case "toggle":
841
+ return /* @__PURE__ */ React.createElement(
842
+ Toggle,
843
+ {
844
+ name: field.name,
845
+ label: field.label,
846
+ checked: !!fieldValue,
847
+ size: field.size || "md",
848
+ labelDisplay: field.labelDisplay || "top",
849
+ textChecked: field.textChecked,
850
+ textUnchecked: field.textUnchecked,
851
+ readonly: isReadOnly,
852
+ onChange: fieldOnChange,
853
+ ...field.fieldProps || {}
854
+ }
855
+ );
856
+ case "checkbox":
857
+ return /* @__PURE__ */ React.createElement(
858
+ Checkbox,
859
+ {
860
+ name: field.name,
861
+ checked: !!fieldValue,
862
+ description: field.description,
863
+ readOnly: isReadOnly,
864
+ inline: field.inline,
865
+ variant: field.variant,
866
+ onChange: fieldOnChange,
867
+ ...field.fieldProps || {}
868
+ },
869
+ field.label
870
+ );
871
+ case "checkboxGroup":
872
+ return /* @__PURE__ */ React.createElement(
873
+ ToggleGroup,
874
+ {
875
+ ...commonProps,
876
+ toggleType: "checkboxList",
877
+ value: fieldValue || [],
878
+ options,
879
+ inline: field.inline,
880
+ variant: field.variant,
881
+ onChange: fieldOnChange
882
+ }
883
+ );
884
+ case "radioGroup":
885
+ return /* @__PURE__ */ React.createElement(
886
+ ToggleGroup,
887
+ {
888
+ ...commonProps,
889
+ toggleType: "radioButtonList",
890
+ value: fieldValue,
891
+ options,
892
+ inline: field.inline,
893
+ variant: field.variant,
894
+ onChange: fieldOnChange
895
+ }
896
+ );
897
+ case "repeater": {
898
+ const rows = Array.isArray(fieldValue) ? fieldValue : [];
899
+ const subFields = field.fields || [];
900
+ const minRows = field.min || 0;
901
+ const maxRows = field.max || Infinity;
902
+ const canAdd = rows.length < maxRows && !isReadOnly;
903
+ const canRemove = rows.length > minRows && !isReadOnly;
904
+ const addRow = () => {
905
+ const emptyRow = {};
906
+ for (const sf of subFields) {
907
+ emptyRow[sf.name] = sf.defaultValue !== void 0 ? sf.defaultValue : getEmptyValue(sf);
908
+ }
909
+ handleFieldChange(field.name, [...rows, emptyRow]);
910
+ };
911
+ const removeRow = (idx) => {
912
+ handleFieldChange(field.name, rows.filter((_, i) => i !== idx));
913
+ };
914
+ const updateRow = (idx, subName, subValue) => {
915
+ const updated = rows.map(
916
+ (row, i) => i === idx ? { ...row, [subName]: subValue } : row
917
+ );
918
+ handleFieldChange(field.name, updated);
919
+ };
920
+ return /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap: "xs" }, field.label && /* @__PURE__ */ React.createElement(Text, { format: { fontWeight: "demibold" } }, field.label, isRequired ? " *" : ""), field.description && /* @__PURE__ */ React.createElement(Text, { variant: "microcopy" }, field.description), rows.map((row, rowIdx) => /* @__PURE__ */ React.createElement(Flex, { key: rowIdx, direction: "row", gap: "xs", align: "end" }, subFields.map((sf) => {
921
+ const sfValue = row[sf.name];
922
+ const sfLabel = rowIdx === 0 ? sf.label : void 0;
923
+ const sfOptions = resolveOptions(sf, formValues);
924
+ const sfProps = {
925
+ name: `${field.name}-${rowIdx}-${sf.name}`,
926
+ label: sfLabel,
927
+ placeholder: sf.placeholder,
928
+ readOnly: isReadOnly,
929
+ ...sf.fieldProps || {}
930
+ };
931
+ let sfElement;
932
+ switch (sf.type) {
933
+ case "select":
934
+ sfElement = /* @__PURE__ */ React.createElement(Select, { ...sfProps, value: sfValue, options: sfOptions, onChange: (v) => updateRow(rowIdx, sf.name, v) });
935
+ break;
936
+ case "number":
937
+ sfElement = /* @__PURE__ */ React.createElement(NumberInput, { ...sfProps, value: sfValue, onChange: (v) => updateRow(rowIdx, sf.name, v) });
938
+ break;
939
+ case "checkbox":
940
+ sfElement = /* @__PURE__ */ React.createElement(Checkbox, { ...sfProps, checked: !!sfValue, onChange: (v) => updateRow(rowIdx, sf.name, v) }, sf.label);
941
+ break;
942
+ default:
943
+ sfElement = /* @__PURE__ */ React.createElement(Input, { ...sfProps, value: sfValue || "", onChange: (v) => updateRow(rowIdx, sf.name, v) });
944
+ }
945
+ return /* @__PURE__ */ React.createElement(Box, { key: sf.name, flex: 1 }, sfElement);
946
+ }), canRemove && /* @__PURE__ */ React.createElement(
947
+ Button,
948
+ {
949
+ variant: "secondary",
950
+ size: "xs",
951
+ onClick: () => removeRow(rowIdx)
952
+ },
953
+ "Remove"
954
+ ))), canAdd && /* @__PURE__ */ React.createElement(Button, { variant: "secondary", size: "sm", onClick: addRow }, "+ Add"), hasError && /* @__PURE__ */ React.createElement(Text, { variant: "microcopy" }, fieldError));
955
+ }
956
+ default:
957
+ return /* @__PURE__ */ React.createElement(
958
+ Input,
959
+ {
960
+ ...commonProps,
961
+ value: fieldValue || "",
962
+ onChange: fieldOnChange,
963
+ onInput: (v) => handleFieldInput(field.name, v),
964
+ onBlur: (v) => handleFieldBlur(field.name, v)
965
+ }
966
+ );
967
+ }
968
+ };
969
+ const getFieldColSpan = (field) => {
970
+ if (field.colSpan != null) return Math.min(field.colSpan, columns);
971
+ if (field.width === "full" && columns > 1) return columns;
972
+ return 1;
973
+ };
974
+ const getDependents = (parentField) => visibleFields.filter((f) => f.dependsOn === parentField.name && f.name !== parentField.name);
975
+ const isDependent = (field) => field.dependsOn && visibleFields.some((f) => f.name === field.dependsOn && f.name !== field.name);
976
+ const renderDependentGroup = (parentField, dependents) => {
977
+ const firstWithLabel = dependents.find((f) => f.dependsOnLabel) || dependents[0];
978
+ const firstWithMessage = dependents.find((f) => f.dependsOnMessage) || dependents[0];
979
+ const groupLabel = firstWithLabel.dependsOnLabel || "Dependent properties";
980
+ const rawMessage = firstWithMessage.dependsOnMessage;
981
+ const tooltipMessage = typeof rawMessage === "function" ? rawMessage(parentField.label) : rawMessage || "";
982
+ return /* @__PURE__ */ React.createElement(Tile, { key: `dep-${parentField.name}`, compact: true }, /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap }, /* @__PURE__ */ React.createElement(Flex, { direction: "row", align: "center", gap: "xs" }, /* @__PURE__ */ React.createElement(Text, { format: { fontWeight: "demibold" } }, groupLabel, " ", tooltipMessage && /* @__PURE__ */ React.createElement(Link, { inline: true, variant: "dark", overlay: /* @__PURE__ */ React.createElement(Tooltip, null, tooltipMessage) }, /* @__PURE__ */ React.createElement(Icon, { name: "info" })))), dependents.map((dep) => /* @__PURE__ */ React.createElement(React.Fragment, { key: dep.name }, renderField(dep)))));
983
+ };
984
+ const renderGridLayout = (fieldSubset) => {
985
+ const fieldList = fieldSubset || visibleFields;
986
+ const elements = [];
987
+ let currentRow = [];
988
+ let currentRowSpan = 0;
989
+ const flushRow = () => {
990
+ if (currentRow.length === 0) return;
991
+ const totalSpan = currentRow.reduce((s, f) => s + getFieldColSpan(f), 0);
992
+ const remainder = columns - totalSpan;
993
+ elements.push(
994
+ /* @__PURE__ */ React.createElement(Flex, { key: `row-${currentRow[0].name}`, direction: "row", gap }, currentRow.map((f) => /* @__PURE__ */ React.createElement(Box, { key: f.name, flex: getFieldColSpan(f) }, renderField(f))), remainder > 0 && /* @__PURE__ */ React.createElement(Box, { flex: remainder }))
995
+ );
996
+ currentRow = [];
997
+ currentRowSpan = 0;
998
+ };
999
+ for (const field of fieldList) {
1000
+ if (isDependent(field)) continue;
1001
+ const span = getFieldColSpan(field);
1002
+ if (span >= columns) {
1003
+ flushRow();
1004
+ elements.push(
1005
+ /* @__PURE__ */ React.createElement(React.Fragment, { key: field.name }, renderField(field))
1006
+ );
1007
+ } else {
1008
+ if (currentRowSpan + span > columns) flushRow();
1009
+ currentRow.push(field);
1010
+ currentRowSpan += span;
1011
+ if (currentRowSpan >= columns) flushRow();
1012
+ }
1013
+ const dependents = getDependents(field);
1014
+ if (dependents.length > 0) {
1015
+ flushRow();
1016
+ elements.push(renderDependentGroup(field, dependents));
1017
+ }
1018
+ }
1019
+ flushRow();
1020
+ return elements;
1021
+ };
1022
+ const renderExplicitLayout = () => {
1023
+ const elements = [];
1024
+ const renderedNames = /* @__PURE__ */ new Set();
1025
+ for (let rowIdx = 0; rowIdx < layout.length; rowIdx++) {
1026
+ const row = layout[rowIdx];
1027
+ const rowFields = [];
1028
+ for (const entry of row) {
1029
+ const fieldName = typeof entry === "string" ? entry : entry.field;
1030
+ const flexValue = typeof entry === "string" ? 1 : entry.flex || 1;
1031
+ const field = visibleFields.find((f) => f.name === fieldName);
1032
+ if (!field) continue;
1033
+ rowFields.push({ field, flex: flexValue });
1034
+ renderedNames.add(fieldName);
1035
+ }
1036
+ if (rowFields.length === 0) continue;
1037
+ if (rowFields.length === 1) {
1038
+ elements.push(
1039
+ /* @__PURE__ */ React.createElement(React.Fragment, { key: rowFields[0].field.name }, renderField(rowFields[0].field))
1040
+ );
1041
+ } else {
1042
+ elements.push(
1043
+ /* @__PURE__ */ React.createElement(Flex, { key: `layout-row-${rowIdx}`, direction: "row", gap }, rowFields.map(({ field, flex }) => /* @__PURE__ */ React.createElement(Box, { key: field.name, flex }, renderField(field))))
1044
+ );
1045
+ }
1046
+ for (const { field } of rowFields) {
1047
+ const dependents = getDependents(field).filter((d) => !renderedNames.has(d.name));
1048
+ if (dependents.length > 0) {
1049
+ elements.push(renderDependentGroup(field, dependents));
1050
+ for (const dep of dependents) renderedNames.add(dep.name);
1051
+ }
1052
+ }
1053
+ }
1054
+ for (const field of visibleFields) {
1055
+ if (renderedNames.has(field.name)) continue;
1056
+ if (isDependent(field)) continue;
1057
+ elements.push(
1058
+ /* @__PURE__ */ React.createElement(React.Fragment, { key: field.name }, renderField(field))
1059
+ );
1060
+ renderedNames.add(field.name);
1061
+ const dependents = getDependents(field).filter((d) => !renderedNames.has(d.name));
1062
+ if (dependents.length > 0) {
1063
+ elements.push(renderDependentGroup(field, dependents));
1064
+ for (const dep of dependents) renderedNames.add(dep.name);
1065
+ }
1066
+ }
1067
+ return elements;
1068
+ };
1069
+ const renderLegacyLayout = (fieldSubset) => {
1070
+ const fieldList = fieldSubset || visibleFields;
1071
+ const rows = [];
1072
+ let i = 0;
1073
+ while (i < fieldList.length) {
1074
+ const field = fieldList[i];
1075
+ if (field.width === "half" && i + 1 < fieldList.length && fieldList[i + 1].width === "half" && !field.dependsOn) {
1076
+ rows.push({ type: "pair", fields: [fieldList[i], fieldList[i + 1]] });
1077
+ i += 2;
1078
+ } else {
1079
+ rows.push({ type: "single", field });
1080
+ i++;
1081
+ }
1082
+ }
1083
+ const elements = [];
1084
+ const processedDeps = /* @__PURE__ */ new Set();
1085
+ for (const row of rows) {
1086
+ if (row.type === "pair") {
1087
+ elements.push(
1088
+ /* @__PURE__ */ React.createElement(Flex, { key: `pair-${row.fields[0].name}`, direction: "row", gap: "sm" }, /* @__PURE__ */ React.createElement(Box, { flex: 1 }, renderField(row.fields[0])), /* @__PURE__ */ React.createElement(Box, { flex: 1 }, renderField(row.fields[1])))
1089
+ );
1090
+ } else {
1091
+ const field = row.field;
1092
+ if (processedDeps.has(field.name)) continue;
1093
+ elements.push(
1094
+ /* @__PURE__ */ React.createElement(React.Fragment, { key: field.name }, renderField(field))
1095
+ );
1096
+ const dependents = getDependents(field);
1097
+ if (dependents.length > 0) {
1098
+ for (const dep of dependents) processedDeps.add(dep.name);
1099
+ elements.push(renderDependentGroup(field, dependents));
1100
+ }
1101
+ }
1102
+ }
1103
+ return elements;
1104
+ };
1105
+ const renderAutoGridLayout = (fieldSubset) => {
1106
+ const fieldList = fieldSubset || visibleFields;
1107
+ const elements = [];
1108
+ let batch = [];
1109
+ const flushBatch = () => {
1110
+ if (batch.length === 0) return;
1111
+ elements.push(
1112
+ /* @__PURE__ */ React.createElement(AutoGrid, { key: `ag-${batch[0].name}`, columnWidth, flexible: true, gap }, batch.map((f) => /* @__PURE__ */ React.createElement(React.Fragment, { key: f.name }, renderField(f))))
1113
+ );
1114
+ batch = [];
1115
+ };
1116
+ for (const field of fieldList) {
1117
+ if (isDependent(field)) continue;
1118
+ batch.push(field);
1119
+ const dependents = getDependents(field);
1120
+ if (dependents.length > 0) {
1121
+ flushBatch();
1122
+ elements.push(renderDependentGroup(field, dependents));
1123
+ }
1124
+ }
1125
+ flushBatch();
1126
+ return elements;
1127
+ };
1128
+ const wrapWithGroups = (fieldList, renderFn) => {
1129
+ const hasGroups = fieldList.some((f) => f.group);
1130
+ if (!hasGroups) return renderFn(fieldList);
1131
+ const chunks = [];
1132
+ let currentGroup = void 0;
1133
+ let currentChunk = [];
1134
+ for (const field of fieldList) {
1135
+ const fieldGroup = field.group || void 0;
1136
+ if (fieldGroup !== currentGroup && currentChunk.length > 0) {
1137
+ chunks.push({ group: currentGroup, fields: [...currentChunk] });
1138
+ currentChunk = [];
1139
+ }
1140
+ currentGroup = fieldGroup;
1141
+ currentChunk.push(field);
1142
+ }
1143
+ if (currentChunk.length > 0) {
1144
+ chunks.push({ group: currentGroup, fields: currentChunk });
1145
+ }
1146
+ const elements = [];
1147
+ for (let i = 0; i < chunks.length; i++) {
1148
+ const chunk = chunks[i];
1149
+ if (i > 0) {
1150
+ elements.push(/* @__PURE__ */ React.createElement(Divider, { key: `group-div-${i}` }));
1151
+ }
1152
+ if (chunk.group) {
1153
+ elements.push(
1154
+ /* @__PURE__ */ React.createElement(Text, { key: `group-label-${i}`, format: { fontWeight: "demibold" } }, chunk.group)
1155
+ );
1156
+ }
1157
+ const chunkElements = renderFn(chunk.fields);
1158
+ if (Array.isArray(chunkElements)) {
1159
+ elements.push(...chunkElements);
1160
+ } else {
1161
+ elements.push(chunkElements);
1162
+ }
1163
+ }
1164
+ return elements;
1165
+ };
1166
+ const renderFieldSubset = (fieldSubset) => {
1167
+ if (layout && fieldSubset === visibleFields) return renderExplicitLayout();
1168
+ if (columnWidth) return renderAutoGridLayout(fieldSubset);
1169
+ if (columns > 1) return renderGridLayout(fieldSubset);
1170
+ return renderLegacyLayout(fieldSubset);
1171
+ };
1172
+ const renderSections = () => {
1173
+ const hasSections = Array.isArray(sections) && sections.length > 0;
1174
+ if (!hasSections) return null;
1175
+ const sectionFieldNames = /* @__PURE__ */ new Set();
1176
+ for (const sec of sections) {
1177
+ if (sec.fields) for (const name of sec.fields) sectionFieldNames.add(name);
1178
+ }
1179
+ const elements = [];
1180
+ for (const sec of sections) {
1181
+ const sectionFields = sec.fields ? visibleFields.filter((f) => sec.fields.includes(f.name)) : [];
1182
+ if (sectionFields.length === 0) continue;
1183
+ const accordionContent = /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap }, renderFieldSubset(sectionFields));
1184
+ const accordion = /* @__PURE__ */ React.createElement(
1185
+ Accordion,
1186
+ {
1187
+ key: sec.id,
1188
+ title: sec.label,
1189
+ size: "sm",
1190
+ defaultOpen: sec.defaultOpen !== false
1191
+ },
1192
+ accordionContent
1193
+ );
1194
+ if (sec.info) {
1195
+ elements.push(
1196
+ /* @__PURE__ */ React.createElement(Flex, { key: sec.id, direction: "row", align: "start", gap: "flush" }, /* @__PURE__ */ React.createElement(Box, { flex: 1 }, accordion), /* @__PURE__ */ React.createElement(Link, { overlay: /* @__PURE__ */ React.createElement(Tooltip, null, sec.info) }, /* @__PURE__ */ React.createElement(Icon, { name: "info", size: "sm", screenReaderText: sec.info })))
1197
+ );
1198
+ } else {
1199
+ elements.push(accordion);
1200
+ }
1201
+ }
1202
+ const unsectionedFields = visibleFields.filter(
1203
+ (f) => !sectionFieldNames.has(f.name)
1204
+ );
1205
+ if (unsectionedFields.length > 0) {
1206
+ elements.push(...renderFieldSubset(unsectionedFields));
1207
+ }
1208
+ return elements;
1209
+ };
1210
+ const renderFieldLayout = () => {
1211
+ const hasSections = Array.isArray(sections) && sections.length > 0;
1212
+ if (hasSections) return renderSections();
1213
+ const hasGroups = visibleFields.some((f) => f.group);
1214
+ if (hasGroups && !layout) {
1215
+ return wrapWithGroups(visibleFields, renderFieldSubset);
1216
+ }
1217
+ if (layout) return renderExplicitLayout();
1218
+ return renderFieldSubset(visibleFields);
1219
+ };
1220
+ const renderButtons = () => {
1221
+ if (submitPosition === "none" || formReadOnly) return null;
1222
+ const isLastStep = !isMultiStep || currentStep === steps.length - 1;
1223
+ const isFirstStep = !isMultiStep || currentStep === 0;
1224
+ if (isMultiStep) {
1225
+ return /* @__PURE__ */ React.createElement(Flex, { direction: "row", justify: "between", align: "center" }, !isFirstStep ? /* @__PURE__ */ React.createElement(Button, { variant: "secondary", onClick: handleBack, disabled }, "Back") : showCancel ? /* @__PURE__ */ React.createElement(Button, { variant: "secondary", onClick: onCancel, disabled }, cancelLabel) : /* @__PURE__ */ React.createElement(Text, null, " "), /* @__PURE__ */ React.createElement(Inline, { gap: "small" }, /* @__PURE__ */ React.createElement(Text, { variant: "microcopy" }, "Step ", currentStep + 1, " of ", steps.length), isLastStep ? /* @__PURE__ */ React.createElement(
1226
+ LoadingButton,
1227
+ {
1228
+ variant: submitVariant,
1229
+ loading: isLoading,
1230
+ onClick: handleSubmit,
1231
+ disabled
1232
+ },
1233
+ submitLabel
1234
+ ) : /* @__PURE__ */ React.createElement(Button, { variant: "primary", onClick: handleNext, disabled }, "Next")));
1235
+ }
1236
+ return /* @__PURE__ */ React.createElement(Flex, { direction: "row", justify: showCancel ? "between" : "start", gap: "sm" }, showCancel && /* @__PURE__ */ React.createElement(Button, { variant: "secondary", onClick: onCancel, disabled }, cancelLabel), /* @__PURE__ */ React.createElement(
1237
+ LoadingButton,
1238
+ {
1239
+ variant: submitVariant,
1240
+ type: noFormWrapper ? "button" : "submit",
1241
+ loading: isLoading,
1242
+ onClick: noFormWrapper ? handleSubmit : void 0,
1243
+ disabled
1244
+ },
1245
+ submitLabel
1246
+ ));
1247
+ };
1248
+ const formContent = /* @__PURE__ */ React.createElement(Flex, { direction: "column", gap }, isMultiStep && showStepIndicator && /* @__PURE__ */ React.createElement(
1249
+ StepIndicator,
1250
+ {
1251
+ currentStep,
1252
+ stepNames: steps.map((s) => s.title)
1253
+ }
1254
+ ), formReadOnly && readOnlyMessage && /* @__PURE__ */ React.createElement(Alert, { title: "Read Only", variant: "warning" }, readOnlyMessage), formError && /* @__PURE__ */ React.createElement(Alert, { title: "Error", variant: "danger" }, typeof formError === "string" ? formError : void 0), formSuccess && /* @__PURE__ */ React.createElement(Alert, { title: "Success", variant: "success" }, formSuccess), isMultiStep && steps[currentStep] && steps[currentStep].render ? steps[currentStep].render({
1255
+ values: formValues,
1256
+ goNext: handleNext,
1257
+ goBack: handleBack,
1258
+ goTo: handleGoTo
1259
+ }) : (
1260
+ /* Field layout */
1261
+ renderFieldLayout()
1262
+ ), renderButtons());
1263
+ if (noFormWrapper) {
1264
+ return formContent;
1265
+ }
1266
+ return /* @__PURE__ */ React.createElement(Form, { onSubmit: handleSubmit, autoComplete: props.autoComplete }, formContent);
1267
+ });
1268
+ export {
1269
+ FormBuilder,
1270
+ useFormPrefill
1271
+ };