text: import{extend}from"../shared/utils/extend.js";import{canUseDOM}from"../shared/utils/canUseDOM.js";import{Base}from"../shared/Base/Base.js";import{Carousel}from"../Carousel/Carousel.js";import{Plugins}from"./plugins/index.js";import en from"./l10n/en.js";const defaults={startIndex:0,preload:1,infinite:!0,showClass:"fancybox-zoomInUp",hideClass:"fancybox-fadeOut",animated:!0,hideScrollbar:!0,parentEl:null,mainClass:null,autoFocus:!0,trapFocus:!0,placeFocusBack:!0,click:"close",closeButton:"inside",dragToClose:!0,keyboard:{Escape:"close",Delete:"close",Backspace:"close",PageUp:"next",PageDown:"prev",ArrowUp:"next",ArrowDown:"prev",ArrowRight:"next",ArrowLeft:"prev"},template:{closeButton:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" tabindex="-1"><path d="M20 20L4 4m16 0L4 20"/></svg>',spinner:'<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="25 25 50 50" tabindex="-1"><circle cx="50" cy="50" r="20"/></svg>',main:null},l10n:en},instances={};let called=0;class Fancybox extends Base{constructor(t,e={}){super(extend(!0,{},defaults,e)),this.bindHandlers(),this.state="init",this.setItems(t),this.attachPlugins(Fancybox.Plugins),this.trigger("init"),!0===this.option("hideScrollbar")&&this.hideScrollbar(),this.initLayout(),this.initCarousel(),this.attachEvents(),(instances[this.id]=this).trigger("prepare"),this.state="ready",this.trigger("ready"),this.$container.setAttribute("aria-hidden","false"),this.option("trapFocus")&&this.focus()}bindHandlers(){for(const t of["onMousedown","onKeydown","onClick","onFocus","onCreateSlide","onTouchMove","onTouchEnd","onTransform"])this[t]=this[t].bind(this)}attachEvents(){document.addEventListener("mousedown",this.onMousedown),document.addEventListener("keydown",this.onKeydown,!0),this.option("trapFocus")&&document.addEventListener("focus",this.onFocus,!0),this.$container.addEventListener("click",this.onClick)}detachEvents(){document.removeEventListener("mousedown",this.onMousedown),document.removeEventListener("keydown",this.onKeydown,!0),document.removeEventListener("focus",this.onFocus,!0),this.$container.removeEventListener("click",this.onClick)}initLayout(){this.$root=this.option("parentEl")||document.body;var t=this.option("template.main");t&&(this.$root.insertAdjacentHTML("beforeend",this.localize(t)),this.$container=this.$root.querySelector(".fancybox__container")),this.$container||(this.$container=document.createElement("div"),this.$root.appendChild(this.$container)),this.$container.onscroll=()=>(this.$container.scrollLeft=0,!1),Object.entries({class:"fancybox__container",role:"dialog","aria-modal":"true","aria-hidden":"true","aria-label":this.localize("{{MODAL}}")}).forEach(t=>this.$container.setAttribute(...t)),this.option("animated")&&this.$container.classList.add("is-animated"),this.$backdrop=this.$container.querySelector(".fancybox__backdrop"),this.$backdrop||(this.$backdrop=document.createElement("div"),this.$backdrop.classList.add("fancybox__backdrop"),this.$container.appendChild(this.$backdrop)),this.$carousel=this.$container.querySelector(".fancybox__carousel"),this.$carousel||(this.$carousel=document.createElement("div"),this.$carousel.classList.add("fancybox__carousel"),this.$container.appendChild(this.$carousel)),(this.$container.Fancybox=this).id=this.$container.getAttribute("id"),this.id||(this.id=this.options.id||++called,this.$container.setAttribute("id","fancybox-"+this.id));const e=this.options.mainClass;return e&&this.$container.classList.add(...e.split(" ")),document.documentElement.classList.add("with-fancybox"),this.trigger("initLayout"),this}setItems(t){const n=[];for(const o of t){const i=o.$trigger;var s;i&&(s=i.dataset||{},o.src=s.src||i.getAttribute("href")||o.src,o.type=s.type||o.type,!o.src&&i instanceof HTMLImageElement&&(o.src=i.currentSrc||o.$trigger.src));let e=o.$thumb;if(!e){let t=o.$trigger&&o.$trigger.origTarget;t&&(e=t instanceof HTMLImageElement?t:t.querySelector("img")),!e&&o.$trigger&&(e=o.$trigger instanceof HTMLImageElement?o.$trigger:o.$trigger.querySelector("img"))}o.$thumb=e||null;let t=o.thumb;!t&&o.$thumb&&(t=e.currentSrc||e.src),t||"image"!==o.type||(t=o.src),o.thumb=t||null,o.caption=o.caption||"",n.push(o)}this.items=n}initCarousel(){return this.Carousel=new Carousel(this.$carousel,extend(!0,{},{prefix:"",classNames:{viewport:"fancybox__viewport",track:"fancybox__track",slide:"fancybox__slide"},textSelection:!0,preload:this.option("preload"),friction:.88,slides:this.items,initialPage:this.options.startIndex,slidesPerPage:1,infiniteX:this.option("infinite"),infiniteY:!0,l10n:this.option("l10n"),Dots:!1,Navigation:{classNames:{main:"fancybox__nav",button:"carousel__button",next:"is-next",prev:"is-prev"}},Panzoom:{textSelection:!0,panOnlyZoomed:()=>this.Carousel&&this.Carousel.pages&&this.Carousel.pages.length<2&&!this.options.dragToClose,lockAxis:()=>{if(this.Carousel){let t="x";return this.options.dragToClose&&(t+="y"),t}}},on:{"*":(t,...e)=>this.trigger(`Carousel.${t}`,...e),init:t=>this.Carousel=t,createSlide:this.onCreateSlide}},this.option("Carousel"))),this.option("dragToClose")&&this.Carousel.Panzoom.on({touchMove:this.onTouchMove,afterTransform:this.onTransform,touchEnd:this.onTouchEnd}),this.trigger("initCarousel"),this}onCreateSlide(t,e){let n=e.caption||"";if("function"==typeof this.options.caption&&(n=this.options.caption.call(this,this,this.Carousel,e)),"string"==typeof n&&n.length){const o=document.createElement("div");var s=`fancybox__caption_${this.id}_${e.index}`;o.className="fancybox__caption",o.innerHTML=n,o.setAttribute("id",s),e.$caption=e.$el.appendChild(o),e.$el.classList.add("has-caption"),e.$el.setAttribute("aria-labelledby",s)}}onFocus(t){this.focus(t)}onClick(t){if(!t.defaultPrevented&&(!t.target.closest(".fancybox__content")&&!getSelection().toString().length&&!1!==this.trigger("click",t)))switch(this.option("click")){case"close":this.close();break;case"next":this.next()}}onTouchMove(){var t=this.getSlide().Panzoom;return!t||1===t.content.scale}onTouchEnd(t){var e=t.dragOffset.y;150<=Math.abs(e)||35<=Math.abs(e)&&t.dragOffset.time<350?(this.option("hideClass")&&(this.getSlide().hideClass=`fancybox-throwOut${t.content.y<0?"Up":"Down"}`),this.close()):"y"===t.lockAxis&&t.panTo({y:0})}onTransform(t){var e;this.$backdrop&&(t=(e=Math.abs(t.content.y))<1?"":Math.max(.33,Math.min(1,1-e/t.content.fitHeight*1.5)),this.$container.style.setProperty("--fancybox-ts",t?"0s":""),this.$container.style.setProperty("--fancybox-opacity",t))}onMousedown(){document.body.classList.add("is-using-mouse")}onKeydown(t){if(Fancybox.getInstance().id===this.id){document.body.classList.remove("is-using-mouse");var e=t.key,n=this.option("keyboard");if(n&&!t.ctrlKey&&!t.altKey&&!t.shiftKey){const o=document.activeElement&&document.activeElement.classList;var s=o&&o.contains("carousel__button");if("Escape"!==e&&!s)if(t.target.isContentEditable||-1!==["BUTTON","TEXTAREA","OPTION","INPUT","SELECT","VIDEO"].indexOf(t.target.nodeName))return;!1===this.trigger("keydown",e,t)||"function"==typeof this[e=n[e]]&&this[e]()}}}getSlide(){const t=this.Carousel;if(!t)return null;var e=null===t.page?t.option("initialPage"):t.page,n=t.pages||[];return n.length&&n[e]?n[e].slides[0]:null}focus(s){var o,i=t=>{if(t){this.ignoreFocusChange=!0;try{t.setActive?t.setActive():Fancybox.preventScrollSupported?t.focus({preventScroll:!0}):t.focus()}catch(t){}this.ignoreFocusChange=!1}};if(!(this.ignoreFocusChange||-1<["init","closing","customClosing","destroy"].indexOf(this.state))){const r=this.getSlide().$el;if(r){s&&s.preventDefault();let t=[],e,n;for(o of Array.from(this.$container.querySelectorAll(["a[href]","area[href]",'input:not([disabled]):not([type="hidden"]):not([aria-hidden])',"select:not([disabled]):not([aria-hidden])","textarea:not([disabled]):not([aria-hidden])","button:not([disabled]):not([aria-hidden])","iframe","object","embed","video","audio","[contenteditable]",'[tabindex]:not([tabindex^="-"]):not([disabled]):not([aria-hidden])']))){var a=r.contains(o);a||!this.Carousel.$viewport.contains(o)?(t.push(o),void 0!==o.dataset.origTabindex&&(o.tabIndex=o.dataset.tabindex,o.removeAttribute("data-tabindex")),o.hasAttribute("autoFocus")||!e&&a?e=o:o.matches(".fancybox__button--close")&&(n=o)):(o.dataset.origTabindex=void 0===o.dataset.origTabindex?o.getAttribute("tabindex"):o.dataset.origTabindex,o.tabIndex=-1)}-1<t.indexOf(document.activeElement)?this.lastFocus=document.activeElement:s?r.contains(document.activeElement)||(this.lastFocus===t[0]?i(t[t.length-1]):(s=t.indexOf(this.lastFocus))<t.length-2?i(t[s+1]):i(t[0]),this.lastFocus=document.activeElement):i(e||n||t[0])}}}hideScrollbar(){if(canUseDOM){var e=window.innerWidth-document.documentElement.getBoundingClientRect().width,n="fancybox-style-noscroll";let t=document.getElementById(n);t||0<e&&(t=document.createElement("style"),t.id=n,t.type="text/css",t.innerHTML=`.compensate-for-scrollbar {padding-right: ${e}px;}`,document.getElementsByTagName("head")[0].appendChild(t),document.body.classList.add("compensate-for-scrollbar"))}}revealScrollbar(){document.body.classList.remove("compensate-for-scrollbar");const t=document.getElementById("fancybox-style-noscroll");t&&t.remove()}clearContent(t){this.Carousel.trigger("removeSlide",t),t.$content&&(t.$content.remove(),t.$content=null),t._className&&t.$el.classList.remove(t._className)}setContent(t,e,n={}){let s;const o=t.$el;if(e instanceof HTMLElement?-1<["img","iframe","video","audio"].indexOf(e.nodeName.toLowerCase())?(s=document.createElement("div"),s.appendChild(e)):s=e:(e=document.createRange().createContextualFragment(e),s=document.createElement("div"),s.appendChild(e)),!(s instanceof Element))throw new Error("Element expected");return t._className=`has-${n.suffix||t.type||"unknown"}`,o.classList.add(t._className),s.classList.add("fancybox__content"),"none"!==s.style.display&&"none"!==getComputedStyle(s).getPropertyValue("display")||(s.style.display=t.display||this.option("defaultDisplay")||"flex"),t.id&&s.setAttribute("id",t.id),t.$content=s,o.prepend(s),this.manageCloseButton(t),"loading"!==t.state&&this.revealContent(t),s}manageCloseButton(t){var e=void 0===t.closeButton?this.option("closeButton"):t.closeButton;if(e&&("top"!==e||!this.$closeButton)){const n=document.createElement("button");n.classList.add("carousel__button","is-close"),n.setAttribute("title",this.options.l10n.CLOSE),n.innerHTML=this.option("template.closeButton"),n.addEventListener("click",t=>this.close(t)),"inside"===e?(t.$closeButton&&t.$closeButton.remove(),t.$closeButton=t.$content.appendChild(n)):this.$closeButton=this.$container.insertBefore(n,this.$container.firstChild)}}revealContent(t){this.trigger("reveal",t),t.$content.style.visibility="";let e=!1;t.error||"loading"===t.state||null!==this.Carousel.prevPage||t.index!==this.options.startIndex||(e=void 0===t.showClass?this.option("showClass"):t.showClass),e?(t.state="animating",this.animateCSS(t.$content,e,()=>{this.done(t)})):this.done(t)}animateCSS(e,n,s){if(e&&e.dispatchEvent(new CustomEvent("animationend",{bubbles:!0,cancelable:!0})),e&&n){const o=function(t){t.currentTarget===this&&(e.removeEventListener("animationend",o),s&&s(),e.classList.remove(n))};e.addEventListener("animationend",o),e.classList.add(n)}else"function"==typeof s&&s()}done(t){t.state="done",this.trigger("done",t);var e=this.getSlide();e&&t.index===e.index&&this.option("autoFocus")&&this.focus()}setError(t,e){t.error=e,this.hideLoading(t),this.clearContent(t);const n=document.createElement("div");n.classList.add("fancybox-error"),n.innerHTML=this.localize(e||"<p>{{ERROR}}</p>"),this.setContent(t,n,{suffix:"error"})}showLoading(t){t.state="loading",t.$el.classList.add("is-loading");let e=t.$el.querySelector(".fancybox__spinner");e||(e=document.createElement("div"),e.classList.add("fancybox__spinner"),e.innerHTML=this.option("template.spinner"),e.addEventListener("click",()=>{this.Carousel.Panzoom.velocity||this.close()}),t.$el.prepend(e))}hideLoading(t){const e=t.$el&&t.$el.querySelector(".fancybox__spinner");e&&(e.remove(),t.$el.classList.remove("is-loading")),"loading"===t.state&&(this.trigger("load",t),t.state="ready")}next(){const t=this.Carousel;t&&1<t.pages.length&&t.slideNext()}prev(){const t=this.Carousel;t&&1<t.pages.length&&t.slidePrev()}jumpTo(...t){this.Carousel&&this.Carousel.slideTo(...t)}close(t){if(t&&t.preventDefault(),!["closing","customClosing","destroy"].includes(this.state)&&!1!==this.trigger("shouldClose",t)&&(this.state="closing",this.Carousel.Panzoom.destroy(),this.detachEvents(),this.trigger("closing",t),"destroy"!==this.state)){this.$container.setAttribute("aria-hidden","true"),this.$container.classList.add("is-closing");const e=this.getSlide();this.Carousel.slides.forEach(t=>{t.$content&&t.index!==e.index&&this.Carousel.trigger("removeSlide",t)}),"closing"===this.state&&(t=void 0===e.hideClass?this.option("hideClass"):e.hideClass,this.animateCSS(e.$content,t,()=>{this.destroy()},!0))}}destroy(){this.state="destroy",this.trigger("destroy");const t=this.option("placeFocusBack")?this.getSlide().$trigger:null;var e;this.Carousel.destroy(),this.detachPlugins(),this.Carousel=null,this.options={},this.events={},this.$container.remove(),this.$container=this.$backdrop=this.$carousel=null,t&&(Fancybox.preventScrollSupported?t.focus({preventScroll:!0}):(e=document.body.scrollTop,t.focus(),document.body.scrollTop=e)),delete instances[this.id];const n=Fancybox.getInstance();n?n.focus():(document.documentElement.classList.remove("with-fancybox"),document.body.classList.remove("is-using-mouse"),this.revealScrollbar())}static show(t,e={}){return new Fancybox(t,e)}static fromEvent(i,a={}){if(!i.defaultPrevented&&!(i.button&&0!==i.button||i.ctrlKey||i.metaKey||i.shiftKey)){let n=i.target,t;var r,c;(n.matches("[data-fancybox-trigger]")||(n=n.closest("[data-fancybox-trigger]")))&&(t=n&&n.dataset&&n.dataset.fancyboxTrigger),t&&(r=document.querySelectorAll(`[data-fancybox="${t}"]`),c=parseInt(n.dataset.fancyboxIndex,10)||0,n=r.length?r[c]:n),n=n||i.target;let s,o;Array.from(Fancybox.openers.keys()).reverse().some(t=>{o=n;let e=!1;try{o instanceof Element&&("string"==typeof t||t instanceof String)&&(e=o.matches(t)||(o=o.closest(t)))}catch(t){}return!!e&&(i.preventDefault(),s=t,!0)});let e=!1;return s&&(a.event=i,a.target=o,o.origTarget=i.target,e=Fancybox.fromOpener(s,a),(a=Fancybox.getInstance())&&"ready"===a.state&&i.detail&&document.body.classList.add("is-using-mouse")),e}}static fromOpener(t,e={}){let n=[],s=e.startIndex||0,o=e.target||null;const i=void 0===(e=extend({},e,Fancybox.openers.get(t))).groupAttr?"data-fancybox":e.groupAttr,a=i&&o&&o.getAttribute(`${i}`);var r=void 0!==e.groupAll&&e.groupAll;if(r||a?(n=[].slice.call(document.querySelectorAll(t)),r||(n=n.filter(t=>t.getAttribute(`${i}`)===a))):n=[o],!n.length)return!1;r=Fancybox.getInstance();return!(r&&-1<n.indexOf(r.options.$trigger))&&(s=o?n.indexOf(o):s,n=n.map(function(t){const e=["false","0","no","null","undefined"],n=["true","1","yes"];var s,o,i=Object.assign({},t.dataset);const a={};for([s,o]of Object.entries(i))if("fancybox"!==s)if("width"===s||"height"===s)a[`_${s}`]=o;else if("string"==typeof o||o instanceof String)if(-1<e.indexOf(o))a[s]=!1;else if(-1<n.indexOf(a[s]))a[s]=!0;else try{a[s]=JSON.parse(o)}catch(t){a[s]=o}else a[s]=o;return t instanceof Element&&(a.$trigger=t),a}),new Fancybox(n,extend({},e,{startIndex:s,$trigger:o})))}static bind(t,e={}){function n(){document.body.addEventListener("click",Fancybox.fromEvent,!1)}canUseDOM&&(Fancybox.openers.size||(/complete|interactive|loaded/.test(document.readyState)?n():document.addEventListener("DOMContentLoaded",n)),Fancybox.openers.set(t,e))}static unbind(t){Fancybox.openers.delete(t),Fancybox.openers.size||Fancybox.destroy()}static destroy(){let t;for(;t=Fancybox.getInstance();)t.destroy();Fancybox.openers=new Map,document.body.removeEventListener("click",Fancybox.fromEvent,!1)}static getInstance(t){return t?instances[t]:Object.values(instances).reverse().find(t=>!["closing","customClosing","destroy"].includes(t.state)&&t)||null}static close(t=!0){let e=null;for(;e=Fancybox.getInstance();)if(e.close(),!t)return}}Fancybox.version="__VERSION__",Fancybox.defaults=defaults,Fancybox.openers=new Map,Fancybox.Plugins=Plugins,Fancybox.bind("[data-fancybox]");for(const[H0,I0]of Object.entries(Fancybox.Plugins||{}))"function"==typeof I0.create&&I0.create(Fancybox);export{Fancybox};