@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,143 @@
1
+ // @ts-nocheck
2
+ /* eslint-disable */
3
+ /**
4
+ * Shared helpers for the Kiva activity hooks (contact-activity, create-task,
5
+ * event-create). Kept React-free so the hooks stay thin adapters and so a single
6
+ * `/v1/users` cache entry can be shared across all three.
7
+ */
8
+
9
+ /** Minimal read surface needed to fetch the shared user list. */
10
+ export interface KivaReadClient {
11
+ get<T = unknown>(url: string, params?: Record<string, unknown>): Promise<T>;
12
+ }
13
+
14
+ /** Unwrap the `{ data }` envelope, tolerating already-unwrapped responses. */
15
+ export function unwrap<T>(response: unknown): T {
16
+ if (response && typeof response === 'object' && 'data' in response) {
17
+ return (response as { data: T }).data;
18
+ }
19
+
20
+ return response as T;
21
+ }
22
+
23
+ /** Unwrap a list payload, tolerating bare arrays and `{ data: [] }` envelopes. */
24
+ export function unwrapList<T>(response: unknown): Array<T> {
25
+ const data = unwrap<Array<T>>(response);
26
+
27
+ return Array.isArray(data) ? data : [];
28
+ }
29
+
30
+ /** First non-empty string among the given keys (variant-tolerant field reads). */
31
+ export function pickString(record: Record<string, unknown>, ...keys: Array<string>): string | null {
32
+ for (const key of keys) {
33
+ const value = record[key];
34
+
35
+ if (typeof value === 'string' && value.length > 0) return value;
36
+ }
37
+
38
+ return null;
39
+ }
40
+
41
+ /** Canonical user shape resolved from `/v1/users` regardless of key casing. */
42
+ export interface KivaUserRecord {
43
+ id: string;
44
+ firstname: string | null;
45
+ lastname: string | null;
46
+ /** Precomposed display name when the API supplies one. */
47
+ name: string | null;
48
+ email: string | null;
49
+ photo: string | null;
50
+ }
51
+
52
+ /**
53
+ * `/v1/users` records are keyed inconsistently (`id` / `userId` / `user_id`,
54
+ * `firstname` / `firstName` / `first_name`, …) — accept every known variant so
55
+ * options never degrade to a raw UUID label.
56
+ */
57
+ export function normalizeKivaUser(record: Record<string, unknown>): KivaUserRecord | null {
58
+ const id = pickString(record, 'id', 'userId', 'user_id');
59
+
60
+ if (!id) return null;
61
+
62
+ return {
63
+ id,
64
+ firstname: pickString(record, 'firstname', 'firstName', 'first_name'),
65
+ lastname: pickString(record, 'lastname', 'lastName', 'last_name'),
66
+ name: pickString(record, 'name', 'fullName', 'full_name', 'display_name', 'displayName'),
67
+ email: pickString(record, 'email'),
68
+ photo: pickString(record, 'photo', 'avatar_url', 'avatarUrl', 'profile_image_url', 'profileImageUrl')
69
+ };
70
+ }
71
+
72
+ /** A person's display name from a normalized user record. */
73
+ export function kivaUserDisplayName(user: KivaUserRecord): string {
74
+ return (
75
+ user.name?.trim()
76
+ || [user.firstname, user.lastname].filter(Boolean).join(' ').trim()
77
+ || user.id
78
+ );
79
+ }
80
+
81
+ /**
82
+ * Shared query key for the full `/v1/users` list. All three activity hooks use
83
+ * this SAME key (and the SAME canonical `KivaUserRecord[]` shape) so React
84
+ * Query dedupes to a single request/cache entry instead of one per hook.
85
+ */
86
+ export function kivaUsersQueryKey(limit: number): readonly ['kiva-users', number] {
87
+ return ['kiva-users', limit] as const;
88
+ }
89
+
90
+ /** Fetch + normalize the shared user list (no server-side search — client filters). */
91
+ export async function fetchKivaUsers(
92
+ client: KivaReadClient,
93
+ limit = 1000,
94
+ endpoint = '/v1/users'
95
+ ): Promise<Array<KivaUserRecord>> {
96
+ const rows = unwrapList<Record<string, unknown>>(await client.get(endpoint, { limit }));
97
+
98
+ return rows
99
+ .map(normalizeKivaUser)
100
+ .filter((u): u is KivaUserRecord => u !== null);
101
+ }
102
+
103
+ const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
104
+
105
+ /**
106
+ * Serialize a **date-only** value (e.g. a `<input type="date">` string) for a
107
+ * datetime column. A bare `YYYY-MM-DD` is anchored to **midday UTC** so the
108
+ * calendar date stays stable across every real timezone (UTC-11…UTC+11) —
109
+ * `T00:00:00Z` would render as the previous day west of UTC. Full datetimes
110
+ * pass through `toISOString()`.
111
+ */
112
+ export function kivaDateToIso(value: Date | string | null | undefined): string | undefined {
113
+ if (!value) return undefined;
114
+
115
+ if (typeof value === 'string') {
116
+ const trimmed = value.trim();
117
+
118
+ if (DATE_ONLY.test(trimmed)) return `${trimmed}T12:00:00.000Z`;
119
+
120
+ const parsed = new Date(trimmed);
121
+
122
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString();
123
+ }
124
+
125
+ return Number.isNaN(value.getTime()) ? undefined : value.toISOString();
126
+ }
127
+
128
+ /**
129
+ * Serialize a **datetime** value (e.g. a `<input type="datetime-local">` string,
130
+ * which is local wall-clock) to a UTC ISO instant. A date-only string still gets
131
+ * the midday-UTC anchoring so it never shifts a day.
132
+ */
133
+ export function kivaDateTimeToIso(value: Date | string | null | undefined): string | undefined {
134
+ if (!value) return undefined;
135
+
136
+ if (typeof value === 'string' && DATE_ONLY.test(value.trim())) {
137
+ return `${value.trim()}T12:00:00.000Z`;
138
+ }
139
+
140
+ const date = value instanceof Date ? value : new Date(value);
141
+
142
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
143
+ }
@@ -0,0 +1,310 @@
1
+ 'use client';
2
+
3
+ // @ts-nocheck
4
+ /* eslint-disable */
5
+ /*
6
+ * Lives in `_internal/` so the registry scanner does not surface it as a
7
+ * standalone hook. Bundled as a transitive file under use-kiva-form-view.
8
+ */
9
+
10
+ import {
11
+ useEffect, useMemo, useRef, useState
12
+ } from 'react';
13
+
14
+ import { type RuleGroupTypeAny } from 'react-querybuilder';
15
+
16
+ import { evaluateJsonata } from '@kivacore/ui-pro-shared/components/kiva/jsonata-editor/lib/evaluate';
17
+ import {
18
+ computeDateBindings,
19
+ convertQueryToJsonata,
20
+ createHelperBindings,
21
+ type DateBindingSpec
22
+ } from '@kivacore/ui-pro-shared/components/kiva/query-builder/lib/query-to-jsonata';
23
+ import { type ComputedBooleanFormula, type IField } from '@kivacore/ui-pro-shared/components/kiva/form-fields/types';
24
+
25
+ export interface ComputedFieldState {
26
+ /** Evaluated result of computedHidden — undefined if formula absent or failed */
27
+ hidden?: boolean;
28
+ /** Evaluated result of computedRequired — undefined if formula absent or failed */
29
+ required?: boolean;
30
+ /** Evaluated result of computedReadonly — undefined if formula absent or failed */
31
+ readOnly?: boolean;
32
+ /** Evaluated result of computedLabel — undefined if formula absent, empty, or failed */
33
+ label?: string;
34
+ /** Evaluated result of computedDescription — undefined if formula absent, empty, or failed */
35
+ description?: string;
36
+ /** Evaluated result of computedFormula */
37
+ value?: unknown;
38
+ /** True when the field has a computedFormula (even if last evaluation produced undefined) */
39
+ hasFormula: boolean;
40
+ }
41
+
42
+ interface FieldEntry {
43
+ slug: string;
44
+ field: IField;
45
+ }
46
+
47
+ interface CompiledEntry {
48
+ hiddenExpr: { expression: string; dateBindings: DateBindingSpec[] } | null;
49
+ requiredExpr: { expression: string; dateBindings: DateBindingSpec[] } | null;
50
+ readOnlyExpr: { expression: string; dateBindings: DateBindingSpec[] } | null;
51
+ labelExpr: string | null;
52
+ descriptionExpr: string | null;
53
+ formulaExpr: string | null;
54
+ }
55
+
56
+ /**
57
+ * Reactive computed-field evaluator for `useKivaFormView`.
58
+ *
59
+ * For each field that has one or more computed properties (computedHidden,
60
+ * computedRequired, computedLabel, computedDescription, computedFormula) stored
61
+ * in `IField`, this hook:
62
+ * 1. Compiles QB JSON → JSONata strings once when the field list changes.
63
+ * 2. Evaluates all compiled expressions asynchronously whenever `values` change.
64
+ * 3. Returns a Map<slug, ComputedFieldState> that the caller merges into resolved fields.
65
+ *
66
+ * Returns an empty Map (no overrides) when no fields have computed properties.
67
+ */
68
+ const NUMERIC_FIELD_TYPES = new Set<string>([
69
+ 'field-number',
70
+ 'field-money',
71
+ 'field-percent',
72
+ 'field-duration',
73
+ 'field-rating'
74
+ ]);
75
+
76
+ export function useComputedFieldEvaluator(
77
+ fields: FieldEntry[],
78
+ values: Record<string, unknown>
79
+ ): Map<string, ComputedFieldState> {
80
+ const helperBindingsRef = useRef<Record<string, unknown>>(createHelperBindings() as Record<string, unknown>);
81
+
82
+ const [states, setStates] = useState<Map<string, ComputedFieldState>>(() => new Map());
83
+
84
+ const hasAnyComputed = fields.some(({ field }) => field.computedHidden != null
85
+ || field.computedRequired != null
86
+ || field.computedReadonly != null
87
+ || field.computedLabel != null
88
+ || field.computedDescription != null
89
+ || field.computedFormula != null);
90
+
91
+ /*
92
+ * Step 1: (Re)compile expressions when the field list changes. Compilation is
93
+ * a pure QB→JSONata string conversion, so it is derived during render with
94
+ * useMemo rather than written to a ref from an effect.
95
+ */
96
+ const compiled = useMemo<Map<string, CompiledEntry>>(() => {
97
+ const map = new Map<string, CompiledEntry>();
98
+
99
+ if (!hasAnyComputed) return map;
100
+
101
+ for (const { slug, field } of fields) {
102
+ const entry: CompiledEntry = {
103
+ hiddenExpr: resolveBooleanExpr(field.computedHidden),
104
+ requiredExpr: resolveBooleanExpr(field.computedRequired),
105
+ readOnlyExpr: resolveBooleanExpr(field.computedReadonly),
106
+ labelExpr: typeof field.computedLabel === 'string' && field.computedLabel.trim() ? field.computedLabel.trim() : null,
107
+ descriptionExpr: typeof field.computedDescription === 'string' && field.computedDescription.trim() ? field.computedDescription.trim() : null,
108
+ formulaExpr: typeof field.computedFormula === 'string' && field.computedFormula.trim() ? field.computedFormula.trim() : null
109
+ };
110
+
111
+ const hasEntry
112
+ = entry.hiddenExpr != null
113
+ || entry.requiredExpr != null
114
+ || entry.readOnlyExpr != null
115
+ || entry.labelExpr != null
116
+ || entry.descriptionExpr != null
117
+ || entry.formulaExpr != null;
118
+
119
+ if (hasEntry) {
120
+ map.set(slug, entry);
121
+ }
122
+ }
123
+
124
+ return map;
125
+ }, [fields, hasAnyComputed]);
126
+
127
+ /*
128
+ * Step 2: Evaluate all compiled expressions async whenever values change.
129
+ * Debounced by 200 ms so rapid keystrokes only trigger one evaluation after
130
+ * the user pauses, rather than one per character. A new `compiled` map
131
+ * (formula definition changed) shares the same debounce — 200 ms is
132
+ * imperceptible for a formula editor.
133
+ * The `cancelled` flag prevents stale async results from overwriting a
134
+ * newer evaluation that may have already completed.
135
+ */
136
+ useEffect(() => {
137
+ if (!hasAnyComputed || compiled.size === 0) {
138
+ return;
139
+ }
140
+
141
+ let cancelled = false;
142
+
143
+ const evaluate = async () => {
144
+ const nextStates = new Map<string, ComputedFieldState>();
145
+ const nowMs = Date.now();
146
+ const helperBindings = helperBindingsRef.current;
147
+
148
+ /*
149
+ * Number fields store their raw input as a string ("12123") because HTML
150
+ * inputs are always strings. Coerce ONLY known numeric field types to JS
151
+ * numbers so JSONata arithmetic works without requiring $number().
152
+ * Enum IDs, phone numbers, zip codes and other string-typed fields are
153
+ * deliberately left as strings to avoid breaking equality comparisons.
154
+ */
155
+ const numericSlugs = new Set(
156
+ fields.filter(f => NUMERIC_FIELD_TYPES.has(f.field.type)).map(f => f.slug)
157
+ );
158
+ const coercedValues = coerceNumericStrings(values, numericSlugs);
159
+
160
+ for (const [slug, entry] of compiled.entries()) {
161
+ const state: ComputedFieldState = { hasFormula: !!entry.formulaExpr };
162
+
163
+ if (entry.hiddenExpr) {
164
+ const dateB = computeDateBindings(entry.hiddenExpr.dateBindings, nowMs);
165
+ const result = await evaluateJsonata(
166
+ entry.hiddenExpr.expression,
167
+ coercedValues,
168
+ { bindings: { ...helperBindings, ...dateB } }
169
+ );
170
+
171
+ if (result.status === 'success') {
172
+ state.hidden = Boolean(result.result);
173
+ }
174
+ }
175
+
176
+ if (entry.requiredExpr) {
177
+ const dateB = computeDateBindings(entry.requiredExpr.dateBindings, nowMs);
178
+ const result = await evaluateJsonata(
179
+ entry.requiredExpr.expression,
180
+ coercedValues,
181
+ { bindings: { ...helperBindings, ...dateB } }
182
+ );
183
+
184
+ if (result.status === 'success') {
185
+ state.required = Boolean(result.result);
186
+ }
187
+ }
188
+
189
+ if (entry.readOnlyExpr) {
190
+ const dateB = computeDateBindings(entry.readOnlyExpr.dateBindings, nowMs);
191
+ const result = await evaluateJsonata(
192
+ entry.readOnlyExpr.expression,
193
+ coercedValues,
194
+ { bindings: { ...helperBindings, ...dateB } }
195
+ );
196
+
197
+ if (result.status === 'success') {
198
+ state.readOnly = Boolean(result.result);
199
+ }
200
+ }
201
+
202
+ if (entry.labelExpr) {
203
+ const result = await evaluateJsonata(entry.labelExpr, coercedValues);
204
+
205
+ if (result.status === 'success' && result.result != null) {
206
+ state.label = String(result.result);
207
+ }
208
+ }
209
+
210
+ if (entry.descriptionExpr) {
211
+ const result = await evaluateJsonata(entry.descriptionExpr, coercedValues);
212
+
213
+ if (result.status === 'success' && result.result != null) {
214
+ state.description = String(result.result);
215
+ }
216
+ }
217
+
218
+ if (entry.formulaExpr) {
219
+ const result = await evaluateJsonata(entry.formulaExpr, coercedValues);
220
+
221
+ if (result.status === 'success') {
222
+ state.value = result.result;
223
+ }
224
+ }
225
+
226
+ nextStates.set(slug, state);
227
+ }
228
+
229
+ if (!cancelled) {
230
+ setStates(nextStates);
231
+ }
232
+ };
233
+
234
+ const timer = setTimeout(() => {
235
+ void evaluate();
236
+ }, 200);
237
+
238
+ return () => {
239
+ cancelled = true;
240
+ clearTimeout(timer);
241
+ };
242
+ }, [
243
+ fields,
244
+ values,
245
+ hasAnyComputed,
246
+ compiled
247
+ ]);
248
+
249
+ return hasAnyComputed ? states : EMPTY_MAP;
250
+ }
251
+
252
+ /*
253
+ * Stable empty map returned when no fields have computed properties,
254
+ * avoiding a new Map() allocation on every render.
255
+ */
256
+ const EMPTY_MAP = new Map<string, ComputedFieldState>();
257
+
258
+ /**
259
+ * Normalises a `ComputedBooleanFormula` value into a compiled expression entry.
260
+ * Returns null when the value is absent, empty, or an empty QB rule group.
261
+ */
262
+ function resolveBooleanExpr(
263
+ raw: ComputedBooleanFormula | undefined
264
+ ): CompiledEntry['hiddenExpr'] {
265
+ if (!raw) return null;
266
+
267
+ if (typeof raw === 'string') {
268
+ const trimmed = raw.trim();
269
+
270
+ return trimmed ? { expression: trimmed, dateBindings: [] } : null;
271
+ }
272
+
273
+ if (
274
+ typeof raw === 'object'
275
+ && 'combinator' in raw
276
+ && 'rules' in raw
277
+ && Array.isArray(raw.rules)
278
+ && raw.rules.length > 0
279
+ ) {
280
+ const result = convertQueryToJsonata(raw as RuleGroupTypeAny);
281
+
282
+ return { expression: result.expression, dateBindings: result.dateBindings };
283
+ }
284
+
285
+ return null;
286
+ }
287
+
288
+ /*
289
+ * Coerce numeric-looking string values to JS numbers ONLY for fields whose
290
+ * type is a known numeric type (field-number, field-money, etc.).
291
+ * Enum IDs, phone numbers, zip codes, and other string-typed fields are
292
+ * intentionally left as strings — coercing them would break equality
293
+ * comparisons like `status = "1"` (coerced 1 ≠ "1" in JSONata).
294
+ */
295
+ function coerceNumericStrings(
296
+ values: Record<string, unknown>,
297
+ numericSlugs: Set<string>
298
+ ): Record<string, unknown> {
299
+ const out: Record<string, unknown> = {};
300
+
301
+ for (const [k, v] of Object.entries(values)) {
302
+ if (numericSlugs.has(k) && typeof v === 'string' && v.trim() !== '' && /^-?\d+(\.\d+)?$/.test(v.trim())) {
303
+ out[k] = Number(v);
304
+ } else {
305
+ out[k] = v;
306
+ }
307
+ }
308
+
309
+ return out;
310
+ }