photoswipe-lightbox.esm.js 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  1. /*!
  2. * PhotoSwipe Lightbox 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. * Get transform string
  25. *
  26. * @param {number} x
  27. * @param {number} [y]
  28. * @param {number} [scale]
  29. * @returns {string}
  30. */
  31. function toTransformString(x, y, scale) {
  32. let propValue = `translate3d(${x}px,${y || 0}px,0)`;
  33. if (scale !== undefined) {
  34. propValue += ` scale3d(${scale},${scale},1)`;
  35. }
  36. return propValue;
  37. }
  38. /**
  39. * Apply width and height CSS properties to element
  40. *
  41. * @param {HTMLElement} el
  42. * @param {string | number} w
  43. * @param {string | number} h
  44. */
  45. function setWidthHeight(el, w, h) {
  46. el.style.width = typeof w === 'number' ? `${w}px` : w;
  47. el.style.height = typeof h === 'number' ? `${h}px` : h;
  48. }
  49. /** @typedef {LOAD_STATE[keyof LOAD_STATE]} LoadState */
  50. /** @type {{ IDLE: 'idle'; LOADING: 'loading'; LOADED: 'loaded'; ERROR: 'error' }} */
  51. const LOAD_STATE = {
  52. IDLE: 'idle',
  53. LOADING: 'loading',
  54. LOADED: 'loaded',
  55. ERROR: 'error'
  56. };
  57. /**
  58. * Check if click or keydown event was dispatched
  59. * with a special key or via mouse wheel.
  60. *
  61. * @param {MouseEvent | KeyboardEvent} e
  62. * @returns {boolean}
  63. */
  64. function specialKeyUsed(e) {
  65. return 'button' in e && e.button === 1 || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey;
  66. }
  67. /**
  68. * Parse `gallery` or `children` options.
  69. *
  70. * @param {import('../photoswipe.js').ElementProvider} [option]
  71. * @param {string} [legacySelector]
  72. * @param {HTMLElement | Document} [parent]
  73. * @returns HTMLElement[]
  74. */
  75. function getElementsFromOption(option, legacySelector, parent = document) {
  76. /** @type {HTMLElement[]} */
  77. let elements = [];
  78. if (option instanceof Element) {
  79. elements = [option];
  80. } else if (option instanceof NodeList || Array.isArray(option)) {
  81. elements = Array.from(option);
  82. } else {
  83. const selector = typeof option === 'string' ? option : legacySelector;
  84. if (selector) {
  85. elements = Array.from(parent.querySelectorAll(selector));
  86. }
  87. }
  88. return elements;
  89. }
  90. /**
  91. * Check if variable is PhotoSwipe class
  92. *
  93. * @param {any} fn
  94. * @returns {boolean}
  95. */
  96. function isPswpClass(fn) {
  97. return typeof fn === 'function' && fn.prototype && fn.prototype.goTo;
  98. }
  99. /**
  100. * Check if browser is Safari
  101. *
  102. * @returns {boolean}
  103. */
  104. function isSafari() {
  105. return !!(navigator.vendor && navigator.vendor.match(/apple/i));
  106. }
  107. /** @typedef {import('../lightbox/lightbox.js').default} PhotoSwipeLightbox */
  108. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  109. /** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
  110. /** @typedef {import('../photoswipe.js').DataSource} DataSource */
  111. /** @typedef {import('../ui/ui-element.js').UIElementData} UIElementData */
  112. /** @typedef {import('../slide/content.js').default} ContentDefault */
  113. /** @typedef {import('../slide/slide.js').default} Slide */
  114. /** @typedef {import('../slide/slide.js').SlideData} SlideData */
  115. /** @typedef {import('../slide/zoom-level.js').default} ZoomLevel */
  116. /** @typedef {import('../slide/get-thumb-bounds.js').Bounds} Bounds */
  117. /**
  118. * Allow adding an arbitrary props to the Content
  119. * https://photoswipe.com/custom-content/#using-webp-image-format
  120. * @typedef {ContentDefault & Record<string, any>} Content
  121. */
  122. /** @typedef {{ x?: number; y?: number }} Point */
  123. /**
  124. * @typedef {Object} PhotoSwipeEventsMap https://photoswipe.com/events/
  125. *
  126. *
  127. * https://photoswipe.com/adding-ui-elements/
  128. *
  129. * @prop {undefined} uiRegister
  130. * @prop {{ data: UIElementData }} uiElementCreate
  131. *
  132. *
  133. * https://photoswipe.com/events/#initialization-events
  134. *
  135. * @prop {undefined} beforeOpen
  136. * @prop {undefined} firstUpdate
  137. * @prop {undefined} initialLayout
  138. * @prop {undefined} change
  139. * @prop {undefined} afterInit
  140. * @prop {undefined} bindEvents
  141. *
  142. *
  143. * https://photoswipe.com/events/#opening-or-closing-transition-events
  144. *
  145. * @prop {undefined} openingAnimationStart
  146. * @prop {undefined} openingAnimationEnd
  147. * @prop {undefined} closingAnimationStart
  148. * @prop {undefined} closingAnimationEnd
  149. *
  150. *
  151. * https://photoswipe.com/events/#closing-events
  152. *
  153. * @prop {undefined} close
  154. * @prop {undefined} destroy
  155. *
  156. *
  157. * https://photoswipe.com/events/#pointer-and-gesture-events
  158. *
  159. * @prop {{ originalEvent: PointerEvent }} pointerDown
  160. * @prop {{ originalEvent: PointerEvent }} pointerMove
  161. * @prop {{ originalEvent: PointerEvent }} pointerUp
  162. * @prop {{ bgOpacity: number }} pinchClose can be default prevented
  163. * @prop {{ panY: number }} verticalDrag can be default prevented
  164. *
  165. *
  166. * https://photoswipe.com/events/#slide-content-events
  167. *
  168. * @prop {{ content: Content }} contentInit
  169. * @prop {{ content: Content; isLazy: boolean }} contentLoad can be default prevented
  170. * @prop {{ content: Content; isLazy: boolean }} contentLoadImage can be default prevented
  171. * @prop {{ content: Content; slide: Slide; isError?: boolean }} loadComplete
  172. * @prop {{ content: Content; slide: Slide }} loadError
  173. * @prop {{ content: Content; width: number; height: number }} contentResize can be default prevented
  174. * @prop {{ content: Content; width: number; height: number; slide: Slide }} imageSizeChange
  175. * @prop {{ content: Content }} contentLazyLoad can be default prevented
  176. * @prop {{ content: Content }} contentAppend can be default prevented
  177. * @prop {{ content: Content }} contentActivate can be default prevented
  178. * @prop {{ content: Content }} contentDeactivate can be default prevented
  179. * @prop {{ content: Content }} contentRemove can be default prevented
  180. * @prop {{ content: Content }} contentDestroy can be default prevented
  181. *
  182. *
  183. * undocumented
  184. *
  185. * @prop {{ point: Point; originalEvent: PointerEvent }} imageClickAction can be default prevented
  186. * @prop {{ point: Point; originalEvent: PointerEvent }} bgClickAction can be default prevented
  187. * @prop {{ point: Point; originalEvent: PointerEvent }} tapAction can be default prevented
  188. * @prop {{ point: Point; originalEvent: PointerEvent }} doubleTapAction can be default prevented
  189. *
  190. * @prop {{ originalEvent: KeyboardEvent }} keydown can be default prevented
  191. * @prop {{ x: number; dragging: boolean }} moveMainScroll
  192. * @prop {{ slide: Slide }} firstZoomPan
  193. * @prop {{ slide: Slide | undefined, data: SlideData, index: number }} gettingData
  194. * @prop {undefined} beforeResize
  195. * @prop {undefined} resize
  196. * @prop {undefined} viewportSize
  197. * @prop {undefined} updateScrollOffset
  198. * @prop {{ slide: Slide }} slideInit
  199. * @prop {{ slide: Slide }} afterSetContent
  200. * @prop {{ slide: Slide }} slideLoad
  201. * @prop {{ slide: Slide }} appendHeavy can be default prevented
  202. * @prop {{ slide: Slide }} appendHeavyContent
  203. * @prop {{ slide: Slide }} slideActivate
  204. * @prop {{ slide: Slide }} slideDeactivate
  205. * @prop {{ slide: Slide }} slideDestroy
  206. * @prop {{ destZoomLevel: number, centerPoint: Point | undefined, transitionDuration: number | false | undefined }} beforeZoomTo
  207. * @prop {{ slide: Slide }} zoomPanUpdate
  208. * @prop {{ slide: Slide }} initialZoomPan
  209. * @prop {{ slide: Slide }} calcSlideSize
  210. * @prop {undefined} resolutionChanged
  211. * @prop {{ originalEvent: WheelEvent }} wheel can be default prevented
  212. * @prop {{ content: Content }} contentAppendImage can be default prevented
  213. * @prop {{ index: number; itemData: SlideData }} lazyLoadSlide can be default prevented
  214. * @prop {undefined} lazyLoad
  215. * @prop {{ slide: Slide }} calcBounds
  216. * @prop {{ zoomLevels: ZoomLevel, slideData: SlideData }} zoomLevelsUpdate
  217. *
  218. *
  219. * legacy
  220. *
  221. * @prop {undefined} init
  222. * @prop {undefined} initialZoomIn
  223. * @prop {undefined} initialZoomOut
  224. * @prop {undefined} initialZoomInEnd
  225. * @prop {undefined} initialZoomOutEnd
  226. * @prop {{ dataSource: DataSource | undefined, numItems: number }} numItems
  227. * @prop {{ itemData: SlideData; index: number }} itemData
  228. * @prop {{ index: number, itemData: SlideData, instance: PhotoSwipe }} thumbBounds
  229. */
  230. /**
  231. * @typedef {Object} PhotoSwipeFiltersMap https://photoswipe.com/filters/
  232. *
  233. * @prop {(numItems: number, dataSource: DataSource | undefined) => number} numItems
  234. * Modify the total amount of slides. Example on Data sources page.
  235. * https://photoswipe.com/filters/#numitems
  236. *
  237. * @prop {(itemData: SlideData, index: number) => SlideData} itemData
  238. * Modify slide item data. Example on Data sources page.
  239. * https://photoswipe.com/filters/#itemdata
  240. *
  241. * @prop {(itemData: SlideData, element: HTMLElement, linkEl: HTMLAnchorElement) => SlideData} domItemData
  242. * Modify item data when it's parsed from DOM element. Example on Data sources page.
  243. * https://photoswipe.com/filters/#domitemdata
  244. *
  245. * @prop {(clickedIndex: number, e: MouseEvent, instance: PhotoSwipeLightbox) => number} clickedIndex
  246. * Modify clicked gallery item index.
  247. * https://photoswipe.com/filters/#clickedindex
  248. *
  249. * @prop {(placeholderSrc: string | false, content: Content) => string | false} placeholderSrc
  250. * Modify placeholder image source.
  251. * https://photoswipe.com/filters/#placeholdersrc
  252. *
  253. * @prop {(isContentLoading: boolean, content: Content) => boolean} isContentLoading
  254. * Modify if the content is currently loading.
  255. * https://photoswipe.com/filters/#iscontentloading
  256. *
  257. * @prop {(isContentZoomable: boolean, content: Content) => boolean} isContentZoomable
  258. * Modify if the content can be zoomed.
  259. * https://photoswipe.com/filters/#iscontentzoomable
  260. *
  261. * @prop {(useContentPlaceholder: boolean, content: Content) => boolean} useContentPlaceholder
  262. * Modify if the placeholder should be used for the content.
  263. * https://photoswipe.com/filters/#usecontentplaceholder
  264. *
  265. * @prop {(isKeepingPlaceholder: boolean, content: Content) => boolean} isKeepingPlaceholder
  266. * Modify if the placeholder should be kept after the content is loaded.
  267. * https://photoswipe.com/filters/#iskeepingplaceholder
  268. *
  269. *
  270. * @prop {(contentErrorElement: HTMLElement, content: Content) => HTMLElement} contentErrorElement
  271. * Modify an element when the content has error state (for example, if image cannot be loaded).
  272. * https://photoswipe.com/filters/#contenterrorelement
  273. *
  274. * @prop {(element: HTMLElement, data: UIElementData) => HTMLElement} uiElement
  275. * Modify a UI element that's being created.
  276. * https://photoswipe.com/filters/#uielement
  277. *
  278. * @prop {(thumbnail: HTMLElement | null | undefined, itemData: SlideData, index: number) => HTMLElement} thumbEl
  279. * Modify the thumbnail element from which opening zoom animation starts or ends.
  280. * https://photoswipe.com/filters/#thumbel
  281. *
  282. * @prop {(thumbBounds: Bounds | undefined, itemData: SlideData, index: number) => Bounds} thumbBounds
  283. * Modify the thumbnail bounds from which opening zoom animation starts or ends.
  284. * https://photoswipe.com/filters/#thumbbounds
  285. *
  286. * @prop {(srcsetSizesWidth: number, content: Content) => number} srcsetSizesWidth
  287. *
  288. * @prop {(preventPointerEvent: boolean, event: PointerEvent, pointerType: string) => boolean} preventPointerEvent
  289. *
  290. */
  291. /**
  292. * @template {keyof PhotoSwipeFiltersMap} T
  293. * @typedef {{ fn: PhotoSwipeFiltersMap[T], priority: number }} Filter
  294. */
  295. /**
  296. * @template {keyof PhotoSwipeEventsMap} T
  297. * @typedef {PhotoSwipeEventsMap[T] extends undefined ? PhotoSwipeEvent<T> : PhotoSwipeEvent<T> & PhotoSwipeEventsMap[T]} AugmentedEvent
  298. */
  299. /**
  300. * @template {keyof PhotoSwipeEventsMap} T
  301. * @typedef {(event: AugmentedEvent<T>) => void} EventCallback
  302. */
  303. /**
  304. * Base PhotoSwipe event object
  305. *
  306. * @template {keyof PhotoSwipeEventsMap} T
  307. */
  308. class PhotoSwipeEvent {
  309. /**
  310. * @param {T} type
  311. * @param {PhotoSwipeEventsMap[T]} [details]
  312. */
  313. constructor(type, details) {
  314. this.type = type;
  315. this.defaultPrevented = false;
  316. if (details) {
  317. Object.assign(this, details);
  318. }
  319. }
  320. preventDefault() {
  321. this.defaultPrevented = true;
  322. }
  323. }
  324. /**
  325. * PhotoSwipe base class that can listen and dispatch for events.
  326. * Shared by PhotoSwipe Core and PhotoSwipe Lightbox, extended by base.js
  327. */
  328. class Eventable {
  329. constructor() {
  330. /**
  331. * @type {{ [T in keyof PhotoSwipeEventsMap]?: ((event: AugmentedEvent<T>) => void)[] }}
  332. */
  333. this._listeners = {};
  334. /**
  335. * @type {{ [T in keyof PhotoSwipeFiltersMap]?: Filter<T>[] }}
  336. */
  337. this._filters = {};
  338. /** @type {PhotoSwipe | undefined} */
  339. this.pswp = undefined;
  340. /** @type {PhotoSwipeOptions | undefined} */
  341. this.options = undefined;
  342. }
  343. /**
  344. * @template {keyof PhotoSwipeFiltersMap} T
  345. * @param {T} name
  346. * @param {PhotoSwipeFiltersMap[T]} fn
  347. * @param {number} priority
  348. */
  349. addFilter(name, fn, priority = 100) {
  350. var _this$_filters$name, _this$_filters$name2, _this$pswp;
  351. if (!this._filters[name]) {
  352. this._filters[name] = [];
  353. }
  354. (_this$_filters$name = this._filters[name]) === null || _this$_filters$name === void 0 || _this$_filters$name.push({
  355. fn,
  356. priority
  357. });
  358. (_this$_filters$name2 = this._filters[name]) === null || _this$_filters$name2 === void 0 || _this$_filters$name2.sort((f1, f2) => f1.priority - f2.priority);
  359. (_this$pswp = this.pswp) === null || _this$pswp === void 0 || _this$pswp.addFilter(name, fn, priority);
  360. }
  361. /**
  362. * @template {keyof PhotoSwipeFiltersMap} T
  363. * @param {T} name
  364. * @param {PhotoSwipeFiltersMap[T]} fn
  365. */
  366. removeFilter(name, fn) {
  367. if (this._filters[name]) {
  368. // @ts-expect-error
  369. this._filters[name] = this._filters[name].filter(filter => filter.fn !== fn);
  370. }
  371. if (this.pswp) {
  372. this.pswp.removeFilter(name, fn);
  373. }
  374. }
  375. /**
  376. * @template {keyof PhotoSwipeFiltersMap} T
  377. * @param {T} name
  378. * @param {Parameters<PhotoSwipeFiltersMap[T]>} args
  379. * @returns {Parameters<PhotoSwipeFiltersMap[T]>[0]}
  380. */
  381. applyFilters(name, ...args) {
  382. var _this$_filters$name3;
  383. (_this$_filters$name3 = this._filters[name]) === null || _this$_filters$name3 === void 0 || _this$_filters$name3.forEach(filter => {
  384. // @ts-expect-error
  385. args[0] = filter.fn.apply(this, args);
  386. });
  387. return args[0];
  388. }
  389. /**
  390. * @template {keyof PhotoSwipeEventsMap} T
  391. * @param {T} name
  392. * @param {EventCallback<T>} fn
  393. */
  394. on(name, fn) {
  395. var _this$_listeners$name, _this$pswp2;
  396. if (!this._listeners[name]) {
  397. this._listeners[name] = [];
  398. }
  399. (_this$_listeners$name = this._listeners[name]) === null || _this$_listeners$name === void 0 || _this$_listeners$name.push(fn); // When binding events to lightbox,
  400. // also bind events to PhotoSwipe Core,
  401. // if it's open.
  402. (_this$pswp2 = this.pswp) === null || _this$pswp2 === void 0 || _this$pswp2.on(name, fn);
  403. }
  404. /**
  405. * @template {keyof PhotoSwipeEventsMap} T
  406. * @param {T} name
  407. * @param {EventCallback<T>} fn
  408. */
  409. off(name, fn) {
  410. var _this$pswp3;
  411. if (this._listeners[name]) {
  412. // @ts-expect-error
  413. this._listeners[name] = this._listeners[name].filter(listener => fn !== listener);
  414. }
  415. (_this$pswp3 = this.pswp) === null || _this$pswp3 === void 0 || _this$pswp3.off(name, fn);
  416. }
  417. /**
  418. * @template {keyof PhotoSwipeEventsMap} T
  419. * @param {T} name
  420. * @param {PhotoSwipeEventsMap[T]} [details]
  421. * @returns {AugmentedEvent<T>}
  422. */
  423. dispatch(name, details) {
  424. var _this$_listeners$name2;
  425. if (this.pswp) {
  426. return this.pswp.dispatch(name, details);
  427. }
  428. const event =
  429. /** @type {AugmentedEvent<T>} */
  430. new PhotoSwipeEvent(name, details);
  431. (_this$_listeners$name2 = this._listeners[name]) === null || _this$_listeners$name2 === void 0 || _this$_listeners$name2.forEach(listener => {
  432. listener.call(this, event);
  433. });
  434. return event;
  435. }
  436. }
  437. class Placeholder {
  438. /**
  439. * @param {string | false} imageSrc
  440. * @param {HTMLElement} container
  441. */
  442. constructor(imageSrc, container) {
  443. // Create placeholder
  444. // (stretched thumbnail or simple div behind the main image)
  445. /** @type {HTMLImageElement | HTMLDivElement | null} */
  446. this.element = createElement('pswp__img pswp__img--placeholder', imageSrc ? 'img' : 'div', container);
  447. if (imageSrc) {
  448. const imgEl =
  449. /** @type {HTMLImageElement} */
  450. this.element;
  451. imgEl.decoding = 'async';
  452. imgEl.alt = '';
  453. imgEl.src = imageSrc;
  454. imgEl.setAttribute('role', 'presentation');
  455. }
  456. this.element.setAttribute('aria-hidden', 'true');
  457. }
  458. /**
  459. * @param {number} width
  460. * @param {number} height
  461. */
  462. setDisplayedSize(width, height) {
  463. if (!this.element) {
  464. return;
  465. }
  466. if (this.element.tagName === 'IMG') {
  467. // Use transform scale() to modify img placeholder size
  468. // (instead of changing width/height directly).
  469. // This helps with performance, specifically in iOS15 Safari.
  470. setWidthHeight(this.element, 250, 'auto');
  471. this.element.style.transformOrigin = '0 0';
  472. this.element.style.transform = toTransformString(0, 0, width / 250);
  473. } else {
  474. setWidthHeight(this.element, width, height);
  475. }
  476. }
  477. destroy() {
  478. var _this$element;
  479. if ((_this$element = this.element) !== null && _this$element !== void 0 && _this$element.parentNode) {
  480. this.element.remove();
  481. }
  482. this.element = null;
  483. }
  484. }
  485. /** @typedef {import('./slide.js').default} Slide */
  486. /** @typedef {import('./slide.js').SlideData} SlideData */
  487. /** @typedef {import('../core/base.js').default} PhotoSwipeBase */
  488. /** @typedef {import('../util/util.js').LoadState} LoadState */
  489. class Content {
  490. /**
  491. * @param {SlideData} itemData Slide data
  492. * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance
  493. * @param {number} index
  494. */
  495. constructor(itemData, instance, index) {
  496. this.instance = instance;
  497. this.data = itemData;
  498. this.index = index;
  499. /** @type {HTMLImageElement | HTMLDivElement | undefined} */
  500. this.element = undefined;
  501. /** @type {Placeholder | undefined} */
  502. this.placeholder = undefined;
  503. /** @type {Slide | undefined} */
  504. this.slide = undefined;
  505. this.displayedImageWidth = 0;
  506. this.displayedImageHeight = 0;
  507. this.width = Number(this.data.w) || Number(this.data.width) || 0;
  508. this.height = Number(this.data.h) || Number(this.data.height) || 0;
  509. this.isAttached = false;
  510. this.hasSlide = false;
  511. this.isDecoding = false;
  512. /** @type {LoadState} */
  513. this.state = LOAD_STATE.IDLE;
  514. if (this.data.type) {
  515. this.type = this.data.type;
  516. } else if (this.data.src) {
  517. this.type = 'image';
  518. } else {
  519. this.type = 'html';
  520. }
  521. this.instance.dispatch('contentInit', {
  522. content: this
  523. });
  524. }
  525. removePlaceholder() {
  526. if (this.placeholder && !this.keepPlaceholder()) {
  527. // With delay, as image might be loaded, but not rendered
  528. setTimeout(() => {
  529. if (this.placeholder) {
  530. this.placeholder.destroy();
  531. this.placeholder = undefined;
  532. }
  533. }, 1000);
  534. }
  535. }
  536. /**
  537. * Preload content
  538. *
  539. * @param {boolean} isLazy
  540. * @param {boolean} [reload]
  541. */
  542. load(isLazy, reload) {
  543. if (this.slide && this.usePlaceholder()) {
  544. if (!this.placeholder) {
  545. const placeholderSrc = this.instance.applyFilters('placeholderSrc', // use image-based placeholder only for the first slide,
  546. // as rendering (even small stretched thumbnail) is an expensive operation
  547. this.data.msrc && this.slide.isFirstSlide ? this.data.msrc : false, this);
  548. this.placeholder = new Placeholder(placeholderSrc, this.slide.container);
  549. } else {
  550. const placeholderEl = this.placeholder.element; // Add placeholder to DOM if it was already created
  551. if (placeholderEl && !placeholderEl.parentElement) {
  552. this.slide.container.prepend(placeholderEl);
  553. }
  554. }
  555. }
  556. if (this.element && !reload) {
  557. return;
  558. }
  559. if (this.instance.dispatch('contentLoad', {
  560. content: this,
  561. isLazy
  562. }).defaultPrevented) {
  563. return;
  564. }
  565. if (this.isImageContent()) {
  566. this.element = createElement('pswp__img', 'img'); // Start loading only after width is defined, as sizes might depend on it.
  567. // Due to Safari feature, we must define sizes before srcset.
  568. if (this.displayedImageWidth) {
  569. this.loadImage(isLazy);
  570. }
  571. } else {
  572. this.element = createElement('pswp__content', 'div');
  573. this.element.innerHTML = this.data.html || '';
  574. }
  575. if (reload && this.slide) {
  576. this.slide.updateContentSize(true);
  577. }
  578. }
  579. /**
  580. * Preload image
  581. *
  582. * @param {boolean} isLazy
  583. */
  584. loadImage(isLazy) {
  585. var _this$data$src, _this$data$alt;
  586. if (!this.isImageContent() || !this.element || this.instance.dispatch('contentLoadImage', {
  587. content: this,
  588. isLazy
  589. }).defaultPrevented) {
  590. return;
  591. }
  592. const imageElement =
  593. /** @type HTMLImageElement */
  594. this.element;
  595. this.updateSrcsetSizes();
  596. if (this.data.srcset) {
  597. imageElement.srcset = this.data.srcset;
  598. }
  599. imageElement.src = (_this$data$src = this.data.src) !== null && _this$data$src !== void 0 ? _this$data$src : '';
  600. imageElement.alt = (_this$data$alt = this.data.alt) !== null && _this$data$alt !== void 0 ? _this$data$alt : '';
  601. this.state = LOAD_STATE.LOADING;
  602. if (imageElement.complete) {
  603. this.onLoaded();
  604. } else {
  605. imageElement.onload = () => {
  606. this.onLoaded();
  607. };
  608. imageElement.onerror = () => {
  609. this.onError();
  610. };
  611. }
  612. }
  613. /**
  614. * Assign slide to content
  615. *
  616. * @param {Slide} slide
  617. */
  618. setSlide(slide) {
  619. this.slide = slide;
  620. this.hasSlide = true;
  621. this.instance = slide.pswp; // todo: do we need to unset slide?
  622. }
  623. /**
  624. * Content load success handler
  625. */
  626. onLoaded() {
  627. this.state = LOAD_STATE.LOADED;
  628. if (this.slide && this.element) {
  629. this.instance.dispatch('loadComplete', {
  630. slide: this.slide,
  631. content: this
  632. }); // if content is reloaded
  633. if (this.slide.isActive && this.slide.heavyAppended && !this.element.parentNode) {
  634. this.append();
  635. this.slide.updateContentSize(true);
  636. }
  637. if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {
  638. this.removePlaceholder();
  639. }
  640. }
  641. }
  642. /**
  643. * Content load error handler
  644. */
  645. onError() {
  646. this.state = LOAD_STATE.ERROR;
  647. if (this.slide) {
  648. this.displayError();
  649. this.instance.dispatch('loadComplete', {
  650. slide: this.slide,
  651. isError: true,
  652. content: this
  653. });
  654. this.instance.dispatch('loadError', {
  655. slide: this.slide,
  656. content: this
  657. });
  658. }
  659. }
  660. /**
  661. * @returns {Boolean} If the content is currently loading
  662. */
  663. isLoading() {
  664. return this.instance.applyFilters('isContentLoading', this.state === LOAD_STATE.LOADING, this);
  665. }
  666. /**
  667. * @returns {Boolean} If the content is in error state
  668. */
  669. isError() {
  670. return this.state === LOAD_STATE.ERROR;
  671. }
  672. /**
  673. * @returns {boolean} If the content is image
  674. */
  675. isImageContent() {
  676. return this.type === 'image';
  677. }
  678. /**
  679. * Update content size
  680. *
  681. * @param {Number} width
  682. * @param {Number} height
  683. */
  684. setDisplayedSize(width, height) {
  685. if (!this.element) {
  686. return;
  687. }
  688. if (this.placeholder) {
  689. this.placeholder.setDisplayedSize(width, height);
  690. }
  691. if (this.instance.dispatch('contentResize', {
  692. content: this,
  693. width,
  694. height
  695. }).defaultPrevented) {
  696. return;
  697. }
  698. setWidthHeight(this.element, width, height);
  699. if (this.isImageContent() && !this.isError()) {
  700. const isInitialSizeUpdate = !this.displayedImageWidth && width;
  701. this.displayedImageWidth = width;
  702. this.displayedImageHeight = height;
  703. if (isInitialSizeUpdate) {
  704. this.loadImage(false);
  705. } else {
  706. this.updateSrcsetSizes();
  707. }
  708. if (this.slide) {
  709. this.instance.dispatch('imageSizeChange', {
  710. slide: this.slide,
  711. width,
  712. height,
  713. content: this
  714. });
  715. }
  716. }
  717. }
  718. /**
  719. * @returns {boolean} If the content can be zoomed
  720. */
  721. isZoomable() {
  722. return this.instance.applyFilters('isContentZoomable', this.isImageContent() && this.state !== LOAD_STATE.ERROR, this);
  723. }
  724. /**
  725. * Update image srcset sizes attribute based on width and height
  726. */
  727. updateSrcsetSizes() {
  728. // Handle srcset sizes attribute.
  729. //
  730. // Never lower quality, if it was increased previously.
  731. // Chrome does this automatically, Firefox and Safari do not,
  732. // so we store largest used size in dataset.
  733. if (!this.isImageContent() || !this.element || !this.data.srcset) {
  734. return;
  735. }
  736. const image =
  737. /** @type HTMLImageElement */
  738. this.element;
  739. const sizesWidth = this.instance.applyFilters('srcsetSizesWidth', this.displayedImageWidth, this);
  740. if (!image.dataset.largestUsedSize || sizesWidth > parseInt(image.dataset.largestUsedSize, 10)) {
  741. image.sizes = sizesWidth + 'px';
  742. image.dataset.largestUsedSize = String(sizesWidth);
  743. }
  744. }
  745. /**
  746. * @returns {boolean} If content should use a placeholder (from msrc by default)
  747. */
  748. usePlaceholder() {
  749. return this.instance.applyFilters('useContentPlaceholder', this.isImageContent(), this);
  750. }
  751. /**
  752. * Preload content with lazy-loading param
  753. */
  754. lazyLoad() {
  755. if (this.instance.dispatch('contentLazyLoad', {
  756. content: this
  757. }).defaultPrevented) {
  758. return;
  759. }
  760. this.load(true);
  761. }
  762. /**
  763. * @returns {boolean} If placeholder should be kept after content is loaded
  764. */
  765. keepPlaceholder() {
  766. return this.instance.applyFilters('isKeepingPlaceholder', this.isLoading(), this);
  767. }
  768. /**
  769. * Destroy the content
  770. */
  771. destroy() {
  772. this.hasSlide = false;
  773. this.slide = undefined;
  774. if (this.instance.dispatch('contentDestroy', {
  775. content: this
  776. }).defaultPrevented) {
  777. return;
  778. }
  779. this.remove();
  780. if (this.placeholder) {
  781. this.placeholder.destroy();
  782. this.placeholder = undefined;
  783. }
  784. if (this.isImageContent() && this.element) {
  785. this.element.onload = null;
  786. this.element.onerror = null;
  787. this.element = undefined;
  788. }
  789. }
  790. /**
  791. * Display error message
  792. */
  793. displayError() {
  794. if (this.slide) {
  795. var _this$instance$option, _this$instance$option2;
  796. let errorMsgEl = createElement('pswp__error-msg', 'div');
  797. 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 : '';
  798. errorMsgEl =
  799. /** @type {HTMLDivElement} */
  800. this.instance.applyFilters('contentErrorElement', errorMsgEl, this);
  801. this.element = createElement('pswp__content pswp__error-msg-container', 'div');
  802. this.element.appendChild(errorMsgEl);
  803. this.slide.container.innerText = '';
  804. this.slide.container.appendChild(this.element);
  805. this.slide.updateContentSize(true);
  806. this.removePlaceholder();
  807. }
  808. }
  809. /**
  810. * Append the content
  811. */
  812. append() {
  813. if (this.isAttached || !this.element) {
  814. return;
  815. }
  816. this.isAttached = true;
  817. if (this.state === LOAD_STATE.ERROR) {
  818. this.displayError();
  819. return;
  820. }
  821. if (this.instance.dispatch('contentAppend', {
  822. content: this
  823. }).defaultPrevented) {
  824. return;
  825. }
  826. const supportsDecode = ('decode' in this.element);
  827. if (this.isImageContent()) {
  828. // Use decode() on nearby slides
  829. //
  830. // Nearby slide images are in DOM and not hidden via display:none.
  831. // However, they are placed offscreen (to the left and right side).
  832. //
  833. // Some browsers do not composite the image until it's actually visible,
  834. // using decode() helps.
  835. //
  836. // You might ask "why dont you just decode() and then append all images",
  837. // that's because I want to show image before it's fully loaded,
  838. // as browser can render parts of image while it is loading.
  839. // We do not do this in Safari due to partial loading bug.
  840. if (supportsDecode && this.slide && (!this.slide.isActive || isSafari())) {
  841. this.isDecoding = true; // purposefully using finally instead of then,
  842. // as if srcset sizes changes dynamically - it may cause decode error
  843. /** @type {HTMLImageElement} */
  844. this.element.decode().catch(() => {}).finally(() => {
  845. this.isDecoding = false;
  846. this.appendImage();
  847. });
  848. } else {
  849. this.appendImage();
  850. }
  851. } else if (this.slide && !this.element.parentNode) {
  852. this.slide.container.appendChild(this.element);
  853. }
  854. }
  855. /**
  856. * Activate the slide,
  857. * active slide is generally the current one,
  858. * meaning the user can see it.
  859. */
  860. activate() {
  861. if (this.instance.dispatch('contentActivate', {
  862. content: this
  863. }).defaultPrevented || !this.slide) {
  864. return;
  865. }
  866. if (this.isImageContent() && this.isDecoding && !isSafari()) {
  867. // add image to slide when it becomes active,
  868. // even if it's not finished decoding
  869. this.appendImage();
  870. } else if (this.isError()) {
  871. this.load(false, true); // try to reload
  872. }
  873. if (this.slide.holderElement) {
  874. this.slide.holderElement.setAttribute('aria-hidden', 'false');
  875. }
  876. }
  877. /**
  878. * Deactivate the content
  879. */
  880. deactivate() {
  881. this.instance.dispatch('contentDeactivate', {
  882. content: this
  883. });
  884. if (this.slide && this.slide.holderElement) {
  885. this.slide.holderElement.setAttribute('aria-hidden', 'true');
  886. }
  887. }
  888. /**
  889. * Remove the content from DOM
  890. */
  891. remove() {
  892. this.isAttached = false;
  893. if (this.instance.dispatch('contentRemove', {
  894. content: this
  895. }).defaultPrevented) {
  896. return;
  897. }
  898. if (this.element && this.element.parentNode) {
  899. this.element.remove();
  900. }
  901. if (this.placeholder && this.placeholder.element) {
  902. this.placeholder.element.remove();
  903. }
  904. }
  905. /**
  906. * Append the image content to slide container
  907. */
  908. appendImage() {
  909. if (!this.isAttached) {
  910. return;
  911. }
  912. if (this.instance.dispatch('contentAppendImage', {
  913. content: this
  914. }).defaultPrevented) {
  915. return;
  916. } // ensure that element exists and is not already appended
  917. if (this.slide && this.element && !this.element.parentNode) {
  918. this.slide.container.appendChild(this.element);
  919. }
  920. if (this.state === LOAD_STATE.LOADED || this.state === LOAD_STATE.ERROR) {
  921. this.removePlaceholder();
  922. }
  923. }
  924. }
  925. /** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
  926. /** @typedef {import('../core/base.js').default} PhotoSwipeBase */
  927. /** @typedef {import('../photoswipe.js').Point} Point */
  928. /** @typedef {import('../slide/slide.js').SlideData} SlideData */
  929. /**
  930. * @param {PhotoSwipeOptions} options
  931. * @param {PhotoSwipeBase} pswp
  932. * @returns {Point}
  933. */
  934. function getViewportSize(options, pswp) {
  935. if (options.getViewportSizeFn) {
  936. const newViewportSize = options.getViewportSizeFn(options, pswp);
  937. if (newViewportSize) {
  938. return newViewportSize;
  939. }
  940. }
  941. return {
  942. x: document.documentElement.clientWidth,
  943. // TODO: height on mobile is very incosistent due to toolbar
  944. // find a way to improve this
  945. //
  946. // document.documentElement.clientHeight - doesn't seem to work well
  947. y: window.innerHeight
  948. };
  949. }
  950. /**
  951. * Parses padding option.
  952. * Supported formats:
  953. *
  954. * // Object
  955. * padding: {
  956. * top: 0,
  957. * bottom: 0,
  958. * left: 0,
  959. * right: 0
  960. * }
  961. *
  962. * // A function that returns the object
  963. * paddingFn: (viewportSize, itemData, index) => {
  964. * return {
  965. * top: 0,
  966. * bottom: 0,
  967. * left: 0,
  968. * right: 0
  969. * };
  970. * }
  971. *
  972. * // Legacy variant
  973. * paddingLeft: 0,
  974. * paddingRight: 0,
  975. * paddingTop: 0,
  976. * paddingBottom: 0,
  977. *
  978. * @param {'left' | 'top' | 'bottom' | 'right'} prop
  979. * @param {PhotoSwipeOptions} options PhotoSwipe options
  980. * @param {Point} viewportSize PhotoSwipe viewport size, for example: { x:800, y:600 }
  981. * @param {SlideData} itemData Data about the slide
  982. * @param {number} index Slide index
  983. * @returns {number}
  984. */
  985. function parsePaddingOption(prop, options, viewportSize, itemData, index) {
  986. let paddingValue = 0;
  987. if (options.paddingFn) {
  988. paddingValue = options.paddingFn(viewportSize, itemData, index)[prop];
  989. } else if (options.padding) {
  990. paddingValue = options.padding[prop];
  991. } else {
  992. const legacyPropName = 'padding' + prop[0].toUpperCase() + prop.slice(1); // @ts-expect-error
  993. if (options[legacyPropName]) {
  994. // @ts-expect-error
  995. paddingValue = options[legacyPropName];
  996. }
  997. }
  998. return Number(paddingValue) || 0;
  999. }
  1000. /**
  1001. * @param {PhotoSwipeOptions} options
  1002. * @param {Point} viewportSize
  1003. * @param {SlideData} itemData
  1004. * @param {number} index
  1005. * @returns {Point}
  1006. */
  1007. function getPanAreaSize(options, viewportSize, itemData, index) {
  1008. return {
  1009. x: viewportSize.x - parsePaddingOption('left', options, viewportSize, itemData, index) - parsePaddingOption('right', options, viewportSize, itemData, index),
  1010. y: viewportSize.y - parsePaddingOption('top', options, viewportSize, itemData, index) - parsePaddingOption('bottom', options, viewportSize, itemData, index)
  1011. };
  1012. }
  1013. const MAX_IMAGE_WIDTH = 4000;
  1014. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  1015. /** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
  1016. /** @typedef {import('../photoswipe.js').Point} Point */
  1017. /** @typedef {import('../slide/slide.js').SlideData} SlideData */
  1018. /** @typedef {'fit' | 'fill' | number | ((zoomLevelObject: ZoomLevel) => number)} ZoomLevelOption */
  1019. /**
  1020. * Calculates zoom levels for specific slide.
  1021. * Depends on viewport size and image size.
  1022. */
  1023. class ZoomLevel {
  1024. /**
  1025. * @param {PhotoSwipeOptions} options PhotoSwipe options
  1026. * @param {SlideData} itemData Slide data
  1027. * @param {number} index Slide index
  1028. * @param {PhotoSwipe} [pswp] PhotoSwipe instance, can be undefined if not initialized yet
  1029. */
  1030. constructor(options, itemData, index, pswp) {
  1031. this.pswp = pswp;
  1032. this.options = options;
  1033. this.itemData = itemData;
  1034. this.index = index;
  1035. /** @type { Point | null } */
  1036. this.panAreaSize = null;
  1037. /** @type { Point | null } */
  1038. this.elementSize = null;
  1039. this.fit = 1;
  1040. this.fill = 1;
  1041. this.vFill = 1;
  1042. this.initial = 1;
  1043. this.secondary = 1;
  1044. this.max = 1;
  1045. this.min = 1;
  1046. }
  1047. /**
  1048. * Calculate initial, secondary and maximum zoom level for the specified slide.
  1049. *
  1050. * It should be called when either image or viewport size changes.
  1051. *
  1052. * @param {number} maxWidth
  1053. * @param {number} maxHeight
  1054. * @param {Point} panAreaSize
  1055. */
  1056. update(maxWidth, maxHeight, panAreaSize) {
  1057. /** @type {Point} */
  1058. const elementSize = {
  1059. x: maxWidth,
  1060. y: maxHeight
  1061. };
  1062. this.elementSize = elementSize;
  1063. this.panAreaSize = panAreaSize;
  1064. const hRatio = panAreaSize.x / elementSize.x;
  1065. const vRatio = panAreaSize.y / elementSize.y;
  1066. this.fit = Math.min(1, hRatio < vRatio ? hRatio : vRatio);
  1067. this.fill = Math.min(1, hRatio > vRatio ? hRatio : vRatio); // zoom.vFill defines zoom level of the image
  1068. // when it has 100% of viewport vertical space (height)
  1069. this.vFill = Math.min(1, vRatio);
  1070. this.initial = this._getInitial();
  1071. this.secondary = this._getSecondary();
  1072. this.max = Math.max(this.initial, this.secondary, this._getMax());
  1073. this.min = Math.min(this.fit, this.initial, this.secondary);
  1074. if (this.pswp) {
  1075. this.pswp.dispatch('zoomLevelsUpdate', {
  1076. zoomLevels: this,
  1077. slideData: this.itemData
  1078. });
  1079. }
  1080. }
  1081. /**
  1082. * Parses user-defined zoom option.
  1083. *
  1084. * @private
  1085. * @param {'initial' | 'secondary' | 'max'} optionPrefix Zoom level option prefix (initial, secondary, max)
  1086. * @returns { number | undefined }
  1087. */
  1088. _parseZoomLevelOption(optionPrefix) {
  1089. const optionName =
  1090. /** @type {'initialZoomLevel' | 'secondaryZoomLevel' | 'maxZoomLevel'} */
  1091. optionPrefix + 'ZoomLevel';
  1092. const optionValue = this.options[optionName];
  1093. if (!optionValue) {
  1094. return;
  1095. }
  1096. if (typeof optionValue === 'function') {
  1097. return optionValue(this);
  1098. }
  1099. if (optionValue === 'fill') {
  1100. return this.fill;
  1101. }
  1102. if (optionValue === 'fit') {
  1103. return this.fit;
  1104. }
  1105. return Number(optionValue);
  1106. }
  1107. /**
  1108. * Get zoom level to which image will be zoomed after double-tap gesture,
  1109. * or when user clicks on zoom icon,
  1110. * or mouse-click on image itself.
  1111. * If you return 1 image will be zoomed to its original size.
  1112. *
  1113. * @private
  1114. * @return {number}
  1115. */
  1116. _getSecondary() {
  1117. let currZoomLevel = this._parseZoomLevelOption('secondary');
  1118. if (currZoomLevel) {
  1119. return currZoomLevel;
  1120. } // 3x of "fit" state, but not larger than original
  1121. currZoomLevel = Math.min(1, this.fit * 3);
  1122. if (this.elementSize && currZoomLevel * this.elementSize.x > MAX_IMAGE_WIDTH) {
  1123. currZoomLevel = MAX_IMAGE_WIDTH / this.elementSize.x;
  1124. }
  1125. return currZoomLevel;
  1126. }
  1127. /**
  1128. * Get initial image zoom level.
  1129. *
  1130. * @private
  1131. * @return {number}
  1132. */
  1133. _getInitial() {
  1134. return this._parseZoomLevelOption('initial') || this.fit;
  1135. }
  1136. /**
  1137. * Maximum zoom level when user zooms
  1138. * via zoom/pinch gesture,
  1139. * via cmd/ctrl-wheel or via trackpad.
  1140. *
  1141. * @private
  1142. * @return {number}
  1143. */
  1144. _getMax() {
  1145. // max zoom level is x4 from "fit state",
  1146. // used for zoom gesture and ctrl/trackpad zoom
  1147. return this._parseZoomLevelOption('max') || Math.max(1, this.fit * 4);
  1148. }
  1149. }
  1150. /**
  1151. * Lazy-load an image
  1152. * This function is used both by Lightbox and PhotoSwipe core,
  1153. * thus it can be called before dialog is opened.
  1154. *
  1155. * @param {SlideData} itemData Data about the slide
  1156. * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox instance
  1157. * @param {number} index
  1158. * @returns {Content} Image that is being decoded or false.
  1159. */
  1160. function lazyLoadData(itemData, instance, index) {
  1161. const content = instance.createContentFromData(itemData, index);
  1162. /** @type {ZoomLevel | undefined} */
  1163. let zoomLevel;
  1164. const {
  1165. options
  1166. } = instance; // We need to know dimensions of the image to preload it,
  1167. // as it might use srcset, and we need to define sizes
  1168. if (options) {
  1169. zoomLevel = new ZoomLevel(options, itemData, -1);
  1170. let viewportSize;
  1171. if (instance.pswp) {
  1172. viewportSize = instance.pswp.viewportSize;
  1173. } else {
  1174. viewportSize = getViewportSize(options, instance);
  1175. }
  1176. const panAreaSize = getPanAreaSize(options, viewportSize, itemData, index);
  1177. zoomLevel.update(content.width, content.height, panAreaSize);
  1178. }
  1179. content.lazyLoad();
  1180. if (zoomLevel) {
  1181. content.setDisplayedSize(Math.ceil(content.width * zoomLevel.initial), Math.ceil(content.height * zoomLevel.initial));
  1182. }
  1183. return content;
  1184. }
  1185. /**
  1186. * Lazy-loads specific slide.
  1187. * This function is used both by Lightbox and PhotoSwipe core,
  1188. * thus it can be called before dialog is opened.
  1189. *
  1190. * By default, it loads image based on viewport size and initial zoom level.
  1191. *
  1192. * @param {number} index Slide index
  1193. * @param {PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox eventable instance
  1194. * @returns {Content | undefined}
  1195. */
  1196. function lazyLoadSlide(index, instance) {
  1197. const itemData = instance.getItemData(index);
  1198. if (instance.dispatch('lazyLoadSlide', {
  1199. index,
  1200. itemData
  1201. }).defaultPrevented) {
  1202. return;
  1203. }
  1204. return lazyLoadData(itemData, instance, index);
  1205. }
  1206. /** @typedef {import("../photoswipe.js").default} PhotoSwipe */
  1207. /** @typedef {import("../slide/slide.js").SlideData} SlideData */
  1208. /**
  1209. * PhotoSwipe base class that can retrieve data about every slide.
  1210. * Shared by PhotoSwipe Core and PhotoSwipe Lightbox
  1211. */
  1212. class PhotoSwipeBase extends Eventable {
  1213. /**
  1214. * Get total number of slides
  1215. *
  1216. * @returns {number}
  1217. */
  1218. getNumItems() {
  1219. var _this$options;
  1220. let numItems = 0;
  1221. const dataSource = (_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.dataSource;
  1222. if (dataSource && 'length' in dataSource) {
  1223. // may be an array or just object with length property
  1224. numItems = dataSource.length;
  1225. } else if (dataSource && 'gallery' in dataSource) {
  1226. // query DOM elements
  1227. if (!dataSource.items) {
  1228. dataSource.items = this._getGalleryDOMElements(dataSource.gallery);
  1229. }
  1230. if (dataSource.items) {
  1231. numItems = dataSource.items.length;
  1232. }
  1233. } // legacy event, before filters were introduced
  1234. const event = this.dispatch('numItems', {
  1235. dataSource,
  1236. numItems
  1237. });
  1238. return this.applyFilters('numItems', event.numItems, dataSource);
  1239. }
  1240. /**
  1241. * @param {SlideData} slideData
  1242. * @param {number} index
  1243. * @returns {Content}
  1244. */
  1245. createContentFromData(slideData, index) {
  1246. return new Content(slideData, this, index);
  1247. }
  1248. /**
  1249. * Get item data by index.
  1250. *
  1251. * "item data" should contain normalized information that PhotoSwipe needs to generate a slide.
  1252. * For example, it may contain properties like
  1253. * `src`, `srcset`, `w`, `h`, which will be used to generate a slide with image.
  1254. *
  1255. * @param {number} index
  1256. * @returns {SlideData}
  1257. */
  1258. getItemData(index) {
  1259. var _this$options2;
  1260. const dataSource = (_this$options2 = this.options) === null || _this$options2 === void 0 ? void 0 : _this$options2.dataSource;
  1261. /** @type {SlideData | HTMLElement} */
  1262. let dataSourceItem = {};
  1263. if (Array.isArray(dataSource)) {
  1264. // Datasource is an array of elements
  1265. dataSourceItem = dataSource[index];
  1266. } else if (dataSource && 'gallery' in dataSource) {
  1267. // dataSource has gallery property,
  1268. // thus it was created by Lightbox, based on
  1269. // gallery and children options
  1270. // query DOM elements
  1271. if (!dataSource.items) {
  1272. dataSource.items = this._getGalleryDOMElements(dataSource.gallery);
  1273. }
  1274. dataSourceItem = dataSource.items[index];
  1275. }
  1276. let itemData = dataSourceItem;
  1277. if (itemData instanceof Element) {
  1278. itemData = this._domElementToItemData(itemData);
  1279. } // Dispatching the itemData event,
  1280. // it's a legacy verion before filters were introduced
  1281. const event = this.dispatch('itemData', {
  1282. itemData: itemData || {},
  1283. index
  1284. });
  1285. return this.applyFilters('itemData', event.itemData, index);
  1286. }
  1287. /**
  1288. * Get array of gallery DOM elements,
  1289. * based on childSelector and gallery element.
  1290. *
  1291. * @param {HTMLElement} galleryElement
  1292. * @returns {HTMLElement[]}
  1293. */
  1294. _getGalleryDOMElements(galleryElement) {
  1295. var _this$options3, _this$options4;
  1296. 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) {
  1297. return getElementsFromOption(this.options.children, this.options.childSelector, galleryElement) || [];
  1298. }
  1299. return [galleryElement];
  1300. }
  1301. /**
  1302. * Converts DOM element to item data object.
  1303. *
  1304. * @param {HTMLElement} element DOM element
  1305. * @returns {SlideData}
  1306. */
  1307. _domElementToItemData(element) {
  1308. /** @type {SlideData} */
  1309. const itemData = {
  1310. element
  1311. };
  1312. const linkEl =
  1313. /** @type {HTMLAnchorElement} */
  1314. element.tagName === 'A' ? element : element.querySelector('a');
  1315. if (linkEl) {
  1316. // src comes from data-pswp-src attribute,
  1317. // if it's empty link href is used
  1318. itemData.src = linkEl.dataset.pswpSrc || linkEl.href;
  1319. if (linkEl.dataset.pswpSrcset) {
  1320. itemData.srcset = linkEl.dataset.pswpSrcset;
  1321. }
  1322. itemData.width = linkEl.dataset.pswpWidth ? parseInt(linkEl.dataset.pswpWidth, 10) : 0;
  1323. itemData.height = linkEl.dataset.pswpHeight ? parseInt(linkEl.dataset.pswpHeight, 10) : 0; // support legacy w & h properties
  1324. itemData.w = itemData.width;
  1325. itemData.h = itemData.height;
  1326. if (linkEl.dataset.pswpType) {
  1327. itemData.type = linkEl.dataset.pswpType;
  1328. }
  1329. const thumbnailEl = element.querySelector('img');
  1330. if (thumbnailEl) {
  1331. var _thumbnailEl$getAttri;
  1332. // msrc is URL to placeholder image that's displayed before large image is loaded
  1333. // by default it's displayed only for the first slide
  1334. itemData.msrc = thumbnailEl.currentSrc || thumbnailEl.src;
  1335. itemData.alt = (_thumbnailEl$getAttri = thumbnailEl.getAttribute('alt')) !== null && _thumbnailEl$getAttri !== void 0 ? _thumbnailEl$getAttri : '';
  1336. }
  1337. if (linkEl.dataset.pswpCropped || linkEl.dataset.cropped) {
  1338. itemData.thumbCropped = true;
  1339. }
  1340. }
  1341. return this.applyFilters('domItemData', itemData, element, linkEl);
  1342. }
  1343. /**
  1344. * Lazy-load by slide data
  1345. *
  1346. * @param {SlideData} itemData Data about the slide
  1347. * @param {number} index
  1348. * @returns {Content} Image that is being decoded or false.
  1349. */
  1350. lazyLoadData(itemData, index) {
  1351. return lazyLoadData(itemData, this, index);
  1352. }
  1353. }
  1354. /**
  1355. * @template T
  1356. * @typedef {import('../types.js').Type<T>} Type<T>
  1357. */
  1358. /** @typedef {import('../photoswipe.js').default} PhotoSwipe */
  1359. /** @typedef {import('../photoswipe.js').PhotoSwipeOptions} PhotoSwipeOptions */
  1360. /** @typedef {import('../photoswipe.js').DataSource} DataSource */
  1361. /** @typedef {import('../photoswipe.js').Point} Point */
  1362. /** @typedef {import('../slide/content.js').default} Content */
  1363. /** @typedef {import('../core/eventable.js').PhotoSwipeEventsMap} PhotoSwipeEventsMap */
  1364. /** @typedef {import('../core/eventable.js').PhotoSwipeFiltersMap} PhotoSwipeFiltersMap */
  1365. /**
  1366. * @template {keyof PhotoSwipeEventsMap} T
  1367. * @typedef {import('../core/eventable.js').EventCallback<T>} EventCallback<T>
  1368. */
  1369. /**
  1370. * PhotoSwipe Lightbox
  1371. *
  1372. * - If user has unsupported browser it falls back to default browser action (just opens URL)
  1373. * - Binds click event to links that should open PhotoSwipe
  1374. * - parses DOM strcture for PhotoSwipe (retrieves large image URLs and sizes)
  1375. * - Initializes PhotoSwipe
  1376. *
  1377. *
  1378. * Loader options use the same object as PhotoSwipe, and supports such options:
  1379. *
  1380. * gallery - Element | Element[] | NodeList | string selector for the gallery element
  1381. * children - Element | Element[] | NodeList | string selector for the gallery children
  1382. *
  1383. */
  1384. class PhotoSwipeLightbox extends PhotoSwipeBase {
  1385. /**
  1386. * @param {PhotoSwipeOptions} [options]
  1387. */
  1388. constructor(options) {
  1389. super();
  1390. /** @type {PhotoSwipeOptions} */
  1391. this.options = options || {};
  1392. this._uid = 0;
  1393. this.shouldOpen = false;
  1394. /**
  1395. * @private
  1396. * @type {Content | undefined}
  1397. */
  1398. this._preloadedContent = undefined;
  1399. this.onThumbnailsClick = this.onThumbnailsClick.bind(this);
  1400. }
  1401. /**
  1402. * Initialize lightbox, should be called only once.
  1403. * It's not included in the main constructor, so you may bind events before it.
  1404. */
  1405. init() {
  1406. // Bind click events to each gallery
  1407. getElementsFromOption(this.options.gallery, this.options.gallerySelector).forEach(galleryElement => {
  1408. galleryElement.addEventListener('click', this.onThumbnailsClick, false);
  1409. });
  1410. }
  1411. /**
  1412. * @param {MouseEvent} e
  1413. */
  1414. onThumbnailsClick(e) {
  1415. // Exit and allow default browser action if:
  1416. if (specialKeyUsed(e) // ... if clicked with a special key (ctrl/cmd...)
  1417. || window.pswp) {
  1418. // ... if PhotoSwipe is already open
  1419. return;
  1420. } // If both clientX and clientY are 0 or not defined,
  1421. // the event is likely triggered by keyboard,
  1422. // so we do not pass the initialPoint
  1423. //
  1424. // Note that some screen readers emulate the mouse position,
  1425. // so it's not the ideal way to detect them.
  1426. //
  1427. /** @type {Point | null} */
  1428. let initialPoint = {
  1429. x: e.clientX,
  1430. y: e.clientY
  1431. };
  1432. if (!initialPoint.x && !initialPoint.y) {
  1433. initialPoint = null;
  1434. }
  1435. let clickedIndex = this.getClickedIndex(e);
  1436. clickedIndex = this.applyFilters('clickedIndex', clickedIndex, e, this);
  1437. /** @type {DataSource} */
  1438. const dataSource = {
  1439. gallery:
  1440. /** @type {HTMLElement} */
  1441. e.currentTarget
  1442. };
  1443. if (clickedIndex >= 0) {
  1444. e.preventDefault();
  1445. this.loadAndOpen(clickedIndex, dataSource, initialPoint);
  1446. }
  1447. }
  1448. /**
  1449. * Get index of gallery item that was clicked.
  1450. *
  1451. * @param {MouseEvent} e click event
  1452. * @returns {number}
  1453. */
  1454. getClickedIndex(e) {
  1455. // legacy option
  1456. if (this.options.getClickedIndexFn) {
  1457. return this.options.getClickedIndexFn.call(this, e);
  1458. }
  1459. const clickedTarget =
  1460. /** @type {HTMLElement} */
  1461. e.target;
  1462. const childElements = getElementsFromOption(this.options.children, this.options.childSelector,
  1463. /** @type {HTMLElement} */
  1464. e.currentTarget);
  1465. const clickedChildIndex = childElements.findIndex(child => child === clickedTarget || child.contains(clickedTarget));
  1466. if (clickedChildIndex !== -1) {
  1467. return clickedChildIndex;
  1468. } else if (this.options.children || this.options.childSelector) {
  1469. // click wasn't on a child element
  1470. return -1;
  1471. } // There is only one item (which is the gallery)
  1472. return 0;
  1473. }
  1474. /**
  1475. * Load and open PhotoSwipe
  1476. *
  1477. * @param {number} index
  1478. * @param {DataSource} [dataSource]
  1479. * @param {Point | null} [initialPoint]
  1480. * @returns {boolean}
  1481. */
  1482. loadAndOpen(index, dataSource, initialPoint) {
  1483. // Check if the gallery is already open
  1484. if (window.pswp || !this.options) {
  1485. return false;
  1486. } // Use the first gallery element if dataSource is not provided
  1487. if (!dataSource && this.options.gallery && this.options.children) {
  1488. const galleryElements = getElementsFromOption(this.options.gallery);
  1489. if (galleryElements[0]) {
  1490. dataSource = {
  1491. gallery: galleryElements[0]
  1492. };
  1493. }
  1494. } // set initial index
  1495. this.options.index = index; // define options for PhotoSwipe constructor
  1496. this.options.initialPointerPos = initialPoint;
  1497. this.shouldOpen = true;
  1498. this.preload(index, dataSource);
  1499. return true;
  1500. }
  1501. /**
  1502. * Load the main module and the slide content by index
  1503. *
  1504. * @param {number} index
  1505. * @param {DataSource} [dataSource]
  1506. */
  1507. preload(index, dataSource) {
  1508. const {
  1509. options
  1510. } = this;
  1511. if (dataSource) {
  1512. options.dataSource = dataSource;
  1513. } // Add the main module
  1514. /** @type {Promise<Type<PhotoSwipe>>[]} */
  1515. const promiseArray = [];
  1516. const pswpModuleType = typeof options.pswpModule;
  1517. if (isPswpClass(options.pswpModule)) {
  1518. promiseArray.push(Promise.resolve(
  1519. /** @type {Type<PhotoSwipe>} */
  1520. options.pswpModule));
  1521. } else if (pswpModuleType === 'string') {
  1522. throw new Error('pswpModule as string is no longer supported');
  1523. } else if (pswpModuleType === 'function') {
  1524. promiseArray.push(
  1525. /** @type {() => Promise<Type<PhotoSwipe>>} */
  1526. options.pswpModule());
  1527. } else {
  1528. throw new Error('pswpModule is not valid');
  1529. } // Add custom-defined promise, if any
  1530. if (typeof options.openPromise === 'function') {
  1531. // allow developers to perform some task before opening
  1532. promiseArray.push(options.openPromise());
  1533. }
  1534. if (options.preloadFirstSlide !== false && index >= 0) {
  1535. this._preloadedContent = lazyLoadSlide(index, this);
  1536. } // Wait till all promises resolve and open PhotoSwipe
  1537. const uid = ++this._uid;
  1538. Promise.all(promiseArray).then(iterableModules => {
  1539. if (this.shouldOpen) {
  1540. const mainModule = iterableModules[0];
  1541. this._openPhotoswipe(mainModule, uid);
  1542. }
  1543. });
  1544. }
  1545. /**
  1546. * @private
  1547. * @param {Type<PhotoSwipe> | { default: Type<PhotoSwipe> }} module
  1548. * @param {number} uid
  1549. */
  1550. _openPhotoswipe(module, uid) {
  1551. // Cancel opening if UID doesn't match the current one
  1552. // (if user clicked on another gallery item before current was loaded).
  1553. //
  1554. // Or if shouldOpen flag is set to false
  1555. // (developer may modify it via public API)
  1556. if (uid !== this._uid && this.shouldOpen) {
  1557. return;
  1558. }
  1559. this.shouldOpen = false; // PhotoSwipe is already open
  1560. if (window.pswp) {
  1561. return;
  1562. }
  1563. /**
  1564. * Pass data to PhotoSwipe and open init
  1565. *
  1566. * @type {PhotoSwipe}
  1567. */
  1568. const pswp = typeof module === 'object' ? new module.default(this.options) // eslint-disable-line
  1569. : new module(this.options); // eslint-disable-line
  1570. this.pswp = pswp;
  1571. window.pswp = pswp; // map listeners from Lightbox to PhotoSwipe Core
  1572. /** @type {(keyof PhotoSwipeEventsMap)[]} */
  1573. Object.keys(this._listeners).forEach(name => {
  1574. var _this$_listeners$name;
  1575. (_this$_listeners$name = this._listeners[name]) === null || _this$_listeners$name === void 0 || _this$_listeners$name.forEach(fn => {
  1576. pswp.on(name,
  1577. /** @type {EventCallback<typeof name>} */
  1578. fn);
  1579. });
  1580. }); // same with filters
  1581. /** @type {(keyof PhotoSwipeFiltersMap)[]} */
  1582. Object.keys(this._filters).forEach(name => {
  1583. var _this$_filters$name;
  1584. (_this$_filters$name = this._filters[name]) === null || _this$_filters$name === void 0 || _this$_filters$name.forEach(filter => {
  1585. pswp.addFilter(name, filter.fn, filter.priority);
  1586. });
  1587. });
  1588. if (this._preloadedContent) {
  1589. pswp.contentLoader.addToCache(this._preloadedContent);
  1590. this._preloadedContent = undefined;
  1591. }
  1592. pswp.on('destroy', () => {
  1593. // clean up public variables
  1594. this.pswp = undefined;
  1595. delete window.pswp;
  1596. });
  1597. pswp.init();
  1598. }
  1599. /**
  1600. * Unbinds all events, closes PhotoSwipe if it's open.
  1601. */
  1602. destroy() {
  1603. var _this$pswp;
  1604. (_this$pswp = this.pswp) === null || _this$pswp === void 0 || _this$pswp.destroy();
  1605. this.shouldOpen = false;
  1606. this._listeners = {};
  1607. getElementsFromOption(this.options.gallery, this.options.gallerySelector).forEach(galleryElement => {
  1608. galleryElement.removeEventListener('click', this.onThumbnailsClick, false);
  1609. });
  1610. }
  1611. }
  1612. export { PhotoSwipeLightbox as default };
  1613. //# sourceMappingURL=photoswipe-lightbox.esm.js.map