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