photoswipe.js 91 KB

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