@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,327 @@
1
+ import { useI18n } from '@chobantonov/jsonforms-react-renderer-common/locale/translate';
2
+ import type { ItemContext } from '@chobantonov/jsonforms-react-renderer-common/cells/CellSummary';
3
+ import {
4
+ LabelProps,
5
+ RankedTester,
6
+ UISchemaElement,
7
+ rankWith,
8
+ uiTypeIs,
9
+ } from '@jsonforms/core';
10
+ import React, { Suspense, lazy } from 'react';
11
+ import { useJsonForms, withJsonFormsLabelProps } from '@jsonforms/react';
12
+ import { LoadBoundary } from '../util/lazyControl';
13
+ import {
14
+ buildNamespaceScope,
15
+ dynamicValuesEnabled,
16
+ hasExpressions,
17
+ reservedParamNames,
18
+ splitTemplate,
19
+ wantsInterpolation,
20
+ } from '../util/interpolate';
21
+ import { escapeMarkdown } from '../util/markdownEscape';
22
+ import { markdownProfile, resolveMarkup } from '../util/markup';
23
+ import { InterpolatedText } from '../components/InterpolatedText';
24
+ import { resolveUrlPolicy } from '../util/urlPolicy';
25
+ import { useExtendedTranslator } from '../util/useExtendedTranslator';
26
+ import type { MarkdownTextProps } from './MarkupLabelRenderer.impl';
27
+
28
+ /**
29
+ * A `Label` whose text is more than a string.
30
+ *
31
+ * ## Why this is not a new element type
32
+ *
33
+ * It would have been simpler to define `MarkdownLabel` and give it its own
34
+ * tester. It would also have been unusable: an element type nothing in the
35
+ * base renderer set knows renders as **nothing at all**, so a form authored
36
+ * against the extended set and opened on the base one would lose the text
37
+ * entirely. `Label` with `options.markup` degrades instead - the base renderer
38
+ * still claims it at rank 1 and still shows the text, unparsed. Section 1's
39
+ * "unknown options are preserved and ignored" is what makes that work, and it
40
+ * only works for options, not for types.
41
+ */
42
+
43
+ /**
44
+ * Whether this element asks for markup or interpolation.
45
+ *
46
+ * Reads the **requested** values, not the resolved ones, so a request the
47
+ * host has switched off still lands here and can be reported. Leaving it to
48
+ * the base renderer would render the source silently, which is the failure
49
+ * the diagnostics exist to prevent.
50
+ */
51
+ const asksForMarkup = (uischema: UISchemaElement): boolean => {
52
+ const options = uischema.options as Record<string, unknown> | undefined;
53
+ const markup = options?.['markup'];
54
+ return (
55
+ wantsInterpolation(options) || (markup !== undefined && markup !== 'plain')
56
+ );
57
+ };
58
+
59
+ /**
60
+ * Rank 3, above the base `Label` renderer's 1.
61
+ *
62
+ * Not 2: the antd renderer set reserves 2 for its own overrides of core
63
+ * elements, and a markup label has to beat those too.
64
+ */
65
+ export const markupLabelTester: RankedTester = rankWith(
66
+ 3,
67
+ (uischema, _schema, _context) =>
68
+ uiTypeIs('Label')(uischema, _schema, _context) && asksForMarkup(uischema),
69
+ );
70
+
71
+ /**
72
+ * The UI library's own text component, if the binding package supplies one.
73
+ *
74
+ * `block` says what it is being handed. Parsed Markdown is already block
75
+ * content - paragraphs, lists - while plain text is a single run, and a
76
+ * library whose paragraph component renders an actual `<p>` must not wrap the
77
+ * former in it: `<p>` accepts phrasing content only, so a `<p>` or a `<ul>`
78
+ * inside one is invalid and the browser closes the outer tag early, leaving a
79
+ * tree that does not match what React thinks it rendered.
80
+ *
81
+ * It is one slot with a flag rather than two components because for some
82
+ * libraries the two coincide - antd's `Typography.Paragraph` renders a `div`,
83
+ * so it is safe for both - and a binding should be able to say that by
84
+ * ignoring the flag rather than by naming the same component twice.
85
+ */
86
+ export type MarkupTypography = React.ComponentType<{
87
+ block: boolean;
88
+ children?: React.ReactNode;
89
+ }>;
90
+
91
+ export interface MarkupLabelProps extends LabelProps {
92
+ typography?: MarkupTypography;
93
+ }
94
+
95
+ /*
96
+ Created once at module scope, so the chunk is requested once however many
97
+ labels there are.
98
+ */
99
+ const LazyMarkdownText = lazy(async () => ({
100
+ default: (await import('./MarkupLabelRenderer.impl'))
101
+ .MarkdownText as React.ComponentType<MarkdownTextProps>,
102
+ }));
103
+
104
+ const DIAGNOSTIC_STYLE: React.CSSProperties = {
105
+ display: 'block',
106
+ fontSize: '0.85em',
107
+ opacity: 0.85,
108
+ };
109
+
110
+ export const MarkupLabelRendererComponent = ({
111
+ uischema,
112
+ text,
113
+ visible,
114
+ config,
115
+ typography,
116
+ }: MarkupLabelProps) => {
117
+ const t = useExtendedTranslator();
118
+ const ownedText = useI18n();
119
+ const ctx = useJsonForms();
120
+ if (visible === false) {
121
+ return null;
122
+ }
123
+ const options = uischema?.options as Record<string, unknown> | undefined;
124
+ const request = resolveMarkup(options, config);
125
+ const content = text ?? '';
126
+
127
+ const diagnostic = request.diagnostic ? (
128
+ <span
129
+ role='alert'
130
+ data-markup-diagnostic={request.diagnostic}
131
+ style={DIAGNOSTIC_STYLE}
132
+ >
133
+ {request.diagnostic === 'markdownDisabled'
134
+ ? t('markup.markdownDisabled')
135
+ : t('markup.unsupported', { markup: JSON.stringify(options?.markup) })}
136
+ </span>
137
+ ) : null;
138
+
139
+ const Typography = request.typography ? typography : undefined;
140
+
141
+ /*
142
+ Split eagerly. It is pure string work, it decides whether the evaluator is
143
+ needed at all, and doing it here keeps that decision out of the chunk.
144
+ */
145
+ const segments = request.interpolate ? splitTemplate(content) : undefined;
146
+ /*
147
+ The segments only when there is something to evaluate, so the type itself
148
+ carries the decision: every path below either has expressions or does not,
149
+ and neither needs to assert it.
150
+ */
151
+ const expressions =
152
+ segments && hasExpressions(segments) ? segments : undefined;
153
+ /*
154
+ The text with no expressions to resolve - which is **not** the authored
155
+ text, because the grammar's brace escaping still has to be applied:
156
+ `{{data.x}}` is the literal `{data.x}`, and a template made only of
157
+ literals must still say so. Skipping the evaluator is right here; skipping
158
+ the unescaping was a bug.
159
+ */
160
+ const plainText = segments
161
+ ? segments
162
+ .map((segment) => (segment.kind === 'literal' ? segment.text : ''))
163
+ .join('')
164
+ : content;
165
+ const textParams = options?.['textParams'] as
166
+ | Record<string, unknown>
167
+ | undefined;
168
+ /*
169
+ The namespaces are for the PARAMETERS, not for the text. A translated
170
+ string that reads `{data.customerName}` couples the catalog to the schema;
171
+ one that reads `{product}` does not, and that is the whole reason the two
172
+ scopes are separate.
173
+ */
174
+ const namespaceScope = expressions
175
+ ? buildNamespaceScope({
176
+ data: ctx.core?.data,
177
+ get item() {
178
+ return (ctx as typeof ctx & ItemContext).item;
179
+ },
180
+ locale: ctx.i18n?.locale,
181
+ config,
182
+ dynamicAllowed: dynamicValuesEnabled(config),
183
+ })
184
+ : {};
185
+ const reserved = reservedParamNames(textParams);
186
+
187
+ /*
188
+ A refusal shows the diagnostic AND the text. A Label's text is inert
189
+ content, not a program: the reason a refused template renders nothing is
190
+ that running it is the whole point, whereas the words of a label are
191
+ readable whether or not their asterisks became bold. Hiding them would
192
+ turn a policy decision into missing information on the page.
193
+ */
194
+ /*
195
+ Nothing to do beyond what the base renderer would do: no parsing, and no
196
+ expression to resolve. The `expressions` half matters - `interpolate:
197
+ true` over text with no placeholder must not reach for the evaluator.
198
+ */
199
+ if (!request.markdown && !expressions) {
200
+ return (
201
+ <label data-markup-label='plain'>
202
+ {Typography ? (
203
+ <Typography block={false}>{plainText}</Typography>
204
+ ) : (
205
+ plainText
206
+ )}
207
+ {diagnostic}
208
+ </label>
209
+ );
210
+ }
211
+
212
+ /*
213
+ The parsed half, as a function of the text, because the text may still be
214
+ on its way: when interpolation is in play this is called with the
215
+ resolved string rather than the authored one.
216
+ */
217
+ const parsed = (source: string) => (
218
+ /*
219
+ Both fallbacks are the text itself, not a spinner and not an error.
220
+ The chunk usually arrives within a frame, and a paragraph of prose
221
+ replaced by "Loading…" and back again is a worse read than the same
222
+ prose unparsed for a moment.
223
+
224
+ The boundary is not optional. Suspense has no error path, so without it
225
+ a chunk that never arrives - an offline reload, a stale hash after a
226
+ deploy - throws past it and takes the whole form down, over a label.
227
+ */
228
+ <LoadBoundary fallback={source}>
229
+ <Suspense fallback={source}>
230
+ <LazyMarkdownText
231
+ text={source}
232
+ profile={markdownProfile(config)}
233
+ urlPolicy={resolveUrlPolicy(config)}
234
+ />
235
+ </Suspense>
236
+ </LoadBoundary>
237
+ );
238
+
239
+ const body = (source: string): React.ReactNode =>
240
+ request.markdown ? parsed(source) : source;
241
+
242
+ const wrap = (node: React.ReactNode, extra?: React.ReactNode) => {
243
+ const inner = Typography ? (
244
+ <Typography block={request.markdown}>{node}</Typography>
245
+ ) : (
246
+ node
247
+ );
248
+ /*
249
+ A `div` once Markdown is parsed, because that is block content and
250
+ `<label>` accepts phrasing content only; a `label` otherwise, which is
251
+ what the base renderer draws.
252
+ */
253
+ return request.markdown ? (
254
+ <div data-markup-label='markdown'>
255
+ {inner}
256
+ {extra}
257
+ </div>
258
+ ) : (
259
+ <label data-markup-label='interpolated'>
260
+ {inner}
261
+ {extra}
262
+ </label>
263
+ );
264
+ };
265
+
266
+ if (!expressions) {
267
+ return wrap(body(plainText), diagnostic);
268
+ }
269
+
270
+ /*
271
+ The evaluator is fetched only when there is something to evaluate. A
272
+ template with no placeholders is resolved here, for free, and never asks
273
+ for the chunk - which is the difference between `interpolate: true` being
274
+ a declaration of intent and a download.
275
+ */
276
+ /*
277
+ The wrapper is outside the boundary on purpose. It depends only on what
278
+ was *asked for*, never on what arrived, so the element, its typography and
279
+ its `data-markup-label` are present while the chunk is in flight and stay
280
+ present if it never lands. Wrapping inside the render prop instead left a
281
+ failed load rendering a bare string with no element at all.
282
+ */
283
+ return wrap(
284
+ <InterpolatedText
285
+ segments={expressions}
286
+ textParams={textParams}
287
+ namespaceScope={namespaceScope}
288
+ locale={ctx.i18n?.locale}
289
+ translate={ctx.i18n?.translate}
290
+ escape={request.markdown ? escapeMarkdown : undefined}
291
+ fallback={plainText}
292
+ >
293
+ {(result) => (
294
+ <>
295
+ {body(result.text)}
296
+ {result.failures.length > 0 || reserved.length > 0 ? (
297
+ <span
298
+ role='alert'
299
+ data-markup-diagnostic='interpolationFailed'
300
+ style={DIAGNOSTIC_STYLE}
301
+ >
302
+ {t('markup.interpolationFailed', {
303
+ detail: [
304
+ ...reserved.map((name) =>
305
+ ownedText('markup.reservedParam', { name }),
306
+ ),
307
+ ...result.failures,
308
+ ].join('; '),
309
+ })}
310
+ </span>
311
+ ) : null}
312
+ </>
313
+ )}
314
+ </InterpolatedText>,
315
+ diagnostic,
316
+ );
317
+ };
318
+
319
+ export const MarkupLabelRenderer = withJsonFormsLabelProps(
320
+ MarkupLabelRendererComponent,
321
+ );
322
+
323
+ /** Binds the typography slots, for a renderer set that has them. */
324
+ export const createMarkupLabelRenderer = (typography: MarkupTypography) =>
325
+ withJsonFormsLabelProps((props: LabelProps) => (
326
+ <MarkupLabelRendererComponent {...props} typography={typography} />
327
+ ));
@@ -0,0 +1,351 @@
1
+ import { useEditorAppearance } from '../util/useEditorAppearance';
2
+ import { useExtendedTranslator } from '../util/useExtendedTranslator';
3
+ import { useMonacoShadowStyles } from '../util/useMonacoShadowStyles';
4
+ import React, { useEffect, useId, useState, useRef } from 'react';
5
+ import { ControlProps } from '@jsonforms/core';
6
+ import { useJsonForms } from '@jsonforms/react';
7
+ import Editor from '@monaco-editor/react';
8
+ import {
9
+ EditorRendererComponents,
10
+ EditorSurfaceProps,
11
+ } from '../components/editorRendererTypes';
12
+ import {
13
+ decodeEditorValue,
14
+ encodeEditorValue,
15
+ resolveEditorLanguage,
16
+ } from '../util/editorControls';
17
+ import { useOwnedAdditionalErrors } from '../util/additionalErrors';
18
+ import {
19
+ EditorMarker,
20
+ countBlockingMarkers,
21
+ editorSummaryError,
22
+ resolvePropagateErrors,
23
+ } from '../util/editorDiagnostics';
24
+
25
+ const PlainSurface = ({ children, maximized }: EditorSurfaceProps) => (
26
+ <div style={{ position: 'relative', height: maximized ? '100%' : undefined }}>
27
+ {children}
28
+ </div>
29
+ );
30
+
31
+ export const createMonacoControl = ({
32
+ Frame,
33
+ Button,
34
+ MaximizeIcon,
35
+ MinimizeIcon,
36
+ Surface,
37
+ useEditorTheme,
38
+ }: EditorRendererComponents) => {
39
+ // Resolved once per renderer set so the hook call below stays unconditional.
40
+ const useHostTheme = useEditorTheme ?? (() => undefined);
41
+ const EditorSurface = Surface ?? PlainSurface;
42
+ const MonacoControl = (props: ControlProps) => {
43
+ const anchor = useRef<HTMLDivElement>(null);
44
+ const editorRef = useRef<any>(null);
45
+ const [maximized, setMaximized] = useState(false);
46
+ const [hovered, setHovered] = useState(false);
47
+ const [focused, setFocused] = useState(false);
48
+ const context = useJsonForms();
49
+ const options = { ...props.config, ...props.uischema.options };
50
+ const hostTheme = useHostTheme();
51
+ const t = useExtendedTranslator();
52
+ const { isDark, customTheme } = useEditorAppearance(
53
+ anchor,
54
+ options.theme ?? options.mode,
55
+ hostTheme?.isDark,
56
+ );
57
+ // Monaco's own vocabulary lives here, not in the shared appearance hook.
58
+ const theme = customTheme ?? (isDark ? 'vs-dark' : 'vs');
59
+ useMonacoShadowStyles(anchor);
60
+ const language = resolveEditorLanguage(options, context.core?.data);
61
+ const convert = language === 'json' && options.convertJson === true;
62
+ const encoded = encodeEditorValue(props.data, convert);
63
+ const [text, setText] = useState(encoded);
64
+ const lastCommitted = useRef<string>();
65
+ const lastExternal = useRef(encoded);
66
+ const [invalid, setInvalid] = useState(false);
67
+
68
+ /*
69
+ Monaco's own diagnostics, as a count.
70
+
71
+ Only error-level markers: warnings, hints and informational messages
72
+ "stay inside Monaco; they do not contribute to the summary count or
73
+ block form validity through this bridge."
74
+
75
+ `onValidate` fires only for a language with a validating service - JSON,
76
+ TypeScript, CSS and so on. For anything else the count stays zero, which
77
+ is the honest answer: "syntax highlighting alone does not establish that
78
+ language validation is available."
79
+ */
80
+ const [errorCount, setErrorCount] = useState(0);
81
+
82
+ /*
83
+ One error per editor **instance**, so two editors bound to the same path
84
+ - or an editor sitting beside a host-published error - never overwrite
85
+ each other. `useId` is unique per mounted component and stable across
86
+ that component's renders, which is exactly the lifetime an owner needs.
87
+ */
88
+ const owner = useId();
89
+ const [monacoApi, setMonacoApi] = useState<any>(null);
90
+ const modelUri = `inmemory://jsonforms/mixed-${encodeURIComponent(
91
+ owner,
92
+ )}.json`;
93
+ const schemaValidation = options.validateJsonSchema === true;
94
+ useEffect(() => {
95
+ if (!monacoApi || !schemaValidation) return;
96
+ const defaults = monacoApi.languages.json.jsonDefaults;
97
+ const rootUri = `${modelUri}.root-schema.json`;
98
+ const sectionUri = `${modelUri}.schema.json`;
99
+ // Local references in the section still refer to the document schema.
100
+ const rebase = (value: any): any => {
101
+ if (Array.isArray(value)) return value.map(rebase);
102
+ if (!value || typeof value !== 'object') return value;
103
+ return Object.fromEntries(
104
+ Object.entries(value).map(([key, child]) => [
105
+ key,
106
+ key === '$ref' && typeof child === 'string' && child.startsWith('#')
107
+ ? rootUri + child
108
+ : rebase(child),
109
+ ]),
110
+ );
111
+ };
112
+ const registrations = [
113
+ { uri: rootUri, schema: { ...context.core?.schema, $id: rootUri } },
114
+ {
115
+ uri: sectionUri,
116
+ fileMatch: [modelUri],
117
+ schema: rebase(props.schema),
118
+ },
119
+ ];
120
+ const owned = (entry: { uri: string }) =>
121
+ entry.uri === rootUri || entry.uri === sectionUri;
122
+ defaults.setDiagnosticsOptions({
123
+ ...defaults.diagnosticsOptions,
124
+ validate: true,
125
+ schemas: [
126
+ ...(defaults.diagnosticsOptions.schemas ?? []).filter(
127
+ (entry) => !owned(entry),
128
+ ),
129
+ ...registrations,
130
+ ],
131
+ });
132
+ return () =>
133
+ defaults.setDiagnosticsOptions({
134
+ ...defaults.diagnosticsOptions,
135
+ schemas: (defaults.diagnosticsOptions.schemas ?? []).filter(
136
+ (entry) => !owned(entry),
137
+ ),
138
+ });
139
+ }, [
140
+ monacoApi,
141
+ schemaValidation,
142
+ modelUri,
143
+ props.schema,
144
+ context.core?.schema,
145
+ ]);
146
+ const propagate = resolvePropagateErrors(
147
+ props.uischema.options,
148
+ props.config,
149
+ );
150
+ const summary =
151
+ propagate && (schemaValidation ? invalid : errorCount > 0)
152
+ ? [
153
+ editorSummaryError({
154
+ owner,
155
+ path: props.path,
156
+ language,
157
+ errorCount: schemaValidation ? 1 : errorCount,
158
+ message: schemaValidation
159
+ ? t('editor.invalidJson')
160
+ : errorCount === 1
161
+ ? t('editor.languageError')
162
+ : t('editor.languageErrors').replace(
163
+ '{count}',
164
+ String(errorCount),
165
+ ),
166
+ }),
167
+ ]
168
+ : [];
169
+ /*
170
+ Publishing an empty list is what clears it, so switching the option off,
171
+ fixing the code, or unmounting all retract the summary through the same
172
+ path rather than three special cases.
173
+ */
174
+ useOwnedAdditionalErrors(owner, summary, {
175
+ /*
176
+ This editor manages its own lifecycle: it republishes or retracts as
177
+ the language service reports. The store's default - clear when the
178
+ field's value changes - would wipe the summary on the first keystroke
179
+ and let it reappear on the next validation pass, which reads as a
180
+ flicker rather than as feedback.
181
+ */
182
+ clearOnChange: false,
183
+ });
184
+
185
+ // Match the editor canvas to the surface. Monaco >= 0.34 exposes its theme
186
+ // colors as --vscode-* custom properties, so recoloring one instance is a
187
+ // matter of setting them on an ancestor (custom properties inherit).
188
+ // Deliberately NOT monaco.editor.defineTheme/setTheme: Monaco's theme
189
+ // registry is global, so doing that would repaint every other Monaco editor
190
+ // on the page, including ones the host application owns.
191
+ const background = hostTheme?.background;
192
+ const surfaceVars = background
193
+ ? ({
194
+ '--vscode-editor-background': background,
195
+ '--vscode-editorGutter-background': background,
196
+ '--vscode-minimap-background': background,
197
+ '--vscode-editorStickyScroll-background': background,
198
+ } as React.CSSProperties)
199
+ : undefined;
200
+
201
+ useEffect(() => {
202
+ // Schema-validated drafts survive blur and echoes of committed data;
203
+ // a changed external value replaces the draft even while focused.
204
+ if (schemaValidation) {
205
+ if (lastExternal.current !== encoded) {
206
+ lastExternal.current = encoded;
207
+ if (lastCommitted.current !== encoded) {
208
+ setText(encoded);
209
+ setInvalid(false);
210
+ }
211
+ }
212
+ return;
213
+ }
214
+ // Other editors defer external updates until blur to avoid moving the
215
+ // caret while typing. The schema-validation branch has already returned.
216
+ if (focused) return;
217
+ /* eslint-disable react/set-state-in-effect -- Synchronize the external editor only after blur; replacing this with unconditional derivation would discard invalid drafts. */
218
+ if (lastCommitted.current !== encoded) setText(encoded);
219
+ setInvalid(false);
220
+ /* eslint-enable react/set-state-in-effect */
221
+ }, [encoded, language, convert, focused, schemaValidation]);
222
+
223
+ useEffect(() => {
224
+ // Toggling maximize swaps the container between fixed and inline layout.
225
+ // automaticLayout does not reliably catch that, leaving the editor stuck
226
+ // at the maximized width after restoring, so re-measure once settled.
227
+ const editor = editorRef.current;
228
+ if (!editor) return;
229
+ const frame = requestAnimationFrame(() => {
230
+ editor.layout({ width: 0, height: 0 });
231
+ requestAnimationFrame(() => editor.layout());
232
+ });
233
+ return () => cancelAnimationFrame(frame);
234
+ }, [maximized]);
235
+
236
+ if (!props.visible) return null;
237
+ const monaco = options.monaco ?? {};
238
+ const rows = monaco.autoGrow
239
+ ? Math.max(
240
+ monaco.minRows ?? 3,
241
+ Math.min(monaco.maxRows ?? 30, text.split('\n').length),
242
+ )
243
+ : (monaco.rows ?? 10);
244
+ const disabled = !props.enabled || props.readonly;
245
+ const label = maximized ? t('editor.restore') : t('editor.maximize');
246
+ return (
247
+ <Frame
248
+ {...props}
249
+ errors={invalid ? t('editor.invalidJson') : props.errors}
250
+ >
251
+ <div
252
+ ref={anchor}
253
+ onKeyDown={(event) => {
254
+ if (event.key === 'Escape') setMaximized(false);
255
+ }}
256
+ onMouseEnter={() => setHovered(true)}
257
+ onMouseLeave={() => setHovered(false)}
258
+ onFocus={() => setFocused(true)}
259
+ onBlur={() => setFocused(false)}
260
+ style={
261
+ maximized
262
+ ? {
263
+ ...surfaceVars,
264
+ position: 'fixed',
265
+ inset: 0,
266
+ zIndex: 1400,
267
+ background: 'rgba(0, 0, 0, 0.45)',
268
+ padding: 24,
269
+ }
270
+ : { ...surfaceVars, minWidth: 0 }
271
+ }
272
+ >
273
+ <EditorSurface
274
+ hovered={hovered}
275
+ focused={focused}
276
+ disabled={disabled}
277
+ invalid={Boolean(invalid || props.errors)}
278
+ maximized={maximized}
279
+ >
280
+ <Editor
281
+ path={schemaValidation ? modelUri : undefined}
282
+ value={text}
283
+ language={language}
284
+ width={options.width}
285
+ height={maximized ? '100%' : (options.height ?? rows * 20 + 20)}
286
+ theme={theme}
287
+ options={{
288
+ automaticLayout: true,
289
+ minimap: { enabled: false },
290
+ scrollBeyondLastLine: false,
291
+ padding: { top: 8, bottom: 8 },
292
+ ...monaco.options,
293
+ readOnly: disabled,
294
+ ariaLabel: props.label || t('editor.ariaLabel'),
295
+ }}
296
+ onMount={(editor, api) => {
297
+ setMonacoApi(api);
298
+ editorRef.current = editor;
299
+ if (options.focus) editor.focus();
300
+ for (const action of monaco.initActions ?? [])
301
+ editor.getAction(action)?.run();
302
+ }}
303
+ onValidate={(markers) =>
304
+ setErrorCount(countBlockingMarkers(markers as EditorMarker[]))
305
+ }
306
+ onChange={(value) => {
307
+ if (disabled) return;
308
+ const next = value ?? '';
309
+ setText(next);
310
+ const decoded = decodeEditorValue(next, convert);
311
+ setInvalid(!decoded.valid);
312
+ if (decoded.valid) {
313
+ lastCommitted.current = encodeEditorValue(
314
+ decoded.value,
315
+ convert,
316
+ );
317
+ props.handleChange(props.path, decoded.value);
318
+ }
319
+ }}
320
+ />
321
+ {(hovered || focused || maximized) && (
322
+ <div
323
+ style={{
324
+ position: 'absolute',
325
+ top: 4,
326
+ right: 4,
327
+ zIndex: 1,
328
+ lineHeight: 0,
329
+ background,
330
+ borderRadius: 4,
331
+ }}
332
+ >
333
+ <Button
334
+ onClick={() => setMaximized((v) => !v)}
335
+ title={label}
336
+ aria-label={label}
337
+ >
338
+ {maximized
339
+ ? MinimizeIcon && <MinimizeIcon />
340
+ : MaximizeIcon && <MaximizeIcon />}
341
+ {!MaximizeIcon && !MinimizeIcon && label}
342
+ </Button>
343
+ </div>
344
+ )}
345
+ </EditorSurface>
346
+ </div>
347
+ </Frame>
348
+ );
349
+ };
350
+ return MonacoControl;
351
+ };
@@ -0,0 +1,24 @@
1
+ import React from 'react';
2
+ import { ControlProps } from '@jsonforms/core';
3
+ import { withJsonFormsControlProps } from '@jsonforms/react';
4
+ import { createLazyControl } from '../util/lazyControl';
5
+ import { EditorRendererComponents } from '../components/editorRendererTypes';
6
+
7
+ /**
8
+ * @monaco-editor/react pulls in the Monaco loader; importing it here would put
9
+ * it in the main bundle for every form, so the implementation is fetched only
10
+ * once a code editor control is actually rendered.
11
+ */
12
+ export const createMonacoControlRenderer = (
13
+ components: EditorRendererComponents,
14
+ ) =>
15
+ withJsonFormsControlProps(
16
+ createLazyControl(
17
+ async () =>
18
+ (await import('./MonacoControlRenderer.impl')).createMonacoControl(
19
+ components,
20
+ ) as React.ComponentType<ControlProps>,
21
+ components,
22
+ { loading: 'editor.loading', error: 'editor.loadError' },
23
+ ),
24
+ );