@base-web-kits/base-tools-web 0.0.2 → 0.0.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/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # @base-web-kits/base-tools-web
1
+ # Base Tools
2
2
 
3
- 薄包装分包,转发到主包的 `web` 子路径:`@base-web-kits/base-tools/web`。
3
+ web前端团队常用工具库,包含`ts`、`web`、`react`、`vue`、`uni`模块。
4
+
5
+ **安装**
6
+
7
+ 用哪个模块就安装哪个,模块之间不会相互依赖
8
+
9
+ - `npm i @base-web-kits/base-tools-ts`
10
+ - `npm i @base-web-kits/base-tools-web`
11
+ - `npm i @base-web-kits/base-tools-react`
12
+ - `npm i @base-web-kits/base-tools-vue`
13
+ - `npm i @base-web-kits/base-tools-uni`
14
+
15
+ **快速使用**
16
+
17
+ ```ts
18
+ // 通用 TS 模块
19
+ import { toDayjs, getUrlParam, toMaskPhone } from '@base-web-kits/base-tools-ts';
20
+
21
+ // Web 模块
22
+ import { copyText, isPC, download, setCookie } from '@base-web-kits/base-tools-web';
23
+
24
+ // React 模块
25
+ import { useCountDown } from '@base-web-kits/base-tools-react';
26
+
27
+ // Vue 模块
28
+ import { useResizeObserver } from '@base-web-kits/base-tools-vue';
29
+
30
+ // Uni 模块
31
+ import { chooseMedia, toPayWx } from '@base-web-kits/base-tools-uni';
32
+ ```
@@ -0,0 +1,73 @@
1
+ /**
2
+ * 复制文本到剪贴板(兼容移动端和PC)
3
+ * @returns Promise<void> 复制成功时 resolve,失败时 reject。
4
+ * @example
5
+ * await copyText('hello');
6
+ * toast('复制成功');
7
+ */
8
+ export declare function copyText(text: string): Promise<void>;
9
+ /**
10
+ * 复制富文本 HTML 到剪贴板(移动端与 PC)
11
+ * 使用场景:图文混排文章、带样式段落,保留格式粘贴。
12
+ * @param html HTML字符串
13
+ * @example
14
+ * await copyHtml('<p><b>加粗</b> 与 <i>斜体</i></p>');
15
+ */
16
+ export declare function copyHtml(html: string): Promise<void>;
17
+ /**
18
+ * 复制 DOM 节点到剪贴板(移动端与 PC)
19
+ * 使用场景:页面已有区域的可视化复制;元素使用 `outerHTML`,非元素使用其文本内容。
20
+ * @param node DOM 节点(元素或文本节点)
21
+ * @example
22
+ * const el = document.querySelector('#article')!;
23
+ * await copyNode(el);
24
+ */
25
+ export declare function copyNode(node: Node): Promise<void>;
26
+ /**
27
+ * 复制单张图片到剪贴板(移动端与 PC,需浏览器支持 `ClipboardItem`)
28
+ * 使用场景:把本地 `canvas` 或 `Blob` 生成的图片直接粘贴到聊天/文档。
29
+ * @param image 图片源(Blob/Canvas/ImageBitmap)
30
+ * @example
31
+ * const canvas = document.querySelector('canvas')!;
32
+ * await copyImage(canvas);
33
+ */
34
+ export declare function copyImage(image: Blob | HTMLCanvasElement | ImageBitmap): Promise<void>;
35
+ /**
36
+ * 复制 URL 到剪贴板(移动端与 PC)
37
+ * 写入 `text/uri-list` 与 `text/plain`,在支持 URI 列表的应用中可识别为链接。
38
+ * @param url 完整的 URL 字符串
39
+ * @example
40
+ * await copyUrl('https://example.com/page');
41
+ */
42
+ export declare function copyUrl(url: string): Promise<void>;
43
+ /**
44
+ * 复制任意 Blob 到剪贴板(移动端与 PC,需 `ClipboardItem`)
45
+ * 使用场景:原生格式粘贴(如 `image/svg+xml`、`application/pdf` 等)。
46
+ * @param blob 任意 Blob 数据
47
+ * @example
48
+ * const svg = new Blob(['<svg></svg>'], { type: 'image/svg+xml' });
49
+ * await copyBlob(svg);
50
+ */
51
+ export declare function copyBlob(blob: Blob): Promise<void>;
52
+ /**
53
+ * 复制 RTF 富文本到剪贴板(移动端与 PC)
54
+ * 同时写入 `text/plain`,增强与 Office/富文本编辑器的兼容性。
55
+ * @param rtf RTF 字符串(如:`{\\rtf1\\ansi ...}`)
56
+ * @example
57
+ * await copyRtf('{\\rtf1\\ansi Hello \\b World}');
58
+ */
59
+ export declare function copyRtf(rtf: string): Promise<void>;
60
+ /**
61
+ * 复制表格到剪贴板(移动端与 PC)
62
+ * 同时写入多种 MIME:`text/html`(表格)、`text/tab-separated-values`(TSV)、`text/csv`、`text/plain`(TSV)。
63
+ * 使用场景:优化粘贴到 Excel/Google Sheets/Docs 的体验
64
+ * @param rows 二维数组,每行一个数组(字符串/数字)
65
+ * @example
66
+ * await copyTable([
67
+ * ['姓名', '分数'],
68
+ * ['张三', 95],
69
+ * ['李四', 88],
70
+ * ]);
71
+ */
72
+ export declare function copyTable(rows: Array<Array<string | number>>): Promise<void>;
73
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/web/clipboard/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAiD1D;AAED;;;;;;GAMG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAW1D;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAWxD;AAED;;;;;;;GAOG;AACH,wBAAsB,SAAS,CAAC,KAAK,EAAE,IAAI,GAAG,iBAAiB,GAAG,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAS5F;AAED;;;;;;GAMG;AACH,wBAAsB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAUxD;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAOxD;AAED;;;;;;GAMG;AACH,wBAAsB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBxD;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAsClF"}
@@ -0,0 +1,26 @@
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 declare function setCookie(name: string, value: string, days: number): void;
10
+ /**
11
+ * 获取 Cookie
12
+ * @param name Cookie 名称
13
+ * @returns 若存在返回解码后的值,否则 `null`
14
+ * @example
15
+ * const token = getCookie('token');
16
+ */
17
+ export declare function getCookie(name: string): string | null;
18
+ /**
19
+ * 移除 Cookie(通过设置过期时间为过去)
20
+ * 路径固定为 `/`,确保与默认写入路径一致。
21
+ * @param name Cookie 名称
22
+ * @example
23
+ * removeCookie('token');
24
+ */
25
+ export declare function removeCookie(name: string): void;
26
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/web/cookie/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,QAKlE;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAQrD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,QAExC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 获取用户代理字符串(UA)
3
+ * @returns navigator.userAgent.toLowerCase();
4
+ */
5
+ export declare function getUA(): string;
6
+ /**
7
+ * 是否为移动端设备(含平板)
8
+ */
9
+ export declare function isMobile(): boolean;
10
+ /**
11
+ * 是否为平板设备
12
+ */
13
+ export declare function isTablet(): boolean;
14
+ /**
15
+ * 是否为 PC 设备
16
+ */
17
+ export declare function isPC(): boolean;
18
+ /**
19
+ * 是否为 iOS 系统
20
+ */
21
+ export declare function isIOS(): boolean;
22
+ /**
23
+ * 是否为 Android 系统
24
+ */
25
+ export declare function isAndroid(): boolean;
26
+ /**
27
+ * 是否微信内置浏览器
28
+ */
29
+ export declare function isWeChat(): boolean;
30
+ /**
31
+ * 是否为 Chrome 浏览器
32
+ * 已排除 Edge、Opera 等基于 Chromium 的浏览器
33
+ */
34
+ export declare function isChrome(): boolean;
35
+ /**
36
+ * 检测是否支持触摸事件
37
+ */
38
+ export declare function isTouchSupported(): boolean;
39
+ /**
40
+ * 获取设备像素比
41
+ */
42
+ export declare function getDevicePixelRatio(): number;
43
+ /**
44
+ * 获取浏览器名字
45
+ */
46
+ export declare function getBrowserName(): string | null;
47
+ /**
48
+ * 获取浏览器版本号
49
+ */
50
+ export declare function getBrowserVersion(): string | null;
51
+ /**
52
+ * 获取操作系统信息
53
+ */
54
+ export declare function getOS(): string;
55
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/web/device/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,KAAK,IAAI,MAAM,CAG9B;AAED;;GAEG;AACH,wBAAgB,QAAQ,IAAI,OAAO,CAGlC;AAED;;GAEG;AACH,wBAAgB,QAAQ,IAAI,OAAO,CAGlC;AAED;;GAEG;AACH,wBAAgB,IAAI,IAAI,OAAO,CAE9B;AAED;;GAEG;AACH,wBAAgB,KAAK,IAAI,OAAO,CAG/B;AAED;;GAEG;AACH,wBAAgB,SAAS,IAAI,OAAO,CAGnC;AAED;;GAEG;AACH,wBAAgB,QAAQ,IAAI,OAAO,CAGlC;AAED;;;GAGG;AACH,wBAAgB,QAAQ,IAAI,OAAO,CAGlC;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAG1C;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CAG5C;AAED;;GAEG;AACH,wBAAgB,cAAc,IAAI,MAAM,GAAG,IAAI,CAW9C;AAED;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,GAAG,IAAI,CAoBjD;AAED;;GAEG;AACH,wBAAgB,KAAK,IAAI,MAAM,CAU9B"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * 获取窗口宽度(不含滚动条)
3
+ * @returns 窗口宽度
4
+ */
5
+ export declare function getWindowWidth(): number;
6
+ /**
7
+ * 获取窗口高度(不含滚动条)
8
+ * @returns 窗口高度
9
+ */
10
+ export declare function getWindowHeight(): number;
11
+ /**
12
+ * 获取文档垂直滚动位置
13
+ * @example
14
+ * const top = getWindowScrollTop();
15
+ */
16
+ export declare function getWindowScrollTop(): number;
17
+ /**
18
+ * 获取文档水平滚动位置
19
+ * @example
20
+ * const left = getWindowScrollLeft();
21
+ */
22
+ export declare function getWindowScrollLeft(): number;
23
+ /**
24
+ * 平滑滚动到指定位置
25
+ * @param top 目标纵向滚动位置
26
+ * @param behavior 滚动行为,默认 'smooth'
27
+ * @example
28
+ * windowScrollTo(0);
29
+ */
30
+ export declare function windowScrollTo(top: number, behavior?: ScrollBehavior): void;
31
+ /**
32
+ * 元素是否在视口内(可设置阈值)
33
+ * @param el 目标元素
34
+ * @param offset 额外判定偏移(像素,正数放宽,负数收紧)
35
+ * @returns 是否在视口内
36
+ */
37
+ export declare function isInViewport(el: Element, offset?: number): boolean;
38
+ /**
39
+ * 锁定页面滚动(移动端/PC)
40
+ * 使用 `body{ position: fixed }` 技术消除滚动条抖动,记录并恢复滚动位置。
41
+ * @example
42
+ * lockBodyScroll();
43
+ */
44
+ export declare function lockBodyScroll(): void;
45
+ /**
46
+ * 解除页面滚动锁定,恢复原始滚动位置
47
+ * @example
48
+ * unlockBodyScroll();
49
+ */
50
+ export declare function unlockBodyScroll(): void;
51
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/web/dom/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,cAAc,WAE7B;AAED;;;GAGG;AACH,wBAAgB,eAAe,WAE9B;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,WAIjC;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,WAIlC;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,GAAE,cAAyB,QAM9E;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,EAAE,EAAE,OAAO,EAAE,MAAM,SAAI,WAUnD;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,SAW7B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,SAY/B"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * 内部统一导出, 外部快捷引入: import {xx} from 'base-tools/web'
3
+ */
4
+ export * from './clipboard';
5
+ export * from './cookie';
6
+ export * from './load';
7
+ export * from './storage';
8
+ export * from './dom';
9
+ export * from './device';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/web/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,QAAQ,CAAC;AACvB,cAAc,WAAW,CAAC;AAC1B,cAAc,OAAO,CAAC;AACtB,cAAc,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,556 @@
1
+ // src/web/clipboard/index.ts
2
+ async function copyText(text) {
3
+ if (typeof text !== "string") text = String(text ?? "");
4
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
5
+ try {
6
+ await navigator.clipboard.writeText(text);
7
+ return;
8
+ } catch (e) {
9
+ }
10
+ }
11
+ return new Promise((resolve, reject) => {
12
+ try {
13
+ const textarea = document.createElement("textarea");
14
+ textarea.value = text;
15
+ textarea.setAttribute("readonly", "");
16
+ textarea.style.position = "fixed";
17
+ textarea.style.top = "0";
18
+ textarea.style.right = "-9999px";
19
+ textarea.style.opacity = "0";
20
+ textarea.style.pointerEvents = "none";
21
+ document.body.appendChild(textarea);
22
+ textarea.focus();
23
+ textarea.select();
24
+ textarea.setSelectionRange(0, textarea.value.length);
25
+ const ok = document.execCommand("copy");
26
+ document.body.removeChild(textarea);
27
+ if (ok) {
28
+ resolve();
29
+ } else {
30
+ reject(new Error("Copy failed: clipboard unavailable"));
31
+ }
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ });
36
+ }
37
+ async function copyHtml(html) {
38
+ const s = String(html ?? "");
39
+ if (canWriteClipboard()) {
40
+ const plain = htmlToText(s);
41
+ await writeClipboard({
42
+ "text/html": new Blob([s], { type: "text/html" }),
43
+ "text/plain": new Blob([plain], { type: "text/plain" })
44
+ });
45
+ return;
46
+ }
47
+ return execCopyFromHtml(s);
48
+ }
49
+ async function copyNode(node) {
50
+ if (canWriteClipboard()) {
51
+ const { html: html2, text } = nodeToHtmlText(node);
52
+ await writeClipboard({
53
+ "text/html": new Blob([html2], { type: "text/html" }),
54
+ "text/plain": new Blob([text], { type: "text/plain" })
55
+ });
56
+ return;
57
+ }
58
+ const { html } = nodeToHtmlText(node);
59
+ return execCopyFromHtml(html);
60
+ }
61
+ async function copyImage(image) {
62
+ const blob = await toImageBlob(image);
63
+ if (!blob) throw new Error("Unsupported image source");
64
+ if (canWriteClipboard()) {
65
+ const type = blob.type || "image/png";
66
+ await writeClipboard({ [type]: blob });
67
+ return;
68
+ }
69
+ throw new Error("Clipboard image write not supported");
70
+ }
71
+ async function copyUrl(url) {
72
+ const s = String(url ?? "");
73
+ if (canWriteClipboard()) {
74
+ await writeClipboard({
75
+ "text/uri-list": new Blob([s], { type: "text/uri-list" }),
76
+ "text/plain": new Blob([s], { type: "text/plain" })
77
+ });
78
+ return;
79
+ }
80
+ await copyText(s);
81
+ }
82
+ async function copyBlob(blob) {
83
+ if (canWriteClipboard()) {
84
+ const type = blob.type || "application/octet-stream";
85
+ await writeClipboard({ [type]: blob });
86
+ return;
87
+ }
88
+ throw new Error("Clipboard blob write not supported");
89
+ }
90
+ async function copyRtf(rtf) {
91
+ const s = String(rtf ?? "");
92
+ if (canWriteClipboard()) {
93
+ const plain = s.replace(/\\par[\s]?/g, "\n").replace(/\{[^}]*\}/g, "").replace(/\\[a-zA-Z]+[0-9'-]*/g, "").replace(/\r?\n/g, "\n").trim();
94
+ await writeClipboard({
95
+ "text/rtf": new Blob([s], { type: "text/rtf" }),
96
+ "text/plain": new Blob([plain], { type: "text/plain" })
97
+ });
98
+ return;
99
+ }
100
+ await copyText(s);
101
+ }
102
+ async function copyTable(rows) {
103
+ const data = Array.isArray(rows) ? rows : [];
104
+ const escapeHtml = (t) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
105
+ const html = (() => {
106
+ const trs = data.map((r) => `<tr>${r.map((c) => `<td>${escapeHtml(String(c))}</td>`).join("")}</tr>`).join("");
107
+ return `<table>${trs}</table>`;
108
+ })();
109
+ const tsv = data.map((r) => r.map((c) => String(c)).join(" ")).join("\n");
110
+ const csv = data.map(
111
+ (r) => r.map((c) => {
112
+ const s = String(c);
113
+ const needQuote = /[",\n]/.test(s);
114
+ const escaped = s.replace(/"/g, '""');
115
+ return needQuote ? `"${escaped}"` : escaped;
116
+ }).join(",")
117
+ ).join("\n");
118
+ if (canWriteClipboard()) {
119
+ await writeClipboard({
120
+ "text/html": new Blob([html], { type: "text/html" }),
121
+ "text/tab-separated-values": new Blob([tsv], { type: "text/tab-separated-values" }),
122
+ "text/csv": new Blob([csv], { type: "text/csv" }),
123
+ "text/plain": new Blob([tsv], { type: "text/plain" })
124
+ });
125
+ return;
126
+ }
127
+ await copyText(tsv);
128
+ }
129
+ async function toImageBlob(image) {
130
+ if (image instanceof Blob) return image;
131
+ if (image instanceof HTMLCanvasElement)
132
+ return await new Promise((resolve, reject) => {
133
+ image.toBlob(
134
+ (b) => b ? resolve(b) : reject(new Error("Canvas toBlob failed")),
135
+ "image/png"
136
+ );
137
+ });
138
+ const isBitmap = typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap;
139
+ if (isBitmap) {
140
+ const cnv = document.createElement("canvas");
141
+ cnv.width = image.width;
142
+ cnv.height = image.height;
143
+ const ctx = cnv.getContext("2d");
144
+ ctx?.drawImage(image, 0, 0);
145
+ return await new Promise((resolve, reject) => {
146
+ cnv.toBlob((b) => b ? resolve(b) : reject(new Error("Canvas toBlob failed")), "image/png");
147
+ });
148
+ }
149
+ return null;
150
+ }
151
+ function canWriteClipboard() {
152
+ return !!(navigator.clipboard && typeof navigator.clipboard.write === "function" && typeof ClipboardItem !== "undefined");
153
+ }
154
+ async function writeClipboard(items) {
155
+ await navigator.clipboard.write([new ClipboardItem(items)]);
156
+ }
157
+ function htmlToText(html) {
158
+ const div = document.createElement("div");
159
+ div.innerHTML = html;
160
+ return div.textContent || "";
161
+ }
162
+ function nodeToHtmlText(node) {
163
+ const container = document.createElement("div");
164
+ container.appendChild(node.cloneNode(true));
165
+ const html = node instanceof Element ? node.outerHTML ?? container.innerHTML : container.innerHTML;
166
+ const text = container.textContent || "";
167
+ return { html, text };
168
+ }
169
+ function execCopyFromHtml(html) {
170
+ return new Promise((resolve, reject) => {
171
+ try {
172
+ const div = document.createElement("div");
173
+ div.contentEditable = "true";
174
+ div.style.position = "fixed";
175
+ div.style.top = "0";
176
+ div.style.right = "-9999px";
177
+ div.style.opacity = "0";
178
+ div.style.pointerEvents = "none";
179
+ div.innerHTML = html;
180
+ document.body.appendChild(div);
181
+ const selection = window.getSelection();
182
+ const range = document.createRange();
183
+ range.selectNodeContents(div);
184
+ selection?.removeAllRanges();
185
+ selection?.addRange(range);
186
+ const ok = document.execCommand("copy");
187
+ document.body.removeChild(div);
188
+ selection?.removeAllRanges();
189
+ if (ok) {
190
+ resolve();
191
+ } else {
192
+ reject(new Error("Copy failed: clipboard unavailable"));
193
+ }
194
+ } catch (e) {
195
+ reject(e);
196
+ }
197
+ });
198
+ }
199
+
200
+ // src/web/cookie/index.ts
201
+ function setCookie(name, value, days) {
202
+ const date = /* @__PURE__ */ new Date();
203
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3);
204
+ const expires = `expires=${date.toUTCString()}; path=/`;
205
+ document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}`;
206
+ }
207
+ function getCookie(name) {
208
+ const value = `; ${document.cookie}`;
209
+ const parts = value.split(`; ${name}=`);
210
+ if (parts.length === 2) {
211
+ const v = parts.pop()?.split(";").shift();
212
+ return v ? decodeURIComponent(v) : null;
213
+ }
214
+ return null;
215
+ }
216
+ function removeCookie(name) {
217
+ document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
218
+ }
219
+
220
+ // src/web/load/index.ts
221
+ async function download(url, fileName = "") {
222
+ if (!url) return;
223
+ let blobUrl = "";
224
+ let needRevoke = false;
225
+ try {
226
+ if (url instanceof Blob) {
227
+ blobUrl = URL.createObjectURL(url);
228
+ needRevoke = true;
229
+ } else if (url.includes(";base64,")) {
230
+ blobUrl = url;
231
+ } else {
232
+ if (fileName) {
233
+ const res = await fetch(url);
234
+ if (!res.ok) throw new Error(`fetch error ${res.status}\uFF1A${url}`);
235
+ const blob = await res.blob();
236
+ blobUrl = URL.createObjectURL(blob);
237
+ needRevoke = true;
238
+ } else {
239
+ blobUrl = url;
240
+ }
241
+ }
242
+ const a = document.createElement("a");
243
+ a.href = blobUrl;
244
+ a.download = fileName;
245
+ document.body.appendChild(a);
246
+ a.click();
247
+ document.body.removeChild(a);
248
+ } finally {
249
+ if (needRevoke) {
250
+ setTimeout(() => URL.revokeObjectURL(blobUrl), 100);
251
+ }
252
+ }
253
+ }
254
+ async function parseAxiosBlob(res) {
255
+ const { data, headers, status, statusText, config } = res;
256
+ if (status < 200 || status >= 300) throw new Error(`${status}\uFF0C${statusText}\uFF1A${config.url}`);
257
+ if (data.type.includes("application/json")) {
258
+ const txt = await data.text();
259
+ throw JSON.parse(txt);
260
+ }
261
+ const fileName = getDispositionFileName(headers["content-disposition"]);
262
+ return { blob: data, fileName };
263
+ }
264
+ function getDispositionFileName(disposition) {
265
+ if (!disposition) return "";
266
+ const rfc5987 = /filename\*\s*=\s*([^']*)''([^;]*)/i.exec(disposition);
267
+ if (rfc5987?.[2]) {
268
+ try {
269
+ return decodeURIComponent(rfc5987[2].trim()).replace(/[\r\n]+/g, "");
270
+ } catch {
271
+ return rfc5987[2].trim().replace(/[\r\n]+/g, "");
272
+ }
273
+ }
274
+ const old = /filename\s*=\s*(?:"([^"]*)"|([^";]*))(?=;|$)/i.exec(disposition);
275
+ if (old) return (old[1] ?? old[2]).trim().replace(/[\r\n]+/g, "");
276
+ return "";
277
+ }
278
+ async function loadJs(src, attrs) {
279
+ return new Promise((resolve, reject) => {
280
+ if (hasJs(src)) return resolve();
281
+ const script = document.createElement("script");
282
+ script.type = "text/javascript";
283
+ script.src = src;
284
+ if (attrs) {
285
+ const keys = Object.keys(attrs);
286
+ keys.forEach((key) => {
287
+ const v = attrs[key];
288
+ if (v === null || v === void 0 || v === false) return;
289
+ script.setAttribute(key, typeof v === "boolean" ? "" : v);
290
+ });
291
+ }
292
+ script.onload = () => resolve();
293
+ script.onerror = (e) => reject(e);
294
+ document.head.appendChild(script);
295
+ });
296
+ }
297
+ function hasJs(src) {
298
+ const target = new URL(src, document.baseURI).href;
299
+ const jsList = Array.from(document.querySelectorAll("script[src]"));
300
+ return jsList.some((e) => {
301
+ const src2 = e.getAttribute("src");
302
+ return src2 && new URL(src2, document.baseURI).href === target;
303
+ });
304
+ }
305
+ async function loadCss(href, attrs) {
306
+ return new Promise((resolve, reject) => {
307
+ if (hasCss(href)) return resolve();
308
+ const link = document.createElement("link");
309
+ link.rel = "stylesheet";
310
+ link.href = href;
311
+ if (attrs) {
312
+ const keys = Object.keys(attrs);
313
+ keys.forEach((key) => {
314
+ const v = attrs[key];
315
+ if (v === null || v === void 0) return;
316
+ link.setAttribute(key, String(v));
317
+ });
318
+ }
319
+ link.onload = () => resolve();
320
+ link.onerror = (e) => reject(e);
321
+ document.head.appendChild(link);
322
+ });
323
+ }
324
+ function hasCss(href) {
325
+ const target = new URL(href, document.baseURI).href;
326
+ const list = Array.from(document.querySelectorAll('link[rel="stylesheet"][href]'));
327
+ return list.some((e) => {
328
+ const h = e.getAttribute("href");
329
+ return h && new URL(h, document.baseURI).href === target;
330
+ });
331
+ }
332
+ function preloadImage(src) {
333
+ return new Promise((resolve, reject) => {
334
+ const img = new Image();
335
+ img.onload = () => resolve(img);
336
+ img.onerror = (e) => reject(e);
337
+ img.src = src;
338
+ });
339
+ }
340
+
341
+ // src/web/storage/index.ts
342
+ function setLocalStorage(key, value, days) {
343
+ if (value === void 0 || value === null) {
344
+ removeLocalStorage(key);
345
+ return;
346
+ }
347
+ let toStore = value;
348
+ if (typeof days === "number" && days > 0) {
349
+ const ms = Math.floor(days * 24 * 60 * 60 * 1e3);
350
+ toStore = { __l_val: value, __l_exp: Date.now() + ms };
351
+ }
352
+ localStorage.setItem(key, JSON.stringify(toStore));
353
+ }
354
+ function getLocalStorage(key) {
355
+ const raw = localStorage.getItem(key);
356
+ if (raw === null) return null;
357
+ try {
358
+ const parsed = JSON.parse(raw);
359
+ if (parsed && typeof parsed === "object") {
360
+ const obj = parsed;
361
+ if ("__l_exp" in obj && "__l_val" in obj) {
362
+ const exp = obj.__l_exp;
363
+ if (typeof exp === "number" && Date.now() >= exp) {
364
+ removeLocalStorage(key);
365
+ return null;
366
+ }
367
+ return obj.__l_val;
368
+ }
369
+ }
370
+ return parsed;
371
+ } catch {
372
+ return raw;
373
+ }
374
+ }
375
+ function removeLocalStorage(key) {
376
+ localStorage.removeItem(key);
377
+ }
378
+
379
+ // src/web/dom/index.ts
380
+ function getWindowWidth() {
381
+ return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
382
+ }
383
+ function getWindowHeight() {
384
+ return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
385
+ }
386
+ function getWindowScrollTop() {
387
+ const doc = document.documentElement;
388
+ const body = document.body;
389
+ return window.pageYOffset || doc.scrollTop || body.scrollTop || 0;
390
+ }
391
+ function getWindowScrollLeft() {
392
+ const doc = document.documentElement;
393
+ const body = document.body;
394
+ return window.pageXOffset || doc.scrollLeft || body.scrollLeft || 0;
395
+ }
396
+ function windowScrollTo(top, behavior = "smooth") {
397
+ if ("scrollBehavior" in document.documentElement.style) {
398
+ window.scrollTo({ top, behavior });
399
+ } else {
400
+ window.scrollTo(0, top);
401
+ }
402
+ }
403
+ function isInViewport(el, offset = 0) {
404
+ const rect = el.getBoundingClientRect();
405
+ const width = getWindowWidth();
406
+ const height = getWindowHeight();
407
+ return rect.bottom >= -offset && rect.right >= -offset && rect.top <= height + offset && rect.left <= width + offset;
408
+ }
409
+ function lockBodyScroll() {
410
+ const body = document.body;
411
+ if (body.dataset.scrollLock === "true") return;
412
+ const y = Math.round(window.scrollY || window.pageYOffset || 0);
413
+ body.dataset.scrollLock = "true";
414
+ body.dataset.scrollLockY = String(y);
415
+ body.style.position = "fixed";
416
+ body.style.top = `-${y}px`;
417
+ body.style.left = "0";
418
+ body.style.right = "0";
419
+ body.style.width = "100%";
420
+ }
421
+ function unlockBodyScroll() {
422
+ const body = document.body;
423
+ if (body.dataset.scrollLock !== "true") return;
424
+ const y = Number(body.dataset.scrollLockY || 0);
425
+ body.style.position = "";
426
+ body.style.top = "";
427
+ body.style.left = "";
428
+ body.style.right = "";
429
+ body.style.width = "";
430
+ delete body.dataset.scrollLock;
431
+ delete body.dataset.scrollLockY;
432
+ window.scrollTo(0, y);
433
+ }
434
+
435
+ // src/web/device/index.ts
436
+ function getUA() {
437
+ if (typeof navigator === "undefined") return "";
438
+ return (navigator.userAgent || "").toLowerCase();
439
+ }
440
+ function isMobile() {
441
+ const ua = getUA();
442
+ return /android|webos|iphone|ipod|blackberry|iemobile|opera mini|mobile/i.test(ua);
443
+ }
444
+ function isTablet() {
445
+ const ua = getUA();
446
+ return /ipad|android(?!.*mobile)|tablet/i.test(ua) && !/mobile/i.test(ua);
447
+ }
448
+ function isPC() {
449
+ return !isMobile() && !isTablet();
450
+ }
451
+ function isIOS() {
452
+ const ua = getUA();
453
+ return /iphone|ipad|ipod/i.test(ua);
454
+ }
455
+ function isAndroid() {
456
+ const ua = getUA();
457
+ return /android/i.test(ua);
458
+ }
459
+ function isWeChat() {
460
+ const ua = getUA();
461
+ return /micromessenger/i.test(ua);
462
+ }
463
+ function isChrome() {
464
+ const ua = getUA();
465
+ return /chrome\//i.test(ua) && !/edg\//i.test(ua) && !/opr\//i.test(ua) && !/whale\//i.test(ua);
466
+ }
467
+ function isTouchSupported() {
468
+ if (typeof window === "undefined") return false;
469
+ return "ontouchstart" in window || navigator.maxTouchPoints > 0;
470
+ }
471
+ function getDevicePixelRatio() {
472
+ if (typeof window === "undefined") return 1;
473
+ return window.devicePixelRatio || 1;
474
+ }
475
+ function getBrowserName() {
476
+ const ua = getUA();
477
+ if (/chrome\//i.test(ua)) return "chrome";
478
+ if (/safari\//i.test(ua)) return "safari";
479
+ if (/firefox\//i.test(ua)) return "firefox";
480
+ if (/opr\//i.test(ua)) return "opera";
481
+ if (/edg\//i.test(ua)) return "edge";
482
+ if (/msie|trident/i.test(ua)) return "ie";
483
+ return null;
484
+ }
485
+ function getBrowserVersion() {
486
+ const ua = getUA();
487
+ const versionPatterns = [
488
+ /(?:edg|edge)\/([0-9.]+)/i,
489
+ /(?:opr|opera)\/([0-9.]+)/i,
490
+ /chrome\/([0-9.]+)/i,
491
+ /firefox\/([0-9.]+)/i,
492
+ /version\/([0-9.]+).*safari/i,
493
+ /(?:msie |rv:)([0-9.]+)/i
494
+ ];
495
+ for (const pattern of versionPatterns) {
496
+ const matches = ua.match(pattern);
497
+ if (matches && matches[1]) {
498
+ return matches[1];
499
+ }
500
+ }
501
+ return null;
502
+ }
503
+ function getOS() {
504
+ const ua = getUA();
505
+ if (/windows/i.test(ua)) return "windows";
506
+ if (/mac os/i.test(ua)) return "macos";
507
+ if (/linux/i.test(ua)) return "linux";
508
+ if (/iphone|ipad|ipod/i.test(ua)) return "ios";
509
+ if (/android/i.test(ua)) return "android";
510
+ return "unknown";
511
+ }
512
+ export {
513
+ copyBlob,
514
+ copyHtml,
515
+ copyImage,
516
+ copyNode,
517
+ copyRtf,
518
+ copyTable,
519
+ copyText,
520
+ copyUrl,
521
+ download,
522
+ getBrowserName,
523
+ getBrowserVersion,
524
+ getCookie,
525
+ getDevicePixelRatio,
526
+ getDispositionFileName,
527
+ getLocalStorage,
528
+ getOS,
529
+ getUA,
530
+ getWindowHeight,
531
+ getWindowScrollLeft,
532
+ getWindowScrollTop,
533
+ getWindowWidth,
534
+ hasCss,
535
+ hasJs,
536
+ isAndroid,
537
+ isChrome,
538
+ isIOS,
539
+ isInViewport,
540
+ isMobile,
541
+ isPC,
542
+ isTablet,
543
+ isTouchSupported,
544
+ isWeChat,
545
+ loadCss,
546
+ loadJs,
547
+ lockBodyScroll,
548
+ parseAxiosBlob,
549
+ preloadImage,
550
+ removeCookie,
551
+ removeLocalStorage,
552
+ setCookie,
553
+ setLocalStorage,
554
+ unlockBodyScroll,
555
+ windowScrollTo
556
+ };
@@ -0,0 +1,77 @@
1
+ import type { AxiosResponse } from 'axios';
2
+ /**
3
+ * 下载文件
4
+ * @param url 完整的下载地址 | base64字符串 | Blob对象
5
+ * @param fileName 自定义文件名(需含后缀)
6
+ * @example
7
+ * download('https://xx/xx.pdf');
8
+ * download('https://xx/xx.pdf', 'xx.pdf');
9
+ * download(blob, '图片.jpg');
10
+ */
11
+ export declare function download(url: string | Blob, fileName?: string): Promise<void>;
12
+ /**
13
+ * 解析Axios返回的Blob数据
14
+ * @param res Axios响应对象 (responseType='blob')
15
+ * @returns 包含blob数据和文件名的对象 { blob, fileName }
16
+ * @example
17
+ * const res = await axios.get(url, { responseType: 'blob' });
18
+ * const { blob, fileName } = await parseAxiosBlob(res);
19
+ * download(blob, fileName);
20
+ */
21
+ export declare function parseAxiosBlob(res: AxiosResponse<Blob>): Promise<{
22
+ blob: Blob;
23
+ fileName: string;
24
+ }>;
25
+ /**
26
+ * 获取文件名
27
+ * @param disposition content-disposition头值
28
+ * @returns content-disposition中的filename
29
+ * @example
30
+ * const fileName = getDispositionFileName(headers['content-disposition']);
31
+ */
32
+ export declare function getDispositionFileName(disposition?: string): string;
33
+ /**
34
+ * 动态加载 JS(重复执行不会重复加载,内部已排重)
35
+ * @param src js 文件路径
36
+ * @param attrs 可选的脚本属性,如 async、defer、crossOrigin
37
+ * @example
38
+ * await loadJs('https://xx/xx.js');
39
+ * await loadJs('/a.js', { defer: true });
40
+ */
41
+ export declare function loadJs(src: string, attrs?: Pick<HTMLScriptElement, 'async' | 'defer' | 'crossOrigin'>): Promise<void>;
42
+ /**
43
+ * 判断某个 JS 地址是否已在页面中加载过
44
+ * @param src 相对、绝对路径的 JS 地址
45
+ * @returns 是否已加载过
46
+ * @example
47
+ * hasJs('https://xx/xx.js'); // boolean
48
+ * hasJs('/xx.js'); // boolean
49
+ * hasJs('xx.js'); // boolean
50
+ */
51
+ export declare function hasJs(src: string): boolean;
52
+ /**
53
+ * 动态加载 CSS(重复执行不会重复加载,内部已排重)
54
+ * @param href css 文件地址
55
+ * @param attrs 可选属性,如 crossOrigin、media
56
+ * @example
57
+ * await loadCss('https://xx/xx.css');
58
+ * await loadCss('/a.css', { media: 'print' });
59
+ */
60
+ export declare function loadCss(href: string, attrs?: Pick<HTMLLinkElement, 'crossOrigin' | 'media'>): Promise<void>;
61
+ /**
62
+ * 判断某个 CSS 地址是否已在页面中加载过
63
+ * @param href 相对、绝对路径的 CSS 地址
64
+ * @returns 是否已加载过
65
+ * @example
66
+ * hasCss('https://xx/xx.css'); // boolean
67
+ */
68
+ export declare function hasCss(href: string): boolean;
69
+ /**
70
+ * 预加载图片
71
+ * @param src 图片地址
72
+ * @returns Promise<HTMLImageElement>
73
+ * @example
74
+ * await preloadImage('/a.png');
75
+ */
76
+ export declare function preloadImage(src: string): Promise<HTMLImageElement>;
77
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/web/load/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAE3C;;;;;;;;GAQG;AACH,wBAAsB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,SAAK,iBAyC/D;AAED;;;;;;;;GAQG;AACH,wBAAsB,cAAc,CAAC,GAAG,EAAE,aAAa,CAAC,IAAI,CAAC;;;GAc5D;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,WAAW,CAAC,EAAE,MAAM,UAkB1D;AAED;;;;;;;GAOG;AACH,wBAAsB,MAAM,CAC1B,GAAG,EAAE,MAAM,EACX,KAAK,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,OAAO,GAAG,OAAO,GAAG,aAAa,CAAC,iBAuBnE;AAED;;;;;;;;GAQG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,MAAM,WAOhC;AAED;;;;;;;GAOG;AACH,wBAAsB,OAAO,CAC3B,IAAI,EAAE,MAAM,EACZ,KAAK,CAAC,EAAE,IAAI,CAAC,eAAe,EAAE,aAAa,GAAG,OAAO,CAAC,iBAuBvD;AAED;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,WAOlC;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,6BAOvC"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * 写入 localStorage(自动 JSON 序列化)
3
+ * 当 `value` 为 `null` 或 `undefined` 时,会移除该键。
4
+ * 支持保存:对象、数组、字符串、数字、布尔值。
5
+ * @param key 键名
6
+ * @param value 任意可序列化的值
7
+ * @param days 过期天数(从当前时间起算)
8
+ * @example
9
+ * setLocalStorage('user', { id: 1, name: 'Alice' }); // 对象
10
+ * setLocalStorage('age', 18); // 数字
11
+ * setLocalStorage('vip', true); // 布尔值
12
+ * setLocalStorage('token', 'abc123', 7); // 7 天后过期
13
+ */
14
+ export declare function setLocalStorage(key: string, value: unknown, days?: number): void;
15
+ /**
16
+ * 读取 localStorage(自动 JSON 反序列化)
17
+ * 若值为合法 JSON,则返回反序列化后的数据;
18
+ * 若值非 JSON(如外部写入的纯字符串),则原样返回字符串。
19
+ * 不存在时返回 `null`。
20
+ * @param key 键名
21
+ * @returns 解析后的值或 `null`
22
+ * @example
23
+ * const user = getLocalStorage<{ id: number; name: string }>('user');
24
+ * const age = getLocalStorage<number>('age');
25
+ * const vip = getLocalStorage<boolean>('vip');
26
+ */
27
+ export declare function getLocalStorage<T = unknown>(key: string): T | null;
28
+ /**
29
+ * 移除 localStorage 指定键
30
+ * @param key 键名
31
+ * @example
32
+ * removeLocalStorage('token');
33
+ */
34
+ export declare function removeLocalStorage(key: string): void;
35
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/web/storage/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAM,QAWzE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI,CAoBlE;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,QAE7C"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@base-web-kits/base-tools-web",
3
- "version": "0.0.2",
3
+ "version": "0.0.8",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
- "description": "Thin wrapper for @base-web-kits/base-tools/web to improve auto-imports in legacy JS projects.",
6
+ "description": "Independent Web utilities package built from src/web.",
7
7
  "keywords": [
8
8
  "base-tools",
9
9
  "web",
@@ -13,18 +13,15 @@
13
13
  "license": "MIT",
14
14
  "exports": {
15
15
  ".": {
16
- "types": "./index.d.ts",
17
- "import": "./index.js"
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
18
  }
19
19
  },
20
20
  "files": [
21
- "index.js",
22
- "index.d.ts",
21
+ "dist",
23
22
  "README.md"
24
23
  ],
25
- "dependencies": {
26
- "@base-web-kits/base-tools": "^0.0.2"
27
- },
24
+ "dependencies": {},
28
25
  "publishConfig": {
29
26
  "registry": "https://registry.npmjs.org"
30
27
  }
package/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- // Types re-export for editor support
2
- export * from '@base-web-kits/base-tools/web';
package/index.js DELETED
@@ -1,2 +0,0 @@
1
- // Thin wrapper: re-export web subpath to improve auto-imports in legacy JS projects
2
- export * from '@base-web-kits/base-tools/web';