photoswipe.js 90 KB

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