-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTextInput.tsx
More file actions
333 lines (305 loc) · 9.41 KB
/
TextInput.tsx
File metadata and controls
333 lines (305 loc) · 9.41 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
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
import { Input, Form, ConfigProvider } from "antd";
import type { Expression, EnsembleAction } from "@ensembleui/react-framework";
import { useRegisterBindings } from "@ensembleui/react-framework";
import { useEffect, useMemo, useState, useCallback, useRef } from "react";
import type { RefCallback, FormEvent } from "react";
import { runes } from "runes2";
import type { Rule } from "antd/es/form";
import { forEach, isObject, omitBy, debounce } from "lodash-es";
import IMask, { type InputMask } from "imask";
import type { EnsembleWidgetProps } from "../../shared/types";
import { WidgetRegistry } from "../../registry";
import type { TextStyles } from "../Text";
import { useEnsembleAction } from "../../runtime/hooks/useEnsembleAction";
import type { FormInputProps } from "./types";
import { EnsembleFormItem } from "./FormItem";
const widgetName = "TextInput";
export type TextInputProps = {
hintStyle?: TextStyles;
labelStyle?: TextStyles;
/** @deprecated see {@link TextInputProps.multiline} */
multiLine?: Expression<boolean>;
/** Specify whether this Text Input should span multiple lines */
multiline?: Expression<boolean>;
maxLines?: number;
maxLength?: Expression<number>;
maxLengthEnforcement?: Expression<
"none" | "enforced" | "truncateAfterCompositionEnds"
>;
inputType?: "email" | "phone" | "number" | "text" | "url"; //| "ipAddress";
onChange?: {
debounceMs?: number;
} & EnsembleAction;
mask?: string;
validator?: {
minLength?: number;
maxLength?: number;
regex?: string;
regexError?: string;
maskError?: string;
};
onKeyDown?: EnsembleAction;
} & EnsembleWidgetProps<TextStyles> &
FormInputProps<string>;
export const TextInput: React.FC<TextInputProps> = (props) => {
const [mask, setMask] = useState<InputMask>();
const [value, setValue] = useState<string>();
const maskRef = useRef<{ input: HTMLInputElement } | null>(null);
const { values, rootRef } = useRegisterBindings(
{ ...props, initialValue: props.value, value, widgetName },
props.id,
{
setValue,
},
{
debounceMs: 300,
},
);
const formInstance = Form.useFormInstance();
const action = useEnsembleAction(props.onChange);
const onKeyDownAction = useEnsembleAction(props.onKeyDown);
const debouncedOnChange = useMemo(
() =>
debounce((inputValue: string) => {
action?.callback({ value: inputValue });
}, values?.onChange?.debounceMs ?? 0),
[action?.callback, values?.onChange?.debounceMs],
);
const handleChange = useCallback(
(newValue: string) => {
setValue(newValue);
debouncedOnChange(newValue);
},
[debouncedOnChange],
);
const handleRef: RefCallback<never> = (node) => {
maskRef.current = node;
rootRef(node);
};
const sanitizeNumberInput = useCallback((e: FormEvent<HTMLInputElement>) => {
const target = e.target as HTMLInputElement;
target.value = target.value.replace(/[^0-9.]/g, "");
}, []);
const handleInputPaste = useCallback(
(e: React.ClipboardEvent) => {
const pastedData = e.clipboardData.getData("text");
if (mask) {
mask.unmaskedValue = pastedData;
handleChange(mask.value);
}
},
[handleChange, mask],
);
const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLTextAreaElement | HTMLInputElement>) =>
onKeyDownAction?.callback({
event: {
...omitBy(event, isObject),
preventDefault: event.preventDefault.bind(event),
},
}),
[onKeyDownAction],
);
useEffect(() => {
setValue(values?.initialValue);
}, [values?.initialValue]);
useEffect(() => {
if (formInstance && (values?.id || values?.label)) {
formInstance.setFieldsValue({
[values.id ?? values.label]: value,
});
}
}, [value, formInstance, values?.id, values?.label]);
useEffect(() => {
if (values?.mask && maskRef.current) {
const iMask = IMask(maskRef.current.input, {
mask: values.mask.replace(/#/g, "0").replace(/A/g, "a"),
lazy: true,
});
setMask(iMask);
}
}, [values?.mask]);
// cleanup debounced function when component unmounts or changes
useEffect(() => {
return () => {
if (
debouncedOnChange &&
typeof debouncedOnChange === "function" &&
"cancel" in debouncedOnChange
) {
(debouncedOnChange as ReturnType<typeof debounce>).cancel();
}
};
}, [debouncedOnChange]);
const inputType = useMemo(() => {
switch (values?.inputType) {
case "email":
return "email";
case "phone":
return "tel";
case "number":
return "tel";
case "url":
return "url";
default:
return "text";
}
}, [values?.inputType]);
const patternValue = useMemo((): string | undefined | RegExp => {
if (!values?.mask) {
return;
}
// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern#overview
const special = [
"[",
"]",
"\\",
"/",
"^",
"$",
".",
"|",
"?",
"*",
"+",
"(",
")",
"{",
"}",
];
let pattern = "^(?:";
forEach(values.mask, (char) => {
switch (char) {
case "#":
pattern += "[0-9]"; // Match any digit
break;
case "A":
pattern += "[a-zA-Z]"; // Match any letter
break;
default:
if (special.includes(char)) {
pattern += `\\${char}`; // Escape special characters
} else {
pattern += char; // Include the character literally
}
break;
}
});
return `${pattern})$`;
}, [values?.mask]);
const rules = useMemo(() => {
const rulesArray: Rule[] = [];
if (values?.validator?.minLength) {
rulesArray.push({
min: values.validator.minLength,
message: `The field must be at least ${values.validator.minLength} characters long`,
});
}
if (values?.validator?.maxLength) {
rulesArray.push({
max: values.validator.maxLength,
message: `The field must be at most ${values.validator.maxLength} characters long`,
});
}
const regex = values?.validator?.regex;
if (regex) {
rulesArray.push({
validator: (_, inputValue?: string) => {
if (!inputValue || new RegExp(regex).test(inputValue || "")) {
return Promise.resolve();
}
return Promise.reject(
new Error(
values.validator?.regexError || "The field has an invalid value",
),
);
},
});
}
if (values?.mask && patternValue) {
rulesArray.push({
validator: (_, inputValue?: string) => {
if (!inputValue || new RegExp(patternValue).test(inputValue)) {
return Promise.resolve();
}
return Promise.reject(
new Error(
values.validator?.maskError ||
`The value must be of the format ${values.mask || ""}`,
),
);
},
});
}
return rulesArray;
}, [
values?.validator?.minLength,
values?.validator?.maxLength,
values?.validator?.regex,
values?.validator?.regexError,
values?.validator?.maskError,
values?.mask,
patternValue,
]);
const maxLengthConfig = values?.maxLength
? {
max: values.maxLength as number,
show: true,
exceedFormatter:
values.maxLengthEnforcement === "none"
? undefined
: (txt: string, { max }: { max: number }): string =>
runes(txt).slice(0, max).join(""),
}
: undefined;
return (
<ConfigProvider
theme={{ token: { colorTextPlaceholder: values?.hintStyle?.color } }}
>
<EnsembleFormItem rules={rules} valuePropName="value" values={values}>
{values?.multiLine || values?.multiline ? (
<Input.TextArea
count={maxLengthConfig}
defaultValue={values.value}
disabled={values.enabled === false}
onChange={(event): void => handleChange(event.target.value)}
onKeyDown={handleKeyDown}
placeholder={values.hintText ?? ""}
ref={rootRef}
rows={values.maxLines ? Number(values.maxLines) : 4} // Adjust the number of rows as needed
style={{
...(values.styles ?? values.hintStyle),
...(values.styles?.visible === false
? { display: "none" }
: undefined),
}}
value={values.value}
/>
) : (
<Input
count={maxLengthConfig}
defaultValue={values?.value}
disabled={values?.enabled === false}
onChange={(event): void => handleChange(event.target.value)}
{...(values?.inputType === "number" && {
onInput: (event): void => sanitizeNumberInput(event),
})}
onKeyDown={handleKeyDown}
onPaste={handleInputPaste}
placeholder={values?.hintText ?? ""}
ref={handleRef}
style={{
...(values?.styles ?? values?.hintStyle),
...(values?.styles?.visible === false
? { display: "none" }
: undefined),
}}
type={inputType}
value={value}
/>
)}
</EnsembleFormItem>
</ConfigProvider>
);
};
WidgetRegistry.register(widgetName, TextInput);