-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetValue.ts
60 lines (48 loc) · 1.86 KB
/
setValue.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
import type { Driver } from '../Driver.js';
import { ElementNotInteractable } from '../errors/ElementNotInteractable.js';
import { fromWebDriverElement } from '../helpers/Element.js';
import { ATOMIC_TYPES, isEditableElement } from '../helpers/isEditableElement.js';
export function setValue(this: Driver, text: string | string[], elementId: string): void {
text = Array.isArray(text) ? text.join('') : text;
const element = fromWebDriverElement(elementId);
const isFocused = this.currentContext.document.activeElement === element;
if (!isEditableElement(element)) {
throw ElementNotInteractable('element is not editable');
}
if (element.isContentEditable) {
const selection = this.currentContext.getSelection();
if (!isFocused) {
element.focus();
selection?.selectAllChildren(element);
selection?.collapseToEnd();
}
if (selection?.rangeCount) {
const node = this.currentContext.document.createTextNode(text);
const range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(node);
selection.collapseToEnd();
} else {
element.innerHTML += text;
}
return;
}
const tagName = element.tagName;
const input = element as HTMLInputElement | HTMLTextAreaElement;
if (!isFocused) {
input.focus();
if (typeof input.selectionStart === 'number') {
input.selectionStart = input.selectionEnd = input.value.length;
}
}
if (tagName === 'INPUT' && ~ATOMIC_TYPES.indexOf(input.type.toLowerCase())) {
input.value = text;
} else {
const value = input.value;
const end = input.selectionEnd ?? value.length;
const start = input.selectionStart ?? value.length;
input.value = value.slice(0, start) + text + value.slice(end);
}
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}