-
Notifications
You must be signed in to change notification settings - Fork 394
Expand file tree
/
Copy pathhelper.ts
More file actions
298 lines (268 loc) · 8.76 KB
/
Copy pathhelper.ts
File metadata and controls
298 lines (268 loc) · 8.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import isArray from 'lodash-es/isArray';
import isNull from 'lodash-es/isNull';
import isNumber from 'lodash-es/isNumber';
import isString from 'lodash-es/isString';
import isUndefined from 'lodash-es/isUndefined';
export function omit(obj: Record<string, any>, fields: string[]) {
const shallowCopy = {
...obj,
};
for (let i = 0; i < fields.length; i++) {
const key = fields[i];
delete shallowCopy[key];
}
return shallowCopy;
}
export function getValidAttrs<T extends Record<string, any>>(obj: T): Partial<T> {
const newObj: Partial<T> = {};
Object.keys(obj).forEach((key) => {
if (!isUndefined(obj[key]) || isNull(obj[key])) {
newObj[key as keyof T] = obj[key];
}
});
return newObj;
}
export function removeEmptyAttrs<T extends Record<string, any>>(obj: T): Partial<T> {
const newObj: Partial<T> = {};
Object.keys(obj).forEach((key) => {
if (!isUndefined(obj[key]) || isNull(obj[key])) {
newObj[key as keyof T] = obj[key];
}
});
return newObj;
}
export function getTabElementByValue(tabs: [] = [], value: string): object {
const [result] = tabs.filter((item) => {
const { id } = item as any;
return id === value;
});
return result || null;
}
export function firstUpperCase(str: string): string {
return str.toLowerCase().replace(/( |^)[a-z]/g, (char: string) => char.toUpperCase());
}
export type Gradients = { [percent: string]: string };
export type FromTo = { from: string; to: string };
export type LinearGradient = { direction?: string } & (Gradients | FromTo);
export function getBackgroundColor(color: string | string[] | LinearGradient): string {
if (isString(color)) {
return color;
}
if (isArray(color)) {
if (color[0] && color[0][0] === '#') {
color.unshift('90deg');
}
return `linear-gradient( ${color.join(',')} )`;
}
const { from, to, direction = 'to right', ...rest } = color;
let keys = Object.keys(rest);
if (keys.length) {
keys = keys.sort((a, b) => {
const c = parseFloat(a.substr(0, a.length - 1)) - parseFloat(b.substr(0, b.length - 1));
return c;
});
const tempArr = keys.map((key: any) => `${rest[key as keyof typeof rest]} ${key}`);
return `linear-gradient(${direction}, ${tempArr.join(',')})`;
}
return `linear-gradient(${direction}, ${from}, ${to})`;
}
/**
*
* @returns 获取 ie 浏览器版本
*/
export function getIEVersion() {
if (typeof navigator === 'undefined' || !navigator) return Number.MAX_SAFE_INTEGER;
const { userAgent } = navigator;
// 判断是否IE<11浏览器
const isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1;
// 判断是否IE11浏览器
const isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
if (isIE) {
const reIE = /MSIE (\d+\.\d+);/;
const match = userAgent.match(reIE);
if (!match) return -1;
const fIEVersion = parseFloat(match[1]);
return fIEVersion < 7 ? 6 : fIEVersion;
}
if (isIE11) {
// IE11
return 11;
}
// 不是ie浏览器
return Number.MAX_SAFE_INTEGER;
}
/**
* Safari Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15
* FireFox Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/114.0
* Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36
* Chrome 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.3
* 搜狗 Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.
* 360 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.9 Safari/537.36 QIHU 360EE
*/
export function getFlexGapPolyFill() {
if (typeof navigator === 'undefined' || !navigator) return false;
const ua = navigator.userAgent;
const chromeMatch = ua.match(/AppleWebKit.+Chrome\/(.+) Safari\/.+/i);
if (Number(chromeMatch?.[1]?.split('.')[0]) < 100) return true;
const safariMatch = ua.match(/AppleWebKit.+Version\/(.+) Safari\/.+/i);
if (Number(safariMatch?.[1]?.split('.')[0]) < 12) return true;
const ieVersion = getIEVersion();
if (ieVersion <= 11) return true;
const fireFoxMatch = ua.match(/Firefox\/(.+)/i);
if (Number(fireFoxMatch?.[1]?.split('.')[0]) < 100) return true;
return false;
}
/**
* 计算字符串字符的长度并可以截取字符串。
* @param str 传入字符串
* @param maxCharacter 规定最大字符串长度
* @returns 当没有传入maxCharacter时返回字符串字符长度,当传入maxCharacter时返回截取之后的字符串和长度。
*/
export function getCharacterLength(str: string): number;
export function getCharacterLength(str: string, maxCharacter?: number): { length: number; characters: string };
export function getCharacterLength(str: string, maxCharacter?: number) {
const hasMaxCharacter = isNumber(maxCharacter);
if (!str || str.length === 0) {
if (hasMaxCharacter) {
return {
length: 0,
characters: str,
};
}
return 0;
}
let len = 0;
for (let i = 0; i < str.length; i++) {
let currentStringLength = 0;
if (str.charCodeAt(i) > 127) {
currentStringLength = 2;
} else {
currentStringLength = 1;
}
if (hasMaxCharacter && len + currentStringLength > maxCharacter) {
return {
length: len,
characters: str.slice(0, i),
};
}
len += currentStringLength;
}
if (hasMaxCharacter) {
return {
length: len,
characters: str,
};
}
return len;
}
/**
* 返回 Unicode 字符长度
* '👨'.length === 2
* getUnicodeLength('👨') === 1
* @param str
* @returns {number}
*/
export function getUnicodeLength(str?: string): number {
return [...(str ?? '')].length;
}
/**
* 修正 Unicode 最大字符长度
* '👨👨👨'.slice(0, 2) === '👨'
* limitUnicodeMaxLength('👨👨👨', 2) === '👨👨'
* @param str
* @param maxLength
* @param oldStr
* @returns {string}
*/
export function limitUnicodeMaxLength(str?: string, maxLength?: number, oldStr?: string): string {
// 旧字符满足字数要求则返回
if ([...(oldStr ?? '')].slice().length === maxLength) return oldStr || '';
return [...(str ?? '')].slice(0, maxLength).join('');
}
/**
* 是否样式单位
* @param value 样式值
* @returns 是否样式单位
*/
export const hasStyleUnit = (value: string): boolean => {
return /px|rpx|em|rem|%|vh|vw/.test(value);
};
/**
* 样式单位格式化
* @param value 样式值
* @param unit 单位,默认为'px'
* @returns 格式化后的样式值
*/
export function formatStyleUnit(value: string | number, unit = 'px'): string {
if (isString(value)) {
return hasStyleUnit(value) ? value : `${value}${unit}`;
}
return `${value}${unit}`;
}
/**
* 兼容样式中支持number/string类型的传值 得出最后的结果。
* @param param number或string类型的可用于样式上的值
* @returns 可使用的样式值。
*/
export function pxCompat(param: string | number) {
return isNumber(param) ? `${param}px` : param;
}
/**
* 计算dom元素盒模型尺寸
* @param targetElement 需要计算盒模型尺寸的元素
* @returns 计算出各维度尺寸。
*/
const DOM_STYLE_PROPS = [
'padding-top',
'padding-bottom',
'padding-left',
'padding-right',
'font-family',
'font-weight',
'font-size',
'font-variant',
'text-rendering',
'text-transform',
'width',
'text-indent',
'border-width',
'box-sizing',
'line-height',
'letter-spacing',
];
export function calculateNodeSize(targetElement: HTMLElement) {
if (typeof window === 'undefined') {
return {
paddingSize: 0,
borderSize: 0,
boxSizing: 0,
sizingStyle: '',
};
}
const style = window.getComputedStyle(targetElement);
const boxSizing =
style.getPropertyValue('box-sizing') ||
style.getPropertyValue('-moz-box-sizing') ||
style.getPropertyValue('-webkit-box-sizing');
const paddingSize =
parseFloat(style.getPropertyValue('padding-bottom')) + parseFloat(style.getPropertyValue('padding-top'));
const borderSize =
parseFloat(style.getPropertyValue('border-bottom-width')) + parseFloat(style.getPropertyValue('border-top-width'));
const sizingStyle = DOM_STYLE_PROPS.map((name) => `${name}:${style.getPropertyValue(name)}`).join(';');
return {
paddingSize,
borderSize,
boxSizing,
sizingStyle,
};
}
export function isSafari(): boolean {
if (typeof window === 'undefined') return false;
const ua = window?.navigator?.userAgent;
return /Safari/.test(ua) && !/Chrome/.test(ua);
}
export function isFirefox(): boolean {
if (typeof window === 'undefined') return false;
const ua = window?.navigator?.userAgent;
return /Firefox/.test(ua);
}