ph-utils 0.10.1 → 0.11.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/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 的节点
@@ -156,12 +156,7 @@ export declare function formatClass(classObj: (boolean | string | undefined | nu
156
156
  * @param styleObj - 样式对象,可以是字符串数组或键值对对象。
157
157
  * @returns 格式化后的 CSS 样式字符串。
158
158
  */
159
- export declare function formatStyle(styleObj: (string | undefined | null | "")[] | Record<string, string>): string;
160
- /**
161
- * 在下一个动画帧执行回调函数。
162
- * @param cb - 要在下一个动画帧执行的回调函数。
163
- */
164
- export declare function nextTick(cb: () => void): void;
159
+ export declare function formatStyle(styleObj: (string | undefined | null | "")[] | Record<string, string | undefined | null>): string;
165
160
  /**
166
161
  * 对指定的 HTML 元素应用显示过渡效果。
167
162
  * @param target - 要应用过渡效果的 HTML 元素。
@@ -185,9 +180,3 @@ export declare function startTransition(target: HTMLElement, properties: [string
185
180
  * @param finish - 过渡结束后可选的回调函数。
186
181
  */
187
182
  export declare function endTransition(target: HTMLElement, properties: [string, string][], finish?: () => void): void;
188
- /**
189
- * 隐藏 Transition 组件
190
- * @param el Transition 组件或者选择器, 不传则为: l-transition
191
- * @param remove 是否在隐藏后移除元素, 对应 vue-vIf
192
- */
193
- export declare function hideTransition(el?: string | HTMLElement, remove?: boolean): void;
package/lib/dom.js CHANGED
@@ -333,22 +333,14 @@ export function formatStyle(styleObj) {
333
333
  }
334
334
  else {
335
335
  for (const key in styleObj) {
336
- if (styleObj[key]) {
337
- styleStr += `${key}:${styleObj[key]};`;
336
+ const value = styleObj[key];
337
+ if (value) {
338
+ styleStr += `${key}:${value};`;
338
339
  }
339
340
  }
340
341
  }
341
342
  return styleStr;
342
343
  }
343
- /**
344
- * 在下一个动画帧执行回调函数。
345
- * @param cb - 要在下一个动画帧执行的回调函数。
346
- */
347
- export function nextTick(cb) {
348
- requestAnimationFrame(() => {
349
- cb();
350
- });
351
- }
352
344
  /**
353
345
  * 对指定的 HTML 元素应用显示过渡效果。
354
346
  * @param target - 要应用过渡效果的 HTML 元素。
@@ -375,9 +367,9 @@ export function startTransition(target, properties, duration) {
375
367
  if (duration) {
376
368
  target.style.setProperty("transition", trans.join(", "));
377
369
  }
378
- nextTick(() => {
370
+ queueMicrotask(() => {
379
371
  target.style.removeProperty("display");
380
- nextTick(() => {
372
+ queueMicrotask(() => {
381
373
  for (let i = 0, len = properties.length; i < len; i++) {
382
374
  const rec = properties[i];
383
375
  target.style.removeProperty(rec[0]);
@@ -407,21 +399,3 @@ export function endTransition(target, properties, finish) {
407
399
  }
408
400
  }, { once: true });
409
401
  }
410
- /**
411
- * 隐藏 Transition 组件
412
- * @param el Transition 组件或者选择器, 不传则为: l-transition
413
- * @param remove 是否在隐藏后移除元素, 对应 vue-vIf
414
- */
415
- export function hideTransition(el, remove = false) {
416
- el = el || "l-transition";
417
- let $el = el;
418
- if (typeof el === "string") {
419
- $el = document.querySelector(el);
420
- }
421
- if ($el) {
422
- $el.hide(() => {
423
- if (remove)
424
- $el.remove();
425
- });
426
- }
427
- }
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
  }
@@ -13,7 +13,6 @@ export type RuleType = string | RegExp | ((v: any) => boolean) | (RegExp | strin
13
13
  export interface SchemaType {
14
14
  key: string;
15
15
  required?: boolean;
16
- type?: string | ((v: any) => void);
17
16
  rules?: RuleType[];
18
17
  message?: string;
19
18
  }
@@ -42,23 +41,24 @@ declare class Validator {
42
41
  * validator.validateKey().then(res => {})
43
42
  */
44
43
  constructor(schemas: SchemaType[]);
44
+ addSchemas(schemas: SchemaType[]): void;
45
+ addSchema(schema: SchemaType): void;
45
46
  /**
46
47
  * 进行数据验证
47
48
  * @param data 待验证的数据
49
+ * @param all 是否全部验证, false - 只要验证错误一个则停止验证
48
50
  * @returns
49
51
  */
50
- validate(data: any): Promise<boolean>;
52
+ validate(data: any, all?: boolean): Promise<boolean>;
51
53
  /**
52
54
  * 只验证指定 key 的数据格式
53
55
  * @param key 指定待验证的 key
54
56
  * @param value 待验证的数据
55
57
  * @param data 原始数据,当验证确认密码时需要使用
56
58
  */
57
- validateKey(key: string, value: any, data?: any): Promise<{
58
- key: string;
59
- value: any;
60
- }>;
59
+ validateKey(key: string, value: any, data?: any): Promise<boolean>;
61
60
  private _validateRule;
61
+ private _parseSchemaRules;
62
62
  private _parseStringRule;
63
63
  }
64
64
  export default Validator;
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
  /**
@@ -60,77 +61,45 @@ class Validator {
60
61
  * validator.validateKey().then(res => {})
61
62
  */
62
63
  constructor(schemas) {
63
- let parsedRules = {};
64
+ this.rules = {};
65
+ this.addSchemas(schemas);
66
+ }
67
+ addSchemas(schemas) {
64
68
  for (let schema of schemas) {
65
- // 解析规则
66
- let rules = [];
67
- let rule = schema.rules;
68
- if (rule != null) {
69
- if (typeof rule === "string") {
70
- rules = rules.concat(this._parseStringRule(rule, schema.message));
71
- }
72
- else if (rule instanceof Array) {
73
- for (let ruleItem of rule) {
74
- if (typeof ruleItem === "string") {
75
- rules.push(...this._parseStringRule(ruleItem, schema.message));
76
- }
77
- else if (ruleItem instanceof RegExp ||
78
- typeof ruleItem === "function") {
79
- rules.push({
80
- rule: ruleItem,
81
- message: schema.message || defaultMsg,
82
- });
83
- }
84
- else {
85
- if (typeof ruleItem.rule === "string") {
86
- rules.push(...this._parseStringRule(ruleItem.rule, ruleItem.message));
87
- }
88
- else {
89
- rules.push({
90
- rule: ruleItem.rule,
91
- message: ruleItem.message || defaultMsg,
92
- });
93
- }
94
- }
95
- }
96
- }
97
- else {
98
- rules.push({ rule, message: defaultMsg });
99
- }
100
- }
101
- if (schema.required === true &&
102
- (rules == null || rules.findIndex((r) => r.rule === "required") === -1)) {
103
- rules.push(...this._parseStringRule("required", schema.message));
104
- }
105
- parsedRules[schema.key] = rules;
69
+ this.rules[schema.key] = this._parseSchemaRules(schema);
106
70
  }
107
- this.rules = parsedRules;
71
+ }
72
+ addSchema(schema) {
73
+ this.rules[schema.key] = this._parseSchemaRules(schema);
108
74
  }
109
75
  /**
110
76
  * 进行数据验证
111
77
  * @param data 待验证的数据
78
+ * @param all 是否全部验证, false - 只要验证错误一个则停止验证
112
79
  * @returns
113
80
  */
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;
81
+ async validate(data, all = false) {
82
+ return new Promise((resolve, reject) => {
83
+ const errors = [];
84
+ for (let key in this.rules) {
85
+ // eslint-disable-next-line no-prototype-builtins
86
+ if (this.rules.hasOwnProperty(key)) {
87
+ let errMsg = this._validateRule(this.rules[key], data[key], data);
88
+ if (errMsg !== "") {
89
+ errMsg = errMsg.replace("%s", key);
90
+ errors.push({ message: errMsg, key });
91
+ if (all)
92
+ break;
93
+ }
125
94
  }
126
95
  }
127
- }
128
- if (errMsg === "") {
129
- return true;
130
- }
131
- else {
132
- throw new ValidateError(errKey, errMsg);
133
- }
96
+ if (errors.length === 0) {
97
+ resolve(true);
98
+ }
99
+ else {
100
+ reject(new ValidateError(errors));
101
+ }
102
+ });
134
103
  }
135
104
  /**
136
105
  * 只验证指定 key 的数据格式
@@ -139,15 +108,17 @@ class Validator {
139
108
  * @param data 原始数据,当验证确认密码时需要使用
140
109
  */
141
110
  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
- }
111
+ return new Promise((resolve, reject) => {
112
+ let keyRules = this.rules[key];
113
+ let errMsg = this._validateRule(keyRules, value, data);
114
+ if (errMsg !== "") {
115
+ errMsg = errMsg.replace("%s", key);
116
+ reject(new ValidateError([{ key, message: errMsg }]));
117
+ }
118
+ else {
119
+ resolve(true);
120
+ }
121
+ });
151
122
  }
152
123
  _validateRule(rules, value, data) {
153
124
  let errMsg = "";
@@ -186,6 +157,49 @@ class Validator {
186
157
  }
187
158
  return errMsg;
188
159
  }
160
+ _parseSchemaRules(schema) {
161
+ // 解析规则
162
+ let rules = [];
163
+ let rule = schema.rules;
164
+ if (rule != null) {
165
+ if (typeof rule === "string") {
166
+ rules = rules.concat(this._parseStringRule(rule, schema.message));
167
+ }
168
+ else if (rule instanceof Array) {
169
+ for (let ruleItem of rule) {
170
+ if (typeof ruleItem === "string") {
171
+ rules.push(...this._parseStringRule(ruleItem, schema.message));
172
+ }
173
+ else if (ruleItem instanceof RegExp ||
174
+ typeof ruleItem === "function") {
175
+ rules.push({
176
+ rule: ruleItem,
177
+ message: schema.message || defaultMsg,
178
+ });
179
+ }
180
+ else {
181
+ if (typeof ruleItem.rule === "string") {
182
+ rules.push(...this._parseStringRule(ruleItem.rule, ruleItem.message));
183
+ }
184
+ else {
185
+ rules.push({
186
+ rule: ruleItem.rule,
187
+ message: ruleItem.message || defaultMsg,
188
+ });
189
+ }
190
+ }
191
+ }
192
+ }
193
+ else {
194
+ rules.push({ rule, message: defaultMsg });
195
+ }
196
+ }
197
+ if (schema.required === true &&
198
+ (rules == null || rules.findIndex((r) => r.rule === "required") === -1)) {
199
+ rules.push(...this._parseStringRule("required", schema.message));
200
+ }
201
+ return rules;
202
+ }
189
203
  _parseStringRule(rule, ruleErrMsg) {
190
204
  let rules = [];
191
205
  let trule = rule.split("|");
package/package.json CHANGED
@@ -68,7 +68,7 @@
68
68
  },
69
69
  "./*": "./lib/*"
70
70
  },
71
- "version": "0.10.1",
71
+ "version": "0.11.0",
72
72
  "type": "module",
73
73
  "repository": {
74
74
  "type": "git",