Geen omschrijving

photoswipe.js 92KB

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