lyb-js 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/package.json +1 -1
  2. package/dist/Base/LibGetDataType/index.d.ts +0 -10
  3. package/dist/Base/LibGetDataType/index.js +0 -15
  4. package/dist/Base/LibPromiseTimeout/index.d.ts +0 -10
  5. package/dist/Base/LibPromiseTimeout/index.js +0 -40
  6. package/dist/Browser/LibColorConsole/index.d.ts +0 -15
  7. package/dist/Browser/LibColorConsole/index.js +0 -38
  8. package/dist/Browser/LibIsMobile/index.d.ts +0 -6
  9. package/dist/Browser/LibIsMobile/index.js +0 -9
  10. package/dist/Browser/LibIsPad/index.d.ts +0 -6
  11. package/dist/Browser/LibIsPad/index.js +0 -15
  12. package/dist/Browser/LibPathParams/index.d.ts +0 -6
  13. package/dist/Browser/LibPathParams/index.js +0 -16
  14. package/dist/Browser/LibSetTitleIcon/index.d.ts +0 -7
  15. package/dist/Browser/LibSetTitleIcon/index.js +0 -14
  16. package/dist/Browser/LibTagTitleTip/index.d.ts +0 -7
  17. package/dist/Browser/LibTagTitleTip/index.js +0 -24
  18. package/dist/Data/LibChunkArray/index.d.ts +0 -9
  19. package/dist/Data/LibChunkArray/index.js +0 -15
  20. package/dist/Data/LibDeepJSONParse/index.d.ts +0 -6
  21. package/dist/Data/LibDeepJSONParse/index.js +0 -32
  22. package/dist/Data/LibGroupArrayByKey/index.d.ts +0 -10
  23. package/dist/Data/LibGroupArrayByKey/index.js +0 -20
  24. package/dist/Data/LibMatchEmail/index.d.ts +0 -10
  25. package/dist/Data/LibMatchEmail/index.js +0 -16
  26. package/dist/Data/LibShuffleArray/index.d.ts +0 -7
  27. package/dist/Data/LibShuffleArray/index.js +0 -14
  28. package/dist/Data/LibStepArray/index.d.ts +0 -8
  29. package/dist/Data/LibStepArray/index.js +0 -14
  30. package/dist/File/LibDownloadImageLink/index.d.ts +0 -7
  31. package/dist/File/LibDownloadImageLink/index.js +0 -17
  32. package/dist/File/LibImageOptimizer/index.d.ts +0 -32
  33. package/dist/File/LibImageOptimizer/index.js +0 -83
  34. package/dist/File/LibSaveJson/index.d.ts +0 -9
  35. package/dist/File/LibSaveJson/index.js +0 -17
  36. package/dist/Formatter/LibFormatterByte/index.d.ts +0 -9
  37. package/dist/Formatter/LibFormatterByte/index.js +0 -17
  38. package/dist/Formatter/LibMaskPhoneNumber/index.d.ts +0 -8
  39. package/dist/Formatter/LibMaskPhoneNumber/index.js +0 -11
  40. package/dist/Formatter/LibNumComma/index.d.ts +0 -9
  41. package/dist/Formatter/LibNumComma/index.js +0 -13
  42. package/dist/Formatter/LibNumberUnit/index.d.ts +0 -12
  43. package/dist/Formatter/LibNumberUnit/index.js +0 -23
  44. package/dist/Formatter/LibSecondsFormatterChinese/index.d.ts +0 -11
  45. package/dist/Formatter/LibSecondsFormatterChinese/index.js +0 -42
  46. package/dist/Math/LibCalculateExpression/index.d.ts +0 -9
  47. package/dist/Math/LibCalculateExpression/index.js +0 -107
  48. package/dist/Math/LibConvertAngle/index.d.ts +0 -12
  49. package/dist/Math/LibConvertAngle/index.js +0 -22
  50. package/dist/Math/LibCoordsAngle/index.d.ts +0 -15
  51. package/dist/Math/LibCoordsAngle/index.js +0 -24
  52. package/dist/Math/LibCoordsDistance/index.d.ts +0 -15
  53. package/dist/Math/LibCoordsDistance/index.js +0 -16
  54. package/dist/Math/LibDecimal/index.d.ts +0 -10
  55. package/dist/Math/LibDecimal/index.js +0 -25
  56. package/dist/Misc/LibRegFormValidate/index.d.ts +0 -32
  57. package/dist/Misc/LibRegFormValidate/index.js +0 -34
  58. package/dist/Misc/LibRetryRequest/index.d.ts +0 -24
  59. package/dist/Misc/LibRetryRequest/index.js +0 -37
  60. package/dist/Random/LibProbabilityResult/index.d.ts +0 -8
  61. package/dist/Random/LibProbabilityResult/index.js +0 -8
  62. package/dist/Random/LibRandom/index.d.ts +0 -9
  63. package/dist/Random/LibRandom/index.js +0 -11
  64. package/dist/Random/LibRandomColor/index.d.ts +0 -7
  65. package/dist/Random/LibRandomColor/index.js +0 -12
  66. package/dist/Random/LibUniqueRandomNumbers/index.d.ts +0 -9
  67. package/dist/Random/LibUniqueRandomNumbers/index.js +0 -16
  68. package/dist/Time/LibSameTimeCheck/index.d.ts +0 -12
  69. package/dist/Time/LibSameTimeCheck/index.js +0 -24
  70. package/dist/Time/LibTimeAgo/index.d.ts +0 -9
  71. package/dist/Time/LibTimeAgo/index.js +0 -27
  72. package/dist/Time/LibTimeGreeting/index.d.ts +0 -17
  73. package/dist/Time/LibTimeGreeting/index.js +0 -23
  74. package/dist/lib.d.ts +0 -394
  75. package/dist/lib.js +0 -404
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lyb-js",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "author": "冷弋白",
5
5
  "description": "lyb自用JS方法库",
6
6
  "repository": {
@@ -1,10 +0,0 @@
1
- export type LibGetDataTypeReturnType = "string" | "number" | "boolean" | "array" | "function" | "object";
2
- /**
3
- * @description 返回数据类型
4
- * @param v 需要判断类型的数据
5
- * @example
6
- * libGetDataType(123); //"number"
7
- * libGetDataType("hello"); //"string"
8
- * libGetDataType([1, 2, 3]); //"array"
9
- */
10
- export declare const libGetDataType: (v: any) => LibGetDataTypeReturnType;
@@ -1,15 +0,0 @@
1
- /**
2
- * @description 返回数据类型
3
- * @param v 需要判断类型的数据
4
- * @example
5
- * libGetDataType(123); //"number"
6
- * libGetDataType("hello"); //"string"
7
- * libGetDataType([1, 2, 3]); //"array"
8
- */
9
- export const libGetDataType = (v) => {
10
- return Object.prototype.toString
11
- .call(v)
12
- .substring(8)
13
- .replace(/]/g, "")
14
- .toLowerCase();
15
- };
@@ -1,10 +0,0 @@
1
- /**
2
- * @description 延时执行,切换到其他页面会暂停
3
- * @param delay 延时毫秒数
4
- * @param fn 延时执行函数
5
- * @example
6
- * libPromiseTimeout(3000, () => {
7
- * console.log("执行延时函数");
8
- * });
9
- */
10
- export declare const libPromiseTimeout: (delay?: number, fn?: () => void) => Promise<void>;
@@ -1,40 +0,0 @@
1
- /**
2
- * @description 延时执行,切换到其他页面会暂停
3
- * @param delay 延时毫秒数
4
- * @param fn 延时执行函数
5
- * @example
6
- * libPromiseTimeout(3000, () => {
7
- * console.log("执行延时函数");
8
- * });
9
- */
10
- export const libPromiseTimeout = (delay = 1, fn) => {
11
- let timeoutId;
12
- let remainingTime = delay;
13
- let startTime = Date.now();
14
- let isPaused = false;
15
- return new Promise((resolve) => {
16
- const handleVisibilityChange = () => {
17
- if (document.hidden) {
18
- isPaused = true;
19
- clearTimeout(timeoutId);
20
- remainingTime -= Date.now() - startTime;
21
- }
22
- else {
23
- if (isPaused) {
24
- isPaused = false;
25
- startTime = Date.now();
26
- startTimeout(resolve);
27
- }
28
- }
29
- };
30
- const startTimeout = (resolve) => {
31
- timeoutId = setTimeout(() => {
32
- fn?.();
33
- resolve();
34
- document.removeEventListener("visibilitychange", handleVisibilityChange);
35
- }, remainingTime);
36
- };
37
- document.addEventListener("visibilitychange", handleVisibilityChange);
38
- startTimeout(resolve);
39
- });
40
- };
@@ -1,15 +0,0 @@
1
- /** @description console颜色打印
2
- * @param title 标题
3
- * @param color 颜色
4
- * @param logs 信息
5
- * @example
6
- * //使用红色打印日志
7
- * libColorConsole("错误提示", "red", [{ label: "错误代码", value: 500 }]);
8
- *
9
- * //使用蓝色打印简单日志
10
- * libColorConsole("信息", "blue", "操作成功");
11
- */
12
- export declare const libColorConsole: (title: string, color: "red" | "orange" | "yellow" | "green" | "blue" | "purple", logs?: {
13
- label: string;
14
- value: any;
15
- }[] | any) => void;
@@ -1,38 +0,0 @@
1
- /** @description console颜色打印
2
- * @param title 标题
3
- * @param color 颜色
4
- * @param logs 信息
5
- * @example
6
- * //使用红色打印日志
7
- * libColorConsole("错误提示", "red", [{ label: "错误代码", value: 500 }]);
8
- *
9
- * //使用蓝色打印简单日志
10
- * libColorConsole("信息", "blue", "操作成功");
11
- */
12
- export const libColorConsole = (title, color, logs = []) => {
13
- const colors = {
14
- red: "#c0392b",
15
- orange: "#d35400",
16
- yellow: "#f1c40f",
17
- green: "#27ae60",
18
- blue: "#2980b9",
19
- purple: "#be2edd",
20
- };
21
- //时间戳生成函数
22
- const getTimestamp = () => {
23
- const now = new Date();
24
- const hour = String(now.getHours()).padStart(2, "0");
25
- const minutes = String(now.getMinutes()).padStart(2, "0");
26
- const seconds = String(now.getSeconds()).padStart(2, "0");
27
- return `[${hour}:${minutes}:${seconds}]`;
28
- };
29
- if (Array.isArray(logs)) {
30
- const v = logs.map((log) => {
31
- return [`\n${log.label}:`, log.value];
32
- });
33
- console.log(`%c${getTimestamp()}-${title}`, `color: #fff;background: ${colors[color]}; font-size:14px;border-radius:5px;padding:0.25em;margin:0.5em 0`, ...v.flat(Infinity));
34
- }
35
- else {
36
- console.log(`%c${getTimestamp()}-${title}`, `color: #fff;background: ${colors[color]}; font-size:14px;border-radius:5px;padding:0.25em;margin:0.5em 0`, logs);
37
- }
38
- };
@@ -1,6 +0,0 @@
1
- /** @description 判断是否为移动设备
2
- * @example
3
- * const isMobile = libIsMobile();
4
- * console.log(isMobile); //true 或 false
5
- */
6
- export declare const libIsMobile: () => boolean;
@@ -1,9 +0,0 @@
1
- /** @description 判断是否为移动设备
2
- * @example
3
- * const isMobile = libIsMobile();
4
- * console.log(isMobile); //true 或 false
5
- */
6
- export const libIsMobile = () => {
7
- const ua = navigator.userAgent.toLowerCase();
8
- return /mobile|android|iphone|ipod/.test(ua);
9
- };
@@ -1,6 +0,0 @@
1
- /** @description 判断是否为平板
2
- * @example
3
- * const isPad = libIsPad();
4
- * console.log(isPad); //true 或 false
5
- */
6
- export declare const libIsPad: () => boolean;
@@ -1,15 +0,0 @@
1
- /** @description 判断是否为平板
2
- * @example
3
- * const isPad = libIsPad();
4
- * console.log(isPad); //true 或 false
5
- */
6
- export const libIsPad = () => {
7
- const ua = navigator.userAgent.toLowerCase();
8
- const width = Math.max(window.screen.width, window.screen.height);
9
- const height = Math.min(window.screen.width, window.screen.height);
10
- const aspectRatio = width / height;
11
- const isTabletUserAgent = /ipad|tablet|playbook|silk/.test(ua) && !/mobile/.test(ua);
12
- const isTabletWidth = width >= 768 && width <= 1366;
13
- const isTabletAspectRatio = aspectRatio >= 1.3 && aspectRatio <= 1.6;
14
- return isTabletUserAgent || (isTabletWidth && isTabletAspectRatio);
15
- };
@@ -1,6 +0,0 @@
1
- /** @description 获取浏览器地址栏参数
2
- * @example
3
- * const params = libPathParams();
4
- * console.log(params); //{ param1: "value1", param2: "value2" }
5
- */
6
- export declare const libPathParams: () => Record<string, string>;
@@ -1,16 +0,0 @@
1
- /** @description 获取浏览器地址栏参数
2
- * @example
3
- * const params = libPathParams();
4
- * console.log(params); //{ param1: "value1", param2: "value2" }
5
- */
6
- export const libPathParams = () => {
7
- const v = location.href;
8
- const url = v.split("?")[1];
9
- if (!url)
10
- return {};
11
- const params = url.split("&").reduce((pre, cur) => {
12
- const [k, v] = cur.split(/=(.+)/);
13
- return (pre[k] = v), pre;
14
- }, {}) || {};
15
- return params;
16
- };
@@ -1,7 +0,0 @@
1
- /** @description 动态设置网站标题及图标
2
- * @param title 网站标题
3
- * @param url 网站图标地址
4
- * @example
5
- * libSetTitleIcon("我的网站", "https://example.com/favicon.ico");
6
- */
7
- export declare const libSetTitleIcon: (title: string, url: string) => void;
@@ -1,14 +0,0 @@
1
- /** @description 动态设置网站标题及图标
2
- * @param title 网站标题
3
- * @param url 网站图标地址
4
- * @example
5
- * libSetTitleIcon("我的网站", "https://example.com/favicon.ico");
6
- */
7
- export const libSetTitleIcon = (title, url) => {
8
- document.title = title;
9
- const link = document.createElement("link");
10
- link.setAttribute("rel", "icon");
11
- link.setAttribute("href", url);
12
- const head = document.head || document.getElementsByTagName("head")[0];
13
- head.appendChild(link);
14
- };
@@ -1,7 +0,0 @@
1
- /** @description 网站标题交互,当从当前网页切换到其他网页,网站标题自动切换
2
- * @param backTitle 从其他网页返回时显示的标题
3
- * @param leaveTitle 从当前网页离开时显示的标题
4
- * * @example
5
- * libTagTitleTip("欢迎回来", "来和妲己玩耍吧!");
6
- */
7
- export declare const libTagTitleTip: (backTitle: string, leaveTitle: string) => void;
@@ -1,24 +0,0 @@
1
- /** @description 网站标题交互,当从当前网页切换到其他网页,网站标题自动切换
2
- * @param backTitle 从其他网页返回时显示的标题
3
- * @param leaveTitle 从当前网页离开时显示的标题
4
- * * @example
5
- * libTagTitleTip("欢迎回来", "来和妲己玩耍吧!");
6
- */
7
- export const libTagTitleTip = (backTitle, leaveTitle) => {
8
- let document_title = "";
9
- let timer;
10
- window.addEventListener("visibilitychange", () => {
11
- clearTimeout(timer);
12
- if (document.hidden) {
13
- if (document.title !== backTitle) {
14
- document_title = document.title;
15
- }
16
- document.title = leaveTitle;
17
- return;
18
- }
19
- document.title = backTitle;
20
- timer = setTimeout(() => {
21
- document.title = document_title;
22
- }, 1000);
23
- });
24
- };
@@ -1,9 +0,0 @@
1
- /**
2
- * @description 将数组拆分成指定数组元素数量的多个数组
3
- * @param arr 需要拆分的数组
4
- * @param chunkSize 每个数组的元素数量
5
- * @example
6
- * const chunks = libChunkArray([1, 2, 3, 4, 5, 6], 2);
7
- * console.log(chunks); //[[1, 2], [3, 4], [5, 6]]
8
- */
9
- export declare const libChunkArray: <T>(arr: T[], chunkSize: number) => T[][];
@@ -1,15 +0,0 @@
1
- /**
2
- * @description 将数组拆分成指定数组元素数量的多个数组
3
- * @param arr 需要拆分的数组
4
- * @param chunkSize 每个数组的元素数量
5
- * @example
6
- * const chunks = libChunkArray([1, 2, 3, 4, 5, 6], 2);
7
- * console.log(chunks); //[[1, 2], [3, 4], [5, 6]]
8
- */
9
- export const libChunkArray = (arr, chunkSize) => {
10
- const result = [];
11
- for (let i = 0; i < arr.length; i += chunkSize) {
12
- result.push(arr.slice(i, i + chunkSize));
13
- }
14
- return result;
15
- };
@@ -1,6 +0,0 @@
1
- /** @description 递归将JSON字符串深度解析为对象
2
- * @example
3
- * const obj = libDeepJSONParse('{"a": 1, "b": "{\"c\": 2}"}');
4
- * console.log(obj); //{ a: 1, b: { c: 2 } }
5
- */
6
- export declare const libDeepJSONParse: <T>(data: any) => T;
@@ -1,32 +0,0 @@
1
- /** @description 递归将JSON字符串深度解析为对象
2
- * @example
3
- * const obj = libDeepJSONParse('{"a": 1, "b": "{\"c\": 2}"}');
4
- * console.log(obj); //{ a: 1, b: { c: 2 } }
5
- */
6
- export const libDeepJSONParse = (data) => {
7
- //检查是否为字符串并尝试解析
8
- if (typeof data === "string") {
9
- try {
10
- const parsed = JSON.parse(data);
11
- //递归解析解析后的结果
12
- return libDeepJSONParse(parsed);
13
- }
14
- catch {
15
- //如果解析失败,返回原始字符串
16
- return data;
17
- }
18
- }
19
- //如果是数组,递归处理每个元素
20
- if (Array.isArray(data)) {
21
- return data.map((item) => libDeepJSONParse(item));
22
- }
23
- //如果是对象,递归处理每个属性值
24
- if (data !== null && typeof data === "object") {
25
- return Object.keys(data).reduce((acc, key) => {
26
- acc[key] = libDeepJSONParse(data[key]);
27
- return acc;
28
- }, {});
29
- }
30
- //其他情况返回原始值
31
- return data;
32
- };
@@ -1,10 +0,0 @@
1
- /**
2
- * @description 分类汇总,将数组对象按照指定键值整理成一个以键值为键名的对象
3
- * @param arr 要分组的数组
4
- * @param key 分组的键
5
- * @returns 分组后的对象
6
- * @example
7
- * const grouped = libGroupArrayByKey([{ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 1, name: 'C' }], 'id');
8
- * console.log(grouped); //{ 1: [{ id: 1, name: 'A' }, { id: 1, name: 'C' }], 2: [{ id: 2, name: 'B' }] }
9
- */
10
- export declare const libGroupArrayByKey: (arr: any[] | undefined, key: string) => any;
@@ -1,20 +0,0 @@
1
- /**
2
- * @description 分类汇总,将数组对象按照指定键值整理成一个以键值为键名的对象
3
- * @param arr 要分组的数组
4
- * @param key 分组的键
5
- * @returns 分组后的对象
6
- * @example
7
- * const grouped = libGroupArrayByKey([{ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 1, name: 'C' }], 'id');
8
- * console.log(grouped); //{ 1: [{ id: 1, name: 'A' }, { id: 1, name: 'C' }], 2: [{ id: 2, name: 'B' }] }
9
- */
10
- export const libGroupArrayByKey = (arr = [], key) => {
11
- return key
12
- ? arr.reduce((t, v) => {
13
- if (!t[v[key]]) {
14
- t[v[key]] = [];
15
- }
16
- t[v[key]].push(v);
17
- return t;
18
- }, {})
19
- : {};
20
- };
@@ -1,10 +0,0 @@
1
- /**
2
- * @description 匹配电子邮件,可用于实时输入时,自动补全常用邮箱后缀
3
- * @param str 要匹配的字符串
4
- * @param emailList 电子邮件后缀列表
5
- * @returns 匹配结果数组
6
- * @example
7
- * const emails = libMatchEmail("user", ["@gmail.com", "@yahoo.com"]);
8
- * console.log(emails); //["user@gmail.com", "user@yahoo.com"]
9
- */
10
- export declare const libMatchEmail: (str: string, emailList: string[]) => string[];
@@ -1,16 +0,0 @@
1
- /**
2
- * @description 匹配电子邮件,可用于实时输入时,自动补全常用邮箱后缀
3
- * @param str 要匹配的字符串
4
- * @param emailList 电子邮件后缀列表
5
- * @returns 匹配结果数组
6
- * @example
7
- * const emails = libMatchEmail("user", ["@gmail.com", "@yahoo.com"]);
8
- * console.log(emails); //["user@gmail.com", "user@yahoo.com"]
9
- */
10
- export const libMatchEmail = (str, emailList) => {
11
- return str.includes("@")
12
- ? emailList
13
- .filter((item) => item.includes(str.slice(str.indexOf("@"))))
14
- .map((item) => (str.includes("@") ? str.split("@")[0] : str) + item)
15
- : emailList.map((item) => str + item);
16
- };
@@ -1,7 +0,0 @@
1
- /** @description 将数组打乱顺序
2
- * @param arr 需要乱序的数组
3
- * @example
4
- * const shuffled = libShuffleArray([1, 2, 3, 4, 5]);
5
- * console.log(shuffled); //[3, 5, 2, 1, 4] (结果每次不同)
6
- */
7
- export declare const libShuffleArray: <T>(arr: T[]) => T[];
@@ -1,14 +0,0 @@
1
- /** @description 将数组打乱顺序
2
- * @param arr 需要乱序的数组
3
- * @example
4
- * const shuffled = libShuffleArray([1, 2, 3, 4, 5]);
5
- * console.log(shuffled); //[3, 5, 2, 1, 4] (结果每次不同)
6
- */
7
- export const libShuffleArray = (arr) => {
8
- const newArr = [...arr];
9
- for (let i = newArr.length - 1; i > 0; i--) {
10
- const j = Math.floor(Math.random() * (i + 1));
11
- [newArr[i], newArr[j]] = [newArr[j], newArr[i]];
12
- }
13
- return newArr;
14
- };
@@ -1,8 +0,0 @@
1
- /** @description 数组元素整体步数移动
2
- * @param arr 移动的数组
3
- * @param step 负数为向后移动,正数为向前移动
4
- * @example
5
- * const moved = libStepArray([1, 2, 3, 4, 5], 2);
6
- * console.log(moved); //[4, 5, 1, 2, 3]
7
- */
8
- export declare const libStepArray: <T>(arr: T[], step: number) => T[];
@@ -1,14 +0,0 @@
1
- /** @description 数组元素整体步数移动
2
- * @param arr 移动的数组
3
- * @param step 负数为向后移动,正数为向前移动
4
- * @example
5
- * const moved = libStepArray([1, 2, 3, 4, 5], 2);
6
- * console.log(moved); //[4, 5, 1, 2, 3]
7
- */
8
- export const libStepArray = (arr, step) => {
9
- const length = arr.length;
10
- if (length === 0 || step % length === 0)
11
- return arr;
12
- const normalizedStep = ((step % length) + length) % length;
13
- return arr.slice(-normalizedStep).concat(arr.slice(0, -normalizedStep));
14
- };
@@ -1,7 +0,0 @@
1
- /** @description 将链接图片下载到本地
2
- * @param link 图片链接
3
- * @param name 图片名称
4
- * @example
5
- * libDownloadImageLink("https://example.com/image.jpg", "图片.jpg");
6
- */
7
- export declare const libDownloadImageLink: (link: string, name: string) => void;
@@ -1,17 +0,0 @@
1
- /** @description 将链接图片下载到本地
2
- * @param link 图片链接
3
- * @param name 图片名称
4
- * @example
5
- * libDownloadImageLink("https://example.com/image.jpg", "图片.jpg");
6
- */
7
- export const libDownloadImageLink = (link, name) => {
8
- fetch(link)
9
- .then((res) => res.blob())
10
- .then((blob) => {
11
- const a = document.createElement("a");
12
- const url = window.URL.createObjectURL(blob);
13
- a.href = url;
14
- a.download = name;
15
- a.click();
16
- });
17
- };
@@ -1,32 +0,0 @@
1
- /** @description 图片压缩参数 */
2
- export type LibImageOptimizerOptionsParams = {
3
- file?: File;
4
- /** 压缩尺寸 */
5
- width?: number;
6
- /** 压缩率 */
7
- ratio?: number;
8
- /** 超过多大进行压缩 */
9
- maxSize?: number;
10
- /** 成功回调 */
11
- success: (formData: FormData, file: File, url: string) => void;
12
- /** 失败回调 */
13
- fail?: (error: ErrorEvent) => void;
14
- };
15
- /** @description 图片压缩,支持png压缩,保留透明背景
16
- * @param obj 压缩参数
17
- * @example
18
- * //图片压缩使用示例
19
- * libImageOptimizerOptionsParams({
20
- * file: myFile,
21
- * ratio: 0.8,
22
- * width: 800,
23
- * maxSize: 1024,
24
- * success: (formData, file, url) => {
25
- * console.log('压缩成功', formData, file, url);
26
- * },
27
- * fail: (error) => {
28
- * console.error('压缩失败', error);
29
- * }
30
- * });
31
- */
32
- export declare const libImageOptimizer: (obj: LibImageOptimizerOptionsParams) => void;
@@ -1,83 +0,0 @@
1
- /** @description 图片压缩,支持png压缩,保留透明背景
2
- * @param obj 压缩参数
3
- * @example
4
- * //图片压缩使用示例
5
- * libImageOptimizerOptionsParams({
6
- * file: myFile,
7
- * ratio: 0.8,
8
- * width: 800,
9
- * maxSize: 1024,
10
- * success: (formData, file, url) => {
11
- * console.log('压缩成功', formData, file, url);
12
- * },
13
- * fail: (error) => {
14
- * console.error('压缩失败', error);
15
- * }
16
- * });
17
- */
18
- export const libImageOptimizer = (obj) => {
19
- const canvas = document.createElement("canvas");
20
- canvas.classList.add("imageOptimizer");
21
- document.body.appendChild(canvas);
22
- const files = obj.file;
23
- if (!files)
24
- return;
25
- const name = files.name;
26
- const extension = name.split(".").pop().toLowerCase();
27
- const ratio = obj.ratio || 1;
28
- const maxSize = obj.maxSize || 1024;
29
- const width = obj.width || 10000;
30
- const mimeType = files.type;
31
- function dataURLtoFile(dataURL, filename) {
32
- const arr = dataURL.split(",");
33
- const mime = arr[0].match(/:(.*?);/)[1];
34
- const bstr = window.atob(arr[1]);
35
- const n = bstr.length;
36
- const u8arr = new Uint8Array(n);
37
- for (let i = 0; i < n; i++) {
38
- u8arr[i] = bstr.charCodeAt(i);
39
- }
40
- return new File([u8arr], filename, { type: mime });
41
- }
42
- function formData(file) {
43
- const data = new FormData();
44
- data.append("file", file);
45
- return data;
46
- }
47
- const reader = new FileReader();
48
- reader.readAsDataURL(files);
49
- reader.onload = (e) => {
50
- const result = e.target.result;
51
- if (e.total / 1024 > maxSize) {
52
- const image = new Image();
53
- image.src = result;
54
- image.onload = () => {
55
- const context = canvas.getContext("2d");
56
- const scale = width / image.width;
57
- if (scale < 1) {
58
- canvas.width = image.width * scale;
59
- canvas.height = image.height * scale;
60
- context.drawImage(image, 0, 0, image.width * scale, image.height * scale);
61
- }
62
- else {
63
- canvas.width = image.width;
64
- canvas.height = image.height;
65
- context.drawImage(image, 0, 0, image.width, image.height);
66
- }
67
- const dataUrl = canvas.toDataURL(mimeType, ratio);
68
- const newName = `${name.split(".")[0]}.${extension}`;
69
- const file = dataURLtoFile(dataUrl, newName);
70
- obj.success(formData(file), file, dataUrl);
71
- canvas.remove();
72
- };
73
- image.onerror = obj.fail;
74
- }
75
- else {
76
- const newName = `${name.split(".")[0]}.${extension}`;
77
- const file = dataURLtoFile(result, newName);
78
- obj.success(formData(file), file, result);
79
- canvas.remove();
80
- }
81
- };
82
- reader.onerror = obj.fail;
83
- };
@@ -1,9 +0,0 @@
1
- /**
2
- * @description 保存文件到本地
3
- * @param data 要保存的数据
4
- * @param name 文件名
5
- * @example
6
- * libSaveJson(JSON.stringify({ key: "value" }), "example.json");
7
- * libSaveJson("Hellow World!", "example.txt");
8
- */
9
- export declare const libSaveJson: (data: BlobPart, name: string) => void;
@@ -1,17 +0,0 @@
1
- /**
2
- * @description 保存文件到本地
3
- * @param data 要保存的数据
4
- * @param name 文件名
5
- * @example
6
- * libSaveJson(JSON.stringify({ key: "value" }), "example.json");
7
- * libSaveJson("Hellow World!", "example.txt");
8
- */
9
- export const libSaveJson = (data, name) => {
10
- const urlObject = window.URL || window.webkitURL;
11
- const exportBlob = new Blob([data]);
12
- const saveLink = document.createElement("a");
13
- saveLink.href = urlObject.createObjectURL(exportBlob);
14
- saveLink.download = name;
15
- saveLink.click();
16
- urlObject.revokeObjectURL(saveLink.href);
17
- };
@@ -1,9 +0,0 @@
1
- /**
2
- * @description 格式化字节大小
3
- * @param bytes 字节数
4
- * @returns ['大小', '单位', '大小及单位']
5
- * @example
6
- * const [size, unit, formatted] = libFormatterByte(2048);
7
- * console.log(size, unit, formatted); //2.00 KB 2.00 KB
8
- */
9
- export declare const libFormatterByte: (bytes: number) => (string | number)[];
@@ -1,17 +0,0 @@
1
- /**
2
- * @description 格式化字节大小
3
- * @param bytes 字节数
4
- * @returns ['大小', '单位', '大小及单位']
5
- * @example
6
- * const [size, unit, formatted] = libFormatterByte(2048);
7
- * console.log(size, unit, formatted); //2.00 KB 2.00 KB
8
- */
9
- export const libFormatterByte = (bytes) => {
10
- if (bytes <= 0)
11
- return [0, "B", "0 B"];
12
- const k = 1024;
13
- const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
14
- const i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1);
15
- const size = (bytes / k ** i).toFixed(2);
16
- return [size, sizes[i], `${size} ${sizes[i]}`];
17
- };