-
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathindex.js
More file actions
476 lines (403 loc) · 12.7 KB
/
index.js
File metadata and controls
476 lines (403 loc) · 12.7 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
class InvalidSelector extends Error {}
class TimedOutPromise extends Error {}
class MouseEventFailed extends Error {}
const EVENTS = {
FOCUS: ["blur", "focus", "focusin", "focusout"],
MOUSE: ["click", "dblclick", "mousedown", "mouseenter", "mouseleave",
"mousemove", "mouseover", "mouseout", "mouseup", "contextmenu"],
FORM: ["submit"]
}
class Cuprite {
constructor() {
this._json = JSON; // In case someone overrides it like mootools
}
find(method, selector, within = document) {
try {
let results = [];
if (method == "xpath") {
let xpath = document.evaluate(selector, within, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0; i < xpath.snapshotLength; i++) {
results.push(xpath.snapshotItem(i));
}
} else {
results = Array.from(within.querySelectorAll(selector));
}
return results;
} catch (error) {
// DOMException.INVALID_EXPRESSION_ERR is undefined, using pure code
if (error.code == DOMException.SYNTAX_ERR || error.code == 51) {
throw new InvalidSelector;
} else {
throw error;
}
}
}
parents(node) {
let nodes = [];
let parent = node.parentNode;
while (parent != document && parent !== null) {
nodes.push(parent);
parent = parent.parentNode;
}
return nodes;
}
visibleText(node) {
if (this.isVisible(node)) {
if (node.nodeName == "TEXTAREA") {
return node.textContent;
} else {
if (node instanceof SVGElement) {
return node.textContent;
} else {
return node.innerText;
}
}
}
}
isVisible(node) {
let mapName, style;
// if node is area, check visibility of relevant image
if (node.tagName === "AREA") {
mapName = document.evaluate("./ancestor::map/@name", node, null, XPathResult.STRING_TYPE, null).stringValue;
node = document.querySelector(`img[usemap="#${mapName}"]`);
if (node == null) {
return false;
}
}
while (node) {
style = window.getComputedStyle(node);
if (style.display === "none" || style.visibility === "hidden" || parseFloat(style.opacity) === 0) {
return false;
}
node = node.parentElement;
}
return true;
}
isDisabled(node) {
let xpath = "parent::optgroup[@disabled] | \
ancestor::select[@disabled] | \
parent::fieldset[@disabled] | \
ancestor::*[not(self::legend) or preceding-sibling::legend][parent::fieldset[@disabled]]";
return node.disabled || document.evaluate(xpath, node, null, XPathResult.BOOLEAN_TYPE, null).booleanValue;
}
path(node) {
let nodes = [node];
let parent = node.parentNode;
while (parent !== document && parent !== null) {
nodes.unshift(parent);
parent = parent.parentNode;
}
let selectors = nodes.map(node => {
let prevSiblings = [];
let xpath = document.evaluate(`./preceding-sibling::${node.tagName}`, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0; i < xpath.snapshotLength; i++) {
prevSiblings.push(xpath.snapshotItem(i));
}
return `${node.tagName}[${(prevSiblings.length + 1)}]`;
});
return `//${selectors.join("/")}`;
}
set(node, value) {
if (node.readOnly) return;
if (node.maxLength >= 0) {
value = value.substr(0, node.maxLength);
}
let valueBefore = node.value;
this.trigger(node, "focus");
this.setValue(node, "");
if (node.type == "date" || node.type == "range") {
this.setValue(node, value);
this.input(node);
} else if (node.type == "time") {
this.setValue(node, new Date(value).toTimeString().split(" ")[0]);
this.input(node);
} else if (node.type == "datetime-local") {
value = new Date(value);
let year = value.getFullYear();
let month = ("0" + (value.getMonth() + 1)).slice(-2);
let date = ("0" + value.getDate()).slice(-2);
let hour = ("0" + value.getHours()).slice(-2);
let min = ("0" + value.getMinutes()).slice(-2);
let sec = ("0" + value.getSeconds()).slice(-2);
this.setValue(node, `${year}-${month}-${date}T${hour}:${min}:${sec}`);
this.input(node);
} else {
for (let char of value.toString()) {
let keyCode = this.characterToKeyCode(char);
// call the following functions in order, if one returns false (preventDefault),
// stop the call chain
[
() => this.keyupdowned(node, "keydown", keyCode),
() => this.keypressed(node, false, false, false, false, char.charCodeAt(0), char.charCodeAt(0)),
() => {
this.setValue(node, node.value + char)
this.input(node)
}
].some(fn => fn())
this.keyupdowned(node, "keyup", keyCode);
}
}
if (valueBefore !== node.value) {
this.changed(node);
}
this.trigger(node, "blur");
}
setValue(node, value) {
let nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
let nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
if (node.tagName.toLowerCase() === 'input') {
return nativeInputValueSetter.call(node, value);
}
return nativeTextareaValueSetter.call(node, value);
}
input(node) {
let event = new InputEvent("input", { inputType: "insertText", bubbles: true, cancelable: false });
node.dispatchEvent(event);
}
/**
* @return {boolean} false when an event handler called preventDefault()
*/
keyupdowned(node, eventName, keyCode) {
let event = document.createEvent("UIEvents");
event.initEvent(eventName, true, true);
event.keyCode = keyCode;
event.charCode = 0;
return !node.dispatchEvent(event);
}
/**
* @return {boolean} false when an event handler called preventDefault()
*/
keypressed(node, altKey, ctrlKey, shiftKey, metaKey, keyCode, charCode) {
event = document.createEvent("UIEvents");
event.initEvent("keypress", true, true);
event.window = window;
event.altKey = altKey;
event.ctrlKey = ctrlKey;
event.shiftKey = shiftKey;
event.metaKey = metaKey;
event.keyCode = keyCode;
event.charCode = charCode;
return !node.dispatchEvent(event);
}
characterToKeyCode(char) {
const specialKeys = {
96: 192, // `
45: 189, // -
61: 187, // =
91: 219, // [
93: 221, // ]
92: 220, // \
59: 186, // ;
39: 222, // '
44: 188, // ,
46: 190, // .
47: 191, // /
127: 46, // delete
126: 192, // ~
33: 49, // !
64: 50, // @
35: 51, // #
36: 52, // $
37: 53, // %
94: 54, // ^
38: 55, // &
42: 56, // *
40: 57, // (
41: 48, // )
95: 189, // _
43: 187, // +
123: 219, // {
125: 221, // }
124: 220, // |
58: 186, // :
34: 222, // "
60: 188, // <
62: 190, // >
63: 191, // ?
}
let code = char.toUpperCase().charCodeAt(0);
return specialKeys[code] || code;
}
scrollIntoViewport(node) {
let areaImage = this._getAreaImage(node);
if (areaImage) {
return this.scrollIntoViewport(areaImage);
} else {
node.scrollIntoViewIfNeeded();
if (!this._isInViewport(node)) {
node.scrollIntoView({block: "center", inline: "center", behavior: "instant"});
return this._isInViewport(node);
}
return true;
}
}
mouseEventTest(node, name, x, y) {
let frameOffset = this._frameOffset();
x -= frameOffset.left;
y -= frameOffset.top;
let element = document.elementFromPoint(x, y);
let el = element;
while (el) {
if (el == node) {
return true;
} else {
el = el.parentNode;
}
}
let selector = element && this._getSelector(element) || "none";
throw new MouseEventFailed([name, selector, x, y].join(", "));
}
_getAreaImage(node) {
if ("area" == node.tagName.toLowerCase()) {
let map = node.parentNode;
if (map.tagName.toLowerCase() != "map") {
throw new Error("the area is not within a map");
}
let mapName = map.getAttribute("name");
if (typeof mapName === "undefined" || mapName === null) {
throw new Error("area's parent map must have a name");
}
mapName = `#${mapName.toLowerCase()}`;
let imageNode = this.find("css", `img[usemap='${mapName}']`)[0];
if (typeof imageNode === "undefined" || imageNode === null) {
throw new Error("no image matches the map");
}
return imageNode;
}
}
_frameOffset() {
let win = window;
let offset = { top: 0, left: 0 };
while (win.frameElement) {
let rect = win.frameElement.getClientRects()[0];
let style = win.getComputedStyle(win.frameElement);
win = win.parent;
offset.top += rect.top + parseInt(style.getPropertyValue("padding-top"), 10)
offset.left += rect.left + parseInt(style.getPropertyValue("padding-left"), 10)
}
return offset;
}
_getSelector(el) {
let selector = (el.tagName != 'HTML') ? this._getSelector(el.parentNode) + " " : "";
selector += el.tagName.toLowerCase();
if (el.id) { selector += `#${el.id}` };
el.classList.forEach(c => selector += `.${c}`);
return selector;
}
_isInViewport(node) {
let rect = node.getBoundingClientRect();
return rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= window.innerHeight &&
rect.right <= window.innerWidth;
}
select(node, value) {
if (this.isDisabled(node)) {
return false;
} else if (value == false && !node.parentNode.multiple) {
return false;
} else {
this.trigger(node.parentNode, "focus");
node.selected = value;
this.changed(node);
this.trigger(node.parentNode, "blur");
return true;
}
}
changed(node) {
let element;
let event = document.createEvent("HTMLEvents");
event.initEvent("change", true, false);
// In the case of an OPTION tag, the change event should come
// from the parent SELECT
if (node.nodeName == "OPTION") {
element = node.parentNode
if (element.nodeName == "OPTGROUP") {
element = element.parentNode
}
element
} else {
element = node
}
element.dispatchEvent(event)
}
trigger(node, name, options = {}) {
let event;
if (EVENTS.MOUSE.indexOf(name) != -1) {
event = document.createEvent("MouseEvent");
event.initMouseEvent(
name, true, true, window, 0,
options["screenX"] || 0, options["screenY"] || 0,
options["clientX"] || 0, options["clientY"] || 0,
options["ctrlKey"] || false,
options["altKey"] || false,
options["shiftKey"] || false,
options["metaKey"] || false,
options["button"] || 0, null
)
} else if (EVENTS.FOCUS.indexOf(name) != -1) {
event = this.obtainEvent(name);
} else if (EVENTS.FORM.indexOf(name) != -1) {
event = this.obtainEvent(name);
} else {
throw "Unknown event";
}
node.dispatchEvent(event);
}
obtainEvent(name) {
let event = document.createEvent("HTMLEvents");
event.initEvent(name, true, true);
return event;
}
getAttributes(node) {
let attrs = {};
for (let i = 0, len = node.attributes.length; i < len; i++) {
let attr = node.attributes[i];
attrs[attr.name] = attr.value.replace("\n", "\\n");
}
return this._json.stringify(attrs);
}
getAttribute(node, name) {
if (name == "checked" || name == "selected") {
return node[name];
} else {
return node.getAttribute(name);
}
}
value(node) {
if (node.tagName == "SELECT" && node.multiple) {
let result = []
for (let i = 0, len = node.children.length; i < len; i++) {
let option = node.children[i];
if (option.selected) {
result.push(option.value);
}
}
return result;
} else {
return node.value;
}
}
deleteText(node) {
let range = document.createRange();
range.selectNodeContents(node);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
window.getSelection().deleteFromDocument();
}
containsSelection(node) {
let selectedNode = document.getSelection().focusNode;
if (!selectedNode) {
return false;
}
if (selectedNode.nodeType == 3) {
selectedNode = selectedNode.parentNode;
}
return node.contains(selectedNode);
}
// This command is purely for testing error handling
browserError() {
throw new Error("zomg");
}
}
window._cuprite = new Cuprite;