@chobantonov/jsonforms-react-shadcn-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 (154) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +157 -2
  3. package/lib/additional/LabelRenderer.d.ts +4 -0
  4. package/lib/additional/index.d.ts +1 -0
  5. package/lib/cells/BooleanCell.d.ts +3 -0
  6. package/lib/cells/Cell.d.ts +3 -0
  7. package/lib/cells/CompositeCell.d.ts +9 -0
  8. package/lib/cells/CompositeDetailDialog.d.ts +3 -0
  9. package/lib/cells/EnumCell.d.ts +3 -0
  10. package/lib/cells/NumberCell.d.ts +3 -0
  11. package/lib/cells/NumberFormatCell.d.ts +4 -0
  12. package/lib/cells/TextCell.d.ts +3 -0
  13. package/lib/cells/asCell.d.ts +12 -0
  14. package/lib/cells/index.d.ts +7 -0
  15. package/lib/complex/AdditionalProperties.d.ts +4 -0
  16. package/lib/complex/AnyOfRenderer.d.ts +7 -0
  17. package/lib/complex/ArrayChoicesControl.d.ts +6 -0
  18. package/lib/complex/ArrayControlRenderer.d.ts +4 -0
  19. package/lib/complex/ArrayPanelToggle.d.ts +6 -0
  20. package/lib/complex/CollectionPager.d.ts +5 -0
  21. package/lib/complex/CombinatorSwitchDialog.d.ts +8 -0
  22. package/lib/complex/DeleteDialog.d.ts +6 -0
  23. package/lib/complex/DetailDialogContent.d.ts +7 -0
  24. package/lib/complex/ErrorIndicator.d.ts +7 -0
  25. package/lib/complex/MixedRenderer.d.ts +6 -0
  26. package/lib/complex/ObjectRenderer.d.ts +3 -0
  27. package/lib/complex/OneOfRenderer.d.ts +5 -0
  28. package/lib/complex/RecursiveTreeRenderer.d.ts +4 -0
  29. package/lib/complex/RowDetailFrame.d.ts +16 -0
  30. package/lib/complex/ScalarCompositionRenderer.d.ts +4 -0
  31. package/lib/complex/TupleAdditionalItems.d.ts +4 -0
  32. package/lib/complex/TupleControlRenderer.d.ts +6 -0
  33. package/lib/complex/TupleField.d.ts +4 -0
  34. package/lib/complex/array/ArrayItemPanels.d.ts +18 -0
  35. package/lib/complex/array/ArrayItemViewProps.d.ts +11 -0
  36. package/lib/complex/array/ArrayListDetail.d.ts +9 -0
  37. package/lib/complex/array/ArrayTable.d.ts +21 -0
  38. package/lib/complex/index.d.ts +10 -0
  39. package/lib/complex/mixed/JsonTypeIcon.d.ts +5 -0
  40. package/lib/complex/mixed/MixedWidgets.d.ts +22 -0
  41. package/lib/complex/mixed/useConfirmation.d.ts +6 -0
  42. package/lib/components/ClearValueButton.d.ts +12 -0
  43. package/lib/components/ScrollRegion.d.ts +4 -0
  44. package/lib/components/TimePicker.d.ts +13 -0
  45. package/lib/components/index.d.ts +2 -0
  46. package/lib/controls/AnyOfStringOrEnumControl.d.ts +4 -0
  47. package/lib/controls/BooleanControl.d.ts +4 -0
  48. package/lib/controls/BooleanToggleControl.d.ts +4 -0
  49. package/lib/controls/ChoiceCards.d.ts +1 -0
  50. package/lib/controls/DateControl.d.ts +4 -0
  51. package/lib/controls/DateTimeControl.d.ts +4 -0
  52. package/lib/controls/EnumControl.d.ts +5 -0
  53. package/lib/controls/InputControl.d.ts +30 -0
  54. package/lib/controls/IntegerControl.d.ts +4 -0
  55. package/lib/controls/NumberControl.d.ts +4 -0
  56. package/lib/controls/OneOfEnumControl.d.ts +3 -0
  57. package/lib/controls/PasswordControl.d.ts +9 -0
  58. package/lib/controls/RadioGroupControl.d.ts +4 -0
  59. package/lib/controls/SliderControl.d.ts +4 -0
  60. package/lib/controls/TextControl.d.ts +4 -0
  61. package/lib/controls/TimeControl.d.ts +4 -0
  62. package/lib/controls/index.d.ts +15 -0
  63. package/lib/index.d.ts +6 -0
  64. package/lib/jsonforms-react-shadcn.cjs.js +3 -0
  65. package/lib/jsonforms-react-shadcn.cjs.js.map +1 -0
  66. package/lib/jsonforms-react-shadcn.esm.js +4040 -0
  67. package/lib/jsonforms-react-shadcn.esm.js.map +1 -0
  68. package/lib/layouts/CategorizationLayout.d.ts +7 -0
  69. package/lib/layouts/GroupLayout.d.ts +4 -0
  70. package/lib/layouts/HorizontalLayout.d.ts +4 -0
  71. package/lib/layouts/Layout.d.ts +5 -0
  72. package/lib/layouts/ValidationIndicator.d.ts +4 -0
  73. package/lib/layouts/VerticalLayout.d.ts +4 -0
  74. package/lib/layouts/index.d.ts +4 -0
  75. package/lib/renderers.d.ts +8 -0
  76. package/lib/util/dateTime.d.ts +12 -0
  77. package/lib/util/groupState.d.ts +1 -0
  78. package/lib/util/useTemporalControl.d.ts +28 -0
  79. package/package.json +86 -3
  80. package/src/additional/LabelRenderer.tsx +8 -0
  81. package/src/additional/index.ts +1 -0
  82. package/src/cells/BooleanCell.tsx +26 -0
  83. package/src/cells/Cell.tsx +101 -0
  84. package/src/cells/CompositeCell.tsx +275 -0
  85. package/src/cells/CompositeDetailDialog.tsx +79 -0
  86. package/src/cells/EnumCell.tsx +74 -0
  87. package/src/cells/NumberCell.tsx +51 -0
  88. package/src/cells/NumberFormatCell.tsx +47 -0
  89. package/src/cells/TextCell.tsx +40 -0
  90. package/src/cells/asCell.tsx +79 -0
  91. package/src/cells/index.ts +7 -0
  92. package/src/complex/AdditionalProperties.tsx +453 -0
  93. package/src/complex/AnyOfRenderer.tsx +341 -0
  94. package/src/complex/ArrayChoicesControl.tsx +303 -0
  95. package/src/complex/ArrayControlRenderer.tsx +400 -0
  96. package/src/complex/ArrayPanelToggle.tsx +33 -0
  97. package/src/complex/CollectionPager.tsx +76 -0
  98. package/src/complex/CombinatorSwitchDialog.tsx +43 -0
  99. package/src/complex/DeleteDialog.tsx +41 -0
  100. package/src/complex/DetailDialogContent.tsx +84 -0
  101. package/src/complex/ErrorIndicator.tsx +136 -0
  102. package/src/complex/MixedRenderer.tsx +262 -0
  103. package/src/complex/ObjectRenderer.tsx +43 -0
  104. package/src/complex/OneOfRenderer.tsx +14 -0
  105. package/src/complex/RecursiveTreeRenderer.tsx +20 -0
  106. package/src/complex/RowDetailFrame.tsx +158 -0
  107. package/src/complex/ScalarCompositionRenderer.tsx +14 -0
  108. package/src/complex/TupleAdditionalItems.tsx +94 -0
  109. package/src/complex/TupleControlRenderer.tsx +54 -0
  110. package/src/complex/TupleField.tsx +41 -0
  111. package/src/complex/array/ArrayItemPanels.tsx +217 -0
  112. package/src/complex/array/ArrayItemViewProps.ts +15 -0
  113. package/src/complex/array/ArrayListDetail.tsx +165 -0
  114. package/src/complex/array/ArrayTable.tsx +535 -0
  115. package/src/complex/index.ts +16 -0
  116. package/src/complex/mixed/JsonTypeIcon.tsx +41 -0
  117. package/src/complex/mixed/MixedWidgets.tsx +326 -0
  118. package/src/complex/mixed/useConfirmation.tsx +34 -0
  119. package/src/components/ClearValueButton.tsx +56 -0
  120. package/src/components/ScrollRegion.tsx +27 -0
  121. package/src/components/TimePicker.tsx +250 -0
  122. package/src/components/index.ts +2 -0
  123. package/src/controls/AnyOfStringOrEnumControl.tsx +44 -0
  124. package/src/controls/BooleanControl.tsx +67 -0
  125. package/src/controls/BooleanToggleControl.tsx +58 -0
  126. package/src/controls/ChoiceCards.tsx +9 -0
  127. package/src/controls/DateControl.tsx +240 -0
  128. package/src/controls/DateTimeControl.tsx +187 -0
  129. package/src/controls/EnumControl.tsx +159 -0
  130. package/src/controls/InputControl.tsx +258 -0
  131. package/src/controls/IntegerControl.tsx +14 -0
  132. package/src/controls/NumberControl.tsx +14 -0
  133. package/src/controls/OneOfEnumControl.tsx +13 -0
  134. package/src/controls/PasswordControl.tsx +216 -0
  135. package/src/controls/RadioGroupControl.tsx +72 -0
  136. package/src/controls/SliderControl.tsx +77 -0
  137. package/src/controls/TextControl.tsx +50 -0
  138. package/src/controls/TimeControl.tsx +135 -0
  139. package/src/controls/index.ts +19 -0
  140. package/src/index.tsx +10 -0
  141. package/src/layouts/CategorizationLayout.tsx +248 -0
  142. package/src/layouts/GroupLayout.tsx +210 -0
  143. package/src/layouts/HorizontalLayout.tsx +12 -0
  144. package/src/layouts/Layout.tsx +62 -0
  145. package/src/layouts/ValidationIndicator.tsx +40 -0
  146. package/src/layouts/VerticalLayout.tsx +12 -0
  147. package/src/layouts/index.ts +4 -0
  148. package/src/renderers.ts +225 -0
  149. package/src/styles.css +482 -0
  150. package/src/tailwind-theme.cjs +42 -0
  151. package/src/theme.css +43 -0
  152. package/src/util/dateTime.ts +80 -0
  153. package/src/util/groupState.ts +5 -0
  154. package/src/util/useTemporalControl.ts +160 -0
@@ -0,0 +1,341 @@
1
+ import { useCombinatorSelection } from '@chobantonov/jsonforms-react-renderer-common/composition/useCombinatorSelection';
2
+ import { X } from 'lucide-react';
3
+ import { discriminatorBranch } from '@chobantonov/jsonforms-react-renderer-common/composition/discriminatorBranch';
4
+ import {
5
+ useJsonForms,
6
+ JsonFormsDispatch,
7
+ withJsonFormsAnyOfProps,
8
+ } from '@jsonforms/react';
9
+ import { isArrayElementPath } from '@chobantonov/jsonforms-react-renderer-common/mixed/mixedSchema';
10
+ import {
11
+ isUnselectedBranchValue,
12
+ clearedBranchValue,
13
+ branchChangeData,
14
+ discardedByBranchChange,
15
+ } from '@chobantonov/jsonforms-react-renderer-common/composition/combinators';
16
+ import { Button } from '@jsonforms-react-shadcn-ui/button';
17
+ import React, { useId, useCallback, useState } from 'react';
18
+ import { useConfirmation } from './mixed/useConfirmation';
19
+ import { CombinatorBranch } from '@chobantonov/jsonforms-react-renderer-common/composition/CombinatorBranch';
20
+ import {
21
+ Select,
22
+ SelectTrigger,
23
+ SelectValue,
24
+ SelectContent,
25
+ SelectItem,
26
+ } from '@jsonforms-react-shadcn-ui/select';
27
+ import {
28
+ CombinatorRendererProps,
29
+ createDefaultValue,
30
+ isAnyOfControl,
31
+ RankedTester,
32
+ rankWith,
33
+ } from '@jsonforms/core';
34
+ import {
35
+ Tabs,
36
+ TabsContent,
37
+ TabsList,
38
+ TabsTrigger,
39
+ } from '@jsonforms-react-shadcn-ui/tabs';
40
+ import { CombinatorProperties } from '@chobantonov/jsonforms-react-renderer-common/composition/CombinatorProperties';
41
+ import { CombinatorSwitchDialog } from './CombinatorSwitchDialog';
42
+
43
+ const isEmptyData = (data: unknown) =>
44
+ data === undefined ||
45
+ data === null ||
46
+ data === '' ||
47
+ (Array.isArray(data) && data.length === 0) ||
48
+ (typeof data === 'object' &&
49
+ !Array.isArray(data) &&
50
+ Object.keys(data as Record<string, unknown>).length === 0);
51
+
52
+ export const ShadcnAnyOfRenderer = ({
53
+ handleChange,
54
+ schema,
55
+ rootSchema,
56
+ indexOfFittingSchema,
57
+ visible,
58
+ path,
59
+ renderers,
60
+ cells,
61
+ uischema,
62
+ uischemas,
63
+ data,
64
+ enabled,
65
+ label,
66
+ config,
67
+ combinator = 'anyOf',
68
+ }: CombinatorRendererProps & { combinator?: 'anyOf' | 'oneOf' }) => {
69
+ const formContext = useJsonForms();
70
+ indexOfFittingSchema =
71
+ discriminatorBranch(schema, rootSchema, combinator, data) ??
72
+ indexOfFittingSchema;
73
+ const selectorId = useId();
74
+ const [selectedIndex, setSelectedIndex] = useState(
75
+ indexOfFittingSchema ??
76
+ (combinator === 'oneOf' && isEmptyData(data) ? -1 : 0),
77
+ );
78
+ const [chosen, setChosen] = useState(false);
79
+ const confirmation = useConfirmation();
80
+ const [pendingIndex, setPendingIndex] = useState<number>();
81
+ const [previousInput, setPreviousInput] = useState({
82
+ initialized: false,
83
+ data,
84
+ indexOfFittingSchema,
85
+ combinator,
86
+ });
87
+ if (
88
+ !previousInput.initialized ||
89
+ previousInput.data !== data ||
90
+ previousInput.indexOfFittingSchema !== indexOfFittingSchema ||
91
+ previousInput.combinator !== combinator
92
+ ) {
93
+ setPreviousInput({
94
+ initialized: true,
95
+ data,
96
+ indexOfFittingSchema,
97
+ combinator,
98
+ });
99
+ if (
100
+ combinator === 'oneOf' &&
101
+ isUnselectedBranchValue(data, indexOfFittingSchema)
102
+ ) {
103
+ setChosen(false);
104
+ setSelectedIndex(-1);
105
+ setPendingIndex(undefined);
106
+ } else if (
107
+ !chosen &&
108
+ indexOfFittingSchema != null &&
109
+ indexOfFittingSchema >= 0
110
+ ) {
111
+ setSelectedIndex(indexOfFittingSchema);
112
+ }
113
+ }
114
+
115
+ const { translate, selectionError, renderInfos } = useCombinatorSelection(
116
+ { schema, rootSchema, uischema, path, uischemas },
117
+ combinator,
118
+ formContext.core,
119
+ );
120
+
121
+ const selectSchema = useCallback(
122
+ (index: number, resetData: boolean) => {
123
+ if (resetData) {
124
+ handleChange(
125
+ path,
126
+ createDefaultValue(renderInfos[index].schema, rootSchema),
127
+ );
128
+ }
129
+ setChosen(true);
130
+ setSelectedIndex(index);
131
+ },
132
+ [handleChange, path, renderInfos, rootSchema],
133
+ );
134
+
135
+ const handleTabChange = (value: string) => {
136
+ const index = value === '' ? -1 : Number(value);
137
+ if (enabled === false || index === selectedIndex) return;
138
+ if (combinator === 'oneOf') {
139
+ confirmation.request({
140
+ catalogId: 'oneOf',
141
+ operation: 'branchChange',
142
+ config,
143
+ options: uischema.options,
144
+ discarded: [discardedByBranchChange(data, schema)],
145
+ perform: () => {
146
+ handleChange(
147
+ path,
148
+ branchChangeData(
149
+ data,
150
+ index < 0
151
+ ? clearedBranchValue(
152
+ isArrayElementPath(formContext.core?.data, path),
153
+ renderInfos.map((info) => info.schema),
154
+ )
155
+ : createDefaultValue(renderInfos[index].schema, rootSchema),
156
+ schema,
157
+ ),
158
+ );
159
+ setChosen(true);
160
+ setSelectedIndex(index);
161
+ },
162
+ });
163
+ return;
164
+ }
165
+ const nextDefault = createDefaultValue(
166
+ renderInfos[index].schema,
167
+ rootSchema,
168
+ );
169
+
170
+ if (isEmptyData(data) || typeof data === typeof nextDefault) {
171
+ selectSchema(index, false);
172
+ return;
173
+ }
174
+
175
+ setPendingIndex(index);
176
+ };
177
+
178
+ if (!visible) {
179
+ return null;
180
+ }
181
+
182
+ if (renderInfos.length === 1) {
183
+ const branch = renderInfos[0];
184
+ return (
185
+ <>
186
+ <CombinatorProperties
187
+ schema={schema}
188
+ combinatorKeyword={combinator}
189
+ path={path}
190
+ rootSchema={rootSchema}
191
+ />
192
+ <CombinatorBranch
193
+ options={uischema.options}
194
+ schema={branch.schema}
195
+ path={path}
196
+ >
197
+ <JsonFormsDispatch
198
+ schema={branch.schema}
199
+ uischema={branch.uischema}
200
+ path={path}
201
+ renderers={renderers}
202
+ cells={cells}
203
+ enabled={enabled}
204
+ />
205
+ </CombinatorBranch>
206
+ </>
207
+ );
208
+ }
209
+
210
+ return (
211
+ <div className='shadcn-jsonforms-combinator'>
212
+ <CombinatorProperties
213
+ schema={schema}
214
+ combinatorKeyword={combinator}
215
+ path={path}
216
+ rootSchema={rootSchema}
217
+ />
218
+ {combinator === 'oneOf' ? (
219
+ <>
220
+ {label && (
221
+ <label
222
+ htmlFor={selectorId}
223
+ className='mb-2 block text-sm font-medium'
224
+ >
225
+ {label}
226
+ </label>
227
+ )}
228
+ <div className='relative w-full'>
229
+ <Select
230
+ value={selectedIndex >= 0 ? String(selectedIndex) : ''}
231
+ disabled={enabled === false}
232
+ onValueChange={handleTabChange}
233
+ >
234
+ <SelectTrigger
235
+ className={selectedIndex >= 0 ? 'w-full pe-16' : 'w-full'}
236
+ id={selectorId}
237
+ aria-invalid={Boolean(selectionError)}
238
+ aria-describedby={
239
+ selectionError ? selectorId + '-error' : undefined
240
+ }
241
+ aria-label={label || schema.title || 'oneOf'}
242
+ >
243
+ <SelectValue />
244
+ </SelectTrigger>
245
+ <SelectContent>
246
+ {renderInfos.map((info, index) => (
247
+ <SelectItem key={index} value={String(index)}>
248
+ {info.label}
249
+ </SelectItem>
250
+ ))}
251
+ </SelectContent>
252
+ </Select>
253
+ {selectedIndex >= 0 && (
254
+ <Button
255
+ type='button'
256
+ variant='ghost'
257
+ size='icon'
258
+ className='absolute end-8 top-1/2 size-7 -translate-y-1/2'
259
+ aria-label={translate('oneOf.clear', 'Clear selection')}
260
+ title={translate('oneOf.clear', 'Clear selection')}
261
+ disabled={enabled === false}
262
+ onClick={() => handleTabChange('')}
263
+ >
264
+ <X className='size-4' aria-hidden='true' />
265
+ </Button>
266
+ )}
267
+ </div>
268
+ {selectionError && (
269
+ <p
270
+ id={selectorId + '-error'}
271
+ role='alert'
272
+ className='text-sm text-destructive'
273
+ >
274
+ {selectionError}
275
+ </p>
276
+ )}
277
+ {renderInfos[selectedIndex] && (
278
+ <CombinatorBranch
279
+ options={uischema.options}
280
+ schema={renderInfos[selectedIndex].schema}
281
+ path={path}
282
+ >
283
+ <JsonFormsDispatch
284
+ schema={renderInfos[selectedIndex].schema}
285
+ uischema={renderInfos[selectedIndex].uischema}
286
+ path={path}
287
+ renderers={renderers}
288
+ cells={cells}
289
+ enabled={enabled}
290
+ />
291
+ </CombinatorBranch>
292
+ )}
293
+ </>
294
+ ) : (
295
+ <Tabs value={String(selectedIndex)} onValueChange={handleTabChange}>
296
+ <TabsList>
297
+ {renderInfos.map((renderInfo, index) => (
298
+ <TabsTrigger key={index} value={String(index)}>
299
+ {renderInfo.label}
300
+ </TabsTrigger>
301
+ ))}
302
+ </TabsList>
303
+ {renderInfos.map((renderInfo, index) => (
304
+ <TabsContent key={index} value={String(index)}>
305
+ {selectedIndex === index ? (
306
+ <CombinatorBranch
307
+ options={uischema.options}
308
+ schema={renderInfo.schema}
309
+ path={path}
310
+ >
311
+ <JsonFormsDispatch
312
+ schema={renderInfo.schema}
313
+ uischema={renderInfo.uischema}
314
+ path={path}
315
+ renderers={renderers}
316
+ cells={cells}
317
+ />
318
+ </CombinatorBranch>
319
+ ) : null}
320
+ </TabsContent>
321
+ ))}
322
+ </Tabs>
323
+ )}
324
+ {confirmation.dialog}
325
+ <CombinatorSwitchDialog
326
+ open={pendingIndex !== undefined}
327
+ onCancel={() => setPendingIndex(undefined)}
328
+ onConfirm={() => {
329
+ if (pendingIndex !== undefined) {
330
+ selectSchema(pendingIndex, true);
331
+ }
332
+ setPendingIndex(undefined);
333
+ }}
334
+ />
335
+ </div>
336
+ );
337
+ };
338
+
339
+ export const anyOfControlTester: RankedTester = rankWith(3, isAnyOfControl);
340
+
341
+ export const ShadcnAnyOfControl = withJsonFormsAnyOfProps(ShadcnAnyOfRenderer);
@@ -0,0 +1,303 @@
1
+ import React, { useState } from 'react';
2
+ import {
3
+ ControlProps,
4
+ defaultErrorTranslator,
5
+ getCombinedErrorMessage,
6
+ and,
7
+ rankWith,
8
+ schemaMatches,
9
+ uiTypeIs,
10
+ } from '@jsonforms/core';
11
+ import { useJsonForms } from '@jsonforms/react';
12
+ import { Input } from '@jsonforms-react-shadcn-ui/input';
13
+ import { Button } from '@jsonforms-react-shadcn-ui/button';
14
+ import { Checkbox } from '@jsonforms-react-shadcn-ui/checkbox';
15
+ import {
16
+ Popover,
17
+ PopoverContent,
18
+ PopoverTrigger,
19
+ } from '@jsonforms-react-shadcn-ui/popover';
20
+ import { X, Plus, ChevronDown, CircleAlert } from 'lucide-react';
21
+ import {
22
+ useI18n,
23
+ useTranslator,
24
+ } from '@chobantonov/jsonforms-react-renderer-common/locale/translate';
25
+ import { displayableErrors } from '@chobantonov/jsonforms-react-renderer-common/validation/validationIndicator';
26
+ import {
27
+ addChoice,
28
+ arrayChoiceItemErrors,
29
+ arrayChoicesOf,
30
+ asArrayValue,
31
+ canAddChoice,
32
+ canRemoveChoice,
33
+ isChipsControl,
34
+ isMultiSelectControl,
35
+ isSelected,
36
+ removeChoiceAt,
37
+ resolveItemSchema,
38
+ sameChoice,
39
+ } from '@chobantonov/jsonforms-react-renderer-common/collections/arrayChoices';
40
+ import { InputShell, makeId } from '../controls/InputControl';
41
+
42
+ export const chipsControlTester = rankWith(
43
+ 6,
44
+ and(uiTypeIs('Control'), isChipsControl),
45
+ );
46
+ export const multiSelectControlTester = rankWith(
47
+ 6,
48
+ and(uiTypeIs('Control'), isMultiSelectControl),
49
+ );
50
+ const enumChoices = (
51
+ schema: ControlProps['schema'],
52
+ root: ControlProps['rootSchema'],
53
+ ) => {
54
+ const items = resolveItemSchema(schema, root);
55
+ const strings = arrayChoicesOf(items);
56
+ if (strings) return strings;
57
+ const branches = items?.oneOf as Array<ControlProps['schema']> | undefined;
58
+ return Array.isArray(branches) &&
59
+ branches.length > 0 &&
60
+ branches.every((branch) => branch.const !== undefined)
61
+ ? branches.map((branch) => ({
62
+ value: branch.const,
63
+ label: branch.title ?? String(branch.const),
64
+ }))
65
+ : undefined;
66
+ };
67
+ export const enumArrayControlTester = rankWith(
68
+ 5,
69
+ and(
70
+ uiTypeIs('Control'),
71
+ schemaMatches(
72
+ (schema, root) =>
73
+ schema.type === 'array' &&
74
+ schema.uniqueItems === true &&
75
+ enumChoices(schema, root) !== undefined,
76
+ ),
77
+ ),
78
+ );
79
+
80
+ export const ShadcnArrayChoicesControl = (props: ControlProps) => {
81
+ const [draft, setDraft] = useState('');
82
+ const [search, setSearch] = useState('');
83
+ const t = useI18n();
84
+ const context = useJsonForms();
85
+ const translate = useTranslator();
86
+ if (!props.visible) return null;
87
+ const { schema, rootSchema, data, path, handleChange } = props;
88
+ const options = { ...props.config, ...props.uischema.options };
89
+ const chips = options.variant === 'chips';
90
+ const dropdown = options.variant === 'multi-select';
91
+ const values = asArrayValue(data);
92
+ const choices = enumChoices(schema, rootSchema);
93
+ const [primary, additional] = displayableErrors(context.core ?? {});
94
+ const itemErrors = arrayChoiceItemErrors(
95
+ [...(primary ?? []), ...(additional ?? [])],
96
+ path,
97
+ values.length,
98
+ );
99
+ const itemSchema = resolveItemSchema(schema, rootSchema);
100
+ const itemMessages = itemErrors.map((errors, index) =>
101
+ getCombinedErrorMessage(
102
+ errors,
103
+ context.i18n?.translateError ?? defaultErrorTranslator,
104
+ translate,
105
+ itemSchema,
106
+ props.uischema,
107
+ path ? `${path}.${index}` : String(index),
108
+ ),
109
+ );
110
+ const errors = [
111
+ props.errors,
112
+ ...itemMessages.map((message, index) =>
113
+ message ? `${String(values[index])}: ${message}` : '',
114
+ ),
115
+ ]
116
+ .filter(Boolean)
117
+ .join('\n');
118
+ const limits = {
119
+ minItems: schema.minItems,
120
+ maxItems: schema.maxItems,
121
+ restrict: options.restrict !== false,
122
+ };
123
+ const disabled = !props.enabled || props.readonly;
124
+ const id = makeId(path, props.label);
125
+ const label = (value: unknown) =>
126
+ choices?.find((choice) => sameChoice(choice.value, value))?.label ??
127
+ String(value);
128
+ const remove = (index: number) => {
129
+ if (!disabled && canRemoveChoice(values, limits))
130
+ handleChange(path, removeChoiceAt(values, index));
131
+ };
132
+ const add = (value: unknown) => {
133
+ if (disabled || value === '' || !canAddChoice(values, limits)) return;
134
+ if (choices && !choices.some((choice) => sameChoice(choice.value, value)))
135
+ return;
136
+ handleChange(path, addChoice(values, value, schema.uniqueItems === true));
137
+ setDraft('');
138
+ };
139
+ const choiceList = [
140
+ ...(choices ?? []),
141
+ ...values
142
+ .filter(
143
+ (value) => !choices?.some((choice) => sameChoice(choice.value, value)),
144
+ )
145
+ .map((value) => ({ value, label: String(value) })),
146
+ ];
147
+ const checks = (
148
+ <div
149
+ className={
150
+ options.vertical ? 'flex flex-col gap-2' : 'flex flex-wrap gap-3'
151
+ }
152
+ role='group'
153
+ aria-label={props.label}
154
+ >
155
+ {choiceList
156
+ .filter((choice) =>
157
+ choice.label.toLocaleLowerCase().includes(search.toLocaleLowerCase()),
158
+ )
159
+ .map((choice, index) => {
160
+ const checked = isSelected(values, choice.value);
161
+ return (
162
+ <label key={index} className='flex items-center gap-2'>
163
+ <Checkbox
164
+ checked={checked}
165
+ disabled={
166
+ disabled ||
167
+ (checked
168
+ ? !canRemoveChoice(values, limits)
169
+ : !canAddChoice(values, limits))
170
+ }
171
+ onCheckedChange={() =>
172
+ checked
173
+ ? remove(
174
+ values.findIndex((value) =>
175
+ sameChoice(value, choice.value),
176
+ ),
177
+ )
178
+ : add(choice.value)
179
+ }
180
+ />
181
+ {choice.label}
182
+ </label>
183
+ );
184
+ })}
185
+ </div>
186
+ );
187
+ const pills = (
188
+ <>
189
+ {values.map((value, index) => (
190
+ <span
191
+ key={index}
192
+ className={`inline-flex max-w-full items-center gap-1 rounded-md border bg-secondary px-2 py-0.5 text-sm text-secondary-foreground ${itemMessages[index] ? 'border-destructive' : 'border-transparent'}`}
193
+ aria-invalid={Boolean(itemMessages[index])}
194
+ title={itemMessages[index] || undefined}
195
+ >
196
+ <span className='min-w-0 truncate' title={label(value)}>
197
+ {label(value)}
198
+ </span>
199
+ {itemMessages[index] ? (
200
+ <CircleAlert
201
+ className='h-3.5 w-3.5 text-destructive'
202
+ role='img'
203
+ aria-label={itemMessages[index]}
204
+ />
205
+ ) : null}
206
+ <Button
207
+ type='button'
208
+ variant='ghost'
209
+ size='icon'
210
+ className='h-4 w-4 shrink-0 rounded-sm p-0'
211
+ disabled={disabled || !canRemoveChoice(values, limits)}
212
+ aria-label={t('composite.remove', { label: label(value) })}
213
+ onClick={() => remove(index)}
214
+ >
215
+ <X className='h-3 w-3' />
216
+ </Button>
217
+ </span>
218
+ ))}
219
+ </>
220
+ );
221
+ return (
222
+ <InputShell {...props} id={id} errors={errors}>
223
+ {chips ? (
224
+ <div className='flex min-w-0 flex-wrap items-center gap-2'>
225
+ {pills}
226
+ <Input
227
+ id={id}
228
+ className='min-w-40 flex-1'
229
+ value={draft}
230
+ list={choices ? id + '-choices' : undefined}
231
+ disabled={disabled || !canAddChoice(values, limits)}
232
+ aria-invalid={Boolean(errors)}
233
+ placeholder={options.placeholder ?? t('chips.addPlaceholder')}
234
+ onChange={(event) => setDraft(event.target.value)}
235
+ onKeyDown={(event) => {
236
+ if (event.key === 'Enter' && !event.nativeEvent.isComposing) {
237
+ event.preventDefault();
238
+ add(draft);
239
+ }
240
+ }}
241
+ />
242
+ {choices && (
243
+ <datalist id={id + '-choices'}>
244
+ {choices.map((choice) => (
245
+ <option key={String(choice.value)} value={String(choice.value)}>
246
+ {choice.label}
247
+ </option>
248
+ ))}
249
+ </datalist>
250
+ )}
251
+ <Button
252
+ type='button'
253
+ variant='outline'
254
+ size='icon'
255
+ disabled={disabled || !draft || !canAddChoice(values, limits)}
256
+ aria-label={t('tuple.add')}
257
+ onClick={() => add(draft)}
258
+ >
259
+ <Plus className='h-4 w-4' />
260
+ </Button>
261
+ </div>
262
+ ) : dropdown ? (
263
+ <Popover>
264
+ <div className='flex min-h-9 w-full min-w-0 items-center gap-1 rounded-md border border-input bg-background px-2 py-1'>
265
+ <div className='flex min-w-0 flex-1 flex-wrap gap-1 max-h-32 overflow-auto'>
266
+ {values.length ? (
267
+ pills
268
+ ) : (
269
+ <span className='text-sm text-muted-foreground'>
270
+ {options.placeholder || props.label}
271
+ </span>
272
+ )}
273
+ </div>
274
+ <PopoverTrigger asChild>
275
+ <Button
276
+ id={id}
277
+ type='button'
278
+ variant='ghost'
279
+ size='icon'
280
+ aria-label={props.label}
281
+ disabled={disabled}
282
+ aria-invalid={Boolean(errors)}
283
+ className='h-7 w-7 shrink-0'
284
+ >
285
+ <ChevronDown className='h-4 w-4' />
286
+ </Button>
287
+ </PopoverTrigger>
288
+ </div>
289
+ <PopoverContent>
290
+ <Input
291
+ aria-label={props.label}
292
+ value={search}
293
+ onChange={(event) => setSearch(event.target.value)}
294
+ />
295
+ <div className='max-h-64 overflow-auto py-2'>{checks}</div>
296
+ </PopoverContent>
297
+ </Popover>
298
+ ) : (
299
+ checks
300
+ )}
301
+ </InputShell>
302
+ );
303
+ };