UNPKG

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