@base-web-kits/base-tools-web 0.9.5 → 0.9.8
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.
- package/dist/base-tools-web.umd.global.js +1 -0
- package/dist/base-tools-web.umd.global.js.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -0
- package/package.json +9 -14
- package/src/web/clipboard/index.ts +311 -0
- package/src/web/cookie/index.ts +42 -0
- package/src/web/device/index.ts +136 -0
- package/src/web/dom/index.ts +108 -0
- package/src/web/index.ts +9 -0
- package/src/web/load/index.ts +225 -0
- package/src/web/storage/index.ts +78 -0
- package/base-tools-web.umd.global.js +0 -586
- package/index.cjs +0 -2
- package/index.d.ts +0 -2
- package/index.js +0 -2
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 复制文本到剪贴板(兼容移动端和PC)
|
|
3
|
+
* @returns Promise<void> 复制成功时 resolve,失败时 reject。
|
|
4
|
+
* @example
|
|
5
|
+
* await copyText('hello');
|
|
6
|
+
* toast('复制成功');
|
|
7
|
+
*/
|
|
8
|
+
export async function copyText(text: string): Promise<void> {
|
|
9
|
+
if (typeof text !== 'string') text = String(text ?? '');
|
|
10
|
+
|
|
11
|
+
// 现代 API
|
|
12
|
+
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
|
|
13
|
+
try {
|
|
14
|
+
await navigator.clipboard.writeText(text);
|
|
15
|
+
return;
|
|
16
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
17
|
+
} catch (e) {
|
|
18
|
+
// 继续尝试回退方案
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// 回退方案:使用隐藏 textarea + execCommand('copy')
|
|
23
|
+
return new Promise<void>((resolve, reject) => {
|
|
24
|
+
try {
|
|
25
|
+
const textarea = document.createElement('textarea');
|
|
26
|
+
textarea.value = text;
|
|
27
|
+
|
|
28
|
+
// 避免视觉影响与页面布局影响
|
|
29
|
+
textarea.setAttribute('readonly', '');
|
|
30
|
+
textarea.style.position = 'fixed';
|
|
31
|
+
textarea.style.top = '0';
|
|
32
|
+
textarea.style.right = '-9999px';
|
|
33
|
+
textarea.style.opacity = '0';
|
|
34
|
+
textarea.style.pointerEvents = 'none';
|
|
35
|
+
|
|
36
|
+
document.body.appendChild(textarea);
|
|
37
|
+
|
|
38
|
+
// 选中文本(移动端兼容)
|
|
39
|
+
textarea.focus();
|
|
40
|
+
textarea.select();
|
|
41
|
+
|
|
42
|
+
// iOS 兼容:明确选区
|
|
43
|
+
textarea.setSelectionRange(0, textarea.value.length);
|
|
44
|
+
|
|
45
|
+
const ok = document.execCommand('copy');
|
|
46
|
+
document.body.removeChild(textarea);
|
|
47
|
+
|
|
48
|
+
if (ok) {
|
|
49
|
+
resolve();
|
|
50
|
+
} else {
|
|
51
|
+
reject(new Error('Copy failed: clipboard unavailable'));
|
|
52
|
+
}
|
|
53
|
+
} catch (e) {
|
|
54
|
+
reject(e);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 复制富文本 HTML 到剪贴板(移动端与 PC)
|
|
61
|
+
* 使用场景:图文混排文章、带样式段落,保留格式粘贴。
|
|
62
|
+
* @param html HTML字符串
|
|
63
|
+
* @example
|
|
64
|
+
* await copyHtml('<p><b>加粗</b> 与 <i>斜体</i></p>');
|
|
65
|
+
*/
|
|
66
|
+
export async function copyHtml(html: string): Promise<void> {
|
|
67
|
+
const s = String(html ?? '');
|
|
68
|
+
if (canWriteClipboard()) {
|
|
69
|
+
const plain = htmlToText(s);
|
|
70
|
+
await writeClipboard({
|
|
71
|
+
'text/html': new Blob([s], { type: 'text/html' }),
|
|
72
|
+
'text/plain': new Blob([plain], { type: 'text/plain' }),
|
|
73
|
+
});
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
return execCopyFromHtml(s);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 复制 DOM 节点到剪贴板(移动端与 PC)
|
|
81
|
+
* 使用场景:页面已有区域的可视化复制;元素使用 `outerHTML`,非元素使用其文本内容。
|
|
82
|
+
* @param node DOM 节点(元素或文本节点)
|
|
83
|
+
* @example
|
|
84
|
+
* const el = document.querySelector('#article')!;
|
|
85
|
+
* await copyNode(el);
|
|
86
|
+
*/
|
|
87
|
+
export async function copyNode(node: Node): Promise<void> {
|
|
88
|
+
if (canWriteClipboard()) {
|
|
89
|
+
const { html, text } = nodeToHtmlText(node);
|
|
90
|
+
await writeClipboard({
|
|
91
|
+
'text/html': new Blob([html], { type: 'text/html' }),
|
|
92
|
+
'text/plain': new Blob([text], { type: 'text/plain' }),
|
|
93
|
+
});
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const { html } = nodeToHtmlText(node);
|
|
97
|
+
return execCopyFromHtml(html);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 复制单张图片到剪贴板(移动端与 PC,需浏览器支持 `ClipboardItem`)
|
|
102
|
+
* 使用场景:把本地 `canvas` 或 `Blob` 生成的图片直接粘贴到聊天/文档。
|
|
103
|
+
* @param image 图片源(Blob/Canvas/ImageBitmap)
|
|
104
|
+
* @example
|
|
105
|
+
* const canvas = document.querySelector('canvas')!;
|
|
106
|
+
* await copyImage(canvas);
|
|
107
|
+
*/
|
|
108
|
+
export async function copyImage(image: Blob | HTMLCanvasElement | ImageBitmap): Promise<void> {
|
|
109
|
+
const blob = await toImageBlob(image);
|
|
110
|
+
if (!blob) throw new Error('Unsupported image source');
|
|
111
|
+
if (canWriteClipboard()) {
|
|
112
|
+
const type = blob.type || 'image/png';
|
|
113
|
+
await writeClipboard({ [type]: blob });
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
throw new Error('Clipboard image write not supported');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 复制 URL 到剪贴板(移动端与 PC)
|
|
121
|
+
* 写入 `text/uri-list` 与 `text/plain`,在支持 URI 列表的应用中可识别为链接。
|
|
122
|
+
* @param url 完整的 URL 字符串
|
|
123
|
+
* @example
|
|
124
|
+
* await copyUrl('https://example.com/page');
|
|
125
|
+
*/
|
|
126
|
+
export async function copyUrl(url: string): Promise<void> {
|
|
127
|
+
const s = String(url ?? '');
|
|
128
|
+
if (canWriteClipboard()) {
|
|
129
|
+
await writeClipboard({
|
|
130
|
+
'text/uri-list': new Blob([s], { type: 'text/uri-list' }),
|
|
131
|
+
'text/plain': new Blob([s], { type: 'text/plain' }),
|
|
132
|
+
});
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
await copyText(s);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* 复制任意 Blob 到剪贴板(移动端与 PC,需 `ClipboardItem`)
|
|
140
|
+
* 使用场景:原生格式粘贴(如 `image/svg+xml`、`application/pdf` 等)。
|
|
141
|
+
* @param blob 任意 Blob 数据
|
|
142
|
+
* @example
|
|
143
|
+
* const svg = new Blob(['<svg></svg>'], { type: 'image/svg+xml' });
|
|
144
|
+
* await copyBlob(svg);
|
|
145
|
+
*/
|
|
146
|
+
export async function copyBlob(blob: Blob): Promise<void> {
|
|
147
|
+
if (canWriteClipboard()) {
|
|
148
|
+
const type = blob.type || 'application/octet-stream';
|
|
149
|
+
await writeClipboard({ [type]: blob });
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
throw new Error('Clipboard blob write not supported');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* 复制 RTF 富文本到剪贴板(移动端与 PC)
|
|
157
|
+
* 同时写入 `text/plain`,增强与 Office/富文本编辑器的兼容性。
|
|
158
|
+
* @param rtf RTF 字符串(如:`{\\rtf1\\ansi ...}`)
|
|
159
|
+
* @example
|
|
160
|
+
* await copyRtf('{\\rtf1\\ansi Hello \\b World}');
|
|
161
|
+
*/
|
|
162
|
+
export async function copyRtf(rtf: string): Promise<void> {
|
|
163
|
+
const s = String(rtf ?? '');
|
|
164
|
+
if (canWriteClipboard()) {
|
|
165
|
+
const plain = s
|
|
166
|
+
.replace(/\\par[\s]?/g, '\n')
|
|
167
|
+
.replace(/\{[^}]*\}/g, '')
|
|
168
|
+
.replace(/\\[a-zA-Z]+[0-9'-]*/g, '')
|
|
169
|
+
.replace(/\r?\n/g, '\n')
|
|
170
|
+
.trim();
|
|
171
|
+
await writeClipboard({
|
|
172
|
+
'text/rtf': new Blob([s], { type: 'text/rtf' }),
|
|
173
|
+
'text/plain': new Blob([plain], { type: 'text/plain' }),
|
|
174
|
+
});
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
await copyText(s);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 复制表格到剪贴板(移动端与 PC)
|
|
182
|
+
* 同时写入多种 MIME:`text/html`(表格)、`text/tab-separated-values`(TSV)、`text/csv`、`text/plain`(TSV)。
|
|
183
|
+
* 使用场景:优化粘贴到 Excel/Google Sheets/Docs 的体验
|
|
184
|
+
* @param rows 二维数组,每行一个数组(字符串/数字)
|
|
185
|
+
* @example
|
|
186
|
+
* await copyTable([
|
|
187
|
+
* ['姓名', '分数'],
|
|
188
|
+
* ['张三', 95],
|
|
189
|
+
* ['李四', 88],
|
|
190
|
+
* ]);
|
|
191
|
+
*/
|
|
192
|
+
export async function copyTable(rows: Array<Array<string | number>>): Promise<void> {
|
|
193
|
+
const data = Array.isArray(rows) ? rows : [];
|
|
194
|
+
const escapeHtml = (t: string) =>
|
|
195
|
+
t
|
|
196
|
+
.replace(/&/g, '&')
|
|
197
|
+
.replace(/</g, '<')
|
|
198
|
+
.replace(/>/g, '>')
|
|
199
|
+
.replace(/"/g, '"')
|
|
200
|
+
.replace(/'/g, ''');
|
|
201
|
+
const html = (() => {
|
|
202
|
+
const trs = data
|
|
203
|
+
.map((r) => `<tr>${r.map((c) => `<td>${escapeHtml(String(c))}</td>`).join('')}</tr>`)
|
|
204
|
+
.join('');
|
|
205
|
+
return `<table>${trs}</table>`;
|
|
206
|
+
})();
|
|
207
|
+
const tsv = data.map((r) => r.map((c) => String(c)).join('\t')).join('\n');
|
|
208
|
+
const csv = data
|
|
209
|
+
.map((r) =>
|
|
210
|
+
r
|
|
211
|
+
.map((c) => {
|
|
212
|
+
const s = String(c);
|
|
213
|
+
const needQuote = /[",\n]/.test(s);
|
|
214
|
+
const escaped = s.replace(/"/g, '""');
|
|
215
|
+
return needQuote ? `"${escaped}"` : escaped;
|
|
216
|
+
})
|
|
217
|
+
.join(','),
|
|
218
|
+
)
|
|
219
|
+
.join('\n');
|
|
220
|
+
if (canWriteClipboard()) {
|
|
221
|
+
await writeClipboard({
|
|
222
|
+
'text/html': new Blob([html], { type: 'text/html' }),
|
|
223
|
+
'text/tab-separated-values': new Blob([tsv], { type: 'text/tab-separated-values' }),
|
|
224
|
+
'text/csv': new Blob([csv], { type: 'text/csv' }),
|
|
225
|
+
'text/plain': new Blob([tsv], { type: 'text/plain' }),
|
|
226
|
+
});
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
await copyText(tsv);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function toImageBlob(image: Blob | HTMLCanvasElement | ImageBitmap) {
|
|
233
|
+
if (image instanceof Blob) return image;
|
|
234
|
+
if (image instanceof HTMLCanvasElement)
|
|
235
|
+
return await new Promise<Blob>((resolve, reject) => {
|
|
236
|
+
image.toBlob(
|
|
237
|
+
(b) => (b ? resolve(b) : reject(new Error('Canvas toBlob failed'))),
|
|
238
|
+
'image/png',
|
|
239
|
+
);
|
|
240
|
+
});
|
|
241
|
+
const isBitmap = typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap;
|
|
242
|
+
if (isBitmap) {
|
|
243
|
+
const cnv = document.createElement('canvas');
|
|
244
|
+
cnv.width = (image as ImageBitmap).width;
|
|
245
|
+
cnv.height = (image as ImageBitmap).height;
|
|
246
|
+
const ctx = cnv.getContext('2d');
|
|
247
|
+
ctx?.drawImage(image as ImageBitmap, 0, 0);
|
|
248
|
+
return await new Promise<Blob>((resolve, reject) => {
|
|
249
|
+
cnv.toBlob((b) => (b ? resolve(b) : reject(new Error('Canvas toBlob failed'))), 'image/png');
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function canWriteClipboard() {
|
|
256
|
+
return !!(
|
|
257
|
+
navigator.clipboard &&
|
|
258
|
+
typeof navigator.clipboard.write === 'function' &&
|
|
259
|
+
typeof ClipboardItem !== 'undefined'
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async function writeClipboard(items: Record<string, Blob>) {
|
|
264
|
+
await navigator.clipboard!.write([new ClipboardItem(items)]);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function htmlToText(html: string) {
|
|
268
|
+
const div = document.createElement('div');
|
|
269
|
+
div.innerHTML = html;
|
|
270
|
+
return div.textContent || '';
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function nodeToHtmlText(node: Node) {
|
|
274
|
+
const container = document.createElement('div');
|
|
275
|
+
container.appendChild(node.cloneNode(true));
|
|
276
|
+
const html =
|
|
277
|
+
node instanceof Element ? (node.outerHTML ?? container.innerHTML) : container.innerHTML;
|
|
278
|
+
const text = container.textContent || '';
|
|
279
|
+
return { html, text };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function execCopyFromHtml(html: string) {
|
|
283
|
+
return new Promise<void>((resolve, reject) => {
|
|
284
|
+
try {
|
|
285
|
+
const div = document.createElement('div');
|
|
286
|
+
div.contentEditable = 'true';
|
|
287
|
+
div.style.position = 'fixed';
|
|
288
|
+
div.style.top = '0';
|
|
289
|
+
div.style.right = '-9999px';
|
|
290
|
+
div.style.opacity = '0';
|
|
291
|
+
div.style.pointerEvents = 'none';
|
|
292
|
+
div.innerHTML = html;
|
|
293
|
+
document.body.appendChild(div);
|
|
294
|
+
const selection = window.getSelection();
|
|
295
|
+
const range = document.createRange();
|
|
296
|
+
range.selectNodeContents(div);
|
|
297
|
+
selection?.removeAllRanges();
|
|
298
|
+
selection?.addRange(range);
|
|
299
|
+
const ok = document.execCommand('copy');
|
|
300
|
+
document.body.removeChild(div);
|
|
301
|
+
selection?.removeAllRanges();
|
|
302
|
+
if (ok) {
|
|
303
|
+
resolve();
|
|
304
|
+
} else {
|
|
305
|
+
reject(new Error('Copy failed: clipboard unavailable'));
|
|
306
|
+
}
|
|
307
|
+
} catch (e) {
|
|
308
|
+
reject(e);
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 设置 Cookie(路径默认为 `/`)
|
|
3
|
+
* @param name Cookie 名称
|
|
4
|
+
* @param value Cookie 值(内部已使用 `encodeURIComponent` 编码)
|
|
5
|
+
* @param days 过期天数(从当前时间起算)
|
|
6
|
+
* @example
|
|
7
|
+
* setCookie('token', 'abc', 7);
|
|
8
|
+
*/
|
|
9
|
+
export function setCookie(name: string, value: string, days: number) {
|
|
10
|
+
const date = new Date();
|
|
11
|
+
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
|
|
12
|
+
const expires = `expires=${date.toUTCString()}; path=/`;
|
|
13
|
+
document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 获取 Cookie
|
|
18
|
+
* @param name Cookie 名称
|
|
19
|
+
* @returns 若存在返回解码后的值,否则 `null`
|
|
20
|
+
* @example
|
|
21
|
+
* const token = getCookie('token');
|
|
22
|
+
*/
|
|
23
|
+
export function getCookie(name: string): string | null {
|
|
24
|
+
const value = `; ${document.cookie}`;
|
|
25
|
+
const parts = value.split(`; ${name}=`);
|
|
26
|
+
if (parts.length === 2) {
|
|
27
|
+
const v = parts.pop()?.split(';').shift();
|
|
28
|
+
return v ? decodeURIComponent(v) : null;
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 移除 Cookie(通过设置过期时间为过去)
|
|
35
|
+
* 路径固定为 `/`,确保与默认写入路径一致。
|
|
36
|
+
* @param name Cookie 名称
|
|
37
|
+
* @example
|
|
38
|
+
* removeCookie('token');
|
|
39
|
+
*/
|
|
40
|
+
export function removeCookie(name: string) {
|
|
41
|
+
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
|
|
42
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 获取用户代理字符串(UA)
|
|
3
|
+
* @returns navigator.userAgent.toLowerCase();
|
|
4
|
+
*/
|
|
5
|
+
export function getUA(): string {
|
|
6
|
+
if (typeof navigator === 'undefined') return ''; // SSR无 navigator
|
|
7
|
+
return (navigator.userAgent || '').toLowerCase();
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 是否为移动端设备(含平板)
|
|
12
|
+
*/
|
|
13
|
+
export function isMobile(): boolean {
|
|
14
|
+
const ua = getUA();
|
|
15
|
+
return /android|webos|iphone|ipod|blackberry|iemobile|opera mini|mobile/i.test(ua);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 是否为平板设备
|
|
20
|
+
*/
|
|
21
|
+
export function isTablet(): boolean {
|
|
22
|
+
const ua = getUA();
|
|
23
|
+
return /ipad|android(?!.*mobile)|tablet/i.test(ua) && !/mobile/i.test(ua);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 是否为 PC 设备
|
|
28
|
+
*/
|
|
29
|
+
export function isPC(): boolean {
|
|
30
|
+
return !isMobile() && !isTablet();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 是否为 iOS 系统
|
|
35
|
+
*/
|
|
36
|
+
export function isIOS(): boolean {
|
|
37
|
+
const ua = getUA();
|
|
38
|
+
return /iphone|ipad|ipod/i.test(ua);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 是否为 Android 系统
|
|
43
|
+
*/
|
|
44
|
+
export function isAndroid(): boolean {
|
|
45
|
+
const ua = getUA();
|
|
46
|
+
return /android/i.test(ua);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 是否微信内置浏览器
|
|
51
|
+
*/
|
|
52
|
+
export function isWeChat(): boolean {
|
|
53
|
+
const ua = getUA();
|
|
54
|
+
return /micromessenger/i.test(ua);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 是否为 Chrome 浏览器
|
|
59
|
+
* 已排除 Edge、Opera 等基于 Chromium 的浏览器
|
|
60
|
+
*/
|
|
61
|
+
export function isChrome(): boolean {
|
|
62
|
+
const ua = getUA();
|
|
63
|
+
return /chrome\//i.test(ua) && !/edg\//i.test(ua) && !/opr\//i.test(ua) && !/whale\//i.test(ua);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 检测是否支持触摸事件
|
|
68
|
+
*/
|
|
69
|
+
export function isTouchSupported(): boolean {
|
|
70
|
+
if (typeof window === 'undefined') return false;
|
|
71
|
+
return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 获取设备像素比
|
|
76
|
+
*/
|
|
77
|
+
export function getDevicePixelRatio(): number {
|
|
78
|
+
if (typeof window === 'undefined') return 1;
|
|
79
|
+
return window.devicePixelRatio || 1;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 获取浏览器名字
|
|
84
|
+
*/
|
|
85
|
+
export function getBrowserName(): string | null {
|
|
86
|
+
const ua = getUA();
|
|
87
|
+
|
|
88
|
+
if (/chrome\//i.test(ua)) return 'chrome';
|
|
89
|
+
if (/safari\//i.test(ua)) return 'safari';
|
|
90
|
+
if (/firefox\//i.test(ua)) return 'firefox';
|
|
91
|
+
if (/opr\//i.test(ua)) return 'opera';
|
|
92
|
+
if (/edg\//i.test(ua)) return 'edge';
|
|
93
|
+
if (/msie|trident/i.test(ua)) return 'ie';
|
|
94
|
+
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* 获取浏览器版本号
|
|
100
|
+
*/
|
|
101
|
+
export function getBrowserVersion(): string | null {
|
|
102
|
+
const ua = getUA();
|
|
103
|
+
|
|
104
|
+
const versionPatterns = [
|
|
105
|
+
/(?:edg|edge)\/([0-9.]+)/i,
|
|
106
|
+
/(?:opr|opera)\/([0-9.]+)/i,
|
|
107
|
+
/chrome\/([0-9.]+)/i,
|
|
108
|
+
/firefox\/([0-9.]+)/i,
|
|
109
|
+
/version\/([0-9.]+).*safari/i,
|
|
110
|
+
/(?:msie |rv:)([0-9.]+)/i,
|
|
111
|
+
];
|
|
112
|
+
|
|
113
|
+
for (const pattern of versionPatterns) {
|
|
114
|
+
const matches = ua.match(pattern);
|
|
115
|
+
if (matches && matches[1]) {
|
|
116
|
+
return matches[1];
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 获取操作系统信息
|
|
125
|
+
*/
|
|
126
|
+
export function getOS(): string {
|
|
127
|
+
const ua = getUA();
|
|
128
|
+
|
|
129
|
+
if (/windows/i.test(ua)) return 'windows';
|
|
130
|
+
if (/mac os/i.test(ua)) return 'macos';
|
|
131
|
+
if (/linux/i.test(ua)) return 'linux';
|
|
132
|
+
if (/iphone|ipad|ipod/i.test(ua)) return 'ios';
|
|
133
|
+
if (/android/i.test(ua)) return 'android';
|
|
134
|
+
|
|
135
|
+
return 'unknown';
|
|
136
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 获取窗口宽度(不含滚动条)
|
|
3
|
+
* @returns 窗口宽度
|
|
4
|
+
*/
|
|
5
|
+
export function getWindowWidth() {
|
|
6
|
+
return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 获取窗口高度(不含滚动条)
|
|
11
|
+
* @returns 窗口高度
|
|
12
|
+
*/
|
|
13
|
+
export function getWindowHeight() {
|
|
14
|
+
return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 获取文档垂直滚动位置
|
|
19
|
+
* @example
|
|
20
|
+
* const top = getWindowScrollTop();
|
|
21
|
+
*/
|
|
22
|
+
export function getWindowScrollTop() {
|
|
23
|
+
const doc = document.documentElement;
|
|
24
|
+
const body = document.body;
|
|
25
|
+
return window.pageYOffset || doc.scrollTop || body.scrollTop || 0;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 获取文档水平滚动位置
|
|
30
|
+
* @example
|
|
31
|
+
* const left = getWindowScrollLeft();
|
|
32
|
+
*/
|
|
33
|
+
export function getWindowScrollLeft() {
|
|
34
|
+
const doc = document.documentElement;
|
|
35
|
+
const body = document.body;
|
|
36
|
+
return window.pageXOffset || doc.scrollLeft || body.scrollLeft || 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 平滑滚动到指定位置
|
|
41
|
+
* @param top 目标纵向滚动位置
|
|
42
|
+
* @param behavior 滚动行为,默认 'smooth'
|
|
43
|
+
* @example
|
|
44
|
+
* windowScrollTo(0);
|
|
45
|
+
*/
|
|
46
|
+
export function windowScrollTo(top: number, behavior: ScrollBehavior = 'smooth') {
|
|
47
|
+
if ('scrollBehavior' in document.documentElement.style) {
|
|
48
|
+
window.scrollTo({ top, behavior });
|
|
49
|
+
} else {
|
|
50
|
+
window.scrollTo(0, top);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 元素是否在视口内(可设置阈值)
|
|
56
|
+
* @param el 目标元素
|
|
57
|
+
* @param offset 额外判定偏移(像素,正数放宽,负数收紧)
|
|
58
|
+
* @returns 是否在视口内
|
|
59
|
+
*/
|
|
60
|
+
export function isInViewport(el: Element, offset = 0) {
|
|
61
|
+
const rect = el.getBoundingClientRect();
|
|
62
|
+
const width = getWindowWidth();
|
|
63
|
+
const height = getWindowHeight();
|
|
64
|
+
return (
|
|
65
|
+
rect.bottom >= -offset &&
|
|
66
|
+
rect.right >= -offset &&
|
|
67
|
+
rect.top <= height + offset &&
|
|
68
|
+
rect.left <= width + offset
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 锁定页面滚动(移动端/PC)
|
|
74
|
+
* 使用 `body{ position: fixed }` 技术消除滚动条抖动,记录并恢复滚动位置。
|
|
75
|
+
* @example
|
|
76
|
+
* lockBodyScroll();
|
|
77
|
+
*/
|
|
78
|
+
export function lockBodyScroll() {
|
|
79
|
+
const body = document.body;
|
|
80
|
+
if (body.dataset.scrollLock === 'true') return;
|
|
81
|
+
const y = Math.round(window.scrollY || window.pageYOffset || 0);
|
|
82
|
+
body.dataset.scrollLock = 'true';
|
|
83
|
+
body.dataset.scrollLockY = String(y);
|
|
84
|
+
body.style.position = 'fixed';
|
|
85
|
+
body.style.top = `-${y}px`;
|
|
86
|
+
body.style.left = '0';
|
|
87
|
+
body.style.right = '0';
|
|
88
|
+
body.style.width = '100%';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 解除页面滚动锁定,恢复原始滚动位置
|
|
93
|
+
* @example
|
|
94
|
+
* unlockBodyScroll();
|
|
95
|
+
*/
|
|
96
|
+
export function unlockBodyScroll() {
|
|
97
|
+
const body = document.body;
|
|
98
|
+
if (body.dataset.scrollLock !== 'true') return;
|
|
99
|
+
const y = Number(body.dataset.scrollLockY || 0);
|
|
100
|
+
body.style.position = '';
|
|
101
|
+
body.style.top = '';
|
|
102
|
+
body.style.left = '';
|
|
103
|
+
body.style.right = '';
|
|
104
|
+
body.style.width = '';
|
|
105
|
+
delete body.dataset.scrollLock;
|
|
106
|
+
delete body.dataset.scrollLockY;
|
|
107
|
+
window.scrollTo(0, y);
|
|
108
|
+
}
|