1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 var EXPORTED_SYMBOLS = [
8 "AnimationFramePromise",
14 var { XPCOMUtils } = ChromeUtils.import(
15 "resource://gre/modules/XPCOMUtils.jsm"
18 XPCOMUtils.defineLazyModuleGetters(this, {
19 Services: "resource://gre/modules/Services.jsm",
22 const { TYPE_REPEATING_SLACK } = Ci.nsITimer;
25 * Wait for a single event to be fired on a specific EventListener.
27 * The returned promise is guaranteed to not be called before the
28 * next event tick after the event listener is called, so that all
29 * other event listeners for the element are executed before the
30 * handler is executed. For example:
32 * const promise = new EventPromise(element, "myEvent");
33 * // same event tick here
35 * // next event tick here
37 * @param {EventListener} listener
38 * Object which receives a notification (an object that implements
39 * the Event interface) when an event of the specificed type occurs.
40 * @param {string} type
41 * Case-sensitive string representing the event type to listen for.
42 * @param {boolean?} [false] options.capture
43 * Indicates the event will be despatched to this subject,
44 * before it bubbles down to any EventTarget beneath it in the
46 * @param {boolean?} [false] options.wantsUntrusted
47 * Receive synthetic events despatched by web content.
48 * @param {boolean?} [false] options.mozSystemGroup
49 * Determines whether to add listener to the system group.
51 * @return {Promise.<Event>}
55 function EventPromise(
60 wantsUntrusted: false,
61 mozSystemGroup: false,
64 if (!listener || !("addEventListener" in listener)) {
65 throw new TypeError();
67 if (typeof type != "string") {
68 throw new TypeError();
71 ("capture" in options && typeof options.capture != "boolean") ||
72 ("wantsUntrusted" in options &&
73 typeof options.wantsUntrusted != "boolean") ||
74 ("mozSystemGroup" in options && typeof options.mozSystemGroup != "boolean")
76 throw new TypeError();
81 return new Promise(resolve => {
82 listener.addEventListener(
85 executeSoon(() => resolve(event));
93 * Wait for the next tick in the event loop to execute a callback.
95 * @param {function} fn
96 * Function to be executed.
98 function executeSoon(fn) {
99 if (typeof fn != "function") {
100 throw new TypeError();
103 Services.tm.dispatchToMainThread(fn);
107 * Throttle until the `window` has performed an animation frame.
109 * @param {ChromeWindow} win
110 * Window to request the animation frame from.
114 function AnimationFramePromise(win) {
115 const animationFramePromise = new Promise(resolve => {
116 win.requestAnimationFrame(resolve);
119 // Abort if the underlying window gets closed
120 const windowClosedPromise = new PollPromise(resolve => {
126 return Promise.race([animationFramePromise, windowClosedPromise]);
130 * Runs a Promise-like function off the main thread until it is resolved
131 * through ``resolve`` or ``rejected`` callbacks. The function is
132 * guaranteed to be run at least once, irregardless of the timeout.
134 * The ``func`` is evaluated every ``interval`` for as long as its
135 * runtime duration does not exceed ``interval``. Evaluations occur
136 * sequentially, meaning that evaluations of ``func`` are queued if
137 * the runtime evaluation duration of ``func`` is greater than ``interval``.
139 * ``func`` is given two arguments, ``resolve`` and ``reject``,
140 * of which one must be called for the evaluation to complete.
141 * Calling ``resolve`` with an argument indicates that the expected
142 * wait condition was met and will return the passed value to the
143 * caller. Conversely, calling ``reject`` will evaluate ``func``
144 * again until the ``timeout`` duration has elapsed or ``func`` throws.
145 * The passed value to ``reject`` will also be returned to the caller
146 * once the wait has expired.
150 * let els = new PollPromise((resolve, reject) => {
151 * let res = document.querySelectorAll("p");
152 * if (res.length > 0) {
153 * resolve(Array.from(res));
157 * }, {timeout: 1000});
159 * @param {Condition} func
160 * Function to run off the main thread.
161 * @param {number=} [timeout] timeout
162 * Desired timeout if wanted. If 0 or less than the runtime evaluation
163 * time of ``func``, ``func`` is guaranteed to run at least once.
164 * Defaults to using no timeout.
165 * @param {number=} [interval=10] interval
166 * Duration between each poll of ``func`` in milliseconds.
167 * Defaults to 10 milliseconds.
169 * @return {Promise.<*>}
170 * Yields the value passed to ``func``'s
171 * ``resolve`` or ``reject`` callbacks.
174 * If ``func`` throws, its error is propagated.
175 * @throws {TypeError}
176 * If `timeout` or `interval`` are not numbers.
177 * @throws {RangeError}
178 * If `timeout` or `interval` are not unsigned integers.
180 function PollPromise(func, { timeout = null, interval = 10 } = {}) {
181 const timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
183 if (typeof func != "function") {
184 throw new TypeError();
186 if (timeout != null && typeof timeout != "number") {
187 throw new TypeError();
189 if (typeof interval != "number") {
190 throw new TypeError();
193 (timeout && (!Number.isInteger(timeout) || timeout < 0)) ||
194 !Number.isInteger(interval) ||
197 throw new RangeError();
200 return new Promise((resolve, reject) => {
203 if (Number.isInteger(timeout)) {
204 start = new Date().getTime();
205 end = start + timeout;
210 .then(resolve, rejected => {
211 if (typeof rejected != "undefined") {
215 // return if there is a timeout and set to 0,
216 // allowing |func| to be evaluated at least once
218 typeof end != "undefined" &&
219 (start == end || new Date().getTime() >= end)
227 // the repeating slack timer waits |interval|
228 // before invoking |evalFn|
231 timer.init(evalFn, interval, TYPE_REPEATING_SLACK);