Skip to content

Commit c84f008

Browse files
feat: respect "default" values when creating new elements in an array
Initialize new array elements with their default values. Fixes default value returned for string schemas with a date format. Fixes #2195
1 parent f905c82 commit c84f008

File tree

5 files changed

+237
-24
lines changed

5 files changed

+237
-24
lines changed

packages/core/src/util/renderer.ts

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ import { createLabelDescriptionFrom } from './label';
5757
import type { CombinatorKeyword } from './combinators';
5858
import { moveDown, moveUp } from './array';
5959
import type { AnyAction, Dispatch } from './type';
60-
import { Resolve } from './util';
60+
import { Resolve, convertDateToString } from './util';
6161
import { composePaths, composeWithUi } from './path';
6262
import { CoreActions, update } from '../actions';
6363
import type { ErrorObject } from 'ajv';
@@ -78,6 +78,7 @@ import {
7878
arrayDefaultTranslations,
7979
ArrayTranslations,
8080
} from '../i18n/arrayTranslations';
81+
import cloneDeep from 'lodash/cloneDeep';
8182

8283
const isRequired = (
8384
schema: JsonSchema,
@@ -137,19 +138,22 @@ export const showAsRequired = (
137138
};
138139

139140
/**
140-
* Create a default value based on the given scheam.
141+
* Create a default value based on the given schema.
141142
* @param schema the schema for which to create a default value.
142143
* @returns {any}
143144
*/
144145
export const createDefaultValue = (schema: JsonSchema) => {
146+
if (schema.default !== undefined) {
147+
return extractDefaults(schema);
148+
}
145149
switch (schema.type) {
146150
case 'string':
147151
if (
148152
schema.format === 'date-time' ||
149153
schema.format === 'date' ||
150154
schema.format === 'time'
151155
) {
152-
return new Date();
156+
return convertDateToString(new Date(), schema.format);
153157
}
154158
return '';
155159
case 'integer':
@@ -161,11 +165,32 @@ export const createDefaultValue = (schema: JsonSchema) => {
161165
return [];
162166
case 'null':
163167
return null;
168+
case 'object':
169+
return extractDefaults(schema);
164170
default:
165171
return {};
166172
}
167173
};
168174

175+
/**
176+
* Returns the default value defined in the given schema.
177+
* @param schema the schema for which to create a default value.
178+
* @returns {any}
179+
*/
180+
export const extractDefaults = (schema: JsonSchema) => {
181+
if (schema.type === 'object' && schema.default === undefined) {
182+
const result: { [key: string]: any } = {};
183+
for (const key in schema.properties) {
184+
const property = schema.properties[key];
185+
if (property.default !== undefined) {
186+
result[key] = cloneDeep(property.default);
187+
}
188+
}
189+
return result;
190+
}
191+
return cloneDeep(schema.default);
192+
};
193+
169194
/**
170195
* Whether an element's description should be hidden.
171196
*

packages/core/src/util/util.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,49 @@ import { composePaths, toDataPathSegments } from './path';
3333
import { isEnabled, isVisible } from './runtime';
3434
import type Ajv from 'ajv';
3535

36+
/**
37+
* Returns the string representation of the given date. The format of the output string can be specified:
38+
* - 'date' for a date-only string (YYYY-MM-DD),
39+
* - 'time' for a time-only string (HH:mm:ss), or
40+
* - 'date-time' for a full date-time string in ISO format (YYYY-MM-DDTHH:mm:ss.sssZ).
41+
* If no format is specified, the full date-time ISO string is returned by default.
42+
*
43+
* @returns {string} A string representation of the date in the specified format.
44+
*
45+
* @example
46+
* // returns '2023-11-09'
47+
* convertDateToString(new Date('2023-11-09T14:22:54.131Z'), 'date');
48+
*
49+
* @example
50+
* // returns '14:22:54'
51+
* convertDateToString(new Date('2023-11-09T14:22:54.131Z'), 'time');
52+
*
53+
* @example
54+
* // returns '2023-11-09T14:22:54.131Z'
55+
* convertDateToString(new Date('2023-11-09T14:22:54.131Z'), 'date-time');
56+
*
57+
* @example
58+
* // returns '2023-11-09T14:22:54.131Z'
59+
* convertDateToString(new Date('2023-11-09T14:22:54.131Z'));
60+
*/
61+
export const convertDateToString = (
62+
date: Date,
63+
format?: 'date' | 'time' | 'date-time'
64+
): string => {
65+
//e.g. '2023-11-09T14:22:54.131Z'
66+
const dateString = date.toISOString();
67+
if (format === 'date-time') {
68+
return dateString;
69+
} else if (format === 'date') {
70+
// e.g. '2023-11-09'
71+
return dateString.split('T')[0];
72+
} else if (format === 'time') {
73+
//e.g. '14:22:54'
74+
return dateString.split('T')[1].split('.')[0];
75+
}
76+
return dateString;
77+
};
78+
3679
/**
3780
* Escape the given string such that it can be used as a class name,
3881
* i.e. hashes and slashes will be replaced.

packages/core/test/util/renderer.test.ts

Lines changed: 63 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ import { createAjv } from '../../src/util/validator';
7070
import { JsonSchema7 } from '../../src/models/jsonSchema7';
7171
import { defaultJsonFormsI18nState } from '../../src/reducers/i18n';
7272
import { i18nJsonSchema } from '../../src/i18n/i18nTypes';
73+
import { convertDateToString } from '../../src/util';
7374

7475
const middlewares: Redux.Middleware[] = [];
7576
const mockStore = configureStore<JsonFormsState>(middlewares);
@@ -494,29 +495,26 @@ test('mapDispatchToControlProps', (t) => {
494495
});
495496

496497
test('createDefaultValue', (t) => {
497-
t.true(
498-
_.isDate(
499-
createDefaultValue({
500-
type: 'string',
501-
format: 'date',
502-
})
503-
)
498+
t.is(
499+
createDefaultValue({
500+
type: 'string',
501+
format: 'date',
502+
}),
503+
convertDateToString(new Date(), 'date')
504504
);
505-
t.true(
506-
_.isDate(
507-
createDefaultValue({
508-
type: 'string',
509-
format: 'date-time',
510-
})
511-
)
505+
t.regex(
506+
createDefaultValue({
507+
type: 'string',
508+
format: 'date-time',
509+
}),
510+
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
512511
);
513-
t.true(
514-
_.isDate(
515-
createDefaultValue({
516-
type: 'string',
517-
format: 'time',
518-
})
519-
)
512+
t.regex(
513+
createDefaultValue({
514+
type: 'string',
515+
format: 'time',
516+
}),
517+
/^\d{2}:\d{2}:\d{2}$/
520518
);
521519
t.is(createDefaultValue({ type: 'string' }), '');
522520
t.is(createDefaultValue({ type: 'number' }), 0);
@@ -526,6 +524,50 @@ test('createDefaultValue', (t) => {
526524
t.is(createDefaultValue({ type: 'null' }), null);
527525
t.deepEqual(createDefaultValue({ type: 'object' }), {});
528526
t.deepEqual(createDefaultValue({ type: 'something' }), {});
527+
528+
// defaults:
529+
t.deepEqual(
530+
createDefaultValue({
531+
type: 'string',
532+
default: '2023-10-10',
533+
}),
534+
'2023-10-10'
535+
);
536+
t.is(
537+
createDefaultValue({ type: 'string', default: 'excellent' }),
538+
'excellent'
539+
);
540+
t.is(createDefaultValue({ type: 'number', default: 10 }), 10);
541+
t.is(createDefaultValue({ type: 'boolean', default: true }), true);
542+
t.is(createDefaultValue({ type: 'integer', default: 11 }), 11);
543+
t.deepEqual(createDefaultValue({ type: 'array', default: ['a', 'b', 'c'] }), [
544+
'a',
545+
'b',
546+
'c',
547+
]);
548+
t.deepEqual(createDefaultValue({ type: 'object', default: { foo: 'bar' } }), {
549+
foo: 'bar',
550+
});
551+
t.deepEqual(
552+
createDefaultValue({
553+
type: 'object',
554+
properties: {
555+
string1: { type: 'string', default: 'excellent' },
556+
string2: { type: 'string' },
557+
number: { type: 'number', default: 10 },
558+
int: { type: 'integer', default: 11 },
559+
bool: { type: 'boolean', default: true },
560+
array: { type: 'array', default: ['a', 'b', 'c'] },
561+
},
562+
}),
563+
{
564+
string1: 'excellent',
565+
number: 10,
566+
int: 11,
567+
bool: true,
568+
array: ['a', 'b', 'c'],
569+
}
570+
);
529571
});
530572

531573
test(`mapStateToJsonFormsRendererProps should use registered UI schema given ownProps schema`, (t) => {
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
The MIT License
3+
4+
Copyright (c) 2023 EclipseSource Munich
5+
https://github.com/eclipsesource/jsonforms
6+
7+
Permission is hereby granted, free of charge, to any person obtaining a copy
8+
of this software and associated documentation files (the 'Software'), to deal
9+
in the Software without restriction, including without limitation the rights
10+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
copies of the Software, and to permit persons to whom the Software is
12+
furnished to do so, subject to the following conditions:
13+
14+
The above copyright notice and this permission notice shall be included in
15+
all copies or substantial portions of the Software.
16+
17+
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
THE SOFTWARE.
24+
*/
25+
import { convertDateToString } from '@jsonforms/core';
26+
import { registerExamples } from '../register';
27+
28+
export const schema = {
29+
type: 'object',
30+
properties: {
31+
objectArray: {
32+
type: 'array',
33+
items: {
34+
type: 'object',
35+
properties: {
36+
name: {
37+
type: 'string',
38+
default: 'foo',
39+
},
40+
name_noDefault: {
41+
type: 'string',
42+
},
43+
description: {
44+
type: 'string',
45+
default: 'bar',
46+
},
47+
done: {
48+
type: 'boolean',
49+
default: false,
50+
},
51+
rating: {
52+
type: 'integer',
53+
default: 5,
54+
},
55+
cost: {
56+
type: 'number',
57+
default: 5.5,
58+
},
59+
date: {
60+
type: 'string',
61+
format: 'date',
62+
default: convertDateToString(new Date(), 'date'),
63+
},
64+
},
65+
},
66+
},
67+
stringArray: {
68+
type: 'array',
69+
items: {
70+
type: 'string',
71+
default: '123',
72+
},
73+
},
74+
},
75+
};
76+
77+
export const uischema = {
78+
type: 'VerticalLayout',
79+
elements: [
80+
{
81+
type: 'Control',
82+
scope: '#/properties/objectArray',
83+
},
84+
{
85+
type: 'Control',
86+
scope: '#/properties/stringArray',
87+
},
88+
],
89+
};
90+
91+
export const data = {};
92+
93+
registerExamples([
94+
{
95+
name: 'array-with-defaults',
96+
label: 'Array with defaults',
97+
data,
98+
schema,
99+
uischema,
100+
},
101+
]);

packages/examples/src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import * as arrayWithDetail from './examples/arrays-with-detail';
3535
import * as arrayWithDetailAndRule from './examples/arrays-with-detail-and-rule';
3636
import * as arrayWithCustomChildLabel from './examples/arrays-with-custom-element-label';
3737
import * as arrayWithSorting from './examples/arrays-with-sorting';
38+
import * as arrayWithDefaults from './examples/arrays-with-defaults';
3839
import * as stringArray from './examples/stringArray';
3940
import * as categorization from './examples/categorization';
4041
import * as stepper from './examples/categorization-stepper';
@@ -125,4 +126,5 @@ export {
125126
conditionalSchemaComposition,
126127
additionalErrors,
127128
issue_1884,
129+
arrayWithDefaults,
128130
};

0 commit comments

Comments
 (0)