/
ScrollableMap.js
executable file
·473 lines (413 loc) · 16.7 KB
/
ScrollableMap.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
/*global $ Message pref */
var ScrollableMap = function (div, type, id) {
// Avoid adding multiple event listeners to the same map
if (div.__scrollMapEnabled) return;
div.__scrollMapEnabled = true;
var self = this;
var mapClicked; // whether the map has ever been clicked (to activate the map)
var bodyScrolls = false;
var style = document.createElement('style');
style.innerHTML = '.gmnoprint { -webkit-transition: opacity 0.3s !important; }' +
'.scrollMapsHideControls .gmnoprint { opacity: 0.5 !important; }';
document.head.appendChild(style);
function getWheelEventTarget(mousePos) {
var hoverElement = document.elementFromPoint(mousePos[0], mousePos[1]);
return hoverElement && div.contains(hoverElement) ? hoverElement : div;
}
Scrollability.monitorScrollabilitySuper(div, function (scrolls) {
bodyScrolls = scrolls;
if (bodyScrolls) { hideControls(); } else { showControls(); }
});
function mapRequiresActivation () {
return self.type != ScrollableMap.TYPE_NEWWEB && bodyScrolls;
}
var States = { idle: 0, scrolling: 1, zooming: 2 };
var state = States.idle;
var averageX = new SMLowPassFilter(2);
var averageY = new SMLowPassFilter(2);
var accelero = new SM2DAccelerationDetector();
self.init = function (div, type) {
self.type = type;
div.addEventListener('wheel', self.handleWheelEvent, true);
window.addEventListener('mousemove', function (e) {
if (e.detail !== 88) {
var event = new CustomEvent('realmousemove', {'detail': [e.pageX, e.pageY]});
e.target.dispatchEvent(event);
}
}, true);
mapClicked = false;
Pref.onPreferenceChanged('frameRequireFocus', function(pair){
(pair.value) ? hideControls() : showControls();
});
div.addEventListener('click', didClickMap, true);
$(div).mouseleave(hideControls);
if (mapRequiresActivation()){
setTimeout(hideControls, 500);
}
}
function didClickMap (event) {
showControls(event);
lastTarget = null;
}
function showControls(event){
if (!mapClicked) {
if (event) event.stopPropagation();
mapClicked = true;
$(div).removeClass('scrollMapsHideControls');
}
}
function hideControls(){
if (mapRequiresActivation() && pref('enabled') && pref('frameRequireFocus')) {
mapClicked = false;
$(div).addClass('scrollMapsHideControls');
}
}
var dragger = new DragSimulator({});
self.realMouseMoved = function (e) {
if (lastTarget) {
dragger.simulateMouseUp(lastTarget);
}
};
window.addEventListener('realmousemove', self.realMouseMoved, true);
self.move = function (point, dx, dy, target) {
dragger.simulateDrag(target, point, dx, dy);
};
self.zoomIn = function (mousePos, target, originalEvent) {
zoomInWeb(mousePos, target, originalEvent);
};
self.zoomOut = function (mousePos, target, originalEvent) {
zoomOutWeb(mousePos, target, originalEvent);
};
var lastZoomTime = 0;
var MINZOOMINTERVAL = 200;
function createBackdoorWheelEvent(originalEvent, zoomIn, scale) {
if (originalEvent instanceof WheelEvent) {
var init = {};
for (var i in originalEvent) {
init[i] = originalEvent[i];
}
init.screenX = -88;
init.screenY = -88;
if (zoomIn && init.deltaY > 0) {
init.deltaY *= -1;
} else if (!zoomIn && init.deltaY < 0) {
init.deltaY *= -1;
}
init.deltaY *= scale || 1;
return new WheelEvent('wheel', init);
} else {
console.log('Trying to create backdoor event out of non-wheel event', originalEvent);
}
}
function zoomInWeb (mousePos, target, originalEvent) {
var e;
// New Google Maps zooms much better with respect to unmodified mouse wheel events. Let's
// keep that behavior for Cmd-scrolling.
if (originalEvent instanceof WheelEvent) {
// Scale the pinch gesture 3x for non-web maps, because pinch gesture normally
// have much less "delta" than scroll
var scale = type !== ScrollableMap.TYPE_NEWWEB && originalEvent.ctrlKey ? 3 : 1;
e = createBackdoorWheelEvent(originalEvent, true /* zoomIn */, scale);
target.dispatchEvent(e);
return;
}
// Fallback, just-in-case the original event is not a wheel event (e.g. programmatic call,
// or keyboard +/-)
if (Date.now() - lastZoomTime < MINZOOMINTERVAL) return;
lastZoomTime = Date.now();
// (-88, -88) is to pass through backdoor that the ScrollMaps event handler left open
e = new WheelEvent('wheel', {
bubbles: true,
cancelable: true,
deltaX: 0,
deltaY: -1200,
screenX: -88,
screenY: -88,
clientX: mousePos[0],
clientY: mousePos[1],
view: window
});
target.dispatchEvent(e);
}
function zoomOutWeb (mousePos, target, originalEvent) {
var e;
// New Google Maps zooms much better with respect to unmodified mouse wheel events. Let's
// keep that behavior for Cmd-scrolling.
if (originalEvent instanceof WheelEvent) {
// Scale the pinch gesture 3x for non-web maps, because pinch gesture normally
// have much less "delta" than scroll
var scale = type !== ScrollableMap.TYPE_NEWWEB && originalEvent.ctrlKey ? 3 : 1;
e = createBackdoorWheelEvent(originalEvent, false /* zoomIn */, scale);
target.dispatchEvent(e);
return;
}
// Fallback, just-in-case the original event is not a wheel event (e.g. programmatic call,
// or keyboard +/-)
if (Date.now() - lastZoomTime < MINZOOMINTERVAL) return;
lastZoomTime = Date.now();
// (-88, -88) is to pass through backdoor that the ScrollMaps event handler left open
e = new WheelEvent('wheel', {
bubbles: true,
cancelable: true,
deltaX: 0,
deltaY: 1200,
screenX: -88,
screenY: -88,
clientX: mousePos[0],
clientY: mousePos[1],
view: window
});
target.dispatchEvent(e);
}
var lastTarget;
self.handleWheelEvent = function (e) {
if (!pref('enabled') && !window.safari) return;
var isFrameType = self.type == ScrollableMap.TYPE_IFRAME || self.type == ScrollableMap.TYPE_API;
if (isFrameType && !pref('enableForFrames')) {
return;
}
if (pref('frameRequireFocus') && mapRequiresActivation() && !mapClicked) {
e.stopPropagation(); return;
}
if (e.screenX == -88 && e.screenY == -88) {
return; // backdoor for zooming
}
var target = e.target || e.srcElement;
var isAccelerating = (!pref('isolateZoomScroll') ||
accelero.isAccelerating(e.wheelDeltaX, e.wheelDeltaY, e.timeStamp));
if (Scrollability.hasScrollableParent(target, div)) {
// something is scrollable, let's allow it to scroll
return;
}
if (lastTarget && arrayContainsElement($(lastTarget).parents(), div))
target = lastTarget;
else
lastTarget = target;
var destinationState = (e.metaKey || e.ctrlKey || e.altKey) ? States.zooming : States.scrolling;
if (isAccelerating || state == destinationState) {
state = destinationState;
var mousePos = [e.clientX, e.clientY];
switch (state) {
case States.zooming:
// In Chrome, ctrl + wheel => pinch gesture. Do not invert zoom for the pinch
// gesture.
var factor = (pref('invertZoom') && !(window.chrome && e.ctrlKey)) ? -1 : 1;
if (window.safari && e.webkitDirectionInvertedFromDevice) {
factor *= -1;
}
if (e.deltaY * factor < 0){
self.zoomIn(mousePos, target, e);
} else if (e.deltaY * factor > 0){
self.zoomOut(mousePos, target, e);
}
break;
case States.scrolling:
setTimer('flushAverage', function () { averageX.flush(); averageY.flush(); }, 200);
// TODO: replace wheelDelta with delta for standards compliance
averageX.push(e.wheelDeltaX); averageY.push(e.wheelDeltaY);
var speedFactor = ( pref('scrollSpeed') / 100 ) * ( pref('invertScroll') ? -1 : 1 );
var dx = averageX.getAverage() * speedFactor;
var dy = averageY.getAverage() * speedFactor;
if (dx !== 0 || dy !== 0) {
self.move(mousePos, dx, dy, target);
}
break;
}
} else {
state = States.idle;
}
e.stopPropagation();
e.preventDefault();
};
self.init(div, type);
};
function arrayContainsElement (array, element) {
if (!array) return false;
for (var i = 0; i < array.length; i++) {
try {
if (element.isSameNode(array[i])) return true;
} catch (e) {
console.warn(e, array, element);
}
}
return false;
}
function setTimer (timerID, newFunction, newDelay) {
window._timers = window._timers || {};
clearTimeout(window._timers[timerID]);
window._timers[timerID] = setTimeout(newFunction, newDelay);
}
ScrollableMap.TYPE_WEB = 0;
ScrollableMap.TYPE_IFRAME = 1;
ScrollableMap.TYPE_API = 2;
ScrollableMap.TYPE_NEWWEB = 3;
ScrollableMap.TYPE_STREETVIEW_API = 4;
var SMLowPassFilter = function SMLowPassFilter () { this.init.apply(this, arguments); };
SMLowPassFilter.SMOOTHING = 0.5;
SMLowPassFilter.prototype = {
init: function () {
this.data = 0;
this.lastDataTime = 0;
},
push: function (data, time) {
this.data = this.data * SMLowPassFilter.SMOOTHING + data * (1 - SMLowPassFilter.SMOOTHING);
this.lastDataTime = time || Date.now();
},
getAverage: function (time) {
time = time || Date.now();
if (this.lastDataTime === 0) {
return 0;
}
return this.data * Math.pow(SMLowPassFilter.SMOOTHING, (time - this.lastDataTime) / 20);
},
flush: function () {
this.data = 0;
}
};
var SMAccelerationDetector = function SMAccelerationDetector() { this.init.apply(this, arguments); };
SMAccelerationDetector.prototype = {
init: function () {
this.max = 0;
this.maxTime = 0;
this.lastDelta = 0;
this.lastTime = Date.now();
},
isAccelerating: function(delta, time){
delta = delta / (time - this.lastTime);
setTimer('stateChangeTimer', this.newScrollAction.bind(this), 200);
var output = false;
if (Math.abs(delta) > Math.abs(this.max)){
this.max = delta;
this.maxTime = time;
output = true;
}
var t = time - this.maxTime;
var prediction = this.max * Math.exp(-0.0038*t);
var difference = (Math.abs(delta) - Math.abs(prediction));
if (difference / Math.abs(prediction) > 1.2 && difference > 0.5){
this.newScrollAction();
output = true;
}
return output;
},
newScrollAction: function (){
this.max = 0;
this.maxTime = 0;
this.lastDelta = 0;
}
};
var SM2DAccelerationDetector = function SM2DAccelerationDetector() { this.init.apply(this, arguments); };
SM2DAccelerationDetector.prototype = {
init: function () {
this.yAccelerationDetector = new SMAccelerationDetector();
this.xAccelerationDetector = new SMAccelerationDetector();
},
isAccelerating: function (deltaX, deltaY, time) {
var x = this.xAccelerationDetector.isAccelerating(deltaX, time);
var y = this.yAccelerationDetector.isAccelerating(deltaY, time);
return x || y;
}
};
var DragSimulator = function DragSimulator() { this.init.apply(this, arguments); };
DragSimulator.defaultOpts = {
// The minimum distance to simulate a drag, to avoid the event being interpreted as
// a click. If the scroll gesture's distance is smaller than this, it will be scaled
// up to reach this distance.
'minDragDistance': 3,
// The maximum distance that can be scrolled (along either X or Y axis) before a
// mouse up is force triggered. This is useful for street view where the panning
// is non-linear, so that the panning response will reset one in a while.
// If this value is too large, the stree view will stop panning until you want for
// the mouse-up timeout. If this value is too small, the event may be treated as a
// mouse move rather than a drag.
'maxDistanceUntilUp': 600,
// The delay in milliseconds before a mouse up is simulated, after the last call to
// simulateDrag. This is non-zero for newer implementations tend to have inertial-drag
// which tracks the mouse events over time, and therefore firing mousedown + mousemove
// + mouseup events in the same loop synchronously will not work.
'mouseUpDelay': 100,
};
DragSimulator.prototype = {
init: function (opts) {
this.opts = {};
for (var i in DragSimulator.defaultOpts) {
if (i in opts) {
this.opts[i] = opts[i];
} else {
this.opts[i] = DragSimulator.defaultOpts[i];
}
}
},
simulateMouseDown: function (target, point) {
this.mouseDownPoint = [point[0], point[1]]; // Deep copy
this.simulatedMousePoint = point;
var downEvent = new MouseEvent('mousedown', {
'bubbles': true,
'cancelable': true,
'detail': 1,
'clientX': point[0],
'clientY': point[1],
'button': 0,
'buttons': 1
});
target.dispatchEvent(downEvent);
},
simulateMouseUp: function (target) {
if (!this.mouseDownPoint) return;
var upEvent = new MouseEvent('mouseup', {
'bubbles': true,
'cancelable': true,
'detail': 1,
'clientX': this.simulatedMousePoint[0],
'clientY': this.simulatedMousePoint[1],
'button': 0,
'buttons': 0
});
target.dispatchEvent(upEvent);
this.mouseDownPoint = null;
},
simulateMouseMove: function (target, dx, dy) {
this.simulatedMousePoint[0] += dx;
this.simulatedMousePoint[1] += dy;
var moveEvent = new MouseEvent('mousemove', {
'bubbles': true,
'cancelable': false,
'detail': 88,
'clientX': this.simulatedMousePoint[0],
'clientY': this.simulatedMousePoint[1],
'button': 0,
'buttons': 1 // Left mouse button should be down when simulating drag-move
})
target.dispatchEvent(moveEvent);
},
simulateDrag: function (target, point, dx, dy) {
var minDragDistance = this.opts.minDragDistance;
var diffX = Math.abs(dx), diffY = Math.abs(dy);
if (diffX < minDragDistance && diffY < minDragDistance) {
// scale to make sure at least one of them is > minDragDistance
// this ensures it's treated as a drag, not a click
var scale = (minDragDistance * 1.05) / Math.max(diffX, diffY);
dx *= scale;
dy *= scale;
}
if (!this.mouseDownPoint) {
this.simulateMouseDown(target, point);
}
this.simulateMouseMove(target, dx, dy);
// Street view panning has set an exponential decaying curve, in order for the scroll
// to continue, pretend a mouse up every so often.
// There is a visible jump when this happens if you observe carefully, but the results
// are good enough for general use.
var maxDistanceUntilUp = this.opts.maxDistanceUntilUp;
if (Math.abs(this.simulatedMousePoint[0] - this.mouseDownPoint[0]) > maxDistanceUntilUp ||
Math.abs(this.simulatedMousePoint[1] - this.mouseDownPoint[1]) > maxDistanceUntilUp) {
this.simulateMouseUp(target);
}
if (this.opts.mouseUpDelay > 0) {
window.clearTimeout(this.timer);
this.timer = window.setTimeout(
this.simulateMouseUp.bind(this, target),
this.opts.mouseUpDelay);
}
}
};