ph-utils 0.20.1 → 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.
Files changed (74) hide show
  1. package/lib/browser.d.ts +416 -0
  2. package/lib/browser.js +858 -0
  3. package/lib/color-CUZrwrjD.js +206 -0
  4. package/lib/index.d.ts +615 -61
  5. package/lib/index.js +1539 -235
  6. package/lib/node.d.ts +115 -0
  7. package/lib/node.js +213 -0
  8. package/package.json +10 -64
  9. package/lib/array.d.ts +0 -79
  10. package/lib/array.js +0 -212
  11. package/lib/color.d.ts +0 -55
  12. package/lib/color.js +0 -294
  13. package/lib/config.d.ts +0 -33
  14. package/lib/config.js +0 -99
  15. package/lib/copy.d.ts +0 -11
  16. package/lib/copy.js +0 -101
  17. package/lib/crypto.d.ts +0 -74
  18. package/lib/crypto.js +0 -261
  19. package/lib/crypto_node.d.ts +0 -61
  20. package/lib/crypto_node.js +0 -133
  21. package/lib/date.d.ts +0 -66
  22. package/lib/date.js +0 -202
  23. package/lib/dom.d.ts +0 -265
  24. package/lib/dom.js +0 -645
  25. package/lib/file.d.ts +0 -29
  26. package/lib/file.js +0 -54
  27. package/lib/id.d.ts +0 -68
  28. package/lib/id.js +0 -170
  29. package/lib/logger.d.ts +0 -62
  30. package/lib/logger.js +0 -122
  31. package/lib/server.d.ts +0 -33
  32. package/lib/server.js +0 -65
  33. package/lib/src/array.d.ts +0 -79
  34. package/lib/src/array.js +0 -212
  35. package/lib/src/color.d.ts +0 -55
  36. package/lib/src/color.js +0 -294
  37. package/lib/src/config.d.ts +0 -33
  38. package/lib/src/config.js +0 -99
  39. package/lib/src/copy.d.ts +0 -11
  40. package/lib/src/copy.js +0 -101
  41. package/lib/src/crypto.d.ts +0 -74
  42. package/lib/src/crypto.js +0 -261
  43. package/lib/src/crypto_node.d.ts +0 -61
  44. package/lib/src/crypto_node.js +0 -133
  45. package/lib/src/date.d.ts +0 -66
  46. package/lib/src/date.js +0 -202
  47. package/lib/src/dom.d.ts +0 -265
  48. package/lib/src/dom.js +0 -635
  49. package/lib/src/file.d.ts +0 -29
  50. package/lib/src/file.js +0 -54
  51. package/lib/src/id.d.ts +0 -68
  52. package/lib/src/id.js +0 -170
  53. package/lib/src/index.d.ts +0 -154
  54. package/lib/src/index.js +0 -239
  55. package/lib/src/logger.d.ts +0 -62
  56. package/lib/src/logger.js +0 -122
  57. package/lib/src/server.d.ts +0 -33
  58. package/lib/src/server.js +0 -65
  59. package/lib/src/storage.d.ts +0 -51
  60. package/lib/src/storage.js +0 -73
  61. package/lib/src/theme.d.ts +0 -44
  62. package/lib/src/theme.js +0 -156
  63. package/lib/src/validator.d.ts +0 -71
  64. package/lib/src/validator.js +0 -238
  65. package/lib/src/web.d.ts +0 -30
  66. package/lib/src/web.js +0 -100
  67. package/lib/storage.d.ts +0 -51
  68. package/lib/storage.js +0 -73
  69. package/lib/theme.d.ts +0 -44
  70. package/lib/theme.js +0 -156
  71. package/lib/validator.d.ts +0 -71
  72. package/lib/validator.js +0 -248
  73. package/lib/web.d.ts +0 -30
  74. package/lib/web.js +0 -100
@@ -1,238 +0,0 @@
1
- /**
2
- * 数据验证器
3
- */
4
- // 默认的错误提示信息
5
- const defaultMsgs = {
6
- mobile: "请输入正确的手机号",
7
- same: "两次输入不一致",
8
- required: "%s为必填字段",
9
- };
10
- const defaultMsg = "请输入正确的数据";
11
- // 一些常用的验证正则
12
- const ruleRegexs = {
13
- /** 验证跟其余数据相等的正则,一般用于验证再次输入密码 */
14
- same: /^same:(.+)$/i,
15
- /** 验证手机号的正则表达式 */
16
- mobile: /^1[3456789]\d{9}$/,
17
- /** 非空验证的正则表达式 */
18
- required: /^\S{1}.*/,
19
- };
20
- // 规则比对函数
21
- const ruleFns = {
22
- /** 验证相等 */
23
- same(val1, val2) {
24
- return val2 === val1;
25
- },
26
- /** 正则匹配 */
27
- pattern(regex, val) {
28
- if (val == null) {
29
- return false;
30
- }
31
- return regex.test(String(val));
32
- },
33
- };
34
- class ValidateError extends Error {
35
- constructor(detail, key, message) {
36
- super(message);
37
- this.name = "ValidateError";
38
- this.key = key;
39
- this.detail = detail;
40
- }
41
- }
42
- /**
43
- * 数据验证器
44
- */
45
- class Validator {
46
- /**
47
- * 构造数据验证转换器
48
- *
49
- * See {@link https://gitee.com/towardly/ph/wikis/utils/validator|Validator文档}.
50
- *
51
- * @param schemas 配置验证转换规则
52
- *
53
- * @example
54
- *
55
- * const validator = new Validator([
56
- * { key: 'mobile', rules: ['required', 'mobile'] },
57
- * { key: 'code': rules: /^\d{6}$/, message: '请输入正确的验证码' },
58
- * { key: 'confirmPassword', rules: ['required', 'same:password'] }
59
- * ])
60
- * // 验证某一个字段
61
- * validator.validateKey().then(res => {})
62
- */
63
- constructor(schemas) {
64
- this.rules = {};
65
- this.addSchemas(schemas);
66
- }
67
- addSchemas(schemas) {
68
- for (let schema of schemas) {
69
- this.rules[schema.key] = this._parseSchemaRules(schema);
70
- }
71
- }
72
- addSchema(schema) {
73
- this.rules[schema.key] = this._parseSchemaRules(schema);
74
- }
75
- /**
76
- * 进行数据验证
77
- * @param data 待验证的数据
78
- * @param all 是否全部验证, false - 只要验证错误一个则停止验证
79
- * @returns
80
- */
81
- async validate(data, all = false) {
82
- return new Promise((resolve, reject) => {
83
- const detail = {};
84
- let currentKey = undefined;
85
- let currentMessage = undefined;
86
- for (let key in this.rules) {
87
- let errMsg = this._validateRule(this.rules[key], data[key], data);
88
- if (errMsg !== "") {
89
- errMsg = errMsg.replace("%s", key);
90
- detail[key] = errMsg;
91
- currentKey = key;
92
- currentMessage = errMsg;
93
- if (all)
94
- break;
95
- }
96
- }
97
- if (currentKey == null) {
98
- resolve(true);
99
- }
100
- else {
101
- reject(new ValidateError(detail, currentKey, currentMessage));
102
- }
103
- });
104
- }
105
- /**
106
- * 只验证指定 key 的数据格式
107
- * @param key 指定待验证的 key
108
- * @param value 待验证的数据
109
- * @param data 原始数据,当验证确认密码时需要使用
110
- */
111
- async validateKey(key, value, data) {
112
- return new Promise((resolve, reject) => {
113
- let keyRules = this.rules[key];
114
- if (keyRules == null) {
115
- resolve({ key, value });
116
- return;
117
- }
118
- let errMsg = this._validateRule(keyRules, value, data);
119
- if (errMsg !== "") {
120
- errMsg = errMsg.replace("%s", key);
121
- reject(new ValidateError({ [key]: errMsg }, key, errMsg));
122
- }
123
- else {
124
- resolve({ key, value });
125
- }
126
- });
127
- }
128
- _validateRule(rules, value, data) {
129
- let errMsg = "";
130
- for (let rule of rules) {
131
- if (!rule)
132
- continue;
133
- // 如果数据为空,则判断是否是必填
134
- if (rule.rule === "required") {
135
- if (value == null || !ruleFns.pattern(ruleRegexs.required, value)) {
136
- errMsg = rule.message;
137
- }
138
- }
139
- else if (typeof rule.rule === "function") {
140
- if (!rule.rule(value)) {
141
- errMsg = rule.message;
142
- }
143
- }
144
- else if (rule.sameKey != null) {
145
- if (data != null) {
146
- if (!ruleFns.same(value, data[rule.sameKey])) {
147
- errMsg = rule.message;
148
- }
149
- }
150
- }
151
- else {
152
- if (rule && !ruleFns.pattern(rule.rule, value)) {
153
- errMsg = rule.message;
154
- }
155
- }
156
- if (errMsg !== "") {
157
- break;
158
- }
159
- }
160
- return errMsg;
161
- }
162
- _parseSchemaRules(schema) {
163
- // 解析规则
164
- let rules = [];
165
- let rule = schema.rules;
166
- if (schema.required === true) {
167
- rules.push(...this._parseStringRule("required", schema.message));
168
- }
169
- if (rule != null) {
170
- if (typeof rule === "string") {
171
- rules.push(...this._parseStringRule(rule, schema.message));
172
- }
173
- else if (rule instanceof Array) {
174
- for (let ruleItem of rule) {
175
- if (typeof ruleItem === "string") {
176
- rules.push(...this._parseStringRule(ruleItem, schema.message));
177
- }
178
- else if (ruleItem instanceof RegExp ||
179
- typeof ruleItem === "function") {
180
- rules.push({
181
- rule: ruleItem,
182
- message: schema.message || defaultMsg,
183
- });
184
- }
185
- else {
186
- const emessage = ruleItem.message || schema.message || defaultMsg;
187
- if (typeof ruleItem.rule === "string") {
188
- rules.push(...this._parseStringRule(ruleItem.rule, emessage));
189
- }
190
- else {
191
- rules.push({
192
- rule: ruleItem.rule,
193
- message: emessage,
194
- });
195
- }
196
- }
197
- }
198
- }
199
- else {
200
- rules.push({ rule, message: defaultMsg });
201
- }
202
- }
203
- return rules;
204
- }
205
- _parseStringRule(rule, ruleErrMsg) {
206
- let rules = [];
207
- let trule = rule.split("|");
208
- for (let r of trule) {
209
- let message = ruleErrMsg;
210
- let rrule = null;
211
- let sameKey;
212
- if (rule === "required") {
213
- rrule = "required";
214
- message = message || ruleErrMsg || defaultMsgs.required;
215
- }
216
- else if (ruleRegexs.same.test(r)) {
217
- let m = r.match(ruleRegexs.same);
218
- if (m != null) {
219
- rrule = ruleRegexs.same;
220
- let m = r.match(ruleRegexs.same);
221
- if (m != null) {
222
- sameKey = m[1];
223
- }
224
- message = message || defaultMsgs["same"];
225
- }
226
- }
227
- else if (Object.hasOwn(ruleRegexs, r)) {
228
- rrule = ruleRegexs[r];
229
- message = message || defaultMsgs[r];
230
- }
231
- if (rrule) {
232
- rules.push({ rule: rrule, message: message, sameKey });
233
- }
234
- }
235
- return rules;
236
- }
237
- }
238
- export default Validator;
package/lib/src/web.d.ts DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * 解析 Form 表单中的 input 元素的数据为 JSON 格式,key: input-name;value: input-value
3
- * @param form {object} Form 节点对象
4
- */
5
- export declare const formJson: <T>(form: HTMLFormElement) => T;
6
- /**
7
- * 获取 url query 参数 (get 请求的参数)
8
- * @param search 如果是 React 应用就需要传递 useLocation().search
9
- * @returns
10
- */
11
- export declare function query(search?: string): {
12
- [index: string]: string;
13
- };
14
- /**
15
- * 函数节流 - 每隔单位时间,只执行一次
16
- * @param cb 待节流的函数
17
- * @param wait 间隔时间
18
- * @returns
19
- */
20
- export declare function throttle<R extends any[], T>(fn: (...args: R) => T, wait?: number): (...args: R) => void;
21
- /**
22
- * 函数防抖 - 当重复触发某一个行为(事件时),只执行最后一次触发
23
- * @param fn 防抖函数
24
- * @param interval 间隔时间段
25
- * @returns
26
- */
27
- export declare function debounce<R extends any[], T>(fn: (...args: R) => T, interval?: number): {
28
- (...args: R): void;
29
- cancel(): void;
30
- };
package/lib/src/web.js DELETED
@@ -1,100 +0,0 @@
1
- /**
2
- * web(浏览器) 端工具类
3
- */
4
- import { isBlank } from "./index.js";
5
- /**
6
- * 解析 Form 表单中的 input 元素的数据为 JSON 格式,key: input-name;value: input-value
7
- * @param form {object} Form 节点对象
8
- */
9
- export const formJson = function (form) {
10
- let elems = form.elements;
11
- let value = {};
12
- for (let i = 0, len = elems.length; i < len; i++) {
13
- let item = elems[i];
14
- if (!isBlank(item.name)) {
15
- if ((item.tagName === "INPUT" || item.tagName === "TEXTAREA") &&
16
- !isBlank(item.value)) {
17
- let dataType = item.getAttribute("data-type");
18
- if (dataType === "number") {
19
- value[item.name] = Number(item.value);
20
- }
21
- else {
22
- value[item.name] = item.value;
23
- }
24
- }
25
- else if (item.tagName === "SELECT") {
26
- value[item.name] = item.options[item.selectedIndex].value;
27
- }
28
- }
29
- }
30
- return value;
31
- };
32
- /**
33
- * 获取 url query 参数 (get 请求的参数)
34
- * @param search 如果是 React 应用就需要传递 useLocation().search
35
- * @returns
36
- */
37
- export function query(search) {
38
- if (isBlank(search)) {
39
- search = location.search;
40
- }
41
- const searchParams = new URLSearchParams(search);
42
- let query = {};
43
- for (const [key, value] of searchParams) {
44
- let oldValue = query[key];
45
- let newValue = value;
46
- if (oldValue != null) {
47
- if (oldValue instanceof Array) {
48
- oldValue.push(value);
49
- newValue = oldValue;
50
- }
51
- else {
52
- newValue = [value, oldValue];
53
- }
54
- }
55
- query[key] = newValue;
56
- }
57
- return query;
58
- }
59
- /**
60
- * 函数节流 - 每隔单位时间,只执行一次
61
- * @param cb 待节流的函数
62
- * @param wait 间隔时间
63
- * @returns
64
- */
65
- export function throttle(fn, wait = 500) {
66
- // 上一次的请求时间
67
- let last = 0;
68
- return (...args) => {
69
- // 当前时间戳
70
- const now = Date.now();
71
- if (now - last > wait) {
72
- fn(...args);
73
- last = now;
74
- }
75
- };
76
- }
77
- /**
78
- * 函数防抖 - 当重复触发某一个行为(事件时),只执行最后一次触发
79
- * @param fn 防抖函数
80
- * @param interval 间隔时间段
81
- * @returns
82
- */
83
- export function debounce(fn, interval = 500) {
84
- let _t;
85
- const handle = (...args) => {
86
- if (_t)
87
- clearTimeout(_t);
88
- _t = setTimeout(() => {
89
- //@ts-ignore
90
- fn.apply(this, args);
91
- }, interval);
92
- };
93
- handle.cancel = function () {
94
- if (_t) {
95
- clearTimeout(_t);
96
- _t = null;
97
- }
98
- };
99
- return handle;
100
- }
package/lib/storage.d.ts DELETED
@@ -1,51 +0,0 @@
1
- /**
2
- * 缓存相关
3
- */
4
- type StorageType = "session" | "local";
5
- interface StorageSetOption {
6
- storage?: StorageType;
7
- /** 数据有效期, 单位秒, 默认: -1 - 永久存储 */
8
- expire?: number;
9
- }
10
- /**
11
- * 存储值到 Storage 中
12
- * @param key 设置的 key
13
- * @param value 设置的值
14
- * @param [option.storage] session 或 local, 默认: session
15
- * @param [option.expire] 数据有效期, 单位秒, 默认: -1 - 永久存储
16
- *
17
- * @example <caption>1. 存储到 SessionStorage</caption>
18
- * set("key", "value");
19
- *
20
- * @example <caption>2. 存储到 LocalStorage</caption>
21
- * set("key", "value", { storage: "local" });
22
- */
23
- export declare function set(key: string, value: any, option?: StorageSetOption): void;
24
- /**
25
- * 清空所有的缓存内容
26
- * @param storage 待清空的缓存对象
27
- */
28
- export declare function clear(storage?: StorageType): void;
29
- /**
30
- * 删除存储到 Storage 中的数据
31
- * @param key
32
- * @param storage
33
- */
34
- export declare function remove(key: string, storage?: StorageType): void;
35
- /** 从 Storage 中获取数据时的配置 */
36
- interface StorageQueryOption {
37
- /** 数据是否持久化, 默认为: false, 设置为 true 则会在每一次取出数据后删除 */
38
- delete?: boolean;
39
- /** 存储对象, session、local */
40
- storage?: StorageType;
41
- }
42
- /**
43
- * 从 Storage 中取出数据
44
- * @param key 保存时的 key
45
- * @param defaultValue 没有数据时的默认值
46
- * @param [option.delete] 是否在取出后,删除数据,默认:false - 取出后删除数据
47
- * @param [option.storage] 使用的 Storage ,可以是 localStorage、sessionStorage, 默认: localStorage、sessionStorage
48
- * @returns Storage 中 key 对应的数据
49
- */
50
- export declare function get<T>(key: string, defaultValue?: T, option?: StorageQueryOption): T;
51
- export {};
package/lib/storage.js DELETED
@@ -1,73 +0,0 @@
1
- function getStorage(storage = "session") {
2
- return storage === "session" ? sessionStorage : localStorage;
3
- }
4
- /**
5
- * 存储值到 Storage 中
6
- * @param key 设置的 key
7
- * @param value 设置的值
8
- * @param [option.storage] session 或 local, 默认: session
9
- * @param [option.expire] 数据有效期, 单位秒, 默认: -1 - 永久存储
10
- *
11
- * @example <caption>1. 存储到 SessionStorage</caption>
12
- * set("key", "value");
13
- *
14
- * @example <caption>2. 存储到 LocalStorage</caption>
15
- * set("key", "value", { storage: "local" });
16
- */
17
- export function set(key, value, option) {
18
- const opts = {
19
- expire: -1,
20
- storage: "session",
21
- ...option,
22
- };
23
- const saveData = JSON.stringify({
24
- value,
25
- time: Date.now(),
26
- expire: opts.expire === -1 ? -1 : Math.floor(Date.now() / 1000) + opts.expire,
27
- });
28
- getStorage(opts.storage).setItem(key, saveData);
29
- }
30
- /**
31
- * 清空所有的缓存内容
32
- * @param storage 待清空的缓存对象
33
- */
34
- export function clear(storage) {
35
- getStorage(storage).clear();
36
- }
37
- /**
38
- * 删除存储到 Storage 中的数据
39
- * @param key
40
- * @param storage
41
- */
42
- export function remove(key, storage) {
43
- getStorage(storage).removeItem(key);
44
- }
45
- /**
46
- * 从 Storage 中取出数据
47
- * @param key 保存时的 key
48
- * @param defaultValue 没有数据时的默认值
49
- * @param [option.delete] 是否在取出后,删除数据,默认:false - 取出后删除数据
50
- * @param [option.storage] 使用的 Storage ,可以是 localStorage、sessionStorage, 默认: localStorage、sessionStorage
51
- * @returns Storage 中 key 对应的数据
52
- */
53
- export function get(key, defaultValue, option) {
54
- const opts = (option || { delete: false });
55
- const storage = getStorage(opts.storage);
56
- let data = storage.getItem(key);
57
- if (data == null) {
58
- return defaultValue || null;
59
- }
60
- data = JSON.parse(data);
61
- let d = data.value;
62
- if (data.expire !== -1) {
63
- // 数据过期
64
- if (Math.floor(Date.now() / 1000) > data.expire) {
65
- d = null;
66
- storage.removeItem(key);
67
- }
68
- }
69
- if (opts.delete) {
70
- storage.removeItem(key);
71
- }
72
- return d || defaultValue;
73
- }
package/lib/theme.d.ts DELETED
@@ -1,44 +0,0 @@
1
- /** 获取当前系统的主题 */
2
- export declare function getSystemTheme(): "light" | "dark" | "auto";
3
- /**
4
- * 初始化主题, 让网页能够适应系统主题, 同时根据缓存的主题切换主题
5
- * @returns 当前应用的主题
6
- */
7
- export declare function initTheme(): Promise<"light" | "dark" | "auto">;
8
- /**
9
- * 切换主题, 通常用于预览
10
- * @param theme 切换的主题
11
- * @param transition 是否使用过渡动画, 注意浏览器必须支持 document.startViewTransition, 默认: true
12
- * @returns 切换后的主题
13
- */
14
- export declare function toggleTheme(theme?: "light" | "dark" | "auto", transition?: boolean): Promise<"light" | "dark" | "auto">;
15
- /** 获取当前主题 */
16
- export declare function getTheme(): string;
17
- /**
18
- * 应用主题
19
- * @param theme 待应用的主题
20
- * @param cache 是否缓存应用的主题, 让应用下一次启动的时候, 可以应用主题, 默认: true
21
- * @param transition 是否使用过渡动画, 注意浏览器必须支持 document.startViewTransition, 默认: true
22
- * @returns 应用的主题
23
- */
24
- export declare function applyTheme(theme?: "light" | "dark" | "auto", cache?: boolean, transition?: boolean): Promise<"light" | "dark" | "auto">;
25
- /** 获取当前主题色 */
26
- export declare function getColorTheme(defaultValue?: string): string | undefined;
27
- /**
28
- * 初始化主题色, 让网页能够适应系统主题色, 同时根据缓存的主题色切换主题色
29
- * @returns 当前应用的主题色
30
- */
31
- export declare function initColorTheme(): Promise<string> | null;
32
- /**
33
- * 切换主题色, 通常用于预览
34
- * @param color 待切换的主题色
35
- * @returns 切换后的主题色
36
- */
37
- export declare function toggleColorTheme(color: string): Promise<string>;
38
- /**
39
- * 应用主题色
40
- * @param color 主题色
41
- * @param cache 是否缓存主题色, 让应用下一次启动的时候, 可以应用主题色, 默认: true
42
- * @returns 切换后的主题色
43
- */
44
- export declare function applyColorTheme(color: string, cache?: boolean): Promise<string>;
package/lib/theme.js DELETED
@@ -1,156 +0,0 @@
1
- import { adjust } from "./color.js";
2
- /** 获取当前系统的主题 */
3
- export function getSystemTheme() {
4
- if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
5
- return "dark";
6
- }
7
- else if (window.matchMedia("(prefers-color-scheme: light)").matches) {
8
- return "light";
9
- }
10
- return "auto";
11
- }
12
- /**
13
- * 初始化主题, 让网页能够适应系统主题, 同时根据缓存的主题切换主题
14
- * @returns 当前应用的主题
15
- */
16
- export async function initTheme() {
17
- // 让网页能够适应系统主题
18
- let $themeStyle = document.getElementById("theme-style");
19
- if ($themeStyle == null) {
20
- $themeStyle = document.createElement("style");
21
- $themeStyle.id = "theme-style";
22
- $themeStyle.innerHTML =
23
- ":root{color-scheme:light dark;}html.light{color-scheme: light;}html.dark {color-scheme: dark;}";
24
- document.head.appendChild($themeStyle);
25
- }
26
- // 获取已经应用的主题设置
27
- const cacheTheme = localStorage.getItem("web-theme-appearance");
28
- return toggleTheme(cacheTheme);
29
- }
30
- /**
31
- * 切换主题, 通常用于预览
32
- * @param theme 切换的主题
33
- * @param transition 是否使用过渡动画, 注意浏览器必须支持 document.startViewTransition, 默认: true
34
- * @returns 切换后的主题
35
- */
36
- export async function toggleTheme(theme, transition = true) {
37
- return new Promise((resolve) => {
38
- const classList = document.documentElement.classList;
39
- if (theme == null) {
40
- theme = getSystemTheme();
41
- }
42
- function updateThemeClass() {
43
- if (theme === "light") {
44
- classList.add("light");
45
- classList.remove("dark");
46
- }
47
- else if (theme === "dark") {
48
- classList.add("dark");
49
- classList.remove("light");
50
- }
51
- else {
52
- classList.remove("light", "dark");
53
- }
54
- }
55
- // @ts-ignore
56
- if (transition && document.startViewTransition) {
57
- // @ts-ignore
58
- document.startViewTransition(() => {
59
- updateThemeClass();
60
- resolve(theme);
61
- });
62
- }
63
- else {
64
- updateThemeClass();
65
- resolve(theme);
66
- }
67
- });
68
- }
69
- /** 获取当前主题 */
70
- export function getTheme() {
71
- // 1. 从根节点获取
72
- let theme = document.documentElement.className.match(/light|dark/);
73
- if (theme != null) {
74
- theme = theme[0];
75
- }
76
- if (theme == null) {
77
- theme = localStorage.getItem("web-theme-appearance");
78
- }
79
- if (theme == null) {
80
- theme = getSystemTheme();
81
- }
82
- return theme;
83
- }
84
- /**
85
- * 应用主题
86
- * @param theme 待应用的主题
87
- * @param cache 是否缓存应用的主题, 让应用下一次启动的时候, 可以应用主题, 默认: true
88
- * @param transition 是否使用过渡动画, 注意浏览器必须支持 document.startViewTransition, 默认: true
89
- * @returns 应用的主题
90
- */
91
- export async function applyTheme(theme, cache = true, transition = true) {
92
- if (cache === true) {
93
- localStorage.setItem("web-theme-appearance", theme == null ? "auto" : theme);
94
- }
95
- return toggleTheme(theme, transition);
96
- }
97
- /** 获取当前主题色 */
98
- export function getColorTheme(defaultValue) {
99
- const root = document.documentElement;
100
- const match = root.className.match(/color-([0-9a-fA-F]{6})/);
101
- if (match == null) {
102
- // 获取 --nt-primary-color 的值
103
- let color = getComputedStyle(root).getPropertyValue("--l-primary-color");
104
- if (color === "") {
105
- color = localStorage.getItem("web-theme-color");
106
- }
107
- return color ? color : defaultValue;
108
- }
109
- return `#${match[1]}`;
110
- }
111
- /**
112
- * 初始化主题色, 让网页能够适应系统主题色, 同时根据缓存的主题色切换主题色
113
- * @returns 当前应用的主题色
114
- */
115
- export function initColorTheme() {
116
- // 获取缓存主题色
117
- const color = localStorage.getItem("web-theme-color");
118
- if (color != null) {
119
- return toggleColorTheme(color);
120
- }
121
- return color;
122
- }
123
- /**
124
- * 切换主题色, 通常用于预览
125
- * @param color 待切换的主题色
126
- * @returns 切换后的主题色
127
- */
128
- export async function toggleColorTheme(color) {
129
- const vars = [
130
- `--l-primary-color: ${color};`,
131
- `--l-primary-color-dark1: ${adjust(color, 1, false)};`,
132
- ];
133
- for (let i = 1; i <= 5; i++) {
134
- vars.push(`--l-primary-color-light${i}: ${adjust(color, i)};`);
135
- }
136
- let $style = document.getElementById("color-theme-style");
137
- if ($style == null) {
138
- $style = document.createElement("style");
139
- $style.id = "color-theme-style";
140
- document.head.appendChild($style);
141
- }
142
- $style.innerHTML = `:root{${vars.join("")}}`;
143
- return color;
144
- }
145
- /**
146
- * 应用主题色
147
- * @param color 主题色
148
- * @param cache 是否缓存主题色, 让应用下一次启动的时候, 可以应用主题色, 默认: true
149
- * @returns 切换后的主题色
150
- */
151
- export function applyColorTheme(color, cache = true) {
152
- if (cache === true) {
153
- localStorage.setItem("web-theme-color", color);
154
- }
155
- return toggleColorTheme(color);
156
- }