Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/datepicker validation #2200

Merged
merged 1 commit into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/core/src/util/defaultDateFormat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
The MIT License

Copyright (c) 2023-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.
*/

export const defaultDateFormat = 'YYYY-MM-DD';
export const defaultTimeFormat = 'HH:mm:ss';
export const defaultDateTimeFormat = 'YYYY-MM-DDTHH:mm:ss.sssZ';
1 change: 1 addition & 0 deletions packages/core/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ export * from './type';
export * from './uischema';
export * from './util';
export * from './validator';
export * from './defaultDateFormat';
4 changes: 2 additions & 2 deletions packages/examples/src/examples/dates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,12 @@ export const uischema = {
export const data = {
schemaBased: {
date: new Date().toISOString().substr(0, 10),
time: '13:37',
time: '13:37:00',
datetime: new Date().toISOString(),
},
uiSchemaBased: {
date: new Date().toISOString().substr(0, 10),
time: '13:37',
time: '13:37:00',
datetime: '1999/12/11 10:05 am',
},
};
Expand Down
3 changes: 2 additions & 1 deletion packages/material-renderers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@
},
"testEnvironment": "jsdom",
"testMatch": [
"**/test/**/*.test.tsx"
"**/test/**/*.test.tsx",
"**/test/**.test.ts"
],
"testPathIgnorePatterns": [
"/node_modules/",
Expand Down
34 changes: 29 additions & 5 deletions packages/material-renderers/src/controls/MaterialDateControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@
THE SOFTWARE.
*/
import merge from 'lodash/merge';
import React, { useMemo } from 'react';
import React, { useCallback, useMemo, useState } from 'react';
import {
ControlProps,
defaultDateFormat,
isDateControl,
isDescriptionHidden,
RankedTester,
Expand All @@ -35,7 +36,12 @@ import { withJsonFormsControlProps } from '@jsonforms/react';
import { FormHelperText, Hidden } from '@mui/material';
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { createOnChangeHandler, getData, useFocus } from '../util';
import {
createOnBlurHandler,
createOnChangeHandler,
getData,
useFocus,
} from '../util';

export const MaterialDateControl = (props: ControlProps) => {
const [focused, onFocus, onBlur] = useFocus();
Expand All @@ -62,8 +68,10 @@ export const MaterialDateControl = (props: ControlProps) => {
appliedUiSchemaOptions.showUnfocusedDescription
);

const [key, setKey] = useState<number>(0);

const format = appliedUiSchemaOptions.dateFormat ?? 'YYYY-MM-DD';
const saveFormat = appliedUiSchemaOptions.dateSaveFormat ?? 'YYYY-MM-DD';
const saveFormat = appliedUiSchemaOptions.dateSaveFormat ?? defaultDateFormat;

const views = appliedUiSchemaOptions.views ?? ['year', 'day'];

Expand All @@ -73,20 +81,36 @@ export const MaterialDateControl = (props: ControlProps) => {
? errors
: null;
const secondFormHelperText = showDescription && !isValid ? errors : null;

const updateChild = useCallback(() => setKey((key) => key + 1), []);

const onChange = useMemo(
() => createOnChangeHandler(path, handleChange, saveFormat),
[path, handleChange, saveFormat]
);

const onBlurHandler = useMemo(
() =>
createOnBlurHandler(
path,
handleChange,
format,
saveFormat,
updateChild,
onBlur
),
[path, handleChange, format, saveFormat, updateChild]
);
const value = getData(data, saveFormat);

return (
<Hidden xsUp={!visible}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
key={key}
label={label}
value={value}
onChange={onChange}
onAccept={onChange}
format={format}
views={views}
disabled={!enabled}
Expand All @@ -109,7 +133,7 @@ export const MaterialDateControl = (props: ControlProps) => {
},
InputLabelProps: data ? { shrink: true } : undefined,
onFocus: onFocus,
onBlur: onBlur,
onBlur: onBlurHandler,
},
}}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import React, { useMemo } from 'react';
import React, { useCallback, useMemo, useState } from 'react';
import merge from 'lodash/merge';
import {
ControlProps,
defaultDateTimeFormat,
isDateTimeControl,
isDescriptionHidden,
RankedTester,
Expand All @@ -35,7 +36,12 @@ import { withJsonFormsControlProps } from '@jsonforms/react';
import { FormHelperText, Hidden } from '@mui/material';
import { DateTimePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { createOnChangeHandler, getData, useFocus } from '../util';
import {
createOnBlurHandler,
createOnChangeHandler,
getData,
useFocus,
} from '../util';

export const MaterialDateTimeControl = (props: ControlProps) => {
const [focused, onFocus, onBlur] = useFocus();
Expand Down Expand Up @@ -64,7 +70,10 @@ export const MaterialDateTimeControl = (props: ControlProps) => {
);

const format = appliedUiSchemaOptions.dateTimeFormat ?? 'YYYY-MM-DD HH:mm';
const saveFormat = appliedUiSchemaOptions.dateTimeSaveFormat ?? undefined;
const saveFormat =
appliedUiSchemaOptions.dateTimeSaveFormat ?? defaultDateTimeFormat;

const [key, setKey] = useState<number>(0);

const views = appliedUiSchemaOptions.views ?? [
'year',
Expand All @@ -80,20 +89,35 @@ export const MaterialDateTimeControl = (props: ControlProps) => {
: null;
const secondFormHelperText = showDescription && !isValid ? errors : null;

const updateChild = useCallback(() => setKey((key) => key + 1), []);

const onChange = useMemo(
() => createOnChangeHandler(path, handleChange, saveFormat),
[path, handleChange, saveFormat]
);

const onBlurHandler = useMemo(
() =>
createOnBlurHandler(
path,
handleChange,
format,
saveFormat,
updateChild,
onBlur
),
[path, handleChange, format, saveFormat, updateChild]
);
const value = getData(data, saveFormat);

return (
<Hidden xsUp={!visible}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DateTimePicker
key={key}
label={label}
value={value}
onChange={onChange}
onAccept={onChange}
format={format}
ampm={!!appliedUiSchemaOptions.ampm}
views={views}
Expand All @@ -117,7 +141,7 @@ export const MaterialDateTimeControl = (props: ControlProps) => {
},
InputLabelProps: data ? { shrink: true } : undefined,
onFocus: onFocus,
onBlur: onBlur,
onBlur: onBlurHandler,
},
}}
/>
Expand Down
34 changes: 29 additions & 5 deletions packages/material-renderers/src/controls/MaterialTimeControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,26 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import React, { useMemo } from 'react';
import React, { useCallback, useMemo, useState } from 'react';
import merge from 'lodash/merge';
import {
ControlProps,
isTimeControl,
isDescriptionHidden,
RankedTester,
rankWith,
defaultTimeFormat,
} from '@jsonforms/core';
import { withJsonFormsControlProps } from '@jsonforms/react';
import { FormHelperText, Hidden } from '@mui/material';
import { TimePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { createOnChangeHandler, getData, useFocus } from '../util';
import {
createOnBlurHandler,
createOnChangeHandler,
getData,
useFocus,
} from '../util';

export const MaterialTimeControl = (props: ControlProps) => {
const [focused, onFocus, onBlur] = useFocus();
Expand All @@ -56,6 +62,8 @@ export const MaterialTimeControl = (props: ControlProps) => {
const appliedUiSchemaOptions = merge({}, config, uischema.options);
const isValid = errors.length === 0;

const [key, setKey] = useState<number>(0);

const showDescription = !isDescriptionHidden(
visible,
description,
Expand All @@ -64,7 +72,7 @@ export const MaterialTimeControl = (props: ControlProps) => {
);

const format = appliedUiSchemaOptions.timeFormat ?? 'HH:mm';
const saveFormat = appliedUiSchemaOptions.timeSaveFormat ?? 'HH:mm:ss';
const saveFormat = appliedUiSchemaOptions.timeSaveFormat ?? defaultTimeFormat;
Comment on lines 74 to +75
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If a time is missing the seconds, the UI now doesn't show it anymore. See the dates example. Is there a way to still show it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The previous implementation didn’t support formats without seconds by default. So this wouldn't be an unexpected/new behavior.
Currently I adjusted the examples in our application to use the HH:mm:ss format.
But it is also possible to check if the time-value uses the HH:mm:ss or HH:mm format and set the saveFormat accordingly. Would you prefer this solution?


const views = appliedUiSchemaOptions.views ?? ['hours', 'minutes'];

Expand All @@ -75,19 +83,35 @@ export const MaterialTimeControl = (props: ControlProps) => {
: null;
const secondFormHelperText = showDescription && !isValid ? errors : null;

const updateChild = useCallback(() => setKey((key) => key + 1), []);

const onChange = useMemo(
() => createOnChangeHandler(path, handleChange, saveFormat),
[path, handleChange, saveFormat]
);

const onBlurHandler = useMemo(
() =>
createOnBlurHandler(
path,
handleChange,
format,
saveFormat,
updateChild,
onBlur
),
[path, handleChange, format, saveFormat, updateChild]
);
const value = getData(data, saveFormat);

return (
<Hidden xsUp={!visible}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<TimePicker
key={key}
label={label}
value={value}
onChange={onChange}
onAccept={onChange}
format={format}
ampm={!!appliedUiSchemaOptions.ampm}
views={views}
Expand All @@ -111,7 +135,7 @@ export const MaterialTimeControl = (props: ControlProps) => {
},
InputLabelProps: data ? { shrink: true } : undefined,
onFocus: onFocus,
onBlur: onBlur,
onBlur: onBlurHandler,
},
}}
/>
Expand Down
51 changes: 45 additions & 6 deletions packages/material-renderers/src/util/datejs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,56 @@ export const createOnChangeHandler =
(
path: string,
handleChange: (path: string, value: any) => void,
saveFormat: string | undefined
saveFormat: string
) =>
(time: dayjs.Dayjs) => {
if (!time) {
(value: dayjs.Dayjs) => {
if (!value) {
handleChange(path, undefined);
return;
} else if (value.toString() !== 'Invalid Date') {
const formatedDate = formatDate(value, saveFormat);
handleChange(path, formatedDate);
}
const result = dayjs(time).format(saveFormat);
handleChange(path, result);
};

export const createOnBlurHandler =
(
path: string,
handleChange: (path: string, value: any) => void,
format: string,
saveFormat: string,
rerenderChild: () => void,
onBlur: () => void
) =>
(e: React.FocusEvent<HTMLTextAreaElement | HTMLInputElement, Element>) => {
const date = dayjs(e.target.value, format);
const formatedDate = formatDate(date, saveFormat);
if (formatedDate.toString() === 'Invalid Date') {
handleChange(path, undefined);
rerenderChild();
} else {
handleChange(path, formatedDate);
}
onBlur();
};

export const formatDate = (date: dayjs.Dayjs, saveFormat: string) => {
let formatedDate = date.format(saveFormat);
// Workaround to address a bug in Dayjs, neglecting leading 0 (https://github.com/iamkun/dayjs/issues/1849)
const indexOfYear = saveFormat.indexOf('YYYY');
if (date.year() < 1000 && indexOfYear !== -1) {
const stringUpToYear = formatedDate.slice(0, indexOfYear);
const stringFromYear = formatedDate.slice(indexOfYear);
if (date.year() >= 100) {
formatedDate = [stringUpToYear, 0, stringFromYear].join('');
} else if (date.year() >= 10) {
formatedDate = [stringUpToYear, 0, 0, stringFromYear].join('');
} else if (date.year() >= 1) {
formatedDate = [stringUpToYear, 0, 0, 0, stringFromYear].join('');
}
}
return formatedDate;
};

export const getData = (
data: any,
saveFormat: string | undefined
Expand Down
Loading