photoswipe.js 92 KB

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