@chobantonov/jsonforms-react-extended-renderers 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +17 -2
  3. package/lib/AgGridControlRenderer.impl-BO-Z1x0Y.js +2 -0
  4. package/lib/AgGridControlRenderer.impl-BO-Z1x0Y.js.map +1 -0
  5. package/lib/AgGridControlRenderer.impl-BZS8_ocu.mjs +429 -0
  6. package/lib/AgGridControlRenderer.impl-BZS8_ocu.mjs.map +1 -0
  7. package/lib/DynamicJSXRenderer-Cyw40Kz0.js +2 -0
  8. package/lib/DynamicJSXRenderer-Cyw40Kz0.js.map +1 -0
  9. package/lib/DynamicJSXRenderer-DyB3ZpZV.mjs +109 -0
  10. package/lib/DynamicJSXRenderer-DyB3ZpZV.mjs.map +1 -0
  11. package/lib/MarkupLabelRenderer.impl-CWfdcUuH.mjs +12 -0
  12. package/lib/MarkupLabelRenderer.impl-CWfdcUuH.mjs.map +1 -0
  13. package/lib/MarkupLabelRenderer.impl-DnuzIPQg.js +2 -0
  14. package/lib/MarkupLabelRenderer.impl-DnuzIPQg.js.map +1 -0
  15. package/lib/MonacoControlRenderer.impl-BwgLGNMK.js +3 -0
  16. package/lib/MonacoControlRenderer.impl-BwgLGNMK.js.map +1 -0
  17. package/lib/MonacoControlRenderer.impl-CyjMHbOd.mjs +186 -0
  18. package/lib/MonacoControlRenderer.impl-CyjMHbOd.mjs.map +1 -0
  19. package/lib/RactiveTemplate-7L44A38e.js +2 -0
  20. package/lib/RactiveTemplate-7L44A38e.js.map +1 -0
  21. package/lib/RactiveTemplate-Cat7CxUp.mjs +74 -0
  22. package/lib/RactiveTemplate-Cat7CxUp.mjs.map +1 -0
  23. package/lib/ajv-localizers.cjs.js +2 -0
  24. package/lib/ajv-localizers.cjs.js.map +1 -0
  25. package/lib/ajv-localizers.esm.js +7 -0
  26. package/lib/ajv-localizers.esm.js.map +1 -0
  27. package/lib/ajvI18n-2UTyJv5g.js +2 -0
  28. package/lib/ajvI18n-2UTyJv5g.js.map +1 -0
  29. package/lib/ajvI18n-DO8FFvx1.mjs +227 -0
  30. package/lib/ajvI18n-DO8FFvx1.mjs.map +1 -0
  31. package/lib/celTemplate-Cl0alaCz.js +3 -0
  32. package/lib/celTemplate-Cl0alaCz.js.map +1 -0
  33. package/lib/celTemplate-D_AGhaIL.mjs +137 -0
  34. package/lib/celTemplate-D_AGhaIL.mjs.map +1 -0
  35. package/lib/components/DynamicJSXRenderer.d.ts +7 -0
  36. package/lib/components/ExtendedJsonForms.d.ts +80 -0
  37. package/lib/components/GenericAdditionalProperties.d.ts +4 -0
  38. package/lib/components/InterpolatedText.d.ts +34 -0
  39. package/lib/components/RactiveTemplate.d.ts +37 -0
  40. package/lib/components/editorRendererTypes.d.ts +139 -0
  41. package/lib/components/elementRender.d.ts +15 -0
  42. package/lib/configNamespaces-BFclHtB8.mjs +1 -0
  43. package/lib/configNamespaces-sboXDudL.js +1 -0
  44. package/lib/core/ajv.d.ts +82 -0
  45. package/lib/core/ajvI18n/bg.d.ts +2 -0
  46. package/lib/core/ajvI18n/index.d.ts +118 -0
  47. package/lib/core/ajvI18n/localizers.d.ts +20 -0
  48. package/lib/core/dynamicDefaults.d.ts +34 -0
  49. package/lib/core/keywords.d.ts +24 -0
  50. package/lib/core/transform.d.ts +29 -0
  51. package/lib/core/uiSchema.d.ts +48 -0
  52. package/lib/elementRender-Dbp2e-Cc.js +2 -0
  53. package/lib/elementRender-Dbp2e-Cc.js.map +1 -0
  54. package/lib/elementRender-y8MK9CCE.mjs +5 -0
  55. package/lib/elementRender-y8MK9CCE.mjs.map +1 -0
  56. package/lib/index.d.ts +41 -0
  57. package/lib/jsonforms-react-extended.cjs.js +16 -0
  58. package/lib/jsonforms-react-extended.cjs.js.map +1 -0
  59. package/lib/jsonforms-react-extended.esm.js +2335 -0
  60. package/lib/jsonforms-react-extended.esm.js.map +1 -0
  61. package/lib/locale/bg.d.ts +14 -0
  62. package/lib/markdown-C_y73Q0w.mjs +123 -0
  63. package/lib/markdown-C_y73Q0w.mjs.map +1 -0
  64. package/lib/markdown-CuqtpGVd.js +2 -0
  65. package/lib/markdown-CuqtpGVd.js.map +1 -0
  66. package/lib/objectWithoutProperties-6zedhz76.js +2 -0
  67. package/lib/objectWithoutProperties-6zedhz76.js.map +1 -0
  68. package/lib/objectWithoutProperties-yjQMyZ0y.mjs +58 -0
  69. package/lib/objectWithoutProperties-yjQMyZ0y.mjs.map +1 -0
  70. package/lib/renderers/AgGridControlRenderer.d.ts +10 -0
  71. package/lib/renderers/AgGridControlRenderer.impl.d.ts +4 -0
  72. package/lib/renderers/ButtonRenderer.d.ts +83 -0
  73. package/lib/renderers/GenericMixedRenderer.d.ts +9 -0
  74. package/lib/renderers/HorizontalLayoutRenderer.d.ts +5 -0
  75. package/lib/renderers/ImageViewRenderer.d.ts +48 -0
  76. package/lib/renderers/LinkRenderer.d.ts +23 -0
  77. package/lib/renderers/MarkupLabelRenderer.d.ts +35 -0
  78. package/lib/renderers/MarkupLabelRenderer.impl.d.ts +17 -0
  79. package/lib/renderers/MonacoControlRenderer.d.ts +8 -0
  80. package/lib/renderers/MonacoControlRenderer.impl.d.ts +4 -0
  81. package/lib/renderers/RactiveTemplateLayoutRenderer.d.ts +6 -0
  82. package/lib/renderers/SeparatorRenderer.d.ts +17 -0
  83. package/lib/renderers/SlotRenderer.d.ts +5 -0
  84. package/lib/renderers/SpacerRenderer.d.ts +5 -0
  85. package/lib/renderers/SplitLayoutRenderer.d.ts +18 -0
  86. package/lib/renderers/TemplateLayoutRenderer.d.ts +13 -0
  87. package/lib/renderers/TemplateRenderer.d.ts +17 -0
  88. package/lib/renderers/TsxTemplateLayoutRenderer.d.ts +111 -0
  89. package/lib/renderers/index.d.ts +13 -0
  90. package/lib/renderers/templateEngines.d.ts +43 -0
  91. package/lib/util/actionContext.d.ts +23 -0
  92. package/lib/util/additionalErrors.d.ts +77 -0
  93. package/lib/util/celEnvironment.d.ts +23 -0
  94. package/lib/util/celTemplate.d.ts +47 -0
  95. package/lib/util/childNames.d.ts +46 -0
  96. package/lib/util/configNamespaces.d.ts +1 -0
  97. package/lib/util/cron.d.ts +122 -0
  98. package/lib/util/editorControls.d.ts +8 -0
  99. package/lib/util/editorDiagnostics.d.ts +56 -0
  100. package/lib/util/extendedControls.d.ts +4 -0
  101. package/lib/util/extendedLocale.d.ts +32 -0
  102. package/lib/util/fileFilterValue.d.ts +3 -0
  103. package/lib/util/formContext.d.ts +54 -0
  104. package/lib/util/gridColumns.d.ts +6 -0
  105. package/lib/util/horizontalLayout.d.ts +10 -0
  106. package/lib/util/i18nDefaults.d.ts +45 -0
  107. package/lib/util/interpolate.d.ts +105 -0
  108. package/lib/util/labelFilterValue.d.ts +2 -0
  109. package/lib/util/lazyControl.d.ts +36 -0
  110. package/lib/util/lazyTemplate.d.ts +18 -0
  111. package/lib/util/markdown.d.ts +55 -0
  112. package/lib/util/markdownEscape.d.ts +27 -0
  113. package/lib/util/markup.d.ts +74 -0
  114. package/lib/util/maskControls.d.ts +2 -0
  115. package/lib/util/templateLang.d.ts +87 -0
  116. package/lib/util/templateUrls.d.ts +40 -0
  117. package/lib/util/urlPolicy.d.ts +42 -0
  118. package/lib/util/useCronPicker.d.ts +24 -0
  119. package/lib/util/useDurationControl.d.ts +99 -0
  120. package/lib/util/useEditorAppearance.d.ts +21 -0
  121. package/lib/util/useExtendedTranslator.d.ts +10 -0
  122. package/lib/util/useMonacoShadowStyles.d.ts +2 -0
  123. package/package.json +110 -3
  124. package/src/components/DynamicJSXRenderer.tsx +274 -0
  125. package/src/components/ExtendedJsonForms.tsx +329 -0
  126. package/src/components/GenericAdditionalProperties.tsx +362 -0
  127. package/src/components/InterpolatedText.tsx +114 -0
  128. package/src/components/RactiveTemplate.tsx +161 -0
  129. package/src/components/editorRendererTypes.ts +135 -0
  130. package/src/components/elementRender.ts +15 -0
  131. package/src/core/ajv.ts +177 -0
  132. package/src/core/ajvI18n/bg.ts +203 -0
  133. package/src/core/ajvI18n/index.ts +267 -0
  134. package/src/core/ajvI18n/localizers.ts +25 -0
  135. package/src/core/dynamicDefaults.ts +170 -0
  136. package/src/core/keywords.ts +71 -0
  137. package/src/core/transform.ts +137 -0
  138. package/src/core/uiSchema.ts +53 -0
  139. package/src/index.tsx +196 -0
  140. package/src/locale/bg.ts +51 -0
  141. package/src/renderers/AgGridControlRenderer.impl.tsx +788 -0
  142. package/src/renderers/AgGridControlRenderer.tsx +24 -0
  143. package/src/renderers/ButtonRenderer.tsx +328 -0
  144. package/src/renderers/GenericMixedRenderer.tsx +224 -0
  145. package/src/renderers/HorizontalLayoutRenderer.tsx +93 -0
  146. package/src/renderers/ImageViewRenderer.tsx +328 -0
  147. package/src/renderers/LinkRenderer.tsx +92 -0
  148. package/src/renderers/MarkupLabelRenderer.impl.tsx +26 -0
  149. package/src/renderers/MarkupLabelRenderer.tsx +327 -0
  150. package/src/renderers/MonacoControlRenderer.impl.tsx +351 -0
  151. package/src/renderers/MonacoControlRenderer.tsx +24 -0
  152. package/src/renderers/RactiveTemplateLayoutRenderer.tsx +172 -0
  153. package/src/renderers/SeparatorRenderer.tsx +55 -0
  154. package/src/renderers/SlotRenderer.tsx +34 -0
  155. package/src/renderers/SpacerRenderer.tsx +69 -0
  156. package/src/renderers/SplitLayoutRenderer.tsx +220 -0
  157. package/src/renderers/TemplateLayoutRenderer.tsx +394 -0
  158. package/src/renderers/TemplateRenderer.tsx +71 -0
  159. package/src/renderers/TsxTemplateLayoutRenderer.tsx +258 -0
  160. package/src/renderers/index.ts +14 -0
  161. package/src/renderers/templateEngines.tsx +100 -0
  162. package/src/util/actionContext.ts +29 -0
  163. package/src/util/additionalErrors.tsx +391 -0
  164. package/src/util/celEnvironment.ts +300 -0
  165. package/src/util/celTemplate.ts +267 -0
  166. package/src/util/childNames.ts +135 -0
  167. package/src/util/configNamespaces.ts +6 -0
  168. package/src/util/cron.ts +433 -0
  169. package/src/util/editorControls.ts +58 -0
  170. package/src/util/editorDiagnostics.ts +103 -0
  171. package/src/util/extendedControls.ts +34 -0
  172. package/src/util/extendedLocale.ts +67 -0
  173. package/src/util/fileFilterValue.ts +28 -0
  174. package/src/util/formContext.ts +74 -0
  175. package/src/util/gridColumns.ts +80 -0
  176. package/src/util/horizontalLayout.ts +59 -0
  177. package/src/util/i18nDefaults.ts +80 -0
  178. package/src/util/interpolate.ts +218 -0
  179. package/src/util/labelFilterValue.ts +49 -0
  180. package/src/util/lazyControl.tsx +66 -0
  181. package/src/util/lazyTemplate.tsx +110 -0
  182. package/src/util/markdown.tsx +345 -0
  183. package/src/util/markdownEscape.ts +29 -0
  184. package/src/util/markup.ts +144 -0
  185. package/src/util/maskControls.ts +6 -0
  186. package/src/util/templateLang.ts +145 -0
  187. package/src/util/templateUrls.ts +274 -0
  188. package/src/util/urlPolicy.ts +115 -0
  189. package/src/util/useCronPicker.ts +102 -0
  190. package/src/util/useDurationControl.ts +272 -0
  191. package/src/util/useEditorAppearance.ts +86 -0
  192. package/src/util/useExtendedTranslator.ts +25 -0
  193. package/src/util/useMonacoShadowStyles.ts +47 -0
@@ -0,0 +1,391 @@
1
+ import React, {
2
+ useLayoutEffect,
3
+ createContext,
4
+ useContext,
5
+ useRef,
6
+ } from 'react';
7
+ import type { JsonFormsCore, Middleware } from '@jsonforms/core';
8
+ import type { ErrorObject } from 'ajv';
9
+ import get from 'lodash/get';
10
+ import isEqual from 'lodash/isEqual';
11
+
12
+ /**
13
+ * Errors that have nothing to do with JSON Schema validation.
14
+ *
15
+ * A server rejects a submit and names two fields; a code editor's language
16
+ * service finds a syntax error; a host wants to mark a field from somewhere
17
+ * else entirely. JSON Forms calls these `additionalErrors` and treats them as
18
+ * first-class - `getErrorsAt` merges them with schema errors, and
19
+ * `validationMode` does not suppress them - but supplies no way for anything
20
+ * inside the form to produce one.
21
+ *
22
+ * This is that way. A **store**, owner-keyed, delivered through JSON Forms'
23
+ * own `middleware` hook.
24
+ *
25
+ * ```tsx
26
+ * const store = useRef(createAdditionalErrorStore()).current;
27
+ *
28
+ * <JsonForms {...useAdditionalErrorProps(store)} … />
29
+ *
30
+ * store.publish('server', response.validationErrors); // after a submit
31
+ * store.all(); // read them back
32
+ * ```
33
+ *
34
+ * `useAdditionalErrorProps` supplies **both** halves, and both are needed:
35
+ *
36
+ * | | Does |
37
+ * | --- | --- |
38
+ * | `additionalErrors` | Carries the published errors in. Middleware is passive - publishing dispatches nothing, so without a prop change the form would not re-reduce until the user happened to type. |
39
+ * | `middleware` | Clears on change, and merges. Only middleware sees `UPDATE` with the data before *and* after, which is what the clearing rule needs. |
40
+ *
41
+ * Neither alone is enough, and that is not an accident of this design: core
42
+ * offers no action a renderer or a host can dispatch to add an additional
43
+ * error, and no hook that fires when one should be withdrawn.
44
+ *
45
+ * ## What the store buys over passing the prop directly
46
+ *
47
+ * - **A renderer can publish**, because the store is reachable through context
48
+ * rather than through the host's props.
49
+ * - **Ownership.** One owner retracting cannot disturb another's errors, or
50
+ * the host's. Two editors on one path, or an editor beside a server error,
51
+ * coexist.
52
+ * - **Clearing is automatic:** the store applies the clear-on-change rule.
53
+ * - The errors are in core state, so `useJsonForms().core.additionalErrors`
54
+ * reads them - the point is having them *on the form*, not only under one
55
+ * control.
56
+ *
57
+ * **A host that already passes its own `additionalErrors` keeps working.**
58
+ * The middleware filters out only what this store produced and leaves the rest
59
+ * in place, so host-supplied errors and published ones coexist and neither
60
+ * clears the other.
61
+ *
62
+ * ## Clearing
63
+ *
64
+ * By default an owner's error is dropped when **the value at its own
65
+ * `instancePath` changes**. The store applies this clear-on-change rule in
66
+ * every form that uses it. Comparison is by value, not by the action's path,
67
+ * so an update that rewrites a field with what it already held clears nothing.
68
+ *
69
+ * An owner that manages its own lifecycle opts out with
70
+ * `{ clearOnChange: false }`. The Monaco control does: it republishes or
71
+ * retracts its summary as the language service reports, and a keystroke
72
+ * clearing it would make the message flicker.
73
+ */
74
+
75
+ /** Marks an error this store produced, so host-supplied ones are left alone. */
76
+ const OWNED = Symbol.for('jsonforms.additionalError.owner');
77
+
78
+ const isOwned = (error: ErrorObject): boolean =>
79
+ (error as unknown as Record<symbol, unknown>)[OWNED] !== undefined;
80
+
81
+ const ownerOf = (error: ErrorObject): string | undefined =>
82
+ (error as unknown as Record<symbol, string>)[OWNED];
83
+
84
+ export interface PublishOptions {
85
+ /**
86
+ * Drop these errors when the value at their `instancePath` changes.
87
+ * Default true.
88
+ */
89
+ clearOnChange?: boolean;
90
+ }
91
+
92
+ interface OwnerEntry {
93
+ errors: ErrorObject[];
94
+ clearOnChange: boolean;
95
+ }
96
+
97
+ /** Stable code, so a host can grep for it. */
98
+ export const NO_STORE_DIAGNOSTIC = 'additionalErrors.noStore';
99
+
100
+ export interface AdditionalErrorStore {
101
+ /**
102
+ * True for the placeholder a renderer gets outside a provider.
103
+ *
104
+ * A renderer that was *asked* to publish - Monaco with `propagateErrors` on
105
+ * - can then say so instead of going quiet, which is the difference between
106
+ * a host learning it forgot the wiring and a host concluding the option
107
+ * does not work.
108
+ */
109
+ readonly inert?: boolean;
110
+ /** Replaces everything this owner had published. An empty list retracts. */
111
+ publish: (
112
+ owner: string,
113
+ errors: ErrorObject[],
114
+ options?: PublishOptions,
115
+ ) => void;
116
+ /** Retracts one owner's errors. */
117
+ clear: (owner: string) => void;
118
+ /** Retracts everything - a fresh submit, for instance. */
119
+ clearAll: () => void;
120
+ /** Everything published, in publication order. */
121
+ all: () => ErrorObject[];
122
+ /** Called after any change; returns an unsubscribe. */
123
+ subscribe: (listener: () => void) => () => void;
124
+ /** Hand this to `<JsonForms middleware={…} />`. */
125
+ middleware: Middleware;
126
+ }
127
+
128
+ /** `/a/b/0/c` as lodash's `a.b.0.c`; the empty pointer is the whole document. */
129
+ const pathOf = (instancePath: string): string =>
130
+ instancePath.replace(/^\//, '').split('/').join('.');
131
+
132
+ const valueAt = (data: unknown, instancePath: string): unknown =>
133
+ instancePath === '' || instancePath === '/'
134
+ ? data
135
+ : get(data, pathOf(instancePath));
136
+
137
+ export const createAdditionalErrorStore = (): AdditionalErrorStore => {
138
+ const owners = new Map<string, OwnerEntry>();
139
+ const listeners = new Set<() => void>();
140
+ let snapshot: ErrorObject[] = [];
141
+
142
+ const rebuild = () => {
143
+ const next: ErrorObject[] = [];
144
+ owners.forEach((entry) => next.push(...entry.errors));
145
+ /*
146
+ Identity follows content. Anything reading this - a React subscription,
147
+ or the middleware deciding whether the state changed - would otherwise
148
+ see a change on every rebuild and re-render or re-dispatch forever.
149
+ */
150
+ if (!isEqual(next, snapshot)) {
151
+ snapshot = next;
152
+ listeners.forEach((listener) => listener());
153
+ return true;
154
+ }
155
+ return false;
156
+ };
157
+
158
+ const publish: AdditionalErrorStore['publish'] = (owner, errors, options) => {
159
+ if (errors.length === 0) {
160
+ if (owners.delete(owner)) {
161
+ rebuild();
162
+ }
163
+ return;
164
+ }
165
+ /*
166
+ Stamped on a copy, so a caller's array is never mutated and a host that
167
+ hands the same objects to something else is unaffected. The marker is a
168
+ `Symbol.for`, which cannot collide with a `params` key a host chose and
169
+ does not appear in JSON.
170
+ */
171
+ const stamped = errors.map((error) => {
172
+ const copy = { ...error } as ErrorObject;
173
+ (copy as unknown as Record<symbol, string>)[OWNED] = owner;
174
+ return copy;
175
+ });
176
+ owners.set(owner, {
177
+ errors: stamped,
178
+ clearOnChange: options?.clearOnChange !== false,
179
+ });
180
+ rebuild();
181
+ };
182
+
183
+ const clear: AdditionalErrorStore['clear'] = (owner) => {
184
+ if (owners.delete(owner)) {
185
+ rebuild();
186
+ }
187
+ };
188
+
189
+ const clearAll = () => {
190
+ if (owners.size > 0) {
191
+ owners.clear();
192
+ rebuild();
193
+ }
194
+ };
195
+
196
+ /**
197
+ * Drops the errors whose own value changed.
198
+ *
199
+ * Only owners that did not opt out, and only the individual errors that
200
+ * point at something that moved - one server error going does not take its
201
+ * siblings with it.
202
+ */
203
+ const pruneChanged = (before: unknown, after: unknown) => {
204
+ let changed = false;
205
+ owners.forEach((entry, owner) => {
206
+ if (!entry.clearOnChange) {
207
+ return;
208
+ }
209
+ const kept = entry.errors.filter((error) =>
210
+ isEqual(
211
+ valueAt(before, error.instancePath ?? ''),
212
+ valueAt(after, error.instancePath ?? ''),
213
+ ),
214
+ );
215
+ if (kept.length === entry.errors.length) {
216
+ return;
217
+ }
218
+ changed = true;
219
+ if (kept.length === 0) {
220
+ owners.delete(owner);
221
+ } else {
222
+ owners.set(owner, { ...entry, errors: kept });
223
+ }
224
+ });
225
+ if (changed) {
226
+ rebuild();
227
+ }
228
+ };
229
+
230
+ const middleware: Middleware = (state, action, defaultReducer) => {
231
+ const next = defaultReducer(state, action) as JsonFormsCore;
232
+
233
+ /*
234
+ `UPDATE_DATA` is spelled `jsonforms/UPDATE`. The published middleware
235
+ documentation names the constant, not the string, and the two do not
236
+ match - a filter written against `'jsonforms/UPDATE_DATA'` silently
237
+ never runs.
238
+ */
239
+ if (action?.type === 'jsonforms/UPDATE' && state !== next) {
240
+ pruneChanged(state?.data, next.data);
241
+ }
242
+
243
+ const published = snapshot;
244
+ /*
245
+ Whatever the host supplied stays: only errors this store produced are
246
+ replaced. That is what lets a form use the prop and this together, and
247
+ what stops one owner's retraction from taking another's - or the host's
248
+ - errors with it.
249
+ */
250
+ const hostErrors = (next.additionalErrors ?? []).filter(
251
+ (error) => !isOwned(error),
252
+ );
253
+ const combined =
254
+ published.length === 0 ? hostErrors : [...hostErrors, ...published];
255
+
256
+ if (
257
+ combined.length === (next.additionalErrors ?? []).length &&
258
+ combined.every((error, index) => error === next.additionalErrors?.[index])
259
+ ) {
260
+ return next;
261
+ }
262
+ return { ...next, additionalErrors: combined };
263
+ };
264
+
265
+ return {
266
+ publish,
267
+ clear,
268
+ clearAll,
269
+ all: () => snapshot,
270
+ subscribe: (listener) => {
271
+ listeners.add(listener);
272
+ return () => listeners.delete(listener);
273
+ },
274
+ middleware,
275
+ };
276
+ };
277
+
278
+ /** Which owner an error belongs to, or undefined for a host-supplied one. */
279
+ export const additionalErrorOwner = (error: ErrorObject): string | undefined =>
280
+ ownerOf(error);
281
+
282
+ const inertStore: AdditionalErrorStore = {
283
+ inert: true,
284
+ publish: () => undefined,
285
+ clear: () => undefined,
286
+ clearAll: () => undefined,
287
+ all: () => [],
288
+ subscribe: () => () => undefined,
289
+ middleware: (state, action, defaultReducer) => defaultReducer(state, action),
290
+ };
291
+
292
+ const StoreContext = createContext<AdditionalErrorStore>(inertStore);
293
+
294
+ export const AdditionalErrorStoreProvider = ({
295
+ store,
296
+ children,
297
+ }: {
298
+ store: AdditionalErrorStore;
299
+ children: React.ReactNode;
300
+ }) => <StoreContext.Provider value={store}>{children}</StoreContext.Provider>;
301
+
302
+ /**
303
+ * The store for the enclosing form, or an inert one.
304
+ *
305
+ * Inert rather than throwing, because a renderer must not require the host to
306
+ * have wired anything: publication is what a host opts into, and a renderer
307
+ * that also shows its diagnostic locally keeps doing so either way.
308
+ */
309
+ export const useAdditionalErrorStore = (): AdditionalErrorStore =>
310
+ useContext(StoreContext);
311
+
312
+ /**
313
+ * Publishes one owner's errors for as long as the component is mounted.
314
+ *
315
+ * Republished when the content changes, and **retracted on unmount** - an
316
+ * error left behind by a control that is no longer on the form would make it
317
+ * invalid with nothing on screen to explain why.
318
+ */
319
+ export const useOwnedAdditionalErrors = (
320
+ owner: string,
321
+ errors: ErrorObject[],
322
+ options?: PublishOptions,
323
+ ): void => {
324
+ const store = useAdditionalErrorStore();
325
+
326
+ /*
327
+ Publication is a host opt-in, so having no store is not an error - but a
328
+ renderer that has something to publish and nowhere to put it must say so.
329
+ Silence here reads as "the option does not work".
330
+ */
331
+ const wanted = errors.length > 0;
332
+ React.useEffect(() => {
333
+ if (!store.inert || !wanted) {
334
+ return;
335
+ }
336
+ // oxlint-disable-next-line no-console
337
+ console.warn(
338
+ `${NO_STORE_DIAGNOSTIC}: ${JSON.stringify(
339
+ owner,
340
+ )} has errors to publish, ` +
341
+ `but this form installed no additional-error store, so they will not ` +
342
+ `appear. Render the form with <ExtendedJsonForms>, or pass ` +
343
+ `useAdditionalErrorProps(store) to <JsonForms> and wrap it in ` +
344
+ `<AdditionalErrorStoreProvider>.`,
345
+ );
346
+ }, [store, owner, wanted]);
347
+ const latest = useRef({ errors, options });
348
+ useLayoutEffect(() => {
349
+ latest.current = { errors, options };
350
+ }, [errors, options]);
351
+
352
+ const signature = errors
353
+ .map((error) => `${error.instancePath}|${error.keyword}|${error.message}`)
354
+ .join('\u0000');
355
+ const clearOnChange = options?.clearOnChange !== false;
356
+
357
+ React.useEffect(() => {
358
+ store.publish(owner, latest.current.errors, latest.current.options);
359
+ }, [store, owner, signature, clearOnChange]);
360
+
361
+ React.useEffect(
362
+ () => () => {
363
+ store.clear(owner);
364
+ },
365
+ [store, owner],
366
+ );
367
+ };
368
+
369
+ /** Everything published, re-rendering the caller when it changes. */
370
+ export const useAdditionalErrors = (): ErrorObject[] => {
371
+ const store = useAdditionalErrorStore();
372
+ return React.useSyncExternalStore(store.subscribe, store.all, store.all);
373
+ };
374
+
375
+ /**
376
+ * Read by `ExtendedJsonForms`, which is how a form should install a store.
377
+ *
378
+ * There is no `useAdditionalErrorProps` for a host assembling `<JsonForms>`
379
+ * itself, and that is deliberate: delivering published errors through the
380
+ * `additionalErrors` **prop** undoes the edit that provoked them.
381
+ * `JsonFormsStateProvider` lists the prop in an effect's dependencies and
382
+ * re-dispatches `updateCore(data, …)` with the prop data of that render, while
383
+ * a renderer publishes from its own effect - which runs before the parent's
384
+ * `onChange` has told the host about the edit. The re-dispatch then carries
385
+ * the previous data.
386
+ *
387
+ * `ExtendedJsonForms` composes JSON Forms' own provider so it can dispatch
388
+ * from **inside**, where the data comes from core and is current by
389
+ * construction. A host that needs to assemble the form itself should copy that
390
+ * arrangement rather than reach for the prop.
391
+ */
@@ -0,0 +1,300 @@
1
+ import { Environment } from '@marcbachmann/cel-js';
2
+
3
+ /**
4
+ * The evaluator, with locale-aware formatting.
5
+ *
6
+ * ## Why formatting is functions rather than automatic
7
+ *
8
+ * A locale decides more than which words are shown: `148.5` is `148,50 €` in
9
+ * German and `€148.50` in English, and a date reads differently in every
10
+ * language. An expression language has none of that built in, so it is
11
+ * supplied here as functions the author calls explicitly.
12
+ *
13
+ * Explicit, because the alternative - formatting every number on its way into
14
+ * the text - cannot tell a price from an order number, a year or an id, and
15
+ * would render `2026` as `2,026`. There is no way to opt out of an implicit
16
+ * rule; there is nothing to opt out of with a function.
17
+ *
18
+ * They are part of the published contract: an author writing
19
+ * `{currency(amount, "EUR")}` in a catalog string is relying on them, and a
20
+ * renderer set that drops one breaks that string in every language.
21
+ *
22
+ * ## The locale comes from the form
23
+ *
24
+ * One environment per locale, cached, so switching language re-formats
25
+ * without re-parsing anything. `Intl` does the work, so there is no data to
26
+ * ship and the result matches the platform's own rendering.
27
+ */
28
+
29
+ /**
30
+ * A temporal value out of the form's data is **always a string**: `data` holds
31
+ * JSON, so a date is whatever the schema's `format` said it was, never a
32
+ * JavaScript `Date`. The three formats parse very differently, and treating
33
+ * them alike is wrong in two of the three cases.
34
+ *
35
+ * | value | `new Date(...)` | formatted in the viewer's zone |
36
+ * | --- | --- | --- |
37
+ * | `2026-10-01` | UTC midnight | **30 September** west of the meridian |
38
+ * | `14:30:00` | **Invalid Date** | - |
39
+ * | `2026-10-01T14:30:00+02:00` | the right instant | correct |
40
+ *
41
+ * So a **calendar date** is read and formatted in UTC, because it denotes a
42
+ * day rather than a moment and must not slide into the day before. A
43
+ * **time-only** value has no date to anchor it and is given one. A
44
+ * **date-time** denotes an instant, and an instant is shown in the reader's
45
+ * own zone - pinning it to UTC would display a time nobody asked for.
46
+ */
47
+ const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
48
+ const TIME_ONLY = /^\d{2}:\d{2}(:\d{2})?(\.\d+)?$/;
49
+
50
+ interface Instant {
51
+ date: Date;
52
+ /** `UTC` where the value denotes a day or a clock time rather than a moment. */
53
+ timeZone?: string;
54
+ }
55
+
56
+ const toInstant = (value: unknown): Instant => {
57
+ /*
58
+ A `Date` is accepted because host `context` may legitimately carry one.
59
+ It never comes from `data`.
60
+ */
61
+ if (value instanceof Date) {
62
+ return { date: value };
63
+ }
64
+ const text = String(value);
65
+ const parse = (iso: string, timeZone?: string): Instant => {
66
+ const date = new Date(iso);
67
+ if (Number.isNaN(date.getTime())) {
68
+ throw new Error(`not a date: ${text}`);
69
+ }
70
+ return { date, timeZone };
71
+ };
72
+ if (DATE_ONLY.test(text)) {
73
+ return parse(`${text}T00:00:00Z`, UTC);
74
+ }
75
+ if (TIME_ONLY.test(text)) {
76
+ // Any date will do; only the clock is shown.
77
+ return parse(`1970-01-01T${text}Z`, UTC);
78
+ }
79
+ return parse(text);
80
+ };
81
+
82
+ const UTC = 'UTC';
83
+
84
+ /** CEL integers arrive as `bigint`; `Intl` handles both, `Number()` is for safety. */
85
+ const toNumeric = (value: unknown): number | bigint =>
86
+ typeof value === 'bigint' ? value : Number(value);
87
+
88
+ const build = (locale: string): Environment =>
89
+ new Environment()
90
+ /*
91
+ Registered per numeric CEL type. A value read out of the form's data is
92
+ a `double` to CEL whether or not it has a fraction; a literal or the
93
+ result of `size()` is an `int`. Both have to be accepted or an author
94
+ has to know which is which, which is not knowable from the schema.
95
+ */
96
+ .registerFunction('number(double): string', (v: unknown) =>
97
+ new Intl.NumberFormat(locale).format(toNumeric(v)),
98
+ )
99
+ .registerFunction('number(int): string', (v: unknown) =>
100
+ new Intl.NumberFormat(locale).format(toNumeric(v)),
101
+ )
102
+ .registerFunction('number(double, int): string', (v: unknown, d: unknown) =>
103
+ new Intl.NumberFormat(locale, {
104
+ minimumFractionDigits: Number(d),
105
+ maximumFractionDigits: Number(d),
106
+ }).format(toNumeric(v)),
107
+ )
108
+ .registerFunction(
109
+ 'currency(double, string): string',
110
+ (v: unknown, code: unknown) =>
111
+ new Intl.NumberFormat(locale, {
112
+ style: 'currency',
113
+ currency: String(code),
114
+ }).format(toNumeric(v)),
115
+ )
116
+ .registerFunction(
117
+ 'currency(int, string): string',
118
+ (v: unknown, code: unknown) =>
119
+ new Intl.NumberFormat(locale, {
120
+ style: 'currency',
121
+ currency: String(code),
122
+ }).format(toNumeric(v)),
123
+ )
124
+ .registerFunction('percent(double): string', (v: unknown) =>
125
+ new Intl.NumberFormat(locale, { style: 'percent' }).format(toNumeric(v)),
126
+ )
127
+ .registerFunction('date(string): string', (v: unknown) => {
128
+ const { date, timeZone } = toInstant(v);
129
+ return new Intl.DateTimeFormat(locale, {
130
+ dateStyle: 'medium',
131
+ timeZone,
132
+ }).format(date);
133
+ })
134
+ .registerFunction('time(string): string', (v: unknown) => {
135
+ const { date, timeZone } = toInstant(v);
136
+ return new Intl.DateTimeFormat(locale, {
137
+ timeStyle: 'short',
138
+ timeZone,
139
+ }).format(date);
140
+ })
141
+ .registerFunction('dateTime(string): string', (v: unknown) => {
142
+ const { date, timeZone } = toInstant(v);
143
+ return new Intl.DateTimeFormat(locale, {
144
+ dateStyle: 'medium',
145
+ timeStyle: 'short',
146
+ timeZone,
147
+ }).format(date);
148
+ });
149
+
150
+ const environments = new Map<string, Environment>();
151
+
152
+ /** The base environment for a locale, built once. */
153
+ const environmentFor = (locale: string | undefined): Environment => {
154
+ const key = locale ?? 'en';
155
+ const existing = environments.get(key);
156
+ if (existing) {
157
+ return existing;
158
+ }
159
+ const created = build(key);
160
+ environments.set(key, created);
161
+ return created;
162
+ };
163
+
164
+ /**
165
+ * Evaluates one expression against a scope.
166
+ *
167
+ * Every name in the scope is declared as `dyn`, which is what an untyped
168
+ * evaluation already gives: measured against this library's own
169
+ * `evaluate()`, a `dyn` declaration accepts everything it accepts and refuses
170
+ * the same things - including `seats + 1`, where CEL will not mix a
171
+ * double-typed value with an integer literal. (`seats + 1.0` works.) So the
172
+ * typed environment costs nothing and is what makes the formatting functions
173
+ * reachable.
174
+ *
175
+ * Declaring the names also keeps the refusal: an identifier that is not in
176
+ * the scope is an error rather than a silent `undefined`.
177
+ */
178
+ /**
179
+ * `constructor` is a legal JSON key, and the evaluator cannot read an object
180
+ * that has one.
181
+ *
182
+ * Its type check is `switch (v.constructor)` with cases `undefined | Object |
183
+ * Map`, so a data property of that name shadows the constructor and the
184
+ * **whole map** is rejected - every sibling field becomes unreadable with it.
185
+ * Measured: only `constructor` does this; `__proto__`, `toString`, `valueOf`
186
+ * and `hasOwnProperty` as data keys are fine.
187
+ *
188
+ * A `Map` is the repair, because its entries live in an internal slot and
189
+ * cannot shadow `.constructor` - `Map` is already one of the accepted cases,
190
+ * and a key called `constructor` then reads like any other.
191
+ */
192
+ const toMaps = (value: unknown): unknown => {
193
+ if (Array.isArray(value)) {
194
+ return value.map(toMaps);
195
+ }
196
+ if (
197
+ value !== null &&
198
+ typeof value === 'object' &&
199
+ !(value instanceof Date) &&
200
+ !(value instanceof Map)
201
+ ) {
202
+ return new Map(
203
+ Object.entries(value as Record<string, unknown>).map(([key, child]) => [
204
+ key,
205
+ toMaps(child),
206
+ ]),
207
+ );
208
+ }
209
+ return value;
210
+ };
211
+
212
+ const isUnsupportedObject = (error: unknown): boolean =>
213
+ error instanceof Error &&
214
+ error.message.startsWith('Unsupported type: object');
215
+
216
+ /**
217
+ * Evaluates one expression against a scope.
218
+ *
219
+ * Every name in the scope is declared as `dyn`, which is what an untyped
220
+ * evaluation already gives: measured against this library's own
221
+ * `evaluate()`, a `dyn` declaration accepts everything it accepts and refuses
222
+ * the same things - including `seats + 1`, where CEL will not mix a
223
+ * double-typed value with an integer literal. (`seats + 1.0` works.) So the
224
+ * typed environment costs nothing and is what makes the formatting functions
225
+ * reachable.
226
+ *
227
+ * Declaring the names also keeps the refusal: an identifier that is not in
228
+ * the scope is an error rather than a silent `undefined`.
229
+ *
230
+ * **The repair runs only after the one failure it fixes.** Data is read as
231
+ * it arrives, so the ordinary path converts nothing; an object carrying a
232
+ * `constructor` key is rebuilt as maps and the expression is tried once
233
+ * more. Converting up front would mean walking the whole form's data on
234
+ * every label of every render to serve a case almost no schema has.
235
+ */
236
+ /** The form's translator, as JSON Forms supplies it. */
237
+ export type Translate = (
238
+ key: string,
239
+ defaultMessage?: string,
240
+ ) => string | undefined;
241
+
242
+ /**
243
+ * Registers `translate`, bound to this form's translator.
244
+ *
245
+ * It has to be **registered** rather than passed in the scope, and that is
246
+ * the whole point: a function placed in `context` is not callable, is not
247
+ * even readable, and no expression can reach it. Measured - a member call
248
+ * finds no overload, a bare call finds no overload, and reading it is an
249
+ * unsupported type. So a host cannot widen what an expression can do by
250
+ * putting a callback in the data, deliberately or by accident. Capability is
251
+ * granted here, in one place, on purpose.
252
+ *
253
+ * What it buys: a value out of the data is often a **key**, not a word.
254
+ * `data.plan` is `"Team"` in every language, and `{translate("plan." + plan)}`
255
+ * turns it into the language's own word for it - which a catalog can do for
256
+ * itself, without the UI schema knowing the set of plans.
257
+ *
258
+ * Registered on the per-call clone rather than the cached environment,
259
+ * because the translator belongs to the form while the environment is shared
260
+ * by locale.
261
+ */
262
+ const withTranslator = (env: Environment, translate: Translate): Environment =>
263
+ env
264
+ .registerFunction('translate(string): string', (key: unknown) =>
265
+ String(translate(String(key), String(key)) ?? String(key)),
266
+ )
267
+ .registerFunction(
268
+ 'translate(string, string): string',
269
+ (key: unknown, fallback: unknown) =>
270
+ String(translate(String(key), String(fallback)) ?? String(fallback)),
271
+ );
272
+
273
+ export const evaluateWith = (
274
+ expression: string,
275
+ scope: Record<string, unknown>,
276
+ locale: string | undefined,
277
+ translate?: Translate,
278
+ ): unknown => {
279
+ const declared = (values: Record<string, unknown>) => {
280
+ let env = environmentFor(locale).clone();
281
+ if (translate) {
282
+ env = withTranslator(env, translate);
283
+ }
284
+ for (const name of Object.keys(values)) {
285
+ env.registerVariable(name, 'dyn');
286
+ }
287
+ return env;
288
+ };
289
+ try {
290
+ return declared(scope).evaluate(expression, scope);
291
+ } catch (error) {
292
+ if (!isUnsupportedObject(error)) {
293
+ throw error;
294
+ }
295
+ const repaired = Object.fromEntries(
296
+ Object.entries(scope).map(([name, value]) => [name, toMaps(value)]),
297
+ );
298
+ return declared(repaired).evaluate(expression, repaired);
299
+ }
300
+ };