import React, { Fragment, useState, useEffect, useMemo } from 'react';
import { injectIntl, InjectedIntlProps } from 'react-intl';
import styled from 'styled-components';
import { Field } from '@atlaskit/form';
import { RadioGroup } from '@atlaskit/radio';
import { DatePicker } from '@atlaskit/datetime-picker';
import TextField from '@atlaskit/textfield';
import {
DateRangeField,
DateRangeResult,
} from '@atlaskit/editor-common/extensions';
import { messages } from '../messages';
import FieldMessages from '../FieldMessages';
import { validate, validateRequired } from '../utils';
import { OnFieldChange } from '../types';
const HorizontalFields = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
`;
const HorizontalFieldWrapper = styled.div`
flex-basis: 47%;
`;
const Hidden = styled.div`
display: none;
`;
const getFromDefaultValue = (
field: DateRangeField,
attribute: keyof DateRangeResult,
): string | undefined => {
if (field.defaultValue) {
return field.defaultValue[attribute];
}
};
const DateField = ({
parentField,
scope,
fieldName,
onFieldChange,
intl,
isRequired,
}: {
parentField: DateRangeField;
scope: string;
fieldName: 'from' | 'to';
onFieldChange: OnFieldChange;
isRequired?: boolean;
} & InjectedIntlProps) => (
{
return validateRequired({ isRequired }, value);
}}
>
{({ fieldProps, error }) => (
{
fieldProps.onChange(date);
onFieldChange(parentField.name, true);
}}
locale={intl.locale}
/>
)}
);
const DateRange = function ({
name,
field,
onFieldChange,
intl,
}: {
name: string;
field: DateRangeField;
onFieldChange: OnFieldChange;
autoFocus?: boolean;
placeholder?: string;
} & InjectedIntlProps) {
const items = useMemo(() => {
return [
...(field.items || []),
{
label: intl.formatMessage(messages.custom),
value: 'custom',
},
].map((option) => ({
...option,
name,
}));
}, [field.items, name, intl]);
const [currentValue, setCurrentValue] = useState(
getFromDefaultValue(field, 'value') || items[0].value,
);
useEffect(() => {
// calling onBlur here based on the currentValue changing will ensure that we
// get the most up to date value after the form has been rendered
onFieldChange(name, true);
}, [currentValue, onFieldChange, name]);
const element = (
{({ fieldProps }) => }
validate(field, value || '')}
>
{({ fieldProps, error }) => (
{
fieldProps.onChange(event.target.value);
setCurrentValue(event.target.value);
}}
/>
)}
{currentValue !== 'custom' ? (
{/** this is a hidden field that will copy the selected value to a field of name 'from'
* when a option that is NOT 'custom' is selected. This is to comply with the atlaskit
* form component that relies on final-form */}
{({ fieldProps }) => }
) : (
)}
);
return element;
};
export default injectIntl(DateRange);