-
Notifications
You must be signed in to change notification settings - Fork 20
/
FaxEvent.js
executable file
·1208 lines (1109 loc) · 51.4 KB
/
FaxEvent.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
/*
* FaxJs User Interface toolkit.
*
* Copyright (c) 2011 Jordan Walke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* I am providing code in this repository to you under an open source license.
* Because this is my personal repository, the license you receive to my code
* is from me and not from my employer (Facebook).
*
*/
/**
* Fax/FaxEvent.js - Fax event system module.
*/
var FEnv = require('./FEnv');
// Forward Declaration
var FaxEvent;
/**
* Helper class. Provides a nicer api for a conceptual 'event'. Eliminates some
* cross-browser inconsistencies. In the future, continue to place x-browser
* event normalization here if possible, and it applies to all events. Gradually
* expand this out to become a very useful normalized object.
* Note, an abstract event should probably always just have an abstractEventType
* that is a base type (not include any 'Direct' or 'FirstHandler' concept.)
* That makes this a bit awkward to reason about, as there's nothing in the apis
* that will enforce that. Just something to think about.
* It's clear that an "Abstract" event is different than an abstract handler
* type. An abstract handler type describes which abstract events to listen for,
* and under which contexts those abstract events apply to the listener (which
* mode, that is (Direct etc.)
*/
function AbstractEvent(abstractEventType,
originatingTopLevelEventType,
target,
nativeEvent,
data) {
this.abstractEventType = abstractEventType;
this.originatingTopLevelEventType = originatingTopLevelEventType;
this.target = target;
this.nativeEvent = nativeEvent;
this.data = data || {};
}
AbstractEvent.prototype.preventDefault = function() {
FaxEvent.preventDefaultOnNativeEvent(this.nativeEvent);
};
/**
* Todo: Once there is a unified events pipeline, drags, mousedowns, mouseups,
* dragdones should all be rethought out. We need a way to listen for global
* "up" events by the id of the object that was the down event. DragDone's work
* this way because they're highly synthetic. But there is no equivalent for
* simply mouse up. Someone would want to listen to a mouse up event even if
* the mouse was not only the object when "up" occured, but the mouse was over
* it when the "down" occured. You could call this type of event onGlobalMouseUp.
* Once there's a unified event pipeline, this kind of thing would be much
* easier to implement - as it's very much what we already do for drag done
* events.
*/
var abstractHandlerTypes = {
onScroll: 1, onTouchTap: 2, onTouchEnd: 3, onTouchMove: 4, onTouchStart: 5,
onTouchDrag: 6, onTouchDragDone: 7, onClick: 8, onDragDone: 9,
onDrag: 10, onMouseWheel: 11, onKeyUp: 12, onKeyDown: 13,
onKeyPress: 14, onFocus: 15, onBlur: 16, onMouseIn: 17, onMouseOut: 18,
onMouseDown: 19, onMouseUp: 20,
/* Direct handlers */
onScrollDirect: 101, onTouchTapDirect: 102, onTouchEndDirect: 103,
onTouchMoveDirect: 104, onTouchStartDirect: 105,
onTouchDragDirect: 106, onTouchDragDoneDirect: 107,
onClickDirect: 108, onDragDoneDirect: 109, onDragDirect: 110,
onMouseWheelDirect: 111, onKeyUpDirect: 112, onKeyDownDirect: 113,
onKeyPressDirect: 114, onFocusDirect: 115, onBlurDirect: 116,
onMouseInDirect: 117, onMouseOutDirect: 118, onMouseDownDirect: 119,
onMouseUpDirect: 120,
/* First handlers */
onScrollFirstHandler: 201, onTouchTapFirstHandler: 202,
onTouchEndFirstHandler: 203, onTouchMoveFirstHandler: 204,
onTouchStartFirstHandler: 205, onTouchDragFirstHandler: 206,
onTouchDragDoneFirstHandler: 207, onClickFirstHandler: 208,
onDragDoneFirstHandler: 209, onDragFirstHandler: 210,
onMouseWheelFirstHandler: 211, onKeyUpFirstHandler: 212,
onKeyDownFirstHandler: 213, onKeyPressFirstHandler: 214,
onFocusFirstHandler: 215, onBlurFirstHandler: 216,
onMouseInFirstHandler: 217, onMouseOutFirstHandler: 218,
onMouseDownFirstHandler: 219, onMouseUpFirstHandler: 220
};
/**
* Raw signals from the browser caught at the top level.
*/
var topLevelEventTypes = {
topLevelMouseMove: { type: 1 },
topLevelMouseIn: { type: 2 },
topLevelMouseDown: { type: 3, mappedToAbstractHandlerType: abstractHandlerTypes.onMouseDown },
topLevelMouseUp: { type: 4, mappedToAbstractHandlerType: abstractHandlerTypes.onMouseUp },
topLevelMouseOut: { type: 5 },
topLevelClick: { type: 6, mappedToAbstractHandlerType: abstractHandlerTypes.onClick },
topLevelMouseWheel: { type: 7, mappedToAbstractHandlerType: abstractHandlerTypes.onMouseWheel },
topLevelTouchStart: { type: 8, mappedToAbstractHandlerType: abstractHandlerTypes.onTouchStart },
topLevelTouchEnd: { type: 9, mappedToAbstractHandlerType: abstractHandlerTypes.onTouchEnd},
topLevelTouchMove: { type: 10, mappedToAbstractHandlerType: abstractHandlerTypes.onTouchMove },
topLevelTouchCancel: { type: 11 },
topLevelKeyUp: { type: 12, mappedToAbstractHandlerType: abstractHandlerTypes.onKeyUp },
topLevelKeyPress: { type: 13, mappedToAbstractHandlerType: abstractHandlerTypes.onKeyPress },
topLevelKeyDown: { type: 14, mappedToAbstractHandlerType: abstractHandlerTypes.onKeyDown },
topLevelFocus: { type: 15, mappedToAbstractHandlerType: abstractHandlerTypes.onFocus },
topLevelBlur: { type: 16, mappedToAbstractHandlerType: abstractHandlerTypes.onBlur },
topLevelScroll: { type: 17, mappedToAbstractHandlerType: abstractHandlerTypes.onScroll }
};
function _constructAbstractEventDirectlyFromTopLevel(topLevelEventType,
nativeEvent,
target) {
var data;
switch(topLevelEventType) {
case topLevelEventTypes.topLevelMouseWheel:
data = FaxEvent._normalizeAbstractMouseWheelEventData(nativeEvent, target);
break;
case topLevelEventTypes.topLevelScroll:
data = FaxEvent._normalizeAbstractScrollEventData(nativeEvent, target);
break;
case topLevelEventTypes.topLevelClick:
case topLevelEventTypes.topLevelMouseDown:
case topLevelEventTypes.topLevelMouseUp:
case topLevelEventTypes.topLevelTouchMove:
case topLevelEventTypes.topLevelTouchStart:
case topLevelEventTypes.topLevelTouchEnd:
data = FaxEvent._normalizeMouseData(nativeEvent, target);
break;
default:
data = {};
}
return new AbstractEvent(
topLevelEventType.mappedToAbstractHandlerType,
topLevelEventType,
target,
nativeEvent,
data);
}
/**
* Fax events module.
*/
FaxEvent = {
/**
* The event system keeps track of some global state, in order to infer
* abstract events that occur over a sequence of more than one top level
* event. The 'active' drag handlers are handlers that are currently active
* and should receive drag signals when the mouse is used. The bubbling has
* already occured at the time of mouse down and the set of registered drag
* handlers have been stored in these global sets. We'll reuse this global
* store for both mouse and also touch events.
*/
activeDragListenersByListenerDesc : {},
currentlyPressingDown: false,
activeDragListenersCount : 0,
activeDragDoneListenersByListenerDesc : {},
activeDragDoneListenersCount: 0,
lastTouchedDownAtX : null,
lastTouchedDownAtY : null,
lastTriggeredDragAtX : null,
lastTriggeredDragAtY : null,
lastTriggeredDragAtTime : 0,
listeningYet: false,
/* Arbitrarily choose 3 as the required delta - easy to customize later.
* Mouse move events can trigger huge propagations in ui appearance and it's
* nice to be able to only do this occasionally. We'll offer two things, 1.
* Custom sample rate, 2. Adaptive sampling - sample less when each signal
* takes a longer amount of time to respond to - trailing average. */
DRAG_PIXEL_SAMPLE_RATE : 1,
/**
* Will not fire drag events spaced further apart than 50 milliseconds.
*/
DRAG_TIME_SAMPLE_THRESH: 5,
/**
* The number of pixels that are tolerated in between a touchStart and
* touchEnd in order to still be considered a 'tap' event. */
TAP_MOVEMENT_THRESHOLD : 10,
/* This funny initialization is only needed so that browserify can reload
* modules from a local cache. */
abstractEventListenersById : {},
/**
* Key compression friendly event handler types. You can refer by key name,
* and that will get minified. But we need a predictable schema to refer to
* them at the system level because of the way the code is designed. It takes
* a base name and needs to dynamically infer the associated Direct/First
* Handler version as well. The way we'll do it for now, is give each base
* type a number between 1-99 and add a "hundreds offset" for each "mode" of
* handler (Direct/First Handler).
* Long term solution make an algorithm intrinsically resilient to key
* compression.
*
* Keys will be minified, values are identities of those event handlers and
* will not be minified. We can make assumptions about the values and use
* *those* as the actual types.
*/
abstractHandlerTypes : abstractHandlerTypes,
/**
* The various event modes and their respective offsets.
*/
EventModes: {
Default: 0,
Direct: 100,
FirstHandler: 200
},
preventDefaultOnNativeEvent: function(nativeEvent) {
if(nativeEvent.preventDefault) {
nativeEvent.preventDefault();
} else {
nativeEvent.returnValue = false;
}
},
/**
* The top level method that kicks off rendering to the dom should call this.
*/
ensureListening: function(mountAt, touchInsteadOfMouse) {
if (!FaxEvent.listeningYet) {
FaxEvent.registerTopLevelListeners(mountAt, touchInsteadOfMouse);
FaxEvent.listeningYet = true;
}
},
/** Puts a particular event listener on the queue. */
enqueueEventReg : function (id, listener) {
FaxEvent.abstractEventListenersById[
id + "@" + listener.listenForAbstractHandlerType] = listener;
},
/**
* Also performs the mapping from handler name to abstract event name.
*/
registerHandlerByName : function(domNodeId, propName, handler) {
if(FaxEvent.abstractHandlerTypes[propName]) {
FaxEvent.enqueueEventReg(domNodeId, {
listenForAbstractHandlerType: FaxEvent.abstractHandlerTypes[propName],
callThis: handler
});
}
},
/**
* Also performs the mapping from handler name to abstract event name.
*/
registerHandlers : function(domNodeId, props) {
var handlerName;
for (handlerName in FaxEvent.abstractHandlerTypes) {
if (!FaxEvent.abstractHandlerTypes.hasOwnProperty(handlerName)) {
continue;
}
var handler = props[handlerName];
if(handler) {
FaxEvent.enqueueEventReg(domNodeId, {
listenForAbstractHandlerType: FaxEvent.abstractHandlerTypes[handlerName],
callThis: handler
});
}
}
},
__trapCapturedEvent: function (topLevelEventType, captureNativeEventType, onWhat) {
var ourHandler = function(eParam) {
var nativeEvent = eParam || window.event;
var targ = nativeEvent.target || nativeEvent.srcElement;
if (targ.nodeType === 3) {
targ = targ.parentNode;
}
_handleTopLevel(topLevelEventType, nativeEvent, targ);
};
if (!onWhat.addEventListener) {
onWhat.attachEvent(captureNativeEventType, ourHandler);
} else {
onWhat.addEventListener(captureNativeEventType, ourHandler , true);
}
},
/**
* Blatantly duplicating this event normalization code (same as
* __trapCapturedEvent) for performance reasons. Factoring out into helper
* method would hurt a bit. This code is very critical to performance since it
* is called very frequently. http://jsperf.com/calling-function-vs-not
* You'll also notice that we don't extensively normalize all of the event
* data here, instead we normalize it as we need it (to save cpu).
*/
__trapBubbledEvent: function(topLevelEventType, windowHandlerName, onWhat) {
var ourHandler = function(eParam) {
var nativeEvent = eParam || window.event;
var targ = nativeEvent.target || nativeEvent.srcElement;
if (targ.nodeType === 3) { // defeat Safari bug
targ = targ.parentNode;
}
_handleTopLevel(topLevelEventType, nativeEvent, targ);
};
if (onWhat[windowHandlerName]) {
onWhat[windowHandlerName] = function(nativeEvent) {
ourHandler(nativeEvent);
onWhat[windowHandlerName](nativeEvent);
};
} else {
onWhat[windowHandlerName] = function(nativeEvent) {
ourHandler(nativeEvent);
};
}
},
/**
* Just inline this in critical sections of code.
*/
_getTarget: function(nativeEvent) {
nativeEvent = nativeEvent || window.event;
var targ = nativeEvent.target || nativeEvent.srcElement;
if (targ.nodeType === 3) { // defeat Safari bug
targ = targ.parentNode;
}
return targ;
},
topLevelEventTypeIsUsableAsAbstract: function(topLevelEventType) {
return !!topLevelEventType.mappedToAbstractHandlerType;
},
dispatchAllAbstractEventsToListeners: function (id, mode, abstractEvents) {
var i, foundOne = false, maybeEventListener = null, abstractEvent,
abstractEventListenersById = FaxEvent.abstractEventListenersById;
for (i=0; i < abstractEvents.length; i=i+1) {
abstractEvent = abstractEvents[i];
maybeEventListener = abstractEventListenersById[
id + '@' + (abstractEvent.abstractEventType + mode)
];
if (maybeEventListener) {
maybeEventListener.callThis(abstractEvent, abstractEvent.nativeEvent);
foundOne = true;
}
}
return foundOne;
},
/**
* Triggers any registered events on an id as part of a very regular bubbling
* procedure (meaning straight up to the top, not like mouseIn/Out).
* It's kind of funny how in the standard bubbling iteration we reason a lot
* about drag handlers - never call them. Yet on mouse move or mouse ups type
* handlers we don't even talk about bubbling. It's because all of the bubbling
* (even for draggy events) were 'locked' in at the time of mouse down (this
* function, actually).
* Another funny thing about this function is that we infer high level onTouchTap
* events here. We never "locked those in" at mouse down time though we could have.
* The motive for locking in mouse move events was performance. Why recalculate
* the exact same bubble path on every pixel? That would have been costly. But
* onTouchTap shouldn't concern us - though it might be cleaner to lock it in
* on mouse down - #todo (we should do this now because when there are multiple
* fingers on the page, we need to know who started the touch down, so that when
* we get a touchEnd event we can match it with the one that started the touch.)
*
* @mode: Such as 'Direct' or 'FirstHandler'.
* @returns whether or not the event was handled by the dom node with this id
*/
standardBubblingIteration: function(nextId,
topLevelEventType,
mode,
nativeEvent,
targ) {
var nextIdAt = nextId + '@',
abstractHandlerTypes = FaxEvent.abstractHandlerTypes,
abstractEventListenersById = FaxEvent.abstractEventListenersById,
mouseDownDragDesc = nextIdAt + (abstractHandlerTypes.onDrag + mode),
touchStartDragDesc = nextIdAt + (abstractHandlerTypes.onTouchDrag + mode),
mouseDownDragDoneDesc = nextIdAt + (abstractHandlerTypes.onDragDone + mode),
touchStartDragDoneDesc = nextIdAt + (abstractHandlerTypes.onTouchDragDone + mode),
dragDesc = topLevelEventType === topLevelEventTypes.topLevelMouseDown ? mouseDownDragDesc :
topLevelEventType === topLevelEventTypes.topLevelTouchStart ? touchStartDragDesc :
false, // in this case you won't be using it anyways.
dragDoneDesc = topLevelEventType === topLevelEventTypes.topLevelMouseDown ? mouseDownDragDoneDesc :
topLevelEventType === topLevelEventTypes.topLevelTouchStart ? touchStartDragDoneDesc:
false; // in this case you won't be using it anyways.
var handledLowLevelEventByRegisteringDragListeners,
handledLowLevelEventByFindingRelevantListeners = false;
/** Lazily defined when we first need it. */
var abstractEvents = [],
newAbstractEvent,
globalX,
globalY;
if (topLevelEventType === topLevelEventTypes.topLevelMouseDown ||
topLevelEventType === topLevelEventTypes.topLevelTouchStart) {
globalX = FaxEvent.eventGlobalX(nativeEvent, true);
globalY = FaxEvent.eventGlobalY(nativeEvent, true);
FaxEvent.currentlyPressingDown = true;
FaxEvent.lastTouchedDownAtX = globalX;
FaxEvent.lastTouchedDownAtY = globalY;
if (abstractEventListenersById[dragDesc]) {
newAbstractEvent = _constructAbstractEventDirectlyFromTopLevel(
topLevelEventType, nativeEvent, targ);
abstractEvents.push(newAbstractEvent);
/* even if nothing handles the mouse down, and something handles the
* click, we say that anything above this in the dom tree will not be
* the first handler, whether or not they're listening for clicks vs.
* drags. We can eventually change that to care about what exactly was
* handled, but this is kind of convenient.*/
if(!newAbstractEvent.data.rightMouseButton) {
handledLowLevelEventByRegisteringDragListeners = true;
FaxEvent.activeDragListenersByListenerDesc[dragDesc] =
abstractEventListenersById[dragDesc];
FaxEvent.activeDragListenersCount++;
var activeDragDoneListenerForNextId =
abstractEventListenersById[dragDoneDesc];
if (activeDragDoneListenerForNextId) {
FaxEvent.activeDragDoneListenersByListenerDesc[dragDoneDesc] =
activeDragDoneListenerForNextId;
FaxEvent.activeDragDoneListenersCount++;
}
FaxEvent.lastTriggeredDragAtX = globalX; // not really, but works
FaxEvent.lastTriggeredDragAtY = globalY;
// Setting this to zero, so that the very first drag event will never
// be held back on account of the drag time. In fact it might be a good
// idea to do something similar with the other two global trackers
// (x/y)
FaxEvent.lastTriggeredDragAtTime = 0;
}
}
} else if (topLevelEventType === topLevelEventTypes.topLevelTouchEnd) {
globalX = FaxEvent.eventGlobalX(nativeEvent);
globalY = FaxEvent.eventGlobalY(nativeEvent);
var totalDistanceSinceLastTouchedDown =
Math.abs(globalX - FaxEvent.lastTouchedDownAtX) +
Math.abs(globalY - FaxEvent.lastTouchedDownAtY);
if (totalDistanceSinceLastTouchedDown < FaxEvent.TAP_MOVEMENT_THRESHOLD) {
/* Code below will search for handlers that are interested in this
* abstract event. */
abstractEvents.push(new AbstractEvent(
abstractHandlerTypes.onTouchTap,
topLevelEventType,
targ,
nativeEvent,
{})
);
}
}
/*
* We may have needed to register drag listeners, or infer touchTaps, but we still
* might need those same top level event types that we used to call handlers that
* are 'directly mapped' to those topLevelEventTypes. (such as onTouchStart etc).
*/
if (FaxEvent.topLevelEventTypeIsUsableAsAbstract(topLevelEventType)) {
/**
* Some abstract events are just simple one-one corresponding event types
* with top level events.
*/
abstractEvents.push(_constructAbstractEventDirectlyFromTopLevel(
topLevelEventType, nativeEvent, targ));
}
handledLowLevelEventByFindingRelevantListeners =
FaxEvent.dispatchAllAbstractEventsToListeners(
nextId, mode, abstractEvents);
return handledLowLevelEventByFindingRelevantListeners ||
handledLowLevelEventByRegisteringDragListeners;
},
/** I <3 Quirksmode.org */
_isNativeClickEventRightClick: function(nativeEvent) {
return nativeEvent.which ? nativeEvent.which === 3 :
nativeEvent.button ? nativeEvent.button === 3 :
false;
},
/**
* There are some normalizations that need to happen for various browsers. In
* addition to replacing the general event fixing with a framework such as
* jquery, we need to normalize mouse events here. The below is mostly borrowed
* from: jScrollPane/script/jquery.mousewheel.js
*/
_normalizeAbstractMouseWheelEventData: function(event /*native */, target) {
var orgEvent = event, args, delta = 0, deltaX = 0, deltaY = 0;
/* traditional scroll wheel data */
if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
if ( event.detail ) { delta = -event.detail/3; }
/* Multidimensional scroll (touchpads) with deltas */
deltaY = delta;
/* Gecko based browsers */
if (orgEvent.axis !== undefined &&
orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
/* Webkit based browsers */
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
return { delta: delta, deltaX: deltaX, deltaY: deltaY };
},
_normalizeAbstractScrollEventData: function(event /*native */, target) {
return {
scrollTop: target.scrollTop,
scrollLeft: target.scrollLeft,
clientWidth: target.clientWidth,
clientHeight: target.clientHeight,
scrollHeight: target.scrollHeight,
scrollWidth: target.scrollWidth
};
},
/**
* Note: for touchEnd the touches will usually be empty, or not what you
* would think they are. Just don't rely on them for handling touchEnd events.
* http://stackoverflow.com/questions/3666929/
* mobile-sarai-touchend-event-not-firing-when-last-touch-is-removed
* We're usually only interested in single finger gestures or mouse clicks,
* which is why we only care about touches of length 1.
* We can extract more interesting gesture patterns later.
*/
eventGlobalY: function(event, log) {
if ((!event.touches || event.touches.length === 0) &&
event.changedTouches && event.changedTouches.length === 1) {
return event.changedTouches[0].pageY;
}
if(event.touches && event.touches.length === 1) {
return event.touches[0].pageY;
}
return event.pageY !== undefined ? event.pageY :
event.clientY + FEnv.currentScrollTop;
},
eventGlobalX: function(event, log) {
if ((!event.touches || event.touches.length === 0) &&
event.changedTouches && event.changedTouches.length === 1) {
return event.changedTouches[0].pageX;
}
if(event.touches && event.touches[0]) {
return event.touches[0].pageX;
}
return event.pageX !== undefined ? event.pageX :
event.clientX + FEnv.currentScrollLeft;
},
_normalizeMouseData: function(event /*native */, target) {
return {
globalX: FaxEvent.eventGlobalX(event),
globalY: FaxEvent.eventGlobalY(event),
rightMouseButton: FaxEvent._isNativeClickEventRightClick(event)
};
},
_normalizeAbstractDragEventData: function(event /*native*/,
globalX,
globalY,
lastTouchedDownAtX,
lastTouchedDownAtY) {
return {
globalX: globalX, globalY: globalY,
startX: lastTouchedDownAtX, startY: lastTouchedDownAtY
};
},
/* Well need to handle all events that have either a from or to starting with
* a '.'. This should be the first thing checked at the top. We only need to
* handle mouse out events, as we can always infer the mouse in event. If we
* handle both, we get duplicate events firing. TODO: All of this would be
* faster if I just used string.split('.'); TODO: These mouseIn and mouseOut
* events should be inferred at the high level event inference stage of the
* event processing pipeline. However, it's tough, because there are N x M
* high level events that occurred. Maybe high level events just contain a
* succinct description of what physically happened, and the dispatcher is
* smart enough to know how to dispatch this to all concerned parties. When
* plugging into the event system, One would only need to write the extracter
* and the dispatcher. TODO: mouseIn and out have different types of
* bubbling. The mouse can jump lineage, from the 'from' branch to the 'to'
* branch. We perform special bubbling from the from to the common ancestor
* triggering the mouse out event. We do not bubble any further. (Similarly
* for mouse in). Ever person along that path has the opportunity to handle
* the mouseIn/out and no one has the ability to top the propagation or
* specify that they aren't interested in bubbled events. The 'out' event
* occurred just as much on every single element in the from path to the
* common ancestor. (Similarly with 'to'). */
_handleMouseInOut: function(topLevelEventType, nativeEvent, targ) {
var to = targ, from = targ, fromId = '', toId = '',
abstractEventListenersById = FaxEvent.abstractEventListenersById;
if (topLevelEventType === topLevelEventTypes.topLevelMouseIn) {
from = nativeEvent.relatedTarget || nativeEvent.fromElement;
if (from) {
return; /* Listening only to mouse out events can catch all
* except mousing from outside
* window into the document. Otherwise we'll listen only
* for mouse outs.*/
}
} else {
to = nativeEvent.relatedTarget || nativeEvent.toElement;
}
while (to && (!to.id || to.id.charAt(0) !== '.')) {
to = to.parentNode;
}
while (from && (!from.id || from.id.charAt(0) !== '.')) {
from = from.parentNode;
}
// Nothing pertains to our managed components.
if (!from && !to) { return; }
if (from && from.id) { fromId = from.id; }
if (to && to.id) { toId = to.id; }
var commonIdx = 0;
// Stays this way if one of from/to is window.
var commonAncestorId = '';
var commonChars = 0;
while (toId.charAt(commonChars) !== '' && fromId.charAt(commonChars) !== '' &&
toId.charAt(commonChars) === fromId.charAt(commonChars)) {
// Find the last common dot (with virtual dots at the end of the from/to)
commonChars++;
}
// could use either to or from - they're in common!
if (toId.charAt(commonChars-1) === '.') {
commonAncestorId = toId.substr(0, commonChars - 1); // remove the dot
} else {
/* Some cases that can happen
* a.b.something a.b.some
* a.b.something a.b.something.else
* a.b.c.something a.b.canyouhearme
* Use two without loss of generality.*/
commonAncestorId = toId.substr(0, (toId.substr(0, commonChars)).lastIndexOf('.'));
}
var i, maybeEventListener, traverseId = fromId;
if (from) {
i = 0;
while (traverseId !== commonAncestorId) {
maybeEventListener = abstractEventListenersById[
traverseId + '@' + FaxEvent.abstractHandlerTypes.onMouseOut
];
if (maybeEventListener) {
maybeEventListener.callThis(
new AbstractEvent(
FaxEvent.abstractHandlerTypes.onMouseOut,
topLevelEventType, targ, nativeEvent, {}),
targ, nativeEvent);
}
var oldtrav = traverseId;
traverseId = traverseId.substr(0, traverseId.lastIndexOf('.'));
i++;
if (i > 200 ) {
FaxEvent.Error('Runaway tree: ' + traverseId);
return;
}
}
}
// todo: should not trigger on common ancestor.
traverseId = toId.substr(0, commonAncestorId.length);
if (to) {
i = 0;
while (traverseId !== toId) {
traverseId = toId.indexOf('.', traverseId.length +1) === -1 ?
toId :
toId.substr(0, (toId.indexOf('.', traverseId.length+1)));
maybeEventListener = abstractEventListenersById[
traverseId + '@' + FaxEvent.abstractHandlerTypes.onMouseIn];
if (maybeEventListener) {
maybeEventListener.callThis(
new AbstractEvent(
FaxEvent.abstractHandlerTypes.onMouseIn, topLevelEventType, nativeEvent, {}),
targ, nativeEvent);
}
i++;
if (i > 200 ) {
FaxEvent.Error('Runaway tree: ' + traverseId);
return;
}
}
}
return;
},
/**
* Handles events that are 'movementy', meaning mouse and touch drags, not mouse
* in or out events which are more instantaneous in nature occurring at element
* boundaries and thus don't need the same quantization as movementy events.
* From these top level movementy events we can infer (currently) two higher
* level events (both drag events) (onTouchDrag and onDrag)
*/
_handleMovementyTopLevelEvent: function(topLevelEventType, nativeEvent, targ) {
if (!FaxEvent.currentlyPressingDown) {
return;
}
var globalX, globalY, dragDesc, totalDistanceSinceLastDrag,
nowMs, totalMsSinceLastDrag;
globalX = FaxEvent.eventGlobalX(nativeEvent);
globalY = FaxEvent.eventGlobalY(nativeEvent);
if (FaxEvent.activeDragListenersCount) {
// Not distance, but sum of deltas along both dimensions
totalDistanceSinceLastDrag =
Math.abs(globalX - FaxEvent.lastTriggeredDragAtX) +
Math.abs(globalY - FaxEvent.lastTriggeredDragAtY);
nowMs = (new Date()).getTime();
totalMsSinceLastDrag = nowMs - FaxEvent.lastTriggeredDragAtTime;
if(totalDistanceSinceLastDrag < FaxEvent.DRAG_PIXEL_SAMPLE_RATE ||
totalMsSinceLastDrag < FaxEvent.DRAG_TIME_SAMPLE_THRESH) {
return;
}
/* Okay, the active drag handlers bank could have either touched drag or regular
* drag handlers, but practically you'll never be running in a context where
* the two types could simultaneously exist - we don't need to check their
* types - in fact we could consolidate this into a conceptual onAnyDrag event
* early on.
*/
for (dragDesc in FaxEvent.activeDragListenersByListenerDesc) {
if (!FaxEvent.activeDragListenersByListenerDesc.hasOwnProperty(dragDesc)) {
continue;
}
var abstractEventData = FaxEvent._normalizeAbstractDragEventData(
nativeEvent, globalX, globalY,
FaxEvent.lastTouchedDownAtX,
FaxEvent.lastTouchedDownAtY),
listener = FaxEvent.activeDragListenersByListenerDesc[dragDesc];
var abstractEvent = new AbstractEvent(
topLevelEventType === topLevelEventTypes.topLevelTouchMove ?
abstractHandlerTypes.onTouchDrag :
abstractHandlerTypes.onDrag,
topLevelEventType,
targ, nativeEvent, abstractEventData);
listener.callThis.call(listener.context || null, abstractEvent, nativeEvent);
}
FaxEvent.lastTriggeredDragAtX = globalX;
FaxEvent.lastTriggeredDragAtY = globalY;
FaxEvent.lastTriggeredDragAtTime = nowMs;
}
},
/**
* Handles events that are of the "let up" nature, meaning a mouseup/touchup, but this
* also gives us an opportunity to infer a higher level event onTouchTap (which is a
* touchStart followed by not much movement followed by a touchEnd). We don't need to
* immediately track the originating element that was toucheStarted upon because no
* movement occured - except in the case where the touchStart hides the element, no
* movement occurs then a touchEnd is observed. (We can fix that if it becomes an
* issue.)
*/
_handleLetUppyTopLevelEvent: function(topLevelEventType, nativeEvent, targ) {
var globalX, globalY, dragDoneDesc,
totalDistanceSinceLastTouchedDown, totalDistanceSinceLastDrag,
activeDragDoneListenerForDragDesc;
globalX = FaxEvent.eventGlobalX(nativeEvent);
globalY = FaxEvent.eventGlobalY(nativeEvent);
totalDistanceSinceLastTouchedDown =
Math.abs(globalX - FaxEvent.lastTouchedDownAtX) +
Math.abs(globalY - FaxEvent.lastTouchedDownAtY);
if (FaxEvent.activeDragDoneListenersCount) {
/* Only trigger the dragDone event if there has been some mouse movement
* while the mouse was depressed (at same quantizeDrag threshold
* (FaxEvent.DRAG_PIXEL_SAMPLE_RATE))*/
if(totalDistanceSinceLastTouchedDown > FaxEvent.DRAG_PIXEL_SAMPLE_RATE) {
for (dragDoneDesc in FaxEvent.activeDragDoneListenersByListenerDesc) {
if (!FaxEvent.activeDragDoneListenersByListenerDesc.hasOwnProperty(dragDoneDesc)) {
continue;
}
activeDragDoneListenerForDragDesc =
FaxEvent.activeDragDoneListenersByListenerDesc[dragDoneDesc];
var abstractEvent = new AbstractEvent(
topLevelEventType === topLevelEventTypes.topLevelMouseUp ?
abstractHandlerTypes.onDragDone :
abstractHandlerTypes.onTouchDragDone,
topLevelEventType, targ, nativeEvent, {});
// Todo: pass an abstract event nicely normalized
activeDragDoneListenerForDragDesc.callThis.call(
activeDragDoneListenerForDragDesc.context || null);
}
}
}
/**
* Currently, all drag handlers are locked down at the time of mousedown/
* touchstart. All drag signal events are sent with respect to the initial
* (single) mousedown/touchstart that triggered. In a world of multiple
* input devices (or touches) that is not sufficient. For each drag handler
* we need to remember the initial event that instigated the drag. That
* will also make handling single taps easier - see the main top level
* handler (we had to handle letUppy events very last because bubbling
* needed certain data that it cleared.) Doing this right will be harder
* than it sounds - we're talking about multiple drag events. That would
* require that when multiple touches occur, and multiple touchmoves occur
* that we track which originating objects should receive which signal
* channel for touch events. Maybe the browser helps us out with this?
*/
FaxEvent.activeDragListenersByListenerDesc = {};
FaxEvent.currentlyPressingDown = false;
FaxEvent.activeDragListenersCount = 0;
FaxEvent.activeDragDoneListenersCount = 0;
FaxEvent.activeDragDoneListenersByListenerDesc = {};
FaxEvent.lastTouchedDownAtX = 0;
FaxEvent.lastTouchedDownAtY = 0;
}
};
/**
* The Fax system needs to listen to document scroll events to update the single
* point of inventory on the document's currently scrolled to position. The idea
* is that there's a single point where this is maintained and always kept up to
* date. Anyone who wants to know that value should as the FEnv what the latest
* value is. If everyone queried the document when they wanted to know the
* value, they'd trigger reflows like mad. I don't think we needed to normalize
* the target here. Check this on safari etc - we only care about one very
* specific event on a very specific target - as long as it works for that case.
* TODO: Make resizing recalculate these as well.
*/
FaxEvent.registerDocumentScrollListener = function() {
var previousDocumentScroll = document.onscroll;
document.onscroll = function(nativeEvent) {
if(nativeEvent.target === document) {
FEnv.refreshAuthoritativeScrollValues();
}
if(previousDocumentScroll) { previousDocumentScroll(nativeEvent); }
if (FaxEvent.applicationDocumentScrollListener) {
FaxEvent.applicationDocumentScrollListener(nativeEvent);
}
};
};
/**
* Default resize batching time is zero (n/a) but you can set this to whatever
* ms you want elapsed in between firing application registered resize events.
* If you reset the FEnv's knowledge of viewport dimensions on every resize,
* you could be causing an entirely new reflow.
*/
FaxEvent.applicationResizeBatchTimeMs = 0;
FaxEvent.registerWindowResizeListener = function() {
var previousResizeListener = window.onresize;
var pendingCallback = null;
var lastMs = (new Date()).getTime(), now, ellapsed;
window.onresize = function(nativeEvent) {
now = (new Date()).getTime();
ellapsed = now - lastMs;
if (!pendingCallback) {
pendingCallback = true;
window.setTimeout(function(nativeEvent) {
FEnv.refreshAuthoritativeViewportValues();
if (previousResizeListener) {previousResizeListener(nativeEvent);}
if (FaxEvent.applicationResizeListener) {
FaxEvent.applicationResizeListener(nativeEvent);
}
pendingCallback = false;
lastMs = now;
}, Math.max(FaxEvent.applicationResizeBatchTimeMs - ellapsed + 1, 1));
return; // Don't trigger a reflow by querying for the window dimensions
}
};
};
/**
* This is just for IE only. For other browsers, we can easily apply a noselect
* class. In IE we need to inspect every element that was selected and see if it
* had a noselect class on it :( This also deactivates that horrible horrible
* horrible horrible "accelerator" popups on IE8.
* This needs to be rethought, for a couple of reasons - first being that key
* minification can ruin any class name we might be looking for. The second, is
* this will prevent less than what non-ie browsers with noSelect will catch. I
* think the best solution, would be to apply a single global listener to
* document.onselectstart when in the process of a drag, which prevents default,
* and detach that listener on drag done.
*/
FaxEvent.registerIeOnSelectStartListener = function() {
var previousOnSelectStart = document.onselectstart;
document.onselectstart = function(nativeEvent) {
var targ = FaxEvent._getTarget(nativeEvent);
if (targ.className && targ.className.search(/noSelect/) !== -1 ) {
(nativeEvent || window.event).returnValue = false;
}
if (previousOnSelectStart) {
previousOnSelectStart(nativeEvent || window.event);
}
};
};
/**
* Ensures that selection of document elements is disabled temporarily. When
* calling the complementary method enableSelectionGlobally, it will restore
* the old handler.
* Todo: Firefox support (by returning false on mousedowns during drags)
* Note: We use 'onselectstart' in string form so that closure compiler doesn't
* eliminate it -which is odd since Chrome actually supports that event.
*/
FaxEvent.disableSelectionGlobally = function() {
if (FaxEvent.haveBackedUpOldOnSelectStart) {
return;
}
FaxEvent.oldOnSelectStart = document['onselectstart'];
FaxEvent.haveBackedUpOldOnSelectStart = true;
document['onselectstart'] = function(nativeEvent) {
FaxEvent.preventDefaultOnNativeEvent(nativeEvent || window.event);
};
};
FaxEvent.enableSelectionGlobally = function() {
if (FaxEvent.haveBackedUpOldOnSelectStart) {
document['onselectstart'] = FaxEvent.oldOnSelectStart;
FaxEvent.oldOnSelectStart = null;
FaxEvent.haveBackedUpOldOnSelectStart = false;
}
};
/**
* We'll put something like this in Utils, and fall back to either a compiled
* regex, or the following algorithm, depending on which is faster on which
* browser. */
function startsWith(str, startsWithStr) {
var i;
for (i=0; i < startsWithStr.length; i=i+1) {
if (str[i] !== startsWithStr[i]) {
return false;
}
}
return true;
}
/**
* Releases memory in a controlled manner. Once artifacts are removed from the
* DOM, simply removing any event handlers in the top level bank should be the
* last thing needed to clear memory.
*
* This particular algorithm will be very slow if you wait too long until
* clearing memory. You may set up a window timeOut to clear memory every
* second or so, but your application likely has a particular moments of
* interest when you know it's most beneficial to clear memory. Choose those
* times, and eliminate any master timeOut when in those application flows.
*
* Coming soon: We'll test a tree hierarchy for event listeners, so in a single
* statement we can clear out all child dependency listeners.
*
* Also: using top level event delegation in the more traditional manner (one
* handler for several instances will make this cleanup process very very
* fast.) Since we don't want to push the burden of thinking about that onto
* the developer, we'll hold off until our static analysis (or api) is robust
* enough to accommodate those patterns.
*/
FaxEvent.releaseMemoryReferences = function (idPrefixes) {
var i, idPrefix, listenerDesc,
abstractListeners = FaxEvent.abstractEventListenersById;
for (idPrefix in idPrefixes) {
if (!idPrefixes.hasOwnProperty(idPrefix)) {
continue;
}
for (listenerDesc in abstractListeners) {
if (!abstractListeners.hasOwnProperty(listenerDesc)) {
continue;
}