-
Notifications
You must be signed in to change notification settings - Fork 3
/
ender.js
3177 lines (2790 loc) · 108 KB
/
ender.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
/*!
* =============================================================
* Ender: open module JavaScript framework (https://ender.no.de)
* Build: ender build jeesh morpheus
* =============================================================
*/
/*!
* Ender: open module JavaScript framework (client-lib)
* copyright Dustin Diaz & Jacob Thornton 2011-2012 (@ded @fat)
* http://ender.jit.su
* License MIT
*/
(function (context) {
// a global object for node.js module compatiblity
// ============================================
context['global'] = context
// Implements simple module system
// losely based on CommonJS Modules spec v1.1.1
// ============================================
var modules = {}
, old = context['$']
, oldEnder = context['ender']
, oldRequire = context['require']
, oldProvide = context['provide']
function require (identifier) {
// modules can be required from ender's build system, or found on the window
var module = modules['$' + identifier] || window[identifier]
if (!module) throw new Error("Ender Error: Requested module '" + identifier + "' has not been defined.")
return module
}
function provide (name, what) {
return (modules['$' + name] = what)
}
context['provide'] = provide
context['require'] = require
function aug(o, o2) {
for (var k in o2) k != 'noConflict' && k != '_VERSION' && (o[k] = o2[k])
return o
}
/**
* main Ender return object
* @constructor
* @param {Array|Node|string} s a CSS selector or DOM node(s)
* @param {Array.|Node} r a root node(s)
*/
function Ender(s, r) {
var elements
, i
this.selector = s
// string || node || nodelist || window
if (typeof s == 'undefined') {
elements = []
this.selector = ''
} else if (typeof s == 'string' || s.nodeName || (s.length && 'item' in s) || s == window) {
elements = ender._select(s, r)
} else {
elements = isFinite(s.length) ? s : [s]
}
this.length = elements.length
for (i = this.length; i--;) this[i] = elements[i]
}
/**
* @param {function(el, i, inst)} fn
* @param {Object} opt_scope
* @returns {Ender}
*/
Ender.prototype['forEach'] = function (fn, opt_scope) {
var i, l
// opt out of native forEach so we can intentionally call our own scope
// defaulting to the current item and be able to return self
for (i = 0, l = this.length; i < l; ++i) i in this && fn.call(opt_scope || this[i], this[i], i, this)
// return self for chaining
return this
}
Ender.prototype.$ = ender // handy reference to self
function ender(s, r) {
return new Ender(s, r)
}
ender['_VERSION'] = '0.4.3-dev'
ender.fn = Ender.prototype // for easy compat to jQuery plugins
ender.ender = function (o, chain) {
aug(chain ? Ender.prototype : ender, o)
}
ender._select = function (s, r) {
if (typeof s == 'string') return (r || document).querySelectorAll(s)
if (s.nodeName) return [s]
return s
}
// use callback to receive Ender's require & provide and remove them from global
ender.noConflict = function (callback) {
context['$'] = old
if (callback) {
context['provide'] = oldProvide
context['require'] = oldRequire
context['ender'] = oldEnder
if (typeof callback == 'function') callback(require, provide, this)
}
return this
}
if (typeof module !== 'undefined' && module.exports) module.exports = ender
// use subscript notation as extern for Closure compilation
context['ender'] = context['$'] = ender
}(this));
(function () {
var module = { exports: {} }, exports = module.exports;
/*!
* Morpheus - A Brilliant Animator
* https://github.com/ded/morpheus - (c) Dustin Diaz 2011
* License MIT
*/
!function (name, definition) {
if (typeof define == 'function') define(definition)
else if (typeof module != 'undefined') module.exports = definition()
else this[name] = definition()
}('morpheus', function () {
var doc = document
, win = window
, perf = win.performance
, perfNow = perf && (perf.now || perf.webkitNow || perf.msNow || perf.mozNow)
, now = perfNow ? function () { return perfNow.call(perf) } : function () { return +new Date() }
, html = doc.documentElement
, thousand = 1000
, rgbOhex = /^rgb\(|#/
, relVal = /^([+\-])=([\d\.]+)/
, numUnit = /^(?:[\+\-]=)?\d+(?:\.\d+)?(%|in|cm|mm|em|ex|pt|pc|px)$/
, rotate = /rotate\(((?:[+\-]=)?([\-\d\.]+))deg\)/
, scale = /scale\(((?:[+\-]=)?([\d\.]+))\)/
, skew = /skew\(((?:[+\-]=)?([\-\d\.]+))deg, ?((?:[+\-]=)?([\-\d\.]+))deg\)/
, translate = /translate\(((?:[+\-]=)?([\-\d\.]+))px, ?((?:[+\-]=)?([\-\d\.]+))px\)/
// these elements do not require 'px'
, unitless = { lineHeight: 1, zoom: 1, zIndex: 1, opacity: 1, transform: 1}
// which property name does this browser use for transform
var transform = function () {
var styles = doc.createElement('a').style
, props = ['webkitTransform', 'MozTransform', 'OTransform', 'msTransform', 'Transform']
, i
for (i = 0; i < props.length; i++) {
if (props[i] in styles) return props[i]
}
}()
// does this browser support the opacity property?
var opasity = function () {
return typeof doc.createElement('a').style.opacity !== 'undefined'
}()
// initial style is determined by the elements themselves
var getStyle = doc.defaultView && doc.defaultView.getComputedStyle ?
function (el, property) {
property = property == 'transform' ? transform : property
var value = null
, computed = doc.defaultView.getComputedStyle(el, '')
computed && (value = computed[camelize(property)])
return el.style[property] || value
} : html.currentStyle ?
function (el, property) {
property = camelize(property)
if (property == 'opacity') {
var val = 100
try {
val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity
} catch (e1) {
try {
val = el.filters('alpha').opacity
} catch (e2) {}
}
return val / 100
}
var value = el.currentStyle ? el.currentStyle[property] : null
return el.style[property] || value
} :
function (el, property) {
return el.style[camelize(property)]
}
var frame = function () {
// native animation frames
// http://webstuff.nfshost.com/anim-timing/Overview.html
// http://dev.chromium.org/developers/design-documents/requestanimationframe-implementation
return win.requestAnimationFrame ||
win.webkitRequestAnimationFrame ||
win.mozRequestAnimationFrame ||
win.msRequestAnimationFrame ||
win.oRequestAnimationFrame ||
function (callback) {
win.setTimeout(function () {
callback(+new Date())
}, 17) // when I was 17..
}
}()
var children = []
function has(array, elem, i) {
if (Array.prototype.indexOf) return array.indexOf(elem)
for (i = 0; i < array.length; ++i) {
if (array[i] === elem) return i
}
}
function render(timestamp) {
var i, count = children.length
// if we're using a high res timer, make sure timestamp is not the old epoch-based value.
// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision
if (perfNow && timestamp > 1e12) timestamp = now()
for (i = count; i--;) {
children[i](timestamp)
}
children.length && frame(render)
}
function live(f) {
if (children.push(f) === 1) frame(render)
}
function die(f) {
var rest, index = has(children, f)
if (index >= 0) {
rest = children.slice(index + 1)
children.length = index
children = children.concat(rest)
}
}
function parseTransform(style, base) {
var values = {}, m
if (m = style.match(rotate)) values.rotate = by(m[1], base ? base.rotate : null)
if (m = style.match(scale)) values.scale = by(m[1], base ? base.scale : null)
if (m = style.match(skew)) {values.skewx = by(m[1], base ? base.skewx : null); values.skewy = by(m[3], base ? base.skewy : null)}
if (m = style.match(translate)) {values.translatex = by(m[1], base ? base.translatex : null); values.translatey = by(m[3], base ? base.translatey : null)}
return values
}
function formatTransform(v) {
var s = ''
if ('rotate' in v) s += 'rotate(' + v.rotate + 'deg) '
if ('scale' in v) s += 'scale(' + v.scale + ') '
if ('translatex' in v) s += 'translate(' + v.translatex + 'px,' + v.translatey + 'px) '
if ('skewx' in v) s += 'skew(' + v.skewx + 'deg,' + v.skewy + 'deg)'
return s
}
function rgb(r, g, b) {
return '#' + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1)
}
// convert rgb and short hex to long hex
function toHex(c) {
var m = c.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/)
return (m ? rgb(m[1], m[2], m[3]) : c)
.replace(/#(\w)(\w)(\w)$/, '#$1$1$2$2$3$3') // short skirt to long jacket
}
// change font-size => fontSize etc.
function camelize(s) {
return s.replace(/-(.)/g, function (m, m1) {
return m1.toUpperCase()
})
}
// aren't we having it?
function fun(f) {
return typeof f == 'function'
}
function nativeTween(t) {
// default to a pleasant-to-the-eye easeOut (like native animations)
return Math.sin(t * Math.PI / 2)
}
/**
* Core tween method that requests each frame
* @param duration: time in milliseconds. defaults to 1000
* @param fn: tween frame callback function receiving 'position'
* @param done {optional}: complete callback function
* @param ease {optional}: easing method. defaults to easeOut
* @param from {optional}: integer to start from
* @param to {optional}: integer to end at
* @returns method to stop the animation
*/
function tween(duration, fn, done, ease, from, to) {
ease = fun(ease) ? ease : morpheus.easings[ease] || nativeTween
var time = duration || thousand
, self = this
, diff = to - from
, start = now()
, stop = 0
, end = 0
function run(t) {
var delta = t - start
if (delta > time || stop) {
to = isFinite(to) ? to : 1
stop ? end && fn(to) : fn(to)
die(run)
return done && done.apply(self)
}
// if you don't specify a 'to' you can use tween as a generic delta tweener
// cool, eh?
isFinite(to) ?
fn((diff * ease(delta / time)) + from) :
fn(ease(delta / time))
}
live(run)
return {
stop: function (jump) {
stop = 1
end = jump // jump to end of animation?
if (!jump) done = null // remove callback if not jumping to end
}
}
}
/**
* generic bezier method for animating x|y coordinates
* minimum of 2 points required (start and end).
* first point start, last point end
* additional control points are optional (but why else would you use this anyway ;)
* @param points: array containing control points
[[0, 0], [100, 200], [200, 100]]
* @param pos: current be(tween) position represented as float 0 - 1
* @return [x, y]
*/
function bezier(points, pos) {
var n = points.length, r = [], i, j
for (i = 0; i < n; ++i) {
r[i] = [points[i][0], points[i][1]]
}
for (j = 1; j < n; ++j) {
for (i = 0; i < n - j; ++i) {
r[i][0] = (1 - pos) * r[i][0] + pos * r[parseInt(i + 1, 10)][0]
r[i][1] = (1 - pos) * r[i][1] + pos * r[parseInt(i + 1, 10)][1]
}
}
return [r[0][0], r[0][1]]
}
// this gets you the next hex in line according to a 'position'
function nextColor(pos, start, finish) {
var r = [], i, e, from, to
for (i = 0; i < 6; i++) {
from = Math.min(15, parseInt(start.charAt(i), 16))
to = Math.min(15, parseInt(finish.charAt(i), 16))
e = Math.floor((to - from) * pos + from)
e = e > 15 ? 15 : e < 0 ? 0 : e
r[i] = e.toString(16)
}
return '#' + r.join('')
}
// this retreives the frame value within a sequence
function getTweenVal(pos, units, begin, end, k, i, v) {
if (k == 'transform') {
v = {}
for (var t in begin[i][k]) {
v[t] = (t in end[i][k]) ? Math.round(((end[i][k][t] - begin[i][k][t]) * pos + begin[i][k][t]) * thousand) / thousand : begin[i][k][t]
}
return v
} else if (typeof begin[i][k] == 'string') {
return nextColor(pos, begin[i][k], end[i][k])
} else {
// round so we don't get crazy long floats
v = Math.round(((end[i][k] - begin[i][k]) * pos + begin[i][k]) * thousand) / thousand
// some css properties don't require a unit (like zIndex, lineHeight, opacity)
if (!(k in unitless)) v += units[i][k] || 'px'
return v
}
}
// support for relative movement via '+=n' or '-=n'
function by(val, start, m, r, i) {
return (m = relVal.exec(val)) ?
(i = parseFloat(m[2])) && (start + (m[1] == '+' ? 1 : -1) * i) :
parseFloat(val)
}
/**
* morpheus:
* @param element(s): HTMLElement(s)
* @param options: mixed bag between CSS Style properties & animation options
* - {n} CSS properties|values
* - value can be strings, integers,
* - or callback function that receives element to be animated. method must return value to be tweened
* - relative animations start with += or -= followed by integer
* - duration: time in ms - defaults to 1000(ms)
* - easing: a transition method - defaults to an 'easeOut' algorithm
* - complete: a callback method for when all elements have finished
* - bezier: array of arrays containing x|y coordinates that define the bezier points. defaults to none
* - this may also be a function that receives element to be animated. it must return a value
*/
function morpheus(elements, options) {
var els = elements ? (els = isFinite(elements.length) ? elements : [elements]) : [], i
, complete = options.complete
, duration = options.duration
, ease = options.easing
, points = options.bezier
, begin = []
, end = []
, units = []
, bez = []
, originalLeft
, originalTop
if (points) {
// remember the original values for top|left
originalLeft = options.left;
originalTop = options.top;
delete options.right;
delete options.bottom;
delete options.left;
delete options.top;
}
for (i = els.length; i--;) {
// record beginning and end states to calculate positions
begin[i] = {}
end[i] = {}
units[i] = {}
// are we 'moving'?
if (points) {
var left = getStyle(els[i], 'left')
, top = getStyle(els[i], 'top')
, xy = [by(fun(originalLeft) ? originalLeft(els[i]) : originalLeft || 0, parseFloat(left)),
by(fun(originalTop) ? originalTop(els[i]) : originalTop || 0, parseFloat(top))]
bez[i] = fun(points) ? points(els[i], xy) : points
bez[i].push(xy)
bez[i].unshift([
parseInt(left, 10),
parseInt(top, 10)
])
}
for (var k in options) {
switch (k) {
case 'complete':
case 'duration':
case 'easing':
case 'bezier':
continue;
break
}
var v = getStyle(els[i], k), unit
, tmp = fun(options[k]) ? options[k](els[i]) : options[k]
if (typeof tmp == 'string' &&
rgbOhex.test(tmp) &&
!rgbOhex.test(v)) {
delete options[k]; // remove key :(
continue; // cannot animate colors like 'orange' or 'transparent'
// only #xxx, #xxxxxx, rgb(n,n,n)
}
begin[i][k] = k == 'transform' ? parseTransform(v) :
typeof tmp == 'string' && rgbOhex.test(tmp) ?
toHex(v).slice(1) :
parseFloat(v)
end[i][k] = k == 'transform' ? parseTransform(tmp, begin[i][k]) :
typeof tmp == 'string' && tmp.charAt(0) == '#' ?
toHex(tmp).slice(1) :
by(tmp, parseFloat(v));
// record original unit
(typeof tmp == 'string') && (unit = tmp.match(numUnit)) && (units[i][k] = unit[1])
}
}
// ONE TWEEN TO RULE THEM ALL
return tween.apply(els, [duration, function (pos, v, xy) {
// normally not a fan of optimizing for() loops, but we want something
// fast for animating
for (i = els.length; i--;) {
if (points) {
xy = bezier(bez[i], pos)
els[i].style.left = xy[0] + 'px'
els[i].style.top = xy[1] + 'px'
}
for (var k in options) {
v = getTweenVal(pos, units, begin, end, k, i)
k == 'transform' ?
els[i].style[transform] = formatTransform(v) :
k == 'opacity' && !opasity ?
(els[i].style.filter = 'alpha(opacity=' + (v * 100) + ')') :
(els[i].style[camelize(k)] = v)
}
}
}, complete, ease])
}
// expose useful methods
morpheus.tween = tween
morpheus.getStyle = getStyle
morpheus.bezier = bezier
morpheus.transform = transform
morpheus.parseTransform = parseTransform
morpheus.formatTransform = formatTransform
morpheus.easings = {}
return morpheus
});
provide("morpheus", module.exports);
var morpheus = require('morpheus')
!function ($) {
$.ender({
animate: function (options) {
return morpheus(this, options)
}
, fadeIn: function (d, fn) {
return morpheus(this, {
duration: d
, opacity: 1
, complete: fn
})
}
, fadeOut: function (d, fn) {
return morpheus(this, {
duration: d
, opacity: 0
, complete: fn
})
}
}, true)
$.ender({
tween: morpheus.tween
})
}(ender)
}());
(function () {
var module = { exports: {} }, exports = module.exports;
/*!
* Bean - copyright (c) Jacob Thornton 2011-2012
* https://github.com/fat/bean
* MIT license
*/
!(function (name, context, definition) {
if (typeof module != 'undefined' && module.exports) module.exports = definition(name, context);
else if (typeof define == 'function' && typeof define.amd == 'object') define(definition);
else context[name] = definition(name, context);
}('bean', this, function (name, context) {
var win = window
, old = context[name]
, namespaceRegex = /[^\.]*(?=\..*)\.|.*/
, nameRegex = /\..*/
, addEvent = 'addEventListener'
, removeEvent = 'removeEventListener'
, doc = document || {}
, root = doc.documentElement || {}
, W3C_MODEL = root[addEvent]
, eventSupport = W3C_MODEL ? addEvent : 'attachEvent'
, ONE = {} // singleton for quick matching making add() do one()
, slice = Array.prototype.slice
, str2arr = function (s, d) { return s.split(d || ' ') }
, isString = function (o) { return typeof o == 'string' }
, isFunction = function (o) { return typeof o == 'function' }
// events that we consider to be 'native', anything not in this list will
// be treated as a custom event
, standardNativeEvents =
'click dblclick mouseup mousedown contextmenu ' + // mouse buttons
'mousewheel mousemultiwheel DOMMouseScroll ' + // mouse wheel
'mouseover mouseout mousemove selectstart selectend ' + // mouse movement
'keydown keypress keyup ' + // keyboard
'orientationchange ' + // mobile
'focus blur change reset select submit ' + // form elements
'load unload beforeunload resize move DOMContentLoaded ' + // window
'readystatechange message ' + // window
'error abort scroll ' // misc
// element.fireEvent('onXYZ'... is not forgiving if we try to fire an event
// that doesn't actually exist, so make sure we only do these on newer browsers
, w3cNativeEvents =
'show ' + // mouse buttons
'input invalid ' + // form elements
'touchstart touchmove touchend touchcancel ' + // touch
'gesturestart gesturechange gestureend ' + // gesture
'textinput' + // TextEvent
'readystatechange pageshow pagehide popstate ' + // window
'hashchange offline online ' + // window
'afterprint beforeprint ' + // printing
'dragstart dragenter dragover dragleave drag drop dragend ' + // dnd
'loadstart progress suspend emptied stalled loadmetadata ' + // media
'loadeddata canplay canplaythrough playing waiting seeking ' + // media
'seeked ended durationchange timeupdate play pause ratechange ' + // media
'volumechange cuechange ' + // media
'checking noupdate downloading cached updateready obsolete ' // appcache
// convert to a hash for quick lookups
, nativeEvents = (function (hash, events, i) {
for (i = 0; i < events.length; i++) events[i] && (hash[events[i]] = 1)
return hash
}({}, str2arr(standardNativeEvents + (W3C_MODEL ? w3cNativeEvents : ''))))
// custom events are events that we *fake*, they are not provided natively but
// we can use native events to generate them
, customEvents = (function () {
var isAncestor = 'compareDocumentPosition' in root
? function (element, container) {
return container.compareDocumentPosition && (container.compareDocumentPosition(element) & 16) === 16
}
: 'contains' in root
? function (element, container) {
container = container.nodeType === 9 || container === window ? root : container
return container !== element && container.contains(element)
}
: function (element, container) {
while (element = element.parentNode) if (element === container) return 1
return 0
}
, check = function (event) {
var related = event.relatedTarget
return !related
? related == null
: (related !== this && related.prefix !== 'xul' && !/document/.test(this.toString())
&& !isAncestor(related, this))
}
return {
mouseenter: { base: 'mouseover', condition: check }
, mouseleave: { base: 'mouseout', condition: check }
, mousewheel: { base: /Firefox/.test(navigator.userAgent) ? 'DOMMouseScroll' : 'mousewheel' }
}
}())
// we provide a consistent Event object across browsers by taking the actual DOM
// event object and generating a new one from its properties.
, Event = (function () {
// a whitelist of properties (for different event types) tells us what to check for and copy
var commonProps = str2arr('altKey attrChange attrName bubbles cancelable ctrlKey currentTarget ' +
'detail eventPhase getModifierState isTrusted metaKey relatedNode relatedTarget shiftKey ' +
'srcElement target timeStamp type view which propertyName')
, mouseProps = commonProps.concat(str2arr('button buttons clientX clientY dataTransfer ' +
'fromElement offsetX offsetY pageX pageY screenX screenY toElement'))
, mouseWheelProps = mouseProps.concat(str2arr('wheelDelta wheelDeltaX wheelDeltaY wheelDeltaZ ' +
'axis')) // 'axis' is FF specific
, keyProps = commonProps.concat(str2arr('char charCode key keyCode keyIdentifier ' +
'keyLocation location'))
, textProps = commonProps.concat(str2arr('data'))
, touchProps = commonProps.concat(str2arr('touches targetTouches changedTouches scale rotation'))
, messageProps = commonProps.concat(str2arr('data origin source'))
, stateProps = commonProps.concat(str2arr('state'))
, overOutRegex = /over|out/
// some event types need special handling and some need special properties, do that all here
, typeFixers = [
{ // key events
reg: /key/i
, fix: function (event, newEvent) {
newEvent.keyCode = event.keyCode || event.which
return keyProps
}
}
, { // mouse events
reg: /click|mouse(?!(.*wheel|scroll))|menu|drag|drop/i
, fix: function (event, newEvent, type) {
newEvent.rightClick = event.which === 3 || event.button === 2
newEvent.pos = { x: 0, y: 0 }
if (event.pageX || event.pageY) {
newEvent.clientX = event.pageX
newEvent.clientY = event.pageY
} else if (event.clientX || event.clientY) {
newEvent.clientX = event.clientX + doc.body.scrollLeft + root.scrollLeft
newEvent.clientY = event.clientY + doc.body.scrollTop + root.scrollTop
}
if (overOutRegex.test(type)) {
newEvent.relatedTarget = event.relatedTarget
|| event[(type == 'mouseover' ? 'from' : 'to') + 'Element']
}
return mouseProps
}
}
, { // mouse wheel events
reg: /mouse.*(wheel|scroll)/i
, fix: function () { return mouseWheelProps }
}
, { // TextEvent
reg: /^text/i
, fix: function () { return textProps }
}
, { // touch and gesture events
reg: /^touch|^gesture/i
, fix: function () { return touchProps }
}
, { // message events
reg: /^message$/i
, fix: function () { return messageProps }
}
, { // popstate events
reg: /^popstate$/i
, fix: function () { return stateProps }
}
, { // everything else
reg: /.*/
, fix: function () { return commonProps }
}
]
, typeFixerMap = {} // used to map event types to fixer functions (above), a basic cache mechanism
, Event = function (event, element, isNative) {
if (!arguments.length) return
event = event || ((element.ownerDocument || element.document || element).parentWindow || win).event
this.originalEvent = event
this.isNative = isNative
this.isBean = true
if (!event) return
var type = event.type
, target = event.target || event.srcElement
, i, l, p, props, fixer
this.target = target && target.nodeType === 3 ? target.parentNode : target
if (isNative) { // we only need basic augmentation on custom events, the rest expensive & pointless
fixer = typeFixerMap[type]
if (!fixer) { // haven't encountered this event type before, map a fixer function for it
for (i = 0, l = typeFixers.length; i < l; i++) {
if (typeFixers[i].reg.test(type)) { // guaranteed to match at least one, last is .*
typeFixerMap[type] = fixer = typeFixers[i].fix
break
}
}
}
props = fixer(event, this, type)
for (i = props.length; i--;) {
if (!((p = props[i]) in this) && p in event) this[p] = event[p]
}
}
}
// preventDefault() and stopPropagation() are a consistent interface to those functions
// on the DOM, stop() is an alias for both of them together
Event.prototype.preventDefault = function () {
if (this.originalEvent.preventDefault) this.originalEvent.preventDefault()
else this.originalEvent.returnValue = false
}
Event.prototype.stopPropagation = function () {
if (this.originalEvent.stopPropagation) this.originalEvent.stopPropagation()
else this.originalEvent.cancelBubble = true
}
Event.prototype.stop = function () {
this.preventDefault()
this.stopPropagation()
this.stopped = true
}
// stopImmediatePropagation() has to be handled internally because we manage the event list for
// each element
// note that originalElement may be a Bean#Event object in some situations
Event.prototype.stopImmediatePropagation = function () {
if (this.originalEvent.stopImmediatePropagation) this.originalEvent.stopImmediatePropagation()
this.isImmediatePropagationStopped = function () { return true }
}
Event.prototype.isImmediatePropagationStopped = function () {
return this.originalEvent.isImmediatePropagationStopped && this.originalEvent.isImmediatePropagationStopped()
}
Event.prototype.clone = function (currentTarget) {
//TODO: this is ripe for optimisation, new events are *expensive*
// improving this will speed up delegated events
var ne = new Event(this, this.element, this.isNative)
ne.currentTarget = currentTarget
return ne
}
return Event
}())
// if we're in old IE we can't do onpropertychange on doc or win so we use doc.documentElement for both
, targetElement = function (element, isNative) {
return !W3C_MODEL && !isNative && (element === doc || element === win) ? root : element
}
/**
* Bean maintains an internal registry for event listeners. We don't touch elements, objects
* or functions to identify them, instead we store everything in the registry.
* Each event listener has a RegEntry object, we have one 'registry' for the whole instance.
*/
, RegEntry = (function () {
// each handler is wrapped so we can handle delegation and custom events
var wrappedHandler = function (element, fn, condition, args) {
var call = function (event, eargs) {
return fn.apply(element, args ? slice.call(eargs, event ? 0 : 1).concat(args) : eargs)
}
, findTarget = function (event, eventElement) {
return fn.__beanDel ? fn.__beanDel.ft(event.target, element) : eventElement
}
, handler = condition
? function (event) {
var target = findTarget(event, this) // deleated event
if (condition.apply(target, arguments)) {
if (event) event.currentTarget = target
return call(event, arguments)
}
}
: function (event) {
if (fn.__beanDel) event = event.clone(findTarget(event)) // delegated event, fix the fix
return call(event, arguments)
}
handler.__beanDel = fn.__beanDel
return handler
}
, RegEntry = function (element, type, handler, original, namespaces, args, root) {
var customType = customEvents[type]
, isNative
if (type == 'unload') {
// self clean-up
handler = once(removeListener, element, type, handler, original)
}
if (customType) {
if (customType.condition) {
handler = wrappedHandler(element, handler, customType.condition, args)
}
type = customType.base || type
}
this.isNative = isNative = nativeEvents[type] && !!element[eventSupport]
this.customType = !W3C_MODEL && !isNative && type
this.element = element
this.type = type
this.original = original
this.namespaces = namespaces
this.eventType = W3C_MODEL || isNative ? type : 'propertychange'
this.target = targetElement(element, isNative)
this[eventSupport] = !!this.target[eventSupport]
this.root = root
this.handler = wrappedHandler(element, handler, null, args)
}
// given a list of namespaces, is our entry in any of them?
RegEntry.prototype.inNamespaces = function (checkNamespaces) {
var i, j, c = 0
if (!checkNamespaces) return true
if (!this.namespaces) return false
for (i = checkNamespaces.length; i--;) {
for (j = this.namespaces.length; j--;) {
if (checkNamespaces[i] == this.namespaces[j]) c++
}
}
return checkNamespaces.length === c
}
// match by element, original fn (opt), handler fn (opt)
RegEntry.prototype.matches = function (checkElement, checkOriginal, checkHandler) {
return this.element === checkElement &&
(!checkOriginal || this.original === checkOriginal) &&
(!checkHandler || this.handler === checkHandler)
}
return RegEntry
}())
, registry = (function () {
// our map stores arrays by event type, just because it's better than storing
// everything in a single array.
// uses '$' as a prefix for the keys for safety and 'r' as a special prefix for
// rootListeners so we can look them up fast
var map = {}
// generic functional search of our registry for matching listeners,
// `fn` returns false to break out of the loop
, forAll = function (element, type, original, handler, root, fn) {
var pfx = root ? 'r' : '$'
if (!type || type == '*') {
// search the whole registry
for (var t in map) {
if (t.charAt(0) == pfx) {
forAll(element, t.substr(1), original, handler, root, fn)
}
}
} else {
var i = 0, l, list = map[pfx + type], all = element == '*'
if (!list) return
for (l = list.length; i < l; i++) {
if ((all || list[i].matches(element, original, handler)) && !fn(list[i], list, i, type)) return
}
}
}
, has = function (element, type, original, root) {
// we're not using forAll here simply because it's a bit slower and this
// needs to be fast
var i, list = map[(root ? 'r' : '$') + type]
if (list) {
for (i = list.length; i--;) {
if (!list[i].root && list[i].matches(element, original, null)) return true
}
}
return false
}
, get = function (element, type, original, root) {
var entries = []
forAll(element, type, original, null, root, function (entry) {
return entries.push(entry)
})
return entries
}
, put = function (entry) {
var has = !entry.root && !this.has(entry.element, entry.type, null, false)
, key = (entry.root ? 'r' : '$') + entry.type
;(map[key] || (map[key] = [])).push(entry)
return has
}
, del = function (entry) {
forAll(entry.element, entry.type, null, entry.handler, entry.root, function (entry, list, i) {
list.splice(i, 1)
entry.removed = true
if (list.length === 0) delete map[(entry.root ? 'r' : '$') + entry.type]
return false
})
}
// dump all entries, used for onunload
, entries = function () {
var t, entries = []
for (t in map) {
if (t.charAt(0) == '$') entries = entries.concat(map[t])
}
return entries
}
return { has: has, get: get, put: put, del: del, entries: entries }
}())
// we need a selector engine for delegated events, use querySelectorAll if it exists
// but for older browsers we need Qwery, Sizzle or similar
, selectorEngine
, setSelectorEngine = function (e) {
if (!arguments.length) {
selectorEngine = doc.querySelectorAll
? function (s, r) {
return r.querySelectorAll(s)
}
: function () {
throw new Error('Bean: No selector engine installed') // eeek
}
} else {
selectorEngine = e
}
}
// we attach this listener to each DOM event that we need to listen to, only once
// per event type per DOM element
, rootListener = function (event, type) {
if (!W3C_MODEL && type && event && event.propertyName != '_on' + type) return
var listeners = registry.get(this, type || event.type, null, false)
, l = listeners.length
, i = 0
event = new Event(event, this, true)
if (type) event.type = type
// iterate through all handlers registered for this type, calling them unless they have
// been removed by a previous handler or stopImmediatePropagation() has been called
for (; i < l && !event.isImmediatePropagationStopped(); i++) {
if (!listeners[i].removed) listeners[i].handler.call(this, event)