-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblaze.js
3581 lines (3146 loc) · 116 KB
/
blaze.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
module.exports = function(Meteor,jQuery) {
var AttributeHandler, makeAttributeHandler, ElementAttributesUpdater, toObjectLiteralKey;
var _ = Meteor.underscore;
var HTML = Meteor.HTML;
var ObserveSequence = Meteor.ObserveSequence;
var ReactiveVar = Meteor.ReactiveVar;
var Tracker = Meteor.Tracker;
var Blaze;
/**
* @namespace Blaze
* @summary The namespace for all Blaze-related methods and classes.
*/
Blaze = {};
// Utility to HTML-escape a string. Included for legacy reasons.
Blaze._escape = (function() {
var escape_map = {
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`", /* IE allows backtick-delimited attributes?? */
"&": "&"
};
var escape_one = function(c) {
return escape_map[c];
};
return function (x) {
return x.replace(/[&<>"'`]/g, escape_one);
};
})();
Blaze._warn = function (msg) {
msg = 'Warning: ' + msg;
if ((typeof console !== 'undefined') && console.warn) {
console.warn(msg);
}
};
var DOMBackend = {};
Blaze._DOMBackend = DOMBackend;
var $jq = (typeof jQuery !== 'undefined' ? jQuery :
(typeof Package !== 'undefined' ?
Package.jquery && Package.jquery.jQuery : null));
if (! $jq)
throw new Error("jQuery not found");
DOMBackend._$jq = $jq;
DOMBackend.parseHTML = function (html) {
// Return an array of nodes.
//
// jQuery does fancy stuff like creating an appropriate
// container element and setting innerHTML on it, as well
// as working around various IE quirks.
return $jq.parseHTML(html) || [];
};
DOMBackend.Events = {
// `selector` is non-null. `type` is one type (but
// may be in backend-specific form, e.g. have namespaces).
// Order fired must be order bound.
delegateEvents: function (elem, type, selector, handler) {
$jq(elem).on(type, selector, handler);
},
undelegateEvents: function (elem, type, handler) {
$jq(elem).off(type, '**', handler);
},
bindEventCapturer: function (elem, type, selector, handler) {
var $elem = $jq(elem);
var wrapper = function (event) {
event = $jq.event.fix(event);
event.currentTarget = event.target;
// Note: It might improve jQuery interop if we called into jQuery
// here somehow. Since we don't use jQuery to dispatch the event,
// we don't fire any of jQuery's event hooks or anything. However,
// since jQuery can't bind capturing handlers, it's not clear
// where we would hook in. Internal jQuery functions like `dispatch`
// are too high-level.
var $target = $jq(event.currentTarget);
if ($target.is($elem.find(selector)))
handler.call(elem, event);
};
handler._meteorui_wrapper = wrapper;
type = DOMBackend.Events.parseEventType(type);
// add *capturing* event listener
elem.addEventListener(type, wrapper, true);
},
unbindEventCapturer: function (elem, type, handler) {
type = DOMBackend.Events.parseEventType(type);
elem.removeEventListener(type, handler._meteorui_wrapper, true);
},
parseEventType: function (type) {
// strip off namespaces
var dotLoc = type.indexOf('.');
if (dotLoc >= 0)
return type.slice(0, dotLoc);
return type;
}
};
///// Removal detection and interoperability.
// For an explanation of this technique, see:
// http://bugs.jquery.com/ticket/12213#comment:23 .
//
// In short, an element is considered "removed" when jQuery
// cleans up its *private* userdata on the element,
// which we can detect using a custom event with a teardown
// hook.
var NOOP = function () {};
// Circular doubly-linked list
var TeardownCallback = function (func) {
this.next = this;
this.prev = this;
this.func = func;
};
// Insert newElt before oldElt in the circular list
TeardownCallback.prototype.linkBefore = function(oldElt) {
this.prev = oldElt.prev;
this.next = oldElt;
oldElt.prev.next = this;
oldElt.prev = this;
};
TeardownCallback.prototype.unlink = function () {
this.prev.next = this.next;
this.next.prev = this.prev;
};
TeardownCallback.prototype.go = function () {
var func = this.func;
func && func();
};
TeardownCallback.prototype.stop = TeardownCallback.prototype.unlink;
DOMBackend.Teardown = {
_JQUERY_EVENT_NAME: 'blaze_teardown_watcher',
_CB_PROP: '$blaze_teardown_callbacks',
// Registers a callback function to be called when the given element or
// one of its ancestors is removed from the DOM via the backend library.
// The callback function is called at most once, and it receives the element
// in question as an argument.
onElementTeardown: function (elem, func) {
var elt = new TeardownCallback(func);
var propName = DOMBackend.Teardown._CB_PROP;
if (! elem[propName]) {
// create an empty node that is never unlinked
elem[propName] = new TeardownCallback;
// Set up the event, only the first time.
$jq(elem).on(DOMBackend.Teardown._JQUERY_EVENT_NAME, NOOP);
}
elt.linkBefore(elem[propName]);
return elt; // so caller can call stop()
},
// Recursively call all teardown hooks, in the backend and registered
// through DOMBackend.onElementTeardown.
tearDownElement: function (elem) {
var elems = [];
// Array.prototype.slice.call doesn't work when given a NodeList in
// IE8 ("JScript object expected").
var nodeList = elem.getElementsByTagName('*');
for (var i = 0; i < nodeList.length; i++) {
elems.push(nodeList[i]);
}
elems.push(elem);
$jq.cleanData(elems);
}
};
$jq.event.special[DOMBackend.Teardown._JQUERY_EVENT_NAME] = {
setup: function () {
// This "setup" callback is important even though it is empty!
// Without it, jQuery will call addEventListener, which is a
// performance hit, especially with Chrome's async stack trace
// feature enabled.
},
teardown: function() {
var elem = this;
var callbacks = elem[DOMBackend.Teardown._CB_PROP];
if (callbacks) {
var elt = callbacks.next;
while (elt !== callbacks) {
elt.go();
elt = elt.next;
}
callbacks.go();
elem[DOMBackend.Teardown._CB_PROP] = null;
}
}
};
// Must use jQuery semantics for `context`, not
// querySelectorAll's. In other words, all the parts
// of `selector` must be found under `context`.
DOMBackend.findBySelector = function (selector, context) {
return $jq(selector, context);
};
// A constant empty array (frozen if the JS engine supports it).
var _emptyArray = Object.freeze ? Object.freeze([]) : [];
// `[new] Blaze._DOMRange([nodeAndRangeArray])`
//
// A DOMRange consists of an array of consecutive nodes and DOMRanges,
// which may be replaced at any time with a new array. If the DOMRange
// has been attached to the DOM at some location, then updating
// the array will cause the DOM to be updated at that location.
Blaze._DOMRange = function (nodeAndRangeArray) {
if (! (this instanceof DOMRange))
// called without `new`
return new DOMRange(nodeAndRangeArray);
var members = (nodeAndRangeArray || _emptyArray);
if (! (members && (typeof members.length) === 'number'))
throw new Error("Expected array");
for (var i = 0; i < members.length; i++)
this._memberIn(members[i]);
this.members = members;
this.emptyRangePlaceholder = null;
this.attached = false;
this.parentElement = null;
this.parentRange = null;
this.attachedCallbacks = _emptyArray;
};
var DOMRange = Blaze._DOMRange;
// In IE 8, don't use empty text nodes as placeholders
// in empty DOMRanges, use comment nodes instead. Using
// empty text nodes in modern browsers is great because
// it doesn't clutter the web inspector. In IE 8, however,
// it seems to lead in some roundabout way to the OAuth
// pop-up crashing the browser completely. In the past,
// we didn't use empty text nodes on IE 8 because they
// don't accept JS properties, so just use the same logic
// even though we don't need to set properties on the
// placeholder anymore.
DOMRange._USE_COMMENT_PLACEHOLDERS = (function () {
var result = false;
var textNode = document.createTextNode("");
try {
textNode.someProp = true;
} catch (e) {
// IE 8
result = true;
}
return result;
})();
// static methods
DOMRange._insert = function (rangeOrNode, parentElement, nextNode, _isMove) {
var m = rangeOrNode;
if (m instanceof DOMRange) {
m.attach(parentElement, nextNode, _isMove);
} else {
if (_isMove)
DOMRange._moveNodeWithHooks(m, parentElement, nextNode);
else
DOMRange._insertNodeWithHooks(m, parentElement, nextNode);
}
};
DOMRange._remove = function (rangeOrNode) {
var m = rangeOrNode;
if (m instanceof DOMRange) {
m.detach();
} else {
DOMRange._removeNodeWithHooks(m);
}
};
DOMRange._removeNodeWithHooks = function (n) {
if (! n.parentNode)
return;
if (n.nodeType === 1 &&
n.parentNode._uihooks && n.parentNode._uihooks.removeElement) {
n.parentNode._uihooks.removeElement(n);
} else {
n.parentNode.removeChild(n);
}
};
DOMRange._insertNodeWithHooks = function (n, parent, next) {
// `|| null` because IE throws an error if 'next' is undefined
next = next || null;
if (n.nodeType === 1 &&
parent._uihooks && parent._uihooks.insertElement) {
parent._uihooks.insertElement(n, next);
} else {
parent.insertBefore(n, next);
}
};
DOMRange._moveNodeWithHooks = function (n, parent, next) {
if (n.parentNode !== parent)
return;
// `|| null` because IE throws an error if 'next' is undefined
next = next || null;
if (n.nodeType === 1 &&
parent._uihooks && parent._uihooks.moveElement) {
parent._uihooks.moveElement(n, next);
} else {
parent.insertBefore(n, next);
}
};
DOMRange.forElement = function (elem) {
if (elem.nodeType !== 1)
throw new Error("Expected element, found: " + elem);
var range = null;
while (elem && ! range) {
range = (elem.$blaze_range || null);
if (! range)
elem = elem.parentNode;
}
return range;
};
DOMRange.prototype.attach = function (parentElement, nextNode, _isMove, _isReplace) {
// This method is called to insert the DOMRange into the DOM for
// the first time, but it's also used internally when
// updating the DOM.
//
// If _isMove is true, move this attached range to a different
// location under the same parentElement.
if (_isMove || _isReplace) {
if (! (this.parentElement === parentElement &&
this.attached))
throw new Error("Can only move or replace an attached DOMRange, and only under the same parent element");
}
var members = this.members;
if (members.length) {
this.emptyRangePlaceholder = null;
for (var i = 0; i < members.length; i++) {
DOMRange._insert(members[i], parentElement, nextNode, _isMove);
}
} else {
var placeholder = (
DOMRange._USE_COMMENT_PLACEHOLDERS ?
document.createComment("") :
document.createTextNode(""));
this.emptyRangePlaceholder = placeholder;
parentElement.insertBefore(placeholder, nextNode || null);
}
this.attached = true;
this.parentElement = parentElement;
if (! (_isMove || _isReplace)) {
for(var i = 0; i < this.attachedCallbacks.length; i++) {
var obj = this.attachedCallbacks[i];
obj.attached && obj.attached(this, parentElement);
}
}
};
DOMRange.prototype.setMembers = function (newNodeAndRangeArray) {
var newMembers = newNodeAndRangeArray;
if (! (newMembers && (typeof newMembers.length) === 'number'))
throw new Error("Expected array");
var oldMembers = this.members;
for (var i = 0; i < oldMembers.length; i++)
this._memberOut(oldMembers[i]);
for (var i = 0; i < newMembers.length; i++)
this._memberIn(newMembers[i]);
if (! this.attached) {
this.members = newMembers;
} else {
// don't do anything if we're going from empty to empty
if (newMembers.length || oldMembers.length) {
// detach the old members and insert the new members
var nextNode = this.lastNode().nextSibling;
var parentElement = this.parentElement;
// Use detach/attach, but don't fire attached/detached hooks
this.detach(true /*_isReplace*/);
this.members = newMembers;
this.attach(parentElement, nextNode, false, true /*_isReplace*/);
}
}
};
DOMRange.prototype.firstNode = function () {
if (! this.attached)
throw new Error("Must be attached");
if (! this.members.length)
return this.emptyRangePlaceholder;
var m = this.members[0];
return (m instanceof DOMRange) ? m.firstNode() : m;
};
DOMRange.prototype.lastNode = function () {
if (! this.attached)
throw new Error("Must be attached");
if (! this.members.length)
return this.emptyRangePlaceholder;
var m = this.members[this.members.length - 1];
return (m instanceof DOMRange) ? m.lastNode() : m;
};
DOMRange.prototype.detach = function (_isReplace) {
if (! this.attached)
throw new Error("Must be attached");
var oldParentElement = this.parentElement;
var members = this.members;
if (members.length) {
for (var i = 0; i < members.length; i++) {
DOMRange._remove(members[i]);
}
} else {
var placeholder = this.emptyRangePlaceholder;
this.parentElement.removeChild(placeholder);
this.emptyRangePlaceholder = null;
}
if (! _isReplace) {
this.attached = false;
this.parentElement = null;
for(var i = 0; i < this.attachedCallbacks.length; i++) {
var obj = this.attachedCallbacks[i];
obj.detached && obj.detached(this, oldParentElement);
}
}
};
DOMRange.prototype.addMember = function (newMember, atIndex, _isMove) {
var members = this.members;
if (! (atIndex >= 0 && atIndex <= members.length))
throw new Error("Bad index in range.addMember: " + atIndex);
if (! _isMove)
this._memberIn(newMember);
if (! this.attached) {
// currently detached; just updated members
members.splice(atIndex, 0, newMember);
} else if (members.length === 0) {
// empty; use the empty-to-nonempty handling of setMembers
this.setMembers([newMember]);
} else {
var nextNode;
if (atIndex === members.length) {
// insert at end
nextNode = this.lastNode().nextSibling;
} else {
var m = members[atIndex];
nextNode = (m instanceof DOMRange) ? m.firstNode() : m;
}
members.splice(atIndex, 0, newMember);
DOMRange._insert(newMember, this.parentElement, nextNode, _isMove);
}
};
DOMRange.prototype.removeMember = function (atIndex, _isMove) {
var members = this.members;
if (! (atIndex >= 0 && atIndex < members.length))
throw new Error("Bad index in range.removeMember: " + atIndex);
if (_isMove) {
members.splice(atIndex, 1);
} else {
var oldMember = members[atIndex];
this._memberOut(oldMember);
if (members.length === 1) {
// becoming empty; use the logic in setMembers
this.setMembers(_emptyArray);
} else {
members.splice(atIndex, 1);
if (this.attached)
DOMRange._remove(oldMember);
}
}
};
DOMRange.prototype.moveMember = function (oldIndex, newIndex) {
var member = this.members[oldIndex];
this.removeMember(oldIndex, true /*_isMove*/);
this.addMember(member, newIndex, true /*_isMove*/);
};
DOMRange.prototype.getMember = function (atIndex) {
var members = this.members;
if (! (atIndex >= 0 && atIndex < members.length))
throw new Error("Bad index in range.getMember: " + atIndex);
return this.members[atIndex];
};
DOMRange.prototype._memberIn = function (m) {
if (m instanceof DOMRange)
m.parentRange = this;
else if (m.nodeType === 1) // DOM Element
m.$blaze_range = this;
};
DOMRange._destroy = function (m, _skipNodes) {
if (m instanceof DOMRange) {
if (m.view)
Blaze._destroyView(m.view, _skipNodes);
} else if ((! _skipNodes) && m.nodeType === 1) {
// DOM Element
if (m.$blaze_range) {
Blaze._destroyNode(m);
m.$blaze_range = null;
}
}
};
DOMRange.prototype._memberOut = DOMRange._destroy;
// Tear down, but don't remove, the members. Used when chunks
// of DOM are being torn down or replaced.
DOMRange.prototype.destroyMembers = function (_skipNodes) {
var members = this.members;
for (var i = 0; i < members.length; i++)
this._memberOut(members[i], _skipNodes);
};
DOMRange.prototype.destroy = function (_skipNodes) {
DOMRange._destroy(this, _skipNodes);
};
DOMRange.prototype.containsElement = function (elem) {
if (! this.attached)
throw new Error("Must be attached");
// An element is contained in this DOMRange if it's possible to
// reach it by walking parent pointers, first through the DOM and
// then parentRange pointers. In other words, the element or some
// ancestor of it is at our level of the DOM (a child of our
// parentElement), and this element is one of our members or
// is a member of a descendant Range.
// First check that elem is a descendant of this.parentElement,
// according to the DOM.
if (! Blaze._elementContains(this.parentElement, elem))
return false;
// If elem is not an immediate child of this.parentElement,
// walk up to its ancestor that is.
while (elem.parentNode !== this.parentElement)
elem = elem.parentNode;
var range = elem.$blaze_range;
while (range && range !== this)
range = range.parentRange;
return range === this;
};
DOMRange.prototype.containsRange = function (range) {
if (! this.attached)
throw new Error("Must be attached");
if (! range.attached)
return false;
// A DOMRange is contained in this DOMRange if it's possible
// to reach this range by following parent pointers. If the
// DOMRange has the same parentElement, then it should be
// a member, or a member of a member etc. Otherwise, we must
// contain its parentElement.
if (range.parentElement !== this.parentElement)
return this.containsElement(range.parentElement);
if (range === this)
return false; // don't contain self
while (range && range !== this)
range = range.parentRange;
return range === this;
};
DOMRange.prototype.onAttached = function (attached) {
this.onAttachedDetached({ attached: attached });
};
// callbacks are `attached(range, element)` and
// `detached(range, element)`, and they may
// access the `callbacks` object in `this`.
// The arguments to `detached` are the same
// range and element that were passed to `attached`.
DOMRange.prototype.onAttachedDetached = function (callbacks) {
if (this.attachedCallbacks === _emptyArray)
this.attachedCallbacks = [];
this.attachedCallbacks.push(callbacks);
};
DOMRange.prototype.$ = function (selector) {
var self = this;
var parentNode = this.parentElement;
if (! parentNode)
throw new Error("Can't select in removed DomRange");
// Strategy: Find all selector matches under parentNode,
// then filter out the ones that aren't in this DomRange
// using `DOMRange#containsElement`. This is
// asymptotically slow in the presence of O(N) sibling
// content that is under parentNode but not in our range,
// so if performance is an issue, the selector should be
// run on a child element.
// Since jQuery can't run selectors on a DocumentFragment,
// we don't expect findBySelector to work.
if (parentNode.nodeType === 11 /* DocumentFragment */)
throw new Error("Can't use $ on an offscreen range");
var results = Blaze._DOMBackend.findBySelector(selector, parentNode);
// We don't assume `results` has jQuery API; a plain array
// should do just as well. However, if we do have a jQuery
// array, we want to end up with one also, so we use
// `.filter`.
// Function that selects only elements that are actually
// in this DomRange, rather than simply descending from
// `parentNode`.
var filterFunc = function (elem) {
// handle jQuery's arguments to filter, where the node
// is in `this` and the index is the first argument.
if (typeof elem === 'number')
elem = this;
return self.containsElement(elem);
};
if (! results.filter) {
// not a jQuery array, and not a browser with
// Array.prototype.filter (e.g. IE <9)
var newResults = [];
for (var i = 0; i < results.length; i++) {
var x = results[i];
if (filterFunc(x))
newResults.push(x);
}
results = newResults;
} else {
// `results.filter` is either jQuery's or ECMAScript's `filter`
results = results.filter(filterFunc);
}
return results;
};
// Returns true if element a contains node b and is not node b.
//
// The restriction that `a` be an element (not a document fragment,
// say) is based on what's easy to implement cross-browser.
Blaze._elementContains = function (a, b) {
if (a.nodeType !== 1) // ELEMENT
return false;
if (a === b)
return false;
if (a.compareDocumentPosition) {
return a.compareDocumentPosition(b) & 0x10;
} else {
// Should be only old IE and maybe other old browsers here.
// Modern Safari has both functions but seems to get contains() wrong.
// IE can't handle b being a text node. We work around this
// by doing a direct parent test now.
b = b.parentNode;
if (! (b && b.nodeType === 1)) // ELEMENT
return false;
if (a === b)
return true;
return a.contains(b);
}
};
var EventSupport = Blaze._EventSupport = {};
var DOMBackend = Blaze._DOMBackend;
// List of events to always delegate, never capture.
// Since jQuery fakes bubbling for certain events in
// certain browsers (like `submit`), we don't want to
// get in its way.
//
// We could list all known bubbling
// events here to avoid creating speculative capturers
// for them, but it would only be an optimization.
var eventsToDelegate = EventSupport.eventsToDelegate = {
blur: 1, change: 1, click: 1, focus: 1, focusin: 1,
focusout: 1, reset: 1, submit: 1
};
var EVENT_MODE = EventSupport.EVENT_MODE = {
TBD: 0,
BUBBLING: 1,
CAPTURING: 2
};
var NEXT_HANDLERREC_ID = 1;
var HandlerRec = function (elem, type, selector, handler, recipient) {
this.elem = elem;
this.type = type;
this.selector = selector;
this.handler = handler;
this.recipient = recipient;
this.id = (NEXT_HANDLERREC_ID++);
this.mode = EVENT_MODE.TBD;
// It's important that delegatedHandler be a different
// instance for each handlerRecord, because its identity
// is used to remove it.
//
// It's also important that the closure have access to
// `this` when it is not called with it set.
this.delegatedHandler = (function (h) {
return function (evt) {
if ((! h.selector) && evt.currentTarget !== evt.target)
// no selector means only fire on target
return;
return h.handler.apply(h.recipient, arguments);
};
})(this);
// WHY CAPTURE AND DELEGATE: jQuery can't delegate
// non-bubbling events, because
// event capture doesn't work in IE 8. However, there
// are all sorts of new-fangled non-bubbling events
// like "play" and "touchenter". We delegate these
// events using capture in all browsers except IE 8.
// IE 8 doesn't support these events anyway.
var tryCapturing = elem.addEventListener &&
(! _.has(eventsToDelegate,
DOMBackend.Events.parseEventType(type)));
if (tryCapturing) {
this.capturingHandler = (function (h) {
return function (evt) {
if (h.mode === EVENT_MODE.TBD) {
// must be first time we're called.
if (evt.bubbles) {
// this type of event bubbles, so don't
// get called again.
h.mode = EVENT_MODE.BUBBLING;
DOMBackend.Events.unbindEventCapturer(
h.elem, h.type, h.capturingHandler);
return;
} else {
// this type of event doesn't bubble,
// so unbind the delegation, preventing
// it from ever firing.
h.mode = EVENT_MODE.CAPTURING;
DOMBackend.Events.undelegateEvents(
h.elem, h.type, h.delegatedHandler);
}
}
h.delegatedHandler(evt);
};
})(this);
} else {
this.mode = EVENT_MODE.BUBBLING;
}
};
EventSupport.HandlerRec = HandlerRec;
HandlerRec.prototype.bind = function () {
// `this.mode` may be EVENT_MODE_TBD, in which case we bind both. in
// this case, 'capturingHandler' is in charge of detecting the
// correct mode and turning off one or the other handlers.
if (this.mode !== EVENT_MODE.BUBBLING) {
DOMBackend.Events.bindEventCapturer(
this.elem, this.type, this.selector || '*',
this.capturingHandler);
}
if (this.mode !== EVENT_MODE.CAPTURING)
DOMBackend.Events.delegateEvents(
this.elem, this.type,
this.selector || '*', this.delegatedHandler);
};
HandlerRec.prototype.unbind = function () {
if (this.mode !== EVENT_MODE.BUBBLING)
DOMBackend.Events.unbindEventCapturer(this.elem, this.type,
this.capturingHandler);
if (this.mode !== EVENT_MODE.CAPTURING)
DOMBackend.Events.undelegateEvents(this.elem, this.type,
this.delegatedHandler);
};
EventSupport.listen = function (element, events, selector, handler, recipient, getParentRecipient) {
// Prevent this method from being JITed by Safari. Due to a
// presumed JIT bug in Safari -- observed in Version 7.0.6
// (9537.78.2) -- this method may crash the Safari render process if
// it is JITed.
// Repro: https://github.com/dgreensp/public/tree/master/safari-crash
try { element = element; } finally {}
var eventTypes = [];
events.replace(/[^ /]+/g, function (e) {
eventTypes.push(e);
});
var newHandlerRecs = [];
for (var i = 0, N = eventTypes.length; i < N; i++) {
var type = eventTypes[i];
var eventDict = element.$blaze_events;
if (! eventDict)
eventDict = (element.$blaze_events = {});
var info = eventDict[type];
if (! info) {
info = eventDict[type] = {};
info.handlers = [];
}
var handlerList = info.handlers;
var handlerRec = new HandlerRec(
element, type, selector, handler, recipient);
newHandlerRecs.push(handlerRec);
handlerRec.bind();
handlerList.push(handlerRec);
// Move handlers of enclosing ranges to end, by unbinding and rebinding
// them. In jQuery (or other DOMBackend) this causes them to fire
// later when the backend dispatches event handlers.
if (getParentRecipient) {
for (var r = getParentRecipient(recipient); r;
r = getParentRecipient(r)) {
// r is an enclosing range (recipient)
for (var j = 0, Nj = handlerList.length;
j < Nj; j++) {
var h = handlerList[j];
if (h.recipient === r) {
h.unbind();
h.bind();
handlerList.splice(j, 1); // remove handlerList[j]
handlerList.push(h);
j--; // account for removed handler
Nj--; // don't visit appended handlers
}
}
}
}
}
return {
// closes over just `element` and `newHandlerRecs`
stop: function () {
var eventDict = element.$blaze_events;
if (! eventDict)
return;
// newHandlerRecs has only one item unless you specify multiple
// event types. If this code is slow, it's because we have to
// iterate over handlerList here. Clearing a whole handlerList
// via stop() methods is O(N^2) in the number of handlers on
// an element.
for (var i = 0; i < newHandlerRecs.length; i++) {
var handlerToRemove = newHandlerRecs[i];
var info = eventDict[handlerToRemove.type];
if (! info)
continue;
var handlerList = info.handlers;
for (var j = handlerList.length - 1; j >= 0; j--) {
if (handlerList[j] === handlerToRemove) {
handlerToRemove.unbind();
handlerList.splice(j, 1); // remove handlerList[j]
}
}
}
newHandlerRecs.length = 0;
}
};
};
var jsUrlsAllowed = false;
Blaze._allowJavascriptUrls = function () {
jsUrlsAllowed = true;
};
Blaze._javascriptUrlsAllowed = function () {
return jsUrlsAllowed;
};
// An AttributeHandler object is responsible for updating a particular attribute
// of a particular element. AttributeHandler subclasses implement
// browser-specific logic for dealing with particular attributes across
// different browsers.
//
// To define a new type of AttributeHandler, use
// `var FooHandler = AttributeHandler.extend({ update: function ... })`
// where the `update` function takes arguments `(element, oldValue, value)`.
// The `element` argument is always the same between calls to `update` on
// the same instance. `oldValue` and `value` are each either `null` or
// a Unicode string of the type that might be passed to the value argument
// of `setAttribute` (i.e. not an HTML string with character references).
// When an AttributeHandler is installed, an initial call to `update` is
// always made with `oldValue = null`. The `update` method can access
// `this.name` if the AttributeHandler class is a generic one that applies
// to multiple attribute names.
//
// AttributeHandlers can store custom properties on `this`, as long as they
// don't use the names `element`, `name`, `value`, and `oldValue`.
//
// AttributeHandlers can't influence how attributes appear in rendered HTML,
// only how they are updated after materialization as DOM.
AttributeHandler = function (name, value) {
this.name = name;
this.value = value;
};
Blaze._AttributeHandler = AttributeHandler;
AttributeHandler.prototype.update = function (element, oldValue, value) {
if (value === null) {
if (oldValue !== null)
element.removeAttribute(this.name);
} else {
element.setAttribute(this.name, value);
}
};
AttributeHandler.extend = function (options) {
var curType = this;
var subType = function AttributeHandlerSubtype(/*arguments*/) {
AttributeHandler.apply(this, arguments);
};
subType.prototype = new curType;
subType.extend = curType.extend;
if (options)
_.extend(subType.prototype, options);
return subType;
};
/// Apply the diff between the attributes of "oldValue" and "value" to "element."
//
// Each subclass must implement a parseValue method which takes a string
// as an input and returns a dict of attributes. The keys of the dict
// are unique identifiers (ie. css properties in the case of styles), and the
// values are the entire attribute which will be injected into the element.
//
// Extended below to support classes, SVG elements and styles.
var DiffingAttributeHandler = AttributeHandler.extend({
update: function (element, oldValue, value) {
if (!this.getCurrentValue || !this.setValue || !this.parseValue)
throw new Error("Missing methods in subclass of 'DiffingAttributeHandler'");
var oldAttrsMap = oldValue ? this.parseValue(oldValue) : {};
var newAttrsMap = value ? this.parseValue(value) : {};
// the current attributes on the element, which we will mutate.
var attrString = this.getCurrentValue(element);
var attrsMap = attrString ? this.parseValue(attrString) : {};
_.each(_.keys(oldAttrsMap), function (t) {
if (! (t in newAttrsMap))
delete attrsMap[t];
});
_.each(_.keys(newAttrsMap), function (t) {
attrsMap[t] = newAttrsMap[t];
});
this.setValue(element, _.values(attrsMap).join(' '));
}