@vvi/browser 1.0.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ # 更新日志 📔
2
+
3
+ ## v0.0.0 (2026-7-29)
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ # MIT License
2
+
3
+ Copyright ©️ <2026> <MrMudBean>
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # browser
2
+
3
+ [![version](<https://img.shields.io/npm/v/@vvi/browser.svg?logo=npm&logoColor=rgb(0,0,0)&label=版本号&labelColor=rgb(73,73,228)&color=rgb(0,0,0)>)](https://www.npmjs.com/package/@vvi/browser) [![issues 提交](<https://img.shields.io/badge/issues-提交-rgb(255,0,63)?logo=github>)](https://github.com/MrMudBean/browser/issues)
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ npm install --save @vvi/browser
9
+
10
+ # pnpm
11
+ pnpm add --save @vvi/browser
12
+
13
+ # yarn
14
+ yarn add --save @vvi/browser
15
+ ```
16
+
17
+ ## 提供
18
+
19
+ - `copyText` - 复制文本到剪切板
20
+ - `matchMediaState` - 媒体查询的结果(与 `window.matchMedia` 返回对象不同的是该方法返回的是布尔值)
21
+ - `isDarkTheme` - 是否为暗黑主题
22
+ - `isOrientation` - 设备是否为横屏状态
23
+ - `Storage` - 导出 `Storage` 类,可构建管理 `localStorage` 或 `sessionStorage` 的方法
24
+ - `getCookie` - 获取本地的 cookie 值
25
+ - `setCookie` - 设置 cookie 值
26
+ - `removeCookie` - 移除 cookie 值
27
+ - `hasCookie` - 判定是否有某指定键的值
28
+ - `getAllCookie` - 返回所有的键值
29
+
30
+ ## 状态
31
+
32
+ 此软件包是 `MrMudBean` 生态系统的一部分。
33
+ 它使用严格的 TypeScript 编写,并通过 Rollup 构建进行验证。
34
+ 虽然单元测试较少,但 API 稳定,并在生产环境中大量使用。
package/cjs/cookie.js ADDED
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ var is = require('@vvi/is');
4
+
5
+ /**
6
+ * # 根据键值获取 cookie 值
7
+ * @param name cookie 键值
8
+ * @returns
9
+ */
10
+ function getCookie(name) {
11
+ if (!name || is.typeOf(name) != 'string') {
12
+ return null;
13
+ }
14
+ const cookies = document.cookie ? document.cookie.split(';') : [];
15
+ const encodedName = encodeURIComponent(name);
16
+ for (let i = 0, j = cookies.length; i < j; i++) {
17
+ const [key, ...valParts] = cookies[i].trim().split('=');
18
+ if (key !== encodedName) {
19
+ continue;
20
+ }
21
+ // 处理可能包含 "=" 的情况
22
+ const val = valParts.join('=');
23
+ const decodedVal = decodeURIComponent(val);
24
+ try {
25
+ // 尝试解析 JSON ,失败则返回原字符串
26
+ return JSON.parse(decodedVal);
27
+ }
28
+ catch {
29
+ return decodedVal;
30
+ }
31
+ }
32
+ return null;
33
+ // 使用正则可能对性能不太好
34
+ // 1. 依赖 `document.cookie.replace` 捕获分组,匹配不到时返回空字符串,容易误判
35
+ // 2. 正则里 `.*` 贪婪匹配,极端 cookie 长度下性能差
36
+ // 3. 对 cookie value 中出现 `;`、空格等边界处理较弱
37
+ // 4. 没有处理 `key=` 后面空格、空值的鲁棒性
38
+ // 5. 无法天然支持 value 中包含 `=` 的场景
39
+ // const handledKey = encodeURIComponent(keyItem).replace(/[-.+*]/g, '\\$&');
40
+ // const regStr =
41
+ // '(?:(?:^|.*;)\\s*' + handledKey + '\\s*\\=\\s*([^;]*).*$)|^.*$';
42
+ // const reg = new RegExp(regStr);
43
+ // const value = document.cookie.replace(reg, '$1');
44
+ // const result = decodeURIComponent(value);
45
+ // return result || null;
46
+ }
47
+ /**
48
+ * # 设置 cookie 值
49
+ *
50
+ * 未传入 `name` 将抛出错误
51
+ * @param name - Cookie 名称
52
+ * @param value - Cookie 值(支持对象/数组,会自动 JSON 序列化)
53
+ * @param cookieOption - 配置项
54
+ * @see CookieOption
55
+ */
56
+ function setCookie(name, value, cookieOption) {
57
+ let { expires, path, domain, secure, sameSite } = cookieOption ?? {};
58
+ if (!name) {
59
+ throw new Error('Cookie 的 "name" 是必须的');
60
+ }
61
+ const valueType = is.typeOf(value);
62
+ // 1. 处理值 : 如果是对象/数组则进行序列化,并统一进行 URI 编码
63
+ let cookieValue = valueType === 'object' ||
64
+ valueType == 'array' ||
65
+ valueType == 'set' ||
66
+ valueType == 'map'
67
+ ? JSON.stringify(value)
68
+ : String(value);
69
+ cookieValue = encodeURIComponent(cookieValue);
70
+ // 2. 构建 Cookie 字符串
71
+ let cookieStr = `${encodeURIComponent(name)}=${cookieValue}`;
72
+ // 3. 处理过期时间
73
+ const expiresType = is.typeOf(expires);
74
+ if (expires &&
75
+ expiresType === 'number' &&
76
+ expires != Infinity &&
77
+ expires != -Infinity &&
78
+ !is.isNaN(expires)) {
79
+ const date = new Date();
80
+ date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);
81
+ cookieStr += `; expires=${date.toUTCString()}`;
82
+ }
83
+ // 4. 处理其他属性
84
+ cookieStr += `; path=${path && is.typeOf(path) == 'string' ? domain : '/'}`;
85
+ if (domain && is.typeOf(domain) === 'string')
86
+ cookieStr += `; domain=${domain}`;
87
+ if (secure)
88
+ cookieStr += `; secure`;
89
+ if (sameSite)
90
+ cookieStr += `; samesite=${sameSite}`;
91
+ document.cookie = cookieStr;
92
+ }
93
+ /**
94
+ * # 删除指定 Cookie
95
+ * @param name - Cookie 名称
96
+ * @param cookieOption - 必须与设置时的 `path/domain` 保持一致才能删除
97
+ */
98
+ function removeCookie(name, cookieOption) {
99
+ // 通过设置过去的时间来删除
100
+ setCookie(name, '', {
101
+ ...cookieOption,
102
+ expires: -1,
103
+ });
104
+ }
105
+ /**
106
+ * # 检测 Cookie 是否存在
107
+ * @param name
108
+ */
109
+ function hasCookie(name) {
110
+ return getCookie(name) !== null;
111
+ }
112
+ /**
113
+ * # 获取所有的 Cookie
114
+ *
115
+ */
116
+ function getAllCookie() {
117
+ const cookies = document.cookie ? document.cookie.split(';') : [];
118
+ const result = {};
119
+ for (let i = 0, j = cookies.length; i < j; i++) {
120
+ const [key, ...valParts] = cookies[i].trim().split('=');
121
+ const val = valParts.join('=');
122
+ const decodeKey = decodeURIComponent(key);
123
+ const decodeValue = decodeURIComponent(val);
124
+ try {
125
+ result[decodeKey] = JSON.parse(decodeValue);
126
+ }
127
+ catch {
128
+ result[decodeKey] = decodeValue;
129
+ }
130
+ }
131
+ return result;
132
+ }
133
+
134
+ exports.getAllCookie = getAllCookie;
135
+ exports.getCookie = getCookie;
136
+ exports.hasCookie = hasCookie;
137
+ exports.removeCookie = removeCookie;
138
+ exports.setCookie = setCookie;
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
5
+ * @file copy-text.ts
6
+ * @since 周四 12/19/2024
7
+ * @lastModified 2026-08-10 20:03
8
+ * @description 复制文本到剪切板
9
+ */
10
+ /**
11
+ * # 复制文本信息到设备剪切板
12
+ * @param text - 要设置的文本
13
+ */
14
+ async function copyText(text) {
15
+ try {
16
+ await navigator.clipboard.writeText(text);
17
+ }
18
+ catch {
19
+ if (clipboardData && clipboardData.clearData && clipboardData.setData) {
20
+ /**
21
+ * IE 大哥
22
+ *
23
+ * 该值 `clipboardData` 存在于 window 上
24
+ */
25
+ clipboardData.clearData();
26
+ clipboardData.setData('Text', text);
27
+ }
28
+ else if (document.execCommand) {
29
+ /* 旧式写法*/
30
+ const hover = document.createElement('input');
31
+ hover.value = text;
32
+ document.body.appendChild(hover);
33
+ hover.select();
34
+ document.execCommand('Copy');
35
+ hover.className = 'hover';
36
+ hover.style.display = 'none';
37
+ }
38
+ }
39
+ }
40
+
41
+ exports.copyText = copyText;
package/cjs/index.js ADDED
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ var cookie = require('./cookie.js');
4
+ var copyText = require('./copy-text.js');
5
+ var isOrientation = require('./is-orientation.js');
6
+ var isDark = require('./is-dark.js');
7
+
8
+
9
+
10
+ exports.getAllCookie = cookie.getAllCookie;
11
+ exports.getCookie = cookie.getCookie;
12
+ exports.hasCookie = cookie.hasCookie;
13
+ exports.removeCookie = cookie.removeCookie;
14
+ exports.setCookie = cookie.setCookie;
15
+ exports.copyText = copyText.copyText;
16
+ exports.isOrientation = isOrientation.isOrientation;
17
+ exports.isDarkTheme = isDark.isDarkTheme;
18
+ exports.matchMediaByString = isDark.matchMediaByString;
19
+ exports.matchMediaEvery = isDark.matchMediaEvery;
20
+ exports.matchMediaEveryState = isDark.matchMediaEveryState;
21
+ exports.matchMediaSome = isDark.matchMediaSome;
22
+ exports.matchMediaSomeState = isDark.matchMediaSomeState;
23
+ exports.matchMediaState = isDark.matchMediaState;
package/cjs/is-dark.js ADDED
@@ -0,0 +1,140 @@
1
+ 'use strict';
2
+
3
+ var is = require('@vvi/is');
4
+
5
+ /**
6
+ * @module @vvi/browser/is-dark
7
+ * @file is-dark.ts
8
+ * @description 是否为暗黑模式
9
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
10
+ * @copyright 2026 ©️ Mr.MudBean
11
+ * @since 2026-08-01 23:43
12
+ * @version 1.0.0
13
+ * @lastModified 2026-08-13 22:05
14
+ */
15
+ /**
16
+ * # 标准化媒体字符串
17
+ * @param mediaQueryString - 媒体查询条件
18
+ * @returns - 整理后的媒体查询条件
19
+ */
20
+ function normsMediaString(mediaQueryString) {
21
+ let result = mediaQueryString;
22
+ // 1. 教研参数合理性
23
+ if (is.typeOf(result) !== 'string') {
24
+ throw new Error('mediaQueryString 必须是有效字符串');
25
+ }
26
+ // 2. 处理边界
27
+ result = result.trim();
28
+ if (!result) {
29
+ throw new Error('mediaQueryString 必须是有效字符串');
30
+ }
31
+ // 3. 不带小括号(只有媒体类型)
32
+ if (['screen', 'print', 'all', 'screen', 'not', 'only'].some((item) => result.startsWith(item))) {
33
+ return result;
34
+ }
35
+ // 4. 必须带小括号(媒体类型)
36
+ if (!result.startsWith('(')) {
37
+ result = '('.concat(result);
38
+ }
39
+ if (!result.endsWith(')')) {
40
+ result = result.concat(')');
41
+ }
42
+ return result;
43
+ }
44
+ /**
45
+ * # 处理查询字符串数组
46
+ * @param mediaQueryList - 媒体查询条件数组
47
+ * @returns - 返回整理后的媒体查询条件数组
48
+ */
49
+ function validMediaQueryList(mediaQueryList) {
50
+ if (is.typeOf(mediaQueryList) !== 'array') {
51
+ throw new TypeError('mediaQueryList 必须是媒体字符串数组');
52
+ }
53
+ const result = [...mediaQueryList];
54
+ return result
55
+ .filter((item) => item && is.typeOf(item) === 'string')
56
+ .map((item) => normsMediaString(item));
57
+ }
58
+ /**
59
+ * # 获取一个指定媒体查询字符串解析后结果(仅是简单的当前状态)
60
+ * 非字符串场景将触发 `Error` 错误
61
+ * @param mediaQueryString - 查询条件
62
+ * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Window/matchMedia
63
+ */
64
+ function matchMediaByString(mediaQueryString) {
65
+ // 1. 处理字符串
66
+ mediaQueryString = normsMediaString(mediaQueryString);
67
+ // 2. 检验当前环境
68
+ if (!window || !window.matchMedia) {
69
+ throw new RangeError('当前环境非 browser 环境');
70
+ }
71
+ // 3. 返回结果
72
+ return window.matchMedia(mediaQueryString);
73
+ }
74
+ /**
75
+ * # 简单获取查询媒体状态
76
+ *
77
+ * @param mediaQueryString - 查询的条件字符串
78
+ */
79
+ function matchMediaState(mediaQueryString) {
80
+ return matchMediaByString(mediaQueryString).matches;
81
+ }
82
+ /**
83
+ * # 同时匹配多个媒体状态
84
+ * - *在字符串非法或非浏览器环境下将抛出错误*
85
+ * - *参数为非数组时将抛出错误*
86
+ * @param mediaQueryList - 匹配媒体查询条件数组
87
+ */
88
+ function matchMediaEvery(mediaQueryList) {
89
+ // 1. 处理参数
90
+ const normsMediaQueryList = validMediaQueryList(mediaQueryList);
91
+ // 2. 整理为标准查询条件字符串
92
+ const mediaQueryString = normsMediaQueryList.join(' and ');
93
+ // 3. 结果并返回
94
+ const result = matchMediaByString(mediaQueryString);
95
+ return result;
96
+ }
97
+ /**
98
+ * # 简单获取多条件查询状态
99
+ * @param mediaQueryList -
100
+ */
101
+ function matchMediaEveryState(mediaQueryList) {
102
+ return matchMediaEvery(mediaQueryList).matches;
103
+ }
104
+ /**
105
+ * # 任意符合条件媒体
106
+ * - *当前非浏览器环境将抛出错误*
107
+ * - *参数为非字符串数组时将抛出错误*
108
+ * @param mediaQueryList - 媒体查询条件数组
109
+ * @returns - 当前查询的结果媒体对象
110
+ */
111
+ function matchMediaSome(mediaQueryList) {
112
+ // 1. 处理参数
113
+ const normsMediaQueryList = validMediaQueryList(mediaQueryList);
114
+ const mediaQueryString = normsMediaQueryList.join(' , ');
115
+ return matchMediaByString(mediaQueryString);
116
+ }
117
+ /**
118
+ * # 是否符合当前任意媒体条件
119
+ * - *当前环境非浏览器环境抛出错误*
120
+ * - *参数为非字符串数组将抛出错误*
121
+ * @param mediaQueryList
122
+ * @returns - 布尔值,但满足提供的任一媒体条件则返回 `true` ,否者将返回 `false`
123
+ */
124
+ function matchMediaSomeState(mediaQueryList) {
125
+ return matchMediaSome(mediaQueryList).matches;
126
+ }
127
+ /**
128
+ * # 当前设备是否是暗黑模式主题
129
+ */
130
+ function isDarkTheme() {
131
+ return matchMediaState('(prefers-color-scheme: dark)');
132
+ }
133
+
134
+ exports.isDarkTheme = isDarkTheme;
135
+ exports.matchMediaByString = matchMediaByString;
136
+ exports.matchMediaEvery = matchMediaEvery;
137
+ exports.matchMediaEveryState = matchMediaEveryState;
138
+ exports.matchMediaSome = matchMediaSome;
139
+ exports.matchMediaSomeState = matchMediaSomeState;
140
+ exports.matchMediaState = matchMediaState;
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @module @vvi/browser/is-orientation
5
+ * @file is-orientation.ts
6
+ * @description 当前设备是否旋转
7
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
8
+ * @copyright 2026 ©️ Mr.MudBean
9
+ * @since 2026-08-01 23:46
10
+ * @version 1.0.0
11
+ * @lastModified 2026-08-13 22:05
12
+ */
13
+ /**
14
+ * # 当前设备是否横屏
15
+ */
16
+ function isOrientation() {
17
+ const orientation = (screen.orientation || {}).type ||
18
+ // eslint-disable-next-line jsdoc/check-tag-names
19
+ /** @ts-ignore: moz 浏览器 */
20
+ screen.mozOrientation ||
21
+ // eslint-disable-next-line jsdoc/check-tag-names
22
+ /** @ts-ignore: ms 浏览器 */
23
+ screen.msOrientation;
24
+ /**
25
+ * - portrait-primary 旋转 360
26
+ * - portrait-secondary 旋转 180
27
+ * - landscape-primary 旋转 90
28
+ * - landscape-secondary 旋转 270
29
+ */
30
+ if (orientation === 'landscape-primary' ||
31
+ orientation === 'landscape-secondary')
32
+ return false;
33
+ return true;
34
+ }
35
+
36
+ exports.isOrientation = isOrientation;
package/es/cookie.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @module @zza/cookie
3
+ * @file cookie.ts
4
+ * @description cookie 管理
5
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
6
+ * @copyright 2026 ©️ Mr.MudBean
7
+ * @since 01/10/2025
8
+ * @lastModified 2026-08-01 23:35
9
+ */
10
+ /**
11
+ * # 允许服务器制定是否/何时通过跨站点请求发送
12
+ * - `Strict` : cookie 仅发送它来源的站点(完全禁止跨站携带)
13
+ * - `Lax` :缺省值,仅部分安全场景允许跨站携带
14
+ * - `None` :指定浏览器会在同站请求和跨站请求下继续发送 cookie
15
+ * @see https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Reference/Headers/Set-Cookie#samesitesamesite-value
16
+ */
17
+ export type CookieSameSite = 'Strict' | 'Lax' | 'None';
18
+ /**
19
+ * # Cookie 的配置项
20
+ */
21
+ export type CookieOption = {
22
+ /**
23
+ * # 过期时间(以天为单位,支持小数)
24
+ * @see https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Reference/Headers/Set-Cookie#expiresdate
25
+ */
26
+ expires?: number;
27
+ /**
28
+ * ## 指定一个 URL 路径
29
+ * 该路径以字符 `%x2F` ("/") 作为路径分隔符,并且子路径也会被匹配
30
+ */
31
+ path?: string;
32
+ /**
33
+ * ## 指定哪些主机可以接受 Cookie
34
+ * 缺省默认为同一 host 设置的 cookie,不包含子域名
35
+ * 例如,如果设置了 `Domain=`
36
+ */
37
+ domain?: string;
38
+ /** 仅允许使用 HTTPS 协议加密过的请求发送给服务器 */
39
+ secure?: string;
40
+ /**
41
+ * # 允许服务器制定是否/何时通过跨站点请求发送
42
+ * @see CookieSameSite
43
+ */
44
+ sameSite?: CookieSameSite;
45
+ };
46
+ /**
47
+ * # 根据键值获取 cookie 值
48
+ * @param name cookie 键值
49
+ * @returns
50
+ */
51
+ export declare function getCookie(name: string): string | null;
52
+ /**
53
+ * # 设置 cookie 值
54
+ *
55
+ * 未传入 `name` 将抛出错误
56
+ * @param name - Cookie 名称
57
+ * @param value - Cookie 值(支持对象/数组,会自动 JSON 序列化)
58
+ * @param cookieOption - 配置项
59
+ * @see CookieOption
60
+ */
61
+ export declare function setCookie(name: string, value: string, cookieOption?: CookieOption): void;
62
+ /**
63
+ * # 删除指定 Cookie
64
+ * @param name - Cookie 名称
65
+ * @param cookieOption - 必须与设置时的 `path/domain` 保持一致才能删除
66
+ */
67
+ export declare function removeCookie(name: string, cookieOption?: CookieOption): void;
68
+ /**
69
+ * # 检测 Cookie 是否存在
70
+ * @param name
71
+ */
72
+ export declare function hasCookie(name: string): boolean;
73
+ /**
74
+ * # 获取所有的 Cookie
75
+ *
76
+ */
77
+ export declare function getAllCookie(): Record<string, any>;
package/es/cookie.js ADDED
@@ -0,0 +1,132 @@
1
+ import { typeOf, isNaN } from '@vvi/is';
2
+
3
+ /**
4
+ * # 根据键值获取 cookie 值
5
+ * @param name cookie 键值
6
+ * @returns
7
+ */
8
+ function getCookie(name) {
9
+ if (!name || typeOf(name) != 'string') {
10
+ return null;
11
+ }
12
+ const cookies = document.cookie ? document.cookie.split(';') : [];
13
+ const encodedName = encodeURIComponent(name);
14
+ for (let i = 0, j = cookies.length; i < j; i++) {
15
+ const [key, ...valParts] = cookies[i].trim().split('=');
16
+ if (key !== encodedName) {
17
+ continue;
18
+ }
19
+ // 处理可能包含 "=" 的情况
20
+ const val = valParts.join('=');
21
+ const decodedVal = decodeURIComponent(val);
22
+ try {
23
+ // 尝试解析 JSON ,失败则返回原字符串
24
+ return JSON.parse(decodedVal);
25
+ }
26
+ catch {
27
+ return decodedVal;
28
+ }
29
+ }
30
+ return null;
31
+ // 使用正则可能对性能不太好
32
+ // 1. 依赖 `document.cookie.replace` 捕获分组,匹配不到时返回空字符串,容易误判
33
+ // 2. 正则里 `.*` 贪婪匹配,极端 cookie 长度下性能差
34
+ // 3. 对 cookie value 中出现 `;`、空格等边界处理较弱
35
+ // 4. 没有处理 `key=` 后面空格、空值的鲁棒性
36
+ // 5. 无法天然支持 value 中包含 `=` 的场景
37
+ // const handledKey = encodeURIComponent(keyItem).replace(/[-.+*]/g, '\\$&');
38
+ // const regStr =
39
+ // '(?:(?:^|.*;)\\s*' + handledKey + '\\s*\\=\\s*([^;]*).*$)|^.*$';
40
+ // const reg = new RegExp(regStr);
41
+ // const value = document.cookie.replace(reg, '$1');
42
+ // const result = decodeURIComponent(value);
43
+ // return result || null;
44
+ }
45
+ /**
46
+ * # 设置 cookie 值
47
+ *
48
+ * 未传入 `name` 将抛出错误
49
+ * @param name - Cookie 名称
50
+ * @param value - Cookie 值(支持对象/数组,会自动 JSON 序列化)
51
+ * @param cookieOption - 配置项
52
+ * @see CookieOption
53
+ */
54
+ function setCookie(name, value, cookieOption) {
55
+ let { expires, path, domain, secure, sameSite } = cookieOption ?? {};
56
+ if (!name) {
57
+ throw new Error('Cookie 的 "name" 是必须的');
58
+ }
59
+ const valueType = typeOf(value);
60
+ // 1. 处理值 : 如果是对象/数组则进行序列化,并统一进行 URI 编码
61
+ let cookieValue = valueType === 'object' ||
62
+ valueType == 'array' ||
63
+ valueType == 'set' ||
64
+ valueType == 'map'
65
+ ? JSON.stringify(value)
66
+ : String(value);
67
+ cookieValue = encodeURIComponent(cookieValue);
68
+ // 2. 构建 Cookie 字符串
69
+ let cookieStr = `${encodeURIComponent(name)}=${cookieValue}`;
70
+ // 3. 处理过期时间
71
+ const expiresType = typeOf(expires);
72
+ if (expires &&
73
+ expiresType === 'number' &&
74
+ expires != Infinity &&
75
+ expires != -Infinity &&
76
+ !isNaN(expires)) {
77
+ const date = new Date();
78
+ date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);
79
+ cookieStr += `; expires=${date.toUTCString()}`;
80
+ }
81
+ // 4. 处理其他属性
82
+ cookieStr += `; path=${path && typeOf(path) == 'string' ? domain : '/'}`;
83
+ if (domain && typeOf(domain) === 'string')
84
+ cookieStr += `; domain=${domain}`;
85
+ if (secure)
86
+ cookieStr += `; secure`;
87
+ if (sameSite)
88
+ cookieStr += `; samesite=${sameSite}`;
89
+ document.cookie = cookieStr;
90
+ }
91
+ /**
92
+ * # 删除指定 Cookie
93
+ * @param name - Cookie 名称
94
+ * @param cookieOption - 必须与设置时的 `path/domain` 保持一致才能删除
95
+ */
96
+ function removeCookie(name, cookieOption) {
97
+ // 通过设置过去的时间来删除
98
+ setCookie(name, '', {
99
+ ...cookieOption,
100
+ expires: -1,
101
+ });
102
+ }
103
+ /**
104
+ * # 检测 Cookie 是否存在
105
+ * @param name
106
+ */
107
+ function hasCookie(name) {
108
+ return getCookie(name) !== null;
109
+ }
110
+ /**
111
+ * # 获取所有的 Cookie
112
+ *
113
+ */
114
+ function getAllCookie() {
115
+ const cookies = document.cookie ? document.cookie.split(';') : [];
116
+ const result = {};
117
+ for (let i = 0, j = cookies.length; i < j; i++) {
118
+ const [key, ...valParts] = cookies[i].trim().split('=');
119
+ const val = valParts.join('=');
120
+ const decodeKey = decodeURIComponent(key);
121
+ const decodeValue = decodeURIComponent(val);
122
+ try {
123
+ result[decodeKey] = JSON.parse(decodeValue);
124
+ }
125
+ catch {
126
+ result[decodeKey] = decodeValue;
127
+ }
128
+ }
129
+ return result;
130
+ }
131
+
132
+ export { getAllCookie, getCookie, hasCookie, removeCookie, setCookie };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
3
+ * @file copy-text.ts
4
+ * @since 周四 12/19/2024
5
+ * @lastModified 2026-08-10 20:03
6
+ * @description 复制文本到剪切板
7
+ */
8
+ declare global {
9
+ const clipboardData: {
10
+ /**
11
+ * 清空当前的剪切板
12
+ */
13
+ clearData(): void;
14
+ /**
15
+ * 设置新的剪切板数据
16
+ */
17
+ setData(arg0: 'Text', arg1: string): void;
18
+ };
19
+ }
20
+ /**
21
+ * # 复制文本信息到设备剪切板
22
+ * @param text - 要设置的文本
23
+ */
24
+ export declare function copyText(text: string): Promise<void>;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
3
+ * @file copy-text.ts
4
+ * @since 周四 12/19/2024
5
+ * @lastModified 2026-08-10 20:03
6
+ * @description 复制文本到剪切板
7
+ */
8
+ /**
9
+ * # 复制文本信息到设备剪切板
10
+ * @param text - 要设置的文本
11
+ */
12
+ async function copyText(text) {
13
+ try {
14
+ await navigator.clipboard.writeText(text);
15
+ }
16
+ catch {
17
+ if (clipboardData && clipboardData.clearData && clipboardData.setData) {
18
+ /**
19
+ * IE 大哥
20
+ *
21
+ * 该值 `clipboardData` 存在于 window 上
22
+ */
23
+ clipboardData.clearData();
24
+ clipboardData.setData('Text', text);
25
+ }
26
+ else if (document.execCommand) {
27
+ /* 旧式写法*/
28
+ const hover = document.createElement('input');
29
+ hover.value = text;
30
+ document.body.appendChild(hover);
31
+ hover.select();
32
+ document.execCommand('Copy');
33
+ hover.className = 'hover';
34
+ hover.style.display = 'none';
35
+ }
36
+ }
37
+ }
38
+
39
+ export { copyText };
package/es/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { setCookie, getAllCookie, getCookie, removeCookie, hasCookie, } from './cookie';
2
+ export type { CookieOption, CookieSameSite } from './cookie';
3
+ export { copyText } from './copy-text';
4
+ export { isOrientation } from './is-orientation';
5
+ export { isDarkTheme, matchMediaByString, matchMediaState, matchMediaEvery, matchMediaEveryState, matchMediaSome, matchMediaSomeState, } from './is-dark';
package/es/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { getAllCookie, getCookie, hasCookie, removeCookie, setCookie } from './cookie.js';
2
+ export { copyText } from './copy-text.js';
3
+ export { isOrientation } from './is-orientation.js';
4
+ export { isDarkTheme, matchMediaByString, matchMediaEvery, matchMediaEveryState, matchMediaSome, matchMediaSomeState, matchMediaState } from './is-dark.js';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @module @vvi/browser/is-dark
3
+ * @file is-dark.ts
4
+ * @description 是否为暗黑模式
5
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
6
+ * @copyright 2026 ©️ Mr.MudBean
7
+ * @since 2026-08-01 23:43
8
+ * @version 1.0.0
9
+ * @lastModified 2026-08-13 22:05
10
+ */
11
+ /**
12
+ * # 获取一个指定媒体查询字符串解析后结果(仅是简单的当前状态)
13
+ * 非字符串场景将触发 `Error` 错误
14
+ * @param mediaQueryString - 查询条件
15
+ * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Window/matchMedia
16
+ */
17
+ export declare function matchMediaByString(mediaQueryString: string): MediaQueryList;
18
+ /**
19
+ * # 简单获取查询媒体状态
20
+ *
21
+ * @param mediaQueryString - 查询的条件字符串
22
+ */
23
+ export declare function matchMediaState(mediaQueryString: string): boolean;
24
+ /**
25
+ * # 同时匹配多个媒体状态
26
+ * - *在字符串非法或非浏览器环境下将抛出错误*
27
+ * - *参数为非数组时将抛出错误*
28
+ * @param mediaQueryList - 匹配媒体查询条件数组
29
+ */
30
+ export declare function matchMediaEvery(mediaQueryList: string[]): MediaQueryList;
31
+ /**
32
+ * # 简单获取多条件查询状态
33
+ * @param mediaQueryList -
34
+ */
35
+ export declare function matchMediaEveryState(mediaQueryList: string[]): boolean;
36
+ /**
37
+ * # 任意符合条件媒体
38
+ * - *当前非浏览器环境将抛出错误*
39
+ * - *参数为非字符串数组时将抛出错误*
40
+ * @param mediaQueryList - 媒体查询条件数组
41
+ * @returns - 当前查询的结果媒体对象
42
+ */
43
+ export declare function matchMediaSome(mediaQueryList: string[]): MediaQueryList;
44
+ /**
45
+ * # 是否符合当前任意媒体条件
46
+ * - *当前环境非浏览器环境抛出错误*
47
+ * - *参数为非字符串数组将抛出错误*
48
+ * @param mediaQueryList
49
+ * @returns - 布尔值,但满足提供的任一媒体条件则返回 `true` ,否者将返回 `false`
50
+ */
51
+ export declare function matchMediaSomeState(mediaQueryList: string[]): boolean;
52
+ /**
53
+ * # 当前设备是否是暗黑模式主题
54
+ */
55
+ export declare function isDarkTheme(): boolean;
package/es/is-dark.js ADDED
@@ -0,0 +1,132 @@
1
+ import { typeOf } from '@vvi/is';
2
+
3
+ /**
4
+ * @module @vvi/browser/is-dark
5
+ * @file is-dark.ts
6
+ * @description 是否为暗黑模式
7
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
8
+ * @copyright 2026 ©️ Mr.MudBean
9
+ * @since 2026-08-01 23:43
10
+ * @version 1.0.0
11
+ * @lastModified 2026-08-13 22:05
12
+ */
13
+ /**
14
+ * # 标准化媒体字符串
15
+ * @param mediaQueryString - 媒体查询条件
16
+ * @returns - 整理后的媒体查询条件
17
+ */
18
+ function normsMediaString(mediaQueryString) {
19
+ let result = mediaQueryString;
20
+ // 1. 教研参数合理性
21
+ if (typeOf(result) !== 'string') {
22
+ throw new Error('mediaQueryString 必须是有效字符串');
23
+ }
24
+ // 2. 处理边界
25
+ result = result.trim();
26
+ if (!result) {
27
+ throw new Error('mediaQueryString 必须是有效字符串');
28
+ }
29
+ // 3. 不带小括号(只有媒体类型)
30
+ if (['screen', 'print', 'all', 'screen', 'not', 'only'].some((item) => result.startsWith(item))) {
31
+ return result;
32
+ }
33
+ // 4. 必须带小括号(媒体类型)
34
+ if (!result.startsWith('(')) {
35
+ result = '('.concat(result);
36
+ }
37
+ if (!result.endsWith(')')) {
38
+ result = result.concat(')');
39
+ }
40
+ return result;
41
+ }
42
+ /**
43
+ * # 处理查询字符串数组
44
+ * @param mediaQueryList - 媒体查询条件数组
45
+ * @returns - 返回整理后的媒体查询条件数组
46
+ */
47
+ function validMediaQueryList(mediaQueryList) {
48
+ if (typeOf(mediaQueryList) !== 'array') {
49
+ throw new TypeError('mediaQueryList 必须是媒体字符串数组');
50
+ }
51
+ const result = [...mediaQueryList];
52
+ return result
53
+ .filter((item) => item && typeOf(item) === 'string')
54
+ .map((item) => normsMediaString(item));
55
+ }
56
+ /**
57
+ * # 获取一个指定媒体查询字符串解析后结果(仅是简单的当前状态)
58
+ * 非字符串场景将触发 `Error` 错误
59
+ * @param mediaQueryString - 查询条件
60
+ * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Window/matchMedia
61
+ */
62
+ function matchMediaByString(mediaQueryString) {
63
+ // 1. 处理字符串
64
+ mediaQueryString = normsMediaString(mediaQueryString);
65
+ // 2. 检验当前环境
66
+ if (!window || !window.matchMedia) {
67
+ throw new RangeError('当前环境非 browser 环境');
68
+ }
69
+ // 3. 返回结果
70
+ return window.matchMedia(mediaQueryString);
71
+ }
72
+ /**
73
+ * # 简单获取查询媒体状态
74
+ *
75
+ * @param mediaQueryString - 查询的条件字符串
76
+ */
77
+ function matchMediaState(mediaQueryString) {
78
+ return matchMediaByString(mediaQueryString).matches;
79
+ }
80
+ /**
81
+ * # 同时匹配多个媒体状态
82
+ * - *在字符串非法或非浏览器环境下将抛出错误*
83
+ * - *参数为非数组时将抛出错误*
84
+ * @param mediaQueryList - 匹配媒体查询条件数组
85
+ */
86
+ function matchMediaEvery(mediaQueryList) {
87
+ // 1. 处理参数
88
+ const normsMediaQueryList = validMediaQueryList(mediaQueryList);
89
+ // 2. 整理为标准查询条件字符串
90
+ const mediaQueryString = normsMediaQueryList.join(' and ');
91
+ // 3. 结果并返回
92
+ const result = matchMediaByString(mediaQueryString);
93
+ return result;
94
+ }
95
+ /**
96
+ * # 简单获取多条件查询状态
97
+ * @param mediaQueryList -
98
+ */
99
+ function matchMediaEveryState(mediaQueryList) {
100
+ return matchMediaEvery(mediaQueryList).matches;
101
+ }
102
+ /**
103
+ * # 任意符合条件媒体
104
+ * - *当前非浏览器环境将抛出错误*
105
+ * - *参数为非字符串数组时将抛出错误*
106
+ * @param mediaQueryList - 媒体查询条件数组
107
+ * @returns - 当前查询的结果媒体对象
108
+ */
109
+ function matchMediaSome(mediaQueryList) {
110
+ // 1. 处理参数
111
+ const normsMediaQueryList = validMediaQueryList(mediaQueryList);
112
+ const mediaQueryString = normsMediaQueryList.join(' , ');
113
+ return matchMediaByString(mediaQueryString);
114
+ }
115
+ /**
116
+ * # 是否符合当前任意媒体条件
117
+ * - *当前环境非浏览器环境抛出错误*
118
+ * - *参数为非字符串数组将抛出错误*
119
+ * @param mediaQueryList
120
+ * @returns - 布尔值,但满足提供的任一媒体条件则返回 `true` ,否者将返回 `false`
121
+ */
122
+ function matchMediaSomeState(mediaQueryList) {
123
+ return matchMediaSome(mediaQueryList).matches;
124
+ }
125
+ /**
126
+ * # 当前设备是否是暗黑模式主题
127
+ */
128
+ function isDarkTheme() {
129
+ return matchMediaState('(prefers-color-scheme: dark)');
130
+ }
131
+
132
+ export { isDarkTheme, matchMediaByString, matchMediaEvery, matchMediaEveryState, matchMediaSome, matchMediaSomeState, matchMediaState };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @module @vvi/browser/is-orientation
3
+ * @file is-orientation.ts
4
+ * @description 当前设备是否旋转
5
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
6
+ * @copyright 2026 ©️ Mr.MudBean
7
+ * @since 2026-08-01 23:46
8
+ * @version 1.0.0
9
+ * @lastModified 2026-08-13 22:05
10
+ */
11
+ /**
12
+ * # 当前设备是否横屏
13
+ */
14
+ export declare function isOrientation(): boolean;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @module @vvi/browser/is-orientation
3
+ * @file is-orientation.ts
4
+ * @description 当前设备是否旋转
5
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
6
+ * @copyright 2026 ©️ Mr.MudBean
7
+ * @since 2026-08-01 23:46
8
+ * @version 1.0.0
9
+ * @lastModified 2026-08-13 22:05
10
+ */
11
+ /**
12
+ * # 当前设备是否横屏
13
+ */
14
+ function isOrientation() {
15
+ const orientation = (screen.orientation || {}).type ||
16
+ // eslint-disable-next-line jsdoc/check-tag-names
17
+ /** @ts-ignore: moz 浏览器 */
18
+ screen.mozOrientation ||
19
+ // eslint-disable-next-line jsdoc/check-tag-names
20
+ /** @ts-ignore: ms 浏览器 */
21
+ screen.msOrientation;
22
+ /**
23
+ * - portrait-primary 旋转 360
24
+ * - portrait-secondary 旋转 180
25
+ * - landscape-primary 旋转 90
26
+ * - landscape-secondary 旋转 270
27
+ */
28
+ if (orientation === 'landscape-primary' ||
29
+ orientation === 'landscape-secondary')
30
+ return false;
31
+ return true;
32
+ }
33
+
34
+ export { isOrientation };
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @module @vvi/browser/storage
3
+ * @file storage.ts
4
+ * @description 本地储存
5
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
6
+ * @copyright 2026 ©️ Mr.MudBean
7
+ * @since 2026-08-06 23:31
8
+ * @version 1.0.0
9
+ * @lastModified 2026-08-08 19:34
10
+ */
11
+ /**
12
+ *
13
+ */
14
+ export declare class Storage {
15
+ #private;
16
+ /**
17
+ * # 前缀
18
+ * 设置可防止多项目部署的时候 key 冲突 (例如 `myApp_` )
19
+ */
20
+ prefix: string;
21
+ /**
22
+ * # 切换储存类型
23
+ * @param type - 要切换的类型,除了传入 `session` 外,其余都将视为更改为 `localStorage`
24
+ */
25
+ use(type?: 'session'): void;
26
+ /**
27
+ *
28
+ */
29
+ set(key: string, value: any): boolean;
30
+ /**
31
+ *
32
+ */
33
+ get(key: string): any;
34
+ /**
35
+ *
36
+ */
37
+ remove(key: string): Storage;
38
+ /**
39
+ *
40
+ */
41
+ clear(): Storage;
42
+ /**
43
+ *
44
+ */
45
+ has(key: string): boolean;
46
+ /**
47
+ * # 获取所有的本地储存值
48
+ * @returns 获取的所有本地储存
49
+ */
50
+ getAll(): Record<string, any>;
51
+ }
package/package.json ADDED
@@ -0,0 +1,112 @@
1
+ {
2
+ "name": "@vvi/browser",
3
+ "version": "1.0.0",
4
+ "main": "cjs/index.js",
5
+ "types": "es/index.d.ts",
6
+ "author": {
7
+ "name": "MrMudBean",
8
+ "email": "Mr.MudBean@outlook.com",
9
+ "url": "https://mudbean.cn"
10
+ },
11
+ "description": "简单的浏览器方法",
12
+ "sideEffects": false,
13
+ "license": "MIT",
14
+ "files": [
15
+ "cjs",
16
+ "es",
17
+ "LICENSE",
18
+ "README.md",
19
+ "CHANGELOG.md"
20
+ ],
21
+ "exports": {
22
+ ".": {
23
+ "import": {
24
+ "default": "./es/index.js",
25
+ "types": "./es/index.d.ts"
26
+ },
27
+ "require": {
28
+ "default": "./cjs/index.js",
29
+ "types": "./es/index.d.ts"
30
+ }
31
+ },
32
+ "./cookie": {
33
+ "import": {
34
+ "default": "./es/cookie.js",
35
+ "types": "./es/cookie.d.ts"
36
+ },
37
+ "require": {
38
+ "default": "./cjs/cookie.js",
39
+ "types": "./es/cookie.d.ts"
40
+ }
41
+ },
42
+ "./copy-text": {
43
+ "import": {
44
+ "default": "./es/copy-text.js",
45
+ "types": "./es/copy-text.d.ts"
46
+ },
47
+ "require": {
48
+ "default": "./cjs/copy-text.js",
49
+ "types": "./es/copy-text.d.ts"
50
+ }
51
+ },
52
+ "./is-dark": {
53
+ "import": {
54
+ "default": "./es/is-dark.js",
55
+ "types": "./es/is-dark.d.ts"
56
+ },
57
+ "require": {
58
+ "default": "./cjs/is-dark.js",
59
+ "types": "./es/is-dark.d.ts"
60
+ }
61
+ },
62
+ "./is-orientation": {
63
+ "import": {
64
+ "default": "./es/is-orientation.js",
65
+ "types": "./es/is-orientation.d.ts"
66
+ },
67
+ "require": {
68
+ "default": "./cjs/is-orientation.js",
69
+ "types": "./es/is-orientation.d.ts"
70
+ }
71
+ },
72
+ "./storage": {
73
+ "import": {
74
+ "default": "./es/storage.js",
75
+ "types": "./es/storage.d.ts"
76
+ },
77
+ "require": {
78
+ "default": "./cjs/storage.js",
79
+ "types": "./es/storage.d.ts"
80
+ }
81
+ }
82
+ },
83
+ "keywords": [
84
+ "browser",
85
+ "vvi",
86
+ "mudbean"
87
+ ],
88
+ "homepage": "https://npm.lmssee.com/browser",
89
+ "dependencies": {
90
+ "@vvi/is": "^2.0.6",
91
+ "@vvi/utils": "^2.1.0"
92
+ },
93
+ "bugs": {
94
+ "url": "https://github.com/MrMudBean/browser/issues",
95
+ "email": "Mr.MudBean@outlook.com"
96
+ },
97
+ "repository": {
98
+ "type": "git",
99
+ "url": "git+https://github.com/MrMudBean/browser.git"
100
+ },
101
+ "publishConfig": {
102
+ "access": "public",
103
+ "registry": "https://registry.npmjs.org/"
104
+ },
105
+ "browserslist": [
106
+ "> 1%",
107
+ "last 2 versions"
108
+ ],
109
+ "engines": {
110
+ "node": ">=18.0.0"
111
+ }
112
+ }