UNPKG

@pivoto/core

Version:

![build](https://img.shields.io/badge/build-passing-success.svg)

1,044 lines (1,019 loc) 29.8 kB
/*! * core (@pivoto/core-v1.1.0) * (c) 2023, Qt * Released under the MIT License. */ /** * 格式化日期为指定格式的字符串 * @param d 日期对象 * @param fmt 格式化模式 * @returns {*} 日期字格式化符串 */ function formatDate(d, fmt) { let o = { "M+": d.getMonth() + 1, "d+": d.getDate(), "h+": d.getHours() == 12 ? 12 : d.getHours() % 12, "H+": d.getHours(), "m+": d.getMinutes(), "s+": d.getSeconds(), "q+": Math.floor((d.getMonth() + 3) / 3), "S+": d.getMilliseconds(), "t+": d.getHours() < 12 ? 'am' : 'pm', "T+": d.getHours() < 12 ? 'AM' : 'PM' }; if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (let k in o) { if (new RegExp("(" + k + ")").test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(-RegExp.$1.length))); } } return fmt; } /** * 按格式解析文件为日期,由于Date.parse作为基础方法已存在,方法名使用`deformat` * @param s 日期字符串 * @param fmt 格式化模式 * @returns {Date} 日期对象 */ function parseDate(s, fmt) { if (typeof s === 'number') return new Date(s); if (!fmt) return new Date(Date.parse(s)); let d = { y: { reg: /y+/g }, M: { reg: /M+/g }, d: { reg: /d+/g }, H: { reg: /H+/g }, h: { reg: /h+/g }, m: { reg: /m+/g }, s: { reg: /s+/g }, S: { reg: /S+/g } }; for (let k in d) { let o = d[k]; let m; while ((m = o.reg.exec(fmt)) != null) { o.idx = m.index; o.len = m[0].length; o.val = parseInt(s.substr(o.idx, o.len)); } } d.y.val = d.y.val || 0; d.M.val = d.M.val || 0; d.d.val = d.d.val || 0; if (d.H.val == null || isNaN(d.H.val)) { if (!isNaN(d.h.val) && typeof (d.h.val) === 'number') { let am = /am/i.test(s); if (am) d.H.val = d.h.val; else d.H.val = d.h.val + 12; } else { d.H.val = 0; } } d.m.val = d.m.val || 0; d.s.val = d.s.val || 0; d.S.val = d.S.val || 0; return (new Date(d.y.val, d.M.val - 1, d.d.val, d.H.val, d.m.val, d.s.val, d.S.val)); } var date = /*#__PURE__*/Object.freeze({ __proto__: null, formatDate: formatDate, parseDate: parseDate }); function trim(s) { return s.replace(/^\s+|\s+$/gm, ''); } var string = /*#__PURE__*/Object.freeze({ __proto__: null, trim: trim }); const MAX = Math.pow(2, 32); function stringHashCode(str) { str = str || ''; let h = 0; let len = str.length; for (let i = 0; i < len; i++) { let c = str.charCodeAt(i); h = 31 * h + Number(c); if (h > MAX) { h = h % MAX; } } return h; } function hashCode(obj) { if (typeof obj === 'string') { return stringHashCode(obj); } return stringHashCode((obj || '').toString()); } var hash = /*#__PURE__*/Object.freeze({ __proto__: null, hashCode: hashCode }); // noinspection DuplicatedCode function enhance() { // @ts-ignore if (!Date.format) Date.format = formatDate; // @ts-ignore if (!Date.deformat) Date.deformat = parseDate; // @ts-ignore if (!Date.prototype.format) { Object.defineProperty(Date.prototype, 'format', { configurable: true, enumerable: false, writable: false, value: function (fmt) { return formatDate(this, fmt); } }); } /*if (!Object.prototype.clone) { Object.defineProperty(Object.prototype, 'clone', { configurable: true, enumerable: false, writable: false, value: function () { return clone(this); } }) }*/ // @ts-ignore if (String.prototype.trim) { Object.defineProperty(String.prototype, 'trim', { configurable: true, enumerable: false, writable: false, value: function () { return trim(this); } }); } // @ts-ignore if (String.prototype.hashCode) { Object.defineProperty(String.prototype, 'hashCode', { configurable: true, enumerable: false, writable: false, value: function () { return hashCode(this); } }); } // @ts-ignore if (Object.prototype.hashCode) { Object.defineProperty(Object.prototype, 'hashCode', { configurable: true, enumerable: false, writable: false, value: function () { return hashCode(this); } }); } } function is(v) { return !!v; } function not(v) { return !v; } function isDef(v) { return v !== undefined && v !== null; } function notDef(v) { return v === undefined || v === null; } function isTrue(v) { return v === true; } function isFalse(v) { return v === false; } function isPrimitive(v) { return (typeof v === 'string' || typeof v === 'number' || typeof v === 'symbol' || typeof v === 'boolean'); } function getType(val) { return Object.prototype.toString.call(val).slice(8, -1); } function isString(val) { return getType(val) === 'String'; } function isNumber(val) { return getType(val) === 'Number'; } function isBoolean(val) { return getType(val) === 'Boolean'; } function isFunction(val) { return getType(val) === 'Function'; } function isNull(val) { return getType(val) === 'Null'; } function isUndefined(val) { return getType(val) === 'Undefined'; } function isObject(val) { return getType(val) === 'Object'; } function isArray(val) { // return getType(val) === 'Array' return Array.isArray(val); } function isRegExp(val) { return getType(val) === 'RegExp'; } function isDate$1(val) { return getType(val) === 'Date'; } function isError(val) { return getType(val) === 'Error'; } function isSymbol(val) { return getType(val) === 'Symbol'; } function isSet(val) { return getType(val) === 'Set'; } function isMap(val) { return getType(val) === 'Map'; } function isPromise(val) { return getType(val) === 'Promise'; /*return ( isDef(val) && typeof val.then === 'function' && typeof val.catch === 'function' )*/ } function isObjectOrArray(value) { return isObject(value) || isArray(value); } function isNumeric(value) { return !isNaN(parseFloat(value)) && isFinite(value); } var type$1 = /*#__PURE__*/Object.freeze({ __proto__: null, is: is, not: not, isDef: isDef, notDef: notDef, isTrue: isTrue, isFalse: isFalse, isPrimitive: isPrimitive, getType: getType, isString: isString, isNumber: isNumber, isBoolean: isBoolean, isFunction: isFunction, isNull: isNull, isUndefined: isUndefined, isObject: isObject, isArray: isArray, isRegExp: isRegExp, isDate: isDate$1, isError: isError, isSymbol: isSymbol, isSet: isSet, isMap: isMap, isPromise: isPromise, isObjectOrArray: isObjectOrArray, isNumeric: isNumeric }); function noop() { } function type(obj) { return (obj === null || obj === undefined) ? String(obj) : getType(obj).toLowerCase(); } function clone(target) { let rs; const targetType = getType(target); if (targetType === 'Object') { rs = {}; } else if (targetType === 'Array') { rs = []; } else { return target; } for (const i in target) { rs[i] = clone(target[i]); } return rs; } function hasProperty(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } // 删除数组中的某一项 function arrayRemove(arr, val) { if (arr.length) { const index = arr.indexOf(val); if (index > -1) { return arr.splice(index, 1); } } return []; } // 删除对象中的某一项 function objectRemove(obj, key) { if (hasProperty(obj, key)) { delete obj[key]; } } function uuid() { if (URL.createObjectURL) { const url = URL.createObjectURL(new Blob()); const uuid = url.toString(); URL.revokeObjectURL(url); return uuid.substr(uuid.lastIndexOf('/') + 1); } return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { let r = Math.random() * 16 | 0; return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); } function each(obj, iterator, context = window) { if (type(obj) === 'number') { for (let i = 0; i < obj; i++) { iterator(i, i, obj); } } else if (hasProperty(obj, 'length') && obj.length === +obj.length) { for (let i = 0; i < obj.length; i++) { if (iterator.call(context, obj[i], i, obj) === false) break; } } else { for (let key in obj) { if (iterator.call(context, obj[key], key, obj) === false) break; } } } function extend(...args) { let target = args[0] || {}; let length = args.length; let i = 1; if (length === 1) { target = this; i = 0; } for (; i < length; i++) { let options = args[i]; if (!options) continue; for (let name in options) { let src = target[name]; let copy = options[name]; if (target === copy) continue; if (copy === undefined) continue; if (isArray(copy)) { target[name] = extend((src && isArray(src) ? src : []), copy); } else if (isObject(copy)) { target[name] = extend((src && isObject(src) ? src : {}), copy); } else { target[name] = copy; } } } return target; } function keys(obj) { let keys = []; for (let key in obj) { if (hasProperty(obj, key)) keys.push(key); } return keys; } function values(obj) { let values = []; for (let key in obj) { if (hasProperty(obj, key)) values.push(obj[key]); } return values; } var utils = /*#__PURE__*/Object.freeze({ __proto__: null, noop: noop, type: type, clone: clone, hasProperty: hasProperty, arrayRemove: arrayRemove, objectRemove: objectRemove, uuid: uuid, each: each, extend: extend, keys: keys, values: values }); const isEmail = (s) => /^([\w_-])+@([\w_-])+((\.[\w_-]+){1,2})$/.test(s); const isMobile$1 = (s) => /^1\d{10}$/.test(s); /** * 座机 * @param s * @return {boolean} */ const isTel = (s) => /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(s); /** * 身份证号 * @param s * @return {boolean} */ const isIdNo = (s) => /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(s); /** * 车牌号 * @param s * @return {boolean} */ const isCarNo = (s) => /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/.test(s); const isChinese = (s) => { return /[u4E00-u9FA5]/.test(s); }; const isUrl = (s) => { return /^(?:(http|https|ftp):\/\/)?((?:[\w_-]+\.)*[\w_-]+)(:\d+)?([^?#]*)(\?[^/?#]*)?(#.+)?$/i.test(s); }; const isDate = (s) => { return /^[1-2]\d{3}-(0?\d|1[0-2])-([0-2]?\d|3[0-1])$/.test(s); }; var regexp = /*#__PURE__*/Object.freeze({ __proto__: null, isEmail: isEmail, isMobile: isMobile$1, isTel: isTel, isIdNo: isIdNo, isCarNo: isCarNo, isChinese: isChinese, isUrl: isUrl, isDate: isDate }); function parseQuery(href = window.location.search) { const args = href.split('?'); if (args[0] === href) { return {}; } const obj = {}; const rs = args[1].split('#')[0].split('&'); for (let i = 0; i < rs.length; i++) { let kv = rs[i].split('='); if (obj[kv[0]] != null) { if (Array.isArray(obj[kv[0]])) { obj[kv[0]].push(kv[1]); } else { obj[kv[0]] = [obj[kv[0]], kv[1]]; } } else { obj[kv[0]] = kv[1]; } } return obj; } function getQuery(name, href = window.location.search) { return parseQuery(href)[name]; } function asQuery(obj) { const rs = []; for (const key in obj) { const value = obj[key]; if (value.constructor === Array) { value.forEach(function (_value) { rs.push(key + '=' + _value); }); } else { rs.push(key + '=' + value); } } return rs.join('&'); } var url = /*#__PURE__*/Object.freeze({ __proto__: null, parseQuery: parseQuery, getQuery: getQuery, asQuery: asQuery }); // 是否移动端 const isMobile = () => /(nokia|iphone|android|ipad|motorola|^mot-|softbank|foma|docomo|kddi|up\.browser|up\.link|htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte-|longcos|pantech|gionee|^sie-|portalmmm|jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220)/i.test(navigator.userAgent); // 是否微信浏览器 const isWechat = () => /microMessenger/i.test(navigator.userAgent); const isAndroid = () => /android/i.test(navigator.userAgent); const isIpad = () => /ipad/i.test(navigator.userAgent); const isIphone = () => /iphone/i.test(navigator.userAgent); const isWindowsPhone = () => /Windows Phone/i.test(navigator.userAgent); const isMac = () => /macintosh/i.test(navigator.userAgent); const isWindows = () => /windows/i.test(navigator.userAgent); const isLinux = () => /linux/i.test(navigator.userAgent); const isPC = () => !isMobile(); const getAgentType = () => { let arr = []; if (isMobile()) { arr.push('mobile'); if (isWechat()) { arr.push('wechat'); } else if (isAndroid()) { arr.push('android'); } else if (isIpad()) { arr.push('iPad'); } else if (isIphone()) { arr.push('iPhone'); } else if (isWindowsPhone()) { arr.push('windowsPhone'); } } else { arr.push('pc'); if (isWechat()) { arr.push('wechat'); } else if (isMac()) { arr.push('mac'); } else if (isLinux()) { arr.push('linux'); } else if (isWindows()) { arr.push('windows'); } } return arr.join(':'); }; var device = /*#__PURE__*/Object.freeze({ __proto__: null, isMobile: isMobile, isWechat: isWechat, isAndroid: isAndroid, isIpad: isIpad, isIphone: isIphone, isWindowsPhone: isWindowsPhone, isMac: isMac, isWindows: isWindows, isLinux: isLinux, isPC: isPC, getAgentType: getAgentType }); function setCookie(key, value, options = {}) { let str = key + '=' + encodeURIComponent(value); if (options.expires) { const curr = new Date(); curr.setTime(curr.getTime() + options.expires * 3600 * 1000); options.expires = curr.toUTCString(); } for (const k in options) { str += ';' + k + '=' + options[k]; } document.cookie = str; } function getCookie(key) { let cookies = document.cookie + ';'; const start = cookies.indexOf(key); if (start <= -1) { return null; } const end = cookies.indexOf(';', start); const value = cookies.slice(start + key.length + 1, end); return decodeURIComponent(value); } function delCookie(key) { const value = getCookie(key); if (value === null) { return false; } setCookie(key, value, { expires: 0 }); return true; } var cookie = /*#__PURE__*/Object.freeze({ __proto__: null, setCookie: setCookie, getCookie: getCookie, delCookie: delCookie }); const parse = (function () { let text, at, ch; const escapee = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t', }; function error(m) { throw { name: 'SyntaxError', message: m, at: at, text: text, }; } function next(c) { if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } ch = text.charAt(at); at += 1; return ch; } function white() { while (ch && ch <= ' ') { next(); } } function number() { let number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch === 'e' || ch === 'E') { string += ch; next(); if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (!isFinite(number)) { error('Bad number'); } else { return Number.isSafeInteger(number) ? number : string; } } function string() { let string = ''; if (ch === '"') { let startAt = at; while (next()) { if (ch === '"') { if (at - 1 > startAt) string += text.substring(startAt, at - 1); next(); return string; } if (ch === '\\') { if (at - 1 > startAt) string += text.substring(startAt, at - 1); next(); if (ch === 'u') { let hex, uffff = 0; for (let i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { string += ch; } startAt = at; } } } error('Bad string'); } function word() { switch (ch) { case 't': next('t'); next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); } function array() { let array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array; // empty array } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error('Bad array'); } function object() { let key, object = {}; if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object; // empty object } while (ch) { key = string(); white(); next(':'); object[key] = value(); white(); if (ch === '}') { next('}'); return object; } next(','); white(); } } error('Bad object'); } function value() { white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } } return function (source, reviver) { let result; text = source + ''; at = 0; ch = ' '; result = value(); if (ch) { error('Syntax error'); } return (reviver != null && typeof reviver === 'function') ? (function walk(holder, key) { let v, value = holder[key]; if (value && typeof value === 'object') { Object.keys(value).forEach(function (k) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } }); } return reviver.call(holder, key, value); })({ '': result }, '') : result; }; })(); const stringify = (function () { const rx_escapable = /[\\"]/g; // /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; const meta = { "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", "\"": "\\\"", "\\": "\\\\" }; let gap; let indent; let rep; function quote(string) { rx_escapable.lastIndex = 0; return rx_escapable.test(string) ? "\"" + string.replace(rx_escapable, function (a) { let c = meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + "\"" : "\"" + string + "\""; } function str(key, holder) { let mind = gap; let value = holder[key]; if (value) { if (typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } else if (value instanceof Date) { value = !isFinite(value.valueOf()) ? null : ((value.getUTCFullYear()) + '-' + ('0' + value.getUTCMonth()).slice(-2) + '-' + ('0' + value.getUTCDate()).slice(-2) + 'T' + ('0' + value.getUTCHours()).slice(-2) + ':' + ('0' + value.getUTCMinutes()).slice(-2) + ':' + ('0' + value.getUTCSeconds()).slice(-2) + '.' + ('00' + value.getUTCMilliseconds()).slice(-3) + 'Z'); } } if (typeof rep === "function") { value = rep.call(holder, key, value); } switch (typeof value) { case "string": return quote(value); case "number": return (isFinite(value)) ? String(value) : "null"; case "boolean": return String(value); case "object": default: { if (!value) { return "null"; } gap += indent; let partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { let length = value.length; for (let i = 0; i < length; i += 1) { partial[i] = str(i, value) || "null"; } let v = partial.length === 0 ? "[]" : gap ? ("[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]") : "[" + partial.join(",") + "]"; gap = mind; return v; } for (let k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { let v = str(k, value); if (v) { partial.push(quote(k) + ((gap) ? ": " : ":") + v); } } } let v = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}"; gap = mind; return v; } } } return function (value, replacer, space) { gap = ""; indent = ""; if (typeof space === "number") { for (let i = 0; i < space; i += 1) { indent += " "; } } else if (typeof space === "string") { indent = space; } if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { throw new Error("stringify"); } rep = replacer; return str("", { "": value }); }; })(); if (typeof JSON === "object") { // @ts-ignore JSON.parse0 = JSON.parse; JSON.parse = parse; } else { // @ts-ignore // eslint-disable-next-line JSON = {}; JSON.stringify = stringify; JSON.parse = parse; } var jsonfix = /*#__PURE__*/Object.freeze({ __proto__: null, parse: parse, stringify: stringify }); function toColorArray(specifier) { var n = specifier.length / 6 | 0, colors = new Array(n), i = 0; while (i < n) colors[i] = "#" + specifier.slice(i * 6, ++i * 6); return colors; } function colors(specifier) { let index = new Map(); let range = toColorArray(specifier); function scale(d) { d = d || 0; let i = 0; if (typeof d === 'number') { i = parseInt(d); } else { let k = index.get(d); if (typeof k === 'undefined' || k === null) { k = hashCode(d); index.set(d, k); } } return range[i % range.length]; } return scale; } const category10 = colors('1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf'); const accent = colors('7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666'); const dark2 = colors('1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666'); const paired = colors("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"); const pastel1 = colors("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"); const pastel2 = colors("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"); const set1 = colors("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"); const set2 = colors("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"); const set3 = colors("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"); const tableau10 = colors("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab"); var colors$1 = /*#__PURE__*/Object.freeze({ __proto__: null, colors: colors, category10: category10, accent: accent, dark2: dark2, paired: paired, pastel1: pastel1, pastel2: pastel2, set1: set1, set2: set2, set3: set3, tableau10: tableau10 }); function proto() { enhance(); } export { colors$1 as colors, cookie, date, device, hash, jsonfix as json, proto, regexp, string, type$1 as type, url, utils };