@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,203 @@
1
+ import type { Localize } from 'ajv-i18n/localize/types';
2
+
3
+ // Each AJV keyword has its own Bulgarian message and grammatical forms.
4
+ // fallow-ignore-next-line complexity
5
+ export const localize_bg: Localize = (errors) => {
6
+ if (!(errors && errors.length)) return;
7
+ for (const e of errors) {
8
+ let out;
9
+ let n;
10
+ let cond;
11
+ switch (e.keyword) {
12
+ case 'additionalItems':
13
+ case 'items':
14
+ out = '';
15
+ n = e.params.limit;
16
+ out += 'не трябва да има повече от ' + n + ' елемент';
17
+ if (n != 1) {
18
+ out += 'а';
19
+ }
20
+ break;
21
+ case 'additionalProperties':
22
+ out = 'не трябва да има допълнителни полета';
23
+ break;
24
+ case 'anyOf':
25
+ out = 'трябва да съответства на схема в "anyOf"';
26
+ break;
27
+ case 'const':
28
+ out = 'трябва да бъде равно на константа';
29
+ break;
30
+ case 'contains':
31
+ out = 'трябва да съдържа валиден елемент';
32
+ break;
33
+ case 'dependencies':
34
+ case 'dependentRequired':
35
+ out = '';
36
+ n = e.params.depsCount;
37
+ out += 'трябва да има поле';
38
+ if (n != 1) {
39
+ out += 'та';
40
+ }
41
+ out +=
42
+ ' ' +
43
+ e.params.deps +
44
+ ' когато полето ' +
45
+ e.params.property +
46
+ ' е налично';
47
+ break;
48
+ case 'discriminator':
49
+ switch (e.params.error) {
50
+ case 'tag':
51
+ out = 'полето "' + e.params.tag + '" трябва да бъде низ';
52
+ break;
53
+ case 'mapping':
54
+ out =
55
+ 'стойноста на полето "' +
56
+ e.params.tag +
57
+ '" трябва да бъде в oneOf';
58
+ break;
59
+ default:
60
+ out =
61
+ 'трябва да премине валидацията на ключовата дума "' +
62
+ e.keyword +
63
+ '"';
64
+ }
65
+ break;
66
+ case 'enum':
67
+ out = 'трябва да бъде равно на едно от разрешените стойности';
68
+ break;
69
+ case 'false schema':
70
+ out = 'схемата е равна на false';
71
+ break;
72
+ case 'format':
73
+ out = 'трябва да съответства на формата "' + e.params.format + '"';
74
+ break;
75
+ case 'formatMaximum':
76
+ case 'formatExclusiveMaximum':
77
+ out = '';
78
+ cond = e.params.comparison + ' ' + e.params.limit;
79
+ out += 'трябва да бъде ' + cond;
80
+ break;
81
+ case 'formatMinimum':
82
+ case 'formatExclusiveMinimum':
83
+ out = '';
84
+ cond = e.params.comparison + ' ' + e.params.limit;
85
+ out += 'трябва да бъде ' + cond;
86
+ break;
87
+ case 'if':
88
+ out =
89
+ 'трябва да съответства на схемата "' + e.params.failingKeyword + '"';
90
+ break;
91
+ case 'maximum':
92
+ case 'exclusiveMaximum':
93
+ out = '';
94
+ cond = e.params.comparison + ' ' + e.params.limit;
95
+ out += 'трябва да бъде ' + cond;
96
+ break;
97
+ case 'maxItems':
98
+ out = '';
99
+ n = e.params.limit;
100
+ out += 'не трябва да има повече от ' + n + ' елемент';
101
+ if (n != 1) {
102
+ out += 'а';
103
+ }
104
+ break;
105
+ case 'maxLength':
106
+ out = '';
107
+ n = e.params.limit;
108
+ out += 'не трябва да бъде по-дълго от ' + n + ' символ';
109
+ if (n != 1) {
110
+ out += 'а';
111
+ }
112
+ break;
113
+ case 'maxProperties':
114
+ out = '';
115
+ n = e.params.limit;
116
+ out += 'не трябва да има повече от ' + n + ' поле';
117
+ if (n != 1) {
118
+ out += 'та';
119
+ }
120
+ break;
121
+ case 'minimum':
122
+ case 'exclusiveMinimum':
123
+ out = '';
124
+ cond = e.params.comparison + ' ' + e.params.limit;
125
+ out += 'трябва да бъде ' + cond;
126
+ break;
127
+ case 'minItems':
128
+ out = '';
129
+ n = e.params.limit;
130
+ out += 'не трябва да има по-малко от ' + n + ' елемент';
131
+ if (n != 1) {
132
+ out += 'а';
133
+ }
134
+ break;
135
+ case 'minLength':
136
+ out = '';
137
+ n = e.params.limit;
138
+ out += 'не трябва да бъде по-късо от ' + n + ' символ';
139
+ if (n != 1) {
140
+ out += 'а';
141
+ }
142
+ break;
143
+ case 'minProperties':
144
+ out = '';
145
+ n = e.params.limit;
146
+ out += 'не трябва да има по-малко от ' + n + ' поле';
147
+ if (n != 1) {
148
+ out += 'та';
149
+ }
150
+ break;
151
+ case 'multipleOf':
152
+ out = 'трябва да бъде кратно на ' + e.params.multipleOf;
153
+ break;
154
+ case 'not':
155
+ out = 'не трябва да бъде валидно съгласно схемата в "not"';
156
+ break;
157
+ case 'oneOf':
158
+ out = 'трябва да съответства точно на една схема в "oneOf"';
159
+ break;
160
+ case 'pattern':
161
+ out = 'трябва да съответства на шаблон "' + e.params.pattern + '"';
162
+ break;
163
+ case 'patternRequired':
164
+ out =
165
+ 'трябва да има поле, което съответства на шаблон "' +
166
+ e.params.missingPattern +
167
+ '"';
168
+ break;
169
+ case 'propertyNames':
170
+ out = 'името на полето е невалидно';
171
+ break;
172
+ case 'required':
173
+ out = 'трябва да има задължително поле ' + e.params.missingProperty;
174
+ break;
175
+ case 'type':
176
+ out = 'трябва да бъде ' + e.params.type;
177
+ break;
178
+ case 'unevaluatedItems':
179
+ out = '';
180
+ n = e.params.len;
181
+ out += 'не трябва да има повече от ' + n + ' елемент';
182
+ if (n != 1) {
183
+ out += 'а';
184
+ }
185
+ break;
186
+ case 'unevaluatedProperties':
187
+ out = 'не трябва да има непроверени полета';
188
+ break;
189
+ case 'uniqueItems':
190
+ out =
191
+ 'не трябва да има дублиращи се елементи (елементи ## ' +
192
+ e.params.j +
193
+ ' и ' +
194
+ e.params.i +
195
+ ' са идентични)';
196
+ break;
197
+ default:
198
+ out =
199
+ 'трябва да премине валидацията на ключовата дума "' + e.keyword + '"';
200
+ }
201
+ e.message = out;
202
+ }
203
+ };
@@ -0,0 +1,267 @@
1
+ import type { ErrorTranslator, JsonFormsI18nState } from '@jsonforms/core';
2
+ import type Ajv from 'ajv';
3
+ import type { ErrorObject, ValidateFunction } from 'ajv';
4
+ import { defaultErrorTranslator } from '@jsonforms/core';
5
+ import { localize_bg } from './bg';
6
+
7
+ /**
8
+ * Localized validator messages, and `errorMessage` unwrapping.
9
+ *
10
+ * Two jobs that have to happen together, because both rewrite `errors` after
11
+ * a validation and each would undo the other if they ran separately:
12
+ *
13
+ * 1. **Translate Ajv's own messages** through `ajv-i18n`, so `must be >= 5`
14
+ * arrives in the form's language.
15
+ * 2. **Unwrap `ajv-errors`.** When a schema carries `errorMessage`, ajv-errors
16
+ * replaces the failures it covers with a single `errorMessage` error and
17
+ * marks the originals `emUsed`. Left alone, that collapses several
18
+ * per-property errors into one at the object's path - and JSON Forms maps
19
+ * errors to controls **by path**, so the fields stop showing them. Unwrapping
20
+ * restores the original errors and puts the schema's message on each.
21
+ *
22
+ * ## How this differs from the Vue 2 original
23
+ *
24
+ * The original takes a Vue `Ref` and sets each unwrapped message to a
25
+ * `computed()`, relying on the template to unwrap it on read. That is not
26
+ * portable: a JSON Forms `ErrorObject.message` is a `string`, and anything
27
+ * else reaches React as an object and renders as `[object Object]`.
28
+ *
29
+ * Here the translator is a **getter**, called at validation time, and the
30
+ * message is a plain string. The practical difference is when the message is
31
+ * resolved - on validation rather than on render - so a locale change has to
32
+ * revalidate to retranslate. JSON Forms already revalidates on an i18n change,
33
+ * so this costs nothing in the normal case and removes a Vue dependency from
34
+ * the contract.
35
+ */
36
+
37
+ /** Ajv's localizers, keyed by language: what `ajv-i18n/localize` exports. */
38
+ export type AjvLocalizers = Record<
39
+ string,
40
+ ((errors: unknown) => void) | undefined
41
+ >;
42
+
43
+ export interface AjvI18nOptions {
44
+ /**
45
+ * The current i18n state, read at validation time.
46
+ *
47
+ * A getter rather than a value because one Ajv instance outlives many
48
+ * locales; capturing the state would freeze the first one.
49
+ */
50
+ i18n?: () => JsonFormsI18nState | undefined;
51
+ /**
52
+ * Ajv's own message localizers.
53
+ *
54
+ * Supplied by the caller, and **not** imported here on purpose: importing
55
+ * `ajv-i18n/localize` pulls every language it ships into the bundle whether
56
+ * the form has a translator or not. `ajvLocalizers` in `./localizers` is the
57
+ * one-line way to ask for all of them.
58
+ */
59
+ localizers?: AjvLocalizers;
60
+ }
61
+
62
+ /**
63
+ * Bulgarian, which `ajv-i18n` does not ship.
64
+ *
65
+ * Upstream PR ajv-validator/ajv-i18n#312 has not landed. The `required`
66
+ * message is overridden after the base localizer runs, because the shipped
67
+ * form interpolates `missingProperty` - an untranslated property name - into
68
+ * the sentence.
69
+ */
70
+ export const localizeBg: NonNullable<AjvLocalizers[string]> = (errors) => {
71
+ const list = errors as ErrorObject[] | undefined;
72
+ if (!list?.length) {
73
+ return;
74
+ }
75
+ localize_bg(list);
76
+ for (const error of list) {
77
+ if (error.keyword === 'required') {
78
+ error.message = 'полето е задължително';
79
+ }
80
+ }
81
+ };
82
+
83
+ /** The localizer for a locale, falling back from `bg-BG` to `bg`. */
84
+ const localizerFor = (
85
+ localizers: AjvLocalizers,
86
+ locale: string | undefined,
87
+ ): AjvLocalizers[string] => {
88
+ if (!locale) {
89
+ return undefined;
90
+ }
91
+ return localizers[locale] ?? localizers[locale.split('-')[0]];
92
+ };
93
+
94
+ /**
95
+ * Expands `ajv-errors` wrappers back into the errors they replaced.
96
+ *
97
+ * Each recovered error keeps its own `instancePath`, so it still reaches the
98
+ * control it belongs to, and takes the schema's message. That message is run
99
+ * through the form's translator under `error.errorMessage.<message>`, so a
100
+ * schema can carry a key rather than a sentence; a message that resolves to
101
+ * nothing is used literally, which is the same rule the rest of this renderer
102
+ * set applies to labels.
103
+ */
104
+ export const unwrapErrorMessageErrors = (
105
+ errors: ErrorObject[] | null | undefined,
106
+ i18n?: () => JsonFormsI18nState | undefined,
107
+ ): ErrorObject[] => {
108
+ if (!errors?.length) {
109
+ return errors ?? [];
110
+ }
111
+ const translate = i18n?.()?.translate;
112
+ return errors
113
+ .filter((error) => (error as { emUsed?: boolean }).emUsed !== true)
114
+ .flatMap((error) => {
115
+ const covered = (error.params as { errors?: ErrorObject[] } | undefined)
116
+ ?.errors;
117
+ if (error.keyword !== 'errorMessage' || !Array.isArray(covered)) {
118
+ return error;
119
+ }
120
+ const message = error.message;
121
+ const translated =
122
+ translate && message
123
+ ? translate(schemaMessageKey(message), message)
124
+ : message;
125
+ /*
126
+ Marked so the render-time translator leaves them alone: the message is
127
+ the schema author's, and a localizer would regenerate Ajv's own
128
+ wording for the keyword they replaced.
129
+ */
130
+ return covered.map((inner) => ({
131
+ ...inner,
132
+ message: translated,
133
+ [SCHEMA_MESSAGE]: message,
134
+ })) as ErrorObject[];
135
+ });
136
+ };
137
+
138
+ /**
139
+ * Carries the **untranslated** message a schema's `errorMessage` supplied.
140
+ *
141
+ * Two things need it. A host using only the validation-time path reads
142
+ * `error.message`, which is already translated. A host using
143
+ * {@link createAjvErrorTranslator} needs the original key, because the locale
144
+ * may have changed since the validation that produced the error and core does
145
+ * not revalidate when it does.
146
+ *
147
+ * A `Symbol.for`, so it survives the error being copied between module
148
+ * instances - the same reasoning as `ElementRender`.
149
+ */
150
+ export const SCHEMA_MESSAGE = Symbol.for('jsonforms.ajv.schemaMessage');
151
+
152
+ /** The catalog key a schema-authored message is looked up under. */
153
+ export const schemaMessageKey = (message: string) =>
154
+ `error.errorMessage.${message}`;
155
+
156
+ /**
157
+ * Localizes an error **when it is rendered**, which is core's own hook for it.
158
+ *
159
+ * Prefer this to the `localizers` option below wherever the form can change
160
+ * language without the data changing. The difference is when the message is
161
+ * produced:
162
+ *
163
+ * | | Produced | A locale change |
164
+ * | --- | --- | --- |
165
+ * | `createFormsAjv({ localizers })` | at **validation** | shows the old language until something revalidates |
166
+ * | this, as `i18n.translateError` | at **render** | takes effect immediately |
167
+ *
168
+ * That second row is not a detail. JSON Forms does **not** revalidate when the
169
+ * locale changes - verified - so a form whose data is untouched goes on
170
+ * displaying the previous language. The validation-time path exists because
171
+ * the Vue 2 original works that way and it needs no extra wiring; this is the
172
+ * one to reach for when the switch has to be visible.
173
+ *
174
+ * The two are safe together: `ajv-i18n` regenerates a message from the error's
175
+ * `keyword` and `params` rather than editing the existing text, so localizing
176
+ * twice is idempotent.
177
+ */
178
+ export const createAjvErrorTranslator = (
179
+ localizers: AjvLocalizers,
180
+ getLocale: () => string | undefined,
181
+ ): ErrorTranslator => {
182
+ return (error, translate, uischema) => {
183
+ /*
184
+ The schema's own message. Re-translated here rather than reused, because
185
+ `error.message` was translated at validation time and the locale may
186
+ have moved since - which is the whole reason this hook is preferred.
187
+ It is never handed to a localizer: the author has already replaced Ajv's
188
+ wording for that keyword.
189
+ */
190
+ const authored = (error as unknown as Record<symbol, unknown>)[
191
+ SCHEMA_MESSAGE
192
+ ];
193
+ if (typeof authored === 'string') {
194
+ return translate(schemaMessageKey(authored), authored) ?? authored;
195
+ }
196
+ const localize = localizerFor(localizers, getLocale());
197
+ if (!localize) {
198
+ return defaultErrorTranslator(error, translate, uischema);
199
+ }
200
+ /*
201
+ On a copy: the error objects live in the JSON Forms store, and localizing
202
+ in place would rewrite state during a render and leave the message stuck
203
+ in whichever language rendered first.
204
+ */
205
+ const copy = { ...error } as ErrorObject;
206
+ localize([copy]);
207
+ // Preserve JSON Forms field/keyword overrides before using localized AJV text.
208
+ return defaultErrorTranslator(copy, translate, uischema);
209
+ };
210
+ };
211
+
212
+ /**
213
+ * Wraps `ajv.compile` so every validation's errors are localized and unwrapped.
214
+ *
215
+ * Ajv exposes no hook after validation, so the compiled function is wrapped.
216
+ * The wrapper copies `errors` back onto itself after each call because callers
217
+ * - JSON Forms among them - read `validate.errors`, not the return value.
218
+ */
219
+ export const ajvTranslations = (
220
+ ajv: Ajv,
221
+ options: AjvI18nOptions = {},
222
+ ): Ajv => {
223
+ const localizers = options.localizers;
224
+ const compile = ajv.compile.bind(ajv) as Ajv['compile'];
225
+
226
+ const wrapped = ((...args: Parameters<Ajv['compile']>) => {
227
+ const validate = compile(...args) as ValidateFunction;
228
+
229
+ const wrapper = ((...data: unknown[]) => {
230
+ const valid = (validate as (...d: unknown[]) => boolean)(...data);
231
+ /*
232
+ Copied every call, not once: Ajv sets `errors`, `evaluated` and friends
233
+ on the compiled function itself, and a caller reads them from whatever
234
+ it was handed - which is this wrapper.
235
+ */
236
+ Object.assign(wrapper, validate);
237
+ if (!valid && validate.errors) {
238
+ const localize = localizers
239
+ ? localizerFor(localizers, options.i18n?.()?.locale)
240
+ : undefined;
241
+ if (localize) {
242
+ /*
243
+ `errorMessage` errors are excluded: their text comes from the
244
+ schema, and a localizer would overwrite it with Ajv's own wording
245
+ for a keyword the author has already replaced.
246
+ */
247
+ localize(
248
+ validate.errors.filter((error) => error.keyword !== 'errorMessage'),
249
+ );
250
+ }
251
+ wrapper.errors = unwrapErrorMessageErrors(
252
+ validate.errors,
253
+ options.i18n,
254
+ );
255
+ } else {
256
+ wrapper.errors = validate.errors;
257
+ }
258
+ return valid;
259
+ }) as ValidateFunction;
260
+
261
+ Object.assign(wrapper, validate);
262
+ return wrapper;
263
+ }) as Ajv['compile'];
264
+
265
+ ajv.compile = wrapped;
266
+ return ajv;
267
+ };
@@ -0,0 +1,25 @@
1
+ import localize from 'ajv-i18n/localize';
2
+ import { AjvLocalizers, localizeBg } from './index';
3
+
4
+ /**
5
+ * Every language `ajv-i18n` ships, plus Bulgarian.
6
+ *
7
+ * **In a module of its own, deliberately.** `ajv-i18n/localize` re-exports
8
+ * around twenty locales, and importing it costs that whether or not the form
9
+ * has a translator. Keeping it out of `createFormsAjv`'s import graph means a
10
+ * form that does not localize validator messages does not pay for the ability:
11
+ *
12
+ * ```ts
13
+ * import { createFormsAjv } from '@chobantonov/jsonforms-react-extended-renderers';
14
+ * import { ajvLocalizers } from '@chobantonov/jsonforms-react-extended-renderers/localizers';
15
+ *
16
+ * createFormsAjv({ i18n: () => i18nState, localizers: ajvLocalizers });
17
+ * ```
18
+ *
19
+ * A host that ships two languages can pass `{ en: ajvLocalizers.en, bg: localizeBg }`
20
+ * instead and carry neither the rest nor this module.
21
+ */
22
+ export const ajvLocalizers: AjvLocalizers = {
23
+ ...(localize as unknown as AjvLocalizers),
24
+ bg: localizeBg,
25
+ };
@@ -0,0 +1,170 @@
1
+ import dayjs, { UnitType } from 'dayjs';
2
+ import customParsingPlugin from 'dayjs/plugin/customParseFormat';
3
+ import durationPlugin from 'dayjs/plugin/duration';
4
+ import timezonePlugin from 'dayjs/plugin/timezone'; // dependent on the utc plugin
5
+ import utcPlugin from 'dayjs/plugin/utc';
6
+
7
+ /**
8
+ * Extra `dynamicDefaults` generators, ported from the Vue 2 `common` package.
9
+ *
10
+ * `ajv-keywords`' `dynamicDefaults` ships `timestamp`, `datetime`, `date`,
11
+ * `time`, `random`, `randomint` and `seq`. The set below replaces the temporal
12
+ * ones with offset-aware versions - `{ "func": "date", "args": { "duration":
13
+ * "P1D" } }` is "tomorrow" - and adds `searchParams` and `dynamic`.
14
+ *
15
+ * Unlike the rest of the validator profile these **write into the data**, so
16
+ * they only run under `useDefaults`.
17
+ */
18
+
19
+ // Required for the custom save formats in the date, time and date-time pickers.
20
+ dayjs.extend(customParsingPlugin);
21
+ dayjs.extend(utcPlugin);
22
+ dayjs.extend(timezonePlugin);
23
+ dayjs.extend(durationPlugin);
24
+
25
+ type Generator = (args: unknown) => () => unknown;
26
+
27
+ const arg = (args: unknown, name: string): string | undefined => {
28
+ const value = (args as Record<string, unknown> | undefined)?.[name];
29
+ return typeof value === 'string' ? value : undefined;
30
+ };
31
+
32
+ /**
33
+ * A default computed by a function **written in the schema**.
34
+ *
35
+ * ```json
36
+ * { "dynamicDefaults": { "ref": { "func": "dynamic", "args": { "func": "(a) => a.x" } } } }
37
+ * ```
38
+ *
39
+ * The Vue 2 original compiles that string with `new Function` unconditionally.
40
+ * Here it is gated: a schema is data, it can arrive with the form, and
41
+ * compiling a string out of it is the same capability the template engines and
42
+ * `Button.script` need permission for. Section 14 is explicit - "String
43
+ * evaluation requires `jsonformsExtended.security.allowScriptEvaluation=true`"
44
+ * - and there is no reason this one entry point should be the exception.
45
+ *
46
+ * Without the permission it is **reported, not silently skipped**: a default
47
+ * that quietly does not appear is indistinguishable from a schema that never
48
+ * asked for one.
49
+ */
50
+ export const makeDynamic = (
51
+ allowScriptEvaluation: () => boolean,
52
+ ): Generator => {
53
+ return (args: unknown) => {
54
+ const source = arg(args, 'func');
55
+ if (!source) {
56
+ throw new Error(
57
+ `missing argument 'func' for dynamicDefaults func 'dynamic'`,
58
+ );
59
+ }
60
+ if (!allowScriptEvaluation()) {
61
+ // oxlint-disable-next-line no-console
62
+ console.warn(
63
+ `dynamicDefaults.evaluationDisabled: the 'dynamic' default compiles a ` +
64
+ `function from the schema, which requires ` +
65
+ `jsonformsExtended.security.allowScriptEvaluation. No default was applied.`,
66
+ );
67
+ return () => undefined;
68
+ }
69
+ try {
70
+ const compiled = new Function(
71
+ 'args',
72
+ `const func = ${source}; return func(args);`,
73
+ );
74
+ return () => {
75
+ try {
76
+ return compiled(args);
77
+ } catch (error) {
78
+ // oxlint-disable-next-line no-console
79
+ console.error(`Error at dynamicDefaults 'dynamic': ${error}`);
80
+ return undefined;
81
+ }
82
+ };
83
+ } catch (error) {
84
+ // oxlint-disable-next-line no-console
85
+ console.error(`Error at dynamicDefaults 'dynamic': ${error}`);
86
+ return () => undefined;
87
+ }
88
+ };
89
+ };
90
+
91
+ /**
92
+ * A default taken from the page's query string, including one after the hash.
93
+ *
94
+ * Guarded for a non-browser host: this package is rendered in jsdom by its own
95
+ * tests and may be server-rendered, where `window` is absent and the original
96
+ * threw.
97
+ */
98
+ export const searchParams: Generator = (args: unknown) => {
99
+ const name = arg(args, 'param');
100
+ if (!name || typeof window === 'undefined' || !window.location) {
101
+ return () => undefined;
102
+ }
103
+
104
+ const url = new URL(window.location.href);
105
+ let result = url.searchParams.get(name) ?? undefined;
106
+
107
+ if (result === undefined) {
108
+ // Also after the hash, where a hash-routed application puts them.
109
+ const hash = url.hash;
110
+ const index = hash.indexOf('?');
111
+ if (index > 0 && index < hash.length - 1) {
112
+ result =
113
+ new URLSearchParams(hash.substring(index + 1)).get(name) ?? undefined;
114
+ }
115
+ }
116
+
117
+ return () => result;
118
+ };
119
+
120
+ /**
121
+ * "now", optionally shifted by an ISO 8601 duration.
122
+ *
123
+ * `{ "date": "2024-01-01", "duration": "P1M", "op": "subtract" }`. `date`
124
+ * defaults to now, and the literal string `"now"` means the same thing.
125
+ */
126
+ const nowOffset = (args: unknown) => {
127
+ const duration = arg(args, 'duration');
128
+ const supplied = arg(args, 'date');
129
+ const date: string | Date =
130
+ supplied && supplied !== 'now' ? supplied : new Date();
131
+
132
+ /*
133
+ `subtract`, and the original's misspelling. The Vue 2 version compares
134
+ against `'substract'`, so every schema written against it spells it that
135
+ way; accepting only the correct spelling would break them, and accepting
136
+ only the misspelling would enshrine it.
137
+ */
138
+ const op = arg(args, 'op');
139
+ const subtracting = op === 'subtract' || op === 'substract';
140
+
141
+ let value = dayjs(date);
142
+ if (value.isValid() && duration) {
143
+ const offset = dayjs.duration(duration);
144
+ value = subtracting ? value.subtract(offset) : value.add(offset);
145
+ }
146
+ return value;
147
+ };
148
+
149
+ const temporal =
150
+ (format: string): Generator =>
151
+ (args: unknown) => {
152
+ const value = nowOffset(args);
153
+ const result = value.isValid() ? value.local().format(format) : undefined;
154
+ return () => result;
155
+ };
156
+
157
+ export const datetimeOffset = temporal('YYYY-MM-DDTHH:mm:ss.SSS');
158
+ export const timeOffset = temporal('HH:mm:ss.SSS');
159
+ export const dateOffset = temporal('YYYY-MM-DD');
160
+
161
+ /** One component of the offset date - `{ "unit": "year" }`. */
162
+ export const dateUnit: Generator = (args: unknown) => {
163
+ const value = nowOffset(args);
164
+ if (!value.isValid()) {
165
+ return () => undefined;
166
+ }
167
+ const unit = (arg(args, 'unit') ?? 'millisecond') as UnitType;
168
+ const result = value.local().get(unit);
169
+ return () => result;
170
+ };