@whitesev/domutils 1.5.3 → 1.5.5

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/dist/index.esm.js CHANGED
@@ -41,6 +41,238 @@ class WindowApi {
41
41
  }
42
42
  }
43
43
 
44
+ const createCache = (lastNumberWeakMap) => {
45
+ return (collection, nextNumber) => {
46
+ lastNumberWeakMap.set(collection, nextNumber);
47
+ return nextNumber;
48
+ };
49
+ };
50
+
51
+ /*
52
+ * The value of the constant Number.MAX_SAFE_INTEGER equals (2 ** 53 - 1) but it
53
+ * is fairly new.
54
+ */
55
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER === undefined ? 9007199254740991 : Number.MAX_SAFE_INTEGER;
56
+ const TWO_TO_THE_POWER_OF_TWENTY_NINE = 536870912;
57
+ const TWO_TO_THE_POWER_OF_THIRTY = TWO_TO_THE_POWER_OF_TWENTY_NINE * 2;
58
+ const createGenerateUniqueNumber = (cache, lastNumberWeakMap) => {
59
+ return (collection) => {
60
+ const lastNumber = lastNumberWeakMap.get(collection);
61
+ /*
62
+ * Let's try the cheapest algorithm first. It might fail to produce a new
63
+ * number, but it is so cheap that it is okay to take the risk. Just
64
+ * increase the last number by one or reset it to 0 if we reached the upper
65
+ * bound of SMIs (which stands for small integers). When the last number is
66
+ * unknown it is assumed that the collection contains zero based consecutive
67
+ * numbers.
68
+ */
69
+ let nextNumber = lastNumber === undefined ? collection.size : lastNumber < TWO_TO_THE_POWER_OF_THIRTY ? lastNumber + 1 : 0;
70
+ if (!collection.has(nextNumber)) {
71
+ return cache(collection, nextNumber);
72
+ }
73
+ /*
74
+ * If there are less than half of 2 ** 30 numbers stored in the collection,
75
+ * the chance to generate a new random number in the range from 0 to 2 ** 30
76
+ * is at least 50%. It's benifitial to use only SMIs because they perform
77
+ * much better in any environment based on V8.
78
+ */
79
+ if (collection.size < TWO_TO_THE_POWER_OF_TWENTY_NINE) {
80
+ while (collection.has(nextNumber)) {
81
+ nextNumber = Math.floor(Math.random() * TWO_TO_THE_POWER_OF_THIRTY);
82
+ }
83
+ return cache(collection, nextNumber);
84
+ }
85
+ // Quickly check if there is a theoretical chance to generate a new number.
86
+ if (collection.size > MAX_SAFE_INTEGER) {
87
+ throw new Error('Congratulations, you created a collection of unique numbers which uses all available integers!');
88
+ }
89
+ // Otherwise use the full scale of safely usable integers.
90
+ while (collection.has(nextNumber)) {
91
+ nextNumber = Math.floor(Math.random() * MAX_SAFE_INTEGER);
92
+ }
93
+ return cache(collection, nextNumber);
94
+ };
95
+ };
96
+
97
+ const LAST_NUMBER_WEAK_MAP = new WeakMap();
98
+ const cache = createCache(LAST_NUMBER_WEAK_MAP);
99
+ const generateUniqueNumber = createGenerateUniqueNumber(cache, LAST_NUMBER_WEAK_MAP);
100
+
101
+ const isCallNotification = (message) => {
102
+ return message.method !== undefined && message.method === 'call';
103
+ };
104
+
105
+ const isClearResponse = (message) => {
106
+ return typeof message.id === 'number' && typeof message.result === 'boolean';
107
+ };
108
+
109
+ const load = (url) => {
110
+ // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification.
111
+ const scheduledIntervalFunctions = new Map([[0, () => { }]]); // tslint:disable-line no-empty
112
+ const scheduledTimeoutFunctions = new Map([[0, () => { }]]); // tslint:disable-line no-empty
113
+ const unrespondedRequests = new Map();
114
+ const worker = new Worker(url);
115
+ worker.addEventListener('message', ({ data }) => {
116
+ if (isCallNotification(data)) {
117
+ const { params: { timerId, timerType } } = data;
118
+ if (timerType === 'interval') {
119
+ const idOrFunc = scheduledIntervalFunctions.get(timerId);
120
+ if (typeof idOrFunc === undefined) {
121
+ throw new Error('The timer is in an undefined state.');
122
+ }
123
+ if (typeof idOrFunc === 'number') {
124
+ const timerIdAndTimerType = unrespondedRequests.get(idOrFunc);
125
+ if (timerIdAndTimerType === undefined ||
126
+ timerIdAndTimerType.timerId !== timerId ||
127
+ timerIdAndTimerType.timerType !== timerType) {
128
+ throw new Error('The timer is in an undefined state.');
129
+ }
130
+ }
131
+ else if (typeof idOrFunc === 'function') {
132
+ idOrFunc();
133
+ }
134
+ }
135
+ else if (timerType === 'timeout') {
136
+ const idOrFunc = scheduledTimeoutFunctions.get(timerId);
137
+ if (typeof idOrFunc === undefined) {
138
+ throw new Error('The timer is in an undefined state.');
139
+ }
140
+ if (typeof idOrFunc === 'number') {
141
+ const timerIdAndTimerType = unrespondedRequests.get(idOrFunc);
142
+ if (timerIdAndTimerType === undefined ||
143
+ timerIdAndTimerType.timerId !== timerId ||
144
+ timerIdAndTimerType.timerType !== timerType) {
145
+ throw new Error('The timer is in an undefined state.');
146
+ }
147
+ }
148
+ else if (typeof idOrFunc === 'function') {
149
+ idOrFunc();
150
+ // A timeout can be savely deleted because it is only called once.
151
+ scheduledTimeoutFunctions.delete(timerId);
152
+ }
153
+ }
154
+ }
155
+ else if (isClearResponse(data)) {
156
+ const { id } = data;
157
+ const timerIdAndTimerType = unrespondedRequests.get(id);
158
+ if (timerIdAndTimerType === undefined) {
159
+ throw new Error('The timer is in an undefined state.');
160
+ }
161
+ const { timerId, timerType } = timerIdAndTimerType;
162
+ unrespondedRequests.delete(id);
163
+ if (timerType === 'interval') {
164
+ scheduledIntervalFunctions.delete(timerId);
165
+ }
166
+ else {
167
+ scheduledTimeoutFunctions.delete(timerId);
168
+ }
169
+ }
170
+ else {
171
+ const { error: { message } } = data;
172
+ throw new Error(message);
173
+ }
174
+ });
175
+ const clearInterval = (timerId) => {
176
+ if (typeof scheduledIntervalFunctions.get(timerId) === 'function') {
177
+ const id = generateUniqueNumber(unrespondedRequests);
178
+ unrespondedRequests.set(id, { timerId, timerType: 'interval' });
179
+ scheduledIntervalFunctions.set(timerId, id);
180
+ worker.postMessage({
181
+ id,
182
+ method: 'clear',
183
+ params: { timerId, timerType: 'interval' }
184
+ });
185
+ }
186
+ };
187
+ const clearTimeout = (timerId) => {
188
+ if (typeof scheduledTimeoutFunctions.get(timerId) === 'function') {
189
+ const id = generateUniqueNumber(unrespondedRequests);
190
+ unrespondedRequests.set(id, { timerId, timerType: 'timeout' });
191
+ scheduledTimeoutFunctions.set(timerId, id);
192
+ worker.postMessage({
193
+ id,
194
+ method: 'clear',
195
+ params: { timerId, timerType: 'timeout' }
196
+ });
197
+ }
198
+ };
199
+ const setInterval = (func, delay = 0, ...args) => {
200
+ const timerId = generateUniqueNumber(scheduledIntervalFunctions);
201
+ scheduledIntervalFunctions.set(timerId, () => {
202
+ func(...args);
203
+ // Doublecheck if the interval should still be rescheduled because it could have been cleared inside of func().
204
+ if (typeof scheduledIntervalFunctions.get(timerId) === 'function') {
205
+ worker.postMessage({
206
+ id: null,
207
+ method: 'set',
208
+ params: {
209
+ delay,
210
+ now: performance.timeOrigin + performance.now(),
211
+ timerId,
212
+ timerType: 'interval'
213
+ }
214
+ });
215
+ }
216
+ });
217
+ worker.postMessage({
218
+ id: null,
219
+ method: 'set',
220
+ params: {
221
+ delay,
222
+ now: performance.timeOrigin + performance.now(),
223
+ timerId,
224
+ timerType: 'interval'
225
+ }
226
+ });
227
+ return timerId;
228
+ };
229
+ const setTimeout = (func, delay = 0, ...args) => {
230
+ const timerId = generateUniqueNumber(scheduledTimeoutFunctions);
231
+ scheduledTimeoutFunctions.set(timerId, () => func(...args));
232
+ worker.postMessage({
233
+ id: null,
234
+ method: 'set',
235
+ params: {
236
+ delay,
237
+ now: performance.timeOrigin + performance.now(),
238
+ timerId,
239
+ timerType: 'timeout'
240
+ }
241
+ });
242
+ return timerId;
243
+ };
244
+ return {
245
+ clearInterval,
246
+ clearTimeout,
247
+ setInterval,
248
+ setTimeout
249
+ };
250
+ };
251
+
252
+ const createLoadOrReturnBroker = (loadBroker, worker) => {
253
+ let broker = null;
254
+ return () => {
255
+ if (broker !== null) {
256
+ return broker;
257
+ }
258
+ const blob = new Blob([worker], { type: 'application/javascript; charset=utf-8' });
259
+ const url = URL.createObjectURL(blob);
260
+ broker = loadBroker(url);
261
+ // Bug #1: Edge up until v18 didn't like the URL to be revoked directly.
262
+ setTimeout(() => URL.revokeObjectURL(url));
263
+ return broker;
264
+ };
265
+ };
266
+
267
+ // This is the minified and stringified code of the worker-timers-worker package.
268
+ const worker = `(()=>{"use strict";const e=new Map,t=new Map,r=t=>{const r=e.get(t);return void 0!==r&&(clearTimeout(r),e.delete(t),!0)},s=e=>{const r=t.get(e);return void 0!==r&&(clearTimeout(r),t.delete(e),!0)},o=(e,t)=>{const r=performance.now(),s=e+t-r-performance.timeOrigin;return{expected:r+s,remainingDelay:s}},i=(e,t,r,s)=>{const o=r-performance.now();o>0?e.set(t,setTimeout(i,o,e,t,r,s)):(e.delete(t),postMessage({id:null,method:"call",params:{timerId:t,timerType:s}}))};addEventListener("message",(({data:n})=>{try{if("clear"===n.method){const{id:e,params:{timerId:t,timerType:o}}=n;if("interval"===o)postMessage({id:e,result:r(t)});else{if("timeout"!==o)throw new Error('The given type "'.concat(o,'" is not supported'));postMessage({id:e,result:s(t)})}}else{if("set"!==n.method)throw new Error('The given method "'.concat(n.method,'" is not supported'));{const{params:{delay:r,now:s,timerId:a,timerType:m}}=n;if("interval"===m)((t,r,s)=>{const{expected:n,remainingDelay:a}=o(t,s);e.set(r,setTimeout(i,a,e,r,n,"interval"))})(r,a,s);else{if("timeout"!==m)throw new Error('The given type "'.concat(m,'" is not supported'));((e,r,s)=>{const{expected:n,remainingDelay:a}=o(e,s);t.set(r,setTimeout(i,a,t,r,n,"timeout"))})(r,a,s)}}}}catch(e){postMessage({error:{message:e.message},id:n.id,result:null})}}))})();`; // tslint:disable-line:max-line-length
269
+
270
+ const loadOrReturnBroker = createLoadOrReturnBroker(load, worker);
271
+ const clearInterval = (timerId) => loadOrReturnBroker().clearInterval(timerId);
272
+ const clearTimeout = (timerId) => loadOrReturnBroker().clearTimeout(timerId);
273
+ const setInterval = (...args) => loadOrReturnBroker().setInterval(...args);
274
+ const setTimeout$1 = (...args) => loadOrReturnBroker().setTimeout(...args);
275
+
44
276
  /** 通用工具类 */
45
277
  const DOMUtilsCommonUtils = {
46
278
  windowApi: new WindowApi({
@@ -174,6 +406,58 @@ const DOMUtilsCommonUtils = {
174
406
  delete target[propName];
175
407
  }
176
408
  },
409
+ /**
410
+ * 自动使用 Worker 执行 setTimeout
411
+ */
412
+ setTimeout(callback, timeout = 0) {
413
+ try {
414
+ return setTimeout$1(callback, timeout);
415
+ }
416
+ catch (error) {
417
+ return globalThis.setTimeout(callback, timeout);
418
+ }
419
+ },
420
+ /**
421
+ * 配合 .setTimeout 使用
422
+ */
423
+ clearTimeout(timeId) {
424
+ try {
425
+ if (timeId != null) {
426
+ clearTimeout(timeId);
427
+ }
428
+ }
429
+ catch (error) {
430
+ }
431
+ finally {
432
+ globalThis.clearTimeout(timeId);
433
+ }
434
+ },
435
+ /**
436
+ * 自动使用 Worker 执行 setInterval
437
+ */
438
+ setInterval(callback, timeout = 0) {
439
+ try {
440
+ return setInterval(callback, timeout);
441
+ }
442
+ catch (error) {
443
+ return globalThis.setInterval(callback, timeout);
444
+ }
445
+ },
446
+ /**
447
+ * 配合 .setInterval 使用
448
+ */
449
+ clearInterval(timeId) {
450
+ try {
451
+ if (timeId != null) {
452
+ clearInterval(timeId);
453
+ }
454
+ }
455
+ catch (error) {
456
+ }
457
+ finally {
458
+ globalThis.clearInterval(timeId);
459
+ }
460
+ },
177
461
  };
178
462
 
179
463
  /* 数据 */
@@ -594,7 +878,7 @@ class DOMUtilsEvent {
594
878
  }
595
879
  if (checkDOMReadyState()) {
596
880
  /* 检查document状态 */
597
- setTimeout(callback);
881
+ DOMUtilsCommonUtils.setTimeout(callback);
598
882
  }
599
883
  else {
600
884
  /* 添加监听 */
@@ -1060,7 +1344,7 @@ class DOMUtils extends DOMUtilsEvent {
1060
1344
  super(option);
1061
1345
  }
1062
1346
  /** 版本号 */
1063
- version = "2025.4.23";
1347
+ version = "2025.5.26";
1064
1348
  attr(element, attrName, attrValue) {
1065
1349
  let DOMUtilsContext = this;
1066
1350
  if (typeof element === "string") {
@@ -1204,7 +1488,8 @@ class DOMUtils extends DOMUtilsEvent {
1204
1488
  return;
1205
1489
  }
1206
1490
  let setStyleProperty = (propertyName, propertyValue) => {
1207
- if (propertyValue === "string" && propertyValue.includes("!important")) {
1491
+ if (typeof propertyValue === "string" &&
1492
+ propertyValue.trim().endsWith("!important")) {
1208
1493
  propertyValue = propertyValue
1209
1494
  .trim()
1210
1495
  .replace(/!important$/gi, "")
@@ -2041,7 +2326,7 @@ class DOMUtils extends DOMUtilsEvent {
2041
2326
  DOMUtilsContext.windowApi.globalThis.getComputedStyle(element)[prop];
2042
2327
  to[prop] = styles[prop];
2043
2328
  }
2044
- let timer = setInterval(function () {
2329
+ let timer = DOMUtilsCommonUtils.setInterval(function () {
2045
2330
  let timePassed = performance.now() - start;
2046
2331
  let progress = timePassed / duration;
2047
2332
  if (progress > 1) {
@@ -2052,7 +2337,7 @@ class DOMUtils extends DOMUtilsEvent {
2052
2337
  from[prop] + (to[prop] - from[prop]) * progress + "px";
2053
2338
  }
2054
2339
  if (progress === 1) {
2055
- clearInterval(timer);
2340
+ DOMUtilsCommonUtils.clearInterval(timer);
2056
2341
  if (callback) {
2057
2342
  callback();
2058
2343
  }