@oeos-components/utils 0.0.21 → 0.0.22

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.
@@ -0,0 +1,134 @@
1
+ /**
2
+ * 现有方法如下
3
+ * formatTime(time, cFormat = '{y}-{m}-{d} {h}:{i}:{s}')
4
+ * formatDurationTime(timestamp, cFormat = '{d} 天 {h} 时 {i} 分 {s} 秒')
5
+ * formatImg(photoName, addPath = '', { basePath = 'assets/images' } = {})
6
+ * formatThousands(number)
7
+ * formatBytes(bytes)
8
+ * formatBytesConvert(bytes)
9
+ * formatNewLines(str)
10
+ */
11
+ /**
12
+ * 格式化字节单位
13
+ * @param bytes - 字节数
14
+ * @param options - 配置项
15
+ * @param options.digit - 小数位数(默认2)
16
+ * @param options.thousands - 是否千分位分隔(默认true)
17
+ * @param options.prefix - 前缀(默认空)
18
+ * @param options.suffix - 后缀(默认空)
19
+ * @param options.roundType - 取整方式:'floor'(向下, 默认) | 'ceil'(向上) | 'round'(四舍五入)
20
+ * @example
21
+ * formatBytes(0.999) => 0.99B
22
+ * formatBytes(1040000, { digit: 3, prefix: "$", suffiex: "/s", roundType: "round", thousands: true }) => $1,015.625 KB
23
+ */
24
+ declare function formatBytes<const T extends {
25
+ digit?: number;
26
+ prefix?: string;
27
+ suffix?: string;
28
+ roundType?: 'floor' | 'ceil' | 'round';
29
+ thousands?: boolean;
30
+ } = {
31
+ digit: 2;
32
+ prefix: '';
33
+ suffix: '';
34
+ roundType: 'floor';
35
+ thousands: false;
36
+ }>(bytes: number | string, options?: T): string;
37
+ /**
38
+ * 字节转数字
39
+ * @param oBytes
40
+ * @param param1
41
+ * @returns number
42
+ * formatBytesConvert('0.5GB') 536870912
43
+ *
44
+ * formatBytesConvert('1,234 GB') 1324997410816
45
+ *
46
+ * formatBytesConvert('1,234 GB', {thousands: true}) 1,324,997,410,816
47
+ *
48
+ * formatBytesConvert('1,234 GB', {digit: 2}) 1324997410816.00
49
+ */
50
+ declare function formatBytesConvert<const T extends {
51
+ thounsands?: boolean;
52
+ digit?: number;
53
+ } = {
54
+ thounsands: false;
55
+ digit: 0;
56
+ }>(oBytes: any, options?: T): any;
57
+ /**
58
+ * 1234 => 1,234
59
+ * 1234b => 1,234b
60
+ * 1234.12b => 1,234.12b
61
+ * @param number 加千分位
62
+ * @returns
63
+ */
64
+ declare function formatThousands(number: any): any;
65
+ type TimeType = Date | string | number;
66
+ /**
67
+ * 时间格式化函数
68
+ * @param {TimeType} time - 可选时间参数,可以是 Date 对象、时间戳字符串或数字
69
+ * @param {FormatType} cFormat - '{y}-{m}-{d} {h}:{i}:{s}' - 格式化字符串,支持 {y}年 {m}月 {d}日 {h}时 {i}分 {s}秒 {a}星期
70
+ * @returns {string} 格式化后的时间字符串
71
+ * @examples
72
+ * formatTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s} 星期{a}') // 示例输出: 2026-02-27 14:47:45 星期五 (实际结果取决于调用时的具体时间)
73
+ */
74
+ declare function formatTime(time?: TimeType, cFormat?: string): string;
75
+ /**
76
+ *
77
+ * @param timestamp 持续的时间戳
78
+ * @param cFormat 格式化的规则 {d}天{h}时{i}分{s}秒
79
+ * @returns 天时分秒的字符串
80
+ * @example
81
+ * formatDurationTime(1162821) => 19分24秒
82
+ */
83
+ declare function formatDurationTime(timestamp: any, cFormat?: string): string;
84
+ /** 获取assets静态资源
85
+ * @example
86
+ * proxy.formatImg('1.png')
87
+ * proxy.formatImg('1.png', 'menu')
88
+ * */
89
+ declare function formatImg(photoName: any, addPath?: string, { basePath }?: {
90
+ basePath?: string | undefined;
91
+ }): any;
92
+ /**
93
+ * 增加小数点
94
+ * formatToFixed(22) -> '22.00'
95
+ *
96
+ * formatToFixed('22') -> '22.00'
97
+ *
98
+ * formatToFixed('22', 4) -> '22.0000'
99
+ *
100
+ * formatToFixed('22', 2) -> 22
101
+ *
102
+ * formatToFixed('22 TB', {prefix: '$', suffix: '%', unit: false}) -> $22.00%
103
+ */
104
+ declare function formatToFixed<const T extends {
105
+ digit?: number;
106
+ prefix?: string;
107
+ suffix?: string;
108
+ unit?: boolean;
109
+ thousands?: boolean;
110
+ } = {
111
+ digit: 2;
112
+ prefix: '';
113
+ suffix: '';
114
+ unit: true;
115
+ thousands: false;
116
+ }>(value: any, options?: T | number | any): string;
117
+ /**
118
+ * 格式化字符串中的换行符和制表符为HTML标签
119
+ * @param str 待格式化的字符串
120
+ * @returns 格式化后的字符串,如果输入的不是字符串或为空,则返回原字符串
121
+ * @example
122
+ $toast(
123
+ formatTextToHtml(
124
+ 'Example file\n File : 111.jpeg\n CreateTime : 1721011155921 2024-07-15 10:39:15\n LastUpdateTime : 1721011155921 2024-07-15 10:39:15\n------------------------------------------------------------------------\nExtract:\n aa=231\n------------------------------------------------------------------------\n',
125
+ ),
126
+ {
127
+ duration: 5000,
128
+ dangerouslyUseHTMLString: true,
129
+ },
130
+ )
131
+ */
132
+ declare function formatTextToHtml(str: any): string;
133
+
134
+ export { formatBytes, formatBytesConvert, formatDurationTime, formatImg, formatTextToHtml, formatThousands, formatTime, formatToFixed };
@@ -0,0 +1,230 @@
1
+ import { isStringNumber, isNumber } from './is.mjs';
2
+ import { getType } from './base.mjs';
3
+ import '@vue/reactivity';
4
+ import 'consola';
5
+ import 'es-toolkit';
6
+ import 'element-plus';
7
+
8
+ function formatBytes(bytes, options) {
9
+ let { digit = 2, thousands = false, prefix = "", suffix = "", roundType = "floor" } = options ?? {};
10
+ if (isStringNumber(bytes) || isNumber(bytes)) {
11
+ bytes = Number(bytes);
12
+ } else {
13
+ return bytes;
14
+ }
15
+ if (bytes <= 1) {
16
+ return Math[roundType](bytes * Math.pow(10, digit)) / Math.pow(10, digit) + " B";
17
+ }
18
+ const k = 1024;
19
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
20
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
21
+ const power = Math.pow(k, i);
22
+ let num = bytes / power;
23
+ num = Math[roundType](num * Math.pow(10, digit)) / Math.pow(10, digit);
24
+ let res = num.toFixed(digit) + " " + sizes[i];
25
+ if (thousands) {
26
+ res = formatThousands(res);
27
+ }
28
+ return `${prefix}${res}${suffix}`;
29
+ }
30
+ function formatBytesConvert(oBytes, options) {
31
+ let { thounsands = false, digit = 0 } = options ?? {};
32
+ let bytes = oBytes;
33
+ if (isStringNumber(oBytes) || isNumber(oBytes) || getType(oBytes) !== "string") {
34
+ return parseDigitThounsands(oBytes);
35
+ }
36
+ if (!oBytes) {
37
+ return parseDigitThounsands(oBytes);
38
+ }
39
+ const regex = /^\d{1,3}(,\d{3})*(\.\d+)?[a-zA-Z ]*$/;
40
+ if (regex.test(oBytes)) {
41
+ bytes = oBytes.replace(/,/g, "");
42
+ if (isStringNumber(bytes) || isNumber(bytes) || getType(bytes) !== "string") {
43
+ return parseDigitThounsands(bytes);
44
+ }
45
+ }
46
+ const bytesRegex = /^(\d+(?:\.\d+)?)\s*([BKMGTPEZY]?B|Byte)$/i;
47
+ const units = {
48
+ B: 1,
49
+ BYTE: 1,
50
+ KB: 1024,
51
+ MB: 1024 ** 2,
52
+ GB: 1024 ** 3,
53
+ TB: 1024 ** 4,
54
+ PB: 1024 ** 5,
55
+ EB: 1024 ** 6,
56
+ ZB: 1024 ** 7,
57
+ YB: 1024 ** 8
58
+ };
59
+ const match = bytes.match(bytesRegex);
60
+ if (!match) {
61
+ console.warn("Invalid bytes format. Please provide a valid bytes string, like '100GB'.");
62
+ return;
63
+ }
64
+ const size = parseFloat(match[1]);
65
+ const unit = match[2].toUpperCase();
66
+ if (!units.hasOwnProperty(unit)) {
67
+ console.warn(
68
+ "Invalid bytes unit. Please provide a valid unit, like 'B', 'BYTE', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', or 'YB'."
69
+ );
70
+ return;
71
+ }
72
+ function parseDigitThounsands(val) {
73
+ let finalRes = val;
74
+ if (digit) {
75
+ finalRes = Number(finalRes).toFixed(digit);
76
+ }
77
+ if (thounsands) {
78
+ finalRes = formatThousands(finalRes);
79
+ }
80
+ return finalRes;
81
+ }
82
+ return parseDigitThounsands(size * units[unit]);
83
+ }
84
+ function formatThousands(number) {
85
+ let matches = ("" + number).match(/^([\d,]+)(\.?)(\d+)?(\D+)?$/);
86
+ if (!matches) {
87
+ return number;
88
+ }
89
+ let numericString = matches[1].replace(/\D/g, "");
90
+ let decimalString = matches[3] ? `.${matches[3]}` : "";
91
+ let unit = matches[4] || "";
92
+ let numberWithSeparator = numericString.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
93
+ return `${numberWithSeparator}${decimalString}${unit}`;
94
+ }
95
+ function formatTime(time = /* @__PURE__ */ new Date(), cFormat = "{y}-{m}-{d} {h}:{i}:{s}") {
96
+ let date;
97
+ const timeStr = String(time);
98
+ if (typeof time === "object" && time instanceof Date) {
99
+ date = time;
100
+ } else {
101
+ const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/;
102
+ if (isoRegex.test(timeStr)) {
103
+ date = new Date(time);
104
+ } else {
105
+ if (timeStr.includes(".") && !isNaN(parseFloat(timeStr))) {
106
+ date = new Date(parseFloat(timeStr) * 1e3);
107
+ } else if (/^\d{10}$/.test(timeStr)) {
108
+ date = new Date(parseInt(timeStr) * 1e3);
109
+ } else {
110
+ date = new Date(time);
111
+ }
112
+ }
113
+ }
114
+ if (isNaN(date.getTime())) {
115
+ throw new Error("Invalid Date");
116
+ }
117
+ const formatObj = {
118
+ y: date.getFullYear(),
119
+ m: date.getMonth() + 1,
120
+ d: date.getDate(),
121
+ h: date.getHours(),
122
+ i: date.getMinutes(),
123
+ s: date.getSeconds(),
124
+ a: date.getDay()
125
+ };
126
+ return cFormat.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
127
+ const value = formatObj[key];
128
+ if (key === "a") {
129
+ return ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"][value];
130
+ }
131
+ if (result.length > 0 && value < 10) {
132
+ return "0" + value;
133
+ }
134
+ return value;
135
+ });
136
+ }
137
+ function formatDurationTime(timestamp, cFormat = "{d}\u5929{h}\u65F6{i}\u5206{s}\u79D2") {
138
+ const secondsPerMinute = 60;
139
+ const minutesPerHour = 60;
140
+ const hoursPerDay = 24;
141
+ let totalSeconds = Math.floor(timestamp / 1e3);
142
+ let days = 0;
143
+ if (cFormat.indexOf("d") !== -1) {
144
+ days = Math.floor(totalSeconds / (secondsPerMinute * minutesPerHour * hoursPerDay));
145
+ totalSeconds %= secondsPerMinute * minutesPerHour * hoursPerDay;
146
+ }
147
+ let hours = Math.floor(totalSeconds / (secondsPerMinute * minutesPerHour));
148
+ totalSeconds %= secondsPerMinute * minutesPerHour;
149
+ let minutes = Math.floor(totalSeconds / secondsPerMinute);
150
+ let seconds = totalSeconds % secondsPerMinute;
151
+ const formatObj = {
152
+ d: days,
153
+ h: hours,
154
+ i: minutes,
155
+ s: seconds
156
+ };
157
+ let parseFormat = cFormat;
158
+ if (days === 0) {
159
+ parseFormat = cFormat.match(/{h}.*/g)?.[0] ?? "";
160
+ if (hours === 0) {
161
+ parseFormat = cFormat.match(/{i}.*/g)?.[0] ?? "";
162
+ if (minutes === 0) {
163
+ parseFormat = cFormat.match(/{s}.*/g)?.[0] ?? "";
164
+ }
165
+ }
166
+ }
167
+ const time_str = parseFormat.replace(/{(y|m|d|h|i|s)+}/g, (result, key) => {
168
+ let value = formatObj[key];
169
+ if (result.length > 0 && value < 10 && value != 0) {
170
+ value = "0" + value;
171
+ }
172
+ return value || "00";
173
+ });
174
+ return time_str;
175
+ }
176
+ function formatImg(photoName, addPath = "", { basePath = "assets/images" } = {}) {
177
+ if (photoName.startsWith("http") || photoName.startsWith("https")) {
178
+ return photoName;
179
+ }
180
+ if (photoName.indexOf(".") === -1) {
181
+ photoName = photoName + ".png";
182
+ }
183
+ const addLastSlash = addPath.endsWith("/") || !addPath ? addPath : `${addPath}/`;
184
+ const addLastBasePathSlash = basePath.endsWith("/") || !basePath ? basePath : `${basePath}/`;
185
+ let mergeSrc = `${addLastSlash}${photoName}`;
186
+ let res = new URL(`../${addLastBasePathSlash}${mergeSrc}`, import.meta.url).href;
187
+ return res;
188
+ }
189
+ function formatToFixed(value, options) {
190
+ if (typeof options === "number") {
191
+ options = { digit: options };
192
+ }
193
+ const finalOptions = {
194
+ digit: 2,
195
+ prefix: "",
196
+ suffix: "",
197
+ unit: true,
198
+ thousands: false,
199
+ ...options
200
+ };
201
+ const { digit, prefix, suffix, unit, thousands } = finalOptions;
202
+ let matches = ("" + value).match(/^([\d,]+)(\.?)(\d+)?(\D+)?$/);
203
+ if (!matches) {
204
+ return value;
205
+ }
206
+ let numericString = matches[1].replace(/\D/g, "");
207
+ let decimalString = matches[3] ? `.${matches[3]}` : "";
208
+ let finalUnit = matches[4] || "";
209
+ let res = numericString;
210
+ if (isStringNumber(numericString) || isNumber(numericString)) {
211
+ res = Number(numericString + decimalString).toFixed(digit);
212
+ }
213
+ if (thousands) {
214
+ res = formatThousands(res);
215
+ }
216
+ if (!unit) {
217
+ finalUnit = "";
218
+ }
219
+ return `${prefix}${res}${finalUnit}${suffix}`;
220
+ }
221
+ function formatTextToHtml(str) {
222
+ if (!str || typeof str !== "string") {
223
+ return str;
224
+ }
225
+ str = str.replace(/\n/g, "<br>");
226
+ str = str.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
227
+ return str;
228
+ }
229
+
230
+ export { formatBytes, formatBytesConvert, formatDurationTime, formatImg, formatTextToHtml, formatThousands, formatTime, formatToFixed };