@kivacore/ui-pro-shared 0.0.9 → 0.0.11

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.
Files changed (145) hide show
  1. package/package.json +167 -1
  2. package/src/.kiva/config.json +27 -0
  3. package/src/components/avatar-group.tsx +222 -0
  4. package/src/components/kiva/bulk-update-dialog/bulk-update-dialog.tsx +240 -0
  5. package/src/components/kiva/bulk-update-dialog/index.tsx +6 -0
  6. package/src/components/kiva/bulk-update-dialog/types.ts +33 -0
  7. package/src/components/kiva/calendar/animations.ts +40 -0
  8. package/src/components/kiva/calendar/calendar-body.tsx +106 -0
  9. package/src/components/kiva/calendar/calendar-sidebar.tsx +103 -0
  10. package/src/components/kiva/calendar/calendar.tsx +243 -0
  11. package/src/components/kiva/calendar/constants.ts +12 -0
  12. package/src/components/kiva/calendar/contexts/calendar-context.tsx +696 -0
  13. package/src/components/kiva/calendar/contexts/dnd-context.tsx +173 -0
  14. package/src/components/kiva/calendar/dialogs/add-edit-event-dialog.tsx +287 -0
  15. package/src/components/kiva/calendar/dialogs/delete-event-dialog.tsx +73 -0
  16. package/src/components/kiva/calendar/dialogs/event-details-dialog.tsx +163 -0
  17. package/src/components/kiva/calendar/dialogs/events-list-dialog.tsx +122 -0
  18. package/src/components/kiva/calendar/dnd/draggable-event.tsx +66 -0
  19. package/src/components/kiva/calendar/dnd/droppable-area.tsx +53 -0
  20. package/src/components/kiva/calendar/dnd/resizable-event.tsx +190 -0
  21. package/src/components/kiva/calendar/header/calendar-header.tsx +84 -0
  22. package/src/components/kiva/calendar/header/date-navigator.tsx +188 -0
  23. package/src/components/kiva/calendar/header/filter.tsx +80 -0
  24. package/src/components/kiva/calendar/header/today-button.tsx +49 -0
  25. package/src/components/kiva/calendar/header/user-select.tsx +111 -0
  26. package/src/components/kiva/calendar/header/view-tabs.tsx +144 -0
  27. package/src/components/kiva/calendar/helpers.ts +617 -0
  28. package/src/components/kiva/calendar/hooks/use-disclosure.ts +19 -0
  29. package/src/components/kiva/calendar/hooks/use-local-storage.ts +40 -0
  30. package/src/components/kiva/calendar/hooks/use-media-query.ts +25 -0
  31. package/src/components/kiva/calendar/hooks.ts +5 -0
  32. package/src/components/kiva/calendar/index.tsx +27 -0
  33. package/src/components/kiva/calendar/interfaces.ts +35 -0
  34. package/src/components/kiva/calendar/schemas.ts +20 -0
  35. package/src/components/kiva/calendar/settings/settings.tsx +116 -0
  36. package/src/components/kiva/calendar/skeletons/calendar-header-skeleton.tsx +27 -0
  37. package/src/components/kiva/calendar/skeletons/calendar-skeleton.tsx +19 -0
  38. package/src/components/kiva/calendar/skeletons/day-view-skeleton.tsx +40 -0
  39. package/src/components/kiva/calendar/skeletons/month-view-skeleton.tsx +36 -0
  40. package/src/components/kiva/calendar/skeletons/week-view-skeleton.tsx +48 -0
  41. package/src/components/kiva/calendar/skeletons/year-view-skeleton.tsx +42 -0
  42. package/src/components/kiva/calendar/types.ts +25 -0
  43. package/src/components/kiva/calendar/views/agenda-view/agenda-events.tsx +150 -0
  44. package/src/components/kiva/calendar/views/month-view/calendar-month-view.tsx +82 -0
  45. package/src/components/kiva/calendar/views/month-view/day-cell.tsx +218 -0
  46. package/src/components/kiva/calendar/views/month-view/event-bullet.tsx +46 -0
  47. package/src/components/kiva/calendar/views/month-view/month-event-badge.tsx +154 -0
  48. package/src/components/kiva/calendar/views/timeline/calendar-timeline-view.tsx +100 -0
  49. package/src/components/kiva/calendar/views/timeline/lib/timeline-layout.ts +130 -0
  50. package/src/components/kiva/calendar/views/timeline/lib/timeline-model.ts +504 -0
  51. package/src/components/kiva/calendar/views/timeline/timeline-event-bar.tsx +68 -0
  52. package/src/components/kiva/calendar/views/timeline/timeline-grid-header.tsx +125 -0
  53. package/src/components/kiva/calendar/views/timeline/timeline-row.tsx +159 -0
  54. package/src/components/kiva/calendar/views/timeline/timeline-section.tsx +61 -0
  55. package/src/components/kiva/calendar/views/timeline/use-timeline-sections.ts +278 -0
  56. package/src/components/kiva/calendar/views/week-and-day-view/calendar-day-view.tsx +277 -0
  57. package/src/components/kiva/calendar/views/week-and-day-view/calendar-time-line.tsx +47 -0
  58. package/src/components/kiva/calendar/views/week-and-day-view/calendar-week-view.tsx +229 -0
  59. package/src/components/kiva/calendar/views/week-and-day-view/day-view-multi-day-events-row.tsx +79 -0
  60. package/src/components/kiva/calendar/views/week-and-day-view/event-block.tsx +116 -0
  61. package/src/components/kiva/calendar/views/week-and-day-view/render-grouped-events.tsx +54 -0
  62. package/src/components/kiva/calendar/views/week-and-day-view/week-view-multi-day-events-row.tsx +159 -0
  63. package/src/components/kiva/calendar/views/year-view/calendar-year-view.tsx +159 -0
  64. package/src/components/kiva/data-table-side-filters/components/side-filter-active-chips.tsx +137 -0
  65. package/src/components/kiva/data-table-side-filters/components/side-filter-clear.tsx +34 -0
  66. package/src/components/kiva/data-table-side-filters/components/side-filter-search.tsx +67 -0
  67. package/src/components/kiva/data-table-side-filters/components/side-filter-section.tsx +77 -0
  68. package/src/components/kiva/data-table-side-filters/controllers/side-filter-async-options.tsx +354 -0
  69. package/src/components/kiva/data-table-side-filters/controllers/side-filter-boolean.tsx +66 -0
  70. package/src/components/kiva/data-table-side-filters/controllers/side-filter-checkbox-list.tsx +137 -0
  71. package/src/components/kiva/data-table-side-filters/controllers/side-filter-date-range.tsx +204 -0
  72. package/src/components/kiva/data-table-side-filters/controllers/side-filter-numeric-range.tsx +162 -0
  73. package/src/components/kiva/data-table-side-filters/controllers/side-filter-options-dropdown.tsx +191 -0
  74. package/src/components/kiva/data-table-side-filters/controllers/side-filter-text.tsx +53 -0
  75. package/src/components/kiva/data-table-side-filters/core/query-translator.ts +367 -0
  76. package/src/components/kiva/data-table-side-filters/core/types.ts +81 -0
  77. package/src/components/kiva/data-table-side-filters/data-table-side-filters.tsx +483 -0
  78. package/src/components/kiva/data-table-side-filters/hooks/use-data-table-side-filters.tsx +160 -0
  79. package/src/components/kiva/data-table-side-filters/hooks/use-show-more.tsx +62 -0
  80. package/src/components/kiva/data-table-side-filters/index.tsx +44 -0
  81. package/src/components/kiva/data-table-side-filters/lib/render-mode.ts +62 -0
  82. package/src/components/kiva/date-time-picker.tsx +163 -0
  83. package/src/components/kiva/editable-record-detail.tsx +809 -0
  84. package/src/components/kiva/enum-option-editor/enum-option-editor.tsx +891 -0
  85. package/src/components/kiva/enum-option-editor/index.tsx +26 -0
  86. package/src/components/kiva/enum-option-editor/kiva-enum-option-editor.tsx +320 -0
  87. package/src/components/kiva/enum-option-editor/types.ts +90 -0
  88. package/src/components/kiva/kanban.tsx +1376 -0
  89. package/src/components/kiva/kiva-data-export-menu.tsx +543 -0
  90. package/src/components/kiva/map.tsx +1631 -0
  91. package/src/components/kiva/pivot-calendar/components/group-sidebar.tsx +95 -0
  92. package/src/components/kiva/pivot-calendar/components/pivot-calendar-toolbar.tsx +113 -0
  93. package/src/components/kiva/pivot-calendar/components/stats-cell.tsx +126 -0
  94. package/src/components/kiva/pivot-calendar/helpers.ts +374 -0
  95. package/src/components/kiva/pivot-calendar/hooks/use-pivot-calendar.ts +222 -0
  96. package/src/components/kiva/pivot-calendar/index.tsx +32 -0
  97. package/src/components/kiva/pivot-calendar/pivot-calendar.tsx +107 -0
  98. package/src/components/kiva/pivot-calendar/types.ts +154 -0
  99. package/src/components/kiva/pivot-calendar/views/days-of-month-view.tsx +37 -0
  100. package/src/components/kiva/pivot-calendar/views/days-of-week-view.tsx +37 -0
  101. package/src/components/kiva/pivot-calendar/views/month-calendar-view.tsx +154 -0
  102. package/src/components/kiva/pivot-calendar/views/months-of-year-view.tsx +40 -0
  103. package/src/components/kiva/pivot-calendar/views/pivot-grid-view.tsx +251 -0
  104. package/src/components/kiva/pivot-filter/index.tsx +9 -0
  105. package/src/components/kiva/pivot-filter/pivot-filter-item.tsx +159 -0
  106. package/src/components/kiva/pivot-filter/pivot-filter-settings.tsx +161 -0
  107. package/src/components/kiva/pivot-filter/pivot-filter.tsx +187 -0
  108. package/src/components/kiva/pivot-filter/types.ts +82 -0
  109. package/src/components/kiva/pivot-grid/hooks/use-pivot-grid.ts +683 -0
  110. package/src/components/kiva/pivot-grid/index.tsx +23 -0
  111. package/src/components/kiva/pivot-grid/lib/pivot-grid-color-rules.ts +98 -0
  112. package/src/components/kiva/pivot-grid/lib/pivot-grid-export.ts +265 -0
  113. package/src/components/kiva/pivot-grid/lib/pivot-grid-model.ts +1110 -0
  114. package/src/components/kiva/pivot-grid/pivot-grid-demo-data.ts +200 -0
  115. package/src/components/kiva/pivot-grid/pivot-grid-export-menu.tsx +66 -0
  116. package/src/components/kiva/pivot-grid/pivot-grid-toolbar.tsx +85 -0
  117. package/src/components/kiva/pivot-grid/pivot-grid.tsx +601 -0
  118. package/src/components/kiva/pivot-grid/types.ts +195 -0
  119. package/src/components/kiva/place-autocomplete.tsx +484 -0
  120. package/src/components/kiva/record-delete-confirm-dialog/index.tsx +10 -0
  121. package/src/components/kiva/record-delete-confirm-dialog/record-delete-confirm-dialog.tsx +266 -0
  122. package/src/components/kiva/record-delete-confirm-dialog/types.ts +25 -0
  123. package/src/hooks/kiva/_internal/autonumber-setting.ts +112 -0
  124. package/src/hooks/kiva/_internal/form-layout-to-view.ts +665 -0
  125. package/src/hooks/kiva/_internal/kiva-hook-utils.ts +143 -0
  126. package/src/hooks/kiva/_internal/use-computed-field-evaluator.tsx +310 -0
  127. package/src/hooks/kiva/_internal/use-field-actions-evaluator.tsx +398 -0
  128. package/src/hooks/kiva/_internal/use-form-actions-evaluator.tsx +363 -0
  129. package/src/hooks/kiva/_internal/use-form-view-engine.tsx +2200 -0
  130. package/src/hooks/kiva/_internal/use-kiva-form-view-fields.tsx +190 -0
  131. package/src/hooks/kiva/_internal/use-kiva-kanban-cards.tsx +311 -0
  132. package/src/hooks/kiva/use-data-export.tsx +265 -0
  133. package/src/hooks/kiva/use-kiva-calendar.tsx +992 -0
  134. package/src/hooks/kiva/use-kiva-data-export.tsx +173 -0
  135. package/src/hooks/kiva/use-kiva-data-grid.tsx +4750 -0
  136. package/src/hooks/kiva/use-kiva-data-view-select.tsx +1273 -0
  137. package/src/hooks/kiva/use-kiva-form-view.tsx +1581 -0
  138. package/src/hooks/kiva/use-kiva-inventory.tsx +184 -0
  139. package/src/hooks/kiva/use-kiva-kanban.tsx +1750 -0
  140. package/src/hooks/kiva/use-kiva-map-view.tsx +2255 -0
  141. package/src/hooks/kiva/use-kiva-pivot-calendar.tsx +759 -0
  142. package/src/hooks/kiva/use-kiva-pivot-filter.tsx +1523 -0
  143. package/src/hooks/kiva/use-kiva-pivot-grid.tsx +543 -0
  144. package/src/hooks/kiva/use-kiva-tenant.tsx +313 -0
  145. package/src/hooks/kiva/use-parameter-persistence.ts +191 -0
@@ -0,0 +1,2200 @@
1
+ 'use client';
2
+
3
+ // @ts-nocheck
4
+ /* eslint-disable */
5
+ import {
6
+ useCallback,
7
+ useEffect,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ type CSSProperties,
12
+ type ReactNode,
13
+ type RefObject
14
+ } from 'react';
15
+
16
+ import { type RestApiClient } from '@kivacore/api-client';
17
+ import { ChevronDown } from 'lucide-react';
18
+
19
+ import {
20
+ getCompanionFieldSlug,
21
+ isReadOnlyField
22
+ } from '@kivacore/ui-pro-shared/components/kiva/form-fields/lib/utils';
23
+ import { getFormLayoutClassName } from '@kivacore/ui-pro-shared/components/kiva/form-fields/lib/form-layout';
24
+ import { validateValidationTokens } from '@kivacore/ui-pro-shared/components/kiva/form-fields/lib/validation-tokens';
25
+ import {
26
+ type ComputedBooleanFormula,
27
+ type CustomValidationRule,
28
+ type KivaFormFieldProps,
29
+ type EnumOption,
30
+ type FieldAction,
31
+ type FieldActionPropertyOverrides,
32
+ type FormAction,
33
+ type FormCustomValidationRule,
34
+ type IField,
35
+ type IFieldType,
36
+ type StoredFileValue
37
+ } from '@kivacore/ui-pro-shared/components/kiva/form-fields/types';
38
+ import {
39
+ EditableRecordDetail,
40
+ EditableRecordDetailField,
41
+ type FieldChange,
42
+ type RecordDetailField
43
+ } from '@kivacore/ui-pro-shared/components/kiva/editable-record-detail';
44
+ import { type KivaValueProps } from '@kivacore/ui-pro-shared/components/kiva/value-renderers/types';
45
+ import {
46
+ FORM_FIELD_MAP
47
+ } from '@kivacore/ui-pro-shared/hooks/kiva/use-kiva-field-component';
48
+
49
+ import { cn } from '@kivacore/ui-pro-shared/lib/utils';
50
+ import {
51
+ FieldDescription,
52
+ FieldLegend,
53
+ FieldSet
54
+ } from '@kivacore/ui-pro-shared/components/field';
55
+ import {
56
+ Collapsible,
57
+ CollapsibleContent,
58
+ CollapsibleTrigger
59
+ } from '@kivacore/ui-pro-shared/components/collapsible';
60
+ import {
61
+ Tabs,
62
+ TabsContent,
63
+ TabsList,
64
+ TabsTrigger
65
+ } from '@kivacore/ui-pro-shared/components/tabs';
66
+
67
+ /*
68
+ * The field-render components live in a sibling `_internal/` module. Imported
69
+ * via the `@ui/library/hooks/...` alias so the BFS resolver in
70
+ * `scripts/lib/dependencies.ts` bundles them into the registry entry of every
71
+ * hook that transitively depends on this engine.
72
+ */
73
+ import {
74
+ KivaFormViewMappedFormField,
75
+ KivaFormViewMappedValueField,
76
+ MacroFormField
77
+ } from '@kivacore/ui-pro-shared/hooks/kiva/_internal/use-kiva-form-view-fields';
78
+ import {
79
+ useComputedFieldEvaluator
80
+ } from '@kivacore/ui-pro-shared/hooks/kiva/_internal/use-computed-field-evaluator';
81
+ import {
82
+ useFieldActionsEvaluator
83
+ } from '@kivacore/ui-pro-shared/hooks/kiva/_internal/use-field-actions-evaluator';
84
+ import {
85
+ useFormActionsEvaluator
86
+ } from '@kivacore/ui-pro-shared/hooks/kiva/_internal/use-form-actions-evaluator';
87
+ import { evaluateJsonata } from '@kivacore/ui-pro-shared/components/kiva/jsonata-editor/lib/evaluate';
88
+
89
+ /*
90
+ * ---------------------------------------------------------------------------
91
+ * Shared, backend-agnostic form-view engine.
92
+ *
93
+ * This module holds the entire rendering / state / computed-field / action /
94
+ * validation / submit-payload engine that powers both `useKivaFormView`
95
+ * (Kiva-wired) and `useDynamicFormView` (backend-agnostic). It owns NO
96
+ * network I/O — the caller injects already-normalized `IField[]`, resolved
97
+ * option lists (`resolveEnumOptions`), an optional `uploadFile`, and an
98
+ * `onSubmit` sink. Keeping this the single source of truth means the two hooks
99
+ * can never drift apart.
100
+ * ---------------------------------------------------------------------------
101
+ */
102
+
103
+ export type KivaFormViewMode = 'create' | 'edit' | 'view';
104
+
105
+ export type KivaFormViewRenderMode = 'form' | 'value';
106
+
107
+ /**
108
+ * Which `validations` token constraints beyond `required` are enforced on
109
+ * submit. `required` is ALWAYS enforced and is unaffected by this setting.
110
+ *
111
+ * - `'off'` (default) — tokens are advisory. Historic behavior: a stale
112
+ * `maxLength:` on a data-source field can never block an existing record.
113
+ * - `'form'` — enforce the token list the form layout supplies for a field
114
+ * (`fieldLayout.validations`), ignoring schema-only tokens.
115
+ * - `'all'` — enforce form tokens where present, otherwise the data-source
116
+ * field's own tokens.
117
+ */
118
+ export type KivaFormViewValidationTokenMode = 'off' | 'form' | 'all';
119
+
120
+ export type KivaFormViewColSpan = 1 | 2 | 3 | 4 | 'full';
121
+
122
+ export interface KivaFormViewLayoutFieldItem {
123
+ type: 'field';
124
+ slug: string;
125
+ colSpan?: KivaFormViewColSpan;
126
+ className?: string;
127
+ /**
128
+ * Per-field label placement override. Only `'top'` is meaningful: it opts
129
+ * this one field out of a form- or panel-level label-LEFT layout and stacks
130
+ * it. `'left'` equals the common default, so it is accepted and ignored.
131
+ */
132
+ labelAlign?: 'top' | 'left';
133
+ }
134
+
135
+ interface KivaFormViewLayoutSectionBase {
136
+ id: string;
137
+ variant: 'fieldset' | 'tabpanel' | 'tab';
138
+ title?: ReactNode;
139
+ description?: ReactNode;
140
+ className?: string;
141
+ contentClassName?: string;
142
+ colSpan?: KivaFormViewColSpan;
143
+ }
144
+
145
+ export interface KivaFormViewFieldsetSection extends KivaFormViewLayoutSectionBase {
146
+ variant: 'fieldset';
147
+ items: Array<KivaFormViewLayoutItem>;
148
+ /** Column count for fields inside the panel. Defaults to the form grid. */
149
+ columns?: 1 | 2 | 3 | 4;
150
+ /** Render the panel with a fold/unfold toggle on its title. */
151
+ collapsible?: boolean;
152
+ /** Start folded. Only honored together with `collapsible`. */
153
+ defaultCollapsed?: boolean;
154
+ }
155
+
156
+ export interface KivaFormViewTabSection extends KivaFormViewLayoutSectionBase {
157
+ variant: 'tab';
158
+ items: Array<KivaFormViewLayoutItem>;
159
+ }
160
+
161
+ export interface KivaFormViewTabPanelSection extends KivaFormViewLayoutSectionBase {
162
+ variant: 'tabpanel';
163
+ items: Array<KivaFormViewTabSection>;
164
+ defaultTabId?: string;
165
+ }
166
+
167
+ export type KivaFormViewSection = KivaFormViewFieldsetSection | KivaFormViewTabPanelSection | KivaFormViewTabSection;
168
+
169
+ export type KivaFormViewLayoutItem = string | KivaFormViewLayoutFieldItem | KivaFormViewSection;
170
+
171
+ export interface KivaFormViewFieldLayout {
172
+ hidden?: boolean | ((values: Record<string, unknown>) => boolean);
173
+ required?: boolean | ((values: Record<string, unknown>) => boolean);
174
+ readOnly?: boolean;
175
+ disabled?: boolean;
176
+ colSpan?: KivaFormViewColSpan;
177
+ className?: string;
178
+ label?: ReactNode;
179
+ description?: ReactNode;
180
+ fieldProps?: Partial<KivaFormFieldProps>;
181
+ valueProps?: Partial<KivaValueProps>;
182
+ /** QB JSON or JSONata expression — evaluated to boolean; true → field is hidden */
183
+ computedHidden?: ComputedBooleanFormula;
184
+ /** QB JSON or JSONata expression — evaluated to boolean; true → field is required */
185
+ computedRequired?: ComputedBooleanFormula;
186
+ /** QB JSON or JSONata expression — evaluated to boolean; true → field is read-only */
187
+ computedReadonly?: ComputedBooleanFormula;
188
+ /** JSONata expression evaluated to a string — overrides the field label at runtime */
189
+ computedLabel?: string | null;
190
+ /** JSONata expression evaluated to a string — overrides the field description at runtime */
191
+ computedDescription?: string | null;
192
+ /** JSONata expression — result is written back as the field's value (computed value) */
193
+ computedFormula?: string | null;
194
+ /** Actions that run when this field's value changes — override IField.fieldActions when provided */
195
+ fieldActions?: FieldAction[] | null;
196
+ /** Runtime custom validation rules — merged with (and override) IField.customValidations */
197
+ customValidations?: CustomValidationRule[] | null;
198
+ /**
199
+ * Validation token list (`required`, `minLength:2`, `pattern:…`, `min:0`, …)
200
+ * that overrides `IField.validations` for this form. Saved form layouts carry
201
+ * per-form tokens here so a form can be stricter than the data-source field.
202
+ */
203
+ validations?: Array<string> | null;
204
+ }
205
+
206
+ export interface KivaFormViewRenderFieldOptions {
207
+ mode?: KivaFormViewMode;
208
+ wrapperClassName?: string;
209
+ className?: string;
210
+ label?: ReactNode;
211
+ description?: ReactNode;
212
+ }
213
+
214
+ export interface KivaFormViewRenderLayoutOptions {
215
+ mode?: KivaFormViewMode;
216
+ columns?: 1 | 2 | 3 | 4;
217
+ className?: string;
218
+ wrapperClassName?: string;
219
+ fieldClassName?: string;
220
+ }
221
+
222
+ export interface KivaFormViewField {
223
+ slug: string;
224
+ /**
225
+ * Raw source field object as supplied by the caller (a Kiva
226
+ * `DataSourceField` in `useKivaFormView`, the raw `IField` in
227
+ * `useDynamicFormView`). The engine never reads it — pure passthrough.
228
+ */
229
+ sourceField: unknown;
230
+ field: IField;
231
+ enumOptions: Array<EnumOption>;
232
+ value: unknown;
233
+ required: boolean;
234
+ hidden: boolean;
235
+ readOnly: boolean;
236
+ disabled: boolean;
237
+ editable: boolean;
238
+ renderMode: KivaFormViewRenderMode;
239
+ colSpan?: KivaFormViewColSpan;
240
+ className?: string;
241
+ label?: ReactNode;
242
+ description?: ReactNode;
243
+ fieldProps?: Partial<KivaFormFieldProps>;
244
+ valueProps?: Partial<KivaValueProps>;
245
+ queryKeys: Array<string>;
246
+ submitKeys: Array<string>;
247
+ /**
248
+ * Token list enforced for this field on submit, resolved from the engine's
249
+ * `validationTokens` mode. `undefined` = nothing beyond `required` is
250
+ * enforced. Read it to render hints that match what validation will do.
251
+ */
252
+ enforcedValidations?: Array<string>;
253
+ }
254
+
255
+ /**
256
+ * Submit context handed to `onSubmit` / `transformSubmit`. `dataSource` is
257
+ * `unknown` at the engine boundary — the Kiva adapter narrows it to a
258
+ * `DataSource`, the dynamic adapter leaves it `undefined`.
259
+ */
260
+ export interface KivaFormViewSubmitContext {
261
+ mode: KivaFormViewMode;
262
+ itemId?: string;
263
+ values: Record<string, unknown>;
264
+ fields: Array<KivaFormViewField>;
265
+ dataSource?: unknown;
266
+ }
267
+
268
+ /*
269
+ * Exported so the extracted field-renderer components in
270
+ * `./use-kiva-form-view-fields` can type their `form` prop without needing
271
+ * access to the rest of `LocalFormState`.
272
+ */
273
+ export interface LocalFormShape {
274
+ Field: ({ name, children }: { name: string; children: (field: any) => ReactNode }) => ReactNode;
275
+ }
276
+
277
+ interface ClickToEditFieldConfig {
278
+ recordField: RecordDetailField;
279
+ readOnly: boolean;
280
+ disabled: boolean;
281
+ submitKeys: Array<string>;
282
+ label?: ReactNode;
283
+ className?: string;
284
+ }
285
+
286
+ interface SortedClickToEditFieldConfig extends ClickToEditFieldConfig {
287
+ sortOrder: number;
288
+ }
289
+
290
+ interface LocalFormState {
291
+ form: LocalFormShape;
292
+ valuesRef: RefObject<Record<string, unknown>>;
293
+ baselineRef: RefObject<Record<string, unknown>>;
294
+ validationErrors: Map<string, string>;
295
+ valuesVersion: number;
296
+ setValue: (slug: string, value: unknown) => void;
297
+ /** Like setValue but also increments resetSignal so MacroFormField re-reads its localValue. Use for programmatic writes (computedFormula). */
298
+ setValueExternal: (slug: string, value: unknown) => void;
299
+ reset: () => void;
300
+ replaceValues: (nextValues: Record<string, unknown>, updateBaseline?: boolean) => void;
301
+ setValidationErrors: (errors: Map<string, string>) => void;
302
+ commit: (nextBaseline?: Record<string, unknown>) => void;
303
+ /** Populated by the engine after the field-actions evaluator is wired up */
304
+ fieldActionsRef: RefObject<((slug: string, value: unknown, formValues: Record<string, unknown>) => void) | null>;
305
+ }
306
+
307
+ /**
308
+ * Everything the engine needs to render / manage / submit a form. All backend
309
+ * work (schema fetch, item fetch, option loading, persistence) is done by the
310
+ * caller and reduced to these plain inputs.
311
+ */
312
+ export interface FormViewEngineInput {
313
+ /** Already-normalized fields (schema → IField happens in the caller). */
314
+ fields: Array<{ sourceField?: unknown; field: IField }>;
315
+ mode: KivaFormViewMode;
316
+ /** Fully-built initial values (defaults merged with the loaded/provided record). */
317
+ initialValues: Record<string, unknown>;
318
+ itemId?: string;
319
+ /** Opaque data-source metadata, exposed on the submit context only. */
320
+ dataSource?: unknown;
321
+ fieldOrder?: Array<string>;
322
+ hiddenFieldSlugs?: Array<string>;
323
+ fieldLayout?: Record<string, KivaFormViewFieldLayout>;
324
+ layout?: Array<KivaFormViewLayoutItem>;
325
+ gridColumns?: 1 | 2 | 3 | 4;
326
+ /** Form-level label placement — 'top' (default) or 'left' (horizontal label column). */
327
+ labelAlign?: 'top' | 'left';
328
+ /** Label column width bucket when labelAlign is 'left'. */
329
+ labelWidth?: 'sm' | 'md' | 'lg';
330
+ /** Form-level field density applied to inputs. */
331
+ fieldSize?: 'sm' | 'md' | 'lg';
332
+ /** Form-level input style. */
333
+ fieldVariant?: 'outline' | 'filled';
334
+ includeReadOnlyFields: boolean;
335
+ /** Token enforcement mode. Defaults to `'off'` — opt in per surface. */
336
+ validationTokens?: KivaFormViewValidationTokenMode;
337
+ unsupportedFieldBehavior: 'skip' | 'value';
338
+ disabled: boolean;
339
+ clickToEdit: boolean;
340
+ /** When false, the one-shot `onFormLoad` trigger is deferred until data is ready. Defaults to true. */
341
+ isReady?: boolean;
342
+ /** Per-field option resolution (static list, remote result, or inline enums — caller's choice). */
343
+ resolveEnumOptions: (field: IField) => Array<EnumOption>;
344
+ /** Optional file/image upload handler injected into image/file field props. */
345
+ uploadFile?: (type: IFieldType, file: File) => Promise<StoredFileValue | null>;
346
+ formActions?: FormAction[] | null;
347
+ formCustomValidations?: FormCustomValidationRule[] | null;
348
+ /** Persistence sink — receives the built payload. `forceUpdate` is set by inline click-to-edit saves. */
349
+ onSubmit: (
350
+ payload: Record<string, unknown>,
351
+ context: KivaFormViewSubmitContext,
352
+ forceUpdate: boolean
353
+ ) => Promise<unknown> | unknown;
354
+ transformSubmit?: (
355
+ payload: Record<string, unknown>,
356
+ context: KivaFormViewSubmitContext
357
+ ) => Record<string, unknown>;
358
+ onSubmitSuccess?: (result: unknown, payload: Record<string, unknown>) => void;
359
+ onSubmitError?: (error: unknown, payload: Record<string, unknown>) => void;
360
+ /** Fires whenever the live values change (field edits + programmatic writes). */
361
+ onValuesChange?: (values: Record<string, unknown>) => void;
362
+ /** Called after a successful edit/click-to-edit save so the caller can refetch the record. */
363
+ refetchItem?: () => void;
364
+ appSlug?: string;
365
+ dataSourceSlug?: string;
366
+ client?: RestApiClient;
367
+ }
368
+
369
+ export interface FormViewEngineResult {
370
+ mode: KivaFormViewMode;
371
+ item: Record<string, unknown>;
372
+ form: LocalFormShape;
373
+ values: Record<string, unknown>;
374
+ defaultValues: Record<string, unknown>;
375
+ fields: Array<KivaFormViewField>;
376
+ allFields: Array<KivaFormViewField>;
377
+ unsupportedFields: Array<KivaFormViewField>;
378
+ validationErrors: Map<string, string>;
379
+ formValidationErrors: string[];
380
+ isDirty: boolean;
381
+ isSubmitting: boolean;
382
+ setValue: (slug: string, value: unknown) => void;
383
+ validate: () => Promise<boolean>;
384
+ reset: () => void;
385
+ submit: () => Promise<unknown>;
386
+ resetActionOverrides: () => void;
387
+ renderField: (slug: string, options?: KivaFormViewRenderFieldOptions) => ReactNode;
388
+ renderLayout: (options?: KivaFormViewRenderLayoutOptions) => ReactNode;
389
+ }
390
+
391
+ function hasKivaFormFieldComponent(fieldType: IFieldType): boolean {
392
+ return Boolean(FORM_FIELD_MAP[fieldType]);
393
+ }
394
+
395
+ function useLocalForm(
396
+ initialValues: Record<string, unknown>
397
+ ): LocalFormState {
398
+ const valuesRef = useRef<Record<string, unknown>>({ ...initialValues });
399
+ const baselineRef = useRef<Record<string, unknown>>({ ...initialValues });
400
+ const validationErrorsRef = useRef<Map<string, string>>(new Map());
401
+ const resetSignalRef = useRef(0);
402
+ const [valuesVersion, setValuesVersion] = useState(0);
403
+ const initialValuesKey = useMemo(() => stableStringify(initialValues), [initialValues]);
404
+
405
+ const onFieldChangeRef = useRef((slug: string, value: unknown) => {
406
+ valuesRef.current[slug] = value;
407
+ if (validationErrorsRef.current.has(slug)) {
408
+ const next = new Map(validationErrorsRef.current);
409
+
410
+ next.delete(slug);
411
+ validationErrorsRef.current = next;
412
+ }
413
+ setValuesVersion(version => version + 1);
414
+ fieldActionsRef.current?.(slug, value, valuesRef.current);
415
+ });
416
+
417
+ const fieldActionsRef = useRef<
418
+ ((slug: string, value: unknown, formValues: Record<string, unknown>) => void) | null
419
+ >(null);
420
+
421
+ /*
422
+ * `form.Field` is a stable wrapper around MacroFormField that threads the
423
+ * hook's refs/state version into each rendered field. We freeze it via
424
+ * useState so the component identity is stable across renders (preventing
425
+ * re-mounts of every field cell on every keystroke). The
426
+ * @eslint-react/component-hook-factories rule normally forbids defining
427
+ * components inside other functions for that exact reason — but here the
428
+ * stability comes from useState itself, and Field is part of the hook's
429
+ * public surface (`<form.Field name="...">{(field) => ...}</form.Field>`).
430
+ */
431
+ const [form] = useState(() => ({
432
+ Field: ({
433
+ name,
434
+ children
435
+ }: {
436
+ name: string;
437
+ children: (field: any) => ReactNode;
438
+ }) => (
439
+ <MacroFormField
440
+ slug={name}
441
+ valuesRef={valuesRef}
442
+ resetSignal={resetSignalRef.current}
443
+ onFieldChange={onFieldChangeRef}
444
+ validationErrors={validationErrorsRef}
445
+ valuesVersion={valuesVersion}>
446
+ {children}
447
+ </MacroFormField>
448
+ )
449
+ }));
450
+
451
+ const replaceValues = useCallback((nextValues: Record<string, unknown>, updateBaseline = false) => {
452
+ valuesRef.current = { ...nextValues };
453
+ if (updateBaseline) {
454
+ baselineRef.current = { ...nextValues };
455
+ }
456
+ validationErrorsRef.current = new Map();
457
+ resetSignalRef.current += 1;
458
+ setValuesVersion(version => version + 1);
459
+ }, []);
460
+
461
+ /*
462
+ * Re-seed values + baseline whenever the parent passes a new identity
463
+ * for `initialValues` (compared by `stableStringify`-keyed identity).
464
+ * Store-and-compare so the inner setState bump doesn't trip
465
+ * `set-state-in-effect`.
466
+ */
467
+ const [trackedInitialValuesKey, setTrackedInitialValuesKey] = useState(initialValuesKey);
468
+
469
+ if (trackedInitialValuesKey !== initialValuesKey) {
470
+ setTrackedInitialValuesKey(initialValuesKey);
471
+ replaceValues(initialValues, true);
472
+ }
473
+
474
+ const setValue = useCallback((slug: string, value: unknown) => {
475
+ valuesRef.current[slug] = value;
476
+ if (validationErrorsRef.current.has(slug)) {
477
+ const next = new Map(validationErrorsRef.current);
478
+
479
+ next.delete(slug);
480
+ validationErrorsRef.current = next;
481
+ }
482
+ setValuesVersion(version => version + 1);
483
+ }, []);
484
+
485
+ const setValueExternal = useCallback((slug: string, value: unknown) => {
486
+ valuesRef.current[slug] = value;
487
+ resetSignalRef.current += 1;
488
+ setValuesVersion(version => version + 1);
489
+ }, []);
490
+
491
+ const setValidationErrors = useCallback((errors: Map<string, string>) => {
492
+ validationErrorsRef.current = new Map(errors);
493
+ setValuesVersion(version => version + 1);
494
+ }, []);
495
+
496
+ const reset = useCallback(() => {
497
+ replaceValues(baselineRef.current, false);
498
+ }, [replaceValues]);
499
+
500
+ const commit = useCallback((nextBaseline?: Record<string, unknown>) => {
501
+ baselineRef.current = { ...(nextBaseline ?? valuesRef.current) };
502
+ validationErrorsRef.current = new Map();
503
+ setValuesVersion(version => version + 1);
504
+ }, []);
505
+
506
+ return {
507
+ form,
508
+ valuesRef,
509
+ baselineRef,
510
+ validationErrors: validationErrorsRef.current,
511
+ valuesVersion,
512
+ setValue,
513
+ setValueExternal,
514
+ reset,
515
+ replaceValues,
516
+ setValidationErrors,
517
+ commit,
518
+ fieldActionsRef
519
+ };
520
+ }
521
+
522
+ export function useFormViewEngine(input: FormViewEngineInput): FormViewEngineResult {
523
+ const {
524
+ fields: mappedFields,
525
+ mode,
526
+ initialValues,
527
+ itemId,
528
+ dataSource,
529
+ fieldOrder,
530
+ hiddenFieldSlugs,
531
+ fieldLayout,
532
+ layout,
533
+ gridColumns: gridColumnsOption,
534
+ labelAlign,
535
+ labelWidth,
536
+ fieldSize,
537
+ fieldVariant,
538
+ includeReadOnlyFields,
539
+ validationTokens = 'off',
540
+ unsupportedFieldBehavior,
541
+ disabled,
542
+ clickToEdit,
543
+ isReady = true,
544
+ resolveEnumOptions,
545
+ uploadFile,
546
+ formActions,
547
+ formCustomValidations,
548
+ onSubmit,
549
+ transformSubmit,
550
+ onSubmitSuccess,
551
+ onSubmitError,
552
+ onValuesChange,
553
+ refetchItem,
554
+ appSlug,
555
+ dataSourceSlug,
556
+ client
557
+ } = input;
558
+
559
+ const gridColumns = gridColumnsOption ?? 2;
560
+ /*
561
+ * Form-level layout styling applied at the field grid container via arbitrary
562
+ * variants that target the shared `[data-slot=field]` / `[data-slot=field-label]`
563
+ * primitives — so label placement/width, field density and input style are
564
+ * honored without threading props into all 40+ field components.
565
+ */
566
+ const formLayoutClassName = getFormLayoutClassName(labelAlign, labelWidth, fieldSize, fieldVariant);
567
+
568
+ const localForm = useLocalForm(initialValues);
569
+
570
+ const values = useMemo(() => {
571
+ void localForm.valuesVersion;
572
+
573
+ return { ...localForm.valuesRef.current };
574
+ }, [localForm.valuesRef, localForm.valuesVersion]);
575
+
576
+ const onValuesChangeRef = useRef(onValuesChange);
577
+
578
+ onValuesChangeRef.current = onValuesChange;
579
+ const valuesChangeMountedRef = useRef(false);
580
+
581
+ useEffect(() => {
582
+ if (!valuesChangeMountedRef.current) {
583
+ valuesChangeMountedRef.current = true;
584
+
585
+ return;
586
+ }
587
+
588
+ onValuesChangeRef.current?.(values);
589
+ }, [values]);
590
+
591
+ const computedFieldEntries = useMemo(() => {
592
+ return mappedFields.map(({ field }) => {
593
+ const layout = fieldLayout?.[field.slug];
594
+
595
+ /*
596
+ * fieldLayout computed properties take priority over backend-sourced IField ones.
597
+ * This is the primary mechanism — app developers configure computed fields via
598
+ * fieldLayout without any backend involvement, mirroring fieldLayout.hidden /
599
+ * fieldLayout.required for dynamic visibility/required logic.
600
+ */
601
+ const mergedField: IField = {
602
+ ...field,
603
+ ...(layout?.computedHidden !== undefined && { computedHidden: layout.computedHidden }),
604
+ ...(layout?.computedRequired !== undefined && { computedRequired: layout.computedRequired }),
605
+ ...(layout?.computedReadonly !== undefined && { computedReadonly: layout.computedReadonly }),
606
+ ...(layout?.computedLabel !== undefined && { computedLabel: layout.computedLabel }),
607
+ ...(layout?.computedDescription !== undefined && { computedDescription: layout.computedDescription }),
608
+ ...(layout?.computedFormula !== undefined && { computedFormula: layout.computedFormula })
609
+ };
610
+
611
+ return { slug: field.slug, field: mergedField };
612
+ });
613
+ }, [mappedFields, fieldLayout]);
614
+
615
+ const computedFieldStates = useComputedFieldEvaluator(computedFieldEntries, values);
616
+
617
+ const actionFieldEntries = useMemo(() => {
618
+ return mappedFields.map(({ field }) => {
619
+ const layout = fieldLayout?.[field.slug];
620
+
621
+ const mergedField = layout?.fieldActions !== undefined ? { ...field, fieldActions: layout.fieldActions } : field;
622
+
623
+ return { slug: field.slug, field: mergedField };
624
+ });
625
+ }, [mappedFields, fieldLayout]);
626
+
627
+ const fieldLayoutActions = useMemo(() => {
628
+ if (!fieldLayout) return undefined;
629
+ const lookup: Partial<Record<string, FieldAction[]>> = {};
630
+
631
+ for (const [slug, layout] of Object.entries(fieldLayout)) {
632
+ if (layout.fieldActions != null) {
633
+ lookup[slug] = layout.fieldActions;
634
+ }
635
+ }
636
+
637
+ return Object.keys(lookup).length > 0 ? lookup : undefined;
638
+ }, [fieldLayout]);
639
+
640
+ const { setValueExternal: setFormValueExternal, valuesRef: formValuesRef } = localForm;
641
+
642
+ const { triggerFieldChange, propertyOverrides: actionPropertyOverrides, resetPropertyOverrides } = useFieldActionsEvaluator({
643
+ fields: actionFieldEntries,
644
+ fieldLayoutActions,
645
+ onSetValue: setFormValueExternal
646
+ });
647
+
648
+ localForm.fieldActionsRef.current = triggerFieldChange;
649
+
650
+ const {
651
+ triggerFormLoad,
652
+ triggerBeforeSubmit,
653
+ triggerAfterSubmit,
654
+ validateFormLevel,
655
+ propertyOverrides: formActionPropertyOverrides,
656
+ resetPropertyOverrides: resetFormActionOverrides
657
+ } = useFormActionsEvaluator({
658
+ formActions,
659
+ formCustomValidations,
660
+ onSetValue: setFormValueExternal
661
+ });
662
+
663
+ const [formValidationErrors, setFormValidationErrors] = useState<string[]>([]);
664
+
665
+ const formLoadFiredRef = useRef(false);
666
+
667
+ useEffect(() => {
668
+ if (!isReady) return;
669
+ if (formLoadFiredRef.current) return;
670
+
671
+ formLoadFiredRef.current = true;
672
+ triggerFormLoad({ ...formValuesRef.current });
673
+ }, [isReady, triggerFormLoad, formValuesRef]);
674
+
675
+ useEffect(() => {
676
+ for (const [slug, state] of computedFieldStates.entries()) {
677
+ if (!state.hasFormula) continue;
678
+ const current = formValuesRef.current[slug];
679
+
680
+ /*
681
+ * When the formula fails or its inputs are empty, state.value is undefined.
682
+ * Treat undefined as null so the field is cleared reactively (e.g. latitude
683
+ * cleared → formula fails → name cleared). Only skip parse-error guard is
684
+ * handled upstream: the 400ms fieldLayout debounce prevents mid-typing clears.
685
+ * Guard against infinite loops: only write when the serialised value differs.
686
+ * setValueExternal also increments resetSignal so MacroFormField re-reads localValue.
687
+ */
688
+ const nextValue = state.value === undefined ? null : state.value;
689
+
690
+ let changed = true;
691
+
692
+ try {
693
+ changed = JSON.stringify(current) !== JSON.stringify(nextValue);
694
+ } catch {
695
+ /*
696
+ * Circular reference or other non-serializable value — treat as changed
697
+ * so the formula result is always applied rather than silently dropped.
698
+ */
699
+ }
700
+
701
+ if (changed) {
702
+ setFormValueExternal(slug, nextValue);
703
+ }
704
+ }
705
+ }, [computedFieldStates, setFormValueExternal, formValuesRef]);
706
+
707
+ const resolvedFields = useMemo<Array<KivaFormViewField>>(() => {
708
+ const orderLookup = new Map((fieldOrder ?? []).map((slug, index) => [slug, index]));
709
+ const hiddenSlugSet = new Set(hiddenFieldSlugs ?? []);
710
+
711
+ const entries = mappedFields.map(({ sourceField, field }) => {
712
+ const layout = fieldLayout?.[field.slug];
713
+ const computed = computedFieldStates.get(field.slug);
714
+ const fieldActionOverride: FieldActionPropertyOverrides | undefined = actionPropertyOverrides.get(field.slug);
715
+ const formActionOverride: FieldActionPropertyOverrides | undefined = formActionPropertyOverrides.get(field.slug);
716
+ let actionOverride: FieldActionPropertyOverrides | undefined;
717
+
718
+ if (fieldActionOverride !== undefined || formActionOverride !== undefined) {
719
+ actionOverride = { ...(formActionOverride ?? {}), ...(fieldActionOverride ?? {}) };
720
+ }
721
+ const enumOptions = resolveEnumOptions(field);
722
+
723
+ /*
724
+ * Priority (highest → lowest):
725
+ * 1. computed formulas (computedHidden / computedRequired / computedReadonly)
726
+ * 2. action overrides (field-action wins over form-action on conflict)
727
+ * 3. fieldLayout static (layout.hidden / layout.required callbacks)
728
+ * 4. field defaults (IField.readOnly, isFieldRequired)
729
+ */
730
+ const required = computed?.required
731
+ ?? actionOverride?.required
732
+ ?? resolveBooleanOrResolver(layout?.required, values)
733
+ ?? isFieldRequired(field);
734
+ const hidden = computed?.hidden
735
+ ?? actionOverride?.hidden
736
+ ?? (hiddenSlugSet.has(field.slug) ? true : undefined)
737
+ ?? (resolveBooleanOrResolver(layout?.hidden, values) ?? false);
738
+
739
+ const readOnly = mode === 'view'
740
+ || computed?.readOnly === true
741
+ || actionOverride?.readOnly === true
742
+ || layout?.readOnly === true
743
+ || field.readOnly === true
744
+ || isReadOnlyField(field.type);
745
+ const supported = hasKivaFormFieldComponent(field.type);
746
+ const editable = supported && !readOnly;
747
+ const shouldShowValue = readOnly || unsupportedFieldBehavior === 'value';
748
+ const renderMode: KivaFormViewRenderMode = editable ? 'form' : 'value';
749
+ const queryKeys = getFieldQueryKeys(field);
750
+ const submitKeys = getFieldSubmitKeys(field);
751
+
752
+ const label = computed?.label !== undefined ? computed.label : layout?.label;
753
+ const description = computed?.description !== undefined ? computed.description : layout?.description;
754
+
755
+ const mergedFieldForValidation: IField = layout?.customValidations !== undefined || layout?.validations !== undefined ? {
756
+ ...field,
757
+ ...(layout?.customValidations !== undefined && { customValidations: layout.customValidations }),
758
+ ...(layout?.validations !== undefined && { validations: layout.validations })
759
+ } : field;
760
+
761
+ /*
762
+ * Which token list (if any) validation will enforce for this field.
763
+ * `'form'` deliberately ignores schema-only tokens so turning enforcement
764
+ * on cannot start rejecting records over bounds nobody put on the form.
765
+ */
766
+ const enforcedValidations = validationTokens === 'off' ? undefined : (layout?.validations ?? (validationTokens === 'all' ? field.validations : undefined)) ?? undefined;
767
+
768
+ return {
769
+ slug: field.slug,
770
+ sourceField,
771
+ field: mergedFieldForValidation,
772
+ enforcedValidations: enforcedValidations ?? undefined,
773
+ enumOptions,
774
+ value: values[field.slug],
775
+ required,
776
+ hidden,
777
+ readOnly,
778
+ disabled: disabled || actionOverride?.disabled === true || layout?.disabled === true,
779
+ editable,
780
+ renderMode,
781
+ colSpan: layout?.colSpan,
782
+ className: layout?.className,
783
+ label,
784
+ description,
785
+ fieldProps: withUploadHandler(field.type, layout?.fieldProps, uploadFile),
786
+ valueProps: layout?.valueProps,
787
+ queryKeys,
788
+ submitKeys,
789
+ supported,
790
+ shouldShowValue,
791
+ sortOrder: orderLookup.get(field.slug) ?? Number.MAX_SAFE_INTEGER
792
+ };
793
+ });
794
+
795
+ entries.sort((left, right) => {
796
+ if (left.sortOrder !== right.sortOrder) {
797
+ return left.sortOrder - right.sortOrder;
798
+ }
799
+
800
+ return left.field.name.localeCompare(right.field.name);
801
+ });
802
+
803
+ return entries
804
+ .filter((entry) => {
805
+ if (entry.hidden) return false;
806
+ if (entry.editable) return true;
807
+ if (entry.readOnly && includeReadOnlyFields) return true;
808
+
809
+ return entry.shouldShowValue;
810
+ })
811
+ .map(({
812
+ supported: _supported,
813
+ shouldShowValue: _shouldShowValue,
814
+ sortOrder: _sortOrder,
815
+ ...field
816
+ }) => ({
817
+ ...field,
818
+ renderMode: field.editable ? 'form' : 'value' as KivaFormViewRenderMode
819
+ }));
820
+ }, [
821
+ mappedFields,
822
+ fieldOrder,
823
+ hiddenFieldSlugs,
824
+ fieldLayout,
825
+ resolveEnumOptions,
826
+ values,
827
+ computedFieldStates,
828
+ actionPropertyOverrides,
829
+ formActionPropertyOverrides,
830
+ mode,
831
+ disabled,
832
+ includeReadOnlyFields,
833
+ validationTokens,
834
+ unsupportedFieldBehavior,
835
+ uploadFile
836
+ ]);
837
+
838
+ const clickToEditFieldConfigs = useMemo<Array<ClickToEditFieldConfig>>(() => {
839
+ if (!clickToEdit || mode !== 'view') {
840
+ return [];
841
+ }
842
+
843
+ const orderLookup = new Map((fieldOrder ?? []).map((slug, index) => [slug, index]));
844
+ const hiddenSlugSet = new Set(hiddenFieldSlugs ?? []);
845
+
846
+ return mappedFields
847
+ .map(({ field }) => {
848
+ if (hiddenSlugSet.has(field.slug)) {
849
+ return null;
850
+ }
851
+
852
+ const layout = fieldLayout?.[field.slug];
853
+
854
+ if (layout?.hidden === true) {
855
+ return null;
856
+ }
857
+
858
+ const supported = hasKivaFormFieldComponent(field.type);
859
+ const readOnly = layout?.readOnly === true
860
+ || field.readOnly === true
861
+ || isReadOnlyField(field.type)
862
+ || !supported;
863
+ const recordField: RecordDetailField = {
864
+ field,
865
+ enumOptions: resolveEnumOptions(field),
866
+ readOnly,
867
+ required: layout?.required ?? isFieldRequired(field),
868
+ hidden: typeof layout?.hidden === 'function' ? layout.hidden : undefined,
869
+ appSlug,
870
+ dataSourceSlug,
871
+ fieldProps: withUploadHandler(field.type, layout?.fieldProps, uploadFile)
872
+ };
873
+
874
+ const config: SortedClickToEditFieldConfig = {
875
+ recordField,
876
+ readOnly,
877
+ disabled: disabled || layout?.disabled === true,
878
+ submitKeys: getFieldSubmitKeys(field),
879
+ label: layout?.label,
880
+ className: layout?.className,
881
+ sortOrder: orderLookup.get(field.slug) ?? Number.MAX_SAFE_INTEGER
882
+ };
883
+
884
+ return config;
885
+ })
886
+ .filter((entry): entry is SortedClickToEditFieldConfig => entry !== null)
887
+ .sort((left, right) => {
888
+ if (left.sortOrder !== right.sortOrder) {
889
+ return left.sortOrder - right.sortOrder;
890
+ }
891
+
892
+ return left.recordField.field.name.localeCompare(right.recordField.field.name);
893
+ })
894
+ .map(({ sortOrder: _sortOrder, ...entry }) => entry);
895
+ }, [
896
+ appSlug,
897
+ clickToEdit,
898
+ dataSourceSlug,
899
+ disabled,
900
+ fieldLayout,
901
+ fieldOrder,
902
+ hiddenFieldSlugs,
903
+ mappedFields,
904
+ mode,
905
+ resolveEnumOptions,
906
+ uploadFile
907
+ ]);
908
+
909
+ const resolvedFieldMap = useMemo(() => new Map(resolvedFields.map(field => [field.slug, field])), [resolvedFields]);
910
+
911
+ const clickToEditFieldConfigMap = useMemo(() => new Map(clickToEditFieldConfigs.map(config => [config.recordField.field.slug, config])), [clickToEditFieldConfigs]);
912
+
913
+ const resolvedLayoutItems = useMemo<Array<KivaFormViewLayoutItem>>(() => {
914
+ if (!layout?.length) {
915
+ return [];
916
+ }
917
+
918
+ const visibleFieldSlugs = new Set(resolvedFields.map(field => field.slug));
919
+ const normalizedItems = normalizeKivaFormViewLayoutItems(layout, visibleFieldSlugs);
920
+ const assignedFieldSlugs = new Set(collectKivaFormViewLayoutFieldSlugs(normalizedItems));
921
+ const unassignedFields = resolvedFields
922
+ .map(field => field.slug)
923
+ .filter(slug => !assignedFieldSlugs.has(slug));
924
+
925
+ return [...normalizedItems, ...unassignedFields];
926
+ }, [layout, resolvedFields]);
927
+
928
+ const unsupportedFields = useMemo(() => resolvedFields.filter(field => !field.editable && field.renderMode === 'value' && !hasKivaFormFieldComponent(field.field.type)), [resolvedFields]);
929
+
930
+ /*
931
+ * Fields the engine COMPUTES are excluded from the dirty check: their value is
932
+ * produced by the evaluator, not entered by the user, so a total that
933
+ * recomputes on load would otherwise mark an untouched form dirty and arm the
934
+ * unsaved-changes guard.
935
+ */
936
+ const computedValueSlugs = useMemo(() => {
937
+ const slugs = new Set<string>();
938
+
939
+ for (const [slug, state] of computedFieldStates) {
940
+ if (state.hasFormula) slugs.add(slug);
941
+ }
942
+
943
+ return slugs;
944
+ }, [computedFieldStates]);
945
+
946
+ const isDirty = useMemo(() => {
947
+ if (computedValueSlugs.size === 0) {
948
+ return !valuesMatch(values, localForm.baselineRef.current);
949
+ }
950
+
951
+ const omitComputed = (source: Record<string, unknown>): Record<string, unknown> => {
952
+ const out: Record<string, unknown> = {};
953
+
954
+ for (const slug of Object.keys(source)) {
955
+ if (!computedValueSlugs.has(slug)) out[slug] = source[slug];
956
+ }
957
+
958
+ return out;
959
+ };
960
+
961
+ return !valuesMatch(omitComputed(values), omitComputed(localForm.baselineRef.current));
962
+ }, [localForm.baselineRef, values, computedValueSlugs]);
963
+
964
+ const validate = useCallback(async () => {
965
+ if (mode === 'view') {
966
+ localForm.setValidationErrors(new Map());
967
+
968
+ return true;
969
+ }
970
+
971
+ const errors = new Map<string, string>();
972
+
973
+ for (const field of resolvedFields) {
974
+ if (field.renderMode !== 'form') continue;
975
+ if (field.readOnly || field.disabled) continue;
976
+
977
+ const fieldValue = localForm.valuesRef.current[field.slug];
978
+
979
+ if (field.required && isEmptyValue(fieldValue)) {
980
+ errors.set(field.slug, `${field.field.name} is required`);
981
+ continue;
982
+ }
983
+
984
+ /*
985
+ * Declarative token constraints (`minLength:` / `maxLength:` / `pattern:`
986
+ * / `min:` / `max:`), opt-in per surface via `validationTokens`.
987
+ * `required` is handled above from the resolved `field.required`, which
988
+ * folds in computed / action overrides, so the token pass skips it.
989
+ */
990
+ if (field.enforcedValidations) {
991
+ const tokenError = validateValidationTokens(fieldValue, field.enforcedValidations, {
992
+ label: field.field.name,
993
+ numeric: NUMERIC_VALIDATION_TYPES.has(field.field.type),
994
+ skipRequired: true
995
+ });
996
+
997
+ if (tokenError) {
998
+ errors.set(field.slug, tokenError);
999
+ continue;
1000
+ }
1001
+ }
1002
+
1003
+ for (const rule of field.field.customValidations ?? []) {
1004
+ if (!rule.expression) continue;
1005
+
1006
+ const normalizedValue = normalizeValueForValidation(field.field, fieldValue);
1007
+ const context = { value: normalizedValue, values: localForm.valuesRef.current };
1008
+
1009
+ try {
1010
+ const result = await evaluateJsonata(rule.expression, context);
1011
+
1012
+ if (result.status === 'success' && result.result !== true) {
1013
+ errors.set(field.slug, rule.message || 'Validation failed');
1014
+ break;
1015
+ }
1016
+ } catch {
1017
+ }
1018
+ }
1019
+ }
1020
+
1021
+ localForm.setValidationErrors(errors);
1022
+
1023
+ if (errors.size > 0) {
1024
+ return false;
1025
+ }
1026
+
1027
+ const formErrors = await validateFormLevel({ ...localForm.valuesRef.current });
1028
+
1029
+ setFormValidationErrors(formErrors);
1030
+
1031
+ return formErrors.length === 0;
1032
+ }, [
1033
+ localForm,
1034
+ mode,
1035
+ resolvedFields,
1036
+ validateFormLevel
1037
+ ]);
1038
+
1039
+ const submitContext = useMemo<KivaFormViewSubmitContext>(() => ({
1040
+ mode,
1041
+ itemId,
1042
+ values,
1043
+ fields: resolvedFields,
1044
+ dataSource
1045
+ }), [
1046
+ mode,
1047
+ itemId,
1048
+ values,
1049
+ resolvedFields,
1050
+ dataSource
1051
+ ]);
1052
+
1053
+ const [isSubmitting, setIsSubmitting] = useState(false);
1054
+
1055
+ const executeSubmit = useCallback(async ({
1056
+ valuesSnapshot,
1057
+ payloadFields,
1058
+ context,
1059
+ forceUpdate = false
1060
+ }: {
1061
+ valuesSnapshot: Record<string, unknown>;
1062
+ payloadFields: Array<Pick<KivaFormViewField, 'readOnly' | 'disabled' | 'submitKeys'>>;
1063
+ context: KivaFormViewSubmitContext;
1064
+ forceUpdate?: boolean;
1065
+ }) => {
1066
+ const basePayload = buildSubmitPayload(payloadFields, valuesSnapshot);
1067
+ const payload = transformSubmit ? transformSubmit(basePayload, context) : basePayload;
1068
+
1069
+ setIsSubmitting(true);
1070
+
1071
+ try {
1072
+ const result = await onSubmit(payload, context, forceUpdate);
1073
+
1074
+ if (forceUpdate) {
1075
+ localForm.replaceValues(valuesSnapshot, true);
1076
+ } else {
1077
+ localForm.commit(valuesSnapshot);
1078
+ }
1079
+ onSubmitSuccess?.(result, payload);
1080
+ triggerAfterSubmit(result, valuesSnapshot);
1081
+
1082
+ if ((context.mode === 'edit' || forceUpdate) && context.itemId) {
1083
+ refetchItem?.();
1084
+ }
1085
+
1086
+ return result;
1087
+ } catch (error) {
1088
+ onSubmitError?.(error, payload);
1089
+ throw error;
1090
+ } finally {
1091
+ setIsSubmitting(false);
1092
+ }
1093
+ }, [
1094
+ localForm,
1095
+ onSubmit,
1096
+ onSubmitError,
1097
+ onSubmitSuccess,
1098
+ refetchItem,
1099
+ transformSubmit,
1100
+ triggerAfterSubmit
1101
+ ]);
1102
+
1103
+ const submit = useCallback(async () => {
1104
+ if (mode === 'view') {
1105
+ return { ...localForm.valuesRef.current };
1106
+ }
1107
+
1108
+ if (!await validate()) {
1109
+ const error = new Error('Form validation failed');
1110
+
1111
+ onSubmitError?.(error, {});
1112
+ throw error;
1113
+ }
1114
+
1115
+ await triggerBeforeSubmit({ ...localForm.valuesRef.current });
1116
+
1117
+ return executeSubmit({
1118
+ valuesSnapshot: { ...localForm.valuesRef.current },
1119
+ payloadFields: resolvedFields,
1120
+ context: submitContext
1121
+ });
1122
+ }, [
1123
+ executeSubmit,
1124
+ localForm,
1125
+ mode,
1126
+ onSubmitError,
1127
+ resolvedFields,
1128
+ submitContext,
1129
+ triggerBeforeSubmit,
1130
+ validate
1131
+ ]);
1132
+
1133
+ const handleClickToEditSave = useCallback(async (
1134
+ changes: Array<FieldChange>,
1135
+ nextValues: Record<string, unknown>
1136
+ ) => {
1137
+ if (changes.length === 0) {
1138
+ return;
1139
+ }
1140
+
1141
+ const clickToEditContext: KivaFormViewSubmitContext = {
1142
+ mode,
1143
+ itemId,
1144
+ values: nextValues,
1145
+ fields: resolvedFields,
1146
+ dataSource
1147
+ };
1148
+
1149
+ await executeSubmit({
1150
+ valuesSnapshot: nextValues,
1151
+ payloadFields: clickToEditFieldConfigs,
1152
+ context: clickToEditContext,
1153
+ forceUpdate: true
1154
+ });
1155
+ }, [
1156
+ clickToEditFieldConfigs,
1157
+ dataSource,
1158
+ executeSubmit,
1159
+ itemId,
1160
+ mode,
1161
+ resolvedFields
1162
+ ]);
1163
+
1164
+ const renderField = useCallback((slug: string, renderOptions?: KivaFormViewRenderFieldOptions) => {
1165
+ const resolved = resolvedFieldMap.get(slug);
1166
+
1167
+ if (!resolved) return null;
1168
+
1169
+ const renderMode: KivaFormViewRenderMode = (renderOptions?.mode ?? mode) === 'view' ? 'value' : resolved.renderMode;
1170
+
1171
+ if (renderMode === 'form') {
1172
+ return (
1173
+ <KivaFormViewMappedFormField
1174
+ resolvedField={resolved}
1175
+ form={localForm.form}
1176
+ appSlug={appSlug}
1177
+ dataSourceSlug={dataSourceSlug}
1178
+ client={client}
1179
+ className={renderOptions?.className} />
1180
+ );
1181
+ }
1182
+
1183
+ return (
1184
+ <KivaFormViewMappedValueField
1185
+ resolvedField={resolved}
1186
+ values={localForm.valuesRef.current}
1187
+ wrapperClassName={renderOptions?.wrapperClassName}
1188
+ className={renderOptions?.className}
1189
+ label={renderOptions?.label}
1190
+ description={renderOptions?.description}
1191
+ client={client} />
1192
+ );
1193
+ }, [
1194
+ appSlug,
1195
+ client,
1196
+ dataSourceSlug,
1197
+ localForm.form,
1198
+ localForm.valuesRef,
1199
+ mode,
1200
+ resolvedFieldMap
1201
+ ]);
1202
+
1203
+ const renderLayout = useCallback((renderOptions?: KivaFormViewRenderLayoutOptions) => {
1204
+ const columnCount = renderOptions?.columns ?? gridColumns;
1205
+ const layoutMode = renderOptions?.mode ?? mode;
1206
+ const shouldUseClickToEdit = clickToEdit && layoutMode === 'view' && clickToEditFieldConfigs.length > 0;
1207
+ const rootItems = resolvedLayoutItems.length > 0 ? resolvedLayoutItems : resolvedFields.map(field => field.slug);
1208
+
1209
+ /*
1210
+ * Key every item by its own IDENTITY (field slug / section id), never by
1211
+ * its POSITION. `normalizeKivaFormViewLayoutItems` DROPS a field the
1212
+ * computed rules hid, so each later sibling shifts one index down; under a
1213
+ * positional key React then matches a surviving key to a DIFFERENT slug
1214
+ * and — when both render the same element shape — keeps the mounted
1215
+ * `MacroFormField` instead of remounting it. That instance seeds its
1216
+ * `localValue` once on mount, so the hidden field's value renders under
1217
+ * the next field's label and editing it writes to the next field's slug.
1218
+ *
1219
+ * Ids are deduped within a sibling list so a layout that repeats one still
1220
+ * produces distinct React keys instead of silently colliding.
1221
+ */
1222
+ function renderLayoutItems(items: Array<KivaFormViewLayoutItem>, path: string): Array<ReactNode> {
1223
+ const usedKeys = new Set<string>();
1224
+ const uniqueKey = (base: string, index: number): string => {
1225
+ const key = usedKeys.has(base) ? `${base}-dup${index}` : base;
1226
+
1227
+ usedKeys.add(key);
1228
+
1229
+ return key;
1230
+ };
1231
+
1232
+ return items.map((item, index) => {
1233
+ if (typeof item === 'string') {
1234
+ return renderFieldGridItem(item, undefined, uniqueKey(`${path}-f-${item}`, index));
1235
+ }
1236
+
1237
+ if (isKivaFormViewLayoutFieldItem(item)) {
1238
+ return renderFieldGridItem(item.slug, item, uniqueKey(`${path}-f-${item.slug}`, index));
1239
+ }
1240
+
1241
+ return renderSection(item, uniqueKey(`${path}-s-${item.id}`, index));
1242
+ });
1243
+ }
1244
+
1245
+ function renderFieldGridItem(
1246
+ slug: string,
1247
+ layoutItem: KivaFormViewLayoutFieldItem | undefined,
1248
+ key: string
1249
+ ): ReactNode {
1250
+ const resolved = resolvedFieldMap.get(slug);
1251
+
1252
+ if (!resolved) {
1253
+ return null;
1254
+ }
1255
+
1256
+ const fieldNode = shouldUseClickToEdit ? (() => {
1257
+ const config = clickToEditFieldConfigMap.get(slug);
1258
+
1259
+ if (!config) {
1260
+ return null;
1261
+ }
1262
+
1263
+ return (
1264
+ <EditableRecordDetailField
1265
+ slug={slug}
1266
+ label={config.label}
1267
+ className={cn(config.className, renderOptions?.fieldClassName)} />
1268
+ );
1269
+ })() : renderField(slug, {
1270
+ mode: layoutMode,
1271
+ wrapperClassName: renderOptions?.fieldClassName
1272
+ });
1273
+
1274
+ if (!fieldNode) {
1275
+ return null;
1276
+ }
1277
+
1278
+ /*
1279
+ * `labelAlign: 'top'` undoes the label-LEFT rules `getFormLayoutClassName`
1280
+ * scopes to the whole grid, for this field only. It re-states every
1281
+ * property that helper sets (direction, alignment, gap, label width and
1282
+ * the label's top nudge), and every one of them is `!important`.
1283
+ *
1284
+ * Both rules compile to `.<hash> [data-slot=field] { … }` — identical
1285
+ * specificity, applied to DIFFERENT elements, so the winner is whichever
1286
+ * Tailwind emits LAST, not the nearer ancestor. tailwind-merge cannot help
1287
+ * either: it only dedupes within a single class string. Without the bang
1288
+ * this override is silently inert.
1289
+ */
1290
+ const labelAlignClassName = layoutItem?.labelAlign === 'top' ? '[&_[data-slot=field]]:flex-col! [&_[data-slot=field]]:items-stretch! [&_[data-slot=field]]:gap-2! [&_[data-slot=field-label]]:w-auto! [&_[data-slot=field-label]]:pt-0!' : undefined;
1291
+
1292
+ return (
1293
+ <div
1294
+ key={key}
1295
+ className={cn(renderOptions?.wrapperClassName, labelAlignClassName, layoutItem?.className)}
1296
+ style={getGridSpanStyle(layoutItem?.colSpan ?? resolved.colSpan)}>
1297
+ {fieldNode}
1298
+ </div>
1299
+ );
1300
+ }
1301
+
1302
+ function renderSectionHeader(title?: ReactNode, description?: ReactNode): ReactNode {
1303
+ if (!title && !description) {
1304
+ return null;
1305
+ }
1306
+
1307
+ return (
1308
+ <div className="space-y-1">
1309
+ {title && <div className="text-sm font-semibold text-foreground">{title}</div>}
1310
+ {description && <FieldDescription className="m-0">{description}</FieldDescription>}
1311
+ </div>
1312
+ );
1313
+ }
1314
+
1315
+ function renderSectionGrid(
1316
+ items: Array<KivaFormViewLayoutItem>,
1317
+ path: string,
1318
+ className?: string,
1319
+ columns?: 1 | 2 | 3 | 4
1320
+ ): ReactNode {
1321
+ return (
1322
+ <div className={cn(getGridColumnsClassName(columns ?? columnCount), formLayoutClassName, className)}>
1323
+ {renderLayoutItems(items, path)}
1324
+ </div>
1325
+ );
1326
+ }
1327
+
1328
+ function renderSection(section: KivaFormViewSection, key: string): ReactNode {
1329
+ if (section.variant === 'fieldset') {
1330
+ const body = (
1331
+ <>
1332
+ {section.description && <FieldDescription>{section.description}</FieldDescription>}
1333
+ {renderSectionGrid(section.items, `${key}-fieldset`, section.contentClassName, section.columns)}
1334
+ </>
1335
+ );
1336
+
1337
+ return (
1338
+ <div
1339
+ key={key}
1340
+ className={cn(renderOptions?.wrapperClassName)}
1341
+ style={getGridSpanStyle(section.colSpan)}>
1342
+ <FieldSet className={cn('rounded-xl border border-border/60 p-4 md:p-5', section.className)}>
1343
+ {section.collapsible ? (
1344
+ <Collapsible defaultOpen={!section.defaultCollapsed} className="group/fieldset space-y-4">
1345
+ <CollapsibleTrigger className="flex w-full items-center justify-between gap-2 text-left">
1346
+ <FieldLegend>{section.title}</FieldLegend>
1347
+ <ChevronDown className="size-4 shrink-0 text-muted-foreground transition-transform group-data-[state=open]/fieldset:rotate-180" />
1348
+ </CollapsibleTrigger>
1349
+ <CollapsibleContent className="space-y-4">
1350
+ {body}
1351
+ </CollapsibleContent>
1352
+ </Collapsible>
1353
+ ) : (
1354
+ <>
1355
+ {section.title && <FieldLegend>{section.title}</FieldLegend>}
1356
+ {body}
1357
+ </>
1358
+ )}
1359
+ </FieldSet>
1360
+ </div>
1361
+ );
1362
+ }
1363
+
1364
+ if (section.variant === 'tabpanel') {
1365
+ const tabs = section.items.filter(tab => tab.variant === 'tab');
1366
+
1367
+ if (tabs.length === 0) {
1368
+ return null;
1369
+ }
1370
+
1371
+ const defaultTab = tabs.find(tab => tab.id === section.defaultTabId) ?? tabs[0];
1372
+
1373
+ if (!defaultTab) {
1374
+ return null;
1375
+ }
1376
+
1377
+ const defaultTabValue = getKivaFormViewTabValue(defaultTab);
1378
+ const tabValues = tabs.map(tab => getKivaFormViewTabValue(tab));
1379
+
1380
+ return (
1381
+ <div
1382
+ key={key}
1383
+ className={cn(renderOptions?.wrapperClassName)}
1384
+ style={getGridSpanStyle(section.colSpan)}>
1385
+ <div className={cn('space-y-4 rounded-xl border border-border/60 p-4 md:p-5', section.className)}>
1386
+ {renderSectionHeader(section.title, section.description)}
1387
+ <ControlledFormViewTabs
1388
+ tabValues={tabValues}
1389
+ defaultTabValue={defaultTabValue}
1390
+ className="gap-4">
1391
+ <TabsList variant="line" className="h-auto w-full justify-start overflow-x-auto rounded-none p-0">
1392
+ {tabs.map((tab) => {
1393
+ const tabValue = getKivaFormViewTabValue(tab);
1394
+
1395
+ return (
1396
+ <TabsTrigger key={tabValue} value={tabValue} className="flex-none px-3 py-2">
1397
+ {tab.title ?? tab.id}
1398
+ </TabsTrigger>
1399
+ );
1400
+ })}
1401
+ </TabsList>
1402
+ {tabs.map((tab) => {
1403
+ const tabValue = getKivaFormViewTabValue(tab);
1404
+
1405
+ return (
1406
+ <TabsContent key={tabValue} value={tabValue} className={cn('space-y-4', tab.className)}>
1407
+ {renderSectionHeader(undefined, tab.description)}
1408
+ {renderSectionGrid(tab.items, `${key}-${tabValue}`, tab.contentClassName)}
1409
+ </TabsContent>
1410
+ );
1411
+ })}
1412
+ </ControlledFormViewTabs>
1413
+ </div>
1414
+ </div>
1415
+ );
1416
+ }
1417
+
1418
+ return (
1419
+ <div
1420
+ key={key}
1421
+ className={cn(renderOptions?.wrapperClassName)}
1422
+ style={getGridSpanStyle(section.colSpan)}>
1423
+ <div className={cn('space-y-4 rounded-xl border border-border/60 p-4 md:p-5', section.className)}>
1424
+ {renderSectionHeader(section.title, section.description)}
1425
+ {renderSectionGrid(section.items, `${key}-tab`, section.contentClassName)}
1426
+ </div>
1427
+ </div>
1428
+ );
1429
+ }
1430
+
1431
+ let structuredLayout: ReactNode = null;
1432
+
1433
+ if (resolvedLayoutItems.length > 0) {
1434
+ structuredLayout = renderSectionGrid(
1435
+ rootItems,
1436
+ 'layout-root',
1437
+ shouldUseClickToEdit ? undefined : renderOptions?.className
1438
+ );
1439
+ }
1440
+
1441
+ if (shouldUseClickToEdit) {
1442
+ return (
1443
+ <EditableRecordDetail
1444
+ fields={clickToEditFieldConfigs.map(config => config.recordField)}
1445
+ record={values}
1446
+ onSave={handleClickToEditSave}
1447
+ disabled={disabled}
1448
+ client={client}
1449
+ className={cn(renderOptions?.className, renderOptions?.wrapperClassName)}>
1450
+ {structuredLayout ?? clickToEditFieldConfigs.map(config => (
1451
+ <EditableRecordDetailField
1452
+ key={config.recordField.field.slug}
1453
+ slug={config.recordField.field.slug}
1454
+ label={config.label}
1455
+ className={cn(config.className, renderOptions?.fieldClassName)} />
1456
+ ))}
1457
+ </EditableRecordDetail>
1458
+ );
1459
+ }
1460
+
1461
+ if (structuredLayout) {
1462
+ return structuredLayout;
1463
+ }
1464
+
1465
+ return (
1466
+ <div className={cn(getGridColumnsClassName(columnCount), formLayoutClassName, renderOptions?.className)}>
1467
+ {resolvedFields.map(field => (
1468
+ <div
1469
+ key={field.slug}
1470
+ className={cn(renderOptions?.wrapperClassName)}
1471
+ style={getGridSpanStyle(field.colSpan)}>
1472
+ {renderField(field.slug, {
1473
+ mode: layoutMode,
1474
+ wrapperClassName: renderOptions?.fieldClassName
1475
+ })}
1476
+ </div>
1477
+ ))}
1478
+ </div>
1479
+ );
1480
+ }, [
1481
+ clickToEdit,
1482
+ clickToEditFieldConfigMap,
1483
+ clickToEditFieldConfigs,
1484
+ client,
1485
+ disabled,
1486
+ formLayoutClassName,
1487
+ gridColumns,
1488
+ handleClickToEditSave,
1489
+ mode,
1490
+ renderField,
1491
+ resolvedFieldMap,
1492
+ resolvedFields,
1493
+ resolvedLayoutItems,
1494
+ values
1495
+ ]);
1496
+
1497
+ const resetActionOverrides = useCallback(() => {
1498
+ resetPropertyOverrides();
1499
+ resetFormActionOverrides();
1500
+ }, [resetPropertyOverrides, resetFormActionOverrides]);
1501
+
1502
+ return {
1503
+ mode,
1504
+ item: values,
1505
+ form: localForm.form,
1506
+ values,
1507
+ defaultValues: initialValues,
1508
+ fields: resolvedFields,
1509
+ allFields: resolvedFields,
1510
+ unsupportedFields,
1511
+ validationErrors: localForm.validationErrors,
1512
+ formValidationErrors,
1513
+ isDirty,
1514
+ isSubmitting,
1515
+ setValue: localForm.setValue,
1516
+ validate,
1517
+ reset: localForm.reset,
1518
+ submit,
1519
+ resetActionOverrides,
1520
+ renderField,
1521
+ renderLayout
1522
+ };
1523
+ }
1524
+
1525
+ /*
1526
+ * ---------------------------------------------------------------------------
1527
+ * Backend-agnostic pure helpers shared by both adapters.
1528
+ * ---------------------------------------------------------------------------
1529
+ */
1530
+
1531
+ /**
1532
+ * Inject a file/image upload handler into image / avatar / file fields so they
1533
+ * persist a real stored value instead of a raw `File` (which serializes to
1534
+ * `{}`) or a browser-local `blob:` URL. A consumer-supplied handler in
1535
+ * `fieldProps` wins — it is spread last. When no `uploadFile` is supplied, the
1536
+ * field props pass through unchanged.
1537
+ */
1538
+ function withUploadHandler(
1539
+ type: IFieldType,
1540
+ base: Partial<KivaFormFieldProps> | undefined,
1541
+ uploadFile: ((type: IFieldType, file: File) => Promise<StoredFileValue | null>) | undefined
1542
+ ): Partial<KivaFormFieldProps> | undefined {
1543
+ if (!uploadFile) {
1544
+ return base;
1545
+ }
1546
+
1547
+ if (type === 'field-image') {
1548
+ return { onImageUpload: (file: File) => uploadFile('field-image', file), ...base };
1549
+ }
1550
+
1551
+ /*
1552
+ * `field-avatar` is an image field too — `AvatarField` forwards this to
1553
+ * `AvatarSelect.uploadImage`. Without it the cropped avatar stays a
1554
+ * browser-local `blob:` URL and is silently lost on save.
1555
+ */
1556
+ if (type === 'field-avatar') {
1557
+ return { onImageUpload: (file: File) => uploadFile('field-avatar', file), ...base };
1558
+ }
1559
+
1560
+ if (type === 'field-file') {
1561
+ return { onFileUpload: (file: File) => uploadFile('field-file', file), ...base };
1562
+ }
1563
+
1564
+ return base;
1565
+ }
1566
+
1567
+ export function getFieldQueryKeys(field: IField): Array<string> {
1568
+ const keys = new Set<string>();
1569
+
1570
+ if (field.slug) keys.add(field.slug);
1571
+
1572
+ switch (field.type) {
1573
+ case 'field-money':
1574
+ keys.add(getCompanionFieldSlug(field.slug, 'currency'));
1575
+ break;
1576
+
1577
+ case 'field-phone':
1578
+ keys.add(getCompanionFieldSlug(field.slug, 'country'));
1579
+ break;
1580
+
1581
+ case 'field-status':
1582
+ keys.add(getCompanionFieldSlug(field.slug, 'secondary'));
1583
+ keys.add(getCompanionFieldSlug(field.slug, 'description'));
1584
+ keys.add(getCompanionFieldSlug(field.slug, 'followup_date'));
1585
+ break;
1586
+
1587
+ /*
1588
+ * field-htmlEditor / field-emailEditor intentionally request NO
1589
+ * `__<slug>_html` companion column. Both editors read and write only the
1590
+ * main slug (htmlEditor stores the HTML string, emailEditor the Unlayer
1591
+ * design JSON). The `_html` companion is an optional, read-only display
1592
+ * convenience consumed solely by RichTextValue, which already falls back
1593
+ * to the main value when it is absent. The backend does not materialize
1594
+ * this column for every html/email field, and a single missing column
1595
+ * makes the entire record GET fail with HTTP 500 — so we never ask for it.
1596
+ * Keep this in sync with getFieldSubmitKeys (which also omits `_html`).
1597
+ */
1598
+
1599
+ case 'field-avatar': {
1600
+ if (field.avatarMapping?.iconField) keys.add(field.avatarMapping.iconField);
1601
+ if (field.avatarMapping?.colorField) keys.add(field.avatarMapping.colorField);
1602
+ if (field.avatarMapping?.imageField) keys.add(field.avatarMapping.imageField);
1603
+ break;
1604
+ }
1605
+
1606
+ default:
1607
+ break;
1608
+ }
1609
+
1610
+ return Array.from(keys);
1611
+ }
1612
+
1613
+ function getFieldSubmitKeys(field: IField): Array<string> {
1614
+ switch (field.type) {
1615
+ case 'field-money':
1616
+ return uniqueStrings([field.slug, getCompanionFieldSlug(field.slug, 'currency')]);
1617
+
1618
+ case 'field-phone':
1619
+ return uniqueStrings([field.slug, getCompanionFieldSlug(field.slug, 'country')]);
1620
+
1621
+ case 'field-status':
1622
+ return uniqueStrings([
1623
+ field.slug,
1624
+ getCompanionFieldSlug(field.slug, 'secondary'),
1625
+ getCompanionFieldSlug(field.slug, 'description'),
1626
+ getCompanionFieldSlug(field.slug, 'followup_date')
1627
+ ]);
1628
+
1629
+ case 'field-avatar':
1630
+ return uniqueStrings([field.avatarMapping?.iconField, field.avatarMapping?.colorField, field.avatarMapping?.imageField]);
1631
+
1632
+ default:
1633
+ return field.slug ? [field.slug] : [];
1634
+ }
1635
+ }
1636
+
1637
+ /** Option-backed fields whose value is a single option id. */
1638
+ const SINGLE_OPTION_FIELD_TYPES = new Set(['field-select', 'field-enum', 'field-status']);
1639
+
1640
+ /** Option-backed fields whose value is a list of option ids. */
1641
+ const MULTI_OPTION_FIELD_TYPES = new Set(['field-multiSelect', 'field-tagSelect']);
1642
+
1643
+ export function buildInitialValues(
1644
+ fields: Array<IField>,
1645
+ item: Record<string, unknown>,
1646
+ providedDefaults?: Record<string, unknown>
1647
+ ): Record<string, unknown> {
1648
+ const values: Record<string, unknown> = {};
1649
+
1650
+ for (const field of fields) {
1651
+ const defaultValue = parseFieldDefaultValue(field.defaultValue, field.type);
1652
+
1653
+ if (field.slug && !(field.slug in values)) {
1654
+ values[field.slug] = defaultValue;
1655
+ }
1656
+
1657
+ if (field.type === 'field-money') {
1658
+ const currencySlug = getCompanionFieldSlug(field.slug, 'currency');
1659
+
1660
+ if (!(currencySlug in values)) values[currencySlug] = 'USD';
1661
+ }
1662
+
1663
+ if (field.type === 'field-phone') {
1664
+ const countrySlug = getCompanionFieldSlug(field.slug, 'country');
1665
+
1666
+ if (!(countrySlug in values)) values[countrySlug] = '';
1667
+ }
1668
+
1669
+ if (field.type === 'field-status') {
1670
+ const secondarySlug = getCompanionFieldSlug(field.slug, 'secondary');
1671
+ const descriptionSlug = getCompanionFieldSlug(field.slug, 'description');
1672
+ const followupDateSlug = getCompanionFieldSlug(field.slug, 'followup_date');
1673
+
1674
+ if (!(secondarySlug in values)) values[secondarySlug] = '';
1675
+ if (!(descriptionSlug in values)) values[descriptionSlug] = '';
1676
+ if (!(followupDateSlug in values)) values[followupDateSlug] = null;
1677
+ }
1678
+
1679
+ if (field.type === 'field-avatar') {
1680
+ if (field.avatarMapping?.iconField && !(field.avatarMapping.iconField in values)) {
1681
+ values[field.avatarMapping.iconField] = null;
1682
+ }
1683
+ if (field.avatarMapping?.colorField && !(field.avatarMapping.colorField in values)) {
1684
+ values[field.avatarMapping.colorField] = null;
1685
+ }
1686
+ if (field.avatarMapping?.imageField && !(field.avatarMapping.imageField in values)) {
1687
+ values[field.avatarMapping.imageField] = null;
1688
+ }
1689
+ }
1690
+ }
1691
+
1692
+ Object.assign(values, providedDefaults ?? {});
1693
+ Object.assign(values, item ?? {});
1694
+
1695
+ /*
1696
+ * User-like and relation fields come back as either a UUID string or an
1697
+ * object shape `{ id: UUID, ... }`. Form fields and value renderers
1698
+ * downstream expect a plain string id (the look-up is done against the loaded
1699
+ * options list, and it is the id — not the object — that must be submitted).
1700
+ * Normalize the object shape here once.
1701
+ */
1702
+ for (const field of fields) {
1703
+ if (field.type === 'field-userSelect') {
1704
+ const raw = values[field.slug];
1705
+
1706
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
1707
+ const id = pickString(toRecord(raw), 'id', 'userId', 'user_id');
1708
+
1709
+ if (id) values[field.slug] = id;
1710
+ }
1711
+ } else if (field.type === 'field-userMultiSelect') {
1712
+ const raw = values[field.slug];
1713
+
1714
+ if (Array.isArray(raw)) {
1715
+ values[field.slug] = raw
1716
+ .map((entry) => {
1717
+ if (typeof entry === 'string') return entry;
1718
+ if (entry && typeof entry === 'object') return pickString(toRecord(entry), 'id', 'userId', 'user_id');
1719
+
1720
+ return null;
1721
+ })
1722
+ .filter((id): id is string => Boolean(id));
1723
+ }
1724
+ } else if (field.type === 'field-relation') {
1725
+ const raw = values[field.slug];
1726
+
1727
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
1728
+ const id = pickString(toRecord(raw), 'id');
1729
+
1730
+ if (id) values[field.slug] = id;
1731
+ }
1732
+ } else if (SINGLE_OPTION_FIELD_TYPES.has(field.type)) {
1733
+ /*
1734
+ * Option-backed fields come back expanded when the record is read with
1735
+ * `expand=enums` — an `{ id, name, color }` object rather than the id the
1736
+ * option list is matched against. Left as an object the control finds no
1737
+ * match and opens blank, quietly dropping a value the record has.
1738
+ */
1739
+ const raw = values[field.slug];
1740
+
1741
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
1742
+ const id = pickString(toRecord(raw), 'id');
1743
+
1744
+ if (id) values[field.slug] = id;
1745
+ }
1746
+ } else if (MULTI_OPTION_FIELD_TYPES.has(field.type)) {
1747
+ const raw = values[field.slug];
1748
+
1749
+ if (Array.isArray(raw)) {
1750
+ values[field.slug] = raw
1751
+ .map((entry) => {
1752
+ if (typeof entry === 'string') return entry;
1753
+ if (entry && typeof entry === 'object') return pickString(toRecord(entry), 'id');
1754
+
1755
+ return null;
1756
+ })
1757
+ .filter((id): id is string => Boolean(id));
1758
+ }
1759
+ }
1760
+ }
1761
+
1762
+ for (const field of fields) {
1763
+ if (field.type === 'field-phone') {
1764
+ const countrySlug = getCompanionFieldSlug(field.slug, 'country');
1765
+ const legacyCountryCodeSlug = getCompanionFieldSlug(field.slug, 'country_code');
1766
+
1767
+ if (!values[countrySlug] && values[legacyCountryCodeSlug]) {
1768
+ values[countrySlug] = values[legacyCountryCodeSlug];
1769
+ }
1770
+ }
1771
+ }
1772
+
1773
+ return values;
1774
+ }
1775
+
1776
+ function parseFieldDefaultValue(value: string | null | undefined, type: IFieldType): unknown {
1777
+ if (value == null || value === '') {
1778
+ if (type === 'field-checkbox' || type === 'field-switch') return false;
1779
+ if (type === 'field-multiSelect' || type === 'field-tagSelect' || type === 'field-userMultiSelect') return [];
1780
+
1781
+ return null;
1782
+ }
1783
+
1784
+ switch (type) {
1785
+ case 'field-checkbox':
1786
+
1787
+ case 'field-switch':
1788
+ return value === 'true' || value === '1';
1789
+
1790
+ case 'field-number':
1791
+
1792
+ case 'field-money':
1793
+
1794
+ case 'field-percent':
1795
+
1796
+ case 'field-duration':
1797
+
1798
+ case 'field-rating':
1799
+
1800
+ case 'field-autonumber':
1801
+
1802
+ case 'field-identity': {
1803
+ const parsed = Number(value);
1804
+
1805
+ return Number.isFinite(parsed) ? parsed : null;
1806
+ }
1807
+
1808
+ case 'field-multiSelect':
1809
+
1810
+ case 'field-tagSelect':
1811
+
1812
+ case 'field-userMultiSelect':
1813
+
1814
+ case 'field-taskList':
1815
+
1816
+ case 'field-schemaRepeater':
1817
+
1818
+ case 'field-queryBuilder':
1819
+
1820
+ case 'field-locationSelect':
1821
+
1822
+ case 'field-approvalStatus':
1823
+
1824
+ case 'field-docEditor':
1825
+
1826
+ case 'field-json':
1827
+
1828
+ case 'field-image':
1829
+
1830
+ case 'field-file':
1831
+ return parseJsonValue(value);
1832
+
1833
+ default:
1834
+ return value;
1835
+ }
1836
+ }
1837
+
1838
+ /**
1839
+ * Read a field's inline enum options (`enums` / `options` /
1840
+ * `options.editorOptions.options`) into a normalized `EnumOption[]`. This is
1841
+ * the backend-free option source used by `useDynamicFormView` and the fallback
1842
+ * for `useKivaFormView`'s enum-backed fields.
1843
+ */
1844
+ export function extractStaticEnumOptions(field: IField): Array<EnumOption> {
1845
+ const raw = toRecord(field as unknown);
1846
+ const optionsObject = toRecord(field.options);
1847
+ const editorOptions = toRecord(optionsObject?.editorOptions);
1848
+ const source = ((): Array<unknown> => {
1849
+ if (Array.isArray(raw.enums)) return raw.enums;
1850
+ if (Array.isArray(raw.options)) return raw.options;
1851
+ if (Array.isArray(optionsObject?.options)) return optionsObject.options;
1852
+ if (Array.isArray(editorOptions?.options)) return editorOptions.options;
1853
+
1854
+ return [];
1855
+ })();
1856
+
1857
+ return source
1858
+ .map(item => normalizeEnumOption(item))
1859
+ .filter((option): option is EnumOption => option !== null);
1860
+ }
1861
+
1862
+ export function normalizeEnumOption(value: unknown): EnumOption | null {
1863
+ if (!value || typeof value !== 'object') return null;
1864
+ const record = toRecord(value);
1865
+ const id = pickString(record, 'id', 'value', 'slug');
1866
+ const name = pickString(record, 'name', 'label', 'title') ?? id;
1867
+
1868
+ if (!id || !name) return null;
1869
+
1870
+ return {
1871
+ id,
1872
+ name,
1873
+ color: pickString(record, 'color') ?? undefined,
1874
+ icon: pickString(record, 'icon') ?? undefined,
1875
+ parent: pickString(record, 'parent') ?? undefined,
1876
+ slug: pickString(record, 'slug') ?? undefined,
1877
+ description: pickString(record, 'description') ?? undefined,
1878
+ active: pickBoolean(record, 'active') ?? undefined
1879
+ };
1880
+ }
1881
+
1882
+ function buildSubmitPayload(
1883
+ fields: Array<Pick<KivaFormViewField, 'readOnly' | 'disabled' | 'submitKeys'>>,
1884
+ values: Record<string, unknown>
1885
+ ): Record<string, unknown> {
1886
+ const payload: Record<string, unknown> = {};
1887
+
1888
+ for (const field of fields) {
1889
+ if (field.readOnly || field.disabled) continue;
1890
+
1891
+ for (const key of field.submitKeys) {
1892
+ if (!key) continue;
1893
+ if (!(key in values)) continue;
1894
+
1895
+ payload[key] = values[key];
1896
+ }
1897
+ }
1898
+
1899
+ return payload;
1900
+ }
1901
+
1902
+ /**
1903
+ * A tab panel whose active tab is CONTROLLED.
1904
+ *
1905
+ * `computedHidden` reshapes the layout live, and the normalizer drops a tab
1906
+ * once all of its fields hide. With an uncontrolled `<Tabs>`, `defaultValue` is
1907
+ * read only at mount, so Radix kept an internal value pointing at a tab that no
1908
+ * longer existed: the panel rendered a tab bar with nothing selected and an
1909
+ * empty body until the user clicked elsewhere.
1910
+ *
1911
+ * The fallback is COMMITTED, not recomputed per render. Once the user has been
1912
+ * moved to another tab they stay there — snapping back when the original
1913
+ * returns would teleport them mid-edit, and Radix unmounts inactive tab content,
1914
+ * so whatever they had typed in the fallback tab would go with it.
1915
+ */
1916
+ function ControlledFormViewTabs({
1917
+ tabValues,
1918
+ defaultTabValue,
1919
+ className,
1920
+ children
1921
+ }: {
1922
+ tabValues: Array<string>;
1923
+ defaultTabValue: string;
1924
+ className?: string;
1925
+ children: ReactNode;
1926
+ }) {
1927
+ const [active, setActive] = useState(defaultTabValue);
1928
+
1929
+ if (!tabValues.includes(active)) {
1930
+ setActive(defaultTabValue);
1931
+ }
1932
+
1933
+ return (
1934
+ <Tabs value={active} onValueChange={setActive} className={className}>
1935
+ {children}
1936
+ </Tabs>
1937
+ );
1938
+ }
1939
+
1940
+ function isKivaFormViewLayoutFieldItem(
1941
+ item: KivaFormViewLayoutItem
1942
+ ): item is KivaFormViewLayoutFieldItem {
1943
+ return typeof item === 'object' && item !== null && 'type' in item && item.type === 'field';
1944
+ }
1945
+
1946
+ function normalizeKivaFormViewLayoutItems(
1947
+ items: Array<KivaFormViewLayoutItem>,
1948
+ visibleFieldSlugs: Set<string>,
1949
+ seenFieldSlugs: Set<string> = new Set()
1950
+ ): Array<KivaFormViewLayoutItem> {
1951
+ const normalizedItems: Array<KivaFormViewLayoutItem> = [];
1952
+
1953
+ for (const item of items) {
1954
+ if (typeof item === 'string') {
1955
+ if (!visibleFieldSlugs.has(item) || seenFieldSlugs.has(item)) {
1956
+ continue;
1957
+ }
1958
+
1959
+ seenFieldSlugs.add(item);
1960
+ normalizedItems.push(item);
1961
+ continue;
1962
+ }
1963
+
1964
+ if (isKivaFormViewLayoutFieldItem(item)) {
1965
+ if (!visibleFieldSlugs.has(item.slug) || seenFieldSlugs.has(item.slug)) {
1966
+ continue;
1967
+ }
1968
+
1969
+ seenFieldSlugs.add(item.slug);
1970
+ normalizedItems.push(item);
1971
+ continue;
1972
+ }
1973
+
1974
+ if (item.variant === 'tabpanel') {
1975
+ const normalizedTabs = item.items
1976
+ .filter(tab => tab.variant === 'tab')
1977
+ .map(tab => ({
1978
+ ...tab,
1979
+ items: normalizeKivaFormViewLayoutItems(tab.items, visibleFieldSlugs, seenFieldSlugs)
1980
+ }))
1981
+ .filter(tab => tab.items.length > 0);
1982
+
1983
+ if (normalizedTabs.length === 0) {
1984
+ continue;
1985
+ }
1986
+
1987
+ normalizedItems.push({
1988
+ ...item,
1989
+ items: normalizedTabs
1990
+ });
1991
+ continue;
1992
+ }
1993
+
1994
+ const normalizedChildren = normalizeKivaFormViewLayoutItems(item.items, visibleFieldSlugs, seenFieldSlugs);
1995
+
1996
+ if (normalizedChildren.length === 0) {
1997
+ continue;
1998
+ }
1999
+
2000
+ normalizedItems.push({
2001
+ ...item,
2002
+ items: normalizedChildren
2003
+ });
2004
+ }
2005
+
2006
+ return normalizedItems;
2007
+ }
2008
+
2009
+ function collectKivaFormViewLayoutFieldSlugs(items: Array<KivaFormViewLayoutItem>): Array<string> {
2010
+ return items.flatMap((item) => {
2011
+ if (typeof item === 'string') {
2012
+ return [item];
2013
+ }
2014
+
2015
+ if (isKivaFormViewLayoutFieldItem(item)) {
2016
+ return [item.slug];
2017
+ }
2018
+
2019
+ return collectKivaFormViewLayoutFieldSlugs(item.items);
2020
+ });
2021
+ }
2022
+
2023
+ function getKivaFormViewTabValue(tab: KivaFormViewTabSection): string {
2024
+ return `tab-${tab.id}`;
2025
+ }
2026
+
2027
+ function resolveBooleanOrResolver(
2028
+ value: boolean | ((values: Record<string, unknown>) => boolean) | undefined,
2029
+ values: Record<string, unknown>
2030
+ ): boolean | undefined {
2031
+ if (typeof value === 'function') return value(values);
2032
+
2033
+ return value;
2034
+ }
2035
+
2036
+ function isFieldRequired(field: IField): boolean {
2037
+ return field.validations?.includes('required') ?? false;
2038
+ }
2039
+
2040
+ /** Types whose value is numeric even when the input hands back a string. */
2041
+ const NUMERIC_VALIDATION_TYPES = new Set<string>([
2042
+ 'field-number',
2043
+ 'field-money',
2044
+ 'field-percent',
2045
+ 'field-duration',
2046
+ 'field-rating'
2047
+ ]);
2048
+
2049
+ function normalizeValueForValidation(field: IField, value: unknown): unknown {
2050
+ const dateTypes = new Set(['field-date', 'field-dateTime']);
2051
+
2052
+ if (NUMERIC_VALIDATION_TYPES.has(field.type)) {
2053
+ if (value == null || value === '') return 0;
2054
+ if (typeof value === 'string') {
2055
+ const cleaned = value.replace(/[^\d.,-]/g, '').replace(',', '.');
2056
+
2057
+ return Number(cleaned) || 0;
2058
+ }
2059
+
2060
+ return Number(value) || 0;
2061
+ }
2062
+
2063
+ if (dateTypes.has(field.type)) {
2064
+ if (value == null) return null;
2065
+ if (value instanceof Date) return value;
2066
+ if (typeof value === 'string' && value) return value;
2067
+
2068
+ return null;
2069
+ }
2070
+
2071
+ return value;
2072
+ }
2073
+
2074
+ function isEmptyValue(value: unknown): boolean {
2075
+ if (value == null) return true;
2076
+ if (typeof value === 'string') return value.trim() === '';
2077
+ if (Array.isArray(value)) return value.length === 0;
2078
+
2079
+ return false;
2080
+ }
2081
+
2082
+ function stableStringify(value: unknown): string {
2083
+ try {
2084
+ /*
2085
+ * Sort keys on the way out — otherwise two structurally identical objects
2086
+ * that were built in a different order stringify differently, and every
2087
+ * comparison built on this (dirty state, the initial-values identity key)
2088
+ * reports a change that never happened.
2089
+ */
2090
+ return JSON.stringify(value, (_key, val) => {
2091
+ if (val && typeof val === 'object' && !Array.isArray(val)) {
2092
+ return Object.fromEntries(
2093
+ Object.entries(val as Record<string, unknown>)
2094
+ .sort(([a], [b]) => a.localeCompare(b))
2095
+ );
2096
+ }
2097
+
2098
+ return val;
2099
+ });
2100
+ } catch {
2101
+ return '';
2102
+ }
2103
+ }
2104
+
2105
+ /**
2106
+ * `undefined`, `null`, `''` and `[]` all mean "this field has no value". A
2107
+ * widget that writes one of them where the record held another is not an edit,
2108
+ * so dirty state has to compare the normalized shape — otherwise a form the
2109
+ * user never touched warns about unsaved changes.
2110
+ */
2111
+ function normalizeEmptyForComparison(value: unknown): unknown {
2112
+ if (value === undefined || value === null || value === '') return null;
2113
+
2114
+ if (Array.isArray(value)) {
2115
+ return value.length === 0 ? null : value.map(normalizeEmptyForComparison);
2116
+ }
2117
+
2118
+ if (typeof value === 'object') {
2119
+ return Object.fromEntries(
2120
+ Object.entries(value as Record<string, unknown>)
2121
+ .map(([key, entry]) => [key, normalizeEmptyForComparison(entry)])
2122
+ );
2123
+ }
2124
+
2125
+ return value;
2126
+ }
2127
+
2128
+ export function valuesMatch(
2129
+ left: Record<string, unknown>,
2130
+ right: Record<string, unknown>
2131
+ ): boolean {
2132
+ return stableStringify(normalizeEmptyForComparison(left))
2133
+ === stableStringify(normalizeEmptyForComparison(right));
2134
+ }
2135
+
2136
+ function getGridColumnsClassName(columns: 1 | 2 | 3 | 4): string {
2137
+ switch (columns) {
2138
+ case 1:
2139
+ return 'grid grid-cols-1 gap-4';
2140
+
2141
+ case 2:
2142
+ return 'grid grid-cols-1 gap-4 lg:grid-cols-2';
2143
+
2144
+ case 3:
2145
+ return 'grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3';
2146
+
2147
+ case 4:
2148
+ return 'grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4';
2149
+
2150
+ default:
2151
+ return 'grid grid-cols-1 gap-4';
2152
+ }
2153
+ }
2154
+
2155
+ function getGridSpanStyle(colSpan: KivaFormViewColSpan | undefined): CSSProperties | undefined {
2156
+ if (!colSpan) return undefined;
2157
+ if (colSpan === 'full') return { gridColumn: '1 / -1' };
2158
+
2159
+ return { gridColumn: `span ${colSpan} / span ${colSpan}` };
2160
+ }
2161
+
2162
+ function parseJsonValue(value: string): unknown {
2163
+ try {
2164
+ return JSON.parse(value);
2165
+ } catch {
2166
+ return value;
2167
+ }
2168
+ }
2169
+
2170
+ function pickString(record: Record<string, unknown>, ...keys: Array<string>): string | null {
2171
+ for (const key of keys) {
2172
+ const value = record[key];
2173
+
2174
+ if (typeof value === 'string' && value.length > 0) return value;
2175
+ }
2176
+
2177
+ return null;
2178
+ }
2179
+
2180
+ function pickBoolean(record: Record<string, unknown>, ...keys: Array<string>): boolean | null {
2181
+ for (const key of keys) {
2182
+ const value = record[key];
2183
+
2184
+ if (typeof value === 'boolean') return value;
2185
+ }
2186
+
2187
+ return null;
2188
+ }
2189
+
2190
+ function toRecord(value: unknown): Record<string, unknown> {
2191
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
2192
+ return {};
2193
+ }
2194
+
2195
+ return value as Record<string, unknown>;
2196
+ }
2197
+
2198
+ function uniqueStrings(values: Array<string | null | undefined>): Array<string> {
2199
+ return Array.from(new Set(values.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)));
2200
+ }