UNPKG

lenye_base

Version:

基础方法

1,972 lines (1,608 loc) 158 kB
/* * lenye_base * version 0.0.115 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('lodash')) : typeof define === 'function' && define.amd ? define(['lodash'], factory) : (global = global || self, global.lenye_base = factory(global._)); }(this, (function (_) { 'use strict'; _ = _ && _.hasOwnProperty('default') ? _['default'] : _; 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."); } var version = '0.0.35'; 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; } var sysenv = typeof window !== 'undefined' ? 'browser' : 'node'; var windows = {}; var document$1 = {}; if (sysenv === 'node') { windows = { location: {}, document: {}, localStorage: {}, console: console }; document$1 = windows.document; } else { windows = window; document$1 = windows.document; } function ua(lower) { if (sysenv !== 'node') { return lower ? windows.navigator.userAgent.toLowerCase() : windows.navigator.userAgent; } else { return 'node'; } } /** * 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()); // 手机QQ } function mqqbrowser() { return /mqqbrowser\//.test(ua()); // 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 windows !== 'undefined' && windows) { var devicePixelRatio = windows.devicePixelRatio, screen = windows.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; } function attr(el, ruleName, val) { el.setAttribute(ruleName, val); } 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; } function g(i) { return document.getElementById(i); } /************************************************************************ * LOGS *************************************************************************/ function log(msg, styles) { var ele = g('_bbo_log'); if (ele === null) { ele = c('div'); attr(ele, 'id', '_bbo_log'); attr('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; } /** * 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); } /************************************************************************ * Private Method *************************************************************************/ var _cache = { urls: {}, logs: {} }; /** * bbo.logs('only id&10', 1, 2); */ function logs() { if (windows.console && windows.console.log) { var onlyId = String(arguments[0]); var times = parseInt(onlyId.split('&')[1], 10) || 10; var logsCache = _cache.logs; if (!logsCache[onlyId]) logsCache[onlyId] = {}; if (!logsCache[onlyId].once) logsCache[onlyId].once = 1; if (logsCache[onlyId].once <= times) { console.log.apply(console, args(arguments, 1)); logsCache[onlyId].once++; } } } /** * a trash object */ var trash = { clear: () => { for (var key in trash) { if (key !== 'log' && key !== 'clear') delete trash[key]; } }, log: () => { for (var key in trash) { if (key !== 'log' && key !== 'clear') console.log('bbo.trash:: ', key, trash[key]); } } }; var noop = () => {}; function removeConsole(clear) { try { if (!windows.console) windows.console = {}; windows.console.log = windows.console.info = windows.console.dir = windows.console.warn = windows.console.trace = noop; if (clear === 'clear' && windows.console.clear) windows.console.clear(); } catch (e) {} } 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; } /** * trigger event * https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript */ var trigger = (element, event, eventType) => { if (document.createEventObject) { var e = document.createEventObject(); return element.fireEvent('on' + event, e); } else { var _e = document.createEvent(eventType || 'HTMLEvents'); _e.initEvent(event, true, true); element.dispatchEvent(_e); } }; /** * 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 = e => { var _e = e || windows.event; if (_e.stopPropagation) { _e.stopPropagation(); // W3C } else { _e.cancelBubble = true; // IE } }; 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); }); } /** * 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 (_str.length === 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 { 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*/); } function getTag(src) { return Object.prototype.toString.call(src); } function isFunction(func) { return getTag(func) === '[object Function]'; } function isObject(value) { var type = typeof value; return value !== null && (type === 'object' || type === 'function'); } function isArray(arr) { return getTag(arr) === '[object Array]'; } 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; } } } /* 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; } } var isDate = d => d instanceof Date; /* 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; } function findIndex(src, func) { var rst = -1; forEach(src, (item, index, obj) => { if (isFunction(func)) { if (func(item, index, obj) === true) { rst = index; return false; } } else if (is(item, func)) { rst = index; return false; } else if (isObject(item) && isObject(func)) { var subEqual = true; forEach(func, (v, k) => { subEqual = isShallowEqual(item[k], v); return subEqual; }); if (subEqual) { rst = index; return false; } } }); return rst; } /** * function handle1(a, b, c) { * console.log('one', a, b, c); * } * * function handle2(a, b, c) { * console.log('two', a, b, c); * } * * function handle3(a, b, c) { * console.log('three', a, b, c); * } * * emitter * .on('demo', handle1) * .once('demo', handle2) * .on('demo', handle3); * * emitter.emit('demo', [1, 2, 3]); */ function EventEmitter() { this.__events = {}; } function isListener(listener) { if (isFunction(listener)) { return true; } else if (listener && isObject(listener)) { return isListener(listener.listener); } else { return false; } } var prototype = EventEmitter.prototype; /** * on * @param {String} eventName * @param {Function} listener * @return {Object} */ prototype.on = function (eventName, listener) { if (!eventName || !listener) return; if (!isListener(listener)) { throw new TypeError('listener is a function'); } var events = this.__events; var listeners = events[eventName] = events[eventName] || []; var listenerIsWrapped = isObject(listener); // not repeat if (findIndex(listeners, listener) === -1) { var listenerOnce = { listener: listener, once: false }; listeners.push(listenerIsWrapped ? listener : listenerOnce); console.log(listeners); } return this; }; /** * once * @param {String} eventName * @param {Function} listener * @return {Object} can chained call */ prototype.once = function (eventName, listener) { return this.on(eventName, { listener: listener, once: true }); }; /** * off * @param {String} eventName * @param {Function} listener * @return {Object} can chained call */ prototype.off = function (eventName, listener) { var listeners = this.__events[eventName]; if (!listeners) return; var index; for (var i = 0, len = listeners.length; i < len; i++) { if (listeners[i] && listeners[i].listener === listener) { index = i; break; } } if (typeof index !== 'undefined') { listeners.splice(index, 1, null); } return this; }; /** * emit * @param {String} eventName * @param {Array} args * @return {Object} can chained call */ prototype.emit = function (eventName, args) { var listeners = this.__events[eventName]; if (!listeners) return; for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; if (listener) { listener.listener.apply(this, args || []); if (listener.once) { this.off(eventName, listener.listener); } } } return this; }; /** * allOff && allOne * @param {String[]} */ prototype.allOff = function (eventName) { if (eventName && this.__events[eventName]) { this.__events[eventName] = []; } else { this.__events = {}; } }; var properObject = o => isObject(o) && !o.hasOwnProperty ? { ...o } : o; function isString(str) { return getTag(str) === '[object String]'; } function isMap(map) { return getTag(map) === '[object Map]'; } function isSet(set) { return getTag(set) === '[object Set]'; } 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) }); /* * 对象转数组 * * objectToArr({a1: { name: "张", age: 10 }, a2: { name: "李", age: 20 }}, 'id') * // [{ name: "张", age: 10, id: 'a1' }, { name: "李", age: 20, id: 'a2' } ] * */ var objectToArr = (o, keyField) => isObject(o) && Object.keys(o).reduce((acc, key) => { acc.push(_extends({}, { [keyField]: key }, o[key])); return acc; }, []); function loadImages(options) { var len = 0; var index = 0; var curIndex = 0; var stepTimer = null; var stepTimeValue = 5; var percentageValue = 0; var targetPercent = 0; var data = options.data || []; var step = options.step || function () {}; var complete = options.complete || function () {}; var needOneStep = options.needOneStep || false; var path = options.path || false; if (typeof data !== 'object' || data.length === 0) { step(100); return false; } len = data.length; if (path) { for (var i = len - 1; i > -1; i--) { data[i] = path + data[i]; // console.info(data[i]); } } var processStep = function () { percentageValue++; // console.info("processStep = ",percentageValue) step(percentageValue); if (percentageValue < targetPercent) { stepTimer = setTimeout(function () { processStep(); }, stepTimeValue); } else if (targetPercent === 100 && percentageValue === targetPercent) { if (complete && typeof complete === 'function') { complete(); } } }; function onload() { curIndex++; targetPercent = Math.floor(curIndex / len * 100); if (needOneStep) { if (stepTimer) { clearTimeout(stepTimer); } processStep(); } else { step(targetPercent); if (targetPercent === 100) { complete(); } } } for (index; index < len; index++) { var strUrl = data[index]; new LoadImageItem(strUrl, onload).start(); } } /** * @name loadImageItem * @param {string} url - images full url * @callback cb - called when load image completed */ function LoadImageItem(url, cb) { var self = this; self.img = new Image(); // readyState:'complete' or 'loaded' => image has been loaded。 // for IE6-IE10。 var onReadyStateChange = function () { removeEventHandlers(); console.info('onReadyStateChange'); cb(self, 'onReadyStateChange'); }; var onError = function () { console.info('onError'); removeEventHandlers(); cb(self, 'onError'); }; var onLoad = function () { removeEventHandlers(); cb(self, 'onload'); }; var removeEventHandlers = function () { self.unbind('load', onLoad); self.unbind('readystatechange', onReadyStateChange); self.unbind('error', onError); }; this.start = function () { this.bind('load', onLoad); this.bind('readystatechange', onReadyStateChange); this.bind('error', onError); this.img.src = url; if (self.img.complete) { removeEventHandlers(); cb(this, 'onload'); } }; } /** * @name bind * @description cross-browser event binding * @param {string} eventName * @param {function} eventHandler */ LoadImageItem.prototype.bind = function (eventName, eventHandler) { if (this.img.addEventListener) { this.img.addEventListener(eventName, eventHandler, false); } else if (this.img.attachEvent) { this.img.attachEvent('on' + eventName, eventHandler); } }; /** * @name unbind * @description cross-browser event un-binding * @param {string} eventName * @param {function} eventHandler */ LoadImageItem.prototype.unbind = function (eventName, eventHandler) { if (this.img.removeEventListener) { this.img.removeEventListener(eventName, eventHandler, false); } else if (this.img.detachEvent) { this.img.detachEvent('on' + eventName, eventHandler); } }; /* eslint-disable no-invalid-this */ /** * load js * 1. bbo.loadjs("//your_url/a.js",func); * 2. bbo.loadjs("//your_url/a.js","only_id",func); */ var _cache$1 = { urls: {}, logs: {} }; var _insertScripts = function (arr, callback) { for (var i = 0; i < arr.length; i++) { _insertScript(arr[i], loaded); } var _index = 0; function loaded() { _index++; if (_index >= arr.length) { callback && callback(); } } }; var _insertScript = function (src, callback) { var script = c('script'); attr(script, 'type', 'text/javascript'); attr(script, 'src', src); attr(script, 'charset', 'utf-8'); document.getElementsByTagName('head')[0].appendChild(script); if (/msie/.test(ua('l'))) { script.onreadystatechange = function () { if (this.readyState === 'loaded' || this.readyState === 'complete') { callback(); } }; } else if (/gecko/.test(ua('l'))) { script.onload = function () { callback(); }; } else { setTimeout(function () { callback(); }, 50); } }; function loadjs(url, b, c) { var onlyId; var callback; if (isFunction(b)) { onlyId = String(hash(String(url))); callback = b; } else if (typeof b === 'undefined') { onlyId = String(hash(String(url))); callback = null; } else { onlyId = String(b); callback = c; } if (_cache$1.urls[onlyId]) { callback && callback(); } else { var func = isString(url) ? _insertScript : _insertScripts; func.call(this, url, function () { _cache$1.urls[onlyId] = true; callback && callback(); }); } } 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 no-invalid-this */ function loadcss(url, callback) { var promise; var resolutions = []; var rejections = []; var resolved = false; var rejected = false; var id; id = 'load-css-' + randomKey(5); promise = { done: function (callback) { resolutions.push(callback); if (resolved) callback(); return promise; }, fail: function (callback) { rejections.push(callback); if (rejected) callback(); return promise; } }; function resolve() { resolved = true; for (var i = 0, len = resolutions.length; i < len; i++) { resolutions[i](); } } function reject() { rejected = true; for (var i = 0, len = rejections.length; i < len; i++) { rejections[i](); } } var link = c('link'); attr(link, 'id', id); attr(link, 'rel', 'stylesheet'); attr(link, 'type', 'text/css'); if (typeof link.addEventListener !== 'undefined') { link.addEventListener('load', resolve, false); link.addEventListener('error', reject, false); } else if (typeof link.attachEvent !== 'undefined') { link.attachEvent('onload', function () { // IE 8 gives us onload for both success and failure // and also readyState is always "completed", even // for failure. The only way to see if a stylesheet // load failed from an external domain is to try and // access its cssText, and then catch the error // ... sweet :/ var cur; var i = document.styleSheets.length; try { while (i--) { cur = document.styleSheets[i]; if (cur.id === id) { resolve(); return; } } } catch (e) {} if (!resolved) { reject(); } }); } document.getElementsByTagName('head')[0].appendChild(link); attr(link, 'href', url); return promise; } var toJson = res => { if (!res) return null; if (typeof res === 'string') { try { return JSON.parse(res); } catch (e) { return res; } } else if (isTypeof(res.json, 'function')) { return res.json(); } else { return res; } }; /* 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); windows[id] = noop(); if (timer) clearTimeout(timer); } function cancel() { if (windows[id]) { cleanup(); } } windows[id] = function (data) { cleanup(); if (fn) fn(data, null); }; url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id); url = url.replace('?&', '?'); script = document.createElement('script'); script.src = url; target.parentNode.insertBefore(script, target); return cancel; } /** * cookie * https://github.com/jiayi2/onavo/blob/master/onavo.js#L209 */ var cookie = () => { function _extend() { var i = 0; var result = {}; for (; i < arguments.length; i++) { var attributes = arguments[i]; for (var key in attributes) { if (Object.prototype.hasOwnProperty.call(key, attributes)) { result[key] = attributes[key]; } } } return result; } function init(converter) { // #lizard forgives function api(key, value, attributes) { var result; if (typeof document === 'undefined') { return; } if (arguments.length > 1) { var _attributes = _extend({ path: '/' }, api.defaults, attributes); if (typeof _attributes.expires === 'number') { var expires = new Date(); expires.setMilliseconds(expires.getMilliseconds() + _attributes.expires * 864e5); _attributes.expires = expires; } var _value = value; 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); } var _key = encodeURIComponent(String(key)); var __key = _key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent); var ___key = __key.replace(/[\(\)]/g, escape); var _cookie = document.cookie = [___key, '=', value, attributes.expires ? '; expires=' + attributes.expires.toUTCString() : '', attributes.path ? '; path=' + attributes.path : '', attributes.domain ? '; domain=' + attributes.domain : '', attributes.secure ? '; secure' : ''].join(''); return _cookie; } if (!key) { result = {}; } var cookies = document.cookie ? document.cookie.split('; ') : []; var setDecode = /(%[0-9A-Z]{2})+/g; var i = 0; for (; i < cookies.length; i++) { var parts = cookies[i].split('='); var _cookie2 = parts.slice(1).join('='); if (_cookie2.charAt(0) === '"') { _cookie2 = _cookie2.slice(1, -1); } try { var name = parts[0].replace(setDecode, decodeURIComponent); _cookie2 = converter.read ? converter.read(_cookie2, name) : converter(_cookie2, name) || _cookie2.replace(setDecode, decodeURIComponent); try { _cookie2 = JSON.parse(_cookie2); } catch (e) { console.log(e); } if (key === name) { result = _cookie2; break; } if (!key) { result[name] = _cookie2; } } catch (e) {} } return result; } api.set = api; api.get = function (key) { return api.call(api, key); }; api.getJSON = api.getjson = api.getJson = function () { return api.apply({ json: true }, [].slice.call(arguments)); }; api.defaults = {}; api.remove = function (key, attributes) { api(key, '', _extend(attributes, { expires: -1 })); }; api.withConverter = init; return api; } return init(function () {}); }; var http = { /*获取顶级域名*/ gettopUrl: () => { var host = windows.location.hostname; var ip = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/; if (ip.test(host) === true || host === 'localhost') return host; var regex = /([^]*).*/; var match = host.match(regex); if (typeof match !== "undefined" && null !== match) host = match[1]; if (typeof host !== "undefined" && null !== host) { var strAry = host.split("."); if (strAry.length > 1) { host = strAry[strAry.length - 2] + "." + strAry[strAry.length - 1]; } } return host; }, getUrl: () => { return windows.location.hostname; } }; /** * setCookie / getCookie / deleteCookie * From https://stackoverflow.com/questions/1458724/how-do-i-set-unset-cookie-with-jquery/1458728#1458728 */ var setCookie = {}; if (sysenv === 'node') { // todo /* global global:true */ if (!global['cookie']) { global['cookie'] = {}; } setCookie = (name, value, option) => { global['cookie'][name] = value; }; } else { setCookie = (name, value, option) => { var longTime = 10; if (isObject(value)) { value = JSON.stringify(value); } if (!windows.localStorage) { windows.localStorage.setItem(name, value); } else { var val = 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; } else { cookie += '; path=' + '/'; } if (option.domain) { cookie += '; domain=' + option.domain; } else { cookie += '; domain=' + http.gettopUrl(); } if (option.secure) cookie += '; true'; } windows.document.cookie = cookie; } }; } var setCookie$1 = setCookie; var getCookie = {}; if (sysenv === 'node') { //todo if (!global['cookie']) { global['cookie'] = {}; } getCookie = name => { return global['cookie'][name]; }; } else { getCookie = name => { if (!windows.localStorage) { var getData = windows.localStorage.getItem(name); if (getData && getData !== 'undefined' && getData !== 'null') { return toJson(getData); } else { return false; } } else { var nameEQ = encodeURIComponent(name) + '='; var ca = windows.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) { var _getData = decodeURIComponent(c.substring(nameEQ.length, c.length)); if (_getData && _getData !== 'undefined' && _getData !== 'null') { return toJson(_getData); } else { return false; } } } return null; } }; } var getCookie$1 = getCookie; var deleteCookie = name => { setCookie$1(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; }, {}); /** * Whether a string contains another string */ function containsWith(target, item) { // example 1: lenye_base.contains('Kevin', 'K') // returns 1: true return String(target).indexOf(item) !== -1; } /************************************************************************ * localStorage && sessionStorage * Method for safely supporting localStorage sessionStorage 'setItem' 'getItem' 'removeItem' 'removeAll', * Some extension method 'has' 'get' adn Store prefix *************************************************************************/ var ulocalStorage = windows.localStorage; var ussesionStorage = windows.sessionStorage; class Storage { constructor(options) { var _options$type = options.type, type = _options$type === void 0 ? 'local' : _options$type, _options$prefix = options.prefix, prefix = _options$prefix === void 0 ? 'bbo.storage' : _options$prefix, _options$message = options.message, message = _options$message === void 0 ? { setItem: 'write in', getItem: 'read', removeAll: 'remove all', removeItem: 'remove item' } : _options$message; this.prefix = prefix; this.type = type; this.message = message; if (type === 'local') { this._storage = ulocalStorage; } else if (type === 'session') { this._storage = ussesionStorage; } } doItem(func, action) { try { if (typeof func === 'function') { return func(); } } catch (err) { this._warn(action); return null; } return true; } setItem(key, value) { if (typeof key === 'object') { Object.keys(key).forEach((k, index) => { this.doItem(() => this._storage.setItem(`${this.prefix}.${k}`, JSON.stringify(key[k])), 'setItem'); }); } else { this.doItem(() => this._storage.setItem(`${this.prefix}.${key}`, JSON.stringify(value)), 'setItem'); } } has() { for (var _len = arguments.length, keys = new Array(_len), _key = 0; _key < _len; _key++) { keys[_key] = arguments[_key]; } return keys.every((key, index) => this._storage.getItem(`${this.prefix}.${key}`)); } get() { var result = {}; for (var _len2 = arguments.length, keys = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { keys[_key2] = arguments[_key2]; } keys.forEach((key, index) => { if (`${this._storage.getItem(`${this.prefix}.${key}`)}` !== 'null') { try { result[key] = JSON.parse(this._storage.getItem(`${this.prefix}.${key}`)); } catch (err) { console.warn(this._warn('getItem')); } } }); return result; } getItem(key) { return this.doItem(() => JSON.parse(this._storage.getItem(`${this.prefix}.${key}`)), 'getItem'); } removeAll() { Object.keys(this._storage).forEach(k => { if (containsWith(k, this.prefix)) { this._remove(`${k}`); } }); } removeItem() { for (var _len3 = arguments.length, keys = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { keys[_key3] = arguments[_key3]; } console.log(keys); keys.forEach((key, index) => this.doItem(() => this._storage.removeItem(`${this.prefix}.${key}`), 'removeItem')); } _warn(action) { var message = this.message; console.warn(`Unable to ${message[action] || ''} ${this.type} Storage`); } _remove(keys) { this.doItem(() => this._storage.removeItem(`${keys}`), 'removeItem'); } } var storage = (_ref) => { var type = _ref.type, prefix = _ref.prefix; return new Storage({ type: type, prefix: prefix }); }; /** * 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] : windows.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 url = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : windows.location.href; var re = new RegExp('([?|&])' + key + '=.*?(&|#|$)', 'i'); if (url.match(re)) { return url.replace(re, '$1' + key + '=' + encodeURIComponent(value) + '$2'); } else { var hash = ''; if (url.indexOf('#') !== -1) { hash = url.replace(/.*#/, '#'); url.replace(/#.*/, ''); } var separator = url.indexOf('?') !== -1 ? '&' : '?'; return url + separator + key + '=' + encodeURIComponent(value) + hash; } }; /** * 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] : windows.location.href; // prefer to use l.search if you have a location/link object var urlparts = url.split('?'); if (urlparts