forked from mvindahl/angular-pan-zoom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sed
626 lines (520 loc) · 28.8 KB
/
sed
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
/*!
AngularJS pan/zoom v$VERSION
@license: MIT
Github: https://github.com/mvindahl/angular-pan-zoom
*/
angular.module('panzoom', ['monospaced.mousewheel'])
.directive('panzoom', ['$document', 'PanZoomService',
function ($document, PanZoomService) {
var api = {};
return {
restrict: 'E',
transclude: true,
scope: {
config: '=',
model: '='
},
controller: ['$scope', '$element',
function ($scope, $element) {
var frameElement = $element;
var contentElement = $element.find('.pan-zoom-contents');
var getCssScale = function (zoomLevel) {
return Math.pow($scope.config.scalePerZoomLevel, zoomLevel - $scope.config.neutralZoomLevel);
};
var getZoomLevel = function (cssScale) {
return Math.log(cssScale) / Math.log($scope.config.scalePerZoomLevel) + $scope.config.neutralZoomLevel;
};
// initialize models. Use passed properties when available, otherwise revert to defaults
// NOTE: all times specified in seconds, all distances specified in pixels
$scope.config.zoomLevels = $scope.config.zoomLevels || 5;
$scope.config.neutralZoomLevel = $scope.config.neutralZoomLevel || 2;
$scope.config.friction = $scope.config.friction || 10.0;
$scope.config.haltSpeed = $scope.config.haltSpeed || 100.0;
$scope.config.scalePerZoomLevel = $scope.config.scalePerZoomLevel || 2;
$scope.config.zoomStepDuration = $scope.config.zoomStepDuration || 0.2;
$scope.config.zoomStepDuration = $scope.config.zoomStepDuration || 0.2;
$scope.config.modelChangedCallback = $scope.config.modelChangedCallback || function () {};
$scope.config.zoomToFitZoomLevelFactor = $scope.config.zoomToFitZoomLevelFactor || 0.95;
$scope.config.zoomButtonIncrement = $scope.config.zoomButtonIncrement || 1.0;
$scope.config.initialZoomLevel = $scope.config.initialZoomLevel || $scope.config.neutralZoomLevel;
$scope.config.initialPanX = $scope.config.initialPanX || 0;
$scope.config.initialPanY = $scope.config.initialPanY || 0;
$scope.config.zoomOnDoubleClick = $scope.config.zoomOnDoubleClick !== undefined ? $scope.config.zoomOnDoubleClick : true;
$scope.config.zoomOnMouseWheel = $scope.config.zoomOnMouseWheel !== undefined ? $scope.config.zoomOnMouseWheel : true;
$scope.config.panOnClickDrag = $scope.config.panOnClickDrag !== undefined ? $scope.config.panOnClickDrag : true;
$scope.config.invertMouseWheel = $scope.config.invertMouseWheel || false;
var calcZoomToFit = function (rect) {
// let (W, H) denote the size of the viewport
// let (w, h) denote the size of the rectangle to zoom to
// then we must CSS scale by the min of W/w and H/h in order to just fit the rectangle
var W = $element.width();
var H = $element.height();
var w = rect.width;
var h = rect.height;
var cssScaleExact = Math.min(W / w, H / h);
var zoomLevelExact = getZoomLevel(cssScaleExact);
var zoomLevel = zoomLevelExact * $scope.config.zoomToFitZoomLevelFactor;
var cssScale = getCssScale(zoomLevel);
return {
zoomLevel: zoomLevel,
pan: {
x: -rect.x * cssScale + (W - w * cssScale) / 2,
y: -rect.y * cssScale + (H - h * cssScale) / 2
}
};
};
if ($scope.config.initialZoomToFit) {
$scope.base = calcZoomToFit($scope.config.initialZoomToFit);
} else {
$scope.base = {
zoomLevel: $scope.config.initialZoomLevel,
pan: {
x: $scope.config.initialPanX,
y: $scope.config.initialPanY
}
};
}
$scope.model.zoomLevel = $scope.base.zoomLevel;
$scope.model.pan = {
x: $scope.base.pan.x,
y: $scope.base.pan.y
};
// FIXME why declare these on $scope? They could be private vars
$scope.previousPosition = undefined;
$scope.dragging = false;
$scope.panVelocity = undefined;
$scope.zoomAnimation = undefined;
// private
var syncModelToDOM = function () {
if ($scope.zoomAnimation) {
$scope.model.zoomLevel = $scope.base.zoomLevel + $scope.zoomAnimation.deltaZoomLevel * $scope.zoomAnimation.progress;
var deltaT = $scope.zoomAnimation.translationFromZoom($scope.model.zoomLevel);
$scope.model.pan.x = $scope.base.pan.x + deltaT.x;
$scope.model.pan.y = $scope.base.pan.y + deltaT.y;
} else {
$scope.model.zoomLevel = $scope.base.zoomLevel;
$scope.model.pan.x = $scope.base.pan.x;
$scope.model.pan.y = $scope.base.pan.y;
}
var scaleString = 'scale(' + getCssScale($scope.model.zoomLevel) + ')';
contentElement.css('transform-origin', '0 0');
contentElement.css('ms-transform-origin', '0 0');
contentElement.css('webkit-transform-origin', '0 0');
contentElement.css('transform', scaleString);
contentElement.css('ms-transform', scaleString);
contentElement.css('webkit-transform', scaleString);
contentElement.css('left', $scope.model.pan.x);
contentElement.css('top', $scope.model.pan.y);
};
var getCenterPoint = function () {
var center = {
x: frameElement.width() / 2,
y: frameElement.height() / 2
};
return center;
};
var changeZoomLevel = function (newZoomLevel, clickPoint, duration) {
if ($scope.zoomAnimation) {
$scope.base.zoomLevel = $scope.model.zoomLevel;
$scope.base.pan.x = $scope.model.pan.x;
$scope.base.pan.y = $scope.model.pan.y;
$scope.zoomAnimation = undefined;
}
// keep in bounds
newZoomLevel = Math.max(0, newZoomLevel);
newZoomLevel = Math.min($scope.config.zoomLevels - 1, newZoomLevel);
var deltaZoomLevel = newZoomLevel - $scope.base.zoomLevel;
if (!deltaZoomLevel) {
return;
}
duration = duration || $scope.config.zoomStepDuration;
//
// Let p be the vector to the clicked point in view coords and let p' be the same point in model coords. Let s be a scale factor
// and let t be a translation vector. Let the transformation be defined as:
//
// p' = p * s + t
//
// And conversely:
//
// p = (1/s)(p' - t)
//
// Now use subscription 0 to denote the value before transform and zoom and let 1 denote the value after transform. Scale
// changes from s0 to s1. Translation changes from t0 to t1. But keep p and p' fixed so that the view coordinate p' still
// corresponds to the model coordinate p. This can be expressed as an equation relying upon solely upon p', s0, s1, t0, and t1:
//
// (1/s0)(p - t0) = (1/s1)(p - t1)
//
// Every variable but t1 is known, thus it is easily isolated to:
//
// t1 = p' - (s1/s0)*(p' - t0)
//
var pmark = clickPoint || getCenterPoint();
var s0 = getCssScale($scope.base.zoomLevel);
var t0 = {
x: $scope.base.pan.x,
y: $scope.base.pan.y
};
var translationFromZoom = function (zoomLevel) {
var s1 = getCssScale(zoomLevel);
var t1 = {
x: pmark.x - (s1 / s0) * (pmark.x - t0.x),
y: pmark.y - (s1 / s0) * (pmark.y - t0.y)
};
return {
x: t1.x - t0.x,
y: t1.y - t0.y
};
};
// now rewind to the start of the anim and let it run its course
$scope.zoomAnimation = {
deltaZoomLevel: deltaZoomLevel,
translationFromZoom: translationFromZoom,
duration: duration,
progress: 0.0
};
wakeupAnimationTick();
};
var zoomIn = function (clickPoint) {
changeZoomLevel(
$scope.base.zoomLevel + $scope.config.zoomButtonIncrement,
clickPoint);
};
var zoomOut = function (clickPoint) {
changeZoomLevel(
$scope.base.zoomLevel - $scope.config.zoomButtonIncrement,
clickPoint);
};
var getViewPosition = function (modelPosition) {
// p' = p * s + t
var p = modelPosition;
var s = getCssScale($scope.base.zoomLevel);
var t = $scope.base.pan;
return {
x: p.x * s + t.x,
y: p.y * s + t.y
};
};
var getModelPosition = function (viewPosition) {
// p = (1/s)(p' - t)
var pmark = viewPosition;
var s = getCssScale($scope.base.zoomLevel);
var t = $scope.base.pan;
return {
x: (1 / s) * (pmark.x - t.x),
y: (1 / s) * (pmark.y - t.y)
};
};
var zoomToFit = function (rectangle) {
// example rectangle: { "x": 0, "y": 100, "width": 100, "height": 100 }
$scope.base = calcZoomToFit(rectangle);
syncModelToDOM();
};
var length = function (vector2d) {
return Math.sqrt(vector2d.x * vector2d.x + vector2d.y * vector2d.y);
};
var scopeIsDestroyed = false;
var AnimationTick = function () {
var lastTick = null;
return function () {
var now = jQuery.now();
var deltaTime = lastTick ? (now - lastTick) / 1000 : 0;
lastTick = now;
if ($scope.zoomAnimation) {
$scope.zoomAnimation.progress += deltaTime / $scope.zoomAnimation.duration;
if ($scope.zoomAnimation.progress >= 1.0) {
$scope.zoomAnimation.progress = 1.0;
syncModelToDOM();
$scope.base.zoomLevel = $scope.model.zoomLevel;
$scope.base.pan.x = $scope.model.pan.x;
$scope.base.pan.y = $scope.model.pan.y;
$scope.zoomAnimation = undefined;
$scope.config.modelChangedCallback($scope.model);
}
}
if ($scope.panVelocity) {
// prevent overshooting if delta time is large for some reason. We apply the simple solution of
// slicing delta time into smaller pieces and applying each one
while (deltaTime > 0) {
var dTime = Math.min(0.02, deltaTime);
deltaTime -= dTime;
$scope.base.pan.x += $scope.panVelocity.x * dTime;
$scope.panVelocity.x *= (1 - $scope.config.friction * dTime);
$scope.base.pan.y += $scope.panVelocity.y * dTime;
$scope.panVelocity.y *= (1 - $scope.config.friction * dTime);
var speed = length($scope.panVelocity);
if (speed < $scope.config.haltSpeed) {
$scope.panVelocity = undefined;
$scope.config.modelChangedCallback($scope.model);
break;
}
}
}
syncModelToDOM();
var doneAnimating = $scope.panVelocity === undefined && $scope.zoomAnimation === undefined;
if (doneAnimating) {
tick.isRegistered = false;
lastTick = null;
return false; // kill the tick for now
} else {
return !scopeIsDestroyed; // kill the tick for good if the directive goes off the page
}
};
};
syncModelToDOM();
var tick = new AnimationTick();
tick.isRegistered = false;
function wakeupAnimationTick() {
if (!tick.isRegistered) {
tick.isRegistered = true; // must be set before registering the timer as registration triggers an immediate tick
jQuery.fx.timer(tick);
}
}
$scope.$on('$destroy', function () {
PanZoomService.unregisterAPI($scope.elementId);
scopeIsDestroyed = true;
});
// event handlers
$scope.onDblClick = function ($event) {
if ($scope.config.zoomOnDoubleClick) {
var clickPoint = {
x: $event.pageX - frameElement.offset().left,
y: $event.pageY - frameElement.offset().top
};
zoomIn(clickPoint);
}
};
var lastMouseEventTime;
var previousPosition;
$scope.onMousedown = function ($event) {
if ($scope.config.panOnClickDrag) {
previousPosition = {
x: $event.pageX,
y: $event.pageY
};
lastMouseEventTime = jQuery.now();
$scope.dragging = true;
$document.on('mousemove', $scope.onMousemove);
$document.on('mouseup', $scope.onMouseup);
}
};
var pan = function (delta) {
delta.x = delta.x || 0;
delta.y = delta.y || 0;
$scope.base.pan.x += delta.x;
$scope.base.pan.y += delta.y;
syncModelToDOM();
};
$scope.onMousemove = function ($event) {
var now = jQuery.now();
var timeSinceLastMouseEvent = (now - lastMouseEventTime) / 1000;
lastMouseEventTime = now;
var dragDelta = {
x: $event.pageX - previousPosition.x,
y: $event.pageY - previousPosition.y
};
pan(dragDelta);
// set these for the animation slow down once drag stops
$scope.panVelocity = {
x: dragDelta.x / timeSinceLastMouseEvent,
y: dragDelta.y / timeSinceLastMouseEvent
};
previousPosition = {
x: $event.pageX,
y: $event.pageY
};
};
$scope.onMouseup = function () {
var now = jQuery.now();
var timeSinceLastMouseEvent = (now - lastMouseEventTime) / 1000;
if ($scope.panVelocity) {
// apply strong initial dampening if the mouse up occured much later than
// the last mouse move, indicating that the mouse hasn't moved recently
// TBD experiment with this formula
var initialMultiplier = Math.max(0, Math.pow(timeSinceLastMouseEvent + 1, -4) - 0.2);
$scope.panVelocity.x *= initialMultiplier;
$scope.panVelocity.y *= initialMultiplier;
}
$scope.dragging = false;
wakeupAnimationTick();
$document.off('mousemove', $scope.onMousemove);
$document.off('mouseup', $scope.onMouseup);
};
$scope.onMouseleave = function () {
$scope.onMouseup(); // same behaviour
};
$scope.onMouseWheel = function ($event, $delta, $deltaX, $deltaY) {
if ($scope.config.zoomOnMouseWheel) {
$event.preventDefault();
if ($scope.zoomAnimation) {
return; // already zooming
}
var sign = $deltaY / Math.abs($deltaY);
if ($scope.config.invertMouseWheel) {
sign = -sign;
}
var clickPoint = {
x: $event.pageX - frameElement.offset().left,
y: $event.pageY - frameElement.offset().top
};
if (sign < 0) {
zoomIn(clickPoint);
} else {
zoomOut(clickPoint);
}
}
};
// create public API
api = {
model: $scope.model,
config: $scope.config,
changeZoomLevel: changeZoomLevel,
zoomIn: zoomIn,
zoomOut: zoomOut,
zoomToFit: zoomToFit,
getViewPosition: getViewPosition,
getModelPosition: getModelPosition
};
}],
link: function (scope, element, attrs) {
scope.elementId = attrs.id;
if (scope.elementId) {
PanZoomService.registerAPI(scope.elementId, api);
}
},
template: '<div class="pan-zoom-frame" ng-dblclick="onDblClick($event)" ng-mousedown="onMousedown($event)"' +
' msd-wheel="onMouseWheel($event, $delta, $deltaX, $deltaY)"' +
' style="position:relative;overflow:hidden;cursor:move">' +
'<div class="pan-zoom-contents" style="position:absolute;left:0px;top:0px" ng-transclude>' +
// transcluded contents will be inserted here
'</div>' +
'</div>',
replace: true
};
}]);angular.module('panzoomwidget', [])
.directive('panzoomwidget', ['$document', 'PanZoomService',
function ($document, PanZoomService) {
var panzoomId;
return {
restrict: 'E',
transclude: true,
compile: function compile(/*tElement, tAttrs, transclude*/) {
return {
pre: function preLink(/*scope, iElement, iAttrs, controller*/) { },
post: function postLink(scope, iElement, iAttrs /*, controller*/) {
// we pick the value ourselves at this point, before the controller is instantiated,
// instead of passing it as a scope variable. This is to not force people to type quotes
// around the string.
// Note: we need to use iAttrs and not directly get the attribute on the element to
// be sure to get the interpolated value ({{foo}})
panzoomId = iAttrs.panzoomId;
if (!panzoomId) {
throw 'Error in setup. You must define attribute panzoom-id on the <panzoomwidget> element in order to link it to the ' +
'id of the <panzoom> element. Ref: ';
}
PanZoomService.getAPI(panzoomId).then(function (api) {
scope.model = api.model;
scope.config = api.config;
var zoomSliderWidget = iElement.find('.zoom-slider-widget');
var isDragging = false;
var sliderWidgetTopFromZoomLevel = function (zoomLevel) {
return ((scope.config.zoomLevels - zoomLevel - 1) * scope.widgetConfig.zoomLevelHeight);
};
var zoomLevelFromSliderWidgetTop = function (sliderWidgetTop) {
return scope.config.zoomLevels - 1 - sliderWidgetTop / scope.widgetConfig.zoomLevelHeight;
};
var getZoomLevelForMousePoint = function ($event) {
var sliderWidgetTop = $event.pageY - iElement.find('.zoom-slider').offset().top - scope.widgetConfig.zoomLevelHeight / 2;
return zoomLevelFromSliderWidgetTop(sliderWidgetTop);
};
scope.getZoomLevels = function () {
var zoomLevels = [];
for (var i = scope.config.zoomLevels - 1; i >= 0; i--) {
zoomLevels.push(i);
}
return zoomLevels;
};
scope.widgetConfig = {
zoomLevelHeight: 10
};
scope.zoomIn = function () {
api.zoomIn();
};
scope.zoomOut = function () {
api.zoomOut();
};
scope.onClick = function ($event) {
var zoomLevel = getZoomLevelForMousePoint($event);
api.changeZoomLevel(zoomLevel);
};
scope.onMousedown = function () {
isDragging = true;
$document.on('mousemove', scope.onMousemove);
$document.on('mouseup', scope.onMouseup);
};
scope.onMousemove = function ($event) {
$event.preventDefault();
var zoomLevel = getZoomLevelForMousePoint($event);
api.changeZoomLevel(zoomLevel);
};
scope.onMouseup = function () {
isDragging = false;
$document.off('mousemove', scope.onMousemove);
$document.off('mouseup', scope.onMouseup);
};
scope.onMouseleave = function () {
isDragging = false;
};
// $watch is not fast enough so we set up our own polling
setInterval(function () {
zoomSliderWidget.css('top', sliderWidgetTopFromZoomLevel(scope.model.zoomLevel) + 'px');
}, 25);
});
}
};
},
template: '<div class="panzoomwidget">' +
'<div ng-click="zoomIn()" ng-mouseenter="zoomToLevelIfDragging(config.zoomLevels - 1)" class="zoom-button zoom-button-in">+</div>' +
'<div class="zoom-slider" ng-mousedown="onMousedown()" ' +
'ng-click="onClick($event)">' +
'<div class="zoom-slider-widget" ng-style="{\'height\': widgetConfig.zoomLevelHeight - 2 +\'px\'}"></div>' +
'<div ng-repeat="zoomLevel in getZoomLevels()" ' +
' class="zoom-level zoom-level-{{zoomLevel}}" ng-style="{\'height\': widgetConfig.zoomLevelHeight +\'px\'}"></div>' +
'</div>' +
'<div ng-click="zoomOut()" ng-mouseenter="zoomToLevelIfDragging(0)" class="zoom-button zoom-button-out">-</div>' +
'<div ng-transclude></div>' +
'</div>',
replace: true
};
}]);
angular.module('panzoom').factory('PanZoomService', ['$q',
function ($q) {
// key -> deferred with promise of API
var panZoomAPIs = {};
var registerAPI = function (key, panZoomAPI) {
if (!panZoomAPIs[key]) {
panZoomAPIs[key] = $q.defer();
}
var deferred = panZoomAPIs[key];
if (deferred.hasBeenResolved) {
throw 'Internal error: attempt to register a panzoom API but key was already used. Did you declare two <panzoom> directives with the same id?';
} else {
deferred.resolve(panZoomAPI);
deferred.hasBeenResolved = true;
}
};
var unregisterAPI = function (key) {
delete panZoomAPIs[key];
};
// this method returns a promise since it's entirely possible that it's called before the <panzoom> directive registered the API
var getAPI = function (key) {
if (!panZoomAPIs[key]) {
panZoomAPIs[key] = $q.defer();
}
return panZoomAPIs[key].promise;
};
return {
registerAPI: registerAPI,
unregisterAPI: unregisterAPI,
getAPI: getAPI
};
}]);