photoswipe.esm.js 183 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081
  1. /*!
  2. * PhotoSwipe 5.4.4 - https://photoswipe.com
  3. * (c) 2024 Dmytro Semenov
  4. */
  5. /** @typedef {import('../photoswipe.js').Point} Point */
  6. /**
  7. * @template {keyof HTMLElementTagNameMap} T
  8. * @param {string} className
  9. * @param {T} tagName
  10. * @param {Node} [appendToEl]
  11. * @returns {HTMLElementTagNameMap[T]}
  12. */
  13. function createElement(className, tagName, appendToEl) {
  14. const el = document.createElement(tagName);
  15. if (className) {
  16. el.className = className;
  17. }
  18. if (appendToEl) {
  19. appendToEl.appendChild(el);
  20. }
  21. return el;
  22. }
  23. /**
  24. * @param {Point} p1
  25. * @param {Point} p2
  26. * @returns {Point}
  27. */
  28. function equalizePoints(p1, p2) {
  29. p1.x = p2.x;
  30. p1.y = p2.y;
  31. if (p2.id !== undefined) {
  32. p1.id = p2.id;
  33. }
  34. return p1;
  35. }
  36. /**
  37. * @param {Point} p
  38. */
  39. function roundPoint(p) {
  40. p.x = Math.round(p.x);
  41. p.y = Math.round(p.y);
  42. }
  43. /**
  44. * Returns distance between two points.
  45. *
  46. * @param {Point} p1
  47. * @param {Point} p2
  48. * @returns {number}
  49. */
  50. function getDistanceBetween(p1, p2) {
  51. const x = Math.abs(p1.x - p2.x);
  52. const y = Math.abs(p1.y - p2.y);
  53. return Math.sqrt(x * x + y * y);
  54. }
  55. /**
  56. * Whether X and Y positions of points are equal
  57. *
  58. * @param {Point} p1
  59. * @param {Point} p2
  60. * @returns {boolean}
  61. */
  62. function pointsEqual(p1, p2) {
  63. return p1.x === p2.x && p1.y === p2.y;
  64. }
  65. /**
  66. * The float result between the min and max values.
  67. *
  68. * @param {number} val
  69. * @param {number} min
  70. * @param {number} max
  71. * @returns {number}
  72. */
  73. function clamp(val, min, max) {
  74. return Math.min(Math.max(val, min), max);
  75. }
  76. /**
  77. * Get transform string
  78. *
  79. * @param {number} x
  80. * @param {number} [y]
  81. * @param {number} [scale]
  82. * @returns {string}
  83. */
  84. function toTransformString(x, y, scale) {
  85. let propValue = `translate3d(${x}px,${y || 0}px,0)`;
  86. if (scale !== undefined) {
  87. propValue += ` scale3d(${scale},${scale},1)`;
  88. }
  89. return propValue;
  90. }
  91. /**
  92. * Apply transform:translate(x, y) scale(scale) to element
  93. *
  94. * @param {HTMLElement} el
  95. * @param {number} x
  96. * @param {number} [y]
  97. * @param {number} [scale]
  98. */
  99. function setTransform(el, x, y, scale) {
  100. el.style.transform = toTransformString(x, y, scale);
  101. }
  102. const defaultCSSEasing = 'cubic-bezier(.4,0,.22,1)';
  103. /**
  104. * Apply CSS transition to element
  105. *
  106. * @param {HTMLElement} el
  107. * @param {string} [prop] CSS property to animate
  108. * @param {number} [duration] in ms
  109. * @param {string} [ease] CSS easing function
  110. */
  111. function setTransitionStyle(el, prop, duration, ease) {
  112. // inOut: 'cubic-bezier(.4, 0, .22, 1)', // for "toggle state" transitions
  113. // out: 'cubic-bezier(0, 0, .22, 1)', // for "show" transitions
  114. // in: 'cubic-bezier(.4, 0, 1, 1)'// for "hide" transitions
  115. el.style.transition = prop ? `${prop} ${duration}ms ${ease || defaultCSSEasing}` : 'none';
  116. }
  117. /**
  118. * Apply width and height CSS properties to element
  119. *
  120. * @param {HTMLElement} el
  121. * @param {string | number} w
  122. * @param {string | number} h
  123. */
  124. function setWidthHeight(el, w, h) {
  125. el.style.width = typeof w === 'number' ? `${w}px` : w;
  126. el.style.height = typeof h === 'number' ? `${h}px` : h;
  127. }
  128. /**
  129. * @param {HTMLElement} el
  130. */
  131. function removeTransitionStyle(el) {
  132. setTransitionStyle(el);
  133. }
  134. /**
  135. * @param {HTMLImageElement} img
  136. * @returns {Promise<HTMLImageElement | void>}
  137. */
  138. function decodeImage(img) {
  139. if ('decode' in img) {
  140. return img.decode().catch(() => {});
  141. }
  142. if (img.complete) {
  143. return Promise.resolve(img);
  144. }
  145. return new Promise((resolve, reject) => {
  146. img.onload = () => resolve(img);
  147. img.onerror = reject;
  148. });
  149. }
  150. /** @typedef {LOAD_STATE[keyof LOAD_STATE]} LoadState */
  151. /** @type {{ IDLE: 'idle'; LOADING: 'loading'; LOADED: 'loaded'; ERROR: 'error' }} */
  152. const LOAD_STATE = {
  153. IDLE: 'idle',
  154. LOADING: 'loading',
  155. LOADED: 'loaded',
  156. ERROR: 'error'
  157. };
  158. /**
  159. * Check if click or keydown event was dispatched
  160. * with a special key or via mouse wheel.
  161. *
  162. * @param {MouseEvent | KeyboardEvent} e
  163. * @returns {boolean}
  164. */
  165. function specialKeyUsed(e) {
  166. return 'button' in e && e.button === 1 || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey;
  167. }
  168. /**
  169. * Parse `gallery` or `children` options.
  170. *
  171. * @param {import('../photoswipe.js').ElementProvider} [option]
  172. * @param {string} [legacySelector]
  173. * @param {HTMLElement | Document} [parent]
  174. * @returns HTMLElement[]
  175. */
  176. function getElementsFromOption(option, legacySelector, parent = document) {
  177. /** @type {HTMLElement[]} */
  178. let elements = [];
  179. if (option instanceof Element) {
  180. elements = [option];
  181. } else if (option instanceof NodeList || Array.isArray(option)) {
  182. elements = Array.from(option);
  183. } else {
  184. const selector = typeof option === 'string' ? option : legacySelector;
  185. if (selector) {
  186. elements = Array.from(parent.querySelectorAll(selector));
  187. }
  188. }
  189. return elements;
  190. }
  191. /**
  192. * Check if browser is Safari
  193. *
  194. * @returns {boolean}
  195. */
  196. function isSafari() {
  197. return !!(navigator.vendor && navigator.vendor.match(/apple/i));
  198. }
  199. // Detect passive event listener support
  200. let supportsPassive = false;
  201. /* eslint-disable */
  202. try {
  203. /* @ts-ignore */
  204. window.addEventListener('test', null, Object.defineProperty({}, 'passive', {
  205. get: () => {
  206. supportsPassive = true;
  207. }
  208. }));
  209. } catch (e) {}
  210. /* eslint-enable */
  211. /**
  212. * @typedef {Object} PoolItem
  213. * @prop {HTMLElement | Window | Document | undefined | null} target
  214. * @prop {string} type
  215. * @prop {EventListenerOrEventListenerObject} listener
  216. * @prop {boolean} [passive]
  217. */
  218. class DOMEvents {
  219. constructor() {
  220. /**
  221. * @type {PoolItem[]}
  222. * @private
  223. */
  224. this._pool = [];
  225. }
  226. /**
  227. * Adds event listeners
  228. *
  229. * @param {PoolItem['target']} target
  230. * @param {PoolItem['type']} type Can be multiple, separated by space.
  231. * @param {PoolItem['listener']} listener
  232. * @param {PoolItem['passive']} [passive]
  233. */
  234. add(target, type, listener, passive) {
  235. this._toggleListener(target, type, listener, passive);
  236. }
  237. /**
  238. * Removes event listeners
  239. *
  240. * @param {PoolItem['target']} target
  241. * @param {PoolItem['type']} type
  242. * @param {PoolItem['listener']} listener
  243. * @param {PoolItem['passive']} [passive]
  244. */
  245. remove(target, type, listener, passive) {
  246. this._toggleListener(target, type, listener, passive, true);
  247. }
  248. /**
  249. * Removes all bound events
  250. */
  251. removeAll() {
  252. this._pool.forEach(poolItem => {
  253. this._toggleListener(poolItem.target, poolItem.type, poolItem.listener, poolItem.passive, true, true);
  254. });
  255. this._pool = [];
  256. }
  257. /**
  258. * Adds or removes event
  259. *
  260. * @private
  261. * @param {PoolItem['target']} target
  262. * @param {PoolItem['type']} type
  263. * @param {PoolItem['listener']} listener
  264. * @param {PoolItem['passive']} [passive]
  265. * @param {boolean} [unbind] Whether the event should be added or removed
  266. * @param {boolean} [skipPool] Whether events pool should be skipped
  267. */
  268. _toggleListener(target, type, listener, passive, unbind, skipPool) {
  269. if (!target) {
  270. return;
  271. }
  272. const methodName = unbind ? 'removeEventListener' : 'addEventListener';
  273. const types = type.split(' ');
  274. types.forEach(eType => {
  275. if (eType) {
  276. // Events pool is used to easily unbind all events when PhotoSwipe is closed,
  277. // so developer doesn't need to do this manually
  278. if (!skipPool) {
  279. if (unbind) {
  280. // Remove from the events pool
  281. this._pool = this._pool.filter(poolItem => {
  282. return poolItem.type !== eType || poolItem.listener !== listener || poolItem.target !== target;
  283. });
  284. } else {
  285. // Add to the events pool
  286. this._pool.push({
  287. target,
  288. type: eType,
  289. listener,
  290. passive
  291. });
  292. }
  293. } // most PhotoSwipe events call preventDefault,
  294. // and we do not need browser to scroll the page
  295. const eventOptions = supportsPassive ? {
  296. passive: passive || false
  297. } : false;
  298. target[methodName](eType, listener, eventOptions);
  299. }
  300. });
  301. }
  302. }
  303. /** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
  304. /** @typedef {import('../core/base.js').default} PhotoSwipeBase */
  305. /** @typedef {import('../photoswipe.js').Point} Point */
  306. /** @typedef {import('../slide/slide.js').SlideData} SlideData */
  307. /**
  308. * @param {PhotoSwipeOptions} options
  309. * @param {PhotoSwipeBase} pswp
  310. * @returns {Point}
  311. */
  312. function getViewportSize(options, pswp) {
  313. if (options.getViewportSizeFn) {
  314. const newViewportSize = options.getViewportSizeFn(options, pswp);
  315. if (newViewportSize) {
  316. return newViewportSize;
  317. }
  318. }
  319. return {
  320. x: document.documentElement.clientWidth,
  321. // TODO: height on mobile is very incosistent due to toolbar
  322. // find a way to improve this
  323. //
  324. // document.documentElement.clientHeight - doesn't seem to work well
  325. y: window.innerHeight
  326. };
  327. }
  328. /**
  329. * Parses padding option.
  330. * Supported formats:
  331. *
  332. * // Object
  333. * padding: {
  334. * top: 0,
  335. * bottom: 0,
  336. * left: 0,
  337. * right: 0
  338. * }
  339. *
  340. * // A function that returns the object
  341. * paddingFn: (viewportSize, itemData, index) => {
  342. * return {
  343. * top: 0,
  344. * bottom: 0,
  345. * left: 0,
  346. * right: 0
  347. * };
  348. * }
  349. *
  350. * // Legacy variant
  351. * paddingLeft: 0,
  352. * paddingRight: 0,
  353. * paddingTop: 0,
  354. * paddingBottom: 0,
  355. *
  356. * @param {'left' | 'top' | 'bottom' | 'right'} prop
  357. * @param {PhotoSwipeOptions} options PhotoSwipe options
  358. * @param {Point} viewportSize PhotoSwipe viewport size, for example: { x:800, y:600 }
  359. * @param {SlideData} itemData Data about the slide
  360. * @param {number} index Slide index
  361. * @returns {number}
  362. */
  363. function parsePaddingOption(prop, options, viewportSize, itemData, index) {
  364. let paddingValue = 0;
  365. if (options.paddingFn) {
  366. paddingValue = options.paddingFn(viewportSize, itemData, index)[prop];
  367. } else if (options.padding) {
  368. paddingValue = options.padding[prop];
  369. } else {
  370. const legacyPropName = 'padding' + prop[0].toUpperCase() + prop.slice(1); // @ts-expect-error
  371. if (options[legacyPropName]) {
  372. // @ts-expect-error
  373. paddingValue = options[legacyPropName];
  374. }
  375. }
  376. return Number(paddingValue) || 0;
  377. }
  378. /**
  379. * @param {PhotoSwipeOptions} options
  380. * @param {Point} viewportSize
  381. * @param {SlideData} itemData
  382. * @param {number} index
  383. * @returns {Point}
  384. */
  385. function getPanAreaSize(options, viewportSize, itemData, index) {
  386. return {
  387. x: viewportSize.x - parsePaddingOption('left', options, viewportSize, itemData, index) - parsePaddingOption('right', options, viewportSize, itemData, index),
  388. y: viewportSize.y - parsePaddingOption('top', options, viewportSize, itemData, index) - parsePaddingOption('bottom', options, viewportSize, itemData, index)
  389. };
  390. }
  391. /** @typedef {import('./slide.js').default} Slide */
  392. /** @typedef {Record<Axis, number>} Point */
  393. /** @typedef {'x' | 'y'} Axis */
  394. /**
  395. * Calculates minimum, maximum and initial (center) bounds of a slide
  396. */
  397. class PanBounds {
  398. /**
  399. * @param {Slide} slide
  400. */
  401. constructor(slide) {
  402. this.slide = slide;
  403. this.currZoomLevel = 1;
  404. this.center =
  405. /** @type {Point} */
  406. {
  407. x: 0,
  408. y: 0
  409. };
  410. this.max =
  411. /** @type {Point} */
  412. {
  413. x: 0,
  414. y: 0
  415. };
  416. this.min =
  417. /** @type {Point} */
  418. {
  419. x: 0,
  420. y: 0
  421. };
  422. }
  423. /**
  424. * _getItemBounds
  425. *
  426. * @param {number} currZoomLevel
  427. */
  428. update(currZoomLevel) {
  429. this.currZoomLevel = currZoomLevel;
  430. if (!this.slide.width) {
  431. this.reset();
  432. } else {
  433. this._updateAxis('x');
  434. this._updateAxis('y');
  435. this.slide.pswp.dispatch('calcBounds', {
  436. slide: this.slide
  437. });
  438. }
  439. }
  440. /**
  441. * _calculateItemBoundsForAxis
  442. *
  443. * @param {Axis} axis
  444. */
  445. _updateAxis(axis) {
  446. const {
  447. pswp
  448. } = this.slide;
  449. const elSize = this.slide[axis === 'x' ? 'width' : 'height'] * this.currZoomLevel;
  450. const paddingProp = axis === 'x' ? 'left' : 'top';
  451. const padding = parsePaddingOption(paddingProp, pswp.options, pswp.viewportSize, this.slide.data, this.slide.index);
  452. const panAreaSize = this.slide.panAreaSize[axis]; // Default position of element.
  453. // By default, it is center of viewport:
  454. this.center[axis] = Math.round((panAreaSize - elSize) / 2) + padding; // maximum pan position
  455. this.max[axis] = elSize > panAreaSize ? Math.round(panAreaSize - elSize) + padding : this.center[axis]; // minimum pan position
  456. this.min[axis] = elSize > panAreaSize ? padding : this.center[axis];
  457. } // _getZeroBounds
  458. reset() {
  459. this.center.x = 0;
  460. this.center.y = 0;
  461. this.max.x = 0;
  462. this.max.y = 0;
  463. this.min.x = 0;
  464. this.min.y = 0;
  465. }
  466. /**
  467. * Correct pan position if it's beyond the bounds
  468. *
  469. * @param {Axis} axis x or y
  470. * @param {number} panOffset
  471. * @returns {number}
  472. */
  473. correctPan(axis, panOffset) {
  474. // checkPanBounds
  475. return clamp(panOffset, this.max[axis], this.min[axis]);
  476. }
  477. }
  478. const MAX_IMAGE_WIDTH = 4000;
  479. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  480. /** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
  481. /** @typedef {import('../photoswipe.js').Point} Point */
  482. /** @typedef {import('../slide/slide.js').SlideData} SlideData */
  483. /** @typedef {'fit' | 'fill' | number | ((zoomLevelObject: ZoomLevel) => number)} ZoomLevelOption */
  484. /**
  485. * Calculates zoom levels for specific slide.
  486. * Depends on viewport size and image size.
  487. */
  488. class ZoomLevel {
  489. /**
  490. * @param {PhotoSwipeOptions} options PhotoSwipe options
  491. * @param {SlideData} itemData Slide data
  492. * @param {number} index Slide index
  493. * @param {PhotoSwipe} [pswp] PhotoSwipe instance, can be undefined if not initialized yet
  494. */
  495. constructor(options, itemData, index, pswp) {
  496. this.pswp = pswp;
  497. this.options = options;
  498. this.itemData = itemData;
  499. this.index = index;
  500. /** @type { Point | null } */
  501. this.panAreaSize = null;
  502. /** @type { Point | null } */
  503. this.elementSize = null;
  504. this.fit = 1;
  505. this.fill = 1;
  506. this.vFill = 1;
  507. this.initial = 1;
  508. this.secondary = 1;
  509. this.max = 1;
  510. this.min = 1;
  511. }
  512. /**
  513. * Calculate initial, secondary and maximum zoom level for the specified slide.
  514. *
  515. * It should be called when either image or viewport size changes.
  516. *
  517. * @param {number} maxWidth
  518. * @param {number} maxHeight
  519. * @param {Point} panAreaSize
  520. */
  521. update(maxWidth, maxHeight, panAreaSize) {
  522. /** @type {Point} */
  523. const elementSize = {
  524. x: maxWidth,
  525. y: maxHeight
  526. };
  527. this.elementSize = elementSize;
  528. this.panAreaSize = panAreaSize;
  529. const hRatio = panAreaSize.x / elementSize.x;
  530. const vRatio = panAreaSize.y / elementSize.y;
  531. this.fit = Math.min(1, hRatio < vRatio ? hRatio : vRatio);
  532. this.fill = Math.min(1, hRatio > vRatio ? hRatio : vRatio); // zoom.vFill defines zoom level of the image
  533. // when it has 100% of viewport vertical space (height)
  534. this.vFill = Math.min(1, vRatio);
  535. this.initial = this._getInitial();
  536. this.secondary = this._getSecondary();
  537. this.max = Math.max(this.initial, this.secondary, this._getMax());
  538. this.min = Math.min(this.fit, this.initial, this.secondary);
  539. if (this.pswp) {
  540. this.pswp.dispatch('zoomLevelsUpdate', {
  541. zoomLevels: this,
  542. slideData: this.itemData
  543. });
  544. }
  545. }
  546. /**
  547. * Parses user-defined zoom option.
  548. *
  549. * @private
  550. * @param {'initial' | 'secondary' | 'max'} optionPrefix Zoom level option prefix (initial, secondary, max)
  551. * @returns { number | undefined }
  552. */
  553. _parseZoomLevelOption(optionPrefix) {
  554. const optionName =
  555. /** @type {'initialZoomLevel' | 'secondaryZoomLevel' | 'maxZoomLevel'} */
  556. optionPrefix + 'ZoomLevel';
  557. const optionValue = this.options[optionName];
  558. if (!optionValue) {
  559. return;
  560. }
  561. if (typeof optionValue === 'function') {
  562. return optionValue(this);
  563. }
  564. if (optionValue === 'fill') {
  565. return this.fill;
  566. }
  567. if (optionValue === 'fit') {
  568. return this.fit;
  569. }
  570. return Number(optionValue);
  571. }
  572. /**
  573. * Get zoom level to which image will be zoomed after double-tap gesture,
  574. * or when user clicks on zoom icon,
  575. * or mouse-click on image itself.
  576. * If you return 1 image will be zoomed to its original size.
  577. *
  578. * @private
  579. * @return {number}
  580. */
  581. _getSecondary() {
  582. let currZoomLevel = this._parseZoomLevelOption('secondary');
  583. if (currZoomLevel) {
  584. return currZoomLevel;
  585. } // 3x of "fit" state, but not larger than original
  586. currZoomLevel = Math.min(1, this.fit * 3);
  587. if (this.elementSize && currZoomLevel * this.elementSize.x > MAX_IMAGE_WIDTH) {
  588. currZoomLevel = MAX_IMAGE_WIDTH / this.elementSize.x;
  589. }
  590. return currZoomLevel;
  591. }
  592. /**
  593. * Get initial image zoom level.
  594. *
  595. * @private
  596. * @return {number}
  597. */
  598. _getInitial() {
  599. return this._parseZoomLevelOption('initial') || this.fit;
  600. }
  601. /**
  602. * Maximum zoom level when user zooms
  603. * via zoom/pinch gesture,
  604. * via cmd/ctrl-wheel or via trackpad.
  605. *
  606. * @private
  607. * @return {number}
  608. */
  609. _getMax() {
  610. // max zoom level is x4 from "fit state",
  611. // used for zoom gesture and ctrl/trackpad zoom
  612. return this._parseZoomLevelOption('max') || Math.max(1, this.fit * 4);
  613. }
  614. }
  615. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  616. /**
  617. * Renders and allows to control a single slide
  618. */
  619. class Slide {
  620. /**
  621. * @param {SlideData} data
  622. * @param {number} index
  623. * @param {PhotoSwipe} pswp
  624. */
  625. constructor(data, index, pswp) {
  626. this.data = data;
  627. this.index = index;
  628. this.pswp = pswp;
  629. this.isActive = index === pswp.currIndex;
  630. this.currentResolution = 0;
  631. /** @type {Point} */
  632. this.panAreaSize = {
  633. x: 0,
  634. y: 0
  635. };
  636. /** @type {Point} */
  637. this.pan = {
  638. x: 0,
  639. y: 0
  640. };
  641. this.isFirstSlide = this.isActive && !pswp.opener.isOpen;
  642. this.zoomLevels = new ZoomLevel(pswp.options, data, index, pswp);
  643. this.pswp.dispatch('gettingData', {
  644. slide: this,
  645. data: this.data,
  646. index
  647. });
  648. this.content = this.pswp.contentLoader.getContentBySlide(this);
  649. this.container = createElement('pswp__zoom-wrap', 'div');
  650. /** @type {HTMLElement | null} */
  651. this.holderElement = null;
  652. this.currZoomLevel = 1;
  653. /** @type {number} */
  654. this.width = this.content.width;
  655. /** @type {number} */
  656. this.height = this.content.height;
  657. this.heavyAppended = false;
  658. this.bounds = new PanBounds(this);
  659. this.prevDisplayedWidth = -1;
  660. this.prevDisplayedHeight = -1;
  661. this.pswp.dispatch('slideInit', {
  662. slide: this
  663. });
  664. }
  665. /**
  666. * If this slide is active/current/visible
  667. *
  668. * @param {boolean} isActive
  669. */
  670. setIsActive(isActive) {
  671. if (isActive && !this.isActive) {
  672. // slide just became active
  673. this.activate();
  674. } else if (!isActive && this.isActive) {
  675. // slide just became non-active
  676. this.deactivate();
  677. }
  678. }
  679. /**
  680. * Appends slide content to DOM
  681. *
  682. * @param {HTMLElement} holderElement
  683. */
  684. append(holderElement) {
  685. this.holderElement = holderElement;
  686. this.container.style.transformOrigin = '0 0'; // Slide appended to DOM
  687. if (!this.data) {
  688. return;
  689. }
  690. this.calculateSize();
  691. this.load();
  692. this.updateContentSize();
  693. this.appendHeavy();
  694. this.holderElement.appendChild(this.container);
  695. this.zoomAndPanToInitial();
  696. this.pswp.dispatch('firstZoomPan', {
  697. slide: this
  698. });
  699. this.applyCurrentZoomPan();
  700. this.pswp.dispatch('afterSetContent', {
  701. slide: this
  702. });
  703. if (this.isActive) {
  704. this.activate();
  705. }
  706. }
  707. load() {
  708. this.content.load(false);
  709. this.pswp.dispatch('slideLoad', {
  710. slide: this
  711. });
  712. }
  713. /**
  714. * Append "heavy" DOM elements
  715. *
  716. * This may depend on a type of slide,
  717. * but generally these are large images.
  718. */
  719. appendHeavy() {
  720. const {
  721. pswp
  722. } = this;
  723. const appendHeavyNearby = true; // todo
  724. // Avoid appending heavy elements during animations
  725. if (this.heavyAppended || !pswp.opener.isOpen || pswp.mainScroll.isShifted() || !this.isActive && !appendHeavyNearby) {
  726. return;
  727. }
  728. if (this.pswp.dispatch('appendHeavy', {
  729. slide: this
  730. }).defaultPrevented) {
  731. return;
  732. }
  733. this.heavyAppended = true;
  734. this.content.append();
  735. this.pswp.dispatch('appendHeavyContent', {
  736. slide: this
  737. });
  738. }
  739. /**
  740. * Triggered when this slide is active (selected).
  741. *
  742. * If it's part of opening/closing transition -
  743. * activate() will trigger after the transition is ended.
  744. */
  745. activate() {
  746. this.isActive = true;
  747. this.appendHeavy();
  748. this.content.activate();
  749. this.pswp.dispatch('slideActivate', {
  750. slide: this
  751. });
  752. }
  753. /**
  754. * Triggered when this slide becomes inactive.
  755. *
  756. * Slide can become inactive only after it was active.
  757. */
  758. deactivate() {
  759. this.isActive = false;
  760. this.content.deactivate();
  761. if (this.currZoomLevel !== this.zoomLevels.initial) {
  762. // allow filtering
  763. this.calculateSize();
  764. } // reset zoom level
  765. this.currentResolution = 0;
  766. this.zoomAndPanToInitial();
  767. this.applyCurrentZoomPan();
  768. this.updateContentSize();
  769. this.pswp.dispatch('slideDeactivate', {
  770. slide: this
  771. });
  772. }
  773. /**
  774. * The slide should destroy itself, it will never be used again.
  775. * (unbind all events and destroy internal components)
  776. */
  777. destroy() {
  778. this.content.hasSlide = false;
  779. this.content.remove();
  780. this.container.remove();
  781. this.pswp.dispatch('slideDestroy', {
  782. slide: this
  783. });
  784. }
  785. resize() {
  786. if (this.currZoomLevel === this.zoomLevels.initial || !this.isActive) {
  787. // Keep initial zoom level if it was before the resize,
  788. // as well as when this slide is not active
  789. // Reset position and scale to original state
  790. this.calculateSize();
  791. this.currentResolution = 0;
  792. this.zoomAndPanToInitial();
  793. this.applyCurrentZoomPan();
  794. this.updateContentSize();
  795. } else {
  796. // readjust pan position if it's beyond the bounds
  797. this.calculateSize();
  798. this.bounds.update(this.currZoomLevel);
  799. this.panTo(this.pan.x, this.pan.y);
  800. }
  801. }
  802. /**
  803. * Apply size to current slide content,
  804. * based on the current resolution and scale.
  805. *
  806. * @param {boolean} [force] if size should be updated even if dimensions weren't changed
  807. */
  808. updateContentSize(force) {
  809. // Use initial zoom level
  810. // if resolution is not defined (user didn't zoom yet)
  811. const scaleMultiplier = this.currentResolution || this.zoomLevels.initial;
  812. if (!scaleMultiplier) {
  813. return;
  814. }
  815. const width = Math.round(this.width * scaleMultiplier) || this.pswp.viewportSize.x;
  816. const height = Math.round(this.height * scaleMultiplier) || this.pswp.viewportSize.y;
  817. if (!this.sizeChanged(width, height) && !force) {
  818. return;
  819. }
  820. this.content.setDisplayedSize(width, height);
  821. }
  822. /**
  823. * @param {number} width
  824. * @param {number} height
  825. */
  826. sizeChanged(width, height) {
  827. if (width !== this.prevDisplayedWidth || height !== this.prevDisplayedHeight) {
  828. this.prevDisplayedWidth = width;
  829. this.prevDisplayedHeight = height;
  830. return true;
  831. }
  832. return false;
  833. }
  834. /** @returns {HTMLImageElement | HTMLDivElement | null | undefined} */
  835. getPlaceholderElement() {
  836. var _this$content$placeho;
  837. return (_this$content$placeho = this.content.placeholder) === null || _this$content$placeho === void 0 ? void 0 : _this$content$placeho.element;
  838. }
  839. /**
  840. * Zoom current slide image to...
  841. *
  842. * @param {number} destZoomLevel Destination zoom level.
  843. * @param {Point} [centerPoint]
  844. * Transform origin center point, or false if viewport center should be used.
  845. * @param {number | false} [transitionDuration] Transition duration, may be set to 0.
  846. * @param {boolean} [ignoreBounds] Minimum and maximum zoom levels will be ignored.
  847. */
  848. zoomTo(destZoomLevel, centerPoint, transitionDuration, ignoreBounds) {
  849. const {
  850. pswp
  851. } = this;
  852. if (!this.isZoomable() || pswp.mainScroll.isShifted()) {
  853. return;
  854. }
  855. pswp.dispatch('beforeZoomTo', {
  856. destZoomLevel,
  857. centerPoint,
  858. transitionDuration
  859. }); // stop all pan and zoom transitions
  860. pswp.animations.stopAllPan(); // if (!centerPoint) {
  861. // centerPoint = pswp.getViewportCenterPoint();
  862. // }
  863. const prevZoomLevel = this.currZoomLevel;
  864. if (!ignoreBounds) {
  865. destZoomLevel = clamp(destZoomLevel, this.zoomLevels.min, this.zoomLevels.max);
  866. } // if (transitionDuration === undefined) {
  867. // transitionDuration = this.pswp.options.zoomAnimationDuration;
  868. // }
  869. this.setZoomLevel(destZoomLevel);
  870. this.pan.x = this.calculateZoomToPanOffset('x', centerPoint, prevZoomLevel);
  871. this.pan.y = this.calculateZoomToPanOffset('y', centerPoint, prevZoomLevel);
  872. roundPoint(this.pan);
  873. const finishTransition = () => {
  874. this._setResolution(destZoomLevel);
  875. this.applyCurrentZoomPan();
  876. };
  877. if (!transitionDuration) {
  878. finishTransition();
  879. } else {
  880. pswp.animations.startTransition({
  881. isPan: true,
  882. name: 'zoomTo',
  883. target: this.container,
  884. transform: this.getCurrentTransform(),
  885. onComplete: finishTransition,
  886. duration: transitionDuration,
  887. easing: pswp.options.easing
  888. });
  889. }
  890. }
  891. /**
  892. * @param {Point} [centerPoint]
  893. */
  894. toggleZoom(centerPoint) {
  895. this.zoomTo(this.currZoomLevel === this.zoomLevels.initial ? this.zoomLevels.secondary : this.zoomLevels.initial, centerPoint, this.pswp.options.zoomAnimationDuration);
  896. }
  897. /**
  898. * Updates zoom level property and recalculates new pan bounds,
  899. * unlike zoomTo it does not apply transform (use applyCurrentZoomPan)
  900. *
  901. * @param {number} currZoomLevel
  902. */
  903. setZoomLevel(currZoomLevel) {
  904. this.currZoomLevel = currZoomLevel;
  905. this.bounds.update(this.currZoomLevel);
  906. }
  907. /**
  908. * Get pan position after zoom at a given `point`.
  909. *
  910. * Always call setZoomLevel(newZoomLevel) beforehand to recalculate
  911. * pan bounds according to the new zoom level.
  912. *
  913. * @param {'x' | 'y'} axis
  914. * @param {Point} [point]
  915. * point based on which zoom is performed, usually refers to the current mouse position,
  916. * if false - viewport center will be used.
  917. * @param {number} [prevZoomLevel] Zoom level before new zoom was applied.
  918. * @returns {number}
  919. */
  920. calculateZoomToPanOffset(axis, point, prevZoomLevel) {
  921. const totalPanDistance = this.bounds.max[axis] - this.bounds.min[axis];
  922. if (totalPanDistance === 0) {
  923. return this.bounds.center[axis];
  924. }
  925. if (!point) {
  926. point = this.pswp.getViewportCenterPoint();
  927. }
  928. if (!prevZoomLevel) {
  929. prevZoomLevel = this.zoomLevels.initial;
  930. }
  931. const zoomFactor = this.currZoomLevel / prevZoomLevel;
  932. return this.bounds.correctPan(axis, (this.pan[axis] - point[axis]) * zoomFactor + point[axis]);
  933. }
  934. /**
  935. * Apply pan and keep it within bounds.
  936. *
  937. * @param {number} panX
  938. * @param {number} panY
  939. */
  940. panTo(panX, panY) {
  941. this.pan.x = this.bounds.correctPan('x', panX);
  942. this.pan.y = this.bounds.correctPan('y', panY);
  943. this.applyCurrentZoomPan();
  944. }
  945. /**
  946. * If the slide in the current state can be panned by the user
  947. * @returns {boolean}
  948. */
  949. isPannable() {
  950. return Boolean(this.width) && this.currZoomLevel > this.zoomLevels.fit;
  951. }
  952. /**
  953. * If the slide can be zoomed
  954. * @returns {boolean}
  955. */
  956. isZoomable() {
  957. return Boolean(this.width) && this.content.isZoomable();
  958. }
  959. /**
  960. * Apply transform and scale based on
  961. * the current pan position (this.pan) and zoom level (this.currZoomLevel)
  962. */
  963. applyCurrentZoomPan() {
  964. this._applyZoomTransform(this.pan.x, this.pan.y, this.currZoomLevel);
  965. if (this === this.pswp.currSlide) {
  966. this.pswp.dispatch('zoomPanUpdate', {
  967. slide: this
  968. });
  969. }
  970. }
  971. zoomAndPanToInitial() {
  972. this.currZoomLevel = this.zoomLevels.initial; // pan according to the zoom level
  973. this.bounds.update(this.currZoomLevel);
  974. equalizePoints(this.pan, this.bounds.center);
  975. this.pswp.dispatch('initialZoomPan', {
  976. slide: this
  977. });
  978. }
  979. /**
  980. * Set translate and scale based on current resolution
  981. *
  982. * @param {number} x
  983. * @param {number} y
  984. * @param {number} zoom
  985. * @private
  986. */
  987. _applyZoomTransform(x, y, zoom) {
  988. zoom /= this.currentResolution || this.zoomLevels.initial;
  989. setTransform(this.container, x, y, zoom);
  990. }
  991. calculateSize() {
  992. const {
  993. pswp
  994. } = this;
  995. equalizePoints(this.panAreaSize, getPanAreaSize(pswp.options, pswp.viewportSize, this.data, this.index));
  996. this.zoomLevels.update(this.width, this.height, this.panAreaSize);
  997. pswp.dispatch('calcSlideSize', {
  998. slide: this
  999. });
  1000. }
  1001. /** @returns {string} */
  1002. getCurrentTransform() {
  1003. const scale = this.currZoomLevel / (this.currentResolution || this.zoomLevels.initial);
  1004. return toTransformString(this.pan.x, this.pan.y, scale);
  1005. }
  1006. /**
  1007. * Set resolution and re-render the image.
  1008. *
  1009. * For example, if the real image size is 2000x1500,
  1010. * and resolution is 0.5 - it will be rendered as 1000x750.
  1011. *
  1012. * Image with zoom level 2 and resolution 0.5 is
  1013. * the same as image with zoom level 1 and resolution 1.
  1014. *
  1015. * Used to optimize animations and make
  1016. * sure that browser renders image in the highest quality.
  1017. * Also used by responsive images to load the correct one.
  1018. *
  1019. * @param {number} newResolution
  1020. */
  1021. _setResolution(newResolution) {
  1022. if (newResolution === this.currentResolution) {
  1023. return;
  1024. }
  1025. this.currentResolution = newResolution;
  1026. this.updateContentSize();
  1027. this.pswp.dispatch('resolutionChanged');
  1028. }
  1029. }
  1030. /** @typedef {import('../photoswipe.js').Point} Point */
  1031. /** @typedef {import('./gestures.js').default} Gestures */
  1032. const PAN_END_FRICTION = 0.35;
  1033. const VERTICAL_DRAG_FRICTION = 0.6; // 1 corresponds to the third of viewport height
  1034. const MIN_RATIO_TO_CLOSE = 0.4; // Minimum speed required to navigate
  1035. // to next or previous slide
  1036. const MIN_NEXT_SLIDE_SPEED = 0.5;
  1037. /**
  1038. * @param {number} initialVelocity
  1039. * @param {number} decelerationRate
  1040. * @returns {number}
  1041. */
  1042. function project(initialVelocity, decelerationRate) {
  1043. return initialVelocity * decelerationRate / (1 - decelerationRate);
  1044. }
  1045. /**
  1046. * Handles single pointer dragging
  1047. */
  1048. class DragHandler {
  1049. /**
  1050. * @param {Gestures} gestures
  1051. */
  1052. constructor(gestures) {
  1053. this.gestures = gestures;
  1054. this.pswp = gestures.pswp;
  1055. /** @type {Point} */
  1056. this.startPan = {
  1057. x: 0,
  1058. y: 0
  1059. };
  1060. }
  1061. start() {
  1062. if (this.pswp.currSlide) {
  1063. equalizePoints(this.startPan, this.pswp.currSlide.pan);
  1064. }
  1065. this.pswp.animations.stopAll();
  1066. }
  1067. change() {
  1068. const {
  1069. p1,
  1070. prevP1,
  1071. dragAxis
  1072. } = this.gestures;
  1073. const {
  1074. currSlide
  1075. } = this.pswp;
  1076. if (dragAxis === 'y' && this.pswp.options.closeOnVerticalDrag && currSlide && currSlide.currZoomLevel <= currSlide.zoomLevels.fit && !this.gestures.isMultitouch) {
  1077. // Handle vertical drag to close
  1078. const panY = currSlide.pan.y + (p1.y - prevP1.y);
  1079. if (!this.pswp.dispatch('verticalDrag', {
  1080. panY
  1081. }).defaultPrevented) {
  1082. this._setPanWithFriction('y', panY, VERTICAL_DRAG_FRICTION);
  1083. const bgOpacity = 1 - Math.abs(this._getVerticalDragRatio(currSlide.pan.y));
  1084. this.pswp.applyBgOpacity(bgOpacity);
  1085. currSlide.applyCurrentZoomPan();
  1086. }
  1087. } else {
  1088. const mainScrollChanged = this._panOrMoveMainScroll('x');
  1089. if (!mainScrollChanged) {
  1090. this._panOrMoveMainScroll('y');
  1091. if (currSlide) {
  1092. roundPoint(currSlide.pan);
  1093. currSlide.applyCurrentZoomPan();
  1094. }
  1095. }
  1096. }
  1097. }
  1098. end() {
  1099. const {
  1100. velocity
  1101. } = this.gestures;
  1102. const {
  1103. mainScroll,
  1104. currSlide
  1105. } = this.pswp;
  1106. let indexDiff = 0;
  1107. this.pswp.animations.stopAll(); // Handle main scroll if it's shifted
  1108. if (mainScroll.isShifted()) {
  1109. // Position of the main scroll relative to the viewport
  1110. const mainScrollShiftDiff = mainScroll.x - mainScroll.getCurrSlideX(); // Ratio between 0 and 1:
  1111. // 0 - slide is not visible at all,
  1112. // 0.5 - half of the slide is visible
  1113. // 1 - slide is fully visible
  1114. const currentSlideVisibilityRatio = mainScrollShiftDiff / this.pswp.viewportSize.x; // Go next slide.
  1115. //
  1116. // - if velocity and its direction is matched,
  1117. // and we see at least tiny part of the next slide
  1118. //
  1119. // - or if we see less than 50% of the current slide
  1120. // and velocity is close to 0
  1121. //
  1122. if (velocity.x < -MIN_NEXT_SLIDE_SPEED && currentSlideVisibilityRatio < 0 || velocity.x < 0.1 && currentSlideVisibilityRatio < -0.5) {
  1123. // Go to next slide
  1124. indexDiff = 1;
  1125. velocity.x = Math.min(velocity.x, 0);
  1126. } else if (velocity.x > MIN_NEXT_SLIDE_SPEED && currentSlideVisibilityRatio > 0 || velocity.x > -0.1 && currentSlideVisibilityRatio > 0.5) {
  1127. // Go to prev slide
  1128. indexDiff = -1;
  1129. velocity.x = Math.max(velocity.x, 0);
  1130. }
  1131. mainScroll.moveIndexBy(indexDiff, true, velocity.x);
  1132. } // Restore zoom level
  1133. if (currSlide && currSlide.currZoomLevel > currSlide.zoomLevels.max || this.gestures.isMultitouch) {
  1134. this.gestures.zoomLevels.correctZoomPan(true);
  1135. } else {
  1136. // we run two animations instead of one,
  1137. // as each axis has own pan boundaries and thus different spring function
  1138. // (correctZoomPan does not have this functionality,
  1139. // it animates all properties with single timing function)
  1140. this._finishPanGestureForAxis('x');
  1141. this._finishPanGestureForAxis('y');
  1142. }
  1143. }
  1144. /**
  1145. * @private
  1146. * @param {'x' | 'y'} axis
  1147. */
  1148. _finishPanGestureForAxis(axis) {
  1149. const {
  1150. velocity
  1151. } = this.gestures;
  1152. const {
  1153. currSlide
  1154. } = this.pswp;
  1155. if (!currSlide) {
  1156. return;
  1157. }
  1158. const {
  1159. pan,
  1160. bounds
  1161. } = currSlide;
  1162. const panPos = pan[axis];
  1163. const restoreBgOpacity = this.pswp.bgOpacity < 1 && axis === 'y'; // 0.995 means - scroll view loses 0.5% of its velocity per millisecond
  1164. // Increasing this number will reduce travel distance
  1165. const decelerationRate = 0.995; // 0.99
  1166. // Pan position if there is no bounds
  1167. const projectedPosition = panPos + project(velocity[axis], decelerationRate);
  1168. if (restoreBgOpacity) {
  1169. const vDragRatio = this._getVerticalDragRatio(panPos);
  1170. const projectedVDragRatio = this._getVerticalDragRatio(projectedPosition); // If we are above and moving upwards,
  1171. // or if we are below and moving downwards
  1172. if (vDragRatio < 0 && projectedVDragRatio < -MIN_RATIO_TO_CLOSE || vDragRatio > 0 && projectedVDragRatio > MIN_RATIO_TO_CLOSE) {
  1173. this.pswp.close();
  1174. return;
  1175. }
  1176. } // Pan position with corrected bounds
  1177. const correctedPanPosition = bounds.correctPan(axis, projectedPosition); // Exit if pan position should not be changed
  1178. // or if speed it too low
  1179. if (panPos === correctedPanPosition) {
  1180. return;
  1181. } // Overshoot if the final position is out of pan bounds
  1182. const dampingRatio = correctedPanPosition === projectedPosition ? 1 : 0.82;
  1183. const initialBgOpacity = this.pswp.bgOpacity;
  1184. const totalPanDist = correctedPanPosition - panPos;
  1185. this.pswp.animations.startSpring({
  1186. name: 'panGesture' + axis,
  1187. isPan: true,
  1188. start: panPos,
  1189. end: correctedPanPosition,
  1190. velocity: velocity[axis],
  1191. dampingRatio,
  1192. onUpdate: pos => {
  1193. // Animate opacity of background relative to Y pan position of an image
  1194. if (restoreBgOpacity && this.pswp.bgOpacity < 1) {
  1195. // 0 - start of animation, 1 - end of animation
  1196. const animationProgressRatio = 1 - (correctedPanPosition - pos) / totalPanDist; // We clamp opacity to keep it between 0 and 1.
  1197. // As progress ratio can be larger than 1 due to overshoot,
  1198. // and we do not want to bounce opacity.
  1199. this.pswp.applyBgOpacity(clamp(initialBgOpacity + (1 - initialBgOpacity) * animationProgressRatio, 0, 1));
  1200. }
  1201. pan[axis] = Math.floor(pos);
  1202. currSlide.applyCurrentZoomPan();
  1203. }
  1204. });
  1205. }
  1206. /**
  1207. * Update position of the main scroll,
  1208. * or/and update pan position of the current slide.
  1209. *
  1210. * Should return true if it changes (or can change) main scroll.
  1211. *
  1212. * @private
  1213. * @param {'x' | 'y'} axis
  1214. * @returns {boolean}
  1215. */
  1216. _panOrMoveMainScroll(axis) {
  1217. const {
  1218. p1,
  1219. dragAxis,
  1220. prevP1,
  1221. isMultitouch
  1222. } = this.gestures;
  1223. const {
  1224. currSlide,
  1225. mainScroll
  1226. } = this.pswp;
  1227. const delta = p1[axis] - prevP1[axis];
  1228. const newMainScrollX = mainScroll.x + delta;
  1229. if (!delta || !currSlide) {
  1230. return false;
  1231. } // Always move main scroll if image can not be panned
  1232. if (axis === 'x' && !currSlide.isPannable() && !isMultitouch) {
  1233. mainScroll.moveTo(newMainScrollX, true);
  1234. return true; // changed main scroll
  1235. }
  1236. const {
  1237. bounds
  1238. } = currSlide;
  1239. const newPan = currSlide.pan[axis] + delta;
  1240. if (this.pswp.options.allowPanToNext && dragAxis === 'x' && axis === 'x' && !isMultitouch) {
  1241. const currSlideMainScrollX = mainScroll.getCurrSlideX(); // Position of the main scroll relative to the viewport
  1242. const mainScrollShiftDiff = mainScroll.x - currSlideMainScrollX;
  1243. const isLeftToRight = delta > 0;
  1244. const isRightToLeft = !isLeftToRight;
  1245. if (newPan > bounds.min[axis] && isLeftToRight) {
  1246. // Panning from left to right, beyond the left edge
  1247. // Wether the image was at minimum pan position (or less)
  1248. // when this drag gesture started.
  1249. // Minimum pan position refers to the left edge of the image.
  1250. const wasAtMinPanPosition = bounds.min[axis] <= this.startPan[axis];
  1251. if (wasAtMinPanPosition) {
  1252. mainScroll.moveTo(newMainScrollX, true);
  1253. return true;
  1254. } else {
  1255. this._setPanWithFriction(axis, newPan); //currSlide.pan[axis] = newPan;
  1256. }
  1257. } else if (newPan < bounds.max[axis] && isRightToLeft) {
  1258. // Paning from right to left, beyond the right edge
  1259. // Maximum pan position refers to the right edge of the image.
  1260. const wasAtMaxPanPosition = this.startPan[axis] <= bounds.max[axis];
  1261. if (wasAtMaxPanPosition) {
  1262. mainScroll.moveTo(newMainScrollX, true);
  1263. return true;
  1264. } else {
  1265. this._setPanWithFriction(axis, newPan); //currSlide.pan[axis] = newPan;
  1266. }
  1267. } else {
  1268. // If main scroll is shifted
  1269. if (mainScrollShiftDiff !== 0) {
  1270. // If main scroll is shifted right
  1271. if (mainScrollShiftDiff > 0
  1272. /*&& isRightToLeft*/
  1273. ) {
  1274. mainScroll.moveTo(Math.max(newMainScrollX, currSlideMainScrollX), true);
  1275. return true;
  1276. } else if (mainScrollShiftDiff < 0
  1277. /*&& isLeftToRight*/
  1278. ) {
  1279. // Main scroll is shifted left (Position is less than 0 comparing to the viewport 0)
  1280. mainScroll.moveTo(Math.min(newMainScrollX, currSlideMainScrollX), true);
  1281. return true;
  1282. }
  1283. } else {
  1284. // We are within pan bounds, so just pan
  1285. this._setPanWithFriction(axis, newPan);
  1286. }
  1287. }
  1288. } else {
  1289. if (axis === 'y') {
  1290. // Do not pan vertically if main scroll is shifted o
  1291. if (!mainScroll.isShifted() && bounds.min.y !== bounds.max.y) {
  1292. this._setPanWithFriction(axis, newPan);
  1293. }
  1294. } else {
  1295. this._setPanWithFriction(axis, newPan);
  1296. }
  1297. }
  1298. return false;
  1299. } // If we move above - the ratio is negative
  1300. // If we move below the ratio is positive
  1301. /**
  1302. * Relation between pan Y position and third of viewport height.
  1303. *
  1304. * When we are at initial position (center bounds) - the ratio is 0,
  1305. * if position is shifted upwards - the ratio is negative,
  1306. * if position is shifted downwards - the ratio is positive.
  1307. *
  1308. * @private
  1309. * @param {number} panY The current pan Y position.
  1310. * @returns {number}
  1311. */
  1312. _getVerticalDragRatio(panY) {
  1313. var _this$pswp$currSlide$, _this$pswp$currSlide;
  1314. return (panY - ((_this$pswp$currSlide$ = (_this$pswp$currSlide = this.pswp.currSlide) === null || _this$pswp$currSlide === void 0 ? void 0 : _this$pswp$currSlide.bounds.center.y) !== null && _this$pswp$currSlide$ !== void 0 ? _this$pswp$currSlide$ : 0)) / (this.pswp.viewportSize.y / 3);
  1315. }
  1316. /**
  1317. * Set pan position of the current slide.
  1318. * Apply friction if the position is beyond the pan bounds,
  1319. * or if custom friction is defined.
  1320. *
  1321. * @private
  1322. * @param {'x' | 'y'} axis
  1323. * @param {number} potentialPan
  1324. * @param {number} [customFriction] (0.1 - 1)
  1325. */
  1326. _setPanWithFriction(axis, potentialPan, customFriction) {
  1327. const {
  1328. currSlide
  1329. } = this.pswp;
  1330. if (!currSlide) {
  1331. return;
  1332. }
  1333. const {
  1334. pan,
  1335. bounds
  1336. } = currSlide;
  1337. const correctedPan = bounds.correctPan(axis, potentialPan); // If we are out of pan bounds
  1338. if (correctedPan !== potentialPan || customFriction) {
  1339. const delta = Math.round(potentialPan - pan[axis]);
  1340. pan[axis] += delta * (customFriction || PAN_END_FRICTION);
  1341. } else {
  1342. pan[axis] = potentialPan;
  1343. }
  1344. }
  1345. }
  1346. /** @typedef {import('../photoswipe.js').Point} Point */
  1347. /** @typedef {import('./gestures.js').default} Gestures */
  1348. const UPPER_ZOOM_FRICTION = 0.05;
  1349. const LOWER_ZOOM_FRICTION = 0.15;
  1350. /**
  1351. * Get center point between two points
  1352. *
  1353. * @param {Point} p
  1354. * @param {Point} p1
  1355. * @param {Point} p2
  1356. * @returns {Point}
  1357. */
  1358. function getZoomPointsCenter(p, p1, p2) {
  1359. p.x = (p1.x + p2.x) / 2;
  1360. p.y = (p1.y + p2.y) / 2;
  1361. return p;
  1362. }
  1363. class ZoomHandler {
  1364. /**
  1365. * @param {Gestures} gestures
  1366. */
  1367. constructor(gestures) {
  1368. this.gestures = gestures;
  1369. /**
  1370. * @private
  1371. * @type {Point}
  1372. */
  1373. this._startPan = {
  1374. x: 0,
  1375. y: 0
  1376. };
  1377. /**
  1378. * @private
  1379. * @type {Point}
  1380. */
  1381. this._startZoomPoint = {
  1382. x: 0,
  1383. y: 0
  1384. };
  1385. /**
  1386. * @private
  1387. * @type {Point}
  1388. */
  1389. this._zoomPoint = {
  1390. x: 0,
  1391. y: 0
  1392. };
  1393. /** @private */
  1394. this._wasOverFitZoomLevel = false;
  1395. /** @private */
  1396. this._startZoomLevel = 1;
  1397. }
  1398. start() {
  1399. const {
  1400. currSlide
  1401. } = this.gestures.pswp;
  1402. if (currSlide) {
  1403. this._startZoomLevel = currSlide.currZoomLevel;
  1404. equalizePoints(this._startPan, currSlide.pan);
  1405. }
  1406. this.gestures.pswp.animations.stopAllPan();
  1407. this._wasOverFitZoomLevel = false;
  1408. }
  1409. change() {
  1410. const {
  1411. p1,
  1412. startP1,
  1413. p2,
  1414. startP2,
  1415. pswp
  1416. } = this.gestures;
  1417. const {
  1418. currSlide
  1419. } = pswp;
  1420. if (!currSlide) {
  1421. return;
  1422. }
  1423. const minZoomLevel = currSlide.zoomLevels.min;
  1424. const maxZoomLevel = currSlide.zoomLevels.max;
  1425. if (!currSlide.isZoomable() || pswp.mainScroll.isShifted()) {
  1426. return;
  1427. }
  1428. getZoomPointsCenter(this._startZoomPoint, startP1, startP2);
  1429. getZoomPointsCenter(this._zoomPoint, p1, p2);
  1430. let currZoomLevel = 1 / getDistanceBetween(startP1, startP2) * getDistanceBetween(p1, p2) * this._startZoomLevel; // slightly over the zoom.fit
  1431. if (currZoomLevel > currSlide.zoomLevels.initial + currSlide.zoomLevels.initial / 15) {
  1432. this._wasOverFitZoomLevel = true;
  1433. }
  1434. if (currZoomLevel < minZoomLevel) {
  1435. if (pswp.options.pinchToClose && !this._wasOverFitZoomLevel && this._startZoomLevel <= currSlide.zoomLevels.initial) {
  1436. // fade out background if zooming out
  1437. const bgOpacity = 1 - (minZoomLevel - currZoomLevel) / (minZoomLevel / 1.2);
  1438. if (!pswp.dispatch('pinchClose', {
  1439. bgOpacity
  1440. }).defaultPrevented) {
  1441. pswp.applyBgOpacity(bgOpacity);
  1442. }
  1443. } else {
  1444. // Apply the friction if zoom level is below the min
  1445. currZoomLevel = minZoomLevel - (minZoomLevel - currZoomLevel) * LOWER_ZOOM_FRICTION;
  1446. }
  1447. } else if (currZoomLevel > maxZoomLevel) {
  1448. // Apply the friction if zoom level is above the max
  1449. currZoomLevel = maxZoomLevel + (currZoomLevel - maxZoomLevel) * UPPER_ZOOM_FRICTION;
  1450. }
  1451. currSlide.pan.x = this._calculatePanForZoomLevel('x', currZoomLevel);
  1452. currSlide.pan.y = this._calculatePanForZoomLevel('y', currZoomLevel);
  1453. currSlide.setZoomLevel(currZoomLevel);
  1454. currSlide.applyCurrentZoomPan();
  1455. }
  1456. end() {
  1457. const {
  1458. pswp
  1459. } = this.gestures;
  1460. const {
  1461. currSlide
  1462. } = pswp;
  1463. if ((!currSlide || currSlide.currZoomLevel < currSlide.zoomLevels.initial) && !this._wasOverFitZoomLevel && pswp.options.pinchToClose) {
  1464. pswp.close();
  1465. } else {
  1466. this.correctZoomPan();
  1467. }
  1468. }
  1469. /**
  1470. * @private
  1471. * @param {'x' | 'y'} axis
  1472. * @param {number} currZoomLevel
  1473. * @returns {number}
  1474. */
  1475. _calculatePanForZoomLevel(axis, currZoomLevel) {
  1476. const zoomFactor = currZoomLevel / this._startZoomLevel;
  1477. return this._zoomPoint[axis] - (this._startZoomPoint[axis] - this._startPan[axis]) * zoomFactor;
  1478. }
  1479. /**
  1480. * Correct currZoomLevel and pan if they are
  1481. * beyond minimum or maximum values.
  1482. * With animation.
  1483. *
  1484. * @param {boolean} [ignoreGesture]
  1485. * Wether gesture coordinates should be ignored when calculating destination pan position.
  1486. */
  1487. correctZoomPan(ignoreGesture) {
  1488. const {
  1489. pswp
  1490. } = this.gestures;
  1491. const {
  1492. currSlide
  1493. } = pswp;
  1494. if (!(currSlide !== null && currSlide !== void 0 && currSlide.isZoomable())) {
  1495. return;
  1496. }
  1497. if (this._zoomPoint.x === 0) {
  1498. ignoreGesture = true;
  1499. }
  1500. const prevZoomLevel = currSlide.currZoomLevel;
  1501. /** @type {number} */
  1502. let destinationZoomLevel;
  1503. let currZoomLevelNeedsChange = true;
  1504. if (prevZoomLevel < currSlide.zoomLevels.initial) {
  1505. destinationZoomLevel = currSlide.zoomLevels.initial; // zoom to min
  1506. } else if (prevZoomLevel > currSlide.zoomLevels.max) {
  1507. destinationZoomLevel = currSlide.zoomLevels.max; // zoom to max
  1508. } else {
  1509. currZoomLevelNeedsChange = false;
  1510. destinationZoomLevel = prevZoomLevel;
  1511. }
  1512. const initialBgOpacity = pswp.bgOpacity;
  1513. const restoreBgOpacity = pswp.bgOpacity < 1;
  1514. const initialPan = equalizePoints({
  1515. x: 0,
  1516. y: 0
  1517. }, currSlide.pan);
  1518. let destinationPan = equalizePoints({
  1519. x: 0,
  1520. y: 0
  1521. }, initialPan);
  1522. if (ignoreGesture) {
  1523. this._zoomPoint.x = 0;
  1524. this._zoomPoint.y = 0;
  1525. this._startZoomPoint.x = 0;
  1526. this._startZoomPoint.y = 0;
  1527. this._startZoomLevel = prevZoomLevel;
  1528. equalizePoints(this._startPan, initialPan);
  1529. }
  1530. if (currZoomLevelNeedsChange) {
  1531. destinationPan = {
  1532. x: this._calculatePanForZoomLevel('x', destinationZoomLevel),
  1533. y: this._calculatePanForZoomLevel('y', destinationZoomLevel)
  1534. };
  1535. } // set zoom level, so pan bounds are updated according to it
  1536. currSlide.setZoomLevel(destinationZoomLevel);
  1537. destinationPan = {
  1538. x: currSlide.bounds.correctPan('x', destinationPan.x),
  1539. y: currSlide.bounds.correctPan('y', destinationPan.y)
  1540. }; // return zoom level and its bounds to initial
  1541. currSlide.setZoomLevel(prevZoomLevel);
  1542. const panNeedsChange = !pointsEqual(destinationPan, initialPan);
  1543. if (!panNeedsChange && !currZoomLevelNeedsChange && !restoreBgOpacity) {
  1544. // update resolution after gesture
  1545. currSlide._setResolution(destinationZoomLevel);
  1546. currSlide.applyCurrentZoomPan(); // nothing to animate
  1547. return;
  1548. }
  1549. pswp.animations.stopAllPan();
  1550. pswp.animations.startSpring({
  1551. isPan: true,
  1552. start: 0,
  1553. end: 1000,
  1554. velocity: 0,
  1555. dampingRatio: 1,
  1556. naturalFrequency: 40,
  1557. onUpdate: now => {
  1558. now /= 1000; // 0 - start, 1 - end
  1559. if (panNeedsChange || currZoomLevelNeedsChange) {
  1560. if (panNeedsChange) {
  1561. currSlide.pan.x = initialPan.x + (destinationPan.x - initialPan.x) * now;
  1562. currSlide.pan.y = initialPan.y + (destinationPan.y - initialPan.y) * now;
  1563. }
  1564. if (currZoomLevelNeedsChange) {
  1565. const newZoomLevel = prevZoomLevel + (destinationZoomLevel - prevZoomLevel) * now;
  1566. currSlide.setZoomLevel(newZoomLevel);
  1567. }
  1568. currSlide.applyCurrentZoomPan();
  1569. } // Restore background opacity
  1570. if (restoreBgOpacity && pswp.bgOpacity < 1) {
  1571. // We clamp opacity to keep it between 0 and 1.
  1572. // As progress ratio can be larger than 1 due to overshoot,
  1573. // and we do not want to bounce opacity.
  1574. pswp.applyBgOpacity(clamp(initialBgOpacity + (1 - initialBgOpacity) * now, 0, 1));
  1575. }
  1576. },
  1577. onComplete: () => {
  1578. // update resolution after transition ends
  1579. currSlide._setResolution(destinationZoomLevel);
  1580. currSlide.applyCurrentZoomPan();
  1581. }
  1582. });
  1583. }
  1584. }
  1585. /**
  1586. * @template {string} T
  1587. * @template {string} P
  1588. * @typedef {import('../types.js').AddPostfix<T, P>} AddPostfix<T, P>
  1589. */
  1590. /** @typedef {import('./gestures.js').default} Gestures */
  1591. /** @typedef {import('../photoswipe.js').Point} Point */
  1592. /** @typedef {'imageClick' | 'bgClick' | 'tap' | 'doubleTap'} Actions */
  1593. /**
  1594. * Whether the tap was performed on the main slide
  1595. * (rather than controls or caption).
  1596. *
  1597. * @param {PointerEvent} event
  1598. * @returns {boolean}
  1599. */
  1600. function didTapOnMainContent(event) {
  1601. return !!
  1602. /** @type {HTMLElement} */
  1603. event.target.closest('.pswp__container');
  1604. }
  1605. /**
  1606. * Tap, double-tap handler.
  1607. */
  1608. class TapHandler {
  1609. /**
  1610. * @param {Gestures} gestures
  1611. */
  1612. constructor(gestures) {
  1613. this.gestures = gestures;
  1614. }
  1615. /**
  1616. * @param {Point} point
  1617. * @param {PointerEvent} originalEvent
  1618. */
  1619. click(point, originalEvent) {
  1620. const targetClassList =
  1621. /** @type {HTMLElement} */
  1622. originalEvent.target.classList;
  1623. const isImageClick = targetClassList.contains('pswp__img');
  1624. const isBackgroundClick = targetClassList.contains('pswp__item') || targetClassList.contains('pswp__zoom-wrap');
  1625. if (isImageClick) {
  1626. this._doClickOrTapAction('imageClick', point, originalEvent);
  1627. } else if (isBackgroundClick) {
  1628. this._doClickOrTapAction('bgClick', point, originalEvent);
  1629. }
  1630. }
  1631. /**
  1632. * @param {Point} point
  1633. * @param {PointerEvent} originalEvent
  1634. */
  1635. tap(point, originalEvent) {
  1636. if (didTapOnMainContent(originalEvent)) {
  1637. this._doClickOrTapAction('tap', point, originalEvent);
  1638. }
  1639. }
  1640. /**
  1641. * @param {Point} point
  1642. * @param {PointerEvent} originalEvent
  1643. */
  1644. doubleTap(point, originalEvent) {
  1645. if (didTapOnMainContent(originalEvent)) {
  1646. this._doClickOrTapAction('doubleTap', point, originalEvent);
  1647. }
  1648. }
  1649. /**
  1650. * @private
  1651. * @param {Actions} actionName
  1652. * @param {Point} point
  1653. * @param {PointerEvent} originalEvent
  1654. */
  1655. _doClickOrTapAction(actionName, point, originalEvent) {
  1656. var _this$gestures$pswp$e;
  1657. const {
  1658. pswp
  1659. } = this.gestures;
  1660. const {
  1661. currSlide
  1662. } = pswp;
  1663. const actionFullName =
  1664. /** @type {AddPostfix<Actions, 'Action'>} */
  1665. actionName + 'Action';
  1666. const optionValue = pswp.options[actionFullName];
  1667. if (pswp.dispatch(actionFullName, {
  1668. point,
  1669. originalEvent
  1670. }).defaultPrevented) {
  1671. return;
  1672. }
  1673. if (typeof optionValue === 'function') {
  1674. optionValue.call(pswp, point, originalEvent);
  1675. return;
  1676. }
  1677. switch (optionValue) {
  1678. case 'close':
  1679. case 'next':
  1680. pswp[optionValue]();
  1681. break;
  1682. case 'zoom':
  1683. currSlide === null || currSlide === void 0 || currSlide.toggleZoom(point);
  1684. break;
  1685. case 'zoom-or-close':
  1686. // by default click zooms current image,
  1687. // if it can not be zoomed - gallery will be closed
  1688. if (currSlide !== null && currSlide !== void 0 && currSlide.isZoomable() && currSlide.zoomLevels.secondary !== currSlide.zoomLevels.initial) {
  1689. currSlide.toggleZoom(point);
  1690. } else if (pswp.options.clickToCloseNonZoomable) {
  1691. pswp.close();
  1692. }
  1693. break;
  1694. case 'toggle-controls':
  1695. (_this$gestures$pswp$e = this.gestures.pswp.element) === null || _this$gestures$pswp$e === void 0 || _this$gestures$pswp$e.classList.toggle('pswp--ui-visible'); // if (_controlsVisible) {
  1696. // _ui.hideControls();
  1697. // } else {
  1698. // _ui.showControls();
  1699. // }
  1700. break;
  1701. }
  1702. }
  1703. }
  1704. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  1705. /** @typedef {import('../photoswipe.js').Point} Point */
  1706. // How far should user should drag
  1707. // until we can determine that the gesture is swipe and its direction
  1708. const AXIS_SWIPE_HYSTERISIS = 10; //const PAN_END_FRICTION = 0.35;
  1709. const DOUBLE_TAP_DELAY = 300; // ms
  1710. const MIN_TAP_DISTANCE = 25; // px
  1711. /**
  1712. * Gestures class bind touch, pointer or mouse events
  1713. * and emits drag to drag-handler and zoom events zoom-handler.
  1714. *
  1715. * Drag and zoom events are emited in requestAnimationFrame,
  1716. * and only when one of pointers was actually changed.
  1717. */
  1718. class Gestures {
  1719. /**
  1720. * @param {PhotoSwipe} pswp
  1721. */
  1722. constructor(pswp) {
  1723. this.pswp = pswp;
  1724. /** @type {'x' | 'y' | null} */
  1725. this.dragAxis = null; // point objects are defined once and reused
  1726. // PhotoSwipe keeps track only of two pointers, others are ignored
  1727. /** @type {Point} */
  1728. this.p1 = {
  1729. x: 0,
  1730. y: 0
  1731. }; // the first pressed pointer
  1732. /** @type {Point} */
  1733. this.p2 = {
  1734. x: 0,
  1735. y: 0
  1736. }; // the second pressed pointer
  1737. /** @type {Point} */
  1738. this.prevP1 = {
  1739. x: 0,
  1740. y: 0
  1741. };
  1742. /** @type {Point} */
  1743. this.prevP2 = {
  1744. x: 0,
  1745. y: 0
  1746. };
  1747. /** @type {Point} */
  1748. this.startP1 = {
  1749. x: 0,
  1750. y: 0
  1751. };
  1752. /** @type {Point} */
  1753. this.startP2 = {
  1754. x: 0,
  1755. y: 0
  1756. };
  1757. /** @type {Point} */
  1758. this.velocity = {
  1759. x: 0,
  1760. y: 0
  1761. };
  1762. /** @type {Point}
  1763. * @private
  1764. */
  1765. this._lastStartP1 = {
  1766. x: 0,
  1767. y: 0
  1768. };
  1769. /** @type {Point}
  1770. * @private
  1771. */
  1772. this._intervalP1 = {
  1773. x: 0,
  1774. y: 0
  1775. };
  1776. /** @private */
  1777. this._numActivePoints = 0;
  1778. /** @type {Point[]}
  1779. * @private
  1780. */
  1781. this._ongoingPointers = [];
  1782. /** @private */
  1783. this._touchEventEnabled = 'ontouchstart' in window;
  1784. /** @private */
  1785. this._pointerEventEnabled = !!window.PointerEvent;
  1786. this.supportsTouch = this._touchEventEnabled || this._pointerEventEnabled && navigator.maxTouchPoints > 1;
  1787. /** @private */
  1788. this._numActivePoints = 0;
  1789. /** @private */
  1790. this._intervalTime = 0;
  1791. /** @private */
  1792. this._velocityCalculated = false;
  1793. this.isMultitouch = false;
  1794. this.isDragging = false;
  1795. this.isZooming = false;
  1796. /** @type {number | null} */
  1797. this.raf = null;
  1798. /** @type {NodeJS.Timeout | null}
  1799. * @private
  1800. */
  1801. this._tapTimer = null;
  1802. if (!this.supportsTouch) {
  1803. // disable pan to next slide for non-touch devices
  1804. pswp.options.allowPanToNext = false;
  1805. }
  1806. this.drag = new DragHandler(this);
  1807. this.zoomLevels = new ZoomHandler(this);
  1808. this.tapHandler = new TapHandler(this);
  1809. pswp.on('bindEvents', () => {
  1810. pswp.events.add(pswp.scrollWrap, 'click',
  1811. /** @type EventListener */
  1812. this._onClick.bind(this));
  1813. if (this._pointerEventEnabled) {
  1814. this._bindEvents('pointer', 'down', 'up', 'cancel');
  1815. } else if (this._touchEventEnabled) {
  1816. this._bindEvents('touch', 'start', 'end', 'cancel'); // In previous versions we also bound mouse event here,
  1817. // in case device supports both touch and mouse events,
  1818. // but newer versions of browsers now support PointerEvent.
  1819. // on iOS10 if you bind touchmove/end after touchstart,
  1820. // and you don't preventDefault touchstart (which PhotoSwipe does),
  1821. // preventDefault will have no effect on touchmove and touchend.
  1822. // Unless you bind it previously.
  1823. if (pswp.scrollWrap) {
  1824. pswp.scrollWrap.ontouchmove = () => {};
  1825. pswp.scrollWrap.ontouchend = () => {};
  1826. }
  1827. } else {
  1828. this._bindEvents('mouse', 'down', 'up');
  1829. }
  1830. });
  1831. }
  1832. /**
  1833. * @private
  1834. * @param {'mouse' | 'touch' | 'pointer'} pref
  1835. * @param {'down' | 'start'} down
  1836. * @param {'up' | 'end'} up
  1837. * @param {'cancel'} [cancel]
  1838. */
  1839. _bindEvents(pref, down, up, cancel) {
  1840. const {
  1841. pswp
  1842. } = this;
  1843. const {
  1844. events
  1845. } = pswp;
  1846. const cancelEvent = cancel ? pref + cancel : '';
  1847. events.add(pswp.scrollWrap, pref + down,
  1848. /** @type EventListener */
  1849. this.onPointerDown.bind(this));
  1850. events.add(window, pref + 'move',
  1851. /** @type EventListener */
  1852. this.onPointerMove.bind(this));
  1853. events.add(window, pref + up,
  1854. /** @type EventListener */
  1855. this.onPointerUp.bind(this));
  1856. if (cancelEvent) {
  1857. events.add(pswp.scrollWrap, cancelEvent,
  1858. /** @type EventListener */
  1859. this.onPointerUp.bind(this));
  1860. }
  1861. }
  1862. /**
  1863. * @param {PointerEvent} e
  1864. */
  1865. onPointerDown(e) {
  1866. // We do not call preventDefault for touch events
  1867. // to allow browser to show native dialog on longpress
  1868. // (the one that allows to save image or open it in new tab).
  1869. //
  1870. // Desktop Safari allows to drag images when preventDefault isn't called on mousedown,
  1871. // even though preventDefault IS called on mousemove. That's why we preventDefault mousedown.
  1872. const isMousePointer = e.type === 'mousedown' || e.pointerType === 'mouse'; // Allow dragging only via left mouse button.
  1873. // http://www.quirksmode.org/js/events_properties.html
  1874. // https://developer.mozilla.org/en-US/docs/Web/API/event.button
  1875. if (isMousePointer && e.button > 0) {
  1876. return;
  1877. }
  1878. const {
  1879. pswp
  1880. } = this; // if PhotoSwipe is opening or closing
  1881. if (!pswp.opener.isOpen) {
  1882. e.preventDefault();
  1883. return;
  1884. }
  1885. if (pswp.dispatch('pointerDown', {
  1886. originalEvent: e
  1887. }).defaultPrevented) {
  1888. return;
  1889. }
  1890. if (isMousePointer) {
  1891. pswp.mouseDetected(); // preventDefault mouse event to prevent
  1892. // browser image drag feature
  1893. this._preventPointerEventBehaviour(e, 'down');
  1894. }
  1895. pswp.animations.stopAll();
  1896. this._updatePoints(e, 'down');
  1897. if (this._numActivePoints === 1) {
  1898. this.dragAxis = null; // we need to store initial point to determine the main axis,
  1899. // drag is activated only after the axis is determined
  1900. equalizePoints(this.startP1, this.p1);
  1901. }
  1902. if (this._numActivePoints > 1) {
  1903. // Tap or double tap should not trigger if more than one pointer
  1904. this._clearTapTimer();
  1905. this.isMultitouch = true;
  1906. } else {
  1907. this.isMultitouch = false;
  1908. }
  1909. }
  1910. /**
  1911. * @param {PointerEvent} e
  1912. */
  1913. onPointerMove(e) {
  1914. this._preventPointerEventBehaviour(e, 'move');
  1915. if (!this._numActivePoints) {
  1916. return;
  1917. }
  1918. this._updatePoints(e, 'move');
  1919. if (this.pswp.dispatch('pointerMove', {
  1920. originalEvent: e
  1921. }).defaultPrevented) {
  1922. return;
  1923. }
  1924. if (this._numActivePoints === 1 && !this.isDragging) {
  1925. if (!this.dragAxis) {
  1926. this._calculateDragDirection();
  1927. } // Drag axis was detected, emit drag.start
  1928. if (this.dragAxis && !this.isDragging) {
  1929. if (this.isZooming) {
  1930. this.isZooming = false;
  1931. this.zoomLevels.end();
  1932. }
  1933. this.isDragging = true;
  1934. this._clearTapTimer(); // Tap can not trigger after drag
  1935. // Adjust starting point
  1936. this._updateStartPoints();
  1937. this._intervalTime = Date.now(); //this._startTime = this._intervalTime;
  1938. this._velocityCalculated = false;
  1939. equalizePoints(this._intervalP1, this.p1);
  1940. this.velocity.x = 0;
  1941. this.velocity.y = 0;
  1942. this.drag.start();
  1943. this._rafStopLoop();
  1944. this._rafRenderLoop();
  1945. }
  1946. } else if (this._numActivePoints > 1 && !this.isZooming) {
  1947. this._finishDrag();
  1948. this.isZooming = true; // Adjust starting points
  1949. this._updateStartPoints();
  1950. this.zoomLevels.start();
  1951. this._rafStopLoop();
  1952. this._rafRenderLoop();
  1953. }
  1954. }
  1955. /**
  1956. * @private
  1957. */
  1958. _finishDrag() {
  1959. if (this.isDragging) {
  1960. this.isDragging = false; // Try to calculate velocity,
  1961. // if it wasn't calculated yet in drag.change
  1962. if (!this._velocityCalculated) {
  1963. this._updateVelocity(true);
  1964. }
  1965. this.drag.end();
  1966. this.dragAxis = null;
  1967. }
  1968. }
  1969. /**
  1970. * @param {PointerEvent} e
  1971. */
  1972. onPointerUp(e) {
  1973. if (!this._numActivePoints) {
  1974. return;
  1975. }
  1976. this._updatePoints(e, 'up');
  1977. if (this.pswp.dispatch('pointerUp', {
  1978. originalEvent: e
  1979. }).defaultPrevented) {
  1980. return;
  1981. }
  1982. if (this._numActivePoints === 0) {
  1983. this._rafStopLoop();
  1984. if (this.isDragging) {
  1985. this._finishDrag();
  1986. } else if (!this.isZooming && !this.isMultitouch) {
  1987. //this.zoomLevels.correctZoomPan();
  1988. this._finishTap(e);
  1989. }
  1990. }
  1991. if (this._numActivePoints < 2 && this.isZooming) {
  1992. this.isZooming = false;
  1993. this.zoomLevels.end();
  1994. if (this._numActivePoints === 1) {
  1995. // Since we have 1 point left, we need to reinitiate drag
  1996. this.dragAxis = null;
  1997. this._updateStartPoints();
  1998. }
  1999. }
  2000. }
  2001. /**
  2002. * @private
  2003. */
  2004. _rafRenderLoop() {
  2005. if (this.isDragging || this.isZooming) {
  2006. this._updateVelocity();
  2007. if (this.isDragging) {
  2008. // make sure that pointer moved since the last update
  2009. if (!pointsEqual(this.p1, this.prevP1)) {
  2010. this.drag.change();
  2011. }
  2012. } else
  2013. /* if (this.isZooming) */
  2014. {
  2015. if (!pointsEqual(this.p1, this.prevP1) || !pointsEqual(this.p2, this.prevP2)) {
  2016. this.zoomLevels.change();
  2017. }
  2018. }
  2019. this._updatePrevPoints();
  2020. this.raf = requestAnimationFrame(this._rafRenderLoop.bind(this));
  2021. }
  2022. }
  2023. /**
  2024. * Update velocity at 50ms interval
  2025. *
  2026. * @private
  2027. * @param {boolean} [force]
  2028. */
  2029. _updateVelocity(force) {
  2030. const time = Date.now();
  2031. const duration = time - this._intervalTime;
  2032. if (duration < 50 && !force) {
  2033. return;
  2034. }
  2035. this.velocity.x = this._getVelocity('x', duration);
  2036. this.velocity.y = this._getVelocity('y', duration);
  2037. this._intervalTime = time;
  2038. equalizePoints(this._intervalP1, this.p1);
  2039. this._velocityCalculated = true;
  2040. }
  2041. /**
  2042. * @private
  2043. * @param {PointerEvent} e
  2044. */
  2045. _finishTap(e) {
  2046. const {
  2047. mainScroll
  2048. } = this.pswp; // Do not trigger tap events if main scroll is shifted
  2049. if (mainScroll.isShifted()) {
  2050. // restore main scroll position
  2051. // (usually happens if stopped in the middle of animation)
  2052. mainScroll.moveIndexBy(0, true);
  2053. return;
  2054. } // Do not trigger tap for touchcancel or pointercancel
  2055. if (e.type.indexOf('cancel') > 0) {
  2056. return;
  2057. } // Trigger click instead of tap for mouse events
  2058. if (e.type === 'mouseup' || e.pointerType === 'mouse') {
  2059. this.tapHandler.click(this.startP1, e);
  2060. return;
  2061. } // Disable delay if there is no doubleTapAction
  2062. const tapDelay = this.pswp.options.doubleTapAction ? DOUBLE_TAP_DELAY : 0; // If tapTimer is defined - we tapped recently,
  2063. // check if the current tap is close to the previous one,
  2064. // if yes - trigger double tap
  2065. if (this._tapTimer) {
  2066. this._clearTapTimer(); // Check if two taps were more or less on the same place
  2067. if (getDistanceBetween(this._lastStartP1, this.startP1) < MIN_TAP_DISTANCE) {
  2068. this.tapHandler.doubleTap(this.startP1, e);
  2069. }
  2070. } else {
  2071. equalizePoints(this._lastStartP1, this.startP1);
  2072. this._tapTimer = setTimeout(() => {
  2073. this.tapHandler.tap(this.startP1, e);
  2074. this._clearTapTimer();
  2075. }, tapDelay);
  2076. }
  2077. }
  2078. /**
  2079. * @private
  2080. */
  2081. _clearTapTimer() {
  2082. if (this._tapTimer) {
  2083. clearTimeout(this._tapTimer);
  2084. this._tapTimer = null;
  2085. }
  2086. }
  2087. /**
  2088. * Get velocity for axis
  2089. *
  2090. * @private
  2091. * @param {'x' | 'y'} axis
  2092. * @param {number} duration
  2093. * @returns {number}
  2094. */
  2095. _getVelocity(axis, duration) {
  2096. // displacement is like distance, but can be negative.
  2097. const displacement = this.p1[axis] - this._intervalP1[axis];
  2098. if (Math.abs(displacement) > 1 && duration > 5) {
  2099. return displacement / duration;
  2100. }
  2101. return 0;
  2102. }
  2103. /**
  2104. * @private
  2105. */
  2106. _rafStopLoop() {
  2107. if (this.raf) {
  2108. cancelAnimationFrame(this.raf);
  2109. this.raf = null;
  2110. }
  2111. }
  2112. /**
  2113. * @private
  2114. * @param {PointerEvent} e
  2115. * @param {'up' | 'down' | 'move'} pointerType Normalized pointer type
  2116. */
  2117. _preventPointerEventBehaviour(e, pointerType) {
  2118. const preventPointerEvent = this.pswp.applyFilters('preventPointerEvent', true, e, pointerType);
  2119. if (preventPointerEvent) {
  2120. e.preventDefault();
  2121. }
  2122. }
  2123. /**
  2124. * Parses and normalizes points from the touch, mouse or pointer event.
  2125. * Updates p1 and p2.
  2126. *
  2127. * @private
  2128. * @param {PointerEvent | TouchEvent} e
  2129. * @param {'up' | 'down' | 'move'} pointerType Normalized pointer type
  2130. */
  2131. _updatePoints(e, pointerType) {
  2132. if (this._pointerEventEnabled) {
  2133. const pointerEvent =
  2134. /** @type {PointerEvent} */
  2135. e; // Try to find the current pointer in ongoing pointers by its ID
  2136. const pointerIndex = this._ongoingPointers.findIndex(ongoingPointer => {
  2137. return ongoingPointer.id === pointerEvent.pointerId;
  2138. });
  2139. if (pointerType === 'up' && pointerIndex > -1) {
  2140. // release the pointer - remove it from ongoing
  2141. this._ongoingPointers.splice(pointerIndex, 1);
  2142. } else if (pointerType === 'down' && pointerIndex === -1) {
  2143. // add new pointer
  2144. this._ongoingPointers.push(this._convertEventPosToPoint(pointerEvent, {
  2145. x: 0,
  2146. y: 0
  2147. }));
  2148. } else if (pointerIndex > -1) {
  2149. // update existing pointer
  2150. this._convertEventPosToPoint(pointerEvent, this._ongoingPointers[pointerIndex]);
  2151. }
  2152. this._numActivePoints = this._ongoingPointers.length; // update points that PhotoSwipe uses
  2153. // to calculate position and scale
  2154. if (this._numActivePoints > 0) {
  2155. equalizePoints(this.p1, this._ongoingPointers[0]);
  2156. }
  2157. if (this._numActivePoints > 1) {
  2158. equalizePoints(this.p2, this._ongoingPointers[1]);
  2159. }
  2160. } else {
  2161. const touchEvent =
  2162. /** @type {TouchEvent} */
  2163. e;
  2164. this._numActivePoints = 0;
  2165. if (touchEvent.type.indexOf('touch') > -1) {
  2166. // Touch Event
  2167. // https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent
  2168. if (touchEvent.touches && touchEvent.touches.length > 0) {
  2169. this._convertEventPosToPoint(touchEvent.touches[0], this.p1);
  2170. this._numActivePoints++;
  2171. if (touchEvent.touches.length > 1) {
  2172. this._convertEventPosToPoint(touchEvent.touches[1], this.p2);
  2173. this._numActivePoints++;
  2174. }
  2175. }
  2176. } else {
  2177. // Mouse Event
  2178. this._convertEventPosToPoint(
  2179. /** @type {PointerEvent} */
  2180. e, this.p1);
  2181. if (pointerType === 'up') {
  2182. // clear all points on mouseup
  2183. this._numActivePoints = 0;
  2184. } else {
  2185. this._numActivePoints++;
  2186. }
  2187. }
  2188. }
  2189. }
  2190. /** update points that were used during previous rAF tick
  2191. * @private
  2192. */
  2193. _updatePrevPoints() {
  2194. equalizePoints(this.prevP1, this.p1);
  2195. equalizePoints(this.prevP2, this.p2);
  2196. }
  2197. /** update points at the start of gesture
  2198. * @private
  2199. */
  2200. _updateStartPoints() {
  2201. equalizePoints(this.startP1, this.p1);
  2202. equalizePoints(this.startP2, this.p2);
  2203. this._updatePrevPoints();
  2204. }
  2205. /** @private */
  2206. _calculateDragDirection() {
  2207. if (this.pswp.mainScroll.isShifted()) {
  2208. // if main scroll position is shifted – direction is always horizontal
  2209. this.dragAxis = 'x';
  2210. } else {
  2211. // calculate delta of the last touchmove tick
  2212. const diff = Math.abs(this.p1.x - this.startP1.x) - Math.abs(this.p1.y - this.startP1.y);
  2213. if (diff !== 0) {
  2214. // check if pointer was shifted horizontally or vertically
  2215. const axisToCheck = diff > 0 ? 'x' : 'y';
  2216. if (Math.abs(this.p1[axisToCheck] - this.startP1[axisToCheck]) >= AXIS_SWIPE_HYSTERISIS) {
  2217. this.dragAxis = axisToCheck;
  2218. }
  2219. }
  2220. }
  2221. }
  2222. /**
  2223. * Converts touch, pointer or mouse event
  2224. * to PhotoSwipe point.
  2225. *
  2226. * @private
  2227. * @param {Touch | PointerEvent} e
  2228. * @param {Point} p
  2229. * @returns {Point}
  2230. */
  2231. _convertEventPosToPoint(e, p) {
  2232. p.x = e.pageX - this.pswp.offset.x;
  2233. p.y = e.pageY - this.pswp.offset.y;
  2234. if ('pointerId' in e) {
  2235. p.id = e.pointerId;
  2236. } else if (e.identifier !== undefined) {
  2237. p.id = e.identifier;
  2238. }
  2239. return p;
  2240. }
  2241. /**
  2242. * @private
  2243. * @param {PointerEvent} e
  2244. */
  2245. _onClick(e) {
  2246. // Do not allow click event to pass through after drag
  2247. if (this.pswp.mainScroll.isShifted()) {
  2248. e.preventDefault();
  2249. e.stopPropagation();
  2250. }
  2251. }
  2252. }
  2253. /** @typedef {import('./photoswipe.js').default} PhotoSwipe */
  2254. /** @typedef {import('./slide/slide.js').default} Slide */
  2255. /** @typedef {{ el: HTMLDivElement; slide?: Slide }} ItemHolder */
  2256. const MAIN_SCROLL_END_FRICTION = 0.35; // const MIN_SWIPE_TRANSITION_DURATION = 250;
  2257. // const MAX_SWIPE_TRABSITION_DURATION = 500;
  2258. // const DEFAULT_SWIPE_TRANSITION_DURATION = 333;
  2259. /**
  2260. * Handles movement of the main scrolling container
  2261. * (for example, it repositions when user swipes left or right).
  2262. *
  2263. * Also stores its state.
  2264. */
  2265. class MainScroll {
  2266. /**
  2267. * @param {PhotoSwipe} pswp
  2268. */
  2269. constructor(pswp) {
  2270. this.pswp = pswp;
  2271. this.x = 0;
  2272. this.slideWidth = 0;
  2273. /** @private */
  2274. this._currPositionIndex = 0;
  2275. /** @private */
  2276. this._prevPositionIndex = 0;
  2277. /** @private */
  2278. this._containerShiftIndex = -1;
  2279. /** @type {ItemHolder[]} */
  2280. this.itemHolders = [];
  2281. }
  2282. /**
  2283. * Position the scroller and slide containers
  2284. * according to viewport size.
  2285. *
  2286. * @param {boolean} [resizeSlides] Whether slides content should resized
  2287. */
  2288. resize(resizeSlides) {
  2289. const {
  2290. pswp
  2291. } = this;
  2292. const newSlideWidth = Math.round(pswp.viewportSize.x + pswp.viewportSize.x * pswp.options.spacing); // Mobile browsers might trigger a resize event during a gesture.
  2293. // (due to toolbar appearing or hiding).
  2294. // Avoid re-adjusting main scroll position if width wasn't changed
  2295. const slideWidthChanged = newSlideWidth !== this.slideWidth;
  2296. if (slideWidthChanged) {
  2297. this.slideWidth = newSlideWidth;
  2298. this.moveTo(this.getCurrSlideX());
  2299. }
  2300. this.itemHolders.forEach((itemHolder, index) => {
  2301. if (slideWidthChanged) {
  2302. setTransform(itemHolder.el, (index + this._containerShiftIndex) * this.slideWidth);
  2303. }
  2304. if (resizeSlides && itemHolder.slide) {
  2305. itemHolder.slide.resize();
  2306. }
  2307. });
  2308. }
  2309. /**
  2310. * Reset X position of the main scroller to zero
  2311. */
  2312. resetPosition() {
  2313. // Position on the main scroller (offset)
  2314. // it is independent from slide index
  2315. this._currPositionIndex = 0;
  2316. this._prevPositionIndex = 0; // This will force recalculation of size on next resize()
  2317. this.slideWidth = 0; // _containerShiftIndex*viewportSize will give you amount of transform of the current slide
  2318. this._containerShiftIndex = -1;
  2319. }
  2320. /**
  2321. * Create and append array of three items
  2322. * that hold data about slides in DOM
  2323. */
  2324. appendHolders() {
  2325. this.itemHolders = []; // append our three slide holders -
  2326. // previous, current, and next
  2327. for (let i = 0; i < 3; i++) {
  2328. const el = createElement('pswp__item', 'div', this.pswp.container);
  2329. el.setAttribute('role', 'group');
  2330. el.setAttribute('aria-roledescription', 'slide');
  2331. el.setAttribute('aria-hidden', 'true'); // hide nearby item holders until initial zoom animation finishes (to avoid extra Paints)
  2332. el.style.display = i === 1 ? 'block' : 'none';
  2333. this.itemHolders.push({
  2334. el //index: -1
  2335. });
  2336. }
  2337. }
  2338. /**
  2339. * Whether the main scroll can be horizontally swiped to the next or previous slide.
  2340. * @returns {boolean}
  2341. */
  2342. canBeSwiped() {
  2343. return this.pswp.getNumItems() > 1;
  2344. }
  2345. /**
  2346. * Move main scroll by X amount of slides.
  2347. * For example:
  2348. * `-1` will move to the previous slide,
  2349. * `0` will reset the scroll position of the current slide,
  2350. * `3` will move three slides forward
  2351. *
  2352. * If loop option is enabled - index will be automatically looped too,
  2353. * (for example `-1` will move to the last slide of the gallery).
  2354. *
  2355. * @param {number} diff
  2356. * @param {boolean} [animate]
  2357. * @param {number} [velocityX]
  2358. * @returns {boolean} whether index was changed or not
  2359. */
  2360. moveIndexBy(diff, animate, velocityX) {
  2361. const {
  2362. pswp
  2363. } = this;
  2364. let newIndex = pswp.potentialIndex + diff;
  2365. const numSlides = pswp.getNumItems();
  2366. if (pswp.canLoop()) {
  2367. newIndex = pswp.getLoopedIndex(newIndex);
  2368. const distance = (diff + numSlides) % numSlides;
  2369. if (distance <= numSlides / 2) {
  2370. // go forward
  2371. diff = distance;
  2372. } else {
  2373. // go backwards
  2374. diff = distance - numSlides;
  2375. }
  2376. } else {
  2377. if (newIndex < 0) {
  2378. newIndex = 0;
  2379. } else if (newIndex >= numSlides) {
  2380. newIndex = numSlides - 1;
  2381. }
  2382. diff = newIndex - pswp.potentialIndex;
  2383. }
  2384. pswp.potentialIndex = newIndex;
  2385. this._currPositionIndex -= diff;
  2386. pswp.animations.stopMainScroll();
  2387. const destinationX = this.getCurrSlideX();
  2388. if (!animate) {
  2389. this.moveTo(destinationX);
  2390. this.updateCurrItem();
  2391. } else {
  2392. pswp.animations.startSpring({
  2393. isMainScroll: true,
  2394. start: this.x,
  2395. end: destinationX,
  2396. velocity: velocityX || 0,
  2397. naturalFrequency: 30,
  2398. dampingRatio: 1,
  2399. //0.7,
  2400. onUpdate: x => {
  2401. this.moveTo(x);
  2402. },
  2403. onComplete: () => {
  2404. this.updateCurrItem();
  2405. pswp.appendHeavy();
  2406. }
  2407. });
  2408. let currDiff = pswp.potentialIndex - pswp.currIndex;
  2409. if (pswp.canLoop()) {
  2410. const currDistance = (currDiff + numSlides) % numSlides;
  2411. if (currDistance <= numSlides / 2) {
  2412. // go forward
  2413. currDiff = currDistance;
  2414. } else {
  2415. // go backwards
  2416. currDiff = currDistance - numSlides;
  2417. }
  2418. } // Force-append new slides during transition
  2419. // if difference between slides is more than 1
  2420. if (Math.abs(currDiff) > 1) {
  2421. this.updateCurrItem();
  2422. }
  2423. }
  2424. return Boolean(diff);
  2425. }
  2426. /**
  2427. * X position of the main scroll for the current slide
  2428. * (ignores position during dragging)
  2429. * @returns {number}
  2430. */
  2431. getCurrSlideX() {
  2432. return this.slideWidth * this._currPositionIndex;
  2433. }
  2434. /**
  2435. * Whether scroll position is shifted.
  2436. * For example, it will return true if the scroll is being dragged or animated.
  2437. * @returns {boolean}
  2438. */
  2439. isShifted() {
  2440. return this.x !== this.getCurrSlideX();
  2441. }
  2442. /**
  2443. * Update slides X positions and set their content
  2444. */
  2445. updateCurrItem() {
  2446. var _this$itemHolders$;
  2447. const {
  2448. pswp
  2449. } = this;
  2450. const positionDifference = this._prevPositionIndex - this._currPositionIndex;
  2451. if (!positionDifference) {
  2452. return;
  2453. }
  2454. this._prevPositionIndex = this._currPositionIndex;
  2455. pswp.currIndex = pswp.potentialIndex;
  2456. let diffAbs = Math.abs(positionDifference);
  2457. /** @type {ItemHolder | undefined} */
  2458. let tempHolder;
  2459. if (diffAbs >= 3) {
  2460. this._containerShiftIndex += positionDifference + (positionDifference > 0 ? -3 : 3);
  2461. diffAbs = 3; // If slides are changed by 3 screens or more - clean up previous slides
  2462. this.itemHolders.forEach(itemHolder => {
  2463. var _itemHolder$slide;
  2464. (_itemHolder$slide = itemHolder.slide) === null || _itemHolder$slide === void 0 || _itemHolder$slide.destroy();
  2465. itemHolder.slide = undefined;
  2466. });
  2467. }
  2468. for (let i = 0; i < diffAbs; i++) {
  2469. if (positionDifference > 0) {
  2470. tempHolder = this.itemHolders.shift();
  2471. if (tempHolder) {
  2472. this.itemHolders[2] = tempHolder; // move first to last
  2473. this._containerShiftIndex++;
  2474. setTransform(tempHolder.el, (this._containerShiftIndex + 2) * this.slideWidth);
  2475. pswp.setContent(tempHolder, pswp.currIndex - diffAbs + i + 2);
  2476. }
  2477. } else {
  2478. tempHolder = this.itemHolders.pop();
  2479. if (tempHolder) {
  2480. this.itemHolders.unshift(tempHolder); // move last to first
  2481. this._containerShiftIndex--;
  2482. setTransform(tempHolder.el, this._containerShiftIndex * this.slideWidth);
  2483. pswp.setContent(tempHolder, pswp.currIndex + diffAbs - i - 2);
  2484. }
  2485. }
  2486. } // Reset transfrom every 50ish navigations in one direction.
  2487. //
  2488. // Otherwise transform will keep growing indefinitely,
  2489. // which might cause issues as browsers have a maximum transform limit.
  2490. // I wasn't able to reach it, but just to be safe.
  2491. // This should not cause noticable lag.
  2492. if (Math.abs(this._containerShiftIndex) > 50 && !this.isShifted()) {
  2493. this.resetPosition();
  2494. this.resize();
  2495. } // Pan transition might be running (and consntantly updating pan position)
  2496. pswp.animations.stopAllPan();
  2497. this.itemHolders.forEach((itemHolder, i) => {
  2498. if (itemHolder.slide) {
  2499. // Slide in the 2nd holder is always active
  2500. itemHolder.slide.setIsActive(i === 1);
  2501. }
  2502. });
  2503. pswp.currSlide = (_this$itemHolders$ = this.itemHolders[1]) === null || _this$itemHolders$ === void 0 ? void 0 : _this$itemHolders$.slide;
  2504. pswp.contentLoader.updateLazy(positionDifference);
  2505. if (pswp.currSlide) {
  2506. pswp.currSlide.applyCurrentZoomPan();
  2507. }
  2508. pswp.dispatch('change');
  2509. }
  2510. /**
  2511. * Move the X position of the main scroll container
  2512. *
  2513. * @param {number} x
  2514. * @param {boolean} [dragging]
  2515. */
  2516. moveTo(x, dragging) {
  2517. if (!this.pswp.canLoop() && dragging) {
  2518. // Apply friction
  2519. let newSlideIndexOffset = (this.slideWidth * this._currPositionIndex - x) / this.slideWidth;
  2520. newSlideIndexOffset += this.pswp.currIndex;
  2521. const delta = Math.round(x - this.x);
  2522. if (newSlideIndexOffset < 0 && delta > 0 || newSlideIndexOffset >= this.pswp.getNumItems() - 1 && delta < 0) {
  2523. x = this.x + delta * MAIN_SCROLL_END_FRICTION;
  2524. }
  2525. }
  2526. this.x = x;
  2527. if (this.pswp.container) {
  2528. setTransform(this.pswp.container, x);
  2529. }
  2530. this.pswp.dispatch('moveMainScroll', {
  2531. x,
  2532. dragging: dragging !== null && dragging !== void 0 ? dragging : false
  2533. });
  2534. }
  2535. }
  2536. /** @typedef {import('./photoswipe.js').default} PhotoSwipe */
  2537. /**
  2538. * @template T
  2539. * @typedef {import('./types.js').Methods<T>} Methods<T>
  2540. */
  2541. const KeyboardKeyCodesMap = {
  2542. Escape: 27,
  2543. z: 90,
  2544. ArrowLeft: 37,
  2545. ArrowUp: 38,
  2546. ArrowRight: 39,
  2547. ArrowDown: 40,
  2548. Tab: 9
  2549. };
  2550. /**
  2551. * @template {keyof KeyboardKeyCodesMap} T
  2552. * @param {T} key
  2553. * @param {boolean} isKeySupported
  2554. * @returns {T | number | undefined}
  2555. */
  2556. const getKeyboardEventKey = (key, isKeySupported) => {
  2557. return isKeySupported ? key : KeyboardKeyCodesMap[key];
  2558. };
  2559. /**
  2560. * - Manages keyboard shortcuts.
  2561. * - Helps trap focus within photoswipe.
  2562. */
  2563. class Keyboard {
  2564. /**
  2565. * @param {PhotoSwipe} pswp
  2566. */
  2567. constructor(pswp) {
  2568. this.pswp = pswp;
  2569. /** @private */
  2570. this._wasFocused = false;
  2571. pswp.on('bindEvents', () => {
  2572. if (pswp.options.trapFocus) {
  2573. // Dialog was likely opened by keyboard if initial point is not defined
  2574. if (!pswp.options.initialPointerPos) {
  2575. // focus causes layout,
  2576. // which causes lag during the animation,
  2577. // that's why we delay it until the opener transition ends
  2578. this._focusRoot();
  2579. }
  2580. pswp.events.add(document, 'focusin',
  2581. /** @type EventListener */
  2582. this._onFocusIn.bind(this));
  2583. }
  2584. pswp.events.add(document, 'keydown',
  2585. /** @type EventListener */
  2586. this._onKeyDown.bind(this));
  2587. });
  2588. const lastActiveElement =
  2589. /** @type {HTMLElement} */
  2590. document.activeElement;
  2591. pswp.on('destroy', () => {
  2592. if (pswp.options.returnFocus && lastActiveElement && this._wasFocused) {
  2593. lastActiveElement.focus();
  2594. }
  2595. });
  2596. }
  2597. /** @private */
  2598. _focusRoot() {
  2599. if (!this._wasFocused && this.pswp.element) {
  2600. this.pswp.element.focus();
  2601. this._wasFocused = true;
  2602. }
  2603. }
  2604. /**
  2605. * @private
  2606. * @param {KeyboardEvent} e
  2607. */
  2608. _onKeyDown(e) {
  2609. const {
  2610. pswp
  2611. } = this;
  2612. if (pswp.dispatch('keydown', {
  2613. originalEvent: e
  2614. }).defaultPrevented) {
  2615. return;
  2616. }
  2617. if (specialKeyUsed(e)) {
  2618. // don't do anything if special key pressed
  2619. // to prevent from overriding default browser actions
  2620. // for example, in Chrome on Mac cmd+arrow-left returns to previous page
  2621. return;
  2622. }
  2623. /** @type {Methods<PhotoSwipe> | undefined} */
  2624. let keydownAction;
  2625. /** @type {'x' | 'y' | undefined} */
  2626. let axis;
  2627. let isForward = false;
  2628. const isKeySupported = ('key' in e);
  2629. switch (isKeySupported ? e.key : e.keyCode) {
  2630. case getKeyboardEventKey('Escape', isKeySupported):
  2631. if (pswp.options.escKey) {
  2632. keydownAction = 'close';
  2633. }
  2634. break;
  2635. case getKeyboardEventKey('z', isKeySupported):
  2636. keydownAction = 'toggleZoom';
  2637. break;
  2638. case getKeyboardEventKey('ArrowLeft', isKeySupported):
  2639. axis = 'x';
  2640. break;
  2641. case getKeyboardEventKey('ArrowUp', isKeySupported):
  2642. axis = 'y';
  2643. break;
  2644. case getKeyboardEventKey('ArrowRight', isKeySupported):
  2645. axis = 'x';
  2646. isForward = true;
  2647. break;
  2648. case getKeyboardEventKey('ArrowDown', isKeySupported):
  2649. isForward = true;
  2650. axis = 'y';
  2651. break;
  2652. case getKeyboardEventKey('Tab', isKeySupported):
  2653. this._focusRoot();
  2654. break;
  2655. } // if left/right/top/bottom key
  2656. if (axis) {
  2657. // prevent page scroll
  2658. e.preventDefault();
  2659. const {
  2660. currSlide
  2661. } = pswp;
  2662. if (pswp.options.arrowKeys && axis === 'x' && pswp.getNumItems() > 1) {
  2663. keydownAction = isForward ? 'next' : 'prev';
  2664. } else if (currSlide && currSlide.currZoomLevel > currSlide.zoomLevels.fit) {
  2665. // up/down arrow keys pan the image vertically
  2666. // left/right arrow keys pan horizontally.
  2667. // Unless there is only one image,
  2668. // or arrowKeys option is disabled
  2669. currSlide.pan[axis] += isForward ? -80 : 80;
  2670. currSlide.panTo(currSlide.pan.x, currSlide.pan.y);
  2671. }
  2672. }
  2673. if (keydownAction) {
  2674. e.preventDefault(); // @ts-ignore
  2675. pswp[keydownAction]();
  2676. }
  2677. }
  2678. /**
  2679. * Trap focus inside photoswipe
  2680. *
  2681. * @private
  2682. * @param {FocusEvent} e
  2683. */
  2684. _onFocusIn(e) {
  2685. const {
  2686. template
  2687. } = this.pswp;
  2688. if (template && document !== e.target && template !== e.target && !template.contains(
  2689. /** @type {Node} */
  2690. e.target)) {
  2691. // focus root element
  2692. template.focus();
  2693. }
  2694. }
  2695. }
  2696. const DEFAULT_EASING = 'cubic-bezier(.4,0,.22,1)';
  2697. /** @typedef {import('./animations.js').SharedAnimationProps} SharedAnimationProps */
  2698. /** @typedef {Object} DefaultCssAnimationProps
  2699. *
  2700. * @prop {HTMLElement} target
  2701. * @prop {number} [duration]
  2702. * @prop {string} [easing]
  2703. * @prop {string} [transform]
  2704. * @prop {string} [opacity]
  2705. * */
  2706. /** @typedef {SharedAnimationProps & DefaultCssAnimationProps} CssAnimationProps */
  2707. /**
  2708. * Runs CSS transition.
  2709. */
  2710. class CSSAnimation {
  2711. /**
  2712. * onComplete can be unpredictable, be careful about current state
  2713. *
  2714. * @param {CssAnimationProps} props
  2715. */
  2716. constructor(props) {
  2717. var _props$prop;
  2718. this.props = props;
  2719. const {
  2720. target,
  2721. onComplete,
  2722. transform,
  2723. onFinish = () => {},
  2724. duration = 333,
  2725. easing = DEFAULT_EASING
  2726. } = props;
  2727. this.onFinish = onFinish; // support only transform and opacity
  2728. const prop = transform ? 'transform' : 'opacity';
  2729. const propValue = (_props$prop = props[prop]) !== null && _props$prop !== void 0 ? _props$prop : '';
  2730. /** @private */
  2731. this._target = target;
  2732. /** @private */
  2733. this._onComplete = onComplete;
  2734. /** @private */
  2735. this._finished = false;
  2736. /** @private */
  2737. this._onTransitionEnd = this._onTransitionEnd.bind(this); // Using timeout hack to make sure that animation
  2738. // starts even if the animated property was changed recently,
  2739. // otherwise transitionend might not fire or transition won't start.
  2740. // https://drafts.csswg.org/css-transitions/#starting
  2741. //
  2742. // ¯\_(ツ)_/¯
  2743. /** @private */
  2744. this._helperTimeout = setTimeout(() => {
  2745. setTransitionStyle(target, prop, duration, easing);
  2746. this._helperTimeout = setTimeout(() => {
  2747. target.addEventListener('transitionend', this._onTransitionEnd, false);
  2748. target.addEventListener('transitioncancel', this._onTransitionEnd, false); // Safari occasionally does not emit transitionend event
  2749. // if element property was modified during the transition,
  2750. // which may be caused by resize or third party component,
  2751. // using timeout as a safety fallback
  2752. this._helperTimeout = setTimeout(() => {
  2753. this._finalizeAnimation();
  2754. }, duration + 500);
  2755. target.style[prop] = propValue;
  2756. }, 30); // Do not reduce this number
  2757. }, 0);
  2758. }
  2759. /**
  2760. * @private
  2761. * @param {TransitionEvent} e
  2762. */
  2763. _onTransitionEnd(e) {
  2764. if (e.target === this._target) {
  2765. this._finalizeAnimation();
  2766. }
  2767. }
  2768. /**
  2769. * @private
  2770. */
  2771. _finalizeAnimation() {
  2772. if (!this._finished) {
  2773. this._finished = true;
  2774. this.onFinish();
  2775. if (this._onComplete) {
  2776. this._onComplete();
  2777. }
  2778. }
  2779. } // Destroy is called automatically onFinish
  2780. destroy() {
  2781. if (this._helperTimeout) {
  2782. clearTimeout(this._helperTimeout);
  2783. }
  2784. removeTransitionStyle(this._target);
  2785. this._target.removeEventListener('transitionend', this._onTransitionEnd, false);
  2786. this._target.removeEventListener('transitioncancel', this._onTransitionEnd, false);
  2787. if (!this._finished) {
  2788. this._finalizeAnimation();
  2789. }
  2790. }
  2791. }
  2792. const DEFAULT_NATURAL_FREQUENCY = 12;
  2793. const DEFAULT_DAMPING_RATIO = 0.75;
  2794. /**
  2795. * Spring easing helper
  2796. */
  2797. class SpringEaser {
  2798. /**
  2799. * @param {number} initialVelocity Initial velocity, px per ms.
  2800. *
  2801. * @param {number} [dampingRatio]
  2802. * Determines how bouncy animation will be.
  2803. * From 0 to 1, 0 - always overshoot, 1 - do not overshoot.
  2804. * "overshoot" refers to part of animation that
  2805. * goes beyond the final value.
  2806. *
  2807. * @param {number} [naturalFrequency]
  2808. * Determines how fast animation will slow down.
  2809. * The higher value - the stiffer the transition will be,
  2810. * and the faster it will slow down.
  2811. * Recommended value from 10 to 50
  2812. */
  2813. constructor(initialVelocity, dampingRatio, naturalFrequency) {
  2814. this.velocity = initialVelocity * 1000; // convert to "pixels per second"
  2815. // https://en.wikipedia.org/wiki/Damping_ratio
  2816. this._dampingRatio = dampingRatio || DEFAULT_DAMPING_RATIO; // https://en.wikipedia.org/wiki/Natural_frequency
  2817. this._naturalFrequency = naturalFrequency || DEFAULT_NATURAL_FREQUENCY;
  2818. this._dampedFrequency = this._naturalFrequency;
  2819. if (this._dampingRatio < 1) {
  2820. this._dampedFrequency *= Math.sqrt(1 - this._dampingRatio * this._dampingRatio);
  2821. }
  2822. }
  2823. /**
  2824. * @param {number} deltaPosition Difference between current and end position of the animation
  2825. * @param {number} deltaTime Frame duration in milliseconds
  2826. *
  2827. * @returns {number} Displacement, relative to the end position.
  2828. */
  2829. easeFrame(deltaPosition, deltaTime) {
  2830. // Inspired by Apple Webkit and Android spring function implementation
  2831. // https://en.wikipedia.org/wiki/Oscillation
  2832. // https://en.wikipedia.org/wiki/Damping_ratio
  2833. // we ignore mass (assume that it's 1kg)
  2834. let displacement = 0;
  2835. let coeff;
  2836. deltaTime /= 1000;
  2837. const naturalDumpingPow = Math.E ** (-this._dampingRatio * this._naturalFrequency * deltaTime);
  2838. if (this._dampingRatio === 1) {
  2839. coeff = this.velocity + this._naturalFrequency * deltaPosition;
  2840. displacement = (deltaPosition + coeff * deltaTime) * naturalDumpingPow;
  2841. this.velocity = displacement * -this._naturalFrequency + coeff * naturalDumpingPow;
  2842. } else if (this._dampingRatio < 1) {
  2843. coeff = 1 / this._dampedFrequency * (this._dampingRatio * this._naturalFrequency * deltaPosition + this.velocity);
  2844. const dumpedFCos = Math.cos(this._dampedFrequency * deltaTime);
  2845. const dumpedFSin = Math.sin(this._dampedFrequency * deltaTime);
  2846. displacement = naturalDumpingPow * (deltaPosition * dumpedFCos + coeff * dumpedFSin);
  2847. this.velocity = displacement * -this._naturalFrequency * this._dampingRatio + naturalDumpingPow * (-this._dampedFrequency * deltaPosition * dumpedFSin + this._dampedFrequency * coeff * dumpedFCos);
  2848. } // Overdamped (>1) damping ratio is not supported
  2849. return displacement;
  2850. }
  2851. }
  2852. /** @typedef {import('./animations.js').SharedAnimationProps} SharedAnimationProps */
  2853. /**
  2854. * @typedef {Object} DefaultSpringAnimationProps
  2855. *
  2856. * @prop {number} start
  2857. * @prop {number} end
  2858. * @prop {number} velocity
  2859. * @prop {number} [dampingRatio]
  2860. * @prop {number} [naturalFrequency]
  2861. * @prop {(end: number) => void} onUpdate
  2862. */
  2863. /** @typedef {SharedAnimationProps & DefaultSpringAnimationProps} SpringAnimationProps */
  2864. class SpringAnimation {
  2865. /**
  2866. * @param {SpringAnimationProps} props
  2867. */
  2868. constructor(props) {
  2869. this.props = props;
  2870. this._raf = 0;
  2871. const {
  2872. start,
  2873. end,
  2874. velocity,
  2875. onUpdate,
  2876. onComplete,
  2877. onFinish = () => {},
  2878. dampingRatio,
  2879. naturalFrequency
  2880. } = props;
  2881. this.onFinish = onFinish;
  2882. const easer = new SpringEaser(velocity, dampingRatio, naturalFrequency);
  2883. let prevTime = Date.now();
  2884. let deltaPosition = start - end;
  2885. const animationLoop = () => {
  2886. if (this._raf) {
  2887. deltaPosition = easer.easeFrame(deltaPosition, Date.now() - prevTime); // Stop the animation if velocity is low and position is close to end
  2888. if (Math.abs(deltaPosition) < 1 && Math.abs(easer.velocity) < 50) {
  2889. // Finalize the animation
  2890. onUpdate(end);
  2891. if (onComplete) {
  2892. onComplete();
  2893. }
  2894. this.onFinish();
  2895. } else {
  2896. prevTime = Date.now();
  2897. onUpdate(deltaPosition + end);
  2898. this._raf = requestAnimationFrame(animationLoop);
  2899. }
  2900. }
  2901. };
  2902. this._raf = requestAnimationFrame(animationLoop);
  2903. } // Destroy is called automatically onFinish
  2904. destroy() {
  2905. if (this._raf >= 0) {
  2906. cancelAnimationFrame(this._raf);
  2907. }
  2908. this._raf = 0;
  2909. }
  2910. }
  2911. /** @typedef {import('./css-animation.js').CssAnimationProps} CssAnimationProps */
  2912. /** @typedef {import('./spring-animation.js').SpringAnimationProps} SpringAnimationProps */
  2913. /** @typedef {Object} SharedAnimationProps
  2914. * @prop {string} [name]
  2915. * @prop {boolean} [isPan]
  2916. * @prop {boolean} [isMainScroll]
  2917. * @prop {VoidFunction} [onComplete]
  2918. * @prop {VoidFunction} [onFinish]
  2919. */
  2920. /** @typedef {SpringAnimation | CSSAnimation} Animation */
  2921. /** @typedef {SpringAnimationProps | CssAnimationProps} AnimationProps */
  2922. /**
  2923. * Manages animations
  2924. */
  2925. class Animations {
  2926. constructor() {
  2927. /** @type {Animation[]} */
  2928. this.activeAnimations = [];
  2929. }
  2930. /**
  2931. * @param {SpringAnimationProps} props
  2932. */
  2933. startSpring(props) {
  2934. this._start(props, true);
  2935. }
  2936. /**
  2937. * @param {CssAnimationProps} props
  2938. */
  2939. startTransition(props) {
  2940. this._start(props);
  2941. }
  2942. /**
  2943. * @private
  2944. * @param {AnimationProps} props
  2945. * @param {boolean} [isSpring]
  2946. * @returns {Animation}
  2947. */
  2948. _start(props, isSpring) {
  2949. const animation = isSpring ? new SpringAnimation(
  2950. /** @type SpringAnimationProps */
  2951. props) : new CSSAnimation(
  2952. /** @type CssAnimationProps */
  2953. props);
  2954. this.activeAnimations.push(animation);
  2955. animation.onFinish = () => this.stop(animation);
  2956. return animation;
  2957. }
  2958. /**
  2959. * @param {Animation} animation
  2960. */
  2961. stop(animation) {
  2962. animation.destroy();
  2963. const index = this.activeAnimations.indexOf(animation);
  2964. if (index > -1) {
  2965. this.activeAnimations.splice(index, 1);
  2966. }
  2967. }
  2968. stopAll() {
  2969. // _stopAllAnimations
  2970. this.activeAnimations.forEach(animation => {
  2971. animation.destroy();
  2972. });
  2973. this.activeAnimations = [];
  2974. }
  2975. /**
  2976. * Stop all pan or zoom transitions
  2977. */
  2978. stopAllPan() {
  2979. this.activeAnimations = this.activeAnimations.filter(animation => {
  2980. if (animation.props.isPan) {
  2981. animation.destroy();
  2982. return false;
  2983. }
  2984. return true;
  2985. });
  2986. }
  2987. stopMainScroll() {
  2988. this.activeAnimations = this.activeAnimations.filter(animation => {
  2989. if (animation.props.isMainScroll) {
  2990. animation.destroy();
  2991. return false;
  2992. }
  2993. return true;
  2994. });
  2995. }
  2996. /**
  2997. * Returns true if main scroll transition is running
  2998. */
  2999. // isMainScrollRunning() {
  3000. // return this.activeAnimations.some((animation) => {
  3001. // return animation.props.isMainScroll;
  3002. // });
  3003. // }
  3004. /**
  3005. * Returns true if any pan or zoom transition is running
  3006. */
  3007. isPanRunning() {
  3008. return this.activeAnimations.some(animation => {
  3009. return animation.props.isPan;
  3010. });
  3011. }
  3012. }
  3013. /** @typedef {import('./photoswipe.js').default} PhotoSwipe */
  3014. /**
  3015. * Handles scroll wheel.
  3016. * Can pan and zoom current slide image.
  3017. */
  3018. class ScrollWheel {
  3019. /**
  3020. * @param {PhotoSwipe} pswp
  3021. */
  3022. constructor(pswp) {
  3023. this.pswp = pswp;
  3024. pswp.events.add(pswp.element, 'wheel',
  3025. /** @type EventListener */
  3026. this._onWheel.bind(this));
  3027. }
  3028. /**
  3029. * @private
  3030. * @param {WheelEvent} e
  3031. */
  3032. _onWheel(e) {
  3033. e.preventDefault();
  3034. const {
  3035. currSlide
  3036. } = this.pswp;
  3037. let {
  3038. deltaX,
  3039. deltaY
  3040. } = e;
  3041. if (!currSlide) {
  3042. return;
  3043. }
  3044. if (this.pswp.dispatch('wheel', {
  3045. originalEvent: e
  3046. }).defaultPrevented) {
  3047. return;
  3048. }
  3049. if (e.ctrlKey || this.pswp.options.wheelToZoom) {
  3050. // zoom
  3051. if (currSlide.isZoomable()) {
  3052. let zoomFactor = -deltaY;
  3053. if (e.deltaMode === 1
  3054. /* DOM_DELTA_LINE */
  3055. ) {
  3056. zoomFactor *= 0.05;
  3057. } else {
  3058. zoomFactor *= e.deltaMode ? 1 : 0.002;
  3059. }
  3060. zoomFactor = 2 ** zoomFactor;
  3061. const destZoomLevel = currSlide.currZoomLevel * zoomFactor;
  3062. currSlide.zoomTo(destZoomLevel, {
  3063. x: e.clientX,
  3064. y: e.clientY
  3065. });
  3066. }
  3067. } else {
  3068. // pan
  3069. if (currSlide.isPannable()) {
  3070. if (e.deltaMode === 1
  3071. /* DOM_DELTA_LINE */
  3072. ) {
  3073. // 18 - average line height
  3074. deltaX *= 18;
  3075. deltaY *= 18;
  3076. }
  3077. currSlide.panTo(currSlide.pan.x - deltaX, currSlide.pan.y - deltaY);
  3078. }
  3079. }
  3080. }
  3081. }
  3082. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  3083. /**
  3084. * @template T
  3085. * @typedef {import('../types.js').Methods<T>} Methods<T>
  3086. */
  3087. /**
  3088. * @typedef {Object} UIElementMarkupProps
  3089. * @prop {boolean} [isCustomSVG]
  3090. * @prop {string} inner
  3091. * @prop {string} [outlineID]
  3092. * @prop {number | string} [size]
  3093. */
  3094. /**
  3095. * @typedef {Object} UIElementData
  3096. * @prop {DefaultUIElements | string} [name]
  3097. * @prop {string} [className]
  3098. * @prop {UIElementMarkup} [html]
  3099. * @prop {boolean} [isButton]
  3100. * @prop {keyof HTMLElementTagNameMap} [tagName]
  3101. * @prop {string} [title]
  3102. * @prop {string} [ariaLabel]
  3103. * @prop {(element: HTMLElement, pswp: PhotoSwipe) => void} [onInit]
  3104. * @prop {Methods<PhotoSwipe> | ((e: MouseEvent, element: HTMLElement, pswp: PhotoSwipe) => void)} [onClick]
  3105. * @prop {'bar' | 'wrapper' | 'root'} [appendTo]
  3106. * @prop {number} [order]
  3107. */
  3108. /** @typedef {'arrowPrev' | 'arrowNext' | 'close' | 'zoom' | 'counter'} DefaultUIElements */
  3109. /** @typedef {string | UIElementMarkupProps} UIElementMarkup */
  3110. /**
  3111. * @param {UIElementMarkup} [htmlData]
  3112. * @returns {string}
  3113. */
  3114. function addElementHTML(htmlData) {
  3115. if (typeof htmlData === 'string') {
  3116. // Allow developers to provide full svg,
  3117. // For example:
  3118. // <svg viewBox="0 0 32 32" width="32" height="32" aria-hidden="true" class="pswp__icn">
  3119. // <path d="..." />
  3120. // <circle ... />
  3121. // </svg>
  3122. // Can also be any HTML string.
  3123. return htmlData;
  3124. }
  3125. if (!htmlData || !htmlData.isCustomSVG) {
  3126. return '';
  3127. }
  3128. const svgData = htmlData;
  3129. let out = '<svg aria-hidden="true" class="pswp__icn" viewBox="0 0 %d %d" width="%d" height="%d">'; // replace all %d with size
  3130. out = out.split('%d').join(
  3131. /** @type {string} */
  3132. svgData.size || 32); // Icons may contain outline/shadow,
  3133. // to make it we "clone" base icon shape and add border to it.
  3134. // Icon itself and border are styled via CSS.
  3135. //
  3136. // Property shadowID defines ID of element that should be cloned.
  3137. if (svgData.outlineID) {
  3138. out += '<use class="pswp__icn-shadow" xlink:href="#' + svgData.outlineID + '"/>';
  3139. }
  3140. out += svgData.inner;
  3141. out += '</svg>';
  3142. return out;
  3143. }
  3144. class UIElement {
  3145. /**
  3146. * @param {PhotoSwipe} pswp
  3147. * @param {UIElementData} data
  3148. */
  3149. constructor(pswp, data) {
  3150. var _container;
  3151. const name = data.name || data.className;
  3152. let elementHTML = data.html; // @ts-expect-error lookup only by `data.name` maybe?
  3153. if (pswp.options[name] === false) {
  3154. // exit if element is disabled from options
  3155. return;
  3156. } // Allow to override SVG icons from options
  3157. // @ts-expect-error lookup only by `data.name` maybe?
  3158. if (typeof pswp.options[name + 'SVG'] === 'string') {
  3159. // arrowPrevSVG
  3160. // arrowNextSVG
  3161. // closeSVG
  3162. // zoomSVG
  3163. // @ts-expect-error lookup only by `data.name` maybe?
  3164. elementHTML = pswp.options[name + 'SVG'];
  3165. }
  3166. pswp.dispatch('uiElementCreate', {
  3167. data
  3168. });
  3169. let className = '';
  3170. if (data.isButton) {
  3171. className += 'pswp__button ';
  3172. className += data.className || `pswp__button--${data.name}`;
  3173. } else {
  3174. className += data.className || `pswp__${data.name}`;
  3175. }
  3176. let tagName = data.isButton ? data.tagName || 'button' : data.tagName || 'div';
  3177. tagName =
  3178. /** @type {keyof HTMLElementTagNameMap} */
  3179. tagName.toLowerCase();
  3180. /** @type {HTMLElement} */
  3181. const element = createElement(className, tagName);
  3182. if (data.isButton) {
  3183. if (tagName === 'button') {
  3184. /** @type {HTMLButtonElement} */
  3185. element.type = 'button';
  3186. }
  3187. let {
  3188. title
  3189. } = data;
  3190. const {
  3191. ariaLabel
  3192. } = data; // @ts-expect-error lookup only by `data.name` maybe?
  3193. if (typeof pswp.options[name + 'Title'] === 'string') {
  3194. // @ts-expect-error lookup only by `data.name` maybe?
  3195. title = pswp.options[name + 'Title'];
  3196. }
  3197. if (title) {
  3198. element.title = title;
  3199. }
  3200. const ariaText = ariaLabel || title;
  3201. if (ariaText) {
  3202. element.setAttribute('aria-label', ariaText);
  3203. }
  3204. }
  3205. element.innerHTML = addElementHTML(elementHTML);
  3206. if (data.onInit) {
  3207. data.onInit(element, pswp);
  3208. }
  3209. if (data.onClick) {
  3210. element.onclick = e => {
  3211. if (typeof data.onClick === 'string') {
  3212. // @ts-ignore
  3213. pswp[data.onClick]();
  3214. } else if (typeof data.onClick === 'function') {
  3215. data.onClick(e, element, pswp);
  3216. }
  3217. };
  3218. } // Top bar is default position
  3219. const appendTo = data.appendTo || 'bar';
  3220. /** @type {HTMLElement | undefined} root element by default */
  3221. let container = pswp.element;
  3222. if (appendTo === 'bar') {
  3223. if (!pswp.topBar) {
  3224. pswp.topBar = createElement('pswp__top-bar pswp__hide-on-close', 'div', pswp.scrollWrap);
  3225. }
  3226. container = pswp.topBar;
  3227. } else {
  3228. // element outside of top bar gets a secondary class
  3229. // that makes element fade out on close
  3230. element.classList.add('pswp__hide-on-close');
  3231. if (appendTo === 'wrapper') {
  3232. container = pswp.scrollWrap;
  3233. }
  3234. }
  3235. (_container = container) === null || _container === void 0 || _container.appendChild(pswp.applyFilters('uiElement', element, data));
  3236. }
  3237. }
  3238. /*
  3239. Backward and forward arrow buttons
  3240. */
  3241. /** @typedef {import('./ui-element.js').UIElementData} UIElementData */
  3242. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  3243. /**
  3244. *
  3245. * @param {HTMLElement} element
  3246. * @param {PhotoSwipe} pswp
  3247. * @param {boolean} [isNextButton]
  3248. */
  3249. function initArrowButton(element, pswp, isNextButton) {
  3250. element.classList.add('pswp__button--arrow'); // TODO: this should point to a unique id for this instance
  3251. element.setAttribute('aria-controls', 'pswp__items');
  3252. pswp.on('change', () => {
  3253. if (!pswp.options.loop) {
  3254. if (isNextButton) {
  3255. /** @type {HTMLButtonElement} */
  3256. element.disabled = !(pswp.currIndex < pswp.getNumItems() - 1);
  3257. } else {
  3258. /** @type {HTMLButtonElement} */
  3259. element.disabled = !(pswp.currIndex > 0);
  3260. }
  3261. }
  3262. });
  3263. }
  3264. /** @type {UIElementData} */
  3265. const arrowPrev = {
  3266. name: 'arrowPrev',
  3267. className: 'pswp__button--arrow--prev',
  3268. title: 'Previous',
  3269. order: 10,
  3270. isButton: true,
  3271. appendTo: 'wrapper',
  3272. html: {
  3273. isCustomSVG: true,
  3274. size: 60,
  3275. inner: '<path d="M29 43l-3 3-16-16 16-16 3 3-13 13 13 13z" id="pswp__icn-arrow"/>',
  3276. outlineID: 'pswp__icn-arrow'
  3277. },
  3278. onClick: 'prev',
  3279. onInit: initArrowButton
  3280. };
  3281. /** @type {UIElementData} */
  3282. const arrowNext = {
  3283. name: 'arrowNext',
  3284. className: 'pswp__button--arrow--next',
  3285. title: 'Next',
  3286. order: 11,
  3287. isButton: true,
  3288. appendTo: 'wrapper',
  3289. html: {
  3290. isCustomSVG: true,
  3291. size: 60,
  3292. inner: '<use xlink:href="#pswp__icn-arrow"/>',
  3293. outlineID: 'pswp__icn-arrow'
  3294. },
  3295. onClick: 'next',
  3296. onInit: (el, pswp) => {
  3297. initArrowButton(el, pswp, true);
  3298. }
  3299. };
  3300. /** @type {import('./ui-element.js').UIElementData} UIElementData */
  3301. const closeButton = {
  3302. name: 'close',
  3303. title: 'Close',
  3304. order: 20,
  3305. isButton: true,
  3306. html: {
  3307. isCustomSVG: true,
  3308. inner: '<path d="M24 10l-2-2-6 6-6-6-2 2 6 6-6 6 2 2 6-6 6 6 2-2-6-6z" id="pswp__icn-close"/>',
  3309. outlineID: 'pswp__icn-close'
  3310. },
  3311. onClick: 'close'
  3312. };
  3313. /** @type {import('./ui-element.js').UIElementData} UIElementData */
  3314. const zoomButton = {
  3315. name: 'zoom',
  3316. title: 'Zoom',
  3317. order: 10,
  3318. isButton: true,
  3319. html: {
  3320. isCustomSVG: true,
  3321. // eslint-disable-next-line max-len
  3322. inner: '<path d="M17.426 19.926a6 6 0 1 1 1.5-1.5L23 22.5 21.5 24l-4.074-4.074z" id="pswp__icn-zoom"/>' + '<path fill="currentColor" class="pswp__zoom-icn-bar-h" d="M11 16v-2h6v2z"/>' + '<path fill="currentColor" class="pswp__zoom-icn-bar-v" d="M13 12h2v6h-2z"/>',
  3323. outlineID: 'pswp__icn-zoom'
  3324. },
  3325. onClick: 'toggleZoom'
  3326. };
  3327. /** @type {import('./ui-element.js').UIElementData} UIElementData */
  3328. const loadingIndicator = {
  3329. name: 'preloader',
  3330. appendTo: 'bar',
  3331. order: 7,
  3332. html: {
  3333. isCustomSVG: true,
  3334. // eslint-disable-next-line max-len
  3335. inner: '<path fill-rule="evenodd" clip-rule="evenodd" d="M21.2 16a5.2 5.2 0 1 1-5.2-5.2V8a8 8 0 1 0 8 8h-2.8Z" id="pswp__icn-loading"/>',
  3336. outlineID: 'pswp__icn-loading'
  3337. },
  3338. onInit: (indicatorElement, pswp) => {
  3339. /** @type {boolean | undefined} */
  3340. let isVisible;
  3341. /** @type {NodeJS.Timeout | null} */
  3342. let delayTimeout = null;
  3343. /**
  3344. * @param {string} className
  3345. * @param {boolean} add
  3346. */
  3347. const toggleIndicatorClass = (className, add) => {
  3348. indicatorElement.classList.toggle('pswp__preloader--' + className, add);
  3349. };
  3350. /**
  3351. * @param {boolean} visible
  3352. */
  3353. const setIndicatorVisibility = visible => {
  3354. if (isVisible !== visible) {
  3355. isVisible = visible;
  3356. toggleIndicatorClass('active', visible);
  3357. }
  3358. };
  3359. const updatePreloaderVisibility = () => {
  3360. var _pswp$currSlide;
  3361. if (!((_pswp$currSlide = pswp.currSlide) !== null && _pswp$currSlide !== void 0 && _pswp$currSlide.content.isLoading())) {
  3362. setIndicatorVisibility(false);
  3363. if (delayTimeout) {
  3364. clearTimeout(delayTimeout);
  3365. delayTimeout = null;
  3366. }
  3367. return;
  3368. }
  3369. if (!delayTimeout) {
  3370. // display loading indicator with delay
  3371. delayTimeout = setTimeout(() => {
  3372. var _pswp$currSlide2;
  3373. setIndicatorVisibility(Boolean((_pswp$currSlide2 = pswp.currSlide) === null || _pswp$currSlide2 === void 0 ? void 0 : _pswp$currSlide2.content.isLoading()));
  3374. delayTimeout = null;
  3375. }, pswp.options.preloaderDelay);
  3376. }
  3377. };
  3378. pswp.on('change', updatePreloaderVisibility);
  3379. pswp.on('loadComplete', e => {
  3380. if (pswp.currSlide === e.slide) {
  3381. updatePreloaderVisibility();
  3382. }
  3383. }); // expose the method
  3384. if (pswp.ui) {
  3385. pswp.ui.updatePreloaderVisibility = updatePreloaderVisibility;
  3386. }
  3387. }
  3388. };
  3389. /** @type {import('./ui-element.js').UIElementData} UIElementData */
  3390. const counterIndicator = {
  3391. name: 'counter',
  3392. order: 5,
  3393. onInit: (counterElement, pswp) => {
  3394. pswp.on('change', () => {
  3395. counterElement.innerText = pswp.currIndex + 1 + pswp.options.indexIndicatorSep + pswp.getNumItems();
  3396. });
  3397. }
  3398. };
  3399. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  3400. /** @typedef {import('./ui-element.js').UIElementData} UIElementData */
  3401. /**
  3402. * Set special class on element when image is zoomed.
  3403. *
  3404. * By default, it is used to adjust
  3405. * zoom icon and zoom cursor via CSS.
  3406. *
  3407. * @param {HTMLElement} el
  3408. * @param {boolean} isZoomedIn
  3409. */
  3410. function setZoomedIn(el, isZoomedIn) {
  3411. el.classList.toggle('pswp--zoomed-in', isZoomedIn);
  3412. }
  3413. class UI {
  3414. /**
  3415. * @param {PhotoSwipe} pswp
  3416. */
  3417. constructor(pswp) {
  3418. this.pswp = pswp;
  3419. this.isRegistered = false;
  3420. /** @type {UIElementData[]} */
  3421. this.uiElementsData = [];
  3422. /** @type {(UIElement | UIElementData)[]} */
  3423. this.items = [];
  3424. /** @type {() => void} */
  3425. this.updatePreloaderVisibility = () => {};
  3426. /**
  3427. * @private
  3428. * @type {number | undefined}
  3429. */
  3430. this._lastUpdatedZoomLevel = undefined;
  3431. }
  3432. init() {
  3433. const {
  3434. pswp
  3435. } = this;
  3436. this.isRegistered = false;
  3437. this.uiElementsData = [closeButton, arrowPrev, arrowNext, zoomButton, loadingIndicator, counterIndicator];
  3438. pswp.dispatch('uiRegister'); // sort by order
  3439. this.uiElementsData.sort((a, b) => {
  3440. // default order is 0
  3441. return (a.order || 0) - (b.order || 0);
  3442. });
  3443. this.items = [];
  3444. this.isRegistered = true;
  3445. this.uiElementsData.forEach(uiElementData => {
  3446. this.registerElement(uiElementData);
  3447. });
  3448. pswp.on('change', () => {
  3449. var _pswp$element;
  3450. (_pswp$element = pswp.element) === null || _pswp$element === void 0 || _pswp$element.classList.toggle('pswp--one-slide', pswp.getNumItems() === 1);
  3451. });
  3452. pswp.on('zoomPanUpdate', () => this._onZoomPanUpdate());
  3453. }
  3454. /**
  3455. * @param {UIElementData} elementData
  3456. */
  3457. registerElement(elementData) {
  3458. if (this.isRegistered) {
  3459. this.items.push(new UIElement(this.pswp, elementData));
  3460. } else {
  3461. this.uiElementsData.push(elementData);
  3462. }
  3463. }
  3464. /**
  3465. * Fired each time zoom or pan position is changed.
  3466. * Update classes that control visibility of zoom button and cursor icon.
  3467. *
  3468. * @private
  3469. */
  3470. _onZoomPanUpdate() {
  3471. const {
  3472. template,
  3473. currSlide,
  3474. options
  3475. } = this.pswp;
  3476. if (this.pswp.opener.isClosing || !template || !currSlide) {
  3477. return;
  3478. }
  3479. let {
  3480. currZoomLevel
  3481. } = currSlide; // if not open yet - check against initial zoom level
  3482. if (!this.pswp.opener.isOpen) {
  3483. currZoomLevel = currSlide.zoomLevels.initial;
  3484. }
  3485. if (currZoomLevel === this._lastUpdatedZoomLevel) {
  3486. return;
  3487. }
  3488. this._lastUpdatedZoomLevel = currZoomLevel;
  3489. const currZoomLevelDiff = currSlide.zoomLevels.initial - currSlide.zoomLevels.secondary; // Initial and secondary zoom levels are almost equal
  3490. if (Math.abs(currZoomLevelDiff) < 0.01 || !currSlide.isZoomable()) {
  3491. // disable zoom
  3492. setZoomedIn(template, false);
  3493. template.classList.remove('pswp--zoom-allowed');
  3494. return;
  3495. }
  3496. template.classList.add('pswp--zoom-allowed');
  3497. const potentialZoomLevel = currZoomLevel === currSlide.zoomLevels.initial ? currSlide.zoomLevels.secondary : currSlide.zoomLevels.initial;
  3498. setZoomedIn(template, potentialZoomLevel <= currZoomLevel);
  3499. if (options.imageClickAction === 'zoom' || options.imageClickAction === 'zoom-or-close') {
  3500. template.classList.add('pswp--click-to-zoom');
  3501. }
  3502. }
  3503. }
  3504. /** @typedef {import('./slide.js').SlideData} SlideData */
  3505. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  3506. /** @typedef {{ x: number; y: number; w: number; innerRect?: { w: number; h: number; x: number; y: number } }} Bounds */
  3507. /**
  3508. * @param {HTMLElement} el
  3509. * @returns Bounds
  3510. */
  3511. function getBoundsByElement(el) {
  3512. const thumbAreaRect = el.getBoundingClientRect();
  3513. return {
  3514. x: thumbAreaRect.left,
  3515. y: thumbAreaRect.top,
  3516. w: thumbAreaRect.width
  3517. };
  3518. }
  3519. /**
  3520. * @param {HTMLElement} el
  3521. * @param {number} imageWidth
  3522. * @param {number} imageHeight
  3523. * @returns Bounds
  3524. */
  3525. function getCroppedBoundsByElement(el, imageWidth, imageHeight) {
  3526. const thumbAreaRect = el.getBoundingClientRect(); // fill image into the area
  3527. // (do they same as object-fit:cover does to retrieve coordinates)
  3528. const hRatio = thumbAreaRect.width / imageWidth;
  3529. const vRatio = thumbAreaRect.height / imageHeight;
  3530. const fillZoomLevel = hRatio > vRatio ? hRatio : vRatio;
  3531. const offsetX = (thumbAreaRect.width - imageWidth * fillZoomLevel) / 2;
  3532. const offsetY = (thumbAreaRect.height - imageHeight * fillZoomLevel) / 2;
  3533. /**
  3534. * Coordinates of the image,
  3535. * as if it was not cropped,
  3536. * height is calculated automatically
  3537. *
  3538. * @type {Bounds}
  3539. */
  3540. const bounds = {
  3541. x: thumbAreaRect.left + offsetX,
  3542. y: thumbAreaRect.top + offsetY,
  3543. w: imageWidth * fillZoomLevel
  3544. }; // Coordinates of inner crop area
  3545. // relative to the image
  3546. bounds.innerRect = {
  3547. w: thumbAreaRect.width,
  3548. h: thumbAreaRect.height,
  3549. x: offsetX,
  3550. y: offsetY
  3551. };
  3552. return bounds;
  3553. }
  3554. /**
  3555. * Get dimensions of thumbnail image
  3556. * (click on which opens photoswipe or closes photoswipe to)
  3557. *
  3558. * @param {number} index
  3559. * @param {SlideData} itemData
  3560. * @param {PhotoSwipe} instance PhotoSwipe instance
  3561. * @returns {Bounds | undefined}
  3562. */
  3563. function getThumbBounds(index, itemData, instance) {
  3564. // legacy event, before filters were introduced
  3565. const event = instance.dispatch('thumbBounds', {
  3566. index,
  3567. itemData,
  3568. instance
  3569. }); // @ts-expect-error
  3570. if (event.thumbBounds) {
  3571. // @ts-expect-error
  3572. return event.thumbBounds;
  3573. }
  3574. const {
  3575. element
  3576. } = itemData;
  3577. /** @type {Bounds | undefined} */
  3578. let thumbBounds;
  3579. /** @type {HTMLElement | null | undefined} */
  3580. let thumbnail;
  3581. if (element && instance.options.thumbSelector !== false) {
  3582. const thumbSelector = instance.options.thumbSelector || 'img';
  3583. thumbnail = element.matches(thumbSelector) ? element :
  3584. /** @type {HTMLElement | null} */
  3585. element.querySelector(thumbSelector);
  3586. }
  3587. thumbnail = instance.applyFilters('thumbEl', thumbnail, itemData, index);
  3588. if (thumbnail) {
  3589. if (!itemData.thumbCropped) {
  3590. thumbBounds = getBoundsByElement(thumbnail);
  3591. } else {
  3592. thumbBounds = getCroppedBoundsByElement(thumbnail, itemData.width || itemData.w || 0, itemData.height || itemData.h || 0);
  3593. }
  3594. }
  3595. return instance.applyFilters('thumbBounds', thumbBounds, itemData, index);
  3596. }
  3597. /** @typedef {import('../lightbox/lightbox.js').default} PhotoSwipeLightbox */
  3598. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  3599. /** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
  3600. /** @typedef {import('../photoswipe.js').DataSource} DataSource */
  3601. /** @typedef {import('../ui/ui-element.js').UIElementData} UIElementData */
  3602. /** @typedef {import('../slide/content.js').default} ContentDefault */
  3603. /** @typedef {import('../slide/slide.js').default} Slide */
  3604. /** @typedef {import('../slide/slide.js').SlideData} SlideData */
  3605. /** @typedef {import('../slide/zoom-level.js').default} ZoomLevel */
  3606. /** @typedef {import('../slide/get-thumb-bounds.js').Bounds} Bounds */
  3607. /**
  3608. * Allow adding an arbitrary props to the Content
  3609. * https://photoswipe.com/custom-content/#using-webp-image-format
  3610. * @typedef {ContentDefault & Record<string, any>} Content
  3611. */
  3612. /** @typedef {{ x?: number; y?: number }} Point */
  3613. /**
  3614. * @typedef {Object} PhotoSwipeEventsMap https://photoswipe.com/events/
  3615. *
  3616. *
  3617. * https://photoswipe.com/adding-ui-elements/
  3618. *
  3619. * @prop {undefined} uiRegister
  3620. * @prop {{ data: UIElementData }} uiElementCreate
  3621. *
  3622. *
  3623. * https://photoswipe.com/events/#initialization-events
  3624. *
  3625. * @prop {undefined} beforeOpen
  3626. * @prop {undefined} firstUpdate
  3627. * @prop {undefined} initialLayout
  3628. * @prop {undefined} change
  3629. * @prop {undefined} afterInit
  3630. * @prop {undefined} bindEvents
  3631. *
  3632. *
  3633. * https://photoswipe.com/events/#opening-or-closing-transition-events
  3634. *
  3635. * @prop {undefined} openingAnimationStart
  3636. * @prop {undefined} openingAnimationEnd
  3637. * @prop {undefined} closingAnimationStart
  3638. * @prop {undefined} closingAnimationEnd
  3639. *
  3640. *
  3641. * https://photoswipe.com/events/#closing-events
  3642. *
  3643. * @prop {undefined} close
  3644. * @prop {undefined} destroy
  3645. *
  3646. *
  3647. * https://photoswipe.com/events/#pointer-and-gesture-events
  3648. *
  3649. * @prop {{ originalEvent: PointerEvent }} pointerDown
  3650. * @prop {{ originalEvent: PointerEvent }} pointerMove
  3651. * @prop {{ originalEvent: PointerEvent }} pointerUp
  3652. * @prop {{ bgOpacity: number }} pinchClose can be default prevented
  3653. * @prop {{ panY: number }} verticalDrag can be default prevented
  3654. *
  3655. *
  3656. * https://photoswipe.com/events/#slide-content-events
  3657. *
  3658. * @prop {{ content: Content }} contentInit
  3659. * @prop {{ content: Content; isLazy: boolean }} contentLoad can be default prevented
  3660. * @prop {{ content: Content; isLazy: boolean }} contentLoadImage can be default prevented
  3661. * @prop {{ content: Content; slide: Slide; isError?: boolean }} loadComplete
  3662. * @prop {{ content: Content; slide: Slide }} loadError
  3663. * @prop {{ content: Content; width: number; height: number }} contentResize can be default prevented
  3664. * @prop {{ content: Content; width: number; height: number; slide: Slide }} imageSizeChange
  3665. * @prop {{ content: Content }} contentLazyLoad can be default prevented
  3666. * @prop {{ content: Content }} contentAppend can be default prevented
  3667. * @prop {{ content: Content }} contentActivate can be default prevented
  3668. * @prop {{ content: Content }} contentDeactivate can be default prevented
  3669. * @prop {{ content: Content }} contentRemove can be default prevented
  3670. * @prop {{ content: Content }} contentDestroy can be default prevented
  3671. *
  3672. *
  3673. * undocumented
  3674. *
  3675. * @prop {{ point: Point; originalEvent: PointerEvent }} imageClickAction can be default prevented
  3676. * @prop {{ point: Point; originalEvent: PointerEvent }} bgClickAction can be default prevented
  3677. * @prop {{ point: Point; originalEvent: PointerEvent }} tapAction can be default prevented
  3678. * @prop {{ point: Point; originalEvent: PointerEvent }} doubleTapAction can be default prevented
  3679. *
  3680. * @prop {{ originalEvent: KeyboardEvent }} keydown can be default prevented
  3681. * @prop {{ x: number; dragging: boolean }} moveMainScroll
  3682. * @prop {{ slide: Slide }} firstZoomPan
  3683. * @prop {{ slide: Slide | undefined, data: SlideData, index: number }} gettingData
  3684. * @prop {undefined} beforeResize
  3685. * @prop {undefined} resize
  3686. * @prop {undefined} viewportSize
  3687. * @prop {undefined} updateScrollOffset
  3688. * @prop {{ slide: Slide }} slideInit
  3689. * @prop {{ slide: Slide }} afterSetContent
  3690. * @prop {{ slide: Slide }} slideLoad
  3691. * @prop {{ slide: Slide }} appendHeavy can be default prevented
  3692. * @prop {{ slide: Slide }} appendHeavyContent
  3693. * @prop {{ slide: Slide }} slideActivate
  3694. * @prop {{ slide: Slide }} slideDeactivate
  3695. * @prop {{ slide: Slide }} slideDestroy
  3696. * @prop {{ destZoomLevel: number, centerPoint: Point | undefined, transitionDuration: number | false | undefined }} beforeZoomTo
  3697. * @prop {{ slide: Slide }} zoomPanUpdate
  3698. * @prop {{ slide: Slide }} initialZoomPan
  3699. * @prop {{ slide: Slide }} calcSlideSize
  3700. * @prop {undefined} resolutionChanged
  3701. * @prop {{ originalEvent: WheelEvent }} wheel can be default prevented
  3702. * @prop {{ content: Content }} contentAppendImage can be default prevented
  3703. * @prop {{ index: number; itemData: SlideData }} lazyLoadSlide can be default prevented
  3704. * @prop {undefined} lazyLoad
  3705. * @prop {{ slide: Slide }} calcBounds
  3706. * @prop {{ zoomLevels: ZoomLevel, slideData: SlideData }} zoomLevelsUpdate
  3707. *
  3708. *
  3709. * legacy
  3710. *
  3711. * @prop {undefined} init
  3712. * @prop {undefined} initialZoomIn
  3713. * @prop {undefined} initialZoomOut
  3714. * @prop {undefined} initialZoomInEnd
  3715. * @prop {undefined} initialZoomOutEnd
  3716. * @prop {{ dataSource: DataSource | undefined, numItems: number }} numItems
  3717. * @prop {{ itemData: SlideData; index: number }} itemData
  3718. * @prop {{ index: number, itemData: SlideData, instance: PhotoSwipe }} thumbBounds
  3719. */
  3720. /**
  3721. * @typedef {Object} PhotoSwipeFiltersMap https://photoswipe.com/filters/
  3722. *
  3723. * @prop {(numItems: number, dataSource: DataSource | undefined) => number} numItems
  3724. * Modify the total amount of slides. Example on Data sources page.
  3725. * https://photoswipe.com/filters/#numitems
  3726. *
  3727. * @prop {(itemData: SlideData, index: number) => SlideData} itemData
  3728. * Modify slide item data. Example on Data sources page.
  3729. * https://photoswipe.com/filters/#itemdata
  3730. *
  3731. * @prop {(itemData: SlideData, element: HTMLElement, linkEl: HTMLAnchorElement) => SlideData} domItemData
  3732. * Modify item data when it's parsed from DOM element. Example on Data sources page.
  3733. * https://photoswipe.com/filters/#domitemdata
  3734. *
  3735. * @prop {(clickedIndex: number, e: MouseEvent, instance: PhotoSwipeLightbox) => number} clickedIndex
  3736. * Modify clicked gallery item index.
  3737. * https://photoswipe.com/filters/#clickedindex
  3738. *
  3739. * @prop {(placeholderSrc: string | false, content: Content) => string | false} placeholderSrc
  3740. * Modify placeholder image source.
  3741. * https://photoswipe.com/filters/#placeholdersrc
  3742. *
  3743. * @prop {(isContentLoading: boolean, content: Content) => boolean} isContentLoading
  3744. * Modify if the content is currently loading.
  3745. * https://photoswipe.com/filters/#iscontentloading
  3746. *
  3747. * @prop {(isContentZoomable: boolean, content: Content) => boolean} isContentZoomable
  3748. * Modify if the content can be zoomed.
  3749. * https://photoswipe.com/filters/#iscontentzoomable
  3750. *
  3751. * @prop {(useContentPlaceholder: boolean, content: Content) => boolean} useContentPlaceholder
  3752. * Modify if the placeholder should be used for the content.
  3753. * https://photoswipe.com/filters/#usecontentplaceholder
  3754. *
  3755. * @prop {(isKeepingPlaceholder: boolean, content: Content) => boolean} isKeepingPlaceholder
  3756. * Modify if the placeholder should be kept after the content is loaded.
  3757. * https://photoswipe.com/filters/#iskeepingplaceholder
  3758. *
  3759. *
  3760. * @prop {(contentErrorElement: HTMLElement, content: Content) => HTMLElement} contentErrorElement
  3761. * Modify an element when the content has error state (for example, if image cannot be loaded).
  3762. * https://photoswipe.com/filters/#contenterrorelement
  3763. *
  3764. * @prop {(element: HTMLElement, data: UIElementData) => HTMLElement} uiElement
  3765. * Modify a UI element that's being created.
  3766. * https://photoswipe.com/filters/#uielement
  3767. *
  3768. * @prop {(thumbnail: HTMLElement | null | undefined, itemData: SlideData, index: number) => HTMLElement} thumbEl
  3769. * Modify the thumbnail element from which opening zoom animation starts or ends.
  3770. * https://photoswipe.com/filters/#thumbel
  3771. *
  3772. * @prop {(thumbBounds: Bounds | undefined, itemData: SlideData, index: number) => Bounds} thumbBounds
  3773. * Modify the thumbnail bounds from which opening zoom animation starts or ends.
  3774. * https://photoswipe.com/filters/#thumbbounds
  3775. *
  3776. * @prop {(srcsetSizesWidth: number, content: Content) => number} srcsetSizesWidth
  3777. *
  3778. * @prop {(preventPointerEvent: boolean, event: PointerEvent, pointerType: string) => boolean} preventPointerEvent
  3779. *
  3780. */
  3781. /**
  3782. * @template {keyof PhotoSwipeFiltersMap} T
  3783. * @typedef {{ fn: PhotoSwipeFiltersMap[T], priority: number }} Filter
  3784. */
  3785. /**
  3786. * @template {keyof PhotoSwipeEventsMap} T
  3787. * @typedef {PhotoSwipeEventsMap[T] extends undefined ? PhotoSwipeEvent<T> : PhotoSwipeEvent<T> & PhotoSwipeEventsMap[T]} AugmentedEvent
  3788. */
  3789. /**
  3790. * @template {keyof PhotoSwipeEventsMap} T
  3791. * @typedef {(event: AugmentedEvent<T>) => void} EventCallback
  3792. */
  3793. /**
  3794. * Base PhotoSwipe event object
  3795. *
  3796. * @template {keyof PhotoSwipeEventsMap} T
  3797. */
  3798. class PhotoSwipeEvent {
  3799. /**
  3800. * @param {T} type
  3801. * @param {PhotoSwipeEventsMap[T]} [details]
  3802. */
  3803. constructor(type, details) {
  3804. this.type = type;
  3805. this.defaultPrevented = false;
  3806. if (details) {
  3807. Object.assign(this, details);
  3808. }
  3809. }
  3810. preventDefault() {
  3811. this.defaultPrevented = true;
  3812. }
  3813. }
  3814. /**
  3815. * PhotoSwipe base class that can listen and dispatch for events.
  3816. * Shared by PhotoSwipe Core and PhotoSwipe Lightbox, extended by base.js
  3817. */
  3818. class Eventable {
  3819. constructor() {
  3820. /**
  3821. * @type {{ [T in keyof PhotoSwipeEventsMap]?: ((event: AugmentedEvent<T>) => void)[] }}
  3822. */
  3823. this._listeners = {};
  3824. /**
  3825. * @type {{ [T in keyof PhotoSwipeFiltersMap]?: Filter<T>[] }}
  3826. */
  3827. this._filters = {};
  3828. /** @type {PhotoSwipe | undefined} */
  3829. this.pswp = undefined;
  3830. /** @type {PhotoSwipeOptions | undefined} */
  3831. this.options = undefined;
  3832. }
  3833. /**
  3834. * @template {keyof PhotoSwipeFiltersMap} T
  3835. * @param {T} name
  3836. * @param {PhotoSwipeFiltersMap[T]} fn
  3837. * @param {number} priority
  3838. */
  3839. addFilter(name, fn, priority = 100) {
  3840. var _this$_filters$name, _this$_filters$name2, _this$pswp;
  3841. if (!this._filters[name]) {
  3842. this._filters[name] = [];
  3843. }
  3844. (_this$_filters$name = this._filters[name]) === null || _this$_filters$name === void 0 || _this$_filters$name.push({
  3845. fn,
  3846. priority
  3847. });
  3848. (_this$_filters$name2 = this._filters[name]) === null || _this$_filters$name2 === void 0 || _this$_filters$name2.sort((f1, f2) => f1.priority - f2.priority);
  3849. (_this$pswp = this.pswp) === null || _this$pswp === void 0 || _this$pswp.addFilter(name, fn, priority);
  3850. }
  3851. /**
  3852. * @template {keyof PhotoSwipeFiltersMap} T
  3853. * @param {T} name
  3854. * @param {PhotoSwipeFiltersMap[T]} fn
  3855. */
  3856. removeFilter(name, fn) {
  3857. if (this._filters[name]) {
  3858. // @ts-expect-error
  3859. this._filters[name] = this._filters[name].filter(filter => filter.fn !== fn);
  3860. }
  3861. if (this.pswp) {
  3862. this.pswp.removeFilter(name, fn);
  3863. }
  3864. }
  3865. /**
  3866. * @template {keyof PhotoSwipeFiltersMap} T
  3867. * @param {T} name
  3868. * @param {Parameters<PhotoSwipeFiltersMap[T]>} args
  3869. * @returns {Parameters<PhotoSwipeFiltersMap[T]>[0]}
  3870. */
  3871. applyFilters(name, ...args) {
  3872. var _this$_filters$name3;
  3873. (_this$_filters$name3 = this._filters[name]) === null || _this$_filters$name3 === void 0 || _this$_filters$name3.forEach(filter => {
  3874. // @ts-expect-error
  3875. args[0] = filter.fn.apply(this, args);
  3876. });
  3877. return args[0];
  3878. }
  3879. /**
  3880. * @template {keyof PhotoSwipeEventsMap} T
  3881. * @param {T} name
  3882. * @param {EventCallback<T>} fn
  3883. */
  3884. on(name, fn) {
  3885. var _this$_listeners$name, _this$pswp2;
  3886. if (!this._listeners[name]) {
  3887. this._listeners[name] = [];
  3888. }
  3889. (_this$_listeners$name = this._listeners[name]) === null || _this$_listeners$name === void 0 || _this$_listeners$name.push(fn); // When binding events to lightbox,
  3890. // also bind events to PhotoSwipe Core,
  3891. // if it's open.
  3892. (_this$pswp2 = this.pswp) === null || _this$pswp2 === void 0 || _this$pswp2.on(name, fn);
  3893. }
  3894. /**
  3895. * @template {keyof PhotoSwipeEventsMap} T
  3896. * @param {T} name
  3897. * @param {EventCallback<T>} fn
  3898. */
  3899. off(name, fn) {
  3900. var _this$pswp3;
  3901. if (this._listeners[name]) {
  3902. // @ts-expect-error
  3903. this._listeners[name] = this._listeners[name].filter(listener => fn !== listener);
  3904. }
  3905. (_this$pswp3 = this.pswp) === null || _this$pswp3 === void 0 || _this$pswp3.off(name, fn);
  3906. }
  3907. /**
  3908. * @template {keyof PhotoSwipeEventsMap} T
  3909. * @param {T} name
  3910. * @param {PhotoSwipeEventsMap[T]} [details]
  3911. * @returns {AugmentedEvent<T>}
  3912. */
  3913. dispatch(name, details) {
  3914. var _this$_listeners$name2;
  3915. if (this.pswp) {
  3916. return this.pswp.dispatch(name, details);
  3917. }
  3918. const event =
  3919. /** @type {AugmentedEvent<T>} */
  3920. new PhotoSwipeEvent(name, details);
  3921. (_this$_listeners$name2 = this._listeners[name]) === null || _this$_listeners$name2 === void 0 || _this$_listeners$name2.forEach(listener => {
  3922. listener.call(this, event);
  3923. });
  3924. return event;
  3925. }
  3926. }
  3927. class Placeholder {
  3928. /**
  3929. * @param {string | false} imageSrc
  3930. * @param {HTMLElement} container
  3931. */
  3932. constructor(imageSrc, container) {
  3933. // Create placeholder
  3934. // (stretched thumbnail or simple div behind the main image)
  3935. /** @type {HTMLImageElement | HTMLDivElement | null} */
  3936. this.element = createElement('pswp__img pswp__img--placeholder', imageSrc ? 'img' : 'div', container);
  3937. if (imageSrc) {
  3938. const imgEl =
  3939. /** @type {HTMLImageElement} */
  3940. this.element;
  3941. imgEl.decoding = 'async';
  3942. imgEl.alt = '';
  3943. imgEl.src = imageSrc;
  3944. imgEl.setAttribute('role', 'presentation');
  3945. }
  3946. this.element.setAttribute('aria-hidden', 'true');
  3947. }
  3948. /**
  3949. * @param {number} width
  3950. * @param {number} height
  3951. */
  3952. setDisplayedSize(width, height) {
  3953. if (!this.element) {
  3954. return;
  3955. }
  3956. if (this.element.tagName === 'IMG') {
  3957. // Use transform scale() to modify img placeholder size
  3958. // (instead of changing width/height directly).
  3959. // This helps with performance, specifically in iOS15 Safari.
  3960. setWidthHeight(this.element, 250, 'auto');
  3961. this.element.style.transformOrigin = '0 0';
  3962. this.element.style.transform = toTransformString(0, 0, width / 250);
  3963. } else {
  3964. setWidthHeight(this.element, width, height);
  3965. }
  3966. }
  3967. destroy() {
  3968. var _this$element;
  3969. if ((_this$element = this.element) !== null && _this$element !== void 0 && _this$element.parentNode) {
  3970. this.element.remove();
  3971. }
  3972. this.element = null;
  3973. }
  3974. }
  3975. /** @typedef {import('./slide.js').default} Slide */
  3976. /** @typedef {import('./slide.js').SlideData} SlideData */
  3977. /** @typedef {import('../core/base.js').default} PhotoSwipeBase */
  3978. /** @typedef {import('../util/util.js').LoadState} LoadState */
  3979. class Content {
  3980. /**
  3981. * @param {SlideData} itemData Slide data
  3982. * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance
  3983. * @param {number} index
  3984. */
  3985. constructor(itemData, instance, index) {
  3986. this.instance = instance;
  3987. this.data = itemData;
  3988. this.index = index;
  3989. /** @type {HTMLImageElement | HTMLDivElement | undefined} */
  3990. this.element = undefined;
  3991. /** @type {Placeholder | undefined} */
  3992. this.placeholder = undefined;
  3993. /** @type {Slide | undefined} */
  3994. this.slide = undefined;
  3995. this.displayedImageWidth = 0;
  3996. this.displayedImageHeight = 0;
  3997. this.width = Number(this.data.w) || Number(this.data.width) || 0;
  3998. this.height = Number(this.data.h) || Number(this.data.height) || 0;
  3999. this.isAttached = false;
  4000. this.hasSlide = false;
  4001. this.isDecoding = false;
  4002. /** @type {LoadState} */
  4003. this.state = LOAD_STATE.IDLE;
  4004. if (this.data.type) {
  4005. this.type = this.data.type;
  4006. } else if (this.data.src) {
  4007. this.type = 'image';
  4008. } else {
  4009. this.type = 'html';
  4010. }
  4011. this.instance.dispatch('contentInit', {
  4012. content: this
  4013. });
  4014. }
  4015. removePlaceholder() {
  4016. if (this.placeholder && !this.keepPlaceholder()) {
  4017. // With delay, as image might be loaded, but not rendered
  4018. setTimeout(() => {
  4019. if (this.placeholder) {
  4020. this.placeholder.destroy();
  4021. this.placeholder = undefined;
  4022. }
  4023. }, 1000);
  4024. }
  4025. }
  4026. /**
  4027. * Preload content
  4028. *
  4029. * @param {boolean} isLazy
  4030. * @param {boolean} [reload]
  4031. */
  4032. load(isLazy, reload) {
  4033. if (this.slide && this.usePlaceholder()) {
  4034. if (!this.placeholder) {
  4035. const placeholderSrc = this.instance.applyFilters('placeholderSrc', // use image-based placeholder only for the first slide,
  4036. // as rendering (even small stretched thumbnail) is an expensive operation
  4037. this.data.msrc && this.slide.isFirstSlide ? this.data.msrc : false, this);
  4038. this.placeholder = new Placeholder(placeholderSrc, this.slide.container);
  4039. } else {
  4040. const placeholderEl = this.placeholder.element; // Add placeholder to DOM if it was already created
  4041. if (placeholderEl && !placeholderEl.parentElement) {
  4042. this.slide.container.prepend(placeholderEl);
  4043. }
  4044. }
  4045. }
  4046. if (this.element && !reload) {
  4047. return;
  4048. }
  4049. if (this.instance.dispatch('contentLoad', {
  4050. content: this,
  4051. isLazy
  4052. }).defaultPrevented) {
  4053. return;
  4054. }
  4055. if (this.isImageContent()) {
  4056. this.element = createElement('pswp__img', 'img'); // Start loading only after width is defined, as sizes might depend on it.
  4057. // Due to Safari feature, we must define sizes before srcset.
  4058. if (this.displayedImageWidth) {
  4059. this.loadImage(isLazy);
  4060. }
  4061. } else {
  4062. this.element = createElement('pswp__content', 'div');
  4063. this.element.innerHTML = this.data.html || '';
  4064. }
  4065. if (reload && this.slide) {
  4066. this.slide.updateContentSize(true);
  4067. }
  4068. }
  4069. /**
  4070. * Preload image
  4071. *
  4072. * @param {boolean} isLazy
  4073. */
  4074. loadImage(isLazy) {
  4075. var _this$data$src, _this$data$alt;
  4076. if (!this.isImageContent() || !this.element || this.instance.dispatch('contentLoadImage', {
  4077. content: this,
  4078. isLazy
  4079. }).defaultPrevented) {
  4080. return;
  4081. }
  4082. const imageElement =
  4083. /** @type HTMLImageElement */
  4084. this.element;
  4085. this.updateSrcsetSizes();
  4086. if (this.data.srcset) {
  4087. imageElement.srcset = this.data.srcset;
  4088. }
  4089. imageElement.src = (_this$data$src = this.data.src) !== null && _this$data$src !== void 0 ? _this$data$src : '';
  4090. imageElement.alt = (_this$data$alt = this.data.alt) !== null && _this$data$alt !== void 0 ? _this$data$alt : '';
  4091. this.state = LOAD_STATE.LOADING;
  4092. if (imageElement.complete) {
  4093. this.onLoaded();
  4094. } else {
  4095. imageElement.onload = () => {
  4096. this.onLoaded();
  4097. };
  4098. imageElement.onerror = () => {
  4099. this.onError();
  4100. };
  4101. }
  4102. }
  4103. /**
  4104. * Assign slide to content
  4105. *
  4106. * @param {Slide} slide
  4107. */
  4108. setSlide(slide) {
  4109. this.slide = slide;
  4110. this.hasSlide = true;
  4111. this.instance = slide.pswp; // todo: do we need to unset slide?
  4112. }
  4113. /**
  4114. * Content load success handler
  4115. */
  4116. onLoaded() {
  4117. this.state = LOAD_STATE.LOADED;
  4118. if (this.slide && this.element) {
  4119. this.instance.dispatch('loadComplete', {
  4120. slide: this.slide,
  4121. content: this
  4122. }); // if content is reloaded
  4123. if (this.slide.isActive && this.slide.heavyAppended && !this.element.parentNode) {
  4124. this.append();
  4125. this.slide.updateContentSize(true);
  4126. }
  4127. if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {
  4128. this.removePlaceholder();
  4129. }
  4130. }
  4131. }
  4132. /**
  4133. * Content load error handler
  4134. */
  4135. onError() {
  4136. this.state = LOAD_STATE.ERROR;
  4137. if (this.slide) {
  4138. this.displayError();
  4139. this.instance.dispatch('loadComplete', {
  4140. slide: this.slide,
  4141. isError: true,
  4142. content: this
  4143. });
  4144. this.instance.dispatch('loadError', {
  4145. slide: this.slide,
  4146. content: this
  4147. });
  4148. }
  4149. }
  4150. /**
  4151. * @returns {Boolean} If the content is currently loading
  4152. */
  4153. isLoading() {
  4154. return this.instance.applyFilters('isContentLoading', this.state === LOAD_STATE.LOADING, this);
  4155. }
  4156. /**
  4157. * @returns {Boolean} If the content is in error state
  4158. */
  4159. isError() {
  4160. return this.state === LOAD_STATE.ERROR;
  4161. }
  4162. /**
  4163. * @returns {boolean} If the content is image
  4164. */
  4165. isImageContent() {
  4166. return this.type === 'image';
  4167. }
  4168. /**
  4169. * Update content size
  4170. *
  4171. * @param {Number} width
  4172. * @param {Number} height
  4173. */
  4174. setDisplayedSize(width, height) {
  4175. if (!this.element) {
  4176. return;
  4177. }
  4178. if (this.placeholder) {
  4179. this.placeholder.setDisplayedSize(width, height);
  4180. }
  4181. if (this.instance.dispatch('contentResize', {
  4182. content: this,
  4183. width,
  4184. height
  4185. }).defaultPrevented) {
  4186. return;
  4187. }
  4188. setWidthHeight(this.element, width, height);
  4189. if (this.isImageContent() && !this.isError()) {
  4190. const isInitialSizeUpdate = !this.displayedImageWidth && width;
  4191. this.displayedImageWidth = width;
  4192. this.displayedImageHeight = height;
  4193. if (isInitialSizeUpdate) {
  4194. this.loadImage(false);
  4195. } else {
  4196. this.updateSrcsetSizes();
  4197. }
  4198. if (this.slide) {
  4199. this.instance.dispatch('imageSizeChange', {
  4200. slide: this.slide,
  4201. width,
  4202. height,
  4203. content: this
  4204. });
  4205. }
  4206. }
  4207. }
  4208. /**
  4209. * @returns {boolean} If the content can be zoomed
  4210. */
  4211. isZoomable() {
  4212. return this.instance.applyFilters('isContentZoomable', this.isImageContent() && this.state !== LOAD_STATE.ERROR, this);
  4213. }
  4214. /**
  4215. * Update image srcset sizes attribute based on width and height
  4216. */
  4217. updateSrcsetSizes() {
  4218. // Handle srcset sizes attribute.
  4219. //
  4220. // Never lower quality, if it was increased previously.
  4221. // Chrome does this automatically, Firefox and Safari do not,
  4222. // so we store largest used size in dataset.
  4223. if (!this.isImageContent() || !this.element || !this.data.srcset) {
  4224. return;
  4225. }
  4226. const image =
  4227. /** @type HTMLImageElement */
  4228. this.element;
  4229. const sizesWidth = this.instance.applyFilters('srcsetSizesWidth', this.displayedImageWidth, this);
  4230. if (!image.dataset.largestUsedSize || sizesWidth > parseInt(image.dataset.largestUsedSize, 10)) {
  4231. image.sizes = sizesWidth + 'px';
  4232. image.dataset.largestUsedSize = String(sizesWidth);
  4233. }
  4234. }
  4235. /**
  4236. * @returns {boolean} If content should use a placeholder (from msrc by default)
  4237. */
  4238. usePlaceholder() {
  4239. return this.instance.applyFilters('useContentPlaceholder', this.isImageContent(), this);
  4240. }
  4241. /**
  4242. * Preload content with lazy-loading param
  4243. */
  4244. lazyLoad() {
  4245. if (this.instance.dispatch('contentLazyLoad', {
  4246. content: this
  4247. }).defaultPrevented) {
  4248. return;
  4249. }
  4250. this.load(true);
  4251. }
  4252. /**
  4253. * @returns {boolean} If placeholder should be kept after content is loaded
  4254. */
  4255. keepPlaceholder() {
  4256. return this.instance.applyFilters('isKeepingPlaceholder', this.isLoading(), this);
  4257. }
  4258. /**
  4259. * Destroy the content
  4260. */
  4261. destroy() {
  4262. this.hasSlide = false;
  4263. this.slide = undefined;
  4264. if (this.instance.dispatch('contentDestroy', {
  4265. content: this
  4266. }).defaultPrevented) {
  4267. return;
  4268. }
  4269. this.remove();
  4270. if (this.placeholder) {
  4271. this.placeholder.destroy();
  4272. this.placeholder = undefined;
  4273. }
  4274. if (this.isImageContent() && this.element) {
  4275. this.element.onload = null;
  4276. this.element.onerror = null;
  4277. this.element = undefined;
  4278. }
  4279. }
  4280. /**
  4281. * Display error message
  4282. */
  4283. displayError() {
  4284. if (this.slide) {
  4285. var _this$instance$option, _this$instance$option2;
  4286. let errorMsgEl = createElement('pswp__error-msg', 'div');
  4287. errorMsgEl.innerText = (_this$instance$option = (_this$instance$option2 = this.instance.options) === null || _this$instance$option2 === void 0 ? void 0 : _this$instance$option2.errorMsg) !== null && _this$instance$option !== void 0 ? _this$instance$option : '';
  4288. errorMsgEl =
  4289. /** @type {HTMLDivElement} */
  4290. this.instance.applyFilters('contentErrorElement', errorMsgEl, this);
  4291. this.element = createElement('pswp__content pswp__error-msg-container', 'div');
  4292. this.element.appendChild(errorMsgEl);
  4293. this.slide.container.innerText = '';
  4294. this.slide.container.appendChild(this.element);
  4295. this.slide.updateContentSize(true);
  4296. this.removePlaceholder();
  4297. }
  4298. }
  4299. /**
  4300. * Append the content
  4301. */
  4302. append() {
  4303. if (this.isAttached || !this.element) {
  4304. return;
  4305. }
  4306. this.isAttached = true;
  4307. if (this.state === LOAD_STATE.ERROR) {
  4308. this.displayError();
  4309. return;
  4310. }
  4311. if (this.instance.dispatch('contentAppend', {
  4312. content: this
  4313. }).defaultPrevented) {
  4314. return;
  4315. }
  4316. const supportsDecode = ('decode' in this.element);
  4317. if (this.isImageContent()) {
  4318. // Use decode() on nearby slides
  4319. //
  4320. // Nearby slide images are in DOM and not hidden via display:none.
  4321. // However, they are placed offscreen (to the left and right side).
  4322. //
  4323. // Some browsers do not composite the image until it's actually visible,
  4324. // using decode() helps.
  4325. //
  4326. // You might ask "why dont you just decode() and then append all images",
  4327. // that's because I want to show image before it's fully loaded,
  4328. // as browser can render parts of image while it is loading.
  4329. // We do not do this in Safari due to partial loading bug.
  4330. if (supportsDecode && this.slide && (!this.slide.isActive || isSafari())) {
  4331. this.isDecoding = true; // purposefully using finally instead of then,
  4332. // as if srcset sizes changes dynamically - it may cause decode error
  4333. /** @type {HTMLImageElement} */
  4334. this.element.decode().catch(() => {}).finally(() => {
  4335. this.isDecoding = false;
  4336. this.appendImage();
  4337. });
  4338. } else {
  4339. this.appendImage();
  4340. }
  4341. } else if (this.slide && !this.element.parentNode) {
  4342. this.slide.container.appendChild(this.element);
  4343. }
  4344. }
  4345. /**
  4346. * Activate the slide,
  4347. * active slide is generally the current one,
  4348. * meaning the user can see it.
  4349. */
  4350. activate() {
  4351. if (this.instance.dispatch('contentActivate', {
  4352. content: this
  4353. }).defaultPrevented || !this.slide) {
  4354. return;
  4355. }
  4356. if (this.isImageContent() && this.isDecoding && !isSafari()) {
  4357. // add image to slide when it becomes active,
  4358. // even if it's not finished decoding
  4359. this.appendImage();
  4360. } else if (this.isError()) {
  4361. this.load(false, true); // try to reload
  4362. }
  4363. if (this.slide.holderElement) {
  4364. this.slide.holderElement.setAttribute('aria-hidden', 'false');
  4365. }
  4366. }
  4367. /**
  4368. * Deactivate the content
  4369. */
  4370. deactivate() {
  4371. this.instance.dispatch('contentDeactivate', {
  4372. content: this
  4373. });
  4374. if (this.slide && this.slide.holderElement) {
  4375. this.slide.holderElement.setAttribute('aria-hidden', 'true');
  4376. }
  4377. }
  4378. /**
  4379. * Remove the content from DOM
  4380. */
  4381. remove() {
  4382. this.isAttached = false;
  4383. if (this.instance.dispatch('contentRemove', {
  4384. content: this
  4385. }).defaultPrevented) {
  4386. return;
  4387. }
  4388. if (this.element && this.element.parentNode) {
  4389. this.element.remove();
  4390. }
  4391. if (this.placeholder && this.placeholder.element) {
  4392. this.placeholder.element.remove();
  4393. }
  4394. }
  4395. /**
  4396. * Append the image content to slide container
  4397. */
  4398. appendImage() {
  4399. if (!this.isAttached) {
  4400. return;
  4401. }
  4402. if (this.instance.dispatch('contentAppendImage', {
  4403. content: this
  4404. }).defaultPrevented) {
  4405. return;
  4406. } // ensure that element exists and is not already appended
  4407. if (this.slide && this.element && !this.element.parentNode) {
  4408. this.slide.container.appendChild(this.element);
  4409. }
  4410. if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {
  4411. this.removePlaceholder();
  4412. }
  4413. }
  4414. }
  4415. /** @typedef {import('./content.js').default} Content */
  4416. /** @typedef {import('./slide.js').default} Slide */
  4417. /** @typedef {import('./slide.js').SlideData} SlideData */
  4418. /** @typedef {import('../core/base.js').default} PhotoSwipeBase */
  4419. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  4420. const MIN_SLIDES_TO_CACHE = 5;
  4421. /**
  4422. * Lazy-load an image
  4423. * This function is used both by Lightbox and PhotoSwipe core,
  4424. * thus it can be called before dialog is opened.
  4425. *
  4426. * @param {SlideData} itemData Data about the slide
  4427. * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance
  4428. * @param {number} index
  4429. * @returns {Content} Image that is being decoded or false.
  4430. */
  4431. function lazyLoadData(itemData, instance, index) {
  4432. const content = instance.createContentFromData(itemData, index);
  4433. /** @type {ZoomLevel | undefined} */
  4434. let zoomLevel;
  4435. const {
  4436. options
  4437. } = instance; // We need to know dimensions of the image to preload it,
  4438. // as it might use srcset, and we need to define sizes
  4439. if (options) {
  4440. zoomLevel = new ZoomLevel(options, itemData, -1);
  4441. let viewportSize;
  4442. if (instance.pswp) {
  4443. viewportSize = instance.pswp.viewportSize;
  4444. } else {
  4445. viewportSize = getViewportSize(options, instance);
  4446. }
  4447. const panAreaSize = getPanAreaSize(options, viewportSize, itemData, index);
  4448. zoomLevel.update(content.width, content.height, panAreaSize);
  4449. }
  4450. content.lazyLoad();
  4451. if (zoomLevel) {
  4452. content.setDisplayedSize(Math.ceil(content.width * zoomLevel.initial), Math.ceil(content.height * zoomLevel.initial));
  4453. }
  4454. return content;
  4455. }
  4456. /**
  4457. * Lazy-loads specific slide.
  4458. * This function is used both by Lightbox and PhotoSwipe core,
  4459. * thus it can be called before dialog is opened.
  4460. *
  4461. * By default, it loads image based on viewport size and initial zoom level.
  4462. *
  4463. * @param {number} index Slide index
  4464. * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox eventable instance
  4465. * @returns {Content | undefined}
  4466. */
  4467. function lazyLoadSlide(index, instance) {
  4468. const itemData = instance.getItemData(index);
  4469. if (instance.dispatch('lazyLoadSlide', {
  4470. index,
  4471. itemData
  4472. }).defaultPrevented) {
  4473. return;
  4474. }
  4475. return lazyLoadData(itemData, instance, index);
  4476. }
  4477. class ContentLoader {
  4478. /**
  4479. * @param {PhotoSwipe} pswp
  4480. */
  4481. constructor(pswp) {
  4482. this.pswp = pswp; // Total amount of cached images
  4483. this.limit = Math.max(pswp.options.preload[0] + pswp.options.preload[1] + 1, MIN_SLIDES_TO_CACHE);
  4484. /** @type {Content[]} */
  4485. this._cachedItems = [];
  4486. }
  4487. /**
  4488. * Lazy load nearby slides based on `preload` option.
  4489. *
  4490. * @param {number} [diff] Difference between slide indexes that was changed recently, or 0.
  4491. */
  4492. updateLazy(diff) {
  4493. const {
  4494. pswp
  4495. } = this;
  4496. if (pswp.dispatch('lazyLoad').defaultPrevented) {
  4497. return;
  4498. }
  4499. const {
  4500. preload
  4501. } = pswp.options;
  4502. const isForward = diff === undefined ? true : diff >= 0;
  4503. let i; // preload[1] - num items to preload in forward direction
  4504. for (i = 0; i <= preload[1]; i++) {
  4505. this.loadSlideByIndex(pswp.currIndex + (isForward ? i : -i));
  4506. } // preload[0] - num items to preload in backward direction
  4507. for (i = 1; i <= preload[0]; i++) {
  4508. this.loadSlideByIndex(pswp.currIndex + (isForward ? -i : i));
  4509. }
  4510. }
  4511. /**
  4512. * @param {number} initialIndex
  4513. */
  4514. loadSlideByIndex(initialIndex) {
  4515. const index = this.pswp.getLoopedIndex(initialIndex); // try to get cached content
  4516. let content = this.getContentByIndex(index);
  4517. if (!content) {
  4518. // no cached content, so try to load from scratch:
  4519. content = lazyLoadSlide(index, this.pswp); // if content can be loaded, add it to cache:
  4520. if (content) {
  4521. this.addToCache(content);
  4522. }
  4523. }
  4524. }
  4525. /**
  4526. * @param {Slide} slide
  4527. * @returns {Content}
  4528. */
  4529. getContentBySlide(slide) {
  4530. let content = this.getContentByIndex(slide.index);
  4531. if (!content) {
  4532. // create content if not found in cache
  4533. content = this.pswp.createContentFromData(slide.data, slide.index);
  4534. this.addToCache(content);
  4535. } // assign slide to content
  4536. content.setSlide(slide);
  4537. return content;
  4538. }
  4539. /**
  4540. * @param {Content} content
  4541. */
  4542. addToCache(content) {
  4543. // move to the end of array
  4544. this.removeByIndex(content.index);
  4545. this._cachedItems.push(content);
  4546. if (this._cachedItems.length > this.limit) {
  4547. // Destroy the first content that's not attached
  4548. const indexToRemove = this._cachedItems.findIndex(item => {
  4549. return !item.isAttached && !item.hasSlide;
  4550. });
  4551. if (indexToRemove !== -1) {
  4552. const removedItem = this._cachedItems.splice(indexToRemove, 1)[0];
  4553. removedItem.destroy();
  4554. }
  4555. }
  4556. }
  4557. /**
  4558. * Removes an image from cache, does not destroy() it, just removes.
  4559. *
  4560. * @param {number} index
  4561. */
  4562. removeByIndex(index) {
  4563. const indexToRemove = this._cachedItems.findIndex(item => item.index === index);
  4564. if (indexToRemove !== -1) {
  4565. this._cachedItems.splice(indexToRemove, 1);
  4566. }
  4567. }
  4568. /**
  4569. * @param {number} index
  4570. * @returns {Content | undefined}
  4571. */
  4572. getContentByIndex(index) {
  4573. return this._cachedItems.find(content => content.index === index);
  4574. }
  4575. destroy() {
  4576. this._cachedItems.forEach(content => content.destroy());
  4577. this._cachedItems = [];
  4578. }
  4579. }
  4580. /** @typedef {import("../photoswipe.js").default} PhotoSwipe */
  4581. /** @typedef {import("../slide/slide.js").SlideData} SlideData */
  4582. /**
  4583. * PhotoSwipe base class that can retrieve data about every slide.
  4584. * Shared by PhotoSwipe Core and PhotoSwipe Lightbox
  4585. */
  4586. class PhotoSwipeBase extends Eventable {
  4587. /**
  4588. * Get total number of slides
  4589. *
  4590. * @returns {number}
  4591. */
  4592. getNumItems() {
  4593. var _this$options;
  4594. let numItems = 0;
  4595. const dataSource = (_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.dataSource;
  4596. if (dataSource && 'length' in dataSource) {
  4597. // may be an array or just object with length property
  4598. numItems = dataSource.length;
  4599. } else if (dataSource && 'gallery' in dataSource) {
  4600. // query DOM elements
  4601. if (!dataSource.items) {
  4602. dataSource.items = this._getGalleryDOMElements(dataSource.gallery);
  4603. }
  4604. if (dataSource.items) {
  4605. numItems = dataSource.items.length;
  4606. }
  4607. } // legacy event, before filters were introduced
  4608. const event = this.dispatch('numItems', {
  4609. dataSource,
  4610. numItems
  4611. });
  4612. return this.applyFilters('numItems', event.numItems, dataSource);
  4613. }
  4614. /**
  4615. * @param {SlideData} slideData
  4616. * @param {number} index
  4617. * @returns {Content}
  4618. */
  4619. createContentFromData(slideData, index) {
  4620. return new Content(slideData, this, index);
  4621. }
  4622. /**
  4623. * Get item data by index.
  4624. *
  4625. * "item data" should contain normalized information that PhotoSwipe needs to generate a slide.
  4626. * For example, it may contain properties like
  4627. * `src`, `srcset`, `w`, `h`, which will be used to generate a slide with image.
  4628. *
  4629. * @param {number} index
  4630. * @returns {SlideData}
  4631. */
  4632. getItemData(index) {
  4633. var _this$options2;
  4634. const dataSource = (_this$options2 = this.options) === null || _this$options2 === void 0 ? void 0 : _this$options2.dataSource;
  4635. /** @type {SlideData | HTMLElement} */
  4636. let dataSourceItem = {};
  4637. if (Array.isArray(dataSource)) {
  4638. // Datasource is an array of elements
  4639. dataSourceItem = dataSource[index];
  4640. } else if (dataSource && 'gallery' in dataSource) {
  4641. // dataSource has gallery property,
  4642. // thus it was created by Lightbox, based on
  4643. // gallery and children options
  4644. // query DOM elements
  4645. if (!dataSource.items) {
  4646. dataSource.items = this._getGalleryDOMElements(dataSource.gallery);
  4647. }
  4648. dataSourceItem = dataSource.items[index];
  4649. }
  4650. let itemData = dataSourceItem;
  4651. if (itemData instanceof Element) {
  4652. itemData = this._domElementToItemData(itemData);
  4653. } // Dispatching the itemData event,
  4654. // it's a legacy verion before filters were introduced
  4655. const event = this.dispatch('itemData', {
  4656. itemData: itemData || {},
  4657. index
  4658. });
  4659. return this.applyFilters('itemData', event.itemData, index);
  4660. }
  4661. /**
  4662. * Get array of gallery DOM elements,
  4663. * based on childSelector and gallery element.
  4664. *
  4665. * @param {HTMLElement} galleryElement
  4666. * @returns {HTMLElement[]}
  4667. */
  4668. _getGalleryDOMElements(galleryElement) {
  4669. var _this$options3, _this$options4;
  4670. if ((_this$options3 = this.options) !== null && _this$options3 !== void 0 && _this$options3.children || (_this$options4 = this.options) !== null && _this$options4 !== void 0 && _this$options4.childSelector) {
  4671. return getElementsFromOption(this.options.children, this.options.childSelector, galleryElement) || [];
  4672. }
  4673. return [galleryElement];
  4674. }
  4675. /**
  4676. * Converts DOM element to item data object.
  4677. *
  4678. * @param {HTMLElement} element DOM element
  4679. * @returns {SlideData}
  4680. */
  4681. _domElementToItemData(element) {
  4682. /** @type {SlideData} */
  4683. const itemData = {
  4684. element
  4685. };
  4686. const linkEl =
  4687. /** @type {HTMLAnchorElement} */
  4688. element.tagName === 'A' ? element : element.querySelector('a');
  4689. if (linkEl) {
  4690. // src comes from data-pswp-src attribute,
  4691. // if it's empty link href is used
  4692. itemData.src = linkEl.dataset.pswpSrc || linkEl.href;
  4693. if (linkEl.dataset.pswpSrcset) {
  4694. itemData.srcset = linkEl.dataset.pswpSrcset;
  4695. }
  4696. itemData.width = linkEl.dataset.pswpWidth ? parseInt(linkEl.dataset.pswpWidth, 10) : 0;
  4697. itemData.height = linkEl.dataset.pswpHeight ? parseInt(linkEl.dataset.pswpHeight, 10) : 0; // support legacy w & h properties
  4698. itemData.w = itemData.width;
  4699. itemData.h = itemData.height;
  4700. if (linkEl.dataset.pswpType) {
  4701. itemData.type = linkEl.dataset.pswpType;
  4702. }
  4703. const thumbnailEl = element.querySelector('img');
  4704. if (thumbnailEl) {
  4705. var _thumbnailEl$getAttri;
  4706. // msrc is URL to placeholder image that's displayed before large image is loaded
  4707. // by default it's displayed only for the first slide
  4708. itemData.msrc = thumbnailEl.currentSrc || thumbnailEl.src;
  4709. itemData.alt = (_thumbnailEl$getAttri = thumbnailEl.getAttribute('alt')) !== null && _thumbnailEl$getAttri !== void 0 ? _thumbnailEl$getAttri : '';
  4710. }
  4711. if (linkEl.dataset.pswpCropped || linkEl.dataset.cropped) {
  4712. itemData.thumbCropped = true;
  4713. }
  4714. }
  4715. return this.applyFilters('domItemData', itemData, element, linkEl);
  4716. }
  4717. /**
  4718. * Lazy-load by slide data
  4719. *
  4720. * @param {SlideData} itemData Data about the slide
  4721. * @param {number} index
  4722. * @returns {Content} Image that is being decoded or false.
  4723. */
  4724. lazyLoadData(itemData, index) {
  4725. return lazyLoadData(itemData, this, index);
  4726. }
  4727. }
  4728. /** @typedef {import('./photoswipe.js').default} PhotoSwipe */
  4729. /** @typedef {import('./slide/get-thumb-bounds.js').Bounds} Bounds */
  4730. /** @typedef {import('./util/animations.js').AnimationProps} AnimationProps */
  4731. // some browsers do not paint
  4732. // elements which opacity is set to 0,
  4733. // since we need to pre-render elements for the animation -
  4734. // we set it to the minimum amount
  4735. const MIN_OPACITY = 0.003;
  4736. /**
  4737. * Manages opening and closing transitions of the PhotoSwipe.
  4738. *
  4739. * It can perform zoom, fade or no transition.
  4740. */
  4741. class Opener {
  4742. /**
  4743. * @param {PhotoSwipe} pswp
  4744. */
  4745. constructor(pswp) {
  4746. this.pswp = pswp;
  4747. this.isClosed = true;
  4748. this.isOpen = false;
  4749. this.isClosing = false;
  4750. this.isOpening = false;
  4751. /**
  4752. * @private
  4753. * @type {number | false | undefined}
  4754. */
  4755. this._duration = undefined;
  4756. /** @private */
  4757. this._useAnimation = false;
  4758. /** @private */
  4759. this._croppedZoom = false;
  4760. /** @private */
  4761. this._animateRootOpacity = false;
  4762. /** @private */
  4763. this._animateBgOpacity = false;
  4764. /**
  4765. * @private
  4766. * @type { HTMLDivElement | HTMLImageElement | null | undefined }
  4767. */
  4768. this._placeholder = undefined;
  4769. /**
  4770. * @private
  4771. * @type { HTMLDivElement | undefined }
  4772. */
  4773. this._opacityElement = undefined;
  4774. /**
  4775. * @private
  4776. * @type { HTMLDivElement | undefined }
  4777. */
  4778. this._cropContainer1 = undefined;
  4779. /**
  4780. * @private
  4781. * @type { HTMLElement | null | undefined }
  4782. */
  4783. this._cropContainer2 = undefined;
  4784. /**
  4785. * @private
  4786. * @type {Bounds | undefined}
  4787. */
  4788. this._thumbBounds = undefined;
  4789. this._prepareOpen = this._prepareOpen.bind(this); // Override initial zoom and pan position
  4790. pswp.on('firstZoomPan', this._prepareOpen);
  4791. }
  4792. open() {
  4793. this._prepareOpen();
  4794. this._start();
  4795. }
  4796. close() {
  4797. if (this.isClosed || this.isClosing || this.isOpening) {
  4798. // if we close during opening animation
  4799. // for now do nothing,
  4800. // browsers aren't good at changing the direction of the CSS transition
  4801. return;
  4802. }
  4803. const slide = this.pswp.currSlide;
  4804. this.isOpen = false;
  4805. this.isOpening = false;
  4806. this.isClosing = true;
  4807. this._duration = this.pswp.options.hideAnimationDuration;
  4808. if (slide && slide.currZoomLevel * slide.width >= this.pswp.options.maxWidthToAnimate) {
  4809. this._duration = 0;
  4810. }
  4811. this._applyStartProps();
  4812. setTimeout(() => {
  4813. this._start();
  4814. }, this._croppedZoom ? 30 : 0);
  4815. }
  4816. /** @private */
  4817. _prepareOpen() {
  4818. this.pswp.off('firstZoomPan', this._prepareOpen);
  4819. if (!this.isOpening) {
  4820. const slide = this.pswp.currSlide;
  4821. this.isOpening = true;
  4822. this.isClosing = false;
  4823. this._duration = this.pswp.options.showAnimationDuration;
  4824. if (slide && slide.zoomLevels.initial * slide.width >= this.pswp.options.maxWidthToAnimate) {
  4825. this._duration = 0;
  4826. }
  4827. this._applyStartProps();
  4828. }
  4829. }
  4830. /** @private */
  4831. _applyStartProps() {
  4832. const {
  4833. pswp
  4834. } = this;
  4835. const slide = this.pswp.currSlide;
  4836. const {
  4837. options
  4838. } = pswp;
  4839. if (options.showHideAnimationType === 'fade') {
  4840. options.showHideOpacity = true;
  4841. this._thumbBounds = undefined;
  4842. } else if (options.showHideAnimationType === 'none') {
  4843. options.showHideOpacity = false;
  4844. this._duration = 0;
  4845. this._thumbBounds = undefined;
  4846. } else if (this.isOpening && pswp._initialThumbBounds) {
  4847. // Use initial bounds if defined
  4848. this._thumbBounds = pswp._initialThumbBounds;
  4849. } else {
  4850. this._thumbBounds = this.pswp.getThumbBounds();
  4851. }
  4852. this._placeholder = slide === null || slide === void 0 ? void 0 : slide.getPlaceholderElement();
  4853. pswp.animations.stopAll(); // Discard animations when duration is less than 50ms
  4854. this._useAnimation = Boolean(this._duration && this._duration > 50);
  4855. this._animateZoom = Boolean(this._thumbBounds) && (slide === null || slide === void 0 ? void 0 : slide.content.usePlaceholder()) && (!this.isClosing || !pswp.mainScroll.isShifted());
  4856. if (!this._animateZoom) {
  4857. this._animateRootOpacity = true;
  4858. if (this.isOpening && slide) {
  4859. slide.zoomAndPanToInitial();
  4860. slide.applyCurrentZoomPan();
  4861. }
  4862. } else {
  4863. var _options$showHideOpac;
  4864. this._animateRootOpacity = (_options$showHideOpac = options.showHideOpacity) !== null && _options$showHideOpac !== void 0 ? _options$showHideOpac : false;
  4865. }
  4866. this._animateBgOpacity = !this._animateRootOpacity && this.pswp.options.bgOpacity > MIN_OPACITY;
  4867. this._opacityElement = this._animateRootOpacity ? pswp.element : pswp.bg;
  4868. if (!this._useAnimation) {
  4869. this._duration = 0;
  4870. this._animateZoom = false;
  4871. this._animateBgOpacity = false;
  4872. this._animateRootOpacity = true;
  4873. if (this.isOpening) {
  4874. if (pswp.element) {
  4875. pswp.element.style.opacity = String(MIN_OPACITY);
  4876. }
  4877. pswp.applyBgOpacity(1);
  4878. }
  4879. return;
  4880. }
  4881. if (this._animateZoom && this._thumbBounds && this._thumbBounds.innerRect) {
  4882. var _this$pswp$currSlide;
  4883. // Properties are used when animation from cropped thumbnail
  4884. this._croppedZoom = true;
  4885. this._cropContainer1 = this.pswp.container;
  4886. this._cropContainer2 = (_this$pswp$currSlide = this.pswp.currSlide) === null || _this$pswp$currSlide === void 0 ? void 0 : _this$pswp$currSlide.holderElement;
  4887. if (pswp.container) {
  4888. pswp.container.style.overflow = 'hidden';
  4889. pswp.container.style.width = pswp.viewportSize.x + 'px';
  4890. }
  4891. } else {
  4892. this._croppedZoom = false;
  4893. }
  4894. if (this.isOpening) {
  4895. // Apply styles before opening transition
  4896. if (this._animateRootOpacity) {
  4897. if (pswp.element) {
  4898. pswp.element.style.opacity = String(MIN_OPACITY);
  4899. }
  4900. pswp.applyBgOpacity(1);
  4901. } else {
  4902. if (this._animateBgOpacity && pswp.bg) {
  4903. pswp.bg.style.opacity = String(MIN_OPACITY);
  4904. }
  4905. if (pswp.element) {
  4906. pswp.element.style.opacity = '1';
  4907. }
  4908. }
  4909. if (this._animateZoom) {
  4910. this._setClosedStateZoomPan();
  4911. if (this._placeholder) {
  4912. // tell browser that we plan to animate the placeholder
  4913. this._placeholder.style.willChange = 'transform'; // hide placeholder to allow hiding of
  4914. // elements that overlap it (such as icons over the thumbnail)
  4915. this._placeholder.style.opacity = String(MIN_OPACITY);
  4916. }
  4917. }
  4918. } else if (this.isClosing) {
  4919. // hide nearby slides to make sure that
  4920. // they are not painted during the transition
  4921. if (pswp.mainScroll.itemHolders[0]) {
  4922. pswp.mainScroll.itemHolders[0].el.style.display = 'none';
  4923. }
  4924. if (pswp.mainScroll.itemHolders[2]) {
  4925. pswp.mainScroll.itemHolders[2].el.style.display = 'none';
  4926. }
  4927. if (this._croppedZoom) {
  4928. if (pswp.mainScroll.x !== 0) {
  4929. // shift the main scroller to zero position
  4930. pswp.mainScroll.resetPosition();
  4931. pswp.mainScroll.resize();
  4932. }
  4933. }
  4934. }
  4935. }
  4936. /** @private */
  4937. _start() {
  4938. if (this.isOpening && this._useAnimation && this._placeholder && this._placeholder.tagName === 'IMG') {
  4939. // To ensure smooth animation
  4940. // we wait till the current slide image placeholder is decoded,
  4941. // but no longer than 250ms,
  4942. // and no shorter than 50ms
  4943. // (just using requestanimationframe is not enough in Firefox,
  4944. // for some reason)
  4945. new Promise(resolve => {
  4946. let decoded = false;
  4947. let isDelaying = true;
  4948. decodeImage(
  4949. /** @type {HTMLImageElement} */
  4950. this._placeholder).finally(() => {
  4951. decoded = true;
  4952. if (!isDelaying) {
  4953. resolve(true);
  4954. }
  4955. });
  4956. setTimeout(() => {
  4957. isDelaying = false;
  4958. if (decoded) {
  4959. resolve(true);
  4960. }
  4961. }, 50);
  4962. setTimeout(resolve, 250);
  4963. }).finally(() => this._initiate());
  4964. } else {
  4965. this._initiate();
  4966. }
  4967. }
  4968. /** @private */
  4969. _initiate() {
  4970. var _this$pswp$element, _this$pswp$element2;
  4971. (_this$pswp$element = this.pswp.element) === null || _this$pswp$element === void 0 || _this$pswp$element.style.setProperty('--pswp-transition-duration', this._duration + 'ms');
  4972. this.pswp.dispatch(this.isOpening ? 'openingAnimationStart' : 'closingAnimationStart'); // legacy event
  4973. this.pswp.dispatch(
  4974. /** @type {'initialZoomIn' | 'initialZoomOut'} */
  4975. 'initialZoom' + (this.isOpening ? 'In' : 'Out'));
  4976. (_this$pswp$element2 = this.pswp.element) === null || _this$pswp$element2 === void 0 || _this$pswp$element2.classList.toggle('pswp--ui-visible', this.isOpening);
  4977. if (this.isOpening) {
  4978. if (this._placeholder) {
  4979. // unhide the placeholder
  4980. this._placeholder.style.opacity = '1';
  4981. }
  4982. this._animateToOpenState();
  4983. } else if (this.isClosing) {
  4984. this._animateToClosedState();
  4985. }
  4986. if (!this._useAnimation) {
  4987. this._onAnimationComplete();
  4988. }
  4989. }
  4990. /** @private */
  4991. _onAnimationComplete() {
  4992. const {
  4993. pswp
  4994. } = this;
  4995. this.isOpen = this.isOpening;
  4996. this.isClosed = this.isClosing;
  4997. this.isOpening = false;
  4998. this.isClosing = false;
  4999. pswp.dispatch(this.isOpen ? 'openingAnimationEnd' : 'closingAnimationEnd'); // legacy event
  5000. pswp.dispatch(
  5001. /** @type {'initialZoomInEnd' | 'initialZoomOutEnd'} */
  5002. 'initialZoom' + (this.isOpen ? 'InEnd' : 'OutEnd'));
  5003. if (this.isClosed) {
  5004. pswp.destroy();
  5005. } else if (this.isOpen) {
  5006. var _pswp$currSlide;
  5007. if (this._animateZoom && pswp.container) {
  5008. pswp.container.style.overflow = 'visible';
  5009. pswp.container.style.width = '100%';
  5010. }
  5011. (_pswp$currSlide = pswp.currSlide) === null || _pswp$currSlide === void 0 || _pswp$currSlide.applyCurrentZoomPan();
  5012. }
  5013. }
  5014. /** @private */
  5015. _animateToOpenState() {
  5016. const {
  5017. pswp
  5018. } = this;
  5019. if (this._animateZoom) {
  5020. if (this._croppedZoom && this._cropContainer1 && this._cropContainer2) {
  5021. this._animateTo(this._cropContainer1, 'transform', 'translate3d(0,0,0)');
  5022. this._animateTo(this._cropContainer2, 'transform', 'none');
  5023. }
  5024. if (pswp.currSlide) {
  5025. pswp.currSlide.zoomAndPanToInitial();
  5026. this._animateTo(pswp.currSlide.container, 'transform', pswp.currSlide.getCurrentTransform());
  5027. }
  5028. }
  5029. if (this._animateBgOpacity && pswp.bg) {
  5030. this._animateTo(pswp.bg, 'opacity', String(pswp.options.bgOpacity));
  5031. }
  5032. if (this._animateRootOpacity && pswp.element) {
  5033. this._animateTo(pswp.element, 'opacity', '1');
  5034. }
  5035. }
  5036. /** @private */
  5037. _animateToClosedState() {
  5038. const {
  5039. pswp
  5040. } = this;
  5041. if (this._animateZoom) {
  5042. this._setClosedStateZoomPan(true);
  5043. } // do not animate opacity if it's already at 0
  5044. if (this._animateBgOpacity && pswp.bgOpacity > 0.01 && pswp.bg) {
  5045. this._animateTo(pswp.bg, 'opacity', '0');
  5046. }
  5047. if (this._animateRootOpacity && pswp.element) {
  5048. this._animateTo(pswp.element, 'opacity', '0');
  5049. }
  5050. }
  5051. /**
  5052. * @private
  5053. * @param {boolean} [animate]
  5054. */
  5055. _setClosedStateZoomPan(animate) {
  5056. if (!this._thumbBounds) return;
  5057. const {
  5058. pswp
  5059. } = this;
  5060. const {
  5061. innerRect
  5062. } = this._thumbBounds;
  5063. const {
  5064. currSlide,
  5065. viewportSize
  5066. } = pswp;
  5067. if (this._croppedZoom && innerRect && this._cropContainer1 && this._cropContainer2) {
  5068. const containerOnePanX = -viewportSize.x + (this._thumbBounds.x - innerRect.x) + innerRect.w;
  5069. const containerOnePanY = -viewportSize.y + (this._thumbBounds.y - innerRect.y) + innerRect.h;
  5070. const containerTwoPanX = viewportSize.x - innerRect.w;
  5071. const containerTwoPanY = viewportSize.y - innerRect.h;
  5072. if (animate) {
  5073. this._animateTo(this._cropContainer1, 'transform', toTransformString(containerOnePanX, containerOnePanY));
  5074. this._animateTo(this._cropContainer2, 'transform', toTransformString(containerTwoPanX, containerTwoPanY));
  5075. } else {
  5076. setTransform(this._cropContainer1, containerOnePanX, containerOnePanY);
  5077. setTransform(this._cropContainer2, containerTwoPanX, containerTwoPanY);
  5078. }
  5079. }
  5080. if (currSlide) {
  5081. equalizePoints(currSlide.pan, innerRect || this._thumbBounds);
  5082. currSlide.currZoomLevel = this._thumbBounds.w / currSlide.width;
  5083. if (animate) {
  5084. this._animateTo(currSlide.container, 'transform', currSlide.getCurrentTransform());
  5085. } else {
  5086. currSlide.applyCurrentZoomPan();
  5087. }
  5088. }
  5089. }
  5090. /**
  5091. * @private
  5092. * @param {HTMLElement} target
  5093. * @param {'transform' | 'opacity'} prop
  5094. * @param {string} propValue
  5095. */
  5096. _animateTo(target, prop, propValue) {
  5097. if (!this._duration) {
  5098. target.style[prop] = propValue;
  5099. return;
  5100. }
  5101. const {
  5102. animations
  5103. } = this.pswp;
  5104. /** @type {AnimationProps} */
  5105. const animProps = {
  5106. duration: this._duration,
  5107. easing: this.pswp.options.easing,
  5108. onComplete: () => {
  5109. if (!animations.activeAnimations.length) {
  5110. this._onAnimationComplete();
  5111. }
  5112. },
  5113. target
  5114. };
  5115. animProps[prop] = propValue;
  5116. animations.startTransition(animProps);
  5117. }
  5118. }
  5119. /**
  5120. * @template T
  5121. * @typedef {import('./types.js').Type<T>} Type<T>
  5122. */
  5123. /** @typedef {import('./slide/slide.js').SlideData} SlideData */
  5124. /** @typedef {import('./slide/zoom-level.js').ZoomLevelOption} ZoomLevelOption */
  5125. /** @typedef {import('./ui/ui-element.js').UIElementData} UIElementData */
  5126. /** @typedef {import('./main-scroll.js').ItemHolder} ItemHolder */
  5127. /** @typedef {import('./core/eventable.js').PhotoSwipeEventsMap} PhotoSwipeEventsMap */
  5128. /** @typedef {import('./core/eventable.js').PhotoSwipeFiltersMap} PhotoSwipeFiltersMap */
  5129. /** @typedef {import('./slide/get-thumb-bounds').Bounds} Bounds */
  5130. /**
  5131. * @template {keyof PhotoSwipeEventsMap} T
  5132. * @typedef {import('./core/eventable.js').EventCallback<T>} EventCallback<T>
  5133. */
  5134. /**
  5135. * @template {keyof PhotoSwipeEventsMap} T
  5136. * @typedef {import('./core/eventable.js').AugmentedEvent<T>} AugmentedEvent<T>
  5137. */
  5138. /** @typedef {{ x: number; y: number; id?: string | number }} Point */
  5139. /** @typedef {{ top: number; bottom: number; left: number; right: number }} Padding */
  5140. /** @typedef {SlideData[]} DataSourceArray */
  5141. /** @typedef {{ gallery: HTMLElement; items?: HTMLElement[] }} DataSourceObject */
  5142. /** @typedef {DataSourceArray | DataSourceObject} DataSource */
  5143. /** @typedef {(point: Point, originalEvent: PointerEvent) => void} ActionFn */
  5144. /** @typedef {'close' | 'next' | 'zoom' | 'zoom-or-close' | 'toggle-controls'} ActionType */
  5145. /** @typedef {Type<PhotoSwipe> | { default: Type<PhotoSwipe> }} PhotoSwipeModule */
  5146. /** @typedef {PhotoSwipeModule | Promise<PhotoSwipeModule> | (() => Promise<PhotoSwipeModule>)} PhotoSwipeModuleOption */
  5147. /**
  5148. * @typedef {string | NodeListOf<HTMLElement> | HTMLElement[] | HTMLElement} ElementProvider
  5149. */
  5150. /** @typedef {Partial<PreparedPhotoSwipeOptions>} PhotoSwipeOptions https://photoswipe.com/options/ */
  5151. /**
  5152. * @typedef {Object} PreparedPhotoSwipeOptions
  5153. *
  5154. * @prop {DataSource} [dataSource]
  5155. * Pass an array of any items via dataSource option. Its length will determine amount of slides
  5156. * (which may be modified further from numItems event).
  5157. *
  5158. * Each item should contain data that you need to generate slide
  5159. * (for image slide it would be src (image URL), width (image width), height, srcset, alt).
  5160. *
  5161. * If these properties are not present in your initial array, you may "pre-parse" each item from itemData filter.
  5162. *
  5163. * @prop {number} bgOpacity
  5164. * Background backdrop opacity, always define it via this option and not via CSS rgba color.
  5165. *
  5166. * @prop {number} spacing
  5167. * Spacing between slides. Defined as ratio relative to the viewport width (0.1 = 10% of viewport).
  5168. *
  5169. * @prop {boolean} allowPanToNext
  5170. * Allow swipe navigation to the next slide when the current slide is zoomed. Does not apply to mouse events.
  5171. *
  5172. * @prop {boolean} loop
  5173. * If set to true you'll be able to swipe from the last to the first image.
  5174. * Option is always false when there are less than 3 slides.
  5175. *
  5176. * @prop {boolean} [wheelToZoom]
  5177. * By default PhotoSwipe zooms image with ctrl-wheel, if you enable this option - image will zoom just via wheel.
  5178. *
  5179. * @prop {boolean} pinchToClose
  5180. * Pinch touch gesture to close the gallery.
  5181. *
  5182. * @prop {boolean} closeOnVerticalDrag
  5183. * Vertical drag gesture to close the PhotoSwipe.
  5184. *
  5185. * @prop {Padding} [padding]
  5186. * Slide area padding (in pixels).
  5187. *
  5188. * @prop {(viewportSize: Point, itemData: SlideData, index: number) => Padding} [paddingFn]
  5189. * The option is checked frequently, so make sure it's performant. Overrides padding option if defined. For example:
  5190. *
  5191. * @prop {number | false} hideAnimationDuration
  5192. * Transition duration in milliseconds, can be 0.
  5193. *
  5194. * @prop {number | false} showAnimationDuration
  5195. * Transition duration in milliseconds, can be 0.
  5196. *
  5197. * @prop {number | false} zoomAnimationDuration
  5198. * Transition duration in milliseconds, can be 0.
  5199. *
  5200. * @prop {string} easing
  5201. * String, 'cubic-bezier(.4,0,.22,1)'. CSS easing function for open/close/zoom transitions.
  5202. *
  5203. * @prop {boolean} escKey
  5204. * Esc key to close.
  5205. *
  5206. * @prop {boolean} arrowKeys
  5207. * Left/right arrow keys for navigation.
  5208. *
  5209. * @prop {boolean} trapFocus
  5210. * Trap focus within PhotoSwipe element while it's open.
  5211. *
  5212. * @prop {boolean} returnFocus
  5213. * Restore focus the last active element after PhotoSwipe is closed.
  5214. *
  5215. * @prop {boolean} clickToCloseNonZoomable
  5216. * If image is not zoomable (for example, smaller than viewport) it can be closed by clicking on it.
  5217. *
  5218. * @prop {ActionType | ActionFn | false} imageClickAction
  5219. * Refer to click and tap actions page.
  5220. *
  5221. * @prop {ActionType | ActionFn | false} bgClickAction
  5222. * Refer to click and tap actions page.
  5223. *
  5224. * @prop {ActionType | ActionFn | false} tapAction
  5225. * Refer to click and tap actions page.
  5226. *
  5227. * @prop {ActionType | ActionFn | false} doubleTapAction
  5228. * Refer to click and tap actions page.
  5229. *
  5230. * @prop {number} preloaderDelay
  5231. * Delay before the loading indicator will be displayed,
  5232. * if image is loaded during it - the indicator will not be displayed at all. Can be zero.
  5233. *
  5234. * @prop {string} indexIndicatorSep
  5235. * Used for slide count indicator ("1 of 10 ").
  5236. *
  5237. * @prop {(options: PhotoSwipeOptions, pswp: PhotoSwipeBase) => Point} [getViewportSizeFn]
  5238. * A function that should return slide viewport width and height, in format {x: 100, y: 100}.
  5239. *
  5240. * @prop {string} errorMsg
  5241. * Message to display when the image wasn't able to load. If you need to display HTML - use contentErrorElement filter.
  5242. *
  5243. * @prop {[number, number]} preload
  5244. * Lazy loading of nearby slides based on direction of movement. Should be an array with two integers,
  5245. * first one - number of items to preload before the current image, second one - after the current image.
  5246. * Two nearby images are always loaded.
  5247. *
  5248. * @prop {string} [mainClass]
  5249. * Class that will be added to the root element of PhotoSwipe, may contain multiple separated by space.
  5250. * Example on Styling page.
  5251. *
  5252. * @prop {HTMLElement} [appendToEl]
  5253. * Element to which PhotoSwipe dialog will be appended when it opens.
  5254. *
  5255. * @prop {number} maxWidthToAnimate
  5256. * Maximum width of image to animate, if initial rendered image width
  5257. * is larger than this value - the opening/closing transition will be automatically disabled.
  5258. *
  5259. * @prop {string} [closeTitle]
  5260. * Translating
  5261. *
  5262. * @prop {string} [zoomTitle]
  5263. * Translating
  5264. *
  5265. * @prop {string} [arrowPrevTitle]
  5266. * Translating
  5267. *
  5268. * @prop {string} [arrowNextTitle]
  5269. * Translating
  5270. *
  5271. * @prop {'zoom' | 'fade' | 'none'} [showHideAnimationType]
  5272. * To adjust opening or closing transition type use lightbox option `showHideAnimationType` (`String`).
  5273. * It supports three values - `zoom` (default), `fade` (default if there is no thumbnail) and `none`.
  5274. *
  5275. * Animations are automatically disabled if user `(prefers-reduced-motion: reduce)`.
  5276. *
  5277. * @prop {number} index
  5278. * Defines start slide index.
  5279. *
  5280. * @prop {(e: MouseEvent) => number} [getClickedIndexFn]
  5281. *
  5282. * @prop {boolean} [arrowPrev]
  5283. * @prop {boolean} [arrowNext]
  5284. * @prop {boolean} [zoom]
  5285. * @prop {boolean} [close]
  5286. * @prop {boolean} [counter]
  5287. *
  5288. * @prop {string} [arrowPrevSVG]
  5289. * @prop {string} [arrowNextSVG]
  5290. * @prop {string} [zoomSVG]
  5291. * @prop {string} [closeSVG]
  5292. * @prop {string} [counterSVG]
  5293. *
  5294. * @prop {string} [arrowPrevTitle]
  5295. * @prop {string} [arrowNextTitle]
  5296. * @prop {string} [zoomTitle]
  5297. * @prop {string} [closeTitle]
  5298. * @prop {string} [counterTitle]
  5299. *
  5300. * @prop {ZoomLevelOption} [initialZoomLevel]
  5301. * @prop {ZoomLevelOption} [secondaryZoomLevel]
  5302. * @prop {ZoomLevelOption} [maxZoomLevel]
  5303. *
  5304. * @prop {boolean} [mouseMovePan]
  5305. * @prop {Point | null} [initialPointerPos]
  5306. * @prop {boolean} [showHideOpacity]
  5307. *
  5308. * @prop {PhotoSwipeModuleOption} [pswpModule]
  5309. * @prop {() => Promise<any>} [openPromise]
  5310. * @prop {boolean} [preloadFirstSlide]
  5311. * @prop {ElementProvider} [gallery]
  5312. * @prop {string} [gallerySelector]
  5313. * @prop {ElementProvider} [children]
  5314. * @prop {string} [childSelector]
  5315. * @prop {string | false} [thumbSelector]
  5316. */
  5317. /** @type {PreparedPhotoSwipeOptions} */
  5318. const defaultOptions = {
  5319. allowPanToNext: true,
  5320. spacing: 0.1,
  5321. loop: true,
  5322. pinchToClose: true,
  5323. closeOnVerticalDrag: true,
  5324. hideAnimationDuration: 333,
  5325. showAnimationDuration: 333,
  5326. zoomAnimationDuration: 333,
  5327. escKey: true,
  5328. arrowKeys: true,
  5329. trapFocus: true,
  5330. returnFocus: true,
  5331. maxWidthToAnimate: 4000,
  5332. clickToCloseNonZoomable: true,
  5333. imageClickAction: 'zoom-or-close',
  5334. bgClickAction: 'close',
  5335. tapAction: 'toggle-controls',
  5336. doubleTapAction: 'zoom',
  5337. indexIndicatorSep: ' / ',
  5338. preloaderDelay: 2000,
  5339. bgOpacity: 0.8,
  5340. index: 0,
  5341. errorMsg: 'The image cannot be loaded',
  5342. preload: [1, 2],
  5343. easing: 'cubic-bezier(.4,0,.22,1)'
  5344. };
  5345. /**
  5346. * PhotoSwipe Core
  5347. */
  5348. class PhotoSwipe extends PhotoSwipeBase {
  5349. /**
  5350. * @param {PhotoSwipeOptions} [options]
  5351. */
  5352. constructor(options) {
  5353. super();
  5354. this.options = this._prepareOptions(options || {});
  5355. /**
  5356. * offset of viewport relative to document
  5357. *
  5358. * @type {Point}
  5359. */
  5360. this.offset = {
  5361. x: 0,
  5362. y: 0
  5363. };
  5364. /**
  5365. * @type {Point}
  5366. * @private
  5367. */
  5368. this._prevViewportSize = {
  5369. x: 0,
  5370. y: 0
  5371. };
  5372. /**
  5373. * Size of scrollable PhotoSwipe viewport
  5374. *
  5375. * @type {Point}
  5376. */
  5377. this.viewportSize = {
  5378. x: 0,
  5379. y: 0
  5380. };
  5381. /**
  5382. * background (backdrop) opacity
  5383. */
  5384. this.bgOpacity = 1;
  5385. this.currIndex = 0;
  5386. this.potentialIndex = 0;
  5387. this.isOpen = false;
  5388. this.isDestroying = false;
  5389. this.hasMouse = false;
  5390. /**
  5391. * @private
  5392. * @type {SlideData}
  5393. */
  5394. this._initialItemData = {};
  5395. /** @type {Bounds | undefined} */
  5396. this._initialThumbBounds = undefined;
  5397. /** @type {HTMLDivElement | undefined} */
  5398. this.topBar = undefined;
  5399. /** @type {HTMLDivElement | undefined} */
  5400. this.element = undefined;
  5401. /** @type {HTMLDivElement | undefined} */
  5402. this.template = undefined;
  5403. /** @type {HTMLDivElement | undefined} */
  5404. this.container = undefined;
  5405. /** @type {HTMLElement | undefined} */
  5406. this.scrollWrap = undefined;
  5407. /** @type {Slide | undefined} */
  5408. this.currSlide = undefined;
  5409. this.events = new DOMEvents();
  5410. this.animations = new Animations();
  5411. this.mainScroll = new MainScroll(this);
  5412. this.gestures = new Gestures(this);
  5413. this.opener = new Opener(this);
  5414. this.keyboard = new Keyboard(this);
  5415. this.contentLoader = new ContentLoader(this);
  5416. }
  5417. /** @returns {boolean} */
  5418. init() {
  5419. if (this.isOpen || this.isDestroying) {
  5420. return false;
  5421. }
  5422. this.isOpen = true;
  5423. this.dispatch('init'); // legacy
  5424. this.dispatch('beforeOpen');
  5425. this._createMainStructure(); // add classes to the root element of PhotoSwipe
  5426. let rootClasses = 'pswp--open';
  5427. if (this.gestures.supportsTouch) {
  5428. rootClasses += ' pswp--touch';
  5429. }
  5430. if (this.options.mainClass) {
  5431. rootClasses += ' ' + this.options.mainClass;
  5432. }
  5433. if (this.element) {
  5434. this.element.className += ' ' + rootClasses;
  5435. }
  5436. this.currIndex = this.options.index || 0;
  5437. this.potentialIndex = this.currIndex;
  5438. this.dispatch('firstUpdate'); // starting index can be modified here
  5439. // initialize scroll wheel handler to block the scroll
  5440. this.scrollWheel = new ScrollWheel(this); // sanitize index
  5441. if (Number.isNaN(this.currIndex) || this.currIndex < 0 || this.currIndex >= this.getNumItems()) {
  5442. this.currIndex = 0;
  5443. }
  5444. if (!this.gestures.supportsTouch) {
  5445. // enable mouse features if no touch support detected
  5446. this.mouseDetected();
  5447. } // causes forced synchronous layout
  5448. this.updateSize();
  5449. this.offset.y = window.pageYOffset;
  5450. this._initialItemData = this.getItemData(this.currIndex);
  5451. this.dispatch('gettingData', {
  5452. index: this.currIndex,
  5453. data: this._initialItemData,
  5454. slide: undefined
  5455. }); // *Layout* - calculate size and position of elements here
  5456. this._initialThumbBounds = this.getThumbBounds();
  5457. this.dispatch('initialLayout');
  5458. this.on('openingAnimationEnd', () => {
  5459. const {
  5460. itemHolders
  5461. } = this.mainScroll; // Add content to the previous and next slide
  5462. if (itemHolders[0]) {
  5463. itemHolders[0].el.style.display = 'block';
  5464. this.setContent(itemHolders[0], this.currIndex - 1);
  5465. }
  5466. if (itemHolders[2]) {
  5467. itemHolders[2].el.style.display = 'block';
  5468. this.setContent(itemHolders[2], this.currIndex + 1);
  5469. }
  5470. this.appendHeavy();
  5471. this.contentLoader.updateLazy();
  5472. this.events.add(window, 'resize', this._handlePageResize.bind(this));
  5473. this.events.add(window, 'scroll', this._updatePageScrollOffset.bind(this));
  5474. this.dispatch('bindEvents');
  5475. }); // set content for center slide (first time)
  5476. if (this.mainScroll.itemHolders[1]) {
  5477. this.setContent(this.mainScroll.itemHolders[1], this.currIndex);
  5478. }
  5479. this.dispatch('change');
  5480. this.opener.open();
  5481. this.dispatch('afterInit');
  5482. return true;
  5483. }
  5484. /**
  5485. * Get looped slide index
  5486. * (for example, -1 will return the last slide)
  5487. *
  5488. * @param {number} index
  5489. * @returns {number}
  5490. */
  5491. getLoopedIndex(index) {
  5492. const numSlides = this.getNumItems();
  5493. if (this.options.loop) {
  5494. if (index > numSlides - 1) {
  5495. index -= numSlides;
  5496. }
  5497. if (index < 0) {
  5498. index += numSlides;
  5499. }
  5500. }
  5501. return clamp(index, 0, numSlides - 1);
  5502. }
  5503. appendHeavy() {
  5504. this.mainScroll.itemHolders.forEach(itemHolder => {
  5505. var _itemHolder$slide;
  5506. (_itemHolder$slide = itemHolder.slide) === null || _itemHolder$slide === void 0 || _itemHolder$slide.appendHeavy();
  5507. });
  5508. }
  5509. /**
  5510. * Change the slide
  5511. * @param {number} index New index
  5512. */
  5513. goTo(index) {
  5514. this.mainScroll.moveIndexBy(this.getLoopedIndex(index) - this.potentialIndex);
  5515. }
  5516. /**
  5517. * Go to the next slide.
  5518. */
  5519. next() {
  5520. this.goTo(this.potentialIndex + 1);
  5521. }
  5522. /**
  5523. * Go to the previous slide.
  5524. */
  5525. prev() {
  5526. this.goTo(this.potentialIndex - 1);
  5527. }
  5528. /**
  5529. * @see slide/slide.js zoomTo
  5530. *
  5531. * @param {Parameters<Slide['zoomTo']>} args
  5532. */
  5533. zoomTo(...args) {
  5534. var _this$currSlide;
  5535. (_this$currSlide = this.currSlide) === null || _this$currSlide === void 0 || _this$currSlide.zoomTo(...args);
  5536. }
  5537. /**
  5538. * @see slide/slide.js toggleZoom
  5539. */
  5540. toggleZoom() {
  5541. var _this$currSlide2;
  5542. (_this$currSlide2 = this.currSlide) === null || _this$currSlide2 === void 0 || _this$currSlide2.toggleZoom();
  5543. }
  5544. /**
  5545. * Close the gallery.
  5546. * After closing transition ends - destroy it
  5547. */
  5548. close() {
  5549. if (!this.opener.isOpen || this.isDestroying) {
  5550. return;
  5551. }
  5552. this.isDestroying = true;
  5553. this.dispatch('close');
  5554. this.events.removeAll();
  5555. this.opener.close();
  5556. }
  5557. /**
  5558. * Destroys the gallery:
  5559. * - instantly closes the gallery
  5560. * - unbinds events,
  5561. * - cleans intervals and timeouts
  5562. * - removes elements from DOM
  5563. */
  5564. destroy() {
  5565. var _this$element;
  5566. if (!this.isDestroying) {
  5567. this.options.showHideAnimationType = 'none';
  5568. this.close();
  5569. return;
  5570. }
  5571. this.dispatch('destroy');
  5572. this._listeners = {};
  5573. if (this.scrollWrap) {
  5574. this.scrollWrap.ontouchmove = null;
  5575. this.scrollWrap.ontouchend = null;
  5576. }
  5577. (_this$element = this.element) === null || _this$element === void 0 || _this$element.remove();
  5578. this.mainScroll.itemHolders.forEach(itemHolder => {
  5579. var _itemHolder$slide2;
  5580. (_itemHolder$slide2 = itemHolder.slide) === null || _itemHolder$slide2 === void 0 || _itemHolder$slide2.destroy();
  5581. });
  5582. this.contentLoader.destroy();
  5583. this.events.removeAll();
  5584. }
  5585. /**
  5586. * Refresh/reload content of a slide by its index
  5587. *
  5588. * @param {number} slideIndex
  5589. */
  5590. refreshSlideContent(slideIndex) {
  5591. this.contentLoader.removeByIndex(slideIndex);
  5592. this.mainScroll.itemHolders.forEach((itemHolder, i) => {
  5593. var _this$currSlide$index, _this$currSlide3;
  5594. let potentialHolderIndex = ((_this$currSlide$index = (_this$currSlide3 = this.currSlide) === null || _this$currSlide3 === void 0 ? void 0 : _this$currSlide3.index) !== null && _this$currSlide$index !== void 0 ? _this$currSlide$index : 0) - 1 + i;
  5595. if (this.canLoop()) {
  5596. potentialHolderIndex = this.getLoopedIndex(potentialHolderIndex);
  5597. }
  5598. if (potentialHolderIndex === slideIndex) {
  5599. // set the new slide content
  5600. this.setContent(itemHolder, slideIndex, true); // activate the new slide if it's current
  5601. if (i === 1) {
  5602. var _itemHolder$slide3;
  5603. this.currSlide = itemHolder.slide;
  5604. (_itemHolder$slide3 = itemHolder.slide) === null || _itemHolder$slide3 === void 0 || _itemHolder$slide3.setIsActive(true);
  5605. }
  5606. }
  5607. });
  5608. this.dispatch('change');
  5609. }
  5610. /**
  5611. * Set slide content
  5612. *
  5613. * @param {ItemHolder} holder mainScroll.itemHolders array item
  5614. * @param {number} index Slide index
  5615. * @param {boolean} [force] If content should be set even if index wasn't changed
  5616. */
  5617. setContent(holder, index, force) {
  5618. if (this.canLoop()) {
  5619. index = this.getLoopedIndex(index);
  5620. }
  5621. if (holder.slide) {
  5622. if (holder.slide.index === index && !force) {
  5623. // exit if holder already contains this slide
  5624. // this could be common when just three slides are used
  5625. return;
  5626. } // destroy previous slide
  5627. holder.slide.destroy();
  5628. holder.slide = undefined;
  5629. } // exit if no loop and index is out of bounds
  5630. if (!this.canLoop() && (index < 0 || index >= this.getNumItems())) {
  5631. return;
  5632. }
  5633. const itemData = this.getItemData(index);
  5634. holder.slide = new Slide(itemData, index, this); // set current slide
  5635. if (index === this.currIndex) {
  5636. this.currSlide = holder.slide;
  5637. }
  5638. holder.slide.append(holder.el);
  5639. }
  5640. /** @returns {Point} */
  5641. getViewportCenterPoint() {
  5642. return {
  5643. x: this.viewportSize.x / 2,
  5644. y: this.viewportSize.y / 2
  5645. };
  5646. }
  5647. /**
  5648. * Update size of all elements.
  5649. * Executed on init and on page resize.
  5650. *
  5651. * @param {boolean} [force] Update size even if size of viewport was not changed.
  5652. */
  5653. updateSize(force) {
  5654. // let item;
  5655. // let itemIndex;
  5656. if (this.isDestroying) {
  5657. // exit if PhotoSwipe is closed or closing
  5658. // (to avoid errors, as resize event might be delayed)
  5659. return;
  5660. } //const newWidth = this.scrollWrap.clientWidth;
  5661. //const newHeight = this.scrollWrap.clientHeight;
  5662. const newViewportSize = getViewportSize(this.options, this);
  5663. if (!force && pointsEqual(newViewportSize, this._prevViewportSize)) {
  5664. // Exit if dimensions were not changed
  5665. return;
  5666. } //this._prevViewportSize.x = newWidth;
  5667. //this._prevViewportSize.y = newHeight;
  5668. equalizePoints(this._prevViewportSize, newViewportSize);
  5669. this.dispatch('beforeResize');
  5670. equalizePoints(this.viewportSize, this._prevViewportSize);
  5671. this._updatePageScrollOffset();
  5672. this.dispatch('viewportSize'); // Resize slides only after opener animation is finished
  5673. // and don't re-calculate size on inital size update
  5674. this.mainScroll.resize(this.opener.isOpen);
  5675. if (!this.hasMouse && window.matchMedia('(any-hover: hover)').matches) {
  5676. this.mouseDetected();
  5677. }
  5678. this.dispatch('resize');
  5679. }
  5680. /**
  5681. * @param {number} opacity
  5682. */
  5683. applyBgOpacity(opacity) {
  5684. this.bgOpacity = Math.max(opacity, 0);
  5685. if (this.bg) {
  5686. this.bg.style.opacity = String(this.bgOpacity * this.options.bgOpacity);
  5687. }
  5688. }
  5689. /**
  5690. * Whether mouse is detected
  5691. */
  5692. mouseDetected() {
  5693. if (!this.hasMouse) {
  5694. var _this$element2;
  5695. this.hasMouse = true;
  5696. (_this$element2 = this.element) === null || _this$element2 === void 0 || _this$element2.classList.add('pswp--has_mouse');
  5697. }
  5698. }
  5699. /**
  5700. * Page resize event handler
  5701. *
  5702. * @private
  5703. */
  5704. _handlePageResize() {
  5705. this.updateSize(); // In iOS webview, if element size depends on document size,
  5706. // it'll be measured incorrectly in resize event
  5707. //
  5708. // https://bugs.webkit.org/show_bug.cgi?id=170595
  5709. // https://hackernoon.com/onresize-event-broken-in-mobile-safari-d8469027bf4d
  5710. if (/iPhone|iPad|iPod/i.test(window.navigator.userAgent)) {
  5711. setTimeout(() => {
  5712. this.updateSize();
  5713. }, 500);
  5714. }
  5715. }
  5716. /**
  5717. * Page scroll offset is used
  5718. * to get correct coordinates
  5719. * relative to PhotoSwipe viewport.
  5720. *
  5721. * @private
  5722. */
  5723. _updatePageScrollOffset() {
  5724. this.setScrollOffset(0, window.pageYOffset);
  5725. }
  5726. /**
  5727. * @param {number} x
  5728. * @param {number} y
  5729. */
  5730. setScrollOffset(x, y) {
  5731. this.offset.x = x;
  5732. this.offset.y = y;
  5733. this.dispatch('updateScrollOffset');
  5734. }
  5735. /**
  5736. * Create main HTML structure of PhotoSwipe,
  5737. * and add it to DOM
  5738. *
  5739. * @private
  5740. */
  5741. _createMainStructure() {
  5742. // root DOM element of PhotoSwipe (.pswp)
  5743. this.element = createElement('pswp', 'div');
  5744. this.element.setAttribute('tabindex', '-1');
  5745. this.element.setAttribute('role', 'dialog'); // template is legacy prop
  5746. this.template = this.element; // Background is added as a separate element,
  5747. // as animating opacity is faster than animating rgba()
  5748. this.bg = createElement('pswp__bg', 'div', this.element);
  5749. this.scrollWrap = createElement('pswp__scroll-wrap', 'section', this.element);
  5750. this.container = createElement('pswp__container', 'div', this.scrollWrap); // aria pattern: carousel
  5751. this.scrollWrap.setAttribute('aria-roledescription', 'carousel');
  5752. this.container.setAttribute('aria-live', 'off');
  5753. this.container.setAttribute('id', 'pswp__items');
  5754. this.mainScroll.appendHolders();
  5755. this.ui = new UI(this);
  5756. this.ui.init(); // append to DOM
  5757. (this.options.appendToEl || document.body).appendChild(this.element);
  5758. }
  5759. /**
  5760. * Get position and dimensions of small thumbnail
  5761. * {x:,y:,w:}
  5762. *
  5763. * Height is optional (calculated based on the large image)
  5764. *
  5765. * @returns {Bounds | undefined}
  5766. */
  5767. getThumbBounds() {
  5768. return getThumbBounds(this.currIndex, this.currSlide ? this.currSlide.data : this._initialItemData, this);
  5769. }
  5770. /**
  5771. * If the PhotoSwipe can have continuous loop
  5772. * @returns Boolean
  5773. */
  5774. canLoop() {
  5775. return this.options.loop && this.getNumItems() > 2;
  5776. }
  5777. /**
  5778. * @private
  5779. * @param {PhotoSwipeOptions} options
  5780. * @returns {PreparedPhotoSwipeOptions}
  5781. */
  5782. _prepareOptions(options) {
  5783. if (window.matchMedia('(prefers-reduced-motion), (update: slow)').matches) {
  5784. options.showHideAnimationType = 'none';
  5785. options.zoomAnimationDuration = 0;
  5786. }
  5787. /** @type {PreparedPhotoSwipeOptions} */
  5788. return { ...defaultOptions,
  5789. ...options
  5790. };
  5791. }
  5792. }
  5793. export { PhotoSwipe as default };
  5794. //# sourceMappingURL=photoswipe.esm.js.map