forked from neolution-ch/react-hook-form-components
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTelephoneNumberInputInternal.tsx
More file actions
156 lines (145 loc) · 5.34 KB
/
TelephoneNumberInputInternal.tsx
File metadata and controls
156 lines (145 loc) · 5.34 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
import TextField from "@mui/material/TextField";
import PopupState, { bindPopover } from "material-ui-popup-state";
import { FieldError, FieldValues, get, useController } from "react-hook-form";
import { useMarkOnFocusHandler } from "../../hooks/useMarkOnFocusHandler";
import { textFieldBootstrapStyle } from "../../helpers/mui";
import { useFormContext } from "../../context/FormContext";
import { useEffect, useMemo, useRef, useState } from "react";
import Popover from "@mui/material/Popover";
import { TelephoneNumberInputProps } from "../../TelephoneNumberInput";
import { getRequiredLabel } from "../../helpers/form";
import { Country, extractCountryCodeFromTelephoneNumber, extractNationalNumberFromTelephoneNumber } from "../../helpers/telephoneNumber";
import { TelephoneNumberInputAdornment } from "./TelephoneNumberInputAdornment";
import { isNullOrWhitespace } from "@neolution-ch/javascript-utils";
import { TelephoneNumberAutocomplete } from "./TelephoneNumberAutocomplete";
const TelephoneNumberInputInternal = <T extends FieldValues>(props: TelephoneNumberInputProps<T>) => {
const {
name,
id,
label,
disabled,
helpText,
defaultCountry,
onChange: propsOnChange,
onBlur: propsOnBlur,
renderAutocompleteField = (children) => children,
style,
markAllOnFocus,
className = "",
useBootstrapStyle = false,
hideValidationMessage,
placeholder,
maxLength,
} = props;
const {
control,
disabled: formDisabled,
getFieldState,
requiredFields,
formState: { errors },
hideValidationMessages,
} = useFormContext<T>();
const focusHandler = useMarkOnFocusHandler(markAllOnFocus);
const {
field: { ref, ...field },
} = useController<T>({
name,
control,
rules: {
validate: {
required: () => getFieldState(name)?.error?.message,
},
},
});
const isDisabled = formDisabled || disabled;
const fieldError = get(errors, name) as FieldError | undefined;
const hideErrorMessage = useMemo(() => hideValidationMessages || hideValidationMessage, [hideValidationMessages, hideValidationMessage]);
const hasError = useMemo(() => !!fieldError, [fieldError]);
const errorMessage = useMemo(() => String(fieldError?.message), [fieldError]);
const finalLabel = useMemo(() => getRequiredLabel<T>(label, name, requiredFields), [label, name, requiredFields]);
// we need to control the country in the case the value inside the form is undefined
const [country, setCountry] = useState<Country>(extractCountryCodeFromTelephoneNumber(field.value as string | undefined, defaultCountry));
const resetCountry = useRef(true);
useEffect(() => {
if (resetCountry.current) {
setCountry(extractCountryCodeFromTelephoneNumber(field.value as string | undefined, defaultCountry));
}
resetCountry.current = true;
}, [defaultCountry, field.value]);
const nationalPhoneNumber: string | undefined = useMemo(
() => extractNationalNumberFromTelephoneNumber(field.value as string | undefined, country),
[country, field.value],
);
return (
<PopupState variant="popover" popupId={`popover-${name}`}>
{(popupState) => (
<>
<TextField
{...field}
value={nationalPhoneNumber || ""}
id={id}
fullWidth
className={className}
sx={{ ...(useBootstrapStyle && textFieldBootstrapStyle) }}
style={style}
error={hasError}
label={useBootstrapStyle ? undefined : finalLabel}
helperText={hasError && !hideErrorMessage ? errorMessage : helpText}
placeholder={placeholder}
disabled={isDisabled}
onFocus={focusHandler}
onChange={(e) => {
if (isNullOrWhitespace(e.target.value)) {
// nothing to do
} else {
// the value in the form must always include the country prefix
const numericValue = `${country.code}${e.target.value}`.replaceAll(/\D/g, "");
e.target.value = `+${numericValue}`;
}
if (propsOnChange) {
propsOnChange(e.target.value);
}
resetCountry.current = false;
field.onChange(e);
}}
onBlur={(e) => {
if (propsOnBlur) {
propsOnBlur(e);
}
field.onBlur();
}}
slotProps={{
htmlInput: {
maxLength,
},
input: {
inputMode: "tel",
startAdornment: <TelephoneNumberInputAdornment disabled={isDisabled} country={country} popupState={popupState} />,
},
}}
inputRef={ref}
/>
<Popover
aria-hidden={false}
{...bindPopover(popupState)}
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
>
{renderAutocompleteField(
<TelephoneNumberAutocomplete<T>
{...props}
popupState={popupState}
nationalPhoneNumber={nationalPhoneNumber}
country={country}
setCountry={setCountry}
/>,
)}
</Popover>
</>
)}
</PopupState>
);
};
export { TelephoneNumberInputInternal };