@itriton/saber
Version:
[@itriton/saber](http://itriton.icjs.ink/itriton/saber/start/introduce.html),提供开箱即用的JS/TS函数工具库
382 lines (369 loc) • 12.1 kB
JavaScript
import { __awaiter } from 'tslib';
const clone = (obj, cache = /* @__PURE__ */ new WeakMap()) => {
if (obj === null || typeof obj !== "object")
return obj;
if (cache.has(obj))
return cache.get(obj);
let result;
if (obj instanceof Date) {
result = new Date(obj.getTime());
} else if (obj instanceof RegExp) {
result = new RegExp(obj);
} else if (obj instanceof Map) {
result = new Map(Array.from(obj, ([key, value]) => [key, clone(value, cache)]));
} else if (obj instanceof Set) {
result = new Set(Array.from(obj, (value) => clone(value, cache)));
} else if (Array.isArray(obj)) {
result = obj.map((value) => clone(value, cache));
} else if (Object.prototype.toString.call(obj) === "[object Object]") {
result = Object.create(Object.getPrototypeOf(obj));
cache.set(obj, result);
for (const [key, value] of Object.entries(obj)) {
result[key] = clone(value, cache);
}
} else {
result = Object.assign({}, obj);
}
cache.set(obj, result);
return result;
};
const rgbToHex = (rgb) => {
let _rgb = rgb;
let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
if (/^(rgb|RGB)/.test(_rgb)) {
let aColor = _rgb.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
let strHex = "#";
for (let i = 0; i < aColor.length; i++) {
let hex = Number(aColor[i]).toString(16);
hex = String(hex).length == 1 ? "0" + hex : hex;
if (hex === "0")
hex += hex;
strHex += hex;
}
if (strHex.length !== 7)
strHex = _rgb;
return strHex;
} else if (reg.test(_rgb)) {
let aNum = _rgb.replace(/#/, "").split("");
if (aNum.length === 6)
return _rgb;
else if (aNum.length === 3) {
let numHex = "#";
for (let i = 0; i < aNum.length; i += 1) {
numHex += aNum[i] + aNum[i];
}
return numHex;
} else
return _rgb;
} else
return _rgb;
};
const hexToRgb = (sColor, isArray = false) => {
let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
sColor = sColor.toLowerCase();
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
let sColorNew = "#";
for (let i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
let sColorChange = [];
for (let i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
if (isArray) {
return sColorChange;
} else {
return `rgb(${sColorChange[0]},${sColorChange[1]},${sColorChange[2]})`;
}
} else if (/^(rgb|RGB)/.test(sColor)) {
let arr = sColor.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
return arr.map((val) => Number(val));
} else {
return sColor;
}
};
const colorToRgba = (color, alpha = 0.3) => {
color = rgbToHex(color);
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
let sColor = color.toLowerCase();
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (let i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
var sColorChange = [];
for (let i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return "rgba(" + sColorChange.join(",") + "," + alpha + ")";
} else {
return sColor;
}
};
const colorGradient = (startColor = "rgb(0, 0, 0)", endColor = "rgb(255, 255, 255)", step = 10) => {
let startRGB = hexToRgb(startColor, true);
let startR = startRGB[0];
let startG = startRGB[1];
let startB = startRGB[2];
let endRGB = hexToRgb(endColor, true);
let endR = endRGB[0];
let endG = endRGB[1];
let endB = endRGB[2];
let sR = (endR - startR) / step;
let sG = (endG - startG) / step;
let sB = (endB - startB) / step;
let colorArr = [];
for (let i = 0; i < step; i++) {
let hex = rgbToHex("rgb(" + Math.round(sR * i + startR) + "," + Math.round(sG * i + startG) + "," + Math.round(sB * i + startB) + ")");
colorArr.push(hex);
}
return colorArr;
};
const colorToDark = (color, level) => {
const r = /^#?[0-9a-fA-F]{6}$/;
if (!r.test(color)) {
console.log("\u8F93\u5165\u9519\u8BEF\u7684hex\u989C\u8272\u503C");
return;
}
let rgbc;
const colorArray = hexToRgb(color, true);
if (Array.isArray(colorArray) && colorArray.every((val) => typeof val === "number")) {
rgbc = colorArray;
} else {
console.log("hexToRgb \u51FD\u6570\u672A\u8FD4\u56DE\u6709\u6548\u7684\u989C\u8272\u6570\u7EC4");
return;
}
for (let i = 0; i < 3; i++) {
if (typeof rgbc[i] === "number") {
rgbc[i] = Math.floor(rgbc[i] * (1 - level));
}
}
return rgbToHex(`rgb(${rgbc[0]}, ${rgbc[1]}, ${rgbc[2]})`);
};
const colorToLight = (color, level) => {
const r = /^#?[0-9a-fA-F]{6}$/;
if (!r.test(color)) {
console.log("\u8F93\u5165\u9519\u8BEF\u7684hex\u989C\u8272\u503C");
return;
}
let rgbc;
const colorArray = hexToRgb(color, true);
if (Array.isArray(colorArray) && colorArray.every((val) => typeof val === "number")) {
rgbc = colorArray;
} else {
console.log("hexToRgb \u51FD\u6570\u672A\u8FD4\u56DE\u6709\u6548\u7684\u989C\u8272\u6570\u7EC4");
return;
}
for (let i = 0; i < 3; i++) {
if (typeof rgbc[i] === "number") {
rgbc[i] = Math.floor(rgbc[i] + (255 - rgbc[i]) * level);
}
}
return rgbToHex(`rgb(${rgbc[0]}, ${rgbc[1]}, ${rgbc[2]})`);
};
let timeout = null;
const debounce = (func, wait = 500, immediate = false) => {
if (timeout !== null)
clearTimeout(timeout);
if (immediate) {
const callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callNow)
typeof func === "function" && func();
} else {
timeout = setTimeout(() => {
typeof func === "function" && func();
}, wait);
}
};
const isDate = (value) => value instanceof Date;
const isRegExp = (value) => value instanceof RegExp;
const isMap = (value) => value instanceof Map;
const isSet = (value) => value instanceof Set;
const deepMergeValues = (targetValue, sourceValue) => {
if (isDate(sourceValue)) {
return new Date(sourceValue);
} else if (isRegExp(sourceValue)) {
return new RegExp(sourceValue);
} else if (isMap(sourceValue)) {
return new Map(sourceValue);
} else if (isSet(sourceValue)) {
return new Set(sourceValue);
} else if (typeof sourceValue === "object" && sourceValue !== null) {
return merge(targetValue, sourceValue);
} else {
return sourceValue;
}
};
const merge = (target = {}, source = {}) => {
target = clone(target);
if (typeof target !== "object" || target === null || typeof source !== "object" || source === null) {
return target;
}
let 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 (target.hasOwnProperty(prop) && typeof targetValue !== "undefined") {
merged[prop] = deepMergeValues(targetValue, sourceValue);
} else {
merged[prop] = clone(sourceValue);
}
}
return merged;
};
const trim = (value, position = "both") => {
if (position == "both") {
return value.replace(/^\s+|\s+$/g, "");
} else if (position == "left") {
return value.replace(/^\s*/, "");
} else if (position == "right") {
return value.replace(/(\s*$)/g, "");
} else if (position == "all") {
return value.replace(/\s+/g, "");
} else {
return value;
}
};
const hyphenate = (value, separator = "-") => {
let hyphenateRE = new RegExp(`([a-z\\d])([A-Z])`, "g");
let result = value.replace(hyphenateRE, `$1${separator}$2`);
hyphenateRE = new RegExp(`([A-Z]+)([A-Z][a-z\\d]+)`, "g");
result = result.replace(hyphenateRE, `$1${separator}$2`);
return result.toLowerCase();
};
const capitalize = (value) => {
return value.charAt(0).toUpperCase() + value.slice(1);
};
const camelize = (value, separator = "-") => {
let camelizeRE = new RegExp(`${separator}(\\w)`, "g");
return value.replace(camelizeRE, (_, c) => {
return c ? c.toUpperCase() : "";
});
};
let flag = false;
const throttle = (func, wait = 500, immediate = true) => {
if (immediate) {
if (!flag) {
flag = true;
typeof func === "function" && func();
setTimeout(() => {
flag = false;
}, wait);
}
} else {
if (!flag) {
flag = true;
setTimeout(() => {
flag = false;
typeof func === "function" && func();
}, wait);
}
}
};
const getDatesBetween = (startDate, endDate, symbol = "-") => {
let result = [];
while (startDate <= endDate) {
result.push(startDate);
const timestamp = new Date(startDate).getTime();
const nextDate = timestamp + 24 * 60 * 60 * 1e3;
const nextDateYear = `${new Date(nextDate).getFullYear()}${symbol}`;
const nextDateMonth = new Date(nextDate).getMonth() + 1 < 10 ? `0${new Date(nextDate).getMonth() + 1}${symbol}` : `${new Date(nextDate).getMonth() + 1}${symbol}`;
const nextDateDay = new Date(nextDate).getDate() < 10 ? "0" + new Date(nextDate).getDate() : new Date(nextDate).getDate();
startDate = `${nextDateYear}${nextDateMonth}${nextDateDay}`;
}
return result;
};
const setUnit = (value = "auto", unit = "px") => {
value = String(value);
const isNumber = /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value);
return isNumber ? `${value}${unit}` : value;
};
const axios = require("axios");
class Updater {
constructor(options) {
this.oldScript = [];
this.newScript = [];
this.dispatch = {};
this.url = (options === null || options === void 0 ? void 0 : options.url) || "/";
this.init();
this.timing(options === null || options === void 0 ? void 0 : options.timer);
}
init() {
return __awaiter(this, void 0, void 0, function* () {
const html = yield this.getHtml();
this.oldScript = this.parserScript(html);
});
}
getHtml() {
return __awaiter(this, void 0, void 0, function* () {
const html = yield axios({
url: this.url,
headers: { "Cache-Control": "no-cache" }
});
return html;
});
}
parserScript(html) {
const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig);
let result = "";
if (typeof html === "string")
result = html;
else
result = html.data;
return result.match(reg);
}
on(key, fn) {
(this.dispatch[key] || (this.dispatch[key] = [])).push(fn);
return this;
}
compare(oldArr, newArr) {
const base = oldArr.length;
const arr = Array.from(new Set(oldArr.concat(newArr)));
if (arr.length === base) {
this.dispatch["no-update"].forEach((fn) => {
fn();
});
} else {
this.dispatch["update"].forEach((fn) => {
fn();
});
}
}
timing(time = 1e4) {
if (this.interval)
clearInterval(this.interval);
this.interval = setInterval(() => __awaiter(this, void 0, void 0, function* () {
const newHtml = yield this.getHtml();
this.newScript = this.parserScript(newHtml);
this.compare(this.oldScript, this.newScript);
}), time);
}
}
const getUrlQuery = (key) => {
const search = window.location.search.substr(1) || window.location.hash.split("?")[1];
const reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
const r = search === null || search === void 0 ? void 0 : search.match(reg);
if (r != null)
return unescape(r[2]);
return null;
};
const isWechat = () => {
var _a;
const ua = window.navigator.userAgent.toLowerCase();
if (((_a = ua.match(/micromessenger/i)) === null || _a === void 0 ? void 0 : _a.toString()) == "micromessenger")
return true;
else
return false;
};
export { Updater, camelize, capitalize, clone, colorGradient, colorToDark, colorToLight, colorToRgba, debounce, getDatesBetween, getUrlQuery, hexToRgb, hyphenate, isWechat, merge, rgbToHex, setUnit, throttle, trim };