ph-utils 0.10.0 → 0.10.2

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,7 +1,7 @@
1
- ## ph-utils
2
-
3
- 整理了 js 前后端开发(web + nodejs)时常用的一些工具;[详细文档](https://gitee.com/towardly/ph/wikis/Home?sort_id=4035190)
4
-
5
- ### 包含如下工具文件
6
-
7
- `index` 基础工具类、`date` 跟日期相关的工具类、`file` 文件操作相关工具类[**服务端**]、`server` 服务端工具类、`validator` 数据验证、`dom` 浏览器节点操作相关[**前端**]、`web` 一些只适用于前端相关的工具、`color` 颜色相关工具
1
+ ## ph-utils
2
+
3
+ 整理了 js 前后端开发(web + nodejs)时常用的一些工具;[详细文档](https://gitee.com/towardly/ph/wikis/Home?sort_id=4035190)
4
+
5
+ ### 包含如下工具文件
6
+
7
+ `index` 基础工具类、`date` 跟日期相关的工具类、`file` 文件操作相关工具类[**服务端**]、`server` 服务端工具类、`validator` 数据验证、`dom` 浏览器节点操作相关[**前端**]、`web` 一些只适用于前端相关的工具、`color` 颜色相关工具
package/lib/array.d.ts CHANGED
@@ -59,14 +59,14 @@ export declare function symmetricDifference<T>(...arrs: T[][]): T[];
59
59
  * @param a2
60
60
  * @returns
61
61
  */
62
- export declare function isSubsetOf<T>(a1: T[] | Set<T>, a2: T[] | Set<T>): any;
62
+ export declare function isSubsetOf<T>(a1: T[] | Set<T>, a2: T[] | Set<T>): boolean;
63
63
  /**
64
64
  * 返回一个布尔值,指示给定集合中的所有元素是否都在此集合中。
65
65
  * @param arr1
66
66
  * @param arr2
67
67
  * @returns
68
68
  */
69
- export declare function isSupersetOf<T>(arr1: T[] | Set<T>, arr2: T[] | Set<T>): any;
69
+ export declare function isSupersetOf<T>(arr1: T[] | Set<T>, arr2: T[] | Set<T>): boolean;
70
70
  /**
71
71
  * 返回一个布尔值,指示此集合是否与给定集合没有公共元素。
72
72
  *
@@ -76,4 +76,4 @@ export declare function isSupersetOf<T>(arr1: T[] | Set<T>, arr2: T[] | Set<T>):
76
76
  * @param arr2
77
77
  * @returns
78
78
  */
79
- export declare function isDisjointFrom<T>(arr1: T[] | Set<T>, arr2: T[] | Set<T>): any;
79
+ export declare function isDisjointFrom<T>(arr1: T[] | Set<T>, arr2: T[] | Set<T>): boolean;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 复制数据, 可以从多种类型的数据
3
+ * 1. 直接复制文本: await copy("待复制的文本")
4
+ * 2. 复制节点上的 data-copy-text:
5
+ * <button data-copy-text="这是待复制的文本">复制</button>
6
+ * await copy(e.target) // or await copy("#a") or await copy(document.querySelector('#a'))
7
+ * 3. 直接复制节点本身数据: await copy('#a')
8
+ * @param {string | HTMLElement} source 复制源, 从中解析待复制的数据
9
+ * @returns {Promise<boolean>} 是否复制成功
10
+ */
11
+ export declare function copy(source: string | HTMLElement): Promise<boolean>;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * 创建一个临时节点缓存待复制数据
3
+ * @param {String} value - 待复制文本
4
+ * @return {HTMLElement}
5
+ */
6
+ function createFakeElement(value) {
7
+ const fakeElement = document.createElement("textarea");
8
+ fakeElement.style.border = "0";
9
+ fakeElement.style.padding = "0";
10
+ fakeElement.style.margin = "0";
11
+ fakeElement.style.position = "absolute";
12
+ fakeElement.style.left = "-9999px";
13
+ fakeElement.style.top = "-9999";
14
+ fakeElement.setAttribute("readonly", "");
15
+ fakeElement.value = value;
16
+ return fakeElement;
17
+ }
18
+ /** 通过执行 execCommand 来执行复制 */
19
+ function copyFromCommand(text) {
20
+ // 添加节点
21
+ const fakeEl = createFakeElement(text);
22
+ document.body.append(fakeEl);
23
+ fakeEl.focus();
24
+ fakeEl.select();
25
+ // 执行复制
26
+ const res = document.execCommand("copy");
27
+ fakeEl.remove(); // 删除节点
28
+ return Promise.resolve(res);
29
+ }
30
+ /** 使用 navigator.clipboard 复制 */
31
+ function copyFromClipboard(text) {
32
+ const theClipboard = navigator.clipboard;
33
+ if (theClipboard != null) {
34
+ return theClipboard
35
+ .writeText(text)
36
+ .then(() => {
37
+ Promise.resolve(true);
38
+ })
39
+ .catch(() => Promise.resolve(false));
40
+ }
41
+ return Promise.resolve(false);
42
+ }
43
+ /** 解析待复制的文本 */
44
+ function parseCopyText(source) {
45
+ let copyText = null; // 待复制文本
46
+ let sourceEl = null;
47
+ // 获取待复制数据
48
+ if (typeof source === "string") {
49
+ // 从节点拿数据
50
+ if (source.startsWith("#") || source.startsWith(".")) {
51
+ sourceEl = document.querySelector(source);
52
+ if (sourceEl == null) {
53
+ copyText = source;
54
+ }
55
+ }
56
+ else {
57
+ copyText = source;
58
+ }
59
+ }
60
+ if (source instanceof HTMLElement) {
61
+ sourceEl = source;
62
+ }
63
+ // 从节点获取待复制数据
64
+ if (sourceEl != null) {
65
+ if (sourceEl.hasAttribute("data-copy-text")) {
66
+ copyText = sourceEl.getAttribute("data-copy-text");
67
+ }
68
+ else {
69
+ const tagName = sourceEl.tagName;
70
+ if (tagName === "INPUT" || tagName === "TEXTAREA") {
71
+ copyText = sourceEl.value;
72
+ }
73
+ else {
74
+ copyText = sourceEl.textContent;
75
+ }
76
+ }
77
+ }
78
+ return copyText;
79
+ }
80
+ /**
81
+ * 复制数据, 可以从多种类型的数据
82
+ * 1. 直接复制文本: await copy("待复制的文本")
83
+ * 2. 复制节点上的 data-copy-text:
84
+ * <button data-copy-text="这是待复制的文本">复制</button>
85
+ * await copy(e.target) // or await copy("#a") or await copy(document.querySelector('#a'))
86
+ * 3. 直接复制节点本身数据: await copy('#a')
87
+ * @param {string | HTMLElement} source 复制源, 从中解析待复制的数据
88
+ * @returns {Promise<boolean>} 是否复制成功
89
+ */
90
+ export async function copy(source) {
91
+ // 待复制文本
92
+ const copyText = parseCopyText(source);
93
+ if (copyText == null) {
94
+ return Promise.resolve(false);
95
+ }
96
+ const v = await copyFromClipboard(copyText);
97
+ if (v === false) {
98
+ return copyFromCommand(copyText);
99
+ }
100
+ return Promise.resolve(true);
101
+ }
package/lib/dom.d.ts CHANGED
@@ -2,21 +2,21 @@
2
2
  * 根据选择器获取节点
3
3
  * @param {string} selector 选择器
4
4
  */
5
- export declare function elem(selector: string | HTMLElement, dom?: HTMLElement): NodeListOf<HTMLElement> | HTMLElement[];
5
+ export declare function elem(selector: string | HTMLElement, dom?: HTMLElement | ShadowRoot | Document): NodeListOf<HTMLElement> | HTMLElement[];
6
6
  /**
7
7
  * 根据选择器获取 DOM 元素。
8
8
  * @param selector - 选择器字符串或 HTMLElement 实例。
9
9
  * @param dom - 可选参数,指定在哪个 DOM 节点下查找元素,默认为 document。
10
10
  * @returns 返回匹配到的 HTMLElement 实例。
11
11
  */
12
- export declare function $(selector: string | HTMLElement, dom?: HTMLElement): NodeListOf<HTMLElement> | HTMLElement[];
12
+ export declare function $(selector: string | HTMLElement, dom?: HTMLElement | ShadowRoot | Document): NodeListOf<HTMLElement> | HTMLElement[];
13
13
  /**
14
14
  * 根据选择器获取匹配的第一个 DOM 元素。
15
15
  * @param selector - 选择器字符串或直接的 HTMLElement。
16
16
  * @param dom - 可选的父级 DOM 元素,默认为当前文档。
17
17
  * @returns 返回匹配的第一个 HTMLElement,如果没有找到则返回 undefined。
18
18
  */
19
- export declare function $one(selector: string | HTMLElement, dom?: HTMLElement): HTMLElement;
19
+ export declare function $one(selector: string | HTMLElement, dom?: HTMLElement | ShadowRoot | Document): HTMLElement;
20
20
  /**
21
21
  * 为节点添加 class
22
22
  * @param {HTMLElement} elem 待添加 class 的节点
@@ -152,10 +152,11 @@ export declare function isMobile(): boolean;
152
152
  */
153
153
  export declare function formatClass(classObj: (boolean | string | undefined | null)[] | Record<string, boolean | string | undefined | null>): string;
154
154
  /**
155
- * 在下一个动画帧执行回调函数。
156
- * @param cb - 要在下一个动画帧执行的回调函数。
155
+ * 将样式对象格式化为 CSS 样式字符串。
156
+ * @param styleObj - 样式对象,可以是字符串数组或键值对对象。
157
+ * @returns 格式化后的 CSS 样式字符串。
157
158
  */
158
- export declare function nextTick(cb: () => void): void;
159
+ export declare function formatStyle(styleObj: (string | undefined | null | "")[] | Record<string, string>): string;
159
160
  /**
160
161
  * 对指定的 HTML 元素应用显示过渡效果。
161
162
  * @param target - 要应用过渡效果的 HTML 元素。
@@ -179,9 +180,3 @@ export declare function startTransition(target: HTMLElement, properties: [string
179
180
  * @param finish - 过渡结束后可选的回调函数。
180
181
  */
181
182
  export declare function endTransition(target: HTMLElement, properties: [string, string][], finish?: () => void): void;
182
- /**
183
- * 隐藏 Transition 组件
184
- * @param el Transition 组件或者选择器, 不传则为: l-transition
185
- * @param remove 是否在隐藏后移除元素, 对应 vue-vIf
186
- */
187
- export declare function hideTransition(el?: string | HTMLElement, remove?: boolean): void;
package/lib/dom.js CHANGED
@@ -317,13 +317,28 @@ export function formatClass(classObj) {
317
317
  return classes.trim();
318
318
  }
319
319
  /**
320
- * 在下一个动画帧执行回调函数。
321
- * @param cb - 要在下一个动画帧执行的回调函数。
320
+ * 将样式对象格式化为 CSS 样式字符串。
321
+ * @param styleObj - 样式对象,可以是字符串数组或键值对对象。
322
+ * @returns 格式化后的 CSS 样式字符串。
322
323
  */
323
- export function nextTick(cb) {
324
- requestAnimationFrame(() => {
325
- cb();
326
- });
324
+ export function formatStyle(styleObj) {
325
+ let styleStr = "";
326
+ if (Array.isArray(styleObj)) {
327
+ for (let i = 0, len = styleObj.length; i < len; i++) {
328
+ const item = styleObj[i];
329
+ if (item) {
330
+ styleStr += `${item};`;
331
+ }
332
+ }
333
+ }
334
+ else {
335
+ for (const key in styleObj) {
336
+ if (styleObj[key]) {
337
+ styleStr += `${key}:${styleObj[key]};`;
338
+ }
339
+ }
340
+ }
341
+ return styleStr;
327
342
  }
328
343
  /**
329
344
  * 对指定的 HTML 元素应用显示过渡效果。
@@ -351,9 +366,9 @@ export function startTransition(target, properties, duration) {
351
366
  if (duration) {
352
367
  target.style.setProperty("transition", trans.join(", "));
353
368
  }
354
- nextTick(() => {
369
+ queueMicrotask(() => {
355
370
  target.style.removeProperty("display");
356
- nextTick(() => {
371
+ queueMicrotask(() => {
357
372
  for (let i = 0, len = properties.length; i < len; i++) {
358
373
  const rec = properties[i];
359
374
  target.style.removeProperty(rec[0]);
@@ -383,21 +398,3 @@ export function endTransition(target, properties, finish) {
383
398
  }
384
399
  }, { once: true });
385
400
  }
386
- /**
387
- * 隐藏 Transition 组件
388
- * @param el Transition 组件或者选择器, 不传则为: l-transition
389
- * @param remove 是否在隐藏后移除元素, 对应 vue-vIf
390
- */
391
- export function hideTransition(el, remove = false) {
392
- el = el || "l-transition";
393
- let $el = el;
394
- if (typeof el === "string") {
395
- $el = document.querySelector(el);
396
- }
397
- if ($el) {
398
- $el.hide(() => {
399
- if (remove)
400
- $el.remove();
401
- });
402
- }
403
- }
package/lib/server.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import type { SpawnOptions } from "node:child_process";
3
2
  /**
4
3
  * 执行命令
package/lib/theme.js CHANGED
@@ -19,10 +19,10 @@ export async function initTheme() {
19
19
  if ($themeStyle == null) {
20
20
  $themeStyle = document.createElement("style");
21
21
  $themeStyle.id = "theme-style";
22
- $themeStyle.innerHTML = `
23
- :root{color-scheme:light dark;}
24
- html.light{color-scheme: light;}
25
- html.dark {color-scheme: dark;}
22
+ $themeStyle.innerHTML = `
23
+ :root{color-scheme:light dark;}
24
+ html.light{color-scheme: light;}
25
+ html.dark {color-scheme: dark;}
26
26
  `;
27
27
  document.head.appendChild($themeStyle);
28
28
  }
@@ -45,19 +45,17 @@ declare class Validator {
45
45
  /**
46
46
  * 进行数据验证
47
47
  * @param data 待验证的数据
48
+ * @param all 是否全部验证, false - 只要验证错误一个则停止验证
48
49
  * @returns
49
50
  */
50
- validate(data: any): Promise<boolean>;
51
+ validate(data: any, all?: boolean): Promise<boolean>;
51
52
  /**
52
53
  * 只验证指定 key 的数据格式
53
54
  * @param key 指定待验证的 key
54
55
  * @param value 待验证的数据
55
56
  * @param data 原始数据,当验证确认密码时需要使用
56
57
  */
57
- validateKey(key: string, value: any, data?: any): Promise<{
58
- key: string;
59
- value: any;
60
- }>;
58
+ validateKey(key: string, value: any, data?: any): Promise<boolean>;
61
59
  private _validateRule;
62
60
  private _parseStringRule;
63
61
  }
package/lib/validator.js CHANGED
@@ -32,10 +32,11 @@ const ruleFns = {
32
32
  },
33
33
  };
34
34
  class ValidateError extends Error {
35
- constructor(key, msg) {
36
- super(msg);
35
+ constructor(errors) {
36
+ super(errors[0].message);
37
37
  this.name = "ValidateError";
38
- this.key = key;
38
+ this.key = errors[0].key;
39
+ this.errors = errors;
39
40
  }
40
41
  }
41
42
  /**
@@ -109,28 +110,31 @@ class Validator {
109
110
  /**
110
111
  * 进行数据验证
111
112
  * @param data 待验证的数据
113
+ * @param all 是否全部验证, false - 只要验证错误一个则停止验证
112
114
  * @returns
113
115
  */
114
- async validate(data) {
115
- let errMsg = "";
116
- let errKey = "";
117
- for (let key in this.rules) {
118
- // eslint-disable-next-line no-prototype-builtins
119
- if (this.rules.hasOwnProperty(key)) {
120
- errMsg = this._validateRule(this.rules[key], data[key], data);
121
- if (errMsg !== "") {
122
- errKey = key;
123
- errMsg = errMsg.replace("%s", key);
124
- break;
116
+ async validate(data, all = false) {
117
+ return new Promise((resolve, reject) => {
118
+ const errors = [];
119
+ for (let key in this.rules) {
120
+ // eslint-disable-next-line no-prototype-builtins
121
+ if (this.rules.hasOwnProperty(key)) {
122
+ let errMsg = this._validateRule(this.rules[key], data[key], data);
123
+ if (errMsg !== "") {
124
+ errMsg = errMsg.replace("%s", key);
125
+ errors.push({ message: errMsg, key });
126
+ if (all)
127
+ break;
128
+ }
125
129
  }
126
130
  }
127
- }
128
- if (errMsg === "") {
129
- return true;
130
- }
131
- else {
132
- throw new ValidateError(errKey, errMsg);
133
- }
131
+ if (errors.length === 0) {
132
+ resolve(true);
133
+ }
134
+ else {
135
+ reject(new ValidateError(errors));
136
+ }
137
+ });
134
138
  }
135
139
  /**
136
140
  * 只验证指定 key 的数据格式
@@ -139,15 +143,17 @@ class Validator {
139
143
  * @param data 原始数据,当验证确认密码时需要使用
140
144
  */
141
145
  async validateKey(key, value, data) {
142
- let keyRules = this.rules[key];
143
- let errMsg = this._validateRule(keyRules, value, data);
144
- if (errMsg !== "") {
145
- errMsg = errMsg.replace("%s", key);
146
- throw new ValidateError(key, errMsg);
147
- }
148
- else {
149
- return { key, value };
150
- }
146
+ return new Promise((resolve, reject) => {
147
+ let keyRules = this.rules[key];
148
+ let errMsg = this._validateRule(keyRules, value, data);
149
+ if (errMsg !== "") {
150
+ errMsg = errMsg.replace("%s", key);
151
+ reject(new ValidateError([{ key, message: errMsg }]));
152
+ }
153
+ else {
154
+ resolve(true);
155
+ }
156
+ });
151
157
  }
152
158
  _validateRule(rules, value, data) {
153
159
  let errMsg = "";
package/package.json CHANGED
@@ -68,7 +68,7 @@
68
68
  },
69
69
  "./*": "./lib/*"
70
70
  },
71
- "version": "0.10.0",
71
+ "version": "0.10.2",
72
72
  "type": "module",
73
73
  "repository": {
74
74
  "type": "git",