Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created July 26, 2013 17:40
Show Gist options
  • Select an option

  • Save WebReflection/6090740 to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/6090740 to your computer and use it in GitHub Desktop.
// ==========================================
// Copyright 2013 Twitter, Inc
// Licensed under The MIT License
// http://opensource.org/licenses/MIT
// ==========================================
// PROTOTYPE --- WON'T WORK, DON'T USE YET, WAIT FOR IT
define(function (require) {
'use strict';
/**
* TouchableComponent.attachTo(
* genericDomNode,
* // options
* {
* onAction: function (e){} // fired as very first action.
* onTap: function (e) {},
* onDoubleTap: function (e) {},
* onLongPressStart: function (e) {},
* onLongPressEnd: function (e) {},
* onPanStart: function (e.direction = 'vertical' || 'horizontal') {},
* onPanMove: function (x, y) {},
* onPanEnd: function (x, y) {},
* onKineticStart: function (x, y) {},
* onKineticMove: function (x, y) {},
* onKineticEnd: function (x, y) {},
* // SPECIAL NATIVE GUEST
* onClick: function (e) {
* // click has special privileges
* // if onAction prevents default
* // click is allowed and does the right thing
* // useful if we check the target
* // and we realize it's something that needs
* // a click that cannot be emulated
* },
* // FUTURE POSSIBILITIES
* onGestureStart,
* onGestureMove,
* onGestureEnd,
* onRage
* }
* );
*/
// SHARED UTILITIES
function commonCopy(source, target) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
function commonHelper(context, node, method) {
for (var key in context) {
if (
context.hasOwnProperty(key) &&
typeof context[key] === 'function' &&
key.charAt(0) !== '_'
) {
method.call(node, key, context);
}
}
}
function fixOptions(object) {
for(var
methods = [
'onAction',
'onTap',
'onDoubleTap',
'onLongPressStart',
'onLongPressEnd',
'onPanStart',
'onPanMove',
'onPanEnd',
'onKineticStart',
'onKineticEnd'
],
i = 0; i < methods.length; i++
) {
if (typeof object[methods[i]] !== 'function') {
object[methods[i]] = emptyCallback;
}
}
return object;
}
function emptyCallback() {}
function humanReadablePointerType(e) {
var pointerType = e.pointerType,
MOUSE = e.POINTER_TYPE_MOUSE || e.MSPOINTER_TYPE_MOUSE;
return (
e.pointerType === MOUSE ||
e.pointerType === 'mouse'
) ? 'mouse' : 'touch'; // right now pen is fine as touch
}
function push(item){
this.push(item);
}
/** Handler
* base class for all handlers. provides most basic
* DOM related methods. Extended by Touch and Pointer
*/
function Handler(events, options) {
commonCopy(events, this);
this._kinetic = new KineticHandler(this);
this._options = options;
}
Handler.prototype.addAsEventListener = function(node) {
if (this._start) {
this._start(node);
}
commonHelper(this, node, node.addEventListener, false);
};
Handler.prototype.removeAsEventListener = function(node) {
commonHelper(this, node, node.removeEventListener, false);
if (this._end) {
this._end(node);
}
};
Handler.prototype.handleEvent = function(e) {
this[e.type](e);
};
/** CommonBehavior (partial class)
* Methods used by all Handlers.
* These methods share most of the logic
* to understand gestures.
* See events object later on
*/
function CommonBehavior(logic) {
commonCopy(CommonBehavior.prototype, this);
commonCopy(logic, this);
}
CommonBehavior.prototype = {
_noKineticAfter: 90,
_slowDevice: 60,
_tollerance: 9,
_tapDelay: 150,
_longPressDelay: 750,
_start: function () {
this._tapTimer =
this._dblTapTimer =
this._longPressTimer = 0;
this._moving =
this._dragging =
this._clickAllowed = false;
},
_end: function () {
clearTimeout(this._tapTimer);
clearTimeout(this._dblTapTimer);
clearTimeout(this._longPressTimer);
this._kinetic.cancel();
this._start();
},
_tap: function (self, e) {
self._tapTimer = 0;
self._options.onTap(e);
},
_dblTap: function (self, e) {
self._dblTapTimer = 0;
self._options.onDoubleTap(e);
},
_longPress: function (self, e) {
clearTimeout(self._tapTimer);
self._tapTimer = self._longPressTimer = 0;
self._longPressed = true;
self._options.onLongPressStart(e);
},
click: function (e) {
if (this._clickAllowed) {
this._clickAllowed = false;
this._options.onClick(e);
}
},
_down: function (e) {
e.preventDefault();
e.stopPropagation();
this._moving = this._clickAllowed = false;
this._kinetic.cancel();
if (this._tapTimer) {
clearTimeout(this._tapTimer);
} else {
this._longPressTimer = setTimeout(
this._longPress, this._longPressDelay, this, e
);
}
},
_move: function () {
clearTimeout(this._tapTimer);
clearTimeout(this._longPressTimer);
this._tapTimer = this._longPressTimer = 0;
},
_initCoords: function (screenX, screenY, timeStamp) {
this._startX = this._currentX = screenX;
this._startY = this._currentY = screenY;
this._moveX = this._moveY = this._diffX = this._diffY = 0;
this._timeStamp = this._lastAction = timeStamp;
this._previousDelay =
this._timeStampDelay = 0;
this._halfTollerance = this._tollerance / 2;
this._halfTolleranceN = -this._halfTollerance;
this._incrementalX = this._incrementalY = 0;
},
_updateCoords: function (screenX, screenY, timeStamp) {
var newDelay;
if (this._previousDelay) {
newDelay = timeStamp - this._previousDelay;
this._timeStampDelay = this._timeStampDelay ?
(newDelay + this._timeStampDelay) / 2 : newDelay;
}
this._previousDelay = timeStamp;
this._diffX = screenX - this._startX;
this._diffY = screenY - this._startY;
this._moveX = screenX - this._currentX;
this._moveY = screenY - this._currentY;
this._currentX = screenX;
this._currentY = screenY;
this._incrementalX += this._moveX;
this._incrementalY += this._moveY;
if (
this._incrementalX < this._halfTolleranceN ||
this._incrementalY < this._halfTolleranceN ||
this._halfTollerance < this._incrementalX ||
this._halfTollerance < this._incrementalY
) {
this._lastAction = timeStamp;
this._incrementalX = this._incrementalY = 0;
}
this._options.onPanMove(this._diffX, this._diffY);
},
_up: function (e) {
if (this._longPressTimer) {
clearTimeout(this._longPressTimer);
this._longPressTimer = 0;
this._tapTimer = setTimeout(this._tap, this._tapDelay, this, e);
} else if (this._tapTimer) {
clearTimeout(this._tapTimer);
this._tapTimer = 0;
this._dblTapTimer = setTimeout(this._dblTap, this._tapDelay, this, e);
}
},
_handleKinetic: function (evt) {
this._moving = false;
this._options.onKineticStart(evt);
if (
evt.defaultPrevented ||
this._slowDevice < this._timeStampDelay ||
(this._noKineticAfter < (Date.now() - this._lastAction)) ||
!this._kinetic.starting(
this._diffX, this._diffY,
this._moveX, this._moveY
)
) {
this._options.onPanEnd(evt);
}
},
_upEndIf: function (evt, condition) {
if (condition && this._longPressed) {
this._longPressed = false;
this._options.onLongPressEnd(evt);
}
}
};
/** SimpleKinetic
* used to calculate direction and deceleration
* It copies over the handler properties/method
* to directly delegate all calls
* (see KineticHandler)
*/
function SimpleKinetic(handlers) {
commonCopy(handlers, this);
}
(function(window, SimpleKineticPrototype){
var
isNaN = window.isNaN,
Math = window.Math,
abs = Math.abs,
round = Math.round,
sqrt = Math.sqrt,
setInterval = window.setInterval,
clearInterval = window.clearInterval,
friction = .2,
multiplier = 9,
FPS = 1000 / 60
;
function clear(self) {
clearInterval(self._a);
self._a = 0;
return self;
}
function next(self) {
// all these properties accessed at runtime ... disturbing *but*
// it avoids creation of N functions over N objects per each kinetic
var
t = (self._t += (self._d - self._t) * friction),
x = round(self._sx + t * self._xa),
y = round(self._sy + t * self._ya)
;
if (x === self._ex && y === self._ey) {
clear(self).end(self._ex, self._ey);
} else {
self.move(x - self._cx, y - self._cy);
self._cx = x;
self._cy = y;
}
}
SimpleKineticPrototype.onstart =
SimpleKineticPrototype.onmove =
SimpleKineticPrototype.onend =
SimpleKineticPrototype.oncancel = function (x, y) {
// avoid checks every single call ... by default: invoked
};
SimpleKineticPrototype.start = function (x, y) {
return this.onstart.call(this.context || this, x, y);
};
SimpleKineticPrototype.move = function (x, y) {
this.onmove.call(this.context || this, x, y);
};
SimpleKineticPrototype.end = function (x, y) {
this.onend.call(this.context || this, x, y);
};
SimpleKineticPrototype.cancel = function (x, y) {
if (this._a) {
clear(this).oncancel.call(this.context || this, x, y);
}
};
SimpleKineticPrototype.init = function (x, y, xdist, ydist) {
var
self = this,
xdist1 = (abs(xdist) < 1 ? 0 : xdist) * multiplier,
ydist1 = (abs(ydist) < 1 ? 0 : ydist) * multiplier,
xdist2 = xdist1 * xdist1,
ydist2 = ydist1 * ydist1,
distance = sqrt(xdist2 + ydist2),
xangle = xdist1 / distance,
yangle = ydist1 / distance;
;
self.cancel(self._cx, self._cy);
if (!(isNaN(xangle) || isNaN(yangle))) {
self._t = 0;
self._d = distance;
self._sx = self._cx = x;
self._sy = self._cy = y;
self._ex = round(x + distance * xangle);
self._ey = round(y + distance * yangle);
self._xa = xangle;
self._ya = yangle;
if (self.start(x, y) !== false) {
self._a = setInterval(next, FPS, self);
return true;
}
}
return false;
};
}(window, SimpleKinetic.prototype));
/** KineticHandler
* using SimpleKinetic under the hood,
* notify any handler about kinetic status
*/
function KineticHandler(handler) {
this._handler = handler;
this.context = this;
this.onstart = this.onstart;
this.onmove = this.onmove;
this.onend = this.onend;
this.oncancel = this.oncancel;
this._kinetic = new SimpleKinetic(this);
}
(function(KineticHandlerPrototype){
KineticHandlerPrototype.onstart = function (x, y) {
this.x = x;
this.y = y;
this._handler._options.onKineticMove(x, y);
};
KineticHandlerPrototype.onmove = function (incrementX, incrementY) {
this.x += incrementX;
this.y += incrementY;
this._handler._options.onKineticMove(this.x, this.y);
};
KineticHandlerPrototype.onend = function (x, y) {
this._handler._options.onKineticMove(this.x, this.y);
this.oncancel(x, y);
};
KineticHandlerPrototype.oncancel = function (x, y) {
this._handler._options.onKineticEnd(this.x, this.y);
this._handler._options.onPanEnd({});
};
KineticHandlerPrototype.cancel = function (x, y) {
this._kinetic.cancel(x, y);
};
KineticHandlerPrototype.starting = function(x, y, distx, disty) {
return this._kinetic.init(x, y, distx, disty);
};
}(KineticHandler.prototype));
// private recycled variables
var
MSPointerEvents = new CommonBehavior(),
events = {
mouse: new CommonBehavior({
_tapDelay: 100,
_longPressDelay: 500,
mousedown: function (e) {
var add;
if (e.button === 2) return;
// if prevent default is called to the custom event
// click should be allowed and nothing else executed
this._options.onAction(e);
if (e.defaultPrevented) {
this._clickAllowed = true;
this._end();
} else {
this._down(e);
this._initCoords(e.pageX, e.pageY, e.timeStamp);
this._dragging = true;
add = document.addEventListener;
add.call(document, 'mousemove', this, true);
add.call(document, 'mouseup', this, true);
}
},
mousemove: function (e) {
if (this._dragging) {
e.stopPropagation();
if (!this._moving) {
this._moving = true;
this._move();
this._options.onPanStart(e);
}
if (e.currentTarget === document) {
this._updateCoords(e.pageX, e.pageY, e.timeStamp);
}
}
},
mouseup: function (e) {
var remove;
this._dragging = false;
e.stopPropagation();
if (e.currentTarget === document) {
remove = document.removeEventListener;
remove.call(document, 'mousemove', this, true);
remove.call(document, 'mouseup', this, true);
if (this._moving) {
this._handleKinetic();
} else {
this._up(e);
}
this._upEndIf(e, true);
}
}
/*,
contextmenu: function (e) {
// NOT IMPLEMENTED YET
},
mousewheel: function (e) {
// NOT IMPLEMENTED YET
}
*/
}),
touch: new CommonBehavior({
touchstart: function (evt) {
var touches = evt.touches,
length = touches.length, // for future events with gestures
e = touches[0];
if (1 < length) return; // not supported right now
// if prevent default is called to the custom event
// click should be allowed and nothing else executed
this._options.onAction(evt);
if (evt.defaultPrevented) {
this._clickAllowed = true;
this._end();
} else {
this._down(evt);
this._initCoords(e.pageX, e.pageY, evt.timeStamp);
}
},
touchmove: function (evt) {
var e = evt.touches[0],
movedX, movedY;
evt.stopPropagation();
if (this._moving) {
this._updateCoords(e.pageX, e.pageY, evt.timeStamp);
} else {
movedX = this._tollerance < Math.abs(e.pageX - this._startX);
movedY = this._tollerance < Math.abs(e.pageY - this._startY);
if (movedX || movedY) {
this._move();
this._moving = true;
this._startX = e.pageX;
this._startY = e.pageY;
evt.direction = movedY ? 'vertical' : 'horizontal';
this._options.onPanStart(evt);
}
}
},
touchend: function (evt) {
var length = evt.touches.length;
evt.stopPropagation();
if (this._moving && !length) {
this._handleKinetic(evt);
} else {
this._up(evt);
}
this._upEndIf(evt, !length);
}
/*,
touchcancel: function (e) {
// NOT IMPLEMENTED YET
}
*/
}),
MSPoi: MSPointerEvents,
point: new CommonBehavior({
pointerdown: MSPointerEvents.MSPointerDown = function (e) {
var handler = events[humanReadablePointerType(e)];
e.touches = [e];
handler[handler === events.touch ? 'touchstart' : 'mousedown'].call(this, e);
},
pointermove: MSPointerEvents.MSPointerMove = function (e) {
var handler = events[humanReadablePointerType(e)];
e.touches = [e];
handler[handler === events.touch ? 'touchmove' : 'mousemove'].call(this, e);
},
pointerout: MSPointerEvents.MSPointerOut = function (e) {
if (humanReadablePointerType(e) === 'touch') {
e.touches = Array.prototype;
events.touch.touchend.call(this, e);
}
},
pointerup: MSPointerEvents.MSPointerUp = function (e) {
if (humanReadablePointerType(e) === 'mouse') {
events.mouse.mouseup.call(this, e);
}
}
/*
,
pointercancel: MSPointerEvents.MSPointerCancel = function (e) {
// NOT IMPLEMENTED YET
},
pointerleave: MSPointerEvents.MSPointerLeave = function (e) {
// NOT IMPLEMENTED YET
},
pointerover: MSPointerEvents.MSPointerOver = function (e) {
// NOT IMPLEMENTED YET
},
pointerenter: MSPointerEvents.MSPointerEnter = function (e) {
// NOT IMPLEMENTED YET
}
// gotpointercapture,
// lostpointercapture
*/
})
},
allEventsName = [],
lastFiredEventTime = 0,
pointerEnabled = !!(
navigator.pointerEnabled ||
navigator.msPointerEnabled
)
;
if (pointerEnabled) {
commonHelper(events.MSPoi, allEventsName, push);
commonHelper(events.point, allEventsName, push);
} else {
commonHelper(events.mouse, allEventsName, push);
commonHelper(events.touch, allEventsName, push);
}
/** Touchable
* the actual class in charge of organizing everything.
*/
function Touchable(node, options) {
this._options = options;
addOrRemove(this, node, node.addEventListener);
}
Touchable.prototype._kind = '';
Touchable.prototype.clear = function (node) {
addOrRemove(this, node, node.removeEventListener);
};
Touchable.prototype.handleEvent = pointerEnabled ?
function handlePointerEvents(e) {
var type = e.type,
eventKind = humanReadablePointerType(e),
current,
node;
if (
// user changed pointer type
this._kind !== eventKind &&
// or this is a click without a type ..
e.pointerType
) {
this._kind = eventKind;
document.title = this._kind;
node = e.currentTarget;
current = this._current;
if (current) {
current.removeAsEventListener(node);
}
(this._current = new Handler(
events[type.slice(0, 5)]
), this._options).addAsEventListener(node);
this._current[type](e);
}
} :
function handleMouseOrTouch(e) {
var
type = e.type,
timeStamp = e.timeStamp,
isTouch = type.slice(0, 5) === 'touch',
eventKind = isTouch ? 'touch' : 'mouse',
current,
node
;
if (
// there is handlers concurrency
// or no handler has ever been set
eventKind !== this._kind && (
// touches always priviledges
// when it comes to concurrent events
isTouch || (
// is not a concurrent event
999 < (timeStamp - lastFiredEventTime)
)
)
) {
this._kind = eventKind;
document.title = this._kind;
node = e.currentTarget;
current = this._current;
if (current) {
current.removeAsEventListener(node);
}
(this._current = new Handler(
events[eventKind]
), this._options).addAsEventListener(node);
this._current[e.type](e);
}
lastFiredEventTime = timeStamp;
}
;
return require('flight/lib/component')(function TouchableComponent() {
var touchable;
this.cancel = function () {
// stop kinetics ?
};
this.initialize = function (node, options) {
if (touchable) throw new Error('unable to recycle a TouchableComponent');
touchable = new Touchable(node, fixOptions(options || {}));
};
this.teardown = function () {
touchable.clear();
touchable = null;
};
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment