@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,809 @@
1
+ 'use client';
2
+
3
+ // @ts-nocheck
4
+ /* eslint-disable */
5
+ import {
6
+ createContext, useCallback, use, useMemo, useReducer, useRef, useState, type ComponentRef, type ComponentProps, type ReactNode, type RefObject, type Ref
7
+ } from 'react';
8
+
9
+ import { type RestApiClient } from '@kivacore/api-client';
10
+ import { RotateCcw, Save } from 'lucide-react';
11
+ import { toast } from 'sonner';
12
+
13
+ import { cn } from '@kivacore/ui-pro-shared/lib/utils';
14
+ import {
15
+ ActionBar,
16
+ ActionBarGroup,
17
+ ActionBarSeparator
18
+ } from '@kivacore/ui-pro-shared/components/action-bar';
19
+ import { Button } from '@kivacore/ui-pro-shared/components/button';
20
+ import {
21
+ Popover,
22
+ PopoverContent,
23
+ PopoverHeader,
24
+ PopoverTitle,
25
+ PopoverTrigger
26
+ } from '@kivacore/ui-pro-shared/components/popover';
27
+
28
+ import {
29
+ EditableValue,
30
+ type EditableValueProps
31
+ } from '@kivacore/ui-pro-shared/components/kiva/editable-value';
32
+ import {
33
+ type EnumOption,
34
+ type IField
35
+ } from '@kivacore/ui-pro-shared/components/kiva/form-fields/types';
36
+ import { getStatusCompanionSlugs } from '@kivacore/ui-pro-shared/lib/kiva/field-format';
37
+ import { describeRecordSaveError } from '@kivacore/ui-pro-shared/lib/kiva/record-save-error';
38
+ import { useUiTranslation } from '@kivacore/ui-pro-shared/hooks/kiva/use-ui-translation';
39
+
40
+ export interface RecordDetailField {
41
+ /** Field configuration */
42
+ field: IField;
43
+ /** Enum options for select-based fields */
44
+ enumOptions?: Array<EnumOption>;
45
+ /** Whether this field is read-only */
46
+ readOnly?: boolean;
47
+ /** Whether this field is required. Accepts a boolean or a function that receives current values. */
48
+ required?: boolean | ((values: Record<string, unknown>) => boolean);
49
+ /** Whether this field should be hidden. Accepts a boolean or a function that receives current values. */
50
+ hidden?: boolean | ((values: Record<string, unknown>) => boolean);
51
+ /** App slug for dynamic enum loading */
52
+ appSlug?: string;
53
+ /** Data source slug for dynamic enum loading */
54
+ dataSourceSlug?: string;
55
+ /**
56
+ * Extra props forwarded to the inline editor (`DynamicFormField`). This is
57
+ * how injected handlers reach click-to-edit — e.g. the form-view engine's
58
+ * `onImageUpload` for `field-image` / `field-avatar`, without which a picked
59
+ * image is never uploaded.
60
+ */
61
+ fieldProps?: EditableValueProps['fieldProps'];
62
+ }
63
+
64
+ export interface FieldChange {
65
+ fieldSlug: string;
66
+ fieldName: string;
67
+ originalValue: unknown;
68
+ newValue: unknown;
69
+ }
70
+
71
+ function valuesEqual(a: unknown, b: unknown): boolean {
72
+ if (Object.is(a, b)) return true;
73
+ if (a == null && b == null) return true;
74
+ if (a == null || b == null) return false;
75
+
76
+ if (Array.isArray(a) && Array.isArray(b)) {
77
+ if (a.length !== b.length) return false;
78
+ const sortedA = a.toSorted();
79
+ const sortedB = b.toSorted();
80
+
81
+ return sortedA.every((v, i) => Object.is(v, sortedB[i]));
82
+ }
83
+
84
+ if (typeof a === 'object' && typeof b === 'object') {
85
+ return JSON.stringify(a) === JSON.stringify(b);
86
+ }
87
+
88
+ return false;
89
+ }
90
+
91
+ function formatValue(value: unknown): string {
92
+ if (value === null || value === undefined) return '';
93
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
94
+ if (typeof value === 'number') return String(value);
95
+ if (typeof value === 'string') return value;
96
+ if (Array.isArray(value)) return value.map(String).join(', ');
97
+
98
+ return JSON.stringify(value);
99
+ }
100
+
101
+ function isEmpty(value: unknown): boolean {
102
+ if (value == null) return true;
103
+ if (typeof value === 'string') return value.trim() === '';
104
+ if (Array.isArray(value)) return value.length === 0;
105
+
106
+ return false;
107
+ }
108
+
109
+ function noop() {}
110
+
111
+ interface EditableRecordDetailContextValue {
112
+ form: any;
113
+ fieldMap: Map<string, RecordDetailField>;
114
+ valuesRef: RefObject<Record<string, unknown>>;
115
+ changedFields: Set<string>;
116
+ validationErrors: Map<string, string>;
117
+ trackChanges: boolean;
118
+ handleFieldValueChange: (slug: string, value: unknown) => void;
119
+ readOnly: boolean;
120
+ disabled: boolean;
121
+ isSaving: boolean;
122
+ changedFieldCount: number;
123
+ valuesVersion: number;
124
+ getChanges: () => Array<FieldChange>;
125
+ handleSave: () => Promise<void>;
126
+ handleCancel: () => void;
127
+ setFieldValue: (slug: string, value: unknown) => void;
128
+ client?: RestApiClient;
129
+ }
130
+
131
+ const EditableRecordDetailContext
132
+ = createContext<EditableRecordDetailContextValue | null>(null);
133
+
134
+ /**
135
+ * A stable per-field component that holds its own value state.
136
+ * Mirrors the MicroFormField pattern from EditableValue.
137
+ */
138
+ function MacroFormField({
139
+ slug,
140
+ valuesRef,
141
+ resetSignal,
142
+ onFieldChange,
143
+ validationErrors,
144
+ valuesVersion,
145
+ children
146
+ }: {
147
+ slug: string;
148
+ valuesRef: RefObject<Record<string, unknown>>;
149
+ resetSignal: number;
150
+ onFieldChange?: (slug: string, value: unknown) => void;
151
+ validationErrors: Map<string, string>;
152
+ valuesVersion: number;
153
+ children: (field: any) => ReactNode;
154
+ }) {
155
+ const [localValue, setLocalValue] = useState<unknown>(
156
+ () => valuesRef.current[slug]
157
+ );
158
+ const [touched, setTouched] = useState(false);
159
+
160
+ const lastResetRef = useRef(resetSignal);
161
+ /*
162
+ * ...and when this mounted instance is handed a DIFFERENT field. `localValue`
163
+ * is seeded once by the `useState` initializer, which does not re-run when
164
+ * React reuses an instance for another slug. The caller keys layout items by
165
+ * identity so that reuse should not happen, but the guard belongs here too:
166
+ * without it a mismatched instance renders the previous field's value under
167
+ * the new field's label, and editing it writes to the new slug.
168
+ */
169
+ const lastSlugRef = useRef(slug);
170
+
171
+ if (lastResetRef.current !== resetSignal || lastSlugRef.current !== slug) {
172
+ lastResetRef.current = resetSignal;
173
+ lastSlugRef.current = slug;
174
+ setLocalValue(valuesRef.current[slug]);
175
+ setTouched(false);
176
+ }
177
+
178
+ const handleChange = useCallback(
179
+ (v: unknown) => {
180
+ setLocalValue(v);
181
+ setTouched(true);
182
+ valuesRef.current[slug] = v;
183
+ onFieldChange?.(slug, v);
184
+ },
185
+ [slug, valuesRef, onFieldChange]
186
+ );
187
+
188
+ const handleBlur = useCallback(() => {
189
+ setTouched(true);
190
+ }, []);
191
+
192
+ void valuesVersion;
193
+ const error = validationErrors.get(slug);
194
+ const hasError = error != null;
195
+
196
+ return (
197
+ <>
198
+ {children({
199
+ name: slug,
200
+ state: {
201
+ value: localValue,
202
+ meta: {
203
+ isTouched: touched || hasError,
204
+ isValid: !hasError,
205
+ errors: hasError ? [{ message: error }] : []
206
+ }
207
+ },
208
+ handleChange,
209
+ handleBlur
210
+ })}
211
+ </>
212
+ );
213
+ }
214
+
215
+ /**
216
+ * Creates a stable multi-field form object matching the TanStack Form
217
+ * `form.Field` duck-typed API. Each field slug gets its own
218
+ * MacroFormField component with local state.
219
+ */
220
+ function useMacroForm(
221
+ record: Record<string, unknown>,
222
+ onFieldChange?: (slug: string, value: unknown) => void,
223
+ validationErrors?: Map<string, string>,
224
+ valuesVersion?: number
225
+ ) {
226
+ const valuesRef = useRef<Record<string, unknown>>({ ...record });
227
+ const resetSignalRef = useRef(0);
228
+ const [, forceUpdate] = useReducer((x: number) => x + 1, 0) as [number, () => void];
229
+ const onFieldChangeRef = useRef(onFieldChange);
230
+ const validationErrorsRef = useRef<Map<string, string>>(validationErrors ?? new Map());
231
+ const valuesVersionRef = useRef(valuesVersion ?? 0);
232
+
233
+ onFieldChangeRef.current = onFieldChange;
234
+ validationErrorsRef.current = validationErrors ?? new Map();
235
+ valuesVersionRef.current = valuesVersion ?? 0;
236
+
237
+ /*
238
+ * Stable `form.Field` wrapper — frozen via useState so its component
239
+ * identity doesn't change across renders. See use-kiva-form-view for
240
+ * the matching pattern; the lint rule's "no nested component" check
241
+ * doesn't apply because the closure target IS the stable identity.
242
+ */
243
+ const [form] = useState(() => ({
244
+ Field: ({
245
+ name,
246
+ children
247
+ }: {
248
+ name: string;
249
+ children: (field: any) => ReactNode;
250
+ }) => (
251
+ <MacroFormField
252
+ slug={name}
253
+ valuesRef={valuesRef}
254
+ resetSignal={resetSignalRef.current}
255
+ onFieldChange={onFieldChangeRef.current}
256
+ validationErrors={validationErrorsRef.current}
257
+ valuesVersion={valuesVersionRef.current}>
258
+ {children}
259
+ </MacroFormField>
260
+ )
261
+ }));
262
+
263
+ const resetForm = useCallback(
264
+ (newValues: Record<string, unknown>) => {
265
+ valuesRef.current = { ...newValues };
266
+ resetSignalRef.current += 1;
267
+ forceUpdate();
268
+ },
269
+ []
270
+ );
271
+
272
+ const setFieldValue = useCallback(
273
+ (slug: string, value: unknown) => {
274
+ valuesRef.current[slug] = value;
275
+ resetSignalRef.current += 1;
276
+ forceUpdate();
277
+ },
278
+ []
279
+ );
280
+
281
+ return {
282
+ form,
283
+ valuesRef,
284
+ resetForm,
285
+ setFieldValue
286
+ };
287
+ }
288
+
289
+ function EditableRecordDetailActionBar({
290
+ changedFieldCount,
291
+ getChanges,
292
+ onSave,
293
+ onDiscard,
294
+ sideOffset = 16,
295
+ isSaving,
296
+ portalContainer
297
+ }: {
298
+ changedFieldCount: number;
299
+ getChanges: () => Array<FieldChange>;
300
+ onSave: () => Promise<void>;
301
+ onDiscard: () => void;
302
+ sideOffset?: number;
303
+ isSaving: boolean;
304
+ portalContainer?: Element | DocumentFragment | null;
305
+ }) {
306
+ const [popoverOpen, setPopoverOpen] = useState(false);
307
+
308
+ const onSaveClick = useCallback(async () => {
309
+ await onSave();
310
+ }, [onSave]);
311
+
312
+ const changes = useMemo(
313
+ () => changedFieldCount === 0 ? [] : getChanges(),
314
+ [getChanges, changedFieldCount]
315
+ );
316
+
317
+ return (
318
+ <ActionBar
319
+ open
320
+ onOpenChange={noop}
321
+ sideOffset={sideOffset}
322
+ portalContainer={portalContainer}>
323
+ <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
324
+ <PopoverTrigger asChild>
325
+ <button
326
+ type="button"
327
+ className="rounded-sm px-2 py-1 text-sm font-medium tabular-nums underline decoration-dotted underline-offset-4 hover:decoration-solid">
328
+ {changedFieldCount}{' '}
329
+ {changedFieldCount === 1 ? 'field' : 'fields'} changed
330
+ </button>
331
+ </PopoverTrigger>
332
+ <PopoverContent
333
+ side="top"
334
+ align="center"
335
+ className="max-h-72 w-80 overflow-y-auto p-0">
336
+ <PopoverHeader className="sticky top-0 z-10 border-b bg-popover px-3 py-2">
337
+ <PopoverTitle>Pending Changes</PopoverTitle>
338
+ </PopoverHeader>
339
+ <div className="divide-y">
340
+ {changes.map(change => (
341
+ <div
342
+ key={change.fieldSlug}
343
+ className="flex items-center gap-1.5 px-3 py-2 text-xs">
344
+ <span className="shrink-0 font-medium">
345
+ {change.fieldName}:
346
+ </span>
347
+ <span
348
+ className="max-w-20 truncate text-muted-foreground line-through"
349
+ title={formatValue(change.originalValue)}>
350
+ {formatValue(change.originalValue) || '(empty)'}
351
+ </span>
352
+ <span className="shrink-0 text-muted-foreground">
353
+ &rarr;
354
+ </span>
355
+ <span
356
+ className="max-w-20 truncate text-foreground"
357
+ title={formatValue(change.newValue)}>
358
+ {formatValue(change.newValue) || '(empty)'}
359
+ </span>
360
+ </div>
361
+ ))}
362
+ </div>
363
+ </PopoverContent>
364
+ </Popover>
365
+ <ActionBarSeparator />
366
+ <ActionBarGroup>
367
+ <Button variant="ghost" size="sm" onClick={onDiscard}>
368
+ <RotateCcw className="size-3.5" />
369
+ Cancel
370
+ </Button>
371
+ <Button
372
+ variant="default"
373
+ size="sm"
374
+ onClick={onSaveClick}
375
+ disabled={isSaving}>
376
+ <Save className="size-3.5" />
377
+ {isSaving ? 'Saving...' : 'Save'}
378
+ </Button>
379
+ </ActionBarGroup>
380
+ </ActionBar>
381
+ );
382
+ }
383
+
384
+ export interface EditableRecordDetailFieldProps
385
+ extends Omit<
386
+ EditableValueProps,
387
+ | 'field'
388
+ | 'value'
389
+ | 'form'
390
+ | 'onValueChange'
391
+ | 'enumOptions'
392
+ | 'appSlug'
393
+ | 'dataSourceSlug'
394
+ | 'record'
395
+ | 'trackChanges'
396
+ | 'changed'
397
+ > {
398
+ ref?: Ref<HTMLDivElement>;
399
+ /** Field slug — looks up config from context */
400
+ slug: string;
401
+ /** Optional label override */
402
+ label?: ReactNode;
403
+ /** Render label + value row. Default: true */
404
+ showLabel?: boolean;
405
+ }
406
+
407
+ /**
408
+ * Pre-wired EditableValue that reads field config, form, and change state
409
+ * from the EditableRecordDetail context. Renders a label + value row
410
+ * unless showLabel is false.
411
+ */
412
+ function EditableRecordDetailField({
413
+ slug, label, showLabel = true, className, ref, ...props
414
+ }: EditableRecordDetailFieldProps) {
415
+ const ctx = use(EditableRecordDetailContext);
416
+
417
+ if (!ctx) {
418
+ throw new Error(
419
+ 'EditableRecordDetailField must be used within <EditableRecordDetail>'
420
+ );
421
+ }
422
+
423
+ const config = ctx.fieldMap.get(slug);
424
+
425
+ if (!config) return null;
426
+
427
+ void ctx.valuesVersion;
428
+
429
+ const isHidden = typeof config.hidden === 'function' ? config.hidden(ctx.valuesRef.current) : config.hidden;
430
+
431
+ if (isHidden) return null;
432
+
433
+ const {
434
+ field,
435
+ enumOptions,
436
+ readOnly: fieldReadOnly,
437
+ appSlug,
438
+ dataSourceSlug,
439
+ fieldProps
440
+ } = config;
441
+
442
+ const isChanged = ctx.changedFields.has(slug);
443
+ const validationError = ctx.validationErrors.get(slug);
444
+ const value = ctx.valuesRef.current[slug];
445
+
446
+ const editableValue = (
447
+ <EditableValue
448
+ ref={showLabel ? undefined : ref}
449
+ field={field}
450
+ value={value}
451
+ form={ctx.form}
452
+ onValueChange={(v) => {
453
+ /*
454
+ * Keep valuesRef (the source for display, getChanges, validate and save)
455
+ * in sync. With an external `form`, the field writes only to that form, so
456
+ * without this valuesRef stays at the original value and edits revert.
457
+ */
458
+ ctx.valuesRef.current[slug] = v;
459
+ ctx.handleFieldValueChange(slug, v);
460
+ }}
461
+ enumOptions={enumOptions}
462
+ record={ctx.valuesRef.current}
463
+ trackChanges={ctx.trackChanges}
464
+ changed={isChanged}
465
+ readOnly={ctx.readOnly || fieldReadOnly}
466
+ editHint={ctx.readOnly || fieldReadOnly ? 'progressive' : 'visible'}
467
+ disabled={ctx.disabled}
468
+ appSlug={appSlug}
469
+ dataSourceSlug={dataSourceSlug}
470
+ client={ctx.client}
471
+ fieldProps={fieldProps}
472
+ className={cn(!showLabel && className)}
473
+ {...props} />
474
+ );
475
+
476
+ if (!showLabel) return editableValue;
477
+
478
+ const isEditable = !ctx.readOnly && !fieldReadOnly && !ctx.disabled;
479
+
480
+ return (
481
+ <div ref={ref} className={cn('rounded-md px-2 py-1.5 transition-colors', className)}>
482
+ <div
483
+ className={cn(
484
+ 'flex items-center gap-4',
485
+ isEditable && 'cursor-pointer hover:bg-muted/50 rounded-md',
486
+ isChanged && 'bg-amber-50/50 dark:bg-amber-950/20',
487
+ validationError && 'ring-1 ring-destructive/40 rounded-md'
488
+ )}>
489
+ <span className="w-32 shrink-0 text-sm text-muted-foreground">
490
+ {label ?? field.name}
491
+ {(typeof config.required === 'function' ? config.required(ctx.valuesRef.current) : config.required) && (
492
+ <span className="ml-0.5 text-destructive">*</span>
493
+ )}
494
+ </span>
495
+ {editableValue}
496
+ </div>
497
+ {validationError && (
498
+ <p className="mt-1 pl-[calc(8rem+16px)] text-xs text-destructive">
499
+ {validationError}
500
+ </p>
501
+ )}
502
+ </div>
503
+ );
504
+ }
505
+
506
+ export interface EditableRecordDetailProps
507
+ extends Omit<ComponentProps<'div'>, 'children'> {
508
+ ref?: Ref<HTMLDivElement>;
509
+ /** Field configurations */
510
+ fields: Array<RecordDetailField>;
511
+ /** Current record values keyed by field slug */
512
+ record: Record<string, unknown>;
513
+ /** Called when save is triggered */
514
+ onSave?: (
515
+ changes: Array<FieldChange>,
516
+ values: Record<string, unknown>
517
+ ) => void | Promise<void>;
518
+ /** Called when cancel is triggered */
519
+ onCancel?: () => void;
520
+ /** External TanStack Form instance — skips internal macro-form */
521
+ form?: any;
522
+ /** Whether all fields are read-only */
523
+ readOnly?: boolean;
524
+ /** Whether all fields are disabled */
525
+ disabled?: boolean;
526
+ /** Whether changed fields should be visually highlighted */
527
+ trackChanges?: boolean;
528
+ /** Side offset for the floating action bar */
529
+ actionBarSideOffset?: number;
530
+ /**
531
+ * Authenticated Kiva REST client. Threaded down to every field's
532
+ * `EditableValue` so email-style fields expose an inline compose action.
533
+ */
534
+ client?: RestApiClient;
535
+ /** Content */
536
+ children: ReactNode;
537
+ }
538
+
539
+ function EditableRecordDetail({
540
+ fields,
541
+ record,
542
+ onSave,
543
+ onCancel,
544
+ form: externalForm,
545
+ readOnly = false,
546
+ disabled = false,
547
+ trackChanges = true,
548
+ actionBarSideOffset,
549
+ client,
550
+ children,
551
+ className, ref, ...props
552
+ }: EditableRecordDetailProps) {
553
+ const containerRef = useRef<ComponentRef<'div'>>(null);
554
+
555
+ const fieldMap = useMemo(() => {
556
+ const map = new Map<string, RecordDetailField>();
557
+
558
+ for (const entry of fields) {
559
+ map.set(entry.field.slug, entry);
560
+ }
561
+
562
+ return map;
563
+ }, [fields]);
564
+
565
+ /*
566
+ * A status field edits its sub-status, note and follow-up date in companion
567
+ * columns that are not declared fields of their own. Map each companion slug
568
+ * back to the status field that owns it, so the diff lets them through —
569
+ * without this the popover's values are tracked as changes and then dropped
570
+ * on save.
571
+ */
572
+ const companionOwnerMap = useMemo(() => {
573
+ const map = new Map<string, RecordDetailField>();
574
+
575
+ for (const entry of fields) {
576
+ if (entry.field.type !== 'field-status') continue;
577
+
578
+ for (const slug of getStatusCompanionSlugs(entry.field.slug)) {
579
+ map.set(slug, entry);
580
+ }
581
+ }
582
+
583
+ return map;
584
+ }, [fields]);
585
+
586
+ const originalValuesRef = useRef<Record<string, unknown>>({
587
+ ...record
588
+ });
589
+
590
+ const [changedFields, setChangedFields] = useState<Set<string>>(() => new Set());
591
+
592
+ const [isSaving, setIsSaving] = useState(false);
593
+ const { t } = useUiTranslation();
594
+ const [validationErrors, setValidationErrors] = useState<Map<string, string>>(() => new Map());
595
+ const onSaveRef = useRef(onSave);
596
+ const onCancelRef = useRef(onCancel);
597
+
598
+ onSaveRef.current = onSave;
599
+ onCancelRef.current = onCancel;
600
+
601
+ const handleFieldValueChange = useCallback(
602
+ (slug: string, newValue: unknown) => {
603
+ const original = originalValuesRef.current[slug];
604
+
605
+ setChangedFields((prev) => {
606
+ const next = new Set(prev);
607
+
608
+ if (valuesEqual(original, newValue)) {
609
+ next.delete(slug);
610
+ } else {
611
+ next.add(slug);
612
+ }
613
+
614
+ return next;
615
+ });
616
+
617
+ setValidationErrors((prev) => {
618
+ if (!prev.has(slug)) return prev;
619
+ const next = new Map(prev);
620
+
621
+ next.delete(slug);
622
+
623
+ return next;
624
+ });
625
+ },
626
+ []
627
+ );
628
+
629
+ const [valuesVersion, setValuesVersion] = useState(0);
630
+
631
+ const onFieldChange = useCallback(
632
+ (slug: string, value: unknown) => {
633
+ handleFieldValueChange(slug, value);
634
+ setValuesVersion(v => v + 1);
635
+ },
636
+ [handleFieldValueChange]
637
+ );
638
+
639
+ const {
640
+ form: internalForm,
641
+ valuesRef,
642
+ resetForm,
643
+ setFieldValue: macroSetFieldValue
644
+ } = useMacroForm(record, onFieldChange, validationErrors, valuesVersion);
645
+
646
+ const setFieldValue = useCallback(
647
+ (slug: string, value: unknown) => {
648
+ macroSetFieldValue(slug, value);
649
+ setValuesVersion(v => v + 1);
650
+ },
651
+ [macroSetFieldValue]
652
+ );
653
+
654
+ const activeForm = externalForm ?? internalForm;
655
+
656
+ const getChanges = useCallback((): Array<FieldChange> => {
657
+ const changes: Array<FieldChange> = [];
658
+
659
+ for (const slug of changedFields) {
660
+ const config = fieldMap.get(slug) ?? companionOwnerMap.get(slug);
661
+
662
+ if (!config) continue;
663
+
664
+ changes.push({
665
+ fieldSlug: slug,
666
+ fieldName: config.field.name,
667
+ originalValue: originalValuesRef.current[slug],
668
+ newValue: valuesRef.current[slug]
669
+ });
670
+ }
671
+
672
+ return changes;
673
+ }, [
674
+ changedFields,
675
+ fieldMap,
676
+ companionOwnerMap,
677
+ valuesRef
678
+ ]);
679
+
680
+ const validate = useCallback((): boolean => {
681
+ const errors = new Map<string, string>();
682
+ const currentValues = valuesRef.current;
683
+
684
+ for (const [slug, config] of fieldMap) {
685
+ if (config.readOnly) continue;
686
+
687
+ const isHidden = typeof config.hidden === 'function' ? config.hidden(currentValues) : config.hidden;
688
+
689
+ if (isHidden) continue;
690
+
691
+ const isRequired = typeof config.required === 'function' ? config.required(currentValues) : config.required;
692
+
693
+ if (!isRequired) continue;
694
+
695
+ const value = currentValues[slug];
696
+
697
+ if (isEmpty(value)) {
698
+ errors.set(slug, `${config.field.name} is required`);
699
+ }
700
+ }
701
+
702
+ setValidationErrors(errors);
703
+
704
+ return errors.size === 0;
705
+ }, [fieldMap, valuesRef]);
706
+
707
+ const handleSave = useCallback(async () => {
708
+ if (!validate()) return;
709
+
710
+ setIsSaving(true);
711
+
712
+ try {
713
+ const changes = getChanges();
714
+
715
+ await onSaveRef.current?.(changes, { ...valuesRef.current });
716
+
717
+ originalValuesRef.current = { ...valuesRef.current };
718
+ setChangedFields(new Set());
719
+ setValidationErrors(new Map());
720
+ } catch (error) {
721
+ toast.error(describeRecordSaveError(error, t, t('ui.record.saveFailed', 'The record could not be saved.')));
722
+ } finally {
723
+ setIsSaving(false);
724
+ }
725
+ }, [
726
+ getChanges,
727
+ valuesRef,
728
+ validate,
729
+ t
730
+ ]);
731
+
732
+ const handleCancel = useCallback(() => {
733
+ resetForm(originalValuesRef.current);
734
+ setChangedFields(new Set());
735
+ setValidationErrors(new Map());
736
+ onCancelRef.current?.();
737
+ }, [resetForm]);
738
+
739
+ const changedFieldCount = changedFields.size;
740
+
741
+ const ctxValue = useMemo<EditableRecordDetailContextValue>(
742
+ () => ({
743
+ form: activeForm,
744
+ fieldMap,
745
+ valuesRef,
746
+ changedFields,
747
+ validationErrors,
748
+ trackChanges,
749
+ handleFieldValueChange,
750
+ readOnly,
751
+ disabled,
752
+ isSaving,
753
+ changedFieldCount,
754
+ valuesVersion,
755
+ getChanges,
756
+ handleSave,
757
+ handleCancel,
758
+ setFieldValue,
759
+ client
760
+ }),
761
+ [
762
+ activeForm,
763
+ fieldMap,
764
+ valuesRef,
765
+ changedFields,
766
+ validationErrors,
767
+ trackChanges,
768
+ handleFieldValueChange,
769
+ readOnly,
770
+ disabled,
771
+ isSaving,
772
+ changedFieldCount,
773
+ valuesVersion,
774
+ getChanges,
775
+ handleSave,
776
+ handleCancel,
777
+ setFieldValue,
778
+ client
779
+ ]
780
+ );
781
+
782
+ return (
783
+ <EditableRecordDetailContext value={ctxValue}>
784
+ <div
785
+ ref={(node) => {
786
+ containerRef.current = node;
787
+ if (typeof ref === 'function') ref(node);
788
+ else if (ref) ref.current = node;
789
+ }}
790
+ data-slot="editable-record-detail"
791
+ className={cn('relative w-full', className)}
792
+ {...props}>
793
+ {children}
794
+ </div>
795
+ {changedFieldCount > 0 && (
796
+ <EditableRecordDetailActionBar
797
+ changedFieldCount={changedFieldCount}
798
+ getChanges={getChanges}
799
+ onSave={handleSave}
800
+ onDiscard={handleCancel}
801
+ sideOffset={actionBarSideOffset}
802
+ isSaving={isSaving}
803
+ portalContainer={containerRef.current} />
804
+ )}
805
+ </EditableRecordDetailContext>
806
+ );
807
+ }
808
+
809
+ export { EditableRecordDetail, EditableRecordDetailField };