-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfunctions.ts
688 lines (644 loc) · 18.1 KB
/
functions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
/* eslint-disable import/no-extraneous-dependencies */
import type { Experimental_ArrayMinItems, RJSFSchema, UiSchema } from '@rjsf/utils'
import intersection from 'lodash/intersection'
import kebabCase from 'lodash/kebabCase'
import uniq from 'lodash/uniq'
import {
ArrayFieldUiOptions,
CheckboxGroupUiOptions,
CheckboxUiOptions,
CustomComponentFieldUiOptions,
CustomComponentType,
DatePickerUiOptions,
FileUploadUiOptions,
InputUiOptions,
markdownTextPrefix,
ObjectFieldUiOptions,
RadioGroupUiOptions,
SchemaUiOptions,
SelectUiOptions,
TextAreaUiOptions,
TimePickerUiOptions,
} from './uiOptionsTypes'
export type Field = {
property: string
schema: () => RJSFSchema
uiSchema: () => UiSchema
required: boolean
skipUiSchema?: boolean
skipSchema?: boolean
}
type ObjectField = Omit<Field, 'property'> & {
property: string | null
fieldProperties: string[]
}
type ConditionalFields = {
condition: RJSFSchema
thenSchema: () => RJSFSchema
elseSchema?: () => RJSFSchema
uiSchema: () => UiSchema
fieldProperties: string[]
}
export type FieldType = Field | ConditionalFields | ObjectField
type BaseOptions = {
title: string
required?: boolean
}
export const select = (
property: string,
options: BaseOptions & {
options: {
value: string
title: string
description?: string
isDefault?: boolean
}[]
},
uiOptions: Omit<SelectUiOptions, 'selectOptions'>,
): Field => {
return {
property,
schema: () => ({
type: 'string',
title: options.title,
// This had to be changed from oneOf to enum because of this bug:
// https://jsonforms.discourse.group/t/function-nested-too-deeply-error-when-enum-has-many-options/1451
// For many options (250) it worked OK in Chrome, but in Firefox it was throwing an error:
// Form validation failed
// Array [ 0: Object { stack: "function nested too deeply", message: "Neznáma chyba" } ]
enum: options.options.map(({ value }) => value),
default: options.options.find(({ isDefault }) => isDefault)?.value,
}),
uiSchema: () => {
const selectOptionsArray = options.options.map(
({ value, title, description }) => [value, { title, description }] as const,
)
return {
'ui:widget': 'Select',
'ui:options': {
...uiOptions,
selectOptions: Object.fromEntries(selectOptionsArray),
},
}
},
required: Boolean(options.required),
}
}
export const selectMultiple = (
property: string,
options: BaseOptions & {
minItems?: number
maxItems?: number
options: {
value: string
title: string
description?: string
isDefault?: boolean
}[]
},
uiOptions: Omit<SelectUiOptions, 'selectOptions'>,
): Field => {
return {
property,
schema: () => ({
type: 'array',
title: options.title,
items: {
type: 'string',
// This had to be changed from oneOf to enum because of this bug:
// https://jsonforms.discourse.group/t/function-nested-too-deeply-error-when-enum-has-many-options/1451
// For many options (250) it worked OK in Chrome, but in Firefox it was throwing an error:
// Form validation failed
// Array [ 0: Object { stack: "function nested too deeply", message: "Neznáma chyba" } ]
enum: options.options.map(({ value }) => value),
},
minItems: options.minItems ?? options.required ? 1 : undefined,
maxItems: options.maxItems,
uniqueItems: true,
default: options.options.filter(({ isDefault }) => isDefault).map(({ value }) => value),
}),
uiSchema: () => {
const selectOptionsArray = options.options.map(
({ value, title, description }) => [value, { title, description }] as const,
)
return {
'ui:widget': 'Select',
'ui:options': {
...uiOptions,
selectOptions: Object.fromEntries(selectOptionsArray),
},
}
},
required: Boolean(options.required),
}
}
export const input = (
property: string,
options: BaseOptions &
(
| {
type?: 'text'
// TODO: Add more formats
format?: 'zip' | 'ratio' | 'ico'
pattern?: RegExp
}
| {
type: 'password' | 'email' | 'tel'
}
) & { default?: string },
uiOptions: Omit<InputUiOptions, 'type'>,
): Field => {
return {
property,
schema: () => {
if ('pattern' in options && 'format' in options) {
// eslint-disable-next-line no-console
console.error(
`Input: ${property} has both pattern and format, only one of them can be provided`,
)
}
const getFormat = () => {
if (options.type == null || options.type === 'text') {
return options.format
}
if (options.type === 'email') {
return 'email'
}
if (options.type === 'tel') {
return 'phone-number'
}
// eslint-disable-next-line unicorn/no-useless-undefined
return undefined
}
const getPattern = () => {
if (options.type == null || options.type === 'text') {
return options.pattern?.source
}
// eslint-disable-next-line unicorn/no-useless-undefined
return undefined
}
return {
type: 'string',
title: options.title,
format: getFormat(),
pattern: getPattern(),
default: options.default,
}
},
uiSchema: () => ({
'ui:widget': 'Input',
'ui:label': false,
'ui:options': { ...uiOptions, type: options.type ?? 'text' },
}),
required: Boolean(options.required),
}
}
export const number = (
property: string,
options: BaseOptions & {
type?: 'number' | 'integer'
default?: number
minimum?: number
exclusiveMinimum?: number
maximum?: number
exclusiveMaximum?: number
},
uiOptions: Omit<InputUiOptions, 'type'>,
): Field => {
return {
property,
schema: () => ({
type: options.type ?? 'number',
title: options.title,
default: options.default,
minimum: options.minimum,
exclusiveMinimum: options.exclusiveMinimum,
maximum: options.maximum,
exclusiveMaximum: options.exclusiveMaximum,
}),
uiSchema: () => ({
'ui:widget': 'Input',
'ui:label': false,
'ui:options': { ...uiOptions, type: 'number' },
}),
required: Boolean(options.required),
}
}
type StringToType<T> = T extends 'string'
? string
: T extends 'number'
? number
: T extends 'boolean'
? boolean
: never
export const radioGroup = <T extends 'string' | 'number' | 'boolean'>(
property: string,
options: BaseOptions & {
type: T
options: {
value: StringToType<T>
title: string
description?: string
isDefault?: boolean
}[]
},
uiOptions: Omit<RadioGroupUiOptions, 'radioOptions'>,
): Field => {
return {
property,
schema: () => ({
type: options.type,
title: options.title,
default: options.options.find(({ isDefault }) => isDefault)?.value,
oneOf: options.options.map(({ value, title }) => ({ const: value, title })),
}),
uiSchema: () => ({
'ui:widget': 'RadioGroup',
'ui:options': {
...uiOptions,
radioOptions: options.options
// These are only used as a lookup for the description, so we need only those that have it
.filter(({ description }) => description)
.map(({ value, description }) => ({ value, description })),
},
}),
required: Boolean(options.required),
}
}
export const textArea = (
property: string,
options: BaseOptions,
uiOptions: TextAreaUiOptions,
): Field => {
return {
property,
schema: () => ({ type: 'string', title: options.title }),
uiSchema: () => ({
'ui:widget': 'TextArea',
'ui:label': false,
'ui:options': uiOptions,
}),
required: Boolean(options.required),
}
}
export const checkbox = (
property: string,
options: BaseOptions & { default?: boolean },
uiOptions: CheckboxUiOptions,
): Field => {
return {
property,
schema: () => ({
type: 'boolean',
title: options.title,
default: options.default,
}),
uiSchema: () => ({
'ui:widget': 'Checkbox',
'ui:options': uiOptions,
}),
required: Boolean(options.required),
}
}
export const checkboxGroup = (
property: string,
options: BaseOptions & {
minItems?: number
maxItems?: number
options: {
value: string
title: string
description?: string
isDefault?: boolean
}[]
},
uiOptions: CheckboxGroupUiOptions,
): Field => {
return {
property,
schema: () => ({
type: 'array',
title: options.title,
minItems: options.minItems ?? options.required ? 1 : undefined,
maxItems: options.maxItems,
uniqueItems: true,
items: {
anyOf: options.options.map(({ value, title }) => ({ const: value, title })),
},
default: options.options.filter(({ isDefault }) => isDefault).map(({ value }) => value),
}),
uiSchema: () => ({
'ui:widget': 'CheckboxGroup',
'ui:options': uiOptions,
}),
required: Boolean(options.required),
}
}
export const fileUpload = (
property: string,
options: BaseOptions & { multiple?: boolean },
uiOptions: FileUploadUiOptions,
): Field => {
return {
property,
schema: () => {
const base = {
title: options.title,
}
if (options.multiple) {
return {
...base,
type: 'array',
items: {
type: 'string',
file: true,
},
minItems: options.required ? 1 : undefined,
default: [],
}
}
return {
...base,
type: 'string',
file: true,
}
},
uiSchema: () => ({ 'ui:widget': 'FileUpload', 'ui:options': uiOptions }),
required: Boolean(options.required),
}
}
export const datePicker = (
property: string,
options: BaseOptions & { default?: string },
uiOptions: DatePickerUiOptions,
): Field => {
return {
property,
schema: () => ({
type: 'string',
format: 'date',
title: options.title,
default: options.default,
}),
uiSchema: () => ({
'ui:widget': 'DatePicker',
'ui:options': uiOptions,
}),
required: Boolean(options.required),
}
}
export const timePicker = (
property: string,
options: BaseOptions & { default?: string },
uiOptions: TimePickerUiOptions,
): Field => {
return {
property,
schema: () => ({
type: 'string',
format: 'localTime',
title: options.title,
default: options.default,
}),
uiSchema: () => ({
'ui:widget': 'TimePicker',
'ui:options': uiOptions,
}),
required: Boolean(options.required),
}
}
let customComponentCounter = 0
/**
* This is a special field that represents no data in the schema. It is a "hacky way", but the easiest how to display
* custom components in the UI anywhere we need.
*/
export const customComponentsField = (
customComponents: CustomComponentType | CustomComponentType[],
uiOptions: Omit<CustomComponentFieldUiOptions, 'customComponents'>,
): Field => {
customComponentCounter += 1
return {
// Random property name to avoid collisions
property: `customComponent${customComponentCounter}_gRbYIKNcAF`,
schema: () => ({
anyOf: [{}],
}),
uiSchema: () => {
const array = Array.isArray(customComponents) ? customComponents : [customComponents]
return {
'ui:widget': 'CustomComponents',
'ui:options': { ...uiOptions, customComponents: array },
}
},
required: false,
}
}
/**
* Object is the most complex field type to handle. For example, step is an instance of object. In JSONSchema, ordinary
* fields are located in the `properties` key, while conditional fields are located in the `allOf` key. However, to
* simplify the usage of the generator we provide a single interface for both ordinary and conditional fields. This
* function splits them to their respective locations.
*/
export const object = (
property: string | null,
options: { required?: boolean },
uiOptions: ObjectFieldUiOptions,
fields: FieldType[],
): ObjectField => {
const ordinaryFields = fields.filter((field) => !('condition' in field)) as Field[]
const ordinaryFieldsWithSchema = ordinaryFields.filter((field) => !field.skipSchema)
const ordinaryFieldsWithUiSchema = ordinaryFields.filter((field) => !field.skipUiSchema)
const conditionalFields = fields.filter((field) => 'condition' in field) as ConditionalFields[]
const fieldProperties = uniq(
fields
.filter((field) => ('skipUiSchema' in field ? !field.skipUiSchema : true))
.flatMap((field) => ('condition' in field ? field.fieldProperties : [field.property]))
.filter((field) => field !== null) as string[],
)
return {
property,
schema: () => {
const allOf = conditionalFields.map((field) => ({
if: field.condition,
then: field.thenSchema(),
else: field.elseSchema?.(),
}))
return {
type: 'object',
properties: Object.fromEntries(
ordinaryFieldsWithSchema.map((field) => [field.property, field.schema()]),
),
required: ordinaryFieldsWithSchema
.filter((field) => field.required)
.map((field) => field.property),
allOf: allOf.length > 0 ? allOf : undefined,
}
},
uiSchema: () => {
const ordinaryFieldsUiSchema = Object.fromEntries(
ordinaryFieldsWithUiSchema.map((field) => [field.property, field.uiSchema()]),
)
const conditionalFieldsUiSchema = conditionalFields.reduce(
(acc, field) => ({ ...acc, ...field.uiSchema() }),
{},
)
return {
...ordinaryFieldsUiSchema,
...conditionalFieldsUiSchema,
// As the order of the properties is not guaranteed in JSON and is lost when having the fields both in `properties`
// and `allOf`, we need to provide it manually.
'ui:order': fieldProperties,
'ui:options': uiOptions,
}
},
required: Boolean(options.required),
fieldProperties,
}
}
export const arrayField = (
property: string,
options: BaseOptions & { minItems?: number; maxItems?: number },
uiOptions: ArrayFieldUiOptions,
fields: FieldType[],
): Field => {
const { schema: objectSchema, uiSchema: objectUiSchema } = object(null, {}, {}, fields)
return {
property,
schema: () => ({
title: options.title,
type: 'array',
items: objectSchema(),
minItems: options.minItems ?? options.required ? 1 : undefined,
maxItems: options.maxItems,
overrideArrayMinItemsBehaviour: {
populate: 'requiredOnly',
} satisfies Experimental_ArrayMinItems,
}),
uiSchema: () => ({
'ui:options': uiOptions,
items: objectUiSchema(),
}),
required: Boolean(options.required),
}
}
export const step = (
property: string,
options: {
title: string
description?: string
stepperTitle?: string
customHash?: string
},
fields: FieldType[],
) => {
const { schema, uiSchema } = object(property, { required: true }, {}, fields)
const getHash = () => {
if (options.customHash) {
return options.customHash
}
if (options.stepperTitle) {
return kebabCase(options.stepperTitle)
}
return kebabCase(options.title)
}
return {
property,
schema: () => ({
type: 'object',
properties: {
[property]: {
title: options.title,
description: options.description,
stepperTitle: options.stepperTitle,
hash: getHash(),
...schema(),
},
},
required: [property],
}),
uiSchema,
}
}
export const conditionalStep = (
property: string,
condition: RJSFSchema,
options: {
title: string
customHash?: string
},
fields: FieldType[],
) => {
const { schema, uiSchema } = step(property, options, fields)
return {
property,
schema: () => ({ if: condition, then: schema() }),
uiSchema: () => uiSchema(),
required: true,
}
}
export const conditionalFields = (
condition: RJSFSchema,
thenFields: FieldType[],
elseFields: FieldType[] = [],
): ConditionalFields => {
const {
schema: thenSchema,
uiSchema: thenUiSchema,
fieldProperties: thenFieldProperties,
} = object(null, {}, {}, thenFields)
const {
schema: elseSchema,
uiSchema: elseUiSchema,
fieldProperties: elseFieldProperties,
} = object(null, {}, {}, elseFields)
return {
condition,
thenSchema,
elseSchema: elseFields.length > 0 ? elseSchema : undefined,
uiSchema: () => {
const intersectionProperties = intersection(thenFieldProperties, elseFieldProperties)
if (intersectionProperties.length > 0) {
// eslint-disable-next-line no-console
console.warn(
`Conditional fields: ${intersectionProperties.join(
', ',
)} is in both then and else uiSchema, it will be overwritten by the else uiSchema`,
)
}
return { ...thenUiSchema(), ...(elseFields.length > 0 ? elseUiSchema() : {}) }
},
fieldProperties: [...thenFieldProperties, ...elseFieldProperties],
}
}
export const schema = (
options: {
pospID: string
pospVersion: string
title: string
description?: string
},
uiOptions: SchemaUiOptions,
steps: ReturnType<typeof step | typeof conditionalStep>[],
) => {
return {
schema: { ...options, allOf: steps.map((stepInner) => stepInner.schema()) },
uiSchema: {
...Object.fromEntries(steps.map((stepInner) => [stepInner.property, stepInner.uiSchema()])),
'ui:options': uiOptions,
'ui:hideError': true,
},
}
}
// TODO: Document
export const skipUiSchema = <F extends Field | ObjectField>(field: F): F => {
return { ...field, skipUiSchema: true }
}
// TODO: Document
export const skipSchema = <F extends Field | ObjectField>(field: F): F => {
return { ...field, skipSchema: true }
}
/**
* If text contains markdown, it is still string, to distinguish it from normal text, we need to prefix it in order to
* detect that it is markdown when used in component.
*/
export const markdownText = (text: string) => `${markdownTextPrefix}${text}`