-
Notifications
You must be signed in to change notification settings - Fork 0
/
taskq.js
615 lines (612 loc) · 18.9 KB
/
taskq.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
(function (root,factory) {
if(typeof root.window !== "object" && typeof root.document !== "object" ) {
var __f = function(){};
var __o = {};
root.window = {
requestAnimationFrame: __f,
addEventListener: __f,
document: {
getElementById: __f,
querySelector: __f,
querySelectorAll: __f,
elementFromPoint: __f,
head: __o,
body: __o
}
};
}
if (typeof define === "function" && define.amd) {
define(factory);
} else if (typeof exports === "object") {
module.exports = factory(root.window,root.window.document);
} else {
factory(root,root.document);
}
}(this,function(window,document){
//version
var version = "2.3.7";
//a salt for getters/setters
var salt = Math.random();
//current script
var oScript = document.querySelector("script[src*='taskq.js']"),
name = (oScript && oScript.getAttribute("global-name")) || "taskq",
//the minimum desired pause between pushed function execution
minPause = (oScript && +oScript.getAttribute("data-min-pause")) || 0,
backSteps = (oScript && +oScript.getAttribute("data-backsteps")) || 3,
stepLimit = (oScript && +oScript.getAttribute("data-step-limit")) || 100,
taskq = (window[name] = new function (){
//internal variables to keep track of pushed functions and exports
var tasks = [],
exports = {},
immediateTasks = [],
scriptQueue = [],
_random = Math.random(),
_paused = false,
_running = false;
Object.defineProperties(
this,
{
paused: {
configurable: false,
enumerable: false,
get: function(){
return _paused;
},
set: function(obj) {
if (typeof obj !== "object" || obj.hash !== _random) {
console.log("You cannot set this manually");
return false;
} else if (typeof obj.value === "boolean") {
_paused = obj.value;
return true;
} else {
return false;
}
}
},
pause: {
configurable: false,
enumerable: false,
get: function(){
var retValue = !_paused;
return ((this.paused = {hash:_random, value: true}),retValue);
}
},
resume: {
configurable: false,
enumerable: false,
get: function() {
var retValue = _paused;
return ((this.paused = {hash:_random, value: false}),retValue);
}
},
running: {
configurable: false,
enumerable: false,
get: function(){
return _running;
},
set: function(obj) {
if (typeof obj !== "object" || obj.hash !== salt) {
console.log("You cannot set this manually");
return false;
} else if (typeof obj.value === "boolean") {
_running = obj.value;
return true;
} else {
return false;
}
}
}
}
);
/*taskq resonates between 3 stages. If taskq.onload is called,
scriptLoading is true and scriptComplete is false, once script is loaded,
scriptLoading is false and scriptLoaded is true, once all pushed
functions execute and thens are consumed, scriptComplete is true*/
this.scriptLoading = false;
this.scriptLoaded = false;
this.scriptComplete = true;
/*clear main thread or the immediate thread*/
this.flush = function(origin){
if (origin === "main") {
tasks = [];
exports = {};
} else if (origin === "script") {
immediateTasks = [];
}
return this;
};
/*export variables with alias*/
this.export = function(f,name){
name = name || "default";
exports[name] = f;
return this;
};
/*if onload is encountered, push the immediateTasks,
otherwise push to main thread*/
this.push = function(f){
if(this.scriptLoading || this.scriptLoaded) {
//console.log("pushing this to immediate queue");
immediateTasks.push(f);
} else {
tasks.push(f);
}
return this;
};
/*perform pushed functions*/
this.perform = function(){
this.execute(
this.sortTasks(tasks,true),
exports,
{
origin:"main"
}
);
return this;
};
//If native Promise or polyfill available use that, otherwise fallback to rAF
this.promise = function(){
if (this.promise.promise) {
return this.promise.promise;
} else if (window.Promise && Promise.constructor === Function) {
//console.log("using promise");
return this.promise.promise = Promise.resolve();
} else {
//console.log("using rAF");
return this.promise.promise = new this.__promise;
}
};
/*set the minimum amount of time to pass between execution of
functions in the main thread*/
this.minPause = minPause;
/*taskq.load returns a thennable object,
for more refer to readme.md*/
this.thenable = function (that){
var queue = [],
_this = this,
resolverValue = undefined,
resolverIsFrozen = false,
resolverIsInitiated = false,
_catch = function(){};
this.errored = false;
this.rejected = false;
this.catch = function(f){
if (typeof f === "function") {
_catch = f;
}
return this;
};
this.target = that;
this.status = {complete:false};
this.counter = 0;
this.next = undefined;
this.resolver = Object.defineProperties(
function(value){
if(resolverIsFrozen) {
return false;
}
if (resolverValue = !!value) {
_this.counter--;
_this.next = true;
} else {
_this.rejected = true;
}
return resolverIsFrozen = true;
},
{
init: {
configurable:false,
enumerable:false,
get:function(){
return resolverIsInitiated = true;
}
},
value: {
configurable:false,
enumerable:false,
get:function(){
return resolverValue;
}
}
}
);
this.then = function(f){
this.counter++;
queue.push(function(){
that.promise().then(function(){
f(_this.resolver);
if(!resolverIsInitiated) {
_this.counter--;
_this.next = true;
}
});
});
return this;
};
/*Starts executing the pushed functions within the
immediate tasks. Upon completion 'status.complete' will be set to
true and impender can start executing then clauses*/
this.execute = function(){
that.execute (
immediateTasks.length && that.sortTasks(immediateTasks),
exports,
{
origin:"script",
status:_this.status,
flush:true
}
);
return this;
};
/*When a thennable is created, its impender is immediately active,
once status is complete, it starts executing the then clauses. When
all then clauses are finished, the next dynamic load, if any is
processed*/
this.impender = function(){
if (!that.running) {
that.running = {hash:salt, value: true};
}
if (
!_paused
&& (
_this.errored
|| _this.rejected
|| (!_this.counter && _this.status.complete)
)
){
that.running = {hash:salt, value: false};
that.scriptLoaded = false;
that.scriptComplete = true;
if (_this.rejected) {
_catch();
}
if (scriptQueue.length) {
scriptQueue.shift()();
}
return;
}
if (
!_paused
&& (
_this.status.complete
&& (
_this.next === undefined
|| _this.next
)
)
){
resolverIsInitiated = false;
resolverIsFrozen = false;
resolverValue = undefined;
_this.next = false;
queue.shift()();
}
window.requestAnimationFrame(_this.impender);
};
this.impender();
};
/*If another load is encountered before current dynamic load
and its then clauses are processed, it is pushed to the
scriptQueue*/
this.queuePacker = function(src,container){
var thens = [],
that = this;
scriptQueue.push(function(){
thens.forEach(function(d,i){this.then(d);},that.load(src,container));
});
return new function(){
this.then = function(f){
thens.push(f);
return this;
};
};
};
}),
prt = taskq.constructor.prototype;
prt.emptyArr = [];
prt.version = function(){
return version;
};
/*This internally called method is either passed the tasks array or
the immediateTasks array. Sorts the passed array and returns a shallow copy*/
prt.sortTasksUnstable = function(tasks,base,keywordStart,keywordEnd,tasksMap){
//series of schwartzian transform(s) for sorting, KSC = keywordStartCoefficient, KEC = keywordEndCoefficient
return tasks.map(function(d,i){
return [d,d._taskqId,d._taskqWaitFor];
}).sort(function(a,b){
var aId = a[1],
bId = b[1],
aL = a[2] || prt.emptyArr,
bL = b[2] || prt.emptyArr,
a0 = a[0],
b0 = b[0],
aKSC = a0._taskqKSC === undefined ? a0._taskqKSC = !~keywordStart.indexOf(aId) : a0._taskqKSC,
aKEC = a0._taskqKEC === undefined ? a0._taskqKEC = !!~keywordEnd.indexOf(aId) : a0._taskqKEC,
bKSC = b0._taskqKSC === undefined ? b0._taskqKSC = !~keywordStart.indexOf(bId) : b0._taskqKSC,
bKEC = b0._taskqKEC === undefined ? b0._taskqKEC = !!~keywordEnd.indexOf(bId) : b0._taskqKEC,
aC = aKSC && (aKEC || aL.some(function(d,i){return d === bId || (tasksMap[d] && tasksMap[d]._taskqWaitFor && ~tasksMap[d]._taskqWaitFor.indexOf(bId));})),
bC = bKSC && (bKEC || bL.some(function(d,i){return d === aId || (tasksMap[d] && tasksMap[d]._taskqWaitFor && ~tasksMap[d]._taskqWaitFor.indexOf(aId));}));
return aC*base + aL.length - bC*base - bL.length;
}).map(function(d,i){
return d[0];
});
};
prt.sortTasks = function(tasks,report){
var start = Date.now(),
steps = 1,
length = tasks.length,
//About max 2^16 tasks
base = Math.max.apply(null,tasks.map(function(d,i){return (d._taskqWaitFor || prt.emptyArr).length;})) + 1,
//regex could do also - executed first
keywordStart = ["start","init","begin","loadstart","loadStart"],
//keywordEnd = ["end","defer","finish","loadend","loadEnd"];
keywordEnd = ["end","defer","finish","loadend","loadEnd"],
//reverse Map, id to function
tasksMap = tasks.reduce(function(ac,d,i,a){d._taskqId && (ac[d._taskqId] = d); return ac;},{});
tasks = this.sortTasksUnstable(tasks,base,keywordStart,keywordEnd,tasksMap);
//chrome sort uses quicksort for arrays of length > 10, I use windows of 9 to force stable sort.
outer:
for(
var i = 0,a = tasks[i],aId = a._taskqId,aL = a._taskqWaitFor || prt.emptyArr,aKSC,aKEC;
i<length;
++i,a = tasks[i],aId = a && a._taskqId,aL = a && (a._taskqWaitFor || prt.emptyArr)
){
if(steps > stepLimit) {
console.log("Max step limit of " + stepLimit + " step(s) has been reached. Terminating sort.");
break outer;
}
aKSC = a._taskqKSC === undefined ? a._taskqKSC = !~keywordStart.indexOf(aId) : a._taskqKSC;
aKEC = a._taskqKEC === undefined ? a._taskqKEC = !!~keywordEnd.indexOf(aId) : a._taskqKEC;
inner:
for(var j = i+1;j<length;++j) {
var b = tasks[j],
bId = b._taskqId,
bL = b._taskqWaitFor || prt.emptyArr,
bKSC = b._taskqKSC === undefined ? b._taskqKSC = !~keywordStart.indexOf(bId) : b._taskqKSC,
bKEC = b._taskqKEC === undefined ? b._taskqKEC = !!~keywordEnd.indexOf(bId) : b._taskqKEC,
aC = aKSC && (aKEC || aL.some(function(d,i){return d === bId || (tasksMap[d] && tasksMap[d]._taskqWaitFor && ~tasksMap[d]._taskqWaitFor.indexOf(bId));})),
bC = bKSC && (bKEC || bL.some(function(d,i){return d === aId || (tasksMap[d] && tasksMap[d]._taskqWaitFor && ~tasksMap[d]._taskqWaitFor.indexOf(aId));}));
if (!this.areCircular(a,b,tasksMap) && (aC*base + this.dependencyIsSubset(a,b,tasksMap)*aL.length - bC*base - bL.length > 0)) {
tasks[i] = b;
tasks[j] = a;
var windowStart = Math.max(0,j-8);
var windowEnd = Math.min(length,Math.max(0,j-8)+9);
tasks = (tasks.slice(0,windowStart).concat(this.sortTasksUnstable(tasks.slice(windowStart,windowEnd),base,keywordStart,keywordEnd,tasksMap)).concat(tasks.slice(windowEnd)));
++steps;
//--i;
i = Math.max(0,(i -= backSteps));
break inner;
}
}
}
report ? console.log("Semi stable sorting done in: "+ steps + " steps, ~" +(Date.now()-start)+"ms") : void(0);
//console.log(tasks.slice());
this.clearDependencyLedger(tasks);
return tasks;
};
/*requestAnimationFrame (rAF) is used instead of Promise wrapper in older browsers (ie9+)*/
prt.__promise = function(){
this.then = function(f) {
window.requestAnimationFrame(f);
return this;
};
};
//execute the pushed & sorted functions one by one
prt.execute = function(sorted,exports,options){
if (!this.running) {
this.running = {hash:salt, value: true};
}
if (!sorted.length) {
//console.log("last routine!");
options.flush === undefined || options.flush ? this.flush(options.origin) : void(0);
options.status ? options.status.complete = true : void(0);
this.running = {hash:salt, value: false};
return;
}
var that = this,
promise = this.promise(),
time = Date.now();
promise = promise.then(function(res){
window.requestAnimationFrame(function(){
var f = sorted.shift(),
diff = 0;
if(typeof f === "function") {
var captured = (/function\s*\w*\s*\(((?:\s*\w+\s*\,?\s*)*)\)\s*\{/).exec(f.toString());
f.apply(
exports[f._taskqScope] || window,
captured
? captured[1]
.replace(/\s+/g,"")
.split(",")
.map(function(d,i){return exports[d];})
: void(0)
);
} else {
console.log("not a function ref");
}
//control the frequency of function execution
if (
!that.paused
&& (
(diff = Date.now() - time) >= that.minPause
&& (
(options.origin === "main" && that.scriptComplete)
|| options.origin === "script"
)
)
) {
that.execute(sorted,exports,options);
} else {
that.wait(that.minPause - diff,sorted,exports,options);
}
});
});
};
//wait until minimum required delay to honor minPause, then resume execution
prt.wait = function(delay,sorted,exports,options) {
var that = this,
startTime = 0,
tick = function(t){
startTime = startTime || t;
if (
!that.paused
&& (
delay + startTime - t <= 0
&& (
(options.origin === "main" && that.scriptComplete)
|| options.origin === "script"
)
)
) {
that.execute(sorted,exports,options);
} else {
window.requestAnimationFrame(tick);
}
};
window.requestAnimationFrame(tick);
};
/*Load scripts asynchronously and keep DOM clean*/
prt.load = function(src,container){
if(!this.scriptComplete) {
return this.queuePacker(src,container);
}
container = container || document.head;
var that = this,
oldNode = container.querySelector("script[src*='" + src.replace(/\?.*$/gi,"") + "']"),
script = document.createElement("script"),
thenable = (new this.thenable(that));
this.scriptLoading = true;
this.scriptComplete = false;
script.async = true;
script.onload = function(){
that.scriptLoading = false;
that.scriptLoaded = true;
thenable.execute();
};
script.onerror = function(){
thenable.errored = true;
};
script.src = src;
if (oldNode) {
container.replaceChild(script,oldNode);
} else {
container.appendChild(script);
}
return thenable;
};
prt.dependencyIsSubset = function(a,b,tasksMap,checked){
a._taskqDependencyIsSubset = a._taskqDependencyIsSubset || [];
a._taskqDependencyIsNotSubset = a._taskqDependencyIsNotSubset || [];
if(~a._taskqDependencyIsSubset.indexOf(b)) {
return true;
} else if (~a._taskqDependencyIsNotSubset.indexOf(b)) {
return false;
}
var checked = checked || [],
aL = a._taskqWaitFor || prt.emptyArr,
bL = b._taskqWaitFor || prt.emptyArr;
if(!aL.length){
a._taskqDependencyIsNotSubset.push(b);
return false;
} else if (!bL.length) {
a._taskqDependencyIsNotSubset.push(b);
checked.push(b);
return false;
} else if (~checked.indexOf(b)) {
return;
} else if (!aL.map(function(d,i){return bL.indexOf(d);}).some(function(d,i){return !~d;})) {
a._taskqDependencyIsSubset.push(b);
checked.push(b);
return true;
} else {
var result = bL.map(function(d,i){
return tasksMap[d] && !this.areCircular(b,tasksMap[d],tasksMap) && this.dependencyIsSubset(a,tasksMap[d],tasksMap,checked);
},this).some(function(d,i){
return d === true;
});
if (result) {
a._taskqDependencyIsSubset.push(b);
} else {
a._taskqDependencyIsNotSubset.push(b);
}
return result;
}
};
prt.dependsOn = function(a,b,tasksMap,checked){
a._taskqDependsOn = a._taskqDependsOn || [];
a._taskqNotDependsOn = a._taskqNotDependsOn || [];
if(~a._taskqDependsOn.indexOf(b)) {
return true;
} else if (~a._taskqNotDependsOn.indexOf(b)) {
return false;
}
var aL = a._taskqWaitFor || prt.emptyArr;
if(checked === undefined && (checked = []) && !aL.length) {
a._taskqNotDependsOn.push(b);
//checked.push(b);
return false;
} else if (~checked.indexOf(b)) {
return;
} else if (~aL.map(function(d,i){return tasksMap[d];}).indexOf(b)) {
a._taskqDependsOn.push(b);
checked.push(b);
return true;
} else {
var result = aL.map(function(d,i){
return tasksMap[d] && !this.areCircular(a,tasksMap[d],tasksMap) && this.dependsOn(tasksMap[d],b,tasksMap,checked);
},this).some(function(d,i){
return d === true;
});
if (result) {
a._taskqDependsOn.push(b);
} else {
a._taskqNotDependsOn.push(b);
}
return result;
}
};
prt.areCircular = function(a,b,tasksMap) {
a._taskqCircular = a._taskqCircular || [];
a._taskqNotCircular = a._taskqNotCircular || [];
b._taskqCircular = b._taskqCircular || [];
b._taskqNotCircular = b._taskqNotCircular || [];
if (~a._taskqCircular.indexOf(b)){
return true;
} else if (~a._taskqNotCircular.indexOf(b)) {
return false;
}
var result = this.dependsOn(a,b,tasksMap) && this.dependsOn(b,a,tasksMap);
if (result) {
a._taskqCircular.push(b);
b._taskqCircular.push(a);
console.log(
"Circular dependency detected, consider revising "
+ (a._taskqId || a.toString().slice(0,30))
+ " and "
+ (b._taskqId || b.toString().slice(0,30))
);
} else {
a._taskqNotCircular.push(b);
b._taskqNotCircular.push(a);
}
return result;
};
prt.clearDependencyLedger = function(tasks){
var that = this;
tasks.forEach(function(d,i){
that.deleteEnum(d,this);
},["_taskqDependencyIsSubset","_taskqDependencyIsNotSubset","_taskqDependsOn","_taskqNotDependsOn","_taskqCircular","_taskqNotCircular"]);
return this;
};
prt.deleteEnum = function(obj,propArr){
obj && typeof obj === "object" && propArr instanceof Array && propArr.forEach(function(d,i){
delete obj[d];
});
return this;
};
window.addEventListener("load",function(){
taskq.perform();
},false);
return taskq;
}));