UNPKG

raf-stub

Version:

Accurate and predictable testing of requestAnimationFrame and cancelAnimationFrame

135 lines (108 loc) 3.06 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.rafStub = {})); }(this, function (exports) { 'use strict'; var defaultFrameDuration = 1000 / 60; var now = (function () { if (performance) { return performance.now(); } return Date.now(); }); function createStub(frameDuration, startTime) { if (frameDuration === void 0) { frameDuration = defaultFrameDuration; } if (startTime === void 0) { startTime = now(); } var frames = []; var frameId = 0; var currentTime = startTime; var add = function add(cb) { var id = ++frameId; var callback = function callback(time) { cb(time); remove(id); }; frames.push({ id: id, callback: callback }); return id; }; var remove = function remove(id) { var index = frames.findIndex(function (frame) { return frame.id === id; }); if (index === -1) { return; } frames.splice(index, 1); }; var flush = function flush(duration) { if (duration === void 0) { duration = frameDuration; } while (frames.length) { step(1, duration); } }; var reset = function reset() { frames.length = 0; currentTime = startTime; }; var step = function step(steps, duration) { if (steps === void 0) { steps = 1; } if (duration === void 0) { duration = frameDuration; } if (steps === 0) { return; } currentTime = currentTime + duration; var shallow = frames.slice(0); shallow.forEach(function (frame) { frame.callback(currentTime); }); return step(steps - 1, duration); }; var api = { add: add, remove: remove, reset: reset, flush: flush, step: step }; return api; } function replaceRaf(roots, _temp) { if (roots === void 0) { roots = []; } var _ref = _temp === void 0 ? {} : _temp, _ref$frameDuration = _ref.frameDuration, frameDuration = _ref$frameDuration === void 0 ? defaultFrameDuration : _ref$frameDuration, _ref$startTime = _ref.startTime, startTime = _ref$startTime === void 0 ? now() : _ref$startTime; if (!roots.length) { roots.push(typeof window !== 'undefined' ? window : global); } var stub = createStub(frameDuration, startTime); roots.forEach(function (root) { root.requestAnimationFrame = stub.add; Object.assign(root.requestAnimationFrame, { step: stub.step, flush: stub.flush, reset: stub.reset }); root.cancelAnimationFrame = stub.remove; }); } exports.default = createStub; exports.replaceRaf = replaceRaf; Object.defineProperty(exports, '__esModule', { value: true }); }));