return date object from date/datetime widgets if no format set (#1296)

* return date object from date/datetime widgets if no format set

BREAKING CHANGE

As of 1.0, the documented behavior for the date and datetime widgets was
to always return a string value, but they were instead returning a date
object if the default date was not manually changed by the user. This
was addressed in #1143, but it became clear afterward that static site
generators were depending on the raw date objects that Netlify CMS was
unintentionally producing. Remaining as is or addressing the bug were
both "breaking" states, so this commit reverts to producing raw date
objects when no format is explicitly set.

It is now considered an edge case to require string dates, as most
static site generators expect to parse a raw date against formatting in
a site's templates.

Also note that this commit improves the original behavior by always
providing a date object when no format is provided, even if the user
manually changes the value.

* produce raw date when no format is provided
This commit is contained in:
Shawn Erquhart
2018-05-25 12:03:44 -04:00
committed by GitHub
parent 55c8302dca
commit 9fd0ff4a6a
4 changed files with 27 additions and 10 deletions

View File

@ -20,7 +20,7 @@ export default class DateControl extends React.Component {
includeTime: PropTypes.bool,
};
format = this.props.field.get('format') || (this.props.includeTime ? DEFAULT_DATETIME_FORMAT : DEFAULT_DATE_FORMAT);
format = this.props.field.get('format');
componentDidMount() {
const { value } = this.props;
@ -41,22 +41,34 @@ export default class DateControl extends React.Component {
handleChange = datetime => {
const { onChange } = this.props;
// Set the date only if the format is valid
if (this.isValidDate(datetime)) {
/**
* Set the date only if it is valid.
*/
if (!this.isValidDate(datetime)) {
return;
}
/**
* Produce a formatted string only if a format is set in the config.
* Otherwise produce a date object.
*/
if (this.format) {
const formattedValue = moment(datetime).format(this.format);
onChange(formattedValue);
} else {
const value = moment.isMoment(datetime) ? datetime.toDate() : datetime;
onChange(value);
}
};
onBlur = datetime => {
const { setInactiveStyle, onChange } = this.props;
const { setInactiveStyle } = this.props;
if (!this.isValidDate(datetime)) {
const parsedDate = moment(datetime);
if (parsedDate.isValid()) {
const formattedValue = parsedDate.format(this.format);
onChange(formattedValue);
this.handleChange(datetime);
} else {
window.alert('The date you entered is invalid.');
}
@ -67,11 +79,10 @@ export default class DateControl extends React.Component {
render() {
const { includeTime, value, classNameWrapper, setActiveStyle, setInactiveStyle } = this.props;
const format = this.format;
return (
<DateTime
timeFormat={!!includeTime}
value={moment(value, format)}
value={moment(value, this.format)}
onChange={this.handleChange}
onFocus={setActiveStyle}
onBlur={this.onBlur}