bbo
Version:
bbo is a utility library of zero dependencies for javascript.
1,971 lines (1,580 loc) • 78 kB
JavaScript
/*
* bbo
* bbo is a utility library of zero dependencies for javascript.
* (c) 2011 - 2021
* https://github.com/tnfe/bbo.git
* version 1.1.26
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.bbo = factory());
}(this, (function () { 'use strict';
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toArray(arr) {
return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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 getTag(src) {
return Object.prototype.toString.call(src);
}
function isString(str) {
return getTag(str) === '[object String]';
}
function isFunction(func) {
return getTag(func) === '[object Function]';
}
var version = '1.1.26';
var globalObject = null;
function getGlobalObject() {
if (globalObject !== null) {
return globalObject;
}
/* istanbul ignore next */
// It's hard to mock the global variables. This code surely works fine. I hope :)
if (typeof global === 'object' && global.Object === Object) {
// NodeJS global object
globalObject = global;
} else if (typeof self === 'object' && self.Object === Object) {
// self property from Window object
globalObject = self;
} else {
// Other cases. Function constructor always has the context as global object
// eslint-disable-next-line no-new-func
globalObject = new Function('return this')();
}
return globalObject;
}
/* eslint-disable no-invalid-this */
var globalObject$1 = getGlobalObject();
var previous = globalObject$1.bbo;
function noConflict() {
if (this === globalObject$1.bbo) {
globalObject$1.bbo = previous;
}
return this;
}
function ua(lower) {
return lower ? window.navigator.userAgent.toLowerCase() : window.navigator.userAgent;
}
/**
* detect IOS
* From https://stackoverflow.com/questions/9038625/detect-if-device-is-ios
* more see:
* https://github.com/madrobby/zepto/blob/master/src/detect.js#files
*/
function isIOS() {
return /iPad|iPhone|iPod/.test(ua());
}
function iPhone() {
return /iPhone/.test(ua());
}
function isIPad() {
return /iPad/.test(ua());
}
/**
* detect Android
* From https://stackoverflow.com/questions/6031412/detect-android-phone-via-javascript-jquery
*/
function isAndroid() {
return ua('l').indexOf('android') > -1;
}
/**
* detect PC / Mobile
* From https://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device-in-jquery
*/
function isMobile() {
return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ua('l'));
}
/**
* detect PC / Mobile
* From https://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device-in-jquery
*/
function isPC() {
return !isMobile();
}
function isWeixin() {
return /MicroMessenger/i.test(ua('l')); // 微信
}
function isNewsApp() {
return /qqnews/.test(ua()); // 腾讯新闻app
}
function isQQ() {
return /qq\//.test(ua('l')); // 手机QQ
}
function isQQbrowser() {
return /mqqbrowser\//.test(ua('l')); // QQ浏览器
}
function isTenvideo() {
return /qqlivebrowser/.test(ua('l')); // 腾讯视频
}
function isWeiShi() {
return /weishi/.test(ua('l')); // 腾讯微视
}
function isIphoneXmodel() {
// X XS, XS Max, XR
var xSeriesConfig = [{
devicePixelRatio: 3,
width: 375,
height: 812
}, {
devicePixelRatio: 3,
width: 414,
height: 896
}, {
devicePixelRatio: 2,
width: 414,
height: 896
}];
if (typeof window !== 'undefined' && window) {
var _window = window,
devicePixelRatio = _window.devicePixelRatio,
screen = _window.screen;
var width = screen.width,
height = screen.height;
return xSeriesConfig.some(item => item.devicePixelRatio === devicePixelRatio && item.width === width && item.height === height);
}
return false;
}
/**
* ie version
* From https://codepen.io/gapcode/pen/vEJNZN
* IE 10 ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
* IE 11 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
* Edge 12 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
* Edge 13 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';
*/
function ieVersion() {
var uakit = ua();
var msie = uakit.indexOf('MSIE ');
if (msie > 0) {
return parseInt(uakit.substring(msie + 5, uakit.indexOf('.', msie)), 10);
}
var trident = uakit.indexOf('Trident/');
if (trident > 0) {
var rv = uakit.indexOf('rv:');
return parseInt(uakit.substring(rv + 3, uakit.indexOf('.', rv)), 10);
}
var edge = uakit.indexOf('Edge/');
if (edge > 0) {
return parseInt(ua.substring(edge + 5, uakit.indexOf('.', edge)), 10);
}
return '';
}
function isIE() {
return ieVersion() > 0;
}
/**
* arguments to array
*/
/**
* Converts the arguments object to an array object and slice it.
* first defalult is 0.
* @export
* @param {*} $arguments
* @param {*} first
* @returns
*/
function args($arguments, first) {
return Array.prototype.slice.call($arguments, first || 0);
}
var noop = () => {};
var merge = function () {
for (var _len = arguments.length, objs = new Array(_len), _key = 0; _key < _len; _key++) {
objs[_key] = arguments[_key];
}
return [].concat(objs).reduce((acc, obj) => Object.keys(obj).reduce((a, k) => {
acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
return acc;
}, {}), {});
};
var over = function () {
for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
}
return function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return fns.map(fn => fn.apply(null, args));
};
};
var call = function (key) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return context => context[key].apply(context, args);
};
function hasOwnProperty(obj, keyName) {
return Object.prototype.hasOwnProperty.call(obj, keyName);
}
function setStyle(el, ruleName, val) {
el.style[ruleName] = val;
}
function attr(el, ruleName, val) {
el.setAttribute(ruleName, val);
}
/**
* trigger event
* https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript
*/
var trigger = (element, event, eventType) => {
// delete document.createEventObject of ie
var e = document.createEvent(eventType || 'HTMLEvents');
e.initEvent(event, true, true);
element.dispatchEvent(e);
};
function g(i) {
return document.getElementById(i);
}
function c(t, cn, i, id) {
var el = document.createElement(t);
if (cn) {
attr(el, 'class', cn);
}
if (i) {
el.innerHTML = i;
}
if (id) {
attr(el, 'id', id);
}
return el;
}
/**
* open new url dont not blocked by browser
*/
var open = href => {
var id = '_bbo_open_proxy';
var a = g(id) || c('a', id, '', id);
setStyle(a, 'display', 'none');
attr(a, 'href', href);
attr(a, 'target', '_blank');
if (!a.parentNode) document.body.appendChild(a);
trigger(a, 'click', 'MouseEvents');
};
var stopPropagation = event => {
var e = event || window.event;
var stop = e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
return stop;
};
function gc(cn) {
return document.getElementsByClassName(cn);
}
function query(i) {
return document.querySelector(i);
}
var show = function () {
for (var _len = arguments.length, el = new Array(_len), _key = 0; _key < _len; _key++) {
el[_key] = arguments[_key];
}
return [].concat(el).forEach(e => {
e.style.display = '';
});
};
var hide = function () {
for (var _len = arguments.length, el = new Array(_len), _key = 0; _key < _len; _key++) {
el[_key] = arguments[_key];
}
return [].concat(el).forEach(e => {
e.style.display = 'none';
});
};
var elementContains = (parent, child) => parent !== child && parent.contains(child);
var getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
/**
* generate uuid
* From https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
*/
function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0;
var v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
}
function isArray(arr) {
return getTag(arr) === '[object Array]';
}
function isMap(map) {
return getTag(map) === '[object Map]';
}
function isSet(set) {
return getTag(set) === '[object Set]';
}
/**
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable string keyed properties for objects.
*
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the collection size.
*/
function size(collection) {
if (collection === null || collection === undefined) {
return 0;
}
if (isArray(collection) || isString(collection)) {
return collection.length;
}
if (isMap(collection) || isSet(collection)) {
return collection.size;
}
return Object.keys(collection).length;
}
/**
* string hash map
* From https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery
*/
function hash(str) {
var _str = String(str);
var hash = 0;
var i;
var chr;
if (size(_str) === 0) return hash;
for (i = 0; i < _str.length; i++) {
chr = _str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
/**
* is typeof type
*/
var isTypeof = (val, type) => {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase() === type;
};
/**
* map condition judge
* bbo.judge = bbo.judgment
*/
function judge(v, vals, strict) {
if (!isTypeof(vals, 'array')) return false;
for (var key in vals) {
if (strict) {
if (v === vals[key]) return true;
} else {
// eslint-disable-next-line eqeqeq
if (v == vals[key]) return true;
}
}
return false;
}
var getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
function construct() {
var classs = arguments[0];
return new (Function.prototype.bind.apply(classs, arguments))();
}
/**
* Gets all the formal parameter names of a function
* https://www.zhihu.com/question/28912825
*/
function paramsName(fn) {
return /\(\s*([\s\S]*?)\s*\)/.exec(fn.toString())[1].split(/\s*,\s*/);
}
/************************************************************************
* LOGS
*************************************************************************/
function log(msg, styles) {
var ele = g('_bbo_log');
if (ele === null) {
ele = c('div');
attr(ele, 'id', '_bbo_log');
attr(ele, 'style', 'position:fixed;left:0;top:0;z-index:9999;padding:4px;');
document.body.appendChild(ele);
}
if (styles) {
for (var style in styles) {
if (Object.prototype.hasOwnProperty.call(styles, style)) {
ele.style[style] = styles[style];
}
}
}
ele.innerHTML = msg;
}
function isObject(value) {
var type = typeof value;
return value !== null && (type === 'object' || type === 'function');
}
var properObject = o => isObject(o) && !o.hasOwnProperty ? { ...o
} : o;
var isDate = d => d instanceof Date;
function isEmpty(obj) {
if (obj === null) {
return true;
}
if (isArray(obj)) {
return !obj.length;
}
if (isString(obj)) {
return !obj.length;
}
if (isObject(obj)) {
return !Object.keys(obj).length;
}
if (isMap(obj) || isSet(obj)) {
return !obj.size;
} // other primitive || unidentifed object type
return Object(obj) !== obj || !Object.keys(obj).length;
}
var objectDiff = (lhs, rhs) => {
if (lhs === rhs) return {}; // equal return no diff
if (!isObject(lhs) || !isObject(rhs)) return rhs; // return updated rhs
var l = properObject(lhs);
var r = properObject(rhs);
var deletedValues = Object.keys(l).reduce((acc, key) => {
return r.hasOwnProperty(key) ? acc : { ...acc,
[key]: undefined
};
}, {});
if (isDate(l) || isDate(r)) {
// eslint-disable-next-line eqeqeq
if (l.valueOf() == r.valueOf()) return {};
return r;
}
return Object.keys(r).reduce((acc, key) => {
if (!l.hasOwnProperty(key)) return { ...acc,
[key]: r[key]
}; // return added r key
var difference = objectDiff(l[key], r[key]);
if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; // return no diff
return { ...acc,
[key]: difference
}; // return updated key
}, deletedValues);
};
var addedDiff = (lhs, rhs) => {
if (lhs === rhs || !isObject(lhs) || !isObject(rhs)) return {};
var l = properObject(lhs);
var r = properObject(rhs);
return Object.keys(r).reduce((acc, key) => {
if (l.hasOwnProperty(key)) {
var difference = addedDiff(l[key], r[key]);
if (isObject(difference) && isEmpty(difference)) return acc;
return { ...acc,
[key]: difference
};
}
return { ...acc,
[key]: r[key]
};
}, {});
};
var deletedDiff = (lhs, rhs) => {
if (lhs === rhs || !isObject(lhs) || !isObject(rhs)) return {};
var l = properObject(lhs);
var r = properObject(rhs);
return Object.keys(l).reduce((acc, key) => {
if (r.hasOwnProperty(key)) {
var difference = deletedDiff(l[key], r[key]);
if (isObject(difference) && isEmpty(difference)) return acc;
return { ...acc,
[key]: difference
};
}
return { ...acc,
[key]: undefined
};
}, {});
};
var updatedDiff = (lhs, rhs) => {
if (lhs === rhs) return {};
if (!isObject(lhs) || !isObject(rhs)) return rhs;
var l = properObject(lhs);
var r = properObject(rhs);
if (isDate(l) || isDate(r)) {
// eslint-disable-next-line eqeqeq
if (l.valueOf() == r.valueOf()) return {};
return r;
}
return Object.keys(r).reduce((acc, key) => {
if (l.hasOwnProperty(key)) {
var difference = updatedDiff(l[key], r[key]);
if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc;
return { ...acc,
[key]: difference
};
}
return acc;
}, {});
};
var detailedDiff = (lhs, rhs) => ({
added: addedDiff(lhs, rhs),
deleted: deletedDiff(lhs, rhs),
updated: updatedDiff(lhs, rhs)
});
/**
* to json
*/
// eval hack
var evil = fn => {
// A variable points to Function, preventing reporting errors
var Fn = Function;
return new Fn('return ' + fn)();
}; // bbo.toJSON = bbo.tojson = bbo.toJson
var toJson = res => {
if (!res) return null;
if (typeof res === 'string') {
try {
return JSON.parse(res);
} catch (e) {
return evil('(' + res + ')');
}
} else {
return res;
}
};
var randomKey = function () {
var len = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32;
/** Removed confusing characters 'oOLl,9gq,Vv,Uu,I1' **/
var possible = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
var key = '';
for (var i = 0; i < len; i++) {
key += possible.charAt(Math.floor(Math.random() * possible.length));
}
return key;
};
/* eslint-disable */
/**
* Options:
* - param {String} qs parameter (`callback`)
* - prefix {String} qs parameter (`bbo`)
* - name {String} qs parameter (`prefix` + incr)
* - timeout {Number} how long after a timeout error is emitted (`60000`)
* @param {String} url
* @param {Object|Function} optional options / callback
* @param {Function} optional callback
*/
function jsonp(url, opts, fn) {
if (isFunction(opts)) {
fn = opts;
opts = {};
}
if (!opts) opts = {};
var prefix = opts.prefix || 'bbo';
var id = opts.name || prefix + randomKey(10);
var param = opts.param || 'callback';
var timeout = null != opts.timeout ? opts.timeout : 60000;
var enc = encodeURIComponent;
var target = document.getElementsByTagName('script')[0] || document.head;
var script;
var timer;
if (timeout) {
timer = setTimeout(function () {
cleanup();
if (fn) fn(new Error('Timeout'));
}, timeout);
}
function cleanup() {
if (script.parentNode) script.parentNode.removeChild(script);
window[id] = noop();
if (timer) clearTimeout(timer);
}
function cancel() {
if (window[id]) {
cleanup();
}
}
window[id] = function (data) {
cleanup();
if (fn) fn(data, null);
};
console.log(url);
url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id);
url = url.replace('?&', '?');
script = document.createElement('script');
script.src = url;
target.parentNode.insertBefore(script, target);
return cancel;
}
function isNumber(number) {
return getTag(number) === '[object Number]';
}
/* eslint-disable guard-for-in */
var cookie = () => {
function cookieAttrExtend() {
var i = 0;
var result = {};
for (; i < arguments.length; i++) {
var attributes = arguments[i];
for (var key in attributes) {
if (hasOwnProperty(attributes, key)) {
result[key] = attributes[key];
}
}
}
return result;
}
function init(converter) {
function api(key, value, attributes) {
var result;
if (size(arguments) > 1) {
attributes = cookieAttrExtend({
path: '/'
}, api.defaults, attributes);
if (isNumber(attributes.expires)) {
var expires = new Date();
expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e5);
attributes.expires = expires;
}
try {
result = JSON.stringify(value);
if (/^[\{\[]/.test(result)) {
value = result;
}
} catch (e) {}
if (!converter.write) {
value = encodeURIComponent(String(value)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
} else {
value = converter.write(value, key);
}
key = encodeURIComponent(String(key));
key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
key = key.replace(/[\(\)]/g, escape); // eslint-disable-next-line no-return-assign
return document.cookie = [key, '=', value, attributes.expires ? '; expires=' + attributes.expires.toUTCString() : '', attributes.path ? '; path=' + attributes.path : '', attributes.domain ? '; domain=' + attributes.domain : '', attributes.secure ? '; secure' : ''].join('');
}
if (!key) {
result = {};
}
var cookies = document.cookie ? document.cookie.split('; ') : [];
var rdecode = /(%[0-9A-Z]{2})+/g;
var i = 0;
for (; i < cookies.length; i++) {
var parts = cookies[i].split('=');
var _cookie = parts.slice(1).join('=');
if (_cookie.charAt(0) === '"') {
_cookie = _cookie.slice(1, -1);
}
try {
var name = parts[0].replace(rdecode, decodeURIComponent);
_cookie = converter.read ? converter.read(_cookie, name) : converter(_cookie, name) || _cookie.replace(rdecode, decodeURIComponent); // eslint-disable-next-line no-invalid-this
if (this.json) {
try {
_cookie = JSON.parse(_cookie);
} catch (e) {}
}
if (key === name) {
result = _cookie;
break;
}
if (!key) {
result[name] = _cookie;
}
} catch (e) {}
}
return result;
}
api.set = api;
api.get = function (key) {
return api.call(api, key);
};
api.getJson = api.getJSON = function () {
return api.apply({
json: true
}, [].slice.call(arguments));
};
api.defaults = {};
api.remove = function (key, attributes) {
api(key, '', cookieAttrExtend(attributes, {
expires: -1
}));
};
api.withConverter = init;
return api;
}
return init(function () {});
};
/**
* setCookie / getCookie / deleteCookie
* From https://stackoverflow.com/questions/1458724/how-do-i-set-unset-cookie-with-jquery/1458728#1458728
*/
var setCookie = (name, value, option) => {
var longTime = 10; // let path = '; path=/';
var val = option && option.raw ? value : encodeURIComponent(value);
var cookie = encodeURIComponent(name) + '=' + val;
if (option) {
if (option.days) {
var date = new Date();
var ms = option.days * 24 * 3600 * 1000;
date.setTime(date.getTime() + ms);
cookie += '; expires=' + date.toGMTString();
} else if (option.hour) {
var _date = new Date();
var _ms = option.hour * 3600 * 1000;
_date.setTime(_date.getTime() + _ms);
cookie += '; expires=' + _date.toGMTString();
} else {
var _date2 = new Date();
var _ms2 = longTime * 365 * 24 * 3600 * 1000;
_date2.setTime(_date2.getTime() + _ms2);
cookie += '; expires=' + _date2.toGMTString();
}
if (option.path) cookie += '; path=' + option.path;
if (option.domain) cookie += '; domain=' + option.domain;
if (option.secure) cookie += '; true';
}
document.cookie = cookie;
};
var getCookie = name => {
var nameEQ = encodeURIComponent(name) + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
};
var deleteCookie = name => {
setCookie(name, '', {
hour: -1
});
};
var parseCookie = str => str.split(';').map(v => v.split('=')).reduce((acc, v) => {
acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
return acc;
}, {});
/**
* getUrlParam / deleteUrlParam
* From https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
*/
var getUrlParam = function (name) {
var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location.href;
name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
var results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
};
/**
* setUrlParam
* From https://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter
*/
var setUrlParam = function (key, value) {
var uri = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : window.location.href;
var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
var separator = uri.indexOf('?') !== -1 ? '&' : '?';
if (uri.match(re)) {
return uri.replace(re, '$1' + key + '=' + value + '$2');
} else {
return uri + separator + key + '=' + value;
}
};
/**
* getUrlParam / deleteUrlParam
* From https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
*/
var deleteUrlParam = function (param) {
var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location.href;
// prefer to use l.search if you have a location/link object
var urlparts = url.split('?');
if (urlparts.length >= 2) {
var prefix = encodeURIComponent(param) + '=';
var pars = urlparts[1].split(/[&;]/g); // reverse iteration as may be destructive
for (var i = pars.length; i-- > 0;) {
// idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
} else {
return url;
}
};
var objectParam = arr => {
var str = '';
if (isArray(arr)) {
str = arr.map(item => {
return item.name + '=' + item.value;
}).join('&');
} else {
str = objectParam(objectBigParam(arr));
}
return str;
};
var objectBigParam = obj => {
var arr = [];
Object.keys(obj).forEach(k => {
if (isArray(obj[k])) {
arr = arr.concat(obj[k].map(v => {
return {
name: k,
value: v
};
}));
} else {
arr.push({
name: k,
value: obj[k]
});
}
});
return arr;
};
var httpGet = function (url, callback) {
var err = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : console.error;
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = () => callback(request.responseText);
request.onerror = () => err(request);
request.send();
};
// eslint-disable-next-line max-params
var httpPost = function (url, data, callback) {
var err = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : console.error;
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
request.onload = () => callback(request.responseText);
request.onerror = () => err(request);
request.send(data);
};
/**
* Returns true if the given string is an absolute URL, false otherwise.
*/
var isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
function clearTimesout(id) {
return clearInterval(id);
}
/**
* setInterval func fix times
* https://stackoverflow.com/questions/2956966/javascript-telling-setinterval-to-only-fire-x-amount-of-times
*/
function setTimesout() {
var func = arguments[0];
var delay = arguments[1] === undefined ? 0 : parseFloat(arguments[1]);
var times = arguments[2] === undefined ? 1 : parseInt(arguments[2], 10);
var _args = arguments.length > 3 ? args(arguments, 3) : null;
var target = {
index: 0,
times: times,
over: false
};
var id = setInterval(function () {
target.index++;
if (target.index > times) {
clearTimesout(id);
} else {
if (target.index === times) target.over = true;
func.apply(target, _args);
}
}, delay);
return id;
}
function fill0(num) {
var _num = parseFloat(num);
return _num < 10 ? '0' + _num : String(_num);
}
/**
* getDate
* https://stackoverflow.com/questions/1531093/how-do-i-get-the-current-date-in-javascript
*/
var getDate = (d1, d2) => {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
var hh = today.getHours();
var ms = today.getMinutes();
var ss = today.getSeconds();
dd = fill0(dd);
mm = fill0(mm);
hh = fill0(hh);
ms = fill0(ms);
ss = fill0(ss);
var _d1 = d1 || '/';
var _d2 = d2 || ':';
return yyyy + _d1 + mm + _d1 + dd + ' ' + hh + _d2 + ms + _d2 + ss;
};
/**
* @param {Date} startTime timestamp
* @return {String}
*/
var formatPassTime = startTime => {
var seconds = Math.floor((new Date() - startTime) / 1000);
var interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) + ' years';
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) + ' months';
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) + ' days';
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) + ' hours';
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) + ' minutes';
}
return Math.floor(seconds) + ' seconds';
};
/**
* @desc format the remaining time from ${endTime}
* @param {Date} endTime
* @return {String}
*/
var formatRemainTime = endTime => {
var startDate = new Date(); // startDate
var endDate = new Date(endTime); // endDate
var t = endDate.getTime() - startDate.getTime();
var d = 0;
var h = 0;
var m = 0;
var s = 0;
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24);
h = Math.floor(t / 1000 / 60 / 60 % 24);
m = Math.floor(t / 1000 / 60 % 60);
s = Math.floor(t / 1000 % 60);
}
return d + 'day ' + h + 'hour ' + m + 'minute ' + s + 'second';
};
var formatDuration = ms => {
// eslint-disable-next-line no-param-reassign
if (ms < 0) ms = -ms;
var time = {
day: Math.floor(ms / 86400000),
hour: Math.floor(ms / 3600000) % 24,
minute: Math.floor(ms / 60000) % 60,
second: Math.floor(ms / 1000) % 60,
millisecond: Math.floor(ms) % 1000
};
return Object.entries(time).filter(val => val[1] !== 0).map((_ref) => {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
val = _ref2[1];
return `${val} ${key}${val !== 1 ? 's' : ''}`;
}).join(', ');
};
var cachedSetTimeout = setTimeout;
function createSleepPromise(timeout, _ref) {
var useCachedSetTimeout = _ref.useCachedSetTimeout;
var timeoutFunction = useCachedSetTimeout ? cachedSetTimeout : setTimeout;
return new Promise(resolve => {
timeoutFunction(resolve, timeout);
});
}
function sleep(timeout) {
var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
useCachedSetTimeout = _ref2.useCachedSetTimeout;
var sleepPromise = createSleepPromise(timeout, {
useCachedSetTimeout: useCachedSetTimeout
});
function promiseFunction(value) {
return sleepPromise.then(() => value);
}
promiseFunction.then = function () {
return sleepPromise.then.apply(sleepPromise, arguments);
};
promiseFunction.catch = Promise.resolve().catch;
return promiseFunction;
}
/* eslint-disable prefer-promise-reject-errors */
/**
* @param {any} attempt
* @param {any} options
* interval: 200, //ms
* retries: 2
* timeout: 8000 //ms
*/
function retry (attempt, options) {
var option = options || {};
var interval = option.interval || 400;
var retries = option.retries || 2;
var timeout = option.timeout || 8000;
function rejectDelay(reason) {
return new Promise(function (resolve, reject) {
setTimeout(reject.bind(null, reason), interval);
});
}
var p = Promise.reject();
for (var i = 0; i < retries; i++) {
p = p.catch(timeoutReject(attempt, timeout)).catch(rejectDelay);
}
return p;
}
function timeoutReject(task, timeout) {
var timer;
return function () {
return Promise.race([Promise.reject().catch(task), new Promise(function (rs, rj) {
timer = setTimeout(function () {
rj('timeout.');
}, timeout || 8000);
})]).then(function (r) {
clearTimeout(timer);
return r;
}, function (err) {
return Promise.reject(err);
});
};
}
var floor = function (n) {
var m = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return Math.floor(n * Math.pow(10, m)) / Math.pow(10, m);
};
var chainAsync = fns => {
var curr = 0;
var last = fns[fns.length - 1];
var next = () => {
var fn = fns[curr++];
fn === last ? fn() : fn(next);
};
next();
};
/**
* https://locutus.io/php/
*/
// eslint-disable-next-line max-params
var numberFormat = (number, decimals, decPoint, thousandsSep) => {
var _number = String(number).replace(/[^0-9+\-Ee.]/g, '');
var _decimals = decimals;
var n = !isFinite(Number(_number)) ? 0 : Number(_number);
var prec = !isFinite(Number(_decimals)) ? 0 : Math.abs(_decimals);
var sep = typeof thousandsSep === 'undefined' ? ',' : thousandsSep;
var dec = typeof decPoint === 'undefined' ? '.' : decPoint;
var s = '';
var toFixedFix = function (n, prec) {
if (String(n).indexOf('e') === -1) {
return Number(Math.round(n + 'e+' + prec) + 'e-' + prec);
} else {
var arr = String(n).split('e');
var sig = '';
if (Number(arr[1]) + prec > 0) {
sig = '+';
}
return Number(Math.round(Number(arr[0]) + 'e' + sig + (Number(arr[1]) + prec)) + 'e-' + prec).toFixed(prec);
}
}; // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec).toString() : String(Math.round(n))).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
};
/**
* modulo of a number and a divisor
*/
function modulo(n, d) {
// bbo.modulo(7, 5); // 2
// bbo.modulo(17, 23); // 17
// bbo.modulo(16.2, 3.8); // 1
// bbo.modulo(5.8, 3.4); //2.4
// bbo.modulo(4, 0); // 4
// bbo.modulo(-7, 5); // 3
// bbo.modulo(-2, 15); // 13
// bbo.modulo(-5.8, 3.4); // 1
// bbo.modulo(12, -1); // NaN
// bbo.modulo(-3, -8); // NaN
// bbo.modulo(12, 'apple'); // NaN
// bbo.modulo('bee', 9); // NaN
// bbo.modulo(null, undefined); // NaN
if (d === 0) {
return n;
}
if (d < 0) {
return NaN;
}
return (n % d + d) % d;
}
function randomColor() {
return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
}
// bbo.randomFromA2B = bbo.randomA2B
var randomA2B = (a, b, int) => {
var result = Math.random() * (b - a) + a;
return int ? Math.floor(result) : result;
};
/**
* lock touch in mobile phone
*/
var lockTouch = () => {
document.addEventListener('touchmove', function (e) {
e.preventDefault();
}, !1);
document.addEventListener('touchstart', preventDefault, !1);
document.addEventListener('touchend', preventDefault, !1);
function not(e, tag) {
return e.target.tagName !== tag.toUpperCase() && e.target.tagName !== tag.toLowerCase();
}
function preventDefault(e) {
if (not(e, 'input') && not(e, 'textarea') && not(e, 'select') && not(e, 'menus')) e.preventDefault();
}
};
function copyToClipboard(str) {
var el = document.createElement('textarea');
el.value = str;
attr(el, 'readonly', '');
setStyle(el, 'position', 'absolute');
setStyle(el, 'left', '-9999px');
document.body.appendChild(el);
var selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
}
/* eslint-disable eqeqeq */
function clone(obj) {
// var arr = [1, 2, 3];
// var subObj = { aa: 1 };
// var obj = { a: 3, b: 5, c: arr, d: subObj };
// var objClone = bbo.clone(obj);
// arr.push(4);
// subObj.bb = 2;
// obj; // {a: 3, b: 5, c: [1, 2, 3, 4], d: {aa: 1}}
// objClone; // {a: 3, b: 5, c: [1, 2, 3], d: {aa: 1, bb: 2}}
if (isFunction(obj)) {
return obj;
}
var result = isArray(obj) ? [] : {};
for (var key in obj) {
// include prototype properties
var value = obj[key];
var type = {}.toString.call(value).slice(8, -1);
if (type == 'Array' || type == 'Object') {
result[key] = clone(value);
} else if (type == 'Date') {
result[key] = new Date(value.getTime());
} else if (type == 'RegExp') {
result[key] = RegExp(value.source, getRegExpFlags(value));
} else {
result[key] = value;
}
}
return result;
}
function getRegExpFlags(regExp) {
if (typeof regExp.source.flags == 'string') {
return regExp.source.flags;
} else {
var flags = [];
regExp.global && flags.push('g');
regExp.ignoreCase && flags.push('i');
regExp.multiline && flags.push('m');
regExp.sticky && flags.push('y');
regExp.unicode && flags.push('u');
return flags.join('');
}
}
function values(obj) {
var result = [];
if (isArray(obj)) {
return obj.slice(0);
}
if (isObject(obj) || isFunction(obj)) {
var keys = Object.keys(obj);
var len = keys.length;
for (var i = 0; i < len; i++) {
result.push(obj[keys[i]]);
}
return result;
}
throw new Error('argument to `values` must be an object');
}
function entries(obj) {
if (!isObject(obj) && !isFunction(obj) || obj === null) {
throw new Error('argument to `entries` must be an object');
}
var result = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
result.push([key, obj[key]]);
}
}
return result;
}
function isBoolean(bool) {
return getTag(bool) === '[object Boolean]';
}
function extend()
/* [deep], obj1, obj2, [objn] */
{
var args = [].slice.call(arguments);
var deep = false;
if (isBoolean(args[0])) {
deep = args.shift();
}
var result = args[0];
if (isUnextendable(result)) {
throw new Error('extendee must be an object');
}
var extenders = args.slice(1);
var len = extenders.length;
for (var i = 0; i < len; i++) {
var extender = extenders[i];
for (var key in extender) {
if (extender.hasOwnProperty(key)) {
var value = extender[key];
if (deep && isCloneable(value)) {
var base = isArray(value) ? [] : {};
result[key] = extend(true, result.hasOwnProperty(key) && !isUnextendable(result[key]) ? result[key] : base, value);
} else {
result[key] = value;
}
}
}
}
return result;
}
function isCloneable(obj) {
return isArray(obj) || isObject(obj);
}
function isUnextendable(val) {
return !val || !isObject(val) && !isFunction(val);
}
/* eslint-disable eqeqeq */
function flush(collection) {
var result;
var len;
var i;
if (!collection) {
return undefined;
}
if (isArray(collection)) {
result = [];
len = collection.length;
for (i = 0; i < len; i++) {
var elem = collection[i];
if (elem != null) {
result.push(elem);
}
}
return result;
}
if (isObject(collection)) {
result = {};
var keys = Object.keys(collection);
len = keys.length;
for (i = 0; i < len; i++) {
var key = keys[i];
var value = collection[key];
if (value != null) {
result[key] = value;
}
}
return result;
}
return undefined;
}
function search(needle, haystack, argStrict) {
var strict = !!argStrict;
var key = '';
for (key in haystack) {
if (hasOwnProperty(haystack, key)) {
// eslint-disable-next-line eqeqeq
if (strict && haystack[key] === needle || !strict && haystack[key] == needle) {
return key;
}
}
}
return false;
}
/* eslint-disable no-self-compare */
function is(x, y) {
// inlined Object.is polyfill to avoid requiring consumers ship their own
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
// Added the nonzero y check to make Flow happy, but it is redundant
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
function isSymbol(symbol) {
return getTag(symbol) === '[object Symbol]';
}
/* eslint-disable no-eq-null */
/* eslint-disable eqeqeq */
function isNil(value) {
return value == undefined || value == null;
}
/* eslint-disable guard-for-in */
function isShallowEqual() {
for (var _len = arguments.length, objs = new Array(_len), _key = 0; _key < _len; _key++) {
objs[_key] = arguments[_key];
}
if (objs.length < 2) return false;
for (var i in objs) {
i = Number(i);
if (objs[i + 1] !== undefined) {
if (isArray(objs[i])) {
if (!compareArrays(objs[i], objs[i + 1])) {
return false;
}
} else if (isObject(objs[i])) {
if (!compareObjects(objs[i], objs[i + 1])) {
return false;
}
} else if (isDate(objs[i])) {
if (!compareDates(objs[i], objs[i + 1])) {
return false;
}
} else {
if (objs[i] !== objs[i + 1]) {
return false;
}
}
}
}
return true;
}
function compare(obj, obj1) {
for (var i in obj) {
if (obj1[i] === undefined) {
return false;
}
if (isArray(obj[i])) {
if (!compareArrays(obj[i], obj1[i])) {
return false;
}
} else if (isObject(obj[i])) {
if (!compareObjects(obj[i], obj1[i])) {
return false;
}
} else if (isDate(obj[i])) {
if (!compareDates(obj[i], obj1[i])) {
return false;
}
} else {
if (obj[i] !== obj1[i]) {
return false;
}
}
}
return true;
}
function compareArrays(obj, obj1) {
if (!isArray(obj1)) return false;
if (obj.length !== obj1.length) return false;
var equal = compare(obj, obj1);
return equal;
}
function compareObjects(obj, obj1) {
if (!isObject(obj1)) return false;
for (var key in obj1) {
if (obj[key] === undefined) {
return false;
}
}
var equal = compare(obj, obj1);
return equal;
}
function compareDates(obj, obj1) {
if (!isDate(obj1) || obj.getTime() !== obj1.getTime()) {
return false;
}
return true;
}
/* eslint-disable eqeqeq */
function has(object, key) {
return object != null && hasOwnProperty(object, key);
}
function map(src, func) {
var rst = [];
var i = 0;
if (isArray(src)) {
while (i < src.length) {
rst.push(func(src[i], i, src));
i += 1;
}
} else if (isObject(src)) {
var keys = Object.keys(src);
while (i < keys.length) {
var key = keys[i];
rst.push(func(src[key], key, src));
i += 1;
}
}
return rst;
}
/* eslint-disable max-params */
var charCodeOfDot = '.'.charCodeAt(0);
var reEscapeChar = /\\(\\)?/g;
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;
function stringToPath(string) {
var result = [];
if (string.charCodeAt(0) === charCodeOfDot) {
result.push('');
}
string.replace(rePropName, (match, expression, quote, subString) => {
var key = match;
if (quote) {
key = subString.replace(reEscapeChar, '$1');
} else if (expression) {
key = expression.trim();
}
result.push(key);
});
return result;
}
/* eslint-disable eqeqeq */
var INFINITY = 1 / 0;
function toKey(value) {
if (isString(value) || isSymbol(value)) {
return value;
}
var result = `${value}`;
return result == '0' && 1 / value == -INFINITY ? '-0' : result;
}
function toPath(value) {
if (isArray(value)) {
return map(value, toKey);
}
return isSymbol(value) ? [value] : clone(stringToPath(String(value)));
}
/* eslint-disable no-param-reassign */
/* eslint-disable max-params */
function reduce(obj, predicate
/* , initialValue */
) {
var args = [callback];
var hasInitialValue = (2 in arguments);
hasInitialValue && args.push(arguments[2]);
function callback(previousValue, currentKey, currentIndex, array) {
if (!hasInitialValue) {
previousValue = obj[array[0]];
hasInitialValue = true;
}
return predicate(previousValue, currentKey, obj[currentKey], currentIndex, array);
}
return Array.prototype.reduce.apply(Object.keys(obj), args);
}
function forEach(src, func) {
var i = 0;
if (isArray(src)) {
while (i < src.length) {
var rst = func(src[i], i, src);
if (rst === false) {
break;
}
i += 1;
}
} else if (isObject(src)) {
var keys = Object.keys(src);
while (i < keys.length) {
var key = keys[i];
var _rst = func(src[key], key, src);
if (_rst === false) {
break;
}
i += 1;
}
}
}
/*
returns a new object with the predicate applied to each value
like map-object, but (value, key, object) are passed to the predicate
*/
function mapValues(obj, predicate) {
var result = {};
var keys = Object.keys(obj);
var len = keys.length;
for (var i = 0; i < len; i++) {
var key = keys[i];
result[key] = predicate(obj[key], key, obj);
}
return result;
}
function find(src, func) {
// eslint-disable-next-line no-undef-init
var rst = undefined;
forEach(src, (item, key, obj) => {
if (isFunction(func)) {
if (func(item, key, obj) === true) {
rst = item;
return false;
}
} else if (is(item, func)) {
rst = item;
return false;
} else if (isObject(item) && isObject(func)) {
var subEqual = true;