审计代码优化

This commit is contained in:
BianLzhaoMin 2024-08-30 17:45:46 +08:00
parent f00b9310bd
commit 8cfbf163c0
7 changed files with 1478 additions and 1222 deletions

View File

@ -6,9 +6,9 @@
*/ */
export const debounce = function (func, wait = 1000, immediate = true) { export const debounce = function (func, wait = 1000, immediate = true) {
let timer; let timer;
console.log(1); // console.log(1);
return function () { return function () {
console.log(123); // console.log(123);
let context = this, let context = this,
args = arguments; args = arguments;
if (timer) clearTimeout(timer); if (timer) clearTimeout(timer);
@ -21,10 +21,10 @@ export const debounce = function(func, wait = 1000, immediate = true) {
} else { } else {
timer = setTimeout(() => { timer = setTimeout(() => {
func.apply(context, args); func.apply(context, args);
}, wait) }, wait);
}
}
} }
};
};
/** /**
* @desc 函数节流 * @desc 函数节流
* @param func 函数 * @param func 函数
@ -48,9 +48,9 @@ export const throttle = (func, wait = 1000, type = 1) => {
if (!timeout) { if (!timeout) {
timeout = setTimeout(() => { timeout = setTimeout(() => {
timeout = null; timeout = null;
func.apply(context, args) func.apply(context, args);
}, wait) }, wait);
}
}
} }
} }
};
};

View File

@ -1,34 +1,28 @@
// 此版本发布于2023-03-27 // 此版本发布于2023-03-27
const version = '2.0.36' const version = "2.0.36";
// 开发环境才提示,生产环境不会提示 // 开发环境才提示,生产环境不会提示
if (process.env.NODE_ENV === 'development') { 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;'); // 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 { export default {
v: version, v: version,
version, version,
// 主题名称 // 主题名称
type: [ type: ["primary", "success", "info", "error", "warning"],
'primary',
'success',
'info',
'error',
'warning'
],
// 颜色部分本来可以通过scss的:export导出供js使用但是奈何nvue不支持 // 颜色部分本来可以通过scss的:export导出供js使用但是奈何nvue不支持
color: { color: {
'u-primary': '#2979ff', "u-primary": "#2979ff",
'u-warning': '#ff9900', "u-warning": "#ff9900",
'u-success': '#19be6b', "u-success": "#19be6b",
'u-error': '#fa3534', "u-error": "#fa3534",
'u-info': '#909399', "u-info": "#909399",
'u-main-color': '#303133', "u-main-color": "#303133",
'u-content-color': '#606266', "u-content-color": "#606266",
'u-tips-color': '#909399', "u-tips-color": "#909399",
'u-light-color': '#c0c4cc' "u-light-color": "#c0c4cc",
}, },
// 默认单位可以通过配置为rpx那么在用于传入组件大小参数为数值时就默认为rpx // 默认单位可以通过配置为rpx那么在用于传入组件大小参数为数值时就默认为rpx
unit: 'px' unit: "px",
} };

View File

@ -17,7 +17,7 @@ function strip(num, precision = 15) {
function digitLength(num) { function digitLength(num) {
// Get digit length of e // Get digit length of e
const eSplit = num.toString().split(/[eE]/); const eSplit = num.toString().split(/[eE]/);
const len = (eSplit[0].split('.')[1] || '').length - +(eSplit[1] || 0); const len = (eSplit[0].split(".")[1] || "").length - +(eSplit[1] || 0);
return len > 0 ? len : 0; return len > 0 ? len : 0;
} }
@ -27,8 +27,8 @@ function digitLength(num) {
* @param {*number} num 输入数 * @param {*number} num 输入数
*/ */
function float2Fixed(num) { function float2Fixed(num) {
if (num.toString().indexOf('e') === -1) { if (num.toString().indexOf("e") === -1) {
return Number(num.toString().replace('.', '')); return Number(num.toString().replace(".", ""));
} }
const dLen = digitLength(num); const dLen = digitLength(num);
return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num); return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num);
@ -42,7 +42,7 @@ function float2Fixed(num) {
function checkBoundary(num) { function checkBoundary(num) {
if (_boundaryCheckingState) { if (_boundaryCheckingState) {
if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) { if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
console.warn(`${num} 超出了精度限制,结果可能不正确`); // console.warn(`${num} 超出了精度限制,结果可能不正确`);
} }
} }
} }
@ -95,7 +95,10 @@ export function plus(...nums) {
const [num1, num2] = nums; const [num1, num2] = nums;
// 取最大的小数位 // 取最大的小数位
const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2))); const baseNum = Math.pow(
10,
Math.max(digitLength(num1), digitLength(num2))
);
// 把小数都转为整数然后再计算 // 把小数都转为整数然后再计算
return (times(num1, baseNum) + times(num2, baseNum)) / baseNum; return (times(num1, baseNum) + times(num2, baseNum)) / baseNum;
} }
@ -110,7 +113,10 @@ export function minus(...nums) {
} }
const [num1, num2] = nums; const [num1, num2] = nums;
const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2))); const baseNum = Math.pow(
10,
Math.max(digitLength(num1), digitLength(num2))
);
return (times(num1, baseNum) - times(num2, baseNum)) / baseNum; return (times(num1, baseNum) - times(num2, baseNum)) / baseNum;
} }
@ -129,7 +135,10 @@ export function divide(...nums) {
checkBoundary(num1Changed); checkBoundary(num1Changed);
checkBoundary(num2Changed); checkBoundary(num2Changed);
// 重要这里必须用strip进行修正 // 重要这里必须用strip进行修正
return times(num1Changed / num2Changed, strip(Math.pow(10, digitLength(num2) - digitLength(num1)))); return times(
num1Changed / num2Changed,
strip(Math.pow(10, digitLength(num2) - digitLength(num1)))
);
} }
/** /**
@ -155,7 +164,6 @@ export function enableBoundaryChecking(flag = true) {
_boundaryCheckingState = flag; _boundaryCheckingState = flag;
} }
export default { export default {
times, times,
plus, plus,
@ -164,4 +172,3 @@ export default {
round, round,
enableBoundaryChecking, enableBoundaryChecking,
}; };

View File

@ -1,5 +1,5 @@
import test from './test.js' import test from "./test.js";
import { round } from './digit.js' import { round } from "./digit.js";
/** /**
* @description 如果value小于min取min如果value大于max取max * @description 如果value小于min取min如果value大于max取max
* @param {number} min * @param {number} min
@ -7,7 +7,7 @@ import { round } from './digit.js'
* @param {number} value * @param {number} value
*/ */
function range(min = 0, max = 0, value = 0) { 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)));
} }
/** /**
@ -18,13 +18,15 @@ function range(min = 0, max = 0, value = 0) {
*/ */
function getPx(value, unit = false) { function getPx(value, unit = false) {
if (test.number(value)) { if (test.number(value)) {
return unit ? `${value}px` : Number(value) return unit ? `${value}px` : Number(value);
} }
// 如果带有rpx先取出其数值部分再转为px值 // 如果带有rpx先取出其数值部分再转为px值
if (/(rpx|upx)$/.test(value)) { if (/(rpx|upx)$/.test(value)) {
return unit ? `${uni.upx2px(parseInt(value))}px` : Number(uni.upx2px(parseInt(value))) return unit
? `${uni.upx2px(parseInt(value))}px`
: Number(uni.upx2px(parseInt(value)));
} }
return unit ? `${parseInt(value)}px` : parseInt(value) return unit ? `${parseInt(value)}px` : parseInt(value);
} }
/** /**
@ -35,9 +37,9 @@ function getPx(value, unit = false) {
function sleep(value = 30) { function sleep(value = 30) {
return new Promise((resolve) => { return new Promise((resolve) => {
setTimeout(() => { setTimeout(() => {
resolve() resolve();
}, value) }, value);
}) });
} }
/** /**
* @description 运行期判断平台 * @description 运行期判断平台
@ -45,14 +47,14 @@ function sleep(value = 30) {
* @link 运行期判断平台 https://uniapp.dcloud.io/frame?id=判断平台 * @link 运行期判断平台 https://uniapp.dcloud.io/frame?id=判断平台
*/ */
function os() { function os() {
return uni.getSystemInfoSync().platform.toLowerCase() return uni.getSystemInfoSync().platform.toLowerCase();
} }
/** /**
* @description 获取系统信息同步接口 * @description 获取系统信息同步接口
* @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync * @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync
*/ */
function sys() { function sys() {
return uni.getSystemInfoSync() return uni.getSystemInfoSync();
} }
/** /**
@ -62,10 +64,10 @@ function sys() {
*/ */
function random(min, max) { function random(min, max) {
if (min >= 0 && max > 0 && max >= min) { if (min >= 0 && max > 0 && max >= min) {
const gab = max - min + 1 const gab = max - min + 1;
return Math.floor(Math.random() * gab + min) return Math.floor(Math.random() * gab + min);
} }
return 0 return 0;
} }
/** /**
@ -74,32 +76,36 @@ function random(min, max) {
* @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制 * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
*/ */
function guid(len = 32, firstU = true, radix = null) { function guid(len = 32, firstU = true, radix = null) {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') const chars =
const uuid = [] "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
radix = radix || chars.length ""
);
const uuid = [];
radix = radix || chars.length;
if (len) { if (len) {
// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位 // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix] for (let i = 0; i < len; i++)
uuid[i] = chars[0 | (Math.random() * radix)];
} else { } else {
let r let r;
// rfc4122标准要求返回的uuid中,某些位为固定的字符 // rfc4122标准要求返回的uuid中,某些位为固定的字符
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-' uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
uuid[14] = '4' uuid[14] = "4";
for (let i = 0; i < 36; i++) { for (let i = 0; i < 36; i++) {
if (!uuid[i]) { if (!uuid[i]) {
r = 0 | Math.random() * 16 r = 0 | (Math.random() * 16);
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r] uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
} }
} }
} }
// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
if (firstU) { if (firstU) {
uuid.shift() uuid.shift();
return `u${uuid.join('')}` return `u${uuid.join("")}`;
} }
return uuid.join('') return uuid.join("");
} }
/** /**
@ -110,18 +116,18 @@ function guid(len = 32, firstU = true, radix = null) {
* @param {string|undefined} name 父组件的参数名 * @param {string|undefined} name 父组件的参数名
*/ */
function $parent(name = undefined) { function $parent(name = undefined) {
let parent = this.$parent let parent = this.$parent;
// 通过while历遍这里主要是为了H5需要多层解析的问题 // 通过while历遍这里主要是为了H5需要多层解析的问题
while (parent) { while (parent) {
// 父组件 // 父组件
if (parent.$options && parent.$options.name !== name) { if (parent.$options && parent.$options.name !== name) {
// 如果组件的name不相等继续上一级寻找 // 如果组件的name不相等继续上一级寻找
parent = parent.$parent parent = parent.$parent;
} else { } else {
return parent return parent;
} }
} }
return false return false;
} }
/** /**
@ -131,38 +137,41 @@ function $parent(name = undefined) {
* @param {String} target 转换的目的object-转为对象string-转为字符串 * @param {String} target 转换的目的object-转为对象string-转为字符串
* @returns {object|string} * @returns {object|string}
*/ */
function addStyle(customStyle, target = 'object') { function addStyle(customStyle, target = "object") {
// 字符串转字符串,对象转对象情形,直接返回 // 字符串转字符串,对象转对象情形,直接返回
if (test.empty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' && if (
typeof(customStyle) === 'string') { test.empty(customStyle) ||
return customStyle (typeof customStyle === "object" && target === "object") ||
(target === "string" && typeof customStyle === "string")
) {
return customStyle;
} }
// 字符串转对象 // 字符串转对象
if (target === 'object') { if (target === "object") {
// 去除字符串样式中的两端空格(中间的空格不能去掉比如padding: 20px 0如果去掉了就错了),空格是无用的 // 去除字符串样式中的两端空格(中间的空格不能去掉比如padding: 20px 0如果去掉了就错了),空格是无用的
customStyle = trim(customStyle) customStyle = trim(customStyle);
// 根据";"将字符串转为数组形式 // 根据";"将字符串转为数组形式
const styleArray = customStyle.split(';') const styleArray = customStyle.split(";");
const style = {} const style = {};
// 历遍数组,拼接成对象 // 历遍数组,拼接成对象
for (let i = 0; i < styleArray.length; i++) { for (let i = 0; i < styleArray.length; i++) {
// 'font-size:20px;color:red;',如此最后字符串有";"的话会导致styleArray最后一个元素为空字符串这里需要过滤 // 'font-size:20px;color:red;',如此最后字符串有";"的话会导致styleArray最后一个元素为空字符串这里需要过滤
if (styleArray[i]) { if (styleArray[i]) {
const item = styleArray[i].split(':') const item = styleArray[i].split(":");
style[trim(item[0])] = trim(item[1]) style[trim(item[0])] = trim(item[1]);
} }
} }
return style return style;
} }
// 这里为对象转字符串形式 // 这里为对象转字符串形式
let string = '' let string = "";
for (const i in customStyle) { for (const i in customStyle) {
// 驼峰转为中划线的形式否则css内联样式无法识别驼峰样式属性名 // 驼峰转为中划线的形式否则css内联样式无法识别驼峰样式属性名
const key = i.replace(/([A-Z])/g, '-$1').toLowerCase() const key = i.replace(/([A-Z])/g, "-$1").toLowerCase();
string += `${key}:${customStyle[i]};` string += `${key}:${customStyle[i]};`;
} }
// 去除两端空格 // 去除两端空格
return trim(string) return trim(string);
} }
/** /**
@ -170,10 +179,10 @@ function addStyle(customStyle, target = 'object') {
* @param {string|number} value 需要添加单位的值 * @param {string|number} value 需要添加单位的值
* @param {string} unit 添加的单位名 比如px * @param {string} unit 添加的单位名 比如px
*/ */
function addUnit(value = 'auto', unit = uni?.$u?.config?.unit ?? 'px') { function addUnit(value = "auto", unit = uni?.$u?.config?.unit ?? "px") {
value = String(value) value = String(value);
// 用uView内置验证规则中的number判断是否为数值 // 用uView内置验证规则中的number判断是否为数值
return test.number(value) ? `${value}${unit}` : value return test.number(value) ? `${value}${unit}` : value;
} }
/** /**
@ -183,7 +192,7 @@ function addUnit(value = 'auto', unit = uni?.$u?.config?.unit ?? 'px') {
* @returns {*} 克隆后的对象或者原值不是对象 * @returns {*} 克隆后的对象或者原值不是对象
*/ */
function deepClone(obj, cache = new WeakMap()) { function deepClone(obj, cache = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj; if (obj === null || typeof obj !== "object") return obj;
if (cache.has(obj)) return cache.get(obj); if (cache.has(obj)) return cache.get(obj);
let clone; let clone;
if (obj instanceof Date) { if (obj instanceof Date) {
@ -191,12 +200,14 @@ function deepClone(obj, cache = new WeakMap()) {
} else if (obj instanceof RegExp) { } else if (obj instanceof RegExp) {
clone = new RegExp(obj); clone = new RegExp(obj);
} else if (obj instanceof Map) { } else if (obj instanceof Map) {
clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value, cache)])); clone = new Map(
Array.from(obj, ([key, value]) => [key, deepClone(value, cache)])
);
} else if (obj instanceof Set) { } else if (obj instanceof Set) {
clone = new Set(Array.from(obj, value => deepClone(value, cache))); clone = new Set(Array.from(obj, (value) => deepClone(value, cache)));
} else if (Array.isArray(obj)) { } else if (Array.isArray(obj)) {
clone = obj.map(value => deepClone(value, cache)); clone = obj.map((value) => deepClone(value, cache));
} else if (Object.prototype.toString.call(obj) === '[object Object]') { } else if (Object.prototype.toString.call(obj) === "[object Object]") {
clone = Object.create(Object.getPrototypeOf(obj)); clone = Object.create(Object.getPrototypeOf(obj));
cache.set(obj, clone); cache.set(obj, clone);
for (const [key, value] of Object.entries(obj)) { for (const [key, value] of Object.entries(obj)) {
@ -216,9 +227,17 @@ function deepClone(obj, cache = new WeakMap()) {
* @returns {object|boolean} 深度合并后的对象或者false入参有不是对象 * @returns {object|boolean} 深度合并后的对象或者false入参有不是对象
*/ */
function deepMerge(target = {}, source = {}) { function deepMerge(target = {}, source = {}) {
target = deepClone(target) target = deepClone(target);
if (typeof target !== 'object' || target === null || typeof source !== 'object' || source === null) return target; if (
const merged = Array.isArray(target) ? target.slice() : Object.assign({}, target); 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) { for (const prop in source) {
if (!source.hasOwnProperty(prop)) continue; if (!source.hasOwnProperty(prop)) continue;
const sourceValue = source[prop]; const sourceValue = source[prop];
@ -231,7 +250,7 @@ function deepMerge(target = {}, source = {}) {
merged[prop] = new Map(sourceValue); merged[prop] = new Map(sourceValue);
} else if (sourceValue instanceof Set) { } else if (sourceValue instanceof Set) {
merged[prop] = new Set(sourceValue); merged[prop] = new Set(sourceValue);
} else if (typeof sourceValue === 'object' && sourceValue !== null) { } else if (typeof sourceValue === "object" && sourceValue !== null) {
merged[prop] = deepMerge(targetValue, sourceValue); merged[prop] = deepMerge(targetValue, sourceValue);
} else { } else {
merged[prop] = sourceValue; merged[prop] = sourceValue;
@ -246,8 +265,8 @@ function deepMerge(target = {}, source = {}) {
*/ */
function error(err) { function error(err) {
// 开发环境才提示,生产环境不会提示 // 开发环境才提示,生产环境不会提示
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === "development") {
console.error(`uView提示${err}`) // console.error(`uView提示${err}`)
} }
} }
@ -258,33 +277,31 @@ function error(err) {
*/ */
function randomArray(array = []) { function randomArray(array = []) {
// 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0 // 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0
return array.sort(() => Math.random() - 0.5) return array.sort(() => Math.random() - 0.5);
} }
// padStart 的 polyfill因为某些机型或情况还无法支持es7的padStart比如电脑版的微信小程序 // padStart 的 polyfill因为某些机型或情况还无法支持es7的padStart比如电脑版的微信小程序
// 所以这里做一个兼容polyfill的兼容处理 // 所以这里做一个兼容polyfill的兼容处理
if (!String.prototype.padStart) { if (!String.prototype.padStart) {
// 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解 // 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解
String.prototype.padStart = function(maxLength, fillString = ' ') { String.prototype.padStart = function (maxLength, fillString = " ") {
if (Object.prototype.toString.call(fillString) !== '[object String]') { if (Object.prototype.toString.call(fillString) !== "[object String]") {
throw new TypeError( throw new TypeError("fillString must be String");
'fillString must be String'
)
} }
const str = this const str = this;
// 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉 // 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉
if (str.length >= maxLength) return String(str) if (str.length >= maxLength) return String(str);
const fillLength = maxLength - str.length const fillLength = maxLength - str.length;
let times = Math.ceil(fillLength / fillString.length) let times = Math.ceil(fillLength / fillString.length);
while (times >>= 1) { while ((times >>= 1)) {
fillString += fillString fillString += fillString;
if (times === 1) { if (times === 1) {
fillString += fillString fillString += fillString;
} }
} }
return fillString.slice(0, fillLength) + str 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 * @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
* @returns {string} 返回格式化后的字符串 * @returns {string} 返回格式化后的字符串
*/ */
function timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') { function timeFormat(dateTime = null, formatStr = "yyyy-mm-dd") {
let date let date;
// 若传入时间为假值,则取当前时间 // 若传入时间为假值,则取当前时间
if (!dateTime) { if (!dateTime) {
date = new Date() date = new Date();
} }
// 若为unix秒时间戳则转为毫秒时间戳逻辑有点奇怪但不敢改以保证历史兼容 // 若为unix秒时间戳则转为毫秒时间戳逻辑有点奇怪但不敢改以保证历史兼容
else if (/^\d{10}$/.test(dateTime?.toString().trim())) { else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
date = new Date(dateTime * 1000) date = new Date(dateTime * 1000);
} }
// 若用户传入字符串格式时间戳new Date无法解析需做兼容 // 若用户传入字符串格式时间戳new Date无法解析需做兼容
else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) { else if (typeof dateTime === "string" && /^\d+$/.test(dateTime.trim())) {
date = new Date(Number(dateTime)) date = new Date(Number(dateTime));
} }
// 处理平台性差异在Safari/Webkit中new Date仅支持/作为分割符的字符串时间 // 处理平台性差异在Safari/Webkit中new Date仅支持/作为分割符的字符串时间
// 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03' // 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03'
else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) { else if (
date = new Date(dateTime.replace(/-/g, '/')) typeof dateTime === "string" &&
dateTime.includes("-") &&
!dateTime.includes("T")
) {
date = new Date(dateTime.replace(/-/g, "/"));
} }
// 其他都认为符合 RFC 2822 规范 // 其他都认为符合 RFC 2822 规范
else { else {
date = new Date(dateTime) date = new Date(dateTime);
} }
const timeSource = { const timeSource = {
'y': date.getFullYear().toString(), // 年 y: date.getFullYear().toString(), // 年
'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月 m: (date.getMonth() + 1).toString().padStart(2, "0"), // 月
'd': date.getDate().toString().padStart(2, '0'), // 日 d: date.getDate().toString().padStart(2, "0"), // 日
'h': date.getHours().toString().padStart(2, '0'), // 时 h: date.getHours().toString().padStart(2, "0"), // 时
'M': date.getMinutes().toString().padStart(2, '0'), // 分 M: date.getMinutes().toString().padStart(2, "0"), // 分
's': date.getSeconds().toString().padStart(2, '0') // 秒 s: date.getSeconds().toString().padStart(2, "0"), // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串 // 有其他格式化字符需求可以继续添加,必须转化成字符串
} };
for (const key in timeSource) { for (const key in timeSource) {
const [ret] = new RegExp(`${key}+`).exec(formatStr) || [] const [ret] = new RegExp(`${key}+`).exec(formatStr) || [];
if (ret) { if (ret) {
// 年可能只需展示两位 // 年可能只需展示两位
const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0 const beginIndex = key === "y" && ret.length === 2 ? 2 : 0;
formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex)) formatStr = formatStr.replace(
ret,
timeSource[key].slice(beginIndex)
);
} }
} }
return formatStr return formatStr;
} }
/** /**
@ -347,41 +371,41 @@ if (!String.prototype.padStart) {
* 如果为布尔值false无论什么时间都返回多久以前的格式 * 如果为布尔值false无论什么时间都返回多久以前的格式
* @returns {string} 转化后的内容 * @returns {string} 转化后的内容
*/ */
function timeFrom(timestamp = null, format = 'yyyy-mm-dd') { function timeFrom(timestamp = null, format = "yyyy-mm-dd") {
if (timestamp == null) timestamp = Number(new Date()) if (timestamp == null) timestamp = Number(new Date());
timestamp = parseInt(timestamp) timestamp = parseInt(timestamp);
// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位) // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
if (timestamp.toString().length == 10) timestamp *= 1000 if (timestamp.toString().length == 10) timestamp *= 1000;
let timer = (new Date()).getTime() - timestamp let timer = new Date().getTime() - timestamp;
timer = parseInt(timer / 1000) timer = parseInt(timer / 1000);
// 如果小于5分钟,则返回"刚刚",其他以此类推 // 如果小于5分钟,则返回"刚刚",其他以此类推
let tips = '' let tips = "";
switch (true) { switch (true) {
case timer < 300: case timer < 300:
tips = '刚刚' tips = "刚刚";
break break;
case timer >= 300 && timer < 3600: case timer >= 300 && timer < 3600:
tips = `${parseInt(timer / 60)}分钟前` tips = `${parseInt(timer / 60)}分钟前`;
break break;
case timer >= 3600 && timer < 86400: case timer >= 3600 && timer < 86400:
tips = `${parseInt(timer / 3600)}小时前` tips = `${parseInt(timer / 3600)}小时前`;
break break;
case timer >= 86400 && timer < 2592000: case timer >= 86400 && timer < 2592000:
tips = `${parseInt(timer / 86400)}天前` tips = `${parseInt(timer / 86400)}天前`;
break break;
default: default:
// 如果format为false则无论什么时间戳都显示xx之前 // 如果format为false则无论什么时间戳都显示xx之前
if (format === false) { if (format === false) {
if (timer >= 2592000 && timer < 365 * 86400) { if (timer >= 2592000 && timer < 365 * 86400) {
tips = `${parseInt(timer / (86400 * 30))}个月前` tips = `${parseInt(timer / (86400 * 30))}个月前`;
} else { } else {
tips = `${parseInt(timer / (86400 * 365))}年前` tips = `${parseInt(timer / (86400 * 365))}年前`;
} }
} else { } else {
tips = timeFormat(timestamp, format) tips = timeFormat(timestamp, format);
} }
} }
return tips return tips;
} }
/** /**
@ -389,21 +413,21 @@ function timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
* @param String str 需要去除空格的字符串 * @param String str 需要去除空格的字符串
* @param String pos both(左右)|left|right|all 默认both * @param String pos both(左右)|left|right|all 默认both
*/ */
function trim(str, pos = 'both') { function trim(str, pos = "both") {
str = String(str) str = String(str);
if (pos == 'both') { if (pos == "both") {
return str.replace(/^\s+|\s+$/g, '') return str.replace(/^\s+|\s+$/g, "");
} }
if (pos == 'left') { if (pos == "left") {
return str.replace(/^\s*/, '') return str.replace(/^\s*/, "");
} }
if (pos == 'right') { if (pos == "right") {
return str.replace(/(\s*$)/g, '') return str.replace(/(\s*$)/g, "");
} }
if (pos == 'all') { if (pos == "all") {
return str.replace(/\s+/g, '') return str.replace(/\s+/g, "");
} }
return str return str;
} }
/** /**
@ -412,56 +436,57 @@ function trim(str, pos = 'both') {
* @param {Boolean} isPrefix,是否自动加上"?" * @param {Boolean} isPrefix,是否自动加上"?"
* @param {string} arrayFormat 规则 indices|brackets|repeat|comma * @param {string} arrayFormat 规则 indices|brackets|repeat|comma
*/ */
function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') { function queryParams(data = {}, isPrefix = true, arrayFormat = "brackets") {
const prefix = isPrefix ? '?' : '' const prefix = isPrefix ? "?" : "";
const _result = [] const _result = [];
if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets' if (["indices", "brackets", "repeat", "comma"].indexOf(arrayFormat) == -1)
arrayFormat = "brackets";
for (const key in data) { for (const key in data) {
const value = data[key] const value = data[key];
// 去掉为空的参数 // 去掉为空的参数
if (['', undefined, null].indexOf(value) >= 0) { if (["", undefined, null].indexOf(value) >= 0) {
continue continue;
} }
// 如果值为数组,另行处理 // 如果值为数组,另行处理
if (value.constructor === Array) { if (value.constructor === Array) {
// e.g. {ids: [1, 2, 3]} // e.g. {ids: [1, 2, 3]}
switch (arrayFormat) { switch (arrayFormat) {
case 'indices': case "indices":
// 结果: ids[0]=1&ids[1]=2&ids[2]=3 // 结果: ids[0]=1&ids[1]=2&ids[2]=3
for (let i = 0; i < value.length; i++) { for (let i = 0; i < value.length; i++) {
_result.push(`${key}[${i}]=${value[i]}`) _result.push(`${key}[${i}]=${value[i]}`);
} }
break break;
case 'brackets': case "brackets":
// 结果: ids[]=1&ids[]=2&ids[]=3 // 结果: ids[]=1&ids[]=2&ids[]=3
value.forEach((_value) => { value.forEach((_value) => {
_result.push(`${key}[]=${_value}`) _result.push(`${key}[]=${_value}`);
}) });
break break;
case 'repeat': case "repeat":
// 结果: ids=1&ids=2&ids=3 // 结果: ids=1&ids=2&ids=3
value.forEach((_value) => { value.forEach((_value) => {
_result.push(`${key}=${_value}`) _result.push(`${key}=${_value}`);
}) });
break break;
case 'comma': case "comma":
// 结果: ids=1,2,3 // 结果: ids=1,2,3
let commaStr = '' let commaStr = "";
value.forEach((_value) => { value.forEach((_value) => {
commaStr += (commaStr ? ',' : '') + _value commaStr += (commaStr ? "," : "") + _value;
}) });
_result.push(`${key}=${commaStr}`) _result.push(`${key}=${commaStr}`);
break break;
default: default:
value.forEach((_value) => { value.forEach((_value) => {
_result.push(`${key}[]=${_value}`) _result.push(`${key}[]=${_value}`);
}) });
} }
} else { } else {
_result.push(`${key}=${value}`) _result.push(`${key}=${value}`);
} }
} }
return _result.length ? prefix + _result.join('&') : '' return _result.length ? prefix + _result.join("&") : "";
} }
/** /**
@ -472,9 +497,9 @@ function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
function toast(title, duration = 2000) { function toast(title, duration = 2000) {
uni.showToast({ uni.showToast({
title: String(title), title: String(title),
icon: 'none', icon: "none",
duration duration,
}) });
} }
/** /**
@ -482,33 +507,34 @@ function toast(title, duration = 2000) {
* @param {String} type 主题名称,primary|info|error|warning|success * @param {String} type 主题名称,primary|info|error|warning|success
* @param {boolean} fill 是否使用fill填充实体的图标 * @param {boolean} fill 是否使用fill填充实体的图标
*/ */
function type2icon(type = 'success', fill = false) { function type2icon(type = "success", fill = false) {
// 如果非预置值,默认为success // 如果非预置值,默认为success
if (['primary', 'info', 'error', 'warning', 'success'].indexOf(type) == -1) type = 'success' if (["primary", "info", "error", "warning", "success"].indexOf(type) == -1)
let iconName = '' type = "success";
let iconName = "";
// 目前(2019-12-12),info和primary使用同一个图标 // 目前(2019-12-12),info和primary使用同一个图标
switch (type) { switch (type) {
case 'primary': case "primary":
iconName = 'info-circle' iconName = "info-circle";
break break;
case 'info': case "info":
iconName = 'info-circle' iconName = "info-circle";
break break;
case 'error': case "error":
iconName = 'close-circle' iconName = "close-circle";
break break;
case 'warning': case "warning":
iconName = 'error-circle' iconName = "error-circle";
break break;
case 'success': case "success":
iconName = 'checkmark-circle' iconName = "checkmark-circle";
break break;
default: default:
iconName = 'checkmark-circle' iconName = "checkmark-circle";
} }
// 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的 // 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的
if (fill) iconName += '-fill' if (fill) iconName += "-fill";
return iconName return iconName;
} }
/** /**
@ -519,25 +545,31 @@ function type2icon(type = 'success', fill = false) {
* @param {string} thousandsSeparator 千分位符号 * @param {string} thousandsSeparator 千分位符号
* @returns {string} 格式化后的数字 * @returns {string} 格式化后的数字
*/ */
function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') { function priceFormat(
number = (`${number}`).replace(/[^0-9+-Ee.]/g, '') number,
const n = !isFinite(+number) ? 0 : +number decimals = 0,
const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals) decimalPoint = ".",
const sep = (typeof thousandsSeparator === 'undefined') ? ',' : thousandsSeparator thousandsSeparator = ","
const dec = (typeof decimalPoint === 'undefined') ? '.' : decimalPoint ) {
let s = '' 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('.') s = (prec ? round(n, prec) + "" : `${Math.round(n)}`).split(".");
const re = /(-?\d+)(\d{3})/ const re = /(-?\d+)(\d{3})/;
while (re.test(s[0])) { while (re.test(s[0])) {
s[0] = s[0].replace(re, `$1${sep}$2`) s[0] = s[0].replace(re, `$1${sep}$2`);
} }
if ((s[1] || '').length < prec) { if ((s[1] || "").length < prec) {
s[1] = s[1] || '' s[1] = s[1] || "";
s[1] += new Array(prec - s[1].length + 1).join('0') s[1] += new Array(prec - s[1].length + 1).join("0");
} }
return s.join(dec) return s.join(dec);
} }
/** /**
@ -549,14 +581,14 @@ function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparato
* @return {string|number} * @return {string|number}
*/ */
function getDuration(value, unit = true) { function getDuration(value, unit = true) {
const valueNum = parseInt(value) const valueNum = parseInt(value);
if (unit) { if (unit) {
if (/s$/.test(value)) return value if (/s$/.test(value)) return value;
return value > 30 ? `${value}ms` : `${value}s` return value > 30 ? `${value}ms` : `${value}s`;
} }
if (/ms$/.test(value)) return valueNum if (/ms$/.test(value)) return valueNum;
if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000 if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000;
return valueNum return valueNum;
} }
/** /**
@ -564,7 +596,7 @@ function getDuration(value, unit = true) {
* @param {String} value 需要补零的值 * @param {String} value 需要补零的值
*/ */
function padZero(value) { function padZero(value) {
return `00${value}`.slice(-2) return `00${value}`.slice(-2);
} }
/** /**
@ -573,12 +605,12 @@ function padZero(value) {
* @param {*} event * @param {*} event
*/ */
function formValidate(instance, event) { function formValidate(instance, event) {
const formItem = uni.$u.$parent.call(instance, 'u-form-item') const formItem = uni.$u.$parent.call(instance, "u-form-item");
const form = uni.$u.$parent.call(instance, 'u-form') const form = uni.$u.$parent.call(instance, "u-form");
// 如果发生变化的input或者textarea等其父组件中有u-form-item或者u-form等就执行form的validate方法 // 如果发生变化的input或者textarea等其父组件中有u-form-item或者u-form等就执行form的validate方法
// 同时将form-item的pros传递给form让其进行精确对象验证 // 同时将form-item的pros传递给form让其进行精确对象验证
if (formItem && form) { if (formItem && form) {
form.validateField(formItem.prop, () => {}, event) form.validateField(formItem.prop, () => {}, event);
} }
} }
@ -590,23 +622,23 @@ function formValidate(instance, event) {
*/ */
function getProperty(obj, key) { function getProperty(obj, key) {
if (!obj) { if (!obj) {
return return;
} }
if (typeof key !== 'string' || key === '') { if (typeof key !== "string" || key === "") {
return '' return "";
} }
if (key.indexOf('.') !== -1) { if (key.indexOf(".") !== -1) {
const keys = key.split('.') const keys = key.split(".");
let firstObj = obj[keys[0]] || {} let firstObj = obj[keys[0]] || {};
for (let i = 1; i < keys.length; i++) { for (let i = 1; i < keys.length; i++) {
if (firstObj) { if (firstObj) {
firstObj = firstObj[keys[i]] firstObj = firstObj[keys[i]];
} }
} }
return firstObj return firstObj;
} }
return obj[key] return obj[key];
} }
/** /**
@ -617,34 +649,34 @@ function getProperty(obj, key) {
*/ */
function setProperty(obj, key, value) { function setProperty(obj, key, value) {
if (!obj) { if (!obj) {
return return;
} }
// 递归赋值 // 递归赋值
const inFn = function (_obj, keys, v) { const inFn = function (_obj, keys, v) {
// 最后一个属性key // 最后一个属性key
if (keys.length === 1) { if (keys.length === 1) {
_obj[keys[0]] = v _obj[keys[0]] = v;
return return;
} }
// 0~length-1个key // 0~length-1个key
while (keys.length > 1) { while (keys.length > 1) {
const k = keys[0] const k = keys[0];
if (!_obj[k] || (typeof _obj[k] !== 'object')) { if (!_obj[k] || typeof _obj[k] !== "object") {
_obj[k] = {} _obj[k] = {};
} }
const key = keys.shift() const key = keys.shift();
// 自调用判断是否存在属性,不存在则自动创建对象 // 自调用判断是否存在属性,不存在则自动创建对象
inFn(_obj[k], keys, v) inFn(_obj[k], keys, v);
}
} }
};
if (typeof key !== 'string' || key === '') { if (typeof key !== "string" || key === "") {
} else if (key.indexOf(".") !== -1) {
} else if (key.indexOf('.') !== -1) { // 支持多层级赋值操作 // 支持多层级赋值操作
const keys = key.split('.') const keys = key.split(".");
inFn(obj, keys, value) inFn(obj, keys, value);
} else { } else {
obj[key] = value obj[key] = value;
} }
} }
@ -652,17 +684,17 @@ function setProperty(obj, key, value) {
* @description 获取当前页面路径 * @description 获取当前页面路径
*/ */
function page() { function page() {
const pages = getCurrentPages() const pages = getCurrentPages();
// 某些特殊情况下(比如页面进行redirectTo时的一些时机)pages可能为空数组 // 某些特殊情况下(比如页面进行redirectTo时的一些时机)pages可能为空数组
return `/${pages[pages.length - 1]?.route ?? ''}` return `/${pages[pages.length - 1]?.route ?? ""}`;
} }
/** /**
* @description 获取当前路由栈实例数组 * @description 获取当前路由栈实例数组
*/ */
function pages() { function pages() {
const pages = getCurrentPages() const pages = getCurrentPages();
return pages return pages;
} }
/** /**
@ -670,9 +702,9 @@ function pages() {
* @param back {number} [0] - 0或者负数表示获取历史栈的哪一层0表示获取当前页面实例-1 表示获取上一个页面实例默认0 * @param back {number} [0] - 0或者负数表示获取历史栈的哪一层0表示获取当前页面实例-1 表示获取上一个页面实例默认0
*/ */
function getHistoryPage(back = 0) { function getHistoryPage(back = 0) {
const pages = getCurrentPages() const pages = getCurrentPages();
const len = pages.length const len = pages.length;
return pages[len - 1 + back] return pages[len - 1 + back];
} }
/** /**
@ -682,19 +714,12 @@ function getHistoryPage(back = 0) {
* @param {object} color 修改内置color属性 * @param {object} color 修改内置color属性
* @param {object} zIndex 修改内置zIndex属性 * @param {object} zIndex 修改内置zIndex属性
*/ */
function setConfig({ function setConfig({ props = {}, config = {}, color = {}, zIndex = {} }) {
props = {}, const { deepMerge } = uni.$u;
config = {}, uni.$u.config = deepMerge(uni.$u.config, config);
color = {}, uni.$u.props = deepMerge(uni.$u.props, props);
zIndex = {} uni.$u.color = deepMerge(uni.$u.color, color);
}) { uni.$u.zIndex = deepMerge(uni.$u.zIndex, 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 { export default {
@ -727,5 +752,5 @@ export default {
page, page,
pages, pages,
getHistoryPage, getHistoryPage,
setConfig setConfig,
} };

View File

@ -11,12 +11,12 @@
* HBuilderX: beat-3.0.4 alpha-3.0.4 * HBuilderX: beat-3.0.4 alpha-3.0.4
*/ */
import dispatchRequest from './dispatchRequest' import dispatchRequest from "./dispatchRequest";
import InterceptorManager from './InterceptorManager' import InterceptorManager from "./InterceptorManager";
import mergeConfig from './mergeConfig' import mergeConfig from "./mergeConfig";
import defaults from './defaults' import defaults from "./defaults";
import { isPlainObject } from '../utils' import { isPlainObject } from "../utils";
import clone from '../utils/clone' import clone from "../utils/clone";
export default class Request { export default class Request {
/** /**
@ -35,14 +35,14 @@ export default class Request {
*/ */
constructor(arg = {}) { constructor(arg = {}) {
if (!isPlainObject(arg)) { if (!isPlainObject(arg)) {
arg = {} arg = {};
console.warn('设置全局参数必须接收一个Object') // console.warn('设置全局参数必须接收一个Object')
} }
this.config = clone({ ...defaults, ...arg }) this.config = clone({ ...defaults, ...arg });
this.interceptors = { this.interceptors = {
request: new InterceptorManager(), request: new InterceptorManager(),
response: new InterceptorManager() response: new InterceptorManager(),
} };
} }
/** /**
@ -50,27 +50,27 @@ export default class Request {
* @param {Request~setConfigCallback} f - 设置全局默认配置 * @param {Request~setConfigCallback} f - 设置全局默认配置
*/ */
setConfig(f) { setConfig(f) {
this.config = f(this.config) this.config = f(this.config);
} }
middleware(config) { middleware(config) {
config = mergeConfig(this.config, config) config = mergeConfig(this.config, config);
const chain = [dispatchRequest, undefined] const chain = [dispatchRequest, undefined];
let promise = Promise.resolve(config) let promise = Promise.resolve(config);
this.interceptors.request.forEach((interceptor) => { this.interceptors.request.forEach((interceptor) => {
chain.unshift(interceptor.fulfilled, interceptor.rejected) chain.unshift(interceptor.fulfilled, interceptor.rejected);
}) });
this.interceptors.response.forEach((interceptor) => { this.interceptors.response.forEach((interceptor) => {
chain.push(interceptor.fulfilled, interceptor.rejected) chain.push(interceptor.fulfilled, interceptor.rejected);
}) });
while (chain.length) { while (chain.length) {
promise = promise.then(chain.shift(), chain.shift()) promise = promise.then(chain.shift(), chain.shift());
} }
return promise return promise;
} }
/** /**
@ -85,24 +85,24 @@ export default class Request {
* @returns {Promise<unknown>} * @returns {Promise<unknown>}
*/ */
request(config = {}) { request(config = {}) {
return this.middleware(config) return this.middleware(config);
} }
get(url, options = {}) { get(url, options = {}) {
return this.middleware({ return this.middleware({
url, url,
method: 'GET', method: "GET",
...options ...options,
}) });
} }
post(url, data, options = {}) { post(url, data, options = {}) {
return this.middleware({ return this.middleware({
url, url,
data, data,
method: 'POST', method: "POST",
...options ...options,
}) });
} }
// #ifndef MP-ALIPAY // #ifndef MP-ALIPAY
@ -110,9 +110,9 @@ export default class Request {
return this.middleware({ return this.middleware({
url, url,
data, data,
method: 'PUT', method: "PUT",
...options ...options,
}) });
} }
// #endif // #endif
@ -122,9 +122,9 @@ export default class Request {
return this.middleware({ return this.middleware({
url, url,
data, data,
method: 'DELETE', method: "DELETE",
...options ...options,
}) });
} }
// #endif // #endif
@ -134,9 +134,9 @@ export default class Request {
return this.middleware({ return this.middleware({
url, url,
data, data,
method: 'CONNECT', method: "CONNECT",
...options ...options,
}) });
} }
// #endif // #endif
@ -146,9 +146,9 @@ export default class Request {
return this.middleware({ return this.middleware({
url, url,
data, data,
method: 'HEAD', method: "HEAD",
...options ...options,
}) });
} }
// #endif // #endif
@ -158,9 +158,9 @@ export default class Request {
return this.middleware({ return this.middleware({
url, url,
data, data,
method: 'OPTIONS', method: "OPTIONS",
...options ...options,
}) });
} }
// #endif // #endif
@ -170,23 +170,23 @@ export default class Request {
return this.middleware({ return this.middleware({
url, url,
data, data,
method: 'TRACE', method: "TRACE",
...options ...options,
}) });
} }
// #endif // #endif
upload(url, config = {}) { upload(url, config = {}) {
config.url = url config.url = url;
config.method = 'UPLOAD' config.method = "UPLOAD";
return this.middleware(config) return this.middleware(config);
} }
download(url, config = {}) { download(url, config = {}) {
config.url = url config.url = url;
config.method = 'DOWNLOAD' config.method = "DOWNLOAD";
return this.middleware(config) return this.middleware(config);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@
export class Mcaptcha { export class Mcaptcha {
constructor(options) { constructor(options) {
this.options = options; this.options = options;
this.fontSize = options.height * 3 / 6; this.fontSize = (options.height * 3) / 6;
this.init(); this.init();
this.refresh(); this.refresh();
} }
@ -13,17 +13,80 @@ export class Mcaptcha {
this.ctx.setFillStyle(this.randomColor(180, 240)); this.ctx.setFillStyle(this.randomColor(180, 240));
} }
refresh() { refresh() {
var code = ''; 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 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++) { for (var i = 0; i < 4; i++) {
code += txtArr[this.randomNum(0, txtArr.length)]; code += txtArr[this.randomNum(0, txtArr.length)];
} }
this.options.createCodeImg = code; this.options.createCodeImg = code;
let arr = (code + '').split(''); let arr = (code + "").split("");
if (arr.length === 0) { if (arr.length === 0) {
arr = ['e', 'r', 'r', 'o', 'r']; arr = ["e", "r", "r", "o", "r"];
}; }
let offsetLeft = this.options.width * 0.6 / (arr.length - 1); let offsetLeft = (this.options.width * 0.6) / (arr.length - 1);
let marginLeft = this.options.width * 0.2; let marginLeft = this.options.width * 0.2;
arr.forEach((item, index) => { arr.forEach((item, index) => {
this.ctx.setFillStyle(this.randomColor(0, 180)); this.ctx.setFillStyle(this.randomColor(0, 180));
@ -32,22 +95,34 @@ export class Mcaptcha {
let dis = offsetLeft * index + marginLeft - size * 0.3; let dis = offsetLeft * index + marginLeft - size * 0.3;
let deg = this.randomNum(-30, 30); let deg = this.randomNum(-30, 30);
this.ctx.translate(dis, this.options.height * 0.5); 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.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); this.ctx.translate(-dis, -this.options.height * 0.5);
}) });
for (var i = 0; i < 4; i++) { for (var i = 0; i < 4; i++) {
this.ctx.strokeStyle = this.randomColor(40, 180); this.ctx.strokeStyle = this.randomColor(40, 180);
this.ctx.beginPath(); this.ctx.beginPath();
this.ctx.moveTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height)); this.ctx.moveTo(
this.ctx.lineTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height)); 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(); this.ctx.stroke();
} }
for (var i = 0; i < this.options.width / 4; i++) { for (var i = 0; i < this.options.width / 4; i++) {
this.ctx.fillStyle = this.randomColor(0, 255); this.ctx.fillStyle = this.randomColor(0, 255);
this.ctx.beginPath(); 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.fill();
} }
this.ctx.draw(); this.ctx.draw();
@ -55,8 +130,8 @@ export class Mcaptcha {
validate(code) { validate(code) {
var code = code.toLowerCase(); var code = code.toLowerCase();
var v_code = this.options.createCodeImg.toLowerCase(); var v_code = this.options.createCodeImg.toLowerCase();
console.log(code) // console.log(code)
console.log(v_code.substring(v_code.length - 4)) // console.log(v_code.substring(v_code.length - 4))
if (code == v_code.substring(v_code.length - 4)) { if (code == v_code.substring(v_code.length - 4)) {
return true; return true;
} else { } else {