@whitesev/pops 3.2.2 → 3.3.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/dist/index.umd.js CHANGED
@@ -181,272 +181,55 @@
181
181
  */
182
182
  const SymbolEvents = Symbol("events_" + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1));
183
183
 
184
- const PopsCoreDefaultEnv = {
184
+ const OriginPrototype = {
185
+ Object: {
186
+ defineProperty: Object.defineProperty,
187
+ },
188
+ };
189
+ const PopsCoreDefaultApi = {
185
190
  document: document,
186
191
  window: window,
187
192
  globalThis: globalThis,
188
193
  self: self,
194
+ setTimeout: globalThis.setTimeout.bind(globalThis),
195
+ setInterval: globalThis.setInterval.bind(globalThis),
196
+ clearTimeout: globalThis.clearTimeout.bind(globalThis),
197
+ clearInterval: globalThis.clearInterval.bind(globalThis),
189
198
  };
190
- const PopsCoreEnv = Object.assign({}, PopsCoreDefaultEnv);
199
+ const PopsCoreApi = Object.assign({}, PopsCoreDefaultApi);
191
200
  const PopsCore = {
201
+ init(option) {
202
+ if (!option) {
203
+ option = Object.assign({}, PopsCoreDefaultApi);
204
+ }
205
+ Object.assign(PopsCoreApi, option);
206
+ },
192
207
  get document() {
193
- return PopsCoreEnv.document;
208
+ return PopsCoreApi.document;
194
209
  },
195
210
  get window() {
196
- return PopsCoreEnv.window;
211
+ return PopsCoreApi.window;
197
212
  },
198
213
  get globalThis() {
199
- return PopsCoreEnv.globalThis;
214
+ return PopsCoreApi.globalThis;
200
215
  },
201
216
  get self() {
202
- return PopsCoreEnv.self;
217
+ return PopsCoreApi.self;
203
218
  },
204
- };
205
- const OriginPrototype = {
206
- Object: {
207
- defineProperty: Object.defineProperty,
219
+ get setTimeout() {
220
+ return PopsCoreApi.setTimeout;
208
221
  },
209
- };
210
-
211
- const createCache = (lastNumberWeakMap) => {
212
- return (collection, nextNumber) => {
213
- lastNumberWeakMap.set(collection, nextNumber);
214
- return nextNumber;
215
- };
216
- };
217
-
218
- /*
219
- * The value of the constant Number.MAX_SAFE_INTEGER equals (2 ** 53 - 1) but it
220
- * is fairly new.
221
- */
222
- const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER === undefined ? 9007199254740991 : Number.MAX_SAFE_INTEGER;
223
- const TWO_TO_THE_POWER_OF_TWENTY_NINE = 536870912;
224
- const TWO_TO_THE_POWER_OF_THIRTY = TWO_TO_THE_POWER_OF_TWENTY_NINE * 2;
225
- const createGenerateUniqueNumber = (cache, lastNumberWeakMap) => {
226
- return (collection) => {
227
- const lastNumber = lastNumberWeakMap.get(collection);
228
- /*
229
- * Let's try the cheapest algorithm first. It might fail to produce a new
230
- * number, but it is so cheap that it is okay to take the risk. Just
231
- * increase the last number by one or reset it to 0 if we reached the upper
232
- * bound of SMIs (which stands for small integers). When the last number is
233
- * unknown it is assumed that the collection contains zero based consecutive
234
- * numbers.
235
- */
236
- let nextNumber = lastNumber === undefined ? collection.size : lastNumber < TWO_TO_THE_POWER_OF_THIRTY ? lastNumber + 1 : 0;
237
- if (!collection.has(nextNumber)) {
238
- return cache(collection, nextNumber);
239
- }
240
- /*
241
- * If there are less than half of 2 ** 30 numbers stored in the collection,
242
- * the chance to generate a new random number in the range from 0 to 2 ** 30
243
- * is at least 50%. It's benifitial to use only SMIs because they perform
244
- * much better in any environment based on V8.
245
- */
246
- if (collection.size < TWO_TO_THE_POWER_OF_TWENTY_NINE) {
247
- while (collection.has(nextNumber)) {
248
- nextNumber = Math.floor(Math.random() * TWO_TO_THE_POWER_OF_THIRTY);
249
- }
250
- return cache(collection, nextNumber);
251
- }
252
- // Quickly check if there is a theoretical chance to generate a new number.
253
- if (collection.size > MAX_SAFE_INTEGER) {
254
- throw new Error('Congratulations, you created a collection of unique numbers which uses all available integers!');
255
- }
256
- // Otherwise use the full scale of safely usable integers.
257
- while (collection.has(nextNumber)) {
258
- nextNumber = Math.floor(Math.random() * MAX_SAFE_INTEGER);
259
- }
260
- return cache(collection, nextNumber);
261
- };
262
- };
263
-
264
- const LAST_NUMBER_WEAK_MAP = new WeakMap();
265
- const cache = createCache(LAST_NUMBER_WEAK_MAP);
266
- const generateUniqueNumber = createGenerateUniqueNumber(cache, LAST_NUMBER_WEAK_MAP);
267
-
268
- const createBrokerFactory = (createOrGetOngoingRequests, extendBrokerImplementation, generateUniqueNumber, isMessagePort) => (brokerImplementation) => {
269
- const fullBrokerImplementation = extendBrokerImplementation(brokerImplementation);
270
- return (sender) => {
271
- const ongoingRequests = createOrGetOngoingRequests(sender);
272
- sender.addEventListener('message', (({ data: message }) => {
273
- const { id } = message;
274
- if (id !== null && ongoingRequests.has(id)) {
275
- const { reject, resolve } = ongoingRequests.get(id);
276
- ongoingRequests.delete(id);
277
- if (message.error === undefined) {
278
- resolve(message.result);
279
- }
280
- else {
281
- reject(new Error(message.error.message));
282
- }
283
- }
284
- }));
285
- if (isMessagePort(sender)) {
286
- sender.start();
287
- }
288
- const call = (method, params = null, transferables = []) => {
289
- return new Promise((resolve, reject) => {
290
- const id = generateUniqueNumber(ongoingRequests);
291
- ongoingRequests.set(id, { reject, resolve });
292
- if (params === null) {
293
- sender.postMessage({ id, method }, transferables);
294
- }
295
- else {
296
- sender.postMessage({ id, method, params }, transferables);
297
- }
298
- });
299
- };
300
- const notify = (method, params, transferables = []) => {
301
- sender.postMessage({ id: null, method, params }, transferables);
302
- };
303
- let functions = {};
304
- for (const [key, handler] of Object.entries(fullBrokerImplementation)) {
305
- functions = { ...functions, [key]: handler({ call, notify }) };
306
- }
307
- return { ...functions };
308
- };
309
- };
310
-
311
- const createCreateOrGetOngoingRequests = (ongoingRequestsMap) => (sender) => {
312
- if (ongoingRequestsMap.has(sender)) {
313
- // @todo TypeScript needs to be convinced that has() works as expected.
314
- return ongoingRequestsMap.get(sender);
315
- }
316
- const ongoingRequests = new Map();
317
- ongoingRequestsMap.set(sender, ongoingRequests);
318
- return ongoingRequests;
319
- };
320
-
321
- const createExtendBrokerImplementation = (portMap) => (partialBrokerImplementation) => ({
322
- ...partialBrokerImplementation,
323
- connect: ({ call }) => {
324
- return async () => {
325
- const { port1, port2 } = new MessageChannel();
326
- const portId = await call('connect', { port: port1 }, [port1]);
327
- portMap.set(port2, portId);
328
- return port2;
329
- };
222
+ get setInterval() {
223
+ return PopsCoreApi.setInterval;
330
224
  },
331
- disconnect: ({ call }) => {
332
- return async (port) => {
333
- const portId = portMap.get(port);
334
- if (portId === undefined) {
335
- throw new Error('The given port is not connected.');
336
- }
337
- await call('disconnect', { portId });
338
- };
225
+ get clearTimeout() {
226
+ return PopsCoreApi.clearTimeout;
227
+ },
228
+ get clearInterval() {
229
+ return PopsCoreApi.clearInterval;
339
230
  },
340
- isSupported: ({ call }) => {
341
- return () => call('isSupported');
342
- }
343
- });
344
-
345
- const isMessagePort = (sender) => {
346
- return typeof sender.start === 'function';
347
- };
348
-
349
- const createBroker = createBrokerFactory(createCreateOrGetOngoingRequests(new WeakMap()), createExtendBrokerImplementation(new WeakMap()), generateUniqueNumber, isMessagePort);
350
-
351
- const createClearIntervalFactory = (scheduledIntervalsState) => (clear) => (timerId) => {
352
- if (typeof scheduledIntervalsState.get(timerId) === 'symbol') {
353
- scheduledIntervalsState.set(timerId, null);
354
- clear(timerId).then(() => {
355
- scheduledIntervalsState.delete(timerId);
356
- });
357
- }
358
- };
359
-
360
- const createClearTimeoutFactory = (scheduledTimeoutsState) => (clear) => (timerId) => {
361
- if (typeof scheduledTimeoutsState.get(timerId) === 'symbol') {
362
- scheduledTimeoutsState.set(timerId, null);
363
- clear(timerId).then(() => {
364
- scheduledTimeoutsState.delete(timerId);
365
- });
366
- }
367
- };
368
-
369
- const createSetIntervalFactory = (generateUniqueNumber, scheduledIntervalsState) => (set) => (func, delay = 0, ...args) => {
370
- const symbol = Symbol();
371
- const timerId = generateUniqueNumber(scheduledIntervalsState);
372
- scheduledIntervalsState.set(timerId, symbol);
373
- const schedule = () => set(delay, timerId).then(() => {
374
- const state = scheduledIntervalsState.get(timerId);
375
- if (state === undefined) {
376
- throw new Error('The timer is in an undefined state.');
377
- }
378
- if (state === symbol) {
379
- func(...args);
380
- // Doublecheck if the interval should still be rescheduled because it could have been cleared inside of func().
381
- if (scheduledIntervalsState.get(timerId) === symbol) {
382
- schedule();
383
- }
384
- }
385
- });
386
- schedule();
387
- return timerId;
388
- };
389
-
390
- const createSetTimeoutFactory = (generateUniqueNumber, scheduledTimeoutsState) => (set) => (func, delay = 0, ...args) => {
391
- const symbol = Symbol();
392
- const timerId = generateUniqueNumber(scheduledTimeoutsState);
393
- scheduledTimeoutsState.set(timerId, symbol);
394
- set(delay, timerId).then(() => {
395
- const state = scheduledTimeoutsState.get(timerId);
396
- if (state === undefined) {
397
- throw new Error('The timer is in an undefined state.');
398
- }
399
- if (state === symbol) {
400
- // A timeout can be savely deleted because it is only called once.
401
- scheduledTimeoutsState.delete(timerId);
402
- func(...args);
403
- }
404
- });
405
- return timerId;
406
- };
407
-
408
- // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification.
409
- const scheduledIntervalsState = new Map([[0, null]]); // tslint:disable-line no-empty
410
- const scheduledTimeoutsState = new Map([[0, null]]); // tslint:disable-line no-empty
411
- const createClearInterval = createClearIntervalFactory(scheduledIntervalsState);
412
- const createClearTimeout = createClearTimeoutFactory(scheduledTimeoutsState);
413
- const createSetInterval = createSetIntervalFactory(generateUniqueNumber, scheduledIntervalsState);
414
- const createSetTimeout = createSetTimeoutFactory(generateUniqueNumber, scheduledTimeoutsState);
415
- const wrap = createBroker({
416
- clearInterval: ({ call }) => createClearInterval((timerId) => call('clear', { timerId, timerType: 'interval' })),
417
- clearTimeout: ({ call }) => createClearTimeout((timerId) => call('clear', { timerId, timerType: 'timeout' })),
418
- setInterval: ({ call }) => createSetInterval((delay, timerId) => call('set', { delay, now: performance.timeOrigin + performance.now(), timerId, timerType: 'interval' })),
419
- setTimeout: ({ call }) => createSetTimeout((delay, timerId) => call('set', { delay, now: performance.timeOrigin + performance.now(), timerId, timerType: 'timeout' }))
420
- });
421
- const load = (url) => {
422
- const worker = new Worker(url);
423
- return wrap(worker);
424
- };
425
-
426
- const createLoadOrReturnBroker = (loadBroker, worker) => {
427
- let broker = null;
428
- return () => {
429
- if (broker !== null) {
430
- return broker;
431
- }
432
- const blob = new Blob([worker], { type: 'application/javascript; charset=utf-8' });
433
- const url = URL.createObjectURL(blob);
434
- broker = loadBroker(url);
435
- // Bug #1: Edge up until v18 didn't like the URL to be revoked directly.
436
- setTimeout(() => URL.revokeObjectURL(url));
437
- return broker;
438
- };
439
231
  };
440
232
 
441
- // This is the minified and stringified code of the worker-timers-worker package.
442
- const worker = `(()=>{var e={455(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<s?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*s);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,u=r(i),c=a(u,i),l=t(c);e.addUniqueNumber=l,e.generateUniqueNumber=c}(t)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}(()=>{"use strict";const e=-32603,t=-32602,n=-32601,o=(e,t)=>Object.assign(new Error(e),{status:t}),s=t=>o('The handler of the method called "'.concat(t,'" returned an unexpected result.'),e),a=(t,r)=>async({data:{id:a,method:i,params:u}})=>{const c=r[i];try{if(void 0===c)throw(e=>o('The requested method called "'.concat(e,'" is not supported.'),n))(i);const r=void 0===u?c():c(u);if(void 0===r)throw(t=>o('The handler of the method called "'.concat(t,'" returned no required result.'),e))(i);const l=r instanceof Promise?await r:r;if(null===a){if(void 0!==l.result)throw s(i)}else{if(void 0===l.result)throw s(i);const{result:e,transferables:r=[]}=l;t.postMessage({id:a,result:e},r)}}catch(e){const{message:r,status:n=-32603}=e;t.postMessage({error:{code:n,message:r},id:a})}};var i=r(455);const u=new Map,c=(e,r,n)=>({...r,connect:({port:t})=>{t.start();const n=e(t,r),o=(0,i.generateUniqueNumber)(u);return u.set(o,()=>{n(),t.close(),u.delete(o)}),{result:o}},disconnect:({portId:e})=>{const r=u.get(e);if(void 0===r)throw(e=>o('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),t))(e);return r(),{result:null}},isSupported:async()=>{if(await new Promise(e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])})){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),l=(e,t,r=()=>!0)=>{const n=c(l,t,r),o=a(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},d=(e,t)=>r=>{const n=t.get(r);if(void 0===n)return Promise.resolve(!1);const[o,s]=n;return e(o),t.delete(r),s(!1),Promise.resolve(!0)},m=(e,t,r,n)=>(o,s,a)=>{const i=o+s-t.timeOrigin,u=i-t.now();return new Promise(t=>{e.set(a,[r(n,u,i,e,t,a),t])})},f=new Map,h=d(globalThis.clearTimeout,f),p=new Map,v=d(globalThis.clearTimeout,p),w=((e,t)=>{const r=(n,o,s,a)=>{const i=n-e.now();i>0?o.set(a,[t(r,i,n,o,s,a),s]):(o.delete(a),s(!0))};return r})(performance,globalThis.setTimeout),g=m(f,performance,globalThis.setTimeout,w),T=m(p,performance,globalThis.setTimeout,w);l(self,{clear:async({timerId:e,timerType:t})=>({result:await("interval"===t?h(e):v(e))}),set:async({delay:e,now:t,timerId:r,timerType:n})=>({result:await("interval"===n?g:T)(e,t,r)})})})()})();`; // tslint:disable-line:max-line-length
443
-
444
- const loadOrReturnBroker = createLoadOrReturnBroker(load, worker);
445
- const clearInterval$1 = (timerId) => loadOrReturnBroker().clearInterval(timerId);
446
- const clearTimeout$1 = (timerId) => loadOrReturnBroker().clearTimeout(timerId);
447
- const setInterval$1 = (...args) => loadOrReturnBroker().setInterval(...args);
448
- const setTimeout$1 = (...args) => loadOrReturnBroker().setTimeout(...args);
449
-
450
233
  let t$1 = class t{constructor(){this.__map={};}beforeEach(t){this.__interceptor=t;}on(t,i){const s=Array.isArray(t)?t:[t];for(const t of s){this.__map[t]=this.__map[t]||[];const s=this.__map[t];s&&s.push(i);}return this}emit(t,i,s){ void 0!==this.__interceptor?this.__interceptor(t,(()=>{this.__emit(t,i),s&&s();})):(this.__emit(t,i),s&&s());}__emit(t,i){const s=this.__map[t];if(Array.isArray(s)&&(null==s?void 0:s.length))for(const _ of s)_(i,t);this.event=i;}off(t,i){const s=this.__map[t];if(void 0!==s)if(void 0===i)delete this.__map[t];else {const t=s.findIndex((t=>t===i));s.splice(t,1);}}destroy(){this.__map={};}};
451
234
 
452
235
  const n$1="clientX",e$2="clientY",t=16,c$3="start",o$1="move",s$1="cancel",u$3="end",a$2="left",i$3="right",r$4="up",d$1="down",m$2={4:"start",5:"move",1:"end",3:"cancel"};function v$1(n){return m$2[n]}function b(n,e,t){const c={1:{0:{move:4},4:{move:5,end:1,cancel:3},5:{move:5,end:1,cancel:3}},0:{4:{move:2,end:1,cancel:3},5:{start:2,move:2,end:1,cancel:3}}}[Number(n)][e];return void 0!==c&&c[t]||0}function g$1(n){[1,3,2].includes(n.state)&&(n.state=0);}function h$3(n){return [5,1,3].includes(n)}function j(n){if(n.disabled)return n.state=0,true}function O(n,e){return Object.assign(Object.assign(Object.assign({},n),e),{state:0,disabled:false})}function p$3(n){return Math.round(100*n)/100}
@@ -712,55 +495,25 @@
712
495
  * 自动使用 Worker 执行 setTimeout
713
496
  */
714
497
  setTimeout(callback, timeout = 0) {
715
- try {
716
- return setTimeout$1(callback, timeout);
717
- }
718
- catch {
719
- return setTimeout(callback, timeout);
720
- }
498
+ return PopsCore.setTimeout(callback, timeout);
721
499
  }
722
500
  /**
723
501
  * 配合 .setTimeout 使用
724
502
  */
725
503
  clearTimeout(timeId) {
726
- try {
727
- if (timeId != null) {
728
- clearTimeout$1(timeId);
729
- }
730
- }
731
- catch {
732
- // TODO
733
- }
734
- finally {
735
- clearTimeout(timeId);
736
- }
504
+ return PopsCore.clearTimeout(timeId);
737
505
  }
738
506
  /**
739
507
  * 自动使用 Worker 执行 setInterval
740
508
  */
741
509
  setInterval(callback, timeout = 0) {
742
- try {
743
- return setInterval$1(callback, timeout);
744
- }
745
- catch {
746
- return setInterval(callback, timeout);
747
- }
510
+ return PopsCore.setInterval(callback, timeout);
748
511
  }
749
512
  /**
750
513
  * 配合 .setInterval 使用
751
514
  */
752
515
  clearInterval(timeId) {
753
- try {
754
- if (timeId != null) {
755
- clearInterval$1(timeId);
756
- }
757
- }
758
- catch {
759
- // 忽略
760
- }
761
- finally {
762
- clearInterval(timeId);
763
- }
516
+ return PopsCore.clearInterval(timeId);
764
517
  }
765
518
  /**
766
519
  * 覆盖对象中的数组新值
@@ -13465,7 +13218,7 @@
13465
13218
  },
13466
13219
  };
13467
13220
 
13468
- const version = "3.2.2";
13221
+ const version = "3.3.0";
13469
13222
 
13470
13223
  class Pops {
13471
13224
  /** 配置 */