-
-
Notifications
You must be signed in to change notification settings - Fork 255
/
click.ts
90 lines (71 loc) · 2.5 KB
/
click.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import getElement from './-get-element';
import fireEvent from './fire-event';
import { __focus__ } from './focus';
import settled from '../settled';
import isFocusable from './-is-focusable';
import { nextTickPromise } from '../-utils';
import isFormControl from './-is-form-control';
import Target from './-target';
/**
@private
@param {Element} element the element to click on
@param {Object} options the options to be merged into the mouse events
*/
export function __click__(element: Element | Document, options: MouseEventInit): void {
fireEvent(element, 'mousedown', options);
if (isFocusable(element)) {
__focus__(element);
}
fireEvent(element, 'mouseup', options);
fireEvent(element, 'click', options);
}
/**
Clicks on the specified target.
Sends a number of events intending to simulate a "real" user clicking on an
element.
For non-focusable elements the following events are triggered (in order):
- `mousedown`
- `mouseup`
- `click`
For focusable (e.g. form control) elements the following events are triggered
(in order):
- `mousedown`
- `focus`
- `focusin`
- `mouseup`
- `click`
The exact listing of events that are triggered may change over time as needed
to continue to emulate how actual browsers handle clicking a given element.
Use the `options` hash to change the parameters of the [MouseEvents](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent).
You can use this to specifiy modifier keys as well.
@public
@param {string|Element} target the element or selector to click on
@param {Object} options the options to be merged into the mouse events
@return {Promise<void>} resolves when settled
@example
<caption>
Emulating clicking a button using `click`
</caption>
click('button');
@example
<caption>
Emulating clicking a button and pressing the `shift` key simultaneously using `click` with `options`.
</caption>
click('button', { shiftKey: true });
*/
export default function click(target: Target, options: MouseEventInit = {}): Promise<void> {
return nextTickPromise().then(() => {
if (!target) {
throw new Error('Must pass an element or selector to `click`.');
}
let element = getElement(target);
if (!element) {
throw new Error(`Element not found when calling \`click('${target}')\`.`);
}
let isDisabledFormControl = isFormControl(element) && element.disabled;
if (!isDisabledFormControl) {
__click__(element, options);
}
return settled();
});
}