From 77b403ac5b7a4e7697d8c8bfdabfdc8c8482e9d8 Mon Sep 17 00:00:00 2001 From: Evgeniy Kirov Date: Fri, 23 Feb 2024 19:35:17 +0100 Subject: [PATCH] Blocks 0.33.2 --- HISTORY.md | 2 +- docs/django-widget.rst | 2 +- pyuploadcare/dj/conf.py | 2 +- pyuploadcare/dj/static/uploadcare/blocks.min.js | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index 51fe317..df7e84a 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -10,7 +10,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Changed -- [Blocks](https://github.com/uploadcare/blocks) have been updated to [v0.32.4](https://github.com/uploadcare/blocks/releases) +- [Blocks](https://github.com/uploadcare/blocks) have been updated to [v0.33.2](https://github.com/uploadcare/blocks/releases) ### Fixed diff --git a/docs/django-widget.rst b/docs/django-widget.rst index cb06601..4b3ea7f 100644 --- a/docs/django-widget.rst +++ b/docs/django-widget.rst @@ -35,7 +35,7 @@ Below is the full default configuration: "use_legacy_widget": False, "use_hosted_assets": True, "widget": { - "version": "0.32.4", + "version": "0.33.2", "variant": "regular", "build": "min", "options": {}, diff --git a/pyuploadcare/dj/conf.py b/pyuploadcare/dj/conf.py index e0e46d3..b036280 100644 --- a/pyuploadcare/dj/conf.py +++ b/pyuploadcare/dj/conf.py @@ -67,7 +67,7 @@ class SettingsType(typing_extensions.TypedDict): "use_legacy_widget": False, "use_hosted_assets": True, "widget": { - "version": "0.32.4", + "version": "0.33.2", "variant": "regular", "build": "min", "options": {}, diff --git a/pyuploadcare/dj/static/uploadcare/blocks.min.js b/pyuploadcare/dj/static/uploadcare/blocks.min.js index 253df6b..9884af2 100644 --- a/pyuploadcare/dj/static/uploadcare/blocks.min.js +++ b/pyuploadcare/dj/static/uploadcare/blocks.min.js @@ -23,6 +23,6 @@ * SOFTWARE. * */ -var Vr=Object.defineProperty;var zr=(s,i,t)=>i in s?Vr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(zr(s,typeof i!="symbol"?i+"":i,t),t);var jr=Object.defineProperty,Hr=(s,i,t)=>i in s?jr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,xi=(s,i,t)=>(Hr(s,typeof i!="symbol"?i+"":i,t),t);function Gr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var w=class{constructor(s){s.constructor===Object?this.store=Gr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(w.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){w.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(w.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=w.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new w(s),w.globalStore.set(i,t)),t}static deleteCtx(s){w.globalStore.delete(s)}static getCtx(s,i=!0){return w.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};w.globalStore=new Map;var y=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),ps="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Wr=ps.length-1,Kt=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function qr(s,i){[...s.querySelectorAll(`[${y.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(y.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(y.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(y.REPEAT_ATTR),t.removeAttribute(y.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function Kr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||us;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=us;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function Yr(s,i){[...s.querySelectorAll(`[${y.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(y.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(y.EL_REF_ATTR)})}function Zr(s,i){[...s.querySelectorAll(`[${y.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(y.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Xr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(y.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(y.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):fs(t,l,p)||(t[y.SET_LATER_KEY]||(t[y.SET_LATER_KEY]=Object.create(null)),t[y.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(y.BIND_ATTR)})}var Ee="{{",qt="}}",Jr="skip-text";function Qr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(Jr))&&r.textContent.includes(Ee)&&r.textContent.includes(qt)&&1}});for(;i=e.nextNode();)t.push(i);return t}var tn=function(s,i){Qr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(qt);)e.textContent.startsWith(Ee)?(n=e.textContent.indexOf(qt)+qt.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(Ee),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(Ee,"").replace(qt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},en=[qr,Kr,Yr,Zr,tn],xe="'",Mt='"',sn=/\\([0-9a-fA-F]{1,6} ?)/g;function rn(s){return(s[0]===Mt||s[0]===xe)&&(s[s.length-1]===Mt||s[s.length-1]===xe)}function nn(s){return(s[0]===Mt||s[0]===xe)&&(s=s.slice(1)),(s[s.length-1]===Mt||s[s.length-1]===xe)&&(s=s.slice(0,-1)),s}function on(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=on(i),i=Mt+i+Mt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Rt=null,ct=null,gt=class extends HTMLElement{constructor(){super(),xi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return gt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(y.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Kt.generate(),this.style.setProperty(y.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(y.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(y.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=w.registerCtx({},this)),this.__localCtx}get nodeCtx(){return w.getCtx(this.ctxName,!1)||w.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(y.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(y.EXT_DATA_CTX_PRFX,"");else if(s.includes(y.NAMED_DATA_CTX_SPLTR)){let r=s.split(y.NAMED_DATA_CTX_SPLTR);t=w.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=gt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=gt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=gt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=gt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=gt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=gt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(y.CTX_OWNER_ATTR)&&this.getAttribute(y.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(y.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(y.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(y.NAMED_DATA_CTX_SPLTR)){let t=i.split(y.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=w.getCtx(e,!1);n||(n=w.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(y.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(y.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[y.SET_LATER_KEY]){for(let t in this[y.SET_LATER_KEY])fs(this,t,this[y.SET_LATER_KEY][t]);delete this[y.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of en)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${y.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(y.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);ct==null||ct.delete(this.updateCssData),ct!=null&&ct.size||(Rt==null||Rt.disconnect(),Rt=null,ct=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${y.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` -`));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=ln(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){ct||(ct=new Set),ct.add(this.updateCssData),Rt||(Rt=new MutationObserver(s=>{s[0].type==="attributes"&&ct.forEach(i=>{i()})}),Rt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},Nt=gt;xi(Nt,"template");var Ei=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Ei.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=w.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Ei.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Ei.appMap=Object.create(null);function Ti(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function an(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function Yt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&an(i,s.attributes),s.styles&&Ti(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Yt(t);i.appendChild(e)}),i}var ms="idb-store-ready",cn="symbiote-db",hn="symbiote-idb-update_",un=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return hn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=cn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new un(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};xi(gs,"_reg",Object.create(null));var $=Object.freeze({FILE_ADDED:"file-added",FILE_REMOVED:"file-removed",FILE_UPLOAD_START:"file-upload-start",FILE_UPLOAD_PROGRESS:"file-upload-progress",FILE_UPLOAD_SUCCESS:"file-upload-success",FILE_UPLOAD_FAILED:"file-upload-failed",FILE_URL_CHANGED:"file-url-changed",MODAL_OPEN:"modal-open",MODAL_CLOSE:"modal-close",DONE_CLICK:"done-click",UPLOAD_CLICK:"upload-click",ACTIVITY_CHANGE:"activity-change",COMMON_UPLOAD_START:"common-upload-start",COMMON_UPLOAD_PROGRESS:"common-upload-progress",COMMON_UPLOAD_SUCCESS:"common-upload-success",COMMON_UPLOAD_FAILED:"common-upload-failed",CHANGE:"change",GROUP_CREATED:"group-created"}),Te=class{constructor(i){h(this,"_timeoutStore",new Map);h(this,"_targets",new Set);h(this,"_debugPrint",null);this._debugPrint=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){var e;for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));(e=this._debugPrint)==null||e.call(this,()=>{let r=t&&typeof t=="object"?{...t}:t;return[`event "${i}"`,r]})}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,typeof t=="function"?t():t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,typeof t=="function"?t():t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};function O(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var _s="--uploadcare-blocks-window-height",St=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),this.clientsRegistry.size===0&&this.detachTracker()}static attachTracker(){window.addEventListener("resize",this.flush,{passive:!0,capture:!0}),this.flush()}static detachTracker(){window.removeEventListener("resize",this.flush,{capture:!0}),document.documentElement.style.removeProperty(_s)}};h(St,"clientsRegistry",new Set),h(St,"flush",O(()=>{document.documentElement.style.setProperty(_s,`${window.innerHeight}px`)},100));var Ae=(s,i)=>new Intl.PluralRules(s).select(i);var dn=s=>s,Ai="{{",ys="}}",bs="plural:";function Zt(s,i,t={}){var o;let{openToken:e=Ai,closeToken:r=ys,transform:n=dn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(Ai);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ai,e)}return i}var ht=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Se=({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=s.getAttribute(i);if(n!==null){t(n);return}let o=new MutationObserver(c=>{let u=c[c.length-1];a(u)});o.observe(s,{attributes:!0,attributeFilter:[i]});let l=setTimeout(()=>{o.disconnect(),e()},r),a=c=>{let u=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&u!==null&&(clearTimeout(l),o.disconnect(),t(u))}};var Cs=new Set;function $t(s){Cs.has(s)||(Cs.add(s),console.warn(s))}function ws(s){return Object.prototype.toString.call(s)==="[object Object]"}var pn=/\W|_/g;function fn(s){return s.split(pn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Es(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>pt(t,{ignoreKeys:i})):s}function pt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return Es(s,{ignoreKeys:i});if(!ws(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ws(r)?r=pt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=Es(r,{ignoreKeys:i})),t[fn(e)]=r}return t}var mn=s=>new Promise(i=>setTimeout(i,s));function Pi({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var gn={factor:2,time:100};function _n(s,i=gn){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>mn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Jt=class extends Error{},Dt=class s extends Jt{constructor(t){super();h(this,"originalProgressEvent");this.name="NetworkError",this.message="Network error",Object.setPrototypeOf(this,s.prototype),this.originalProgressEvent=t}},Ie=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},_t=class s extends Jt{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);this.name="CancelError",Object.setPrototypeOf(this,s.prototype)}},bn=500,Ts=({check:s,interval:i=bn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Ie(e,()=>{o&&clearTimeout(o),n(new _t("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new _t("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),S={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Oe="application/octet-stream",As="original",bt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Ie(r,()=>{u=!0,a.abort(),l(new _t)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function(T){let A=T.split(": "),x=A.shift(),C=A.join(": ");x&&typeof x!="undefined"&&(m[x]=C)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new Dt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function yn(s,...i){return s}var vn=({name:s})=>s?[s]:[],Cn=yn,wn=()=>new FormData,Ss=s=>!1,ke=s=>typeof Blob!="undefined"&&s instanceof Blob,Le=s=>typeof File!="undefined"&&s instanceof File,Pe=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Ft=s=>ke(s)||Le(s)||Ss()||Pe(s),En=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",xn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),Tn=s=>!!s&&typeof s=="object"&&"data"in s&&Ft(s.data);function $s(s,i,t){if(Array.isArray(t))for(let e of t)$s(s,`${i}[]`,e);else if(Tn(t)){let{name:e,contentType:r}=t,n=Cn(t.data,e,r!=null?r:Oe),o=vn({name:e,contentType:r});s.push([i,n,...o])}else if(xn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else En(t)&&t&&s.push([i,t.toString()])}function An(s){let i=[];for(let[t,e]of Object.entries(s))$s(i,t,e);return i}function Ue(s){let i=wn(),t=An(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var D=class s extends Jt{constructor(t,e,r,n,o){super();h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,s.prototype)}},Sn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ut=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=Sn(t)),e.toString()},$n="6.13.0",In="UploadcareUploadClient",On=$n;function It(s){return Pi({libraryName:In,libraryVersion:On,...s})}var kn="RequestThrottledError",xs=15e3,Ln=1e3;function Pn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return xs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:xs}function yt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return _n(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===kn&&r{let i="";return(ke(s)||Le(s)||Pe(s))&&(i=s.type),i||Oe},Os=s=>{let i="";return Le(s)&&s.name?i=s.name:ke(s)||Ss()?i="":Pe(s)&&s.name&&(i=s.name),i||As};function Ui(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Un(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=S.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=S.retryNetworkErrorMaxTimes,metadata:_}){return yt(()=>bt({method:"POST",url:ut(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":It({publicKey:i,integration:d,userAgent:p})},data:Ue({file:{data:s,name:t||Os(s),contentType:e||Is(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Ui(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:T,headers:A,request:x})=>{let C=pt(JSON.parse(T));if("error"in C)throw new D(C.error.content,C.error.errorCode,x,C,A);return C}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Ii;(function(s){s.Token="token",s.FileInfo="file_info"})(Ii||(Ii={}));function Rn(s,{publicKey:i,baseURL:t=S.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=S.retryNetworkErrorMaxTimes,metadata:_}){return yt(()=>bt({method:"POST",headers:{"X-UC-User-Agent":It({publicKey:i,integration:d,userAgent:p})},url:ut(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Ui(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:T,headers:A,request:x})=>{let C=pt(JSON.parse(T));if("error"in C)throw new D(C.error.content,C.error.errorCode,x,C,A);return C}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var j;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(j||(j={}));var Mn=s=>"status"in s&&s.status===j.Error;function Nn(s,{publicKey:i,baseURL:t=S.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=S.retryNetworkErrorMaxTimes}={}){return yt(()=>bt({method:"GET",headers:i?{"X-UC-User-Agent":It({publicKey:i,integration:r,userAgent:n})}:void 0,url:ut(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=pt(JSON.parse(a));if("error"in d&&!Mn(d))throw new D(d.error.content,d.error.errorCode,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Dn(s,{publicKey:i,baseURL:t=S.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=S.retryNetworkErrorMaxTimes}){return yt(()=>bt({method:"POST",headers:{"X-UC-User-Agent":It({publicKey:i,integration:a,userAgent:c})},url:ut(t,"/group/",{jsonerrors:1}),data:Ue({files:s,callback:e,pub_key:i,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=pt(JSON.parse(p));if("error"in _)throw new D(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=S.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=S.retryNetworkErrorMaxTimes}){return yt(()=>bt({method:"GET",headers:{"X-UC-User-Agent":It({publicKey:i,integration:n,userAgent:o})},url:ut(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=pt(JSON.parse(c));if("error"in p)throw new D(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Fn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=S.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=S.retryNetworkErrorMaxTimes,metadata:_}){return yt(()=>bt({method:"POST",url:ut(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":It({publicKey:i,integration:d,userAgent:p})},data:Ue({filename:e||As,size:s,content_type:t||Oe,part_size:r,UPLOADCARE_STORE:Ui(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:T,headers:A,request:x})=>{let C=pt(JSON.parse(T));if("error"in C)throw new D(C.error.content,C.error.errorCode,x,C,A);return C.parts=Object.keys(C.parts).map(V=>C.parts[V]),C}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Bn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=S.retryNetworkErrorMaxTimes}){return yt(()=>bt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Oe}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Vn(s,{publicKey:i,baseURL:t=S.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=S.retryNetworkErrorMaxTimes}){return yt(()=>bt({method:"POST",url:ut(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":It({publicKey:i,integration:n,userAgent:o})},data:Ue({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=pt(JSON.parse(c));if("error"in p)throw new D(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Ri(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return Ts({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function zn(s){return"defaultEffects"in s}var dt=class{constructor(i,{baseCDN:t=S.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);h(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=ut(t,`${r}/`),l=n?ut(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,zn(i)&&(this.defaultEffects=i.defaultEffects)}},jn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:T})=>Un(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:T}).then(({file:A})=>Ri(A,{publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new dt(A,{baseCDN:_})),Hn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new dt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Gn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Ie(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Wn=window.WebSocket,Oi=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Xn=(s,i)=>s==="success"?{status:j.Success,...i}:s==="progress"?{status:j.Progress,...i}:{status:j.Error,...i},ki=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Oi);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Wn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,Xn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Si=null,Mi=s=>{if(!Si){let i=typeof window=="undefined"?0:3e4;Si=new ki(s,i)}return Si},qn=s=>{Mi(s).connect()};function Kn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return Ts({check:c=>Nn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case j.Error:return new D(u.error,u.errorCode);case j.Waiting:return!1;case j.Unknown:return new D(`Token "${s}" was not found.`);case j.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case j.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Yn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Mi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Ie(t,()=>{a(),n(new _t("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case j.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case j.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case j.Error:a(),n(new D(c.msg,c.error_code))}})}),Zn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:T=S.pusherKey,metadata:A})=>Promise.resolve(qn(T)).then(()=>Rn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(x=>{let C=Mi(T);return C==null||C.disconnect(),Promise.reject(x)}).then(x=>x.type===Ii.FileInfo?x:Gn([({signal:C})=>Kn({token:x.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:C}),({signal:C})=>Yn({token:x.token,pusherKey:T,signal:C,onProgress:d})],{signal:u})).then(x=>{if(x instanceof D)throw x;return x}).then(x=>Ri(x.uuid,{publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(x=>new dt(x,{baseCDN:r})),$i=new WeakMap,Jn=async s=>{if($i.has(s))return $i.get(s);let i=await fetch(s.uri).then(t=>t.blob());return $i.set(s,i),i},Ls=async s=>{if(Le(s)||ke(s))return s.size;if(Pe(s))return(await Jn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Qn=(s,i=S.multipartMinFileSize)=>s>=i,Ps=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Ft(s)&&t.test(s)},Ni=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Ft(s)&&t.test(s)},to=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},io=async(s,i,t)=>e=>eo(s,e,i,t),so=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Bn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),ro=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:T=S.multipartChunkSize,maxConcurrentRequests:A=S.maxConcurrentRequests,baseCDN:x,metadata:C})=>{let V=e!=null?e:await Ls(s),lt,At=(U,z)=>{if(!c)return;lt||(lt=Array(U).fill(0));let J=tt=>tt.reduce((at,wi)=>at+wi,0);return tt=>{tt.isComputable&&(lt[z]=tt.value,c({isComputable:!0,value:J(lt)/U}))}};return _||(_=Is(s)),Fn(V,{publicKey:i,contentType:_,fileName:t||Os(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:C}).then(async({uuid:U,parts:z})=>{let J=await io(s,V,T);return Promise.all([U,to(A,z.map((tt,at)=>()=>so(J(at),tt,{publicKey:i,contentType:_,onProgress:At(z.length,at),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([U])=>Vn(U,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(U=>U.isReady?U:Ri(U.uuid,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(U=>new dt(U,{baseCDN:x}))};async function Di(s,{publicKey:i,fileName:t,baseURL:e=S.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:T,maxConcurrentRequests:A,baseCDN:x=S.baseCDN,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:V,pusherKey:lt,metadata:At}){if(Ft(s)){let U=await Ls(s);return Qn(U,_)?ro(s,{publicKey:i,contentType:f,multipartChunkSize:T,fileSize:U,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x,metadata:At}):jn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x,metadata:At})}if(Ni(s))return Zn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:x,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:V,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:lt,metadata:At});if(Ps(s))return Hn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x});throw new TypeError(`File uploading from "${s}" is not supported`)}var Li=class{constructor(i,{baseCDN:t=S.baseCDN}={}){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new dt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},no=s=>{for(let i of s)if(!Ft(i))return!1;return!0},oo=s=>{for(let i of s)if(!Ps(i))return!1;return!0},lo=s=>{for(let i of s)if(!Ni(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=S.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=S.multipartChunkSize,baseCDN:T=S.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x,jsonpCallback:C}){if(!no(s)&&!lo(s)&&!oo(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let V,lt=!0,At=s.length,U=(z,J)=>{if(!a)return;V||(V=Array(z).fill(0));let tt=at=>at.reduce((wi,Br)=>wi+Br)/z;return at=>{if(!at.isComputable||!lt){lt=!1,a({isComputable:!1});return}V[J]=at.value,a({isComputable:!0,value:tt(V)})}};return Promise.all(s.map((z,J)=>Ft(z)||Ni(z)?Di(z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:U(At,J),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:T,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x}).then(tt=>tt.uuid):z)).then(z=>Dn(z,{publicKey:i,baseURL:e,jsonpCallback:C,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(J=>new Li(J,{baseCDN:T})).then(J=>(a&&a({isComputable:!0,value:1}),J)))}var $e=class{constructor(i){h(this,"_concurrency",1);h(this,"_pending",[]);h(this,"_running",0);h(this,"_resolvers",new Map);h(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var Fi=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),Bi=s=>({...Fi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Re=s=>({...Bi(s),"*commonProgress":0,"*uploadList":[],"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new $e(1),"*uploadCollection":null,"*collectionErrors":[],"*collectionState":null,"*groupInfo":null,"*uploadTrigger":null});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var F=s=>`*cfg/${s}`;var Vi="lr-",v=class extends Nt{constructor(){super();h(this,"requireCtxName",!1);h(this,"allowCustomTemplate",!0);h(this,"activityType",null);h(this,"init$",Fi());h(this,"updateCtxCssData",()=>{$t("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return Zt(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Ae(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Vi}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Se({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),St.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),St.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new Te(this.debugPrint.bind(this)))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),w.deleteCtx(this),t.size===0&&setTimeout(()=>{this.destroyCtxCallback()},0)}destroyCtxCallback(){w.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Zt(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=F(r);return this.$[o]=n,!0},get:(e,r)=>{let n=F(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):($t("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ht(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(F(t));r.ctx.has(r.name)?this.sub(F(t),e):(this.bindCssData(`--cfg-${ht(t)}`),this.sub(`--cfg-${ht(t)}`,e))}debugPrint(...t){if(!this.cfg.debug)return;let e=t;if(typeof(t==null?void 0:t[0])=="function"){let r=t[0];e=r()}console.log(`[${this.debugCtxName}]`,...e)}get debugCtxName(){return this.ctxName}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Vi)?t:Vi+t)}};h(v,"StateConsumerScope",null),h(v,"className","");var Ms="active",Qt="___ACTIVITY_IS_ACTIVE___",Q=class Q extends v{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Bi(this));h(this,"_debouncedHistoryFlush",O(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=Q._activityRegistry[this.activityKey];this[Qt]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=Q._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[Qt]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush(),this.emit($.ACTIVITY_CHANGE,{activity:this.activityType})}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[Qt]?this._deactivate():this.activityType===t&&!this[Qt]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!Q._activityRegistry[this.activityKey]}get isActivityActive(){return this[Qt]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;Q._activityRegistry||(Q._activityRegistry=Object.create(null)),Q._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),Q._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(Q._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===r);n=(e=l==null?void 0:l.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}};h(Q,"_activityRegistry",Object.create(null));var g=Q;g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var te=33.333333333333336,b=1,zi=24,Ns=6;function Ot(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function K(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Ot(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Bs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Vs({rect:s,delta:[i,t],imageBox:e}){return Vt({...s,x:s.x+i,y:s.y+t},e)}function Vt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function ao({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Gs(s,i){return Math.abs(s.width/s.height-i)<.1}function zt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function jt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function vt(s,i,t){return Math.min(Math.max(s,i),t)}var Ne=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var Y=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs=s=>s?s.split(",").map(i=>i.trim()):[],kt=s=>s?s.join(","):"";var De="blocks",Fe="0.32.4";function qs(s){return Pi({...s,libraryName:De,libraryVersion:Fe})}var Ks=({type:s,message:i,...t})=>({type:s,message:i,...t}),Lt=Ks,Be=Ks;var Ys=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Ve=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ys(i)).join("/-/"),R=(...s)=>{let i=Ve(...s);return i?`-/${i}/`:""};function Zs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Js(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Qs(s){let i=tr(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ys(n))}function tr(s){let i=new URL(s),t=Zs(s),e=er(t)?ir(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function er(s){return s.startsWith("http")}function ir(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var k=(s,i,t)=>{let e=new URL(tr(s));if(t=t||Zs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),er(t)){let r=ir(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},Ct=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var M=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var ee=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],ji=s=>s?s.filter(i=>typeof i=="string").map(i=>M(i)).flat():[],Hi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),sr=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),ie=s=>{let i=s==null?void 0:s.type;return i?Hi(i,ee):!1};var it=1e3,Pt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),se=s=>Math.ceil(s*100)/100,rr=(s,i=Pt.AUTO)=>{let t=i===Pt.AUTO;if(i===Pt.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=w.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(nr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(_o+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(nr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){w.deleteCtx(this.__ctxId)}};var je=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Kt.generate(),this.__data=w.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.__items.size>0&&this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new ze(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__items.add(t.uid),this.notify(),this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),t.uid}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){w.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var or=s=>{let i=new Map;return(...t)=>{let e=JSON.stringify(t);if(i.has(e))return i.get(e);let r=s(...t);return i.set(e,r),r}};function bo(s){let i=!1;return setTimeout(()=>{i=!0},0),e=>(...r)=>(i&&$t(s),e(...r))}function lr(s){let i={progress:()=>s.$["*commonProgress"],errors:()=>s.$["*collectionErrors"],group:()=>s.$["*groupInfo"],totalCount:()=>s.uploadCollection.size,failedCount:()=>t.failedEntries.length,successCount:()=>t.successEntries.length,uploadingCount:()=>t.uploadingEntries.length,status:()=>t.isFailed?"failed":t.isUploading?"uploading":t.isSuccess?"success":"idle",isSuccess:()=>t.errors.length===0&&t.successEntries.length===t.allEntries.length,isUploading:()=>t.allEntries.some(r=>r.status==="uploading"),isFailed:()=>t.errors.length>0||t.failedEntries.length>0,allEntries:()=>s.getOutputData(),successEntries:()=>t.allEntries.filter(r=>r.status==="success"),failedEntries:()=>t.allEntries.filter(r=>r.status==="failed"),uploadingEntries:()=>t.allEntries.filter(r=>r.status==="uploading"),idleEntries:()=>t.allEntries.filter(r=>r.status==="idle")},t={},e=bo("You're trying to access the OutputCollectionState asynchronously. In this case, the data you retrieve will be newer than it was when the OutputCollectionState was created or when the event was dispatched. If you want to retain the state at a specific moment in time, you should use the spread operator like this: `{...outputCollectionState}` or `{...e.detail}`");for(let[r,n]of Object.entries(i)){let o=r,a=or(e(n));Object.defineProperty(t,o,{get:a,enumerable:!0})}return t}var ar=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:dt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silent:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0},metadata:{type:Object,value:null,nullable:!0},errors:{type:Array,value:[]},uploadError:{type:Error,value:null,nullable:!0},isRemoved:{type:Boolean,value:!1}});var He=(s,i)=>{let t,e,r,n=(...o)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...o),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...o),r=Date.now(),t=!0)};return Object.defineProperty(n,"cancel",{configurable:!1,writable:!1,enumerable:!1,value:()=>{clearTimeout(e)}}),n};var E=class s extends g{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!1);h(this,"isCtxOwner",!1);h(this,"init$",Re(this));h(this,"__initialUploadMetadata",null);h(this,"_fileValidators",[this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this),this._validateUploadError.bind(this)]);h(this,"_collectionValidators",[t=>{let e=t.size,r=this.cfg.multiple?this.cfg.multipleMin:0,n=this.cfg.multiple?this.cfg.multipleMax:1;if(r&&en){let o=this.l10n("files-count-limit-error-too-many",{min:r,max:n,total:e});return Be({type:"TOO_MANY_FILES",message:o,total:e,min:r,max:n})}},t=>{if(t.items().some(e=>t.readProp(e,"errors").length>0))return Be({type:"SOME_FILES_HAS_ERRORS",message:this.l10n("some-files-were-not-uploaded")})}]);h(this,"uploadAll",()=>{let t=this.uploadCollection.items().filter(e=>{let r=this.uploadCollection.read(e);return!r.getValue("isRemoved")&&!r.getValue("isUploading")&&!r.getValue("fileInfo")});this.$["*uploadTrigger"]=t,t.length>0&&this.emit($.COMMON_UPLOAD_START,this.getOutputCollectionState())});h(this,"_flushOutputItems",O(async()=>{if(this.getOutputData().length!==this.uploadCollection.size)return;let e=this.getOutputCollectionState();this.$["*collectionState"]=e,this.emit($.CHANGE,()=>this.getOutputCollectionState(),{debounce:!0}),this.cfg.groupOutput&&e.totalCount>0&&e.status==="success"&&this._createGroup(e)},300));h(this,"_handleCollectionUpdate",(t,e,r)=>{var n;(e.size||r.size)&&(this.$["*groupInfo"]=null),this._runFileValidators(),this._runCollectionValidators();for(let o of e)o.getValue("silent")||this.emit($.FILE_ADDED,this.getOutputItem(o.uid));for(let o of r)(n=o.getValue("abortController"))==null||n.abort(),o.setMultipleValues({isRemoved:!0,abortController:null,isUploading:!1,uploadProgress:0}),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl")),this.emit($.FILE_REMOVED,this.getOutputItem(o.uid));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushCommonUploadProgress(),this._flushOutputItems()});h(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.entries(t).filter(([n])=>["uploadError","fileInfo"].includes(n)).map(([,n])=>[...n]).flat())];if(r.length>0&&setTimeout(()=>{this._runFileValidators(r)}),t.uploadProgress){for(let n of t.uploadProgress){let{isUploading:o,silent:l}=w.getCtx(n).store;o&&!l&&this.emit($.FILE_UPLOAD_PROGRESS,this.getOutputItem(n))}this._flushCommonUploadProgress()}if(t.isUploading)for(let n of t.isUploading){let{isUploading:o,silent:l}=w.getCtx(n).store;o&&!l&&this.emit($.FILE_UPLOAD_START,this.getOutputItem(n))}if(t.fileInfo){for(let l of t.fileInfo){let{fileInfo:a,silent:c}=w.getCtx(l).store;a&&!c&&this.emit($.FILE_UPLOAD_SUCCESS,this.getOutputItem(l))}this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo"));e.findItems(l=>l.getValue("errors").length>0).length===0&&e.size===n.length&&this.emit($.COMMON_UPLOAD_SUCCESS,this.getOutputCollectionState())}if(t.errors)for(let n of t.errors){let{errors:o}=w.getCtx(n).store;o.length>0&&(this.emit($.FILE_UPLOAD_FAILED,this.getOutputItem(n)),this.emit($.COMMON_UPLOAD_FAILED,()=>this.getOutputCollectionState(),{debounce:!0}))}t.cdnUrl&&([...t.cdnUrl].filter(o=>{var l;return!!((l=this.uploadCollection.read(o))!=null&&l.getValue("cdnUrl"))}).forEach(o=>{this.emit($.FILE_URL_CHANGED,this.getOutputItem(o))}),this.$["*groupInfo"]=null)});h(this,"_flushCommonUploadProgress",()=>{var n;if(!this.$["*uploadTrigger"])return;let t=0,e=(n=this.$["*uploadTrigger"])!=null?n:[];e.forEach(o=>{t+=this.uploadCollection.readProp(o,"uploadProgress")});let r=e.length?Math.round(t/e.length):0;this.$["*commonProgress"]=r,this.emit($.COMMON_UPLOAD_PROGRESS,this.getOutputCollectionState())})}setUploadMetadata(t){$t("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof s?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new je({typedSchema:ar,watchList:["uploadProgress","uploadError","fileInfo","errors","cdnUrl","isUploading"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectionUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate);let t=()=>{this._runFileValidators(),this._runCollectionValidators()};this.subConfigValue("maxLocalFileSizeBytes",t),this.subConfigValue("multipleMin",t),this.subConfigValue("multipleMax",t),this.subConfigValue("multiple",t),this.subConfigValue("imgOnly",t),this.subConfigValue("accept",t),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){let o=this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silent:e!=null?e:!1,source:n!=null?n:Y.API});return this.getOutputItem(o)}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){let o=this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silent:e!=null?e:!1,source:n!=null?n:Y.API});return this.getOutputItem(o)}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){let l=this.uploadCollection.add({file:t,isImage:ie(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silent:e!=null?e:!1,source:n!=null?n:Y.API,fullPath:o!=null?o:null});return this.getOutputItem(l)}addFiles(t){return console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.map(e=>{let r=this.uploadCollection.add({file:e,isImage:ie(e),mimeType:e.type,fileName:e.name,fileSize:e.size});return this.getOutputItem(r)})}openSystemDialog(t={}){var r;let e=kt(ji([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?ee:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=kt(ee)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Y.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=M(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(s.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=ji([...e?ee:[],r]);if(!n.length)return;let o=t.mimeType,l=t.name;if(!o||!l)return;let a=Hi(o,n),c=sr(l,n);if(!a&&!c)return Lt({type:"FORBIDDEN_FILE_TYPE",message:this.l10n("file-type-not-allowed"),entry:t})}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.size;if(e&&r&&r>e)return Lt({type:"FILE_SIZE_EXCEEDED",message:this.l10n("files-max-size-limit-error",{maxFileSize:rr(e)}),entry:t})}_validateUploadError(t,e){let r=e==null?void 0:e.getValue("uploadError");if(r){if(r instanceof D)return Lt({type:"UPLOAD_ERROR",message:r.message,entry:t,error:r});if(r instanceof Dt)return Lt({type:"NETWORK_ERROR",message:r.message,entry:t,error:r});{let n=r instanceof Error?r:new Error("Unknown error",{cause:r});return Lt({type:"UNKNOWN_ERROR",message:n.message,entry:t,error:n})}}}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.isImage;if(!(!e||r)&&!(!t.fileInfo&&t.externalUrl)&&!(!t.fileInfo&&!t.mimeType))return Lt({type:"NOT_AN_IMAGE",message:this.l10n("images-only-accepted"),entry:t})}_runFileValidatorsForEntry(t){let e=this.getOutputItem(t.uid),r=[];for(let n of this._fileValidators){let o=n(e,t);o&&r.push(o)}t.setValue("errors",r)}_runFileValidators(t){let e=t!=null?t:this.uploadCollection.items();for(let r of e){let n=this.uploadCollection.read(r);n&&this._runFileValidatorsForEntry(n)}}_runCollectionValidators(){let t=this.uploadCollection,e=[];for(let r of this._collectionValidators){let n=r(t);n&&(Array.isArray(n)?e.push(...n):e.push(n))}this.$["*collectionErrors"]=e,e.length>0&&this.emit($.COMMON_UPLOAD_FAILED,()=>this.getOutputCollectionState(),{debounce:!0})}async _createGroup(t){let e=this.getUploadClientOptions(),r=t.allEntries.map(a=>a.uuid+(a.cdnUrlModifiers?`/${a.cdnUrlModifiers}`:"")),n=new AbortController,o=await Us(r,{...e,signal:n.signal});if(this.$["*collectionState"]!==t){n.abort();return}this.$["*groupInfo"]=o;let l=this.getOutputCollectionState();this.emit($.GROUP_CREATED,l),this.emit($.CHANGE,()=>this.getOutputCollectionState(),{debounce:!0}),this.$["*collectionState"]=l}setInitialCrop(){let t=Ne(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=R(`crop/${u.width}x${u.height}/${u.x},${u.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:k(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:qs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var l,a,c,u,d,p,m,f,_,T;let e=w.getCtx(t).store,r=e.fileInfo,n=e.isRemoved?"removed":e.errors.length>0?"failed":e.fileInfo?"success":e.isUploading?"uploading":"idle";return{uuid:(a=(l=r==null?void 0:r.uuid)!=null?l:e.uuid)!=null?a:null,internalId:t,name:(c=r==null?void 0:r.originalFilename)!=null?c:e.fileName,size:(u=r==null?void 0:r.size)!=null?u:e.fileSize,isImage:(d=r==null?void 0:r.isImage)!=null?d:e.isImage,mimeType:(p=r==null?void 0:r.mimeType)!=null?p:e.mimeType,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(f=(m=e.cdnUrl)!=null?m:r==null?void 0:r.cdnUrl)!=null?f:null,fullPath:e.fullPath,uploadProgress:e.uploadProgress,fileInfo:r!=null?r:null,metadata:(T=(_=e.metadata)!=null?_:r==null?void 0:r.metadata)!=null?T:null,isSuccess:n==="success",isUploading:n==="uploading",isFailed:n==="failed",isRemoved:n==="removed",errors:e.errors,status:n}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}getOutputCollectionState(){return lr(this)}};E.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});E.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...E.extSrcList});var X=Object.freeze({brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0,mirror:!1,flip:!1,crop:void 0}),hr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function yo(s,i){if(typeof i=="number"){let t=i;return X[s]!==t?`${s}/${t}`:""}if(typeof i=="boolean"){let t=i;return X[s]!==t?`${s}`:""}if(s==="filter"&&i){let{name:t,amount:e}=i;return X.filter===e?"":`${s}/${t}/${e}`}if(s==="crop"&&i){let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}function wt(s){return Ve(...hr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yo(i,t)}).filter(i=>!!i))}var Ge=Ve("format/auto","progressive/yes"),ft=([s])=>typeof s!="undefined"?Number(s):void 0,cr=()=>!0,vo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Co=([s,i])=>{if(!/\d+x\d+/.test(s)||!/\d+,\d+/.test(i))throw new Error("Crop by aspect ratio, percentage or alignment shortcuts is not supported.");return{dimensions:M(s,"x").map(Number),coords:M(i).map(Number)}},wo=Object.freeze({enhance:ft,brightness:ft,exposure:ft,gamma:ft,contrast:ft,saturation:ft,vibrance:ft,warmth:ft,filter:vo,mirror:cr,flip:cr,rotate:ft,crop:Co});function ur(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!hr.includes(e))continue;let n=e,o=wo[n];try{let l=o(r);i[n]=l}catch(l){console.warn([`Failed to parse URL operation "${t}". It will be ignored.`,l instanceof Error?`Error message: "${l.message}"`:l,"If you need this functionality, please feel free to open an issue at https://github.com/uploadcare/blocks/issues/new"].join(` `))}}return i}var L=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),H=[L.CROP,L.TUNING,L.FILTERS],dr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],pr=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],fr=["rotate","mirror","flip"],st=Object.freeze({brightness:{zero:X.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:X.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:X.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:X.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:X.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:X.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:X.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:X.enhance,range:[0,100],keypointsNumber:1},filter:{zero:X.filter,range:[0,100],keypointsNumber:1}});var Eo="https://ucarecdn.com",xo="https://upload.uploadcare.com",To="https://social.uploadcare.com",Et={pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:kt(H),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Eo,baseUrl:xo,socialBaseUrl:To,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",debug:!1,metadata:null};var G=s=>String(s),rt=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},I=s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},Ao=s=>s==="auto"?s:I(s),So={pubkey:G,multiple:I,multipleMin:rt,multipleMax:rt,confirmUpload:I,imgOnly:I,accept:G,externalSourcesPreferredTypes:G,store:Ao,cameraMirror:I,sourceList:G,maxLocalFileSizeBytes:rt,thumbSize:rt,showEmptyList:I,useLocalImageEditor:I,useCloudImageEditor:I,cloudImageEditorTabs:G,removeCopyright:I,cropPreset:G,modalScrollLock:I,modalBackdropStrokes:I,sourceListWrap:I,remoteTabSessionKey:G,cdnCname:G,baseUrl:G,socialBaseUrl:G,secureSignature:G,secureExpire:G,secureDeliveryProxy:G,retryThrottledRequestMaxTimes:rt,multipartMinFileSize:rt,multipartChunkSize:rt,maxConcurrentRequests:rt,multipartMaxConcurrentRequests:rt,multipartMaxAttempts:rt,checkForUrlDuplicates:I,saveUrlForRecurrentUploads:I,groupOutput:I,userAgentIntegration:G,debug:I},mr=(s,i)=>{if(!(typeof i=="undefined"||i===null))try{return So[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),Et[s]}};var re=Object.keys(Et),$o=["metadata"],Io=s=>$o.includes(s),We=re.filter(s=>!Io(s)),Oo={...Object.fromEntries(We.map(s=>[ht(s),s])),...Object.fromEntries(We.map(s=>[s.toLowerCase(),s]))},ko={...Object.fromEntries(re.map(s=>[ht(s),F(s)])),...Object.fromEntries(re.map(s=>[s.toLowerCase(),F(s)]))},Xe=class extends v{constructor(){super();h(this,"requireCtxName",!0);h(this,"_debugPrint",O(()=>{let t=Object.create(null);for(let e of re)t[e]=this.$[F(e)];this.debugPrint("config",t)},0));this.init$={...this.init$,...Object.fromEntries(Object.entries(Et).map(([t,e])=>[F(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of We)this.sub(F(e),r=>{r!==Et[e]&&(t[e]=r)},!1);for(let e of re){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,We.includes(e)){let o=[...new Set([ht(e),e.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[F(e)]!==n&&(typeof n=="undefined"||n===null?this.$[F(e)]=Et[e]:this.$[F(e)]=n)},get:()=>this.$[F(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Oo[t],o=mr(n,r),l=o!=null?o:Et[n],a=this;a[n]=l}};Xe.bindAttributes(ko);var Lo=Xe;var ne=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ne.template=``;ne.bindAttributes({name:"name",size:"size"});var gr=s=>[...new Set(s)];var _r=s=>Object.entries(s).filter(([i,t])=>t!==void 0&&t!=="").map(([i,t])=>i==="cdn-operations"||i==="analytics"?t:`${i}/${t}`);var Po="https://ucarecdn.com",oe=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Po},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{},"cdn-operations":{},progressive:{},quality:{},"is-background-for":{},"is-preview-blur":{default:1}});var Ht="--lr-img-",Gi="unresolved";var Wi=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),Xi=3e3,qi=5e3,Ki=Object.freeze({PREVIEW:"PREVIEW",MAIN:"MAIN"});var yr=Object.create(null),br;for(let s in oe)yr[Ht+s]=((br=oe[s])==null?void 0:br.default)||"";var qe=class extends Nt{constructor(){super(...arguments);h(this,"cssInit$",yr)}$$(t){return this.$[Ht+t]}set$$(t){for(let e in t)this.$[Ht+e]=t[e]}sub$$(t,e){this.sub(Ht+t,r=>{r===null||r===""||e(r)})}analyticsParams(){return`-/@clib/${De}/${Fe}/lr-img/`}initAttributes(t){[...this.attributes].forEach(e=>{oe[e.name]||t.setAttribute(e.name,e.value)})}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),w.deleteCtx(this)}static get observedAttributes(){return Object.keys(oe)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[Ht+t]=r})}};var Ze=class extends qe{constructor(){super(...arguments);h(this,"_img",new Image);h(this,"_imgPreview",new Image)}_fmtAbs(t){return!t.includes("//")&&!Wi&&(t=new URL(t,document.baseURI).href),t}_validateSize(t){if((t==null?void 0:t.trim())!==""){let e=t.match(/\d+/)[0],r=t.match(/[a-zA-Z]+/)[0],n=parseInt(e,10);if(Number(n)>qi&&this.hasFormatJPG)return qi+r;if(Number(n)>Xi&&!this.hasFormatJPG)return Xi+r}return t}_getCdnModifiers(t,e){let r={format:this.$$("format"),quality:this.$$("quality"),resize:this._validateSize(t),blur:e,"cdn-operations":this.$$("cdn-operations"),analytics:this.analyticsParams()};return R(..._r(r))}_getUrlBase(t="",e=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(Wi&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let r=this._getCdnModifiers(t,e);if(this.$$("src").startsWith(this.$$("cdn-cname")))return k(this.$$("src"),r);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(k(Ct(this.$$("cdn-cname"),this.$$("uuid")),r));if(this.$$("uuid"))return this._proxyUrl(k(Ct(this.$$("cdn-cname"),this.$$("uuid")),r));if(this.$$("proxy-cname"))return this._proxyUrl(k(this.$$("proxy-cname"),r,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(k(`https://${this.$$("pubkey")}.ucr.io/`,r,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Zt(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this.hasPreviewImage||(this._setupConfigForImage({elNode:this._img}),this.appendChild(this._img)),this._img}get currentImg(){return this.hasPreviewImage?{type:Ki.PREVIEW,img:this._imgPreview}:{type:Ki.MAIN,img:this.img}}get hasPreviewImage(){return this.$$("is-preview-blur")}get bgSelector(){return this.$$("is-background-for")}get breakpoints(){if(this.$$("breakpoints")){let t=M(this.$$("breakpoints"));return gr(t.map(e=>parseInt(e,10)))}else return null}get hasFormatJPG(){return this.$$("format").toLowerCase()==="jpeg"}renderBg(t){let e=new Set;e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,2))}") ${2}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,3))}") ${3}x`);let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${this._validateSize(e+"w")}`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*2+"x")+` ${this._validateSize(e*2+"w")}`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*3+"x")+` ${this._validateSize(e*3+"w")}`)}):(t.add(this._getUrlBase(this._getElSize(this.currentImg.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.currentImg.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.currentImg.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}get srcUrlPreview(){return this._getUrlBase("100x","100")}renderBackground(){[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)})}_appendURL({elNode:t,src:e,srcset:r}){e&&(t.src=e),r&&(t.srcset=r)}_setupConfigForImage({elNode:t}){this._setupEventProxy(t),this.initAttributes(t)}loaderImage({src:t,srcset:e,elNode:r}){return new Promise((n,o)=>{this._setupConfigForImage({elNode:r}),r.setAttribute(Gi,""),r.addEventListener("load",()=>{r.removeAttribute(Gi),n(r)}),r.addEventListener("error",()=>{o(!1)}),this._appendURL({elNode:r,src:t,srcset:e})})}async renderImage(){var t,e;if(this.$$("intersection")){this.hasPreviewImage&&(this._setupConfigForImage({elNode:this._imgPreview}),this.appendChild(this._imgPreview)),this.initIntersection(this.currentImg.img,async()=>{var r;this.hasPreviewImage&&(this._imgPreview.src=this.srcUrlPreview);try{await this.loaderImage({src:this.getSrc(),srcset:this.getSrcset(),elNode:this._img}),this.hasPreviewImage&&await this._imgPreview.remove(),this.appendChild(this._img)}catch{this.hasPreviewImage&&await((r=this._imgPreview)==null?void 0:r.remove()),this.appendChild(this._img)}});return}try{this.hasPreviewImage&&(await this.loaderImage({src:this.srcUrlPreview,elNode:this._imgPreview}),this.appendChild(this._imgPreview)),await this.loaderImage({src:this.getSrc(),srcset:this.getSrcset(),elNode:this._img}),this.hasPreviewImage&&await((t=this._imgPreview)==null?void 0:t.remove()),this.appendChild(this._img)}catch{this.hasPreviewImage&&await((e=this._imgPreview)==null?void 0:e.remove()),this.appendChild(this._img)}}init(){this.bgSelector?this.renderBackground():this.renderImage()}};var Yi=class extends Ze{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{!this.$$("is-background-for")&&!this.$$("is-preview-blur")&&(this.img.loading=i?"lazy":"eager")})}};var le=class extends E{constructor(){super();h(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=I(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};le.template=``;le.bindAttributes({dropzone:null});var Je=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};Je.template='
';function Uo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function Ro(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function vr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Uo(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var B={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},Cr=["focus"],Mo=100,Zi=new Map;function No(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Ji(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=B.INACTIVE,o=f=>{s.shouldIgnore()&&f!==B.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(B.INACTIVE)},c=()=>{i+=1,n===B.INACTIVE&&o(B.ACTIVE)},u=()=>{i-=1,l()||o(B.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(B.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let _=[f.x,f.y],T=s.element.getBoundingClientRect(),A=Math.floor(No(_,T)),x=A{if(s.shouldIgnore())return;f.preventDefault();let _=await vr(f.dataTransfer);s.onItems(_),o(B.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),Cr.forEach(f=>{window.addEventListener(f,a)}),()=>{Zi.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),Cr.forEach(f=>{window.removeEventListener(f,a)})}}var wr="lr-drop-area",Gt=`${wr}/registry`,ae=class extends E{constructor(){super(),this.init$={...this.init$,state:B.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[Gt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[Gt]||(this.$[Gt]=new Set),this.$[Gt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!I(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:I(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:I(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:I(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Ji({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Y.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Y.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=Ji({element:i,onChange:t=>{var r;let e=(r=Object.entries(B).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(B).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=M(t);this.$.isEnabled=e.includes(E.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[Gt]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[Gt];i&&(i.delete(this),i.size===0&&w.deleteCtx(wr)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ae.template=`
{{text}}
`;ae.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Do="src-type-",ce=class extends E{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:E.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:E.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:E.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(E.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${Do}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ce.template=`
`;ce.bindAttributes({type:null});var Qi=class extends v{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=M(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function Er(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function xr(s="#fff",i="rgba(0, 0, 0, .1)"){return Er(``)}function he(s="hsl(209, 21%, 65%)",i=32,t=32){return Er(``)}function Tr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var Z=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3)}),ue=class s extends E{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",O(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",O(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,state:Z.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=Z.IDLE;t.getValue("errors").length>0?e=Z.FAILED:t.getValue("isUploading")?e=Z.UPLOADING:t.getValue("fileInfo")&&(e=Z.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(k(Ct(this.cfg.cdnCname,this._entry.getValue("uuid")),R(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Tr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",he(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",he(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("fileInfo",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("errors",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{s.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t!=null&&t.includes(this._entry.uid)&&setTimeout(()=>this.isConnected&&this.upload())}),s.activeInstances.add(this)}_handleState(t){var e,r,n,o;this.set$({isFailed:t===Z.FAILED,isUploading:t===Z.UPLOADING,isFinished:t===Z.FINISHED,progressVisible:t===Z.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:(o=(n=this._entry.getValue("errors"))==null?void 0:n[0])==null?void 0:o.message}),t===Z.FAILED?this.$.badgeIcon="badge-error":t===Z.FINISHED&&(this.$.badgeIcon="badge-success"),t===Z.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),s.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var r,n,o;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("errors").length>0)return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(!(e&&this.uploadCollection.size>e)){this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("errors",[]),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let l=new AbortController;t.setValue("abortController",l);let a=async()=>{let u=t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),p={...this.getUploadClientOptions(),fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:m=>{if(m.isComputable){let f=m.value*100;t.setValue("uploadProgress",f)}this.$.progressUnknown=!m.isComputable},signal:l.signal,metadata:await this.getMetadataFor(t.uid)};return this.debugPrint("upload options",u,p),Di(u,p)},c=await this.$["*uploadQueue"].add(a);t.setMultipleValues({fileInfo:c,isUploading:!1,fileName:c.originalFilename,fileSize:c.size,isImage:c.isImage,mimeType:(o=(n=(r=c.contentInfo)==null?void 0:r.mime)==null?void 0:n.mime)!=null?o:c.mimeType,uuid:c.uuid,cdnUrl:c.cdnUrl,uploadProgress:100}),t===this._entry&&this._debouncedCalculateState()}catch(l){l instanceof _t&&l.isCancel?t.setMultipleValues({isUploading:!1,uploadProgress:0}):t.setMultipleValues({isUploading:!1,uploadProgress:0,uploadError:l}),t===this._entry&&this._debouncedCalculateState()}}}};ue.template=`
{{itemName}}{{errorText}}
`;ue.activeInstances=new Set;var de=class extends v{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogMouseDown",t=>{this._mouseDownTarget=t.target});h(this,"_handleDialogMouseUp",t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};h(de,"StateConsumerScope","modal");de.template=``;var Qe=class extends E{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_throttledHandleCollectionUpdate",He(()=>{this.isConnected&&(this._updateUploadsState(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},300));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",commonErrorMessage:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.emit($.UPLOAD_CLICK),this.uploadAll(),this._throttledHandleCollectionUpdate()},onDone:()=>{this.emit($.DONE_CLICK,this.getOutputCollectionState()),this.doneFlow()},onCancel:()=>{this.uploadCollection.clearAll()}}}_updateUploadsState(){let t=this.getOutputCollectionState(),e={total:t.totalCount,succeed:t.successCount,uploading:t.uploadingCount,failed:t.failedCount},r=!t.errors.some(p=>p.type==="TOO_MANY_FILES"||p.type==="TOO_FEW_FILES"),n=t.errors.some(p=>p.type==="TOO_MANY_FILES"),o=t.totalCount===(this.cfg.multiple?this.cfg.multipleMax:1),l=e.failed===0,a=!1,c=!1,u=!1;e.total-e.succeed-e.uploading-e.failed>0&&r?a=!0:(c=!0,u=e.total===e.succeed&&r&&l),this.set$({doneBtnVisible:c,doneBtnEnabled:u,uploadBtnVisible:a,addMoreBtnEnabled:e.total===0||!n&&!o,addMoreBtnVisible:!o||this.cfg.multiple,headerText:this._getHeaderText(e)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._throttledHandleCollectionUpdate),this.subConfigValue("multipleMin",this._throttledHandleCollectionUpdate),this.subConfigValue("multipleMax",this._throttledHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._throttledHandleCollectionUpdate),this.sub("*uploadList",t=>{this._throttledHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.uploadAll()},!1),this.sub("*collectionErrors",t=>{let e=t.filter(r=>r.type!=="SOME_FILES_HAS_ERRORS")[0];if(!e){this.set$({commonErrorMessage:null});return}this.set$({commonErrorMessage:e.message})})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._throttledHandleCollectionUpdate)}};Qe.template=`{{headerText}}
`;var ti=class extends E{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Y.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};ti.template=`
`;var ts=()=>typeof navigator.permissions!="undefined";var ei=class extends E{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:ts(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{ts()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",O(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Y.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ei.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var es=class extends E{constructor(){super(...arguments);h(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},Fo=es;var ii=class extends E{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=he(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=ie(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("errors",n=>{var o;this.$.errorTxt=(o=n[0])==null?void 0:o.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=k(n,R("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ii.template=`
{{fileSize}}
{{errorTxt}}
`;var is=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},si=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new is);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};si.template=`{{activityCaption}}
{{messageTxt}}
`;var ri=class extends E{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};ri.template=``;var ni=class extends v{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ni.template='
';var q="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var pe=class extends v{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:q})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${xr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=q}};pe.template='';pe.bindAttributes({checkerboard:"checkerboard"});var Ar="--cfg-ctx-name",P=class extends v{get cfgCssCtxName(){return this.getCssData(Ar,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;if(!i)throw new Error(`ctx-name attribute is required for ${this.constructor.name}`);return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(Ar,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:w.getCtx(this.cfgCtxName)}}get debugCtxName(){return this.cfgCtxName}};function Sr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function N(...s){let i=Sr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function $r(s,...i){let t=Sr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var Ir=s=>{if(!s)return H;let i=Xs(s).filter(t=>H.includes(t));return i.length===0?H:i};function Or(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":H,"*tabId":L.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:q,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:kt(H),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=q,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=R(wt(i),"preview"),r=k(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var kr=`
Network error
{{fileType}}
{{msg}}
`;var nt=class extends P{constructor(){super();h(this,"_debouncedShowLoader",O(this._showLoader.bind(this),300));this.init$={...this.init$,...Or(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$.cdnUrl){let t=Js(this.$.cdnUrl),e=Ct(this.$.cdnUrl,t);if(e===this.$["*originalUrl"])return;this.$["*originalUrl"]=e;let r=Qs(this.$.cdnUrl),n=ur(r);this.$["*editorTransformations"]=n}else if(this.$.uuid){let t=Ct(this.cfg.cdnCname,this.$.uuid);if(t===this.$["*originalUrl"])return;this.$["*originalUrl"]=t,this.$["*editorTransformations"]={}}else throw new Error("No UUID nor CDN URL provided");this.$["*tabId"]===L.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate();try{let t=k(this.$["*originalUrl"],R("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===L.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==q&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||q)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Ne(t)}),this.sub("tabs",t=>{this.$["*tabList"]=Ir(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=N("image",{image_hidden_to_cropper:t===L.CROP,image_hidden_effects:t!==L.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=R(wt(t),"preview"),n=k(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(nt,"className","cloud-image-editor");nt.template=kr;nt.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var oi=class extends P{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=b&&t.width<=b)return!0;let e=t.height<=b&&(i.includes("n")||i.includes("s")),r=t.width<=b&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=K("mask",{id:"backdrop-mask"}),a=K("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=K("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=K("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Ot(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Ot(n,f)}else{let f=vt(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:T}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(zi*vt(Math.min(d,p)/zi/3,0,1),Ns);Ot(n,{x:T[0]-A,y:T[1]-A,width:A*2,height:A*2}),Ot(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",N("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ot(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=K("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=K("rect",{fill:"transparent"}),l=K("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=K("svg"),t=K("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=K("line",{x1:`${te*e}%`,y1:"0%",x2:`${te*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=K("line",{x1:"0%",y1:`${te*e}%`,x2:"100%",y2:`${te*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Vs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Vt(jt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Bs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",N("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=b||i.width<=b,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",N({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};oi.template='';var mt=class extends P{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=N({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};mt.template=`
{{title}}
`;function Vo(s){let i=s+90;return i=i>=360?0:i,i}function zo(s,i){return s==="rotate"?Vo(i):["mirror","flip"].includes(s)?!i:null}var fe=class extends mt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=zo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var me={FILTER:"filter",COLOR_OPERATION:"color_operation"},ot="original",li=class extends P{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?me.FILTER:me.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ot?void 0:this.$.value,filter:this._filter===ot?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=st[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===me.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===me.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===me.FILTER?this._filter===ot?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};li.template=``;function ge(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=q)}}}function _e(s){let i=[];for(let n of s){let o=ge(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Wt=class extends mt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ot?{name:this._filter,amount:o}:void 0,k(this._originalUrl,R(Ge,wt(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=ge(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ot,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Wt.template=`
`;var be=class extends mt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=st[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};function Lr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Xt(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return k(s,R(Ge,wt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function jo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ai=class extends P{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=O(this._commit.bind(this),300),this._handleResizeThrottled=He(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Lr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=zt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=jt(l)}_alignCrop(){var d;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[p,m],coords:[f,_]}=n,{width:T}=zt(this._imageSize,r),A=o/T;i=Vt(jt({x:l+f*A,y:a+_*A,width:p*A,height:m*A}),this.$["*imageBox"])}let c=(d=this.$["*cropPresetList"])==null?void 0:d[0],u=c?c.width/c.height:void 0;if(!Hs(i,t)||u&&!Gs(i,u)){let p=t.width/t.height,m=t.width,f=t.height;u&&(p>u?m=Math.min(t.height*u,t.width):f=Math.min(t.width/u,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Vt(jt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=zt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=N({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=zt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[vt(Math.round(c/d),1,l),vt(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=zt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),T={dimensions:_,coords:[vt(Math.round((d-l)/m),0,c-_[0]),vt(Math.round((p-a)/f),0,u-_[1])]};if(!jo(T)){console.error("Cropper is trying to create invalid crop object",{payload:T});return}if(!(_[0]===c&&_[1]===u))return T}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=N({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(Xt(i,e,t)),{promise:n,cancel:o,image:l}=ge(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ai.template=``;function ss(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Ho(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Wo(s,i){return s.map((t,e)=>tn-o)}var rs=class extends P{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=O(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(Xt(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=st[i],r=this._keypoints.map(l=>l.value),n=Go(r,t,e),o=Wo(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=_e(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Pr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=_e(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Pr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=N({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Xo=1,ci=class extends P{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Xo?this.scrollLeft+=e:this.scrollLeft+=t})}};ci.template=" ";function qo(s){return``}function Ko(s){return`
`}var hi=class extends P{constructor(){super();h(this,"_updateInfoTooltip",O(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===L.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(ot);else if(this.$["*tabId"]===L.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||st[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ot,"*currentOperation":null,showLoader:!1,filters:pr,colorOperations:dr,cropOperations:fr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=O(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===L.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new be;return e.operation=t,e}_createFilterControl(t){let e=new Wt;return e.filter=t,e}_createToggleControl(t){let e=new fe;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===L.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===L.FILTERS?[ot,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===L.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===L.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of H){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Xt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=_e([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of H){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};hi.template=`
{{*operationTooltip}}
${H.map(Ko).join("")}
${H.map(qo).join("")}
`;var ye=class extends v{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return N("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};ye.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ye.template=`
{{text}}
`;var ui=class extends v{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};ui.template=`
`;var di={transition:"transition",visible:"visible",hidden:"hidden"},pi=class extends v{constructor(){super(),this._visible=!1,this._visibleStyle=di.visible,this._hiddenStyle=di.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",$r(this,{[di.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(di.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};pi.template=" ";var fi=class extends v{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var ns=class extends E{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new nt,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>{let l=o;this.handleApply(l),this.debugPrint('editor event "apply"',l.detail)}),t.addEventListener("cancel",o=>{let l=o;this.handleCancel(),this.debugPrint('editor event "cancel"',l.detail)}),t.addEventListener("change",o=>{let l=o;this.debugPrint('editor event "change"',l.detail)}),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};var Yo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Ur=function(s,i="i"){let t=s.split("*").map(Yo);return new RegExp("^"+t.join(".+")+"$",i)};var Zo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Rr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Zo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var xt={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in xt){let t=xt[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Mr=function(s,i,t){s in xt||(xt[s]=[]),xt[s].push([i,t])},Nr=function(s,i){s in xt&&(xt[s]=xt[s].filter(t=>t[0]!==i))};function Dr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var mi=class extends E{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,multiple:!1,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length}),this.subConfigValue("multiple",t=>{this.$.multiple=t})}extractUrlFromMessage(t){if(t.alternatives){let e=M(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Ur(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){!this.$.multiple&&this.$.selectedList.length||(this.$.selectedList=[...this.$.selectedList,t],this.$.multiple||this.$.onDone())}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Rr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e="false",{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Dr(n),o.toString()}mountIframe(){let t=Yt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Mr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Nr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};mi.template=`
{{activityCaption}}
{{counter}}
`;var ve=class extends v{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;M(i).forEach(e=>{let r=Yt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ve.bindAttributes({"tab-list":null,default:null});ve.template=`
`;var os=class extends E{constructor(){super(...arguments);h(this,"requireCtxName",!0)}_createValidationInput(){let t=document.createElement("input");return t.type="text",t.name=this.ctxName,t.required=this.cfg.multipleMin>0,t.tabIndex=-1,Ti(t,{opacity:0,height:0,width:0}),t}initCallback(){super.initCallback(),this._validationInputElement=this._createValidationInput(),this.appendChild(this._validationInputElement),this.sub("*collectionState",t=>{var e;{if(this._dynamicInputsContainer||(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer)),!this._validationInputElement){let l=this._createValidationInput();this.appendChild(l),this._validationInputElement=l}if(this._dynamicInputsContainer.innerHTML="",t.status==="uploading"||t.status==="idle"){this._validationInputElement.value="",this._validationInputElement.setCustomValidity("");return}if(t.status==="failed"){let l=(e=t.errors[0])==null?void 0:e.message;this._validationInputElement.value="",this._validationInputElement.setCustomValidity(l);return}let r=t.group?t.group:null;if(r){this._validationInputElement.value=r.cdnUrl,this._validationInputElement.setCustomValidity("");return}let n=t.allEntries.map(l=>l.cdnUrl);if(!this.cfg.multiple&&n.length===1){this._validationInputElement.value=n[0],this._validationInputElement.setCustomValidity("");return}this._validationInputElement.remove(),this._validationInputElement=null;let o=new DocumentFragment;for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=`${this.ctxName}[]`,a.value=l,o.appendChild(a)}this._dynamicInputsContainer.replaceChildren(o)}},!1)}};var ls=class extends g{};var gi=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};gi.template=``;var W={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Fr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Ce=class s extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:W.PLAY,fsIcon:W.FS_ON,volIcon:W.VOL_ON,capIcon:W.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Fr.exitFullscreen():Fr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===W.CAP_OFF?(this.$.capIcon=W.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(s.is+":captions","1")):(this.$.capIcon=W.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(s.is+":captions"))}toggleSound(){this.$.volIcon===W.VOL_ON?(this.$.volIcon=W.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=W.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(s.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(s.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=W.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=W.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=W.FS_OFF:this.$.fsIcon=W.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(s.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};Ce.template=`
{{currentTime}} / {{totalTime}}
`;Ce.bindAttributes({video:"video",src:"src"});var Jo="css-src";function _i(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0);h(this,"requireCtxName",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Se({element:this,attribute:Jo,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var we=class extends _i(v){};var bi=class extends v{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(bi,"template",`Powered by Uploadcare`);var Tt=class extends we{constructor(){super(...arguments);h(this,"requireCtxName",!0);h(this,"init$",Re(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var yi=class extends Tt{shadowReadyCallback(){super.shadowReadyCallback(),this.sub("*modalActive",i=>{this._lastModalActive!==i&&this.emit(i?$.MODAL_OPEN:$.MODAL_CLOSE,void 0,{debounce:!0}),this._lastModalActive=i},!1)}};yi.template=``;var vi=class extends Tt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};vi.template=``;var Ci=class extends Tt{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==g.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};Ci.template=``;var as=class extends _i(nt){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Qo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,Nt as BaseComponent,v as Block,ei as CameraSource,as as CloudImageEditor,ns as CloudImageEditorActivity,nt as CloudImageEditorBlock,Lo as Config,si as ConfirmationDialog,bi as Copyright,oi as CropFrame,w as Data,ae as DropArea,fe as EditorCropButtonControl,Wt as EditorFilterControl,ai as EditorImageCropper,rs as EditorImageFader,be as EditorOperationControl,ci as EditorScroller,li as EditorSlider,hi as EditorToolbar,mi as ExternalSource,ue as FileItem,pe as FilePreview,Ci as FileUploaderInline,vi as FileUploaderMinimal,yi as FileUploaderRegular,os as FormInput,ne as Icon,Yi as Img,ui as LineLoaderUi,ye as LrBtnUi,de as Modal,De as PACKAGE_NAME,Fe as PACKAGE_VERSION,pi as PresenceToggle,ni as ProgressBar,ri as ProgressBarCommon,gi as Select,we as ShadowWrapper,le as SimpleBtn,fi as SliderUi,ce as SourceBtn,Qi as SourceList,Je as StartFrom,ve as Tabs,Fo as UploadCtxProvider,ii as UploadDetails,Qe as UploadList,E as UploaderBlock,ti as UrlSource,Ce as Video,Qo as connectBlocksFrom,cs as registerBlocks,_i as shadowed,ht as toKebabCase}; \ No newline at end of file +var rn=Object.defineProperty;var nn=(s,i,t)=>i in s?rn(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(nn(s,typeof i!="symbol"?i+"":i,t),t);var on=Object.defineProperty,ln=(s,i,t)=>i in s?on(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,$i=(s,i,t)=>(ln(s,typeof i!="symbol"?i+"":i,t),t);function an(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=an(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var C=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),bs="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",cn=bs.length-1,Yt=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function un(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var gs="__default__";function dn(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||gs;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=gs;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function pn(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function fn(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=hn(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):ys(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var xe="{{",Kt="}}",mn="skip-text";function gn(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(mn))&&r.textContent.includes(xe)&&r.textContent.includes(Kt)&&1}});for(;i=e.nextNode();)t.push(i);return t}var _n=function(s,i){gn(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(Kt);)e.textContent.startsWith(xe)?(n=e.textContent.indexOf(Kt)+Kt.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(xe),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(xe,"").replace(Kt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},bn=[un,dn,pn,fn,_n],Te="'",Nt='"',yn=/\\([0-9a-fA-F]{1,6} ?)/g;function vn(s){return(s[0]===Nt||s[0]===Te)&&(s[s.length-1]===Nt||s[s.length-1]===Te)}function Cn(s){return(s[0]===Nt||s[0]===Te)&&(s=s.slice(1)),(s[s.length-1]===Nt||s[s.length-1]===Te)&&(s=s.slice(0,-1)),s}function wn(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ +`,"\\n"),i=wn(i),i=Nt+i+Nt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var _s=0,Mt=null,ct=null,gt=class extends HTMLElement{constructor(){super(),$i(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return gt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Yt.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=gt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=gt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=gt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=gt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=gt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=gt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])ys(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of bn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);ct==null||ct.delete(this.updateCssData),ct!=null&&ct.size||(Mt==null||Mt.disconnect(),Mt=null,ct=null)},100)))}static reg(s,i=!1){s||(_s++,s=`${C.AUTO_TAG_PRFX}-${_s}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` +`));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=An(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){ct||(ct=new Set),ct.add(this.updateCssData),Mt||(Mt=new MutationObserver(s=>{s[0].type==="attributes"&&ct.forEach(i=>{i()})}),Mt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},Dt=gt;$i(Dt,"template");var Si=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Si.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Si.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Si.appMap=Object.create(null);function Ii(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function En(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function Jt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&En(i,s.attributes),s.styles&&Ii(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Jt(t);i.appendChild(e)}),i}var vs="idb-store-ready",xn="symbiote-db",Tn="symbiote-idb-update_",Sn=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(vs,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return Tn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Cs.clear(this.name)}},Cs=class{static get readyEventName(){return vs}static open(s=xn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new Sn(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};$i(Cs,"_reg",Object.create(null));var $=Object.freeze({FILE_ADDED:"file-added",FILE_REMOVED:"file-removed",FILE_UPLOAD_START:"file-upload-start",FILE_UPLOAD_PROGRESS:"file-upload-progress",FILE_UPLOAD_SUCCESS:"file-upload-success",FILE_UPLOAD_FAILED:"file-upload-failed",FILE_URL_CHANGED:"file-url-changed",MODAL_OPEN:"modal-open",MODAL_CLOSE:"modal-close",DONE_CLICK:"done-click",UPLOAD_CLICK:"upload-click",ACTIVITY_CHANGE:"activity-change",COMMON_UPLOAD_START:"common-upload-start",COMMON_UPLOAD_PROGRESS:"common-upload-progress",COMMON_UPLOAD_SUCCESS:"common-upload-success",COMMON_UPLOAD_FAILED:"common-upload-failed",CHANGE:"change",GROUP_CREATED:"group-created"}),Se=class{constructor(i){h(this,"_timeoutStore",new Map);h(this,"_targets",new Set);h(this,"_debugPrint",null);this._debugPrint=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,t){var e;for(let r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:t}));(e=this._debugPrint)==null||e.call(this,()=>{let r=t&&typeof t=="object"?{...t}:t;return[`event "${i}"`,r]})}emit(i,t,{debounce:e}={}){if(typeof e!="number"&&!e){this._dispatch(i,typeof t=="function"?t():t);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let r=typeof e=="number"?e:20,n=window.setTimeout(()=>{this._dispatch(i,typeof t=="function"?t():t),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}};function k(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var ws="--uploadcare-blocks-window-height",$t=class{static registerClient(i){this.clientsRegistry.size===0&&this.attachTracker(),this.clientsRegistry.add(i)}static unregisterClient(i){this.clientsRegistry.delete(i),this.clientsRegistry.size===0&&this.detachTracker()}static attachTracker(){window.addEventListener("resize",this.flush,{passive:!0,capture:!0}),this.flush()}static detachTracker(){window.removeEventListener("resize",this.flush,{capture:!0}),document.documentElement.style.removeProperty(ws)}};h($t,"clientsRegistry",new Set),h($t,"flush",k(()=>{document.documentElement.style.setProperty(ws,`${window.innerHeight}px`)},100));var $e=(s,i)=>new Intl.PluralRules(s).select(i);var $n=s=>s,ki="{{",Es="}}",As="plural:";function Zt(s,i,t={}){var o;let{openToken:e=ki,closeToken:r=Es,transform:n=$n}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function xs(s){let i=[],t=s.indexOf(ki);for(;t!==-1;){let e=s.indexOf(Es,t),r=s.substring(t+2,e);if(r.startsWith(As)){let n=s.substring(t+2,e).replace(As,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(ki,e)}return i}var ht=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ie=({element:s,attribute:i,onSuccess:t,onTimeout:e,timeout:r=300})=>{let n=s.getAttribute(i);if(n!==null){t(n);return}let o=new MutationObserver(c=>{let u=c[c.length-1];a(u)});o.observe(s,{attributes:!0,attributeFilter:[i]});let l=setTimeout(()=>{o.disconnect(),e()},r),a=c=>{let u=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&u!==null&&(clearTimeout(l),o.disconnect(),t(u))}};var Ts=new Set;function It(s){Ts.has(s)||(Ts.add(s),console.warn(s))}function Ss(s){return Object.prototype.toString.call(s)==="[object Object]"}var In=/\W|_/g;function kn(s){return s.split(In).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function $s(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>pt(t,{ignoreKeys:i})):s}function pt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return $s(s,{ignoreKeys:i});if(!Ss(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Ss(r)?r=pt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=$s(r,{ignoreKeys:i})),t[kn(e)]=r}return t}var On=s=>new Promise(i=>setTimeout(i,s));function Ni({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var Pn={factor:2,time:100};function Ln(s,i=Pn){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>On(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Qt=class extends Error{},Ft=class s extends Qt{constructor(t){super();h(this,"originalProgressEvent");this.name="NetworkError",this.message="Network error",Object.setPrototypeOf(this,s.prototype),this.originalProgressEvent=t}},Oe=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},_t=class s extends Qt{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);this.name="CancelError",Object.setPrototypeOf(this,s.prototype)}},Un=500,ks=({check:s,interval:i=Un,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Oe(e,()=>{o&&clearTimeout(o),n(new _t("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new _t("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),S={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Pe="application/octet-stream",Os="original",bt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Oe(r,()=>{u=!0,a.abort(),l(new _t)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function(b){let x=b.split(": "),v=x.shift(),A=x.join(": ");v&&typeof v!="undefined"&&(m[v]=A)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new Ft(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function Rn(s,...i){return s}var Mn=({name:s})=>s?[s]:[],Nn=Rn,Dn=()=>new FormData,Ps=s=>!1,Le=s=>typeof Blob!="undefined"&&s instanceof Blob,Ue=s=>typeof File!="undefined"&&s instanceof File,Re=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Bt=s=>Le(s)||Ue(s)||Ps()||Re(s),Fn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",Bn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),zn=s=>!!s&&typeof s=="object"&&"data"in s&&Bt(s.data);function Ls(s,i,t){if(Array.isArray(t))for(let e of t)Ls(s,`${i}[]`,e);else if(zn(t)){let{name:e,contentType:r}=t,n=Nn(t.data,e,r!=null?r:Pe),o=Mn({name:e,contentType:r});s.push([i,n,...o])}else if(Bn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else Fn(t)&&t&&s.push([i,t.toString()])}function Vn(s){let i=[];for(let[t,e]of Object.entries(s))Ls(i,t,e);return i}function Me(s){let i=Dn(),t=Vn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var D=class s extends Qt{constructor(t,e,r,n,o){super();h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,s.prototype)}},jn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ut=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=jn(t)),e.toString()},Hn="6.13.0",Gn="UploadcareUploadClient",Wn=Hn;function kt(s){return Ni({libraryName:Gn,libraryVersion:Wn,...s})}var Xn="RequestThrottledError",Is=15e3,qn=1e3;function Kn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return Is;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Is}function yt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return Ln(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Xn&&r{let i="";return(Le(s)||Ue(s)||Re(s))&&(i=s.type),i||Pe},Rs=s=>{let i="";return Ue(s)&&s.name?i=s.name:Le(s)||Ps()?i="":Re(s)&&s.name&&(i=s.name),i||Os};function Di(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Yn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=S.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=S.retryNetworkErrorMaxTimes,metadata:_}){return yt(()=>bt({method:"POST",url:ut(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Me({file:{data:s,name:t||Rs(s),contentType:e||Us(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Di(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:b,headers:x,request:v})=>{let A=pt(JSON.parse(b));if("error"in A)throw new D(A.error.content,A.error.errorCode,v,A,x);return A}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Li;(function(s){s.Token="token",s.FileInfo="file_info"})(Li||(Li={}));function Jn(s,{publicKey:i,baseURL:t=S.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=S.retryNetworkErrorMaxTimes,metadata:_}){return yt(()=>bt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},url:ut(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Di(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:b,headers:x,request:v})=>{let A=pt(JSON.parse(b));if("error"in A)throw new D(A.error.content,A.error.errorCode,v,A,x);return A}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var H;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(H||(H={}));var Zn=s=>"status"in s&&s.status===H.Error;function Qn(s,{publicKey:i,baseURL:t=S.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=S.retryNetworkErrorMaxTimes}={}){return yt(()=>bt({method:"GET",headers:i?{"X-UC-User-Agent":kt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ut(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=pt(JSON.parse(a));if("error"in d&&!Zn(d))throw new D(d.error.content,d.error.errorCode,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function to(s,{publicKey:i,baseURL:t=S.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=S.retryNetworkErrorMaxTimes}){return yt(()=>bt({method:"POST",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:a,userAgent:c})},url:ut(t,"/group/",{jsonerrors:1}),data:Me({files:s,callback:e,pub_key:i,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=pt(JSON.parse(p));if("error"in _)throw new D(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function Ms(s,{publicKey:i,baseURL:t=S.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=S.retryNetworkErrorMaxTimes}){return yt(()=>bt({method:"GET",headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},url:ut(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=pt(JSON.parse(c));if("error"in p)throw new D(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function eo(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=S.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=S.retryNetworkErrorMaxTimes,metadata:_}){return yt(()=>bt({method:"POST",url:ut(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:d,userAgent:p})},data:Me({filename:e||Os,size:s,content_type:t||Pe,part_size:r,UPLOADCARE_STORE:Di(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:b,headers:x,request:v})=>{let A=pt(JSON.parse(b));if("error"in A)throw new D(A.error.content,A.error.errorCode,v,A,x);return A.parts=Object.keys(A.parts).map(V=>A.parts[V]),A}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function io(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=S.retryNetworkErrorMaxTimes}){return yt(()=>bt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Pe}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function so(s,{publicKey:i,baseURL:t=S.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=S.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=S.retryNetworkErrorMaxTimes}){return yt(()=>bt({method:"POST",url:ut(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":kt({publicKey:i,integration:n,userAgent:o})},data:Me({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=pt(JSON.parse(c));if("error"in p)throw new D(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Fi(s,{publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return ks({check:u=>Ms(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function ro(s){return"defaultEffects"in s}var dt=class{constructor(i,{baseCDN:t=S.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);h(this,"defaultEffects",null);let{uuid:r,s3Bucket:n}=i,o=ut(t,`${r}/`),l=n?ut(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l,ro(i)&&(this.defaultEffects=i.defaultEffects)}},no=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:b})=>Yn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:b}).then(({file:x})=>Fi(x,{publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(x=>new dt(x,{baseCDN:_})),oo=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>Ms(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new dt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),lo=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Oe(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},ao=window.WebSocket,Ui=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},co=(s,i)=>s==="success"?{status:H.Success,...i}:s==="progress"?{status:H.Progress,...i}:{status:H.Error,...i},Ri=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ui);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new ao(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,co(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Oi=null,Bi=s=>{if(!Oi){let i=typeof window=="undefined"?0:3e4;Oi=new Ri(s,i)}return Oi},ho=s=>{Bi(s).connect()};function uo({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return ks({check:c=>Qn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case H.Error:return new D(u.error,u.errorCode);case H.Waiting:return!1;case H.Unknown:return new D(`Token "${s}" was not found.`);case H.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case H.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var po=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Bi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Oe(t,()=>{a(),n(new _t("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case H.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case H.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case H.Error:a(),n(new D(c.msg,c.error_code))}})}),fo=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:b=S.pusherKey,metadata:x})=>Promise.resolve(ho(b)).then(()=>Jn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:x})).catch(v=>{let A=Bi(b);return A==null||A.disconnect(),Promise.reject(v)}).then(v=>v.type===Li.FileInfo?v:lo([({signal:A})=>uo({token:v.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:A}),({signal:A})=>po({token:v.token,pusherKey:b,signal:A,onProgress:d})],{signal:u})).then(v=>{if(v instanceof D)throw v;return v}).then(v=>Fi(v.uuid,{publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(v=>new dt(v,{baseCDN:r})),Pi=new WeakMap,mo=async s=>{if(Pi.has(s))return Pi.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Pi.set(s,i),i},Ns=async s=>{if(Ue(s)||Le(s))return s.size;if(Re(s))return(await mo(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},go=(s,i=S.multipartMinFileSize)=>s>=i,Ds=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Bt(s)&&t.test(s)},zi=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Bt(s)&&t.test(s)},_o=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},yo=async(s,i,t)=>e=>bo(s,e,i,t),vo=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>io(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Co=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:b=S.multipartChunkSize,maxConcurrentRequests:x=S.maxConcurrentRequests,baseCDN:v,metadata:A})=>{let V=e!=null?e:await Ns(s),lt,St=(U,j)=>{if(!c)return;lt||(lt=Array(U).fill(0));let Z=tt=>tt.reduce((at,Ti)=>at+Ti,0);return tt=>{tt.isComputable&&(lt[j]=tt.value,c({isComputable:!0,value:Z(lt)/U}))}};return _||(_=Us(s)),eo(V,{publicKey:i,contentType:_,fileName:t||Rs(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:A}).then(async({uuid:U,parts:j})=>{let Z=await yo(s,V,b);return Promise.all([U,_o(x,j.map((tt,at)=>()=>vo(Z(at),tt,{publicKey:i,contentType:_,onProgress:St(j.length,at),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([U])=>so(U,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(U=>U.isReady?U:Fi(U.uuid,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(U=>new dt(U,{baseCDN:v}))};async function Vi(s,{publicKey:i,fileName:t,baseURL:e=S.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:b,maxConcurrentRequests:x,baseCDN:v=S.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:V,pusherKey:lt,metadata:St}){if(Bt(s)){let U=await Ns(s);return go(U,_)?Co(s,{publicKey:i,contentType:f,multipartChunkSize:b,fileSize:U,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:x,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:v,metadata:St}):no(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:v,metadata:St})}if(zi(s))return fo(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:v,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:V,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:lt,metadata:St});if(Ds(s))return oo(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:v});throw new TypeError(`File uploading from "${s}" is not supported`)}var Mi=class{constructor(i,{baseCDN:t=S.baseCDN}={}){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;let e=i.files.filter(Boolean);this.totalSize=Object.values(e).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(e).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=e.map(r=>new dt(r,{baseCDN:t})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},wo=s=>{for(let i of s)if(!Bt(i))return!1;return!0},Ao=s=>{for(let i of s)if(!Ds(i))return!1;return!0},Eo=s=>{for(let i of s)if(!zi(i))return!1;return!0};function Fs(s,{publicKey:i,fileName:t,baseURL:e=S.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=S.multipartChunkSize,baseCDN:b=S.baseCDN,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:v,jsonpCallback:A}){if(!wo(s)&&!Eo(s)&&!Ao(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let V,lt=!0,St=s.length,U=(j,Z)=>{if(!a)return;V||(V=Array(j).fill(0));let tt=at=>at.reduce((Ti,sn)=>Ti+sn)/j;return at=>{if(!at.isComputable||!lt){lt=!1,a({isComputable:!1});return}V[Z]=at.value,a({isComputable:!0,value:tt(V)})}};return Promise.all(s.map((j,Z)=>Bt(j)||zi(j)?Vi(j,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:U(St,Z),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:b,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:v}).then(tt=>tt.uuid):j)).then(j=>to(j,{publicKey:i,baseURL:e,jsonpCallback:A,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(Z=>new Mi(Z,{baseCDN:b})).then(Z=>(a&&a({isComputable:!0,value:1}),Z)))}var ke=class{constructor(i){h(this,"_concurrency",1);h(this,"_pending",[]);h(this,"_running",0);h(this,"_resolvers",new Map);h(this,"_rejectors",new Map);this._concurrency=i}_run(){let i=this._concurrency-this._running;for(let t=0;t{this._resolvers.delete(e),this._rejectors.delete(e),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((t,e)=>{this._resolvers.set(i,t),this._rejectors.set(i,e),this._pending.push(i),this._run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this._run()}get concurrency(){return this._concurrency}};var ji=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),Hi=s=>({...ji(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Ne=s=>({...Hi(s),"*commonProgress":0,"*uploadList":[],"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new ke(1),"*uploadCollection":null,"*collectionErrors":[],"*collectionState":null,"*groupInfo":null,"*uploadTrigger":new Set});function Bs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var F=s=>`*cfg/${s}`;var Gi="lr-",w=class extends Dt{constructor(){super();h(this,"requireCtxName",!1);h(this,"allowCustomTemplate",!0);h(this,"activityType",null);h(this,"init$",ji());h(this,"updateCtxCssData",()=>{It("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/");let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.addTemplateProcessor(Bs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=xs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return Zt(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=$e(r,e);return this.l10n(`${t}__${n}`)}emit(t,e,r){let n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(t,e,r)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Gi}${t}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Ie({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),$t.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),$t.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new Se(this.debugPrint.bind(this)))}destroyCallback(){let t=this.$["*blocksRegistry"];t.delete(this),E.deleteCtx(this),t.size===0&&setTimeout(()=>{this.destroyCtxCallback()},0)}destroyCtxCallback(){E.deleteCtx(this.ctxName)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Zt(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{set:(e,r,n)=>{if(typeof r!="string")return!1;let o=F(r);return this.$[o]=n,!0},get:(e,r)=>{let n=F(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(It("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ht(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(F(t));r.ctx.has(r.name)?this.sub(F(t),e):(this.bindCssData(`--cfg-${ht(t)}`),this.sub(`--cfg-${ht(t)}`,e))}debugPrint(...t){if(!this.cfg.debug)return;let e=t;if(typeof(t==null?void 0:t[0])=="function"){let r=t[0];e=r()}console.log(`[${this.debugCtxName}]`,...e)}get debugCtxName(){return this.ctxName}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Gi)?t:Gi+t)}};h(w,"StateConsumerScope",null),h(w,"className","");var zs="active",te="___ACTIVITY_IS_ACTIVE___",Q=class Q extends w{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Hi(this));h(this,"_debouncedHistoryFlush",k(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=Q._activityRegistry[this.activityKey];this[te]=!1,this.removeAttribute(zs),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=Q._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[te]=!0,this.setAttribute(zs,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush(),this.emit($.ACTIVITY_CHANGE,{activity:this.activityType})}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[te]?this._deactivate():this.activityType===t&&!this[te]&&this._activate(),t||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",t=>{!t&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t[t.length-1]!==this.activityType&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!Q._activityRegistry[this.activityKey]}get isActivityActive(){return this[te]}get couldOpenActivity(){return!0}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;Q._activityRegistry||(Q._activityRegistry=Object.create(null)),Q._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),Q._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(Q._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){var e;let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();let n=!!r;if(r){let l=[...this.$["*blocksRegistry"]].find(a=>a.activityType===r);n=(e=l==null?void 0:l.couldOpenActivity)!=null?e:!1}r=n?r:void 0,this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}};h(Q,"_activityRegistry",Object.create(null));var g=Q;g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ee=33.333333333333336,y=1,Wi=24,Vs=6;function Ot(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function K(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Ot(t,i),t}function js(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Hs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Gs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Ws({rect:s,delta:[i,t],imageBox:e}){return Vt({...s,x:s.x+i,y:s.y+t},e)}function Vt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function xo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Ys(s,i){return Math.abs(s.width/s.height-i)<.1}function jt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Js(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Ht(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function vt(s,i,t){return Math.min(Math.max(s,i),t)}var Fe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var Y=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Zs=s=>s?s.split(",").map(i=>i.trim()):[],Pt=s=>s?s.join(","):"";var Be="blocks",ze="0.33.2";function Qs(s){return Ni({...s,libraryName:Be,libraryVersion:ze})}var tr=({type:s,message:i,...t})=>({type:s,message:i,...t}),Lt=tr,Ve=tr;var er=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},je=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>er(i)).join("/-/"),R=(...s)=>{let i=je(...s);return i?`-/${i}/`:""};function ir(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function sr(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function rr(s){let i=nr(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>er(n))}function nr(s){let i=new URL(s),t=ir(s),e=or(t)?lr(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function or(s){return s.startsWith("http")}function lr(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var O=(s,i,t)=>{let e=new URL(nr(s));if(t=t||ir(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),or(t)){let r=lr(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},Ct=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var M=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var ie=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Xi=s=>s?s.filter(i=>typeof i=="string").map(i=>M(i)).flat():[],qi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ar=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),se=s=>{let i=s==null?void 0:s.type;return i?qi(i,ie):!1};var it=1e3,Ut=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),re=s=>Math.ceil(s*100)/100,cr=(s,i=Ut.AUTO)=>{let t=i===Ut.AUTO;if(i===Ut.BYTE||t&&s(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(hr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(Lo+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(hr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Ge=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Yt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__subsMap=Object.create(null),this.__propertyObservers=new Set,this.__collectionObservers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(t).length!==0&&(this.__propertyObservers.forEach(n=>{n({...t})}),t=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(let e of this.__collectionObservers)e==null||e([...this.__items],i,t)})}observeCollection(i){return this.__collectionObservers.add(i),this.__items.size>0&&this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var t;(t=this.__collectionObservers)==null||t.delete(i)}add(i){let t=new He(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__items.add(t.uid),this.notify(),this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),t.uid}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observeProperties(i){return this.__propertyObservers.add(i),()=>{this.unobserveProperties(i)}}unobserveProperties(i){var t;(t=this.__propertyObservers)==null||t.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var ur=s=>{let i=new Map;return(...t)=>{let e=JSON.stringify(t);if(i.has(e))return i.get(e);let r=s(...t);return i.set(e,r),r}};function Uo(s){let i=!1;return setTimeout(()=>{i=!0},0),e=>(...r)=>(i&&It(s),e(...r))}function dr(s){let i={progress:()=>s.$["*commonProgress"],errors:()=>s.$["*collectionErrors"],group:()=>s.$["*groupInfo"],totalCount:()=>s.uploadCollection.size,failedCount:()=>t.failedEntries.length,successCount:()=>t.successEntries.length,uploadingCount:()=>t.uploadingEntries.length,status:()=>t.isFailed?"failed":t.isUploading?"uploading":t.isSuccess?"success":"idle",isSuccess:()=>t.errors.length===0&&t.successEntries.length===t.allEntries.length,isUploading:()=>t.allEntries.some(r=>r.status==="uploading"),isFailed:()=>t.errors.length>0||t.failedEntries.length>0,allEntries:()=>s.getOutputData(),successEntries:()=>t.allEntries.filter(r=>r.status==="success"),failedEntries:()=>t.allEntries.filter(r=>r.status==="failed"),uploadingEntries:()=>t.allEntries.filter(r=>r.status==="uploading"),idleEntries:()=>t.allEntries.filter(r=>r.status==="idle")},t={},e=Uo("You're trying to access the OutputCollectionState asynchronously. In this case, the data you retrieve will be newer than it was when the OutputCollectionState was created or when the event was dispatched. If you want to retain the state at a specific moment in time, you should use the spread operator like this: `{...outputCollectionState}` or `{...e.detail}`");for(let[r,n]of Object.entries(i)){let o=r,a=ur(e(n));Object.defineProperty(t,o,{get:a,enumerable:!0})}return t}var pr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:dt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silent:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0},metadata:{type:Object,value:null,nullable:!0},errors:{type:Array,value:[]},uploadError:{type:Error,value:null,nullable:!0},isRemoved:{type:Boolean,value:!1}});var We=(s,i)=>{let t,e,r,n=(...o)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...o),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...o),r=Date.now(),t=!0)};return Object.defineProperty(n,"cancel",{configurable:!1,writable:!1,enumerable:!1,value:()=>{clearTimeout(e)}}),n};var T=class s extends g{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!1);h(this,"isCtxOwner",!1);h(this,"init$",Ne(this));h(this,"__initialUploadMetadata",null);h(this,"_fileValidators",[this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this),this._validateUploadError.bind(this)]);h(this,"_collectionValidators",[t=>{let e=t.size,r=this.cfg.multiple?this.cfg.multipleMin:0,n=this.cfg.multiple?this.cfg.multipleMax:1;if(r&&en){let o=this.l10n("files-count-limit-error-too-many",{min:r,max:n,total:e});return Ve({type:"TOO_MANY_FILES",message:o,total:e,min:r,max:n})}},t=>{if(t.items().some(e=>t.readProp(e,"errors").length>0))return Ve({type:"SOME_FILES_HAS_ERRORS",message:this.l10n("some-files-were-not-uploaded")})}]);h(this,"uploadAll",()=>{let t=this.uploadCollection.items().filter(e=>{let r=this.uploadCollection.read(e);return!r.getValue("isRemoved")&&!r.getValue("isUploading")&&!r.getValue("fileInfo")});t.length!==0&&(this.$["*uploadTrigger"]=new Set(t),this.emit($.COMMON_UPLOAD_START,this.getOutputCollectionState()))});h(this,"_flushOutputItems",k(async()=>{if(this.getOutputData().length!==this.uploadCollection.size)return;let e=this.getOutputCollectionState();this.$["*collectionState"]=e,this.emit($.CHANGE,()=>this.getOutputCollectionState(),{debounce:!0}),this.cfg.groupOutput&&e.totalCount>0&&e.status==="success"&&this._createGroup(e)},300));h(this,"_handleCollectionUpdate",(t,e,r)=>{var n;(e.size||r.size)&&(this.$["*groupInfo"]=null),this._runFileValidators(),this._runCollectionValidators();for(let o of e)o.getValue("silent")||this.emit($.FILE_ADDED,this.getOutputItem(o.uid));for(let o of r)this.$["*uploadTrigger"].delete(o.uid),(n=o.getValue("abortController"))==null||n.abort(),o.setMultipleValues({isRemoved:!0,abortController:null,isUploading:!1,uploadProgress:0}),URL.revokeObjectURL(o==null?void 0:o.getValue("thumbUrl")),this.emit($.FILE_REMOVED,this.getOutputItem(o.uid));this.$["*uploadList"]=t.map(o=>({uid:o})),this._flushCommonUploadProgress(),this._flushOutputItems()});h(this,"_handleCollectionPropertiesUpdate",t=>{this._flushOutputItems();let e=this.uploadCollection,r=[...new Set(Object.entries(t).filter(([n])=>["uploadError","fileInfo"].includes(n)).map(([,n])=>[...n]).flat())];if(r.length>0&&setTimeout(()=>{this._runFileValidators(r)}),t.uploadProgress){for(let n of t.uploadProgress){let{isUploading:o,silent:l}=E.getCtx(n).store;o&&!l&&this.emit($.FILE_UPLOAD_PROGRESS,this.getOutputItem(n))}this._flushCommonUploadProgress()}if(t.isUploading)for(let n of t.isUploading){let{isUploading:o,silent:l}=E.getCtx(n).store;o&&!l&&this.emit($.FILE_UPLOAD_START,this.getOutputItem(n))}if(t.fileInfo){for(let l of t.fileInfo){let{fileInfo:a,silent:c}=E.getCtx(l).store;a&&!c&&this.emit($.FILE_UPLOAD_SUCCESS,this.getOutputItem(l))}this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo"));e.findItems(l=>l.getValue("errors").length>0).length===0&&e.size===n.length&&this.emit($.COMMON_UPLOAD_SUCCESS,this.getOutputCollectionState())}if(t.errors)for(let n of t.errors){let{errors:o}=E.getCtx(n).store;o.length>0&&(this.emit($.FILE_UPLOAD_FAILED,this.getOutputItem(n)),this.emit($.COMMON_UPLOAD_FAILED,()=>this.getOutputCollectionState(),{debounce:!0}))}t.cdnUrl&&([...t.cdnUrl].filter(o=>{var l;return!!((l=this.uploadCollection.read(o))!=null&&l.getValue("cdnUrl"))}).forEach(o=>{this.emit($.FILE_URL_CHANGED,this.getOutputItem(o))}),this.$["*groupInfo"]=null)});h(this,"_flushCommonUploadProgress",()=>{let t=0,r=[...this.$["*uploadTrigger"]].filter(o=>!!this.uploadCollection.read(o));r.forEach(o=>{let l=this.uploadCollection.readProp(o,"uploadProgress");t+=l});let n=r.length?Math.round(t/r.length):0;this.$["*commonProgress"]!==n&&(this.$["*commonProgress"]=n,this.emit($.COMMON_UPLOAD_PROGRESS,this.getOutputCollectionState()))})}setUploadMetadata(t){It("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}get hasCtxOwner(){return this.hasBlockInCtx(t=>t instanceof s?t.isCtxOwner&&t.isConnected&&t!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let t=new Ge({typedSchema:pr,watchList:["uploadProgress","uploadError","fileInfo","errors","cdnUrl","isUploading"]});this.$["*uploadCollection"]=t}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCtxCallback(){var t,e;(t=this._unobserveCollectionProperties)==null||t.call(this),(e=this._unobserveCollection)==null||e.call(this),this.uploadCollection.destroy(),this.$["*uploadCollection"]=null,super.destroyCtxCallback()}initCtxOwner(){this.isCtxOwner=!0,this._unobserveCollection=this.uploadCollection.observeCollection(this._handleCollectionUpdate),this._unobserveCollectionProperties=this.uploadCollection.observeProperties(this._handleCollectionPropertiesUpdate);let t=()=>{this._runFileValidators(),this._runCollectionValidators()};this.subConfigValue("maxLocalFileSizeBytes",t),this.subConfigValue("multipleMin",t),this.subConfigValue("multipleMax",t),this.subConfigValue("multiple",t),this.subConfigValue("imgOnly",t),this.subConfigValue("accept",t),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){let o=this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silent:e!=null?e:!1,source:n!=null?n:Y.API});return this.getOutputItem(o)}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){let o=this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silent:e!=null?e:!1,source:n!=null?n:Y.API});return this.getOutputItem(o)}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){let l=this.uploadCollection.add({file:t,isImage:se(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silent:e!=null?e:!1,source:n!=null?n:Y.API,fullPath:o!=null?o:null});return this.getOutputItem(l)}addFiles(t){return console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.map(e=>{let r=this.uploadCollection.add({file:e,isImage:se(e),mimeType:e.type,fileName:e.name,fileSize:e.size});return this.getOutputItem(r)})}openSystemDialog(t={}){var r;let e=Pt(Xi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?ie:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Pt(ie)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:Y.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=M(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(s.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Xi([...e?ie:[],r]);if(!n.length)return;let o=t.mimeType,l=t.name;if(!o||!l)return;let a=qi(o,n),c=ar(l,n);if(!a&&!c)return Lt({type:"FORBIDDEN_FILE_TYPE",message:this.l10n("file-type-not-allowed"),entry:t})}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.size;if(e&&r&&r>e)return Lt({type:"FILE_SIZE_EXCEEDED",message:this.l10n("files-max-size-limit-error",{maxFileSize:cr(e)}),entry:t})}_validateUploadError(t,e){let r=e==null?void 0:e.getValue("uploadError");if(r){if(r instanceof D)return Lt({type:"UPLOAD_ERROR",message:r.message,entry:t,error:r});if(r instanceof Ft)return Lt({type:"NETWORK_ERROR",message:r.message,entry:t,error:r});{let n=r instanceof Error?r:new Error("Unknown error",{cause:r});return Lt({type:"UNKNOWN_ERROR",message:n.message,entry:t,error:n})}}}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.isImage;if(!(!e||r)&&!(!t.fileInfo&&t.externalUrl)&&!(!t.fileInfo&&!t.mimeType))return Lt({type:"NOT_AN_IMAGE",message:this.l10n("images-only-accepted"),entry:t})}_runFileValidatorsForEntry(t){let e=this.getOutputItem(t.uid),r=[];for(let n of this._fileValidators){let o=n(e,t);o&&r.push(o)}t.setValue("errors",r)}_runFileValidators(t){let e=t!=null?t:this.uploadCollection.items();for(let r of e){let n=this.uploadCollection.read(r);n&&this._runFileValidatorsForEntry(n)}}_runCollectionValidators(){let t=this.uploadCollection,e=[];for(let r of this._collectionValidators){let n=r(t);n&&(Array.isArray(n)?e.push(...n):e.push(n))}this.$["*collectionErrors"]=e,e.length>0&&this.emit($.COMMON_UPLOAD_FAILED,()=>this.getOutputCollectionState(),{debounce:!0})}async _createGroup(t){let e=this.getUploadClientOptions(),r=t.allEntries.map(a=>a.uuid+(a.cdnUrlModifiers?`/${a.cdnUrlModifiers}`:"")),n=new AbortController,o=await Fs(r,{...e,signal:n.signal});if(this.$["*collectionState"]!==t){n.abort();return}this.$["*groupInfo"]=o;let l=this.getOutputCollectionState();this.emit($.GROUP_CREATED,l),this.emit($.CHANGE,()=>this.getOutputCollectionState(),{debounce:!0}),this.$["*collectionState"]=l}setInitialCrop(){let t=Fe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Js(l,a,c),d=R(`crop/${u.width}x${u.height}/${u.x},${u.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:O(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(t){var r;let e=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];if(typeof e=="function"){let n=this.getOutputItem(t);return await e(n)}return e}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Qs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads}}getOutputItem(t){var l,a,c,u,d,p,m,f,_,b;let e=E.getCtx(t).store,r=e.fileInfo,n=e.isRemoved?"removed":e.errors.length>0?"failed":e.fileInfo?"success":e.isUploading?"uploading":"idle";return{uuid:(a=(l=r==null?void 0:r.uuid)!=null?l:e.uuid)!=null?a:null,internalId:t,name:(c=r==null?void 0:r.originalFilename)!=null?c:e.fileName,size:(u=r==null?void 0:r.size)!=null?u:e.fileSize,isImage:(d=r==null?void 0:r.isImage)!=null?d:e.isImage,mimeType:(p=r==null?void 0:r.mimeType)!=null?p:e.mimeType,file:e.file,externalUrl:e.externalUrl,cdnUrlModifiers:e.cdnUrlModifiers,cdnUrl:(f=(m=e.cdnUrl)!=null?m:r==null?void 0:r.cdnUrl)!=null?f:null,fullPath:e.fullPath,uploadProgress:e.uploadProgress,fileInfo:r!=null?r:null,metadata:(b=(_=e.metadata)!=null?_:r==null?void 0:r.metadata)!=null?b:null,isSuccess:n==="success",isUploading:n==="uploading",isFailed:n==="failed",isRemoved:n==="removed",errors:e.errors,status:n}}getOutputData(t){return(t?this.uploadCollection.findItems(t):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}getOutputCollectionState(){return dr(this)}};T.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});T.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...T.extSrcList});var X=Object.freeze({brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0,mirror:!1,flip:!1,crop:void 0}),mr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function Ro(s,i){if(typeof i=="number"){let t=i;return X[s]!==t?`${s}/${t}`:""}if(typeof i=="boolean"){let t=i;return X[s]!==t?`${s}`:""}if(s==="filter"&&i){let{name:t,amount:e}=i;return X.filter===e?"":`${s}/${t}/${e}`}if(s==="crop"&&i){let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}function wt(s){return je(...mr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return Ro(i,t)}).filter(i=>!!i))}var Xe=je("format/auto","progressive/yes"),ft=([s])=>typeof s!="undefined"?Number(s):void 0,fr=()=>!0,Mo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),No=([s,i])=>{if(!/\d+x\d+/.test(s)||!/\d+,\d+/.test(i))throw new Error("Crop by aspect ratio, percentage or alignment shortcuts is not supported.");return{dimensions:M(s,"x").map(Number),coords:M(i).map(Number)}},Do=Object.freeze({enhance:ft,brightness:ft,exposure:ft,gamma:ft,contrast:ft,saturation:ft,vibrance:ft,warmth:ft,filter:Mo,mirror:fr,flip:fr,rotate:ft,crop:No});function gr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!mr.includes(e))continue;let n=e,o=Do[n];try{let l=o(r);i[n]=l}catch(l){console.warn([`Failed to parse URL operation "${t}". It will be ignored.`,l instanceof Error?`Error message: "${l.message}"`:l,"If you need this functionality, please feel free to open an issue at https://github.com/uploadcare/blocks/issues/new"].join(` `))}}return i}var P=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),G=[P.CROP,P.TUNING,P.FILTERS],_r=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],br=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],yr=["rotate","mirror","flip"],st=Object.freeze({brightness:{zero:X.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:X.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:X.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:X.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:X.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:X.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:X.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:X.enhance,range:[0,100],keypointsNumber:1},filter:{zero:X.filter,range:[0,100],keypointsNumber:1}});var Fo="https://ucarecdn.com",Bo="https://upload.uploadcare.com",zo="https://social.uploadcare.com",At={pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Pt(G),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Fo,baseUrl:Bo,socialBaseUrl:zo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",debug:!1,metadata:null};var B=s=>String(s),rt=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},I=s=>{if(typeof s=="undefined"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},Vo=s=>s==="auto"?s:I(s),jo={pubkey:B,multiple:I,multipleMin:rt,multipleMax:rt,confirmUpload:I,imgOnly:I,accept:B,externalSourcesPreferredTypes:B,store:Vo,cameraMirror:I,sourceList:B,maxLocalFileSizeBytes:rt,thumbSize:rt,showEmptyList:I,useLocalImageEditor:I,useCloudImageEditor:I,cloudImageEditorTabs:B,removeCopyright:I,cropPreset:B,imageShrink:B,modalScrollLock:I,modalBackdropStrokes:I,sourceListWrap:I,remoteTabSessionKey:B,cdnCname:B,baseUrl:B,socialBaseUrl:B,secureSignature:B,secureExpire:B,secureDeliveryProxy:B,retryThrottledRequestMaxTimes:rt,multipartMinFileSize:rt,multipartChunkSize:rt,maxConcurrentRequests:rt,multipartMaxConcurrentRequests:rt,multipartMaxAttempts:rt,checkForUrlDuplicates:I,saveUrlForRecurrentUploads:I,groupOutput:I,userAgentIntegration:B,debug:I},vr=(s,i)=>{if(!(typeof i=="undefined"||i===null))try{return jo[s](i)}catch(t){return console.error(`Invalid value for config key "${s}".`,t),At[s]}};var ne=Object.keys(At),Ho=["metadata"],Go=s=>Ho.includes(s),qe=ne.filter(s=>!Go(s)),Wo={...Object.fromEntries(qe.map(s=>[ht(s),s])),...Object.fromEntries(qe.map(s=>[s.toLowerCase(),s]))},Xo={...Object.fromEntries(ne.map(s=>[ht(s),F(s)])),...Object.fromEntries(ne.map(s=>[s.toLowerCase(),F(s)]))},Ke=class extends w{constructor(){super();h(this,"requireCtxName",!0);h(this,"_debugPrint",k(()=>{let t=Object.create(null);for(let e of ne)t[e]=this.$[F(e)];this.debugPrint("config",t)},0));this.init$={...this.init$,...Object.fromEntries(Object.entries(At).map(([t,e])=>[F(t),e]))}}initCallback(){super.initCallback();let t=this;for(let e of qe)this.sub(F(e),r=>{r!==At[e]&&(t[e]=r)},!1);for(let e of ne){let r="__"+e;t[r]=t[e],Object.defineProperty(this,e,{set:n=>{if(t[r]=n,qe.includes(e)){let o=[...new Set([ht(e),e.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[F(e)]!==n&&(typeof n=="undefined"||n===null?this.$[F(e)]=At[e]:this.$[F(e)]=n)},get:()=>this.$[F(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Wo[t],o=vr(n,r),l=o!=null?o:At[n],a=this;a[n]=l}};Ke.bindAttributes(Xo);var qo=Ke;var oe=class extends w{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};oe.template=``;oe.bindAttributes({name:"name",size:"size"});var Cr=s=>[...new Set(s)];var wr=s=>Object.entries(s).filter(([i,t])=>t!==void 0&&t!=="").map(([i,t])=>i==="cdn-operations"||i==="analytics"?t:`${i}/${t}`);var Ko="https://ucarecdn.com",le=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Ko},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{},"cdn-operations":{},progressive:{},quality:{},"is-background-for":{},"is-preview-blur":{default:1}});var Gt="--lr-img-",Ki="unresolved";var Yi=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),Ji=3e3,Zi=5e3,Qi=Object.freeze({PREVIEW:"PREVIEW",MAIN:"MAIN"});var Er=Object.create(null),Ar;for(let s in le)Er[Gt+s]=((Ar=le[s])==null?void 0:Ar.default)||"";var Ye=class extends Dt{constructor(){super(...arguments);h(this,"cssInit$",Er)}$$(t){return this.$[Gt+t]}set$$(t){for(let e in t)this.$[Gt+e]=t[e]}sub$$(t,e){this.sub(Gt+t,r=>{r===null||r===""||e(r)})}analyticsParams(){return`-/@clib/${Be}/${ze}/lr-img/`}initAttributes(t){[...this.attributes].forEach(e=>{le[e.name]||t.setAttribute(e.name,e.value)})}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),E.deleteCtx(this)}static get observedAttributes(){return Object.keys(le)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[Gt+t]=r})}};var Qe=class extends Ye{constructor(){super(...arguments);h(this,"_img",new Image);h(this,"_imgPreview",new Image)}_fmtAbs(t){return!t.includes("//")&&!Yi&&(t=new URL(t,document.baseURI).href),t}_validateSize(t){if((t==null?void 0:t.trim())!==""){let e=t.match(/\d+/)[0],r=t.match(/[a-zA-Z]+/)[0],n=parseInt(e,10);if(Number(n)>Zi&&this.hasFormatJPG)return Zi+r;if(Number(n)>Ji&&!this.hasFormatJPG)return Ji+r}return t}_getCdnModifiers(t,e){let r={format:this.$$("format"),quality:this.$$("quality"),resize:this._validateSize(t),blur:e,"cdn-operations":this.$$("cdn-operations"),analytics:this.analyticsParams()};return R(...wr(r))}_getUrlBase(t="",e=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(Yi&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let r=this._getCdnModifiers(t,e);if(this.$$("src").startsWith(this.$$("cdn-cname")))return O(this.$$("src"),r);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(O(Ct(this.$$("cdn-cname"),this.$$("uuid")),r));if(this.$$("uuid"))return this._proxyUrl(O(Ct(this.$$("cdn-cname"),this.$$("uuid")),r));if(this.$$("proxy-cname"))return this._proxyUrl(O(this.$$("proxy-cname"),r,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(O(`https://${this.$$("pubkey")}.ucr.io/`,r,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Zt(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this.hasPreviewImage||(this._setupConfigForImage({elNode:this._img}),this.appendChild(this._img)),this._img}get currentImg(){return this.hasPreviewImage?{type:Qi.PREVIEW,img:this._imgPreview}:{type:Qi.MAIN,img:this.img}}get hasPreviewImage(){return this.$$("is-preview-blur")}get bgSelector(){return this.$$("is-background-for")}get breakpoints(){if(this.$$("breakpoints")){let t=M(this.$$("breakpoints"));return Cr(t.map(e=>parseInt(e,10)))}else return null}get hasFormatJPG(){return this.$$("format").toLowerCase()==="jpeg"}renderBg(t){let e=new Set;e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,2))}") ${2}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,3))}") ${3}x`);let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${this._validateSize(e+"w")}`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*2+"x")+` ${this._validateSize(e*2+"w")}`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*3+"x")+` ${this._validateSize(e*3+"w")}`)}):(t.add(this._getUrlBase(this._getElSize(this.currentImg.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.currentImg.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.currentImg.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}get srcUrlPreview(){return this._getUrlBase("100x","100")}renderBackground(){[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)})}_appendURL({elNode:t,src:e,srcset:r}){e&&(t.src=e),r&&(t.srcset=r)}_setupConfigForImage({elNode:t}){this._setupEventProxy(t),this.initAttributes(t)}loaderImage({src:t,srcset:e,elNode:r}){return new Promise((n,o)=>{this._setupConfigForImage({elNode:r}),r.setAttribute(Ki,""),r.addEventListener("load",()=>{r.removeAttribute(Ki),n(r)}),r.addEventListener("error",()=>{o(!1)}),this._appendURL({elNode:r,src:t,srcset:e})})}async renderImage(){var t,e;if(this.$$("intersection")){this.hasPreviewImage&&(this._setupConfigForImage({elNode:this._imgPreview}),this.appendChild(this._imgPreview)),this.initIntersection(this.currentImg.img,async()=>{var r;this.hasPreviewImage&&(this._imgPreview.src=this.srcUrlPreview);try{await this.loaderImage({src:this.getSrc(),srcset:this.getSrcset(),elNode:this._img}),this.hasPreviewImage&&await this._imgPreview.remove(),this.appendChild(this._img)}catch{this.hasPreviewImage&&await((r=this._imgPreview)==null?void 0:r.remove()),this.appendChild(this._img)}});return}try{this.hasPreviewImage&&(await this.loaderImage({src:this.srcUrlPreview,elNode:this._imgPreview}),this.appendChild(this._imgPreview)),await this.loaderImage({src:this.getSrc(),srcset:this.getSrcset(),elNode:this._img}),this.hasPreviewImage&&await((t=this._imgPreview)==null?void 0:t.remove()),this.appendChild(this._img)}catch{this.hasPreviewImage&&await((e=this._imgPreview)==null?void 0:e.remove()),this.appendChild(this._img)}}init(){this.bgSelector?this.renderBackground():this.renderImage()}};var ts=class extends Qe{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{!this.$$("is-background-for")&&!this.$$("is-preview-blur")&&(this.img.loading=i?"lazy":"eager")})}};var ae=class extends T{constructor(){super();h(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",t=>{typeof t!="undefined"&&(this.$.withDropZone=I(t))}),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};ae.template=``;ae.bindAttributes({dropzone:null});var ti=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};ti.template='
';function Yo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function Jo(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function xr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Yo(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},Tr=["focus"],Zo=100,es=new Map;function Qo(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function is(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=z.INACTIVE,o=f=>{s.shouldIgnore()&&f!==z.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(z.INACTIVE)},c=()=>{i+=1,n===z.INACTIVE&&o(z.ACTIVE)},u=()=>{i-=1,l()||o(z.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(z.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let _=[f.x,f.y],b=s.element.getBoundingClientRect(),x=Math.floor(Qo(_,b)),v=x{if(s.shouldIgnore())return;f.preventDefault();let _=await xr(f.dataTransfer);s.onItems(_),o(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),Tr.forEach(f=>{window.addEventListener(f,a)}),()=>{es.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),Tr.forEach(f=>{window.removeEventListener(f,a)})}}var Sr="lr-drop-area",Wt=`${Sr}/registry`,ce=class extends T{constructor(){super(),this.init$={...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[Wt]:null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$[Wt]||(this.$[Wt]=new Set),this.$[Wt].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!I(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:I(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:I(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:I(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=is({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:Y.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:Y.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=is({element:i,onChange:t=>{var r;let e=(r=Object.entries(z).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(z).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=M(t);this.$.isEnabled=e.includes(T.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.sub("isClickable",t=>{this.toggleAttribute("clickable",t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[Wt]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var t,e;super.destroyCallback();let i=this.$[Wt];i&&(i.delete(this),i.size===0&&E.deleteCtx(Sr)),(t=this._destroyDropzone)==null||t.call(this),(e=this._destroyContentWrapperDropzone)==null||e.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ce.template=`
{{text}}
`;ce.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var tl="src-type-",he=class extends T{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:T.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:T.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:T.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(T.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${tl}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};he.template=`
`;he.bindAttributes({type:null});var ss=class extends w{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=M(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};var el=[1,3],il=[192,193,194,195,197,198,199,201,202,203,205,206,207],$r={squareSide:[Math.floor(Math.sqrt(5*1e3*1e3)),4096,8192,11180,10836,11402,14188,16384],dimension:[4096,8192,16384,32767,65535]},Ir=(s,i)=>{let t={};return(...e)=>{let r=i(e,t);return r in t?t[r]:t[r]=s(...e)}},kr=(s,i)=>{let[t]=s,e=Object.keys(i).map(r=>parseInt(r,10)).sort((r,n)=>r-n);for(let r=0;rt&&o||n{let s=document.createElement("canvas"),i=s.getContext("2d");return{canvas:s,ctx:i}},Et={R:55,G:110,B:165,A:255},sl=`rgba(${Et.R}, ${Et.G}, ${Et.B}, ${Et.A/255})`,Or=(s,i)=>{try{let t=[s-1,i-1,1,1],{canvas:e,ctx:r}=ue();e.width=1,e.height=1;let{canvas:n,ctx:o}=ue();n.width=s,n.height=i,o&&(o.fillStyle=sl,o.fillRect(...t),r.drawImage(n,s-1,i-1,1,1,0,0,1,1));let l=r&&r.getImageData(0,0,1,1).data,a=!1;return l&&(a=l[0]===Et.R&&l[1]===Et.G&&l[2]===Et.B&&l[3]===Et.A),n.width=n.height=1,a}catch{return console.error(`Failed to test for max canvas size of ${s}x${i}.`),!1}};function Pr(s){return(...i)=>new Promise(t=>{setTimeout(()=>{let e=s(...i);t(e)},0)})}var rl=Pr(Ir(Or,kr)),nl=Pr(Ir(Or,kr)),Lr=(s,i)=>new Promise((t,e)=>{let r=$r.squareSide.find(o=>o*o>=s*i),n=$r.dimension.find(o=>o>=s&&o>=i);if(!r||!n){e();return}Promise.all([rl(r,r),nl(n,1)]).then(([o,l])=>{o&&l?t(!0):e()})}),Ur=(s,i,t)=>new Promise((e,r)=>{try{let{ctx:n,canvas:o}=ue();o.width=i,o.height=t,n.imageSmoothingQuality="high",n.drawImage(s,0,0,i,t),s.src="//:0",s.width=s.height=1,e(o)}catch(n){r(`Failed to resize image. ${n}`)}}),ol=({img:s,targetW:i,targetH:t})=>Ur(s,i,t),ll=function(s,i,t,e){let r=[],n=i,o=t;do r.push([n,o]),n=Math.round(n/e),o=Math.round(o/e);while(nll(i,t,e,r).reduce((o,[l,a])=>o.then(c=>Lr(l,a).then(()=>c).catch(()=>Ur(c,l,a))).then(c=>{let u=(i-l)/(i-t);return{canvas:c,progress:u}}),Promise.resolve(s)).then(({canvas:o})=>o).catch(o=>Promise.reject(o)),cl=()=>/iPad|iPhone|iPod/.test(navigator.platform)?!0:navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&/MacIntel/.test(navigator.platform),hl=navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&/MacIntel/.test(navigator.platform),rs=.71,ul=(s,i)=>new Promise((t,e)=>{s.width*rs*s.height*rs{let{ctx:c}=ue();return"imageSmoothingQuality"in c&&!cl()&&!hl?ol({img:s,targetW:l,targetH:a}):al({img:s,sourceW:r,targetW:l,targetH:a,step:rs})}).then(c=>t(c)).catch(()=>e("Not supported"))}),ii=()=>{let s=[];return{stack:s,promiseReadJpegChunks:t=>new Promise((e,r)=>{let n,o=(c,u)=>{let d=new FileReader;d.addEventListener("load",()=>{u(new DataView(d.result))}),d.addEventListener("error",p=>{r(`Reader error: ${p}`)}),d.readAsArrayBuffer(c)},l=()=>o(t.slice(n,n+128),c=>{let u,d,p;for(u=d=0,p=c.byteLength;p>=0?dp;u=p>=0?++d:--d)if(c.getUint8(u)===255){n+=u;break}return a()}),a=()=>{let c=n;return o(t.slice(n,n+=4),u=>{if(u.byteLength!==4||u.getUint8(0)!==255)return r("Corrupted");let d=u==null?void 0:u.getUint8(1);if(d===218)return e(!0);let p=u.getUint16(2)-2;return o(t.slice(n,n+=p),m=>m.byteLength!==p?r("Corrupted"):(s.push({startPos:c,length:p,marker:d,view:m}),l()))})};FileReader&&DataView||r("Not Support"),n=2,o(t.slice(0,2),function(c){return c.getUint16(0)!==65496&&r("Not jpeg"),l()})})}},Rr=(s,i,t)=>new Promise((e,r)=>{let n=[],o=[],{promiseReadJpegChunks:l,stack:a}=ii();return l(s).then(()=>{a.forEach(c=>{if(c.marker===i)return n.push(c.startPos),o.push(c.length)})}).then(()=>{let c=[s.slice(0,2)];for(let d of t){let p=new DataView(new ArrayBuffer(4));p.setUint16(0,65280+i),p.setUint16(2,d.byteLength+2),c.push(p.buffer),c.push(d)}let u=2;for(let d=0;du&&c.push(s.slice(u,n[d])),u=n[d]+o[d]+4;c.push(s.slice(u,s.size)),e(new Blob(c,{type:s.type}))}).catch(()=>r(s))}).catch(()=>s),dl=226,Mr=(s,i)=>Rr(s,dl,i.map(t=>t.buffer)),pl=(s,i)=>new Promise((t,e)=>{i&&(s.src=i),s.complete?t(s):(s.addEventListener("load",()=>{t(s)}),s.addEventListener("error",()=>{e(s)}))}),fl=s=>pl(new Image,s),ml=async s=>{try{let i=await Mr(s,[]),t=await fl(URL.createObjectURL(i));return URL.revokeObjectURL(t.src),t}catch(i){throw new Error(`Failed to strip ICC profile and not image ${i}`)}},gl=async s=>{let i=!1,{promiseReadJpegChunks:t,stack:e}=ii();return await t(s).then(()=>(e.forEach(({marker:r,view:n})=>{if(!i&&il.indexOf(r)>=0){let o=n.getUint8(5);el.indexOf(o)<0&&(i=!0)}}),i)).catch(()=>i)},_l=(s,i,t,e)=>s.toBlob(e,i,t),bl=s=>{let{ctx:t,canvas:e}=ue();e.width=e.height=50,t.drawImage(s,0,0,50,50);let r=t.getImageData(0,0,50,50).data;e.width=e.height=1;for(let n=3;n{ei=i.naturalWidth{let i=null,{promiseReadJpegChunks:t,stack:e}=ii();return t(s).then(()=>{e.forEach(({marker:r,view:n})=>(!i&&r===225&&n.byteLength>=14&&n.getUint32(0)===1165519206&&n.getUint16(4)===0&&(i=n),i))}).catch(()=>i)},wl=async s=>{let i=[],{promiseReadJpegChunks:t,stack:e}=ii();return await t(s).then(()=>(e.forEach(({marker:r,view:n})=>{r===226&&n.getUint32(0)===1229144927&&n.getUint32(4)===1347571526&&n.getUint32(8)===1229735168&&i.push(n)}),i)).catch(()=>i)},Al=(s,i)=>{let t,e,r,n;if(!s||s.byteLength<14||s.getUint32(0)!==1165519206||s.getUint16(4)!==0)return null;if(s.getUint16(6)===18761)e=!0;else if(s.getUint16(6)===19789)e=!1;else return null;if(s.getUint16(8,e)!==42)return null;r=8+s.getUint32(10,e);let o=s.getUint16(r-2,e);for(t=0,n=o;n>=0?tn;n>=0?++t:--t){if(s.byteLength{Al(s,(t,e)=>s.setUint16(t,i,e))},xl=async(s,i,t)=>(t&&El(i,1),Rr(s,225,[i.buffer])),Nr=(s,i)=>new Promise(async(t,e)=>{URL&&DataView&&Blob||e("Not support");try{let r=await gl(s).then(o=>{if(o)return e("Should skipped")}).then(()=>ml(s).catch(()=>{e("Failed to strip ICC profile and not image")}));Promise.allSettled([Cl(s),vl(),wl(s)]).then(async o=>{let l=o.some(p=>p.status==="rejected"),[a,c,u]=o,d=!l;return ul(r,i).then(async p=>{let m="image/jpeg",f=(i==null?void 0:i.quality)||.8;!d&&bl(p)&&(m="image/png",f=void 0),_l(p,m,f,_=>{var x;p.width=p.height=1;let b=Promise.resolve(_);a.value&&(b=b.then(v=>xl(v,a.value,c.value)).catch(()=>_)),((x=u==null?void 0:u.value)==null?void 0:x.length)>0&&(b=b.then(v=>Mr(v,u.value)).catch(()=>_)),b.then(t).catch(()=>t(_))})}).catch(()=>e(s))})}catch(r){e(`Failed to shrink image: ${r}`)}});function Dr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function Fr(s="#fff",i="rgba(0, 0, 0, .1)"){return Dr(``)}function de(s="hsl(209, 21%, 65%)",i=32,t=32){return Dr(``)}function Br(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var Tl=/^([0-9]+)x([0-9]+)(?:\s+(\d{1,2}|100)%)?$/i,zr=s=>{let i=Tl.exec(s==null?void 0:s.toLocaleLowerCase())||[];if(!i.length)return!1;let t=i[1]*i[2],e=16384*16384;return t>e?(console.warn(`Shrinked size can not be larger than ${Math.floor(e/1e3/1e3)}MP. You have set ${i[1]}x${i[2]} (${Math.ceil(t/1e3/100)/10}MP).`),!1):{quality:i[3]?i[3]/100:void 0,size:t}};var J=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3)}),pe=class s extends T{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",k(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",k(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,state:J.IDLE,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=J.IDLE;t.getValue("errors").length>0?e=J.FAILED:t.getValue("isUploading")?e=J.UPLOADING:t.getValue("fileInfo")&&(e=J.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(O(Ct(this.cfg.cdnCname,this._entry.getValue("uuid")),R(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Br(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",de(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",de(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("fileInfo",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("errors",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{s.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.sub("*uploadTrigger",t=>{t.has(this._entry.uid)&&setTimeout(()=>this.isConnected&&this.upload())}),s.activeInstances.add(this)}_handleState(t){var e,r,n,o;this.set$({isFailed:t===J.FAILED,isUploading:t===J.UPLOADING,isFinished:t===J.FINISHED,progressVisible:t===J.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:(o=(n=this._entry.getValue("errors"))==null?void 0:n[0])==null?void 0:o.message}),t===J.FAILED?this.$.badgeIcon="badge-error":t===J.FINISHED&&(this.$.badgeIcon="badge-success"),t===J.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),s.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}_settingsOfShrink(){return zr(this.cfg.imageShrink)}_processShrink(t){return Nr(t,this._settingsOfShrink())}async upload(){var r,n,o;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("errors").length>0)return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(!(e&&this.uploadCollection.size>e)){this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("errors",[]),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let l=new AbortController;t.setValue("abortController",l);let a=async()=>{let u=t.getValue("file");u&&this.cfg.imageShrink&&(u=await this._processShrink(u).catch(()=>u));let d=u||t.getValue("externalUrl")||t.getValue("uuid"),m={...this.getUploadClientOptions(),fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let _=f.value*100;t.setValue("uploadProgress",_)}this.$.progressUnknown=!f.isComputable},signal:l.signal,metadata:await this.getMetadataFor(t.uid)};return this.debugPrint("upload options",d,m),Vi(d,m)},c=await this.$["*uploadQueue"].add(a);t.setMultipleValues({fileInfo:c,isUploading:!1,fileName:c.originalFilename,fileSize:c.size,isImage:c.isImage,mimeType:(o=(n=(r=c.contentInfo)==null?void 0:r.mime)==null?void 0:n.mime)!=null?o:c.mimeType,uuid:c.uuid,cdnUrl:c.cdnUrl,cdnUrlModifiers:"",uploadProgress:100}),t===this._entry&&this._debouncedCalculateState()}catch(l){l instanceof _t&&l.isCancel?t.setMultipleValues({isUploading:!1,uploadProgress:0}):t.setMultipleValues({isUploading:!1,uploadProgress:0,uploadError:l}),t===this._entry&&this._debouncedCalculateState()}}}};pe.template=`
{{itemName}}{{errorText}}
`;pe.activeInstances=new Set;var fe=class extends w{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogMouseDown",t=>{this._mouseDownTarget=t.target});h(this,"_handleDialogMouseUp",t=>{t.target===this.ref.dialog&&t.target===this._mouseDownTarget&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.addEventListener("mouseup",this._handleDialogMouseUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this._mouseDownTarget=void 0,this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("mousedown",this._handleDialogMouseDown),this.ref.dialog.removeEventListener("mouseup",this._handleDialogMouseUp)}};h(fe,"StateConsumerScope","modal");fe.template=``;var si=class extends T{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_throttledHandleCollectionUpdate",We(()=>{this.isConnected&&(this._updateUploadsState(),!this.couldOpenActivity&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},300));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",commonErrorMessage:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.emit($.UPLOAD_CLICK),this.uploadAll(),this._throttledHandleCollectionUpdate()},onDone:()=>{this.emit($.DONE_CLICK,this.getOutputCollectionState()),this.doneFlow()},onCancel:()=>{this.uploadCollection.clearAll()}}}_updateUploadsState(){let t=this.getOutputCollectionState(),e={total:t.totalCount,succeed:t.successCount,uploading:t.uploadingCount,failed:t.failedCount},r=!t.errors.some(p=>p.type==="TOO_MANY_FILES"||p.type==="TOO_FEW_FILES"),n=t.errors.some(p=>p.type==="TOO_MANY_FILES"),o=t.totalCount===(this.cfg.multiple?this.cfg.multipleMax:1),l=e.failed===0,a=!1,c=!1,u=!1;e.total-e.succeed-e.uploading-e.failed>0&&r?a=!0:(c=!0,u=e.total===e.succeed&&r&&l),this.set$({doneBtnVisible:c,doneBtnEnabled:u,uploadBtnVisible:a,addMoreBtnEnabled:e.total===0||!n&&!o,addMoreBtnVisible:!o||this.cfg.multiple,headerText:this._getHeaderText(e)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}get couldOpenActivity(){return this.cfg.showEmptyList||this.uploadCollection.size>0}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._throttledHandleCollectionUpdate),this.subConfigValue("multipleMin",this._throttledHandleCollectionUpdate),this.subConfigValue("multipleMax",this._throttledHandleCollectionUpdate),this.sub("*currentActivity",t=>{!this.couldOpenActivity&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._throttledHandleCollectionUpdate),this.sub("*uploadList",t=>{this._throttledHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.uploadAll()},!1),this.sub("*collectionErrors",t=>{let e=t.filter(r=>r.type!=="SOME_FILES_HAS_ERRORS")[0];if(!e){this.set$({commonErrorMessage:null});return}this.set$({commonErrorMessage:e.message})})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._throttledHandleCollectionUpdate)}};si.template=`{{headerText}}
`;var ri=class extends T{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:Y.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};ri.template=`
`;var ns=()=>typeof navigator.permissions!="undefined";var ni=class extends T{constructor(){super(...arguments);h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:ns(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{ns()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",k(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:Y.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ni.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var os=class extends T{constructor(){super(...arguments);h(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}},Sl=os;var oi=class extends T{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=de(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=se(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("errors",n=>{var o;this.$.errorTxt=(o=n[0])==null?void 0:o.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=O(n,R("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};oi.template=`
{{fileSize}}
{{errorTxt}}
`;var ls=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},li=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ls);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};li.template=`{{activityCaption}}
{{messageTxt}}
`;var ai=class extends T{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}destroyCallback(){var t;super.destroyCallback(),(t=this._unobserveCollection)==null||t.call(this)}};ai.template=``;var ci=class extends w{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ci.template='
';var q="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var me=class extends w{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:q})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${Fr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=q}};me.template='';me.bindAttributes({checkerboard:"checkerboard"});var Vr="--cfg-ctx-name",L=class extends w{get cfgCssCtxName(){return this.getCssData(Vr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;if(!i)throw new Error(`ctx-name attribute is required for ${this.constructor.name}`);return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(Vr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}get debugCtxName(){return this.cfgCtxName}};function jr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function N(...s){let i=jr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function Hr(s,...i){let t=jr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var Gr=s=>{if(!s)return G;let i=Zs(s).filter(t=>G.includes(t));return i.length===0?G:i};function Wr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":G,"*tabId":P.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:q,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Pt(G),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=q,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=R(wt(i),"preview"),r=O(t,e),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var Xr=`
Network error
{{fileType}}
{{msg}}
`;var nt=class extends L{constructor(){super();h(this,"_debouncedShowLoader",k(this._showLoader.bind(this),300));this.init$={...this.init$,...Wr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.$.cdnUrl){let t=sr(this.$.cdnUrl),e=Ct(this.$.cdnUrl,t);if(e===this.$["*originalUrl"])return;this.$["*originalUrl"]=e;let r=rr(this.$.cdnUrl),n=gr(r);this.$["*editorTransformations"]=n}else if(this.$.uuid){let t=Ct(this.cfg.cdnCname,this.$.uuid);if(t===this.$["*originalUrl"])return;this.$["*originalUrl"]=t,this.$["*editorTransformations"]={}}else throw new Error("No UUID nor CDN URL provided");this.$["*tabId"]===P.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate();try{let t=O(this.$["*originalUrl"],R("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===P.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==q&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||q)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Fe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=Gr(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=N("image",{image_hidden_to_cropper:t===P.CROP,image_hidden_effects:t!==P.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=R(wt(t),"preview"),n=O(e,r),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(nt,"className","cloud-image-editor");nt.template=Xr;nt.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var hi=class extends L{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=K("mask",{id:"backdrop-mask"}),a=K("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=K("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=K("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Ot(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Ot(n,f)}else{let f=vt(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:b}=a?js(i,e,f):Hs(i,e,f),x=Math.max(Wi*vt(Math.min(d,p)/Wi/3,0,1),Vs);Ot(n,{x:b[0]-x,y:b[1]-x,width:x*2,height:x*2}),Ot(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",N("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ot(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=K("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=K("rect",{fill:"transparent"}),l=K("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=K("svg"),t=K("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=K("line",{x1:`${ee*e}%`,y1:"0%",x2:`${ee*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=K("line",{x1:"0%",y1:`${ee*e}%`,x2:"100%",y2:`${ee*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Ws({rect:o,delta:[e,r],imageBox:n}):o=Xs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Vt(Ht(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return qs(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Gs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",N("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",N({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};hi.template='';var mt=class extends L{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=N({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};mt.template=`
{{title}}
`;function Il(s){let i=s+90;return i=i>=360?0:i,i}function kl(s,i){return s==="rotate"?Il(i):["mirror","flip"].includes(s)?!i:null}var ge=class extends mt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=kl(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var _e={FILTER:"filter",COLOR_OPERATION:"color_operation"},ot="original",ui=class extends L{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?_e.FILTER:_e.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ot?void 0:this.$.value,filter:this._filter===ot?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=st[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===_e.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===_e.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===_e.FILTER?this._filter===ot?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ui.template=``;function be(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=q)}}}function ye(s){let i=[];for(let n of s){let o=be(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Xt=class extends mt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ot?{name:this._filter,amount:o}:void 0,O(this._originalUrl,R(Xe,wt(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=be(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ot,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Xt.template=`
`;var ve=class extends mt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=st[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};function qr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function qt(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return O(s,R(Xe,wt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Ol(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var di=class extends L{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=k(this._commit.bind(this),300),this._handleResizeThrottled=We(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=qr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=jt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Ht(l)}_alignCrop(){var d;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[p,m],coords:[f,_]}=n,{width:b}=jt(this._imageSize,r),x=o/b;i=Vt(Ht({x:l+f*x,y:a+_*x,width:p*x,height:m*x}),this.$["*imageBox"])}let c=(d=this.$["*cropPresetList"])==null?void 0:d[0],u=c?c.width/c.height:void 0;if(!Ks(i,t)||u&&!Ys(i,u)){let p=t.width/t.height,m=t.width,f=t.height;u&&(p>u?m=Math.min(t.height*u,t.width):f=Math.min(t.width/u,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Vt(Ht(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=jt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=N({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=jt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[vt(Math.round(c/d),1,l),vt(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=jt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),b={dimensions:_,coords:[vt(Math.round((d-l)/m),0,c-_[0]),vt(Math.round((p-a)/f),0,u-_[1])]};if(!Ol(b)){console.error("Cropper is trying to create invalid crop object",{payload:b});return}if(!(_[0]===c&&_[1]===u))return b}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=N({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(qt(i,e,t)),{promise:n,cancel:o,image:l}=be(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};di.template=``;function as(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Pl(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Ul(s,i){return s.map((t,e)=>tn-o)}var cs=class extends L{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=k(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(qt(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=st[i],r=this._keypoints.map(l=>l.value),n=Ll(r,t,e),o=Ul(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=ye(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Kr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=ye(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Kr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=N({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Rl=1,pi=class extends L{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Rl?this.scrollLeft+=e:this.scrollLeft+=t})}};pi.template=" ";function Ml(s){return``}function Nl(s){return`
`}var fi=class extends L{constructor(){super();h(this,"_updateInfoTooltip",k(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===P.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(ot);else if(this.$["*tabId"]===P.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||st[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ot,"*currentOperation":null,showLoader:!1,filters:br,colorOperations:_r,cropOperations:yr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=k(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===P.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new ve;return e.operation=t,e}_createFilterControl(t){let e=new Xt;return e.filter=t,e}_createToggleControl(t){let e=new ge;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===P.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===P.FILTERS?[ot,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===P.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===P.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of G){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(qt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=ye([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1;for(let e of G){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}t.includes(this.$["*tabId"])||this._activateTab(t[0],{fromViewer:!1})}),this._updateInfoTooltip()}};fi.template=`
{{*operationTooltip}}
${G.map(Nl).join("")}
${G.map(Ml).join("")}
`;var Ce=class extends w{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return N("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Ce.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Ce.template=`
{{text}}
`;var mi=class extends w{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};mi.template=`
`;var gi={transition:"transition",visible:"visible",hidden:"hidden"},_i=class extends w{constructor(){super(),this._visible=!1,this._visibleStyle=gi.visible,this._hiddenStyle=gi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Hr(this,{[gi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(gi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};_i.template=" ";var bi=class extends w{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var hs=class extends T{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);this.init$={...this.init$,cdnUrl:null}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))}),this.subConfigValue("cropPreset",t=>{this._instance&&this._instance.getAttribute("crop-preset")!==t&&this._instance.setAttribute("crop-preset",t)}),this.subConfigValue("cloudImageEditorTabs",t=>{this._instance&&this._instance.getAttribute("tabs")!==t&&this._instance.setAttribute("tabs",t)})}handleApply(t){if(!this.entry)return;let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new nt,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>{let l=o;this.handleApply(l),this.debugPrint('editor event "apply"',l.detail)}),t.addEventListener("cancel",o=>{let l=o;this.handleCancel(),this.debugPrint('editor event "cancel"',l.detail)}),t.addEventListener("change",o=>{let l=o;this.debugPrint('editor event "change"',l.detail)}),this.innerHTML="",this.appendChild(t),this._mounted=!0,this._instance=t}unmountEditor(){this._instance=void 0,this.innerHTML=""}};var Dl=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Yr=function(s,i="i"){let t=s.split("*").map(Dl);return new RegExp("^"+t.join(".+")+"$",i)};var Fl=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Jr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Fl({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var xt={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in xt){let t=xt[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Zr=function(s,i,t){s in xt||(xt[s]=[]),xt[s].push([i,t])},Qr=function(s,i){s in xt&&(xt[s]=xt[s].filter(t=>t[0]!==i))};function tn(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var yi=class extends T{constructor(){super();h(this,"couldBeCtxOwner",!0);h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,multiple:!1,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length}),this.subConfigValue("multiple",t=>{this.$.multiple=t})}extractUrlFromMessage(t){if(t.alternatives){let e=M(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Yr(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){!this.$.multiple&&this.$.selectedList.length||(this.$.selectedList=[...this.$.selectedList,t],this.$.multiple||this.$.onDone())}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Jr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e="false",{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=tn(n),o.toString()}mountIframe(){let t=Jt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Zr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Qr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};yi.template=`
{{activityCaption}}
{{counter}}
`;var we=class extends w{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;M(i).forEach(e=>{let r=Jt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};we.bindAttributes({"tab-list":null,default:null});we.template=`
`;var us=class extends T{constructor(){super(...arguments);h(this,"requireCtxName",!0)}_createValidationInput(){let t=document.createElement("input");return t.type="text",t.name=this.ctxName,t.required=this.cfg.multipleMin>0,t.tabIndex=-1,Ii(t,{opacity:0,height:0,width:0}),t}initCallback(){super.initCallback(),this._validationInputElement=this._createValidationInput(),this.appendChild(this._validationInputElement),this.sub("*collectionState",t=>{var e;{if(this._dynamicInputsContainer||(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer)),!this._validationInputElement){let l=this._createValidationInput();this.appendChild(l),this._validationInputElement=l}if(this._dynamicInputsContainer.innerHTML="",t.status==="uploading"||t.status==="idle"){this._validationInputElement.value="",this._validationInputElement.setCustomValidity("");return}if(t.status==="failed"){let l=(e=t.errors[0])==null?void 0:e.message;this._validationInputElement.value="",this._validationInputElement.setCustomValidity(l);return}let r=t.group?t.group:null;if(r){this._validationInputElement.value=r.cdnUrl,this._validationInputElement.setCustomValidity("");return}let n=t.allEntries.map(l=>l.cdnUrl);if(!this.cfg.multiple&&n.length===1){this._validationInputElement.value=n[0],this._validationInputElement.setCustomValidity("");return}this._validationInputElement.remove(),this._validationInputElement=null;let o=new DocumentFragment;for(let l of n){let a=document.createElement("input");a.type="hidden",a.name=`${this.ctxName}[]`,a.value=l,o.appendChild(a)}this._dynamicInputsContainer.replaceChildren(o)}},!1)}};var ds=class extends g{};var vi=class extends w{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};vi.template=``;var W={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},en={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Ae=class s extends w{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:W.PLAY,fsIcon:W.FS_ON,volIcon:W.VOL_ON,capIcon:W.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?en.exitFullscreen():en.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===W.CAP_OFF?(this.$.capIcon=W.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(s.is+":captions","1")):(this.$.capIcon=W.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(s.is+":captions"))}toggleSound(){this.$.volIcon===W.VOL_ON?(this.$.volIcon=W.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=W.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(s.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(s.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=W.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=W.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=W.FS_OFF:this.$.fsIcon=W.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(s.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};Ae.template=`
{{currentTime}} / {{totalTime}}
`;Ae.bindAttributes({video:"video",src:"src"});var Bl="css-src";function Ci(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0);h(this,"requireCtxName",!0)}shadowReadyCallback(){}async _waitForShadowStylesLoad(){if(!this.shadowRoot)return;let t=this.constructor.__shadowStylesUrl,e=this.shadowRoot.querySelector(`link[href="${t}"]`);e&&await new Promise((r,n)=>{e.addEventListener("load",r),e.addEventListener("error",n)})}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Ie({element:this,attribute:Bl,onSuccess:t=>{this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(async()=>{this.render(),await this._waitForShadowStylesLoad(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)},onTimeout:()=>{console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")}})}}}var Ee=class extends Ci(w){};var wi=class extends w{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(wi,"template",`Powered by Uploadcare`);var Tt=class extends Ee{constructor(){super(...arguments);h(this,"requireCtxName",!0);h(this,"init$",Ne(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var Ai=class extends Tt{shadowReadyCallback(){super.shadowReadyCallback(),this.sub("*modalActive",i=>{this._lastModalActive!==i&&this.emit(i?$.MODAL_OPEN:$.MODAL_CLOSE,void 0,{debounce:!0}),this._lastModalActive=i},!1)}};Ai.template=``;var Ei=class extends Tt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};Ei.template=``;var xi=class extends Tt{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}}}get couldHistoryBack(){let i=this.$["*history"];return i.length>1&&i[i.length-1]!==g.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0&&this.$["*currentActivity"]===(i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};xi.template=``;var ps=class extends Ci(nt){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function fs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var ms="LR";async function zl(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ms]){t(window[ms]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[ms];i&&fs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ds as ActivityHeader,Dt as BaseComponent,w as Block,ni as CameraSource,ps as CloudImageEditor,hs as CloudImageEditorActivity,nt as CloudImageEditorBlock,qo as Config,li as ConfirmationDialog,wi as Copyright,hi as CropFrame,E as Data,ce as DropArea,ge as EditorCropButtonControl,Xt as EditorFilterControl,di as EditorImageCropper,cs as EditorImageFader,ve as EditorOperationControl,pi as EditorScroller,ui as EditorSlider,fi as EditorToolbar,yi as ExternalSource,pe as FileItem,me as FilePreview,xi as FileUploaderInline,Ei as FileUploaderMinimal,Ai as FileUploaderRegular,us as FormInput,oe as Icon,ts as Img,mi as LineLoaderUi,Ce as LrBtnUi,fe as Modal,Be as PACKAGE_NAME,ze as PACKAGE_VERSION,_i as PresenceToggle,ci as ProgressBar,ai as ProgressBarCommon,vi as Select,Ee as ShadowWrapper,ae as SimpleBtn,bi as SliderUi,he as SourceBtn,ss as SourceList,ti as StartFrom,we as Tabs,Sl as UploadCtxProvider,oi as UploadDetails,si as UploadList,T as UploaderBlock,ri as UrlSource,Ae as Video,zl as connectBlocksFrom,fs as registerBlocks,Ci as shadowed,ht as toKebabCase}; \ No newline at end of file