UNPKG

@open-formulieren/formio-builder

Version:

An opinionated Formio webform builder for Open Forms

68 lines (67 loc) 3.08 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { useFormikContext } from 'formik'; import { FormattedMessage, defineMessage, useIntl } from 'react-intl'; import { Select } from '../../../components/formio'; // Mappings of value-label to produce dropdown options. Note that you need to filter out // only the options relevant to the particular field. const ALL_DATE_CONSTRAINT_MODE_OPTIONS = [ { value: 'fixedValue', label: defineMessage({ id: "45IQhq", defaultMessage: [{ type: 0, value: "Fixed value" }] }), }, { value: 'future', label: defineMessage({ id: "SH67gH", defaultMessage: [{ type: 0, value: "In the future" }] }), }, { value: 'past', label: defineMessage({ id: "WZJG0y", defaultMessage: [{ type: 0, value: "In the past" }] }), }, { value: 'relativeToVariable', label: defineMessage({ id: "7Ldfn+", defaultMessage: [{ type: 0, value: "Relative to variable" }] }), }, ]; const MODES_TO_EXCLUDE = { minDate: ['past'], maxDate: ['future'], }; const DEFAULT_VALUES = { '': {}, fixedValue: {}, future: {}, past: {}, relativeToVariable: { variable: 'now', delta: { years: null, months: null, days: null, }, operator: 'add', }, }; const ModeSelect = ({ constraint }) => { const fieldName = `openForms.${constraint}.mode`; const intl = useIntl(); const { setFieldValue } = useFormikContext(); // filter out the validation modes not relevant for this particular constraint const modesToExclude = MODES_TO_EXCLUDE[constraint]; const options = ALL_DATE_CONSTRAINT_MODE_OPTIONS.filter(opt => !modesToExclude.includes(opt.value)); return (_jsx(Select, { name: fieldName, label: _jsx(FormattedMessage, { id: 'SEXqhC', defaultMessage: [{ type: 0, value: "Mode preset" }] }), options: options.map(item => (Object.assign(Object.assign({}, item), { label: intl.formatMessage(item.label) }))), isClearable: true, onChange: event => { var _a; // the select *always* sets the selected value in the state, we can just use an // additional onChange here (as better alternative to useEffect). // The idea here is that we set the default, empty values that are mode-specific // so that we don't get "uncontrolled-component-becomes-controlled" warning // from React. It also helps in clearing out any left-over state from other // modes when switching between them. const mode = (_a = event.target.value) !== null && _a !== void 0 ? _a : ''; const emptyDefaults = Object.assign({ mode }, DEFAULT_VALUES[mode]); setFieldValue(`openForms.${constraint}`, emptyDefaults); // whenever the mode *changes*, clear the datePicker fixed value to prevent // stale values from being in the form state while visually hidden setFieldValue(`datePicker.${constraint}`, null); } })); }; export default ModeSelect;