/
FEvent.js
executable file
·1335 lines (1233 loc) · 55.5 KB
/
FEvent.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).
*
*/
/**
* @FEvent.js - Top level event system module.
*/
/**
* A note about touch events: See:
* http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
* http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html Clicks
* likely require mounting the event listener somewhere deep in the dom tree
* (not at doc/window). Though we don't care much about clicks because they have
* a 300 ms delay anyways and we roll our own clicks. What is supported, is
* actually very complicated and varies by version of iOS - please populate and
* complete this table as you find more information. On IOS5
* overflow:touch-scroll divs, rumor has it, that if you can listen to bubbled
* touch events somewhere deep in the dom (document/one level deep?), if you
* stop bubbling, you can prevent the rubber band.
*
* IOS5:
* Using event bubbling - listening on dom element one level deep (from body):
* Could not get any touch events.
* Using event bubbling - listening on dom element two level deep (from body):
* Could not get any touch events.
* Using event bubbling - listening on document:
* Could get touch events, and could prevent default on the touch move.
* Using event bubbling - listening on window:
* Could get touch events, and could prevent default on the touch move.
*
* Trap capture - listening on two deep from body
* Could NOT get touch events, and could NOT prevent default on touch move.
* Trap capture - listening on one deep from body
* Could NOT get touch events, and could NOT prevent default on touch move.
* Trap capture - listening on document
* Could get touch events, and could prevent default on the touch move.
* Trap capture - listening on window
* Could get touch events, and could prevent default on the touch move.
*
* IOS4:
* Using event bubbling - listening on dom element one level deep (from body):
* Could get touch events, and could prevent default on the touch move.
* Using event bubbling - listening on dom element two level deep (from body):
* Could get touch events, and could prevent default on the touch move.
* Using event bubbling - listening on document:
* Could get touch events, and could prevent default on the touch move.
* Using event bubbling - listening on window:
* Could get touch events, and could prevent default on the touch move.
*
* Trap capture - listening on two deep from body
* Could get touch events, and could prevent default on the touch move.
* Trap capture - listening on one deep from body
* Could get touch events, and could prevent default on the touch move.
* Trap capture - listening on document
* Could get touch events, and could prevent default on the touch move.
* Trap capture - listening on window
* Could NOT get touch events, and could NOT prevent default on the touch
* move.
*
* At least for the iOS world, it seems listening for bubbled touch events on
* the document object is actually the best for compatibility.
*
* In addition: Firefox v8.01 (and possibly others exhibited strange behavior
* when mounting onmousemove events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the top
* level handlers for onmousemove won't be called. However, if you register the
* mousemove on the document object, then it will of course catch all
* mousemoves. This along with iOS quirks, justifies restricting top level
* handlers to the document object only, at least for these movementy types of
* events and possibly all events. There seems to be no reason for allowing
* arbitrary mount points.
*
*/
var FEnv = require('./FEnv');
// Forward Declaration
var FEvent;
/**
* 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() {
FEvent.preventDefaultOnNativeEvent(this.nativeEvent);
};
/**
* @abstractHandlers: Type of abstract handlers. 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 abstractHandlers = {
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, onChange: 21,
/* 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, onChangeDirect: 121,
/* 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,
onChangeFirstHandler: 221
};
/**
* @topLevelEvents: Raw signals from the browser caught at the top level.
*/
var topLevelEvents = {
mouseMove: {type: 1},
mouseIn: {type: 2},
mouseDown: {type: 3, mappedToAbstractHandler: abstractHandlers.onMouseDown},
mouseUp: {type: 4, mappedToAbstractHandler: abstractHandlers.onMouseUp},
mouseOut: {type: 5},
click: {type: 6, mappedToAbstractHandler: abstractHandlers.onClick},
mouseWheel: {type: 7, mappedToAbstractHandler: abstractHandlers.onMouseWheel},
touchStart: {type: 8, mappedToAbstractHandler: abstractHandlers.onTouchStart},
touchEnd: {type: 9, mappedToAbstractHandler: abstractHandlers.onTouchEnd},
touchMove: {type: 10, mappedToAbstractHandler: abstractHandlers.onTouchMove},
touchCancel: {type: 11},
keyUp: {type: 12, mappedToAbstractHandler: abstractHandlers.onKeyUp},
keyPress: {type: 13, mappedToAbstractHandler: abstractHandlers.onKeyPress},
keyDown: {type: 14, mappedToAbstractHandler: abstractHandlers.onKeyDown},
focus: {type: 15, mappedToAbstractHandler: abstractHandlers.onFocus},
blur: {type: 16, mappedToAbstractHandler: abstractHandlers.onBlur},
scroll: {type: 17, mappedToAbstractHandler: abstractHandlers.onScroll},
change: {type: 18, mappedToAbstractHandler: abstractHandlers.onChange}
};
/**
* @_constructAbstractEventDirectlyFromTopLevel: helper function for the
* simplest types of event handlers that require no special inference. (A click
* is a click etc.)
*/
function _constructAbstractEventDirectlyFromTopLevel(topLevelEventType,
nativeEvent,
target) {
var data;
switch(topLevelEventType) {
case topLevelEvents.mouseWheel:
data = FEvent.normalizeAbstractMouseWheelEventData(nativeEvent, target);
break;
case topLevelEvents.scroll:
data = FEvent._normalizeAbstractScrollEventData(nativeEvent, target);
break;
case topLevelEvents.click:
case topLevelEvents.change:
case topLevelEvents.mouseDown:
case topLevelEvents.mouseUp:
case topLevelEvents.touchMove:
case topLevelEvents.touchStart:
case topLevelEvents.touchEnd:
data = FEvent._normalizeMouseData(nativeEvent, target);
break;
default:
data = {};
}
return new AbstractEvent(
topLevelEventType.mappedToAbstractHandler,
topLevelEventType,
target,
nativeEvent,
data);
}
FEvent = {
/**
* 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.
*/
abstractHandlers : abstractHandlers,
/**
* 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 (!FEvent.listeningYet) {
FEvent.registerTopLevelListeners(mountAt, touchInsteadOfMouse);
FEvent.listeningYet = true;
}
},
/** Puts a particular event listener on the queue. */
enqueueEventReg: function(id, listener) {
FEvent.abstractEventListenersById[
id + "@" + listener.listenForAbstractHandlerType] = listener;
},
/**
* Also performs the mapping from handler name to abstract event name.
*/
registerHandlerByName : function(domNodeId, propName, handler) {
if(FEvent.abstractHandlers[propName]) {
FEvent.enqueueEventReg(domNodeId, {
listenForAbstractHandlerType: FEvent.abstractHandlers[propName],
callThis: handler
});
}
},
/**
* @registerHandlers: Registers all applicable handlers.
*/
registerHandlers : function(domNodeId, props) {
var handlerName;
for (handlerName in FEvent.abstractHandlers) {
if (!FEvent.abstractHandlers.hasOwnProperty(handlerName)) {
continue;
}
var handler = props[handlerName];
if(handler) {
FEvent.enqueueEventReg(domNodeId, {
listenForAbstractHandlerType:
FEvent.abstractHandlers[handlerName],
callThis: handler
});
}
}
},
/**
* @trapCapturedEvent: Traps a top level event by using event capturing.
*/
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);
}
},
/**
* @trapBubbledEvent: Traps a top level event by using event bubbling.
* 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);
};
}
},
/**
* @_getTarget: x-browser normalization. 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: Some top level events directly map to
* an abstract handler type that a user of the event system would register.
*/
topLevelEventTypeIsUsableAsAbstract: function(topLevelEventType) {
return !!topLevelEventType.mappedToAbstractHandler;
},
/**
* @dispatchAllAbstractEventsToListeners: Given a particular dom node id, a
* mode of bubbling, and a list of abstract events that have occured at the
* top level - dispatches accordingly.
*/
dispatchAllAbstractEventsToListeners: function(id, mode, abstractEvents) {
var i, foundOne = false, maybeEventListener = null, abstractEvent,
abstractEventListenersById = FEvent.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 interesting 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 + '@',
abstractHandlers = FEvent.abstractHandlers,
abstractEventListenersById = FEvent.abstractEventListenersById,
mouseDownDragDesc = nextIdAt + (abstractHandlers.onDrag + mode),
touchStartDragDesc = nextIdAt + (abstractHandlers.onTouchDrag + mode),
mouseDownDragDoneDesc = nextIdAt + (abstractHandlers.onDragDone + mode),
touchStartDragDoneDesc = nextIdAt +
(abstractHandlers.onTouchDragDone + mode),
dragDesc =
topLevelEventType === topLevelEvents.mouseDown ? mouseDownDragDesc :
topLevelEventType === topLevelEvents.touchStart ?
touchStartDragDesc : false, // You won't be using it anyways.
dragDoneDesc = topLevelEventType === topLevelEvents.mouseDown ?
mouseDownDragDoneDesc :
topLevelEventType === topLevelEvents.touchStart ?
touchStartDragDoneDesc: false; // Won't be using it anyways.
var handledLowLevelEventByRegisteringDragListeners,
handledLowLevelEventByFindingRelevantListeners = false;
/** Lazily defined when we first need it. */
var abstractEvents = [],
newAbstractEvent,
globalX,
globalY;
if (topLevelEventType === topLevelEvents.mouseDown ||
topLevelEventType === topLevelEvents.touchStart) {
globalX = FEvent.eventGlobalX(nativeEvent, true);
globalY = FEvent.eventGlobalY(nativeEvent, true);
FEvent.currentlyPressingDown = true;
FEvent.lastTouchedDownAtX = globalX;
FEvent.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;
FEvent.activeDragListenersByListenerDesc[dragDesc] =
abstractEventListenersById[dragDesc];
FEvent.activeDragListenersCount++;
var activeDragDoneListenerForNextId =
abstractEventListenersById[dragDoneDesc];
if (activeDragDoneListenerForNextId) {
FEvent.activeDragDoneListenersByListenerDesc[dragDoneDesc] =
activeDragDoneListenerForNextId;
FEvent.activeDragDoneListenersCount++;
}
FEvent.lastTriggeredDragAtX = globalX; // not really, but works
FEvent.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) */
FEvent.lastTriggeredDragAtTime = 0;
}
}
} else if (topLevelEventType === topLevelEvents.touchEnd) {
globalX = FEvent.eventGlobalX(nativeEvent);
globalY = FEvent.eventGlobalY(nativeEvent);
var totalDistanceSinceLastTouchedDown =
Math.abs(globalX - FEvent.lastTouchedDownAtX) +
Math.abs(globalY - FEvent.lastTouchedDownAtY);
if (totalDistanceSinceLastTouchedDown < FEvent.TAP_MOVEMENT_THRESHOLD) {
/* Code below will search for handlers that are interested in this
* abstract event. */
abstractEvents.push(new AbstractEvent(
abstractHandlers.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 topLevelEvents. (such as
* onTouchStart etc).
*/
if (FEvent.topLevelEventTypeIsUsableAsAbstract(topLevelEventType)) {
/*
* Some abstract events are just simple one-one corresponding event types
* with top level events.
*/
abstractEvents.push(_constructAbstractEventDirectlyFromTopLevel(
topLevelEventType, nativeEvent, targ));
}
handledLowLevelEventByFindingRelevantListeners =
FEvent.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: FEvent.eventGlobalX(event),
globalY: FEvent.eventGlobalY(event),
rightMouseButton: FEvent._isNativeClickEventRightClick(event)
};
},
_normalizeAbstractDragEventData: function(event /*native*/,
globalX,
globalY,
lastTouchedDownAtX,
lastTouchedDownAtY) {
return {
globalX: globalX, globalY: globalY,
startX: lastTouchedDownAtX, startY: lastTouchedDownAtY
};
},
/**
* @_handleMouseInOut: 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 = FEvent.abstractEventListenersById;
if (topLevelEventType === topLevelEvents.mouseIn) {
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 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 + '@' + FEvent.abstractHandlers.onMouseOut
];
if (maybeEventListener) {
maybeEventListener.callThis(
new AbstractEvent(
FEvent.abstractHandlers.onMouseOut,
topLevelEventType, targ, nativeEvent, {}),
targ, nativeEvent);
}
var oldtrav = traverseId;
traverseId = traverseId.substr(0, traverseId.lastIndexOf('.'));
i++;
if (i > 200 ) {
FEvent.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 + '@' + FEvent.abstractHandlers.onMouseIn];
if (maybeEventListener) {
maybeEventListener.callThis(
new AbstractEvent(
FEvent.abstractHandlers.onMouseIn,
topLevelEventType,
nativeEvent,
{}
),
targ,
nativeEvent
);
}
i++;
if (i > 200 ) {
FEvent.Error('Runaway tree: ' + traverseId);
return;
}
}
}
return;
},
/**
* @handleMovementyTopLevelEvent: 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 (!FEvent.currentlyPressingDown) {
return;
}
var globalX, globalY, dragDesc, totalDistanceSinceLastDrag,
nowMs, totalMsSinceLastDrag;
globalX = FEvent.eventGlobalX(nativeEvent);
globalY = FEvent.eventGlobalY(nativeEvent);
if (FEvent.activeDragListenersCount) {
/* Not distance, but sum of deltas along both dimensions */
totalDistanceSinceLastDrag =
Math.abs(globalX - FEvent.lastTriggeredDragAtX) +
Math.abs(globalY - FEvent.lastTriggeredDragAtY);
nowMs = (new Date()).getTime();
totalMsSinceLastDrag = nowMs - FEvent.lastTriggeredDragAtTime;
if(totalDistanceSinceLastDrag < FEvent.DRAG_PIXEL_SAMPLE_RATE ||
totalMsSinceLastDrag < FEvent.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 FEvent.activeDragListenersByListenerDesc) {
if (!FEvent.
activeDragListenersByListenerDesc.hasOwnProperty(dragDesc)) {
continue;
}
var abstractEventData = FEvent._normalizeAbstractDragEventData(
nativeEvent, globalX, globalY,
FEvent.lastTouchedDownAtX,
FEvent.lastTouchedDownAtY),
listener = FEvent.activeDragListenersByListenerDesc[dragDesc];
var abstractEvent = new AbstractEvent(
topLevelEventType === topLevelEvents.touchMove ?
abstractHandlers.onTouchDrag :
abstractHandlers.onDrag,
topLevelEventType,
targ, nativeEvent, abstractEventData);
listener.callThis.call(
listener.context || null, abstractEvent, nativeEvent
);
}
FEvent.lastTriggeredDragAtX = globalX;
FEvent.lastTriggeredDragAtY = globalY;
FEvent.lastTriggeredDragAtTime = nowMs;
}
},
/**
* @_handleLetUppyTopLevelEvent: 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 = FEvent.eventGlobalX(nativeEvent);
globalY = FEvent.eventGlobalY(nativeEvent);
totalDistanceSinceLastTouchedDown =
Math.abs(globalX - FEvent.lastTouchedDownAtX) +
Math.abs(globalY - FEvent.lastTouchedDownAtY);
if (FEvent.activeDragDoneListenersCount) {
/* Only trigger the dragDone event if there has been some mouse movement
* while the mouse was depressed (at same quantizeDrag threshold
* (FEvent.DRAG_PIXEL_SAMPLE_RATE))*/
if(totalDistanceSinceLastTouchedDown > FEvent.DRAG_PIXEL_SAMPLE_RATE) {
for (dragDoneDesc in FEvent.activeDragDoneListenersByListenerDesc) {
if (!FEvent.activeDragDoneListenersByListenerDesc.
hasOwnProperty(dragDoneDesc)) {
continue;
}
activeDragDoneListenerForDragDesc =
FEvent.activeDragDoneListenersByListenerDesc[dragDoneDesc];
var abstractEvent = new AbstractEvent(
topLevelEventType === topLevelEvents.mouseUp ?
abstractHandlers.onDragDone :
abstractHandlers.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?
*/
FEvent.activeDragListenersByListenerDesc = {};
FEvent.currentlyPressingDown = false;
FEvent.activeDragListenersCount = 0;
FEvent.activeDragDoneListenersCount = 0;
FEvent.activeDragDoneListenersByListenerDesc = {};
FEvent.lastTouchedDownAtX = 0;
FEvent.lastTouchedDownAtY = 0;
}
};
/**
* @registerDocumentScrollListener: The F 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.
*/
FEvent.registerDocumentScrollListener = function() {
var previousDocumentScroll = document.onscroll;
document.onscroll = function(nativeEvent) {
if(nativeEvent.target === document) {
FEnv.refreshAuthoritativeScrollValues();
}
if(previousDocumentScroll) { previousDocumentScroll(nativeEvent); }
if (FEvent.applicationDocumentScrollListener) {
FEvent.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.
*/
FEvent.applicationResizeBatchTimeMs = 0;
FEvent.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) {