-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathFormDialog.tsx
More file actions
160 lines (149 loc) Β· 4.81 KB
/
FormDialog.tsx
File metadata and controls
160 lines (149 loc) Β· 4.81 KB
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
import type { ChangeEvent, ChangeEventHandler, ComponentProps } from 'react';
import React, { useCallback, useState } from 'react';
import clsx from 'clsx';
import { FieldError } from '../Form/FieldError';
import { useTranslationContext } from '../../context';
type FormElements = 'input' | 'textarea';
type FieldId = string;
type Validator = (
value: string | readonly string[] | number | boolean | undefined,
) => Error | undefined;
export type FieldConfig = {
element: FormElements;
props: ComponentProps<FormElements>;
label?: React.ReactNode;
validator?: Validator;
};
type TextInputFormProps<F extends FormValue<Record<FieldId, FieldConfig>>> = {
close: () => void;
fields: Record<FieldId, FieldConfig>;
onSubmit: (formValue: F) => Promise<void>;
className?: string;
shouldDisableSubmitButton?: (formValue: F) => boolean;
title?: string;
};
type FormValue<F extends Record<FieldId, FieldConfig>> = {
[K in keyof F]: F[K]['props']['value'];
};
export const FormDialog = <
F extends FormValue<Record<FieldId, FieldConfig>> = FormValue<
Record<FieldId, FieldConfig>
>,
>({
className,
close,
fields,
onSubmit,
shouldDisableSubmitButton,
title,
}: TextInputFormProps<F>) => {
const { t } = useTranslationContext();
const [fieldErrors, setFieldErrors] = useState<Record<FieldId, Error>>({});
const [value, setValue] = useState<F>(() => {
let acc: Partial<F> = {};
for (const [id, config] of Object.entries(fields)) {
acc = { ...acc, [id]: config.props.value };
}
return acc as F;
});
const handleChange = useCallback<
ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>
>(
(event) => {
const fieldId = event.target.id;
const fieldConfig = fields[fieldId];
if (!fieldConfig) return;
const error = fieldConfig.validator?.(event.target.value);
if (error) {
setFieldErrors((prev) => ({ [fieldId]: error, ...prev }));
} else {
setFieldErrors((prev) => {
delete prev[fieldId];
return prev;
});
}
setValue((prev) => ({ ...prev, [fieldId]: event.target.value }));
if (!fieldConfig.props.onChange) return;
if (fieldConfig.element === 'input') {
(fieldConfig.props.onChange as ChangeEventHandler<HTMLInputElement>)(
event as ChangeEvent<HTMLInputElement>,
);
} else if (fieldConfig.element === 'textarea') {
(fieldConfig.props.onChange as ChangeEventHandler<HTMLTextAreaElement>)(
event as ChangeEvent<HTMLTextAreaElement>,
);
}
},
[fields],
);
const handleSubmit = async () => {
if (!Object.keys(value).length) return;
const errors: Record<FieldId, Error> = {};
for (const [id, fieldValue] of Object.entries(value)) {
const thisFieldError = fields[id].validator?.(fieldValue);
if (thisFieldError) {
errors[id] = thisFieldError;
}
}
if (Object.keys(errors).length) {
setFieldErrors(errors);
return;
}
await onSubmit(value);
close();
};
return (
<div className={clsx('str-chat__dialog str-chat__dialog--form', className)}>
<div className='str-chat__dialog__body'>
{title && <div className='str-chat__dialog__title'>{title}</div>}
<form
autoComplete='off'
onSubmit={(e) => {
e.preventDefault();
handleSubmit();
}}
>
{Object.entries(fields).map(([id, fieldConfig]) => (
<div className='str-chat__dialog__field' key={`dialog-field-${id}`}>
{fieldConfig.label && (
<label
className={clsx(
`str-chat__dialog__title str-chat__dialog__title--${id}`,
)}
htmlFor={id}
>
{fieldConfig.label}
</label>
)}
{React.createElement(fieldConfig.element, {
id,
...fieldConfig.props,
onChange: handleChange,
value: value[id],
})}
<FieldError text={fieldErrors[id]?.message} />
</div>
))}
<div className='str-chat__dialog__controls'>
<button
className='str-chat__dialog__controls-button str-chat__dialog__controls-button--cancel'
onClick={close}
type='button'
>
{t('Cancel')}
</button>
<button
className='str-chat__dialog__controls-button str-chat__dialog__controls-button--submit'
disabled={
Object.keys(fieldErrors).length > 0 || shouldDisableSubmitButton?.(value)
}
type='submit'
>
{t('Send')}
</button>
</div>
</form>
</div>
</div>
);
};