-
Notifications
You must be signed in to change notification settings - Fork 26
/
AdditionalProperties.vue
509 lines (481 loc) · 15.4 KB
/
AdditionalProperties.vue
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
<template>
<v-card
v-if="control.visible"
v-bind="vuetifyProps('v-card', { elevation: '0' })"
>
<v-card-title v-bind="vuetifyProps('v-card-title')">
<v-toolbar flat>
<v-toolbar-title>{{ additionalPropertiesTitle }}</v-toolbar-title>
<v-spacer></v-spacer>
<v-hover v-slot="{ hover }">
<v-text-field
v-disabled-icon-focus
:required="true"
:class="styles.control.input"
:error-messages="newPropertyErrors"
v-model="newPropertyName"
:clearable="hover"
:placeholder="placeholder"
:disabled="!control.enabled"
v-bind="vuetifyProps('v-text-field')"
>
</v-text-field>
</v-hover>
<v-tooltip bottom>
<template v-slot:activator="{ on: onTooltip }">
<v-btn
fab
text
elevation="0"
small
:aria-label="addToLabel"
v-on="onTooltip"
:disabled="addPropertyDisabled"
@click="addProperty"
>
<v-icon>mdi-plus</v-icon>
</v-btn>
</template>
{{ addToLabel }}
</v-tooltip>
</v-toolbar>
</v-card-title>
<v-container v-bind="vuetifyProps('v-container')">
<v-row
v-for="(element, index) in additionalPropertyItems"
:key="`${index}`"
>
<v-col>
<dispatch-renderer
v-if="element.schema && element.uischema"
:schema="element.schema"
:uischema="element.uischema"
:path="element.path"
:enabled="control.enabled"
:renderers="control.renderers"
:cells="control.cells"
/></v-col>
<v-col v-if="control.enabled" class="shrink">
<v-tooltip bottom>
<template v-slot:activator="{ on: onTooltip }">
<v-btn
v-on="onTooltip"
fab
text
elevation="0"
small
:aria-label="deleteLabel"
:disabled="removePropertyDisabled"
@click="removeProperty(element.propertyName)"
>
<v-icon class="notranslate">mdi-delete</v-icon>
</v-btn>
</template>
{{ deleteLabel }}
</v-tooltip></v-col
>
</v-row>
</v-container>
</v-card>
</template>
<script lang="ts">
import {
composePaths,
createControlElement,
createDefaultValue,
encode,
Generate,
getI18nKey,
GroupLayout,
JsonSchema,
JsonSchema7,
UISchemaElement,
validate,
} from '@jsonforms/core';
import {
DispatchRenderer,
useJsonFormsControlWithDetail,
} from '@jsonforms/vue2';
import Ajv, { ValidateFunction } from 'ajv';
import isPlainObject from 'lodash/isPlainObject';
import startCase from 'lodash/startCase';
import { defineComponent, PropType, ref } from 'vue';
import {
VBtn,
VCard,
VCardTitle,
VCol,
VContainer,
VHover,
VIcon,
VRow,
VSpacer,
VTextField,
VToolbar,
VToolbarTitle,
VTooltip,
} from 'vuetify/lib';
import { DisabledIconFocus } from '../../controls/directives';
import { useStyles } from '../../styles';
import {
useAjv,
useControlAppliedOptions,
useTranslator,
useVuetifyProps,
} from '../../util';
type Input = ReturnType<typeof useJsonFormsControlWithDetail>;
interface AdditionalPropertyType {
propertyName: string;
path: string;
schema: JsonSchema | undefined;
uischema: UISchemaElement | undefined;
}
const reuseAjvForSchema = (ajv: Ajv, schema: JsonSchema): Ajv => {
if (
Object.prototype.hasOwnProperty.call(schema, 'id') ||
Object.prototype.hasOwnProperty.call(schema, '$id')
) {
ajv.removeSchema(schema);
}
return ajv;
};
export default defineComponent({
name: 'additional-properties',
components: {
DispatchRenderer,
VCard,
VTooltip,
VToolbar,
VIcon,
VBtn,
VCardTitle,
VSpacer,
VToolbarTitle,
VTextField,
VContainer,
VRow,
VCol,
VHover,
},
directives: {
DisabledIconFocus,
},
props: {
input: {
type: Object as PropType<Input>,
required: true,
},
},
setup(props) {
const control = props.input.control;
const reservedPropertyNames = Object.keys(
(control.value.schema && control.value.schema.properties) || {}
);
const additionalKeys =
control.value.data && isPlainObject(control.value.data)
? Object.keys(control.value.data).filter(
(k) => !reservedPropertyNames.includes(k)
)
: [];
const toAdditionalPropertyType = (
propName: string,
propValue: any
): AdditionalPropertyType => {
let propSchema: JsonSchema | undefined = undefined;
let propUiSchema: UISchemaElement | undefined = undefined;
if (
control.value.schema &&
control.value.schema.patternProperties &&
typeof control.value.schema.patternProperties === 'object'
) {
const matchedPattern = Object.keys(
control.value.schema.patternProperties
).find((pattern) => new RegExp(pattern).test(propName));
if (matchedPattern) {
propSchema = control.value.schema.patternProperties[matchedPattern];
}
}
if (
!propSchema &&
control.value.schema &&
control.value.schema.additionalProperties &&
typeof control.value.schema.additionalProperties === 'object'
) {
propSchema = control.value.schema.additionalProperties;
}
if (!propSchema && propValue !== undefined) {
// can't find the propertySchema so use the schema based on the value
// this covers case where the data in invalid according to the schema
propSchema = Generate.jsonSchema(
{ prop: propValue },
{
additionalProperties: false,
required: () => false,
}
).properties?.prop;
}
if (propSchema) {
if (propSchema.type === 'object' || propSchema.type === 'array') {
propUiSchema = Generate.uiSchema(propSchema, 'Group');
(propUiSchema as GroupLayout).label =
propSchema.title ?? startCase(propName);
} else {
propUiSchema = createControlElement(
control.value.path + '/' + encode(propName)
);
}
}
return {
propertyName: propName,
path: composePaths(control.value.path, propName),
schema: propSchema,
uischema: propUiSchema,
};
};
const appliedOptions = useControlAppliedOptions(props.input);
const additionalPropertyItems = ref<AdditionalPropertyType[]>([]);
additionalKeys.forEach((propName) => {
const additionalProperty = toAdditionalPropertyType(
propName,
control.value.data?.[propName]
);
additionalPropertyItems.value.push(additionalProperty);
});
const styles = useStyles(control.value.uischema);
const newPropertyName = ref<string | null>('');
const ajv = useAjv();
let propertyNameSchema: JsonSchema7 | undefined = undefined;
let propertyNameValidator: ValidateFunction<unknown> | undefined =
undefined;
// TODO: create issue against jsonforms to add propertyNames into the JsonSchema interface
// propertyNames exist in draft-6 but not defined in the JsonSchema
if (
control.value.schema &&
(control.value.schema as any).propertyNames &&
typeof (control.value.schema as any).propertyNames === 'object'
) {
propertyNameSchema = (control.value.schema as any).propertyNames;
}
if (
control.value.schema &&
control.value.schema.patternProperties &&
typeof control.value.schema.additionalProperties !== 'object' &&
typeof control.value.schema.patternProperties === 'object'
) {
const matchPatternPropertiesKeys: JsonSchema7 = {
type: 'string',
pattern: Object.keys(control.value.schema.patternProperties).join('|'),
};
propertyNameSchema = propertyNameSchema
? { allOf: [propertyNameSchema, matchPatternPropertiesKeys] }
: matchPatternPropertiesKeys;
}
if (propertyNameSchema) {
propertyNameValidator = reuseAjvForSchema(
ajv,
propertyNameSchema
).compile(propertyNameSchema);
}
const vuetifyProps = useVuetifyProps(appliedOptions);
const t = useTranslator();
return {
t,
vuetifyProps,
ajv,
propertyNameValidator,
control,
styles,
appliedOptions,
additionalPropertyItems,
toAdditionalPropertyType,
newPropertyName,
};
},
computed: {
addPropertyDisabled(): boolean {
return (
// add is disabled because the overall control is disabled
!this.control.enabled ||
// add is disabled because of contraints
(this.appliedOptions.restrict && this.maxPropertiesReached) ||
// add is disabled because there are errors for the new property name or it is not specified
this.newPropertyErrors.length > 0 ||
!this.newPropertyName
);
},
maxPropertiesReached(): boolean {
return (
this.control.schema &&
this.control.schema.maxProperties !== undefined && // we have maxProperties constraint
this.control.data && // we have data to check
// the current number of properties in the object is greater or equals to the maxProperties
Object.keys(this.control.data).length >=
this.control.schema.maxProperties
);
},
removePropertyDisabled(): boolean {
return (
// add is disabled because the overall control is disabled
!this.control.enabled ||
// add is disabled because of contraints
(this.appliedOptions.restrict && this.minPropertiesReached)
);
},
minPropertiesReached(): boolean {
return (
this.control.schema &&
this.control.schema.minProperties !== undefined && // we have minProperties constraint
this.control.data && // we have data to check
// the current number of properties in the object is less or equals to the minProperties
Object.keys(this.control.data).length <=
this.control.schema.minProperties
);
},
newPropertyErrors(): string[] {
if (this.newPropertyName) {
const messages = this.propertyNameValidator
? (validate(this.propertyNameValidator, this.newPropertyName)
.map((error) => error.message)
.filter((message) => message) as string[])
: [];
if (
this.reservedPropertyNames.includes(this.newPropertyName) ||
this.additionalPropertyItems.find(
(ap) => ap.propertyName === this.newPropertyName
) !== undefined
) {
// already defined
messages.push(
`Property '${this.newPropertyName}' is already defined`
);
}
// JSONForms has special means for "[]." chars - those are part of the path composition so for not we can't support those without special handling
if (this.newPropertyName.includes('[')) {
messages.push('Property name contains invalid char: [');
}
if (this.newPropertyName.includes(']')) {
messages.push('Property name contains invalid char: ]');
}
if (this.newPropertyName.includes('.')) {
messages.push('Property name contains invalid char: .');
}
return messages;
}
return [];
},
placeholder(): string {
return this.t(this.i18nKey('newProperty.placeholder'), 'New Property');
},
reservedPropertyNames(): string[] {
return Object.keys(this.control.schema.properties || {});
},
additionalPropertiesTitle(): string | undefined {
const additionalProperties = this.control.schema.additionalProperties;
const label =
additionalProperties &&
typeof additionalProperties === 'object' &&
additionalProperties.title
? additionalProperties.title
: 'Additional Properties';
return this.t(this.i18nKey('title'), label);
},
addToLabel(): string {
return this.t(
this.i18nKey('btn.add'),
'Add to ${additionalProperties.title}',
{
additionalProperties: {
title: this.additionalPropertiesTitle,
},
}
);
},
deleteLabel(): string {
return this.t(
this.i18nKey('btn.delete'),
'Delete from ${additionalProperties.title}',
{
additionalProperties: {
title: this.additionalPropertiesTitle,
},
}
);
},
},
watch: {
'control.data': {
handler(newData) {
// revert back any undefined values back to the default value when the key is part of the addtional properties since we want to preserved the key
// for example when we have a string additonal property then when we clear the text component the componet by default sets the value to undefined to remove the property from the object - for additional properties we do not want that behaviour
if (this.control.data && typeof this.control.data === 'object') {
const keys = Object.keys(newData);
let hasChanges = false;
this.additionalPropertyItems.forEach((ap) => {
if (
ap.schema &&
(!keys.includes(ap.propertyName) ||
newData[ap.propertyName] === undefined ||
(newData[ap.propertyName] === null &&
ap.schema.type !== 'null')) // createDefaultValue will return null only when the ap.schema.type is 'null'
) {
const newValue = createDefaultValue(ap.schema);
hasChanges = newData[ap.propertyName] !== newValue;
newData[ap.propertyName] = newValue;
}
});
if (hasChanges) {
this.input.handleChange(this.control.path, newData);
}
}
},
deep: true,
},
},
methods: {
composePaths,
i18nKey(key: string): string {
return getI18nKey(
this.control.schema,
this.control.uischema,
this.control.path,
`additionalProperties.${key}`
);
},
addProperty() {
if (this.newPropertyName) {
const additionalProperty = this.toAdditionalPropertyType(
this.newPropertyName,
undefined
);
if (additionalProperty) {
this.additionalPropertyItems = [
...this.additionalPropertyItems,
additionalProperty,
];
}
if (
this.control.data &&
typeof this.control.data === 'object' &&
additionalProperty.schema
) {
this.control.data[this.newPropertyName] = createDefaultValue(
additionalProperty.schema
);
// we need always to preserve the key even when the value is "empty"
this.input.handleChange(this.control.path, this.control.data);
}
}
this.newPropertyName = '';
},
removeProperty(propName: string): void {
this.additionalPropertyItems = this.additionalPropertyItems.filter(
(d) => d.propertyName !== propName
);
if (this.control.data && typeof this.control.data === 'object') {
delete this.control.data[propName];
this.input.handleChange(this.control.path, this.control.data);
}
},
},
});
</script>