-
-
Notifications
You must be signed in to change notification settings - Fork 251
/
blur.ts
71 lines (56 loc) · 1.95 KB
/
blur.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
import getElement from './-get-element';
import fireEvent from './fire-event';
import settled from '../settled';
import isFocusable from './-is-focusable';
import { nextTickPromise } from '../-utils';
import Target from './-target';
import { log } from '@ember/test-helpers/dom/-logging';
/**
@private
@param {Element} element the element to trigger events on
*/
export function __blur__(element: HTMLElement | SVGElement): void {
let browserIsNotFocused = document.hasFocus && !document.hasFocus();
// makes `document.activeElement` be `body`.
// If the browser is focused, it also fires a blur event
element.blur();
// Chrome/Firefox does not trigger the `blur` event if the window
// does not have focus. If the document does not have focus then
// fire `blur` event via native event.
if (browserIsNotFocused) {
fireEvent(element, 'blur', { bubbles: false });
fireEvent(element, 'focusout');
}
}
/**
Unfocus the specified target.
Sends a number of events intending to simulate a "real" user unfocusing an
element.
The following events are triggered (in order):
- `blur`
- `focusout`
The exact listing of events that are triggered may change over time as needed
to continue to emulate how actual browsers handle unfocusing a given element.
@public
@param {string|Element} [target=document.activeElement] the element or selector to unfocus
@return {Promise<void>} resolves when settled
@example
<caption>
Emulating blurring an input using `blur`
</caption>
blur('input');
*/
export default function blur(target: Target = document.activeElement!): Promise<void> {
log('blur', target);
return nextTickPromise().then(() => {
let element = getElement(target);
if (!element) {
throw new Error(`Element not found when calling \`blur('${target}')\`.`);
}
if (!isFocusable(element)) {
throw new Error(`${target} is not focusable`);
}
__blur__(element);
return settled();
});
}