forked from FremyCompany/css-regions-polyfill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cssregions.js
6107 lines (4864 loc) · 232 KB
/
cssregions.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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
//
// start by polyfilling caretRangeFromPoint
//
if(!document.caretRangeFromPoint) {
if (document.caretPositionFromPoint) {
document.caretRangeFromPoint = function caretRangeFromPoint(x,y) {
var r = document.createRange();
var p = document.caretPositionFromPoint(x,y);
if(p.offsetNode) {
r.setStart(p.offsetNode, p.offset);
r.setEnd(p.offsetNode, p.offset);
}
return r;
}
} else if((document.body||document.createElement('body')).createTextRange) {
//
// we may want to convert TextRange to Range
//
var TextRangeUtils = {
convertToDOMRange: function (textRange, document) {
function adoptBoundary(domRange, textRange, bStart) {
// iterate backwards through parent element to find anchor location
var cursorNode = document.createElement('a'), cursor = textRange.duplicate();
cursor.collapse(bStart);
var parent = cursor.parentElement();
do {
parent.insertBefore(cursorNode, cursorNode.previousSibling);
cursor.moveToElementText(cursorNode);
} while (cursor.compareEndPoints(bStart ? 'StartToStart' : 'StartToEnd', textRange) > 0 && cursorNode.previousSibling);
// when we exceed or meet the cursor, we've found the node
if (cursor.compareEndPoints(bStart ? 'StartToStart' : 'StartToEnd', textRange) == -1 && cursorNode.nextSibling) {
// data node
cursor.setEndPoint(bStart ? 'EndToStart' : 'EndToEnd', textRange);
domRange[bStart ? 'setStart' : 'setEnd'](cursorNode.nextSibling, cursor.text.length);
} else {
// element
domRange[bStart ? 'setStartBefore' : 'setEndBefore'](cursorNode);
}
cursorNode.parentNode.removeChild(cursorNode);
}
// validate arguments
if(!document) { document=window.document; }
// return a DOM range
var domRange = document.createRange();
adoptBoundary(domRange, textRange, true);
adoptBoundary(domRange, textRange, false);
return domRange;
},
convertFromDOMRange: function (domRange) {
function adoptEndPoint(textRange, domRange, bStart) {
// find anchor node and offset
var container = domRange[bStart ? 'startContainer' : 'endContainer'];
var offset = domRange[bStart ? 'startOffset' : 'endOffset'], textOffset = 0;
var anchorNode = DOMUtils.isDataNode(container) ? container : container.childNodes[offset];
var anchorParent = DOMUtils.isDataNode(container) ? container.parentNode : container;
// visible data nodes need a text offset
if (container.nodeType == 3 || container.nodeType == 4)
textOffset = offset;
// create a cursor element node to position range (since we can't select text nodes)
var cursorNode = domRange._document.createElement('a');
anchorParent.insertBefore(cursorNode, anchorNode);
var cursor = domRange._document.body.createTextRange();
cursor.moveToElementText(cursorNode);
cursorNode.parentNode.removeChild(cursorNode);
// move range
textRange.setEndPoint(bStart ? 'StartToStart' : 'EndToStart', cursor);
textRange[bStart ? 'moveStart' : 'moveEnd']('character', textOffset);
}
// return an IE text range
var textRange = domRange._document.body.createTextRange();
adoptEndPoint(textRange, domRange, true);
adoptEndPoint(textRange, domRange, false);
return textRange;
}
};
document.caretRangeFromPoint = function caretRangeFromPoint(x,y) {
// the accepted number of vertical backtracking, in CSS pixels
var IYDepth = 40;
// try to create a text range at the specified location
var r = document.body.createTextRange();
for(var iy=IYDepth; iy; iy=iy-4) {
var ix = x; if(true) {
try {
r.moveToPoint(ix,iy+y-IYDepth);
return TextRangeUtils.convertToDOMRange(r);
} catch(ex) {}
}
}
// if that fails, return the location just after the element located there
try {
var elem = document.elementFromPoint(x-1,y-1);
var r = document.createRange();
r.setStartAfter(elem);
return r;
} catch(ex) {
return null;
}
}
}
}
///
/// helper function for moving ranges char by char
///
Range.prototype.myMoveOneCharLeft = function() {
var r = this;
// move to the previous cursor location
if(r.endOffset > 0) {
// if we can enter into the previous sibling
var previousSibling = r.endContainer.childNodes[r.endOffset-1];
if(previousSibling && previousSibling.lastChild) {
// enter the previous sibling from its end
r.setEndAfter(previousSibling.lastChild);
} else if(previousSibling && previousSibling.nodeType==previousSibling.TEXT_NODE) { // todo: lookup value
// enter the previous text node from its end
r.setEnd(previousSibling, previousSibling.nodeValue.length);
} else {
// else move before that element
r.setEnd(r.endContainer, r.endOffset-1);
}
} else {
r.setEndBefore(r.endContainer);
}
}
Range.prototype.myMoveOneCharRight = function() {
var r = this;
// move to the previous cursor location
var max = (r.startContainer.nodeType==r.startContainer.TEXT_NODE ? r.startContainer.nodeValue.length : r.startContainer.childNodes.length)
if(r.startOffset < max) {
// if we can enter into the next sibling
var nextSibling = r.endContainer.childNodes[r.endOffset];
if(nextSibling && nextSibling.firstChild) {
// enter the next sibling from its start
r.setStartBefore(nextSibling.firstChild);
} else if(nextSibling && nextSibling.nodeType==nextSibling.TEXT_NODE && nextSibling.nodeValue!='') { // todo: lookup value
// enter the next text node from its start
r.setStart(nextSibling, 0);
} else {
// else move before that element
r.setStart(r.startContainer, r.startOffset+1);
}
} else {
r.setStartAfter(r.endContainer);
}
// shouldn't be needed but who knows...
r.setEnd(r.startContainer, r.startOffset);
}
///
/// This functions is optimized to not yield inside a word in a text node
///
Range.prototype.myMoveTowardRight = function() {
var r = this;
// move to the previous cursor location
var isTextNode = r.startContainer.nodeType==r.startContainer.TEXT_NODE;
var max = (isTextNode ? r.startContainer.nodeValue.length : r.startContainer.childNodes.length)
if(r.startOffset < max) {
// if we can enter into the next sibling
var nextSibling = r.endContainer.childNodes[r.endOffset];
if(nextSibling && nextSibling.firstChild) {
// enter the next sibling from its start
r.setStartBefore(nextSibling.firstChild);
} else if(nextSibling && nextSibling.nodeType==nextSibling.TEXT_NODE && nextSibling.nodeValue!='') { // todo: lookup value
// enter the next text node from its start
r.setStart(nextSibling, 0);
} else if(isTextNode) {
// move to the next non a-zA-Z symbol
var currentText = r.startContainer.nodeValue;
var currentOffset = r.startOffset;
var currentLetter = currentText[currentOffset++];
while(currentOffset < max && /^\w$/.test(currentLetter)) {
currentLetter = currentText[currentOffset++];
}
r.setStart(r.startContainer, currentOffset);
} else {
// else move before that element
r.setStart(r.startContainer, r.startOffset+1);
}
} else {
r.setStartAfter(r.endContainer);
}
// shouldn't be needed but who knows...
r.setEnd(r.startContainer, r.startOffset);
}
Range.prototype.myMoveEndOneCharLeft = function() {
var r = this;
// move to the previous cursor location
if(r.endOffset > 0) {
// if we can enter into the previous sibling
var previousSibling = r.endContainer.childNodes[r.endOffset-1];
if(previousSibling && previousSibling.lastChild) {
// enter the previous sibling from its end
r.setEndAfter(previousSibling.lastChild);
} else if(previousSibling && previousSibling.nodeType==previousSibling.TEXT_NODE) { // todo: lookup value
// enter the previous text node from its end
r.setEnd(previousSibling, previousSibling.nodeValue.length);
} else {
// else move before that element
r.setEnd(r.endContainer, r.endOffset-1);
}
} else {
r.setEndBefore(r.endContainer);
}
}
Range.prototype.myMoveEndOneCharRight = function() {
var r = this;
// move to the previous cursor location
var max = (r.endContainer.nodeType==r.endContainer.TEXT_NODE ? r.endContainer.nodeValue.length : r.endContainer.childNodes.length)
if(r.endOffset < max) {
// if we can enter into the next sibling
var nextSibling = r.endContainer.childNodes[r.endOffset];
if(nextSibling && nextSibling.firstChild) {
// enter the next sibling from its start
r.setEndBefore(nextSibling.firstChild);
} else if(nextSibling && nextSibling.nodeType==nextSibling.TEXT_NODE) { // todo: lookup value
// enter the next text node from its start
r.setEnd(nextSibling, 0);
} else {
// else move before that element
r.setEnd(r.endContainer, r.endOffset+1);
}
} else {
r.setEndAfter(r.endContainer);
}
}
//
// Get the *real* bounding client rect of the range
// { therefore we need to fix some browser bugs... }
//
Range.prototype.myGetSelectionRect = function() {
// get the browser's claimed rect
var rect = this.getBoundingClientRect();
// HACK FOR ANDROID BROWSER AND OLD WEBKIT
if(!rect) {
rect={top:0,right:0,bottom:0,left:0,width:0,height:0};
}
// if the value seems wrong... (some browsers don't like collapsed selections)
if(this.collapsed && rect.top===0 && rect.bottom===0) {
// select one char and infer location
var clone = this.cloneRange(); var collapseToLeft=false; clone.collapse(false);
// the case where no char before is tricky...
if(clone.startOffset==0) {
// let's move on char to the right
clone.myMoveTowardRight();
collapseToLeft=true;
// note: some browsers don't like selections
// that spans multiple containers, so we will
// iterate this process until we have one true
// char selected
clone.setStart(clone.endContainer, 0);
} else {
// else, just select the char before
clone.setStart(this.startContainer, this.startOffset-1);
collapseToLeft=false;
}
// get some real rect
var rect = clone.myGetSelectionRect();
// compute final value
if(collapseToLeft) {
return {
left: rect.left,
right: rect.left,
width: 0,
top: rect.top,
bottom: rect.bottom,
height: rect.height
}
} else {
return {
left: rect.right,
right: rect.right,
width: 0,
top: rect.top,
bottom: rect.bottom,
height: rect.height
}
}
} else {
return rect;
}
}
// not sure it's needed but still
if(!window.Element) window.Element=window.HTMLElement;
if(!window.Node) window.Node = {};
// make getBCR working on text nodes & stuff
Node.getBoundingClientRect = function getBoundingClientRect(element) {
if (element.getBoundingClientRect) {
var rect = element.getBoundingClientRect();
} else {
var range = document.createRange();
range.selectNode(element);
var rect = range.getBoundingClientRect();
}
// HACK FOR ANDROID BROWSER AND OLD WEBKIT
if(!rect) {
rect={top:0,right:0,bottom:0,left:0,width:0,height:0};
}
return rect;
};
// make getCR working on text nodes & stuff
Node.getClientRects = function getClientRects(firstChild) {
if (firstChild.getBoundingClientRect) {
return firstChild.getClientRects();
} else {
var range = document.createRange();
range.selectNode(firstChild);
return range.getClientRects();
}
};
// fix for IE (contains fails for text nodes...)
Node.contains = function contains(parentNode,node) {
if(node.nodeType != 1) {
if(!node.parentNode) return false;
return node.parentNode==parentNode || parentNode.contains(node.parentNode);
} else {
return parentNode.contains(node);
}
}
//
// get the bounding rect of the selection, including the bottom padding/marging of the previous element if required
// { this is a special version for breaking algorithms that do not want to miss the previous element real size }
//
Range.prototype.myGetExtensionRect = function() {
// this function returns the selection rect
// but does take care of taking in account
// the bottom-{padding/border} of the previous
// sibling element, to detect overflow points
// more accurately
var rect = this.myGetSelectionRect();
var previousSibling = this.endContainer.childNodes[this.endOffset-1];
if(previousSibling) {
// correct with the new take
var prevSibRect = Node.getBoundingClientRect(previousSibling);
var adjustedBottom = Math.max(rect.bottom,prevSibRect.bottom);
if(adjustedBottom == rect.bottom) return rect;
return {
left: rect.left,
right: rect.right,
width: rect.width,
top: rect.top,
bottom: adjustedBottom,
height: adjustedBottom - rect.top
};
} else if(this.bottom==0 && this.endContainer.nodeType === 3) {
// note that if we are in a text node,
// we may want to cover all the previous
// text in the node to avoid whitespace
// related bugs
var onlyWhiteSpaceBefore = /^(\s|\n)*$/.test(this.endContainer.nodeValue.substr(0,this.endOffset));
if(onlyWhiteSpaceBefore) {
// if we are in the fucking whitespace land, return first line
var prevSibRect = Node.getClientRects(this.endContainer)[0];
return prevSibRect;
} else {
// otherwhise, let's rely on previous chars
var auxiliaryRange = this.cloneRange();
auxiliaryRange.setStart(this.endContainer,0);
// correct with the new take
var prevSibRect = auxiliaryRange.getBoundingClientRect();
var adjustedBottom = Math.max(rect.bottom,prevSibRect.bottom);
return {
left: rect.left,
right: rect.right,
width: rect.width,
top: rect.top,
bottom: adjustedBottom,
height: adjustedBottom - rect.top
};
}
} else {
return rect;
}
}
"use strict";
//
// some code for console polyfilling
//
if(!window.console) {
window.console = {
backlog: '',
log: function(x) { this.backlog+=x+'\n'; if(window.debug) alert(x); },
dir: function(x) { try {
function elm(e) {
if(e.innerHTML) {
return {
tagName: e.tagName,
className: e.className,
id: e.id,
innerHTML: e.innerHTML.substr(0,100)
}
} else {
return {
nodeName: e.nodeName,
nodeValue: e.nodeValue
}
}
};
function jsonify(o){
var seen=[];
var jso=JSON.stringify(o, function(k,v){
if (typeof v =='object') {
if ( !seen.indexOf(v) ) { return '__cycle__'; }
if ( v instanceof window.Node) { return elm(v); }
seen.push(v);
} return v;
});
return jso;
};
this.log(jsonify(x));
} catch(ex) { this.log(x) } },
warn: function(x) { this.log(x) }
};
window.onerror = function() {
console.log([].slice.call(arguments,0).join("\n"))
};
}
window.cssConsole = {
enabled: (!!window.debug), warnEnabled: (true),
log: function(x) { if(this.enabled) console.log(x) },
dir: function(x) { if(this.enabled) console.dir(x) },
warn: function(x) { if(this.warnEnabled) console.warn(x) },
}
//
// some other basic om code
//
var basicObjectModel = {
//
// the following functions are about event cloning
//
cloneMouseEvent: function cloneMouseEvent(e) {
var evt = document.createEvent("MouseEvent");
evt.initMouseEvent(
e.type,
e.canBubble||e.bubbles,
e.cancelable,
e.view,
e.detail,
e.screenX,
e.screenY,
e.clientX,
e.clientY,
e.ctrlKey,
e.altKey,
e.shiftKey,
e.metaKey,
e.button,
e.relatedTarget
);
return evt;
},
cloneKeyboardEvent: function cloneKeyboardEvent(e) {
// TODO: this doesn't work cross-browswer...
// see https://gist.github.com/termi/4654819/ for the huge code
return basicObjectModel.cloneCustomEvent(e);
},
cloneCustomEvent: function cloneCustomEvent(e) {
var ne = document.createEvent("CustomEvent");
ne.initCustomEvent(e.type, e.canBubble||e.bubbles, e.cancelable, "detail" in e ? e.detail : e);
for(var prop in e) {
try {
if(e[prop] != ne[prop] && e[prop] != e.target) {
try { ne[prop] = e[prop]; }
catch (ex) { Object.defineProperty(ne,prop,{get:function() { return e[prop]} }) }
}
} catch(ex) {}
}
return ne;
},
cloneEvent: function cloneEvent(e) {
if(e instanceof MouseEvent) {
return basicObjectModel.cloneMouseEvent(e);
} else if(e instanceof KeyboardEvent) {
return basicObjectModel.cloneKeyboardEvent(e);
} else {
return basicObjectModel.cloneCustomEvent(e);
}
},
//
// allows you to drop event support to any class easily
//
EventTarget: {
implementsIn: function(eventClass, static_class) {
if(!static_class && typeof(eventClass)=="function") eventClass=eventClass.prototype;
eventClass.dispatchEvent = basicObjectModel.EventTarget.prototype.dispatchEvent;
eventClass.addEventListener = basicObjectModel.EventTarget.prototype.addEventListener;
eventClass.removeEventListener = basicObjectModel.EventTarget.prototype.removeEventListener;
},
prototype: {}
}
};
basicObjectModel.EventTarget.prototype.addEventListener = function(eventType,f) {
if(!this.eventListeners) this.eventListeners=[];
var ls = (this.eventListeners[eventType] || (this.eventListeners[eventType]=[]));
if(ls.indexOf(f)==-1) {
ls.push(f);
}
}
basicObjectModel.EventTarget.prototype.removeEventListener = function(eventType,f) {
if(!this.eventListeners) this.eventListeners=[];
var ls = (this.eventListeners[eventType] || (this.eventListeners[eventType]=[])), i;
if((i=ls.indexOf(f))!==-1) {
ls.splice(i,1);
}
}
basicObjectModel.EventTarget.prototype.dispatchEvent = function(event_or_type) {
if(!this.eventListeners) this.eventListeners=[];
// abort quickly when no listener has been set up
if(typeof(event_or_type) == "string") {
if(!this.eventListeners[event_or_type] || this.eventListeners[event_or_type].length==0) {
return;
}
} else {
if(!this.eventListeners[event_or_type.type] || this.eventListeners[event_or_type.type].length==0) {
return;
}
}
// convert the event
var event = event_or_type;
function setUpPropertyForwarding(e,ee,key) {
Object.defineProperty(ee,key,{
get:function() {
var v = e[key];
if(typeof(v)=="function") {
return v.bind(e);
} else {
return v;
}
},
set:function(v) {
e[key] = v;
}
});
}
function setUpTarget(e,v) {
try { Object.defineProperty(e,"target",{get:function() {return v}}); }
catch(ex) {}
finally {
if(e.target !== v) {
var ee = Object.create(Object.getPrototypeOf(e));
ee = setUpTarget(ee,v);
for(key in e) {
if(key != "target") setUpPropertyForwarding(e,ee,key);
}
return ee;
} else {
return e;
}
}
}
// try to set the target
if(typeof(event)=="object") {
try { event=setUpTarget(event,this); } catch(ex) {}
} else if(typeof(event)=="string") {
event = document.createEvent("CustomEvent");
event.initCustomEvent(event_or_type, /*canBubble:*/ true, /*cancelable:*/ false, /*detail:*/this);
try { event=setUpTarget(event,this); } catch(ex) {}
} else {
throw new Error("dispatchEvent expect an Event object or a string containing the event type");
}
// call all listeners
var ls = (this.eventListeners[event.type] || (this.eventListeners[event.type]=[]));
for(var i=ls.length; i--;) {
try {
ls[i](event);
} catch(ex) {
setImmediate(function() { throw ex; });
}
}
return event.isDefaultPrevented;
}
"use strict";
(function() {
//
// polyfill setImmediate
//
window.setImmediate = window.setImmediate || function(f) {
setTimeout(f, 0);
};
window.clearImmediate = window.clearImmediate || window.clearTimeout;
//
// polyfill requestAnimationFrame
//
window.requestAnimationFrame = window.requestAnimationFrame || function(f) {
return setTimeout(function() {
f(+new Date());
}, 16);
};
window.cancelAnimationFrame = window.cancelAnimationFrame || window.clearTimeout;
//
// polyfill performance.now()
//
if(window.performance && window.performance.now) {
var now = function() { return performance.now(); }
} else if(Date.now) {
var now = function() { return Date.now(); }
} else {
var now = function() { return +new Date(); }
}
//
// Encapsulate a task
//
function Task(action) {
this.call = action;
}
//
// Encapsulate task priority logic
//
function TaskScheduler(parent) {
this.isRunning = false;
this.isScheduledNow = false;
this.taskQueue = [];
this.delayedTasks = 0;
this.childSchedulers = [];
this.parentScheduler = parent;
if(parent) { parent.childSchedulers.push(this); }
var This = this;
This.tryRun = function() {
if(This.parentScheduler) {
This.parentScheduler.tryRun();
} else {
This.run();
}
}
This.run = function() {
This.isRunning = true;
// calling code should not face scheduler errors
try {
//
// walk through all tasks
//
if(This.taskQueue.length !== 0) {
var task; while(task=This.taskQueue.shift()) {
// run the task
// (the loop should not break if a task fails)
try { task.call(); }
catch(ex) { setImmediate(function() { throw ex; }) }
}
}
//
// let child schedulers execute if no task is pending
//
if(This.delayedTasks === 0) {
for(var i=0; i<This.childSchedulers.length; i++) {
// run the scheduler
// (the loop should not break if a scheduler fails)
try { This.childSchedulers[i].run(); }
catch(ex) { setImmediate(function() { throw ex; }) }
}
}
//
// execute new immediates, if any
//
if(This.taskQueue.length !== 0) {
This.run();
}
} catch(ex) { setImmediate(function() { throw ex; }) }
This.isRunning = false;
}
}
TaskScheduler.prototype.pushTask = function(f) {
// push the task
this.taskQueue.push(f);
// ensure the scheduler will run soon
this.scheduleNow();
};
TaskScheduler.prototype.pushDelayedTask = function(f, scheduler) {
// ask for a delayed execution
var This = this;
var result = scheduler(function() {
// push the task
This.pushTask(f);
This.delayedTasks--;
// empty the queue
This.scheduleNow();
});
// record the future task
this.delayedTasks++;
// return scheduler-relative info
return result;
}
// aliases for common web functions
TaskScheduler.prototype.setImmediate = TaskScheduler.prototype.pushTask;
TaskScheduler.prototype.setTimeout = function(f,d) {
this.pushDelayedTask(f, function(f) { setTimeout(f,d) })
}
TaskScheduler.prototype.requestAnimationFrame = function(f,d) {
this.pushDelayedTask(f, requestAnimationFrame);
}
TaskScheduler.prototype.scheduleNow = function() {
// avoid creating multiple running
// version of the scheduler
if(this.isRunning) return;
if(this.isScheduledNow) return;
// schedule a new run
setImmediate(this.tryRun);
}
window.JSTaskScheduler = TaskScheduler;
}());
//
// note: this file is based on Tab Atkins's CSS Parser
// please include him (@tabatkins) if you open any issue for this file
//
"use strict";
var cssSyntax = {
tokenize: function(string) {},
parse: function(tokens) {},
parseCSSValue: function(bestValue, stringOnly) {
if(stringOnly) {
var result = /*bestValue ? cssSyntax.parse("*{a:"+bestValue+"}").value[0].value[0].value : */new cssSyntax.TokenList();
result.asCSSString = bestValue; // optimize conversion
return result;
} else {
var result = bestValue ? cssSyntax.parse("*{a:"+bestValue+"}").value[0].value[0].value : new cssSyntax.TokenList();
result.asCSSString = bestValue; // optimize conversion
return result;
}
}
};
//
// css tokenizer
//
(function() {
var between = function (num, first, last) { return num >= first && num <= last; }
function digit(code) { return between(code, 0x30,0x39); }
function hexdigit(code) { return digit(code) || between(code, 0x41,0x46) || between(code, 0x61,0x66); }
function uppercaseletter(code) { return between(code, 0x41,0x5a); }
function lowercaseletter(code) { return between(code, 0x61,0x7a); }
function letter(code) { return uppercaseletter(code) || lowercaseletter(code); }
function nonascii(code) { return code >= 0xa0; }
function namestartchar(code) { return letter(code) || nonascii(code) || code == 0x5f; }
function namechar(code) { return namestartchar(code) || digit(code) || code == 0x2d; }
function nonprintable(code) { return between(code, 0,8) || between(code, 0xe,0x1f) || between(code, 0x7f,0x9f); }
function newline(code) { return code == 0xa || code == 0xc; }
function whitespace(code) { return newline(code) || code == 9 || code == 0x20; }
function badescape(code) { return newline(code) || isNaN(code); }
// Note: I'm not yet acting smart enough to actually handle astral characters.
var maximumallowedcodepoint = 0x10ffff;
// Add support for token lists (superclass of array)
var TokenList = cssSyntax.TokenList = function TokenList() {
var array = [];
array.toCSSString=cssSyntax.TokenListToCSSString;
return array;
}
var TokenListToCSSString = cssSyntax.TokenListToCSSString = function TokenListToCSSString(sep) {
if(sep) {
return this.map(function(o) { return o.toCSSString(); }).join(sep);
} else {
return this.asCSSString || (this.asCSSString = (
this.map(function(o) { return o.toCSSString(); }).join("/**/")
.replace(/( +\/\*\*\/ *| * | *\/\*\*\/ +)/g," ")
.replace(/( +\/\*\*\/ *| * | *\/\*\*\/ +)/g," ")
.replace(/(\!|\:|\;|\@|\.|\,|\*|\=|\&|\\|\/|\<|\>|\[|\{|\(|\]|\}|\)|\|)\/\*\*\//g,"$1")
.replace(/\/\*\*\/(\!|\:|\;|\@|\.|\,|\*|\=|\&|\\|\/|\<|\>|\[|\{|\(|\]|\}|\)|\|)/g,"$1")
));
}
}