@fallen-zero/use
Version:
1,368 lines (1,338 loc) • 40.5 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/index.ts
var src_exports = {};
__export(src_exports, {
CreateRequest: () => CreateRequest,
DATE_FORMAT: () => DATE_FORMAT,
FontSize: () => FontSize,
ImageCompression: () => ImageCompression,
Loader: () => Loader,
StorageEnum: () => StorageEnum,
UseDefer: () => UseDefer,
UserAgent: () => UserAgent,
anyIsEqual: () => anyIsEqual,
arrayIsEqual: () => arrayIsEqual,
base64ToBlob: () => base64ToBlob,
base64ToFile: () => base64ToFile,
browserPerformChunk: () => browserPerformChunk,
createField: () => createField,
dateFormat: () => dateFormat,
decimalPlaces: () => decimalPlaces,
encrypt: () => encrypt,
encryptName: () => encryptName,
fileToBinary: () => fileToBinary,
fommaterIndex: () => fommaterIndex,
getAgeByIdCard: () => getAgeByIdCard,
getFileExt: () => getFileExt,
getFileName: () => getFileName,
getFileSize: () => getFileSize,
getIdCardInfo: () => getIdCardInfo,
getSexByIdCard: () => getSexByIdCard,
getSystemAgent: () => getSystemAgent,
isAllEqual: () => isAllEqual,
isArray: () => isArray,
isBoolean: () => isBoolean,
isDate: () => isDate,
isEmptyValue: () => isEmptyValue,
isFile: () => isFile,
isFunction: () => isFunction,
isImage: () => isImage,
isNull: () => isNull,
isNumber: () => isNumber,
isObject: () => isObject,
isPromise: () => isPromise,
isRegExp: () => isRegExp,
isString: () => isString,
isUndefined: () => isUndefined,
isVehicleNumber: () => isVehicleNumber,
numToCapital: () => numToCapital,
objectIsEqual: () => objectIsEqual,
preformChunk: () => preformChunk,
strToArray: () => strToArray,
sum: () => sum,
timeoutPerformChunk: () => timeoutPerformChunk,
toFixed: () => toFixed,
toPrecision: () => toPrecision,
useAnimation: () => useAnimation,
useApiList: () => useApiList,
useCompRef: () => useCompRef,
useCompRefs: () => useCompRefs,
useDebounceRef: () => useDebounceRef,
useFormData: () => useFormData,
useFullUrl: () => useFullUrl,
useIntervalDate: () => useIntervalDate,
useLoopExec: () => useLoopExec,
useRem: () => useRem,
useRequest: () => useRequest,
useRequestImmediate: () => useRequestImmediate,
useResize: () => useResize,
useStore: () => useStore,
validatePhone: () => validatePhone,
validatePhoneAndTel: () => validatePhoneAndTel,
validatePhoneAndTelMD: () => validatePhoneAndTelMD,
validateTel: () => validateTel
});
module.exports = __toCommonJS(src_exports);
// src/useEncryptName/index.ts
function encryptName(name, { start = 1, end = 1, info = "一-龥", char = "*" } = {}) {
const trueName = name.replace(/\s/g, "");
const regExp = new RegExp(
`^([${info}]{${start}})[${info}]+([${info}]{${trueName.length > 2 ? end : 0}})`,
"g"
);
return trueName.replace(
regExp,
"$1" + char.repeat(Math.max(trueName.length - start - end, 1)) + "$2"
);
}
var EncryptType = {
name: {},
phone: {
start: 3,
end: 4,
info: "\\d",
char: "*"
},
idCard: {
start: 3,
end: 4,
info: "\\dxX",
char: "*"
},
bankCard: {
start: 6,
end: 4,
info: "\\d",
char: "*"
},
email: {}
};
function encrypt(type, str, options = {}) {
if (type === "email") {
return str.replace(/^(.{1,2})@(.*)$/, "$1***@$2");
}
const typeOptions = EncryptType[type] || {};
return encryptName(str, __spreadValues(__spreadValues({}, typeOptions), options));
}
// src/getSystemAgent/index.ts
var UserAgent = /* @__PURE__ */ ((UserAgent2) => {
UserAgent2["IOS"] = "ios";
UserAgent2["ANDROID"] = "android";
UserAgent2["I_PHONE"] = "iPhone";
UserAgent2["I_PAD"] = "iPad";
UserAgent2["微信"] = "wx";
UserAgent2["钉钉"] = "dingding";
UserAgent2["浙政钉"] = "dingding_zy";
return UserAgent2;
})(UserAgent || {});
var getSystemAgent = (type) => {
var _a, _b;
const u = (_b = (_a = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a.toLowerCase()) != null ? _b : "";
const result = {
["ios" /* IOS */]: !!u.match(/\(i[^;]+;( u;)? cpu.+mac os x/),
["android" /* ANDROID */]: u.includes("android") || u.includes("adr") || u.includes("linux"),
// android终端或uc浏览器
["iPhone" /* I_PHONE */]: u.includes("iphone"),
// 是否为iPhone或者QQHD浏览器
["iPad" /* I_PAD */]: u.includes("ipad"),
["wx" /* 微信 */]: u.includes("micromessenger"),
// 是否在微信
["dingding" /* 钉钉 */]: u.includes("dingding") || u.includes("dingtalk"),
// 钉钉
["dingding_zy" /* 浙政钉 */]: u.indexOf("taurusapp") > -1
// 是否在专有钉钉/浙政钉
};
return type ? Boolean(result[type]) : result;
};
// src/dateFormat/index.ts
var import_dayjs = __toESM(require("dayjs"));
var import_zh_cn = require("dayjs/locale/zh-cn");
import_dayjs.default.locale("zh-cn");
var DATE_FORMAT = /* @__PURE__ */ ((DATE_FORMAT2) => {
DATE_FORMAT2["DATE-"] = "YYYY-MM-DD";
DATE_FORMAT2["DATETIME-"] = "YYYY-MM-DD HH:mm";
DATE_FORMAT2["DATETIMES-"] = "YYYY-MM-DD HH:mm:ss";
DATE_FORMAT2["DATE/"] = "YYYY/MM/DD";
DATE_FORMAT2["DATETIME/"] = "YYYY/MM/DD HH:mm";
DATE_FORMAT2["DATETIMES/"] = "YYYY/MM/DD HH:mm:ss";
DATE_FORMAT2["DATE."] = "YYYY.MM.DD";
DATE_FORMAT2["DATETIME."] = "YYYY.MM.DD HH:mm";
DATE_FORMAT2["DATETIMES."] = "YYYY.MM.DD HH:mm:ss";
DATE_FORMAT2["DATE"] = "YYYY年MM月DD日";
DATE_FORMAT2["DATETIME"] = "YYYY年MM月DD日 HH:mm";
DATE_FORMAT2["DATETIME_ZH"] = "YYYY年MM月DD日 HH时mm分";
DATE_FORMAT2["DATETIMES"] = "YYYY年MM月DD日 HH:mm:ss";
DATE_FORMAT2["DATETIMES_ZH"] = "YYYY年MM月DD日 HH时mm分ss秒";
DATE_FORMAT2["TIME"] = "HH:mm";
DATE_FORMAT2["TIMES"] = "HH:mm:ss";
DATE_FORMAT2["MONTH-"] = "MM-DD";
DATE_FORMAT2["MONTH/"] = "MM/DD";
DATE_FORMAT2["MONTHTIME-"] = "MM-DD HH:mm";
DATE_FORMAT2["MONTHTIMES-"] = "MM-DD HH:mm:ss";
DATE_FORMAT2["MONTHTIME/"] = "MM/DD HH:mm";
DATE_FORMAT2["MONTHTIMES/"] = "MM/DD HH:mm:ss";
DATE_FORMAT2["MONTHTIME_ZH"] = "MM月DD日 HH时mm分";
DATE_FORMAT2["MONTHTIMES_ZH"] = "MM月DD日 HH时mm分ss秒";
DATE_FORMAT2["YEAR"] = "YYYY";
DATE_FORMAT2["MONTH"] = "MM";
DATE_FORMAT2["DAY"] = "DD";
DATE_FORMAT2["HOUR"] = "HH";
DATE_FORMAT2["MINUTES"] = "mm";
DATE_FORMAT2["SECONDS"] = "ss";
DATE_FORMAT2["WEEK"] = "dddd";
return DATE_FORMAT2;
})(DATE_FORMAT || {});
function dateFormat(date, format = "YYYY-MM-DD" /* DATE- */) {
let _date = date;
if (date === "" || date === 0)
return "";
if (date === void 0)
_date = /* @__PURE__ */ new Date();
if (typeof _date === "string")
_date = _date.replace(/-/g, "/");
if ((typeof _date === "string" || typeof _date === "number") && new Date(_date).toString() === "Invalid Date") {
return `${date}`;
}
return (0, import_dayjs.default)(_date).format(format);
}
// src/is.ts
var isFunction = (val) => {
return typeof val === "function";
};
var isObject = (val) => {
return val !== null && typeof val === "object";
};
var isArray = (val) => {
return Array.isArray(val);
};
var isString = (val) => {
return typeof val === "string";
};
var isNumber = (val) => {
return typeof val === "number";
};
var isBoolean = (val) => {
return typeof val === "boolean";
};
var isDate = (val) => {
return val instanceof Date;
};
var isRegExp = (val) => {
return val instanceof RegExp;
};
var isUndefined = (val) => {
return typeof val === "undefined";
};
var isNull = (val) => {
return val === null;
};
var isPromise = (val) => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch);
};
var isFile = (val) => {
return val instanceof File;
};
// src/useFormData/index.ts
function useFormData(form) {
if (!form || typeof form !== "object") {
throw new Error("form is not object");
}
const formData = new FormData();
for (const key in form) {
if (Object.prototype.hasOwnProperty.call(form, key) && form[key] !== void 0 && form[key] !== null) {
const value = form[key];
if (isFile(value)) {
formData.append(key, value);
} else if (isArray(value) || isObject(value)) {
formData.append(key, JSON.stringify(value));
} else {
formData.append(key, String(value));
}
}
}
return formData;
}
// src/strToArray/index.ts
function strToArray(str, separator = ",") {
if (!str)
return [];
return str.split(separator).filter(Boolean);
}
// src/FontSize/index.ts
function FontSize(res, box = 1920) {
var _a, _b;
const clientWidth = (_b = (_a = window.innerWidth) != null ? _a : document.documentElement.clientWidth) != null ? _b : document.body.clientWidth;
if (!clientWidth)
return res;
const fontSize = clientWidth / box;
return res * fontSize;
}
// src/fileProcessing/index.ts
var ImageCompression = class {
constructor(options) {
this.options = options;
this.compress();
}
/** 压缩图片 */
compress() {
var _a, _b, _c, _d;
try {
this.readImage((url) => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const image = new Image();
image.src = url;
image.onload = () => {
var _a2, _b2;
canvas.width = image.width;
canvas.height = image.height;
ctx == null ? void 0 : ctx.drawImage(image, 0, 0, image.width, image.height);
const result = canvas.toDataURL(
this.options.file.type,
this.options.quality
);
(_b2 = (_a2 = this.options).success) == null ? void 0 : _b2.call(_a2, result);
};
});
} catch (error) {
(_b = (_a = this.options).fail) == null ? void 0 : _b.call(_a);
} finally {
(_d = (_c = this.options).complete) == null ? void 0 : _d.call(_c);
}
}
/** 读取图片 */
readImage(callback) {
const reader = new FileReader();
reader.onload = () => {
callback(reader.result);
};
reader.readAsDataURL(this.options.file);
}
};
function base64ToBlob(base64, type) {
const byteCharacters = atob(
base64.replace(/^data:image\/(png|jpeg|jpg);base64,/, "")
);
const arrayBuffer = new Uint8Array(
Array.from(byteCharacters, (char) => char.charCodeAt(0))
).buffer;
return new Blob([arrayBuffer], { type });
}
function base64ToFile(base64, fileName, type) {
const blob = base64ToBlob(base64, type);
return new File([blob], fileName, { type });
}
function fileToBinary(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result;
const binary = new Uint8Array(arrayBuffer);
resolve(binary);
};
reader.onerror = () => {
reject(new Error("Failed to read file as binary"));
};
reader.readAsArrayBuffer(file);
});
}
function getFileExt(filename) {
const index = filename.lastIndexOf(".");
if (index === -1) {
return "";
}
return filename.substring(index + 1).toLowerCase();
}
function getFileSize(file) {
let size = file.size;
const units = ["B", "KB", "MB", "GB", "TB"];
let i = 0;
while (size >= 1024 && i < units.length - 1) {
size /= 1024;
i++;
}
return `${size.toFixed(2)} ${units[i]}`;
}
function getFileName(file) {
const index = file.lastIndexOf("/");
if (index === -1) {
return file;
}
return file.substring(index + 1);
}
function useFullUrl(FILE_URL = "") {
function fullUrl(path, isBase64 = false) {
if (!path)
return "";
if (/^http(s)?:\/\//.test(path) || /base64/i.test(path)) {
return path;
}
if (isBase64) {
return `data:image/png;base64,${path}`;
}
return `${FILE_URL != null ? FILE_URL : ""}${path.replace(/^~/, "")}`;
}
return fullUrl;
}
// src/numToCapital/index.ts
var numToCapital = (num, type = false) => {
if (!num)
return "零";
const strNum = Number((num + "").replace(/[,,]*/g, "")) + "";
num = parseInt(strNum);
let capitalAr = "零一二三四五六七八九十";
let unitAr = [
"十",
"百",
"千",
"万",
"十",
"百",
"千",
"亿",
"十",
"百",
"千"
];
if (type) {
capitalAr = "零壹贰叁肆伍陆柒捌玖拾";
unitAr = ["拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"];
}
const resultAr = [];
const index = strNum.length - 1;
let idx = 0;
const percent = 10;
const turnNum = (num2, percent2, index2) => {
const unit = num2 / percent2;
const capital = capitalAr[Number(strNum[index2])];
if (unit < 1) {
resultAr.push(capital);
if (Number(strNum[index2]) === 1 && (strNum.length === 2 || strNum.length === 6 || strNum.length === 10)) {
resultAr.pop();
}
return false;
} else {
if (capital === "零") {
if (!["万", "亿"].includes(resultAr[resultAr.length - 1])) {
resultAr.pop();
}
if (resultAr[resultAr.length - 1] === "零") {
resultAr.pop();
}
}
resultAr.push(capital);
if (["万", "亿"].includes(resultAr[resultAr.length - 2]) && capital === "零") {
resultAr.pop();
}
if (resultAr[0] === "万" && resultAr[1] === "亿") {
resultAr.shift();
}
if (resultAr[0] === "零") {
resultAr.pop();
}
resultAr.push(unitAr[idx++]);
turnNum(num2, percent2 * 10, --index2);
}
};
turnNum(num, percent, index);
return resultAr.reverse().join("");
};
// src/getIdCardInfo/index.ts
function getSexByIdCard(idCard) {
let sexDigit;
if (idCard.length === 15) {
sexDigit = idCard.charAt(idCard.length - 1);
} else if (idCard.length === 18) {
sexDigit = idCard.charAt(idCard.length - 2);
} else {
return "";
}
return parseInt(sexDigit) % 2 === 0 ? "女" : "男";
}
function getAgeByIdCard(idCard) {
const userCard = idCard;
if (!userCard) {
return "";
}
const yearBirth = parseInt(userCard.substring(6, 10));
const monthBirth = parseInt(userCard.substring(10, 12));
const dayBirth = parseInt(userCard.substring(12, 14));
const myDate = /* @__PURE__ */ new Date();
const monthNow = myDate.getMonth() + 1;
const dayNow = myDate.getDate();
let age = myDate.getFullYear() - yearBirth;
if (monthNow < monthBirth || monthNow == monthBirth && dayNow < dayBirth) {
age--;
}
return age;
}
var getIdCardInfo = (idCardNumber) => {
return {
age: getAgeByIdCard(idCardNumber),
gender: getSexByIdCard(idCardNumber)
};
};
// src/estimate/index.ts
function decimalPlaces(num) {
if (Number.isInteger(num))
return 0;
if (!num)
return NaN;
const count = num.toString().split(".")[1].length;
return count;
}
var toFixed = (num, places) => {
const decimal = decimalPlaces(num);
return decimal > places ? places : decimal;
};
var toPrecision = (num, places = 2) => {
const value = num.toFixed(toFixed(num, places));
return +value;
};
function isEmptyValue(value) {
return [void 0, null, ""].includes(value);
}
var isImage = (path) => {
const regex = /\.(jpe?g|png|gif|bmp|webp|svgz?|tiff?|jfif|pjp|pjpeg|avif)$/i;
return regex.test(path);
};
function isVehicleNumber(vehicleNumber) {
const xxreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DABCEFGHJK]$)|([DABCEFGHJK][A-HJ-NP-Z0-9][0-9]{4}$))/;
const creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
if (vehicleNumber.length === 7) {
return creg.test(vehicleNumber);
} else if (vehicleNumber.length === 8) {
return xxreg.test(vehicleNumber);
} else {
return false;
}
}
function validatePhoneAndTel(phone) {
const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
const tel = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/;
if (reg.test(phone) || tel.test(phone)) {
return true;
}
return false;
}
function validatePhone(phone) {
const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/;
return reg.test(phone);
}
function validateTel(phone) {
const reg = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/;
return reg.test(phone);
}
function validatePhoneAndTelMD(phone) {
const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+[\d|*]{4}\d{4})$/;
const tel = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/;
if (reg.test(phone) || tel.test(phone)) {
return true;
}
return false;
}
function isAllEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
var isNil = (v) => {
return typeof v === "undefined" || v === null;
};
function arrayIsEqual(a, b, ignoreArrayPosition = false) {
if (a.length !== b.length)
return false;
if (!ignoreArrayPosition)
return a.every((v, i) => anyIsEqual(v, b[i]));
return a.every(
(v) => b.findIndex((v2) => anyIsEqual(v2, v)) >= 0 && b.filter((v2) => anyIsEqual(v2, v)).length === a.filter((v1) => anyIsEqual(v1, v)).length
);
}
function objectIsEqual(a, b) {
if (Object.keys(a).length !== Object.keys(b).length)
return false;
return Object.keys(a).every((k) => {
if (Object.keys(b).includes(k)) {
return anyIsEqual(a[k], b[k]);
}
return false;
});
}
function anyIsEqual(a, b, ignoreArrayPosition = false) {
if (isNil(a) || isNil(b)) {
return a === b;
}
if (a.constructor === b.constructor) {
if (a.constructor === Array) {
return arrayIsEqual(a, b, ignoreArrayPosition);
}
if (a.constructor === Object) {
return objectIsEqual(a, b);
}
return a === b;
}
return false;
}
var sum = (...arg) => {
return arg.reduce((prev, curr) => prev += curr, 0);
};
// node_modules/.pnpm/js-cookie@3.0.5/node_modules/js-cookie/dist/js.cookie.mjs
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
target[key] = source[key];
}
}
return target;
}
var defaultConverter = {
read: function(value) {
if (value[0] === '"') {
value = value.slice(1, -1);
}
return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
},
write: function(value) {
return encodeURIComponent(value).replace(
/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
decodeURIComponent
);
}
};
function init(converter, defaultAttributes) {
function set(name, value, attributes) {
if (typeof document === "undefined") {
return;
}
attributes = assign({}, defaultAttributes, attributes);
if (typeof attributes.expires === "number") {
attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
}
if (attributes.expires) {
attributes.expires = attributes.expires.toUTCString();
}
name = encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
var stringifiedAttributes = "";
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue;
}
stringifiedAttributes += "; " + attributeName;
if (attributes[attributeName] === true) {
continue;
}
stringifiedAttributes += "=" + attributes[attributeName].split(";")[0];
}
return document.cookie = name + "=" + converter.write(value, name) + stringifiedAttributes;
}
function get(name) {
if (typeof document === "undefined" || arguments.length && !name) {
return;
}
var cookies = document.cookie ? document.cookie.split("; ") : [];
var jar = {};
for (var i = 0; i < cookies.length; i++) {
var parts = cookies[i].split("=");
var value = parts.slice(1).join("=");
try {
var found = decodeURIComponent(parts[0]);
jar[found] = converter.read(value, found);
if (name === found) {
break;
}
} catch (e) {
}
}
return name ? jar[name] : jar;
}
return Object.create(
{
set,
get,
remove: function(name, attributes) {
set(
name,
"",
assign({}, attributes, {
expires: -1
})
);
},
withAttributes: function(attributes) {
return init(this.converter, assign({}, this.attributes, attributes));
},
withConverter: function(converter2) {
return init(assign({}, this.converter, converter2), this.attributes);
}
},
{
attributes: { value: Object.freeze(defaultAttributes) },
converter: { value: Object.freeze(converter) }
}
);
}
var api = init(defaultConverter, { path: "/" });
// src/useStore/index.ts
var StorageEnum = /* @__PURE__ */ ((StorageEnum2) => {
StorageEnum2["LOCAL"] = "localStorage";
StorageEnum2["SESSION"] = "sessionStorage";
StorageEnum2["COOKIE"] = "cookie";
return StorageEnum2;
})(StorageEnum || {});
var storages = {
["localStorage" /* LOCAL */]: localStorage,
["sessionStorage" /* SESSION */]: sessionStorage,
["cookie" /* COOKIE */]: api
};
var useStore = (prefix = "") => ({
/** 设置存储中的键值对。
* @param {string} key - 要设置值的键。
* @param {T} data - 要存储的数据。
* @param {IStorage} [options] - 可选的存储配置。
* - expire: 过期时间(秒)若是cookie类型的存储,单位是(天),过期时间默认为7天。
* - storage: 存储类型(默认为 StorageEnum.SESSION)。
* @return {void}
*/
set(key, data, { expire, storage = "sessionStorage" /* SESSION */ } = {}) {
const _key = `${prefix}-${key}`;
if (storage === "cookie" /* COOKIE */) {
const _storage2 = storages[storage];
_storage2.set(_key, JSON.stringify(data), { expires: expire || 7 });
return;
}
const _storage = storages[storage];
const cache = { data };
if (expire) {
cache.expire = (/* @__PURE__ */ new Date()).getTime() + expire * 1e3;
}
_storage.setItem(_key, JSON.stringify(cache));
},
/** 从指定的存储中检索与指定键相关联的值。
* @param {string} key - 用于检索值的键。
* @param {StorageEnum} [storage=StorageEnum.SESSION] - 要从中检索值的存储类型。默认为 `StorageEnum.SESSION`。
* @return {T | null} - 检索到的值,如果键不存在或值已过期,则返回 `null`。
*/
get(key, storage = "sessionStorage" /* SESSION */) {
const _key = `${prefix}-${key}`;
if (storage === "cookie" /* COOKIE */) {
const _storage2 = storages[storage];
const data = _storage2.get(_key);
return data ? JSON.parse(data) : null;
}
const _storage = storages[storage];
const cacheStore = _storage.getItem(_key);
if (cacheStore) {
const cache = JSON.parse(cacheStore);
const expire = cache.expire;
if (expire && expire < (/* @__PURE__ */ new Date()).getTime()) {
_storage.removeItem(_key);
return null;
}
return cache.data;
}
return null;
},
/** 从指定的存储中删除一个键。
* @param {string} key - 要删除的键。
* @param {StorageEnum} [storage=StorageEnum.SESSION] - 要从中删除键的存储。默认为 StorageEnum.SESSION。
*/
remove(key, storage = "sessionStorage" /* SESSION */) {
const _key = `${prefix}-${key}`;
if (storage === "cookie" /* COOKIE */) {
storages[storage].remove(_key);
return;
}
const _storage = storages[storage];
_storage.removeItem(_key);
}
});
// src/useDefer/index.ts
var import_vue = require("vue");
var UseDefer = class {
constructor(maxFrameCount = 1e3) {
this.frameCount = (0, import_vue.ref)(0);
this.maxFrameCount = (0, import_vue.ref)(1e3);
this.maxFrameCount.value = maxFrameCount;
this.refreshFrameCount();
}
refreshFrameCount() {
requestAnimationFrame(() => {
this.frameCount.value++;
if (this.frameCount.value < this.maxFrameCount.value) {
this.refreshFrameCount();
}
});
}
setMaxCount(maxFrameCount) {
this.maxFrameCount.value = maxFrameCount;
this.refreshFrameCount();
}
getMaxCount() {
return this.maxFrameCount.value;
}
defer(showInFrameCount) {
return this.frameCount.value >= showInFrameCount;
}
};
// src/useCompRef/index.ts
var import_vue2 = require("vue");
var useCompRef = (_comp) => {
return (0, import_vue2.ref)();
};
var useCompRefs = (_comp) => {
return (0, import_vue2.ref)([]);
};
// src/useRequest/index.ts
var import_vue3 = require("vue");
var CreateRequest = class {
constructor(config = {}) {
this.config = config;
this.requestApi = (api2, params, {
immediate = true,
success,
fail,
complate,
checkStatus = this.config.checkStatus,
showLoading = this.config.showLoading
} = {}) => {
let currentCancel;
let currParams = params;
const data = (0, import_vue3.ref)();
const error = (0, import_vue3.ref)();
const loading = (0, import_vue3.ref)(false);
const run = () => __async(this, null, function* () {
try {
currentCancel && currentCancel();
loading.value = true;
showLoading && showLoading(true);
const method = api2(...currParams);
currentCancel = "cancel" in method ? method.cancel : void 0;
const res = yield method;
if (!checkStatus || checkStatus(res)) {
data.value = res;
error.value = void 0;
success && (yield success(res));
return;
}
throw res;
} catch (err) {
data.value = void 0;
error.value = err;
if (fail && (yield fail(err))) {
return;
}
this.config.showError && this.config.showError(err);
} finally {
currentCancel = void 0;
loading.value = false;
showLoading && showLoading(false);
complate && (yield complate());
}
});
const setParams = (newParams, immediate2 = true) => __async(this, null, function* () {
currParams = newParams;
immediate2 && (yield run());
});
const reset = () => __async(this, null, function* () {
currParams = params;
yield run();
});
if (immediate) {
if ((0, import_vue3.getCurrentInstance)()) {
(0, import_vue3.onMounted)(() => {
run();
});
} else {
run();
}
}
return {
/** 开始请求 */
run,
/**
* 设置请求参数
* @param newParams 新的请求参数
* @param immediate 是否立即请求
*/
setParams,
/** 重置请求 */
reset,
/** 请求数据 */
data,
/** 请求错误信息 */
error,
/** 请求加载状态 */
loading,
/** 取消请求 */
cancel: currentCancel
};
};
}
};
var request = new CreateRequest();
var useRequest = request.requestApi.bind(request);
// src/performChunk/index.ts
function preformChunk(datas, taskHandler, scheduler) {
const list = typeof datas === "number" ? Array(datas) : datas;
if (list.length === 0)
return;
let i = 0;
function _run() {
if (i >= list.length)
return;
scheduler((isGoOn) => {
while (isGoOn() && i < list.length) {
taskHandler(list[i], i);
i++;
}
_run();
});
}
_run();
}
function browserPerformChunk(datas, taskHandler) {
const scheduler = (task) => {
requestIdleCallback((deadline) => {
task(() => deadline.timeRemaining() > 0);
});
};
preformChunk(datas, taskHandler, scheduler);
}
function timeoutPerformChunk(datas, taskHandler, duration = 50, waitTime = 100) {
const scheduler = (task) => {
setTimeout(() => {
const start = Date.now();
task(() => Date.now() - start < duration);
}, waitTime);
};
preformChunk(datas, taskHandler, scheduler);
}
// src/useAnimation/index.ts
var useAnimation = (duration, from, to, callback) => {
const start = Date.now();
let value = from;
const speed = (to - from) / duration;
const _run = () => {
const time = Date.now() - start;
if (time >= duration) {
value = to;
callback && callback(value);
return;
}
value = from + time * speed;
callback && callback(value);
requestAnimationFrame(_run);
};
_run();
};
// src/useDebounceRef/index.ts
var import_vue4 = require("vue");
function useDebounceRef(value, delay = 200) {
let timer = null;
const clear = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
if ((0, import_vue4.getCurrentInstance)()) {
(0, import_vue4.onUnmounted)(() => {
clear();
});
}
return (0, import_vue4.customRef)((tracker, trigger) => {
return {
get() {
tracker();
return value;
},
set(newValue) {
clear();
timer = setTimeout(() => {
value = newValue;
timer = null;
trigger();
}, delay);
}
};
});
}
// src/useRequestImmediate/index.ts
var useRequestImmediate = (fn, ...params) => __async(void 0, null, function* () {
const { data, error, loading, run } = useRequest(fn, [...params]);
yield run();
return {
/** 请求数据 */
data,
/** 请求错误信息 */
error,
/** 是否正在请求 */
loading
};
});
// src/useIntervalDate/index.ts
var import_vue5 = require("vue");
var useIntervalDate = () => {
const currentDate = /* @__PURE__ */ new Date();
const currDate = (0, import_vue5.reactive)({
date: dateFormat(currentDate, "YYYY-MM-DD" /* DATE- */),
time: dateFormat(currentDate, "HH:mm:ss" /* TIMES */),
week: dateFormat(currentDate, "dddd" /* WEEK */)
});
const setCurrDate = () => {
const currentDate2 = /* @__PURE__ */ new Date();
currDate.date = dateFormat(currentDate2, "YYYY-MM-DD" /* DATE- */);
currDate.time = dateFormat(currentDate2, "HH:mm:ss" /* TIMES */);
currDate.week = dateFormat(currentDate2, "dddd" /* WEEK */);
};
let timer = null;
const clearTimer = () => {
timer && clearInterval(timer);
timer = null;
};
const startTimer = () => {
clearTimer();
timer = setInterval(setCurrDate, 1e3);
};
if ((0, import_vue5.getCurrentInstance)()) {
(0, import_vue5.onMounted)(() => {
startTimer();
});
(0, import_vue5.onBeforeUnmount)(() => {
timer && clearInterval(timer);
});
} else {
startTimer();
}
return { currDate };
};
// src/useApiList/index.ts
var import_vue6 = require("vue");
var useApiList = (api2, params, { immediate = true } = {}) => {
var _a;
const defaultParams = { page: 1, limit: 10 };
const initParams = params != null ? params : defaultParams;
let currentParams = initParams;
const {
data,
run,
setParams: setApiParams
} = useRequest(api2, [currentParams]);
const loading = (0, import_vue6.ref)(false);
const finished = (0, import_vue6.ref)(false);
const refreshing = (0, import_vue6.ref)(false);
const list = (0, import_vue6.ref)([]);
const total = (0, import_vue6.ref)(0);
let currLimit = (_a = currentParams.limit) != null ? _a : 10;
let page = 1;
const setParams = (_params) => __async(void 0, null, function* () {
var _a2;
list.value = [];
page = 1;
currentParams = __spreadProps(__spreadValues(__spreadValues({}, currentParams), _params), { page });
setApiParams([currentParams]);
currLimit = (_a2 = currentParams.limit) != null ? _a2 : 10;
finished.value = false;
yield getData();
});
const getData = () => __async(void 0, null, function* () {
var _a2, _b, _c, _d;
loading.value = true;
yield run();
list.value = [...list.value, ...(_b = (_a2 = data.value) == null ? void 0 : _a2.list) != null ? _b : []];
total.value = (_d = (_c = data.value) == null ? void 0 : _c.total) != null ? _d : 0;
loading.value = false;
refreshing.value = false;
page++;
if (data.value && data.value.list.length < currLimit) {
finished.value = true;
}
});
const onLoad = () => __async(void 0, null, function* () {
setApiParams([__spreadProps(__spreadValues({}, currentParams), { page })]);
yield getData();
});
const reset = () => __async(void 0, null, function* () {
yield setParams({});
});
if (immediate) {
if ((0, import_vue6.getCurrentInstance)()) {
(0, import_vue6.onMounted)(() => {
onLoad();
});
} else {
onLoad();
}
}
return {
/* 列表数据 */
list,
/** 总数 */
total,
/** 加载状态 */
loading,
/** 是否请求结束 */
finished,
/** 是否正在刷新 */
refreshing,
/** 修改请求参数 */
setParams,
/** 加载方法 */
onLoad,
/** 重置 */
reset
};
};
// src/Loader/index.ts
var import_vue7 = require("vue");
var Loader = class {
/**
* @param comp 组件
* @param div 组件挂载的容器
* @param teleport 容器
*/
constructor(comp, div = document.createElement("div"), teleport = document.body) {
this.comp = comp;
this.div = div;
this.teleport = teleport;
this.app = null;
}
show() {
this.app = (0, import_vue7.createApp)(this.comp);
this.teleport.appendChild(this.div);
this.app.mount(this.div);
}
hide() {
var _a;
(_a = this.app) == null ? void 0 : _a.unmount();
this.div.remove();
this.app = null;
}
};
// src/useRem/index.ts
function useRem({
designWidth: defaultDesignWidth = 1920,
size: defaultSize = 192,
listener: defaultListener = true,
immediate = true,
rootWidth: defaultRootWidth
} = {}) {
const root = document.documentElement;
const dpr = window.devicePixelRatio || 1;
let tid = null;
let screenWidth = defaultDesignWidth;
let baseSize = defaultSize;
let rootWidth = defaultRootWidth;
function setBodyFontSize() {
if (document.body) {
document.body.style.fontSize = `${12 * dpr}px`;
return;
}
document.addEventListener("DOMContentLoaded", setBodyFontSize);
}
setBodyFontSize();
function refreshRem() {
const scale = screenWidth / baseSize;
const width = rootWidth || root.clientWidth;
root.style.fontSize = `${width / scale}px`;
}
function onResize() {
!!tid && clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}
function startListener() {
window.addEventListener("resize", onResize, false);
window.addEventListener(
"pageshow",
(e) => {
if (e.persisted) {
onResize();
}
},
false
);
}
function stopListener() {
window.removeEventListener("resize", onResize, false);
window.removeEventListener(
"pageshow",
(e) => {
if (e.persisted) {
onResize();
}
},
false
);
}
function changeRem({
designWidth = defaultDesignWidth,
size = defaultSize,
listener = defaultListener,
rootWidth: newRootWidth
} = {}) {
screenWidth = designWidth;
baseSize = size;
rootWidth = newRootWidth;
listener && startListener();
!listener && stopListener();
refreshRem();
}
if (immediate) {
defaultListener && startListener();
refreshRem();
}
if (dpr >= 2) {
const fakeBody = document.createElement("body");
const testElement = document.createElement("div");
testElement.style.border = ".5px solid transparent";
fakeBody.appendChild(testElement);
root.appendChild(fakeBody);
if (testElement.offsetHeight === 1) {
root.classList.add("hairlines");
}
root.removeChild(fakeBody);
}
return {
changeRem
};
}
// src/useLoopExec/index.ts
function useLoopExec(fn, interval = 2e4) {
let timer = null;
function cancel() {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
function loop() {
return __async(this, null, function* () {
cancel();
yield fn();
timer = setTimeout(() => {
loop();
}, interval);
});
}
return {
/** 执行函数 */
loop,
/** 取消函数 */
cancel
};
}
// src/fields/index.tsx
function fommaterIndex(value) {
return value < 10 ? `0${value}` : `${value}`;
}
function createField(options, data) {
return options.map((option) => {
const { key, fommater, span = 1, color, visible, handler, tip } = option;
const value = fommater ? fommater(data[key], data) : data[key];
return {
label: option.label,
value,
span,
render: option.render ? option.render(data[key], data) : void 0,
color: typeof color === "function" ? color(data[key], data) : color,
visible: typeof visible === "function" ? visible(data[key], data) : visible,
tip: typeof tip === "function" ? tip(data[key], data) : tip,
handler: handler ? () => handler(data[key], data) : void 0
};
}).filter((item) => item.visible !== false);
}
// src/useResize/index.ts
var domMap = /* @__PURE__ */ new WeakMap();
var resizeObserver = null;
function useResize() {
if (!resizeObserver) {
resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const callback = domMap.get(entry.target);
if (callback) {
callback();
}
}
});
}
function observe(dom, callback) {
if (!dom)
return;
domMap.set(dom, callback);
resizeObserver == null ? void 0 : resizeObserver.observe(dom);
}
function unobserve(dom) {
if (!dom)
return;
domMap.delete(dom);
resizeObserver == null ? void 0 : resizeObserver.unobserve(dom);
}
return { observe, unobserve };
}
/*! Bundled license information:
js-cookie/dist/js.cookie.mjs:
(*! js-cookie v3.0.5 | MIT *)
*/