From 8cfbf163c0b9961ac51ae6d4b758589bc50df3fb Mon Sep 17 00:00:00 2001 From: BianLzhaoMin <11485688+bianliangzhaomin123@user.noreply.gitee.com> Date: Fri, 30 Aug 2024 17:45:46 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=A1=E8=AE=A1=E4=BB=A3=E7=A0=81=E4=BC=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/uni-easyinput/common.js | 84 +- uni_modules/uview-ui/libs/config/config.js | 38 +- uni_modules/uview-ui/libs/function/digit.js | 147 +- uni_modules/uview-ui/libs/function/index.js | 969 ++++++------- .../libs/luch-request/core/Request.js | 156 +-- .../uview-ui/libs/util/async-validator.js | 1199 ++++++++++------- utils/mcaptcha.js | 107 +- 7 files changed, 1478 insertions(+), 1222 deletions(-) diff --git a/uni_modules/uni-easyinput/components/uni-easyinput/common.js b/uni_modules/uni-easyinput/components/uni-easyinput/common.js index df9abe1..eee3b0c 100644 --- a/uni_modules/uni-easyinput/components/uni-easyinput/common.js +++ b/uni_modules/uni-easyinput/components/uni-easyinput/common.js @@ -4,27 +4,27 @@ * @param wait 延迟执行毫秒数 * @param immediate true - 立即执行, false - 延迟执行 */ -export const debounce = function(func, wait = 1000, immediate = true) { - let timer; - console.log(1); - return function() { - console.log(123); - let context = this, - args = arguments; - if (timer) clearTimeout(timer); - if (immediate) { - let callNow = !timer; - timer = setTimeout(() => { - timer = null; - }, wait); - if (callNow) func.apply(context, args); - } else { - timer = setTimeout(() => { - func.apply(context, args); - }, wait) - } - } -} +export const debounce = function (func, wait = 1000, immediate = true) { + let timer; + // console.log(1); + return function () { + // console.log(123); + let context = this, + args = arguments; + if (timer) clearTimeout(timer); + if (immediate) { + let callNow = !timer; + timer = setTimeout(() => { + timer = null; + }, wait); + if (callNow) func.apply(context, args); + } else { + timer = setTimeout(() => { + func.apply(context, args); + }, wait); + } + }; +}; /** * @desc 函数节流 * @param func 函数 @@ -32,25 +32,25 @@ export const debounce = function(func, wait = 1000, immediate = true) { * @param type 1 使用表时间戳,在时间段开始的时候触发 2 使用表定时器,在时间段结束的时候触发 */ export const throttle = (func, wait = 1000, type = 1) => { - let previous = 0; - let timeout; - return function() { - let context = this; - let args = arguments; - if (type === 1) { - let now = Date.now(); + let previous = 0; + let timeout; + return function () { + let context = this; + let args = arguments; + if (type === 1) { + let now = Date.now(); - if (now - previous > wait) { - func.apply(context, args); - previous = now; - } - } else if (type === 2) { - if (!timeout) { - timeout = setTimeout(() => { - timeout = null; - func.apply(context, args) - }, wait) - } - } - } -} + if (now - previous > wait) { + func.apply(context, args); + previous = now; + } + } else if (type === 2) { + if (!timeout) { + timeout = setTimeout(() => { + timeout = null; + func.apply(context, args); + }, wait); + } + } + }; +}; diff --git a/uni_modules/uview-ui/libs/config/config.js b/uni_modules/uview-ui/libs/config/config.js index a3a784e..6090de0 100644 --- a/uni_modules/uview-ui/libs/config/config.js +++ b/uni_modules/uview-ui/libs/config/config.js @@ -1,34 +1,28 @@ // 此版本发布于2023-03-27 -const version = '2.0.36' +const version = "2.0.36"; // 开发环境才提示,生产环境不会提示 -if (process.env.NODE_ENV === 'development') { - console.log(`\n %c uView V${version} %c https://uviewui.com/ \n\n`, 'color: #ffffff; background: #3c9cff; padding:5px 0; border-radius: 5px;'); +if (process.env.NODE_ENV === "development") { + // console.log(`\n %c uView V${version} %c https://uviewui.com/ \n\n`, 'color: #ffffff; background: #3c9cff; padding:5px 0; border-radius: 5px;'); } export default { v: version, version, // 主题名称 - type: [ - 'primary', - 'success', - 'info', - 'error', - 'warning' - ], + type: ["primary", "success", "info", "error", "warning"], // 颜色部分,本来可以通过scss的:export导出供js使用,但是奈何nvue不支持 color: { - 'u-primary': '#2979ff', - 'u-warning': '#ff9900', - 'u-success': '#19be6b', - 'u-error': '#fa3534', - 'u-info': '#909399', - 'u-main-color': '#303133', - 'u-content-color': '#606266', - 'u-tips-color': '#909399', - 'u-light-color': '#c0c4cc' + "u-primary": "#2979ff", + "u-warning": "#ff9900", + "u-success": "#19be6b", + "u-error": "#fa3534", + "u-info": "#909399", + "u-main-color": "#303133", + "u-content-color": "#606266", + "u-tips-color": "#909399", + "u-light-color": "#c0c4cc", }, - // 默认单位,可以通过配置为rpx,那么在用于传入组件大小参数为数值时,就默认为rpx - unit: 'px' -} + // 默认单位,可以通过配置为rpx,那么在用于传入组件大小参数为数值时,就默认为rpx + unit: "px", +}; diff --git a/uni_modules/uview-ui/libs/function/digit.js b/uni_modules/uview-ui/libs/function/digit.js index c8260a0..e1cdfe0 100644 --- a/uni_modules/uview-ui/libs/function/digit.js +++ b/uni_modules/uview-ui/libs/function/digit.js @@ -6,7 +6,7 @@ let _boundaryCheckingState = true; // 是否进行越界检查的全局开关 * @example strip(0.09999999999999998)=0.1 */ function strip(num, precision = 15) { - return +parseFloat(Number(num).toPrecision(precision)); + return +parseFloat(Number(num).toPrecision(precision)); } /** @@ -15,10 +15,10 @@ function strip(num, precision = 15) { * @param {*number} num Input number */ function digitLength(num) { - // Get digit length of e - const eSplit = num.toString().split(/[eE]/); - const len = (eSplit[0].split('.')[1] || '').length - +(eSplit[1] || 0); - return len > 0 ? len : 0; + // Get digit length of e + const eSplit = num.toString().split(/[eE]/); + const len = (eSplit[0].split(".")[1] || "").length - +(eSplit[1] || 0); + return len > 0 ? len : 0; } /** @@ -27,11 +27,11 @@ function digitLength(num) { * @param {*number} num 输入数 */ function float2Fixed(num) { - if (num.toString().indexOf('e') === -1) { - return Number(num.toString().replace('.', '')); - } - const dLen = digitLength(num); - return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num); + if (num.toString().indexOf("e") === -1) { + return Number(num.toString().replace(".", "")); + } + const dLen = digitLength(num); + return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num); } /** @@ -40,11 +40,11 @@ function float2Fixed(num) { * @param {*number} num 输入数 */ function checkBoundary(num) { - if (_boundaryCheckingState) { - if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) { - console.warn(`${num} 超出了精度限制,结果可能不正确`); + if (_boundaryCheckingState) { + if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) { + // console.warn(`${num} 超出了精度限制,结果可能不正确`); + } } - } } /** @@ -54,14 +54,14 @@ function checkBoundary(num) { * @private */ function iteratorOperation(arr, operation) { - const [num1, num2, ...others] = arr; - let res = operation(num1, num2); + const [num1, num2, ...others] = arr; + let res = operation(num1, num2); - others.forEach((num) => { - res = operation(res, num); - }); + others.forEach((num) => { + res = operation(res, num); + }); - return res; + return res; } /** @@ -69,19 +69,19 @@ function iteratorOperation(arr, operation) { * @export */ export function times(...nums) { - if (nums.length > 2) { - return iteratorOperation(nums, times); - } + if (nums.length > 2) { + return iteratorOperation(nums, times); + } - const [num1, num2] = nums; - const num1Changed = float2Fixed(num1); - const num2Changed = float2Fixed(num2); - const baseNum = digitLength(num1) + digitLength(num2); - const leftValue = num1Changed * num2Changed; + const [num1, num2] = nums; + const num1Changed = float2Fixed(num1); + const num2Changed = float2Fixed(num2); + const baseNum = digitLength(num1) + digitLength(num2); + const leftValue = num1Changed * num2Changed; - checkBoundary(leftValue); + checkBoundary(leftValue); - return leftValue / Math.pow(10, baseNum); + return leftValue / Math.pow(10, baseNum); } /** @@ -89,15 +89,18 @@ export function times(...nums) { * @export */ export function plus(...nums) { - if (nums.length > 2) { - return iteratorOperation(nums, plus); - } + if (nums.length > 2) { + return iteratorOperation(nums, plus); + } - const [num1, num2] = nums; - // 取最大的小数位 - const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2))); - // 把小数都转为整数然后再计算 - return (times(num1, baseNum) + times(num2, baseNum)) / baseNum; + const [num1, num2] = nums; + // 取最大的小数位 + const baseNum = Math.pow( + 10, + Math.max(digitLength(num1), digitLength(num2)) + ); + // 把小数都转为整数然后再计算 + return (times(num1, baseNum) + times(num2, baseNum)) / baseNum; } /** @@ -105,13 +108,16 @@ export function plus(...nums) { * @export */ export function minus(...nums) { - if (nums.length > 2) { - return iteratorOperation(nums, minus); - } + if (nums.length > 2) { + return iteratorOperation(nums, minus); + } - const [num1, num2] = nums; - const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2))); - return (times(num1, baseNum) - times(num2, baseNum)) / baseNum; + const [num1, num2] = nums; + const baseNum = Math.pow( + 10, + Math.max(digitLength(num1), digitLength(num2)) + ); + return (times(num1, baseNum) - times(num2, baseNum)) / baseNum; } /** @@ -119,17 +125,20 @@ export function minus(...nums) { * @export */ export function divide(...nums) { - if (nums.length > 2) { - return iteratorOperation(nums, divide); - } + if (nums.length > 2) { + return iteratorOperation(nums, divide); + } - const [num1, num2] = nums; - const num1Changed = float2Fixed(num1); - const num2Changed = float2Fixed(num2); - checkBoundary(num1Changed); - checkBoundary(num2Changed); - // 重要,这里必须用strip进行修正 - return times(num1Changed / num2Changed, strip(Math.pow(10, digitLength(num2) - digitLength(num1)))); + const [num1, num2] = nums; + const num1Changed = float2Fixed(num1); + const num2Changed = float2Fixed(num2); + checkBoundary(num1Changed); + checkBoundary(num2Changed); + // 重要,这里必须用strip进行修正 + return times( + num1Changed / num2Changed, + strip(Math.pow(10, digitLength(num2) - digitLength(num1))) + ); } /** @@ -137,13 +146,13 @@ export function divide(...nums) { * @export */ export function round(num, ratio) { - const base = Math.pow(10, ratio); - let result = divide(Math.round(Math.abs(times(num, base))), base); - if (num < 0 && result !== 0) { - result = times(result, -1); - } - // 位数不足则补0 - return result; + const base = Math.pow(10, ratio); + let result = divide(Math.round(Math.abs(times(num, base))), base); + if (num < 0 && result !== 0) { + result = times(result, -1); + } + // 位数不足则补0 + return result; } /** @@ -152,16 +161,14 @@ export function round(num, ratio) { * @export */ export function enableBoundaryChecking(flag = true) { - _boundaryCheckingState = flag; + _boundaryCheckingState = flag; } - export default { - times, - plus, - minus, - divide, - round, - enableBoundaryChecking, + times, + plus, + minus, + divide, + round, + enableBoundaryChecking, }; - diff --git a/uni_modules/uview-ui/libs/function/index.js b/uni_modules/uview-ui/libs/function/index.js index bd80ee7..71ddd36 100644 --- a/uni_modules/uview-ui/libs/function/index.js +++ b/uni_modules/uview-ui/libs/function/index.js @@ -1,5 +1,5 @@ -import test from './test.js' -import { round } from './digit.js' +import test from "./test.js"; +import { round } from "./digit.js"; /** * @description 如果value小于min,取min;如果value大于max,取max * @param {number} min @@ -7,7 +7,7 @@ import { round } from './digit.js' * @param {number} value */ function range(min = 0, max = 0, value = 0) { - return Math.max(min, Math.min(max, Number(value))) + return Math.max(min, Math.min(max, Number(value))); } /** @@ -17,14 +17,16 @@ function range(min = 0, max = 0, value = 0) { * @returns {number|string} */ function getPx(value, unit = false) { - if (test.number(value)) { - return unit ? `${value}px` : Number(value) - } - // 如果带有rpx,先取出其数值部分,再转为px值 - if (/(rpx|upx)$/.test(value)) { - return unit ? `${uni.upx2px(parseInt(value))}px` : Number(uni.upx2px(parseInt(value))) - } - return unit ? `${parseInt(value)}px` : parseInt(value) + if (test.number(value)) { + return unit ? `${value}px` : Number(value); + } + // 如果带有rpx,先取出其数值部分,再转为px值 + if (/(rpx|upx)$/.test(value)) { + return unit + ? `${uni.upx2px(parseInt(value))}px` + : Number(uni.upx2px(parseInt(value))); + } + return unit ? `${parseInt(value)}px` : parseInt(value); } /** @@ -33,11 +35,11 @@ function getPx(value, unit = false) { * @returns {Promise} 返回promise */ function sleep(value = 30) { - return new Promise((resolve) => { - setTimeout(() => { - resolve() - }, value) - }) + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, value); + }); } /** * @description 运行期判断平台 @@ -45,14 +47,14 @@ function sleep(value = 30) { * @link 运行期判断平台 https://uniapp.dcloud.io/frame?id=判断平台 */ function os() { - return uni.getSystemInfoSync().platform.toLowerCase() + return uni.getSystemInfoSync().platform.toLowerCase(); } /** * @description 获取系统信息同步接口 * @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync */ function sys() { - return uni.getSystemInfoSync() + return uni.getSystemInfoSync(); } /** @@ -61,11 +63,11 @@ function sys() { * @param {Number} max 最大值 */ function random(min, max) { - if (min >= 0 && max > 0 && max >= min) { - const gab = max - min + 1 - return Math.floor(Math.random() * gab + min) - } - return 0 + if (min >= 0 && max > 0 && max >= min) { + const gab = max - min + 1; + return Math.floor(Math.random() * gab + min); + } + return 0; } /** @@ -74,32 +76,36 @@ function random(min, max) { * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制 */ function guid(len = 32, firstU = true, radix = null) { - const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') - const uuid = [] - radix = radix || chars.length + const chars = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split( + "" + ); + const uuid = []; + radix = radix || chars.length; - if (len) { - // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位 - for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix] - } else { - let r - // rfc4122标准要求返回的uuid中,某些位为固定的字符 - uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-' - uuid[14] = '4' + if (len) { + // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位 + for (let i = 0; i < len; i++) + uuid[i] = chars[0 | (Math.random() * radix)]; + } else { + let r; + // rfc4122标准要求返回的uuid中,某些位为固定的字符 + uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-"; + uuid[14] = "4"; - for (let i = 0; i < 36; i++) { - if (!uuid[i]) { - r = 0 | Math.random() * 16 - uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r] - } - } - } - // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class - if (firstU) { - uuid.shift() - return `u${uuid.join('')}` - } - return uuid.join('') + for (let i = 0; i < 36; i++) { + if (!uuid[i]) { + r = 0 | (Math.random() * 16); + uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]; + } + } + } + // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class + if (firstU) { + uuid.shift(); + return `u${uuid.join("")}`; + } + return uuid.join(""); } /** @@ -110,18 +116,18 @@ function guid(len = 32, firstU = true, radix = null) { * @param {string|undefined} name 父组件的参数名 */ function $parent(name = undefined) { - let parent = this.$parent - // 通过while历遍,这里主要是为了H5需要多层解析的问题 - while (parent) { - // 父组件 - if (parent.$options && parent.$options.name !== name) { - // 如果组件的name不相等,继续上一级寻找 - parent = parent.$parent - } else { - return parent - } - } - return false + let parent = this.$parent; + // 通过while历遍,这里主要是为了H5需要多层解析的问题 + while (parent) { + // 父组件 + if (parent.$options && parent.$options.name !== name) { + // 如果组件的name不相等,继续上一级寻找 + parent = parent.$parent; + } else { + return parent; + } + } + return false; } /** @@ -131,38 +137,41 @@ function $parent(name = undefined) { * @param {String} target 转换的目的,object-转为对象,string-转为字符串 * @returns {object|string} */ -function addStyle(customStyle, target = 'object') { - // 字符串转字符串,对象转对象情形,直接返回 - if (test.empty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' && - typeof(customStyle) === 'string') { - return customStyle - } - // 字符串转对象 - if (target === 'object') { - // 去除字符串样式中的两端空格(中间的空格不能去掉,比如padding: 20px 0如果去掉了就错了),空格是无用的 - customStyle = trim(customStyle) - // 根据";"将字符串转为数组形式 - const styleArray = customStyle.split(';') - const style = {} - // 历遍数组,拼接成对象 - for (let i = 0; i < styleArray.length; i++) { - // 'font-size:20px;color:red;',如此最后字符串有";"的话,会导致styleArray最后一个元素为空字符串,这里需要过滤 - if (styleArray[i]) { - const item = styleArray[i].split(':') - style[trim(item[0])] = trim(item[1]) - } - } - return style - } - // 这里为对象转字符串形式 - let string = '' - for (const i in customStyle) { - // 驼峰转为中划线的形式,否则css内联样式,无法识别驼峰样式属性名 - const key = i.replace(/([A-Z])/g, '-$1').toLowerCase() - string += `${key}:${customStyle[i]};` - } - // 去除两端空格 - return trim(string) +function addStyle(customStyle, target = "object") { + // 字符串转字符串,对象转对象情形,直接返回 + if ( + test.empty(customStyle) || + (typeof customStyle === "object" && target === "object") || + (target === "string" && typeof customStyle === "string") + ) { + return customStyle; + } + // 字符串转对象 + if (target === "object") { + // 去除字符串样式中的两端空格(中间的空格不能去掉,比如padding: 20px 0如果去掉了就错了),空格是无用的 + customStyle = trim(customStyle); + // 根据";"将字符串转为数组形式 + const styleArray = customStyle.split(";"); + const style = {}; + // 历遍数组,拼接成对象 + for (let i = 0; i < styleArray.length; i++) { + // 'font-size:20px;color:red;',如此最后字符串有";"的话,会导致styleArray最后一个元素为空字符串,这里需要过滤 + if (styleArray[i]) { + const item = styleArray[i].split(":"); + style[trim(item[0])] = trim(item[1]); + } + } + return style; + } + // 这里为对象转字符串形式 + let string = ""; + for (const i in customStyle) { + // 驼峰转为中划线的形式,否则css内联样式,无法识别驼峰样式属性名 + const key = i.replace(/([A-Z])/g, "-$1").toLowerCase(); + string += `${key}:${customStyle[i]};`; + } + // 去除两端空格 + return trim(string); } /** @@ -170,10 +179,10 @@ function addStyle(customStyle, target = 'object') { * @param {string|number} value 需要添加单位的值 * @param {string} unit 添加的单位名 比如px */ -function addUnit(value = 'auto', unit = uni?.$u?.config?.unit ?? 'px') { - value = String(value) - // 用uView内置验证规则中的number判断是否为数值 - return test.number(value) ? `${value}${unit}` : value +function addUnit(value = "auto", unit = uni?.$u?.config?.unit ?? "px") { + value = String(value); + // 用uView内置验证规则中的number判断是否为数值 + return test.number(value) ? `${value}${unit}` : value; } /** @@ -183,30 +192,32 @@ function addUnit(value = 'auto', unit = uni?.$u?.config?.unit ?? 'px') { * @returns {*} 克隆后的对象或者原值(不是对象) */ function deepClone(obj, cache = new WeakMap()) { - if (obj === null || typeof obj !== 'object') return obj; - if (cache.has(obj)) return cache.get(obj); - let clone; - if (obj instanceof Date) { - clone = new Date(obj.getTime()); - } else if (obj instanceof RegExp) { - clone = new RegExp(obj); - } else if (obj instanceof Map) { - clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value, cache)])); - } else if (obj instanceof Set) { - clone = new Set(Array.from(obj, value => deepClone(value, cache))); - } else if (Array.isArray(obj)) { - clone = obj.map(value => deepClone(value, cache)); - } else if (Object.prototype.toString.call(obj) === '[object Object]') { - clone = Object.create(Object.getPrototypeOf(obj)); - cache.set(obj, clone); - for (const [key, value] of Object.entries(obj)) { - clone[key] = deepClone(value, cache); - } - } else { - clone = Object.assign({}, obj); - } - cache.set(obj, clone); - return clone; + if (obj === null || typeof obj !== "object") return obj; + if (cache.has(obj)) return cache.get(obj); + let clone; + if (obj instanceof Date) { + clone = new Date(obj.getTime()); + } else if (obj instanceof RegExp) { + clone = new RegExp(obj); + } else if (obj instanceof Map) { + clone = new Map( + Array.from(obj, ([key, value]) => [key, deepClone(value, cache)]) + ); + } else if (obj instanceof Set) { + clone = new Set(Array.from(obj, (value) => deepClone(value, cache))); + } else if (Array.isArray(obj)) { + clone = obj.map((value) => deepClone(value, cache)); + } else if (Object.prototype.toString.call(obj) === "[object Object]") { + clone = Object.create(Object.getPrototypeOf(obj)); + cache.set(obj, clone); + for (const [key, value] of Object.entries(obj)) { + clone[key] = deepClone(value, cache); + } + } else { + clone = Object.assign({}, obj); + } + cache.set(obj, clone); + return clone; } /** @@ -216,28 +227,36 @@ function deepClone(obj, cache = new WeakMap()) { * @returns {object|boolean} 深度合并后的对象或者false(入参有不是对象) */ function deepMerge(target = {}, source = {}) { - target = deepClone(target) - if (typeof target !== 'object' || target === null || typeof source !== 'object' || source === null) return target; - const merged = Array.isArray(target) ? target.slice() : Object.assign({}, target); - for (const prop in source) { - if (!source.hasOwnProperty(prop)) continue; - const sourceValue = source[prop]; - const targetValue = merged[prop]; - if (sourceValue instanceof Date) { - merged[prop] = new Date(sourceValue); - } else if (sourceValue instanceof RegExp) { - merged[prop] = new RegExp(sourceValue); - } else if (sourceValue instanceof Map) { - merged[prop] = new Map(sourceValue); - } else if (sourceValue instanceof Set) { - merged[prop] = new Set(sourceValue); - } else if (typeof sourceValue === 'object' && sourceValue !== null) { - merged[prop] = deepMerge(targetValue, sourceValue); - } else { - merged[prop] = sourceValue; - } - } - return merged; + target = deepClone(target); + if ( + typeof target !== "object" || + target === null || + typeof source !== "object" || + source === null + ) + return target; + const merged = Array.isArray(target) + ? target.slice() + : Object.assign({}, target); + for (const prop in source) { + if (!source.hasOwnProperty(prop)) continue; + const sourceValue = source[prop]; + const targetValue = merged[prop]; + if (sourceValue instanceof Date) { + merged[prop] = new Date(sourceValue); + } else if (sourceValue instanceof RegExp) { + merged[prop] = new RegExp(sourceValue); + } else if (sourceValue instanceof Map) { + merged[prop] = new Map(sourceValue); + } else if (sourceValue instanceof Set) { + merged[prop] = new Set(sourceValue); + } else if (typeof sourceValue === "object" && sourceValue !== null) { + merged[prop] = deepMerge(targetValue, sourceValue); + } else { + merged[prop] = sourceValue; + } + } + return merged; } /** @@ -245,10 +264,10 @@ function deepMerge(target = {}, source = {}) { * @param {*} err 错误内容 */ function error(err) { - // 开发环境才提示,生产环境不会提示 - if (process.env.NODE_ENV === 'development') { - console.error(`uView提示:${err}`) - } + // 开发环境才提示,生产环境不会提示 + if (process.env.NODE_ENV === "development") { + // console.error(`uView提示:${err}`) + } } /** @@ -257,34 +276,32 @@ function error(err) { * @returns {array} 打乱后的数组 */ function randomArray(array = []) { - // 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0 - return array.sort(() => Math.random() - 0.5) + // 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0 + return array.sort(() => Math.random() - 0.5); } // padStart 的 polyfill,因为某些机型或情况,还无法支持es7的padStart,比如电脑版的微信小程序 // 所以这里做一个兼容polyfill的兼容处理 if (!String.prototype.padStart) { - // 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解 - String.prototype.padStart = function(maxLength, fillString = ' ') { - if (Object.prototype.toString.call(fillString) !== '[object String]') { - throw new TypeError( - 'fillString must be String' - ) - } - const str = this - // 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉 - if (str.length >= maxLength) return String(str) + // 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解 + String.prototype.padStart = function (maxLength, fillString = " ") { + if (Object.prototype.toString.call(fillString) !== "[object String]") { + throw new TypeError("fillString must be String"); + } + const str = this; + // 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉 + if (str.length >= maxLength) return String(str); - const fillLength = maxLength - str.length - let times = Math.ceil(fillLength / fillString.length) - while (times >>= 1) { - fillString += fillString - if (times === 1) { - fillString += fillString - } - } - return fillString.slice(0, fillLength) + str - } + const fillLength = maxLength - str.length; + let times = Math.ceil(fillLength / fillString.length); + while ((times >>= 1)) { + fillString += fillString; + if (times === 1) { + fillString += fillString; + } + } + return fillString.slice(0, fillLength) + str; + }; } /** @@ -293,50 +310,57 @@ if (!String.prototype.padStart) { * @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd * @returns {string} 返回格式化后的字符串 */ - function timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') { - let date - // 若传入时间为假值,则取当前时间 - if (!dateTime) { - date = new Date() - } - // 若为unix秒时间戳,则转为毫秒时间戳(逻辑有点奇怪,但不敢改,以保证历史兼容) - else if (/^\d{10}$/.test(dateTime?.toString().trim())) { - date = new Date(dateTime * 1000) - } - // 若用户传入字符串格式时间戳,new Date无法解析,需做兼容 - else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) { - date = new Date(Number(dateTime)) - } - // 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间 - // 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03' - else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) { - date = new Date(dateTime.replace(/-/g, '/')) - } - // 其他都认为符合 RFC 2822 规范 - else { - date = new Date(dateTime) - } - - const timeSource = { - 'y': date.getFullYear().toString(), // 年 - 'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月 - 'd': date.getDate().toString().padStart(2, '0'), // 日 - 'h': date.getHours().toString().padStart(2, '0'), // 时 - 'M': date.getMinutes().toString().padStart(2, '0'), // 分 - 's': date.getSeconds().toString().padStart(2, '0') // 秒 - // 有其他格式化字符需求可以继续添加,必须转化成字符串 - } - - for (const key in timeSource) { - const [ret] = new RegExp(`${key}+`).exec(formatStr) || [] - if (ret) { - // 年可能只需展示两位 - const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0 - formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex)) +function timeFormat(dateTime = null, formatStr = "yyyy-mm-dd") { + let date; + // 若传入时间为假值,则取当前时间 + if (!dateTime) { + date = new Date(); + } + // 若为unix秒时间戳,则转为毫秒时间戳(逻辑有点奇怪,但不敢改,以保证历史兼容) + else if (/^\d{10}$/.test(dateTime?.toString().trim())) { + date = new Date(dateTime * 1000); + } + // 若用户传入字符串格式时间戳,new Date无法解析,需做兼容 + else if (typeof dateTime === "string" && /^\d+$/.test(dateTime.trim())) { + date = new Date(Number(dateTime)); + } + // 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间 + // 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03' + else if ( + typeof dateTime === "string" && + dateTime.includes("-") && + !dateTime.includes("T") + ) { + date = new Date(dateTime.replace(/-/g, "/")); + } + // 其他都认为符合 RFC 2822 规范 + else { + date = new Date(dateTime); } - } - return formatStr + const timeSource = { + y: date.getFullYear().toString(), // 年 + m: (date.getMonth() + 1).toString().padStart(2, "0"), // 月 + d: date.getDate().toString().padStart(2, "0"), // 日 + h: date.getHours().toString().padStart(2, "0"), // 时 + M: date.getMinutes().toString().padStart(2, "0"), // 分 + s: date.getSeconds().toString().padStart(2, "0"), // 秒 + // 有其他格式化字符需求可以继续添加,必须转化成字符串 + }; + + for (const key in timeSource) { + const [ret] = new RegExp(`${key}+`).exec(formatStr) || []; + if (ret) { + // 年可能只需展示两位 + const beginIndex = key === "y" && ret.length === 2 ? 2 : 0; + formatStr = formatStr.replace( + ret, + timeSource[key].slice(beginIndex) + ); + } + } + + return formatStr; } /** @@ -347,41 +371,41 @@ if (!String.prototype.padStart) { * 如果为布尔值false,无论什么时间,都返回多久以前的格式 * @returns {string} 转化后的内容 */ -function timeFrom(timestamp = null, format = 'yyyy-mm-dd') { - if (timestamp == null) timestamp = Number(new Date()) - timestamp = parseInt(timestamp) - // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位) - if (timestamp.toString().length == 10) timestamp *= 1000 - let timer = (new Date()).getTime() - timestamp - timer = parseInt(timer / 1000) - // 如果小于5分钟,则返回"刚刚",其他以此类推 - let tips = '' - switch (true) { - case timer < 300: - tips = '刚刚' - break - case timer >= 300 && timer < 3600: - tips = `${parseInt(timer / 60)}分钟前` - break - case timer >= 3600 && timer < 86400: - tips = `${parseInt(timer / 3600)}小时前` - break - case timer >= 86400 && timer < 2592000: - tips = `${parseInt(timer / 86400)}天前` - break - default: - // 如果format为false,则无论什么时间戳,都显示xx之前 - if (format === false) { - if (timer >= 2592000 && timer < 365 * 86400) { - tips = `${parseInt(timer / (86400 * 30))}个月前` - } else { - tips = `${parseInt(timer / (86400 * 365))}年前` - } - } else { - tips = timeFormat(timestamp, format) - } - } - return tips +function timeFrom(timestamp = null, format = "yyyy-mm-dd") { + if (timestamp == null) timestamp = Number(new Date()); + timestamp = parseInt(timestamp); + // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位) + if (timestamp.toString().length == 10) timestamp *= 1000; + let timer = new Date().getTime() - timestamp; + timer = parseInt(timer / 1000); + // 如果小于5分钟,则返回"刚刚",其他以此类推 + let tips = ""; + switch (true) { + case timer < 300: + tips = "刚刚"; + break; + case timer >= 300 && timer < 3600: + tips = `${parseInt(timer / 60)}分钟前`; + break; + case timer >= 3600 && timer < 86400: + tips = `${parseInt(timer / 3600)}小时前`; + break; + case timer >= 86400 && timer < 2592000: + tips = `${parseInt(timer / 86400)}天前`; + break; + default: + // 如果format为false,则无论什么时间戳,都显示xx之前 + if (format === false) { + if (timer >= 2592000 && timer < 365 * 86400) { + tips = `${parseInt(timer / (86400 * 30))}个月前`; + } else { + tips = `${parseInt(timer / (86400 * 365))}年前`; + } + } else { + tips = timeFormat(timestamp, format); + } + } + return tips; } /** @@ -389,21 +413,21 @@ function timeFrom(timestamp = null, format = 'yyyy-mm-dd') { * @param String str 需要去除空格的字符串 * @param String pos both(左右)|left|right|all 默认both */ -function trim(str, pos = 'both') { - str = String(str) - if (pos == 'both') { - return str.replace(/^\s+|\s+$/g, '') - } - if (pos == 'left') { - return str.replace(/^\s*/, '') - } - if (pos == 'right') { - return str.replace(/(\s*$)/g, '') - } - if (pos == 'all') { - return str.replace(/\s+/g, '') - } - return str +function trim(str, pos = "both") { + str = String(str); + if (pos == "both") { + return str.replace(/^\s+|\s+$/g, ""); + } + if (pos == "left") { + return str.replace(/^\s*/, ""); + } + if (pos == "right") { + return str.replace(/(\s*$)/g, ""); + } + if (pos == "all") { + return str.replace(/\s+/g, ""); + } + return str; } /** @@ -412,56 +436,57 @@ function trim(str, pos = 'both') { * @param {Boolean} isPrefix,是否自动加上"?" * @param {string} arrayFormat 规则 indices|brackets|repeat|comma */ -function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') { - const prefix = isPrefix ? '?' : '' - const _result = [] - if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets' - for (const key in data) { - const value = data[key] - // 去掉为空的参数 - if (['', undefined, null].indexOf(value) >= 0) { - continue - } - // 如果值为数组,另行处理 - if (value.constructor === Array) { - // e.g. {ids: [1, 2, 3]} - switch (arrayFormat) { - case 'indices': - // 结果: ids[0]=1&ids[1]=2&ids[2]=3 - for (let i = 0; i < value.length; i++) { - _result.push(`${key}[${i}]=${value[i]}`) - } - break - case 'brackets': - // 结果: ids[]=1&ids[]=2&ids[]=3 - value.forEach((_value) => { - _result.push(`${key}[]=${_value}`) - }) - break - case 'repeat': - // 结果: ids=1&ids=2&ids=3 - value.forEach((_value) => { - _result.push(`${key}=${_value}`) - }) - break - case 'comma': - // 结果: ids=1,2,3 - let commaStr = '' - value.forEach((_value) => { - commaStr += (commaStr ? ',' : '') + _value - }) - _result.push(`${key}=${commaStr}`) - break - default: - value.forEach((_value) => { - _result.push(`${key}[]=${_value}`) - }) - } - } else { - _result.push(`${key}=${value}`) - } - } - return _result.length ? prefix + _result.join('&') : '' +function queryParams(data = {}, isPrefix = true, arrayFormat = "brackets") { + const prefix = isPrefix ? "?" : ""; + const _result = []; + if (["indices", "brackets", "repeat", "comma"].indexOf(arrayFormat) == -1) + arrayFormat = "brackets"; + for (const key in data) { + const value = data[key]; + // 去掉为空的参数 + if (["", undefined, null].indexOf(value) >= 0) { + continue; + } + // 如果值为数组,另行处理 + if (value.constructor === Array) { + // e.g. {ids: [1, 2, 3]} + switch (arrayFormat) { + case "indices": + // 结果: ids[0]=1&ids[1]=2&ids[2]=3 + for (let i = 0; i < value.length; i++) { + _result.push(`${key}[${i}]=${value[i]}`); + } + break; + case "brackets": + // 结果: ids[]=1&ids[]=2&ids[]=3 + value.forEach((_value) => { + _result.push(`${key}[]=${_value}`); + }); + break; + case "repeat": + // 结果: ids=1&ids=2&ids=3 + value.forEach((_value) => { + _result.push(`${key}=${_value}`); + }); + break; + case "comma": + // 结果: ids=1,2,3 + let commaStr = ""; + value.forEach((_value) => { + commaStr += (commaStr ? "," : "") + _value; + }); + _result.push(`${key}=${commaStr}`); + break; + default: + value.forEach((_value) => { + _result.push(`${key}[]=${_value}`); + }); + } + } else { + _result.push(`${key}=${value}`); + } + } + return _result.length ? prefix + _result.join("&") : ""; } /** @@ -470,11 +495,11 @@ function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') { * @param {Number} duration 提示的延迟时间,单位毫秒,默认:2000 */ function toast(title, duration = 2000) { - uni.showToast({ - title: String(title), - icon: 'none', - duration - }) + uni.showToast({ + title: String(title), + icon: "none", + duration, + }); } /** @@ -482,33 +507,34 @@ function toast(title, duration = 2000) { * @param {String} type 主题名称,primary|info|error|warning|success * @param {boolean} fill 是否使用fill填充实体的图标 */ -function type2icon(type = 'success', fill = false) { - // 如果非预置值,默认为success - if (['primary', 'info', 'error', 'warning', 'success'].indexOf(type) == -1) type = 'success' - let iconName = '' - // 目前(2019-12-12),info和primary使用同一个图标 - switch (type) { - case 'primary': - iconName = 'info-circle' - break - case 'info': - iconName = 'info-circle' - break - case 'error': - iconName = 'close-circle' - break - case 'warning': - iconName = 'error-circle' - break - case 'success': - iconName = 'checkmark-circle' - break - default: - iconName = 'checkmark-circle' - } - // 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的 - if (fill) iconName += '-fill' - return iconName +function type2icon(type = "success", fill = false) { + // 如果非预置值,默认为success + if (["primary", "info", "error", "warning", "success"].indexOf(type) == -1) + type = "success"; + let iconName = ""; + // 目前(2019-12-12),info和primary使用同一个图标 + switch (type) { + case "primary": + iconName = "info-circle"; + break; + case "info": + iconName = "info-circle"; + break; + case "error": + iconName = "close-circle"; + break; + case "warning": + iconName = "error-circle"; + break; + case "success": + iconName = "checkmark-circle"; + break; + default: + iconName = "checkmark-circle"; + } + // 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的 + if (fill) iconName += "-fill"; + return iconName; } /** @@ -519,25 +545,31 @@ function type2icon(type = 'success', fill = false) { * @param {string} thousandsSeparator 千分位符号 * @returns {string} 格式化后的数字 */ -function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') { - number = (`${number}`).replace(/[^0-9+-Ee.]/g, '') - const n = !isFinite(+number) ? 0 : +number - const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals) - const sep = (typeof thousandsSeparator === 'undefined') ? ',' : thousandsSeparator - const dec = (typeof decimalPoint === 'undefined') ? '.' : decimalPoint - let s = '' +function priceFormat( + number, + decimals = 0, + decimalPoint = ".", + thousandsSeparator = "," +) { + number = `${number}`.replace(/[^0-9+-Ee.]/g, ""); + const n = !isFinite(+number) ? 0 : +number; + const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals); + const sep = + typeof thousandsSeparator === "undefined" ? "," : thousandsSeparator; + const dec = typeof decimalPoint === "undefined" ? "." : decimalPoint; + let s = ""; - s = (prec ? round(n, prec) + '' : `${Math.round(n)}`).split('.') - const re = /(-?\d+)(\d{3})/ - while (re.test(s[0])) { - s[0] = s[0].replace(re, `$1${sep}$2`) - } + s = (prec ? round(n, prec) + "" : `${Math.round(n)}`).split("."); + const re = /(-?\d+)(\d{3})/; + while (re.test(s[0])) { + s[0] = s[0].replace(re, `$1${sep}$2`); + } - if ((s[1] || '').length < prec) { - s[1] = s[1] || '' - s[1] += new Array(prec - s[1].length + 1).join('0') - } - return s.join(dec) + if ((s[1] || "").length < prec) { + s[1] = s[1] || ""; + s[1] += new Array(prec - s[1].length + 1).join("0"); + } + return s.join(dec); } /** @@ -549,14 +581,14 @@ function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparato * @return {string|number} */ function getDuration(value, unit = true) { - const valueNum = parseInt(value) - if (unit) { - if (/s$/.test(value)) return value - return value > 30 ? `${value}ms` : `${value}s` - } - if (/ms$/.test(value)) return valueNum - if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000 - return valueNum + const valueNum = parseInt(value); + if (unit) { + if (/s$/.test(value)) return value; + return value > 30 ? `${value}ms` : `${value}s`; + } + if (/ms$/.test(value)) return valueNum; + if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000; + return valueNum; } /** @@ -564,7 +596,7 @@ function getDuration(value, unit = true) { * @param {String} value 需要补零的值 */ function padZero(value) { - return `00${value}`.slice(-2) + return `00${value}`.slice(-2); } /** @@ -573,13 +605,13 @@ function padZero(value) { * @param {*} event */ function formValidate(instance, event) { - const formItem = uni.$u.$parent.call(instance, 'u-form-item') - const form = uni.$u.$parent.call(instance, 'u-form') - // 如果发生变化的input或者textarea等,其父组件中有u-form-item或者u-form等,就执行form的validate方法 - // 同时将form-item的pros传递给form,让其进行精确对象验证 - if (formItem && form) { - form.validateField(formItem.prop, () => {}, event) - } + const formItem = uni.$u.$parent.call(instance, "u-form-item"); + const form = uni.$u.$parent.call(instance, "u-form"); + // 如果发生变化的input或者textarea等,其父组件中有u-form-item或者u-form等,就执行form的validate方法 + // 同时将form-item的pros传递给form,让其进行精确对象验证 + if (formItem && form) { + form.validateField(formItem.prop, () => {}, event); + } } /** @@ -589,24 +621,24 @@ function formValidate(instance, event) { * @returns {*} */ function getProperty(obj, key) { - if (!obj) { - return - } - if (typeof key !== 'string' || key === '') { - return '' - } - if (key.indexOf('.') !== -1) { - const keys = key.split('.') - let firstObj = obj[keys[0]] || {} + if (!obj) { + return; + } + if (typeof key !== "string" || key === "") { + return ""; + } + if (key.indexOf(".") !== -1) { + const keys = key.split("."); + let firstObj = obj[keys[0]] || {}; - for (let i = 1; i < keys.length; i++) { - if (firstObj) { - firstObj = firstObj[keys[i]] - } - } - return firstObj - } - return obj[key] + for (let i = 1; i < keys.length; i++) { + if (firstObj) { + firstObj = firstObj[keys[i]]; + } + } + return firstObj; + } + return obj[key]; } /** @@ -616,53 +648,53 @@ function getProperty(obj, key) { * @param {string} value 设置的值 */ function setProperty(obj, key, value) { - if (!obj) { - return - } - // 递归赋值 - const inFn = function(_obj, keys, v) { - // 最后一个属性key - if (keys.length === 1) { - _obj[keys[0]] = v - return - } - // 0~length-1个key - while (keys.length > 1) { - const k = keys[0] - if (!_obj[k] || (typeof _obj[k] !== 'object')) { - _obj[k] = {} - } - const key = keys.shift() - // 自调用判断是否存在属性,不存在则自动创建对象 - inFn(_obj[k], keys, v) - } - } + if (!obj) { + return; + } + // 递归赋值 + const inFn = function (_obj, keys, v) { + // 最后一个属性key + if (keys.length === 1) { + _obj[keys[0]] = v; + return; + } + // 0~length-1个key + while (keys.length > 1) { + const k = keys[0]; + if (!_obj[k] || typeof _obj[k] !== "object") { + _obj[k] = {}; + } + const key = keys.shift(); + // 自调用判断是否存在属性,不存在则自动创建对象 + inFn(_obj[k], keys, v); + } + }; - if (typeof key !== 'string' || key === '') { - - } else if (key.indexOf('.') !== -1) { // 支持多层级赋值操作 - const keys = key.split('.') - inFn(obj, keys, value) - } else { - obj[key] = value - } + if (typeof key !== "string" || key === "") { + } else if (key.indexOf(".") !== -1) { + // 支持多层级赋值操作 + const keys = key.split("."); + inFn(obj, keys, value); + } else { + obj[key] = value; + } } /** * @description 获取当前页面路径 */ function page() { - const pages = getCurrentPages() - // 某些特殊情况下(比如页面进行redirectTo时的一些时机),pages可能为空数组 - return `/${pages[pages.length - 1]?.route ?? ''}` + const pages = getCurrentPages(); + // 某些特殊情况下(比如页面进行redirectTo时的一些时机),pages可能为空数组 + return `/${pages[pages.length - 1]?.route ?? ""}`; } /** * @description 获取当前路由栈实例数组 */ function pages() { - const pages = getCurrentPages() - return pages + const pages = getCurrentPages(); + return pages; } /** @@ -670,9 +702,9 @@ function pages() { * @param back {number} [0] - 0或者负数,表示获取历史栈的哪一层,0表示获取当前页面实例,-1 表示获取上一个页面实例。默认0。 */ function getHistoryPage(back = 0) { - const pages = getCurrentPages() - const len = pages.length - return pages[len - 1 + back] + const pages = getCurrentPages(); + const len = pages.length; + return pages[len - 1 + back]; } /** @@ -682,50 +714,43 @@ function getHistoryPage(back = 0) { * @param {object} color 修改内置color属性 * @param {object} zIndex 修改内置zIndex属性 */ -function setConfig({ - props = {}, - config = {}, - color = {}, - zIndex = {} -}) { - const { - deepMerge, - } = uni.$u - uni.$u.config = deepMerge(uni.$u.config, config) - uni.$u.props = deepMerge(uni.$u.props, props) - uni.$u.color = deepMerge(uni.$u.color, color) - uni.$u.zIndex = deepMerge(uni.$u.zIndex, zIndex) +function setConfig({ props = {}, config = {}, color = {}, zIndex = {} }) { + const { deepMerge } = uni.$u; + uni.$u.config = deepMerge(uni.$u.config, config); + uni.$u.props = deepMerge(uni.$u.props, props); + uni.$u.color = deepMerge(uni.$u.color, color); + uni.$u.zIndex = deepMerge(uni.$u.zIndex, zIndex); } export default { - range, - getPx, - sleep, - os, - sys, - random, - guid, - $parent, - addStyle, - addUnit, - deepClone, - deepMerge, - error, - randomArray, - timeFormat, - timeFrom, - trim, - queryParams, - toast, - type2icon, - priceFormat, - getDuration, - padZero, - formValidate, - getProperty, - setProperty, - page, - pages, - getHistoryPage, - setConfig -} + range, + getPx, + sleep, + os, + sys, + random, + guid, + $parent, + addStyle, + addUnit, + deepClone, + deepMerge, + error, + randomArray, + timeFormat, + timeFrom, + trim, + queryParams, + toast, + type2icon, + priceFormat, + getDuration, + padZero, + formValidate, + getProperty, + setProperty, + page, + pages, + getHistoryPage, + setConfig, +}; diff --git a/uni_modules/uview-ui/libs/luch-request/core/Request.js b/uni_modules/uview-ui/libs/luch-request/core/Request.js index cc48566..dd21c90 100644 --- a/uni_modules/uview-ui/libs/luch-request/core/Request.js +++ b/uni_modules/uview-ui/libs/luch-request/core/Request.js @@ -11,98 +11,98 @@ * HBuilderX: beat-3.0.4 alpha-3.0.4 */ -import dispatchRequest from './dispatchRequest' -import InterceptorManager from './InterceptorManager' -import mergeConfig from './mergeConfig' -import defaults from './defaults' -import { isPlainObject } from '../utils' -import clone from '../utils/clone' +import dispatchRequest from "./dispatchRequest"; +import InterceptorManager from "./InterceptorManager"; +import mergeConfig from "./mergeConfig"; +import defaults from "./defaults"; +import { isPlainObject } from "../utils"; +import clone from "../utils/clone"; export default class Request { /** - * @param {Object} arg - 全局配置 - * @param {String} arg.baseURL - 全局根路径 - * @param {Object} arg.header - 全局header - * @param {String} arg.method = [GET|POST|PUT|DELETE|CONNECT|HEAD|OPTIONS|TRACE] - 全局默认请求方式 - * @param {String} arg.dataType = [json] - 全局默认的dataType - * @param {String} arg.responseType = [text|arraybuffer] - 全局默认的responseType。支付宝小程序不支持 - * @param {Object} arg.custom - 全局默认的自定义参数 - * @param {Number} arg.timeout - 全局默认的超时时间,单位 ms。默认60000。H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)、微信小程序(2.10.0)、支付宝小程序 - * @param {Boolean} arg.sslVerify - 全局默认的是否验证 ssl 证书。默认true.仅App安卓端支持(HBuilderX 2.3.3+) - * @param {Boolean} arg.withCredentials - 全局默认的跨域请求时是否携带凭证(cookies)。默认false。仅H5支持(HBuilderX 2.6.15+) - * @param {Boolean} arg.firstIpv4 - 全DNS解析时优先使用ipv4。默认false。仅 App-Android 支持 (HBuilderX 2.8.0+) - * @param {Function(statusCode):Boolean} arg.validateStatus - 全局默认的自定义验证器。默认statusCode >= 200 && statusCode < 300 - */ + * @param {Object} arg - 全局配置 + * @param {String} arg.baseURL - 全局根路径 + * @param {Object} arg.header - 全局header + * @param {String} arg.method = [GET|POST|PUT|DELETE|CONNECT|HEAD|OPTIONS|TRACE] - 全局默认请求方式 + * @param {String} arg.dataType = [json] - 全局默认的dataType + * @param {String} arg.responseType = [text|arraybuffer] - 全局默认的responseType。支付宝小程序不支持 + * @param {Object} arg.custom - 全局默认的自定义参数 + * @param {Number} arg.timeout - 全局默认的超时时间,单位 ms。默认60000。H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)、微信小程序(2.10.0)、支付宝小程序 + * @param {Boolean} arg.sslVerify - 全局默认的是否验证 ssl 证书。默认true.仅App安卓端支持(HBuilderX 2.3.3+) + * @param {Boolean} arg.withCredentials - 全局默认的跨域请求时是否携带凭证(cookies)。默认false。仅H5支持(HBuilderX 2.6.15+) + * @param {Boolean} arg.firstIpv4 - 全DNS解析时优先使用ipv4。默认false。仅 App-Android 支持 (HBuilderX 2.8.0+) + * @param {Function(statusCode):Boolean} arg.validateStatus - 全局默认的自定义验证器。默认statusCode >= 200 && statusCode < 300 + */ constructor(arg = {}) { if (!isPlainObject(arg)) { - arg = {} - console.warn('设置全局参数必须接收一个Object') + arg = {}; + // console.warn('设置全局参数必须接收一个Object') } - this.config = clone({ ...defaults, ...arg }) + this.config = clone({ ...defaults, ...arg }); this.interceptors = { request: new InterceptorManager(), - response: new InterceptorManager() - } + response: new InterceptorManager(), + }; } /** - * @Function - * @param {Request~setConfigCallback} f - 设置全局默认配置 - */ + * @Function + * @param {Request~setConfigCallback} f - 设置全局默认配置 + */ setConfig(f) { - this.config = f(this.config) + this.config = f(this.config); } middleware(config) { - config = mergeConfig(this.config, config) - const chain = [dispatchRequest, undefined] - let promise = Promise.resolve(config) + config = mergeConfig(this.config, config); + const chain = [dispatchRequest, undefined]; + let promise = Promise.resolve(config); this.interceptors.request.forEach((interceptor) => { - chain.unshift(interceptor.fulfilled, interceptor.rejected) - }) + chain.unshift(interceptor.fulfilled, interceptor.rejected); + }); this.interceptors.response.forEach((interceptor) => { - chain.push(interceptor.fulfilled, interceptor.rejected) - }) + chain.push(interceptor.fulfilled, interceptor.rejected); + }); while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()) + promise = promise.then(chain.shift(), chain.shift()); } - return promise + return promise; } /** - * @Function - * @param {Object} config - 请求配置项 - * @prop {String} options.url - 请求路径 - * @prop {Object} options.data - 请求参数 - * @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应的数据类型 - * @prop {Object} [options.dataType = config.dataType] - 如果设为 json,会尝试对返回的数据做一次 JSON.parse - * @prop {Object} [options.header = config.header] - 请求header - * @prop {Object} [options.method = config.method] - 请求方法 - * @returns {Promise} - */ + * @Function + * @param {Object} config - 请求配置项 + * @prop {String} options.url - 请求路径 + * @prop {Object} options.data - 请求参数 + * @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应的数据类型 + * @prop {Object} [options.dataType = config.dataType] - 如果设为 json,会尝试对返回的数据做一次 JSON.parse + * @prop {Object} [options.header = config.header] - 请求header + * @prop {Object} [options.method = config.method] - 请求方法 + * @returns {Promise} + */ request(config = {}) { - return this.middleware(config) + return this.middleware(config); } get(url, options = {}) { return this.middleware({ url, - method: 'GET', - ...options - }) + method: "GET", + ...options, + }); } post(url, data, options = {}) { return this.middleware({ url, data, - method: 'POST', - ...options - }) + method: "POST", + ...options, + }); } // #ifndef MP-ALIPAY @@ -110,9 +110,9 @@ export default class Request { return this.middleware({ url, data, - method: 'PUT', - ...options - }) + method: "PUT", + ...options, + }); } // #endif @@ -122,9 +122,9 @@ export default class Request { return this.middleware({ url, data, - method: 'DELETE', - ...options - }) + method: "DELETE", + ...options, + }); } // #endif @@ -134,9 +134,9 @@ export default class Request { return this.middleware({ url, data, - method: 'CONNECT', - ...options - }) + method: "CONNECT", + ...options, + }); } // #endif @@ -146,9 +146,9 @@ export default class Request { return this.middleware({ url, data, - method: 'HEAD', - ...options - }) + method: "HEAD", + ...options, + }); } // #endif @@ -158,9 +158,9 @@ export default class Request { return this.middleware({ url, data, - method: 'OPTIONS', - ...options - }) + method: "OPTIONS", + ...options, + }); } // #endif @@ -170,23 +170,23 @@ export default class Request { return this.middleware({ url, data, - method: 'TRACE', - ...options - }) + method: "TRACE", + ...options, + }); } // #endif upload(url, config = {}) { - config.url = url - config.method = 'UPLOAD' - return this.middleware(config) + config.url = url; + config.method = "UPLOAD"; + return this.middleware(config); } download(url, config = {}) { - config.url = url - config.method = 'DOWNLOAD' - return this.middleware(config) + config.url = url; + config.method = "DOWNLOAD"; + return this.middleware(config); } } diff --git a/uni_modules/uview-ui/libs/util/async-validator.js b/uni_modules/uview-ui/libs/util/async-validator.js index 9e114df..9e1e55a 100644 --- a/uni_modules/uview-ui/libs/util/async-validator.js +++ b/uni_modules/uview-ui/libs/util/async-validator.js @@ -1,264 +1,286 @@ function _extends() { - _extends = Object.assign || function (target) { - for (let i = 1; i < arguments.length; i++) { - const source = arguments[i] + _extends = + Object.assign || + function (target) { + for (let i = 1; i < arguments.length; i++) { + const source = arguments[i]; - for (const key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key] + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } } } - } - return target - } + return target; + }; - return _extends.apply(this, arguments) + return _extends.apply(this, arguments); } /* eslint no-console:0 */ -const formatRegExp = /%[sdj%]/g -let warning = function warning() {} // don't print warning message when in production env or node runtime +const formatRegExp = /%[sdj%]/g; +let warning = function warning() {}; // don't print warning message when in production env or node runtime -if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production' && typeof window - !== 'undefined' && typeof document !== 'undefined') { +if ( + typeof process !== "undefined" && + process.env && + process.env.NODE_ENV !== "production" && + typeof window !== "undefined" && + typeof document !== "undefined" +) { warning = function warning(type, errors) { - if (typeof console !== 'undefined' && console.warn) { - if (errors.every((e) => typeof e === 'string')) { - console.warn(type, errors) + if (typeof console !== "undefined" && console.warn) { + if (errors.every((e) => typeof e === "string")) { + // console.warn(type, errors) } } - } + }; } function convertFieldsError(errors) { - if (!errors || !errors.length) return null - const fields = {} + if (!errors || !errors.length) return null; + const fields = {}; errors.forEach((error) => { - const { field } = error - fields[field] = fields[field] || [] - fields[field].push(error) - }) - return fields + const { field } = error; + fields[field] = fields[field] || []; + fields[field].push(error); + }); + return fields; } function format() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key] + for ( + var _len = arguments.length, args = new Array(_len), _key = 0; + _key < _len; + _key++ + ) { + args[_key] = arguments[_key]; } - let i = 1 - const f = args[0] - const len = args.length + let i = 1; + const f = args[0]; + const len = args.length; - if (typeof f === 'function') { - return f.apply(null, args.slice(1)) + if (typeof f === "function") { + return f.apply(null, args.slice(1)); } - if (typeof f === 'string') { + if (typeof f === "string") { let str = String(f).replace(formatRegExp, (x) => { - if (x === '%%') { - return '%' + if (x === "%%") { + return "%"; } if (i >= len) { - return x + return x; } switch (x) { - case '%s': - return String(args[i++]) + case "%s": + return String(args[i++]); - case '%d': - return Number(args[i++]) + case "%d": + return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]) - } catch (_) { - return '[Circular]' - } + case "%j": + try { + return JSON.stringify(args[i++]); + } catch (_) { + return "[Circular]"; + } - break - - default: - return x + default: + return x; } - }) + }); for (let arg = args[i]; i < len; arg = args[++i]) { - str += ` ${arg}` + str += ` ${arg}`; } - return str + return str; } - return f + return f; } function isNativeStringType(type) { - return type === 'string' || type === 'url' || type === 'hex' || type === 'email' || type === 'pattern' + return ( + type === "string" || + type === "url" || + type === "hex" || + type === "email" || + type === "pattern" + ); } function isEmptyValue(value, type) { if (value === undefined || value === null) { - return true + return true; } - if (type === 'array' && Array.isArray(value) && !value.length) { - return true + if (type === "array" && Array.isArray(value) && !value.length) { + return true; } - if (isNativeStringType(type) && typeof value === 'string' && !value) { - return true + if (isNativeStringType(type) && typeof value === "string" && !value) { + return true; } - return false + return false; } function asyncParallelArray(arr, func, callback) { - const results = [] - let total = 0 - const arrLength = arr.length + const results = []; + let total = 0; + const arrLength = arr.length; function count(errors) { - results.push.apply(results, errors) - total++ + results.push.apply(results, errors); + total++; if (total === arrLength) { - callback(results) + callback(results); } } arr.forEach((a) => { - func(a, count) - }) + func(a, count); + }); } function asyncSerialArray(arr, func, callback) { - let index = 0 - const arrLength = arr.length + let index = 0; + const arrLength = arr.length; function next(errors) { if (errors && errors.length) { - callback(errors) - return + callback(errors); + return; } - const original = index - index += 1 + const original = index; + index += 1; if (original < arrLength) { - func(arr[original], next) + func(arr[original], next); } else { - callback([]) + callback([]); } } - next([]) + next([]); } function flattenObjArr(objArr) { - const ret = [] + const ret = []; Object.keys(objArr).forEach((k) => { - ret.push.apply(ret, objArr[k]) - }) - return ret + ret.push.apply(ret, objArr[k]); + }); + return ret; } function asyncMap(objArr, option, func, callback) { if (option.first) { const _pending = new Promise((resolve, reject) => { const next = function next(errors) { - callback(errors) - return errors.length ? reject({ - errors, - fields: convertFieldsError(errors) - }) : resolve() - } + callback(errors); + return errors.length + ? reject({ + errors, + fields: convertFieldsError(errors), + }) + : resolve(); + }; - const flattenArr = flattenObjArr(objArr) - asyncSerialArray(flattenArr, func, next) - }) + const flattenArr = flattenObjArr(objArr); + asyncSerialArray(flattenArr, func, next); + }); - _pending.catch((e) => e) + _pending.catch((e) => e); - return _pending + return _pending; } - let firstFields = option.firstFields || [] + let firstFields = option.firstFields || []; if (firstFields === true) { - firstFields = Object.keys(objArr) + firstFields = Object.keys(objArr); } - const objArrKeys = Object.keys(objArr) - const objArrLength = objArrKeys.length - let total = 0 - const results = [] + const objArrKeys = Object.keys(objArr); + const objArrLength = objArrKeys.length; + let total = 0; + const results = []; const pending = new Promise((resolve, reject) => { const next = function next(errors) { - results.push.apply(results, errors) - total++ + results.push.apply(results, errors); + total++; if (total === objArrLength) { - callback(results) - return results.length ? reject({ - errors: results, - fields: convertFieldsError(results) - }) : resolve() + callback(results); + return results.length + ? reject({ + errors: results, + fields: convertFieldsError(results), + }) + : resolve(); } - } + }; if (!objArrKeys.length) { - callback(results) - resolve() + callback(results); + resolve(); } objArrKeys.forEach((key) => { - const arr = objArr[key] + const arr = objArr[key]; if (firstFields.indexOf(key) !== -1) { - asyncSerialArray(arr, func, next) + asyncSerialArray(arr, func, next); } else { - asyncParallelArray(arr, func, next) + asyncParallelArray(arr, func, next); } - }) - }) - pending.catch((e) => e) - return pending + }); + }); + pending.catch((e) => e); + return pending; } function complementError(rule) { return function (oe) { if (oe && oe.message) { - oe.field = oe.field || rule.fullField - return oe + oe.field = oe.field || rule.fullField; + return oe; } return { - message: typeof oe === 'function' ? oe() : oe, - field: oe.field || rule.fullField - } - } + message: typeof oe === "function" ? oe() : oe, + field: oe.field || rule.fullField, + }; + }; } function deepMerge(target, source) { if (source) { for (const s in source) { if (source.hasOwnProperty(s)) { - const value = source[s] + const value = source[s]; - if (typeof value === 'object' && typeof target[s] === 'object') { - target[s] = { ...target[s], ...value } + if ( + typeof value === "object" && + typeof target[s] === "object" + ) { + target[s] = { ...target[s], ...value }; } else { - target[s] = value + target[s] = value; } } } } - return target + return target; } /** @@ -274,8 +296,12 @@ function deepMerge(target, source) { */ function required(rule, value, source, errors, options, type) { - if (rule.required && (!source.hasOwnProperty(rule.field) || isEmptyValue(value, type || rule.type))) { - errors.push(format(options.messages.required, rule.fullField)) + if ( + rule.required && + (!source.hasOwnProperty(rule.field) || + isEmptyValue(value, type || rule.type)) + ) { + errors.push(format(options.messages.required, rule.fullField)); } } @@ -292,8 +318,8 @@ function required(rule, value, source, errors, options, type) { */ function whitespace(rule, value, source, errors, options) { - if (/^\s+$/.test(value) || value === '') { - errors.push(format(options.messages.whitespace, rule.fullField)) + if (/^\s+$/.test(value) || value === "") { + errors.push(format(options.messages.whitespace, rule.fullField)); } } @@ -303,11 +329,11 @@ const pattern = { // http://emailregex.com/ email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, url: new RegExp( - '^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$', - 'i' + "^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$", + "i" ), - hex: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i -} + hex: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i, +}; var types = { integer: function integer(value) { return /^(-)?\d+$/.test(value); @@ -316,47 +342,54 @@ var types = { return /^(-)?\d+(\.\d+)?$/.test(value); }, array: function array(value) { - return Array.isArray(value) + return Array.isArray(value); }, regexp: function regexp(value) { if (value instanceof RegExp) { - return true + return true; } try { - return !!new RegExp(value) + return !!new RegExp(value); } catch (e) { - return false + return false; } }, date: function date(value) { - return typeof value.getTime === 'function' && typeof value.getMonth === 'function' && typeof value.getYear - === 'function' + return ( + typeof value.getTime === "function" && + typeof value.getMonth === "function" && + typeof value.getYear === "function" + ); }, number: function number(value) { if (isNaN(value)) { - return false + return false; } // 修改源码,将字符串数值先转为数值 - return typeof +value === 'number' + return typeof +value === "number"; }, object: function object(value) { - return typeof value === 'object' && !types.array(value) + return typeof value === "object" && !types.array(value); }, method: function method(value) { - return typeof value === 'function' + return typeof value === "function"; }, email: function email(value) { - return typeof value === 'string' && !!value.match(pattern.email) && value.length < 255 + return ( + typeof value === "string" && + !!value.match(pattern.email) && + value.length < 255 + ); }, url: function url(value) { - return typeof value === 'string' && !!value.match(pattern.url) + return typeof value === "string" && !!value.match(pattern.url); }, hex: function hex(value) { - return typeof value === 'string' && !!value.match(pattern.hex) - } -} + return typeof value === "string" && !!value.match(pattern.hex); + }, +}; /** * Rule for validating the type of a value. * @@ -371,19 +404,39 @@ var types = { function type(rule, value, source, errors, options) { if (rule.required && value === undefined) { - required(rule, value, source, errors, options) - return + required(rule, value, source, errors, options); + return; } - const custom = ['integer', 'float', 'array', 'regexp', 'object', 'method', 'email', 'number', 'date', 'url', 'hex'] - const ruleType = rule.type + const custom = [ + "integer", + "float", + "array", + "regexp", + "object", + "method", + "email", + "number", + "date", + "url", + "hex", + ]; + const ruleType = rule.type; if (custom.indexOf(ruleType) > -1) { if (!types[ruleType](value)) { - errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type)) + errors.push( + format( + options.messages.types[ruleType], + rule.fullField, + rule.type + ) + ); } // straight typeof check } else if (ruleType && typeof value !== rule.type) { - errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type)) + errors.push( + format(options.messages.types[ruleType], rule.fullField, rule.type) + ); } } @@ -400,54 +453,67 @@ function type(rule, value, source, errors, options) { */ function range(rule, value, source, errors, options) { - const len = typeof rule.len === 'number' - const min = typeof rule.min === 'number' - const max = typeof rule.max === 'number' // 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane) + const len = typeof rule.len === "number"; + const min = typeof rule.min === "number"; + const max = typeof rule.max === "number"; // 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane) - const spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g - let val = value - let key = null - const num = typeof value === 'number' - const str = typeof value === 'string' - const arr = Array.isArray(value) + const spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + let val = value; + let key = null; + const num = typeof value === "number"; + const str = typeof value === "string"; + const arr = Array.isArray(value); if (num) { - key = 'number' + key = "number"; } else if (str) { - key = 'string' + key = "string"; } else if (arr) { - key = 'array' + key = "array"; } // if the value is not of a supported type for range validation // the validation rule rule should use the // type property to also test for a particular type if (!key) { - return false + return false; } if (arr) { - val = value.length + val = value.length; } if (str) { // 处理码点大于U+010000的文字length属性不准确的bug,如"𠮷𠮷𠮷".lenght !== 3 - val = value.replace(spRegexp, '_').length + val = value.replace(spRegexp, "_").length; } if (len) { if (val !== rule.len) { - errors.push(format(options.messages[key].len, rule.fullField, rule.len)) + errors.push( + format(options.messages[key].len, rule.fullField, rule.len) + ); } } else if (min && !max && val < rule.min) { - errors.push(format(options.messages[key].min, rule.fullField, rule.min)) + errors.push( + format(options.messages[key].min, rule.fullField, rule.min) + ); } else if (max && !min && val > rule.max) { - errors.push(format(options.messages[key].max, rule.fullField, rule.max)) + errors.push( + format(options.messages[key].max, rule.fullField, rule.max) + ); } else if (min && max && (val < rule.min || val > rule.max)) { - errors.push(format(options.messages[key].range, rule.fullField, rule.min, rule.max)) + errors.push( + format( + options.messages[key].range, + rule.fullField, + rule.min, + rule.max + ) + ); } } -const ENUM = 'enum' +const ENUM = "enum"; /** * Rule for validating a value exists in an enumerable list. * @@ -461,10 +527,16 @@ const ENUM = 'enum' */ function enumerable(rule, value, source, errors, options) { - rule[ENUM] = Array.isArray(rule[ENUM]) ? rule[ENUM] : [] + rule[ENUM] = Array.isArray(rule[ENUM]) ? rule[ENUM] : []; if (rule[ENUM].indexOf(value) === -1) { - errors.push(format(options.messages[ENUM], rule.fullField, rule[ENUM].join(', '))) + errors.push( + format( + options.messages[ENUM], + rule.fullField, + rule[ENUM].join(", ") + ) + ); } } @@ -486,16 +558,30 @@ function pattern$1(rule, value, source, errors, options) { // if a RegExp instance is passed, reset `lastIndex` in case its `global` // flag is accidentally set to `true`, which in a validation scenario // is not necessary and the result might be misleading - rule.pattern.lastIndex = 0 + rule.pattern.lastIndex = 0; if (!rule.pattern.test(value)) { - errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern)) + errors.push( + format( + options.messages.pattern.mismatch, + rule.fullField, + value, + rule.pattern + ) + ); } - } else if (typeof rule.pattern === 'string') { - const _pattern = new RegExp(rule.pattern) + } else if (typeof rule.pattern === "string") { + const _pattern = new RegExp(rule.pattern); if (!_pattern.test(value)) { - errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern)) + errors.push( + format( + options.messages.pattern.mismatch, + rule.fullField, + value, + rule.pattern + ) + ); } } } @@ -507,8 +593,8 @@ const rules = { type, range, enum: enumerable, - pattern: pattern$1 -} + pattern: pattern$1, +}; /** * Performs validation for string types. @@ -522,28 +608,29 @@ const rules = { */ function string(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { - if (isEmptyValue(value, 'string') && !rule.required) { - return callback() + if (isEmptyValue(value, "string") && !rule.required) { + return callback(); } - rules.required(rule, value, source, errors, options, 'string') + rules.required(rule, value, source, errors, options, "string"); - if (!isEmptyValue(value, 'string')) { - rules.type(rule, value, source, errors, options) - rules.range(rule, value, source, errors, options) - rules.pattern(rule, value, source, errors, options) + if (!isEmptyValue(value, "string")) { + rules.type(rule, value, source, errors, options); + rules.range(rule, value, source, errors, options); + rules.pattern(rule, value, source, errors, options); if (rule.whitespace === true) { - rules.whitespace(rule, value, source, errors, options) + rules.whitespace(rule, value, source, errors, options); } } } - callback(errors) + callback(errors); } /** @@ -558,22 +645,23 @@ function string(rule, value, callback, source, options) { */ function method(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); if (value !== undefined) { - rules.type(rule, value, source, errors, options) + rules.type(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } /** @@ -588,27 +676,28 @@ function method(rule, value, callback, source, options) { */ function number(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { - if (value === '') { - value = undefined + if (value === "") { + value = undefined; } if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); if (value !== undefined) { - rules.type(rule, value, source, errors, options) - rules.range(rule, value, source, errors, options) + rules.type(rule, value, source, errors, options); + rules.range(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } /** @@ -623,22 +712,23 @@ function number(rule, value, callback, source, options) { */ function _boolean(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); if (value !== undefined) { - rules.type(rule, value, source, errors, options) + rules.type(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } /** @@ -653,22 +743,23 @@ function _boolean(rule, value, callback, source, options) { */ function regexp(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); if (!isEmptyValue(value)) { - rules.type(rule, value, source, errors, options) + rules.type(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } /** @@ -683,23 +774,24 @@ function regexp(rule, value, callback, source, options) { */ function integer(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); if (value !== undefined) { - rules.type(rule, value, source, errors, options) - rules.range(rule, value, source, errors, options) + rules.type(rule, value, source, errors, options); + rules.range(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } /** @@ -714,23 +806,24 @@ function integer(rule, value, callback, source, options) { */ function floatFn(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); if (value !== undefined) { - rules.type(rule, value, source, errors, options) - rules.range(rule, value, source, errors, options) + rules.type(rule, value, source, errors, options); + rules.range(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } /** @@ -745,23 +838,24 @@ function floatFn(rule, value, callback, source, options) { */ function array(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { - if (isEmptyValue(value, 'array') && !rule.required) { - return callback() + if (isEmptyValue(value, "array") && !rule.required) { + return callback(); } - rules.required(rule, value, source, errors, options, 'array') + rules.required(rule, value, source, errors, options, "array"); - if (!isEmptyValue(value, 'array')) { - rules.type(rule, value, source, errors, options) - rules.range(rule, value, source, errors, options) + if (!isEmptyValue(value, "array")) { + rules.type(rule, value, source, errors, options); + rules.range(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } /** @@ -776,25 +870,26 @@ function array(rule, value, callback, source, options) { */ function object(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); if (value !== undefined) { - rules.type(rule, value, source, errors, options) + rules.type(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } -const ENUM$1 = 'enum' +const ENUM$1 = "enum"; /** * Validates an enumerable list. * @@ -807,22 +902,23 @@ const ENUM$1 = 'enum' */ function enumerable$1(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); if (value !== undefined) { - rules[ENUM$1](rule, value, source, errors, options) + rules[ENUM$1](rule, value, source, errors, options); } } - callback(errors) + callback(errors); } /** @@ -840,80 +936,89 @@ function enumerable$1(rule, value, callback, source, options) { */ function pattern$2(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { - if (isEmptyValue(value, 'string') && !rule.required) { - return callback() + if (isEmptyValue(value, "string") && !rule.required) { + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); - if (!isEmptyValue(value, 'string')) { - rules.pattern(rule, value, source, errors, options) + if (!isEmptyValue(value, "string")) { + rules.pattern(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } function date(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); if (!isEmptyValue(value)) { - let dateObject + let dateObject; - if (typeof value === 'number') { - dateObject = new Date(value) + if (typeof value === "number") { + dateObject = new Date(value); } else { - dateObject = value + dateObject = value; } - rules.type(rule, dateObject, source, errors, options) + rules.type(rule, dateObject, source, errors, options); if (dateObject) { - rules.range(rule, dateObject.getTime(), source, errors, options) + rules.range( + rule, + dateObject.getTime(), + source, + errors, + options + ); } } } - callback(errors) + callback(errors); } function required$1(rule, value, callback, source, options) { - const errors = [] - const type = Array.isArray(value) ? 'array' : typeof value - rules.required(rule, value, source, errors, options, type) - callback(errors) + const errors = []; + const type = Array.isArray(value) ? "array" : typeof value; + rules.required(rule, value, source, errors, options, type); + callback(errors); } function type$1(rule, value, callback, source, options) { - const ruleType = rule.type - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const ruleType = rule.type; + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value, ruleType) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options, ruleType) + rules.required(rule, value, source, errors, options, ruleType); if (!isEmptyValue(value, ruleType)) { - rules.type(rule, value, source, errors, options) + rules.type(rule, value, source, errors, options); } } - callback(errors) + callback(errors); } /** @@ -928,18 +1033,19 @@ function type$1(rule, value, callback, source, options) { */ function any(rule, value, callback, source, options) { - const errors = [] - const validate = rule.required || !rule.required && source.hasOwnProperty(rule.field) + const errors = []; + const validate = + rule.required || (!rule.required && source.hasOwnProperty(rule.field)); if (validate) { if (isEmptyValue(value) && !rule.required) { - return callback() + return callback(); } - rules.required(rule, value, source, errors, options) + rules.required(rule, value, source, errors, options); } - callback(errors) + callback(errors); } const validators = { @@ -959,64 +1065,64 @@ const validators = { hex: type$1, email: type$1, required: required$1, - any -} + any, +}; function newMessages() { return { - default: 'Validation error on field %s', - required: '%s is required', - enum: '%s must be one of %s', - whitespace: '%s cannot be empty', + default: "Validation error on field %s", + required: "%s is required", + enum: "%s must be one of %s", + whitespace: "%s cannot be empty", date: { - format: '%s date %s is invalid for format %s', - parse: '%s date could not be parsed, %s is invalid ', - invalid: '%s date %s is invalid' + format: "%s date %s is invalid for format %s", + parse: "%s date could not be parsed, %s is invalid ", + invalid: "%s date %s is invalid", }, types: { - string: '%s is not a %s', - method: '%s is not a %s (function)', - array: '%s is not an %s', - object: '%s is not an %s', - number: '%s is not a %s', - date: '%s is not a %s', - boolean: '%s is not a %s', - integer: '%s is not an %s', - float: '%s is not a %s', - regexp: '%s is not a valid %s', - email: '%s is not a valid %s', - url: '%s is not a valid %s', - hex: '%s is not a valid %s' + string: "%s is not a %s", + method: "%s is not a %s (function)", + array: "%s is not an %s", + object: "%s is not an %s", + number: "%s is not a %s", + date: "%s is not a %s", + boolean: "%s is not a %s", + integer: "%s is not an %s", + float: "%s is not a %s", + regexp: "%s is not a valid %s", + email: "%s is not a valid %s", + url: "%s is not a valid %s", + hex: "%s is not a valid %s", }, string: { - len: '%s must be exactly %s characters', - min: '%s must be at least %s characters', - max: '%s cannot be longer than %s characters', - range: '%s must be between %s and %s characters' + len: "%s must be exactly %s characters", + min: "%s must be at least %s characters", + max: "%s cannot be longer than %s characters", + range: "%s must be between %s and %s characters", }, number: { - len: '%s must equal %s', - min: '%s cannot be less than %s', - max: '%s cannot be greater than %s', - range: '%s must be between %s and %s' + len: "%s must equal %s", + min: "%s cannot be less than %s", + max: "%s cannot be greater than %s", + range: "%s must be between %s and %s", }, array: { - len: '%s must be exactly %s in length', - min: '%s cannot be less than %s in length', - max: '%s cannot be greater than %s in length', - range: '%s must be between %s and %s in length' + len: "%s must be exactly %s in length", + min: "%s cannot be less than %s in length", + max: "%s cannot be greater than %s in length", + range: "%s must be between %s and %s in length", }, pattern: { - mismatch: '%s value %s does not match pattern %s' + mismatch: "%s value %s does not match pattern %s", }, clone: function clone() { - const cloned = JSON.parse(JSON.stringify(this)) - cloned.clone = this.clone - return cloned - } - } + const cloned = JSON.parse(JSON.stringify(this)); + cloned.clone = this.clone; + return cloned; + }, + }; } -const messages = newMessages() +const messages = newMessages(); /** * Encapsulates a validation schema. @@ -1026,318 +1132,367 @@ const messages = newMessages() */ function Schema(descriptor) { - this.rules = null - this._messages = messages - this.define(descriptor) + this.rules = null; + this._messages = messages; + this.define(descriptor); } Schema.prototype = { messages: function messages(_messages) { if (_messages) { - this._messages = deepMerge(newMessages(), _messages) + this._messages = deepMerge(newMessages(), _messages); } - return this._messages + return this._messages; }, define: function define(rules) { if (!rules) { - throw new Error('Cannot configure a schema with no rules') + throw new Error("Cannot configure a schema with no rules"); } - if (typeof rules !== 'object' || Array.isArray(rules)) { - throw new Error('Rules must be an object') + if (typeof rules !== "object" || Array.isArray(rules)) { + throw new Error("Rules must be an object"); } - this.rules = {} - let z - let item + this.rules = {}; + let z; + let item; for (z in rules) { if (rules.hasOwnProperty(z)) { - item = rules[z] - this.rules[z] = Array.isArray(item) ? item : [item] + item = rules[z]; + this.rules[z] = Array.isArray(item) ? item : [item]; } } }, validate: function validate(source_, o, oc) { - const _this = this + const _this = this; if (o === void 0) { - o = {} + o = {}; } if (oc === void 0) { - oc = function oc() {} + oc = function oc() {}; } - let source = source_ - let options = o - let callback = oc + let source = source_; + let options = o; + let callback = oc; - if (typeof options === 'function') { - callback = options - options = {} + if (typeof options === "function") { + callback = options; + options = {}; } if (!this.rules || Object.keys(this.rules).length === 0) { if (callback) { - callback() + callback(); } - return Promise.resolve() + return Promise.resolve(); } function complete(results) { - let i - let errors = [] - let fields = {} + let i; + let errors = []; + let fields = {}; function add(e) { if (Array.isArray(e)) { - let _errors + let _errors; - errors = (_errors = errors).concat.apply(_errors, e) + errors = (_errors = errors).concat.apply(_errors, e); } else { - errors.push(e) + errors.push(e); } } for (i = 0; i < results.length; i++) { - add(results[i]) + add(results[i]); } if (!errors.length) { - errors = null - fields = null + errors = null; + fields = null; } else { - fields = convertFieldsError(errors) + fields = convertFieldsError(errors); } - callback(errors, fields) + callback(errors, fields); } if (options.messages) { - let messages$1 = this.messages() + let messages$1 = this.messages(); if (messages$1 === messages) { - messages$1 = newMessages() + messages$1 = newMessages(); } - deepMerge(messages$1, options.messages) - options.messages = messages$1 + deepMerge(messages$1, options.messages); + options.messages = messages$1; } else { - options.messages = this.messages() + options.messages = this.messages(); } - let arr - let value - const series = {} - const keys = options.keys || Object.keys(this.rules) + let arr; + let value; + const series = {}; + const keys = options.keys || Object.keys(this.rules); keys.forEach((z) => { - arr = _this.rules[z] - value = source[z] + arr = _this.rules[z]; + value = source[z]; arr.forEach((r) => { - let rule = r + let rule = r; - if (typeof rule.transform === 'function') { + if (typeof rule.transform === "function") { if (source === source_) { - source = { ...source } + source = { ...source }; } - value = source[z] = rule.transform(value) + value = source[z] = rule.transform(value); } - if (typeof rule === 'function') { + if (typeof rule === "function") { rule = { - validator: rule - } + validator: rule, + }; } else { - rule = { ...rule } + rule = { ...rule }; } - rule.validator = _this.getValidationMethod(rule) - rule.field = z - rule.fullField = rule.fullField || z - rule.type = _this.getType(rule) + rule.validator = _this.getValidationMethod(rule); + rule.field = z; + rule.fullField = rule.fullField || z; + rule.type = _this.getType(rule); if (!rule.validator) { - return + return; } - series[z] = series[z] || [] + series[z] = series[z] || []; series[z].push({ rule, value, source, - field: z - }) - }) - }) - const errorFields = {} - return asyncMap(series, options, (data, doIt) => { - const { rule } = data - let deep = (rule.type === 'object' || rule.type === 'array') && (typeof rule.fields === 'object' || typeof rule.defaultField - === 'object') - deep = deep && (rule.required || !rule.required && data.value) - rule.field = data.field + field: z, + }); + }); + }); + const errorFields = {}; + return asyncMap( + series, + options, + (data, doIt) => { + const { rule } = data; + let deep = + (rule.type === "object" || rule.type === "array") && + (typeof rule.fields === "object" || + typeof rule.defaultField === "object"); + deep = + deep && (rule.required || (!rule.required && data.value)); + rule.field = data.field; - function addFullfield(key, schema) { - return { ...schema, fullField: `${rule.fullField}.${key}` } - } - - function cb(e) { - if (e === void 0) { - e = [] + function addFullfield(key, schema) { + return { ...schema, fullField: `${rule.fullField}.${key}` }; } - let errors = e - - if (!Array.isArray(errors)) { - errors = [errors] - } - - if (!options.suppressWarning && errors.length) { - Schema.warning('async-validator:', errors) - } - - if (errors.length && rule.message) { - errors = [].concat(rule.message) - } - - errors = errors.map(complementError(rule)) - - if (options.first && errors.length) { - errorFields[rule.field] = 1 - return doIt(errors) - } - - if (!deep) { - doIt(errors) - } else { - // if rule is required but the target object - // does not exist fail at the rule level and don't - // go deeper - if (rule.required && !data.value) { - if (rule.message) { - errors = [].concat(rule.message).map(complementError(rule)) - } else if (options.error) { - errors = [options.error(rule, format(options.messages.required, rule.field))] - } else { - errors = [] - } - - return doIt(errors) + function cb(e) { + if (e === void 0) { + e = []; } - let fieldsSchema = {} + let errors = e; - if (rule.defaultField) { - for (const k in data.value) { - if (data.value.hasOwnProperty(k)) { - fieldsSchema[k] = rule.defaultField + if (!Array.isArray(errors)) { + errors = [errors]; + } + + if (!options.suppressWarning && errors.length) { + Schema.warning("async-validator:", errors); + } + + if (errors.length && rule.message) { + errors = [].concat(rule.message); + } + + errors = errors.map(complementError(rule)); + + if (options.first && errors.length) { + errorFields[rule.field] = 1; + return doIt(errors); + } + + if (!deep) { + doIt(errors); + } else { + // if rule is required but the target object + // does not exist fail at the rule level and don't + // go deeper + if (rule.required && !data.value) { + if (rule.message) { + errors = [] + .concat(rule.message) + .map(complementError(rule)); + } else if (options.error) { + errors = [ + options.error( + rule, + format( + options.messages.required, + rule.field + ) + ), + ]; + } else { + errors = []; + } + + return doIt(errors); + } + + let fieldsSchema = {}; + + if (rule.defaultField) { + for (const k in data.value) { + if (data.value.hasOwnProperty(k)) { + fieldsSchema[k] = rule.defaultField; + } } } - } - fieldsSchema = { ...fieldsSchema, ...data.rule.fields } + fieldsSchema = { ...fieldsSchema, ...data.rule.fields }; - for (const f in fieldsSchema) { - if (fieldsSchema.hasOwnProperty(f)) { - const fieldSchema = Array.isArray(fieldsSchema[f]) ? fieldsSchema[f] : [fieldsSchema[f]] - fieldsSchema[f] = fieldSchema.map(addFullfield.bind(null, f)) - } - } - - const schema = new Schema(fieldsSchema) - schema.messages(options.messages) - - if (data.rule.options) { - data.rule.options.messages = options.messages - data.rule.options.error = options.error - } - - schema.validate(data.value, data.rule.options || options, (errs) => { - const finalErrors = [] - - if (errors && errors.length) { - finalErrors.push.apply(finalErrors, errors) + for (const f in fieldsSchema) { + if (fieldsSchema.hasOwnProperty(f)) { + const fieldSchema = Array.isArray( + fieldsSchema[f] + ) + ? fieldsSchema[f] + : [fieldsSchema[f]]; + fieldsSchema[f] = fieldSchema.map( + addFullfield.bind(null, f) + ); + } } - if (errs && errs.length) { - finalErrors.push.apply(finalErrors, errs) + const schema = new Schema(fieldsSchema); + schema.messages(options.messages); + + if (data.rule.options) { + data.rule.options.messages = options.messages; + data.rule.options.error = options.error; } - doIt(finalErrors.length ? finalErrors : null) - }) + schema.validate( + data.value, + data.rule.options || options, + (errs) => { + const finalErrors = []; + + if (errors && errors.length) { + finalErrors.push.apply(finalErrors, errors); + } + + if (errs && errs.length) { + finalErrors.push.apply(finalErrors, errs); + } + + doIt(finalErrors.length ? finalErrors : null); + } + ); + } } - } - let res + let res; - if (rule.asyncValidator) { - res = rule.asyncValidator(rule, data.value, cb, data.source, options) - } else if (rule.validator) { - res = rule.validator(rule, data.value, cb, data.source, options) + if (rule.asyncValidator) { + res = rule.asyncValidator( + rule, + data.value, + cb, + data.source, + options + ); + } else if (rule.validator) { + res = rule.validator( + rule, + data.value, + cb, + data.source, + options + ); - if (res === true) { - cb() - } else if (res === false) { - cb(rule.message || `${rule.field} fails`) - } else if (res instanceof Array) { - cb(res) - } else if (res instanceof Error) { - cb(res.message) + if (res === true) { + cb(); + } else if (res === false) { + cb(rule.message || `${rule.field} fails`); + } else if (res instanceof Array) { + cb(res); + } else if (res instanceof Error) { + cb(res.message); + } } - } - if (res && res.then) { - res.then(() => cb(), (e) => cb(e)) + if (res && res.then) { + res.then( + () => cb(), + (e) => cb(e) + ); + } + }, + (results) => { + complete(results); } - }, (results) => { - complete(results) - }) + ); }, getType: function getType(rule) { if (rule.type === undefined && rule.pattern instanceof RegExp) { - rule.type = 'pattern' + rule.type = "pattern"; } - if (typeof rule.validator !== 'function' && rule.type && !validators.hasOwnProperty(rule.type)) { - throw new Error(format('Unknown rule type %s', rule.type)) + if ( + typeof rule.validator !== "function" && + rule.type && + !validators.hasOwnProperty(rule.type) + ) { + throw new Error(format("Unknown rule type %s", rule.type)); } - return rule.type || 'string' + return rule.type || "string"; }, getValidationMethod: function getValidationMethod(rule) { - if (typeof rule.validator === 'function') { - return rule.validator + if (typeof rule.validator === "function") { + return rule.validator; } - const keys = Object.keys(rule) - const messageIndex = keys.indexOf('message') + const keys = Object.keys(rule); + const messageIndex = keys.indexOf("message"); if (messageIndex !== -1) { - keys.splice(messageIndex, 1) + keys.splice(messageIndex, 1); } - if (keys.length === 1 && keys[0] === 'required') { - return validators.required + if (keys.length === 1 && keys[0] === "required") { + return validators.required; } - return validators[this.getType(rule)] || false - } -} + return validators[this.getType(rule)] || false; + }, +}; Schema.register = function register(type, validator) { - if (typeof validator !== 'function') { - throw new Error('Cannot register a validator by type, validator is not a function') + if (typeof validator !== "function") { + throw new Error( + "Cannot register a validator by type, validator is not a function" + ); } - validators[type] = validator -} + validators[type] = validator; +}; -Schema.warning = warning -Schema.messages = messages +Schema.warning = warning; +Schema.messages = messages; -export default Schema +export default Schema; // # sourceMappingURL=index.js.map diff --git a/utils/mcaptcha.js b/utils/mcaptcha.js index bf40790..84ead76 100644 --- a/utils/mcaptcha.js +++ b/utils/mcaptcha.js @@ -3,7 +3,7 @@ export class Mcaptcha { constructor(options) { this.options = options; - this.fontSize = options.height * 3 / 6; + this.fontSize = (options.height * 3) / 6; this.init(); this.refresh(); } @@ -13,17 +13,80 @@ export class Mcaptcha { this.ctx.setFillStyle(this.randomColor(180, 240)); } refresh() { - var code = ''; - var txtArr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + var code = ""; + var txtArr = [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + ]; for (var i = 0; i < 4; i++) { code += txtArr[this.randomNum(0, txtArr.length)]; } this.options.createCodeImg = code; - let arr = (code + '').split(''); + let arr = (code + "").split(""); if (arr.length === 0) { - arr = ['e', 'r', 'r', 'o', 'r']; - }; - let offsetLeft = this.options.width * 0.6 / (arr.length - 1); + arr = ["e", "r", "r", "o", "r"]; + } + let offsetLeft = (this.options.width * 0.6) / (arr.length - 1); let marginLeft = this.options.width * 0.2; arr.forEach((item, index) => { this.ctx.setFillStyle(this.randomColor(0, 180)); @@ -32,22 +95,34 @@ export class Mcaptcha { let dis = offsetLeft * index + marginLeft - size * 0.3; let deg = this.randomNum(-30, 30); this.ctx.translate(dis, this.options.height * 0.5); - this.ctx.rotate(deg * Math.PI / 180); + this.ctx.rotate((deg * Math.PI) / 180); this.ctx.fillText(item, 0, 0); - this.ctx.rotate(-deg * Math.PI / 180); + this.ctx.rotate((-deg * Math.PI) / 180); this.ctx.translate(-dis, -this.options.height * 0.5); - }) + }); for (var i = 0; i < 4; i++) { this.ctx.strokeStyle = this.randomColor(40, 180); this.ctx.beginPath(); - this.ctx.moveTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height)); - this.ctx.lineTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height)); + this.ctx.moveTo( + this.randomNum(0, this.options.width), + this.randomNum(0, this.options.height) + ); + this.ctx.lineTo( + this.randomNum(0, this.options.width), + this.randomNum(0, this.options.height) + ); this.ctx.stroke(); } for (var i = 0; i < this.options.width / 4; i++) { this.ctx.fillStyle = this.randomColor(0, 255); this.ctx.beginPath(); - this.ctx.arc(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height), 1, 0, 2 * Math.PI); + this.ctx.arc( + this.randomNum(0, this.options.width), + this.randomNum(0, this.options.height), + 1, + 0, + 2 * Math.PI + ); this.ctx.fill(); } this.ctx.draw(); @@ -55,8 +130,8 @@ export class Mcaptcha { validate(code) { var code = code.toLowerCase(); var v_code = this.options.createCodeImg.toLowerCase(); - console.log(code) - console.log(v_code.substring(v_code.length - 4)) + // console.log(code) + // console.log(v_code.substring(v_code.length - 4)) if (code == v_code.substring(v_code.length - 4)) { return true; } else { @@ -72,4 +147,4 @@ export class Mcaptcha { let b = this.randomNum(min, max); return "rgb(" + r + "," + g + "," + b + ")"; } -} \ No newline at end of file +}