@jinming6/ming-tool
Version:
Front-end tool library
388 lines (376 loc) • 11.2 kB
JavaScript
import { i as isPlainObject, a as isString, b as isArray, c as cloneDeep, d as isArrayBuffer, e as isNumber } from './chunks/vendor-DhDXQY8D.js';
function warn(msg) {
console.warn(`[${"@jinming6/ming-tool"} warn] ${msg}`);
}
const DefaultReplaceStr = '--';
const DefaultSplitStr = ',';
/**
* 空值替换
*/
function replaceEmpty(str, replaceStr = DefaultReplaceStr) {
if (str === null || str === undefined || str === '') {
return replaceStr;
}
return str;
}
/**
* 格式化地址字符串
*/
function fmtAddressStr(options) {
if (!isPlainObject(options)) {
warn('options必须是一个对象');
}
const { addressStr, needSplit = true, splitFlag = DefaultSplitStr, needJoin = true, joinFlag = DefaultSplitStr, extraStrArr = [], } = options;
if (!isString(addressStr)) {
warn('addressStr必须是一个字符串');
return addressStr;
}
let addressArr = [];
if (needSplit) {
addressArr = addressStr.split(splitFlag).filter((item) => item !== '');
}
if (isArray(extraStrArr)) {
addressArr.push(...extraStrArr);
}
else {
warn('extraStrArr必须是一个数组');
}
if (needJoin) {
return addressArr.join(joinFlag);
}
return addressArr;
}
const DefaultFieldsName = { label: 'label', value: 'value' };
class Option {
constructor(options) {
this.dataSource = [];
this.fieldsName = DefaultFieldsName;
const { dataSource, fieldsName } = options;
this.dataSource = isArray(dataSource) ? cloneDeep(dataSource) : [];
this.fieldsName = isPlainObject(fieldsName)
? fieldsName
: DefaultFieldsName;
}
/**
* 获取下拉选项
*/
get options() {
return this.dataSource;
}
/**
* 获取label映射对象
*/
get labelMap() {
const map = {};
this.dataSource.forEach((item) => {
if (this.fieldsName.value in item && this.fieldsName.label in item) {
const key = item[this.fieldsName.value];
const label = item[this.fieldsName.label];
map[key] = label;
}
});
return map;
}
/**
* 获取label
*/
getLabel(options) {
if (!isPlainObject(options)) {
warn('getLabel的参数必须是一个对象');
}
const { key, allowReplaceEmpty = false, replaceStr = DefaultReplaceStr, } = options;
const label = this.labelMap[key];
return allowReplaceEmpty
? replaceEmpty(label, replaceStr)
: label;
}
/**
* 更新
*/
update(options) {
if (!isPlainObject(options)) {
warn('update的参数必须是一个对象');
}
const { dataSource, fieldsName } = options;
if (isArray(dataSource)) {
this.dataSource = cloneDeep(dataSource);
}
if (isPlainObject(fieldsName)) {
this.fieldsName = fieldsName;
}
}
}
/**
* 输入的类型
*/
var InputType;
(function (InputType) {
InputType["ArrayBuffer"] = "arrayBuffer";
InputType["URL"] = "url";
})(InputType || (InputType = {}));
/**
* 下载文件(arrayBuffer)
*/
function downloadArrayBuffer(stream, filename) {
try {
const blob = new Blob([stream], { type: 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.target = '_blank';
a.click();
URL.revokeObjectURL(url);
return true;
}
catch (e) {
warn(`下载文件流失败 ${e.message}`);
return false;
}
}
/**
* 转换为webp格式
*/
function convert2Webp(file, quality = 0.8) {
return new Promise((resolve, reject) => {
if (!file.type.startsWith('image/')) {
reject(new Error('不是图片类型'));
return;
}
if (file.type === 'image/webp') {
resolve(file);
return;
}
const url = window.URL.createObjectURL(file);
const img = new window.Image();
img.src = url;
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
if (ctx === null) {
reject(new Error('无法获取canvas上下文'));
window.URL.revokeObjectURL(url);
return;
}
ctx.drawImage(img, 0, 0, img.width, img.height);
canvas.toBlob((blob) => {
if (blob == null) {
reject(new Error('无法获取blob对象'));
window.URL.revokeObjectURL(url);
return;
}
resolve(blob);
window.URL.revokeObjectURL(url);
}, 'image/webp', quality);
};
img.onerror = (err) => {
reject(err);
window.URL.revokeObjectURL(url);
};
});
}
/**
* 下载文件(url)
*/
function downloadUrl(url, filename) {
try {
const a = document.createElement('a');
a.href = url;
a.setAttribute('download', filename);
a.target = '_blank';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
return true;
}
catch (e) {
warn(`下载文件失败 ${e.message}`);
return false;
}
}
/**
* 下载文件
* @deprecated 从 1.2.3 版本开始
* 请使用 downloadFileV2 代替
*/
function downloadFile(options) {
const { inputType = InputType.URL, filename, url, arrayBuffer } = options;
if (!isString(filename)) {
warn('filename 不能为空');
return false;
}
if (inputType === InputType.ArrayBuffer) {
if (!isArrayBuffer(arrayBuffer)) {
warn('arrayBuffer 不能为空');
return false;
}
return downloadArrayBuffer(arrayBuffer, filename);
}
if (!isString(url)) {
warn('url 不能为空');
return false;
}
return downloadUrl(url, filename);
}
/**
* 下载文件 v2
*/
function downloadFileV2(options) {
const { type = InputType.URL, filename, dataSource } = options;
if (!isString(filename)) {
warn('filename 不能为空');
return false;
}
if (type === InputType.ArrayBuffer) {
if (!isArrayBuffer(dataSource)) {
warn('dataSource 不能为空');
return false;
}
return downloadArrayBuffer(dataSource, filename);
}
if (!isString(dataSource)) {
warn('dataSource 不能为空');
return false;
}
return downloadUrl(dataSource, filename);
}
var ColorType;
(function (ColorType) {
ColorType["RGB"] = "rgb";
ColorType["HEX"] = "hex";
})(ColorType || (ColorType = {}));
/**
* 随机rgb
* @deprecated
*/
const getRandomRgb = () => {
const random = () => {
return Math.floor(Math.random() * 256);
};
return `rgb(${random()}, ${random()}, ${random()})`;
};
/**
* 随机hex
* @deprecated
*/
const getRandomHex = () => {
const random = () => {
return Math.floor(Math.random() * 256).toString(16);
};
return `#${random()}${random()}${random()}`;
};
/**
* 生成随机色值
*/
const getRandomColor = (options) => {
const { type, lightColor } = options;
const minNum = (lightColor !== null && lightColor !== void 0 ? lightColor : false) ? 256 : 201;
const random = () => {
return Math.floor(Math.random() * minNum);
};
if (type === ColorType.RGB) {
return `rgb(${random()}, ${random()}, ${random()})`;
}
const randomHex = () => {
return random().toString(16);
};
return `#${randomHex()}${randomHex()}${randomHex()}`;
};
/**
* 从url中获取文件名
*/
function getFilenameFromUrl(url) {
if (!isString(url) || url === '') {
warn('url为空');
return '';
}
const arr = url.split('/');
return arr[arr.length - 1];
}
/**
* 从content-disposition中获取文件ming
*/
function getFilenameFromDisposition(contentDisposition, decode = true, decodeCallback = decodeURIComponent) {
if (!isString(contentDisposition))
return null;
// 尝试解析 `filename*`(使用RFC 5987编码)
const filenameStarMatch = contentDisposition.match(/filename\*=[^;]+/);
if (filenameStarMatch != null) {
const filenameStar = filenameStarMatch[0];
const parts = filenameStar.split("'");
if (parts.length === 3) {
return decode ? decodeCallback(parts[2]) : parts[2];
}
}
// 尝试解析 `filename`
const filenameMatch = contentDisposition.match(/filename="([^"]+)"/);
if (filenameMatch != null) {
return decode ? decodeCallback(filenameMatch[1]) : filenameMatch[1];
}
// 尝试解析未加引号的 `filename`
const filenameMatchUnquoted = contentDisposition.match(/filename=([^;]+)/);
if (filenameMatchUnquoted != null) {
return decode
? decodeCallback(filenameMatchUnquoted[1])
: filenameMatchUnquoted[1];
}
return null;
}
// 默认的字段名
const DEFAULT_FIELDS = {
startDate: 'startDate',
endDate: 'endDate',
};
/**
* 检查日期值是否有效
*/
function checkDateValue(dateValue) {
return isString(dateValue) || isNumber(dateValue);
}
/**
* 拆分日期区间
*/
function splitDateRange(options) {
if (!isPlainObject(options)) {
warn('options必须是一个对象');
return {};
}
const { dateRange, outStartField = DEFAULT_FIELDS.startDate, outEndField = DEFAULT_FIELDS.endDate, defaultValue = null, } = options;
const result = {
[outStartField]: defaultValue,
[outEndField]: defaultValue,
};
if (!isArray(dateRange) || dateRange.length !== 2) {
return result;
}
result[outStartField] = dateRange[0];
result[outEndField] = dateRange[1];
return result;
}
/**
* 组合日期区间
*/
function combineDateRange(options) {
const result = [];
if (!isPlainObject(options)) {
warn('options必须是一个对象');
return result;
}
const { obj, inStartField = DEFAULT_FIELDS.startDate, inEndField = DEFAULT_FIELDS.endDate, } = options;
if (!isPlainObject(obj)) {
warn('obj必须是一个对象');
return result;
}
const startDateValue = obj[inStartField];
const endDateValue = obj[inEndField];
if (!checkDateValue(startDateValue) || !checkDateValue(endDateValue)) {
return result;
}
result.push(startDateValue);
result.push(endDateValue);
return result;
}
export { DefaultFieldsName, DefaultReplaceStr, DefaultSplitStr, Option, combineDateRange, convert2Webp, downloadArrayBuffer, downloadFile, downloadFileV2, downloadUrl, fmtAddressStr, getFilenameFromDisposition, getFilenameFromUrl, getRandomColor, getRandomHex, getRandomRgb, replaceEmpty, splitDateRange };