utils.ts
9.62 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
import { h } from 'vue'
import { NIcon } from 'naive-ui'
import screenfull from 'screenfull'
import throttle from 'lodash/throttle'
import Image_404 from '../assets/images/exception/image-404.png'
import html2canvas from 'html2canvas'
import { downloadByA } from './file'
import { toString } from './type'
import cloneDeep from 'lodash/cloneDeep'
import { WinKeyboard } from '@/enums/editPageEnum'
import { RequestHttpIntervalEnum, RequestParamsObjType } from '@/enums/httpEnum'
import { CreateComponentType, CreateComponentGroupType } from '@/packages/index.d'
import { excludeParseEventKeyList, excludeParseEventValueList } from '@/enums/eventEnum'
/// THINGS_KIT 替换JSONParse解析
export { JSONParse } from './external/utils'
/**
* * 判断是否是开发环境
* @return { Boolean }
*/
export const isDev = () => {
return import.meta.env.DEV
}
/**
* * 生成一个不重复的ID
* @param { Number } randomLength
*/
export const getUUID = (randomLength = 10) => {
return Number(Math.random().toString().substring(2, randomLength) + Date.now()).toString(36)
}
/**
* 生成一个UUIDv4版本的
* GUID 的格式为“xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”
*/
export function generateUUIDv4() {
let d = new Date().getTime()
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (d + Math.random() * 16) % 16 | 0
d = Math.floor(d / 16)
return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
})
return uuid
}
/**
* * render 图标
* @param icon 图标
* @param set 设置项
*/
export const renderIcon = (icon: any, set = {}) => {
return () => h(NIcon, set, { default: () => h(icon) })
}
/**
* * render 语言
* @param lang 语言标识
* @param set 设置项
* @param tag 要渲染成的标签
*/
export const renderLang = (lang: string, set = {}, tag = 'span') => {
return () => h(tag, set, { default: () => window['$t'](lang) })
}
/**
* * 获取错误处理图片,默认 404 图
* @returns url
*/
export const requireErrorImg = () => {
return Image_404
}
/**
* * 全屏操作函数
* @param isFullscreen
* @param isEnabled
* @returns
*/
export const screenfullFn = (isFullscreen?: boolean, isEnabled?: boolean) => {
// 是否是全屏
if (isFullscreen) return screenfull.isFullscreen
// 是否支持全屏
if (isEnabled) return screenfull.isEnabled
if (screenfull.isEnabled) {
screenfull.toggle()
return
}
// TODO lang
window['$message'].warning('您的浏览器不支持全屏功能!')
}
/**
* 修改元素位置
* @param target 对象
* @param x X轴
* @param y Y轴
*/
export const setComponentPosition = (
target: CreateComponentType | CreateComponentGroupType,
x?: number,
y?: number
) => {
x && (target.attr.x = x)
y && (target.attr.y = y)
}
/**
* * 设置元素属性
* @param HTMLElement 元素
* @param key 键名
* @param value 键值
*/
export const setDomAttribute = <K extends keyof CSSStyleDeclaration, V extends CSSStyleDeclaration[K]>(
HTMLElement: HTMLElement,
key: K,
value: V
) => {
if (HTMLElement) {
HTMLElement.style[key] = value
}
}
/**
* * 判断是否是 mac
* @returns boolean
*/
export const isMac = () => {
return /macintosh|mac os x/i.test(navigator.userAgent)
}
/**
* * file转url
*/
export const fileToUrl = (file: File): string => {
const Url = URL || window.URL || window.webkitURL
const ImageUrl = Url.createObjectURL(file)
return ImageUrl
}
/**
* * file转base64
*/
export const fileTobase64 = (file: File, callback: Function) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function (e: ProgressEvent<FileReader>) {
if (e.target) {
const base64 = e.target.result
callback(base64)
}
}
}
/**
* * 挂载监听
*/
// eslint-disable-next-line no-undef
export const addEventListener = <K extends keyof WindowEventMap>(
target: HTMLElement | Document,
type: K,
listener: any,
delay?: number,
// eslint-disable-next-line no-undef
options?: boolean | AddEventListenerOptions | undefined
) => {
if (!target) return
target.addEventListener(
type,
throttle(listener, delay || 300, {
leading: true,
trailing: false
}),
options
)
}
/**
* * 卸载监听
*/
// eslint-disable-next-line no-undef
export const removeEventListener = <K extends keyof WindowEventMap>(
target: HTMLElement | Document,
type: K,
listener: any
) => {
if (!target) return
target.removeEventListener(type, listener)
}
/**
* * 截取画面为图片并下载
* @param html 需要截取的 DOM
*/
export const canvasCut = (html: HTMLElement | null, callback?: Function) => {
if (!html) {
window['$message'].error('导出失败!')
if (callback) callback()
return
}
html2canvas(html, {
backgroundColor: null,
allowTaint: true,
useCORS: true
}).then((canvas: HTMLCanvasElement) => {
window['$message'].success('导出成功!')
downloadByA(canvas.toDataURL(), undefined, 'png')
if (callback) callback()
})
}
/**
* * 函数过滤器
* @param data 数据值
* @param res 返回顶级对象
* @param funcStr 函数字符串
* @param isToString 是否转为字符串
* @param errorCallBack 错误回调函数
* @param successCallBack 成功回调函数
* @returns
*/
export const newFunctionHandle = (
data: any,
res: any,
funcStr?: string,
isToString?: boolean,
errorCallBack?: Function,
successCallBack?: Function
) => {
try {
if (!funcStr) return data
const fn = new Function('data', 'res', funcStr)
const fnRes = fn(cloneDeep(data), cloneDeep(res))
const resHandle = isToString ? toString(fnRes) : fnRes
// 成功回调
successCallBack && successCallBack(resHandle)
return resHandle
} catch (error) {
// 失败回调
errorCallBack && errorCallBack(error)
return '函数执行错误'
}
}
/**
* * 处理请求事件单位
* @param num 时间间隔
* @param unit RequestHttpIntervalEnum
* @return number 秒数
*/
export const intervalUnitHandle = (num: number, unit: RequestHttpIntervalEnum) => {
switch (unit) {
// 秒
case RequestHttpIntervalEnum.SECOND:
return num * 1000
// 分
case RequestHttpIntervalEnum.MINUTE:
return num * 1000 * 60
// 时
case RequestHttpIntervalEnum.HOUR:
return num * 1000 * 60 * 60
// 天
case RequestHttpIntervalEnum.DAY:
return num * 1000 * 60 * 60 * 24
default:
return num * 1000
}
}
/**
* * 对象转换 cookie 格式
* @param obj
* @returns string
*/
export const objToCookie = (obj: RequestParamsObjType) => {
if (!obj) return ''
let str = ''
for (const key in obj) {
str += key + '=' + obj[key] + ';'
}
return str.substring(0, str.length - 1)
}
/**
* * 设置按下键盘按键的底部展示
* @param keyCode
* @returns
*/
export const setKeyboardDressShow = (keyCode?: number) => {
const t = window['$t']
const code = new Map([
[17, WinKeyboard.CTRL],
[32, WinKeyboard.SPACE]
])
const dom = document.getElementById('keyboard-dress-show')
if (!dom) return
if (!keyCode) {
window.onKeySpacePressHold?.(false)
dom.innerText = ''
return
}
if (keyCode && code.has(keyCode)) {
if (keyCode == 32) window.onKeySpacePressHold?.(true)
dom.innerText = `${t('common.pressIt')}${code.get(keyCode)}${t('common.keysIt')}`
}
}
/**
* * JSON序列化,支持函数和 undefined
* @param data
*/
export const JSONStringify = <T>(data: T) => {
return JSON.stringify(
data,
(key, val) => {
// 处理函数丢失问题
if (typeof val === 'function') {
return `${val}`
}
// 处理 undefined 丢失问题
if (typeof val === 'undefined') {
return null
}
return val
},
2
)
}
export const evalFn = (fn: string) => {
const Fun = Function // 一个变量指向Function,防止前端编译工具报错
return new Fun('return ' + fn)()
}
/**
* * JSON反序列化,支持函数和 undefined
* @param data
*/
/// THINGS_KIT 重命名 JSONParse 为 JSONParseOriginal
export const JSONParseOriginal = (data: string) => {
return JSON.parse(data, (k, v) => {
// 过滤函数字符串
if (excludeParseEventKeyList.includes(k)) return v
// 过滤函数值表达式
if (typeof v === 'string') {
const someValue = excludeParseEventValueList.some(excludeValue => v.indexOf(excludeValue) > -1)
if (someValue) return v
}
// 还原函数值
if (typeof v === 'string' && v.indexOf && (v.indexOf('function') > -1 || v.indexOf('=>') > -1)) {
return evalFn(`(function(){return ${v}})()`)
} else if (typeof v === 'string' && v.indexOf && v.indexOf('return ') > -1) {
const baseLeftIndex = v.indexOf('(')
if (baseLeftIndex > -1) {
const newFn = `function ${v.substring(baseLeftIndex)}`
return evalFn(`(function(){return ${newFn}})()`)
}
}
return v
})
}
/**
* * 修改顶部标题
* @param title
*/
export const setTitle = (title?: string) => {
title && (document.title = title)
}
export const getUrlSearch = (name: string) => {
// 未传参,返回空
if (!name) return null
// 查询参数:先通过search取值,如果取不到就通过hash来取
let after = window.location.search
after = after.substr(1) || window.location.hash.split('?')[1]
// 地址栏URL没有查询参数,返回空
if (!after) return null
// 如果查询参数中没有"name",返回空
if (after.indexOf(name) === -1) return null
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
// 当地址栏参数存在中文时,需要解码,不然会乱码
const r = decodeURI(after).match(reg)
// 如果url中"name"没有值,返回空
if (!r) return null
return r[2]
}