-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpointerEventWrapper.js
More file actions
588 lines (530 loc) · 23.3 KB
/
pointerEventWrapper.js
File metadata and controls
588 lines (530 loc) · 23.3 KB
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
/**
* Created by Simplex Studio, Ltd on 1/16/16.
*/
/**
* @namespace
* @description Provides an api for normalizing, handling, & binding the PointerEvent, MouseEvent, & TouchEvent.
* See the docs below and {@link PointerEvents.PointerEventWrapper|PointerEventWrapper} for more details.
* @version 0.1.0
* @author Simplex Studio, LTD
* @copyright Copyright (c) 2016 Simplex Studio, LTD
* @license The MIT License (MIT)
* Copyright (c) 2016 Simplex Studio, LTD
*
* 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.
*/
var PointerEvents = new function (){
/**
* @class
* A wrapper around a pointer like event which provides a constant set of properties across browsers and
* event types as well as some added value.
*
* Similar to `touchEvent.touches` and `touchEvent.changedTouches`, we implemented points and currentPoints. Since
* the pointerEvent has no similar properties, this is a way to provide some utility that we became accustomed to
* when working with pointerEvents. There are a few notable differences in the latter:
*
* - **`PointerEventWrapper.points`:** is an object indexed by a pointerId rather than an array like `touchEvent.touches`.
* This was a necessary change as PointerEvents provide a pointerId that does not start from zero.
*
* - **`PointerEventWrapper.points`:** Are updated at the end of a change event rather than at the start. This
* way the previous state of a changedPoint will always be available in points.
*
* - **`PointerEventWrapper.changedPoints`:** continue to use zero based indexing like `touchEvent.changedTouches`.
* This way you can still easily loop through changedTouches or work with only the first touch.
* - **`PointerEventWrapper.changedPoints`:** Contain a few extra properties such as `.deltaX` and `.deltaY`
* which are calculated base on the previous client position of a changed touch.
*
* - **`PointerEventWrapper.touches` & `PointerEventWrapper.changedTouches`:** Are equivalent to the
* old PointerEvent implementations for backwards compatibility with TouchEvents.
*
* >NOTE: touches and changedTouches should be considered depreciated and will be removed eventually.
*
* >IMPORTANT: `isTouch` will always be accurate. However, most TouchEvents are accompanied by
* fake MouseEvents in browsers that do not natively support the PointerEvent. Therefor `isMouse` & `isPen`
* will always be `undefined` in these browsers. Use `isTouch` for most cases.
*
* @description This class is returned by `PointerEvents.parse`.
*
* @param action {Event | string} - An Event object or action (event suffix as a string).
* @param permittedPrefixes {Array}- Array of permitted prefixes for this instance.
* @returns {PointerEventWrapper}
* @memberof PointerEvents
*/
var PointerEventWrapper = function(action, permittedPrefixes){
if (!(this instanceof PointerEventWrapper))
return new PointerEventWrapper(action)
// Allow action to be an event or valid action from POINTER_EVENT_ACTIONS
var event = typeof action == 'object'
? action.originalEvent || action : undefined
action = typeof action == 'string'
? action : undefined
/**
* PointerEvent is natively supported by browser.
* @type {boolean}
*/
this.hasPointer = window.PointerEvent || window.MSPointerEvent ? true : false
/**
* The original unmodified browser event.
* @type {Event}
*/
this.originalEvent = event // The original event
/**
* The action performed by the event.
* A non PointerEvent action (suffix) will be converted to a PointerType action
* TODO: This should be renamed pointerAction since it is always converted
* ie: touchstart -> down
* @type {string}
*/
this.eAction = action
/**
* The pointerType or the original event type (prefix) ex: touchstart -> touch (not modified)
* TODO: This should be renamed eventType
* @type {string}
*/
this.eType = ''
/**
* The eventTypes permitted for this instance.
* @type {Array}
*/
this.eventTypes = []
/**
* The pointer type responsible for the pointerEvent.
* TODO: should always be populated with pointerType || eType
* @type {string}
*/
this.pointerType = ''
/**
* Test for a confirmed touch Event.
* >NOTE: This property will always accurately reflect the presence of a touch.
* @type {boolean}
*/
this.isTouch = false
/**
* Test for a confirmed pen Event.
* >NOTE: The value will always be `undefined` when the PointerEvent is not
* natively supported by the browser.
* @type {boolean}
*/
this.isPen = false
/**
* Test for a confirmed mouse Event.
* >WARNING: The value will always be `undefined` when the PointerEvent is not
* natively supported by the browser.
* @type {boolean}
*/
this.isMouse = false
/**
* Test for a native PointerEvent
* @type {boolean}
*/
this.isPointer = false
/**
* Array of touches currently in contact with the surface (mimics `TouchEvent.touches`).
* >DEPRECIATED: This property is depreciated and will be removed eventually.
* @type {Array}
*/
this.touches = []
/**
* Array of touches triggering this event (mimics `TouchEvent.changedTouches`).
* >DEPRECIATED: This property is depreciated and will be removed eventually.
* @type {Array}
*/
this.changedTouches = []
/**
* Object containing all the points currently in contact withe the surface.
* If this event was triggered by removal of a point, the removed point will still exist.
* Each point is indexed by it's pointerId.
*
* Points contain the original event's properties as well as all PointerEvent
* properties weather the original event was a PointerEvent or not.
*
* Use {@link PointerEvents.PointerEventWrapper#changedTouches|changedTouches} to access the points triggering this event.
*
* >USAGE NOTE: This object differs from TouchEvent.touches which is an array and indexes
* always start at zero and removed points do not exist.
*
* @property length {number} The quantity of points in contact.
* @property array {Array} All points in contact as an array rather than on object.
* @property pointerId {point} each point will be indexed by it's unique pointerId.
* @type {{}}
*/
this.points = {length:0, array:[]}
/**
* Array of points triggering this event.
*
* Points contain the original event's properties as well as all PointerEvent
* properties weather the original event was a PointerEvent or not.
*
* Use {@link PointerEvents.PointerEventWrapper#points|points} [changedPoint.pointerId]
* to access the previous state of each point.
*
* @type {Array}
*/
this.changedPoints = []
this.init(permittedPrefixes)
if(this.originalEvent) this.parse(this.originalEvent)
}
PointerEventWrapper.prototype = function() {
// constants
var POINTER_TYPES = ['zero', 'one', 'touch', 'pen', 'mouse']
var POINTER_PREFIX = window.MSPointerEvent ? 'MSPointer' : 'pointer'
var PREFIXES = [POINTER_PREFIX, 'mouse', 'touch']
// class variables
var points = {length: 0, array: []}
var lastChangedPoints = []
// private vars
var _permittedPrefixes = ['mouse', 'touch']
// Allows Global prefixes limit changes
function permittedPrefixes(prefixes) {
if (prefixes) {
_permittedPrefixes = prefixes.split(' ')
}
return _permittedPrefixes
}
function toString() {
return this.eventTypes.join(' ')
}
function init(permittedPrefixes) {
this.eventTypes = getEventTypes.call(this, permittedPrefixes)
//console.info('PointerEventWrapper instantiated for ('+(this.eAction || this.originalEvent +' ts:'+this.originalEvent.timeStamp)+') with types: ', this.eventTypes)
}
// parse event
function parse(e) {
// remove jQuery wrapper
e = e.originalEvent || e
// Dont parse the same event twice!
if (this.originalEvent && this.originalEvent.timeStamp == e.timeStamp) return this
this.originalEvent = e
this.pointerType = getPointerType.call(this)
this.eType = eventPrefix.call(this)
this.eAction = suffixFromEvent.call(this)
this.eventTypes = getEventTypes.call(this)
// a touch event is sure to be touch
this.isTouch = this.pointerType == 'touch' || this.eType == 'touch'
// no way to know for sure without pointer event
this.isPen = this.pointerType == 'pen' || this.hasPointer ? false : undefined
// no way to know for sure without pointer event
this.isMouse = this.pointerType == 'mouse' || this.hasPointer ? false : undefined
// guaranteed by 'pointer' prefix
this.isPointer = this.eType.toLowerCase().indexOf('pointer') + 1
? true : false
setActionProp.call(this)
getPoints.call(this)
//todo: enable gestures
return this
}
/** Test for down action.
* @member PointerEventWrapper#down {PointerEventWrapper}
*/
/** Test for up action.
* @member PointerEventWrapper#up {PointerEventWrapper}
*/
/** Test for move action.
* @member PointerEventWrapper#move {PointerEventWrapper}
*/
/** Test for over action.
* @member PointerEventWrapper#over {PointerEventWrapper}
*/
/** Test for out action.
* @member PointerEventWrapper#out {PointerEventWrapper}
*/
/** Test for cancel action.
* @member PointerEventWrapper#cancel {PointerEventWrapper}
*/
/** Test for enter action.
* @member PointerEventWrapper#enter {PointerEventWrapper}
*/
/** Test for leave action.
* @member PointerEventWrapper#leave {PointerEventWrapper}
*/
function setActionProp() {
// Set action as a property when event.type is permitted.
// Allows test for pe.move etc..
if (this.eventTypes.indexOf(this.originalEvent.type) > -1)
this[this.eAction.toLowerCase()] = true
}
function getPoints() {
var changedPoints = []
var touchesArray = []
// create points & touches from TouchEvent
if (!this.isPointer && this.isTouch) {
// Just use the objects provided
changedPoints = this.originalEvent.changedTouches
touchesArray = this.originalEvent.touches
touchesToPoints.call(this, changedPoints, 'changed')
touchesToPoints.call(this, touchesArray)
}
// create points & touches from all non TouchEvent
else {
// Update points object
changedPoints = [this.originalEvent]
modifyPoints.call(this, changedPoints)
// Create backwards compatible array of touches
touchesArray = []
for (var k in points)
if (!isNaN(parseInt(k)))
touchesArray.push(points[k])
touchesArray.sort(function (a, b) {
return a.pointerId - b.pointerId
})
}
// For TouchEvent support on PointerEvent and nonPointerEvent browsers
if(this.isTouch) {
this.changedTouches = changedPoints
this.touches = touchesArray
}
this.changedPoints = changedPoints
points.array = touchesArray
this.points = points
}
/**
* Adds PointerEvent Properties to non pointer Events & modifies PointerEvent properties.
* @param newPoint
* @private
*/
function addPointerProps(newPoint){
var p = newPoint
// Assigning eType as pointerId when there is no pointerId
// means there can only be one at a time
p.pointerId = p.pointerId || p.identifier || this.eType
p.pointerType = this.pointerType || this.eType
p.isPrimary = isPrimary.call(this, p)
p.height = p.height || 0
p.width = p.width || 0
p.pressure = p.pressure || 0
p.tiltX = p.tiltX || 0
p.tiltY = p.tiltY || 0
// For TouchEvent support on PointerEvent and nonPointerEvent browsers
if(this.isTouch)
p.identifier = p.pointerId
}
function isPrimary(newPoint){
if (newPoint.isPrimary !== 'undefined') return newPoint.isPrimary
// Mouse is always primary
if (this.eType == 'mouse')
return true
// First touch is primary if no existing touch
// First pen is primary if no existing pen
else{
// Gather existing ids of same pointerType
var exIds = []
for (var id in points){
if (id in ['array', 'length']) continue
//console.log('test is primary for id:' + i)
var point = points[id]
if (point.pointerType == this.eType)
exIds.push(parseInt(point.pointerId))
}
// primary if pointerId equal to type
if (newPoint.pointerId == this.eType)
return true
// primary if pointerId equal to lowest id
if (newPoint.pointerId == Math.min.apply(Math,exIds))
return true
}
return false
}
function touchesToPoints(array, type){
var touch
for (var i in array || []) {
if (isNaN(parseInt(i))) break
touch = array[i]
touch.pointerId = touch.identifier
touch.timeStamp = this.originalEvent.timeStamp
}
if(type == 'changed')
modifyPoints.call(this, array)
}
function modifyPoints(modPoints){
//console.info('modifying points', modPoints)
// update existing points with previously changed values
var oldPoint, lcPoint
modPoints.timeStamp = this.originalEvent.timeStamp
if (lastChangedPoints.timeStamp !== modPoints.timeStamp) {
for (var i in lastChangedPoints) {
if (isNaN(parseInt(i))) break
lcPoint = lastChangedPoints[i]
oldPoint = points[lcPoint.pointerId]
if (oldPoint) {
points[lcPoint.pointerId] = lcPoint
}
}
lastChangedPoints = modPoints
}
// update existing points object & add pointer props
var newPoint
for (var i = 0; modPoints.length > i; i++) {
newPoint = modPoints[i]
// add properties before points objecect is updated
addPointerProps.call(this, newPoint)
// Add new point contact to points
if (this.eAction == 'down') {
points[newPoint.pointerId] = newPoint
points.length++
}
// Remove point contact from points
else if (this.eAction == 'up' || this.eAction == 'cancel') {
delete points[newPoint.pointerId]
points.length--
// Recalculate point values for changed items
} else {
oldPoint = points[newPoint.pointerId]
if (oldPoint) {
newPoint.deltaX = newPoint.clientX - oldPoint.clientX
newPoint.deltaY = newPoint.clientY - oldPoint.clientY
}
}
}
}
function eventPrefix(e){
e = e || this.originalEvent
if (this.pointerType) return this.pointerType
for (var s in PREFIXES) {
if (e.type.indexOf(PREFIXES[s]) + 1)
return PREFIXES[s]
}
//TODO: add handler for wheel & mousewheel? its part of PointerEvent Spec
//console.log('eventPrefix not found for:', e.type)
return e.type
}
function suffixFromEvent(e){
e = e && e.originalEvent ? e.originalEvent : e
var prefix = this.eType || eventPrefix.call(this, e)
var eventType = e ? e.type : this.originalEvent.type
var suffix = eventType.replace(prefix, '').toLowerCase()
// correct touch event suffix to pointer suffix
if (suffix == 'start') suffix = 'down'
if (suffix == 'end') suffix = 'up'
return suffix
}
function pointerToTouch(suffix){
// fix suffix for pointer events
if (suffix == 'down') suffix = 'start'
if (suffix == 'up') suffix = 'end'
return suffix
}
function getEventTypes(permittedPrefixes){
if (!this.eAction || !eventPermitted.call(this, this.eType)) return []
var eventTypes = []
var suffix = this.eAction
// add pointer event name
var pointerEventName = POINTER_PREFIX + suffix
if (window.MSPointerEvent)
pointerEventName = POINTER_PREFIX + suffix[0].toUpperCase() + suffix.substr(1);
eventTypes.push(pointerEventName)
// add other permitted event names
var prefixes = permittedPrefixes || _permittedPrefixes
for (var i in prefixes)
if(prefixes[i] == 'touch')
eventTypes.push(prefixes[i]+ pointerToTouch(suffix))
else
eventTypes.push(prefixes[i]+ (suffix))
return eventTypes
}
function eventPermitted(prefix){
if (!prefix || prefix == POINTER_PREFIX) return true
for (var p in _permittedPrefixes)
if (prefix == _permittedPrefixes[p])
return true
return false
}
// IE PointerType polyfill
function getPointerType(){
var e = this.originalEvent
return typeof e.pointerType == 'string' ? e.pointerType : POINTER_TYPES[e.pointerType]
}
return {toString:toString, parse:parse, init:init, permittedPrefixes:permittedPrefixes, suffixFromEvent:suffixFromEvent}
}()
/**
* Available pointer event actions.
* ["down", "up", "move", "over", "out", "cancel", "enter", "leave"]
* @type {string[]}
*/
this.POINTER_EVENT_ACTIONS = [ "down", "up", "move", "over", "out", "cancel", "enter", "leave"];
/** PointerEventWrapper bound to the down action.
* @member PointerEvents#down {PointerEventWrapper}
*/
/** PointerEventWrapper bound to the up action.
* @member PointerEvents#up {PointerEventWrapper}
*/
/** PointerEventWrapper bound to the move action.
* @member PointerEvents#move {PointerEventWrapper}
*/
/** PointerEventWrapper bound to the over action.
* @member PointerEvents#over {PointerEventWrapper}
*/
/** PointerEventWrapper bound to the out action.
* @member PointerEvents#out {PointerEventWrapper}
*/
/** PointerEventWrapper bound to the cancel action.
* @member PointerEvents#cancel {PointerEventWrapper}
*/
/** PointerEventWrapper bound to the enter action.
* @member PointerEvents#enter {PointerEventWrapper}
*/
/** PointerEventWrapper bound to the leave action.
* @member PointerEvents#leave {PointerEventWrapper}
*/
// Instantiate a PointerEventWrapper for each POINTER_EVENT_ACTIONS.
for (var i in this.POINTER_EVENT_ACTIONS){
var action = this.POINTER_EVENT_ACTIONS[i]
this[action] = PointerEventWrapper(action)
}
/** Determine if actual pointerEvents are available.
* @type {bool}
*/
this.available = window.PointerEvent || window.MSPointerEvent
/**
* Convenience method for binding event listeners to an element.
*
* Simply specify the action or actions to bind and the actual bound events wil be
* determined by what the browser supports automatically.
*
* @param element {HTMLElement} The element to bind the events
* @param action {string} Space separated string of event actions.
* @param callback{function} The callback for the events
*
* @example <caption>Bind all down and up events:</caption>
* PointerEvents.bind(document, 'down up', upDnHandler)
*/
this.bind = function(element, action, callback){
action = action.split(' ')
for (var i in action) {
var events = this[action[i]].toString().split(' ')
for (var i in events)
element.addEventListener(events[i], callback)
}
}
/**
* Returns a PointerEventWrapper for a given event.
* @param event {Event} The event to parse.
* @returns {PointerEventWrapper}
*
* @example <caption>Convert an event to a PointerEventWrapper</caption>
* function moveHandler(e){
* var pe = PointerEvents.parse(e)
* if(pe.isTouch)
* console.log('this is a touchmove event or pointermove with a touch pointerType'.)
* }
*/
this.parse = function (event){
var suffix = PointerEventWrapper.prototype.suffixFromEvent(event)
return this[suffix].parse(event)
}
}();