-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLocationAndTimeStep.jsx
197 lines (175 loc) · 5.53 KB
/
LocationAndTimeStep.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import {Heading3, UnorderedList, UnorderedListItem} from '@utrecht/component-library-react';
import {Form, Formik, useFormikContext} from 'formik';
import PropTypes from 'prop-types';
import {useContext} from 'react';
import {flushSync} from 'react-dom';
import {FormattedMessage, useIntl} from 'react-intl';
import {Navigate, useNavigate} from 'react-router';
import {useAsync} from 'react-use';
import {z} from 'zod';
import {toFormikValidationSchema} from 'zod-formik-adapter';
import {ConfigContext} from 'Context';
import {CardTitle} from 'components/Card';
import Loader from 'components/Loader';
import useTitle from 'hooks/useTitle';
import {useCreateAppointmentContext} from '../CreateAppointment/CreateAppointmentState';
import SubmitRow from '../SubmitRow';
import {DateSelect, LocationSelect, TimeSelect} from '../fields';
import {getAllProducts} from '../fields/ProductSelect';
import {ProductsType} from '../types';
const schema = z.object({
location: z.string(),
date: z.coerce.date(),
datetime: z.string().datetime({offset: true}),
});
// XXX: check field dependencies - clear time if date/location is not valid etc.
const INITIAL_VALUES = {
location: '',
date: '',
datetime: '',
};
const LocationAndTimeStepFields = () => {
const intl = useIntl();
const {values, setFieldValue} = useFormikContext();
const {
appointmentData: {products = []},
} = useCreateAppointmentContext();
const onFieldChange = event => {
const {name, value: newValue} = event.target;
const currentValue = values[name];
if (newValue === currentValue) return;
switch (name) {
case 'location': {
setFieldValue('date', '');
setFieldValue('datetime', '');
break;
}
case 'date': {
setFieldValue('datetime', '');
break;
}
default:
throw new Error(`Unknown field: '${name}'`);
}
};
// if we don't have products in the state, redirect back to the start
if (!products.length) {
return <Navigate to="/" replace />;
}
return (
// TODO: don't do inline style
<Form style={{width: '100%'}}>
<div className="openforms-form-field-container">
<LocationSelect products={products} onChange={onFieldChange} />
<DateSelect products={products} onChange={onFieldChange} />
<TimeSelect products={products} />
</div>
<SubmitRow
canSubmit
nextText={intl.formatMessage({
description: 'Appointments location and time step: next step text',
defaultMessage: 'To contact details',
})}
previousText={intl.formatMessage({
description: 'Appointments location and time step: previous step text',
defaultMessage: 'Back to products',
})}
navigateBackTo="producten"
/>
</Form>
);
};
const LocationAndTimeStep = ({navigateTo = null}) => {
const intl = useIntl();
const {
appointmentData: {products = []},
stepData,
stepErrors: {initialErrors, initialTouched},
clearStepErrors,
submitStep,
} = useCreateAppointmentContext();
const navigate = useNavigate();
useTitle(
intl.formatMessage({
description: 'Appointments: location and time step step page title',
defaultMessage: 'Location and time',
})
);
return (
<>
<CardTitle
title={
<FormattedMessage
description="Appointments: select location and time step title"
defaultMessage="Location and time"
/>
}
headingType="subtitle"
padded
/>
<ProductSummary products={products} />
<Formik
initialValues={{...INITIAL_VALUES, ...stepData}}
initialErrors={initialErrors}
initialTouched={initialTouched}
validateOnChange={false}
validateOnBlur={false}
validationSchema={toFormikValidationSchema(schema)}
onSubmit={(values, {setSubmitting}) => {
flushSync(() => {
clearStepErrors();
submitStep(values);
setSubmitting(false);
});
if (navigateTo !== null) navigate(navigateTo);
}}
component={LocationAndTimeStepFields}
/>
</>
);
};
LocationAndTimeStep.propTypes = {
navigateTo: PropTypes.string,
};
const ProductSummary = ({products}) => {
const {baseUrl} = useContext(ConfigContext);
const {
loading,
value: allProducts,
error,
} = useAsync(async () => await getAllProducts(baseUrl), [baseUrl]);
if (!products.length) return null;
if (error) throw error;
if (loading) {
return <Loader modifiers={['small']} />;
}
const productsById = Object.fromEntries(allProducts.map(p => [p.identifier, p.name]));
return (
<>
<Heading3 className="utrecht-heading-3--distanced">
<FormattedMessage
description="Product summary on appointments location and time step heading"
defaultMessage="Your products"
/>
</Heading3>
<UnorderedList className="utrecht-unordered-list--distanced">
{products.map(({productId, amount}, index) => (
<UnorderedListItem key={`${productId}-${index}`}>
<FormattedMessage
description="Product summary on appointments location and time step"
defaultMessage="{name}: {amount}x"
values={{
amount,
name: productsById[productId],
}}
/>
</UnorderedListItem>
))}
</UnorderedList>
</>
);
};
ProductSummary.propTypes = {
products: ProductsType.isRequired,
};
export default LocationAndTimeStep;