ziya-utils 1.1.4 → 1.1.6

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.
@@ -0,0 +1,368 @@
1
+ 'use strict';
2
+
3
+ var tslib_es6 = require('../node_modules/tslib/tslib.es6.js');
4
+
5
+ /**
6
+ * 开发浏览器脚本DOM构建器
7
+ */
8
+ class ScriptDomBuilder {
9
+ constructor(parentNode = document.body, containerId = "glk-script-container") {
10
+ this.container = null;
11
+ this.elements = new Map();
12
+ this.data = new Map();
13
+ this.styleElement = null;
14
+ this.parentNode = parentNode;
15
+ this.containerId = containerId;
16
+ }
17
+ // 创建主容器和子元素
18
+ createMain(items, styles = "", containerConfig = {}) {
19
+ // 创建样式
20
+ if (styles) {
21
+ this.createStyles(styles);
22
+ }
23
+ // 创建容器
24
+ this.container = this.createElement("div", Object.assign({ id: this.containerId }, containerConfig));
25
+ // 创建子元素
26
+ items.forEach((item, index) => {
27
+ const element = this.createItem(item, index);
28
+ if (element) {
29
+ this.container.appendChild(element);
30
+ }
31
+ });
32
+ // 添加到父节点
33
+ this.parentNode.appendChild(this.container);
34
+ return {
35
+ container: this.container,
36
+ get: (keyword) => this.getChild(keyword),
37
+ getValue: (keyword) => this.getValue(keyword),
38
+ setValue: (keyword, value) => this.setValue(keyword, value),
39
+ show: (keyword) => this.show(keyword),
40
+ hide: (keyword) => this.hide(keyword),
41
+ remove: () => this.remove(),
42
+ on: (keyword, event, handler) => this.on(keyword, event, handler),
43
+ getData: (key) => this.getData(key),
44
+ setData: (key, value) => this.setData(key, value),
45
+ };
46
+ }
47
+ // 创建样式
48
+ createStyles(styles) {
49
+ this.styleElement = document.createElement("style");
50
+ this.styleElement.textContent = styles;
51
+ document.head.appendChild(this.styleElement);
52
+ }
53
+ // 创建单个元素
54
+ createItem(config, index) {
55
+ const { type, keyword } = config; tslib_es6.__rest(config, ["type", "keyword"]);
56
+ let element = null;
57
+ switch (type) {
58
+ case "input":
59
+ element = this.createInput(config);
60
+ break;
61
+ case "button":
62
+ element = this.createButton(config);
63
+ break;
64
+ case "select":
65
+ element = this.createSelect(config);
66
+ break;
67
+ case "textarea":
68
+ element = this.createTextarea(config);
69
+ break;
70
+ case "checkbox":
71
+ element = this.createCheckbox(config);
72
+ break;
73
+ case "label":
74
+ element = this.createLabel(config);
75
+ break;
76
+ case "div":
77
+ element = this.createDiv(config);
78
+ break;
79
+ default:
80
+ console.warn(`未支持的元素类型: ${type}`);
81
+ return null;
82
+ }
83
+ // 存储元素引用
84
+ if (keyword && element) {
85
+ this.setChild(keyword, element);
86
+ // 处理本地存储逻辑
87
+ if (config.saveToLocal && this.isFormElement(type)) {
88
+ this.handleLocalStorage(element, config, type);
89
+ }
90
+ }
91
+ return element;
92
+ }
93
+ // 判断是否为表单元素
94
+ isFormElement(type) {
95
+ return ["input", "textarea", "select", "checkbox"].includes(type);
96
+ }
97
+ // 处理本地存储逻辑
98
+ handleLocalStorage(element, config, type) {
99
+ const storageKey = this.getStorageKey(config.keyword);
100
+ const savedValue = this.getFromLocalStorage(storageKey);
101
+ // 设置初始值
102
+ if (savedValue !== null) {
103
+ // 有本地存储值,使用本地值
104
+ if (type === "checkbox") {
105
+ const checkbox = element.querySelector('input[type="checkbox"]');
106
+ if (checkbox) {
107
+ checkbox.checked = savedValue === "true";
108
+ }
109
+ }
110
+ else {
111
+ const formElement = element;
112
+ formElement.value = savedValue;
113
+ }
114
+ }
115
+ else {
116
+ // 没有本地存储值,使用初始值或空值
117
+ if (type === "checkbox") {
118
+ const checkbox = element.querySelector('input[type="checkbox"]');
119
+ if (checkbox) {
120
+ checkbox.checked = config.checked || false;
121
+ }
122
+ }
123
+ else {
124
+ const formElement = element;
125
+ formElement.value = config.value || "";
126
+ }
127
+ }
128
+ // 绑定实时保存事件
129
+ if (type === "checkbox") {
130
+ const checkbox = element.querySelector('input[type="checkbox"]');
131
+ if (checkbox) {
132
+ checkbox.addEventListener("change", (e) => {
133
+ const target = e.target;
134
+ this.saveToLocalStorage(storageKey, target.checked.toString());
135
+ });
136
+ }
137
+ }
138
+ else {
139
+ const eventType = type === "select" ? "change" : "input";
140
+ element.addEventListener(eventType, (e) => {
141
+ const target = e.target;
142
+ this.saveToLocalStorage(storageKey, target.value);
143
+ });
144
+ }
145
+ }
146
+ // 创建输入框
147
+ createInput(config) {
148
+ const input = this.createElement("input", Object.assign({ type: config.inputType || "text", name: config.keyword, placeholder: config.placeholder || "", value: config.value || "" }, config.props));
149
+ // 绑定事件
150
+ this.bindEvents(input, config);
151
+ return input;
152
+ }
153
+ // 创建按钮
154
+ createButton(config) {
155
+ const button = this.createElement("button", Object.assign({ textContent: config.text || config.keyword || "Button", name: config.keyword }, config.props));
156
+ // 绑定事件
157
+ this.bindEvents(button, config);
158
+ return button;
159
+ }
160
+ // 创建下拉框
161
+ createSelect(config) {
162
+ const select = this.createElement("select", Object.assign({ name: config.keyword }, config.props));
163
+ // 添加选项
164
+ if (config.options) {
165
+ config.options.forEach((option) => {
166
+ const optionEl = document.createElement("option");
167
+ if (typeof option === 'string') {
168
+ optionEl.value = option;
169
+ optionEl.textContent = option;
170
+ }
171
+ else {
172
+ optionEl.value = option.value || option.text || '';
173
+ optionEl.textContent = option.text || option.value || '';
174
+ if (option.selected)
175
+ optionEl.selected = true;
176
+ }
177
+ select.appendChild(optionEl);
178
+ });
179
+ }
180
+ // 绑定事件
181
+ this.bindEvents(select, config);
182
+ return select;
183
+ }
184
+ // 创建文本域
185
+ createTextarea(config) {
186
+ const textarea = this.createElement("textarea", Object.assign({ name: config.keyword, placeholder: config.placeholder || "", value: config.value || "", rows: config.rows || 3 }, config.props));
187
+ // 绑定事件
188
+ this.bindEvents(textarea, config);
189
+ return textarea;
190
+ }
191
+ // 创建复选框
192
+ createCheckbox(config) {
193
+ const wrapper = document.createElement("div");
194
+ const checkbox = this.createElement("input", Object.assign({ type: "checkbox", id: config.keyword, name: config.keyword, checked: config.checked || false }, config.props));
195
+ const label = document.createElement("label");
196
+ label.setAttribute("for", config.keyword || '');
197
+ label.textContent = config.text || config.keyword || "Checkbox";
198
+ // 绑定事件
199
+ this.bindEvents(checkbox, config);
200
+ wrapper.appendChild(checkbox);
201
+ wrapper.appendChild(label);
202
+ // 将checkbox存储为主要元素
203
+ if (config.keyword) {
204
+ this.setChild(config.keyword, checkbox);
205
+ }
206
+ return wrapper;
207
+ }
208
+ // 创建标签
209
+ createLabel(config) {
210
+ return this.createElement("label", Object.assign({ textContent: config.text || config.keyword || "", name: config.keyword }, config.props));
211
+ }
212
+ // 创建DIV
213
+ createDiv(config) {
214
+ const div = this.createElement("div", Object.assign({ textContent: config.text || "", innerHTML: config.html || undefined, name: config.keyword }, config.props));
215
+ // 绑定事件
216
+ this.bindEvents(div, config);
217
+ return div;
218
+ }
219
+ // 通用元素创建方法
220
+ createElement(tag, props = {}) {
221
+ const element = document.createElement(tag);
222
+ Object.keys(props).forEach((key) => {
223
+ if (key === "innerHTML") {
224
+ element.innerHTML = props[key];
225
+ }
226
+ else {
227
+ element[key] = props[key];
228
+ }
229
+ });
230
+ return element;
231
+ }
232
+ // 绑定事件
233
+ bindEvents(element, config) {
234
+ const eventTypes = ["onClick", "onChange", "onInput", "onFocus", "onBlur", "onMouseEnter", "onMouseLeave"];
235
+ eventTypes.forEach((eventType) => {
236
+ const handler = config[eventType];
237
+ if (handler) {
238
+ const eventName = eventType.slice(2).toLowerCase();
239
+ element.addEventListener(eventName, handler);
240
+ }
241
+ });
242
+ }
243
+ // 获取子元素
244
+ getChild(keyword) {
245
+ return this.elements.get(keyword) || null;
246
+ }
247
+ // 设置子元素
248
+ setChild(keyword, element) {
249
+ if (!this.elements.has(keyword)) {
250
+ this.elements.set(keyword, element);
251
+ }
252
+ }
253
+ // 获取元素值
254
+ getValue(keyword) {
255
+ const element = this.getChild(keyword);
256
+ if (!element)
257
+ return null;
258
+ if (element.type === "checkbox") {
259
+ return element.checked;
260
+ }
261
+ const formElement = element;
262
+ return formElement.value || element.textContent || null;
263
+ }
264
+ // 设置元素值
265
+ setValue(keyword, value) {
266
+ const element = this.getChild(keyword);
267
+ if (!element)
268
+ return;
269
+ if (element.type === "checkbox") {
270
+ element.checked = Boolean(value);
271
+ }
272
+ else {
273
+ const formElement = element;
274
+ if (formElement.value !== undefined) {
275
+ formElement.value = String(value);
276
+ }
277
+ else {
278
+ element.textContent = String(value);
279
+ }
280
+ }
281
+ }
282
+ // 显示容器或子元素
283
+ show(keyword) {
284
+ if (keyword) {
285
+ const element = this.getChild(keyword);
286
+ if (element) {
287
+ // 显示元素,如果是checkbox,显示其父容器
288
+ const targetElement = element.type === "checkbox" ? element.parentElement : element;
289
+ if (targetElement) {
290
+ targetElement.style.display = "";
291
+ }
292
+ }
293
+ }
294
+ else {
295
+ if (this.container) {
296
+ this.container.style.display = "";
297
+ }
298
+ }
299
+ }
300
+ // 隐藏容器或子元素
301
+ hide(keyword) {
302
+ if (keyword) {
303
+ const element = this.getChild(keyword);
304
+ if (element) {
305
+ // 隐藏元素,如果是checkbox,隐藏其父容器
306
+ const targetElement = element.type === "checkbox" ? element.parentElement : element;
307
+ if (targetElement) {
308
+ targetElement.style.display = "none";
309
+ }
310
+ }
311
+ }
312
+ else {
313
+ if (this.container) {
314
+ this.container.style.display = "none";
315
+ }
316
+ }
317
+ }
318
+ // 移除容器
319
+ remove() {
320
+ if (this.container) {
321
+ this.container.remove();
322
+ this.container = null;
323
+ this.elements.clear();
324
+ }
325
+ if (this.styleElement) {
326
+ this.styleElement.remove();
327
+ this.styleElement = null;
328
+ }
329
+ }
330
+ // 事件绑定
331
+ on(keyword, event, handler) {
332
+ const element = this.getChild(keyword);
333
+ if (element) {
334
+ element.addEventListener(event, handler);
335
+ }
336
+ }
337
+ // 获取存储key
338
+ getStorageKey(keyword) {
339
+ return `${this.containerId}_${keyword}`;
340
+ }
341
+ // 本地存储相关方法
342
+ saveToLocalStorage(key, value) {
343
+ try {
344
+ localStorage.setItem(key, value);
345
+ }
346
+ catch (e) {
347
+ console.warn("无法保存到本地存储:", e);
348
+ }
349
+ }
350
+ getFromLocalStorage(key) {
351
+ try {
352
+ return localStorage.getItem(key);
353
+ }
354
+ catch (e) {
355
+ console.warn("无法从本地存储读取:", e);
356
+ return null;
357
+ }
358
+ }
359
+ // 内存数据存储
360
+ setData(key, value) {
361
+ this.data.set(key, value);
362
+ }
363
+ getData(key) {
364
+ return this.data.get(key);
365
+ }
366
+ }
367
+
368
+ exports.ScriptDomBuilder = ScriptDomBuilder;
package/lib/index.d.ts CHANGED
@@ -6,3 +6,6 @@ export * from "./regexp";
6
6
  export * from "./form";
7
7
  export * from "./count";
8
8
  export * from "./xhr";
9
+ export * from "./constant";
10
+ export * from "./document";
11
+ export * from "./async";
package/lib/index.js CHANGED
@@ -8,6 +8,10 @@ var index$4 = require('./regexp/index.js');
8
8
  var index$5 = require('./form/index.js');
9
9
  var index$6 = require('./count/index.js');
10
10
  var index$7 = require('./xhr/index.js');
11
+ var index$8 = require('./constant/index.js');
12
+ var index$9 = require('./document/index.js');
13
+ var index$a = require('./async/index.js');
14
+ var scriptDomBuilder = require('./document/script-dom-builder.js');
11
15
 
12
16
 
13
17
 
@@ -27,3 +31,8 @@ exports.createFormData = index$5.createFormData;
27
31
  exports.precisionFormat = index$6.precisionFormat;
28
32
  exports.XHRInterceptor = index$7.XHRInterceptor;
29
33
  exports.xhrInterceptor = index$7.xhrInterceptor;
34
+ exports.Lib_Name = index$8.Lib_Name;
35
+ exports.addStyleStr = index$9.addStyleStr;
36
+ exports.createMaskLoading = index$9.createMaskLoading;
37
+ exports.createAsyncTask = index$a.createAsyncTask;
38
+ exports.ScriptDomBuilder = scriptDomBuilder.ScriptDomBuilder;
@@ -17,6 +17,18 @@ PERFORMANCE OF THIS SOFTWARE.
17
17
  /* global Reflect, Promise, SuppressedError, Symbol */
18
18
 
19
19
 
20
+ function __rest(s, e) {
21
+ var t = {};
22
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
23
+ t[p] = s[p];
24
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
25
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
26
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
27
+ t[p[i]] = s[p[i]];
28
+ }
29
+ return t;
30
+ }
31
+
20
32
  function __awaiter(thisArg, _arguments, P, generator) {
21
33
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
22
34
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -33,3 +45,4 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
33
45
  };
34
46
 
35
47
  exports.__awaiter = __awaiter;
48
+ exports.__rest = __rest;
@@ -7,8 +7,12 @@
7
7
  * 拦截规则
8
8
  */
9
9
  interface InterceptRule {
10
+ /** 拦截的 URL,模糊匹配 */
10
11
  url: string;
11
- responseCallback: (data: any) => any | Promise<any>;
12
+ /** 拦截响应的回调函数 */
13
+ responseCallback: (data: any) => any;
14
+ /** 拦截请求的回调函数 */
15
+ requestCallback?: (data: any) => any;
12
16
  }
13
17
  /**
14
18
  * 拦截器配置
@@ -40,7 +44,7 @@ declare class XHRInterceptor {
40
44
  /**
41
45
  * 添加单个拦截规则
42
46
  */
43
- addRule(url: string, responseCallback: InterceptRule["responseCallback"]): void;
47
+ addRule(url: string, responseCallback: InterceptRule["responseCallback"], requestCallback?: InterceptRule["requestCallback"]): void;
44
48
  /**
45
49
  * 移除指定URL的拦截规则
46
50
  */
package/lib/xhr/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- var tslib_es6 = require('../node_modules/tslib/tslib.es6.js');
4
-
5
3
  /**
6
4
  * @fileoverview XMLHttpRequest模块
7
5
  * @created 2025-04-02
@@ -46,41 +44,51 @@ class XHRInterceptor {
46
44
  // 没有匹配的规则,直接执行原始请求
47
45
  return originalSend.call(this, body);
48
46
  }
47
+ // 处理请求数据拦截
48
+ let processedBody = body;
49
+ if (matchingRule.requestCallback && body) {
50
+ try {
51
+ processedBody = matchingRule.requestCallback(body);
52
+ }
53
+ catch (error) {
54
+ console.error('XHR请求拦截器处理失败:', error);
55
+ // 出错时使用原始请求体
56
+ processedBody = body;
57
+ }
58
+ }
49
59
  // 保存原始的 onreadystatechange
50
60
  const originalOnReadyStateChange = xhr.onreadystatechange;
51
61
  xhr.onreadystatechange = function (event) {
52
- return tslib_es6.__awaiter(this, void 0, void 0, function* () {
53
- if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
54
- try {
55
- // 解析原始响应
56
- const originalData = JSON.parse(xhr.responseText);
57
- // 使用回调函数处理响应数据
58
- const modifiedData = yield matchingRule.responseCallback(originalData);
59
- // 重写响应属性
60
- Object.defineProperty(xhr, "responseText", {
61
- writable: true,
62
- configurable: true,
63
- value: JSON.stringify(modifiedData),
64
- });
65
- Object.defineProperty(xhr, "response", {
66
- writable: true,
67
- configurable: true,
68
- value: JSON.stringify(modifiedData),
69
- });
70
- self.log(`已拦截并修改响应: ${requestUrl}`);
71
- }
72
- catch (error) {
73
- self.log("拦截器处理失败:", error);
74
- // 出错时保持原始响应
75
- }
62
+ if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
63
+ try {
64
+ // 解析原始响应
65
+ const originalData = JSON.parse(xhr.responseText);
66
+ // 使用回调函数处理响应数据
67
+ const modifiedData = matchingRule.responseCallback(originalData);
68
+ // 重写响应属性
69
+ Object.defineProperty(xhr, "responseText", {
70
+ writable: true,
71
+ configurable: true,
72
+ value: JSON.stringify(modifiedData),
73
+ });
74
+ Object.defineProperty(xhr, "response", {
75
+ writable: true,
76
+ configurable: true,
77
+ value: JSON.stringify(modifiedData),
78
+ });
79
+ self.log(`已拦截并修改响应: ${requestUrl}`);
76
80
  }
77
- // 调用原始的 onreadystatechange
78
- if (originalOnReadyStateChange) {
79
- originalOnReadyStateChange.call(this, event);
81
+ catch (error) {
82
+ self.log("拦截器处理失败:", error);
83
+ // 出错时保持原始响应
80
84
  }
81
- });
85
+ }
86
+ // 调用原始的 onreadystatechange
87
+ if (originalOnReadyStateChange) {
88
+ originalOnReadyStateChange.call(this, event);
89
+ }
82
90
  };
83
- return originalSend.call(this, body);
91
+ return originalSend.call(this, processedBody);
84
92
  };
85
93
  return xhr;
86
94
  };
@@ -112,8 +120,8 @@ class XHRInterceptor {
112
120
  /**
113
121
  * 添加单个拦截规则
114
122
  */
115
- addRule(url, responseCallback) {
116
- this.interceptRules.push({ url, responseCallback });
123
+ addRule(url, responseCallback, requestCallback) {
124
+ this.interceptRules.push({ url, responseCallback, requestCallback });
117
125
  this.log(`已添加拦截规则: ${url}`);
118
126
  }
119
127
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ziya-utils",
3
- "version": "1.1.4",
3
+ "version": "1.1.6",
4
4
  "description": "A javascript tool library.",
5
5
  "main": "./lib/index.js",
6
6
  "browser": "dist/ziya-utils.js",
@@ -1,7 +0,0 @@
1
- declare const loger: {
2
- info: (...args: any[]) => void;
3
- error: (...args: any[]) => void;
4
- warn: (...args: any[]) => void;
5
- debug: (...args: any[]) => void;
6
- };
7
- export { loger };
@@ -1,7 +0,0 @@
1
- declare const loger: {
2
- info: (...args: any[]) => void;
3
- error: (...args: any[]) => void;
4
- warn: (...args: any[]) => void;
5
- debug: (...args: any[]) => void;
6
- };
7
- export { loger };