forked from emberjs/ember.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode-query.js
120 lines (88 loc) · 2.29 KB
/
node-query.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/* global Node */
import { assert } from '@ember/debug';
import { fireEvent, focus, matches } from './system/synthetic-events';
export default class NodeQuery {
static query(selector, context = document) {
assert(`Invalid second parameter to NodeQuery.query`, context && context instanceof Node);
return new NodeQuery(toArray(context.querySelectorAll(selector)));
}
static element(element) {
return new NodeQuery([element]);
}
constructor(nodes) {
assert('NodeQuery must be initialized with a literal array', Array.isArray(nodes));
this.nodes = nodes;
for (let i = 0; i < nodes.length; i++) {
this[i] = nodes[i];
}
this.length = nodes.length;
Object.freeze(this);
}
find(selector) {
assertSingle(this);
return this[0].querySelector(selector);
}
findAll(selector) {
let nodes = [];
this.nodes.forEach(node => {
nodes.push(...node.querySelectorAll(selector));
});
return new NodeQuery(nodes);
}
trigger(eventName, options) {
return this.nodes.map(node => fireEvent(node, eventName, options));
}
click() {
return this.trigger('click');
}
focus() {
this.nodes.forEach(focus);
}
text() {
return this.nodes.map(node => node.textContent).join('');
}
attr(name) {
if (arguments.length !== 1) {
throw new Error('not implemented');
}
assertSingle(this);
return this.nodes[0].getAttribute(name);
}
prop(name, value) {
if (arguments.length > 1) {
return this.setProp(name, value);
}
assertSingle(this);
return this.nodes[0][name];
}
setProp(name, value) {
this.nodes.forEach(node => (node[name] = value));
return this;
}
val(value) {
if (arguments.length === 1) {
return this.setProp('value', value);
}
return this.prop('value');
}
is(selector) {
return this.nodes.every(node => matches(node, selector));
}
hasClass(className) {
return this.is(`.${className}`);
}
}
function assertSingle(nodeQuery) {
if (nodeQuery.length !== 1) {
throw new Error(
`attr(name) called on a NodeQuery with ${this.nodes.length} elements. Expected one element.`
);
}
}
function toArray(nodes) {
let out = [];
for (let i = 0; i < nodes.length; i++) {
out.push(nodes[i]);
}
return out;
}