forked from mozilla-extensions/firefox-voice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.js
More file actions
88 lines (79 loc) · 2.47 KB
/
Copy pathhelpers.js
File metadata and controls
88 lines (79 loc) · 2.47 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
/* globals communicate */
this.helpers = (function() {
const exports = {};
exports.Runner = class Runner {
constructor() {
this._logMessages = [];
}
log(...args) {
this._logMessages.push(args);
}
querySelector(selector) {
const element = document.querySelector(selector);
if (!element) {
const e = new Error(`Could not find element ${selector}`);
e.name = "ElementNotFound";
throw e;
}
return element;
}
querySelectorAll(selector) {
return document.querySelectorAll(selector);
}
setReactInputValue(input, value) {
// See https://hustle.bizongo.in/simulate-react-on-change-on-controlled-components-baa336920e04
// for the why of this
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value"
).set;
nativeInputValueSetter.call(input, value);
const inputEvent = new Event("input", { bubbles: true });
input.dispatchEvent(inputEvent);
}
waitForSelector(selector, options) {
const interval = (options && options.interval) || 50;
const timeout = (options && options.timeout) || 1000;
const minCount = (options && options.minCount) || 1;
return new Promise((resolve, reject) => {
const start = Date.now();
const id = setInterval(() => {
const result = document.querySelectorAll(selector);
if (result.length && result.length >= minCount) {
clearTimeout(id);
if (options && options.all) {
resolve(result);
} else {
resolve(result[0]);
}
return;
}
if (Date.now() > start + timeout) {
const e = new Error(`Timeout waiting for ${selector}`);
e.name = "TimeoutError";
clearTimeout(id);
reject(e);
}
}, interval);
});
}
};
exports.Runner.register = function() {
const Class = this;
for (const name of Object.getOwnPropertyNames(Class.prototype)) {
if (name.startsWith("action_")) {
const actionName = name.substr("action_".length);
communicate.register(actionName, message => {
const instance = new Class();
try {
return instance[name](message);
} catch (e) {
e.log = instance._logMessages;
throw e;
}
});
}
}
};
return exports;
})();