UNPKG

1.98 kBJavaScriptView Raw
1var __assign = (this && this.__assign) || Object.assign || function(t) {
2 for (var s, i = 1, n = arguments.length; i < n; i++) {
3 s = arguments[i];
4 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
5 t[p] = s[p];
6 }
7 return t;
8};
9/**
10 * Generic function to wait for something to happen. Uses polling
11 * @param getter: a getter function that returns anything else than `null` or an
12 * empty array or an empty jQuery object when the
13 * condition is met
14 * @param options: lookup options, defaults to
15 * `{present: true, interval: 50, timeout: 5000}`
16 */
17export function waitFor(getter, options) {
18 if (options === void 0) { options = { present: true, interval: 50, timeout: 5000 }; }
19 // prevents infinite recursion if the request times out
20 var timedOut = false;
21 options = __assign({ present: true, interval: 50, timeout: 5000 }, options);
22 function wait() {
23 var element = getter();
24 // boolean is needed here, hence the length > 0
25 var found = element !== null && (!(element instanceof NodeList) &&
26 !element.jquery || element.length > 0);
27 if (!options.present === !found || timedOut) {
28 return Promise.resolve(element);
29 }
30 return new Promise(function (rs) { return setTimeout(rs, options.interval); }).then(wait);
31 }
32 return Promise.race([
33 new Promise(function (_, rj) { return setTimeout(function () {
34 timedOut = true;
35 rj(new Error(options.present ? 'Element not found' : 'Element not removed'));
36 }, options.timeout); }),
37 wait()
38 ]);
39}
40export function waitForDocumentElement(selector, options) {
41 return waitFor(function () { return document.querySelector(selector); }, options);
42}
43export function waitForDocumentElements(selector, options) {
44 return waitFor(function () { return document.querySelectorAll(selector); }, options);
45}