-
-
Notifications
You must be signed in to change notification settings - Fork 260
/
Copy pathfill-in.ts
81 lines (67 loc) · 2.5 KB
/
fill-in.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
import getElement from './-get-element';
import isFormControl from './-is-form-control';
import guardForMaxlength from './-guard-for-maxlength';
import { __focus__ } from './focus';
import settled from '../settled';
import fireEvent from './fire-event';
import { Promise } from '../-utils';
import Target, { isContentEditable } from './-target';
import { log } from '@ember/test-helpers/dom/-logging';
import { runHooks, registerHook } from '../-internal/helper-hooks';
registerHook('fillIn', 'start', (target: Target, text: string) => {
log('fillIn', target, text);
});
/**
Fill the provided text into the `value` property (or set `.innerHTML` when
the target is a content editable element) then trigger `change` and `input`
events on the specified target.
@public
@param {string|Element} target the element or selector to enter text into
@param {string} text the text to fill into the target element
@return {Promise<void>} resolves when the application is settled
@example
<caption>
Emulating filling an input with text using `fillIn`
</caption>
fillIn('input', 'hello world');
*/
export default function fillIn(target: Target, text: string): Promise<void> {
return Promise.resolve()
.then(() => runHooks('fillIn', 'start', target, text))
.then(() => {
if (!target) {
throw new Error('Must pass an element or selector to `fillIn`.');
}
let element = getElement(target) as Element | HTMLElement;
if (!element) {
throw new Error(
`Element not found when calling \`fillIn('${target}')\`.`
);
}
if (typeof text === 'undefined' || text === null) {
throw new Error('Must provide `text` when calling `fillIn`.');
}
if (isFormControl(element)) {
if (element.disabled) {
throw new Error(`Can not \`fillIn\` disabled '${target}'.`);
}
if ('readOnly' in element && element.readOnly) {
throw new Error(`Can not \`fillIn\` readonly '${target}'.`);
}
guardForMaxlength(element, text, 'fillIn');
__focus__(element);
element.value = text;
} else if (isContentEditable(element)) {
__focus__(element);
element.innerHTML = text;
} else {
throw new Error(
'`fillIn` is only usable on form controls or contenteditable elements.'
);
}
fireEvent(element, 'input');
fireEvent(element, 'change');
return settled();
})
.then(() => runHooks('fillIn', 'end', target, text));
}