-
-
Notifications
You must be signed in to change notification settings - Fork 367
/
type.ts
68 lines (54 loc) · 1.69 KB
/
type.ts
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
import { isFocusable, warning } from "reakit-utils";
import { subscribeDefaultPrevented } from "./__utils/subscribeDefaultPrevented";
import { isTextField } from "./__utils/isTextField";
import { DirtiableElement } from "./__utils/types";
import { fireEvent } from "./fireEvent";
import { focus } from "./focus";
import "./mockClientRects";
const charMap: Record<string, string> = {
"\b": "Backspace"
};
const keyMap: Record<
string,
(
element: HTMLInputElement | HTMLTextAreaElement,
options: InputEventInit
) => string
> = {
Backspace(element) {
return element.value.substr(0, element.value.length - 1);
}
};
export function type(
text: string,
element?: DirtiableElement | null,
options: InputEventInit = {}
) {
if (element == null) {
element = document.activeElement;
}
if (!element || !isFocusable(element)) return;
if (!isTextField(element)) {
warning(
true,
"[reakit-test-utils/type]",
"You're trying to type on an element that is not able of being typed on a keyboard."
);
return;
}
focus(element);
// Set element dirty so blur() can dispatch a change event
element.dirty = true;
for (const char of text) {
const key = char in charMap ? charMap[char] : char;
const value =
key in keyMap ? keyMap[key](element, options) : `${element.value}${char}`;
const defaultPrevented = subscribeDefaultPrevented(element, "keydown");
fireEvent.keyDown(element, { key, ...options });
if (!defaultPrevented.current && !element.readOnly) {
fireEvent.input(element, { data: char, target: { value }, ...options });
}
fireEvent.keyUp(element, { key, ...options });
defaultPrevented.unsubscribe();
}
}