-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathindex.tsx
554 lines (515 loc) · 13.6 KB
/
index.tsx
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
import 'date-fns';
import 'react-app-polyfill/ie11';
import * as Yup from 'yup';
import {
AppBar,
Box,
Button,
CssBaseline,
FormControlLabel,
Grid,
InputAdornment,
Link,
Checkbox as MuiCheckbox,
Paper,
Toolbar,
Typography,
} from '@mui/material';
import {
Autocomplete,
AutocompleteData,
CheckboxData,
Checkboxes,
DatePicker,
DateTimePicker,
Debug,
RadioData,
Radios,
Select,
SelectData,
SwitchData,
Switches,
TextField,
TimePicker,
makeRequired,
makeValidate,
} from '../.';
import { Form } from 'react-final-form';
import { FormSubscription } from 'final-form';
import { StyledEngineProvider, ThemeProvider, createTheme } from '@mui/material/styles';
import { createFilterOptions } from '@mui/material/useAutocomplete';
import { styled } from '@mui/system';
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers';
import ruLocale from 'date-fns/locale/ru';
const theme = createTheme({
components: {
MuiTextField: {
defaultProps: {
margin: 'normal',
},
},
MuiFormControl: {
defaultProps: {
margin: 'normal',
},
},
},
});
const Subscription = styled(Paper)(({ theme }) => ({
marginTop: theme.spacing(3),
padding: theme.spacing(3),
}));
/**
* Little helper to see how good rendering is
*/
class RenderCount extends React.Component {
renders = 0;
render() {
return <>{++this.renders}</>;
}
}
interface FormData {
planet_one: string;
planet: string[];
best: string[];
available: boolean;
switch: string[];
terms: boolean;
date: Date;
hello: string;
cities: string[];
gender: string;
birthday: Date;
break: Date;
hidden: string;
keyboardDateTime: Date;
dateTime: Date;
dateTimeLocale: Date;
firstName: string;
lastName: string;
}
const schema = Yup.object({
planet_one: Yup.string().required(),
planet: Yup.array().of(Yup.string().required()).min(1).required(),
best: Yup.array().of(Yup.string().required()).min(1).required(),
available: Yup.boolean().oneOf([true], 'We are not available!').required(),
switch: Yup.array().of(Yup.string().required()).min(1).required(),
terms: Yup.boolean().oneOf([true], 'Please accept the terms').required(),
date: Yup.date().required(),
hello: Yup.string().required(),
cities: Yup.array().of(Yup.string().required()).min(1).required(),
gender: Yup.string().required(),
birthday: Yup.date().required(),
break: Yup.date().required(),
hidden: Yup.string().required(),
keyboardDateTime: Yup.date().required(),
dateTime: Yup.date().required(),
dateTimeLocale: Yup.date().required(),
firstName: Yup.string().required(),
lastName: Yup.string().required(),
});
/**
* Uses the optional helper makeValidate function to format the error messages
* into something usable by final form.
*/
const validate = makeValidate(schema);
/**
* Grabs all the required fields from the schema so that they can be passed into
* the components without having to declare them in both the schema and the component.
*/
const required = makeRequired(schema);
function AppWrapper() {
return (
<StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</StyledEngineProvider>
);
}
function App() {
const subscription = { submitting: true };
const [subscriptionState, setSubscriptionState] = useState<FormSubscription | undefined>(subscription);
const onChange = () => {
setSubscriptionState(subscriptionState === undefined ? subscription : undefined);
};
return (
<Box mx={2}>
<CssBaseline />
<Subscription>
<FormControlLabel
control={
<MuiCheckbox
checked={subscriptionState !== undefined}
color="secondary"
onChange={onChange}
value={true}
/>
}
label="Enable React Final Form subscription render optimization. Watch the render count when interacting with the form."
/>
<Link
href="https://final-form.org/docs/react-final-form/types/FormProps#subscription"
target="_blank"
underline="hover"
>
Documentation
</Link>
</Subscription>
<MainForm subscription={subscriptionState} />
<Footer />
</Box>
);
}
const Offset = styled('div')(({ theme }) => (theme.mixins as any).toolbar);
function Footer() {
return (
<>
<AppBar
sx={{ top: 'auto', bottom: 0, backgroundColor: 'lightblue' }}
color="inherit"
position="fixed"
elevation={0}
>
<Toolbar>
<Grid container spacing={1} alignItems="center" justifyContent="center" direction="row">
<Grid item>
<Link
href="https://github.com/lookfirst/mui-rff"
target="_blank"
color="textSecondary"
underline="hover"
variant="body1"
>
MUI-RFF Github Project
</Link>
</Grid>
</Grid>
</Toolbar>
</AppBar>
<Offset />
</>
);
}
const PaperInner = styled(Paper)(({ theme }) => ({
marginLeft: theme.spacing(3),
marginTop: theme.spacing(3),
padding: theme.spacing(3),
}));
function MainForm({ subscription }: { subscription: any }) {
const [submittedValues, setSubmittedValues] = useState<FormData | undefined>(undefined);
const autocompleteData: AutocompleteData[] = [
{ label: 'Earth', value: 'earth' },
{ label: 'Mars', value: 'mars' },
{ label: 'Venus', value: 'venus' },
{ label: 'Brown Dwarf Glese 229B', value: '229B' },
];
const checkboxData: CheckboxData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
{ label: 'Indeterminate', value: 'indeterminate', indeterminate: true },
];
const switchData: SwitchData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
const selectData: SelectData[] = [
{ label: 'Choose...', value: '', disabled: true },
{ label: 'San Diego', value: 'sandiego' },
{ label: 'San Francisco', value: 'sanfrancisco' },
{ label: 'Los Angeles', value: 'losangeles' },
{ label: 'Saigon', value: 'saigon' },
];
const radioData: RadioData[] = [
{ label: 'Female', value: 'female' },
{ label: 'Male', value: 'male' },
{ label: 'Both', value: 'both' },
];
const initialValues: FormData = {
planet_one: autocompleteData[1].value,
planet: [autocompleteData[1].value],
best: [],
switch: ['bar'],
available: false,
terms: false,
date: new Date('2014-08-18T21:11:54'),
hello: 'some text',
cities: ['losangeles'],
gender: '',
birthday: new Date('2014-08-18'),
break: new Date('2019-04-20T16:20:00'),
hidden: 'secret',
keyboardDateTime: new Date('2017-06-21T17:20:00'),
dateTime: new Date('2023-05-25T12:29:10'),
dateTimeLocale: new Date('2023-04-26T12:29:10'),
firstName: '',
lastName: '',
};
const onSubmit = (values: FormData) => {
setSubmittedValues(values);
};
const onReset = () => {
setSubmittedValues(undefined);
};
const helperText = '* Required';
const filter = createFilterOptions<AutocompleteData>();
let key = 0;
const formFields = [
<Autocomplete
key={key++}
label="Choose one planet"
name="planet_one"
multiple={false}
required={required.planet}
options={autocompleteData}
getOptionValue={(option) => option.value}
getOptionLabel={(option: string | AutocompleteData) => (option as AutocompleteData).label}
renderOption={(props, option) => <li {...props}>{option.label}</li>}
disableCloseOnSelect={true}
helperText={helperText}
freeSolo={true}
onChange={(_event, newValue, reason, details) => {
if (newValue && reason === 'selectOption' && details?.option.inputValue) {
// Create a new value from the user input
autocompleteData.push({
value: details?.option.inputValue,
label: details?.option.inputValue,
});
}
}}
filterOptions={(options, params) => {
const filtered = filter(options, params);
// Suggest the creation of a new value
if (params.inputValue.length) {
filtered.push({
inputValue: params.inputValue,
label: `Add "${params.inputValue}"`,
value: params.inputValue,
});
}
return filtered;
}}
selectOnFocus
clearOnBlur
handleHomeEndKeys
/>,
<Autocomplete
key={key++}
label="Choose at least one planet"
name="planet"
multiple={true}
required={required.planet}
options={autocompleteData}
getOptionValue={(option) => option.value}
getOptionLabel={(option: string | AutocompleteData) => (option as AutocompleteData).label}
disableCloseOnSelect={true}
renderOption={(props, option, { selected }) =>
option.inputValue ? (
option.label
) : (
<li {...props}>
<MuiCheckbox style={{ marginRight: 8 }} checked={selected} />
{option.label}
</li>
)
}
helperText={helperText}
freeSolo={true}
onChange={(_event, newValue, reason, details) => {
if (newValue && reason === 'selectOption' && details?.option.inputValue) {
// Create a new value from the user input
autocompleteData.push({
value: details?.option.inputValue,
label: details?.option.inputValue,
});
}
}}
filterOptions={(options, params) => {
const filtered = filter(options, params);
// Suggest the creation of a new value
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
label: `Add "${params.inputValue}"`,
value: params.inputValue,
});
}
return filtered;
}}
selectOnFocus
clearOnBlur
handleHomeEndKeys
textFieldProps={{
InputProps: {
startAdornment: <InputAdornment position="start">🪐</InputAdornment>,
endAdornment: <InputAdornment position="end">🪐</InputAdornment>,
},
}}
/>,
<Switches
key={key++}
label="Available"
name="available"
required={required.available}
data={{ label: 'available', value: 'available' }}
helperText={helperText}
/>,
<Switches
key={key++}
label="Check at least one..."
name="switch"
required={required.switch}
data={switchData}
helperText={helperText}
/>,
<Checkboxes
key={key++}
label="Check at least one..."
name="best"
required={required.best}
data={checkboxData}
helperText={helperText}
/>,
<Radios
key={key++}
label="Pick a gender"
name="gender"
required={required.gender}
data={radioData}
helperText={helperText}
/>,
<DatePicker key={key++} label="Birthday" name="birthday" required={required.birthday} />,
<TimePicker key={key++} label="Break time" name="break" required={required.break} />,
<DateTimePicker key={key++} label="Pick a date and time" name="dateTime" required={required.dateTime} />,
<DateTimePicker
key={key++}
label="Pick a date and time (russian locale)"
name="dateTimeLocale"
required={required.dateTimeLocale}
locale={ruLocale}
/>,
<TextField key={key++} label="Hello world" name="hello" required={required.hello} helperText={helperText} />,
<TextField
key={key++}
label="Hidden text"
name="hidden"
type="password"
autoComplete="new-password"
required={required.hidden}
helperText={helperText}
/>,
<Select
key={key++}
label="Pick some cities..."
name="cities"
required={required.cities}
data={selectData}
multiple={true}
helperText="Woah helper text"
/>,
<Checkboxes
key={key++}
name="terms"
required={required.terms}
data={{
label: 'Do you accept the terms?',
value: true,
}}
helperText={helperText}
/>,
<TextField
key={key++}
label="Field with inputProps"
name="firstName"
required={true}
inputProps={{
autoComplete: 'name',
}}
/>,
<TextField key={key++} label="Field WITHOUT inputProps" name="lastName" required={true} />,
];
return (
<Paper sx={{ marginTop: 3, padding: 3, marginBottom: 5 }}>
<Form
onSubmit={onSubmit}
initialValues={submittedValues ? submittedValues : initialValues}
subscription={subscription}
validate={validate}
key={subscription as any}
render={({ handleSubmit, submitting }) => (
<form onSubmit={handleSubmit} noValidate={true} autoComplete="new-password">
<Grid container>
<Grid item xs={6}>
<LocalizationProvider dateAdapter={AdapterDateFns}>
{formFields.map((field, index) => (
<Grid item key={index}>
{field}
</Grid>
))}
</LocalizationProvider>
<Grid item>
<Button
type="button"
variant="contained"
onClick={onReset}
disabled={submitting}
sx={{ mt: 3, mr: 1 }}
color="inherit"
>
Reset
</Button>
<Button
variant="contained"
type="submit"
disabled={submitting}
sx={{ mt: 3, mr: 1 }}
>
Submit
</Button>
</Grid>
</Grid>
<Grid item xs={6}>
<Grid item>
<Paper sx={{ ml: 3, mt: 3, p: 3 }} elevation={3}>
<Typography>
<strong>Render count:</strong> <RenderCount />
</Typography>
</Paper>
</Grid>
<Grid item>
<PaperInner elevation={3}>
<Typography>
<strong>Form field data</strong>
</Typography>
<Debug />
</PaperInner>
</Grid>
<Grid item>
<PaperInner elevation={3}>
<Typography>
<strong>Submitted data</strong>
</Typography>
<pre>
{JSON.stringify(submittedValues ? submittedValues : {}, undefined, 2)}
</pre>
</PaperInner>
</Grid>
</Grid>
</Grid>
</form>
)}
/>
</Paper>
);
}
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
<React.StrictMode>
<AppWrapper />
</React.StrictMode>,
);