refactor(web/input): use form control instead of controlled state

This commit is contained in:
Luke
2023-01-03 18:55:02 +01:00
parent 440a7564a3
commit d0811be0ce
9 changed files with 121 additions and 76 deletions

View File

@@ -27,6 +27,7 @@
"prettier": "^2.7.1", "prettier": "^2.7.1",
"react": "18.2.0", "react": "18.2.0",
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-hook-form": "^7.41.3",
"react-hot-toast": "^2.4.0", "react-hot-toast": "^2.4.0",
"react-markdown": "^8.0.1", "react-markdown": "^8.0.1",
"typescript": "^4.6.3", "typescript": "^4.6.3",

11
web/pnpm-lock.yaml generated
View File

@@ -38,6 +38,7 @@ specifiers:
prop-types: ^15.8.1 prop-types: ^15.8.1
react: 18.2.0 react: 18.2.0
react-dom: 18.2.0 react-dom: 18.2.0
react-hook-form: ^7.41.3
react-hot-toast: ^2.4.0 react-hot-toast: ^2.4.0
react-markdown: ^8.0.1 react-markdown: ^8.0.1
rimraf: ^3.0.2 rimraf: ^3.0.2
@@ -69,6 +70,7 @@ dependencies:
prettier: 2.7.1 prettier: 2.7.1
react: 18.2.0 react: 18.2.0
react-dom: 18.2.0_react@18.2.0 react-dom: 18.2.0_react@18.2.0
react-hook-form: 7.41.3_react@18.2.0
react-hot-toast: 2.4.0_6dztgcaza2bodipt2i5a4is4mu_npw22p3c4ehm7n7vxn2gqac44u react-hot-toast: 2.4.0_6dztgcaza2bodipt2i5a4is4mu_npw22p3c4ehm7n7vxn2gqac44u
react-markdown: 8.0.1_bbvjflvjoibwhtpmedigb26h6y react-markdown: 8.0.1_bbvjflvjoibwhtpmedigb26h6y
typescript: 4.6.3 typescript: 4.6.3
@@ -2346,6 +2348,15 @@ packages:
scheduler: 0.23.0 scheduler: 0.23.0
dev: false dev: false
/react-hook-form/7.41.3_react@18.2.0:
resolution: {integrity: sha512-5QNTmqJtDb88WV5n41b6+AmcDMVyaJ3tccPgHAgS215w3jZ3bmJhDO27kNTr8u4YHNYXmS7p1/4/KachBAlUtw==}
engines: {node: '>=12.22.0'}
peerDependencies:
react: ^16.8.0 || ^17 || ^18
dependencies:
react: 18.2.0
dev: false
/react-hot-toast/2.4.0_6dztgcaza2bodipt2i5a4is4mu_npw22p3c4ehm7n7vxn2gqac44u: /react-hot-toast/2.4.0_6dztgcaza2bodipt2i5a4is4mu_npw22p3c4ehm7n7vxn2gqac44u:
resolution: {integrity: sha512-qnnVbXropKuwUpriVVosgo8QrB+IaPJCpL8oBI6Ov84uvHZ5QQcTp2qg6ku2wNfgJl6rlQXJIQU5q+5lmPOutA==} resolution: {integrity: sha512-qnnVbXropKuwUpriVVosgo8QrB+IaPJCpL8oBI6Ov84uvHZ5QQcTp2qg6ku2wNfgJl6rlQXJIQU5q+5lmPOutA==}
engines: {node: '>=10'} engines: {node: '>=10'}

View File

@@ -1,5 +1,5 @@
import { Group, Modal, Button, Stack } from '@mantine/core'; import { Group, Modal, Button, Stack } from '@mantine/core';
import React from 'react'; import React, { FormEvent, useRef } from 'react';
import { useNuiEvent } from '../../hooks/useNuiEvent'; import { useNuiEvent } from '../../hooks/useNuiEvent';
import { useLocales } from '../../providers/LocaleProvider'; import { useLocales } from '../../providers/LocaleProvider';
import { fetchNui } from '../../utils/fetchNui'; import { fetchNui } from '../../utils/fetchNui';
@@ -9,12 +9,19 @@ import CheckboxField from './components/fields/checkbox';
import SelectField from './components/fields/select'; import SelectField from './components/fields/select';
import NumberField from './components/fields/number'; import NumberField from './components/fields/number';
import SliderField from './components/fields/slider'; import SliderField from './components/fields/slider';
import { useFieldArray, useForm } from 'react-hook-form';
export interface InputProps { export interface InputProps {
heading: string; heading: string;
rows: Array<IInput | ICheckbox | ISelect | INumber | ISlider>; rows: Array<IInput | ICheckbox | ISelect | INumber | ISlider>;
} }
export type FormValues = {
test: {
value: any;
}[];
};
const InputDialog: React.FC = () => { const InputDialog: React.FC = () => {
const [fields, setFields] = React.useState<InputProps>({ const [fields, setFields] = React.useState<InputProps>({
heading: '', heading: '',
@@ -25,6 +32,12 @@ const InputDialog: React.FC = () => {
const [visible, setVisible] = React.useState(false); const [visible, setVisible] = React.useState(false);
const { locale } = useLocales(); const { locale } = useLocales();
const form = useForm<{ test: { value: any }[] }>({});
const fieldForm = useFieldArray({
control: form.control,
name: 'test',
});
const handlePasswordStates = (index: number) => { const handlePasswordStates = (index: number) => {
setPasswordStates({ setPasswordStates({
...passwordStates, ...passwordStates,
@@ -37,6 +50,9 @@ const InputDialog: React.FC = () => {
setFields(data); setFields(data);
setInputData([]); setInputData([]);
setVisible(true); setVisible(true);
data.rows.forEach((row, index) => {
fieldForm.insert(index, { value: row.type !== 'checkbox' ? row.default : row.checked } || { value: null });
});
}); });
useNuiEvent('closeInputDialog', () => { useNuiEvent('closeInputDialog', () => {
@@ -60,6 +76,15 @@ const InputDialog: React.FC = () => {
fetchNui('inputData', inputData); fetchNui('inputData', inputData);
}; };
const onSubmit = form.handleSubmit(async (data) => {
const values: any[] = [];
Object.values(data.test).forEach((obj: { value: any }) => values.push(obj.value));
console.log(values);
await new Promise((resolve) => setTimeout(resolve, 200));
form.reset();
fieldForm.remove();
});
return ( return (
<> <>
<Modal <Modal
@@ -78,33 +103,40 @@ const InputDialog: React.FC = () => {
transition="fade" transition="fade"
exitTransitionDuration={150} exitTransitionDuration={150}
> >
<form onSubmit={onSubmit}>
<Stack> <Stack>
{fields.rows.map((row: IInput | ICheckbox | ISelect | INumber | ISlider, index) => ( {fieldForm.fields.map((item, index) => {
<React.Fragment key={`row-${index}-${row.type}-${row.label}`}> const row = fields.rows[index];
return (
<React.Fragment key={item.id}>
{row.type === 'input' && ( {row.type === 'input' && (
<InputField <InputField
register={form.register(`test.${index}.value`)}
row={row} row={row}
index={index} index={index}
handleChange={handleChange}
passwordStates={passwordStates} passwordStates={passwordStates}
handlePasswordStates={handlePasswordStates} handlePasswordStates={handlePasswordStates}
/> />
)} )}
{row.type === 'checkbox' && <CheckboxField row={row} index={index} handleChange={handleChange} />} {row.type === 'checkbox' && (
{row.type === 'select' && <SelectField row={row} index={index} handleChange={handleChange} />} <CheckboxField register={form.register(`test.${index}.value`)} row={row} index={index} />
{row.type === 'number' && <NumberField row={row} index={index} handleChange={handleChange} />} )}
{row.type === 'slider' && <SliderField row={row} index={index} handleChange={handleChange} />} {row.type === 'select' && <SelectField row={row} index={index} control={form.control} />}
{row.type === 'number' && <NumberField control={form.control} row={row} index={index} />}
{row.type === 'slider' && <SliderField control={form.control} row={row} index={index} />}
</React.Fragment> </React.Fragment>
))} );
})}
<Group position="right" spacing={10}> <Group position="right" spacing={10}>
<Button uppercase variant="default" onClick={handleClose} mr={3}> <Button uppercase variant="default" onClick={handleClose} mr={3}>
{locale.ui.cancel} {locale.ui.cancel}
</Button> </Button>
<Button uppercase variant="light" onClick={handleClose}> <Button uppercase variant="light" onClick={handleClose} type="submit">
{locale.ui.confirm} {locale.ui.confirm}
</Button> </Button>
</Group> </Group>
</Stack> </Stack>
</form>
</Modal> </Modal>
</> </>
); );

View File

@@ -1,25 +1,17 @@
import { Checkbox } from '@mantine/core'; import { Checkbox } from '@mantine/core';
import { useEffect } from 'react'; import { useEffect } from 'react';
import { ICheckbox } from '../../../../interfaces/dialog'; import { ICheckbox } from '../../../../interfaces/dialog';
import { UseFormRegisterReturn } from 'react-hook-form';
interface Props { interface Props {
row: ICheckbox; row: ICheckbox;
index: number; index: number;
handleChange: (value: boolean, index: number) => void; register: UseFormRegisterReturn;
} }
const CheckboxField: React.FC<Props> = (props) => { const CheckboxField: React.FC<Props> = (props) => {
useEffect(() => {
if (props.row.checked) props.handleChange(props.row.checked, props.index);
}, []);
return ( return (
<Checkbox <Checkbox {...props.register} sx={{ display: 'flex' }} label={props.row.label} defaultChecked={props.row.checked} />
sx={{ display: 'flex' }}
label={props.row.label}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => props.handleChange(e.target.checked, props.index)}
defaultChecked={props.row.checked}
/>
); );
}; };

View File

@@ -1,28 +1,26 @@
import { TextInput } from '@mantine/core'; import { TextInput } from '@mantine/core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useEffect } from 'react'; import React, { useEffect } from 'react';
import { IInput } from '../../../../interfaces/dialog'; import { IInput } from '../../../../interfaces/dialog';
import { UseFormRegisterReturn } from 'react-hook-form';
interface Props { interface Props {
register: UseFormRegisterReturn;
row: IInput; row: IInput;
index: number; index: number;
handleChange: (value: string, index: number) => void;
passwordStates: boolean[]; passwordStates: boolean[];
handlePasswordStates: (index: number) => void; handlePasswordStates: (index: number) => void;
} }
const InputField: React.FC<Props> = (props) => { const InputField: React.FC<Props> = (props) => {
useEffect(() => {
if (props.row.default) props.handleChange(props.row.default, props.index);
}, []);
return ( return (
<TextInput <TextInput
{...props.register}
defaultValue={props.row.default}
label={props.row.label} label={props.row.label}
description={props.row.description} description={props.row.description}
icon={props.row.icon && <FontAwesomeIcon icon={props.row.icon} fixedWidth />} icon={props.row.icon && <FontAwesomeIcon icon={props.row.icon} fixedWidth />}
placeholder={props.row.placeholder} placeholder={props.row.placeholder}
defaultValue={props.row.default}
disabled={props.row.disabled} disabled={props.row.disabled}
type={!props.row.password || props.passwordStates[props.index] ? 'text' : 'password'} type={!props.row.password || props.passwordStates[props.index] ? 'text' : 'password'}
rightSection={ rightSection={

View File

@@ -2,27 +2,35 @@ import { NumberInput } from '@mantine/core';
import { useEffect } from 'react'; import { useEffect } from 'react';
import { INumber } from '../../../../interfaces/dialog'; import { INumber } from '../../../../interfaces/dialog';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Control, useController, UseFormRegisterReturn } from 'react-hook-form';
import { FormValues } from '../../InputDialog';
interface Props { interface Props {
row: INumber; row: INumber;
index: number; index: number;
handleChange: (value: number, index: number) => void; control: Control<FormValues>;
} }
const NumberField: React.FC<Props> = (props) => { const NumberField: React.FC<Props> = (props) => {
useEffect(() => { const controller = useController({
if (props.row.default) props.handleChange(props.row.default, props.index); name: `test.${props.index}.value`,
}, []); control: props.control,
defaultValue: props.row.default,
});
return ( return (
<NumberInput <NumberInput
value={controller.field.value}
name={controller.field.name}
ref={controller.field.ref}
onBlur={controller.field.onBlur}
onChange={controller.field.onChange}
label={props.row.label} label={props.row.label}
description={props.row.description} description={props.row.description}
defaultValue={props.row.default} defaultValue={props.row.default}
min={props.row.min} min={props.row.min}
max={props.row.max} max={props.row.max}
disabled={props.row.disabled} disabled={props.row.disabled}
onChange={(value) => props.handleChange(value as number, props.index)}
icon={props.row.icon && <FontAwesomeIcon icon={props.row.icon} fixedWidth />} icon={props.row.icon && <FontAwesomeIcon icon={props.row.icon} fixedWidth />}
/> />
); );

View File

@@ -1,31 +1,31 @@
import { Select } from '@mantine/core'; import { Select } from '@mantine/core';
import { useEffect } from 'react';
import { ISelect } from '../../../../interfaces/dialog'; import { ISelect } from '../../../../interfaces/dialog';
import { Control, FieldValues, useController, UseFormRegisterReturn, UseFormSetValue } from 'react-hook-form';
import { FormValues } from '../../InputDialog';
interface Props { interface Props {
row: ISelect; row: ISelect;
index: number; index: number;
handleChange: (value: string, index: number) => void; control: Control<FormValues>;
} }
// TODO: set label to value of value when there is no label provided // TODO: set label to value of value when there is no label provided
const SelectField: React.FC<Props> = (props) => { const SelectField: React.FC<Props> = (props) => {
useEffect(() => { const controller = useController({
if (props.row.default) { name: `test.${props.index}.value`,
props.row.options?.map((option) => { control: props.control,
if (props.row.default === option.value) { defaultValue: props.row.default,
props.handleChange(option.value, props.index);
}
}); });
}
}, []);
return ( return (
<Select <Select
onChange={(value) => props.handleChange(value as string, props.index)}
defaultValue={props.row.default || ''}
disabled={props.row.disabled}
data={props.row.options} data={props.row.options}
value={controller.field.value}
name={controller.field.name}
ref={controller.field.ref}
onBlur={controller.field.onBlur}
onChange={controller.field.onChange}
disabled={props.row.disabled}
label={props.row.label} label={props.row.label}
description={props.row.description} description={props.row.description}
/> />

View File

@@ -1,27 +1,32 @@
import { Box, Slider, Text } from '@mantine/core'; import { Box, Slider, Text } from '@mantine/core';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { ISlider } from '../../../../interfaces/dialog'; import { ISlider } from '../../../../interfaces/dialog';
import { Control, FieldValues, useController, UseFormRegisterReturn, UseFormSetValue } from 'react-hook-form';
import { FormValues } from '../../InputDialog';
interface Props { interface Props {
row: ISlider; row: ISlider;
index: number; index: number;
handleChange: (value: number, index: number) => void; control: Control<FormValues>;
} }
const SliderField: React.FC<Props> = (props) => { const SliderField: React.FC<Props> = (props) => {
useEffect(() => { const controller = useController({
if (props.row.default || props.row.min) props.handleChange(props.row.default || props.row.min!, props.index); name: `test.${props.index}.value`,
}, []); control: props.control,
defaultValue: props.row.default || props.row.min || 0,
const [sliderValue, setSliderValue] = useState(props.row.default || props.row.min || 0); });
return ( return (
<Box> <Box>
<Text sx={{ fontSize: 14, fontWeight: 500 }}>{props.row.label}</Text> <Text sx={{ fontSize: 14, fontWeight: 500 }}>{props.row.label}</Text>
<Slider <Slider
mb={10} mb={10}
onChangeEnd={(val: number) => props.handleChange(val, props.index)} value={controller.field.value}
onChange={(val: number) => setSliderValue(val)} name={controller.field.name}
ref={controller.field.ref}
onBlur={controller.field.onBlur}
onChange={controller.field.onChange}
defaultValue={props.row.default || props.row.min || 0} defaultValue={props.row.default || props.row.min || 0}
min={props.row.min} min={props.row.min}
max={props.row.max} max={props.row.max}

View File

@@ -153,9 +153,7 @@ const Notifications: React.FC = () => {
: exitAnimationRight : exitAnimationRight
} 0.4s ease-in forwards`, } 0.4s ease-in forwards`,
}} }}
style={{ style={data.style}
...data.style,
}}
className={`${classes.container}`} className={`${classes.container}`}
> >
<Group noWrap spacing={12}> <Group noWrap spacing={12}>