1/*! PhotoSwipe - v4.1.0 - 2015-09-24 2* http://photoswipe.com 3* Copyright (c) 2015 Dmitry Semenov; */ 4(function (root, factory) { 5 if (typeof define === 'function' && define.amd) { 6 define(factory); 7 } else if (typeof exports === 'object') { 8 module.exports = factory(); 9 } else { 10 root.PhotoSwipe = factory(); 11 } 12})(this, function () { 13 14 'use strict'; 15 var PhotoSwipe = function(template, UiClass, items, options){ 16 17/*>>framework-bridge*/ 18/** 19 * 20 * Set of generic functions used by gallery. 21 * 22 * You're free to modify anything here as long as functionality is kept. 23 * 24 */ 25var framework = { 26 features: null, 27 bind: function(target, type, listener, unbind) { 28 var methodName = (unbind ? 'remove' : 'add') + 'EventListener'; 29 type = type.split(' '); 30 for(var i = 0; i < type.length; i++) { 31 if(type[i]) { 32 target[methodName]( type[i], listener, false); 33 } 34 } 35 }, 36 isArray: function(obj) { 37 return (obj instanceof Array); 38 }, 39 createEl: function(classes, tag) { 40 var el = document.createElement(tag || 'div'); 41 if(classes) { 42 el.className = classes; 43 } 44 return el; 45 }, 46 getScrollY: function() { 47 var yOffset = window.pageYOffset; 48 return yOffset !== undefined ? yOffset : document.documentElement.scrollTop; 49 }, 50 unbind: function(target, type, listener) { 51 framework.bind(target,type,listener,true); 52 }, 53 removeClass: function(el, className) { 54 var reg = new RegExp('(\\s|^)' + className + '(\\s|$)'); 55 el.className = el.className.replace(reg, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 56 }, 57 addClass: function(el, className) { 58 if( !framework.hasClass(el,className) ) { 59 el.className += (el.className ? ' ' : '') + className; 60 } 61 }, 62 hasClass: function(el, className) { 63 return el.className && new RegExp('(^|\\s)' + className + '(\\s|$)').test(el.className); 64 }, 65 getChildByClass: function(parentEl, childClassName) { 66 var node = parentEl.firstChild; 67 while(node) { 68 if( framework.hasClass(node, childClassName) ) { 69 return node; 70 } 71 node = node.nextSibling; 72 } 73 }, 74 arraySearch: function(array, value, key) { 75 var i = array.length; 76 while(i--) { 77 if(array[i][key] === value) { 78 return i; 79 } 80 } 81 return -1; 82 }, 83 extend: function(o1, o2, preventOverwrite) { 84 for (var prop in o2) { 85 if (o2.hasOwnProperty(prop)) { 86 if(preventOverwrite && o1.hasOwnProperty(prop)) { 87 continue; 88 } 89 o1[prop] = o2[prop]; 90 } 91 } 92 }, 93 easing: { 94 sine: { 95 out: function(k) { 96 return Math.sin(k * (Math.PI / 2)); 97 }, 98 inOut: function(k) { 99 return - (Math.cos(Math.PI * k) - 1) / 2; 100 } 101 }, 102 cubic: { 103 out: function(k) { 104 return --k * k * k + 1; 105 } 106 } 107 /* 108 elastic: { 109 out: function ( k ) { 110 111 var s, a = 0.1, p = 0.4; 112 if ( k === 0 ) return 0; 113 if ( k === 1 ) return 1; 114 if ( !a || a < 1 ) { a = 1; s = p / 4; } 115 else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); 116 return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); 117 118 }, 119 }, 120 back: { 121 out: function ( k ) { 122 var s = 1.70158; 123 return --k * k * ( ( s + 1 ) * k + s ) + 1; 124 } 125 } 126 */ 127 }, 128 129 /** 130 * 131 * @return {object} 132 * 133 * { 134 * raf : request animation frame function 135 * caf : cancel animation frame function 136 * transfrom : transform property key (with vendor), or null if not supported 137 * oldIE : IE8 or below 138 * } 139 * 140 */ 141 detectFeatures: function() { 142 if(framework.features) { 143 return framework.features; 144 } 145 var helperEl = framework.createEl(), 146 helperStyle = helperEl.style, 147 vendor = '', 148 features = {}; 149 150 // IE8 and below 151 features.oldIE = document.all && !document.addEventListener; 152 153 features.touch = 'ontouchstart' in window; 154 155 if(window.requestAnimationFrame) { 156 features.raf = window.requestAnimationFrame; 157 features.caf = window.cancelAnimationFrame; 158 } 159 160 features.pointerEvent = navigator.pointerEnabled || navigator.msPointerEnabled; 161 162 // fix false-positive detection of old Android in new IE 163 // (IE11 ua string contains "Android 4.0") 164 165 if(!features.pointerEvent) { 166 167 var ua = navigator.userAgent; 168 169 // Detect if device is iPhone or iPod and if it's older than
169iOS 8 170 // http://stackoverflow.com/a/14223920 171 // 172 // This detection is made because of buggy top/bottom toolbars 173 // that don't trigger window.resize event. 174 // For more info refer to _isFixedPosition variable in core.js 175 176 if (/iP(hone|od)/.test(navigator.platform)) { 177 var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/); 178 if(v && v.length > 0) { 179 v = parseInt(v[1], 10); 180 if(v >= 1 && v < 8 ) { 181 features.isOldIOSPhone = true; 182 } 183 } 184 } 185 186 // Detect old Android (before KitKat) 187 // due to bugs related to position:fixed 188 // http://stackoverflow.com/questions/7184573/pick-up-the-android-version-in-the-browser-by-javascript 189 190 var match = ua.match(/Android\s([0-9\.]*)/); 191 var androidversion = match ? match[1] : 0; 192 androidversion = parseFloat(androidversion); 193 if(androidversion >= 1 ) { 194 if(androidversion < 4.4) { 195 features.isOldAndroid = true; // for fixed position bug & performance 196 } 197 features.androidVersion = androidversion; // for touchend bug 198 }
199 features.isMobileOpera = /opera mini|opera mobi/i.test(ua); 200 201 // p.s. yes, yes, UA sniffing is bad, propose your solution for above bugs. 202 } 203 204 var styleChecks = ['transform', 'perspective', 'animationName'], 205 vendors = ['', 'webkit','Moz','ms','O'], 206 styleCheckItem, 207 styleName; 208 209 for(var i = 0; i < 4; i++) { 210 vendor = vendors[i]; 211 212 for(var a = 0; a < 3; a++) { 213 styleCheckItem = styleChecks[a]; 214 215 // uppercase first letter of property name, if vendor is present 216 styleName = vendor + (vendor ? 217 styleCheckItem.charAt(0).toUpperCase() + styleCheckItem.slice(1) : 218 styleCheckItem); 219 220 if(!features[styleCheckItem] && styleName in helperStyle ) { 221 features[styleCheckItem] = styleName; 222 } 223 } 224 225 if(vendor && !features.raf) { 226 vendor = vendor.toLowerCase(); 227 features.raf = window[vendor+'RequestAnimationFrame']; 228 if(features.raf) { 229 features.caf = window[vendor+'CancelAnimationFrame'] || 230 window[vendor+'CancelRequestAnimationFrame']; 231 } 232 } 233 } 234 235 if(!features.raf) { 236 var lastTime = 0; 237 features.raf = function(fn) { 238 var currTime = new Date().getTime(); 239 var timeToCall = Math.max(0, 16 - (currTime - lastTime)); 240 var id = window.setTimeout(function() { fn(currTime + timeToCall); }, timeToCall); 241 lastTime = currTime + timeToCall; 242 return id; 243 }; 244 features.caf = function(id) { clearTimeout(id); }; 245 } 246 247 // Detect SVG support 248 features.svg = !!document.createElementNS && 249 !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect; 250 251 framework.features = features; 252 253 return features; 254 } 255}; 256 257framework.detectFeatures(); 258 259// Override addEventListener for old versions of IE 260if(framework.features.oldIE) { 261 262 framework.bind = function(target, type, listener, unbind) { 263 264 type = type.split(' '); 265 266 var methodName = (unbind ? 'detach' : 'attach') + 'Event', 267 evName, 268 _handleEv = function() { 269 listener.handleEvent.call(listener); 270 }; 271 272 for(var i = 0; i < type.length; i++) { 273 evName = type[i]; 274 if(evName) { 275 276 if(typeof listener === 'object' && listener.handleEvent) { 277 if(!unbind) { 278 listener['oldIE' + evName] = _handleEv; 279 } else { 280 if(!listener['oldIE' + evName]) { 281 return false; 282 } 283 } 284 285 target[methodName]( 'on' + evName, listener['oldIE' + evName]); 286 } else { 287 target[methodName]( 'on' + evName, listener); 288 } 289 290 } 291 } 292 }; 293 294} 295 296/*>>framework-bridge*/ 297 298/*>>core*/ 299//function(template, UiClass, items, options) 300 301var self = this; 302 303/** 304 * Static vars, don't change unless you know what you're doing. 305 */ 306var DOUBLE_TAP_RADIUS = 25, 307 NUM_HOLDERS = 3; 308 309/** 310 * Options 311 */ 312var _options = { 313 allowPanToNext:true, 314 spacing: 0.12, 315 bgOpacity: 1, 316 mouseUsed: false, 317 loop: true, 318 pinchToClose: true, 319 closeOnScroll: true, 320 closeOnVerticalDrag: true, 321 verticalDragRange: 0.75, 322 hideAnimationDuration: 333, 323 showAnimationDuration: 333, 324 showHideOpacity: false, 325 focus: true, 326 escKey: true, 327 arrowKeys: true, 328 mainScrollEndFriction: 0.35, 329 panEndFriction: 0.35, 330 isClickableElement: function(el) { 331 return el.tagName === 'A'; 332 }, 333 getDoubleTapZoom: function(isMouseClick, item) { 334 if(isMouseClick) { 335 return 1; 336 } else { 337 return item.initialZoomLevel < 0.7 ? 1 : 1.33; 338 } 339 }, 340 maxSpreadZoom: 1.33, 341 modal: true, 342 343 // not fully implemented yet 344 scaleMode: 'fit' // TODO 345}; 346framework.extend(_options, options); 347 348 349/** 350 * Private helper variables & functions 351 */ 352 353var _getEmptyPoint = function() { 354 return {x:0,y:0}; 355 }; 356 357var _isOpen, 358 _isDestroying, 359 _closedByScroll, 360 _currentItemIndex, 361 _containerStyle, 362 _containerShiftIndex, 363 _currPanDist = _getEmptyPoint(), 364 _startPanOffset = _getEmptyPoint(), 365 _panOffset = _getEmptyPoint(), 366 _upMoveEvents, // drag move, drag end & drag cancel events array 367 _downEvents, // drag start events array 368 _globalEventHandlers, 369 _viewportSize = {}, 370 _currZoomLevel, 371 _startZoomLevel, 372 _translatePrefix, 373 _translateSufix, 374 _updateSizeInterval, 375 _itemsNeedUpdate, 376 _currPositionIndex = 0, 377 _offset = {}, 378 _slideSize = _getEmptyPoint(), // size of slide area, including spacing 379 _itemHolders, 380 _prevItemIndex, 381 _indexDiff = 0, // difference of indexes since last content update 382 _dragStartEvent, 383 _dragMoveEvent, 384 _dragEndEvent, 385 _dragCancelEvent, 386 _transformKey, 387 _pointerEventEnabled, 388 _isFixedPosition = true, 389 _likelyTouchDevice, 390 _modules = [], 391 _requestAF, 392 _cancelAF, 393 _initalClassName, 394 _initalWindowScrollY, 395 _oldIE, 396 _currentWindowScrollY, 397 _features, 398 _windowVisibleSize = {}, 399 _renderMaxResolution = false, 400 401 // Registers PhotoSWipe module (History, Controller ...) 402 _registerModule = function(name, module) { 403 framework.extend(self, module.publicMethods); 404 _modules.push(name); 405 }, 406
407 _getLoopedId = function(index) { 408 var numSlides = _getNumItems(); 409 if(index > numSlides - 1) { 410 return index - numSlides; 411 } else if(index < 0) { 412 return numSlides + index; 413 } 414 return index; 415 }, 416 417 // Micro bind/trigger 418 _listeners = {}, 419 _listen = function(name, fn) { 420 if(!_listeners[name]) { 421 _listeners[name] = []; 422 } 423 return _listeners[name].push(fn); 424 }, 425 _shout = function(name) { 426 var listeners = _listeners[name]; 427 428 if(listeners) { 429 var args = Array.prototype.slice.call(arguments); 430 args.shift(); 431 432 for(var i = 0; i < listeners.length; i++) { 433 listeners[i].apply(self, args); 434 } 435 } 436 }, 437 438 _getCurrentTime = function() { 439 return new Date().getTime(); 440 }, 441 _applyBgOpacity = function(opacity) { 442 _bgOpacity = opacity; 443 self.bg.style.opacity = opacity * _options.bgOpacity; 444 }, 445 446 _applyZoomTransform = function(styleObj,x,y,zoom,item) { 447 if(!_renderMaxResolution || (item && item !== self.currItem) ) { 448 zoom = zoom / (item ? item.fitRatio : self.currItem.fitRatio); 449 } 450 451 styleObj[_transformKey] = _translatePrefix + x + 'px, ' + y + 'px' + _translateSufix + ' scale(' + zoom + ')'; 452 }, 453 _applyCurrentZoomPan = function( allowRenderResolution ) { 454 if(_currZoomElementStyle) { 455 456 if(allowRenderResolution) { 457 if(_currZoomLevel > self.currItem.fitRatio) { 458 if(!_renderMaxResolution) { 459 _setImageSize(self.currItem, false, true); 460 _renderMaxResolution = true; 461 } 462 } else { 463 if(_renderMaxResolution) { 464 _setImageSize(self.currItem); 465 _renderMaxResolution = false; 466 } 467 } 468 } 469 470 471 _applyZoomTransform(_currZoomElementStyle, _panOffset.x, _panOffset.y, _currZoomLevel); 472 } 473 }, 474 _applyZoomPanToItem = function(item) { 475 if(item.container) { 476 477 _applyZoomTransform(item.container.style, 478 item.initialPosition.x, 479 item.initialPosition.y, 480 item.initialZoomLevel, 481 item); 482 } 483 }, 484 _setTranslateX = function(x, elStyle) { 485 elStyle[_transformKey] = _translatePrefix + x + 'px, 0px' + _translateSufix; 486 }, 487 _moveMainScroll = function(x, dragging) { 488 489 if(!_options.loop && dragging) { 490 var newSlideIndexOffset = _currentItemIndex + (_slideSize.x * _currPositionIndex - x) / _slideSize.x, 491 delta = Math.round(x - _mainScrollPos.x); 492 493 if( (newSlideIndexOffset < 0 && delta > 0) || 494 (newSlideIndexOffset >= _getNumItems() - 1 && delta < 0) ) { 495 x = _mainScrollPos.x + delta * _options.mainScrollEndFriction; 496 } 497 } 498 499 _mainScrollPos.x = x; 500 _setTranslateX(x, _containerStyle); 501 }, 502 _calculatePanOffset = function(axis, zoomLevel) { 503 var m = _midZoomPoint[axis] - _offset[axis]; 504 return _startPanOffset[axis] + _currPanDist[axis] + m - m * ( zoomLevel / _startZoomLevel ); 505 }, 506 507 _equalizePoints = function(p1, p2) { 508 p1.x = p2.x; 509 p1.y = p2.y; 510 if(p2.id) { 511 p1.id = p2.id; 512 } 513 }, 514 _roundPoint = function(p) { 515 p.x = Math.round(p.x); 516 p.y = Math.round(p.y); 517 }, 518 519 _mouseMoveTimeout = null, 520 _onFirstMouseMove = function() { 521 // Wait until mouse move event is fired at least twice during 100ms 522 // We do this, because some mobile browsers trigger it on touchstart 523 if(_mouseMoveTimeout ) { 524 framework.unbind(document, 'mousemove', _onFirstMouseMove); 525 framework.addClass(template, 'pswp--has_mouse'); 526 _options.mouseUsed = true; 527 _shout('mouseUsed'); 528 } 529 _mouseMoveTimeout = setTimeout(function() { 530 _mouseMoveTimeout = null; 531 }, 100); 532 }, 533 534 _bindEvents = function() { 535 framework.bind(document, 'keydown', self); 536 537 if(_features.transform) { 538 // don't bind click event in browsers that don't support transform (mostly IE8) 539 framework.bind(self.scrollWrap, 'click', self); 540 } 541 542 543 if(!_options.mouseUsed) { 544 framework.bind(document, 'mousemove', _onFirstMouseMove); 545 } 546 547 framework.bind(window, 'resize scroll', self); 548 549 _shout('bindEvents'); 550 }, 551 552 _unbindEvents = function() { 553 framework.unbind(window, 'resize', self); 554 framework.unbind(window, 'scroll', _globalEventHandlers.scroll); 555 framework.unbind(document, 'keydown', self); 556 framework.unbind(document, 'mousemove', _onFirstMouseMove); 557 558 if(_features.transform) { 559 framework.unbind(self.scrollWrap, 'click', self); 560 } 561 562 if(_isDragging) { 563 framework.unbind(window, _upMoveEvents, self); 564 } 565 566 _shout('unbindEvents'); 567 }, 568 569 _calculatePanBounds = function(zoomLevel, update) { 570 var bounds = _calculateItemSize( self.currItem, _viewportSize, zoomLevel ); 571 if(update) { 572 _currPanBounds = bounds; 573 } 574 return bounds; 575 }, 576 577 _getMinZoomLevel = function(item) { 578 if(!item) { 579 item = self.currItem; 580 } 581 return item.initialZoomLevel; 582 }, 583 _getMaxZoomLevel = function(item) { 584 if(!item) { 585 item = self.currItem; 586 } 587 return item.w > 0 ? _options.maxSpreadZoom : 1; 588 }, 589 590 // Return true if offset is out of the bounds 591 _modifyDestPanOffset = function(axis, destPanBounds, destPanOffset, destZoomLevel) { 592 if(destZoomLevel === self.currItem.initialZoomLevel) { 593 destPanOffset[axis] = self.currItem.initialPosition[axis]; 594 return true; 595 } else { 596 destPanOffset[axis] = _calculatePanOffset(axis, destZoomLevel); 597 598 if(destPanOffset[axis] > destPanBounds.min[axis]) { 599 destPanOffset[axis] = destPanBounds.min[axis]; 600 return true; 601 } else if(destPanOffset[axis] < destPanBounds.max[axis] ) { 602 destPanOffset[axis] = destPanBounds.max[axis]; 603 return true; 604 } 605 } 606 return false;
607 }, 608 609 _setupTransforms = function() { 610 611 if(_transformKey) { 612 // setup 3d transforms 613 var allow3dTransform = _features.perspective && !_likelyTouchDevice; 614 _translatePrefix = 'translate' + (allow3dTransform ? '3d(' : '('); 615 _translateSufix = _features.perspective ? ', 0px)' : ')'; 616 return; 617 } 618 619 // Override zoom/pan/move functions in case old browser is used (most likely IE) 620 // (so they use left/top/width/height, instead of CSS transform) 621 622 _transformKey = 'left'; 623 framework.addClass(template, 'pswp--ie'); 624 625 _setTranslateX = function(x, elStyle) { 626 elStyle.left = x + 'px'; 627 }; 628 _applyZoomPanToItem = function(item) { 629 630 var zoomRatio = item.fitRatio > 1 ? 1 : item.fitRatio, 631 s = item.container.style, 632 w = zoomRatio * item.w, 633 h = zoomRatio * item.h; 634 635 s.width = w + 'px'; 636 s.height = h + 'px'; 637 s.left = item.initialPosition.x + 'px'; 638 s.top = item.initialPosition.y + 'px'; 639 640 }; 641 _applyCurrentZoomPan = function() { 642 if(_currZoomElementStyle) { 643 644 var s = _currZoomElementStyle, 645 item = self.currItem, 646 zoomRatio = item.fitRatio > 1 ? 1 : item.fitRatio, 647 w = zoomRatio * item.w, 648 h = zoomRatio * item.h; 649 650 s.width = w + 'px'; 651 s.height = h + 'px'; 652 653 654 s.left = _panOffset.x + 'px'; 655 s.top = _panOffset.y + 'px'; 656 } 657 658 }; 659 }, 660 661 _onKeyDown = function(e) { 662 var keydownAction = ''; 663 if(_options.escKey && e.keyCode === 27) { 664 keydownAction = 'close'; 665 } else if(_options.arrowKeys) { 666 if(e.keyCode === 37) { 667 keydownAction = 'prev'; 668 } else if(e.keyCode === 39) { 669 keydownAction = 'next'; 670 } 671 } 672 673 if(keydownAction) { 674 // don't do anything if special key pressed to prevent from overriding default browser actions 675 // e.g. in Chrome on Mac cmd+arrow-left returns to previous page 676 if( !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey ) { 677 if(e.preventDefault) { 678 e.preventDefault(); 679 } else { 680 e.returnValue = false; 681 } 682 self[keydownAction](); 683 } 684 } 685 }, 686 687 _onGlobalClick = function(e) { 688 if(!e) { 689 return; 690 } 691 692 // don't allow click event to pass through when triggering after drag or some other gesture 693 if(_moved || _zoomStarted || _mainScrollAnimating || _verticalDragInitiated) { 694 e.preventDefault(); 695 e.stopPropagation(); 696 } 697 }, 698 699 _updatePageScrollOffset = function() { 700 self.setScrollOffset(0, framework.getScrollY()); 701 }; 702 703 704 705 706 707 708 709// Micro animation engine 710var _animations = {}, 711 _numAnimations = 0, 712 _stopAnimation = function(name) { 713 if(_animations[name]) { 714 if(_animations[name].raf) { 715 _cancelAF( _animations[name].raf ); 716 } 717 _numAnimations--; 718 delete _animations[name]; 719 } 720 }, 721 _registerStartAnimation = function(name) { 722 if(_animations[name]) { 723 _stopAnimation(name); 724 } 725 if(!_animations[name]) { 726 _numAnimations++; 727 _animations[name] = {}; 728 } 729 }, 730 _stopAllAnimations = function() { 731 for (var prop in _animations) { 732 733 if( _animations.hasOwnProperty( prop ) ) { 734 _stopAnimation(prop); 735 } 736 737 } 738 }, 739 _animateProp = function(name, b, endProp, d, easingFn, onUpdate, onComplete) { 740 var startAnimTime = _getCurrentTime(), t; 741 _registerStartAnimation(name); 742 743 var animloop = function(){ 744 if ( _animations[name] ) { 745 746 t = _getCurrentTime() - startAnimTime; // time diff 747 //b - beginning (start prop) 748 //d - anim duration 749 750 if ( t >= d ) { 751 _stopAnimation(name); 752 onUpdate(endProp); 753 if(onComplete) { 754 onComplete(); 755 } 756 return; 757 } 758 onUpdate( (endProp - b) * easingFn(t/d) + b ); 759 760 _animations[name].raf = _requestAF(animloop); 761 } 762 }; 763 animloop(); 764 }; 765 766 767 768var publicMethods = { 769 770 // make a few local variables and functions public 771 shout: _shout, 772 listen: _listen, 773 viewportSize: _viewportSize, 774 options: _options, 775 776 isMainScrollAnimating: function() { 777 return _mainScrollAnimating; 778 }, 779 getZoomLevel: function() { 780 return _currZoomLevel; 781 }, 782 getCurrentIndex: function() { 783 return _currentItemIndex; 784 }, 785 isDragging: function() { 786 return _isDragging; 787 }, 788 isZooming: function() { 789 return _isZooming; 790 }, 791 setScrollOffset: function(x,y) { 792 _offset.x = x; 793 _currentWindowScrollY = _offset.y = y; 794 _shout('updateScrollOffset', _offset); 795 }, 796 applyZoomPan: function(zoomLevel,panX,panY,allowRenderResolution) { 797 _panOffset.x = panX;
798 _panOffset.y = panY; 799 _currZoomLevel = zoomLevel; 800 _applyCurrentZoomPan( allowRenderResolution ); 801 }, 802 803 init: function() { 804 805 if(_isOpen || _isDestroying) { 806 return; 807 } 808 809 var i; 810 811 self.framework = framework; // basic functionality 812 self.template = template; // root DOM element of PhotoSwipe 813 self.bg = framework.getChildByClass(template, 'pswp__bg'); 814 815 _initalClassName = template.className; 816 _isOpen = true; 817 818 _features = framework.detectFeatures(); 819 _requestAF = _features.raf; 820 _cancelAF = _features.caf; 821 _transformKey = _features.transform; 822 _oldIE = _features.oldIE; 823 824 self.scrollWrap = framework.getChildByClass(template, 'pswp__scroll-wrap'); 825 self.container = framework.getChildByClass(self.scrollWrap, 'pswp__container'); 826 827 _containerStyle = self.container.style; // for fast access 828 829 // Objects that hold slides (there are only 3 in DOM) 830 self.itemHolders = _itemHolders = [ 831 {el:self.container.children[0] , wrap:0, index: -1}, 832 {el:self.container.children[1] , wrap:0, index: -1}, 833 {el:self.container.children[2] , wrap:0, index: -1} 834 ]; 835 836 // hide nearby item holders until initial zoom animation finishes (to avoid extra Paints) 837 _itemHolders[0].el.style.display = _itemHolders[2].el.style.display = 'none'; 838 839 _setupTransforms(); 840 841 // Setup global events 842 _globalEventHandlers = { 843 resize: self.updateSize, 844 scroll: _updatePageScrollOffset, 845 keydown: _onKeyDown, 846 click: _onGlobalClick 847 }; 848 849 // disable show/hide effects on old browsers that don't support CSS animations or transforms, 850 // old IOS, Android and Opera mobile. Blackberry seems to work fine, even older models. 851 var oldPhone = _features.isOldIOSPhone || _features.isOldAndroid || _features.isMobileOpera; 852 if(!_features.animationName || !_features.transform || oldPhone) { 853 _options.showAnimationDuration = _options.hideAnimationDuration = 0; 854 } 855 856 // init modules 857 for(i = 0; i < _modules.length; i++) { 858 self['init' + _modules[i]](); 859 } 860 861 // init 862 if(UiClass) { 863 var ui = self.ui = new UiClass(self, framework); 864 ui.init(); 865 } 866 867 _shout('firstUpdate'); 868 _currentItemIndex = _currentItemIndex || _options.index || 0; 869 // validate index 870 if( isNaN(_currentItemIndex) || _currentItemIndex < 0 || _currentItemIndex >= _getNumItems() ) { 871 _currentItemIndex = 0; 872 } 873 self.currItem = _getItemAt( _currentItemIndex ); 874 875 876 if(_features.isOldIOSPhone || _features.isOldAndroid) { 877 _isFixedPosition = false; 878 } 879 880 template.setAttribute('aria-hidden', 'false'); 881 if(_options.modal) { 882 if(!_isFixedPosition) { 883 template.style.position = 'absolute'; 884 template.style.top = framework.getScrollY() + 'px'; 885 } else { 886 template.style.position = 'fixed'; 887 } 888 } 889 890 if(_currentWindowScrollY === undefined) { 891 _shout('initialLayout'); 892 _currentWindowScrollY = _initalWindowScrollY = framework.getScrollY(); 893 } 894 895 // add classes to root element of PhotoSwipe 896 var rootClasses = 'pswp--open '; 897 if(_options.mainClass) { 898 rootClasses += _options.mainClass + ' '; 899 } 900 if(_options.showHideOpacity) { 901 rootClasses += 'pswp--animate_opacity '; 902 } 903 rootClasses += _likelyTouchDevice ? 'pswp--touch' : 'pswp--notouch'; 904 rootClasses += _features.animationName ? ' pswp--css_animation' : ''; 905 rootClasses += _features.svg ? ' pswp--svg' : ''; 906 framework.addClass(template, rootClasses); 907 908 self.updateSize(); 909 910 // initial update 911 _containerShiftIndex = -1; 912 _indexDiff = null; 913 for(i = 0; i < NUM_HOLDERS; i++) { 914 _setTranslateX( (i+_containerShiftIndex) * _slideSize.x, _itemHolders[i].el.style); 915 } 916 917 if(!_oldIE) { 918 framework.bind(self.scrollWrap, _downEvents, self); // no dragging for old IE 919 } 920 921 _listen('initialZoomInEnd', function() { 922 self.setContent(_itemHolders[0], _currentItemIndex-1); 923 self.setContent(_itemHolders[2], _currentItemIndex+1); 924 925 _itemHolders[0].el.style.display = _itemHolders[2].el.style.display = 'block'; 926 927 if(_options.focus) { 928 // focus causes layout, 929 // which causes lag during the animation, 930 // that's why we delay it untill the initial zoom transition ends 931 template.focus(); 932 } 933 934 935 _bindEvents(); 936 }); 937 938 // set content for center slide (first time) 939 self.setContent(_itemHolders[1], _currentItemIndex); 940 941 self.updateCurrItem(); 942 943 _shout('afterInit'); 944 945 if(!_isFixedPosition) { 946 947 // On all versions of iOS lower than 8.0, we check size of viewport every second. 948 // 949 // This is done to detect when Safari top & bottom bars appear, 950 // as this action doesn't trigger any events (like resize). 951 // 952 // On iOS8 they fixed this. 953 // 954 // 10 Nov 2014: iOS 7 usage ~40%. iOS 8 usage 56%. 955 956 _updateSizeInterval = setInterval(function() { 957 if(!_numAnimations && !_isDragging && !_isZooming && (_currZoomLevel === self.currItem.initialZoomLevel) ) { 958 self.updateSize(); 959 } 960 }, 1000); 961 } 962
963 framework.addClass(template, 'pswp--visible'); 964 }, 965 966 // Close the gallery, then destroy it 967 close: function() { 968 if(!_isOpen) { 969 return; 970 } 971 972 _isOpen = false; 973 _isDestroying = true; 974 _shout('close'); 975 _unbindEvents(); 976 977 _showOrHide(self.currItem, null, true, self.destroy); 978 }, 979 980 // destroys the gallery (unbinds events, cleans up intervals and timeouts to avoid memory leaks) 981 destroy: function() { 982 _shout('destroy'); 983 984 if(_showOrHideTimeout) { 985 clearTimeout(_showOrHideTimeout); 986 } 987 988 template.setAttribute('aria-hidden', 'true'); 989 template.className = _initalClassName; 990 991 if(_updateSizeInterval) { 992 clearInterval(_updateSizeInterval); 993 } 994 995 framework.unbind(self.scrollWrap, _downEvents, self); 996 997 // we unbind scroll event at the end, as closing animation may depend on it 998 framework.unbind(window, 'scroll', self); 999 1000 _stopDragUpdateLoop(); 1001 1002 _stopAllAnimations(); 1003 1004 _listeners = null; 1005 }, 1006 1007 /** 1008 * Pan image to position 1009 * @param {Number} x 1010 * @param {Number} y 1011 * @param {Boolean} force Will ignore bounds if set to true. 1012 */ 1013 panTo: function(x,y,force) { 1014 if(!force) { 1015 if(x > _currPanBounds.min.x) { 1016 x = _currPanBounds.min.x; 1017 } else if(x < _currPanBounds.max.x) { 1018 x = _currPanBounds.max.x; 1019 } 1020 1021 if(y > _currPanBounds.min.y) { 1022 y = _currPanBounds.min.y; 1023 } else if(y < _currPanBounds.max.y) { 1024 y = _currPanBounds.max.y; 1025 } 1026 } 1027 1028 _panOffset.x = x; 1029 _panOffset.y = y; 1030 _applyCurrentZoomPan(); 1031 }, 1032 1033 handleEvent: function (e) { 1034 e = e || window.event; 1035 if(_globalEventHandlers[e.type]) { 1036 _globalEventHandlers[e.type](e); 1037 } 1038 }, 1039 1040 1041 goTo: function(index) { 1042 1043 index = _getLoopedId(index); 1044 1045 var diff = index - _currentItemIndex; 1046 _indexDiff = diff; 1047 1048 _currentItemIndex = index; 1049 self.currItem = _getItemAt( _currentItemIndex ); 1050 _currPositionIndex -= diff; 1051 1052 _moveMainScroll(_slideSize.x * _currPositionIndex); 1053 1054 1055 _stopAllAnimations(); 1056 _mainScrollAnimating = false; 1057 1058 self.updateCurrItem(); 1059 }, 1060 next: function() { 1061 self.goTo( _currentItemIndex + 1); 1062 }, 1063 prev: function() { 1064 self.goTo( _currentItemIndex - 1); 1065 }, 1066 1067 // update current zoom/pan objects 1068 updateCurrZoomItem: function(emulateSetContent) { 1069 if(emulateSetContent) { 1070 _shout('beforeChange', 0); 1071 } 1072 1073 // itemHolder[1] is middle (current) item 1074 if(_itemHolders[1].el.children.length) { 1075 var zoomElement = _itemHolders[1].el.children[0]; 1076 if( framework.hasClass(zoomElement, 'pswp__zoom-wrap') ) { 1077 _currZoomElementStyle = zoomElement.style; 1078 } else { 1079 _currZoomElementStyle = null; 1080 } 1081 } else { 1082 _currZoomElementStyle = null; 1083 } 1084 1085 _currPanBounds = self.currItem.bounds; 1086 _startZoomLevel = _currZoomLevel = self.currItem.initialZoomLevel; 1087 1088 _panOffset.x = _currPanBounds.center.x; 1089 _panOffset.y = _currPanBounds.center.y; 1090 1091 if(emulateSetContent) { 1092 _shout('afterChange'); 1093 } 1094 }, 1095 1096 1097 invalidateCurrItems: function() { 1098 _itemsNeedUpdate = true; 1099 for(var i = 0; i < NUM_HOLDERS; i++) { 1100 if( _itemHolders[i].item ) { 1101 _itemHolders[i].item.needsUpdate = true; 1102 } 1103 } 1104 }, 1105 1106 updateCurrItem: function(beforeAnimation) { 1107 1108 if(_indexDiff === 0) { 1109 return; 1110 } 1111 1112 var diffAbs = Math.abs(_indexDiff), 1113 tempHolder; 1114 1115 if(beforeAnimation && diffAbs < 2) { 1116 return; 1117 } 1118 1119 1120 self.currItem = _getItemAt( _currentItemIndex ); 1121 _renderMaxResolution = false; 1122 1123 _shout('beforeChange', _indexDiff); 1124 1125 if(diffAbs >= NUM_HOLDERS) { 1126 _containerShiftIndex += _indexDiff + (_indexDiff > 0 ? -NUM_HOLDERS : NUM_HOLDERS); 1127 diffAbs = NUM_HOLDERS; 1128 } 1129 for(var i = 0; i < diffAbs; i++) { 1130 if(_indexDiff > 0) { 1131 tempHolder = _itemHolders.shift(); 1132 _itemHolders[NUM_HOLDERS-1] = tempHolder; // move first to last 1133 1134 _containerShiftIndex++; 1135 _setTranslateX( (_containerShiftIndex+2) * _slideSize.x, tempHolder.el.style); 1136 self.setContent(tempHolder, _currentItemIndex - diffAbs + i + 1 + 1); 1137 } else { 1138 tempHolder = _itemHolders.pop(); 1139 _itemHolders.unshift( tempHolder ); // move last to first 1140 1141 _containerShiftIndex--; 1142 _setTranslateX( _containerShiftIndex * _slideSize.x, tempHolder.el.style); 1143 self.setContent(tempHolder, _currentItemIndex + diffAbs - i - 1 - 1); 1144 } 1145 1146 } 1147 1148 // reset zoom/pan on previous item 1149 if(_currZoomElementStyle && Math.abs(_indexDiff) === 1) { 1150 1151 var prevItem = _getItemAt(_prevItemIndex); 1152 if(prevItem.initialZoomLevel !== _currZoomLevel) { 1153 _calculateItemSize(prevItem , _viewportSize ); 1154 _setImageSize(prevItem); 1155 _applyZoomPanToItem( prevItem ); 1156 } 1157 1158 } 1159 1160 // reset diff after update 1161 _indexDiff = 0; 1162 1163 self.updateCurrZoomItem(); 1164 1165 _prevItemIndex = _currentItemIndex; 1166 1167 _shout('afterChange'); 1168 1169 }, 1170 1171 1172 1173 updateSize: function(force) { 1174 1175 if(!_isFixedPosition && _options.modal) { 1176 var windowScrollY = framework.getScrollY(); 1177 if(_currentWindowScrollY !== windowScrollY) { 1178 template.style.top = windowScrollY + 'px'; 1179 _currentWindowScrollY = windowScrollY; 1180 } 1181 if(!force && _windowVisibleSize.x === window.innerWidth && _windowVisibleSize.y === window.innerHeight) { 1182 return; 1183 } 1184 _windowVisibleSize.x = window.innerWidth; 1185 _windowVisibleSize.y = window.innerHeight; 1186 1187 //template.style.width = _windowVisibleSize.x + 'px'; 1188 template.style.height = _windowVisibleSize.y + 'px'; 1189 } 1190 1191 1192 1193 _viewportSize.x = self.scrollWrap.clientWidth; 1194 _viewportSize.y = self.scrollWrap.clientHeight; 1195 1196 _updatePageScrollOffset(); 1197 1198 _slideSize.x = _viewportSize.x + Math.round(_viewportSize.x * _options.spacing); 1199 _slideSize.y = _viewportSize.y; 1200 1201 _moveMainScroll(_slideSize.x * _currPositionIndex); 1202 1203 _shout('beforeResize'); // even may be used for example to switch image sources 1204 1205 1206 // don't re-calculate size on inital size update 1207 if(_containerShiftIndex !== undefined) { 1208 1209 var holder, 1210 item, 1211 hIndex; 1212 1213 for(var i = 0; i < NUM_HOLDERS; i++) { 1214 holder = _itemHolders[i]; 1215 _setTranslateX( (i+_containerShiftIndex) * _slideSize.x, holder.el.style); 1216 1217 hIndex = _currentItemIndex+i-1; 1218 1219 if(_options.loop && _getNumItems() > 2) { 1220 hIndex = _getLoopedId(hIndex); 1221 } 1222 1223 // update zoom level on items and refresh source (if needsUpdate) 1224 item = _getItemAt( hIndex ); 1225 1226 // re-render gallery item if `needsUpdate`, 1227 // or doesn't have `bounds` (entirely new slide object) 1228 if( item && (_itemsNeedUpdate || item.needsUpdate || !item.bounds) ) { 1229 1230 self.cleanSlide( item ); 1231 1232 self.setContent( holder, hIndex ); 1233 1234 // if "center" slide 1235 if(i === 1) { 1236 self.currItem = item; 1237 self.updateCurrZoomItem(true); 1238 } 1239 1240 item.needsUpdate = false;
1241 1242 } else if(holder.index === -1 && hIndex >= 0) { 1243 // add content first time 1244 self.setContent( holder, hIndex ); 1245 } 1246 if(item && item.container) { 1247 _calculateItemSize(item, _viewportSize); 1248 _setImageSize(item); 1249 _applyZoomPanToItem( item ); 1250 } 1251 1252 } 1253 _itemsNeedUpdate = false; 1254 } 1255 1256 _startZoomLevel = _currZoomLevel = self.currItem.initialZoomLevel; 1257 _currPanBounds = self.currItem.bounds; 1258 1259 if(_currPanBounds) { 1260 _panOffset.x = _currPanBounds.center.x; 1261 _panOffset.y = _currPanBounds.center.y; 1262 _applyCurrentZoomPan( true ); 1263 } 1264 1265 _shout('resize'); 1266 }, 1267 1268 // Zoom current item to 1269 zoomTo: function(destZoomLevel, centerPoint, speed, easingFn, updateFn) { 1270 /* 1271 if(destZoomLevel === 'fit') { 1272 destZoomLevel = self.currItem.fitRatio; 1273 } else if(destZoomLevel === 'fill') { 1274 destZoomLevel = self.currItem.fillRatio; 1275 } 1276 */ 1277 1278 if(centerPoint) { 1279 _startZoomLevel = _currZoomLevel; 1280 _midZoomPoint.x = Math.abs(centerPoint.x) - _panOffset.x ; 1281 _midZoomPoint.y = Math.abs(centerPoint.y) - _panOffset.y ; 1282 _equalizePoints(_startPanOffset, _panOffset); 1283 } 1284 1285 var destPanBounds = _calculatePanBounds(destZoomLevel, false), 1286 destPanOffset = {}; 1287 1288 _modifyDestPanOffset('x', destPanBounds, destPanOffset, destZoomLevel); 1289 _modifyDestPanOffset('y', destPanBounds, destPanOffset, destZoomLevel); 1290 1291 var initialZoomLevel = _currZoomLevel; 1292 var initialPanOffset = { 1293 x: _panOffset.x, 1294 y: _panOffset.y 1295 }; 1296 1297 _roundPoint(destPanOffset); 1298 1299 var onUpdate = function(now) { 1300 if(now === 1) { 1301 _currZoomLevel = destZoomLevel; 1302 _panOffset.x = destPanOffset.x; 1303 _panOffset.y = destPanOffset.y; 1304 } else { 1305 _currZoomLevel = (destZoomLevel - initialZoomLevel) * now + initialZoomLevel; 1306 _panOffset.x = (destPanOffset.x - initialPanOffset.x) * now + initialPanOffset.x;
1307 _panOffset.y = (destPanOffset.y - initialPanOffset.y) * now + initialPanOffset.y; 1308 } 1309 1310 if(updateFn) { 1311 updateFn(now); 1312 } 1313 1314 _applyCurrentZoomPan( now === 1 ); 1315 }; 1316 1317 if(speed) { 1318 _animateProp('customZoomTo', 0, 1, speed, easingFn || framework.easing.sine.inOut, onUpdate); 1319 } else { 1320 onUpdate(1); 1321 } 1322 } 1323 1324 1325}; 1326 1327 1328/*>>core*/ 1329 1330/*>>gestures*/ 1331/** 1332 * Mouse/touch/pointer event handlers. 1333 * 1334 * separated from @core.js for readability 1335 */ 1336 1337var MIN_SWIPE_DISTANCE = 30, 1338 DIRECTION_CHECK_OFFSET = 10; // amount of pixels to drag to determine direction of swipe 1339 1340var _gestureStartTime, 1341 _gestureCheckSpeedTime, 1342 1343 // pool of objects that are used during dragging of zooming 1344 p = {}, // first point 1345 p2 = {}, // second point (for zoom gesture) 1346 delta = {}, 1347 _currPoint = {}, 1348 _startPoint = {}, 1349 _currPointers = [], 1350 _startMainScrollPos = {}, 1351 _releaseAnimData, 1352 _posPoints = [], // array of points during dragging, used to determine type of gesture 1353 _tempPoint = {}, 1354 1355 _isZoomingIn, 1356 _verticalDragInitiated, 1357 _oldAndroidTouchEndTimeout, 1358 _currZoomedItemIndex = 0, 1359 _centerPoint = _getEmptyPoint(), 1360 _lastReleaseTime = 0, 1361 _isDragging, // at least one pointer is down 1362 _isMultitouch, // at least two _pointers are down 1363 _zoomStarted, // zoom level changed during zoom gesture 1364 _moved, 1365 _dragAnimFrame, 1366 _mainScrollShifted, 1367 _currentPoints, // array of current touch points 1368 _isZooming, 1369 _currPointsDistance, 1370 _startPointsDistance, 1371 _currPanBounds, 1372 _mainScrollPos = _getEmptyPoint(), 1373 _currZoomElementStyle, 1374 _mainScrollAnimating, // true, if animation after swipe gesture is running 1375 _midZoomPoint = _getEmptyPoint(), 1376 _currCenterPoint = _getEmptyPoint(), 1377 _direction, 1378 _isFirstMove, 1379 _opacityChanged, 1380 _bgOpacity, 1381 _wasOverInitialZoom, 1382 1383 _isEqualPoints = function(p1, p2) { 1384 return p1.x === p2.x && p1.y === p2.y; 1385 }, 1386 _isNearbyPoints = function(touch0, touch1) { 1387 return Math.abs(touch0.x - touch1.x) < DOUBLE_TAP_RADIUS && Math.abs(touch0.y - touch1.y) < DOUBLE_TAP_RADIUS; 1388 }, 1389 _calculatePointsDistance = function(p1, p2) { 1390 _tempPoint.x = Math.abs( p1.x - p2.x ); 1391 _tempPoint.y = Math.abs( p1.y - p2.y ); 1392 return Math.sqrt(_tempPoint.x * _tempPoint.x + _tempPoint.y * _tempPoint.y); 1393 }, 1394 _stopDragUpdateLoop = function() { 1395 if(_dragAnimFrame) { 1396 _cancelAF(_dragAnimFrame); 1397 _dragAnimFrame = null; 1398 } 1399 }, 1400 _dragUpdateLoop = function() { 1401 if(_isDragging) { 1402 _dragAnimFrame = _requestAF(_dragUpdateLoop); 1403 _renderMovement(); 1404 } 1405 }, 1406 _canPan = function() { 1407 return !(_options.scaleMode === 'fit' && _currZoomLevel === self.currItem.initialZoomLevel); 1408 }, 1409 1410 // find the closest parent DOM element 1411 _closestElement = function(el, fn) { 1412 if(!el) { 1413 return false; 1414 } 1415 1416 // don't search elements above pswp__scroll-wrap 1417 if(el.className && el.className.indexOf('pswp__scroll-wrap') > -1 ) { 1418 return false; 1419 } 1420 1421 if( fn(el) ) { 1422 return el; 1423 } 1424 1425 return _closestElement(el.parentNode, fn); 1426 }, 1427 1428 _preventObj = {}, 1429 _preventDefaultEventBehaviour = function(e, isDown) { 1430 _preventObj.prevent = !_closestElement(e.target, _options.isClickableElement); 1431 1432 _shout('preventDragEvent', e, isDown, _preventObj); 1433 return _preventObj.prevent; 1434 1435 }, 1436 _convertTouchToPoint = function(touch, p) { 1437 p.x = touch.pageX; 1438 p.y = touch.pageY; 1439 p.id = touch.identifier; 1440 return p; 1441 }, 1442 _findCenterOfPoints = function(p1, p2, pCenter) { 1443 pCenter.x = (p1.x + p2.x) * 0.5; 1444 pCenter.y = (p1.y + p2.y) * 0.5; 1445 }, 1446 _pushPosPoint = function(time, x, y) { 1447 if(time - _gestureCheckSpeedTime > 50) { 1448 var o = _posPoints.length > 2 ? _posPoints.shift() : {}; 1449 o.x = x; 1450 o.y = y; 1451 _posPoints.push(o); 1452 _gestureCheckSpeedTime = time; 1453 } 1454 }, 1455 1456 _calculateVerticalDragOpacityRatio = function() { 1457 var yOffset = _panOffset.y - self.currItem.initialPosition.y; // difference between initial and current position 1458 return 1 - Math.abs( yOffset / (_viewportSize.y / 2) ); 1459 }, 1460 1461 1462 // points pool, reused during touch events 1463 _ePoint1 = {}, 1464 _ePoint2 = {}, 1465 _tempPointsArr = [], 1466 _tempCounter, 1467 _getTouchPoints = function(e) { 1468 // clean up previous points, without recreating array 1469 while(_tempPointsArr.length > 0) { 1470 _tempPointsArr.pop(); 1471 } 1472 1473 if(!_pointerEventEnabled) { 1474 if(e.type.indexOf('touch') > -1) { 1475 1476 if(e.touches && e.touches.length > 0) { 1477 _tempPointsArr[0] = _convertTouchToPoint(e.touches[0], _ePoint1); 1478 if(e.touches.length > 1) { 1479 _tempPointsArr[1] = _convertTouchToPoint(e.touches[1], _ePoint2); 1480 } 1481 } 1482 1483 } else { 1484 _ePoint1.x = e.pageX; 1485 _ePoint1.y = e.pageY; 1486 _ePoint1.id = ''; 1487 _tempPointsArr[0] = _ePoint1;//_ePoint1; 1488 } 1489 } else { 1490 _tempCounter = 0; 1491 // we can use forEach, as pointer events are supported only in modern browsers
1492 _currPointers.forEach(function(p) { 1493 if(_tempCounter === 0) { 1494 _tempPointsArr[0] = p; 1495 } else if(_tempCounter === 1) { 1496 _tempPointsArr[1] = p; 1497 } 1498 _tempCounter++; 1499 1500 }); 1501 } 1502 return _tempPointsArr; 1503 }, 1504 1505 _panOrMoveMainScroll = function(axis, delta) { 1506 1507 var panFriction, 1508 overDiff = 0, 1509 newOffset = _panOffset[axis] + delta[axis], 1510 startOverDiff, 1511 dir = delta[axis] > 0, 1512 newMainScrollPosition = _mainScrollPos.x + delta.x, 1513 mainScrollDiff = _mainScrollPos.x - _startMainScrollPos.x, 1514 newPanPos, 1515 newMainScrollPos; 1516 1517 // calculate fdistance over the bounds and friction 1518 if(newOffset > _currPanBounds.min[axis] || newOffset < _currPanBounds.max[axis]) { 1519 panFriction = _options.panEndFriction; 1520 // Linear increasing of friction, so at 1/4 of viewport it's at max value. 1521 // Looks not as nice as was expected. Left for history. 1522 // panFriction = (1 - (_panOffset[axis] + delta[axis] + panBounds.min[axis]) / (_viewportSize[axis] / 4) ); 1523 } else { 1524 panFriction = 1; 1525 } 1526 1527 newOffset = _panOffset[axis] + delta[axis] * panFriction; 1528 1529 // move main scroll or start panning 1530 if(_options.allowPanToNext || _currZoomLevel === self.currItem.initialZoomLevel) { 1531 1532 1533 if(!_currZoomElementStyle) { 1534 1535 newMainScrollPos = newMainScrollPosition; 1536 1537 } else if(_direction === 'h' && axis === 'x' && !_zoomStarted ) { 1538 1539 if(dir) { 1540 if(newOffset > _currPanBounds.min[axis]) { 1541 panFriction = _options.panEndFriction; 1542 overDiff = _currPanBounds.min[axis] - newOffset; 1543 startOverDiff = _currPanBounds.min[axis] - _startPanOffset[axis]; 1544 } 1545 1546 // drag right 1547 if( (startOverDiff <= 0 || mainScrollDiff < 0) && _getNumItems() > 1 ) { 1548 newMainScrollPos = newMainScrollPosition; 1549 if(mainScrollDiff < 0 && newMainScrollPosition > _startMainScrollPos.x) { 1550 newMainScrollPos = _startMainScrollPos.x; 1551 } 1552 } else { 1553 if(_currPanBounds.min.x !== _currPanBounds.max.x) { 1554 newPanPos = newOffset; 1555 } 1556 1557 } 1558 1559 } else { 1560 1561 if(newOffset < _currPanBounds.max[axis] ) { 1562 panFriction =_options.panEndFriction; 1563 overDiff = newOffset - _currPanBounds.max[axis]; 1564 startOverDiff = _startPanOffset[axis] - _currPanBounds.max[axis]; 1565 } 1566 1567 if( (startOverDiff <= 0 || mainScrollDiff > 0) && _getNumItems() > 1 ) { 1568 newMainScrollPos = newMainScrollPosition; 1569 1570 if(mainScrollDiff > 0 && newMainScrollPosition < _startMainScrollPos.x) { 1571 newMainScrollPos = _startMainScrollPos.x; 1572 } 1573 1574 } else { 1575 if(_currPanBounds.min.x !== _currPanBounds.max.x) { 1576 newPanPos = newOffset; 1577 } 1578 } 1579 1580 } 1581 1582 1583 // 1584 } 1585 1586 if(axis === 'x') { 1587 1588 if(newMainScrollPos !== undefined) { 1589 _moveMainScroll(newMainScrollPos, true); 1590 if(newMainScrollPos === _startMainScrollPos.x) { 1591 _mainScrollShifted = false; 1592 } else { 1593 _mainScrollShifted = true; 1594 } 1595 } 1596 1597 if(_currPanBounds.min.x !== _currPanBounds.max.x) { 1598 if(newPanPos !== undefined) { 1599 _panOffset.x = newPanPos; 1600 } else if(!_mainScrollShifted) { 1601 _panOffset.x += delta.x * panFriction; 1602 } 1603 } 1604 1605 return newMainScrollPos !== undefined; 1606 } 1607 1608 } 1609 1610 if(!_mainScrollAnimating) { 1611 1612 if(!_mainScrollShifted) { 1613 if(_currZoomLevel > self.currItem.fitRatio) { 1614 _panOffset[axis] += delta[axis] * panFriction; 1615 1616 } 1617 } 1618 1619 1620 } 1621 1622 }, 1623 1624 // Pointerdown/touchstart/mousedown handler 1625 _onDragStart = function(e) { 1626 1627 // Allow dragging only via left mouse button. 1628 // As this handler is not added in IE8 - we ignore e.which 1629 // 1630 // http://www.quirksmode.org/js/events_properties.html 1631 // https://developer.mozilla.org/en-US/docs/Web/API/event.button 1632 if(e.type === 'mousedown' && e.button > 0 ) { 1633 return; 1634 } 1635 1636 if(_initialZoomRunning) { 1637 e.preventDefault(); 1638 return; 1639 } 1640 1641 if(_oldAndroidTouchEndTimeout && e.type === 'mousedown') { 1642 return; 1643 } 1644 1645 if(_preventDefaultEventBehaviour(e, true)) { 1646 e.preventDefault(); 1647 } 1648 1649 1650 1651 _shout('pointerDown'); 1652 1653 if(_pointerEventEnabled) { 1654 var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id'); 1655 if(pointerIndex < 0) { 1656 pointerIndex = _currPointers.length; 1657 } 1658 _currPointers[pointerIndex] = {x:e.pageX, y:e.pageY, id: e.pointerId}; 1659 } 1660 1661 1662 1663 var startPointsList = _getTouchPoints(e), 1664 numPoints = startPointsList.length; 1665 1666 _currentPoints = null; 1667 1668 _stopAllAnimations(); 1669 1670 // init drag 1671 if(!_isDragging || numPoints === 1) { 1672 1673 1674 1675 _isDragging = _isFirstMove = true; 1676 framework.bind(window, _upMoveEvents, self); 1677 1678 _isZoomingIn = 1679 _wasOverInitialZoom = 1680 _opacityChanged = 1681 _verticalDragInitiated = 1682 _mainScrollShifted = 1683 _moved = 1684 _isMultitouch = 1685 _zoomStarted = false;
1686 1687 _direction = null; 1688 1689 _shout('firstTouchStart', startPointsList); 1690 1691 _equalizePoints(_startPanOffset, _panOffset); 1692 1693 _currPanDist.x = _currPanDist.y = 0; 1694 _equalizePoints(_currPoint, startPointsList[0]); 1695 _equalizePoints(_startPoint, _currPoint); 1696 1697 //_equalizePoints(_startMainScrollPos, _mainScrollPos); 1698 _startMainScrollPos.x = _slideSize.x * _currPositionIndex; 1699 1700 _posPoints = [{ 1701 x: _currPoint.x, 1702 y: _currPoint.y 1703 }]; 1704 1705 _gestureCheckSpeedTime = _gestureStartTime = _getCurrentTime(); 1706 1707 //_mainScrollAnimationEnd(true); 1708 _calculatePanBounds( _currZoomLevel, true ); 1709 1710 // Start rendering 1711 _stopDragUpdateLoop(); 1712 _dragUpdateLoop(); 1713 1714 } 1715 1716 // init zoom 1717 if(!_isZooming && numPoints > 1 && !_mainScrollAnimating && !_mainScrollShifted) { 1718 _startZoomLevel = _currZoomLevel; 1719 _zoomStarted = false; // true if zoom changed at least once 1720 1721 _isZooming = _isMultitouch = true; 1722 _currPanDist.y = _currPanDist.x = 0; 1723 1724 _equalizePoints(_startPanOffset, _panOffset); 1725 1726 _equalizePoints(p, startPointsList[0]); 1727 _equalizePoints(p2, startPointsList[1]); 1728 1729 _findCenterOfPoints(p, p2, _currCenterPoint); 1730 1731 _midZoomPoint.x = Math.abs(_currCenterPoint.x) - _panOffset.x; 1732 _midZoomPoint.y = Math.abs(_currCenterPoint.y) - _panOffset.y; 1733 _currPointsDistance = _startPointsDistance = _calculatePointsDistance(p, p2); 1734 } 1735 1736 1737 }, 1738 1739 // Pointermove/touchmove/mousemove handler 1740 _onDragMove = function(e) { 1741 1742 e.preventDefault(); 1743 1744 if(_pointerEventEnabled) { 1745 var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id'); 1746 if(pointerIndex > -1) { 1747 var p = _currPointers[pointerIndex]; 1748 p.x = e.pageX; 1749 p.y = e.pageY; 1750 } 1751 } 1752 1753 if(_isDragging) { 1754 var touchesList = _getTouchPoints(e); 1755 if(!_direction && !_moved && !_isZooming) { 1756 1757 if(_mainScrollPos.x !== _slideSize.x * _currPositionIndex) { 1758 // if main scroll position is shifted – direction is always horizontal 1759 _direction = 'h'; 1760 } else { 1761 var diff = Math.abs(touchesList[0].x - _currPoint.x) - Math.abs(touchesList[0].y - _currPoint.y); 1762 // check the direction of movement 1763 if(Math.abs(diff) >= DIRECTION_CHECK_OFFSET) { 1764 _direction = diff > 0 ? 'h' : 'v'; 1765 _currentPoints = touchesList; 1766 } 1767 } 1768 1769 } else { 1770 _currentPoints = touchesList; 1771 } 1772 } 1773 }, 1774 // 1775 _renderMovement = function() { 1776 1777 if(!_currentPoints) { 1778 return; 1779 } 1780 1781 var numPoints = _currentPoints.length; 1782 1783 if(numPoints === 0) { 1784 return; 1785 } 1786 1787 _equalizePoints(p, _currentPoints[0]); 1788 1789 delta.x = p.x - _currPoint.x; 1790 delta.y = p.y - _currPoint.y; 1791 1792 if(_isZooming && numPoints > 1) { 1793 // Handle behaviour for more than 1 point 1794 1795 _currPoint.x = p.x; 1796 _currPoint.y = p.y; 1797 1798 // check if one of two points changed 1799 if( !delta.x && !delta.y && _isEqualPoints(_currentPoints[1], p2) ) { 1800 return; 1801 } 1802 1803 _equalizePoints(p2, _currentPoints[1]); 1804 1805 1806 if(!_zoomStarted) { 1807 _zoomStarted = true; 1808 _shout('zoomGestureStarted'); 1809 } 1810 1811 // Distance between two points 1812 var pointsDistance = _calculatePointsDistance(p,p2); 1813 1814 var zoomLevel = _calculateZoomLevel(pointsDistance); 1815 1816 // slightly over the of initial zoom level 1817 if(zoomLevel > self.currItem.initialZoomLevel + self.currItem.initialZoomLevel / 15) { 1818 _wasOverInitialZoom = true; 1819 } 1820 1821 // Apply the friction if zoom level is out of the bounds 1822 var zoomFriction = 1, 1823 minZoomLevel = _getMinZoomLevel(), 1824 maxZoomLevel = _getMaxZoomLevel(); 1825 1826 if ( zoomLevel < minZoomLevel ) { 1827 1828 if(_options.pinchToClose && !_wasOverInitialZoom && _startZoomLevel <= self.currItem.initialZoomLevel) { 1829 // fade out background if zooming out 1830 var minusDiff = minZoomLevel - zoomLevel; 1831 var percent = 1 - minusDiff / (minZoomLevel / 1.2); 1832 1833 _applyBgOpacity(percent); 1834 _shout('onPinchClose', percent); 1835 _opacityChanged = true; 1836 } else { 1837 zoomFriction = (minZoomLevel - zoomLevel) / minZoomLevel; 1838 if(zoomFriction > 1) { 1839 zoomFriction = 1; 1840 } 1841 zoomLevel = minZoomLevel - zoomFriction * (minZoomLevel / 3); 1842 } 1843 1844 } else if ( zoomLevel > maxZoomLevel ) { 1845 // 1.5 - extra zoom level above the max. E.g. if max is x6, real max 6 + 1.5 = 7.5 1846 zoomFriction = (zoomLevel - maxZoomLevel) / ( minZoomLevel * 6 ); 1847 if(zoomFriction > 1) { 1848 zoomFriction = 1; 1849 } 1850 zoomLevel = maxZoomLevel + zoomFriction * minZoomLevel; 1851 } 1852 1853 if(zoomFriction < 0) { 1854 zoomFriction = 0; 1855 } 1856 1857 // distance between touch points after friction is applied 1858 _currPointsDistance = pointsDistance; 1859 1860 // _centerPoint - The point in the middle of two pointers 1861 _findCenterOfPoints(p, p2, _centerPoint); 1862 1863 // paning with two pointers pressed 1864 _currPanDist.x += _centerPoint.x - _currCenterPoint.x; 1865 _currPanDist.y += _centerPoint.y - _currCenterPoint.y; 1866 _equalizePoints(_currCenterPoint, _centerPoint); 1867 1868 _panOffset.x = _calculatePanOffset('x', zoomLevel);
1869 _panOffset.y = _calculatePanOffset('y', zoomLevel); 1870 1871 _isZoomingIn = zoomLevel > _currZoomLevel; 1872 _currZoomLevel = zoomLevel; 1873 _applyCurrentZoomPan(); 1874 1875 } else { 1876 1877 // handle behaviour for one point (dragging or panning) 1878 1879 if(!_direction) { 1880 return; 1881 } 1882 1883 if(_isFirstMove) { 1884 _isFirstMove = false; 1885 1886 // subtract drag distance that was used during the detection direction 1887 1888 if( Math.abs(delta.x) >= DIRECTION_CHECK_OFFSET) { 1889 delta.x -= _currentPoints[0].x - _startPoint.x; 1890 } 1891 1892 if( Math.abs(delta.y) >= DIRECTION_CHECK_OFFSET) { 1893 delta.y -= _currentPoints[0].y - _startPoint.y; 1894 } 1895 } 1896 1897 _currPoint.x = p.x; 1898 _currPoint.y = p.y; 1899 1900 // do nothing if pointers position hasn't changed 1901 if(delta.x === 0 && delta.y === 0) { 1902 return; 1903 } 1904 1905 if(_direction === 'v' && _options.closeOnVerticalDrag) { 1906 if(!_canPan()) { 1907 _currPanDist.y += delta.y; 1908 _panOffset.y += delta.y; 1909 1910 var opacityRatio = _calculateVerticalDragOpacityRatio(); 1911 1912 _verticalDragInitiated = true; 1913 _shout('onVerticalDrag', opacityRatio); 1914 1915 _applyBgOpacity(opacityRatio); 1916 _applyCurrentZoomPan(); 1917 return ; 1918 } 1919 } 1920 1921 _pushPosPoint(_getCurrentTime(), p.x, p.y); 1922 1923 _moved = true; 1924 _currPanBounds = self.currItem.bounds; 1925 1926 var mainScrollChanged = _panOrMoveMainScroll('x', delta); 1927 if(!mainScrollChanged) { 1928 _panOrMoveMainScroll('y', delta); 1929 1930 _roundPoint(_panOffset); 1931 _applyCurrentZoomPan(); 1932 } 1933 1934 } 1935 1936 }, 1937 1938 // Pointerup/pointercancel/touchend/touchcancel/mouseup event handler 1939 _onDragRelease = function(e) { 1940 1941 if(_features.isOldAndroid ) { 1942 1943 if(_oldAndroidTouchEndTimeout && e.type === 'mouseup') { 1944 return; 1945 } 1946 1947 // on Android (v4.1, 4.2, 4.3 & possibly older) 1948 // ghost mousedown/up event isn't preventable via e.preventDefault, 1949 // which causes fake mousedown event 1950 // so we block mousedown/up for 600ms 1951 if( e.type.indexOf('touch') > -1 ) { 1952 clearTimeout(_oldAndroidTouchEndTimeout); 1953 _oldAndroidTouchEndTimeout = setTimeout(function() { 1954 _oldAndroidTouchEndTimeout = 0; 1955 }, 600); 1956 } 1957 1958 } 1959 1960 _shout('pointerUp'); 1961 1962 if(_preventDefaultEventBehaviour(e, false)) { 1963 e.preventDefault(); 1964 } 1965 1966 var releasePoint; 1967 1968 if(_pointerEventEnabled) { 1969 var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id'); 1970 1971 if(pointerIndex > -1) { 1972 releasePoint = _currPointers.splice(pointerIndex, 1)[0]; 1973 1974 if(navigator.pointerEnabled) { 1975 releasePoint.type = e.pointerType || 'mouse'; 1976 } else { 1977 var MSPOINTER_TYPES = { 1978 4: 'mouse', // event.MSPOINTER_TYPE_MOUSE 1979 2: 'touch', // event.MSPOINTER_TYPE_TOUCH 1980 3: 'pen' // event.MSPOINTER_TYPE_PEN 1981 }; 1982 releasePoint.type = MSPOINTER_TYPES[e.pointerType]; 1983 1984 if(!releasePoint.type) { 1985 releasePoint.type = e.pointerType || 'mouse'; 1986 } 1987 } 1988 1989 } 1990 } 1991 1992 var touchList = _getTouchPoints(e), 1993 gestureType, 1994 numPoints = touchList.length; 1995 1996 if(e.type === 'mouseup') { 1997 numPoints = 0; 1998 } 1999 2000 // Do nothing if there were 3 touch points or more 2001 if(numPoints === 2) { 2002 _currentPoints = null; 2003 return true; 2004 } 2005 2006 // if second pointer released 2007 if(numPoints === 1) { 2008 _equalizePoints(_startPoint, touchList[0]); 2009 } 2010 2011 2012 // pointer hasn't moved, send "tap release" point 2013 if(numPoints === 0 && !_direction && !_mainScrollAnimating) { 2014 if(!releasePoint) { 2015 if(e.type === 'mouseup') { 2016 releasePoint = {x: e.pageX, y: e.pageY, type:'mouse'}; 2017 } else if(e.changedTouches && e.changedTouches[0]) { 2018 releasePoint = {x: e.changedTouches[0].pageX, y: e.changedTouches[0].pageY, type:'touch'}; 2019 } 2020 } 2021 2022 _shout('touchRelease', e, releasePoint); 2023 } 2024 2025 // Difference in time between releasing of two last touch points (zoom gesture) 2026 var releaseTimeDiff = -1; 2027 2028 // Gesture completed, no pointers left 2029 if(numPoints === 0) { 2030 _isDragging = false; 2031 framework.unbind(window, _upMoveEvents, self); 2032 2033 _stopDragUpdateLoop(); 2034 2035 if(_isZooming) { 2036 // Two points released at the same time 2037 releaseTimeDiff = 0; 2038 } else if(_lastReleaseTime !== -1) { 2039 releaseTimeDiff = _getCurrentTime() - _lastReleaseTime; 2040 } 2041 } 2042 _lastReleaseTime = numPoints === 1 ? _getCurrentTime() : -1; 2043
2044 if(releaseTimeDiff !== -1 && releaseTimeDiff < 150) { 2045 gestureType = 'zoom'; 2046 } else { 2047 gestureType = 'swipe'; 2048 } 2049 2050 if(_isZooming && numPoints < 2) { 2051 _isZooming = false; 2052 2053 // Only second point released 2054 if(numPoints === 1) { 2055 gestureType = 'zoomPointerUp'; 2056 } 2057 _shout('zoomGestureEnded'); 2058 } 2059 2060 _currentPoints = null; 2061 if(!_moved && !_zoomStarted && !_mainScrollAnimating && !_verticalDragInitiated) { 2062 // nothing to animate 2063 return; 2064 } 2065 2066 _stopAllAnimations(); 2067 2068 2069 if(!_releaseAnimData) { 2070 _releaseAnimData = _initDragReleaseAnimationData(); 2071 } 2072 2073 _releaseAnimData.calculateSwipeSpeed('x'); 2074 2075 2076 if(_verticalDragInitiated) { 2077 2078 var opacityRatio = _calculateVerticalDragOpacityRatio(); 2079 2080 if(opacityRatio < _options.verticalDragRange) { 2081 self.close(); 2082 } else { 2083 var initalPanY = _panOffset.y, 2084 initialBgOpacity = _bgOpacity; 2085 2086 _animateProp('verticalDrag', 0, 1, 300, framework.easing.cubic.out, function(now) { 2087 2088 _panOffset.y = (self.currItem.initialPosition.y - initalPanY) * now + initalPanY; 2089 2090 _applyBgOpacity( (1 - initialBgOpacity) * now + initialBgOpacity ); 2091 _applyCurrentZoomPan(); 2092 }); 2093 2094 _shout('onVerticalDrag', 1); 2095 } 2096 2097 return; 2098 } 2099 2100 2101 // main scroll 2102 if( (_mainScrollShifted || _mainScrollAnimating) && numPoints === 0) { 2103 var itemChanged = _finishSwipeMainScrollGesture(gestureType, _releaseAnimData); 2104 if(itemChanged) { 2105 return; 2106 } 2107 gestureType = 'zoomPointerUp'; 2108 } 2109 2110 // prevent zoom/pan animation when main scroll animation runs 2111 if(_mainScrollAnimating) { 2112 return; 2113 } 2114 2115 // Complete simple zoom gesture (reset zoom level if it's out of the bounds) 2116 if(gestureType !== 'swipe') { 2117 _completeZoomGesture(); 2118 return; 2119 } 2120 2121 // Complete pan gesture if main scroll is not shifted, and it's possible to pan current image 2122 if(!_mainScrollShifted && _currZoomLevel > self.currItem.fitRatio) { 2123 _completePanGesture(_releaseAnimData); 2124 } 2125 }, 2126 2127 2128 // Returns object with data about gesture 2129 // It's created only once and then reused 2130 _initDragReleaseAnimationData = function() { 2131 // temp local vars 2132 var lastFlickDuration, 2133 tempReleasePos; 2134 2135 // s = this 2136 var s = { 2137 lastFlickOffset: {}, 2138 lastFlickDist: {}, 2139 lastFlickSpeed: {}, 2140 slowDownRatio: {}, 2141 slowDownRatioReverse: {}, 2142 speedDecelerationRatio: {}, 2143 speedDecelerationRatioAbs: {}, 2144 distanceOffset: {}, 2145 backAnimDestination: {}, 2146 backAnimStarted: {}, 2147 calculateSwipeSpeed: function(axis) { 2148 2149 2150 if( _posPoints.length > 1) { 2151 lastFlickDuration = _getCurrentTime() - _gestureCheckSpeedTime + 50; 2152 tempReleasePos = _posPoints[_posPoints.length-2][axis]; 2153 } else { 2154 lastFlickDuration = _getCurrentTime() - _gestureStartTime; // total gesture duration 2155 tempReleasePos = _startPoint[axis]; 2156 } 2157 s.lastFlickOffset[axis] = _currPoint[axis] - tempReleasePos; 2158 s.lastFlickDist[axis] = Math.abs(s.lastFlickOffset[axis]); 2159 if(s.lastFlickDist[axis] > 20) { 2160 s.lastFlickSpeed[axis] = s.lastFlickOffset[axis] / lastFlickDuration; 2161 } else { 2162 s.lastFlickSpeed[axis] = 0; 2163 } 2164 if( Math.abs(s.lastFlickSpeed[axis]) < 0.1 ) { 2165 s.lastFlickSpeed[axis] = 0; 2166 } 2167 2168 s.slowDownRatio[axis] = 0.95; 2169 s.slowDownRatioReverse[axis] = 1 - s.slowDownRatio[axis]; 2170 s.speedDecelerationRatio[axis] = 1; 2171 }, 2172 2173 calculateOverBoundsAnimOffset: function(axis, speed) { 2174 if(!s.backAnimStarted[axis]) { 2175 2176 if(_panOffset[axis] > _currPanBounds.min[axis]) { 2177 s.backAnimDestination[axis] = _currPanBounds.min[axis]; 2178 2179 } else if(_panOffset[axis] < _currPanBounds.max[axis]) { 2180 s.backAnimDestination[axis] = _currPanBounds.max[axis]; 2181 } 2182 2183 if(s.backAnimDestination[axis] !== undefined) { 2184 s.slowDownRatio[axis] = 0.7; 2185 s.slowDownRatioReverse[axis] = 1 - s.slowDownRatio[axis]; 2186 if(s.speedDecelerationRatioAbs[axis] < 0.05) { 2187 2188 s.lastFlickSpeed[axis] = 0; 2189 s.backAnimStarted[axis] = true; 2190 2191 _animateProp('bounceZoomPan'+axis,_panOffset[axis], 2192 s.backAnimDestination[axis], 2193 speed || 300, 2194 framework.easing.sine.out, 2195 function(pos) { 2196 _panOffset[axis] = pos; 2197 _applyCurrentZoomPan(); 2198 } 2199 ); 2200 2201 } 2202 } 2203 } 2204 }, 2205 2206 // Reduces the speed by slowDownRatio (per 10ms) 2207 calculateAnimOffset: function(axis) {
2208 if(!s.backAnimStarted[axis]) { 2209 s.speedDecelerationRatio[axis] = s.speedDecelerationRatio[axis] * (s.slowDownRatio[axis] + 2210 s.slowDownRatioReverse[axis] - 2211 s.slowDownRatioReverse[axis] * s.timeDiff / 10); 2212 2213 s.speedDecelerationRatioAbs[axis] = Math.abs(s.lastFlickSpeed[axis] * s.speedDecelerationRatio[axis]); 2214 s.distanceOffset[axis] = s.lastFlickSpeed[axis] * s.speedDecelerationRatio[axis] * s.timeDiff; 2215 _panOffset[axis] += s.distanceOffset[axis]; 2216 2217 } 2218 }, 2219 2220 panAnimLoop: function() { 2221 if ( _animations.zoomPan ) { 2222 _animations.zoomPan.raf = _requestAF(s.panAnimLoop); 2223 2224 s.now = _getCurrentTime(); 2225 s.timeDiff = s.now - s.lastNow; 2226 s.lastNow = s.now; 2227 2228 s.calculateAnimOffset('x'); 2229 s.calculateAnimOffset('y'); 2230 2231 _applyCurrentZoomPan(); 2232 2233 s.calculateOverBoundsAnimOffset('x'); 2234 s.calculateOverBoundsAnimOffset('y'); 2235 2236 2237 if (s.speedDecelerationRatioAbs.x < 0.05 && s.speedDecelerationRatioAbs.y < 0.05) { 2238 2239 // round pan position 2240 _panOffset.x = Math.round(_panOffset.x); 2241 _panOffset.y = Math.round(_panOffset.y); 2242 _applyCurrentZoomPan(); 2243 2244 _stopAnimation('zoomPan'); 2245 return; 2246 } 2247 } 2248 2249 } 2250 }; 2251 return s; 2252 }, 2253 2254 _completePanGesture = function(animData) { 2255 // calculate swipe speed for Y axis (paanning) 2256 animData.calculateSwipeSpeed('y'); 2257 2258 _currPanBounds = self.currItem.bounds; 2259 2260 animData.backAnimDestination = {}; 2261 animData.backAnimStarted = {}; 2262 2263 // Avoid acceleration animation if speed is too low 2264 if(Math.abs(animData.lastFlickSpeed.x) <= 0.05 && Math.abs(animData.lastFlickSpeed.y) <= 0.05 ) { 2265 animData.speedDecelerationRatioAbs.x = animData.speedDecelerationRatioAbs.y = 0; 2266 2267 // Run pan drag release animation. E.g. if you drag image and release finger without momentum. 2268 animData.calculateOverBoundsAnimOffset('x'); 2269 animData.calculateOverBoundsAnimOffset('y'); 2270 return true; 2271 } 2272 2273 // Animation loop that controls the acceleration after pan gesture ends 2274 _registerStartAnimation('zoomPan'); 2275 animData.lastNow = _getCurrentTime(); 2276 animData.panAnimLoop(); 2277 }, 2278 2279 2280 _finishSwipeMainScrollGesture = function(gestureType, _releaseAnimData) { 2281 var itemChanged; 2282 if(!_mainScrollAnimating) { 2283 _currZoomedItemIndex = _currentItemIndex; 2284 } 2285 2286 2287 2288 var itemsDiff; 2289 2290 if(gestureType === 'swipe') { 2291 var totalShiftDist = _currPoint.x - _startPoint.x, 2292 isFastLastFlick = _releaseAnimData.lastFlickDist.x < 10; 2293 2294 // if container is shifted for more than MIN_SWIPE_DISTANCE, 2295 // and last flick gesture was in right direction 2296 if(totalShiftDist > MIN_SWIPE_DISTANCE && 2297 (isFastLastFlick || _releaseAnimData.lastFlickOffset.x > 20) ) { 2298 // go to prev item 2299 itemsDiff = -1; 2300 } else if(totalShiftDist < -MIN_SWIPE_DISTANCE && 2301 (isFastLastFlick || _releaseAnimData.lastFlickOffset.x < -20) ) { 2302 // go to next item 2303 itemsDiff = 1; 2304 } 2305 } 2306 2307 var nextCircle; 2308 2309 if(itemsDiff) { 2310 2311 _currentItemIndex += itemsDiff; 2312 2313 if(_currentItemIndex < 0) { 2314 _currentItemIndex = _options.loop ? _getNumItems()-1 : 0; 2315 nextCircle = true; 2316 } else if(_currentItemIndex >= _getNumItems()) { 2317 _currentItemIndex = _options.loop ? 0 : _getNumItems()-1; 2318 nextCircle = true; 2319 } 2320 2321 if(!nextCircle || _options.loop) { 2322 _indexDiff += itemsDiff; 2323 _currPositionIndex -= itemsDiff; 2324 itemChanged = true; 2325 } 2326 2327 2328 2329 } 2330 2331 var animateToX = _slideSize.x * _currPositionIndex; 2332 var animateToDist = Math.abs( animateToX - _mainScrollPos.x ); 2333 var finishAnimDuration; 2334 2335 2336 if(!itemChanged && animateToX > _mainScrollPos.x !== _releaseAnimData.lastFlickSpeed.x > 0) { 2337 // "return to current" duration, e.g. when dragging from slide 0 to -1 2338 finishAnimDuration = 333; 2339 } else { 2340 finishAnimDuration = Math.abs(_releaseAnimData.lastFlickSpeed.x) > 0 ? 2341 animateToDist / Math.abs(_releaseAnimData.lastFlickSpeed.x) : 2342 333; 2343 2344 finishAnimDuration = Math.min(finishAnimDuration, 400); 2345 finishAnimDuration = Math.max(finishAnimDuration, 250); 2346 } 2347 2348 if(_currZoomedItemIndex === _currentItemIndex) { 2349 itemChanged = false;
2350 } 2351 2352 _mainScrollAnimating = true; 2353 2354 _shout('mainScrollAnimStart'); 2355 2356 _animateProp('mainScroll', _mainScrollPos.x, animateToX, finishAnimDuration, framework.easing.cubic.out, 2357 _moveMainScroll, 2358 function() { 2359 _stopAllAnimations(); 2360 _mainScrollAnimating = false; 2361 _currZoomedItemIndex = -1; 2362 2363 if(itemChanged || _currZoomedItemIndex !== _currentItemIndex) { 2364 self.updateCurrItem(); 2365 } 2366 2367 _shout('mainScrollAnimComplete'); 2368 } 2369 ); 2370 2371 if(itemChanged) { 2372 self.updateCurrItem(true); 2373 } 2374 2375 return itemChanged; 2376 }, 2377 2378 _calculateZoomLevel = function(touchesDistance) { 2379 return 1 / _startPointsDistance * touchesDistance * _startZoomLevel; 2380 }, 2381 2382 // Resets zoom if it's out of bounds 2383 _completeZoomGesture = function() { 2384 var destZoomLevel = _currZoomLevel, 2385 minZoomLevel = _getMinZoomLevel(), 2386 maxZoomLevel = _getMaxZoomLevel(); 2387 2388 if ( _currZoomLevel < minZoomLevel ) { 2389 destZoomLevel = minZoomLevel; 2390 } else if ( _currZoomLevel > maxZoomLevel ) { 2391 destZoomLevel = maxZoomLevel; 2392 } 2393 2394 var destOpacity = 1, 2395 onUpdate, 2396 initialOpacity = _bgOpacity; 2397 2398 if(_opacityChanged && !_isZoomingIn && !_wasOverInitialZoom && _currZoomLevel < minZoomLevel) { 2399 //_closedByScroll = true; 2400 self.close(); 2401 return true; 2402 } 2403 2404 if(_opacityChanged) { 2405 onUpdate = function(now) { 2406 _applyBgOpacity( (destOpacity - initialOpacity) * now + initialOpacity ); 2407 }; 2408 } 2409 2410 self.zoomTo(destZoomLevel, 0, 200, framework.easing.cubic.out, onUpdate); 2411 return true; 2412 }; 2413 2414 2415_registerModule('Gestures', { 2416 publicMethods: { 2417 2418 initGestures: function() { 2419 2420 // helper function that builds touch/pointer/mouse events 2421 var addEventNames = function(pref, down, move, up, cancel) { 2422 _dragStartEvent = pref + down; 2423 _dragMoveEvent = pref + move; 2424 _dragEndEvent = pref + up; 2425 if(cancel) { 2426 _dragCancelEvent = pref + cancel; 2427 } else { 2428 _dragCancelEvent = ''; 2429 } 2430 }; 2431 2432 _pointerEventEnabled = _features.pointerEvent; 2433 if(_pointerEventEnabled && _features.touch) { 2434 // we don't need touch events, if browser supports pointer events 2435 _features.touch = false; 2436 } 2437 2438 if(_pointerEventEnabled) { 2439 if(navigator.pointerEnabled) { 2440 addEventNames('pointer', 'down', 'move', 'up', 'cancel'); 2441 } else { 2442 // IE10 pointer events are case-sensitive 2443 addEventNames('MSPointer', 'Down', 'Move', 'Up', 'Cancel'); 2444 } 2445 } else if(_features.touch) { 2446 addEventNames('touch', 'start', 'move', 'end', 'cancel'); 2447 _likelyTouchDevice = true; 2448 } else { 2449 addEventNames('mouse', 'down', 'move', 'up'); 2450 } 2451 2452 _upMoveEvents = _dragMoveEvent + ' ' + _dragEndEvent + ' ' + _dragCancelEvent; 2453 _downEvents = _dragStartEvent; 2454 2455 if(_pointerEventEnabled && !_likelyTouchDevice) { 2456 _likelyTouchDevice = (navigator.maxTouchPoints > 1) || (navigator.msMaxTouchPoints > 1); 2457 } 2458 // make variable public 2459 self.likelyTouchDevice = _likelyTouchDevice; 2460 2461 _globalEventHandlers[_dragStartEvent] = _onDragStart; 2462 _globalEventHandlers[_dragMoveEvent] = _onDragMove; 2463 _globalEventHandlers[_dragEndEvent] = _onDragRelease; // the Kraken 2464 2465 if(_dragCancelEvent) { 2466 _globalEventHandlers[_dragCancelEvent] = _globalEventHandlers[_dragEndEvent]; 2467 } 2468 2469 // Bind mouse events on device with detected hardware touch support, in case it supports multiple types of input. 2470 if(_features.touch) { 2471 _downEvents += ' mousedown'; 2472 _upMoveEvents += ' mousemove mouseup'; 2473 _globalEventHandlers.mousedown = _globalEventHandlers[_dragStartEvent]; 2474 _globalEventHandlers.mousemove = _globalEventHandlers[_dragMoveEvent]; 2475 _globalEventHandlers.mouseup = _globalEventHandlers[_dragEndEvent]; 2476 } 2477 2478 if(!_likelyTouchDevice) { 2479 // don't allow pan to next slide from zoomed state on Desktop 2480 _options.allowPanToNext = false; 2481 } 2482 } 2483 2484 } 2485}); 2486 2487 2488/*>>gestures*/ 2489 2490/*>>show-hide-transition*/ 2491/**
2492 * show-hide-transition.js: 2493 * 2494 * Manages initial opening or closing transition. 2495 * 2496 * If you're not planning to use transition for gallery at all, 2497 * you may set options hideAnimationDuration and showAnimationDuration to 0, 2498 * and just delete startAnimation function. 2499 * 2500 */ 2501 2502 2503var _showOrHideTimeout, 2504 _showOrHide = function(item, img, out, completeFn) { 2505 2506 if(_showOrHideTimeout) { 2507 clearTimeout(_showOrHideTimeout); 2508 } 2509 2510 _initialZoomRunning = true; 2511 _initialContentSet = true; 2512 2513 // dimensions of small thumbnail {x:,y:,w:}. 2514 // Height is optional, as calculated based on large image. 2515 var thumbBounds; 2516 if(item.initialLayout) { 2517 thumbBounds = item.initialLayout; 2518 item.initialLayout = null; 2519 } else { 2520 thumbBounds = _options.getThumbBoundsFn && _options.getThumbBoundsFn(_currentItemIndex); 2521 } 2522 2523 var duration = out ? _options.hideAnimationDuration : _options.showAnimationDuration; 2524 2525 var onComplete = function() { 2526 _stopAnimation('initialZoom'); 2527 if(!out) { 2528 _applyBgOpacity(1); 2529 if(img) { 2530 img.style.display = 'block'; 2531 } 2532 framework.addClass(template, 'pswp--animated-in'); 2533 _shout('initialZoom' + (out ? 'OutEnd' : 'InEnd')); 2534 } else { 2535 self.template.removeAttribute('style'); 2536 self.bg.removeAttribute('style'); 2537 } 2538 2539 if(completeFn) { 2540 completeFn(); 2541 } 2542 _initialZoomRunning = false; 2543 }; 2544 2545 // if bounds aren't provided, just open gallery without animation 2546 if(!duration || !thumbBounds || thumbBounds.x === undefined) { 2547 2548 _shout('initialZoom' + (out ? 'Out' : 'In') ); 2549 2550 _currZoomLevel = item.initialZoomLevel; 2551 _equalizePoints(_panOffset, item.initialPosition ); 2552 _applyCurrentZoomPan(); 2553 2554 template.style.opacity = out ? 0 : 1; 2555 _applyBgOpacity(1); 2556 2557 if(duration) { 2558 setTimeout(function() { 2559 onComplete(); 2560 }, duration); 2561 } else { 2562 onComplete(); 2563 } 2564 2565 return; 2566 } 2567 2568 var startAnimation = function() { 2569 var closeWithRaf = _closedByScroll, 2570 fadeEverything = !self.currItem.src || self.currItem.loadError || _options.showHideOpacity; 2571 2572 // apply hw-acceleration to image 2573 if(item.miniImg) { 2574 item.miniImg.style.webkitBackfaceVisibility = 'hidden'; 2575 } 2576 2577 if(!out) { 2578 _currZoomLevel = thumbBounds.w / item.w; 2579 _panOffset.x = thumbBounds.x; 2580 _panOffset.y = thumbBounds.y - _initalWindowScrollY; 2581 2582 self[fadeEverything ? 'template' : 'bg'].style.opacity = 0.001; 2583 _applyCurrentZoomPan(); 2584 } 2585 2586 _registerStartAnimation('initialZoom'); 2587 2588 if(out && !closeWithRaf) { 2589 framework.removeClass(template, 'pswp--animated-in'); 2590 } 2591 2592 if(fadeEverything) { 2593 if(out) { 2594 framework[ (closeWithRaf ? 'remove' : 'add') + 'Class' ](template, 'pswp--animate_opacity'); 2595 } else { 2596 setTimeout(function() { 2597 framework.addClass(template, 'pswp--animate_opacity'); 2598 }, 30); 2599 } 2600 } 2601 2602 _showOrHideTimeout = setTimeout(function() { 2603 2604 _shout('initialZoom' + (out ? 'Out' : 'In') ); 2605 2606 2607 if(!out) { 2608 2609 // "in" animation always uses CSS transitions (instead of rAF). 2610 // CSS transition work faster here, 2611 // as developer may also want to animate other things, 2612 // like ui on top of sliding area, which can be animated just via CSS 2613 2614 _currZoomLevel = item.initialZoomLevel; 2615 _equalizePoints(_panOffset, item.initialPosition ); 2616 _applyCurrentZoomPan(); 2617 _applyBgOpacity(1); 2618 2619 if(fadeEverything) { 2620 template.style.opacity = 1; 2621 } else { 2622 _applyBgOpacity(1); 2623 } 2624 2625 _showOrHideTimeout = setTimeout(onComplete, duration + 20); 2626 } else { 2627 2628 // "out" animation uses rAF only when PhotoSwipe is closed by browser scroll, to recalculate position 2629 var destZoomLevel = thumbBounds.w / item.w, 2630 initialPanOffset = { 2631 x: _panOffset.x, 2632 y: _panOffset.y 2633 }, 2634 initialZoomLevel = _currZoomLevel, 2635 initalBgOpacity = _bgOpacity, 2636 onUpdate = function(now) { 2637 2638 if(now === 1) { 2639 _currZoomLevel = destZoomLevel; 2640 _panOffset.x = thumbBounds.x; 2641 _panOffset.y = thumbBounds.y - _currentWindowScrollY; 2642 } else { 2643 _currZoomLevel = (destZoomLevel - initialZoomLevel) * now + initialZoomLevel; 2644 _panOffset.x = (thumbBounds.x - initialPanOffset.x) * now + initialPanOffset.x;
2645 _panOffset.y = (thumbBounds.y - _currentWindowScrollY - initialPanOffset.y) * now + initialPanOffset.y; 2646 } 2647 2648 _applyCurrentZoomPan(); 2649 if(fadeEverything) { 2650 template.style.opacity = 1 - now; 2651 } else { 2652 _applyBgOpacity( initalBgOpacity - now * initalBgOpacity ); 2653 } 2654 }; 2655 2656 if(closeWithRaf) { 2657 _animateProp('initialZoom', 0, 1, duration, framework.easing.cubic.out, onUpdate, onComplete); 2658 } else { 2659 onUpdate(1); 2660 _showOrHideTimeout = setTimeout(onComplete, duration + 20); 2661 } 2662 } 2663 2664 }, out ? 25 : 90); // Main purpose of this delay is to give browser time to paint and 2665 // create composite layers of PhotoSwipe UI parts (background, controls, caption, arrows). 2666 // Which avoids lag at the beginning of scale transition. 2667 }; 2668 startAnimation(); 2669 2670 2671 }; 2672 2673/*>>show-hide-transition*/ 2674 2675/*>>items-controller*/ 2676/** 2677* 2678* Controller manages gallery items, their dimensions, and their content. 2679* 2680*/ 2681 2682var _items, 2683 _tempPanAreaSize = {}, 2684 _imagesToAppendPool = [], 2685 _initialContentSet, 2686 _initialZoomRunning, 2687 _controllerDefaultOptions = { 2688 index: 0, 2689 errorMsg: '<div class="pswp__error-msg"><a href="%url%" target="_blank">The image</a> could not be loaded.</div>', 2690 forceProgressiveLoading: false, // TODO 2691 preload: [1,1], 2692 getNumItemsFn: function() { 2693 return _items.length; 2694 } 2695 }; 2696 2697 2698var _getItemAt, 2699 _getNumItems, 2700 _initialIsLoop, 2701 _getZeroBounds = function() { 2702 return { 2703 center:{x:0,y:0}, 2704 max:{x:0,y:0}, 2705 min:{x:0,y:0} 2706 }; 2707 }, 2708 _calculateSingleItemPanBounds = function(item, realPanElementW, realPanElementH ) { 2709 var bounds = item.bounds; 2710 2711 // position of element when it's centered 2712 bounds.center.x = Math.round((_tempPanAreaSize.x - realPanElementW) / 2); 2713 bounds.center.y = Math.round((_tempPanAreaSize.y - realPanElementH) / 2) + item.vGap.top; 2714 2715 // maximum pan position 2716 bounds.max.x = (realPanElementW > _tempPanAreaSize.x) ? 2717 Math.round(_tempPanAreaSize.x - realPanElementW) : 2718 bounds.center.x; 2719 2720 bounds.max.y = (realPanElementH > _tempPanAreaSize.y) ? 2721 Math.round(_tempPanAreaSize.y - realPanElementH) + item.vGap.top : 2722 bounds.center.y; 2723 2724 // minimum pan position 2725 bounds.min.x = (realPanElementW > _tempPanAreaSize.x) ? 0 : bounds.center.x; 2726 bounds.min.y = (realPanElementH > _tempPanAreaSize.y) ? item.vGap.top : bounds.center.y; 2727 }, 2728 _calculateItemSize = function(item, viewportSize, zoomLevel) { 2729 2730 if (item.src && !item.loadError) { 2731 var isInitial = !zoomLevel; 2732 2733 if(isInitial) { 2734 if(!item.vGap) { 2735 item.vGap = {top:0,bottom:0}; 2736 } 2737 // allows overriding vertical margin for individual items 2738 _shout('parseVerticalMargin', item); 2739 } 2740 2741 2742 _tempPanAreaSize.x = viewportSize.x; 2743 _tempPanAreaSize.y = viewportSize.y - item.vGap.top - item.vGap.bottom; 2744 2745 if (isInitial) { 2746 var hRatio = _tempPanAreaSize.x / item.w; 2747 var vRatio = _tempPanAreaSize.y / item.h; 2748 2749 item.fitRatio = hRatio < vRatio ? hRatio : vRatio; 2750 //item.fillRatio = hRatio > vRatio ? hRatio : vRatio; 2751 2752 var scaleMode = _options.scaleMode; 2753 2754 if (scaleMode === 'orig') { 2755 zoomLevel = 1; 2756 } else if (scaleMode === 'fit') { 2757 zoomLevel = item.fitRatio; 2758 } 2759 2760 if (zoomLevel > 1) { 2761 zoomLevel = 1; 2762 } 2763 2764 item.initialZoomLevel = zoomLevel; 2765 2766 if(!item.bounds) { 2767 // reuse bounds object 2768 item.bounds = _getZeroBounds(); 2769 } 2770 } 2771 2772 if(!zoomLevel) { 2773 return; 2774 } 2775 2776 _calculateSingleItemPanBounds(item, item.w * zoomLevel, item.h * zoomLevel); 2777 2778 if (isInitial && zoomLevel === item.initialZoomLevel) { 2779 item.initialPosition = item.bounds.center; 2780 } 2781 2782 return item.bounds; 2783 } else { 2784 item.w = item.h = 0; 2785 item.initialZoomLevel = item.fitRatio = 1; 2786 item.bounds = _getZeroBounds(); 2787 item.initialPosition = item.bounds.center; 2788 2789 // if it's not image, we return zero bounds (content is not zoomable) 2790 return item.bounds; 2791 } 2792 2793 }, 2794 2795 2796 2797 2798 _appendImage = function(index, item, baseDiv, img, preventAnimation, keepPlaceholder) { 2799 2800 2801 if(item.loadError) { 2802 return; 2803 } 2804 2805 if(img) { 2806 2807 item.imageAppended = true; 2808 _setImageSize(item, img, (item === self.currItem && _renderMaxResolution) ); 2809 2810 baseDiv.appendChild(img); 2811 2812 if(keepPlaceholder) { 2813 setTimeout(function() { 2814 if(item && item.loaded && item.placeholder) { 2815 item.placeholder.style.display = 'none'; 2816 item.placeholder = null; 2817 } 2818 }, 500); 2819 } 2820 } 2821 }, 2822 2823 2824 2825 _preloadImage = function(item) { 2826 item.loading = true; 2827 item.loaded = false;
2828 var img = item.img = framework.createEl('pswp__img', 'img'); 2829 var onComplete = function() { 2830 item.loading = false; 2831 item.loaded = true; 2832 2833 if(item.loadComplete) { 2834 item.loadComplete(item); 2835 } else { 2836 item.img = null; // no need to store image object 2837 } 2838 img.onload = img.onerror = null; 2839 img = null; 2840 }; 2841 img.onload = onComplete; 2842 img.onerror = function() { 2843 item.loadError = true; 2844 onComplete(); 2845 }; 2846 2847 img.src = item.src;// + '?a=' + Math.random(); 2848 2849 return img; 2850 }, 2851 _checkForError = function(item, cleanUp) { 2852 if(item.src && item.loadError && item.container) { 2853 2854 if(cleanUp) { 2855 item.container.innerHTML = ''; 2856 } 2857 2858 item.container.innerHTML = _options.errorMsg.replace('%url%', item.src ); 2859 return true; 2860 2861 } 2862 }, 2863 _setImageSize = function(item, img, maxRes) { 2864 if(!item.src) { 2865 return; 2866 } 2867 2868 if(!img) { 2869 img = item.container.lastChild; 2870 } 2871 2872 var w = maxRes ? item.w : Math.round(item.w * item.fitRatio), 2873 h = maxRes ? item.h : Math.round(item.h * item.fitRatio); 2874 2875 if(item.placeholder && !item.loaded) { 2876 item.placeholder.style.width = w + 'px'; 2877 item.placeholder.style.height = h + 'px'; 2878 } 2879 2880 img.style.width = w + 'px'; 2881 img.style.height = h + 'px'; 2882 }, 2883 _appendImagesPool = function() { 2884 2885 if(_imagesToAppendPool.length) { 2886 var poolItem; 2887 2888 for(var i = 0; i < _imagesToAppendPool.length; i++) { 2889 poolItem = _imagesToAppendPool[i]; 2890 if( poolItem.holder.index === poolItem.index ) { 2891 _appendImage(poolItem.index, poolItem.item, poolItem.baseDiv, poolItem.img, false, poolItem.clearPlaceholder); 2892 } 2893 } 2894 _imagesToAppendPool = []; 2895 } 2896 }; 2897 2898 2899 2900_registerModule('Controller', { 2901 2902 publicMethods: { 2903 2904 lazyLoadItem: function(index) { 2905 index = _getLoopedId(index); 2906 var item = _getItemAt(index); 2907 2908 if(!item || ((item.loaded || item.loading) && !_itemsNeedUpdate)) { 2909 return; 2910 } 2911 2912 _shout('gettingData', index, item); 2913 2914 if (!item.src) { 2915 return; 2916 } 2917 2918 _preloadImage(item); 2919 }, 2920 initController: function() { 2921 framework.extend(_options, _controllerDefaultOptions, true); 2922 self.items = _items = items; 2923 _getItemAt = self.getItemAt; 2924 _getNumItems = _options.getNumItemsFn; //self.getNumItems; 2925 2926 2927 2928 _initialIsLoop = _options.loop; 2929 if(_getNumItems() < 3) { 2930 _options.loop = false; // disable loop if less then 3 items 2931 } 2932 2933 _listen('beforeChange', function(diff) { 2934 2935 var p = _options.preload, 2936 isNext = diff === null ? true : (diff >= 0), 2937 preloadBefore = Math.min(p[0], _getNumItems() ), 2938 preloadAfter = Math.min(p[1], _getNumItems() ), 2939 i; 2940 2941 2942 for(i = 1; i <= (isNext ? preloadAfter : preloadBefore); i++) { 2943 self.lazyLoadItem(_currentItemIndex+i); 2944 } 2945 for(i = 1; i <= (isNext ? preloadBefore : preloadAfter); i++) { 2946 self.lazyLoadItem(_currentItemIndex-i); 2947 } 2948 }); 2949 2950 _listen('initialLayout', function() { 2951 self.currItem.initialLayout = _options.getThumbBoundsFn && _options.getThumbBoundsFn(_currentItemIndex); 2952 }); 2953 2954 _listen('mainScrollAnimComplete', _appendImagesPool); 2955 _listen('initialZoomInEnd', _appendImagesPool); 2956 2957 2958 2959 _listen('destroy', function() { 2960 var item; 2961 for(var i = 0; i < _items.length; i++) { 2962 item = _items[i]; 2963 // remove reference to DOM elements, for GC 2964 if(item.container) { 2965 item.container = null; 2966 } 2967 if(item.placeholder) { 2968 item.placeholder = null; 2969 } 2970 if(item.img) { 2971 item.img = null; 2972 } 2973 if(item.preloader) { 2974 item.preloader = null; 2975 } 2976 if(item.loadError) { 2977 item.loaded = item.loadError = false; 2978 } 2979 } 2980 _imagesToAppendPool = null; 2981 }); 2982 }, 2983 2984 2985 getItemAt: function(index) { 2986 if (index >= 0) { 2987 return _items[index] !== undefined ? _items[index] : false; 2988 } 2989 return false; 2990 }, 2991 2992 allowProgressiveImg: function() { 2993 // 1. Progressive image loading isn't working on webkit/blink 2994 // when hw-acceleration (e.g. translateZ) is applied to IMG element. 2995 // That's why in PhotoSwipe parent element gets zoom transform, not image itself. 2996 // 2997 // 2. Progressive image loading sometimes blinks in webkit/blink when applying animation to parent element. 2998 // That's why it's disabled on touch devices (mainly because of swipe transition) 2999 // 3000 // 3. Progressive image loading sometimes doesn't work in IE (up to 11). 3001 3002 // Don't allow progressive loading on non-large touch devices 3003 return _options.forceProgressiveLoading || !_likelyTouchDevice || _options.mouseUsed || screen.width > 1200; 3004 // 1200 - to eliminate touch devices with large screen (like Chromebook Pixel) 3005 }, 3006 3007 setContent: function(holder, index) { 3008 3009 if(_options.loop) { 3010 index = _getLoopedId(index); 3011 } 3012 3013 var prevItem = self.getItemAt(holder.index); 3014 if(prevItem) { 3015 prevItem.container = null; 3016 } 3017 3018 var item = self.getItemAt(index), 3019 img; 3020 3021 if(!item) { 3022 holder.el.innerHTML = ''; 3023 return; 3024 } 3025 3026 // allow to override data 3027 _shout('gettingData', index, item); 3028 3029 holder.index = index; 3030 holder.item = item; 3031 3032 // base container DIV is created only once for each of 3 holders 3033 var baseDiv = item.container = framework.createEl('pswp__zoom-wrap'); 3034 3035 3036 3037 if(!item.src && item.html) { 3038 if(item.html.tagName) { 3039 baseDiv.appendChild(item.html); 3040 } else { 3041 baseDiv.innerHTML = item.html; 3042 } 3043 } 3044 3045 _checkForError(item); 3046 3047 _calculateItemSize(item, _viewportSize); 3048 3049 if(item.src && !item.loadError && !item.loaded) { 3050 3051 item.loadComplete = function(item) { 3052 3053 // gallery closed before image finished loading 3054 if(!_isOpen) { 3055 return; 3056 } 3057 3058 // check if holder hasn't changed while image was loading 3059 if(holder && holder.index === index ) { 3060 if( _checkForError(item, true) ) { 3061 item.loadComplete = item.img = null; 3062 _calculateItemSize(item, _viewportSize); 3063 _applyZoomPanToItem(item); 3064 3065 if(holder.index === _currentItemIndex) { 3066 // recalculate dimensions 3067 self.updateCurrZoomItem(); 3068 } 3069 return; 3070 } 3071 if( !item.imageAppended ) { 3072 if(_features.transform && (_mainScrollAnimating || _initialZoomRunning) ) {
3073 _imagesToAppendPool.push({ 3074 item:item, 3075 baseDiv:baseDiv, 3076 img:item.img, 3077 index:index, 3078 holder:holder, 3079 clearPlaceholder:true 3080 }); 3081 } else { 3082 _appendImage(index, item, baseDiv, item.img, _mainScrollAnimating || _initialZoomRunning, true); 3083 } 3084 } else { 3085 // remove preloader & mini-img 3086 if(!_initialZoomRunning && item.placeholder) { 3087 item.placeholder.style.display = 'none'; 3088 item.placeholder = null; 3089 } 3090 } 3091 } 3092 3093 item.loadComplete = null; 3094 item.img = null; // no need to store image element after it's added 3095 3096 _shout('imageLoadComplete', index, item); 3097 }; 3098 3099 if(framework.features.transform) { 3100 3101 var placeholderClassName = 'pswp__img pswp__img--placeholder'; 3102 placeholderClassName += (item.msrc ? '' : ' pswp__img--placeholder--blank'); 3103 3104 var placeholder = framework.createEl(placeholderClassName, item.msrc ? 'img' : ''); 3105 if(item.msrc) { 3106 placeholder.src = item.msrc; 3107 } 3108 3109 _setImageSize(item, placeholder); 3110 3111 baseDiv.appendChild(placeholder); 3112 item.placeholder = placeholder; 3113 3114 } 3115 3116 3117 3118 3119 if(!item.loading) { 3120 _preloadImage(item); 3121 } 3122 3123 3124 if( self.allowProgressiveImg() ) { 3125 // just append image 3126 if(!_initialContentSet && _features.transform) { 3127 _imagesToAppendPool.push({ 3128 item:item, 3129 baseDiv:baseDiv, 3130 img:item.img, 3131 index:index, 3132 holder:holder 3133 }); 3134 } else { 3135 _appendImage(index, item, baseDiv, item.img, true, true); 3136 } 3137 } 3138 3139 } else if(item.src && !item.loadError) { 3140 // image object is created every time, due to bugs of image loading & delay when switching images 3141 img = framework.createEl('pswp__img', 'img'); 3142 img.style.opacity = 1; 3143 img.src = item.src; 3144 _setImageSize(item, img); 3145 _appendImage(index, item, baseDiv, img, true); 3146 } 3147 3148 3149 if(!_initialContentSet && index === _currentItemIndex) { 3150 _currZoomElementStyle = baseDiv.style; 3151 _showOrHide(item, (img ||item.img) ); 3152 } else { 3153 _applyZoomPanToItem(item); 3154 } 3155 3156 holder.el.innerHTML = ''; 3157 holder.el.appendChild(baseDiv); 3158 }, 3159 3160 cleanSlide: function( item ) { 3161 if(item.img ) { 3162 item.img.onload = item.img.onerror = null; 3163 } 3164 item.loaded = item.loading = item.img = item.imageAppended = false; 3165 } 3166 3167 } 3168}); 3169 3170/*>>items-controller*/ 3171 3172/*>>tap*/ 3173/** 3174 * tap.js: 3175 * 3176 * Displatches tap and double-tap events. 3177 * 3178 */ 3179 3180var tapTimer, 3181 tapReleasePoint = {}, 3182 _dispatchTapEvent = function(origEvent, releasePoint, pointerType) { 3183 var e = document.createEvent( 'CustomEvent' ), 3184 eDetail = { 3185 origEvent:origEvent, 3186 target:origEvent.target, 3187 releasePoint: releasePoint, 3188 pointerType:pointerType || 'touch' 3189 }; 3190 3191 e.initCustomEvent( 'pswpTap', true, true, eDetail ); 3192 origEvent.target.dispatchEvent(e); 3193 }; 3194 3195_registerModule('Tap', { 3196 publicMethods: { 3197 initTap: function() { 3198 _listen('firstTouchStart', self.onTapStart); 3199 _listen('touchRelease', self.onTapRelease); 3200 _listen('destroy', function() { 3201 tapReleasePoint = {}; 3202 tapTimer = null; 3203 }); 3204 }, 3205 onTapStart: function(touchList) { 3206 if(touchList.length > 1) { 3207 clearTimeout(tapTimer); 3208 tapTimer = null; 3209 } 3210 }, 3211 onTapRelease: function(e, releasePoint) { 3212 if(!releasePoint) { 3213 return; 3214 } 3215 3216 if(!_moved && !_isMultitouch && !_numAnimations) { 3217 var p0 = releasePoint; 3218 if(tapTimer) { 3219 clearTimeout(tapTimer); 3220 tapTimer = null; 3221 3222 // Check if taped on the same place 3223 if ( _isNearbyPoints(p0, tapReleasePoint) ) { 3224 _shout('doubleTap', p0); 3225 return; 3226 } 3227 } 3228 3229 if(releasePoint.type === 'mouse') { 3230 _dispatchTapEvent(e, releasePoint, 'mouse'); 3231 return; 3232 } 3233 3234 var clickedTagName = e.target.tagName.toUpperCase(); 3235 // avoid double tap delay on buttons and elements that have class pswp__single-tap 3236 if(clickedTagName === 'BUTTON' || framework.hasClass(e.target, 'pswp__single-tap') ) { 3237 _dispatchTapEvent(e, releasePoint); 3238 return; 3239 } 3240 3241 _equalizePoints(tapReleasePoint, p0); 3242 3243 tapTimer = setTimeout(function() { 3244 _dispatchTapEvent(e, releasePoint); 3245 tapTimer = null; 3246 }, 300); 3247 } 3248 } 3249 } 3250}); 3251 3252/*>>tap*/ 3253 3254/*>>desktop-zoom*/ 3255/** 3256 * 3257 * desktop-zoom.js: 3258 * 3259 * - Binds mousewheel event for paning zoomed image. 3260 * - Manages "dragging", "zoomed-in", "zoom-out" classes. 3261 * (which are used for cursors and zoom icon) 3262 * - Adds toggleDesktopZoom function. 3263 * 3264 */ 3265 3266var _wheelDelta; 3267 3268_registerModule('DesktopZoom', { 3269 3270 publicMethods: { 3271 3272 initDesktopZoom: function() { 3273 3274 if(_oldIE) { 3275 // no zoom for old IE (<=8) 3276 return; 3277 } 3278 3279 if(_likelyTouchDevice) { 3280 // if detected hardware touch support, we wait until mouse is used, 3281 // and only then apply desktop-zoom features 3282 _listen('mouseUsed', function() { 3283 self.setupDesktopZoom(); 3284 }); 3285 } else { 3286 self.setupDesktopZoom(true); 3287 } 3288 3289 }, 3290 3291 setupDesktopZoom: function(onInit) { 3292 3293 _wheelDelta = {}; 3294 3295 var events = 'wheel mousewheel DOMMouseScroll'; 3296 3297 _listen('bindEvents', function() { 3298 framework.bind(template, events, self.handleMouseWheel); 3299 }); 3300 3301 _listen('unbindEvents', function() { 3302 if(_wheelDelta) { 3303 framework.unbind(template, events, self.handleMouseWheel); 3304 } 3305 }); 3306 3307 self.mouseZoomedIn = false;
3308 3309 var hasDraggingClass, 3310 updateZoomable = function() { 3311 if(self.mouseZoomedIn) { 3312 framework.removeClass(template, 'pswp--zoomed-in'); 3313 self.mouseZoomedIn = false; 3314 } 3315 if(_currZoomLevel < 1) { 3316 framework.addClass(template, 'pswp--zoom-allowed'); 3317 } else { 3318 framework.removeClass(template, 'pswp--zoom-allowed'); 3319 } 3320 removeDraggingClass(); 3321 }, 3322 removeDraggingClass = function() { 3323 if(hasDraggingClass) { 3324 framework.removeClass(template, 'pswp--dragging'); 3325 hasDraggingClass = false; 3326 } 3327 }; 3328 3329 _listen('resize' , updateZoomable); 3330 _listen('afterChange' , updateZoomable); 3331 _listen('pointerDown', function() { 3332 if(self.mouseZoomedIn) { 3333 hasDraggingClass = true; 3334 framework.addClass(template, 'pswp--dragging'); 3335 } 3336 }); 3337 _listen('pointerUp', removeDraggingClass); 3338 3339 if(!onInit) { 3340 updateZoomable(); 3341 } 3342 3343 }, 3344 3345 handleMouseWheel: function(e) { 3346 3347 if(_currZoomLevel <= self.currItem.fitRatio) { 3348 if( _options.modal ) { 3349 3350 if (!_options.closeOnScroll || _numAnimations || _isDragging) { 3351 e.preventDefault(); 3352 } else if(_transformKey && Math.abs(e.deltaY) > 2) { 3353 // close PhotoSwipe 3354 // if browser supports transforms & scroll changed enough 3355 _closedByScroll = true; 3356 self.close(); 3357 } 3358 3359 } 3360 return true; 3361 } 3362 3363 // allow just one event to fire 3364 e.stopPropagation(); 3365 3366 // https://developer.mozilla.org/en-US/docs/Web/Events/wheel 3367 _wheelDelta.x = 0; 3368 3369 if('deltaX' in e) { 3370 if(e.deltaMode === 1 /* DOM_DELTA_LINE */) { 3371 // 18 - average line height 3372 _wheelDelta.x = e.deltaX * 18; 3373 _wheelDelta.y = e.deltaY * 18; 3374 } else { 3375 _wheelDelta.x = e.deltaX; 3376 _wheelDelta.y = e.deltaY; 3377 } 3378 } else if('wheelDelta' in e) { 3379 if(e.wheelDeltaX) { 3380 _wheelDelta.x = -0.16 * e.wheelDeltaX; 3381 } 3382 if(e.wheelDeltaY) { 3383 _wheelDelta.y = -0.16 * e.wheelDeltaY; 3384 } else { 3385 _wheelDelta.y = -0.16 * e.wheelDelta; 3386 } 3387 } else if('detail' in e) { 3388 _wheelDelta.y = e.detail; 3389 } else { 3390 return; 3391 } 3392 3393 _calculatePanBounds(_currZoomLevel, true); 3394 3395 var newPanX = _panOffset.x - _wheelDelta.x, 3396 newPanY = _panOffset.y - _wheelDelta.y; 3397 3398 // only prevent scrolling in nonmodal mode when not at edges 3399 if (_options.modal || 3400 ( 3401 newPanX <= _currPanBounds.min.x && newPanX >= _currPanBounds.max.x && 3402 newPanY <= _currPanBounds.min.y && newPanY >= _currPanBounds.max.y 3403 ) ) { 3404 e.preventDefault(); 3405 } 3406 3407 // TODO: use rAF instead of mousewheel? 3408 self.panTo(newPanX, newPanY); 3409 }, 3410 3411 toggleDesktopZoom: function(centerPoint) { 3412 centerPoint = centerPoint || {x:_viewportSize.x/2 + _offset.x, y:_viewportSize.y/2 + _offset.y }; 3413 3414 var doubleTapZoomLevel = _options.getDoubleTapZoom(true, self.currItem); 3415 var zoomOut = _currZoomLevel === doubleTapZoomLevel; 3416 3417 self.mouseZoomedIn = !zoomOut; 3418 3419 self.zoomTo(zoomOut ? self.currItem.initialZoomLevel : doubleTapZoomLevel, centerPoint, 333); 3420 framework[ (!zoomOut ? 'add' : 'remove') + 'Class'](template, 'pswp--zoomed-in'); 3421 } 3422 3423 } 3424}); 3425 3426 3427/*>>desktop-zoom*/ 3428 3429/*>>history*/ 3430/** 3431 * 3432 * history.js: 3433 * 3434 * - Back button to close gallery. 3435 * 3436 * - Unique URL for each slide: example.com/&pid=1&gid=3 3437 * (where PID is picture index, and GID and gallery index) 3438 * 3439 * - Switch URL when slides change. 3440 * 3441 */ 3442 3443 3444var _historyDefaultOptions = { 3445 history: true, 3446 galleryUID: 1 3447}; 3448 3449var _historyUpdateTimeout, 3450 _hashChangeTimeout, 3451 _hashAnimCheckTimeout, 3452 _hashChangedByScript, 3453 _hashChangedByHistory, 3454 _hashReseted, 3455 _initialHash, 3456 _historyChanged, 3457 _closedFromURL, 3458 _urlChangedOnce, 3459 _windowLoc, 3460 3461 _supportsPushState, 3462 3463 _getHash = function() { 3464 return _windowLoc.hash.substring(1); 3465 }, 3466 _cleanHistoryTimeouts = function() { 3467 3468 if(_historyUpdateTimeout) { 3469 clearTimeout(_historyUpdateTimeout); 3470 } 3471 3472 if(_hashAnimCheckTimeout) { 3473 clearTimeout(_hashAnimCheckTimeout); 3474 } 3475 }, 3476 3477 // pid - Picture index 3478 // gid - Gallery index 3479 _parseItemIndexFromURL = function() { 3480 var hash = _getHash(), 3481 params = {}; 3482 3483 if(hash.length < 5) { // pid=1 3484 return params; 3485 } 3486 3487 var i, vars = hash.split('&'); 3488 for (i = 0; i < vars.length; i++) { 3489 if(!vars[i]) { 3490 continue; 3491 } 3492 var pair = vars[i].split('='); 3493 if(pair.length < 2) { 3494 continue; 3495 } 3496 params[pair[0]] = pair[1]; 3497 } 3498 if(_options.galleryPIDs) { 3499 // detect custom pid in hash and search for it among the items collection 3500 var searchfor = params.pid; 3501 params.pid = 0; // if custom pid cannot be found, fallback to the first item 3502 for(i = 0; i < _items.length; i++) { 3503 if(_items[i].pid === searchfor) { 3504 params.pid = i; 3505 break; 3506 } 3507 } 3508 } else { 3509 params.pid = parseInt(params.pid,10)-1; 3510 } 3511 if( params.pid < 0 ) { 3512 params.pid = 0; 3513 } 3514 return params; 3515 }, 3516 _updateHash = function() { 3517 3518 if(_hashAnimCheckTimeout) { 3519 clearTimeout(_hashAnimCheckTimeout); 3520 } 3521 3522 3523 if(_numAnimations || _isDragging) { 3524 // changing browser URL forces layout/paint in some browsers, which causes noticable lag during animation 3525 // that's why we update hash only when no animations running 3526 _hashAnimCheckTimeout = setTimeout(_updateHash, 500); 3527 return; 3528 } 3529 3530 if(_hashChangedByScript) { 3531 clearTimeout(_hashChangeTimeout); 3532 } else { 3533 _hashChangedByScript = true; 3534 } 3535 3536 3537 var pid = (_currentItemIndex + 1); 3538 var item = _getItemAt( _currentItemIndex ); 3539 if(item.hasOwnProperty('pid')) { 3540 // carry forward any custom pid assigned to the item 3541 pid = item.pid; 3542 } 3543 var newHash = _initialHash + '&' + 'gid=' + _options.galleryUID + '&' + 'pid=' + pid; 3544 3545 if(!_historyChanged) { 3546 if(_windowLoc.hash.indexOf(newHash) === -1) { 3547 _urlChangedOnce = true; 3548 } 3549 // first time - add new hisory record, then just replace 3550 } 3551 3552 var newURL = _windowLoc.href.split('#')[0] + '#' + newHash; 3553 3554 if( _supportsPushState ) { 3555 3556 if('#' + newHash !== window.location.hash) { 3557 history[_historyChanged ? 'replaceState' : 'pushState']('', document.title, newURL); 3558 } 3559 3560 } else { 3561 if(_historyChanged) { 3562 _windowLoc.replace( newURL ); 3563 } else { 3564 _windowLoc.hash = newHash; 3565 } 3566 } 3567 3568 3569 3570 _historyChanged = true; 3571 _hashChangeTimeout = setTimeout(function() { 3572 _hashChangedByScript = false;
3573 }, 60); 3574 }; 3575 3576 3577 3578 3579 3580_registerModule('History', { 3581 3582 3583 3584 publicMethods: { 3585 initHistory: function() { 3586 3587 framework.extend(_options, _historyDefaultOptions, true); 3588 3589 if( !_options.history ) { 3590 return; 3591 } 3592 3593 3594 _windowLoc = window.location; 3595 _urlChangedOnce = false; 3596 _closedFromURL = false; 3597 _historyChanged = false; 3598 _initialHash = _getHash(); 3599 _supportsPushState = ('pushState' in history); 3600 3601 3602 if(_initialHash.indexOf('gid=') > -1) { 3603 _initialHash = _initialHash.split('&gid=')[0]; 3604 _initialHash = _initialHash.split('?gid=')[0]; 3605 } 3606 3607 3608 _listen('afterChange', self.updateURL); 3609 _listen('unbindEvents', function() { 3610 framework.unbind(window, 'hashchange', self.onHashChange); 3611 }); 3612 3613 3614 var returnToOriginal = function() { 3615 _hashReseted = true; 3616 if(!_closedFromURL) { 3617 3618 if(_urlChangedOnce) { 3619 history.back(); 3620 } else { 3621 3622 if(_initialHash) { 3623 _windowLoc.hash = _initialHash; 3624 } else { 3625 if (_supportsPushState) { 3626 3627 // remove hash from url without refreshing it or scrolling to top 3628 history.pushState('', document.title, _windowLoc.pathname + _windowLoc.search ); 3629 } else { 3630 _windowLoc.hash = ''; 3631 } 3632 } 3633 } 3634 3635 } 3636 3637 _cleanHistoryTimeouts(); 3638 }; 3639 3640 3641 _listen('unbindEvents', function() { 3642 if(_closedByScroll) { 3643 // if PhotoSwipe is closed by scroll, we go "back" before the closing animation starts 3644 // this is done to keep the scroll position 3645 returnToOriginal(); 3646 } 3647 }); 3648 _listen('destroy', function() { 3649 if(!_hashReseted) { 3650 returnToOriginal(); 3651 } 3652 }); 3653 _listen('firstUpdate', function() { 3654 _currentItemIndex = _parseItemIndexFromURL().pid; 3655 }); 3656 3657 3658 3659 3660 var index = _initialHash.indexOf('pid='); 3661 if(index > -1) { 3662 _initialHash = _initialHash.substring(0, index); 3663 if(_initialHash.slice(-1) === '&') { 3664 _initialHash = _initialHash.slice(0, -1); 3665 } 3666 } 3667 3668 3669 setTimeout(function() { 3670 if(_isOpen) { // hasn't destroyed yet 3671 framework.bind(window, 'hashchange', self.onHashChange); 3672 } 3673 }, 40); 3674 3675 }, 3676 onHashChange: function() { 3677 3678 if(_getHash() === _initialHash) { 3679 3680 _closedFromURL = true; 3681 self.close(); 3682 return; 3683 } 3684 if(!_hashChangedByScript) { 3685 3686 _hashChangedByHistory = true; 3687 self.goTo( _parseItemIndexFromURL().pid ); 3688 _hashChangedByHistory = false; 3689 } 3690 3691 }, 3692 updateURL: function() { 3693 3694 // Delay the update of URL, to avoid lag during transition, 3695 // and to not to trigger actions like "refresh page sound" or "blinking favicon" to often 3696 3697 _cleanHistoryTimeouts(); 3698 3699 3700 if(_hashChangedByHistory) { 3701 return; 3702 } 3703 3704 if(!_historyChanged) { 3705 _updateHash(); // first time 3706 } else { 3707 _historyUpdateTimeout = setTimeout(_updateHash, 800); 3708 } 3709 } 3710 3711 } 3712}); 3713 3714 3715/*>>history*/ 3716 framework.extend(self, publicMethods); }; 3717 return PhotoSwipe; 3718});
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.