UNPKG

@mcmhomes/panorama-viewer

Version:
1,536 lines (1,427 loc) 236 kB
import React, { memo as memo$1, useRef as useRef$1, useMemo as useMemo$1, useCallback as useCallback$1, useEffect as useEffect$1, useState as useState$1 } from 'react'; import { useThree, extend, Canvas } from '@react-three/fiber'; import { PerspectiveCamera } from '@react-three/drei'; import { MathUtils, CompressedCubeTexture, CubeTexture, MeshBasicMaterial, LinearSRGBColorSpace, UnsignedByteType, LinearFilter, TextureLoader, Mesh, SphereGeometry } from 'three'; import { KTX2Loader } from 'three-stdlib'; function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } 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 = true, o = false; 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 = true, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } 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 _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 _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 _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var kindOf; var hasRequiredKindOf; function requireKindOf () { if (hasRequiredKindOf) return kindOf; hasRequiredKindOf = 1; var toString = Object.prototype.toString; kindOf = function kindOf(val) { if (val === void 0) return 'undefined'; if (val === null) return 'null'; var type = typeof val; if (type === 'boolean') return 'boolean'; if (type === 'string') return 'string'; if (type === 'number') return 'number'; if (type === 'symbol') return 'symbol'; if (type === 'function') { return isGeneratorFn(val) ? 'generatorfunction' : 'function'; } if (isArray(val)) return 'array'; if (isBuffer(val)) return 'buffer'; if (isArguments(val)) return 'arguments'; if (isDate(val)) return 'date'; if (isError(val)) return 'error'; if (isRegexp(val)) return 'regexp'; switch (ctorName(val)) { case 'Symbol': return 'symbol'; case 'Promise': return 'promise'; // Set, Map, WeakSet, WeakMap case 'WeakMap': return 'weakmap'; case 'WeakSet': return 'weakset'; case 'Map': return 'map'; case 'Set': return 'set'; // 8-bit typed arrays case 'Int8Array': return 'int8array'; case 'Uint8Array': return 'uint8array'; case 'Uint8ClampedArray': return 'uint8clampedarray'; // 16-bit typed arrays case 'Int16Array': return 'int16array'; case 'Uint16Array': return 'uint16array'; // 32-bit typed arrays case 'Int32Array': return 'int32array'; case 'Uint32Array': return 'uint32array'; case 'Float32Array': return 'float32array'; case 'Float64Array': return 'float64array'; } if (isGeneratorObj(val)) { return 'generator'; } // Non-plain objects type = toString.call(val); switch (type) { case '[object Object]': return 'object'; // iterators case '[object Map Iterator]': return 'mapiterator'; case '[object Set Iterator]': return 'setiterator'; case '[object String Iterator]': return 'stringiterator'; case '[object Array Iterator]': return 'arrayiterator'; } // other return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); }; function ctorName(val) { return typeof val.constructor === 'function' ? val.constructor.name : null; } function isArray(val) { if (Array.isArray) return Array.isArray(val); return val instanceof Array; } function isError(val) { return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); } function isDate(val) { if (val instanceof Date) return true; return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function'; } function isRegexp(val) { if (val instanceof RegExp) return true; return typeof val.flags === 'string' && typeof val.ignoreCase === 'boolean' && typeof val.multiline === 'boolean' && typeof val.global === 'boolean'; } function isGeneratorFn(name, val) { return ctorName(name) === 'GeneratorFunction'; } function isGeneratorObj(val) { return typeof val.throw === 'function' && typeof val.return === 'function' && typeof val.next === 'function'; } function isArguments(val) { try { if (typeof val.length === 'number' && typeof val.callee === 'function') { return true; } } catch (err) { if (err.message.indexOf('callee') !== -1) { return true; } } return false; } /** * If you need to support Safari 5-7 (8-10 yr-old browser), * take a look at https://github.com/feross/is-buffer */ function isBuffer(val) { if (val.constructor && typeof val.constructor.isBuffer === 'function') { return val.constructor.isBuffer(val); } return false; } return kindOf; } /*! * shallow-clone <https://github.com/jonschlinkert/shallow-clone> * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ var shallowClone; var hasRequiredShallowClone; function requireShallowClone () { if (hasRequiredShallowClone) return shallowClone; hasRequiredShallowClone = 1; const valueOf = Symbol.prototype.valueOf; const typeOf = requireKindOf(); function clone(val, deep) { switch (typeOf(val)) { case 'array': return val.slice(); case 'object': return Object.assign({}, val); case 'date': return new val.constructor(Number(val)); case 'map': return new Map(val); case 'set': return new Set(val); case 'buffer': return cloneBuffer(val); case 'symbol': return cloneSymbol(val); case 'arraybuffer': return cloneArrayBuffer(val); case 'float32array': case 'float64array': case 'int16array': case 'int32array': case 'int8array': case 'uint16array': case 'uint32array': case 'uint8clampedarray': case 'uint8array': return cloneTypedArray(val); case 'regexp': return cloneRegExp(val); case 'error': return Object.create(val); default: { return val; } } } function cloneRegExp(val) { const flags = val.flags !== void 0 ? val.flags : (/\w+$/.exec(val) || void 0); const re = new val.constructor(val.source, flags); re.lastIndex = val.lastIndex; return re; } function cloneArrayBuffer(val) { const res = new val.constructor(val.byteLength); new Uint8Array(res).set(new Uint8Array(val)); return res; } function cloneTypedArray(val, deep) { return new val.constructor(val.buffer, val.byteOffset, val.length); } function cloneBuffer(val) { const len = val.length; const buf = Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : Buffer.from(len); val.copy(buf); return buf; } function cloneSymbol(val) { return valueOf ? Object(valueOf.call(val)) : {}; } /** * Expose `clone` */ shallowClone = clone; return shallowClone; } /*! * isobject <https://github.com/jonschlinkert/isobject> * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ var isobject; var hasRequiredIsobject; function requireIsobject () { if (hasRequiredIsobject) return isobject; hasRequiredIsobject = 1; isobject = function isObject(val) { return val != null && typeof val === 'object' && Array.isArray(val) === false; }; return isobject; } /*! * is-plain-object <https://github.com/jonschlinkert/is-plain-object> * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ var isPlainObject; var hasRequiredIsPlainObject; function requireIsPlainObject () { if (hasRequiredIsPlainObject) return isPlainObject; hasRequiredIsPlainObject = 1; var isObject = requireIsobject(); function isObjectObject(o) { return isObject(o) === true && Object.prototype.toString.call(o) === '[object Object]'; } isPlainObject = function isPlainObject(o) { var ctor,prot; if (isObjectObject(o) === false) return false; // If has modified constructor ctor = o.constructor; if (typeof ctor !== 'function') return false; // If has modified prototype prot = ctor.prototype; if (isObjectObject(prot) === false) return false; // If constructor does not have an Object-specific method if (prot.hasOwnProperty('isPrototypeOf') === false) { return false; } // Most likely a plain Object return true; }; return isPlainObject; } var cloneDeep_1; var hasRequiredCloneDeep; function requireCloneDeep () { if (hasRequiredCloneDeep) return cloneDeep_1; hasRequiredCloneDeep = 1; /** * Module dependenices */ const clone = requireShallowClone(); const typeOf = requireKindOf(); const isPlainObject = requireIsPlainObject(); function cloneDeep(val, instanceClone) { switch (typeOf(val)) { case 'object': return cloneObjectDeep(val, instanceClone); case 'array': return cloneArrayDeep(val, instanceClone); default: { return clone(val); } } } function cloneObjectDeep(val, instanceClone) { if (typeof instanceClone === 'function') { return instanceClone(val); } if (instanceClone || isPlainObject(val)) { const res = new val.constructor(); for (let key in val) { res[key] = cloneDeep(val[key], instanceClone); } return res; } return val; } function cloneArrayDeep(val, instanceClone) { const res = new val.constructor(val.length); for (let i = 0; i < val.length; i++) { res[i] = cloneDeep(val[i], instanceClone); } return res; } /** * Expose `cloneDeep` */ cloneDeep_1 = cloneDeep; return cloneDeep_1; } var cloneDeepExports = requireCloneDeep(); var clone = /*@__PURE__*/getDefaultExportFromCjs(cloneDeepExports); function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _typeof$1(o) { "@babel/helpers - typeof"; return _typeof$1 = "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$1(o); } function toPrimitive(t, r) { if ("object" != _typeof$1(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != _typeof$1(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function toPropertyKey(t) { var i = toPrimitive(t, "string"); return "symbol" == _typeof$1(i) ? i : i + ""; } function _defineProperty(e, r, t) { return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; } var regeneratorRuntime$1 = {exports: {}}; var _typeof = {exports: {}}; var hasRequired_typeof; function require_typeof () { if (hasRequired_typeof) return _typeof.exports; hasRequired_typeof = 1; (function (module) { function _typeof(o) { "@babel/helpers - typeof"; return module.exports = _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; }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o); } module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; } (_typeof)); return _typeof.exports; } var hasRequiredRegeneratorRuntime; function requireRegeneratorRuntime () { if (hasRequiredRegeneratorRuntime) return regeneratorRuntime$1.exports; hasRequiredRegeneratorRuntime = 1; (function (module) { var _typeof = require_typeof()["default"]; function _regeneratorRuntime() { module.exports = _regeneratorRuntime = function _regeneratorRuntime() { return r; }, module.exports.__esModule = true, module.exports["default"] = module.exports; var t, r = {}, e = Object.prototype, n = e.hasOwnProperty, o = "function" == typeof Symbol ? Symbol : {}, i = o.iterator || "@@iterator", a = o.asyncIterator || "@@asyncIterator", u = o.toStringTag || "@@toStringTag"; function c(t, r, e, n) { return Object.defineProperty(t, r, { value: e, enumerable: !n, configurable: !n, writable: !n }); } try { c({}, ""); } catch (t) { c = function c(t, r, e) { return t[r] = e; }; } function h(r, e, n, o) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype); return c(a, "_invoke", function (r, e, n) { var o = 1; return function (i, a) { if (3 === o) throw Error("Generator is already running"); if (4 === o) { if ("throw" === i) throw a; return { value: t, done: true }; } for (n.method = i, n.arg = a;;) { var u = n.delegate; if (u) { var c = d(u, n); if (c) { if (c === f) continue; return c; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (1 === o) throw o = 4, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = 3; var h = s(r, e, n); if ("normal" === h.type) { if (o = n.done ? 4 : 2, h.arg === f) continue; return { value: h.arg, done: n.done }; } "throw" === h.type && (o = 4, n.method = "throw", n.arg = h.arg); } }; }(r, n, new Context(o || [])), true), a; } function s(t, r, e) { try { return { type: "normal", arg: t.call(r, e) }; } catch (t) { return { type: "throw", arg: t }; } } r.wrap = h; var f = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var l = {}; c(l, i, function () { return this; }); var p = Object.getPrototypeOf, y = p && p(p(x([]))); y && y !== e && n.call(y, i) && (l = y); var v = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(l); function g(t) { ["next", "throw", "return"].forEach(function (r) { c(t, r, function (t) { return this._invoke(r, t); }); }); } function AsyncIterator(t, r) { function e(o, i, a, u) { var c = s(t[o], t, i); if ("throw" !== c.type) { var h = c.arg, f = h.value; return f && "object" == _typeof(f) && n.call(f, "__await") ? r.resolve(f.__await).then(function (t) { e("next", t, a, u); }, function (t) { e("throw", t, a, u); }) : r.resolve(f).then(function (t) { h.value = t, a(h); }, function (t) { return e("throw", t, a, u); }); } u(c.arg); } var o; c(this, "_invoke", function (t, n) { function i() { return new r(function (r, o) { e(t, n, r, o); }); } return o = o ? o.then(i, i) : i(); }, true); } function d(r, e) { var n = e.method, o = r.i[n]; if (o === t) return e.delegate = null, "throw" === n && r.i["return"] && (e.method = "return", e.arg = t, d(r, e), "throw" === e.method) || "return" !== n && (e.method = "throw", e.arg = new TypeError("The iterator does not provide a '" + n + "' method")), f; var i = s(o, r.i, e.arg); if ("throw" === i.type) return e.method = "throw", e.arg = i.arg, e.delegate = null, f; var a = i.arg; return a ? a.done ? (e[r.r] = a.value, e.next = r.n, "return" !== e.method && (e.method = "next", e.arg = t), e.delegate = null, f) : a : (e.method = "throw", e.arg = new TypeError("iterator result is not an object"), e.delegate = null, f); } function w(t) { this.tryEntries.push(t); } function m(r) { var e = r[4] || {}; e.type = "normal", e.arg = t, r[4] = e; } function Context(t) { this.tryEntries = [[-1]], t.forEach(w, this), this.reset(true); } function x(r) { if (null != r) { var e = r[i]; if (e) return e.call(r); if ("function" == typeof r.next) return r; if (!isNaN(r.length)) { var o = -1, a = function e() { for (; ++o < r.length;) if (n.call(r, o)) return e.value = r[o], e.done = false, e; return e.value = t, e.done = true, e; }; return a.next = a; } } throw new TypeError(_typeof(r) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, c(v, "constructor", GeneratorFunctionPrototype), c(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = c(GeneratorFunctionPrototype, u, "GeneratorFunction"), r.isGeneratorFunction = function (t) { var r = "function" == typeof t && t.constructor; return !!r && (r === GeneratorFunction || "GeneratorFunction" === (r.displayName || r.name)); }, r.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, c(t, u, "GeneratorFunction")), t.prototype = Object.create(v), t; }, r.awrap = function (t) { return { __await: t }; }, g(AsyncIterator.prototype), c(AsyncIterator.prototype, a, function () { return this; }), r.AsyncIterator = AsyncIterator, r.async = function (t, e, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(h(t, e, n, o), i); return r.isGeneratorFunction(e) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, g(v), c(v, u, "Generator"), c(v, i, function () { return this; }), c(v, "toString", function () { return "[object Generator]"; }), r.keys = function (t) { var r = Object(t), e = []; for (var n in r) e.unshift(n); return function t() { for (; e.length;) if ((n = e.pop()) in r) return t.value = n, t.done = false, t; return t.done = true, t; }; }, r.values = x, Context.prototype = { constructor: Context, reset: function reset(r) { if (this.prev = this.next = 0, this.sent = this._sent = t, this.done = false, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(m), !r) for (var e in this) "t" === e.charAt(0) && n.call(this, e) && !isNaN(+e.slice(1)) && (this[e] = t); }, stop: function stop() { this.done = true; var t = this.tryEntries[0][4]; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(r) { if (this.done) throw r; var e = this; function n(t) { a.type = "throw", a.arg = r, e.next = t; } for (var o = e.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i[4], u = this.prev, c = i[1], h = i[2]; if (-1 === i[0]) return n("end"), false; if (!c && !h) throw Error("try statement without catch or finally"); if (null != i[0] && i[0] <= u) { if (u < c) return this.method = "next", this.arg = t, n(c), true; if (u < h) return n(h), false; } } }, abrupt: function abrupt(t, r) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var n = this.tryEntries[e]; if (n[0] > -1 && n[0] <= this.prev && this.prev < n[2]) { var o = n; break; } } o && ("break" === t || "continue" === t) && o[0] <= r && r <= o[2] && (o = null); var i = o ? o[4] : {}; return i.type = t, i.arg = r, o ? (this.method = "next", this.next = o[2], f) : this.complete(i); }, complete: function complete(t, r) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && r && (this.next = r), f; }, finish: function finish(t) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var e = this.tryEntries[r]; if (e[2] === t) return this.complete(e[4], e[3]), m(e), f; } }, "catch": function _catch(t) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var e = this.tryEntries[r]; if (e[0] === t) { var n = e[4]; if ("throw" === n.type) { var o = n.arg; m(e); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(r, e, n) { return this.delegate = { i: x(r), r: e, n: n }, "next" === this.method && (this.arg = t), f; } }, r; } module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; } (regeneratorRuntime$1)); return regeneratorRuntime$1.exports; } var regenerator; var hasRequiredRegenerator; function requireRegenerator () { if (hasRequiredRegenerator) return regenerator; hasRequiredRegenerator = 1; // TODO(Babel 8): Remove this file. var runtime = requireRegeneratorRuntime()(); regenerator = runtime; // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { if (typeof globalThis === "object") { globalThis.regeneratorRuntime = runtime; } else { Function("r", "regeneratorRuntime = r")(runtime); } } return regenerator; } var regeneratorExports = requireRegenerator(); var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regeneratorExports); function ownKeys$4(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$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } /** * Returns true if the value is set (not undefined and not null). * * @param {*} value * @returns {boolean} */ var ISSET = function ISSET(value) { return typeof value !== 'undefined' && value !== null; }; /** * Returns true if the value is an array. * * @param {*} value * @returns {boolean} */ var IS_ARRAY = function IS_ARRAY(value) { return Array.isArray(value); }; /** * Ensures the given value is an array (returns the value wrapped in an array if it's not). * * @param {*} value * @returns {*[]} */ var ARRAY = function ARRAY(value) { return IS_ARRAY(value) ? value : typeof value !== 'undefined' ? [value] : []; }; /** * Returns true if the value is an object. * * @param {*} value * @returns {boolean} */ var IS_OBJECT = function IS_OBJECT(value) { return _typeof$1(value) === 'object' && value !== null && !Array.isArray(value); }; /** * Ensures the given value is an object (returns an empty object if it's not). * * @param value * @returns {object} */ var OBJECT = function OBJECT(value) { return IS_OBJECT(value) ? value : {}; }; /** * Ensures the given value is a string (casts it to a string if it's not, null and undefined will return an empty string). * * @param {*} value * @returns {string} */ var STRING = function STRING(value) { return ISSET(value) ? '' + value : ''; }; /** * Ensures the given value is an integer (attempts to cast it to an integer if it's not, null and undefined will return 0). * This version is less strict than INT, as it relies on parseFloat instead of on +value, meaning that it will accept strings that contain a number followed by other characters, which +value doesn't. * * @param {*} value * @returns {number} */ var INT_LAX = function INT_LAX(value) { return Math.round(FLOAT_LAX(value)); }; /** * Returns the first non-null non-undefined int-castable value as an integer. * This version is less strict than INT_ANY, as it relies on parseFloat instead of on +value, meaning that it will accept strings that contain a number followed by other characters, which +value doesn't. * * @param {*} values * @returns {number} */ var INT_LAX_ANY = function INT_LAX_ANY() { return Math.round(FLOAT_LAX_ANY.apply(void 0, arguments)); }; var REGEX_ALL_NON_FLOAT_CHARACTERS = /[^0-9.\-]/g; /** * Ensures the given value is a float (attempts to cast it to a float if it's not, null and undefined will return 0). * This version is less strict than FLOAT, as it relies on parseFloat instead of on +value, meaning that it will accept strings that contain a number followed by other characters, which +value doesn't. * * @param {*} value * @returns {number} */ var FLOAT_LAX = function FLOAT_LAX(value) { var v = typeof value === 'number' ? value : parseFloat((value + '').replace(REGEX_ALL_NON_FLOAT_CHARACTERS, '')); if (!isNaN(v)) { return v; } return 0; }; /** * Returns the first non-null non-undefined float-castable value as a float. * This version is less strict than FLOAT_ANY, as it relies on parseFloat instead of on +value, meaning that it will accept strings that contain a number followed by other characters, which +value doesn't. * * @param {*} values * @returns {number} */ var FLOAT_LAX_ANY = function FLOAT_LAX_ANY() { for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { values[_key3] = arguments[_key3]; } for (var _i3 = 0, _values3 = values; _i3 < _values3.length; _i3++) { var value = _values3[_i3]; if (value !== null) { var v = typeof value === 'number' ? value : parseFloat((value + '').replace(REGEX_ALL_NON_FLOAT_CHARACTERS, '')); if (!isNaN(v)) { return v; } } } return 0; }; /** * Loops through each element in the given array or object, and calls the callback for each element. * * @param {*[]|object|Function} elements * @param {Function} callback * @param {boolean} [optionalSkipHasOwnPropertyCheck] * @returns {*[]|object|Function} */ var each = function each(elements, callback) { var optionalSkipHasOwnPropertyCheck = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (elements !== null && typeof elements !== 'undefined') { if (Array.isArray(elements)) { for (var index = 0; index < elements.length; index++) { if (callback.call(elements[index], elements[index], index) === false) { break; } } } else if (_typeof$1(elements) === 'object' || typeof elements === 'function') { for (var _index in elements) { if (optionalSkipHasOwnPropertyCheck === true || Object.prototype.hasOwnProperty.call(elements, _index)) { if (callback.call(elements[_index], elements[_index], _index) === false) { break; } } } } else { console.warn('Executed each() on an invalid type: [' + _typeof$1(elements) + ']', elements); } } return elements; }; /** * Returns true if the array or object contains the given value. * * Values are compared by casting both of them to a string. * * @param {array|object|Function} array * @param {*} value * @returns {boolean} */ var contains = function contains(array, value) { if (!array) { return false; } var result = false; value = STRING(value); each(array, function (val) { if (STRING(val) === value) { result = true; return false; } }); return result; }; /** * @callback __filterCallback * @param {*} value * @param {*} index * @returns {boolean|undefined} */ /** * Loops through the given elements, and returns a new array or object, with only the elements that returned true (or a value equals to true) from the callback. * If no callback is given, it will return all elements that are of a true value (for example, values that are: not null, not undefined, not false, not 0, not an empty string, not an empty array, not an empty object). * * @param {*[]|object|Function} elements * @param {__filterCallback} [callback] * @param {boolean} [optionalSkipHasOwnPropertyCheck] * @returns {*[]|object|Function} */ var filter = function filter(elements, callback) { var optionalSkipHasOwnPropertyCheck = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (elements !== null && typeof elements !== 'undefined') { if (Array.isArray(elements)) { var result = []; for (var index = 0; index < elements.length; index++) { if (!callback && elements[index] || callback && callback.call(elements[index], elements[index], index)) { result.push(elements[index]); } } return result; } else if (_typeof$1(elements) === 'object' || typeof elements === 'function') { var _result = {}; for (var _index2 in elements) { if (optionalSkipHasOwnPropertyCheck === true || Object.prototype.hasOwnProperty.call(elements, _index2)) { if (!callback && elements[_index2] || callback && callback.call(elements[_index2], elements[_index2], _index2)) { _result[_index2] = elements[_index2]; } } } return _result; } else { console.warn('Executed filter() on an invalid type: [' + _typeof$1(elements) + ']', elements); } } return elements; }; /** * Generates a base64 string (with +/ replaced by -_) that is guaranteed to be unique. * * @returns {string} */ var uniqueId = function () { var previousUniqueIdsTime = null; var previousUniqueIds = {}; var safeAtob = function safeAtob(base64string) { if (typeof atob === 'function') { return atob(base64string); } return window.Buffer.from(base64string, 'base64').toString(); }; var safeBtoa = function safeBtoa(string) { if (typeof btoa === 'function') { return btoa(string); } return window.Buffer.from(string).toString('base64'); }; var numberToBytes = function numberToBytes(number) { var size = number === 0 ? 0 : Math.ceil((Math.floor(Math.log2(number)) + 1) / 8); var bytes = new Uint8ClampedArray(size); var x = number; for (var i = size - 1; i >= 0; i--) { var rightByte = x & 0xff; bytes[i] = rightByte; x = Math.floor(x / 0x100); } return bytes; }; var base64ToBytes = function base64ToBytes(base64string) { var binary = safeAtob(base64string.trim()); var len = binary.length; var data = new Uint8Array(len); for (var i = 0; i < len; i++) { data[i] = binary.charCodeAt(i); } return data; }; var hexToBase64 = function hexToBase64(hexstring) { return safeBtoa(hexstring.replace(/[^0-9A-F]/gi, '').match(/\w{2}/g).map(function (a) { return String.fromCharCode(parseInt(a, 16)); }).join('')); }; var bytesToBase64 = function bytesToBase64(arraybuffer) { var bytes = new Uint8Array(arraybuffer); var len = bytes.byteLength; var binary = ''; for (var i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]); } return safeBtoa(binary); }; var generateUniqueId = function generateUniqueId() { var now; try { if (typeof window === 'undefined') { throw new Error(); } // noinspection JSDeprecatedSymbols now = (performance.timeOrigin || performance.timing.navigationStart) + performance.now(); if (typeof now !== 'number') { throw new Error(); } } catch (e) { now = Date.now ? Date.now() : new Date().getTime(); } now = Math.round(now); if (typeof window === 'undefined') { var _uuid = null; try { var _crypto; _uuid = (_crypto = crypto) === null || _crypto === void 0 ? void 0 : _crypto.randomUUID(); } catch (e) { _uuid = ''; _uuid += (Math.random() + ' ').substring(2, 12).padEnd(10, '0'); _uuid += (Math.random() + ' ').substring(2, 12).padEnd(10, '0'); _uuid += (Math.random() + ' ').substring(2, 12).padEnd(10, '0'); _uuid += (Math.random() + ' ').substring(2, 12).padEnd(10, '0'); } return { time: now, id: ('' + now + _uuid).replaceAll('=', '').replaceAll('+', '-').replaceAll('/', '_') }; } var nowBytes = numberToBytes(now); var uuid = null; try { var _crypto2; uuid = (_crypto2 = crypto) === null || _crypto2 === void 0 ? void 0 : _crypto2.randomUUID(); } catch (e) {} if (uuid) { uuid = base64ToBytes(hexToBase64(uuid)); } else { var bytesChunkA = numberToBytes((Math.random() + ' ').substring(2, 12).padEnd(10, '0')); var bytesChunkB = numberToBytes((Math.random() + ' ').substring(2, 12).padEnd(10, '0')); var bytesChunkC = numberToBytes((Math.random() + ' ').substring(2, 12).padEnd(10, '0')); var bytesChunkD = numberToBytes((Math.random() + ' ').substring(2, 12).padEnd(10, '0')); uuid = new Uint8Array(bytesChunkA.length + bytesChunkB.length + bytesChunkC.length + bytesChunkD.length); uuid.set(bytesChunkA, 0); uuid.set(bytesChunkB, bytesChunkA.length); uuid.set(bytesChunkC, bytesChunkA.length + bytesChunkB.length); uuid.set(bytesChunkD, bytesChunkA.length + bytesChunkB.length + bytesChunkC.length); } var bytes = new Uint8Array(nowBytes.length + uuid.length); bytes.set(nowBytes, 0); bytes.set(uuid, nowBytes.length); uuid = bytesToBase64(bytes).replaceAll('=', '').replaceAll('+', '-').replaceAll('/', '_'); return { time: now, id: uuid }; }; return function () { while (true) { var result = generateUniqueId(); if (previousUniqueIdsTime !== result.time) { previousUniqueIdsTime = result.time; previousUniqueIds = _defineProperty({}, result.id, true); return result.id; } else if (previousUniqueIds[result.id] !== true) { previousUniqueIds[result.id] = true; return result.id; } } }; }(); /** * @callback __setTimeoutCallback * @param {number} deltaTime */ /** * Executes the callback after the given number of milliseconds. Passes the elapsed time in seconds to the callback. * * To cancel the timeout, call remove() on the result of this function (example: "const timeoutHandler = setTimeout((deltaTime)=>{}, 1000); timeoutHandler.remove();") * * @param {__setTimeoutCallback} callback ([number] deltaTime) * @param {number} ms * @returns {{remove:Function}} */ var setTimeoutRemovable = function setTimeoutRemovable(callback, ms) { if (typeof window === 'undefined') { return { remove: function remove() {} }; } ms = FLOAT_LAX(ms); var lastTime = performance.now(); /** @type {number|null} */ var handler = window.setTimeout(function () { var currentTime = performance.now(); try { callback((currentTime - lastTime) / 1000); } catch (e) { console.error(e); } lastTime = currentTime; }, ms); return { remove: function remove() { if (handler !== null) { window.clearTimeout(handler); handler = null; } } }; }; /** * @callback __setAnimationFrameTimeoutCallback * @param {number} deltaTime */ /** * Executes the callback after the given number of frames. Passes the elapsed time in seconds to the callback. * * To cancel the timeout, call remove() on the result of this function (example: "const timeoutHandler = setAnimationFrameTimeout((deltaTime){}, 5); timeoutHandler.remove();") * * @param {__setAnimationFrameTimeoutCallback} callback ([number] deltaTime) * @param {number} [frames] * @returns {{remove:Function}} */ var setAnimationFrameTimeoutRemovable = function setAnimationFrameTimeoutRemovable(callback) { var frames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; if (typeof window === 'undefined') { return { remove: function remove() {} }; } frames = INT_LAX_ANY(frames, 1); var run = true; var requestAnimationFrameId = null; var lastTime = performance.now(); var _tick = function tick() { if (run) { if (frames <= 0) { run = false; requestAnimationFrameId = null; var currentTime = performance.now(); try { callback((currentTime - lastTime) / 1000); } catch (e) { console.error(e); } lastTime = currentTime; return; } frames--; requestAnimationFrameId = window.requestAnimationFrame(_tick); } }; _tick(); return { remove: function remove() { run = false; if (requestAnimationFrameId !== null) { window.cancelAnimationFrame(requestAnimationFrameId); requestAnimationFrameId = null; } } }; }; /** * @callback __setAnimationFrameIntervalCallback * @param {number} deltaTime */ /** * Executes the callback every given number of frames. Passes the time difference in seconds between the last frame and now to it. * * To remove the interval, call remove() on the result of this function (example: "const intervalHandler = setAnimationFrameInterval((deltaTime)=>{}, 5); intervalHandler.remove();") * * @param {__setAnimationFrameIntervalCallback} callback ([number] deltaTime) * @param {number} [intervalFrames] * @param {boolean} [fireImmediately] * @returns {{remove:Function}} */ var setAnimationFrameIntervalRemovable = function setAnimationFrameIntervalRemovable(callback) { var intervalFrames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var fireImmediately = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; intervalFrames = INT_LAX_ANY(intervalFrames, 1); if (fireImmediately) { try { callback(0); } catch (e) { console.error(e); } } if (typeof window === 'undefined') { return { remove: function remove() {} }; } var run = true; var requestAnimationFrameId = null; var lastTime = performance.now(); var frames = intervalFrames; var _tick2 = function tick() { if (run) { if (frames <= 0) { var currentTime = performance.now(); try { callback((currentTime - lastTime) / 1000); } catch (e) { console.error(e); } lastTime = currentTime; frames = intervalFrames; } frames--; if (run) { requestAnimationFrameId = window.requestAnimationFrame(_tick2); } } }; window.requestAnimationFrame(_tick2); return { remove: function remove() { run = false; if (requestAnimationFrameId !== null) { window.cancelAnimationFrame(requestAnimationFrameId); requestAnimationFrameId = null; } } }; }; /** * Returns a promise, which will be resolved after the given number of milliseconds. * * @param {number} ms * @returns {Promise} */ var promiseTimeout = function promiseTimeout(ms) { ms = FLOAT_LAX(ms); if (ms <= 0) { return new Promise(function (resolve) { return resolve(undefined); }); } return new Promise(function (resolve) { return setTimeoutRemovable(resolve, ms); }); }; /** * Allows you to do a fetch, with built-in retry and abort functionality. * * @param {string} url * @param {Object} [options] * @returns {{then:Function, catch:Function, finally:Function, remove:Function, isRemoved:Function}|Promise<Response|any>} */ var retryingFetch = function retryingFetch(url, options) { var currentRetries = 0; var retries = INT_LAX(options === null || options === void 0 ? void 0 : options.retries); var controllerAborted = false; var controller = null; if (typeof window !== 'undefined' && typeof window.AbortController !== 'undefined') { controller = new AbortController(); } var promise = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { var _attemptFetch; return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _attemptFetch = /*#__PURE__*/function () { var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() { var _controller; var _controller2, response, _controller3; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (!(controllerAborted || (_controller = controller) !== null && _controller !== void 0 && (_controller = _controller.signal) !== null && _controller !== void 0 && _controller.aborted)) { _context.next = 2; break; } throw new Error('Aborted'); case 2: _context.prev = 2; _context.next = 5; return fetch(url, _objectSpread$4(_objectSpread$4({ signal: (_controller2 = controller) === null || _controller2 === void 0 ? void 0 : _controller2.signal }, options !== null && options !== void 0 ? options : {}), {}, { retries: undefined, delay: undefined })); case 5: response = _context.sent; if (response.ok) { _context.next = 8; break; } throw new Error('Network request failed: ' + response.status + ' ' + response.statusText); case 8: return _context.abrupt("return", response); case 11: _context.prev = 11; _context.t0 = _context["catch"](2); if (!(controllerAborted || (_controller3 = controller) !== null && _controller3 !== void 0 && (_controller3 = _controller3.signal) !== null && _controller3 !== void 0 && _controller3.aborted)) { _context.next = 15; break; } throw new Error('Aborted'); case 15: if (!(currentRetries >= retries)) { _context.next = 17; break; } throw _context.t0; case 17: currentRetries++; _context.next = 20; return promiseTimeout(typeof (options === null || options === void 0 ? void 0 : options.delay) === 'function' ? INT_LAX_ANY(options === null || options === void 0 ? void 0 : options.delay(currentRetries), 500) : INT_LAX_ANY(options === null || options === void 0 ? void 0 : options.delay, 500)); case 20: _context.next = 22; return _attemptFetch(); case 22: return _context.abrupt("return", _context.sent); case 23: case "end": return _context.stop(); } }, _callee, null, [[2, 11]]); })); return function attemptFetch() { return _ref2.apply(this, arguments); }; }(); _context2.next = 3; return _attemptFetch(); case 3: return _context2.abrupt("return", _context2.sent); case 4: case "end": return _context2.stop(); } }, _callee2); }))(); var result = {}; result.then = function () { var _promise; promise = (_promise = promise).then.apply(_promise, arguments); return result; }; result["catch"] = function () { var _promise2; promise = (_promise2 = promise)["catch"].apply(_promise2, arguments); return result; }; result["finally"] = function () { var _promise3; promise = (_promise3 = promise)["finally"].apply(_promise3, arguments); return result; }; result.remove = function () { controllerAborted = true; if (controller) { var _controller4; (_controller4 = controller).abort.apply(_controller4, arguments); } return result; }; result.isRemoved = function () { var _controller5; return controllerAborted || !!((_controller5 = controller) !== null && _controller5 !== void 0 && (_controller5 = _controller5.signal) !== null && _controller5 !== void 0 && _controller5.aborted); }; return result; }; /** * @callback __mapToArrayCallback * @param {*} value * @param {*} index * @returns {*} */ /** * Loops through the given elements, and returns a new array, with the elements that were returned from the callback. Always returns an array. * * @param {*[]|object|Function} elements * @param {__mapToArrayCallback} [callback] * @param {boolean} [optionalSkipHasOwnPropertyCheck] * @returns {*[]} */ var mapToArray = function mapToArray(elements, callback) { var optionalSkipHasOwnPropertyCheck = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var result = []; if (elements !== null && typeof elements !== 'undefined') { if (Array.isArray(elements)) { for (var index = 0; index < elements.length; index++) { if (!callback) { result.push(elements[index]); } else { result.push(callback.call(elements[index], elements[index], index)); } } } else if (_typeof$1(elements) === 'object' || typeof elements === 'function') { for (var _index3 in elements) { if (optionalSkipHasOwnPropertyCheck === true || Object.prototype.hasOwnProperty.call(elements, _index3)) { if (!callback) { result.push(elements[_index3]); } else { result.push(callback.call(elements[_index3], elements[_index3], _index3)); } } } } else { console.warn('Executed mapToArray() on an invalid type: [' + _typeof$1(elements) + ']', elements); } }