Skip to content

Commit

Permalink
feat: respect "default" values when creating new elements in an array
Browse files Browse the repository at this point in the history
Initialize new array elements with their default values.
Fixes default value returned for string schemas with a date format.

Fixes #2195
  • Loading branch information
AlexandraBuzila committed Nov 9, 2023
1 parent f905c82 commit c84f008
Show file tree
Hide file tree
Showing 5 changed files with 237 additions and 24 deletions.
31 changes: 28 additions & 3 deletions packages/core/src/util/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ import { createLabelDescriptionFrom } from './label';
import type { CombinatorKeyword } from './combinators';
import { moveDown, moveUp } from './array';
import type { AnyAction, Dispatch } from './type';
import { Resolve } from './util';
import { Resolve, convertDateToString } from './util';
import { composePaths, composeWithUi } from './path';
import { CoreActions, update } from '../actions';
import type { ErrorObject } from 'ajv';
Expand All @@ -78,6 +78,7 @@ import {
arrayDefaultTranslations,
ArrayTranslations,
} from '../i18n/arrayTranslations';
import cloneDeep from 'lodash/cloneDeep';

const isRequired = (
schema: JsonSchema,
Expand Down Expand Up @@ -137,19 +138,22 @@ export const showAsRequired = (
};

/**
* Create a default value based on the given scheam.
* Create a default value based on the given schema.
* @param schema the schema for which to create a default value.
* @returns {any}
*/
export const createDefaultValue = (schema: JsonSchema) => {
if (schema.default !== undefined) {
return extractDefaults(schema);
}
switch (schema.type) {
case 'string':
if (
schema.format === 'date-time' ||
schema.format === 'date' ||
schema.format === 'time'
) {
return new Date();
return convertDateToString(new Date(), schema.format);
}
return '';
case 'integer':
Expand All @@ -161,11 +165,32 @@ export const createDefaultValue = (schema: JsonSchema) => {
return [];
case 'null':
return null;
case 'object':
return extractDefaults(schema);
default:
return {};
}
};

/**
* Returns the default value defined in the given schema.
* @param schema the schema for which to create a default value.
* @returns {any}
*/
export const extractDefaults = (schema: JsonSchema) => {
if (schema.type === 'object' && schema.default === undefined) {
const result: { [key: string]: any } = {};
for (const key in schema.properties) {
const property = schema.properties[key];
if (property.default !== undefined) {
result[key] = cloneDeep(property.default);
}
}
return result;
}
return cloneDeep(schema.default);
};

/**
* Whether an element's description should be hidden.
*
Expand Down
43 changes: 43 additions & 0 deletions packages/core/src/util/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,49 @@ import { composePaths, toDataPathSegments } from './path';
import { isEnabled, isVisible } from './runtime';
import type Ajv from 'ajv';

/**
* Returns the string representation of the given date. The format of the output string can be specified:
* - 'date' for a date-only string (YYYY-MM-DD),
* - 'time' for a time-only string (HH:mm:ss), or
* - 'date-time' for a full date-time string in ISO format (YYYY-MM-DDTHH:mm:ss.sssZ).
* If no format is specified, the full date-time ISO string is returned by default.
*
* @returns {string} A string representation of the date in the specified format.
*
* @example
* // returns '2023-11-09'
* convertDateToString(new Date('2023-11-09T14:22:54.131Z'), 'date');
*
* @example
* // returns '14:22:54'
* convertDateToString(new Date('2023-11-09T14:22:54.131Z'), 'time');
*
* @example
* // returns '2023-11-09T14:22:54.131Z'
* convertDateToString(new Date('2023-11-09T14:22:54.131Z'), 'date-time');
*
* @example
* // returns '2023-11-09T14:22:54.131Z'
* convertDateToString(new Date('2023-11-09T14:22:54.131Z'));
*/
export const convertDateToString = (
date: Date,
format?: 'date' | 'time' | 'date-time'
): string => {
//e.g. '2023-11-09T14:22:54.131Z'
const dateString = date.toISOString();
if (format === 'date-time') {
return dateString;
} else if (format === 'date') {
// e.g. '2023-11-09'
return dateString.split('T')[0];
} else if (format === 'time') {
//e.g. '14:22:54'
return dateString.split('T')[1].split('.')[0];
}
return dateString;
};

/**
* Escape the given string such that it can be used as a class name,
* i.e. hashes and slashes will be replaced.
Expand Down
84 changes: 63 additions & 21 deletions packages/core/test/util/renderer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ import { createAjv } from '../../src/util/validator';
import { JsonSchema7 } from '../../src/models/jsonSchema7';
import { defaultJsonFormsI18nState } from '../../src/reducers/i18n';
import { i18nJsonSchema } from '../../src/i18n/i18nTypes';
import { convertDateToString } from '../../src/util';

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

test('createDefaultValue', (t) => {
t.true(
_.isDate(
createDefaultValue({
type: 'string',
format: 'date',
})
)
t.is(
createDefaultValue({
type: 'string',
format: 'date',
}),
convertDateToString(new Date(), 'date')
);
t.true(
_.isDate(
createDefaultValue({
type: 'string',
format: 'date-time',
})
)
t.regex(
createDefaultValue({
type: 'string',
format: 'date-time',
}),
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
);
t.true(
_.isDate(
createDefaultValue({
type: 'string',
format: 'time',
})
)
t.regex(
createDefaultValue({
type: 'string',
format: 'time',
}),
/^\d{2}:\d{2}:\d{2}$/
);
t.is(createDefaultValue({ type: 'string' }), '');
t.is(createDefaultValue({ type: 'number' }), 0);
Expand All @@ -526,6 +524,50 @@ test('createDefaultValue', (t) => {
t.is(createDefaultValue({ type: 'null' }), null);
t.deepEqual(createDefaultValue({ type: 'object' }), {});
t.deepEqual(createDefaultValue({ type: 'something' }), {});

// defaults:
t.deepEqual(
createDefaultValue({
type: 'string',
default: '2023-10-10',
}),
'2023-10-10'
);
t.is(
createDefaultValue({ type: 'string', default: 'excellent' }),
'excellent'
);
t.is(createDefaultValue({ type: 'number', default: 10 }), 10);
t.is(createDefaultValue({ type: 'boolean', default: true }), true);
t.is(createDefaultValue({ type: 'integer', default: 11 }), 11);
t.deepEqual(createDefaultValue({ type: 'array', default: ['a', 'b', 'c'] }), [
'a',
'b',
'c',
]);
t.deepEqual(createDefaultValue({ type: 'object', default: { foo: 'bar' } }), {
foo: 'bar',
});
t.deepEqual(
createDefaultValue({
type: 'object',
properties: {
string1: { type: 'string', default: 'excellent' },
string2: { type: 'string' },
number: { type: 'number', default: 10 },
int: { type: 'integer', default: 11 },
bool: { type: 'boolean', default: true },
array: { type: 'array', default: ['a', 'b', 'c'] },
},
}),
{
string1: 'excellent',
number: 10,
int: 11,
bool: true,
array: ['a', 'b', 'c'],
}
);
});

test(`mapStateToJsonFormsRendererProps should use registered UI schema given ownProps schema`, (t) => {
Expand Down
101 changes: 101 additions & 0 deletions packages/examples/src/examples/arrays-with-defaults.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
The MIT License
Copyright (c) 2023 EclipseSource Munich
https://github.com/eclipsesource/jsonforms
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { convertDateToString } from '@jsonforms/core';
import { registerExamples } from '../register';

export const schema = {
type: 'object',
properties: {
objectArray: {
type: 'array',
items: {
type: 'object',
properties: {
name: {
type: 'string',
default: 'foo',
},
name_noDefault: {
type: 'string',
},
description: {
type: 'string',
default: 'bar',
},
done: {
type: 'boolean',
default: false,
},
rating: {
type: 'integer',
default: 5,
},
cost: {
type: 'number',
default: 5.5,
},
date: {
type: 'string',
format: 'date',
default: convertDateToString(new Date(), 'date'),
},
},
},
},
stringArray: {
type: 'array',
items: {
type: 'string',
default: '123',
},
},
},
};

export const uischema = {
type: 'VerticalLayout',
elements: [
{
type: 'Control',
scope: '#/properties/objectArray',
},
{
type: 'Control',
scope: '#/properties/stringArray',
},
],
};

export const data = {};

registerExamples([
{
name: 'array-with-defaults',
label: 'Array with defaults',
data,
schema,
uischema,
},
]);
2 changes: 2 additions & 0 deletions packages/examples/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import * as arrayWithDetail from './examples/arrays-with-detail';
import * as arrayWithDetailAndRule from './examples/arrays-with-detail-and-rule';
import * as arrayWithCustomChildLabel from './examples/arrays-with-custom-element-label';
import * as arrayWithSorting from './examples/arrays-with-sorting';
import * as arrayWithDefaults from './examples/arrays-with-defaults';
import * as stringArray from './examples/stringArray';
import * as categorization from './examples/categorization';
import * as stepper from './examples/categorization-stepper';
Expand Down Expand Up @@ -125,4 +126,5 @@ export {
conditionalSchemaComposition,
additionalErrors,
issue_1884,
arrayWithDefaults,
};

0 comments on commit c84f008

Please sign in to comment.