forked from SitePen/dgrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TouchScroll.js
646 lines (555 loc) · 20.5 KB
/
TouchScroll.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
// FIXME:
// * fully make use of transitions in glide routines
define(["dojo/_base/declare", "dojo/on", "./util/touch", "./util/has-css3", "put-selector/put", "xstyle/css!./css/TouchScroll.css"],
function(declare, on, touchUtil, has, put){
var
calcTimerRes = 50, // ms between drag velocity measurements
glideTimerRes = 30, // ms between glide animation ticks
current = {}, // records info for widget(s) currently being scrolled
previous = {}, // records info for widget(s) that were in the middle of being scrolled when someone decided to scroll again
glideThreshold = 1, // speed (in px) below which to stop glide - TODO: remove
scrollbarAdjustment = 8, // number of px to adjust scrollbar dimension calculations
// RegExps for parsing relevant x/y from translate and matrix values:
translateRx = /^translate(?:3d)?\((-?\d+)(?:\.\d*)?(?:px)?, (-?\d+)/,
matrixRx = /^matrix\(1, 0, 0, 1, (-?\d+)(?:\.\d*)?(?:px)?, (-?\d+)/,
// store has-features we need, for computing property/function names:
hasTransitions = has("css-transitions"),
hasTransitionEnd = has("transitionend"),
hasTransforms = has("css-transforms"),
hasTransforms3d = has("css-transforms3d"),
// and declare vars to store info on the properties/functions we'll need
cssPrefix, transitionPrefix, transformProp, translatePrefix, translateSuffix;
if(hasTransforms3d){
translatePrefix = "translate3d(";
translateSuffix = ",0)";
}else if(hasTransforms){
translatePrefix = "translate(";
translateSuffix = ")";
}
if(!hasTransitions || !translatePrefix){
console.warn("CSS3 features unavailable for touch scroll effects.");
return function(){};
}
// figure out strings for use later in events
transformProp = hasTransforms3d || hasTransforms;
transformProp = transformProp === true ? "transform" : transformProp + "Transform";
transitionPrefix = hasTransitions === true ? "transition" :
hasTransitions + "Transition";
cssPrefix = hasTransforms === true ? "" :
"-" + hasTransforms.toLowerCase() + "-";
function showScrollbars(widget, curr){
// Handles displaying of X/Y scrollbars as appropriate when a touchstart
// occurs.
var node = widget.touchNode,
parentNode = node.parentNode,
adjustedParentWidth = parentNode.offsetWidth - scrollbarAdjustment,
adjustedParentHeight = parentNode.offsetHeight - scrollbarAdjustment,
// Also populate scroll/offset properties on curr for reuse,
// to avoid having to repeatedly hit the DOM.
scrollWidth = curr.scrollWidth = node.scrollWidth,
scrollHeight = curr.scrollHeight = node.scrollHeight,
parentWidth = curr.parentWidth = parentNode.offsetWidth,
parentHeight = curr.parentHeight = parentNode.offsetHeight,
scrollbarNode;
if(scrollWidth > parentWidth){
if(!widget._scrollbarXNode){
scrollbarNode = put(parentNode, "div.touchscroll-x");
}
scrollbarNode = widget._scrollbarXNode =
widget._scrollbarXNode || put(scrollbarNode, "div.touchscroll-bar");
scrollbarNode.style.width =
adjustedParentWidth * adjustedParentWidth / scrollWidth + "px";
scrollbarNode.style.left = node.offsetLeft + "px";
put(parentNode, ".touchscroll-scrollable-x");
curr.scrollableX = true;
}else{
put(parentNode, "!touchscroll-scrollable-x");
}
if(scrollHeight > parentHeight){
if(!widget._scrollbarYNode){
scrollbarNode = put(parentNode, "div.touchscroll-y");
}
scrollbarNode = widget._scrollbarYNode =
widget._scrollbarYNode || put(scrollbarNode, "div.touchscroll-bar");
scrollbarNode.style.height =
adjustedParentHeight * adjustedParentHeight / scrollHeight + "px";
scrollbarNode.style.top = node.offsetTop + "px";
put(parentNode, ".touchscroll-scrollable-y");
curr.scrollableY = true;
}else{
put(parentNode, "!touchscroll-scrollable-y");
}
put(parentNode, "!touchscroll-fadeout");
}
function scroll(widget, options){
// Handles updating of scroll position (from touchmove or glide).
var node = widget.touchNode,
curr = current[widget.id],
pos, hasX, hasY, x, y;
if(typeof options !== "object"){
// Allow x, y to be passed directly w/o extra object creation.
// (e.g. from ontouchmove)
x = options;
y = arguments[2];
options = arguments[3];
hasX = hasY = true;
}else{
hasX = "x" in options;
hasY = "y" in options;
// If either x or y weren't specified, pass through the current value.
if(!hasX || !hasY){
pos = widget.getScrollPosition();
}
x = hasX ? options.x : pos.x;
y = hasY ? options.y : pos.y;
}
// Update transform on touchNode
node.style[transformProp] =
translatePrefix + -x + "px," + -y + "px" + translateSuffix;
// Update scrollbar positions
if(curr && hasX && widget._scrollbarXNode){
widget._scrollbarXNode.style[transformProp] = translatePrefix +
(x * curr.parentWidth / curr.scrollWidth) + "px,0" + translateSuffix;
}
if(curr && hasY && widget._scrollbarYNode){
widget._scrollbarYNode.style[transformProp] = translatePrefix + "0," +
(y * curr.parentHeight / curr.scrollHeight) + "px" + translateSuffix;
}
// Emit a scroll event that can be captured by handlers, passing along
// scroll information in the event itself (since we already have the info,
// and it'd be difficult to get from the node).
on.emit(widget.touchNode.parentNode, "scroll", {
scrollLeft: x,
scrollTop: y
});
}
function getScrollStyle(widget){
// Returns match object for current scroll position based on transform.
if(current[widget.id]){
// Mid-transition: determine current X/Y from computed values.
return matrixRx.exec(window.getComputedStyle(widget.touchNode)[transformProp]);
}
// Otherwise, determine current X/Y from applied style.
return translateRx.exec(widget.touchNode.style[transformProp]);
}
function resetEffects(options){
// Function to cut glide/bounce short, called in context of an object
// from the current hash; attached only when a glide or bounce occurs.
// Called on touchstart, when touch scrolling is canceled, when
// momentum/bounce finishes, and by scrollTo on instances (in case it's
// called directly during a glide/bounce).
var widget = this.widget,
nodes = [this.node, widget._scrollbarXNode, widget._scrollbarYNode],
i = nodes.length;
// Clear glide timer.
if(this.timer){
clearTimeout(this.timer);
this.timer = null;
}
// Clear transition handlers, as we're about to cut it short.
if(this.transitionHandler){
// Unhook any existing transitionend handler, since we'll be
// canceling the transition.
this.transitionHandler.remove();
}
// Clear transition duration on main node and scrollbars.
while(i--){
if(nodes[i]){ nodes[i].style[transitionPrefix + "Duration"] = "0"; }
}
// Fade out scrollbars unless indicated otherwise (e.g. re-touch).
if(!options || !options.preserveScrollbars){
put(this.node.parentNode, ".touchscroll-fadeout");
}
// Remove this method so it can't be called again.
delete this.resetEffects;
}
// functions for handling touch events on node to be scrolled
function ontouchstart(evt){
var widget = evt.widget,
node = widget.touchNode,
id = widget.id,
posX = 0,
posY = 0,
touch, match, curr;
// Check touches count (which hasn't counted this event yet);
// ignore touch events on inappropriate number of contact points.
if(touchUtil.countCurrentTouches(evt, node) !== widget.touchesToScroll){
return;
}
match = getScrollStyle(widget);
if(match){
posX = +match[1];
posY = +match[2];
}
if((curr = current[id])){
// stop any active glide or bounce, since it's been re-touched
if(curr.resetEffects){
curr.resetEffects({ preserveScrollbars: true });
}
node.style[transformProp] =
translatePrefix + posX + "px," + posY + "px" + translateSuffix;
previous[id] = curr;
}
touch = evt.targetTouches[0];
curr = current[id] = {
widget: widget,
node: node,
// Subtract touch coords now, then add back later, so that translation
// goes further negative when moving upwards.
startX: posX - touch.pageX,
startY: posY - touch.pageY,
// Initialize lastX/Y, in case of a fast flick (< 1 full calc cycle).
lastX: posX,
lastY: posY,
// Also store original pageX/Y for threshold check.
pageX: touch.pageX,
pageY: touch.pageY,
tickFunc: function(){ calcTick(id); }
};
curr.timer = setTimeout(curr.tickFunc, calcTimerRes);
}
function ontouchmove(evt){
var widget = evt.widget,
id = widget.id,
touchesToScroll = widget.touchesToScroll,
curr = current[id],
activeTouches, targetTouches, touch, nx, ny, minX, minY, i;
// Ignore touchmove events with inappropriate number of contact points.
if(!curr || (activeTouches = touchUtil.countCurrentTouches(evt, widget.touchNode)) !== touchesToScroll){
// Also cancel touch scrolling if there are too many contact points.
if(activeTouches > touchesToScroll){
widget.cancelTouchScroll();
}
return;
}
targetTouches = evt.targetTouches;
touch = targetTouches[0];
// Show touch scrollbars on first sign of drag.
if(!curr.scrollbarsShown){
if(previous[id] || (
Math.abs(touch.pageX - curr.pageX) > widget.scrollThreshold ||
Math.abs(touch.pageY - curr.pageY) > widget.scrollThreshold)){
showScrollbars(widget, curr);
curr.scrollbarsShown = true;
// Add flag to involved touches to provide indication to other handlers.
for(i = targetTouches.length; i--;){
targetTouches[i].touchScrolled = true;
}
}
}
if(curr.scrollbarsShown && (curr.scrollableX || curr.scrollableY)){
// If area can be scrolled, prevent default behavior and perform scroll.
evt.preventDefault();
nx = curr.scrollableX ? curr.startX + touch.pageX : 0;
ny = curr.scrollableY ? curr.startY + touch.pageY : 0;
minX = curr.scrollableX ? -(curr.scrollWidth - curr.parentWidth) : 0;
minY = curr.scrollableY ? -(curr.scrollHeight - curr.parentHeight) : 0;
// If dragged beyond edge, halve the distance between.
if(nx > 0){
nx = nx / 2;
}else if(nx < minX){
nx = minX - (minX - nx) / 2;
}
if(ny > 0){
ny = ny / 2;
}else if(ny < minY){
ny = minY - (minY - ny) / 2;
}
scroll(widget, -nx, -ny); // call scroll with positive coordinates
}
}
function ontouchend(evt){
var widget = evt.widget,
id = widget.id,
curr = current[id];
if(!curr || touchUtil.countCurrentTouches(evt, widget.touchNode) != widget.touchesToScroll - 1){
return;
}
startGlide(id);
}
// glide-related functions
function calcTick(id){
// Calculates current speed of touch drag
var curr = current[id],
node, match, x, y;
if(!curr){ return; } // no currently-scrolling widget; abort
node = curr.node;
match = translateRx.exec(node.style[transformProp]);
if(match){
x = +match[1];
y = +match[2];
// If previous reference point already exists, calculate velocity
curr.velX = x - curr.lastX;
curr.velY = y - curr.lastY;
// set previous reference point for future iteration or calculation
curr.lastX = x;
curr.lastY = y;
} else {
curr.lastX = curr.lastY = 0;
}
curr.timer = setTimeout(curr.tickFunc, calcTimerRes);
}
function bounce(id, lastX, lastY){
// Function called when a scroll ends, to handle rubber-banding beyond edges.
var curr = current[id],
widget = curr.widget,
node = curr.node,
scrollbarNode,
x = curr.scrollableX ?
Math.max(Math.min(0, lastX), -(curr.scrollWidth - curr.parentWidth)) :
lastX,
y = curr.scrollableY ?
Math.max(Math.min(0, lastY), -(curr.scrollHeight - curr.parentHeight)) :
lastY;
function end(){
// Performs reset operations upon end of scroll process.
// Since transitions have run, delete transitionHandler up-front
// (since it auto-removed itself anyway), then let
// resetEffects do the rest of its usual job.
delete curr.transitionHandler;
curr.resetEffects();
delete current[id];
}
// Timeout will have been cleared before bounce call, so remove timer.
delete curr.timer;
if (x != lastX || y != lastY){
curr.transitionHandler = on.once(node, hasTransitionEnd, end);
node.style[transitionPrefix + "Duration"] = widget.bounceDuration + "ms";
node.style[transformProp] =
translatePrefix + x + "px," + y + "px" + translateSuffix;
// Also handle transitions for scrollbars.
if(x != lastX && curr.scrollableX){
scrollbarNode = curr.widget._scrollbarXNode;
scrollbarNode.style[transitionPrefix + "Duration"] =
widget.bounceDuration + "ms";
if(lastX > x){
// Further left; bounce back right
scrollbarNode.style[transformProp] =
translatePrefix + "0,0" + translateSuffix;
}else{
// Further right; bounce back left
scrollbarNode.style[transformProp] =
translatePrefix +
(scrollbarNode.parentNode.offsetWidth - scrollbarNode.offsetWidth) +
"px,0" + translateSuffix;
}
}
if(y != lastY && curr.scrollableY){
scrollbarNode = curr.widget._scrollbarYNode;
scrollbarNode.style[transitionPrefix + "Duration"] =
widget.bounceDuration + "ms";
if(lastY > y){
// Above top; bounce back down
scrollbarNode.style[transformProp] =
translatePrefix + "0,0" + translateSuffix;
}else{
// Below bottom; bounce back up
scrollbarNode.style[transformProp] =
translatePrefix + "0," +
(scrollbarNode.parentNode.offsetHeight - scrollbarNode.offsetHeight) +
"px" + translateSuffix;
}
}
}else{
end(); // no rubber-banding necessary; just reset
}
}
function startGlide(id){
// starts glide operation when drag ends
var curr = current[id],
prev = previous[id],
match, posX, posY,
INERTIA_ACCELERATION = 1.15;
delete previous[id];
if(curr.timer){ clearTimeout(curr.timer); }
// Enable usage of resetEffects during glide or bounce.
curr.resetEffects = resetEffects;
// calculate velocity based on time and displacement since last tick
match = translateRx.exec(curr.node.style[transformProp]);
if(match){
posX = +match[1];
posY = +match[2];
} else {
posX = posY = 0;
}
// If there is no glide to perform (no exit velocity), or if we are
// beyond boundaries on all applicable edges, immediately bounce back.
if((!curr.velX && !curr.velY) ||
((posX >= 0 || posX <= -(curr.scrollWidth - curr.parentWidth)) &&
(posY >= 0 || posY <= -(curr.scrollHeight - curr.parentHeight)))){
bounce(id, posX, posY);
return;
}
function sameSign(a, b){
return ((a.velX <= 0 && b.velX <= 0) || (a.velX >= 0 && b.velX >= 0)) &&
((a.velY <= 0 && b.velY <= 0) || (a.velY >= 0 && b.velY >= 0));
}
if(prev && (prev.velX || prev.velY) && sameSign(curr, prev)){
curr.velX = (curr.velX + prev.velX) * INERTIA_ACCELERATION;
curr.velY = (curr.velY + prev.velY) * INERTIA_ACCELERATION;
}
// update lastX/Y with current position, for glide calculations
curr.lastX = posX;
curr.lastY = posY;
curr.calcFunc = function(){ calcGlide(id); };
curr.timer = setTimeout(curr.calcFunc, glideTimerRes);
}
function calcGlide(id){
// performs glide and decelerates according to widget's glideDecel method
var curr = current[id],
node, parentNode, widget, i,
nx, ny, nvx, nvy, // old/new coords and new velocities
BOUNCE_DECELERATION_AMOUNT = 6;
if(!curr){ return; }
node = curr.node;
parentNode = node.parentNode;
widget = curr.widget;
nvx = widget.glideDecel(curr.velX);
nvy = widget.glideDecel(curr.velY);
if(Math.abs(nvx) >= glideThreshold || Math.abs(nvy) >= glideThreshold){
// still above stop threshold; update transformation
nx = curr.lastX + nvx;
ny = curr.lastY + nvy;
// If glide has traveled beyond any edges, institute rubber-band effect
// by further decelerating.
if(nx > 0 || nx < -(curr.scrollWidth - curr.parentWidth)){
for(i = BOUNCE_DECELERATION_AMOUNT; i--;){
nvx = widget.glideDecel(nvx);
}
}
if(ny > 0 || ny < -(curr.scrollHeight - curr.parentHeight)){
for(i = BOUNCE_DECELERATION_AMOUNT; i--;){
nvy = widget.glideDecel(nvy);
}
}
// still scrollable; update offsets/velocities and schedule next tick
scroll(widget, -nx, -ny); // call scroll with positive coordinates
// update information
curr.lastX = nx;
curr.lastY = ny;
curr.velX = nvx;
curr.velY = nvy;
curr.timer = setTimeout(curr.calcFunc, glideTimerRes);
}else{
bounce(id, curr.lastX, curr.lastY);
}
}
return declare(null, {
// touchesToScroll: Number
// Number of touches to require on the component's touch target node
// in order to trigger scrolling behavior.
touchesToScroll: 1,
// touchNode: DOMNode?
// Node upon which scroll behavior will be based; transformations will be
// applied to this node, and events and some DOM/styles will be applied
// to its *parent*. If not specified, defaults to containerNode.
touchNode: null,
// scrollThreshold: Number
// Minimum number of pixels to wait for user to scroll (in any direction)
// before initiating scroll.
scrollThreshold: 10,
// bounceDuration: Number
// Number of milliseconds which "rubber-banding" transitions
// (i.e. bouncing back from beyond edges) should take.
bounceDuration: 300,
postCreate: function(){
this._initTouch();
this.inherited(arguments);
},
_initTouch: function(){
var node = this.touchNode = this.touchNode || this.containerNode,
widget = this,
parentNode;
if(!node || !node.parentNode){
// Bail out if we have no touchNode or containerNode, or if we don't
// seem to have a parent node to work with.
console.warn("TouchScroll requires a nested node upon which to operate.");
return;
}
parentNode = node.parentNode;
// Set overflow to hidden in order to prevent any native scroll logic.
parentNode.style.overflow = "hidden";
node.style[transitionPrefix + "Property"] = cssPrefix + "transform";
node.style[transitionPrefix + "TimingFunction"] =
"cubic-bezier(0.33, 0.66, 0.66, 1)";
function cancelTouchScroll(){
widget.cancelTouchScroll();
}
function wrapHandler(func){
return function(evt){
evt.widget = widget;
evt.cancelTouchScroll = cancelTouchScroll;
func.call(this, evt);
};
}
this._touchScrollListeners = [
on(parentNode, "touchstart", wrapHandler(ontouchstart)),
on(parentNode, "touchmove", wrapHandler(ontouchmove)),
on(parentNode, "touchend,touchcancel", wrapHandler(ontouchend))
];
},
destroy: function(){
var i = this._touchScrollListeners.length;
while(i--){
this._touchScrollListeners[i].remove();
}
delete current[this.id];
this.inherited(arguments);
},
scrollTo: function(options){
// summary:
// Scrolls the widget to a specific position.
// options: Object
// Object containing target x and/or y position to scroll to
// (if unspecified, scroll in that direction will be preserved).
// Also supports the following other options:
// * preserveMomentum: if true, will not reset any active
// momentum or bounce on the widget
var curr = current[this.id],
touchNode = this.touchNode,
parentNode = touchNode.parentNode;
if(!options.preserveMomentum && curr && curr.resetEffects){
// Stop any glide or bounce occurring before scrolling.
curr.resetEffects();
}
// Constrain coordinates within scrollable boundaries.
if(options.x){
options.x = Math.max(0, Math.min(options.x,
touchNode.scrollWidth - parentNode.offsetWidth));
}
if(options.y){
options.y = Math.max(0, Math.min(options.y,
touchNode.scrollHeight - parentNode.offsetHeight));
}
scroll(this, options);
},
getScrollPosition: function(){
// summary:
// Determines current translation from computed style
// (if mid-transition), or applied style.
var match = getScrollStyle(this);
return match ? { x: -match[1], y: -match[2] } : { x: 0, y: 0 };
},
cancelTouchScroll: function(){
// summary:
// Removes any existing scroll information for this component from the
// current map, effectively canceling any TouchScroll behavior for
// that particular touch gesture.
var curr = current[this.id];
if(!curr){ return; }
if(curr.resetEffects){ curr.resetEffects(); }
else{
if(curr.timer){ clearTimeout(curr.timer); }
put(curr.node.parentNode, ".touchscroll-fadeout");
}
delete current[this.id];
},
glideDecel: function(n){
// summary:
// Deceleration algorithm. Given a number representing velocity,
// returns a new velocity to impose for the next "tick".
// (Don't forget that velocity can be positive or negative!)
return n * 0.9; // Number
}
});
});