@webkrafters/long-count
Version:
Long Count - intervals and timeout capable of handling superbly long wait times surviving device sleep and wake cycles.
235 lines (234 loc) • 14.2 kB
JavaScript
;
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.internal = exports.clearTimeout = exports.clearInterval = exports.LongCounter = exports.Interval = void 0;
exports.setInterval = setInterval;
exports.setTimeout = setTimeout;
var _$global = require("./$global");
var _index = _interopRequireDefault(require("./observable/index"));
var _index2 = _interopRequireDefault(require("./timer/index"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var counter = 0;
var longCounterMap = {};
var internal = exports.internal = {
current: Math.random(),
graceId: undefined,
gracePeriod: 1e4,
// 10 seconds
is: function is(envcode) {
return envcode && (envcode === this.current || envcode === this.previous);
},
previous: undefined,
ttl: 1.08e7,
// 3 hour cycle
unwatch: function unwatch() {
_$global.$global.clearTimeout(this.graceId);
_$global.$global.clearInterval(this.watchId);
this.graceId = this.watchId = undefined;
},
watch: function watch() {
var _this2 = this;
if (this.watchId) {
throw new TypeError('Cannot begin new watch at this time. An exisitng watch is currently underway. Use the `unwatch()` method to disable it in order to begin a new watch.');
}
var _this = this;
this.watchId = _$global.$global.setInterval(function () {
_this.previous = _this.current;
_this.current = Math.random();
_this.graceId = _$global.$global.setTimeout(function () {
_this.graceId = _this.previous = undefined;
}, _this2.gracePeriod);
}, this.ttl);
},
watchId: undefined
};
internal.watch();
var LongCounter = exports.LongCounter = /*#__PURE__*/function (_TimerObservable) {
function LongCounter(timer) {
var _this3;
_classCallCheck(this, LongCounter);
_this3 = _callSuper(this, LongCounter);
_this3._timer = timer;
_this3._id = ++counter;
longCounterMap[_this3._id] = _this3;
return _this3;
}
_inherits(LongCounter, _TimerObservable);
return _createClass(LongCounter, [{
key: "expired",
get: function get() {
return this._timer === undefined;
}
}, {
key: "id",
get: function get() {
return this._id;
}
}, {
key: "timeRemaining",
get: function get() {
var _this$_timer;
return (_this$_timer = this._timer) === null || _this$_timer === void 0 ? void 0 : _this$_timer.currentWaitTime;
}
}, {
key: "timer",
set: function set(timer) {
this._timer = timer;
}
}, {
key: "addEventListener",
value: function addEventListener(eventType, listener) {
this._timer && this._observers[eventType].add(listener) && this._timer.addEventListener(eventType, listener);
}
}, {
key: "cancel",
value: function cancel() {
delete longCounterMap[this.id];
if (!this._timer) {
return;
}
if (this._timer.disposed) {
this._timer = undefined;
return;
}
// preempts exit listeners
var _iterator = _createForOfIteratorHelper(this._observers.exit),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var listener = _step.value;
this._timer.removeEventListener('exit', listener);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
this._timer.exit();
this._timer = undefined;
}
}, {
key: "dispatchEvent",
value: function dispatchEvent(eventType) {
var _this$_timer2;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
(_this$_timer2 = this._timer) === null || _this$_timer2 === void 0 || _this$_timer2.dispatchEvent.apply(_this$_timer2, [eventType].concat(args));
}
}, {
key: "removeEventListener",
value: function removeEventListener(eventType, listener) {
this._timer && this._observers[eventType]["delete"](listener) && this._timer.removeEventListener(eventType, listener);
}
}, {
key: "valueOf",
value: function valueOf() {
return this.id;
}
}]);
}(_index["default"]);
var Interval = exports.Interval = /*#__PURE__*/function (_LongCounter) {
function Interval(timer) {
_classCallCheck(this, Interval);
return _callSuper(this, Interval, [timer]);
}
_inherits(Interval, _LongCounter);
return _createClass(Interval, [{
key: "updateTimer",
value: function updateTimer(timer, internalCode) {
if (!internal.is(internalCode)) {
throw new SyntaxError("Following operation cannot be completed using the following code: ".concat(internalCode, "."));
}
for (var _i = 0, _Object$entries = Object.entries(this._observers); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
eventType = _Object$entries$_i[0],
listeners = _Object$entries$_i[1];
var _iterator2 = _createForOfIteratorHelper(listeners),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var listener = _step2.value;
timer.addEventListener(eventType, listener);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
this.cancel();
this.timer = timer;
longCounterMap[this.id] = this;
}
}]);
}(LongCounter);
/** @param longCounter - LongCounter instance or LongCounter.id property value */
var endLongCount = function endLongCount(longCounter) {
var _ref;
return (_ref = typeof longCounter === 'number' ? longCounterMap[longCounter] : longCounter) === null || _ref === void 0 ? void 0 : _ref.cancel();
};
/** @param longCounter - LongCounter instance or LongCounter.id property value */
var clearInterval = exports.clearInterval = endLongCount;
/** @param longCounter - LongCounter instance or LongCounter.id property value */
var clearTimeout = exports.clearTimeout = endLongCount;
/** @param options - Options object or Options.immediate property value */
var resolveTimerOptions = function resolveTimerOptions(options) {
return typeof options === 'boolean' ? {
immediate: options
} : options;
};
/** @param options - Options object or Options.immediate property value */
function setInterval(fn) {
var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
for (var _len2 = arguments.length, args = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
args[_key2 - 3] = arguments[_key2];
}
var tOptions = resolveTimerOptions(options);
var interval = new Interval(_construct(_index2["default"], [fn, delay, tOptions].concat(args)));
interval.addEventListener('exit', function () {
return interval.updateTimer(_construct(_index2["default"], [fn, delay, _objectSpread(_objectSpread({}, tOptions), {}, {
immediate: false
})].concat(args)), internal.current);
});
return interval;
}
;
/** @param options - Options object or Options.immediate property value */
function setTimeout(fn) {
var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
for (var _len3 = arguments.length, args = new Array(_len3 > 3 ? _len3 - 3 : 0), _key3 = 3; _key3 < _len3; _key3++) {
args[_key3 - 3] = arguments[_key3];
}
var counter = new LongCounter(_construct(_index2["default"], [fn, delay, resolveTimerOptions(options)].concat(args)));
counter.addEventListener('exit', counter.cancel.bind(counter));
return counter;
}
;