@uploadcare/react-uploader 0.3.0-alpha.0 → 0.3.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
- "use strict";var cr=Object.defineProperty;var hr=(s,i,e)=>i in s?cr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e;var u=(s,i,e)=>(hr(s,typeof i!="symbol"?i+"":i,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("react");var ur=Object.defineProperty,dr=(s,i,e)=>i in s?ur(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,Nt=(s,i,e)=>(dr(s,typeof i!="symbol"?i+"":i,e),e);function fr(s){let i=e=>{var t;for(let r in e)((t=e[r])==null?void 0:t.constructor)===Object&&(e[r]=i(e[r]));return{...e}};return i(s)}var T=class{constructor(s){s.constructor===Object?this.store=fr(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)?(T.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,e=!1){!e&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){T.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,e=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(T.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),e&&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 e=T.globalStore.get(i);return e?console.warn('State: context UID "'+i+'" already in use'):(e=new T(s),T.globalStore.set(i,e)),e}static deleteCtx(s){T.globalStore.delete(s)}static getCtx(s,i=!0){return T.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};T.globalStore=new Map;var _=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"}),Wi="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",pr=Wi.length-1,Ae=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let e=0;e<s.length;e++)i+=s[e]==="-"?s[e]:Wi.charAt(Math.random()*pr);return i}};function qi(s,i,e){let t=!0,r,n=i.split(".");return n.forEach((o,l)=>{l<n.length-1?s=s[o]:r=o}),s?s[r]=e:t=!1,t}function mr(s){return s.split("-").map((i,e)=>i&&e?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,e)=>i&&e?i.toUpperCase():i).join("")}function gr(s,i){[...s.querySelectorAll(`[${_.REPEAT_ATTR}]`)].forEach(e=>{let t=e.getAttribute(_.REPEAT_ITEM_TAG_ATTR),r;if(t&&(r=window.customElements.get(t)),!r){r=class extends i.BaseComponent{constructor(){super(),t||(this.style.display="contents")}};let o=e.innerHTML;r.template=o,r.reg(t)}for(;e.firstChild;)e.firstChild.remove();let n=e.getAttribute(_.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;e.firstChild;)e.firstChild.remove();return}let l=[...e.children],a,c=h=>{h.forEach((f,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(f)});else for(let p in f)l[m][p]=f[p];else{a||(a=new DocumentFragment);let p=new r;Object.assign(p.init$,f),a.appendChild(p)}}),a&&e.appendChild(a);let d=l.slice(h.length,l.length);for(let f of d)f.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let h=[];for(let d in o){let f=o[d];Object.defineProperty(f,"_KEY_",{value:d,enumerable:!0}),h.push(f)}c(h)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),e.removeAttribute(_.REPEAT_ATTR),e.removeAttribute(_.REPEAT_ITEM_TAG_ATTR)})}var mi="__default__";function br(s,i){if(i.shadowRoot)return;let e=[...s.querySelectorAll("slot")];if(!e.length)return;let t={};e.forEach(r=>{let n=r.getAttribute("name")||mi;t[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=mi;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=t[o])==null||n.fr.appendChild(r)}),Object.values(t).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 _r(s,i){[...s.querySelectorAll(`[${_.EL_REF_ATTR}]`)].forEach(e=>{let t=e.getAttribute(_.EL_REF_ATTR);i.ref[t]=e,e.removeAttribute(_.EL_REF_ATTR)})}function yr(s,i){[...s.querySelectorAll(`[${_.BIND_ATTR}]`)].forEach(e=>{let r=e.getAttribute(_.BIND_ATTR).split(";");[...e.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=mr(n.name.replace("-",""));r.push(o+":"+n.value),e.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(h=>h.trim()),l=o[0],a;l.indexOf(_.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(_.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(h=>h.trim());for(let h of c){let d;h.startsWith("!!")?(d="double",h=h.replace("!!","")):h.startsWith("!")&&(d="single",h=h.replace("!","")),i.sub(h,f=>{d==="double"?f=!!f:d==="single"&&(f=!f),a?(f==null?void 0:f.constructor)===Boolean?f?e.setAttribute(l,""):e.removeAttribute(l):e.setAttribute(l,f):qi(e,l,f)||(e[_.SET_LATER_KEY]||(e[_.SET_LATER_KEY]=Object.create(null)),e[_.SET_LATER_KEY][l]=f)})}}),e.removeAttribute(_.BIND_ATTR)})}var tt="{{",Be="}}",vr="skip-text";function Cr(s){let i,e=[],t=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(vr))&&r.textContent.includes(tt)&&r.textContent.includes(Be)&&1}});for(;i=t.nextNode();)e.push(i);return e}var wr=function(s,i){Cr(s).forEach(t=>{let r=[],n;for(;t.textContent.includes(Be);)t.textContent.startsWith(tt)?(n=t.textContent.indexOf(Be)+Be.length,t.splitText(n),r.push(t)):(n=t.textContent.indexOf(tt),t.splitText(n)),t=t.nextSibling;r.forEach(o=>{let l=o.textContent.replace(tt,"").replace(Be,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Er=[gr,br,_r,yr,wr],st="'",Pe='"',Ar=/\\([0-9a-fA-F]{1,6} ?)/g;function Tr(s){return(s[0]===Pe||s[0]===st)&&(s[s.length-1]===Pe||s[s.length-1]===st)}function $r(s){return(s[0]===Pe||s[0]===st)&&(s=s.slice(1)),(s[s.length-1]===Pe||s[s.length-1]===st)&&(s=s.slice(0,-1)),s}function Sr(s){let i="",e="";for(var t=0;t<s.length;t++){const r=s[t+1];s[t]==="\\"&&r==='"'?(i+='\\"',t++):s[t]==='"'&&e!=="\\"?i+='\\"':i+=s[t],e=s[t]}return i}function xr(s){let i=s;Tr(s)&&(i=$r(i),i=i.replace(Ar,(e,t)=>String.fromCodePoint(parseInt(t.trim(),16))),i=i.replaceAll(`\\
2
- `,"\\n"),i=Sr(i),i=Pe+i+Pe);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var gi=0,$e=null,se=null,he=class extends HTMLElement{constructor(){super(),Nt(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let e=this.getCssData(this.__extractCssName(i),!0);e!==null&&this.$[i]!==e&&(this.$[i]=e)})}),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 he}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let e;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(_.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)e=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,e=r.content.cloneNode(!0)}else this.constructor.__tpl&&(e=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(e,this)}let t=()=>{e&&(i&&this.shadowRoot.appendChild(e)||this.appendChild(e)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=t,this.shadowRoot.prepend(r)}else t()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Ae.generate(),this.style.setProperty(_.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(_.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(_.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=T.registerCtx({},this)),this.__localCtx}get nodeCtx(){return T.getCtx(this.ctxName,!1)||T.registerCtx({},this.ctxName)}static __parseProp(s,i){let e,t;if(s.startsWith(_.EXT_DATA_CTX_PRFX))e=i.nodeCtx,t=s.replace(_.EXT_DATA_CTX_PRFX,"");else if(s.includes(_.NAMED_DATA_CTX_SPLTR)){let r=s.split(_.NAMED_DATA_CTX_SPLTR);e=T.getCtx(r[0]),t=r[1]}else e=i.localCtx,t=s;return{ctx:e,name:t}}sub(s,i,e=!0){let t=n=>{this.isConnected&&i(n)},r=he.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,t,e)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,t,e))})}notify(s){let i=he.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=he.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,e=!1){let t=he.__parseProp(s,this);t.ctx.add(t.name,i,e)}add$(s,i=!1){for(let e in s)this.add(e,s[e],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,e,t)=>{let r=he.__parseProp(e,this);return r.ctx.pub(r.name,t),!0},get:(i,e)=>{let t=he.__parseProp(e,this);return t.ctx.read(t.name)}})}return this.__stateProxy}set$(s,i=!1){for(let e in s){let t=s[e];i||![String,Number,Boolean].includes(t==null?void 0:t.constructor)?this.$[e]=t:this.$[e]!==t&&(this.$[e]=t)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(_.CTX_OWNER_ATTR)&&this.getAttribute(_.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(_.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(_.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(_.NAMED_DATA_CTX_SPLTR)){let e=i.split(_.NAMED_DATA_CTX_SPLTR),t=e[0].trim(),r=e[1].trim();if(t&&r){let n=T.getCtx(t,!1);n||(n=T.registerCtx({},t)),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(_.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(_.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[_.SET_LATER_KEY]){for(let e in this[_.SET_LATER_KEY])qi(this,e,this[_.SET_LATER_KEY][e]);delete this[_.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let e of Er)this.addTemplateProcessor(e);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let e=this.getRootNode();if(!e)return;if(e==null?void 0:e.querySelector(`link[${_.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(_.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},e.nodeType===Node.DOCUMENT_NODE?e.head.appendChild(r):e.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);se==null||se.delete(this.updateCssData),se!=null&&se.size||($e==null||$e.disconnect(),$e=null,se=null)},100)))}static reg(s,i=!1){s||(gi++,s=`${_.AUTO_TAG_PRFX}-${gi}`),this.__tag=s;let e=window.customElements.get(s);if(e){!i&&e!==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(`
3
- `));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,e){var t;if(i===e)return;let r=(t=this.constructor.__attrDesc)==null?void 0:t[s];r?this.__dataCtxInitialized?this.$[r]=e:this.init$[r]=e:this[s]=e}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 e=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=xr(e)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,e)=>e===0?"":i).join("--")}__initStyleAttrObserver(){se||(se=new Set),se.add(this.updateCssData),$e||($e=new MutationObserver(s=>{s[0].type==="attributes"&&se.forEach(i=>{i()})}),$e.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let e=this.getCssData(this.__extractCssName(s),!0);e===null&&(e=i),this.add(s,e),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,e){let t="__"+s;this[t]=this[s],Object.defineProperty(this,s,{set:r=>{this[t]=r,e?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[t]}),this[s]=this[t]}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"}),e=URL.createObjectURL(i),t=document.createElement("link");t.href=e,t.rel="stylesheet",this.__rootStylesLink=t}}},ht=he;Nt(ht,"template");function Gi(s,i){for(let e in i)e.includes("-")?s.style.setProperty(e,i[e]):s.style[e]=i[e]}function Ir(s,i){for(let e in i)i[e].constructor===Boolean?i[e]?s.setAttribute(e,""):s.removeAttribute(e):s.setAttribute(e,i[e])}function Dt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&Ir(i,s.attributes),s.styles&&Gi(i,s.styles),s.properties)for(let e in s.properties)i[e]=s.properties[e];return s.processors&&s.processors.forEach(e=>{e(i)}),s.children&&s.children.forEach(e=>{let t=Dt(e);i.appendChild(t)}),i}var Xi="idb-store-ready",kr="symbiote-db",Or="symbiote-idb-update_",Pr=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(Xi,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return Or+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=e=>{this.db=e.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=t=>{this._notifyWhenReady(t)}},this.request.onsuccess=e=>{this.db=e.target.result,this._notifyWhenReady(e)},this.request.onerror=e=>{console.error(e)},this._subscriptionsMap={},this._updateHandler=e=>{e.key===this.name&&this._subscriptionsMap[e.newValue]&&this._subscriptionsMap[e.newValue].forEach(async r=>{r(await this.read(e.newValue))})},this._localUpdateHandler=e=>{this._updateHandler(e.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((t,r)=>{e.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?t(n.target.result._value):(t(null),console.warn(`IDB: cannot read "${s}"`))},e.onerror=n=>{r(n)}})}write(s,i,e=!1){let t={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(t);return new Promise((o,l)=>{n.onsuccess=a=>{e||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{t.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},t.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((e,t)=>{i.onsuccess=r=>{let n=r.target.result;e(n.map(o=>o._value))},i.onerror=r=>{t(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let e=this._subscriptionsMap[s];return e.add(i),{remove:()=>{e.delete(i),e.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Ki.clear(this.name)}},Ki=class{static get readyEventName(){return Xi}static open(s=kr,i="store"){let e=s+"/"+i;return this._reg[e]||(this._reg[e]=new Pr(s,i)),this._reg[e]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Nt(Ki,"_reg",Object.create(null));const Lr=20,x=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"});class Ur{constructor(i){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);u(this,"_debugPrint",null);this._debugPrint=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,e){var t;for(const r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:e}));(t=this._debugPrint)==null||t.call(this,()=>{const r=e&&typeof e=="object"?{...e}:e;return[`event "${i}"`,r]})}emit(i,e,{debounce:t}={}){if(typeof t!="number"&&!t){this._dispatch(i,typeof e=="function"?e():e);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));const r=typeof t=="number"?t:Lr,n=window.setTimeout(()=>{this._dispatch(i,typeof e=="function"?e():e),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}}function H(s,i){let e;const t=(...r)=>{clearTimeout(e),e=setTimeout(()=>s(...r),i)};return t.cancel=()=>{clearTimeout(e)},t}const bi="--uploadcare-blocks-window-height";class rt{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(bi)}}u(rt,"clientsRegistry",new Set),u(rt,"flush",H(()=>{document.documentElement.style.setProperty(bi,`${window.innerHeight}px`)},100));const Yi=(s,i)=>new Intl.PluralRules(s).select(i),Rr=s=>s,kt="{{",Ji="}}",_i="plural:";function Ot(s,i,e={}){var o;let{openToken:t=kt,closeToken:r=Ji,transform:n=Rr}=e;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(t+l+r,typeof a=="string"?n(a):a)}return s}function Mr(s){const i=[];let e=s.indexOf(kt);for(;e!==-1;){const t=s.indexOf(Ji,e),r=s.substring(e+2,t);if(r.startsWith(_i)){const n=s.substring(e+2,t).replace(_i,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}e=s.indexOf(kt,t)}return i}const Ce=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(e=>e.toLowerCase()).join("-")},Zi=({element:s,attribute:i,onSuccess:e,onTimeout:t,timeout:r=300})=>{const n=s.getAttribute(i);if(n!==null){e(n);return}const o=new MutationObserver(c=>{const h=c[c.length-1];a(h)});o.observe(s,{attributes:!0,attributeFilter:[i]});const l=setTimeout(()=>{o.disconnect(),t()},r),a=c=>{const h=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&h!==null&&(clearTimeout(l),o.disconnect(),e(h))}},yi=new Set;function nt(s){yi.has(s)||(yi.add(s),console.warn(s))}function vi(s){return Object.prototype.toString.call(s)==="[object Object]"}const Fr=/\W|_/g;function Nr(s){return s.split(Fr).map((i,e)=>i.charAt(0)[e>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Ci(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(e=>ce(e,{ignoreKeys:i})):s}function ce(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return Ci(s,{ignoreKeys:i});if(!vi(s))return s;const e={};for(const t of Object.keys(s)){let r=s[t];if(i.includes(t)){e[t]=r;continue}vi(r)?r=ce(r,{ignoreKeys:i}):Array.isArray(r)&&(r=Ci(r,{ignoreKeys:i})),e[Nr(t)]=r}return e}const Dr=s=>new Promise(i=>setTimeout(i,s));function Qi({libraryName:s,libraryVersion:i,userAgent:e,publicKey:t="",integration:r=""}){const n="JavaScript";if(typeof e=="string")return e;if(typeof e=="function")return e({publicKey:t,libraryName:s,libraryVersion:i,languageName:n,integration:r});const o=[s,i,t].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}const zr={factor:2,time:100};function Vr(s,i=zr){let e=0;function t(r){const n=Math.round(i.time*i.factor**e);return r({attempt:e,retry:l=>Dr(l??n).then(()=>(e+=1,t(r)))})}return t(s)}class zt extends Error{}class Ge extends zt{constructor(e){super();u(this,"originalProgressEvent");this.name="NetworkError",this.message="Network error",Object.setPrototypeOf(this,Ge.prototype),this.originalProgressEvent=e}}const ut=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))};class Ee extends zt{constructor(e="Request canceled"){super(e);u(this,"isCancel",!0);this.name="CancelError",Object.setPrototypeOf(this,Ee.prototype)}}const Br=500,es=({check:s,interval:i=Br,timeout:e,signal:t})=>new Promise((r,n)=>{let o,l;ut(t,()=>{o&&clearTimeout(o),n(new Ee("Poll cancelled"))}),e&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ee("Timed out"))},e));const a=()=>{try{Promise.resolve(s(t)).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)}),E={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"},dt="application/octet-stream",ts="original",me=({method:s,url:i,data:e,headers:t={},signal:r,onProgress:n})=>new Promise((o,l)=>{const a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET";let h=!1;a.open(c,i,!0),t&&Object.entries(t).forEach(d=>{const[f,m]=d;typeof m<"u"&&!Array.isArray(m)&&a.setRequestHeader(f,m)}),a.responseType="text",ut(r,()=>{h=!0,a.abort(),l(new Ee)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{const d={method:c,url:i,data:e,headers:t||void 0,signal:r,onProgress:n},f=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};f.forEach(function(A){const w=A.split(": "),C=w.shift(),y=w.join(": ");C&&typeof C<"u"&&(m[C]=y)});const p=a.response,g=a.status;o({request:d,data:p,headers:m,status:g})}},a.onerror=d=>{h||l(new Ge(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),e?a.send(e):a.send()});function jr(s,...i){return s}const Hr=({name:s})=>s?[s]:[],Wr=jr;var qr=()=>new FormData;const is=s=>!1,ft=s=>typeof Blob<"u"&&s instanceof Blob,pt=s=>typeof File<"u"&&s instanceof File,mt=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Re=s=>ft(s)||pt(s)||is()||mt(s),Gr=s=>typeof s=="string"||typeof s=="number"||typeof s>"u",Xr=s=>!!s&&typeof s=="object"&&!Array.isArray(s),Kr=s=>!!s&&typeof s=="object"&&"data"in s&&Re(s.data);function ss(s,i,e){if(Array.isArray(e))for(const t of e)ss(s,`${i}[]`,t);else if(Kr(e)){const{name:t,contentType:r}=e,n=Wr(e.data,t,r??dt),o=Hr({name:t,contentType:r});s.push([i,n,...o])}else if(Xr(e))for(const[t,r]of Object.entries(e))typeof r<"u"&&s.push([`${i}[${t}]`,String(r)]);else Gr(e)&&e&&s.push([i,e.toString()])}function Yr(s){const i=[];for(const[e,t]of Object.entries(s))ss(i,e,t);return i}function gt(s){const i=qr(),e=Yr(s);for(const t of e){const[r,n,...o]=t;i.append(r,n,...o)}return i}class D extends zt{constructor(e,t,r,n,o){super();u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadError",this.message=e,this.code=t,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,D.prototype)}}const Jr=s=>{const i=new URLSearchParams;for(const[e,t]of Object.entries(s))t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).filter(r=>r[1]??!1).forEach(r=>i.set(`${e}[${r[0]}]`,String(r[1]))):Array.isArray(t)?t.forEach(r=>{i.append(`${e}[]`,r)}):typeof t=="string"&&t?i.set(e,t):typeof t=="number"&&i.set(e,t.toString());return i.toString()},oe=(s,i,e)=>{const t=new URL(s);return t.pathname=(t.pathname+i).replace("//","/"),e&&(t.search=Jr(e)),t.toString()};var Zr="6.14.1";const Qr="UploadcareUploadClient",en=Zr;function Te(s){return Qi({libraryName:Qr,libraryVersion:en,...s})}const tn="RequestThrottledError",wi=15e3,sn=1e3;function rn(s){const{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return wi;const e=parseInt(i["retry-after"],10);return Number.isFinite(e)?e*1e3:wi}function ge(s,i){const{retryThrottledRequestMaxTimes:e,retryNetworkErrorMaxTimes:t}=i;return Vr(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===tn&&r<e)return n(rn(o));if(o instanceof Ge&&r<t)return n((r+1)*sn);throw o}))}const rs=s=>{let i="";return(ft(s)||pt(s)||mt(s))&&(i=s.type),i||dt},ns=s=>{let i="";return pt(s)&&s.name?i=s.name:ft(s)||is()?i="":mt(s)&&s.name&&(i=s.name),i||ts};function Vt(s){return typeof s>"u"||s==="auto"?"auto":s?"1":"0"}function nn(s,{publicKey:i,fileName:e,contentType:t,baseURL:r=E.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:h="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=E.retryNetworkErrorMaxTimes,metadata:g}){return ge(()=>me({method:"POST",url:oe(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Te({publicKey:i,integration:d,userAgent:f})},data:gt({file:{data:s,name:e||ns(s),contentType:t||rs(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Vt(l),signature:n,expire:o,source:h,metadata:g}),signal:a,onProgress:c}).then(({data:A,headers:w,request:C})=>{const y=ce(JSON.parse(A));if("error"in y)throw new D(y.error.content,y.error.errorCode,C,y,w);return y}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var Pt;(function(s){s.Token="token",s.FileInfo="file_info"})(Pt||(Pt={}));function on(s,{publicKey:i,baseURL:e=E.baseURL,store:t,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=E.retryNetworkErrorMaxTimes,metadata:g}){return ge(()=>me({method:"POST",headers:{"X-UC-User-Agent":Te({publicKey:i,integration:d,userAgent:f})},url:oe(e,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Vt(t),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:g}),signal:h}).then(({data:A,headers:w,request:C})=>{const y=ce(JSON.parse(A));if("error"in y)throw new D(y.error.content,y.error.errorCode,C,y,w);return y}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var N;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(N||(N={}));const ln=s=>"status"in s&&s.status===N.Error;function an(s,{publicKey:i,baseURL:e=E.baseURL,signal:t,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=E.retryNetworkErrorMaxTimes}={}){return ge(()=>me({method:"GET",headers:i?{"X-UC-User-Agent":Te({publicKey:i,integration:r,userAgent:n})}:void 0,url:oe(e,"/from_url/status/",{jsonerrors:1,token:s}),signal:t}).then(({data:a,headers:c,request:h})=>{const d=ce(JSON.parse(a));if("error"in d&&!ln(d))throw new D(d.error.content,d.error.errorCode,h,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function cn(s,{publicKey:i,baseURL:e=E.baseURL,jsonpCallback:t,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=E.retryNetworkErrorMaxTimes}){return ge(()=>me({method:"POST",headers:{"X-UC-User-Agent":Te({publicKey:i,integration:a,userAgent:c})},url:oe(e,"/group/",{jsonerrors:1}),data:gt({files:s,callback:t,pub_key:i,signature:r,expire:n,source:l}),signal:o}).then(({data:f,headers:m,request:p})=>{const g=ce(JSON.parse(f));if("error"in g)throw new D(g.error.content,g.error.errorCode,p,g,m);return g}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function os(s,{publicKey:i,baseURL:e=E.baseURL,signal:t,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=E.retryNetworkErrorMaxTimes}){return ge(()=>me({method:"GET",headers:{"X-UC-User-Agent":Te({publicKey:i,integration:n,userAgent:o})},url:oe(e,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:t}).then(({data:c,headers:h,request:d})=>{const f=ce(JSON.parse(c));if("error"in f)throw new D(f.error.content,f.error.errorCode,d,f,h);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function hn(s,{publicKey:i,contentType:e,fileName:t,multipartChunkSize:r=E.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:h="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=E.retryNetworkErrorMaxTimes,metadata:g}){return ge(()=>me({method:"POST",url:oe(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Te({publicKey:i,integration:d,userAgent:f})},data:gt({filename:t||ts,size:s,content_type:e||dt,part_size:r,UPLOADCARE_STORE:Vt(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:h,metadata:g}),signal:c}).then(({data:A,headers:w,request:C})=>{const y=ce(JSON.parse(A));if("error"in y)throw new D(y.error.content,y.error.errorCode,C,y,w);return y.parts=Object.keys(y.parts).map(U=>y.parts[Number(U)]),y}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})}function un(s,i,{contentType:e,signal:t,onProgress:r,retryThrottledRequestMaxTimes:n=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=E.retryNetworkErrorMaxTimes}){return ge(()=>me({method:"PUT",url:i,data:s,onProgress:r,signal:t,headers:{"Content-Type":e||dt}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function dn(s,{publicKey:i,baseURL:e=E.baseURL,source:t="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=E.retryNetworkErrorMaxTimes}){return ge(()=>me({method:"POST",url:oe(e,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Te({publicKey:i,integration:n,userAgent:o})},data:gt({uuid:s,UPLOADCARE_PUB_KEY:i,source:t}),signal:r}).then(({data:c,headers:h,request:d})=>{const f=ce(JSON.parse(c));if("error"in f)throw new D(f.error.content,f.error.errorCode,d,f,h);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Bt(s,{publicKey:i,baseURL:e,source:t,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return es({check:h=>os(s,{publicKey:i,baseURL:e,signal:h,source:t,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function fn(s){return"defaultEffects"in s}class Me{constructor(i,{baseCDN:e=E.baseCDN,fileName:t}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);u(this,"defaultEffects",null);const{uuid:r,s3Bucket:n}=i,o=oe(e,`${r}/`),l=n?oe(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=t||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,fn(i)&&(this.defaultEffects=i.defaultEffects)}}const pn=(s,{publicKey:i,fileName:e,baseURL:t,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,baseCDN:g,metadata:A})=>nn(s,{publicKey:i,fileName:e,contentType:l,baseURL:t,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:A}).then(({file:w})=>Bt(w,{publicKey:i,baseURL:t,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:c,signal:a})).then(w=>new Me(w,{baseCDN:g})),mn=(s,{publicKey:i,fileName:e,baseURL:t,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h,baseCDN:d})=>os(s,{publicKey:i,baseURL:t,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h}).then(f=>new Me(f,{baseCDN:d,fileName:e})).then(f=>(n&&n({isComputable:!0,value:1}),f)),gn=(s,{signal:i}={})=>{let e=null,t=null;const r=s.map(()=>new AbortController),n=o=>()=>{t=o,r.forEach((l,a)=>a!==o&&l.abort())};return ut(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{const a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(e=c,null))})).then(o=>{if(t===null)throw e;return o[t]})};var bn=window.WebSocket;class _n{constructor(){u(this,"events",Object.create({}))}emit(i,e){var t;(t=this.events[i])==null||t.forEach(r=>r(e))}on(i,e){this.events[i]=this.events[i]||[],this.events[i].push(e)}off(i,e){e?this.events[i]=this.events[i].filter(t=>t!==e):this.events[i]=[]}}const yn=(s,i)=>s==="success"?{status:N.Success,...i}:s==="progress"?{status:N.Progress,...i}:{status:N.Error,...i};class vn{constructor(i,e=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new _n);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=e}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){const i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new bn(i),this.ws.addEventListener("error",e=>{this.emmitter.emit("error",new Error(e.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(e=>this.send(e.event,e.data)),this.queue=[]}),this.ws.addEventListener("message",e=>{const t=JSON.parse(e.data.toString());switch(t.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(t.channel,yn(t.event,JSON.parse(t.data)))}})}}disconnect(){const i=()=>{var e;(e=this.ws)==null||e.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,e){var r;const t=JSON.stringify({event:i,data:e});(r=this.ws)==null||r.send(t)}subscribe(i,e){this.subscribers+=1,this.connect();const t=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:t}};this.emmitter.on(t,e),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;const e=`task-status-${i}`,t={event:"pusher:unsubscribe",data:{channel:e}};this.emmitter.off(e),this.isConnected?this.send(t.event,t.data):this.queue=this.queue.filter(r=>r.data.channel!==e),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}}let Et=null;const jt=s=>{if(!Et){const i=typeof window>"u"?0:3e4;Et=new vn(s,i)}return Et},Cn=s=>{jt(s).connect()};function wn({token:s,publicKey:i,baseURL:e,integration:t,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return es({check:c=>an(s,{publicKey:i,baseURL:e,integration:t,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(h=>{switch(h.status){case N.Error:return new D(h.error,h.errorCode);case N.Waiting:return!1;case N.Unknown:return new D(`Token "${s}" was not found.`);case N.Progress:return l&&(h.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:h.done/h.total})),!1;case N.Success:return l&&l({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:a})}const En=({token:s,pusherKey:i,signal:e,onProgress:t})=>new Promise((r,n)=>{const o=jt(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};ut(e,()=>{a(),n(new Ee("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case N.Progress:{t&&(c.total==="unknown"?t({isComputable:!1}):t({isComputable:!0,value:c.done/c.total}));break}case N.Success:{a(),t&&t({isComputable:!0,value:c.done/c.total}),r(c);break}case N.Error:a(),n(new D(c.msg,c.error_code))}})}),An=(s,{publicKey:i,fileName:e,baseURL:t,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:h,onProgress:d,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:g,pusherKey:A=E.pusherKey,metadata:w})=>Promise.resolve(Cn(A)).then(()=>on(s,{publicKey:i,fileName:e,baseURL:t,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:h,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:g,metadata:w})).catch(C=>{const y=jt(A);return y==null||y.disconnect(),Promise.reject(C)}).then(C=>C.type===Pt.FileInfo?C:gn([({signal:y})=>wn({token:C.token,publicKey:i,baseURL:t,integration:m,userAgent:p,retryThrottledRequestMaxTimes:g,onProgress:d,signal:y}),({signal:y})=>En({token:C.token,pusherKey:A,signal:y,onProgress:d})],{signal:h})).then(C=>{if(C instanceof D)throw C;return C}).then(C=>Bt(C.uuid,{publicKey:i,baseURL:t,integration:m,userAgent:p,retryThrottledRequestMaxTimes:g,onProgress:d,signal:h})).then(C=>new Me(C,{baseCDN:r})),At=new WeakMap,Tn=async s=>{if(At.has(s))return At.get(s);const i=await fetch(s.uri).then(e=>e.blob());return At.set(s,i),i},ls=async s=>{if(pt(s)||ft(s))return s.size;if(mt(s))return(await Tn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},$n=(s,i=E.multipartMinFileSize)=>s>=i,as=s=>{const i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",e=new RegExp(i);return!Re(s)&&e.test(s)},Ht=s=>{const i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",e=new RegExp(i);return!Re(s)&&e.test(s)},Sn=(s,i)=>new Promise((e,t)=>{const r=[];let n=!1,o=i.length;const l=[...i],a=()=>{const c=i.length-l.length,h=l.shift();h&&h().then(d=>{n||(r[c]=d,o-=1,o?a():e(r))}).catch(d=>{n=!0,t(d)})};for(let c=0;c<s;c++)a()}),xn=(s,i,e,t)=>{const r=t*i,n=Math.min(r+t,e);return s.slice(r,n)},In=async(s,i,e)=>t=>xn(s,t,i,e),kn=(s,i,{publicKey:e,contentType:t,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>un(s,i,{publicKey:e,contentType:t,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),On=async(s,{publicKey:i,fileName:e,fileSize:t,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,contentType:g,multipartChunkSize:A=E.multipartChunkSize,maxConcurrentRequests:w=E.maxConcurrentRequests,baseCDN:C,metadata:y})=>{const U=t??await ls(s);let te;const _e=(O,R)=>{if(!c)return;te||(te=Array(O).fill(0));const W=K=>K.reduce((ie,wt)=>ie+wt,0);return K=>{K.isComputable&&(te[R]=K.value,c({isComputable:!0,value:W(te)/O}))}};return g||(g=rs(s)),hn(U,{publicKey:i,contentType:g,fileName:e||ns(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:y}).then(async({uuid:O,parts:R})=>{const W=await In(s,U,A);return Promise.all([O,Sn(w,R.map((K,ie)=>()=>kn(W(ie),K,{publicKey:i,contentType:g,onProgress:_e(R.length,ie),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})))])}).then(([O])=>dn(O,{publicKey:i,baseURL:r,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})).then(O=>O.isReady?O:Bt(O.uuid,{publicKey:i,baseURL:r,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:c,signal:a})).then(O=>new Me(O,{baseCDN:C}))};async function cs(s,{publicKey:i,fileName:e,baseURL:t=E.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartMinFileSize:g,multipartChunkSize:A,maxConcurrentRequests:w,baseCDN:C=E.baseCDN,checkForUrlDuplicates:y,saveUrlForRecurrentUploads:U,pusherKey:te,metadata:_e}){if(Re(s)){const O=await ls(s);return $n(O,g)?On(s,{publicKey:i,contentType:p,multipartChunkSize:A,fileSize:O,fileName:e,baseURL:t,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,maxConcurrentRequests:w,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:C,metadata:_e}):pn(s,{publicKey:i,fileName:e,contentType:p,baseURL:t,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:C,metadata:_e})}if(Ht(s))return An(s,{publicKey:i,fileName:e,baseURL:t,baseCDN:C,checkForUrlDuplicates:y,saveUrlForRecurrentUploads:U,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,pusherKey:te,metadata:_e});if(as(s))return mn(s,{publicKey:i,fileName:e,baseURL:t,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:C});throw new TypeError(`File uploading from "${s}" is not supported`)}class Pn{constructor(i,{baseCDN:e=E.baseCDN}={}){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;const t=i.files.filter(Boolean);this.totalSize=Object.values(t).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(t).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t.map(r=>new Me(r,{baseCDN:e})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}}const Ln=s=>{for(const i of s)if(!Re(i))return!1;return!0},Un=s=>{for(const i of s)if(!as(i))return!1;return!0},Rn=s=>{for(const i of s)if(!Ht(i))return!1;return!0};function Mn(s,{publicKey:i,fileName:e,baseURL:t=E.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:g=E.multipartChunkSize,baseCDN:A=E.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:C,jsonpCallback:y}){if(!Ln(s)&&!Rn(s)&&!Un(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let U,te=!0;const _e=s.length,O=(R,W)=>{if(!a)return;U||(U=Array(R).fill(0));const K=ie=>ie.reduce((wt,ar)=>wt+ar)/R;return ie=>{if(!ie.isComputable||!te){te=!1,a({isComputable:!1});return}U[W]=ie.value,a({isComputable:!0,value:K(U)})}};return Promise.all(s.map((R,W)=>Re(R)||Ht(R)?cs(R,{publicKey:i,fileName:e,baseURL:t,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:O(_e,W),source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:g,baseCDN:A,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:C}).then(K=>K.uuid):R)).then(R=>cn(R,{publicKey:i,baseURL:t,jsonpCallback:y,secureSignature:r,secureExpire:n,signal:l,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m}).then(W=>new Pn(W,{baseCDN:A})).then(W=>(a&&a({isComputable:!0,value:1}),W)))}class Fn{constructor(i){u(this,"_concurrency",1);u(this,"_pending",[]);u(this,"_running",0);u(this,"_resolvers",new Map);u(this,"_rejectors",new Map);this._concurrency=i}_run(){const i=this._concurrency-this._running;for(let e=0;e<i;e++){const t=this._pending.shift();if(!t)return;const r=this._resolvers.get(t),n=this._rejectors.get(t);if(!r||!n)throw new Error("Unexpected behavior: resolver or rejector is undefined");this._running+=1,t().finally(()=>{this._resolvers.delete(t),this._rejectors.delete(t),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((e,t)=>{this._resolvers.set(i,e),this._rejectors.set(i,t),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}}const hs=()=>({"*blocksRegistry":new Set,"*eventEmitter":null}),us=s=>({...hs(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),ds=s=>({...us(s),"*commonProgress":0,"*uploadList":[],"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Fn(1),"*uploadCollection":null,"*collectionErrors":[],"*collectionState":null,"*groupInfo":null,"*uploadTrigger":new Set});function Nn(s,i){[...s.querySelectorAll("[l10n]")].forEach(e=>{let t=e.getAttribute("l10n"),r="textContent";if(t.includes(":")){let o=t.split(":");r=o[0],t=o[1]}let n="l10n:"+t;i.__l10nKeys.push(n),i.add(n,t),i.sub(n,o=>{e[r]=i.l10n(o)}),e.removeAttribute("l10n")})}const z=s=>`*cfg/${s}`,Tt="lr-";class k extends ht{constructor(){super();u(this,"requireCtxName",!1);u(this,"allowCustomTemplate",!0);u(this,"activityType",null);u(this,"init$",hs());u(this,"updateCtxCssData",()=>{nt("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 e=this.$["*blocksRegistry"];for(let t of e)t.isConnected&&t.updateCssData()});this.addTemplateProcessor(Nn),this.__l10nKeys=[]}l10n(e,t={}){if(!e)return"";let r=this.getCssData("--l10n-"+e,!0)||e,n=Mr(r);for(let l of n)t[l.variable]=this.pluralize(l.pluralKey,Number(t[l.countVariable]));return Ot(r,t)}pluralize(e,t){const r=this.l10n("locale-name")||"en-US",n=Yi(r,t);return this.l10n(`${e}__${n}`)}emit(e,t,r){const n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(e,t,r)}applyL10nKey(e,t){let r="l10n:"+e;this.$[r]=t,this.__l10nKeys.push(e)}hasBlockInCtx(e){let t=this.$["*blocksRegistry"];for(let r of t)if(e(r))return!0;return!1}setOrAddState(e,t){this.add$({[e]:t},!0)}setActivity(e){if(this.hasBlockInCtx(t=>t.activityType===e)){this.$["*currentActivity"]=e;return}console.warn(`Activity type "${e}" not found in the context`)}connectedCallback(){const e=this.constructor.className;e&&this.classList.toggle(`${Tt}${e}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Zi({element:this,attribute:"ctx-name",onSuccess:()=>{super.connectedCallback()},onTimeout:()=>{console.error("Attribute `ctx-name` is required and it is not set.")}}):super.connectedCallback(),rt.registerClient(this)}disconnectedCallback(){super.disconnectedCallback(),rt.unregisterClient(this)}initCallback(){this.$["*blocksRegistry"].add(this),this.$["*eventEmitter"]||(this.$["*eventEmitter"]=new Ur(this.debugPrint.bind(this)))}destroyCallback(){let e=this.$["*blocksRegistry"];e.delete(this),T.deleteCtx(this),e.size===0&&setTimeout(()=>{this.destroyCtxCallback()},0)}destroyCtxCallback(){T.deleteCtx(this.ctxName)}fileSizeFmt(e,t=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(e===0)return`0 ${n(r[0])}`;let o=1024,l=t<0?0:t,a=Math.floor(Math.log(e)/Math.log(o));return parseFloat((e/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(e){let t=this.cfg.secureDeliveryProxy;return t?Ot(t,{previewUrl:e},{transform:r=>window.encodeURIComponent(r)}):e}parseCfgProp(e){return{ctx:this.nodeCtx,name:e.replace("*","")}}get cfg(){if(!this.__cfgProxy){let e=Object.create(null);this.__cfgProxy=new Proxy(e,{set:(t,r,n)=>{if(typeof r!="string")return!1;const o=z(r);return this.$[o]=n,!0},get:(t,r)=>{const n=z(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(nt("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-${Ce(r)}`))}})}return this.__cfgProxy}subConfigValue(e,t){const r=this.parseCfgProp(z(e));r.ctx.has(r.name)?this.sub(z(e),t):(this.bindCssData(`--cfg-${Ce(e)}`),this.sub(`--cfg-${Ce(e)}`,t))}debugPrint(...e){if(!this.cfg.debug)return;let t=e;if(typeof(e==null?void 0:e[0])=="function"){const r=e[0];t=r()}console.log(`[${this.debugCtxName}]`,...t)}get debugCtxName(){return this.ctxName}static reg(e){if(!e){super.reg();return}super.reg(e.startsWith(Tt)?e:Tt+e)}}u(k,"StateConsumerScope",null),u(k,"className","");const Ei="active",Ne="___ACTIVITY_IS_ACTIVE___",G=class G extends k{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",us(this));u(this,"_debouncedHistoryFlush",H(this._historyFlush.bind(this),10))}_deactivate(){var t;let e=G._activityRegistry[this.activityKey];this[Ne]=!1,this.removeAttribute(Ei),(t=e==null?void 0:e.deactivateCallback)==null||t.call(e)}_activate(){var t;let e=G._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[Ne]=!0,this.setAttribute(Ei,""),(t=e==null?void 0:e.activateCallback)==null||t.call(e),this._debouncedHistoryFlush(),this.emit(x.ACTIVITY_CHANGE,{activity:this.activityType})}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",e=>{this.setAttribute("current-activity",e)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",e=>{this.activityType!==e&&this[Ne]?this._deactivate():this.activityType===e&&!this[Ne]&&this._activate(),e||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",e=>{!e&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let e=this.$["*history"];e&&(e.length>10&&(e=e.slice(e.length-11,e.length-1)),this.historyTracked&&e[e.length-1]!==this.activityType&&e.push(this.activityType),this.$["*history"]=e)}_isActivityRegistered(){return this.activityType&&!!G._activityRegistry[this.activityKey]}get isActivityActive(){return this[Ne]}get couldOpenActivity(){return!0}registerActivity(e,t={}){const{onActivate:r,onDeactivate:n}=t;G._activityRegistry||(G._activityRegistry=Object.create(null)),G._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),G._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(G._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(){let e=this.$["*history"];if(e){let t=e.pop();for(;t===this.activityType;)t=e.pop();let r=!!t;if(t){const o=[...this.$["*blocksRegistry"]].find(l=>l.activityType===t);r=(o==null?void 0:o.couldOpenActivity)??!1}t=r?t:void 0,this.$["*currentActivity"]=t,this.$["*history"]=e,t||this.setOrAddState("*modalActive",!1)}}};u(G,"_activityRegistry",Object.create(null));let b=G;b.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"});const Dn=20,Lt=24,je=34,fs=3,Z=fs/2,ye=1,Ye=100/3,v=1,Ai=24,zn=6;function Ie(s,i){for(let e in i)s.setAttributeNS(null,e,i[e].toString())}function q(s,i={}){let e=document.createElementNS("http://www.w3.org/2000/svg",s);return Ie(e,i),e}function Vn(s,i,e){let{x:t,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],h=[-1,1][a],d=[t+l*n+Z*c,r+a*o+Z*h-Lt*e*h],f=[t+l*n+Z*c,r+a*o+Z*h],m=[t+l*n-Lt*e*c+Z*c,r+a*o+Z*h];return{d:`M ${d[0]} ${d[1]} L ${f[0]} ${f[1]} L ${m[0]} ${m[1]}`,center:f}}function Bn(s,i,e){let{x:t,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],h=[-1,1][a],d,f;["n","s"].includes(i)?(d=[t+l*n-je*e/2,r+a*o+Z*h],f=[t+l*n+je*e/2,r+a*o+Z*h]):(d=[t+l*n+Z*c,r+a*o-je*e/2],f=[t+l*n+Z*c,r+a*o+je*e/2]);let m=`M ${d[0]} ${d[1]} L ${f[0]} ${f[1]}`,p=[f[0]-(f[0]-d[0])/2,f[1]-(f[1]-d[1])/2];return{d:m,center:p}}function jn(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 Hn({rect:s,delta:[i,e],imageBox:t}){return ot({...s,x:s.x+i,y:s.y+e},t)}function ot(s,i){let{x:e}=s,{y:t}=s;return s.x<i.x?e=i.x:s.x+s.width>i.x+i.width&&(e=i.x+i.width-s.width),s.y<i.y?t=i.y:s.y+s.height>i.y+i.height&&(t=i.y+i.height-s.height),{...s,x:e,y:t}}function Wn({rect:s,delta:i,aspectRatio:e,imageBox:t}){const[,r]=i;let{y:n,width:o,height:l}=s;n+=r,l-=r,e&&(o=l*e);let a=s.x+s.width/2-o/2;return n<=t.y&&(n=t.y,l=s.y+s.height-n,e&&(o=l*e,a=s.x+s.width/2-o/2)),a<=t.x&&(a=t.x,n=s.y+s.height-l),a+o>=t.x+t.width&&(a=Math.max(t.x,t.x+t.width-o),o=t.x+t.width-a,e&&(l=o/e),n=s.y+s.height-l),l<v&&(l=v,e&&(o=l*e,a=s.x+s.width/2-o/2),n=s.y+s.height-l),o<v&&(o=v,e&&(l=o/e,a=s.x+s.width/2-o/2),n=s.y+s.height-l),{x:a,y:n,width:o,height:l}}function qn({rect:s,delta:i,aspectRatio:e,imageBox:t}){const[r]=i;let{x:n,width:o,height:l}=s;n+=r,o-=r,e&&(l=o/e);let a=s.y+s.height/2-l/2;return n<=t.x&&(n=t.x,o=s.x+s.width-n,e&&(l=o/e,a=s.y+s.height/2-l/2)),a<=t.y&&(a=t.y,n=s.x+s.width-o),a+l>=t.y+t.height&&(a=Math.max(t.y,t.y+t.height-l),l=t.y+t.height-a,e&&(o=l*e),n=s.x+s.width-o),l<v&&(l=v,e&&(o=l*e),a=s.y+s.height/2-l/2,n=s.x+s.width-o),o<v&&(o=v,e&&(l=o/e),a=s.y+s.height/2-l/2,n=s.x+s.width-o),{x:n,y:a,width:o,height:l}}function Gn({rect:s,delta:i,aspectRatio:e,imageBox:t}){const[,r]=i;let{y:n,width:o,height:l}=s;l+=r,e&&(o=l*e);let a=s.x+s.width/2-o/2;return n+l>=t.y+t.height&&(l=t.y+t.height-n,e&&(o=l*e),a=s.x+s.width/2-o/2),a<=t.x&&(a=t.x,n=s.y),a+o>=t.x+t.width&&(a=Math.max(t.x,t.x+t.width-o),o=t.x+t.width-a,e&&(l=o/e),n=s.y),l<v&&(l=v,e&&(o=l*e),a=s.x+s.width/2-o/2),o<v&&(o=v,e&&(l=o/e),a=s.x+s.width/2-o/2),{x:a,y:n,width:o,height:l}}function Xn({rect:s,delta:i,aspectRatio:e,imageBox:t}){const[r]=i;let{x:n,width:o,height:l}=s;o+=r,e&&(l=o/e);let a=s.y+s.height/2-l/2;return n+o>=t.x+t.width&&(o=t.x+t.width-n,e&&(l=o/e),a=s.y+s.height/2-l/2),a<=t.y&&(a=t.y,n=s.x),a+l>=t.y+t.height&&(a=Math.max(t.y,t.y+t.height-l),l=t.y+t.height-a,e&&(o=l*e),n=s.x),l<v&&(l=v,e&&(o=l*e),a=s.y+s.height/2-l/2),o<v&&(o=v,e&&(l=o/e),a=s.y+s.height/2-l/2),{x:n,y:a,width:o,height:l}}function Kn({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,n]=i,{x:o,y:l,width:a,height:c}=s;return o+r<t.x&&(r=t.x-o),l+n<t.y&&(n=t.y-l),o+=r,a-=r,l+=n,c-=n,e&&Math.abs(a/c)>e?(n=a/e-c,c+=n,l-=n,l<=t.y&&(c=c-(t.y-l),a=c*e,o=s.x+s.width-a,l=t.y)):e&&(r=c*e-a,a=a+r,o-=r,o<=t.x&&(a=a-(t.x-o),c=a/e,o=t.x,l=s.y+s.height-c)),c<v&&(c=v,e&&(a=c*e),o=s.x+s.width-a,l=s.y+s.height-c),a<v&&(a=v,e&&(c=a/e),o=s.x+s.width-a,l=s.y+s.height-c),{x:o,y:l,width:a,height:c}}function Yn({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,n]=i,{x:o,y:l,width:a,height:c}=s;return o+a+r>t.x+t.width&&(r=t.x+t.width-o-a),l+n<t.y&&(n=t.y-l),a+=r,l+=n,c-=n,e&&Math.abs(a/c)>e?(n=a/e-c,c+=n,l-=n,l<=t.y&&(c=c-(t.y-l),a=c*e,o=s.x,l=t.y)):e&&(r=c*e-a,a+=r,o+a>=t.x+t.width&&(a=t.x+t.width-o,c=a/e,o=t.x+t.width-a,l=s.y+s.height-c)),c<v&&(c=v,e&&(a=c*e),l=s.y+s.height-c),a<v&&(a=v,e&&(c=a/e),l=s.y+s.height-c),{x:o,y:l,width:a,height:c}}function Jn({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,n]=i,{x:o,y:l,width:a,height:c}=s;return o+r<t.x&&(r=t.x-o),l+c+n>t.y+t.height&&(n=t.y+t.height-l-c),o+=r,a-=r,c+=n,e&&Math.abs(a/c)>e?(n=a/e-c,c+=n,l+c>=t.y+t.height&&(c=t.y+t.height-l,a=c*e,o=s.x+s.width-a,l=t.y+t.height-c)):e&&(r=c*e-a,a+=r,o-=r,o<=t.x&&(a=a-(t.x-o),c=a/e,o=t.x,l=s.y)),c<v&&(c=v,e&&(a=c*e),o=s.x+s.width-a),a<v&&(a=v,e&&(c=a/e),o=s.x+s.width-a),{x:o,y:l,width:a,height:c}}function Zn({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,n]=i,{x:o,y:l,width:a,height:c}=s;return o+a+r>t.x+t.width&&(r=t.x+t.width-o-a),l+c+n>t.y+t.height&&(n=t.y+t.height-l-c),a+=r,c+=n,e&&Math.abs(a/c)>e?(n=a/e-c,c+=n,l+c>=t.y+t.height&&(c=t.y+t.height-l,a=c*e,o=s.x,l=t.y+t.height-c)):e&&(r=c*e-a,a+=r,o+a>=t.x+t.width&&(a=t.x+t.width-o,c=a/e,o=t.x+t.width-a,l=s.y)),c<v&&(c=v,e&&(a=c*e)),a<v&&(a=v,e&&(c=a/e)),{x:o,y:l,width:a,height:c}}function Qn({direction:s,...i}){switch(s){case"n":return Wn(i);case"w":return qn(i);case"s":return Gn(i);case"e":return Xn(i);case"nw":return Kn(i);case"ne":return Yn(i);case"sw":return Jn(i);case"se":return Zn(i);default:return i.rect}}function eo(s,[i,e]){return s.x<=i&&i<=s.x+s.width&&s.y<=e&&e<=s.y+s.height}function to(s,i){return s.x>=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function io(s,i){return Math.abs(s.width/s.height-i)<.1}function De({width:s,height:i},e){let t=e/90%2!==0;return{width:t?i:s,height:t?s:i}}function so(s,i,e){const t=s/i;let r,n;t>e?(r=Math.round(i*e),n=i):(r=s,n=Math.round(s/e));const 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 it(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function ke(s,i,e){return Math.min(Math.max(s,i),e)}const ps=s=>{if(!s)return[];const[i,e]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(e)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:e}]},Q=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"}),ro=s=>s?s.split(",").map(i=>i.trim()):[],Wt=s=>s?s.join(","):"",qt="blocks",bt="0.36.0";function no(s){return Qi({...s,libraryName:qt,libraryVersion:bt})}const ms=({type:s,message:i,...e})=>({type:s,message:i,...e}),Se=ms,$t=ms,gs=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},Gt=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>gs(i)).join("/-/"),le=(...s)=>{let i=Gt(...s);return i?`-/${i}/`:""};function bs(s){let i=new URL(s),e=i.pathname+i.search+i.hash,t=e.lastIndexOf("http"),r=e.lastIndexOf("/"),n="";return t>=0?n=e.slice(t):r>=0&&(n=e.slice(r+1)),n}function oo(s){let i=new URL(s),{pathname:e}=i;const t=e.indexOf("/"),r=e.indexOf("/",t+1);return e.substring(t+1,r)}function lo(s){let i=_s(s),e=new URL(i),t=e.pathname.indexOf("/-/");return t===-1?[]:e.pathname.substring(t).split("/-/").filter(Boolean).map(n=>gs(n))}function _s(s){let i=new URL(s),e=bs(s),t=ys(e)?vs(e).pathname:e;return i.pathname=i.pathname.replace(t,""),i.search="",i.hash="",i.toString()}function ys(s){return s.startsWith("http")}function vs(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}const V=(s,i,e)=>{let t=new URL(_s(s));if(e=e||bs(s),t.pathname.startsWith("//")&&(t.pathname=t.pathname.replace("//","/")),ys(e)){let r=vs(e);t.pathname=t.pathname+(i||"")+(r.pathname||""),t.search=r.search,t.hash=r.hash}else t.pathname=t.pathname+(i||"")+(e||"");return t.toString()},We=(s,i)=>{let e=new URL(s);return e.pathname=i+"/",e.toString()},ae=(s,i=",")=>s.trim().split(i).map(e=>e.trim()).filter(e=>e.length>0),Ut=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Ti=s=>s?s.filter(i=>typeof i=="string").map(i=>ae(i)).flat():[],Cs=(s,i)=>i.some(e=>e.endsWith("*")?(e=e.replace("*",""),s.startsWith(e)):s===e),ao=(s,i)=>i.some(e=>e.startsWith(".")?s.toLowerCase().endsWith(e.toLowerCase()):!1),Rt=s=>{let i=s==null?void 0:s.type;return i?Cs(i,Ut):!1},Y=1e3,ve=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ze=s=>Math.ceil(s*100)/100,co=(s,i=ve.AUTO)=>{const e=i===ve.AUTO;if(i===ve.BYTE||e&&s<Y**1){const t=Yi("en-US",s),r={one:"byte",other:"bytes"}[t];return`${s} ${r}`}return i===ve.KB||e&&s<Y**2?`${ze(s/Y**1)} KB`:i===ve.MB||e&&s<Y**3?`${ze(s/Y**2)} MB`:i===ve.GB||e&&s<Y**4?`${ze(s/Y**3)} GB`:i===ve.TB||e&&s<Y**5?`${ze(s/Y**4)} TB`:`${ze(s/Y**5)} PB`},$i="[Typed State] Wrong property name: ",ho="[Typed State] Wrong property type: ";class uo{constructor(i,e){this.__typedSchema=i,this.__ctxId=e||Ae.generate(),this.__schema=Object.keys(i).reduce((t,r)=>(t[r]=i[r].value,t),{}),this.__data=T.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,e){if(!this.__typedSchema.hasOwnProperty(i)){console.warn($i+i);return}let t=this.__typedSchema[i];if((e==null?void 0:e.constructor)===t.type||e instanceof t.type||t.nullable&&e===null){this.__data.pub(i,e);return}console.warn(ho+i)}setMultipleValues(i){for(let e in i)this.setValue(e,i[e])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn($i+i);return}return this.__data.read(i)}subscribe(i,e){return this.__data.sub(i,e)}remove(){T.deleteCtx(this.__ctxId)}}class fo{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Ae.generate(),this.__data=T.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 e=Object.create(null);this.__notifyObservers=(t,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),e[t]||(e[t]=new Set),e[t].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(e).length!==0&&(this.__propertyObservers.forEach(n=>{n({...e})}),e=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),e=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(const t of this.__collectionObservers)t==null||t([...this.__items],i,e)})}observeCollection(i){return this.__collectionObservers.add(i),this.__items.size>0&&this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var e;(e=this.__collectionObservers)==null||e.delete(i)}add(i){let e=new uo(this.__typedSchema);for(let t in i)e.setValue(t,i[t]);return this.__items.add(e.uid),this.notify(),this.__data.add(e.uid,e),this.__added.add(e),this.__watchList.forEach(t=>{this.__subsMap[e.uid]||(this.__subsMap[e.uid]=[]),this.__subsMap[e.uid].push(e.subscribe(t,()=>{this.__notifyObservers(t,e.uid)}))}),e.uid}read(i){return this.__data.read(i)}readProp(i,e){return this.read(i).getValue(e)}publishProp(i,e,t){this.read(i).setValue(e,t)}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 e;(e=this.__propertyObservers)==null||e.delete(i)}findItems(i){let e=[];return this.__items.forEach(t=>{let r=this.read(t);i(r)&&e.push(t)}),e}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){T.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(e=>{e.remove()}),delete this.__subsMap[i]}}const po=s=>{const i=new Map;return(...e)=>{const t=JSON.stringify(e);if(i.has(t))return i.get(t);const r=s(...e);return i.set(t,r),r}};function mo(s){let i=!1;return setTimeout(()=>{i=!0},0),t=>(...r)=>(i&&nt(s),t(...r))}function go(s){const i={progress:()=>s.$["*commonProgress"],errors:()=>s.$["*collectionErrors"],group:()=>s.$["*groupInfo"],totalCount:()=>s.uploadCollection.size,failedCount:()=>e.failedEntries.length,successCount:()=>e.successEntries.length,uploadingCount:()=>e.uploadingEntries.length,status:()=>e.isFailed?"failed":e.isUploading?"uploading":e.isSuccess?"success":"idle",isSuccess:()=>e.errors.length===0&&e.successEntries.length===e.allEntries.length,isUploading:()=>e.allEntries.some(r=>r.status==="uploading"),isFailed:()=>e.errors.length>0||e.failedEntries.length>0,allEntries:()=>s.getOutputData(),successEntries:()=>e.allEntries.filter(r=>r.status==="success"),failedEntries:()=>e.allEntries.filter(r=>r.status==="failed"),uploadingEntries:()=>e.allEntries.filter(r=>r.status==="uploading"),idleEntries:()=>e.allEntries.filter(r=>r.status==="idle")},e={},t=mo("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(const[r,n]of Object.entries(i)){const o=r,a=po(t(n));Object.defineProperty(e,o,{get:a,enumerable:!0})}return e}const bo=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:Me,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}}),_o=/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i,yo=new RegExp(`^/?(${_o.source})(?:/(-/(?:[^/]+/)+)?([^/]*))?$`,"i"),vo=({url:s,cdnBase:i})=>{const e=new URL(i),t=new URL(s);if(e.host!==t.host)return null;const[,r,n,o]=yo.exec(t.pathname);return{uuid:r,cdnUrlModifiers:n||"",filename:o||null}};class $ extends b{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!1);u(this,"isCtxOwner",!1);u(this,"init$",ds(this));u(this,"__initialUploadMetadata",null);u(this,"_fileValidators",[this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this),this._validateUploadError.bind(this)]);u(this,"_collectionValidators",[e=>{const t=e.size,r=this.cfg.multiple?this.cfg.multipleMin:0,n=this.cfg.multiple?this.cfg.multipleMax:1;if(r&&t<r){const o=this.l10n("files-count-limit-error-too-few",{min:r,max:n,total:t});return $t({type:"TOO_FEW_FILES",message:o,total:t,min:r,max:n})}if(n&&t>n){const o=this.l10n("files-count-limit-error-too-many",{min:r,max:n,total:t});return $t({type:"TOO_MANY_FILES",message:o,total:t,min:r,max:n})}},e=>{if(e.items().some(t=>e.readProp(t,"errors").length>0))return $t({type:"SOME_FILES_HAS_ERRORS",message:this.l10n("some-files-were-not-uploaded")})}]);u(this,"uploadAll",()=>{const e=this.uploadCollection.items().filter(t=>{const r=this.uploadCollection.read(t);return!r.getValue("isRemoved")&&!r.getValue("isUploading")&&!r.getValue("fileInfo")});e.length!==0&&(this.$["*uploadTrigger"]=new Set(e),this.emit(x.COMMON_UPLOAD_START,this.getOutputCollectionState()))});u(this,"_flushOutputItems",H(async()=>{if(this.getOutputData().length!==this.uploadCollection.size)return;const t=this.getOutputCollectionState();this.$["*collectionState"]=t,this.emit(x.CHANGE,()=>this.getOutputCollectionState(),{debounce:!0}),this.cfg.groupOutput&&t.totalCount>0&&t.status==="success"&&this._createGroup(t)},300));u(this,"_handleCollectionUpdate",(e,t,r)=>{var n;(t.size||r.size)&&(this.$["*groupInfo"]=null),this._runFileValidators(),this._runCollectionValidators();for(const o of t)o.getValue("silent")||this.emit(x.FILE_ADDED,this.getOutputItem(o.uid));for(const 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(x.FILE_REMOVED,this.getOutputItem(o.uid));this.$["*uploadList"]=e.map(o=>({uid:o})),this._flushCommonUploadProgress(),this._flushOutputItems()});u(this,"_handleCollectionPropertiesUpdate",e=>{this._flushOutputItems();const t=this.uploadCollection,r=[...new Set(Object.entries(e).filter(([n])=>["uploadError","fileInfo"].includes(n)).map(([,n])=>[...n]).flat())];if(r.length>0&&setTimeout(()=>{this._runFileValidators(r)}),e.uploadProgress){for(const n of e.uploadProgress){const{isUploading:o,silent:l}=T.getCtx(n).store;o&&!l&&this.emit(x.FILE_UPLOAD_PROGRESS,this.getOutputItem(n))}this._flushCommonUploadProgress()}if(e.isUploading)for(const n of e.isUploading){const{isUploading:o,silent:l}=T.getCtx(n).store;o&&!l&&this.emit(x.FILE_UPLOAD_START,this.getOutputItem(n))}if(e.fileInfo){for(const l of e.fileInfo){const{fileInfo:a,silent:c}=T.getCtx(l).store;a&&!c&&this.emit(x.FILE_UPLOAD_SUCCESS,this.getOutputItem(l))}this.cfg.cropPreset&&this.setInitialCrop();let n=t.findItems(l=>!!l.getValue("fileInfo"));t.findItems(l=>l.getValue("errors").length>0).length===0&&t.size===n.length&&this.emit(x.COMMON_UPLOAD_SUCCESS,this.getOutputCollectionState())}if(e.errors)for(const n of e.errors){const{errors:o}=T.getCtx(n).store;o.length>0&&(this.emit(x.FILE_UPLOAD_FAILED,this.getOutputItem(n)),this.emit(x.COMMON_UPLOAD_FAILED,()=>this.getOutputCollectionState(),{debounce:!0}))}e.cdnUrl&&([...e.cdnUrl].filter(o=>{var l;return!!((l=this.uploadCollection.read(o))!=null&&l.getValue("cdnUrl"))}).forEach(o=>{this.emit(x.FILE_URL_CHANGED,this.getOutputItem(o))}),this.$["*groupInfo"]=null)});u(this,"_flushCommonUploadProgress",()=>{let e=0;const r=[...this.$["*uploadTrigger"]].filter(o=>!!this.uploadCollection.read(o));r.forEach(o=>{const l=this.uploadCollection.readProp(o,"uploadProgress");e+=l});const n=r.length?Math.round(e/r.length):0;this.$["*commonProgress"]!==n&&(this.$["*commonProgress"]=n,this.emit(x.COMMON_UPLOAD_PROGRESS,this.getOutputCollectionState()))})}setUploadMetadata(e){nt("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"]=e:this.__initialUploadMetadata=e}get hasCtxOwner(){return this.hasBlockInCtx(e=>e instanceof $?e.isCtxOwner&&e.isConnected&&e!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let e=new fo({typedSchema:bo,watchList:["uploadProgress","uploadError","fileInfo","errors","cdnUrl","isUploading"]});this.$["*uploadCollection"]=e}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCtxCallback(){var e,t;(e=this._unobserveCollectionProperties)==null||e.call(this),(t=this._unobserveCollection)==null||t.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);const e=()=>{this._runFileValidators(),this._runCollectionValidators()};this.subConfigValue("maxLocalFileSizeBytes",e),this.subConfigValue("multipleMin",e),this.subConfigValue("multipleMax",e),this.subConfigValue("multiple",e),this.subConfigValue("imgOnly",e),this.subConfigValue("accept",e),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(e,{silent:t,fileName:r,source:n}={}){const o=this.uploadCollection.add({externalUrl:e,fileName:r??null,silent:t??!1,source:n??Q.API});return this.getOutputItem(o)}addFileFromUuid(e,{silent:t,fileName:r,source:n}={}){const o=this.uploadCollection.add({uuid:e,fileName:r??null,silent:t??!1,source:n??Q.API});return this.getOutputItem(o)}addFileFromCdnUrl(e,{silent:t,fileName:r,source:n}={}){const o=vo({url:e,cdnBase:this.cfg.cdnCname});if(!o)throw new Error("Invalid CDN URL");const l=this.uploadCollection.add({uuid:o.uuid,cdnUrl:e,cdnUrlModifiers:o.cdnUrlModifiers,fileName:r??o.filename??null,silent:t??!1,source:n??Q.API});return this.getOutputItem(l)}addFileFromObject(e,{silent:t,fileName:r,source:n,fullPath:o}={}){const l=this.uploadCollection.add({file:e,isImage:Rt(e),mimeType:e.type,fileName:r??e.name,fileSize:e.size,silent:t??!1,source:n??Q.API,fullPath:o??null});return this.getOutputItem(l)}addFiles(e){return console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),e.map(t=>{const r=this.uploadCollection.add({file:t,isImage:Rt(t),mimeType:t.type,fileName:t.name,fileSize:t.size});return this.getOutputItem(r)})}removeFileByInternalId(e){if(!this.uploadCollection.read(e))throw new Error(`File with internalId ${e} not found`);this.uploadCollection.remove(e)}removeAllFiles(){this.uploadCollection.clearAll()}openSystemDialog(e={}){let t=Wt(Ti([this.cfg.accept??"",...this.cfg.imgOnly?Ut:[]]));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,e.captureCamera?(this.fileInput.capture=this.cfg.cameraCapture,this.fileInput.accept="image/*"):this.fileInput.accept=t,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(r=>this.addFileFromObject(r,{source:e.captureCamera?Q.CAMERA:Q.LOCAL})),this.$["*currentActivity"]=b.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let e=[];return this.cfg.sourceList&&(e=ae(this.cfg.sourceList)),e}initFlow(e=!1){var t;if(this.uploadCollection.size>0&&!e)this.set$({"*currentActivity":b.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((t=this.sourceList)==null?void 0:t.length)===1){const r=this.sourceList[0];if(r==="local"){this.$["*currentActivity"]=b.activities.UPLOAD_LIST,this==null||this.openSystemDialog();return}const n=this.$["*blocksRegistry"],o=a=>"type"in a&&a.type===r,l=[...n].find(o);l==null||l.activate(),this.$["*currentActivity"]&&this.setOrAddState("*modalActive",!0)}else this.set$({"*currentActivity":b.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(e){const t=this.cfg.imgOnly,r=this.cfg.accept,n=Ti([...t?Ut:[],r]);if(!n.length)return;const o=e.mimeType,l=e.name;if(!o||!l)return;const a=Cs(o,n),c=ao(l,n);if(!a&&!c)return Se({type:"FORBIDDEN_FILE_TYPE",message:this.l10n("file-type-not-allowed"),entry:e})}_validateMaxSizeLimit(e){const t=this.cfg.maxLocalFileSizeBytes,r=e.size;if(t&&r&&r>t)return Se({type:"FILE_SIZE_EXCEEDED",message:this.l10n("files-max-size-limit-error",{maxFileSize:co(t)}),entry:e})}_validateUploadError(e,t){const r=t==null?void 0:t.getValue("uploadError");if(r){if(r instanceof D)return Se({type:"UPLOAD_ERROR",message:r.message,entry:e,error:r});if(r instanceof Ge)return Se({type:"NETWORK_ERROR",message:r.message,entry:e,error:r});{const n=r instanceof Error?r:new Error("Unknown error",{cause:r});return Se({type:"UNKNOWN_ERROR",message:n.message,entry:e,error:n})}}}_validateIsImage(e){const t=this.cfg.imgOnly,r=e.isImage;if(!(!t||r)&&!(!e.fileInfo&&e.externalUrl)&&!(!e.fileInfo&&!e.mimeType))return Se({type:"NOT_AN_IMAGE",message:this.l10n("images-only-accepted"),entry:e})}_runFileValidatorsForEntry(e){const t=this.getOutputItem(e.uid),r=[];for(const n of this._fileValidators){const o=n(t,e);o&&r.push(o)}e.setValue("errors",r)}_runFileValidators(e){const t=e??this.uploadCollection.items();for(const r of t){const n=this.uploadCollection.read(r);n&&this._runFileValidatorsForEntry(n)}}_runCollectionValidators(){const e=this.uploadCollection,t=[];for(const r of this._collectionValidators){const n=r(e);n&&(Array.isArray(n)?t.push(...n):t.push(n))}this.$["*collectionErrors"]=t,t.length>0&&this.emit(x.COMMON_UPLOAD_FAILED,()=>this.getOutputCollectionState(),{debounce:!0})}async _createGroup(e){const t=this.getUploadClientOptions(),r=e.allEntries.map(a=>a.uuid+(a.cdnUrlModifiers?`/${a.cdnUrlModifiers}`:"")),n=new AbortController,o=await Mn(r,{...t,signal:n.signal});if(this.$["*collectionState"]!==e){n.abort();return}this.$["*groupInfo"]=o;const l=this.getOutputCollectionState();this.emit(x.GROUP_CREATED,l),this.emit(x.CHANGE,()=>this.getOutputCollectionState(),{debounce:!0}),this.$["*collectionState"]=l}setInitialCrop(){const e=ps(this.cfg.cropPreset);if(e){const[t]=e,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(const n of r){const o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=t.width/t.height,h=so(l,a,c),d=le(`crop/${h.width}x${h.height}/${h.x},${h.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:V(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===b.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=b.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(e){const t=this.cfg.metadata??this.$["*uploadMetadata"];if(typeof t=="function"){const r=this.getOutputItem(e);return await t(r)}return t}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:no,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(e){const t=T.getCtx(e).store,r=t.fileInfo;let n=t.isRemoved?"removed":t.errors.length>0?"failed":t.fileInfo?"success":t.isUploading?"uploading":"idle";return{uuid:(r==null?void 0:r.uuid)??t.uuid??null,internalId:e,name:(r==null?void 0:r.originalFilename)??t.fileName,size:(r==null?void 0:r.size)??t.fileSize,isImage:(r==null?void 0:r.isImage)??t.isImage,mimeType:(r==null?void 0:r.mimeType)??t.mimeType,file:t.file,externalUrl:t.externalUrl,cdnUrlModifiers:t.cdnUrlModifiers,cdnUrl:t.cdnUrl??(r==null?void 0:r.cdnUrl)??null,fullPath:t.fullPath,uploadProgress:t.uploadProgress,fileInfo:r??null,metadata:t.metadata??(r==null?void 0:r.metadata)??null,isSuccess:n==="success",isUploading:n==="uploading",isFailed:n==="failed",isRemoved:n==="removed",errors:t.errors,status:n}}getOutputData(e){return(e?this.uploadCollection.findItems(e):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}getOutputCollectionState(){return go(this)}}$.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"});$.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...$.extSrcList});const j=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}),ws=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function Co(s,i){if(typeof i=="number"){const e=i;return j[s]!==e?`${s}/${e}`:""}if(typeof i=="boolean"){const e=i;return j[s]!==e?`${s}`:""}if(s==="filter"&&i){const{name:e,amount:t}=i;return j.filter===t?"":`${s}/${e}/${t}`}if(s==="crop"&&i){let{dimensions:e,coords:t}=i;return`${s}/${e.join("x")}/${t.join(",")}`}return""}function _t(s){return Gt(...ws.filter(i=>typeof s[i]<"u"&&s[i]!==null).map(i=>{let e=s[i];return Co(i,e)}).filter(i=>!!i))}const Es=Gt("format/auto","progressive/yes"),re=([s])=>typeof s<"u"?Number(s):void 0,Si=()=>!0,wo=([s,i])=>({name:s,amount:typeof i<"u"?Number(i):100}),Eo=([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:ae(s,"x").map(Number),coords:ae(i).map(Number)}},Ao=Object.freeze({enhance:re,brightness:re,exposure:re,gamma:re,contrast:re,saturation:re,vibrance:re,warmth:re,filter:wo,mirror:Si,flip:Si,rotate:re,crop:Eo});function To(s){const i={};for(const e of s){const[t,...r]=e.split("/");if(!ws.includes(t))continue;const n=t,o=Ao[n];try{const l=o(r);i[n]=l}catch(l){console.warn([`Failed to parse URL operation "${e}". 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(`
4
- `))}}return i}const L=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),ee=[L.CROP,L.TUNING,L.FILTERS],$o=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],So=["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"],xo=["rotate","mirror","flip"],Le=Object.freeze({brightness:{zero:j.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:j.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:j.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:j.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:j.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:j.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:j.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:j.enhance,range:[0,100],keypointsNumber:1},filter:{zero:j.filter,range:[0,100],keypointsNumber:1}}),Io="https://ucarecdn.com",ko="https://upload.uploadcare.com",Oo="https://social.uploadcare.com",Oe={pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,cameraCapture:"",sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Wt(ee),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Io,baseUrl:ko,socialBaseUrl:Oo,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},P=s=>String(s),J=s=>{const i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},I=s=>{if(typeof s>"u"||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}"`)},Po=s=>s==="auto"?s:I(s),Lo=s=>{const i=P(s);if(i!=="user"&&i!=="environment"&&i!=="")throw new Error(`Invalid "cameraCapture" value: "${i}"`);return i},Uo={pubkey:P,multiple:I,multipleMin:J,multipleMax:J,confirmUpload:I,imgOnly:I,accept:P,externalSourcesPreferredTypes:P,store:Po,cameraMirror:I,cameraCapture:Lo,sourceList:P,maxLocalFileSizeBytes:J,thumbSize:J,showEmptyList:I,useLocalImageEditor:I,useCloudImageEditor:I,cloudImageEditorTabs:P,removeCopyright:I,cropPreset:P,imageShrink:P,modalScrollLock:I,modalBackdropStrokes:I,sourceListWrap:I,remoteTabSessionKey:P,cdnCname:P,baseUrl:P,socialBaseUrl:P,secureSignature:P,secureExpire:P,secureDeliveryProxy:P,retryThrottledRequestMaxTimes:J,multipartMinFileSize:J,multipartChunkSize:J,maxConcurrentRequests:J,multipartMaxConcurrentRequests:J,multipartMaxAttempts:J,checkForUrlDuplicates:I,saveUrlForRecurrentUploads:I,groupOutput:I,userAgentIntegration:P,debug:I},Ro=(s,i)=>{if(!(typeof i>"u"||i===null))try{return Uo[s](i)}catch(e){return console.error(`Invalid value for config key "${s}".`,e),Oe[s]}},Ue=Object.keys(Oe),Mo=["metadata"],Fo=s=>Mo.includes(s),lt=Ue.filter(s=>!Fo(s)),No={...Object.fromEntries(lt.map(s=>[Ce(s),s])),...Object.fromEntries(lt.map(s=>[s.toLowerCase(),s]))},Do={...Object.fromEntries(Ue.map(s=>[Ce(s),z(s)])),...Object.fromEntries(Ue.map(s=>[s.toLowerCase(),z(s)]))};class Xt extends k{constructor(){super();u(this,"requireCtxName",!0);u(this,"_debugPrint",H(()=>{const e=Object.create(null);for(const t of Ue)e[t]=this.$[z(t)];this.debugPrint("config",e)},0));this.init$={...this.init$,...Object.fromEntries(Object.entries(Oe).map(([e,t])=>[z(e),t]))}}initCallback(){super.initCallback();const e=this;for(const t of lt)this.sub(z(t),r=>{r!==Oe[t]&&(e[t]=r)},!1);for(const t of Ue){let r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,lt.includes(t)){const o=[...new Set([Ce(t),t.toLowerCase()])];for(const l of o)typeof n>"u"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[z(t)]!==n&&(typeof n>"u"||n===null?this.$[z(t)]=Oe[t]:this.$[z(t)]=n)},get:()=>this.$[z(t)]}),typeof e[t]<"u"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(e,t,r){if(t===r)return;const n=No[e],l=Ro(n,r)??Oe[n],a=this;a[n]=l}}Xt.bindAttributes(Do);for(const s of Ue){const i="__"+s;Object.defineProperty(Xt.prototype,s,{set:function(e){this[i]=e},get:function(){return this[i]}})}const As=Xt;class Kt extends k{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",e=>{if(!e)return;let t=this.getCssData(`--icon-${e}`);t&&(this.$.path=t)}),this.sub("path",e=>{if(!e)return;e.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=e):(this.removeAttribute("raw"),this.ref.svg.innerHTML=`<path fill-rule="evenodd" d="${e}"></path>`)}),this.sub("size",e=>{this.$.viewBox=`0 0 ${e} ${e}`})}}Kt.template=`
1
+ "use strict";var cr=Object.defineProperty;var hr=(s,i,e)=>i in s?cr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e;var u=(s,i,e)=>(hr(s,typeof i!="symbol"?i+"":i,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("react");var ur=Object.defineProperty,dr=(s,i,e)=>i in s?ur(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,Rt=(s,i,e)=>(dr(s,typeof i!="symbol"?i+"":i,e),e);function fr(s){let i=e=>{var t;for(let r in e)((t=e[r])==null?void 0:t.constructor)===Object&&(e[r]=i(e[r]));return{...e}};return i(s)}var T=class{constructor(s){s.constructor===Object?this.store=fr(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)?(T.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,e=!1){!e&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){T.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,e=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(T.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),e&&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 e=T.globalStore.get(i);return e?console.warn('State: context UID "'+i+'" already in use'):(e=new T(s),T.globalStore.set(i,e)),e}static deleteCtx(s){T.globalStore.delete(s)}static getCtx(s,i=!0){return T.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};T.globalStore=new Map;var v=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"}),Wi="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",pr=Wi.length-1,Ae=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let e=0;e<s.length;e++)i+=s[e]==="-"?s[e]:Wi.charAt(Math.random()*pr);return i}};function qi(s,i,e){let t=!0,r,n=i.split(".");return n.forEach((o,l)=>{l<n.length-1?s=s[o]:r=o}),s?s[r]=e:t=!1,t}function mr(s){return s.split("-").map((i,e)=>i&&e?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,e)=>i&&e?i.toUpperCase():i).join("")}function gr(s,i){[...s.querySelectorAll(`[${v.REPEAT_ATTR}]`)].forEach(e=>{let t=e.getAttribute(v.REPEAT_ITEM_TAG_ATTR),r;if(t&&(r=window.customElements.get(t)),!r){r=class extends i.BaseComponent{constructor(){super(),t||(this.style.display="contents")}};let o=e.innerHTML;r.template=o,r.reg(t)}for(;e.firstChild;)e.firstChild.remove();let n=e.getAttribute(v.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;e.firstChild;)e.firstChild.remove();return}let l=[...e.children],a,c=h=>{h.forEach((f,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(f)});else for(let p in f)l[m][p]=f[p];else{a||(a=new DocumentFragment);let p=new r;Object.assign(p.init$,f),a.appendChild(p)}}),a&&e.appendChild(a);let d=l.slice(h.length,l.length);for(let f of d)f.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let h=[];for(let d in o){let f=o[d];Object.defineProperty(f,"_KEY_",{value:d,enumerable:!0}),h.push(f)}c(h)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),e.removeAttribute(v.REPEAT_ATTR),e.removeAttribute(v.REPEAT_ITEM_TAG_ATTR)})}var fi="__default__";function br(s,i){if(i.shadowRoot)return;let e=[...s.querySelectorAll("slot")];if(!e.length)return;let t={};e.forEach(r=>{let n=r.getAttribute("name")||fi;t[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=fi;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=t[o])==null||n.fr.appendChild(r)}),Object.values(t).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 _r(s,i){[...s.querySelectorAll(`[${v.EL_REF_ATTR}]`)].forEach(e=>{let t=e.getAttribute(v.EL_REF_ATTR);i.ref[t]=e,e.removeAttribute(v.EL_REF_ATTR)})}function vr(s,i){[...s.querySelectorAll(`[${v.BIND_ATTR}]`)].forEach(e=>{let r=e.getAttribute(v.BIND_ATTR).split(";");[...e.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=mr(n.name.replace("-",""));r.push(o+":"+n.value),e.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(h=>h.trim()),l=o[0],a;l.indexOf(v.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(v.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(h=>h.trim());for(let h of c){let d;h.startsWith("!!")?(d="double",h=h.replace("!!","")):h.startsWith("!")&&(d="single",h=h.replace("!","")),i.sub(h,f=>{d==="double"?f=!!f:d==="single"&&(f=!f),a?(f==null?void 0:f.constructor)===Boolean?f?e.setAttribute(l,""):e.removeAttribute(l):e.setAttribute(l,f):qi(e,l,f)||(e[v.SET_LATER_KEY]||(e[v.SET_LATER_KEY]=Object.create(null)),e[v.SET_LATER_KEY][l]=f)})}}),e.removeAttribute(v.BIND_ATTR)})}var et="{{",Ve="}}",yr="skip-text";function Cr(s){let i,e=[],t=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(yr))&&r.textContent.includes(et)&&r.textContent.includes(Ve)&&1}});for(;i=t.nextNode();)e.push(i);return e}var wr=function(s,i){Cr(s).forEach(t=>{let r=[],n;for(;t.textContent.includes(Ve);)t.textContent.startsWith(et)?(n=t.textContent.indexOf(Ve)+Ve.length,t.splitText(n),r.push(t)):(n=t.textContent.indexOf(et),t.splitText(n)),t=t.nextSibling;r.forEach(o=>{let l=o.textContent.replace(et,"").replace(Ve,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Er=[gr,br,_r,vr,wr],it="'",ke='"',Ar=/\\([0-9a-fA-F]{1,6} ?)/g;function Tr(s){return(s[0]===ke||s[0]===it)&&(s[s.length-1]===ke||s[s.length-1]===it)}function $r(s){return(s[0]===ke||s[0]===it)&&(s=s.slice(1)),(s[s.length-1]===ke||s[s.length-1]===it)&&(s=s.slice(0,-1)),s}function Sr(s){let i="",e="";for(var t=0;t<s.length;t++){const r=s[t+1];s[t]==="\\"&&r==='"'?(i+='\\"',t++):s[t]==='"'&&e!=="\\"?i+='\\"':i+=s[t],e=s[t]}return i}function xr(s){let i=s;Tr(s)&&(i=$r(i),i=i.replace(Ar,(e,t)=>String.fromCodePoint(parseInt(t.trim(),16))),i=i.replaceAll(`\\
2
+ `,"\\n"),i=Sr(i),i=ke+i+ke);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var pi=0,$e=null,ie=null,ce=class extends HTMLElement{constructor(){super(),Rt(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let e=this.getCssData(this.__extractCssName(i),!0);e!==null&&this.$[i]!==e&&(this.$[i]=e)})}),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 ce}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let e;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(v.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)e=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,e=r.content.cloneNode(!0)}else this.constructor.__tpl&&(e=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(e,this)}let t=()=>{e&&(i&&this.shadowRoot.appendChild(e)||this.appendChild(e)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=t,this.shadowRoot.prepend(r)}else t()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Ae.generate(),this.style.setProperty(v.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(v.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(v.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=T.registerCtx({},this)),this.__localCtx}get nodeCtx(){return T.getCtx(this.ctxName,!1)||T.registerCtx({},this.ctxName)}static __parseProp(s,i){let e,t;if(s.startsWith(v.EXT_DATA_CTX_PRFX))e=i.nodeCtx,t=s.replace(v.EXT_DATA_CTX_PRFX,"");else if(s.includes(v.NAMED_DATA_CTX_SPLTR)){let r=s.split(v.NAMED_DATA_CTX_SPLTR);e=T.getCtx(r[0]),t=r[1]}else e=i.localCtx,t=s;return{ctx:e,name:t}}sub(s,i,e=!0){let t=n=>{this.isConnected&&i(n)},r=ce.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,t,e)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,t,e))})}notify(s){let i=ce.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=ce.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,e=!1){let t=ce.__parseProp(s,this);t.ctx.add(t.name,i,e)}add$(s,i=!1){for(let e in s)this.add(e,s[e],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,e,t)=>{let r=ce.__parseProp(e,this);return r.ctx.pub(r.name,t),!0},get:(i,e)=>{let t=ce.__parseProp(e,this);return t.ctx.read(t.name)}})}return this.__stateProxy}set$(s,i=!1){for(let e in s){let t=s[e];i||![String,Number,Boolean].includes(t==null?void 0:t.constructor)?this.$[e]=t:this.$[e]!==t&&(this.$[e]=t)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(v.CTX_OWNER_ATTR)&&this.getAttribute(v.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(v.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(v.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(v.NAMED_DATA_CTX_SPLTR)){let e=i.split(v.NAMED_DATA_CTX_SPLTR),t=e[0].trim(),r=e[1].trim();if(t&&r){let n=T.getCtx(t,!1);n||(n=T.registerCtx({},t)),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(v.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(v.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[v.SET_LATER_KEY]){for(let e in this[v.SET_LATER_KEY])qi(this,e,this[v.SET_LATER_KEY][e]);delete this[v.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let e of Er)this.addTemplateProcessor(e);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let e=this.getRootNode();if(!e)return;if(e==null?void 0:e.querySelector(`link[${v.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(v.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},e.nodeType===Node.DOCUMENT_NODE?e.head.appendChild(r):e.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);ie==null||ie.delete(this.updateCssData),ie!=null&&ie.size||($e==null||$e.disconnect(),$e=null,ie=null)},100)))}static reg(s,i=!1){s||(pi++,s=`${v.AUTO_TAG_PRFX}-${pi}`),this.__tag=s;let e=window.customElements.get(s);if(e){!i&&e!==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(`
3
+ `));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,e){var t;if(i===e)return;let r=(t=this.constructor.__attrDesc)==null?void 0:t[s];r?this.__dataCtxInitialized?this.$[r]=e:this.init$[r]=e:this[s]=e}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 e=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=xr(e)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,e)=>e===0?"":i).join("--")}__initStyleAttrObserver(){ie||(ie=new Set),ie.add(this.updateCssData),$e||($e=new MutationObserver(s=>{s[0].type==="attributes"&&ie.forEach(i=>{i()})}),$e.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let e=this.getCssData(this.__extractCssName(s),!0);e===null&&(e=i),this.add(s,e),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,e){let t="__"+s;this[t]=this[s],Object.defineProperty(this,s,{set:r=>{this[t]=r,e?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[t]}),this[s]=this[t]}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"}),e=URL.createObjectURL(i),t=document.createElement("link");t.href=e,t.rel="stylesheet",this.__rootStylesLink=t}}},at=ce;Rt(at,"template");function Gi(s,i){for(let e in i)e.includes("-")?s.style.setProperty(e,i[e]):s.style[e]=i[e]}function Ir(s,i){for(let e in i)i[e].constructor===Boolean?i[e]?s.setAttribute(e,""):s.removeAttribute(e):s.setAttribute(e,i[e])}function Mt(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&Ir(i,s.attributes),s.styles&&Gi(i,s.styles),s.properties)for(let e in s.properties)i[e]=s.properties[e];return s.processors&&s.processors.forEach(e=>{e(i)}),s.children&&s.children.forEach(e=>{let t=Mt(e);i.appendChild(t)}),i}var Xi="idb-store-ready",Or="symbiote-db",kr="symbiote-idb-update_",Lr=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(Xi,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return kr+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=e=>{this.db=e.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=t=>{this._notifyWhenReady(t)}},this.request.onsuccess=e=>{this.db=e.target.result,this._notifyWhenReady(e)},this.request.onerror=e=>{console.error(e)},this._subscriptionsMap={},this._updateHandler=e=>{e.key===this.name&&this._subscriptionsMap[e.newValue]&&this._subscriptionsMap[e.newValue].forEach(async r=>{r(await this.read(e.newValue))})},this._localUpdateHandler=e=>{this._updateHandler(e.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((t,r)=>{e.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?t(n.target.result._value):(t(null),console.warn(`IDB: cannot read "${s}"`))},e.onerror=n=>{r(n)}})}write(s,i,e=!1){let t={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(t);return new Promise((o,l)=>{n.onsuccess=a=>{e||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{t.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},t.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((e,t)=>{i.onsuccess=r=>{let n=r.target.result;e(n.map(o=>o._value))},i.onerror=r=>{t(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let e=this._subscriptionsMap[s];return e.add(i),{remove:()=>{e.delete(i),e.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Yi.clear(this.name)}},Yi=class{static get readyEventName(){return Xi}static open(s=Or,i="store"){let e=s+"/"+i;return this._reg[e]||(this._reg[e]=new Lr(s,i)),this._reg[e]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Rt(Yi,"_reg",Object.create(null));const Pr=20,I=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"});class Ur{constructor(i){u(this,"_timeoutStore",new Map);u(this,"_targets",new Set);u(this,"_debugPrint",null);this._debugPrint=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,e){var t;for(const r of this._targets)r.dispatchEvent(new CustomEvent(i,{detail:e}));(t=this._debugPrint)==null||t.call(this,()=>{const r=e&&typeof e=="object"?{...e}:e;return[`event "${i}"`,r]})}emit(i,e,{debounce:t}={}){if(typeof t!="number"&&!t){this._dispatch(i,typeof e=="function"?e():e);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));const r=typeof t=="number"?t:Pr,n=window.setTimeout(()=>{this._dispatch(i,typeof e=="function"?e():e),this._timeoutStore.delete(i)},r);this._timeoutStore.set(i,n)}}function H(s,i){let e;const t=(...r)=>{clearTimeout(e),e=setTimeout(()=>s(...r),i)};return t.cancel=()=>{clearTimeout(e)},t}const mi="--uploadcare-blocks-window-height";class st{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(mi)}}u(st,"clientsRegistry",new Set),u(st,"flush",H(()=>{document.documentElement.style.setProperty(mi,`${window.innerHeight}px`)},100));const Rr=s=>{var t;const i=new Intl.Locale(s);let e="ltr";return typeof i.getTextInfo=="function"&&i.getTextInfo().direction?e=i.getTextInfo().direction:"textInfo"in i&&((t=i.textInfo)!=null&&t.direction)&&(e=i.textInfo.direction),e},Ki=(s,i)=>new Intl.PluralRules(s).select(i),Mr=s=>s,xt="{{",Ji="}}",gi="plural:";function It(s,i,e={}){var o;let{openToken:t=xt,closeToken:r=Ji,transform:n=Mr}=e;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(t+l+r,typeof a=="string"?n(a):a)}return s}function Fr(s){const i=[];let e=s.indexOf(xt);for(;e!==-1;){const t=s.indexOf(Ji,e),r=s.substring(e+2,t);if(r.startsWith(gi)){const n=s.substring(e+2,t).replace(gi,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}e=s.indexOf(xt,t)}return i}const Dr=({element:s,attribute:i,onSuccess:e,onTimeout:t,timeout:r=300})=>{const n=s.getAttribute(i);if(n!==null){e(n);return}const o=new MutationObserver(c=>{const h=c[c.length-1];a(h)});o.observe(s,{attributes:!0,attributeFilter:[i]});const l=setTimeout(()=>{o.disconnect(),t()},r),a=c=>{const h=s.getAttribute(i);c.type==="attributes"&&c.attributeName===i&&h!==null&&(clearTimeout(l),o.disconnect(),e(h))}};function bi(s){return Object.prototype.toString.call(s)==="[object Object]"}const Nr=/\W|_/g;function zr(s){return s.split(Nr).map((i,e)=>i.charAt(0)[e>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function _i(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(e=>ae(e,{ignoreKeys:i})):s}function ae(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return _i(s,{ignoreKeys:i});if(!bi(s))return s;const e={};for(const t of Object.keys(s)){let r=s[t];if(i.includes(t)){e[t]=r;continue}bi(r)?r=ae(r,{ignoreKeys:i}):Array.isArray(r)&&(r=_i(r,{ignoreKeys:i})),e[zr(t)]=r}return e}const Vr=s=>new Promise(i=>setTimeout(i,s));function Zi({libraryName:s,libraryVersion:i,userAgent:e,publicKey:t="",integration:r=""}){const n="JavaScript";if(typeof e=="string")return e;if(typeof e=="function")return e({publicKey:t,libraryName:s,libraryVersion:i,languageName:n,integration:r});const o=[s,i,t].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}const Br={factor:2,time:100};function jr(s,i=Br){let e=0;function t(r){const n=Math.round(i.time*i.factor**e);return r({attempt:e,retry:l=>Vr(l??n).then(()=>(e+=1,t(r)))})}return t(s)}class Ft extends Error{}class qe extends Ft{constructor(e){super();u(this,"originalProgressEvent");this.name="NetworkError",this.message="Network error",Object.setPrototypeOf(this,qe.prototype),this.originalProgressEvent=e}}const ct=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))};class Ee extends Ft{constructor(e="Request canceled"){super(e);u(this,"isCancel",!0);this.name="CancelError",Object.setPrototypeOf(this,Ee.prototype)}}const Hr=500,Qi=({check:s,interval:i=Hr,timeout:e,signal:t})=>new Promise((r,n)=>{let o,l;ct(t,()=>{o&&clearTimeout(o),n(new Ee("Poll cancelled"))}),e&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ee("Timed out"))},e));const a=()=>{try{Promise.resolve(s(t)).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)}),A={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"},ht="application/octet-stream",es="original",ge=({method:s,url:i,data:e,headers:t={},signal:r,onProgress:n})=>new Promise((o,l)=>{const a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET";let h=!1;a.open(c,i,!0),t&&Object.entries(t).forEach(d=>{const[f,m]=d;typeof m<"u"&&!Array.isArray(m)&&a.setRequestHeader(f,m)}),a.responseType="text",ct(r,()=>{h=!0,a.abort(),l(new Ee)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{const d={method:c,url:i,data:e,headers:t||void 0,signal:r,onProgress:n},f=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};f.forEach(function(w){const E=w.split(": "),b=E.shift(),y=E.join(": ");b&&typeof b<"u"&&(m[b]=y)});const p=a.response,g=a.status;o({request:d,data:p,headers:m,status:g})}},a.onerror=d=>{h||l(new qe(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),e?a.send(e):a.send()});function Wr(s,...i){return s}const qr=({name:s})=>s?[s]:[],Gr=Wr;var Xr=()=>new FormData;const ts=s=>!1,ut=s=>typeof Blob<"u"&&s instanceof Blob,dt=s=>typeof File<"u"&&s instanceof File,ft=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",Ue=s=>ut(s)||dt(s)||ts()||ft(s),Yr=s=>typeof s=="string"||typeof s=="number"||typeof s>"u",Kr=s=>!!s&&typeof s=="object"&&!Array.isArray(s),Jr=s=>!!s&&typeof s=="object"&&"data"in s&&Ue(s.data);function is(s,i,e){if(Array.isArray(e))for(const t of e)is(s,`${i}[]`,t);else if(Jr(e)){const{name:t,contentType:r}=e,n=Gr(e.data,t,r??ht),o=qr({name:t,contentType:r});s.push([i,n,...o])}else if(Kr(e))for(const[t,r]of Object.entries(e))typeof r<"u"&&s.push([`${i}[${t}]`,String(r)]);else Yr(e)&&e&&s.push([i,e.toString()])}function Zr(s){const i=[];for(const[e,t]of Object.entries(s))is(i,e,t);return i}function pt(s){const i=Xr(),e=Zr(s);for(const t of e){const[r,n,...o]=t;i.append(r,n,...o)}return i}class N extends Ft{constructor(e,t,r,n,o){super();u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadError",this.message=e,this.code=t,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,N.prototype)}}const Qr=s=>{const i=new URLSearchParams;for(const[e,t]of Object.entries(s))t&&typeof t=="object"&&!Array.isArray(t)?Object.entries(t).filter(r=>r[1]??!1).forEach(r=>i.set(`${e}[${r[0]}]`,String(r[1]))):Array.isArray(t)?t.forEach(r=>{i.append(`${e}[]`,r)}):typeof t=="string"&&t?i.set(e,t):typeof t=="number"&&i.set(e,t.toString());return i.toString()},oe=(s,i,e)=>{const t=new URL(s);return t.pathname=(t.pathname+i).replace("//","/"),e&&(t.search=Qr(e)),t.toString()};var en="6.14.1";const tn="UploadcareUploadClient",sn=en;function Te(s){return Zi({libraryName:tn,libraryVersion:sn,...s})}const rn="RequestThrottledError",vi=15e3,nn=1e3;function on(s){const{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return vi;const e=parseInt(i["retry-after"],10);return Number.isFinite(e)?e*1e3:vi}function be(s,i){const{retryThrottledRequestMaxTimes:e,retryNetworkErrorMaxTimes:t}=i;return jr(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===rn&&r<e)return n(on(o));if(o instanceof qe&&r<t)return n((r+1)*nn);throw o}))}const ss=s=>{let i="";return(ut(s)||dt(s)||ft(s))&&(i=s.type),i||ht},rs=s=>{let i="";return dt(s)&&s.name?i=s.name:ut(s)||ts()?i="":ft(s)&&s.name&&(i=s.name),i||es};function Dt(s){return typeof s>"u"||s==="auto"?"auto":s?"1":"0"}function ln(s,{publicKey:i,fileName:e,contentType:t,baseURL:r=A.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:h="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=A.retryNetworkErrorMaxTimes,metadata:g}){return be(()=>ge({method:"POST",url:oe(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Te({publicKey:i,integration:d,userAgent:f})},data:pt({file:{data:s,name:e||rs(s),contentType:t||ss(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Dt(l),signature:n,expire:o,source:h,metadata:g}),signal:a,onProgress:c}).then(({data:w,headers:E,request:b})=>{const y=ae(JSON.parse(w));if("error"in y)throw new N(y.error.content,y.error.errorCode,b,y,E);return y}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var Ot;(function(s){s.Token="token",s.FileInfo="file_info"})(Ot||(Ot={}));function an(s,{publicKey:i,baseURL:e=A.baseURL,store:t,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=A.retryNetworkErrorMaxTimes,metadata:g}){return be(()=>ge({method:"POST",headers:{"X-UC-User-Agent":Te({publicKey:i,integration:d,userAgent:f})},url:oe(e,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Dt(t),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:g}),signal:h}).then(({data:w,headers:E,request:b})=>{const y=ae(JSON.parse(w));if("error"in y)throw new N(y.error.content,y.error.errorCode,b,y,E);return y}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var D;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(D||(D={}));const cn=s=>"status"in s&&s.status===D.Error;function hn(s,{publicKey:i,baseURL:e=A.baseURL,signal:t,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=A.retryNetworkErrorMaxTimes}={}){return be(()=>ge({method:"GET",headers:i?{"X-UC-User-Agent":Te({publicKey:i,integration:r,userAgent:n})}:void 0,url:oe(e,"/from_url/status/",{jsonerrors:1,token:s}),signal:t}).then(({data:a,headers:c,request:h})=>{const d=ae(JSON.parse(a));if("error"in d&&!cn(d))throw new N(d.error.content,d.error.errorCode,h,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function un(s,{publicKey:i,baseURL:e=A.baseURL,jsonpCallback:t,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=A.retryNetworkErrorMaxTimes}){return be(()=>ge({method:"POST",headers:{"X-UC-User-Agent":Te({publicKey:i,integration:a,userAgent:c})},url:oe(e,"/group/",{jsonerrors:1}),data:pt({files:s,callback:t,pub_key:i,signature:r,expire:n,source:l}),signal:o}).then(({data:f,headers:m,request:p})=>{const g=ae(JSON.parse(f));if("error"in g)throw new N(g.error.content,g.error.errorCode,p,g,m);return g}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function ns(s,{publicKey:i,baseURL:e=A.baseURL,signal:t,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return be(()=>ge({method:"GET",headers:{"X-UC-User-Agent":Te({publicKey:i,integration:n,userAgent:o})},url:oe(e,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:t}).then(({data:c,headers:h,request:d})=>{const f=ae(JSON.parse(c));if("error"in f)throw new N(f.error.content,f.error.errorCode,d,f,h);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function dn(s,{publicKey:i,contentType:e,fileName:t,multipartChunkSize:r=A.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:h="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=A.retryNetworkErrorMaxTimes,metadata:g}){return be(()=>ge({method:"POST",url:oe(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Te({publicKey:i,integration:d,userAgent:f})},data:pt({filename:t||es,size:s,content_type:e||ht,part_size:r,UPLOADCARE_STORE:Dt(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:h,metadata:g}),signal:c}).then(({data:w,headers:E,request:b})=>{const y=ae(JSON.parse(w));if("error"in y)throw new N(y.error.content,y.error.errorCode,b,y,E);return y.parts=Object.keys(y.parts).map(U=>y.parts[Number(U)]),y}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})}function fn(s,i,{contentType:e,signal:t,onProgress:r,retryThrottledRequestMaxTimes:n=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=A.retryNetworkErrorMaxTimes}){return be(()=>ge({method:"PUT",url:i,data:s,onProgress:r,signal:t,headers:{"Content-Type":e||ht}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function pn(s,{publicKey:i,baseURL:e=A.baseURL,source:t="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=A.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=A.retryNetworkErrorMaxTimes}){return be(()=>ge({method:"POST",url:oe(e,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Te({publicKey:i,integration:n,userAgent:o})},data:pt({uuid:s,UPLOADCARE_PUB_KEY:i,source:t}),signal:r}).then(({data:c,headers:h,request:d})=>{const f=ae(JSON.parse(c));if("error"in f)throw new N(f.error.content,f.error.errorCode,d,f,h);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Nt(s,{publicKey:i,baseURL:e,source:t,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return Qi({check:h=>ns(s,{publicKey:i,baseURL:e,signal:h,source:t,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}function mn(s){return"defaultEffects"in s}class Re{constructor(i,{baseCDN:e=A.baseCDN,fileName:t}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);u(this,"defaultEffects",null);const{uuid:r,s3Bucket:n}=i,o=oe(e,`${r}/`),l=n?oe(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=t||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,mn(i)&&(this.defaultEffects=i.defaultEffects)}}const gn=(s,{publicKey:i,fileName:e,baseURL:t,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,baseCDN:g,metadata:w})=>ln(s,{publicKey:i,fileName:e,contentType:l,baseURL:t,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:w}).then(({file:E})=>Nt(E,{publicKey:i,baseURL:t,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:c,signal:a})).then(E=>new Re(E,{baseCDN:g})),bn=(s,{publicKey:i,fileName:e,baseURL:t,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h,baseCDN:d})=>ns(s,{publicKey:i,baseURL:t,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:h}).then(f=>new Re(f,{baseCDN:d,fileName:e})).then(f=>(n&&n({isComputable:!0,value:1}),f)),_n=(s,{signal:i}={})=>{let e=null,t=null;const r=s.map(()=>new AbortController),n=o=>()=>{t=o,r.forEach((l,a)=>a!==o&&l.abort())};return ct(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{const a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(e=c,null))})).then(o=>{if(t===null)throw e;return o[t]})};var vn=window.WebSocket;class yn{constructor(){u(this,"events",Object.create({}))}emit(i,e){var t;(t=this.events[i])==null||t.forEach(r=>r(e))}on(i,e){this.events[i]=this.events[i]||[],this.events[i].push(e)}off(i,e){e?this.events[i]=this.events[i].filter(t=>t!==e):this.events[i]=[]}}const Cn=(s,i)=>s==="success"?{status:D.Success,...i}:s==="progress"?{status:D.Progress,...i}:{status:D.Error,...i};class wn{constructor(i,e=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new yn);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=e}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){const i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new vn(i),this.ws.addEventListener("error",e=>{this.emmitter.emit("error",new Error(e.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(e=>this.send(e.event,e.data)),this.queue=[]}),this.ws.addEventListener("message",e=>{const t=JSON.parse(e.data.toString());switch(t.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(t.channel,Cn(t.event,JSON.parse(t.data)))}})}}disconnect(){const i=()=>{var e;(e=this.ws)==null||e.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,e){var r;const t=JSON.stringify({event:i,data:e});(r=this.ws)==null||r.send(t)}subscribe(i,e){this.subscribers+=1,this.connect();const t=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:t}};this.emmitter.on(t,e),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;const e=`task-status-${i}`,t={event:"pusher:unsubscribe",data:{channel:e}};this.emmitter.off(e),this.isConnected?this.send(t.event,t.data):this.queue=this.queue.filter(r=>r.data.channel!==e),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}}let Ct=null;const zt=s=>{if(!Ct){const i=typeof window>"u"?0:3e4;Ct=new wn(s,i)}return Ct},En=s=>{zt(s).connect()};function An({token:s,publicKey:i,baseURL:e,integration:t,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return Qi({check:c=>hn(s,{publicKey:i,baseURL:e,integration:t,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(h=>{switch(h.status){case D.Error:return new N(h.error,h.errorCode);case D.Waiting:return!1;case D.Unknown:return new N(`Token "${s}" was not found.`);case D.Progress:return l&&(h.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:h.done/h.total})),!1;case D.Success:return l&&l({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:a})}const Tn=({token:s,pusherKey:i,signal:e,onProgress:t})=>new Promise((r,n)=>{const o=zt(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};ct(e,()=>{a(),n(new Ee("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case D.Progress:{t&&(c.total==="unknown"?t({isComputable:!1}):t({isComputable:!0,value:c.done/c.total}));break}case D.Success:{a(),t&&t({isComputable:!0,value:c.done/c.total}),r(c);break}case D.Error:a(),n(new N(c.msg,c.error_code))}})}),$n=(s,{publicKey:i,fileName:e,baseURL:t,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:h,onProgress:d,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:g,pusherKey:w=A.pusherKey,metadata:E})=>Promise.resolve(En(w)).then(()=>an(s,{publicKey:i,fileName:e,baseURL:t,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:h,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:g,metadata:E})).catch(b=>{const y=zt(w);return y==null||y.disconnect(),Promise.reject(b)}).then(b=>b.type===Ot.FileInfo?b:_n([({signal:y})=>An({token:b.token,publicKey:i,baseURL:t,integration:m,userAgent:p,retryThrottledRequestMaxTimes:g,onProgress:d,signal:y}),({signal:y})=>Tn({token:b.token,pusherKey:w,signal:y,onProgress:d})],{signal:h})).then(b=>{if(b instanceof N)throw b;return b}).then(b=>Nt(b.uuid,{publicKey:i,baseURL:t,integration:m,userAgent:p,retryThrottledRequestMaxTimes:g,onProgress:d,signal:h})).then(b=>new Re(b,{baseCDN:r})),wt=new WeakMap,Sn=async s=>{if(wt.has(s))return wt.get(s);const i=await fetch(s.uri).then(e=>e.blob());return wt.set(s,i),i},os=async s=>{if(dt(s)||ut(s))return s.size;if(ft(s))return(await Sn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},xn=(s,i=A.multipartMinFileSize)=>s>=i,ls=s=>{const i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",e=new RegExp(i);return!Ue(s)&&e.test(s)},Vt=s=>{const i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",e=new RegExp(i);return!Ue(s)&&e.test(s)},In=(s,i)=>new Promise((e,t)=>{const r=[];let n=!1,o=i.length;const l=[...i],a=()=>{const c=i.length-l.length,h=l.shift();h&&h().then(d=>{n||(r[c]=d,o-=1,o?a():e(r))}).catch(d=>{n=!0,t(d)})};for(let c=0;c<s;c++)a()}),On=(s,i,e,t)=>{const r=t*i,n=Math.min(r+t,e);return s.slice(r,n)},kn=async(s,i,e)=>t=>On(s,t,i,e),Ln=(s,i,{publicKey:e,contentType:t,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>fn(s,i,{publicKey:e,contentType:t,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Pn=async(s,{publicKey:i,fileName:e,fileSize:t,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,contentType:g,multipartChunkSize:w=A.multipartChunkSize,maxConcurrentRequests:E=A.maxConcurrentRequests,baseCDN:b,metadata:y})=>{const U=t??await os(s);let ee;const _e=(k,R)=>{if(!c)return;ee||(ee=Array(k).fill(0));const W=X=>X.reduce((te,yt)=>te+yt,0);return X=>{X.isComputable&&(ee[R]=X.value,c({isComputable:!0,value:W(ee)/k}))}};return g||(g=ss(s)),dn(U,{publicKey:i,contentType:g,fileName:e||rs(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:y}).then(async({uuid:k,parts:R})=>{const W=await kn(s,U,w);return Promise.all([k,In(E,R.map((X,te)=>()=>Ln(W(te),X,{publicKey:i,contentType:g,onProgress:_e(R.length,te),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})))])}).then(([k])=>pn(k,{publicKey:i,baseURL:r,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})).then(k=>k.isReady?k:Nt(k.uuid,{publicKey:i,baseURL:r,source:h,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:c,signal:a})).then(k=>new Re(k,{baseCDN:b}))};async function as(s,{publicKey:i,fileName:e,baseURL:t=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartMinFileSize:g,multipartChunkSize:w,maxConcurrentRequests:E,baseCDN:b=A.baseCDN,checkForUrlDuplicates:y,saveUrlForRecurrentUploads:U,pusherKey:ee,metadata:_e}){if(Ue(s)){const k=await os(s);return xn(k,g)?Pn(s,{publicKey:i,contentType:p,multipartChunkSize:w,fileSize:k,fileName:e,baseURL:t,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,maxConcurrentRequests:E,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:_e}):gn(s,{publicKey:i,fileName:e,contentType:p,baseURL:t,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:_e})}if(Vt(s))return $n(s,{publicKey:i,fileName:e,baseURL:t,baseCDN:b,checkForUrlDuplicates:y,saveUrlForRecurrentUploads:U,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,pusherKey:ee,metadata:_e});if(ls(s))return bn(s,{publicKey:i,fileName:e,baseURL:t,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b});throw new TypeError(`File uploading from "${s}" is not supported`)}class Un{constructor(i,{baseCDN:e=A.baseCDN}={}){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount;const t=i.files.filter(Boolean);this.totalSize=Object.values(t).reduce((r,n)=>r+n.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(t).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t.map(r=>new Re(r,{baseCDN:e})),this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}}const Rn=s=>{for(const i of s)if(!Ue(i))return!1;return!0},Mn=s=>{for(const i of s)if(!ls(i))return!1;return!0},Fn=s=>{for(const i of s)if(!Vt(i))return!1;return!0};function Dn(s,{publicKey:i,fileName:e,baseURL:t=A.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:g=A.multipartChunkSize,baseCDN:w=A.baseCDN,checkForUrlDuplicates:E,saveUrlForRecurrentUploads:b,jsonpCallback:y}){if(!Rn(s)&&!Fn(s)&&!Mn(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let U,ee=!0;const _e=s.length,k=(R,W)=>{if(!a)return;U||(U=Array(R).fill(0));const X=te=>te.reduce((yt,ar)=>yt+ar)/R;return te=>{if(!te.isComputable||!ee){ee=!1,a({isComputable:!1});return}U[W]=te.value,a({isComputable:!0,value:X(U)})}};return Promise.all(s.map((R,W)=>Ue(R)||Vt(R)?as(R,{publicKey:i,fileName:e,baseURL:t,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:k(_e,W),source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:g,baseCDN:w,checkForUrlDuplicates:E,saveUrlForRecurrentUploads:b}).then(X=>X.uuid):R)).then(R=>un(R,{publicKey:i,baseURL:t,jsonpCallback:y,secureSignature:r,secureExpire:n,signal:l,source:c,integration:h,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m}).then(W=>new Un(W,{baseCDN:w})).then(W=>(a&&a({isComputable:!0,value:1}),W)))}class Nn{constructor(i){u(this,"_concurrency",1);u(this,"_pending",[]);u(this,"_running",0);u(this,"_resolvers",new Map);u(this,"_rejectors",new Map);this._concurrency=i}_run(){const i=this._concurrency-this._running;for(let e=0;e<i;e++){const t=this._pending.shift();if(!t)return;const r=this._resolvers.get(t),n=this._rejectors.get(t);if(!r||!n)throw new Error("Unexpected behavior: resolver or rejector is undefined");this._running+=1,t().finally(()=>{this._resolvers.delete(t),this._rejectors.delete(t),this._running-=1,this._run()}).then(o=>r(o)).catch(o=>n(o))}}add(i){return new Promise((e,t)=>{this._resolvers.set(i,e),this._rejectors.set(i,t),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}}const cs=()=>({}),hs=s=>({...cs(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),us=s=>({...hs(s),"*commonProgress":0,"*uploadList":[],"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Nn(1),"*uploadCollection":null,"*collectionErrors":[],"*collectionState":null,"*groupInfo":null,"*uploadTrigger":new Set}),Bt={"locale-id":"en","social-source-lang":"en","upload-file":"Upload file","upload-files":"Upload files","choose-file":"Choose file","choose-files":"Choose files","drop-files-here":"Drop files here","select-file-source":"Select file source",selected:"Selected",upload:"Upload","add-more":"Add more",cancel:"Cancel","start-from-cancel":"Cancel",clear:"Clear","camera-shot":"Shot","upload-url":"Import","upload-url-placeholder":"Paste link here","edit-image":"Edit image","edit-detail":"Details",back:"Back",done:"Done",ok:"Ok","remove-from-list":"Remove",no:"No",yes:"Yes","confirm-your-action":"Confirm your action","are-you-sure":"Are you sure?","selected-count":"Selected:","upload-error":"Upload error","validation-error":"Validation error","no-files":"No files selected",browse:"Browse","not-uploaded-yet":"Not uploaded yet...",file__one:"file",file__other:"files",error__one:"error",error__other:"errors","header-uploading":"Uploading {{count}} {{plural:file(count)}}","header-failed":"{{count}} {{plural:error(count)}}","header-succeed":"{{count}} {{plural:file(count)}} uploaded","header-total":"{{count}} {{plural:file(count)}} selected","src-type-local":"From device","src-type-from-url":"From link","src-type-camera":"Camera","src-type-draw":"Draw","src-type-facebook":"Facebook","src-type-dropbox":"Dropbox","src-type-gdrive":"Google Drive","src-type-gphotos":"Google Photos","src-type-instagram":"Instagram","src-type-flickr":"Flickr","src-type-vk":"VK","src-type-evernote":"Evernote","src-type-box":"Box","src-type-onedrive":"Onedrive","src-type-huddle":"Huddle","src-type-other":"Other","caption-from-url":"Import from link","caption-camera":"Camera","caption-draw":"Draw","caption-edit-file":"Edit file","file-no-name":"No name...","toggle-fullscreen":"Toggle fullscreen","toggle-guides":"Toggle guides",rotate:"Rotate","flip-vertical":"Flip vertical","flip-horizontal":"Flip horizontal",apply:"Apply",brightness:"Brightness",contrast:"Contrast",saturation:"Saturation",exposure:"Exposure",gamma:"Gamma",vibrance:"Vibrance",warmth:"Warmth",enhance:"Enhance",original:"Original",resize:"Resize image",crop:"Crop","select-color":"Select color",text:"Text",draw:"Draw","cancel-edit":"Cancel edit","tab-view":"Preview","tab-details":"Details","file-name":"Name","file-size":"Size","cdn-url":"CDN URL","file-size-unknown":"Unknown","camera-permissions-denied":"Camera access denied","camera-permissions-prompt":"Please allow access to the camera","camera-permissions-request":"Request access","files-count-limit-error-title":"Files count limit overflow","files-count-limit-error-too-few":"You’ve chosen {{total}} {{plural:file(total)}}. At least {{min}} {{plural:file(min)}} required.","files-count-limit-error-too-many":"You’ve chosen too many files. {{max}} {{plural:file(max)}} is maximum.","files-max-size-limit-error":"File is too big. Max file size is {{maxFileSize}}.","has-validation-errors":"File validation error ocurred. Please, check your files before upload.","images-only-accepted":"Only image files are accepted.","file-type-not-allowed":"Uploading of these file types is not allowed.","some-files-were-not-uploaded":"Some files were not uploaded."},rt=new Map,kt=new Map,ds=(s,i)=>{rt.has(s)&&console.log(`Locale ${s} is already defined. Overwriting...`),rt.set(s,{...Bt,...i})},zn=(s,i)=>{kt.set(s,i)},fs=(s,i)=>{typeof i=="function"?zn(s,i):ds(s,i)},Vn=async s=>{if(!rt.has(s)){if(!kt.has(s))throw new Error(`Locale ${s} is not defined`);const e=await kt.get(s)();ds(s,e)}return rt.get(s)};fs("en",Bt);const Ce=s=>`*l10n/${s}`,Bn="en";class jn{constructor(i){u(this,"_blockInstance",null);u(this,"_localeName","");u(this,"_callbacks",new Set);u(this,"_boundBlocks",new Map);this._blockInstance=i;for(let[e,t]of Object.entries(Bt))this._blockInstance.add(Ce(e),t,!1);setTimeout(()=>{i.subConfigValue("localeName",async e=>{var n;if(!this._blockInstance||!e)return;this._localeName=e;const t=await Vn(e);if(e!==Bn&&this._localeName!==e)return;const r=(n=this._blockInstance.cfg.localeDefinitionOverride)==null?void 0:n[e];for(const[o,l]of Object.entries(t)){const a=r==null?void 0:r[o];this._blockInstance.add(Ce(o),a??l,!0);for(const c of this._callbacks)c()}}),i.subConfigValue("localeDefinitionOverride",e=>{var r;if(!e)return;const t=e[this._localeName];if(t)for(const[n,o]of Object.entries(t)){(r=this._blockInstance)==null||r.add(Ce(n),o,!0);for(const l of this._callbacks)l()}})})}onLocaleChange(i){const e=H(i,0);return this._callbacks.add(e),()=>{this._callbacks.delete(e)}}bindL10n(i,e,t){var n,o,l;i.$[e]=t(),this._boundBlocks.has(i)||this._boundBlocks.set(i,new Map),(o=(n=this._boundBlocks.get(i))==null?void 0:n.get(e))==null||o();const r=this.onLocaleChange(()=>{i.$[e]=t()});(l=this._boundBlocks.get(i))==null||l.set(e,r)}destroyL10nBindings(i){const e=this._boundBlocks.get(i);if(e){for(const t of e.values())t();this._boundBlocks.delete(i)}}destroy(){this._callbacks.clear()}}function Hn(s,i){[...s.querySelectorAll("[l10n]")].forEach(e=>{let t=e.getAttribute("l10n");if(!t)return;let r="textContent",n=!1;if(t.includes(":")){const a=t.split(":");r=a[0],t=a[1],r.startsWith("@")&&(r=r.slice(1),n=!0)}const o=t;i.has(o)&&i.sub(o,a=>{if(!a)return;i.l10nProcessorSubs.has(o)||i.l10nProcessorSubs.set(o,new Set);const c=i.l10nProcessorSubs.get(o);c==null||c.forEach(f=>{f.remove(),c.delete(f),i.allSubs.delete(f)});const h=Ce(a).replace("*","");i.nodeCtx.has(h)||i.nodeCtx.add(h,a);const d=i.nodeCtx.sub(h,()=>{e[r]=i.l10n(a)});c==null||c.add(d),i.allSubs.add(d),e.removeAttribute("l10n")});const l=Ce(t);i.has(l)||i.add(l,""),i.sub(l,()=>{t=t,n?e.setAttribute(r,i.l10n(t)):e[r]=i.l10n(t)}),e.removeAttribute("l10n")})}const B=s=>`*cfg/${s}`,jt="blocks",Ht="0.39.1",ps=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},Wt=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>ps(i)).join("/-/"),pe=(...s)=>{let i=Wt(...s);return i?`-/${i}/`:""};function ms(s){let i=new URL(s),e=i.pathname+i.search+i.hash,t=e.lastIndexOf("http"),r=e.lastIndexOf("/"),n="";return t>=0?n=e.slice(t):r>=0&&(n=e.slice(r+1)),n}function Wn(s){let i=new URL(s),{pathname:e}=i;const t=e.indexOf("/"),r=e.indexOf("/",t+1);return e.substring(t+1,r)}function qn(s){let i=gs(s),e=new URL(i),t=e.pathname.indexOf("/-/");return t===-1?[]:e.pathname.substring(t).split("/-/").filter(Boolean).map(n=>ps(n))}function gs(s){let i=new URL(s),e=ms(s),t=bs(e)?_s(e).pathname:e;return i.pathname=i.pathname.replace(t,""),i.search="",i.hash="",i.toString()}function bs(s){return s.startsWith("http")}function _s(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}const j=(s,i,e)=>{let t=new URL(gs(s));if(e=e||ms(s),t.pathname.startsWith("//")&&(t.pathname=t.pathname.replace("//","/")),bs(e)){let r=_s(e);t.pathname=t.pathname+(i||"")+(r.pathname||""),t.search=r.search,t.hash=r.hash}else t.pathname=t.pathname+(i||"")+(e||"");return t.toString()},He=(s,i)=>{let e=new URL(s);return e.pathname=i+"/",e.toString()},le=(s,i=",")=>s.trim().split(i).map(e=>e.trim()).filter(e=>e.length>0),V=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}),vs=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function Gn(s,i){if(typeof i=="number"){const e=i;return V[s]!==e?`${s}/${e}`:""}if(typeof i=="boolean"){const e=i;return V[s]!==e?`${s}`:""}if(s==="filter"&&i){const{name:e,amount:t}=i;return V.filter===t?"":`${s}/${e}/${t}`}if(s==="crop"&&i){let{dimensions:e,coords:t}=i;return`${s}/${e.join("x")}/${t.join(",")}`}return""}function mt(s){return Wt(...vs.filter(i=>typeof s[i]<"u"&&s[i]!==null).map(i=>{let e=s[i];return Gn(i,e)}).filter(i=>!!i))}const ys=Wt("format/auto","progressive/yes"),se=([s])=>typeof s<"u"?Number(s):void 0,yi=()=>!0,Xn=([s,i])=>({name:s,amount:typeof i<"u"?Number(i):100}),Yn=([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:le(s,"x").map(Number),coords:le(i).map(Number)}},Kn=Object.freeze({enhance:se,brightness:se,exposure:se,gamma:se,contrast:se,saturation:se,vibrance:se,warmth:se,filter:Xn,mirror:yi,flip:yi,rotate:se,crop:Yn});function Jn(s){const i={};for(const e of s){const[t,...r]=e.split("/");if(!vs.includes(t))continue;const n=t,o=Kn[n];try{const l=o(r);i[n]=l}catch(l){console.warn([`Failed to parse URL operation "${e}". 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(`
4
+ `))}}return i}const P=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),Q=[P.CROP,P.TUNING,P.FILTERS],Zn=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],Qn=["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"],eo=["rotate","mirror","flip"],Le=Object.freeze({brightness:{zero:V.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:V.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:V.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:V.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:V.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:V.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:V.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:V.enhance,range:[0,100],keypointsNumber:1},filter:{zero:V.filter,range:[0,100],keypointsNumber:1}}),to=s=>s?s.split(",").map(i=>i.trim()):[],qt=s=>s?s.join(","):"",io="https://ucarecdn.com",so="https://upload.uploadcare.com",ro="https://social.uploadcare.com",ue={pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,cameraCapture:"",sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:qt(Q),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:io,baseUrl:so,socialBaseUrl:ro,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,localeName:"en",localeDefinitionOverride:null},Et="lr-";class $ extends at{constructor(){super();u(this,"requireCtxName",!1);u(this,"allowCustomTemplate",!0);u(this,"activityType",null);u(this,"init$",cs());this.l10nProcessorSubs=new Map,this.addTemplateProcessor(Hn)}l10n(e,t={}){if(!e)return"";let r=this.$[Ce(e)]||e,n=Fr(r);for(let l of n)t[l.variable]=this.pluralize(l.pluralKey,Number(t[l.countVariable]));return It(r,t)}pluralize(e,t){const r=this.l10n("locale-id")||"en",n=Ki(r,t);return this.l10n(`${e}__${n}`)}bindL10n(e,t){var r;(r=this.localeManager)==null||r.bindL10n(this,e,t)}emit(e,t,r){const n=this.has("*eventEmitter")&&this.$["*eventEmitter"];n&&n.emit(e,t,r)}hasBlockInCtx(e){let t=this.$["*blocksRegistry"];for(let r of t)if(e(r))return!0;return!1}setOrAddState(e,t){this.add$({[e]:t},!0)}setActivity(e){if(this.hasBlockInCtx(t=>t.activityType===e)){this.$["*currentActivity"]=e;return}console.warn(`Activity type "${e}" not found in the context`)}connectedCallback(){const e=this.constructor.className;e&&this.classList.toggle(`${Et}${e}`,!0),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.requireCtxName?Dr({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.has("*blocksRegistry")||this.add("*blocksRegistry",new Set),this.$["*blocksRegistry"].add(this),this.has("*eventEmitter")||this.add("*eventEmitter",new Ur(this.debugPrint.bind(this))),this.has("*localeManager")||this.add("*localeManager",new jn(this)),this.sub(Ce("locale-id"),t=>{this.style.direction=Rr(t)})}get localeManager(){return this.has("*localeManager")?this.$["*localeManager"]:null}destroyCallback(){var t;let e=this.$["*blocksRegistry"];e.delete(this),(t=this.localeManager)==null||t.destroyL10nBindings(this),this.l10nProcessorSubs=new Map,T.deleteCtx(this),e.size===0&&setTimeout(()=>{this.destroyCtxCallback()},0)}destroyCtxCallback(){var e;T.deleteCtx(this.ctxName),(e=this.localeManager)==null||e.destroy()}fileSizeFmt(e,t=2){let r=["B","KB","MB","GB","TB"];if(e===0)return`0 ${r[0]}`;let n=1024,o=t<0?0:t,l=Math.floor(Math.log(e)/Math.log(n));return parseFloat((e/n**l).toFixed(o))+" "+r[l]}proxyUrl(e){let t=this.cfg.secureDeliveryProxy;return t?It(t,{previewUrl:e},{transform:r=>window.encodeURIComponent(r)}):e}get cfg(){if(!this.__cfgProxy){let e=Object.create(null);this.__cfgProxy=new Proxy(e,{set:(t,r,n)=>{if(typeof r!="string")return!1;const o=B(r);return this.has(o)||this.add(o,ue[r]),this.$[o]=n,!0},get:(t,r)=>{const n=B(r);return this.has(n)||this.add(n,ue[r]),this.$[B(r)]}})}return this.__cfgProxy}subConfigValue(e,t){const r=B(e);this.has(r)||this.add(r,ue[e]),this.sub(r,t)}debugPrint(...e){if(!this.cfg.debug)return;let t=e;if(typeof(e==null?void 0:e[0])=="function"){const r=e[0];t=r()}console.log(`[${this.ctxName}]`,...t)}static reg(e){if(!e){super.reg();return}super.reg(e.startsWith(Et)?e:Et+e)}}u($,"StateConsumerScope",null),u($,"className","");const Ci="active",Fe="___ACTIVITY_IS_ACTIVE___",re=class re extends ${constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",hs(this));u(this,"_debouncedHistoryFlush",H(this._historyFlush.bind(this),10))}_deactivate(){var t;let e=re._activityCallbacks.get(this);this[Fe]=!1,this.removeAttribute(Ci),(t=e==null?void 0:e.deactivateCallback)==null||t.call(e)}_activate(){var t;let e=re._activityCallbacks.get(this);this.$["*historyBack"]=this.historyBack.bind(this),this[Fe]=!0,this.setAttribute(Ci,""),(t=e==null?void 0:e.activateCallback)==null||t.call(e),this._debouncedHistoryFlush(),this.emit(I.ACTIVITY_CHANGE,{activity:this.activityType})}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",e=>{this.setAttribute("current-activity",e)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",e=>{this.activityType!==e&&this[Fe]?this._deactivate():this.activityType===e&&!this[Fe]&&this._activate(),e||(this.$["*history"]=[])}),this.has("*modalActive")&&this.sub("*modalActive",e=>{!e&&this.activityType===this.$["*currentActivity"]&&(this.$["*currentActivity"]=null)}))}_historyFlush(){let e=this.$["*history"];e&&(e.length>10&&(e=e.slice(e.length-11,e.length-1)),this.historyTracked&&e[e.length-1]!==this.activityType&&e.push(this.activityType),this.$["*history"]=e)}_isActivityRegistered(){return this.activityType&&re._activityCallbacks.has(this)}get isActivityActive(){return this[Fe]}get couldOpenActivity(){return!0}registerActivity(e,t={}){const{onActivate:r,onDeactivate:n}=t;re._activityCallbacks.set(this,{activateCallback:r,deactivateCallback:n})}unregisterActivity(){this.isActivityActive&&this._deactivate(),re._activityCallbacks.delete(this)}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity();const e=this.$["*currentActivity"];!![...this.$["*blocksRegistry"]].find(n=>n instanceof re&&n.activityType===e)||(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(){let e=this.$["*history"];if(e){let t=e.pop();for(;t===this.activityType;)t=e.pop();let r=!!t;if(t){const o=[...this.$["*blocksRegistry"]].find(l=>l.activityType===t);r=(o==null?void 0:o.couldOpenActivity)??!1}t=r?t:void 0,this.$["*currentActivity"]=t,this.$["*history"]=e,t||this.setOrAddState("*modalActive",!1)}}};u(re,"_activityCallbacks",new Map);let _=re;_.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"});const no=20,Lt=24,Be=34,Cs=3,J=Cs/2,ve=1,Ye=100/3,C=1,wi=24,oo=6;function Ie(s,i){for(let e in i)s.setAttributeNS(null,e,i[e].toString())}function q(s,i={}){let e=document.createElementNS("http://www.w3.org/2000/svg",s);return Ie(e,i),e}function lo(s,i,e){let{x:t,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],h=[-1,1][a],d=[t+l*n+J*c,r+a*o+J*h-Lt*e*h],f=[t+l*n+J*c,r+a*o+J*h],m=[t+l*n-Lt*e*c+J*c,r+a*o+J*h];return{d:`M ${d[0]} ${d[1]} L ${f[0]} ${f[1]} L ${m[0]} ${m[1]}`,center:f}}function ao(s,i,e){let{x:t,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],h=[-1,1][a],d,f;["n","s"].includes(i)?(d=[t+l*n-Be*e/2,r+a*o+J*h],f=[t+l*n+Be*e/2,r+a*o+J*h]):(d=[t+l*n+J*c,r+a*o-Be*e/2],f=[t+l*n+J*c,r+a*o+Be*e/2]);let m=`M ${d[0]} ${d[1]} L ${f[0]} ${f[1]}`,p=[f[0]-(f[0]-d[0])/2,f[1]-(f[1]-d[1])/2];return{d:m,center:p}}function co(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 ho({rect:s,delta:[i,e],imageBox:t}){return nt({...s,x:s.x+i,y:s.y+e},t)}function nt(s,i){let{x:e}=s,{y:t}=s;return s.x<i.x?e=i.x:s.x+s.width>i.x+i.width&&(e=i.x+i.width-s.width),s.y<i.y?t=i.y:s.y+s.height>i.y+i.height&&(t=i.y+i.height-s.height),{...s,x:e,y:t}}function uo({rect:s,delta:i,aspectRatio:e,imageBox:t}){const[,r]=i;let{y:n,width:o,height:l}=s;n+=r,l-=r,e&&(o=l*e);let a=s.x+s.width/2-o/2;return n<=t.y&&(n=t.y,l=s.y+s.height-n,e&&(o=l*e,a=s.x+s.width/2-o/2)),a<=t.x&&(a=t.x,n=s.y+s.height-l),a+o>=t.x+t.width&&(a=Math.max(t.x,t.x+t.width-o),o=t.x+t.width-a,e&&(l=o/e),n=s.y+s.height-l),l<C&&(l=C,e&&(o=l*e,a=s.x+s.width/2-o/2),n=s.y+s.height-l),o<C&&(o=C,e&&(l=o/e,a=s.x+s.width/2-o/2),n=s.y+s.height-l),{x:a,y:n,width:o,height:l}}function fo({rect:s,delta:i,aspectRatio:e,imageBox:t}){const[r]=i;let{x:n,width:o,height:l}=s;n+=r,o-=r,e&&(l=o/e);let a=s.y+s.height/2-l/2;return n<=t.x&&(n=t.x,o=s.x+s.width-n,e&&(l=o/e,a=s.y+s.height/2-l/2)),a<=t.y&&(a=t.y,n=s.x+s.width-o),a+l>=t.y+t.height&&(a=Math.max(t.y,t.y+t.height-l),l=t.y+t.height-a,e&&(o=l*e),n=s.x+s.width-o),l<C&&(l=C,e&&(o=l*e),a=s.y+s.height/2-l/2,n=s.x+s.width-o),o<C&&(o=C,e&&(l=o/e),a=s.y+s.height/2-l/2,n=s.x+s.width-o),{x:n,y:a,width:o,height:l}}function po({rect:s,delta:i,aspectRatio:e,imageBox:t}){const[,r]=i;let{y:n,width:o,height:l}=s;l+=r,e&&(o=l*e);let a=s.x+s.width/2-o/2;return n+l>=t.y+t.height&&(l=t.y+t.height-n,e&&(o=l*e),a=s.x+s.width/2-o/2),a<=t.x&&(a=t.x,n=s.y),a+o>=t.x+t.width&&(a=Math.max(t.x,t.x+t.width-o),o=t.x+t.width-a,e&&(l=o/e),n=s.y),l<C&&(l=C,e&&(o=l*e),a=s.x+s.width/2-o/2),o<C&&(o=C,e&&(l=o/e),a=s.x+s.width/2-o/2),{x:a,y:n,width:o,height:l}}function mo({rect:s,delta:i,aspectRatio:e,imageBox:t}){const[r]=i;let{x:n,width:o,height:l}=s;o+=r,e&&(l=o/e);let a=s.y+s.height/2-l/2;return n+o>=t.x+t.width&&(o=t.x+t.width-n,e&&(l=o/e),a=s.y+s.height/2-l/2),a<=t.y&&(a=t.y,n=s.x),a+l>=t.y+t.height&&(a=Math.max(t.y,t.y+t.height-l),l=t.y+t.height-a,e&&(o=l*e),n=s.x),l<C&&(l=C,e&&(o=l*e),a=s.y+s.height/2-l/2),o<C&&(o=C,e&&(l=o/e),a=s.y+s.height/2-l/2),{x:n,y:a,width:o,height:l}}function go({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,n]=i,{x:o,y:l,width:a,height:c}=s;return o+r<t.x&&(r=t.x-o),l+n<t.y&&(n=t.y-l),o+=r,a-=r,l+=n,c-=n,e&&Math.abs(a/c)>e?(n=a/e-c,c+=n,l-=n,l<=t.y&&(c=c-(t.y-l),a=c*e,o=s.x+s.width-a,l=t.y)):e&&(r=c*e-a,a=a+r,o-=r,o<=t.x&&(a=a-(t.x-o),c=a/e,o=t.x,l=s.y+s.height-c)),c<C&&(c=C,e&&(a=c*e),o=s.x+s.width-a,l=s.y+s.height-c),a<C&&(a=C,e&&(c=a/e),o=s.x+s.width-a,l=s.y+s.height-c),{x:o,y:l,width:a,height:c}}function bo({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,n]=i,{x:o,y:l,width:a,height:c}=s;return o+a+r>t.x+t.width&&(r=t.x+t.width-o-a),l+n<t.y&&(n=t.y-l),a+=r,l+=n,c-=n,e&&Math.abs(a/c)>e?(n=a/e-c,c+=n,l-=n,l<=t.y&&(c=c-(t.y-l),a=c*e,o=s.x,l=t.y)):e&&(r=c*e-a,a+=r,o+a>=t.x+t.width&&(a=t.x+t.width-o,c=a/e,o=t.x+t.width-a,l=s.y+s.height-c)),c<C&&(c=C,e&&(a=c*e),l=s.y+s.height-c),a<C&&(a=C,e&&(c=a/e),l=s.y+s.height-c),{x:o,y:l,width:a,height:c}}function _o({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,n]=i,{x:o,y:l,width:a,height:c}=s;return o+r<t.x&&(r=t.x-o),l+c+n>t.y+t.height&&(n=t.y+t.height-l-c),o+=r,a-=r,c+=n,e&&Math.abs(a/c)>e?(n=a/e-c,c+=n,l+c>=t.y+t.height&&(c=t.y+t.height-l,a=c*e,o=s.x+s.width-a,l=t.y+t.height-c)):e&&(r=c*e-a,a+=r,o-=r,o<=t.x&&(a=a-(t.x-o),c=a/e,o=t.x,l=s.y)),c<C&&(c=C,e&&(a=c*e),o=s.x+s.width-a),a<C&&(a=C,e&&(c=a/e),o=s.x+s.width-a),{x:o,y:l,width:a,height:c}}function vo({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,n]=i,{x:o,y:l,width:a,height:c}=s;return o+a+r>t.x+t.width&&(r=t.x+t.width-o-a),l+c+n>t.y+t.height&&(n=t.y+t.height-l-c),a+=r,c+=n,e&&Math.abs(a/c)>e?(n=a/e-c,c+=n,l+c>=t.y+t.height&&(c=t.y+t.height-l,a=c*e,o=s.x,l=t.y+t.height-c)):e&&(r=c*e-a,a+=r,o+a>=t.x+t.width&&(a=t.x+t.width-o,c=a/e,o=t.x+t.width-a,l=s.y)),c<C&&(c=C,e&&(a=c*e)),a<C&&(a=C,e&&(c=a/e)),{x:o,y:l,width:a,height:c}}function yo({direction:s,...i}){switch(s){case"n":return uo(i);case"w":return fo(i);case"s":return po(i);case"e":return mo(i);case"nw":return go(i);case"ne":return bo(i);case"sw":return _o(i);case"se":return vo(i);default:return i.rect}}function Co(s,[i,e]){return s.x<=i&&i<=s.x+s.width&&s.y<=e&&e<=s.y+s.height}function wo(s,i){return s.x>=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Eo(s,i){return Math.abs(s.width/s.height-i)<.1}function De({width:s,height:i},e){let t=e/90%2!==0;return{width:t?i:s,height:t?s:i}}function Ao(s,i,e){const t=s/i;let r,n;t>e?(r=Math.round(i*e),n=i):(r=s,n=Math.round(s/e));const 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 tt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Oe(s,i,e){return Math.min(Math.max(s,i),e)}const ws=s=>{if(!s)return[];const[i,e]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(e)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:e}]},Z=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});function To(s){return Zi({...s,libraryName:jt,libraryVersion:Ht})}const Es=({type:s,message:i,...e})=>({type:s,message:i,...e}),Se=Es,At=Es,Pt=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Ei=s=>s?s.filter(i=>typeof i=="string").map(i=>le(i)).flat():[],As=(s,i)=>i.some(e=>e.endsWith("*")?(e=e.replace("*",""),s.startsWith(e)):s===e),$o=(s,i)=>i.some(e=>e.startsWith(".")?s.toLowerCase().endsWith(e.toLowerCase()):!1),Ai=s=>{let i=s==null?void 0:s.type;return i?As(i,Pt):!1},Y=1e3,ye=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),Ne=s=>Math.ceil(s*100)/100,So=(s,i=ye.AUTO)=>{const e=i===ye.AUTO;if(i===ye.BYTE||e&&s<Y**1){const t=Ki("en-US",s),r={one:"byte",other:"bytes"}[t];return`${s} ${r}`}return i===ye.KB||e&&s<Y**2?`${Ne(s/Y**1)} KB`:i===ye.MB||e&&s<Y**3?`${Ne(s/Y**2)} MB`:i===ye.GB||e&&s<Y**4?`${Ne(s/Y**3)} GB`:i===ye.TB||e&&s<Y**5?`${Ne(s/Y**4)} TB`:`${Ne(s/Y**5)} PB`},Ti=new Set;function Ts(s){Ti.has(s)||(Ti.add(s),console.warn(s))}const $i="[Typed State] Wrong property name: ",xo="[Typed State] Wrong property type: ";class Io{constructor(i,e){this.__typedSchema=i,this.__ctxId=e||Ae.generate(),this.__schema=Object.keys(i).reduce((t,r)=>(t[r]=i[r].value,t),{}),this.__data=T.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,e){if(!this.__typedSchema.hasOwnProperty(i)){console.warn($i+i);return}let t=this.__typedSchema[i];if((e==null?void 0:e.constructor)===t.type||e instanceof t.type||t.nullable&&e===null){this.__data.pub(i,e);return}console.warn(xo+i)}setMultipleValues(i){for(let e in i)this.setValue(e,i[e])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn($i+i);return}return this.__data.read(i)}subscribe(i,e){return this.__data.sub(i,e)}remove(){T.deleteCtx(this.__ctxId)}}class Oo{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Ae.generate(),this.__data=T.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 e=Object.create(null);this.__notifyObservers=(t,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),e[t]||(e[t]=new Set),e[t].add(r),this.__observeTimeout=window.setTimeout(()=>{Object.keys(e).length!==0&&(this.__propertyObservers.forEach(n=>{n({...e})}),e=Object.create(null))})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{let i=new Set(this.__added),e=new Set(this.__removed);this.__added.clear(),this.__removed.clear();for(const t of this.__collectionObservers)t==null||t([...this.__items],i,e)})}observeCollection(i){return this.__collectionObservers.add(i),this.__items.size>0&&this.notify(),()=>{this.unobserveCollection(i)}}unobserveCollection(i){var e;(e=this.__collectionObservers)==null||e.delete(i)}add(i){let e=new Io(this.__typedSchema);for(let t in i)e.setValue(t,i[t]);return this.__items.add(e.uid),this.notify(),this.__data.add(e.uid,e),this.__added.add(e),this.__watchList.forEach(t=>{this.__subsMap[e.uid]||(this.__subsMap[e.uid]=[]),this.__subsMap[e.uid].push(e.subscribe(t,()=>{this.__notifyObservers(t,e.uid)}))}),e.uid}read(i){return this.__data.read(i)}readProp(i,e){return this.read(i).getValue(e)}publishProp(i,e,t){this.read(i).setValue(e,t)}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 e;(e=this.__propertyObservers)==null||e.delete(i)}findItems(i){let e=[];return this.__items.forEach(t=>{let r=this.read(t);i(r)&&e.push(t)}),e}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){T.deleteCtx(this.__ctxId),this.__propertyObservers=null,this.__collectionObservers=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(e=>{e.remove()}),delete this.__subsMap[i]}}const ko=s=>{const i=new Map;return(...e)=>{const t=JSON.stringify(e);if(i.has(t))return i.get(t);const r=s(...e);return i.set(t,r),r}};function Lo(s){let i=!1;return setTimeout(()=>{i=!0},0),t=>(...r)=>(i&&Ts(s),t(...r))}function Po(s){const i={progress:()=>s.$["*commonProgress"],errors:()=>s.$["*collectionErrors"],group:()=>s.$["*groupInfo"],totalCount:()=>s.uploadCollection.size,failedCount:()=>e.failedEntries.length,successCount:()=>e.successEntries.length,uploadingCount:()=>e.uploadingEntries.length,status:()=>e.isFailed?"failed":e.isUploading?"uploading":e.isSuccess?"success":"idle",isSuccess:()=>e.errors.length===0&&e.successEntries.length===e.allEntries.length,isUploading:()=>e.allEntries.some(r=>r.status==="uploading"),isFailed:()=>e.errors.length>0||e.failedEntries.length>0,allEntries:()=>s.getOutputData(),successEntries:()=>e.allEntries.filter(r=>r.status==="success"),failedEntries:()=>e.allEntries.filter(r=>r.status==="failed"),uploadingEntries:()=>e.allEntries.filter(r=>r.status==="uploading"),idleEntries:()=>e.allEntries.filter(r=>r.status==="idle")},e={},t=Lo("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(const[r,n]of Object.entries(i)){const o=r,a=ko(t(n));Object.defineProperty(e,o,{get:a,enumerable:!0})}return e}const Uo=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:Re,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}}),Ro=/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i,Mo=new RegExp(`^/?(${Ro.source})(?:/(-/(?:[^/]+/)+)?([^/]*))?$`,"i"),Fo=({url:s,cdnBase:i})=>{const e=new URL(i),t=new URL(s);if(e.host!==t.host)return null;const[,r,n,o]=Mo.exec(t.pathname);return{uuid:r,cdnUrlModifiers:n||"",filename:o||null}};class x extends _{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!1);u(this,"isCtxOwner",!1);u(this,"init$",us(this));u(this,"__initialUploadMetadata",null);u(this,"_fileValidators",[this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this),this._validateUploadError.bind(this)]);u(this,"_collectionValidators",[e=>{const t=e.size,r=this.cfg.multiple?this.cfg.multipleMin:0,n=this.cfg.multiple?this.cfg.multipleMax:1;if(r&&t<r){const o=this.l10n("files-count-limit-error-too-few",{min:r,max:n,total:t});return At({type:"TOO_FEW_FILES",message:o,total:t,min:r,max:n})}if(n&&t>n){const o=this.l10n("files-count-limit-error-too-many",{min:r,max:n,total:t});return At({type:"TOO_MANY_FILES",message:o,total:t,min:r,max:n})}},e=>{if(e.items().some(t=>e.readProp(t,"errors").length>0))return At({type:"SOME_FILES_HAS_ERRORS",message:this.l10n("some-files-were-not-uploaded")})}]);u(this,"uploadAll",()=>{const e=this.uploadCollection.items().filter(t=>{const r=this.uploadCollection.read(t);return!r.getValue("isRemoved")&&!r.getValue("isUploading")&&!r.getValue("fileInfo")});e.length!==0&&(this.$["*uploadTrigger"]=new Set(e),this.emit(I.COMMON_UPLOAD_START,this.getOutputCollectionState()))});u(this,"_flushOutputItems",H(async()=>{if(this.getOutputData().length!==this.uploadCollection.size)return;const t=this.getOutputCollectionState();this.$["*collectionState"]=t,this.emit(I.CHANGE,()=>this.getOutputCollectionState(),{debounce:!0}),this.cfg.groupOutput&&t.totalCount>0&&t.status==="success"&&this._createGroup(t)},300));u(this,"_handleCollectionUpdate",(e,t,r)=>{var n;(t.size||r.size)&&(this.$["*groupInfo"]=null),this._runFileValidators(),this._runCollectionValidators();for(const o of t)o.getValue("silent")||this.emit(I.FILE_ADDED,this.getOutputItem(o.uid));for(const 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(I.FILE_REMOVED,this.getOutputItem(o.uid));this.$["*uploadList"]=e.map(o=>({uid:o})),this._flushCommonUploadProgress(),this._flushOutputItems()});u(this,"_handleCollectionPropertiesUpdate",e=>{this._flushOutputItems();const t=this.uploadCollection,r=[...new Set(Object.entries(e).filter(([n])=>["uploadError","fileInfo"].includes(n)).map(([,n])=>[...n]).flat())];if(r.length>0&&setTimeout(()=>{this._runFileValidators(r)}),e.uploadProgress){for(const n of e.uploadProgress){const{isUploading:o,silent:l}=T.getCtx(n).store;o&&!l&&this.emit(I.FILE_UPLOAD_PROGRESS,this.getOutputItem(n))}this._flushCommonUploadProgress()}if(e.isUploading)for(const n of e.isUploading){const{isUploading:o,silent:l}=T.getCtx(n).store;o&&!l&&this.emit(I.FILE_UPLOAD_START,this.getOutputItem(n))}if(e.fileInfo){for(const l of e.fileInfo){const{fileInfo:a,silent:c}=T.getCtx(l).store;a&&!c&&this.emit(I.FILE_UPLOAD_SUCCESS,this.getOutputItem(l))}this.cfg.cropPreset&&this.setInitialCrop();let n=t.findItems(l=>!!l.getValue("fileInfo"));t.findItems(l=>l.getValue("errors").length>0).length===0&&t.size===n.length&&this.emit(I.COMMON_UPLOAD_SUCCESS,this.getOutputCollectionState())}if(e.errors)for(const n of e.errors){const{errors:o}=T.getCtx(n).store;o.length>0&&(this.emit(I.FILE_UPLOAD_FAILED,this.getOutputItem(n)),this.emit(I.COMMON_UPLOAD_FAILED,()=>this.getOutputCollectionState(),{debounce:!0}))}e.cdnUrl&&([...e.cdnUrl].filter(o=>{var l;return!!((l=this.uploadCollection.read(o))!=null&&l.getValue("cdnUrl"))}).forEach(o=>{this.emit(I.FILE_URL_CHANGED,this.getOutputItem(o))}),this.$["*groupInfo"]=null)});u(this,"_flushCommonUploadProgress",()=>{let e=0;const r=[...this.$["*uploadTrigger"]].filter(o=>!!this.uploadCollection.read(o));r.forEach(o=>{const l=this.uploadCollection.readProp(o,"uploadProgress");e+=l});const n=r.length?Math.round(e/r.length):0;this.$["*commonProgress"]!==n&&(this.$["*commonProgress"]=n,this.emit(I.COMMON_UPLOAD_PROGRESS,this.getOutputCollectionState()))})}setUploadMetadata(e){Ts("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"]=e:this.__initialUploadMetadata=e}get hasCtxOwner(){return this.hasBlockInCtx(e=>e instanceof x?e.isCtxOwner&&e.isConnected&&e!==this:!1)}initCallback(){if(super.initCallback(),!this.$["*uploadCollection"]){let e=new Oo({typedSchema:Uo,watchList:["uploadProgress","uploadError","fileInfo","errors","cdnUrl","isUploading"]});this.$["*uploadCollection"]=e}!this.hasCtxOwner&&this.couldBeCtxOwner&&this.initCtxOwner()}destroyCtxCallback(){var e,t;(e=this._unobserveCollectionProperties)==null||e.call(this),(t=this._unobserveCollection)==null||t.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);const e=()=>{this._runFileValidators(),this._runCollectionValidators()};this.subConfigValue("maxLocalFileSizeBytes",e),this.subConfigValue("multipleMin",e),this.subConfigValue("multipleMax",e),this.subConfigValue("multiple",e),this.subConfigValue("imgOnly",e),this.subConfigValue("accept",e),this.subConfigValue("maxConcurrentRequests",t=>{this.$["*uploadQueue"].concurrency=Number(t)||1}),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata)}addFileFromUrl(e,{silent:t,fileName:r,source:n}={}){const o=this.uploadCollection.add({externalUrl:e,fileName:r??null,silent:t??!1,source:n??Z.API});return this.getOutputItem(o)}addFileFromUuid(e,{silent:t,fileName:r,source:n}={}){const o=this.uploadCollection.add({uuid:e,fileName:r??null,silent:t??!1,source:n??Z.API});return this.getOutputItem(o)}addFileFromCdnUrl(e,{silent:t,fileName:r,source:n}={}){const o=Fo({url:e,cdnBase:this.cfg.cdnCname});if(!o)throw new Error("Invalid CDN URL");const l=this.uploadCollection.add({uuid:o.uuid,cdnUrl:e,cdnUrlModifiers:o.cdnUrlModifiers,fileName:r??o.filename??null,silent:t??!1,source:n??Z.API});return this.getOutputItem(l)}addFileFromObject(e,{silent:t,fileName:r,source:n,fullPath:o}={}){const l=this.uploadCollection.add({file:e,isImage:Ai(e),mimeType:e.type,fileName:r??e.name,fileSize:e.size,silent:t??!1,source:n??Z.API,fullPath:o??null});return this.getOutputItem(l)}addFiles(e){return console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),e.map(t=>{const r=this.uploadCollection.add({file:t,isImage:Ai(t),mimeType:t.type,fileName:t.name,fileSize:t.size});return this.getOutputItem(r)})}removeFileByInternalId(e){if(!this.uploadCollection.read(e))throw new Error(`File with internalId ${e} not found`);this.uploadCollection.remove(e)}removeAllFiles(){this.uploadCollection.clearAll()}openSystemDialog(e={}){let t=qt(Ei([this.cfg.accept??"",...this.cfg.imgOnly?Pt:[]]));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,e.captureCamera?(this.fileInput.capture=this.cfg.cameraCapture,this.fileInput.accept="image/*"):this.fileInput.accept=t,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(r=>this.addFileFromObject(r,{source:e.captureCamera?Z.CAMERA:Z.LOCAL})),this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let e=[];return this.cfg.sourceList&&(e=le(this.cfg.sourceList)),e}initFlow(e=!1){var t;if(this.uploadCollection.size>0&&!e)this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((t=this.sourceList)==null?void 0:t.length)===1){const r=this.sourceList[0];if(r==="local"){this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this==null||this.openSystemDialog();return}const n=this.$["*blocksRegistry"],o=a=>"type"in a&&a.type===r,l=[...n].find(o);l==null||l.activate(),this.$["*currentActivity"]&&this.setOrAddState("*modalActive",!0)}else this.set$({"*currentActivity":_.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(e){const t=this.cfg.imgOnly,r=this.cfg.accept,n=Ei([...t?Pt:[],r]);if(!n.length)return;const o=e.mimeType,l=e.name;if(!o||!l)return;const a=As(o,n),c=$o(l,n);if(!a&&!c)return Se({type:"FORBIDDEN_FILE_TYPE",message:this.l10n("file-type-not-allowed"),entry:e})}_validateMaxSizeLimit(e){const t=this.cfg.maxLocalFileSizeBytes,r=e.size;if(t&&r&&r>t)return Se({type:"FILE_SIZE_EXCEEDED",message:this.l10n("files-max-size-limit-error",{maxFileSize:So(t)}),entry:e})}_validateUploadError(e,t){const r=t==null?void 0:t.getValue("uploadError");if(r){if(r instanceof N)return Se({type:"UPLOAD_ERROR",message:r.message,entry:e,error:r});if(r instanceof qe)return Se({type:"NETWORK_ERROR",message:r.message,entry:e,error:r});{const n=r instanceof Error?r:new Error("Unknown error",{cause:r});return Se({type:"UNKNOWN_ERROR",message:n.message,entry:e,error:n})}}}_validateIsImage(e){const t=this.cfg.imgOnly,r=e.isImage;if(!(!t||r)&&!(!e.fileInfo&&e.externalUrl)&&!(!e.fileInfo&&!e.mimeType))return Se({type:"NOT_AN_IMAGE",message:this.l10n("images-only-accepted"),entry:e})}_runFileValidatorsForEntry(e){const t=this.getOutputItem(e.uid),r=[];for(const n of this._fileValidators){const o=n(t,e);o&&r.push(o)}e.setValue("errors",r)}_runFileValidators(e){const t=e??this.uploadCollection.items();for(const r of t){const n=this.uploadCollection.read(r);n&&this._runFileValidatorsForEntry(n)}}_runCollectionValidators(){const e=this.uploadCollection,t=[];for(const r of this._collectionValidators){const n=r(e);n&&(Array.isArray(n)?t.push(...n):t.push(n))}this.$["*collectionErrors"]=t,t.length>0&&this.emit(I.COMMON_UPLOAD_FAILED,()=>this.getOutputCollectionState(),{debounce:!0})}async _createGroup(e){const t=this.getUploadClientOptions(),r=e.allEntries.map(a=>a.uuid+(a.cdnUrlModifiers?`/${a.cdnUrlModifiers}`:"")),n=new AbortController,o=await Dn(r,{...t,signal:n.signal});if(this.$["*collectionState"]!==e){n.abort();return}this.$["*groupInfo"]=o;const l=this.getOutputCollectionState();this.emit(I.GROUP_CREATED,l),this.emit(I.CHANGE,()=>this.getOutputCollectionState(),{debounce:!0}),this.$["*collectionState"]=l}setInitialCrop(){const e=ws(this.cfg.cropPreset);if(e){const[t]=e,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(const n of r){const o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=t.width/t.height,h=Ao(l,a,c),d=pe(`crop/${h.width}x${h.height}/${h.x},${h.y}`,"preview");n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:j(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===_.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT)}}}async getMetadataFor(e){const t=this.cfg.metadata??this.$["*uploadMetadata"];if(typeof t=="function"){const r=this.getOutputItem(e);return await t(r)}return t}getUploadClientOptions(){return{store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:To,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(e){const t=T.getCtx(e).store,r=t.fileInfo;let n=t.isRemoved?"removed":t.errors.length>0?"failed":t.fileInfo?"success":t.isUploading?"uploading":"idle";return{uuid:(r==null?void 0:r.uuid)??t.uuid??null,internalId:e,name:(r==null?void 0:r.originalFilename)??t.fileName,size:(r==null?void 0:r.size)??t.fileSize,isImage:(r==null?void 0:r.isImage)??t.isImage,mimeType:(r==null?void 0:r.mimeType)??t.mimeType,file:t.file,externalUrl:t.externalUrl,cdnUrlModifiers:t.cdnUrlModifiers,cdnUrl:t.cdnUrl??(r==null?void 0:r.cdnUrl)??null,fullPath:t.fullPath,uploadProgress:t.uploadProgress,fileInfo:r??null,metadata:t.metadata??(r==null?void 0:r.metadata)??null,isSuccess:n==="success",isUploading:n==="uploading",isFailed:n==="failed",isRemoved:n==="removed",errors:t.errors,status:n}}getOutputData(e){return(e?this.uploadCollection.findItems(e):this.uploadCollection.items()).map(n=>this.getOutputItem(n))}getOutputCollectionState(){return Po(this)}}x.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"});x.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...x.extSrcList});const gt=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(e=>e.toLowerCase()).join("-")},L=s=>String(s),K=s=>{const i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},O=s=>{if(typeof s>"u"||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}"`)},Do=s=>s==="auto"?s:O(s),No=s=>{const i=L(s);if(i!=="user"&&i!=="environment"&&i!=="")throw new Error(`Invalid "cameraCapture" value: "${i}"`);return i},zo=s=>{if(typeof s=="object"&&!Array.isArray(s)||typeof s=="function")return s;throw new Error("Invalid metadata value. Must be an object or function.")},Vo=s=>{if(typeof s=="object")return s;throw new Error("Invalid localeDefinitionOverride value. Must be an object.")},Bo={pubkey:L,multiple:O,multipleMin:K,multipleMax:K,confirmUpload:O,imgOnly:O,accept:L,externalSourcesPreferredTypes:L,store:Do,cameraMirror:O,cameraCapture:No,sourceList:L,maxLocalFileSizeBytes:K,thumbSize:K,showEmptyList:O,useLocalImageEditor:O,useCloudImageEditor:O,cloudImageEditorTabs:L,removeCopyright:O,cropPreset:L,imageShrink:L,modalScrollLock:O,modalBackdropStrokes:O,sourceListWrap:O,remoteTabSessionKey:L,cdnCname:L,baseUrl:L,socialBaseUrl:L,secureSignature:L,secureExpire:L,secureDeliveryProxy:L,retryThrottledRequestMaxTimes:K,multipartMinFileSize:K,multipartChunkSize:K,maxConcurrentRequests:K,multipartMaxConcurrentRequests:K,multipartMaxAttempts:K,checkForUrlDuplicates:O,saveUrlForRecurrentUploads:O,groupOutput:O,userAgentIntegration:L,debug:O,localeName:L,metadata:zo,localeDefinitionOverride:Vo},jo=(s,i)=>{if(!(typeof i>"u"||i===null))try{return Bo[s](i)}catch(e){return console.error(`Invalid value for config key "${s}".`,e),ue[s]}},Gt=[...new Set(["debug",...Object.keys(ue)])],Ho=["metadata","localeDefinitionOverride"],Wo=s=>Ho.includes(s),Pe=Gt.filter(s=>!Wo(s)),qo={...Object.fromEntries(Pe.map(s=>[gt(s),s])),...Object.fromEntries(Pe.map(s=>[s.toLowerCase(),s]))},Go={...Object.fromEntries(Pe.map(s=>[gt(s),B(s)])),...Object.fromEntries(Pe.map(s=>[s.toLowerCase(),B(s)]))},Si=s=>"__"+s;class Xt extends ${constructor(){super();u(this,"requireCtxName",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(ue).map(([e,t])=>[B(e),t]))}}_flushValueToAttribute(e,t){if(Pe.includes(e)){const r=[...new Set([gt(e),e.toLowerCase()])];for(const n of r)typeof t>"u"||t===null?this.removeAttribute(n):this.getAttribute(n)!==t.toString()&&this.setAttribute(n,t.toString())}}_flushValueToState(e,t){this.$[B(e)]!==t&&(typeof t>"u"||t===null?this.$[B(e)]=ue[e]:this.$[B(e)]=t)}_setValue(e,t){const r=this,n=jo(e,t),o=Si(e);r[o]!==n&&(this._assertSameValueDifferentReference(e,r[o],n),r[o]=n,this._flushValueToAttribute(e,n),this._flushValueToState(e,n),this.debugPrint(`[lr-config] "${e}"`,n))}_getValue(e){const t=this,r=Si(e);return t[r]}_assertSameValueDifferentReference(e,t,r){this.cfg.debug&&JSON.stringify(r)===JSON.stringify(t)&&(console.warn(`[lr-config] Option "${e}" value is the same as the previous one but the reference is different`),console.warn("[lr-config] You should avoid changing the reference of the object to prevent unnecessary calculations"),console.warn(`[lr-config] "${e}" previous value:`,t),console.warn(`[lr-config] "${e}" new value:`,r))}initCallback(){super.initCallback();const e=this;for(const t of Pe)this.sub(B(t),r=>{this._setValue(t,r)},!1);for(const t of Gt){const r=e[t]??this.$[B(t)];r!==ue[t]&&this._setValue(t,r),Object.defineProperty(this,t,{set:n=>{this._setValue(t,n)},get:()=>this._getValue(t)})}}attributeChangedCallback(e,t,r){if(t===r)return;const n=this,o=qo[e];n[o]=r}}Xt.bindAttributes(Go);for(const s of Gt)Xt.prototype[s]=void 0;const $s=Xt;class Yt extends ${constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",e=>{if(!e)return;let t=this.getCssData(`--icon-${e}`);t&&(this.$.path=t)}),this.sub("path",e=>{if(!e)return;e.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=e):(this.removeAttribute("raw"),this.ref.svg.innerHTML=`<path fill-rule="evenodd" d="${e}"></path>`)}),this.sub("size",e=>{this.$.viewBox=`0 0 ${e} ${e}`})}}Yt.template=`
5
5
  <svg ref="svg" xmlns="http://www.w3.org/2000/svg" set="@viewBox: viewBox; @height: size; @width: size"></svg>
6
- `;Kt.bindAttributes({name:"name",size:"size"});const zo=s=>[...new Set(s)],Vo=s=>Object.entries(s).filter(([i,e])=>e!==void 0&&e!=="").map(([i,e])=>i==="cdn-operations"||i==="analytics"?e:`${i}/${e}`),Bo="https://ucarecdn.com",at=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Bo},"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}}),He="--lr-img-",xi="unresolved",Je=2,Ze=3,Ii=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ki=3e3,Oi=5e3,Pi=Object.freeze({PREVIEW:"PREVIEW",MAIN:"MAIN"}),Ts=Object.create(null);var Hi;for(let s in at)Ts[He+s]=((Hi=at[s])==null?void 0:Hi.default)||"";class jo extends ht{constructor(){super(...arguments);u(this,"cssInit$",Ts)}$$(e){return this.$[He+e]}set$$(e){for(let t in e)this.$[He+t]=e[t]}sub$$(e,t){this.sub(He+e,r=>{r===null||r===""||t(r)})}analyticsParams(){return`-/@clib/${qt}/${bt}/lr-img/`}initAttributes(e){[...this.attributes].forEach(t=>{at[t.name]||e.setAttribute(t.name,t.value)})}initIntersection(e,t){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(t(),this._isnObserver.unobserve(e))})},r),this._isnObserver.observe(e),this._observed||(this._observed=new Set),this._observed.add(e)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(e=>{this._isnObserver.unobserve(e)}),this._isnObserver=null),T.deleteCtx(this)}static get observedAttributes(){return Object.keys(at)}attributeChangedCallback(e,t,r){window.setTimeout(()=>{this.$[He+e]=r})}}class Ho extends jo{constructor(){super(...arguments);u(this,"_img",new Image);u(this,"_imgPreview",new Image)}_fmtAbs(e){return!e.includes("//")&&!Ii&&(e=new URL(e,document.baseURI).href),e}_validateSize(e){if((e==null?void 0:e.trim())!==""){let t=e.match(/\d+/)[0],r=e.match(/[a-zA-Z]+/)[0];const n=parseInt(t,10);if(Number(n)>Oi&&this.hasFormatJPG)return Oi+r;if(Number(n)>ki&&!this.hasFormatJPG)return ki+r}return e}_getCdnModifiers(e,t){const r={format:this.$$("format"),quality:this.$$("quality"),resize:this._validateSize(e),blur:t,"cdn-operations":this.$$("cdn-operations"),analytics:this.analyticsParams()};return le(...Vo(r))}_getUrlBase(e="",t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(Ii&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let r=this._getCdnModifiers(e,t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return V(this.$$("src"),r);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(V(We(this.$$("cdn-cname"),this.$$("uuid")),r));if(this.$$("uuid"))return this._proxyUrl(V(We(this.$$("cdn-cname"),this.$$("uuid")),r));if(this.$$("proxy-cname"))return this._proxyUrl(V(this.$$("proxy-cname"),r,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(V(`https://${this.$$("pubkey")}.ucr.io/`,r,this._fmtAbs(this.$$("src"))))}_proxyUrl(e){return this.$$("secure-delivery-proxy")?Ot(this.$$("secure-delivery-proxy"),{previewUrl:e},{transform:r=>window.encodeURIComponent(r)}):e}_getElSize(e,t=1,r=!0){let n=e.getBoundingClientRect(),o=t*Math.round(n.width),l=r?"":t*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(e){let t=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)e.addEventListener(n,t)}get img(){return this.hasPreviewImage||(this._setupConfigForImage({elNode:this._img}),this.appendChild(this._img)),this._img}get currentImg(){return this.hasPreviewImage?{type:Pi.PREVIEW,img:this._imgPreview}:{type:Pi.MAIN,img:this.img}}get hasPreviewImage(){return this.$$("is-preview-blur")}get bgSelector(){return this.$$("is-background-for")}get breakpoints(){if(this.$$("breakpoints")){const e=ae(this.$$("breakpoints"));return zo(e.map(t=>parseInt(t,10)))}else return null}get hasFormatJPG(){return this.$$("format").toLowerCase()==="jpeg"}renderBg(e){let t=new Set;t.add(`url("${this._getUrlBase(this._getElSize(e))}") 1x`),this.$$("hi-res-support")&&t.add(`url("${this._getUrlBase(this._getElSize(e,Je))}") ${Je}x`),this.$$("ultra-res-support")&&t.add(`url("${this._getUrlBase(this._getElSize(e,Ze))}") ${Ze}x`);let r=`image-set(${[...t].join(", ")})`;e.style.setProperty("background-image",r),e.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let e=new Set;return this.breakpoints?this.breakpoints.forEach(t=>{e.add(this._getUrlBase(t+"x")+` ${this._validateSize(t+"w")}`),this.$$("hi-res-support")&&e.add(this._getUrlBase(t*Je+"x")+` ${this._validateSize(t*Je+"w")}`),this.$$("ultra-res-support")&&e.add(this._getUrlBase(t*Ze+"x")+` ${this._validateSize(t*Ze+"w")}`)}):(e.add(this._getUrlBase(this._getElSize(this.currentImg.img))+" 1x"),this.$$("hi-res-support")&&e.add(this._getUrlBase(this._getElSize(this.currentImg.img,2))+" 2x"),this.$$("ultra-res-support")&&e.add(this._getUrlBase(this._getElSize(this.currentImg.img,3))+" 3x")),[...e].join()}getSrc(){return this._getUrlBase()}get srcUrlPreview(){return this._getUrlBase("100x","100")}renderBackground(){[...document.querySelectorAll(this.bgSelector)].forEach(e=>{this.$$("intersection")?this.initIntersection(e,()=>{this.renderBg(e)}):this.renderBg(e)})}_appendURL({elNode:e,src:t,srcset:r}){t&&(e.src=t),r&&(e.srcset=r)}_setupConfigForImage({elNode:e}){this._setupEventProxy(e),this.initAttributes(e)}loaderImage({src:e,srcset:t,elNode:r}){return new Promise((n,o)=>{this._setupConfigForImage({elNode:r}),r.setAttribute(xi,""),r.addEventListener("load",()=>{r.removeAttribute(xi),n(r)}),r.addEventListener("error",()=>{o(!1)}),this._appendURL({elNode:r,src:e,srcset:t})})}async renderImage(){var e,t;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((e=this._imgPreview)==null?void 0:e.remove()),this.appendChild(this._img)}catch{this.hasPreviewImage&&await((t=this._imgPreview)==null?void 0:t.remove()),this.appendChild(this._img)}}init(){this.bgSelector?this.renderBackground():this.renderImage()}}class Wo extends Ho{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")})}}class Yt extends ${constructor(){super();u(this,"couldBeCtxOwner",!0);this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",e=>{typeof e>"u"||(this.$.withDropZone=I(e))}),this.subConfigValue("multiple",e=>{this.$["*simpleButtonText"]=e?this.l10n("upload-files"):this.l10n("upload-file")})}}Yt.template=`
6
+ `;Yt.bindAttributes({name:"name",size:"size"});const Xo=s=>[...new Set(s)],Yo=s=>Object.entries(s).filter(([i,e])=>e!==void 0&&e!=="").map(([i,e])=>i==="cdn-operations"||i==="analytics"?e:`${i}/${e}`),Ko="https://ucarecdn.com",ot=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}}),je="--lr-img-",xi="unresolved",Ke=2,Je=3,Ii=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),Oi=3e3,ki=5e3,Li=Object.freeze({PREVIEW:"PREVIEW",MAIN:"MAIN"}),Ss=Object.create(null);var Hi;for(let s in ot)Ss[je+s]=((Hi=ot[s])==null?void 0:Hi.default)||"";class Jo extends at{constructor(){super(...arguments);u(this,"cssInit$",Ss)}$$(e){return this.$[je+e]}set$$(e){for(let t in e)this.$[je+t]=e[t]}sub$$(e,t){this.sub(je+e,r=>{r===null||r===""||t(r)})}analyticsParams(){return`-/@clib/${jt}/${Ht}/lr-img/`}initAttributes(e){[...this.attributes].forEach(t=>{ot[t.name]||e.setAttribute(t.name,t.value)})}initIntersection(e,t){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(t(),this._isnObserver.unobserve(e))})},r),this._isnObserver.observe(e),this._observed||(this._observed=new Set),this._observed.add(e)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(e=>{this._isnObserver.unobserve(e)}),this._isnObserver=null),T.deleteCtx(this)}static get observedAttributes(){return Object.keys(ot)}attributeChangedCallback(e,t,r){window.setTimeout(()=>{this.$[je+e]=r})}}class Zo extends Jo{constructor(){super(...arguments);u(this,"_img",new Image);u(this,"_imgPreview",new Image)}_fmtAbs(e){return!e.includes("//")&&!Ii&&(e=new URL(e,document.baseURI).href),e}_validateSize(e){if((e==null?void 0:e.trim())!==""){let t=e.match(/\d+/)[0],r=e.match(/[a-zA-Z]+/)[0];const n=parseInt(t,10);if(Number(n)>ki&&this.hasFormatJPG)return ki+r;if(Number(n)>Oi&&!this.hasFormatJPG)return Oi+r}return e}_getCdnModifiers(e,t){const r={format:this.$$("format"),quality:this.$$("quality"),resize:this._validateSize(e),blur:t,"cdn-operations":this.$$("cdn-operations"),analytics:this.analyticsParams()};return pe(...Yo(r))}_getUrlBase(e="",t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(Ii&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let r=this._getCdnModifiers(e,t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return j(this.$$("src"),r);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(j(He(this.$$("cdn-cname"),this.$$("uuid")),r));if(this.$$("uuid"))return this._proxyUrl(j(He(this.$$("cdn-cname"),this.$$("uuid")),r));if(this.$$("proxy-cname"))return this._proxyUrl(j(this.$$("proxy-cname"),r,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(j(`https://${this.$$("pubkey")}.ucr.io/`,r,this._fmtAbs(this.$$("src"))))}_proxyUrl(e){return this.$$("secure-delivery-proxy")?It(this.$$("secure-delivery-proxy"),{previewUrl:e},{transform:r=>window.encodeURIComponent(r)}):e}_getElSize(e,t=1,r=!0){let n=e.getBoundingClientRect(),o=t*Math.round(n.width),l=r?"":t*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(e){let t=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)e.addEventListener(n,t)}get img(){return this.hasPreviewImage||(this._setupConfigForImage({elNode:this._img}),this.appendChild(this._img)),this._img}get currentImg(){return this.hasPreviewImage?{type:Li.PREVIEW,img:this._imgPreview}:{type:Li.MAIN,img:this.img}}get hasPreviewImage(){return this.$$("is-preview-blur")}get bgSelector(){return this.$$("is-background-for")}get breakpoints(){if(this.$$("breakpoints")){const e=le(this.$$("breakpoints"));return Xo(e.map(t=>parseInt(t,10)))}else return null}get hasFormatJPG(){return this.$$("format").toLowerCase()==="jpeg"}renderBg(e){let t=new Set;t.add(`url("${this._getUrlBase(this._getElSize(e))}") 1x`),this.$$("hi-res-support")&&t.add(`url("${this._getUrlBase(this._getElSize(e,Ke))}") ${Ke}x`),this.$$("ultra-res-support")&&t.add(`url("${this._getUrlBase(this._getElSize(e,Je))}") ${Je}x`);let r=`image-set(${[...t].join(", ")})`;e.style.setProperty("background-image",r),e.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let e=new Set;return this.breakpoints?this.breakpoints.forEach(t=>{e.add(this._getUrlBase(t+"x")+` ${this._validateSize(t+"w")}`),this.$$("hi-res-support")&&e.add(this._getUrlBase(t*Ke+"x")+` ${this._validateSize(t*Ke+"w")}`),this.$$("ultra-res-support")&&e.add(this._getUrlBase(t*Je+"x")+` ${this._validateSize(t*Je+"w")}`)}):(e.add(this._getUrlBase(this._getElSize(this.currentImg.img))+" 1x"),this.$$("hi-res-support")&&e.add(this._getUrlBase(this._getElSize(this.currentImg.img,2))+" 2x"),this.$$("ultra-res-support")&&e.add(this._getUrlBase(this._getElSize(this.currentImg.img,3))+" 3x")),[...e].join()}getSrc(){return this._getUrlBase()}get srcUrlPreview(){return this._getUrlBase("100x","100")}renderBackground(){[...document.querySelectorAll(this.bgSelector)].forEach(e=>{this.$$("intersection")?this.initIntersection(e,()=>{this.renderBg(e)}):this.renderBg(e)})}_appendURL({elNode:e,src:t,srcset:r}){t&&(e.src=t),r&&(e.srcset=r)}_setupConfigForImage({elNode:e}){this._setupEventProxy(e),this.initAttributes(e)}loaderImage({src:e,srcset:t,elNode:r}){return new Promise((n,o)=>{this._setupConfigForImage({elNode:r}),r.setAttribute(xi,""),r.addEventListener("load",()=>{r.removeAttribute(xi),n(r)}),r.addEventListener("error",()=>{o(!1)}),this._appendURL({elNode:r,src:e,srcset:t})})}async renderImage(){var e,t;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((e=this._imgPreview)==null?void 0:e.remove()),this.appendChild(this._img)}catch{this.hasPreviewImage&&await((t=this._imgPreview)==null?void 0:t.remove()),this.appendChild(this._img)}}init(){this.bgSelector?this.renderBackground():this.renderImage()}}class Qo extends Zo{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")})}}class Kt extends x{constructor(){super();u(this,"couldBeCtxOwner",!0);this.init$={...this.init$,withDropZone:!0,onClick:()=>{this.initFlow()},"button-text":""}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",e=>{typeof e>"u"||(this.$.withDropZone=O(e))}),this.subConfigValue("multiple",e=>{this.$["button-text"]=e?"upload-files":"upload-file"})}}Kt.template=`
7
7
  <lr-drop-area set="@disabled: !withDropZone">
8
8
  <button type="button" set="onclick: onClick">
9
9
  <lr-icon name="upload"></lr-icon>
10
- <span>{{*simpleButtonText}}</span>
10
+ <span l10n="button-text"></span>
11
11
  <slot></slot>
12
- <div class="visual-drop-area"></div>
12
+ <div class="visual-drop-area" l10n="drop-files-here"></div>
13
13
  </button>
14
14
  </lr-drop-area>
15
- `;Yt.bindAttributes({dropzone:null});class $s extends b{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}}$s.template=' <div class="content"><slot></slot></div> ';function qo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let e=new FileReader;e.onerror=()=>{i(!0)};let t=r=>{r.type!=="loadend"&&e.abort(),i(!1)};e.onloadend=t,e.onprogress=t,e.readAsDataURL(s)}catch{i(!1)}})}function Go(s,i){return new Promise(e=>{let t=0;const r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),e(null)),l.isFile?(t++,l.file(a=>{t--;const c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),t===0&&e(r)})):l.isDirectory&&o(l.createReader())};let o=l=>{t++,l.readEntries(a=>{t--;for(let c of a)n(c);t===0&&e(r)})};n(s)})}function Xo(s){const i=[],e=[];for(let t=0;t<s.items.length;t++){let r=s.items[t];if(r)if(r.kind==="file"){const n=r.type;if(typeof r.webkitGetAsEntry=="function"||typeof r.getAsEntry=="function"){let l=typeof r.webkitGetAsEntry=="function"?r.webkitGetAsEntry():r.getAsEntry();e.push(Go(l,n).then(a=>{a&&i.push(...a)}));continue}const o=r.getAsFile();o&&e.push(qo(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&e.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(e).then(()=>i)}const F={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3};let Li=["focus"],Ko=100,St=new Map;function Yo(s,i){let e=Math.max(Math.min(s[0],i.x+i.width),i.x),t=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-e)*(s[0]-e)+(s[1]-t)*(s[1]-t))}function Ui(s){let i=0,e=document.body,t=new Set,r=p=>t.add(p),n=F.INACTIVE,o=p=>{s.shouldIgnore()&&p!==F.INACTIVE||(n!==p&&t.forEach(g=>g(p)),n=p)},l=()=>i>0;r(p=>s.onChange(p));let a=()=>{i=0,o(F.INACTIVE)},c=()=>{i+=1,n===F.INACTIVE&&o(F.ACTIVE)},h=()=>{i-=1,l()||o(F.INACTIVE)},d=p=>{p.preventDefault(),i=0,o(F.INACTIVE)},f=p=>{if(s.shouldIgnore())return;l()||(i+=1);let g=[p.x,p.y],A=s.element.getBoundingClientRect(),w=Math.floor(Yo(g,A)),C=w<Ko,y=p.composedPath().includes(s.element);St.set(s.element,w);let U=Math.min(...St.values())===w;y&&U?(p.preventDefault(),o(F.OVER)):o(C&&U?F.NEAR:F.ACTIVE)},m=async p=>{if(s.shouldIgnore())return;p.preventDefault();let g=await Xo(p.dataTransfer);s.onItems(g),o(F.INACTIVE)};return e.addEventListener("drop",d),e.addEventListener("dragleave",h),e.addEventListener("dragenter",c),e.addEventListener("dragover",f),s.element.addEventListener("drop",m),Li.forEach(p=>{window.addEventListener(p,a)}),()=>{St.delete(s.element),e.removeEventListener("drop",d),e.removeEventListener("dragleave",h),e.removeEventListener("dragenter",c),e.removeEventListener("dragover",f),s.element.removeEventListener("drop",m),Li.forEach(p=>{window.removeEventListener(p,a)})}}const Ss="lr-drop-area",xe=`${Ss}/registry`;class Jt extends ${constructor(){super(),this.init$={...this.init$,state:F.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),[xe]:null}}isActive(){if(!this.$.isEnabled)return!1;const i=this.getBoundingClientRect(),e=i.width>0&&i.height>0,t=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 e&&n&&t}initCallback(){super.initCallback(),this.$[xe]||(this.$[xe]=new Set),this.$[xe].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!I(e)})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:I(e)})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:I(e)})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:I(e)})}),this.defineAccessor("text",e=>{typeof e=="string"?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Ui({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(t=>{t.type==="url"?this.addFileFromUrl(t.url,{source:Q.DROP_AREA}):t.type==="file"&&this.addFileFromObject(t.file,{source:Q.DROP_AREA,fullPath:t.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":b.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=Ui({element:i,onChange:e=>{var r;const t=(r=Object.entries(F).find(([,n])=>n===e))==null?void 0:r[0].toLowerCase();t&&i.setAttribute("drag-state",t)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var r;const t=(r=Object.entries(F).find(([,n])=>n===e))==null?void 0:r[0].toLowerCase();t&&this.setAttribute("drag-state",t)}),this.subConfigValue("sourceList",e=>{const t=ae(e);this.$.isEnabled=t.includes($.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.sub("isClickable",e=>{this.toggleAttribute("clickable",e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[xe]].filter(t=>t!==this).filter(t=>t.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,e=this.cfg.multipleMax,t=this.uploadCollection.size;return!(i&&e&&t>=e||!i&&t>0)}destroyCallback(){var e,t;super.destroyCallback();const i=this.$[xe];i&&(i.delete(this),i.size===0&&T.deleteCtx(Ss)),(e=this._destroyDropzone)==null||e.call(this),(t=this._destroyContentWrapperDropzone)==null||t.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}}Jt.template=`
15
+ `;Kt.bindAttributes({dropzone:null});class xs extends _{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}}xs.template=' <div class="content"><slot></slot></div> ';function el(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let e=new FileReader;e.onerror=()=>{i(!0)};let t=r=>{r.type!=="loadend"&&e.abort(),i(!1)};e.onloadend=t,e.onprogress=t,e.readAsDataURL(s)}catch{i(!1)}})}function tl(s,i){return new Promise(e=>{let t=0;const r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),e(null)),l.isFile?(t++,l.file(a=>{t--;const c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),t===0&&e(r)})):l.isDirectory&&o(l.createReader())};let o=l=>{t++,l.readEntries(a=>{t--;for(let c of a)n(c);t===0&&e(r)})};n(s)})}function il(s){const i=[],e=[];for(let t=0;t<s.items.length;t++){let r=s.items[t];if(r)if(r.kind==="file"){const n=r.type;if(typeof r.webkitGetAsEntry=="function"||typeof r.getAsEntry=="function"){let l=typeof r.webkitGetAsEntry=="function"?r.webkitGetAsEntry():r.getAsEntry();e.push(tl(l,n).then(a=>{a&&i.push(...a)}));continue}const o=r.getAsFile();o&&e.push(el(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&e.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(e).then(()=>i)}const F={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3};let Pi=["focus"],sl=100,Tt=new Map;function rl(s,i){let e=Math.max(Math.min(s[0],i.x+i.width),i.x),t=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-e)*(s[0]-e)+(s[1]-t)*(s[1]-t))}function Ui(s){let i=0,e=document.body,t=new Set,r=p=>t.add(p),n=F.INACTIVE,o=p=>{s.shouldIgnore()&&p!==F.INACTIVE||(n!==p&&t.forEach(g=>g(p)),n=p)},l=()=>i>0;r(p=>s.onChange(p));let a=()=>{i=0,o(F.INACTIVE)},c=()=>{i+=1,n===F.INACTIVE&&o(F.ACTIVE)},h=()=>{i-=1,l()||o(F.INACTIVE)},d=p=>{p.preventDefault(),i=0,o(F.INACTIVE)},f=p=>{if(s.shouldIgnore())return;l()||(i+=1);let g=[p.x,p.y],w=s.element.getBoundingClientRect(),E=Math.floor(rl(g,w)),b=E<sl,y=p.composedPath().includes(s.element);Tt.set(s.element,E);let U=Math.min(...Tt.values())===E;y&&U?(p.preventDefault(),o(F.OVER)):o(b&&U?F.NEAR:F.ACTIVE)},m=async p=>{if(s.shouldIgnore())return;p.preventDefault();let g=await il(p.dataTransfer);s.onItems(g),o(F.INACTIVE)};return e.addEventListener("drop",d),e.addEventListener("dragleave",h),e.addEventListener("dragenter",c),e.addEventListener("dragover",f),s.element.addEventListener("drop",m),Pi.forEach(p=>{window.addEventListener(p,a)}),()=>{Tt.delete(s.element),e.removeEventListener("drop",d),e.removeEventListener("dragleave",h),e.removeEventListener("dragenter",c),e.removeEventListener("dragover",f),s.element.removeEventListener("drop",m),Pi.forEach(p=>{window.removeEventListener(p,a)})}}const Is="lr-drop-area",xe=`${Is}/registry`;class Jt extends x{constructor(){super(),this.init$={...this.init$,state:F.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:"",[xe]:null}}isActive(){if(!this.$.isEnabled)return!1;const i=this.getBoundingClientRect(),e=i.width>0&&i.height>0,t=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 e&&n&&t}initCallback(){super.initCallback(),this.bindL10n("text",()=>this.l10n("drop-files-here")),this.$[xe]||(this.$[xe]=new Set),this.$[xe].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!O(e)})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:O(e)})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:O(e)})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:O(e)})}),this.defineAccessor("text",e=>{typeof e=="string"?this.bindL10n("text",()=>this.l10n(e)||e):this.bindL10n("text",()=>this.l10n("drop-files-here"))}),this._destroyDropzone=Ui({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(t=>{t.type==="url"?this.addFileFromUrl(t.url,{source:Z.DROP_AREA}):t.type==="file"&&this.addFileFromObject(t.file,{source:Z.DROP_AREA,fullPath:t.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=Ui({element:i,onChange:e=>{var r;const t=(r=Object.entries(F).find(([,n])=>n===e))==null?void 0:r[0].toLowerCase();t&&i.setAttribute("drag-state",t)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var r;const t=(r=Object.entries(F).find(([,n])=>n===e))==null?void 0:r[0].toLowerCase();t&&this.setAttribute("drag-state",t)}),this.subConfigValue("sourceList",e=>{const t=le(e);this.$.isEnabled=t.includes(x.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.sub("isClickable",e=>{this.toggleAttribute("clickable",e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$[xe]].filter(t=>t!==this).filter(t=>t.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,e=this.cfg.multipleMax,t=this.uploadCollection.size;return!(i&&e&&t>=e||!i&&t>0)}destroyCallback(){var e,t;super.destroyCallback();const i=this.$[xe];i&&(i.delete(this),i.size===0&&T.deleteCtx(Is)),(e=this._destroyDropzone)==null||e.call(this),(t=this._destroyContentWrapperDropzone)==null||t.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}}Jt.template=`
16
16
  <slot>
17
17
  <div data-default-slot hidden></div>
18
18
  <div ref="content-wrapper" class="content-wrapper" set="@hidden: !isVisible">
@@ -23,18 +23,18 @@
23
23
  <span class="text">{{text}}</span>
24
24
  </div>
25
25
  </slot>
26
- `;Jt.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});const Jo="src-type-";class Zt extends ${constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"type");u(this,"_registeredTypes",{});this.init$={...this.init$,iconName:"default"}}initTypes(){this.registerType({type:$.sourceTypes.LOCAL,activate:()=>(this.openSystemDialog(),!1)}),this.registerType({type:$.sourceTypes.URL,activity:b.activities.URL,textKey:"from-url"}),this.registerType({type:$.sourceTypes.CAMERA,activity:b.activities.CAMERA,activate:()=>{const e="capture"in document.createElement("input");return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:b.activities.DRAW,icon:"edit-draw"});for(let e of Object.values($.extSrcList))this.registerType({type:e,activity:b.activities.EXTERNAL,activityParams:{externalSourceType:e}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",e=>{e&&this.applyType(e)})}registerType(e){this._registeredTypes[e.type]=e}getType(e){return this._registeredTypes[e]}activate(){if(!this.type)return;const e=this._registeredTypes[this.type],{activity:t,activate:r,activityParams:n={}}=e;(r?r():!!t)&&this.set$({"*currentActivityParams":n,"*currentActivity":t})}applyType(e){const t=this._registeredTypes[e];if(!t){console.warn("Unsupported source type: "+e);return}const{textKey:r=e,icon:n=e}=t;this.applyL10nKey("src-type",`${Jo}${r}`),this.$.iconName=n,this.onclick=()=>{this.activate()}}}Zt.template=`
26
+ `;Jt.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});const nl="src-type-";class Zt extends x{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"type");u(this,"_registeredTypes",{});this.init$={...this.init$,iconName:"default","src-type":""}}initTypes(){this.registerType({type:x.sourceTypes.LOCAL,activate:()=>(this.openSystemDialog(),!1)}),this.registerType({type:x.sourceTypes.URL,activity:_.activities.URL,textKey:"from-url"}),this.registerType({type:x.sourceTypes.CAMERA,activity:_.activities.CAMERA,activate:()=>{const e="capture"in document.createElement("input");return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:_.activities.DRAW,icon:"edit-draw"});for(let e of Object.values(x.extSrcList))this.registerType({type:e,activity:_.activities.EXTERNAL,activityParams:{externalSourceType:e}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",e=>{e&&this.applyType(e)})}registerType(e){this._registeredTypes[e.type]=e}getType(e){return this._registeredTypes[e]}activate(){if(!this.type)return;const e=this._registeredTypes[this.type],{activity:t,activate:r,activityParams:n={}}=e;(r?r():!!t)&&this.set$({"*currentActivityParams":n,"*currentActivity":t})}applyType(e){const t=this._registeredTypes[e];if(!t){console.warn("Unsupported source type: "+e);return}const{textKey:r=e,icon:n=e}=t;this.$["src-type"]=`${nl}${r}`,this.$.iconName=n,this.onclick=()=>{this.activate()}}}Zt.template=`
27
27
  <lr-icon set="@name: iconName"></lr-icon>
28
28
  <div class="txt" l10n="src-type"></div>
29
- `;Zt.bindAttributes({type:null});class Zo extends k{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let e=ae(i),t="";e.forEach(r=>{t+=`<lr-source-btn type="${r}"></lr-source-btn>`}),this.cfg.sourceListWrap?this.innerHTML=t:this.outerHTML=t})}}const yt=()=>{const s=[];return{stack:s,promiseReadJpegChunks:e=>new Promise((t,r)=>{let n=2;const o=(c,h)=>{const d=new FileReader;d.addEventListener("load",()=>{h(new DataView(d.result))}),d.addEventListener("error",f=>{r(`Reader error: ${f}`)}),d.readAsArrayBuffer(c)},l=()=>o(e.slice(n,n+128),c=>{let h,d,f;for(h=d=0,f=c.byteLength;f>=0?d<f:d>f;h=f>=0?++d:--d)if(c.getUint8(h)===255){n+=h;break}a()}),a=()=>{const c=n;return o(e.slice(n,n+=4),h=>{if(h.byteLength!==4||h.getUint8(0)!==255){r("Corrupted");return}const d=h.getUint8(1);if(d===218){t(!0);return}const f=h.getUint16(2)-2;return o(e.slice(n,n+=f),m=>{if(m.byteLength!==f){r("Corrupted");return}s.push({startPos:c,length:f,marker:d,view:m}),l()})})};FileReader&&DataView||r("Not Support"),o(e.slice(0,2),c=>{c.getUint16(0)!==65496&&r("Not jpeg"),l()})})}},Qo=async s=>{const i=[],{promiseReadJpegChunks:e,stack:t}=yt();return await e(s),t.forEach(({marker:r,view:n})=>{r===226&&n.getUint32(0)===1229144927&&n.getUint32(4)===1347571526&&n.getUint32(8)===1229735168&&i.push(n)}),i},xs=async(s,i,e)=>{{const t=[],r=[],{promiseReadJpegChunks:n,stack:o}=yt();await n(s),o.forEach(c=>{if(c.marker===i)return t.push(c.startPos),r.push(c.length)});const l=[s.slice(0,2)];for(const c of e){const h=new DataView(new ArrayBuffer(4));h.setUint16(0,65280+i),h.setUint16(2,c.byteLength+2),l.push(h.buffer),l.push(c)}let a=2;for(let c=0;c<t.length;c++)t[c]>a&&l.push(s.slice(a,t[c])),a=t[c]+r[c]+4;return l.push(s.slice(a,s.size)),new Blob(l,{type:s.type})}},el=226,Is=(s,i)=>xs(s,el,i.map(e=>e.buffer)),tl=async s=>{try{return await Is(s,[])}catch(i){throw new Error(`Failed to strip ICC profile: ${i}`)}},il=(s,i,e)=>new Promise((t,r)=>{const n=o=>{if(!o){r("Failed to convert canvas to blob");return}t(o)};s.toBlob(n,i,e),s.width=s.height=1}),qe=()=>{const s=document.createElement("canvas"),i=s.getContext("2d");return{canvas:s,ctx:i}},sl=s=>{const{ctx:e,canvas:t}=qe();t.width=t.height=50,e.drawImage(s,0,0,50,50);const r=e.getImageData(0,0,50,50).data;t.width=t.height=1;for(let n=3;n<r.length;n+=4)if(r[n]<254)return!0;return!1},rl=async s=>{let i=null;const{promiseReadJpegChunks:e,stack:t}=yt();return await e(s),t.forEach(({marker:r,view:n})=>{if(!i&&r===225&&n.byteLength>=14&&n.getUint32(0)===1165519206&&n.getUint16(4)===0){i=n;return}}),i},nl="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4QA6RXhpZgAATU0AKgAAAAgAAwESAAMAAAABAAYAAAEoAAMAAAABAAIAAAITAAMAAAABAAEAAAAAAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wAALCAABAAIBASIA/8QAJgABAAAAAAAAAAAAAAAAAAAAAxABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQAAPwBH/9k=";let Qe;const ol=()=>new Promise(s=>{if(Qe!==void 0)s(Qe);else{const i=new Image;i.addEventListener("load",()=>{Qe=i.naturalWidth<i.naturalHeight,i.src="//:0",s(Qe)}),i.src=nl}}),ll=(s,i)=>{let e,t,r,n;if(!s||s.byteLength<14||s.getUint32(0)!==1165519206||s.getUint16(4)!==0)return;if(s.getUint16(6)===18761)t=!0;else if(s.getUint16(6)===19789)t=!1;else return;if(s.getUint16(8,t)!==42)return;r=8+s.getUint32(10,t);const o=s.getUint16(r-2,t);for(e=0,n=o;n>=0?e<n:e>n;n>=0?++e:--e){if(s.byteLength<r+10)return;s.getUint16(r,t)===274&&i(r+8,t),r+=12}},al=(s,i)=>{ll(s,(e,t)=>s.setUint16(e,i,t))},cl=async(s,i,e)=>(e&&al(i,1),xs(s,225,[i.buffer])),hl=(s,i)=>new Promise((e,t)=>{i&&(s.src=i),s.complete?e(s):(s.addEventListener("load",()=>{e(s)}),s.addEventListener("error",()=>{t(new Error("Failed to load image. Probably not an image."))}))}),ul=s=>hl(new Image,s),dl=[1,3],fl=[192,193,194,195,197,198,199,201,202,203,205,206,207],Ri={squareSide:[Math.floor(Math.sqrt(5*1e3*1e3)),4096,8192,11180,10836,11402,14188,16384],dimension:[4096,8192,16384,32767,65535]},pl=async s=>{let i=!1;const{promiseReadJpegChunks:e,stack:t}=yt();return await e(s).then(()=>(t.forEach(({marker:r,view:n})=>{if(!i&&fl.indexOf(r)>=0){const o=n.getUint8(5);dl.indexOf(o)<0&&(i=!0)}}),i)).catch(()=>i)},ks=(s,i)=>{const e={};return(...t)=>{const r=i(t,e);return r in e?e[r]:e[r]=s(...t)}},Os=(s,i)=>{const[e]=s,t=Object.keys(i).map(r=>parseInt(r,10)).sort((r,n)=>r-n);for(let r=0;r<t.length;r++){const n=t[r],o=!!i[n];if(n>e&&o||n<e&&!o)return n}return e},ue={R:55,G:110,B:165,A:255},ml=`rgba(${ue.R}, ${ue.G}, ${ue.B}, ${ue.A/255})`,Ps=(s,i)=>{try{const e=[s-1,i-1,1,1],{canvas:t,ctx:r}=qe();t.width=1,t.height=1;const{canvas:n,ctx:o}=qe();n.width=s,n.height=i,o&&(o.fillStyle=ml,o.fillRect(...e),r.drawImage(n,s-1,i-1,1,1,0,0,1,1));const l=r&&r.getImageData(0,0,1,1).data;let a=!1;return l&&(a=l[0]===ue.R&&l[1]===ue.G&&l[2]===ue.B&&l[3]===ue.A),n.width=n.height=1,a}catch{return console.error(`Failed to test for max canvas size of ${s}x${i}.`),!1}};function Ls(s){return(...i)=>new Promise(e=>{setTimeout(()=>{const t=s(...i);e(t)},0)})}const gl=Ls(ks(Ps,Os)),bl=Ls(ks(Ps,Os)),Us=async(s,i)=>{const e=Ri.squareSide.find(o=>o*o>=s*i),t=Ri.dimension.find(o=>o>=s&&o>=i);if(!e||!t)throw new Error("Not supported");const[r,n]=await Promise.all([gl(e,e),bl(t,1)]);if(r&&n)return!0;throw new Error("Not supported")},Rs=async(s,i,e)=>{try{const{ctx:t,canvas:r}=qe();return r.width=i,r.height=e,t.imageSmoothingQuality="high",t.drawImage(s,0,0,i,e),s instanceof HTMLImageElement&&(s.src="//:0"),s instanceof HTMLCanvasElement&&(s.width=s.height=1),r}catch(t){throw new Error("Canvas resize error",{cause:t})}},_l=({img:s,targetW:i,targetH:e})=>Rs(s,i,e),yl=function({sourceW:s,targetW:i,targetH:e,step:t}){const r=[];let n=i,o=e;do r.push([n,o]),n=Math.round(n/t),o=Math.round(o/t);while(n<s*t);return r.reverse()},vl=({img:s,sourceW:i,targetW:e,targetH:t,step:r})=>yl({sourceW:i,targetW:e,targetH:t,step:r}).reduce((o,[l,a])=>o.then(c=>Us(l,a).then(()=>Rs(c,l,a)).catch(()=>c)),Promise.resolve(s)),Cl=()=>/iPad|iPhone|iPod/.test(navigator.platform)?!0:navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&/MacIntel/.test(navigator.platform),wl=navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&/MacIntel/.test(navigator.platform),xt=.71,El=(s,i)=>{if(s.width*xt*s.height*xt<i.size)throw new Error("Not required");const e=s.width,t=s.height,r=e/t,n=Math.floor(Math.sqrt(i.size*r)),o=Math.floor(i.size/Math.sqrt(i.size*r));return Us(n,o).then(()=>{const{ctx:l}=qe();return"imageSmoothingQuality"in l&&!Cl()&&!wl?_l({img:s,targetW:n,targetH:o}):vl({img:s,sourceW:e,targetW:n,targetH:o,step:xt})}).catch(()=>Promise.reject("Not supported"))},Al=async(s,i)=>{try{if(await pl(s))throw new Error("Should skipped");const t=await Promise.allSettled([rl(s),ol(),Qo(s)]),n=!t.some(g=>g.status==="rejected"),[o,l,a]=t,c=await tl(s).catch(()=>s),h=await ul(URL.createObjectURL(c));URL.revokeObjectURL(h.src);const d=await El(h,i);let f="image/jpeg",m=(i==null?void 0:i.quality)||.8;!n&&sl(d)&&(f="image/png",m=void 0);let p=await il(d,f,m);if(n&&o.status==="fulfilled"&&o.value){const g=o.value,A=l.status==="fulfilled"?l.value:!1;p=await cl(p,g,A)}return n&&a.status==="fulfilled"&&a.value.length>0&&(p=await Is(p,a.value)),p}catch(e){let t;throw e instanceof Error&&(t=e.message),typeof e=="string"&&(t=e),new Error(`Failed to shrink image. ${t?`Message: "${t}".`:""}`,{cause:e})}};function Ms(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function Tl(s="#fff",i="rgba(0, 0, 0, .1)"){return Ms(`<svg height="20" width="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
29
+ `;Zt.bindAttributes({type:null});class ol extends ${initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let e=le(i),t="";e.forEach(r=>{t+=`<lr-source-btn type="${r}"></lr-source-btn>`}),this.cfg.sourceListWrap?this.innerHTML=t:this.outerHTML=t})}}const bt=()=>{const s=[];return{stack:s,promiseReadJpegChunks:e=>new Promise((t,r)=>{let n=2;const o=(c,h)=>{const d=new FileReader;d.addEventListener("load",()=>{h(new DataView(d.result))}),d.addEventListener("error",f=>{r(`Reader error: ${f}`)}),d.readAsArrayBuffer(c)},l=()=>o(e.slice(n,n+128),c=>{let h,d,f;for(h=d=0,f=c.byteLength;f>=0?d<f:d>f;h=f>=0?++d:--d)if(c.getUint8(h)===255){n+=h;break}a()}),a=()=>{const c=n;return o(e.slice(n,n+=4),h=>{if(h.byteLength!==4||h.getUint8(0)!==255){r("Corrupted");return}const d=h.getUint8(1);if(d===218){t(!0);return}const f=h.getUint16(2)-2;return o(e.slice(n,n+=f),m=>{if(m.byteLength!==f){r("Corrupted");return}s.push({startPos:c,length:f,marker:d,view:m}),l()})})};FileReader&&DataView||r("Not Support"),o(e.slice(0,2),c=>{c.getUint16(0)!==65496&&r("Not jpeg"),l()})})}},ll=async s=>{const i=[],{promiseReadJpegChunks:e,stack:t}=bt();return await e(s),t.forEach(({marker:r,view:n})=>{r===226&&n.getUint32(0)===1229144927&&n.getUint32(4)===1347571526&&n.getUint32(8)===1229735168&&i.push(n)}),i},Os=async(s,i,e)=>{{const t=[],r=[],{promiseReadJpegChunks:n,stack:o}=bt();await n(s),o.forEach(c=>{if(c.marker===i)return t.push(c.startPos),r.push(c.length)});const l=[s.slice(0,2)];for(const c of e){const h=new DataView(new ArrayBuffer(4));h.setUint16(0,65280+i),h.setUint16(2,c.byteLength+2),l.push(h.buffer),l.push(c)}let a=2;for(let c=0;c<t.length;c++)t[c]>a&&l.push(s.slice(a,t[c])),a=t[c]+r[c]+4;return l.push(s.slice(a,s.size)),new Blob(l,{type:s.type})}},al=226,ks=(s,i)=>Os(s,al,i.map(e=>e.buffer)),cl=async s=>{try{return await ks(s,[])}catch(i){throw new Error(`Failed to strip ICC profile: ${i}`)}},hl=(s,i,e)=>new Promise((t,r)=>{const n=o=>{if(!o){r("Failed to convert canvas to blob");return}t(o)};s.toBlob(n,i,e),s.width=s.height=1}),We=()=>{const s=document.createElement("canvas"),i=s.getContext("2d");return{canvas:s,ctx:i}},ul=s=>{const{ctx:e,canvas:t}=We();t.width=t.height=50,e.drawImage(s,0,0,50,50);const r=e.getImageData(0,0,50,50).data;t.width=t.height=1;for(let n=3;n<r.length;n+=4)if(r[n]<254)return!0;return!1},dl=async s=>{let i=null;const{promiseReadJpegChunks:e,stack:t}=bt();return await e(s),t.forEach(({marker:r,view:n})=>{if(!i&&r===225&&n.byteLength>=14&&n.getUint32(0)===1165519206&&n.getUint16(4)===0){i=n;return}}),i},fl="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4QA6RXhpZgAATU0AKgAAAAgAAwESAAMAAAABAAYAAAEoAAMAAAABAAIAAAITAAMAAAABAAEAAAAAAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wAALCAABAAIBASIA/8QAJgABAAAAAAAAAAAAAAAAAAAAAxABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQAAPwBH/9k=";let Ze;const pl=()=>new Promise(s=>{if(Ze!==void 0)s(Ze);else{const i=new Image;i.addEventListener("load",()=>{Ze=i.naturalWidth<i.naturalHeight,i.src="//:0",s(Ze)}),i.src=fl}}),ml=(s,i)=>{let e,t,r,n;if(!s||s.byteLength<14||s.getUint32(0)!==1165519206||s.getUint16(4)!==0)return;if(s.getUint16(6)===18761)t=!0;else if(s.getUint16(6)===19789)t=!1;else return;if(s.getUint16(8,t)!==42)return;r=8+s.getUint32(10,t);const o=s.getUint16(r-2,t);for(e=0,n=o;n>=0?e<n:e>n;n>=0?++e:--e){if(s.byteLength<r+10)return;s.getUint16(r,t)===274&&i(r+8,t),r+=12}},gl=(s,i)=>{ml(s,(e,t)=>s.setUint16(e,i,t))},bl=async(s,i,e)=>(e&&gl(i,1),Os(s,225,[i.buffer])),_l=(s,i)=>new Promise((e,t)=>{i&&(s.src=i),s.complete?e(s):(s.addEventListener("load",()=>{e(s)}),s.addEventListener("error",()=>{t(new Error("Failed to load image. Probably not an image."))}))}),vl=s=>_l(new Image,s),yl=[1,3],Cl=[192,193,194,195,197,198,199,201,202,203,205,206,207],Ri={squareSide:[Math.floor(Math.sqrt(5*1e3*1e3)),4096,8192,11180,10836,11402,14188,16384],dimension:[4096,8192,16384,32767,65535]},wl=async s=>{let i=!1;const{promiseReadJpegChunks:e,stack:t}=bt();return await e(s).then(()=>(t.forEach(({marker:r,view:n})=>{if(!i&&Cl.indexOf(r)>=0){const o=n.getUint8(5);yl.indexOf(o)<0&&(i=!0)}}),i)).catch(()=>i)},Ls=(s,i)=>{const e={};return(...t)=>{const r=i(t,e);return r in e?e[r]:e[r]=s(...t)}},Ps=(s,i)=>{const[e]=s,t=Object.keys(i).map(r=>parseInt(r,10)).sort((r,n)=>r-n);for(let r=0;r<t.length;r++){const n=t[r],o=!!i[n];if(n>e&&o||n<e&&!o)return n}return e},he={R:55,G:110,B:165,A:255},El=`rgba(${he.R}, ${he.G}, ${he.B}, ${he.A/255})`,Us=(s,i)=>{try{const e=[s-1,i-1,1,1],{canvas:t,ctx:r}=We();t.width=1,t.height=1;const{canvas:n,ctx:o}=We();n.width=s,n.height=i,o&&(o.fillStyle=El,o.fillRect(...e),r.drawImage(n,s-1,i-1,1,1,0,0,1,1));const l=r&&r.getImageData(0,0,1,1).data;let a=!1;return l&&(a=l[0]===he.R&&l[1]===he.G&&l[2]===he.B&&l[3]===he.A),n.width=n.height=1,a}catch{return console.error(`Failed to test for max canvas size of ${s}x${i}.`),!1}};function Rs(s){return(...i)=>new Promise(e=>{setTimeout(()=>{const t=s(...i);e(t)},0)})}const Al=Rs(Ls(Us,Ps)),Tl=Rs(Ls(Us,Ps)),Ms=async(s,i)=>{const e=Ri.squareSide.find(o=>o*o>=s*i),t=Ri.dimension.find(o=>o>=s&&o>=i);if(!e||!t)throw new Error("Not supported");const[r,n]=await Promise.all([Al(e,e),Tl(t,1)]);if(r&&n)return!0;throw new Error("Not supported")},Fs=async(s,i,e)=>{try{const{ctx:t,canvas:r}=We();return r.width=i,r.height=e,t.imageSmoothingQuality="high",t.drawImage(s,0,0,i,e),s instanceof HTMLImageElement&&(s.src="//:0"),s instanceof HTMLCanvasElement&&(s.width=s.height=1),r}catch(t){throw new Error("Canvas resize error",{cause:t})}},$l=({img:s,targetW:i,targetH:e})=>Fs(s,i,e),Sl=function({sourceW:s,targetW:i,targetH:e,step:t}){const r=[];let n=i,o=e;do r.push([n,o]),n=Math.round(n/t),o=Math.round(o/t);while(n<s*t);return r.reverse()},xl=({img:s,sourceW:i,targetW:e,targetH:t,step:r})=>Sl({sourceW:i,targetW:e,targetH:t,step:r}).reduce((o,[l,a])=>o.then(c=>Ms(l,a).then(()=>Fs(c,l,a)).catch(()=>c)),Promise.resolve(s)),Il=()=>/iPad|iPhone|iPod/.test(navigator.platform)?!0:navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&/MacIntel/.test(navigator.platform),Ol=navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&/MacIntel/.test(navigator.platform),$t=.71,kl=(s,i)=>{if(s.width*$t*s.height*$t<i.size)throw new Error("Not required");const e=s.width,t=s.height,r=e/t,n=Math.floor(Math.sqrt(i.size*r)),o=Math.floor(i.size/Math.sqrt(i.size*r));return Ms(n,o).then(()=>{const{ctx:l}=We();return"imageSmoothingQuality"in l&&!Il()&&!Ol?$l({img:s,targetW:n,targetH:o}):xl({img:s,sourceW:e,targetW:n,targetH:o,step:$t})}).catch(()=>Promise.reject("Not supported"))},Ll=async(s,i)=>{try{if(await wl(s))throw new Error("Should skipped");const t=await Promise.allSettled([dl(s),pl(),ll(s)]),n=!t.some(g=>g.status==="rejected"),[o,l,a]=t,c=await cl(s).catch(()=>s),h=await vl(URL.createObjectURL(c));URL.revokeObjectURL(h.src);const d=await kl(h,i);let f="image/jpeg",m=(i==null?void 0:i.quality)||.8;!n&&ul(d)&&(f="image/png",m=void 0);let p=await hl(d,f,m);if(n&&o.status==="fulfilled"&&o.value){const g=o.value,w=l.status==="fulfilled"?l.value:!1;p=await bl(p,g,w)}return n&&a.status==="fulfilled"&&a.value.length>0&&(p=await ks(p,a.value)),p}catch(e){let t;throw e instanceof Error&&(t=e.message),typeof e=="string"&&(t=e),new Error(`Failed to shrink image. ${t?`Message: "${t}".`:""}`,{cause:e})}};function Ds(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function Pl(s="#fff",i="rgba(0, 0, 0, .1)"){return Ds(`<svg height="20" width="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
30
30
  <rect x="0" y="0" width="20" height="20" fill="${s}" />
31
31
  <rect x="0" y="0" width="10" height="10" fill="${i}" />
32
32
  <rect x="10" y="10" width="10" height="10" fill="${i}" />
33
- </svg>`)}function Mt(s="hsl(209, 21%, 65%)",i=32,e=32){return Ms(`
33
+ </svg>`)}function Mi(s="hsl(209, 21%, 65%)",i=32,e=32){return Ds(`
34
34
  <svg width="${i}" height="${e}" viewBox="0 0 30 30" fill="none" xmlns="http://www.w3.org/2000/svg">
35
35
  <path fill-rule="evenodd" fill="${s}" d="M9.68848 8.70068C9.68848 8.42454 9.91233 8.20068 10.1885 8.20068H15.0885C15.2211 8.20068 15.3483 8.25336 15.442 8.34713L20.342 13.2471C20.4358 13.3409 20.4885 13.4681 20.4885 13.6007V21.3007C20.4885 21.5768 20.2646 21.8007 19.9885 21.8007H10.1885C9.91233 21.8007 9.68848 21.5768 9.68848 21.3007V8.70068ZM10.6885 9.20068V20.8007H19.4885V14.1007L15.0885 14.1007C14.8123 14.1007 14.5885 13.8768 14.5885 13.6007L14.5885 9.20068H10.6885ZM15.5885 9.90779L18.7814 13.1007L15.5885 13.1007L15.5885 9.90779Z"/>
36
36
  </svg>
37
- `)}function $l(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let e=document.createElement("canvas"),t=e.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(e.width=i,e.height=i*a):(e.height=i,e.width=i/a),t.fillStyle="rgb(240, 240, 240)",t.fillRect(0,0,e.width,e.height),t.drawImage(r,0,0,e.width,e.height),e.toBlob(c=>{if(!c){l();return}let h=URL.createObjectURL(c);o(h)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}const Mi=16384,Sl=/^([0-9]+)x([0-9]+)(?:\s+(\d{1,2}|100)%)?$/i,xl=s=>{const i=Sl.exec(s==null?void 0:s.toLocaleLowerCase())||[];if(!i.length)return!1;const e=i[1]*i[2],t=Mi*Mi;return e>t?(console.warn(`Shrinked size can not be larger than ${Math.floor(t/1e3/1e3)}MP. You have set ${i[1]}x${i[2]} (${Math.ceil(e/1e3/100)/10}MP).`),!1):{quality:i[3]?i[3]/100:void 0,size:e}},B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3)});class we extends ${constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",H(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",H(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,state:B.IDLE,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(e=>e.activityType===b.activities.DETAILS)?this.$["*currentActivity"]=b.activities.DETAILS:this.$["*currentActivity"]=b.activities.CLOUD_IMG_EDIT},onRemove:()=>{this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let e of this._entrySubs)e.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(e){let[t]=e;this._isIntersecting=t.isIntersecting,t.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),t.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let e=this._entry,t=B.IDLE;e.getValue("errors").length>0?t=B.FAILED:e.getValue("isUploading")?t=B.UPLOADING:e.getValue("fileInfo")&&(t=B.FINISHED),this.$.state=t}async _generateThumbnail(){var t;if(!this._entry)return;let e=this._entry;if(e.getValue("fileInfo")&&e.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(V(We(this.cfg.cdnCname,this._entry.getValue("uuid")),le(e.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=e.getValue("thumbUrl");o!==n&&(e.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!e.getValue("thumbUrl"))if((t=e.getValue("file"))!=null&&t.type.includes("image"))try{let r=await $l(e.getValue("file"),this.cfg.thumbSize);e.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");e.setValue("thumbUrl",Mt(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");e.setValue("thumbUrl",Mt(r))}}_subEntry(e,t){let r=this._entry.subscribe(e,n=>{this.isConnected&&t(n)});this._entrySubs.add(r)}_handleEntryId(e){var r;this._reset();let t=(r=this.uploadCollection)==null?void 0:r.read(e);this._entry=t,t&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||t.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=t.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",e=>{this._handleEntryId(e)}),this.sub("state",e=>{this._handleState(e)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{we.activeInstances.forEach(e=>{e===this?e.setAttribute("focused",""):e.removeAttribute("focused")})},this.sub("*uploadTrigger",e=>{e.has(this._entry.uid)&&setTimeout(()=>this.isConnected&&this.upload())}),we.activeInstances.add(this)}_handleState(e){var t,r,n,o;e===B.FAILED?this.$.badgeIcon="badge-error":e===B.FINISHED&&(this.$.badgeIcon="badge-success"),e===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0,this.set$({isFailed:e===B.FAILED,isUploading:e===B.UPLOADING,isFinished:e===B.FINISHED,progressVisible:e===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((t=this._entry)==null?void 0:t.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})}destroyCallback(){super.destroyCallback(),we.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 e;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(e=this._observer)==null||e.disconnect()}_settingsOfShrink(){return xl(this.cfg.imageShrink)}_processShrink(e){return Al(e,this._settingsOfShrink())}async upload(){var r,n;let e=this._entry;if(!this.uploadCollection.read(e.uid)||e.getValue("fileInfo")||e.getValue("isUploading")||e.getValue("errors").length>0)return;const t=this.cfg.multiple?this.cfg.multipleMax:1;if(!(t&&this.uploadCollection.size>t)){this._debouncedCalculateState(),e.setValue("isUploading",!0),e.setValue("errors",[]);try{let o=new AbortController;e.setValue("abortController",o);const l=async()=>{let c=e.getValue("file");c&&this.cfg.imageShrink&&(c=await this._processShrink(c).catch(()=>c));const h=c||e.getValue("externalUrl")||e.getValue("uuid"),f={...this.getUploadClientOptions(),fileName:e.getValue("fileName"),source:e.getValue("source"),onProgress:m=>{if(m.isComputable){let p=m.value*100;e.setValue("uploadProgress",p)}},signal:o.signal,metadata:await this.getMetadataFor(e.uid)};return this.debugPrint("upload options",h,f),cs(h,f)};let a=await this.$["*uploadQueue"].add(l);e.setMultipleValues({fileInfo:a,isUploading:!1,fileName:a.originalFilename,fileSize:a.size,isImage:a.isImage,mimeType:((n=(r=a.contentInfo)==null?void 0:r.mime)==null?void 0:n.mime)??a.mimeType,uuid:a.uuid,cdnUrl:e.getValue("cdnUrl")??a.cdnUrl,cdnUrlModifiers:e.getValue("cdnUrlModifiers")??"",uploadProgress:100}),e===this._entry&&this._debouncedCalculateState()}catch(o){o instanceof Ee&&o.isCancel?e.setMultipleValues({isUploading:!1,uploadProgress:0}):e.setMultipleValues({isUploading:!1,uploadProgress:0,uploadError:o}),e===this._entry&&this._debouncedCalculateState()}}}}we.template=`
37
+ `)}function Ul(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let e=document.createElement("canvas"),t=e.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(e.width=i,e.height=i*a):(e.height=i,e.width=i/a),t.fillStyle="rgb(240, 240, 240)",t.fillRect(0,0,e.width,e.height),t.drawImage(r,0,0,e.width,e.height),e.toBlob(c=>{if(!c){l();return}let h=URL.createObjectURL(c);o(h)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}const Fi=16384,Rl=/^([0-9]+)x([0-9]+)(?:\s+(\d{1,2}|100)%)?$/i,Ml=s=>{const i=Rl.exec(s==null?void 0:s.toLocaleLowerCase())||[];if(!i.length)return!1;const e=i[1]*i[2],t=Fi*Fi;return e>t?(console.warn(`Shrinked size can not be larger than ${Math.floor(t/1e3/1e3)}MP. You have set ${i[1]}x${i[2]} (${Math.ceil(e/1e3/100)/10}MP).`),!1):{quality:i[3]?i[3]/100:void 0,size:e}},z=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3)});class we extends x{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",H(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",H(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,state:z.IDLE,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(e=>e.activityType===_.activities.DETAILS)?this.$["*currentActivity"]=_.activities.DETAILS:this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT},onRemove:()=>{this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let e of this._entrySubs)e.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(e){let[t]=e;this._isIntersecting=t.isIntersecting,t.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),t.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let e=this._entry,t=z.IDLE;e.getValue("errors").length>0?t=z.FAILED:e.getValue("isUploading")?t=z.UPLOADING:e.getValue("fileInfo")&&(t=z.FINISHED),this.$.state=t}async _generateThumbnail(){var t;if(!this._entry)return;let e=this._entry;if(e.getValue("fileInfo")&&e.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(j(He(this.cfg.cdnCname,this._entry.getValue("uuid")),pe(e.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=e.getValue("thumbUrl");o!==n&&(e.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!e.getValue("thumbUrl"))if((t=e.getValue("file"))!=null&&t.type.includes("image"))try{let r=await Ul(e.getValue("file"),this.cfg.thumbSize);e.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");e.setValue("thumbUrl",Mi(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");e.setValue("thumbUrl",Mi(r))}}_subEntry(e,t){let r=this._entry.subscribe(e,n=>{this.isConnected&&t(n)});this._entrySubs.add(r)}_handleEntryId(e){var r;this._reset();let t=(r=this.uploadCollection)==null?void 0:r.read(e);this._entry=t,t&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||t.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=t.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",e=>{this._handleEntryId(e)}),this.sub("state",e=>{this._handleState(e)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{we.activeInstances.forEach(e=>{e===this?e.setAttribute("focused",""):e.removeAttribute("focused")})},this.sub("*uploadTrigger",e=>{e.has(this._entry.uid)&&setTimeout(()=>this.isConnected&&this.upload())}),we.activeInstances.add(this)}_handleState(e){var t,r,n,o;e===z.FAILED?this.$.badgeIcon="badge-error":e===z.FINISHED&&(this.$.badgeIcon="badge-success"),e===z.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0,this.set$({isFailed:e===z.FAILED,isUploading:e===z.UPLOADING,isFinished:e===z.FINISHED,progressVisible:e===z.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((t=this._entry)==null?void 0:t.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})}destroyCallback(){super.destroyCallback(),we.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 e;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(e=this._observer)==null||e.disconnect()}_settingsOfShrink(){return Ml(this.cfg.imageShrink)}_processShrink(e){return Ll(e,this._settingsOfShrink())}async upload(){var r,n;let e=this._entry;if(!this.uploadCollection.read(e.uid)||e.getValue("fileInfo")||e.getValue("isUploading")||e.getValue("errors").length>0)return;const t=this.cfg.multiple?this.cfg.multipleMax:1;if(!(t&&this.uploadCollection.size>t)){this._debouncedCalculateState(),e.setValue("isUploading",!0),e.setValue("errors",[]);try{let o=new AbortController;e.setValue("abortController",o);const l=async()=>{let c=e.getValue("file");c&&this.cfg.imageShrink&&(c=await this._processShrink(c).catch(()=>c));const h=c||e.getValue("externalUrl")||e.getValue("uuid"),f={...this.getUploadClientOptions(),fileName:e.getValue("fileName"),source:e.getValue("source"),onProgress:m=>{if(m.isComputable){let p=m.value*100;e.setValue("uploadProgress",p)}},signal:o.signal,metadata:await this.getMetadataFor(e.uid)};return this.debugPrint("upload options",h,f),as(h,f)};let a=await this.$["*uploadQueue"].add(l);e.setMultipleValues({fileInfo:a,isUploading:!1,fileName:a.originalFilename,fileSize:a.size,isImage:a.isImage,mimeType:((n=(r=a.contentInfo)==null?void 0:r.mime)==null?void 0:n.mime)??a.mimeType,uuid:a.uuid,cdnUrl:e.getValue("cdnUrl")??a.cdnUrl,cdnUrlModifiers:e.getValue("cdnUrlModifiers")??"",uploadProgress:100}),e===this._entry&&this._debouncedCalculateState()}catch(o){o instanceof Ee&&o.isCancel?e.setMultipleValues({isUploading:!1,uploadProgress:0}):e.setMultipleValues({isUploading:!1,uploadProgress:0,uploadError:o}),e===this._entry&&this._debouncedCalculateState()}}}}we.template=`
38
38
  <div class="inner" set="@finished: isFinished; @uploading: isUploading; @failed: isFailed; @focused: isFocused">
39
39
  <div class="thumb" set="style.backgroundImage: thumbUrl">
40
40
  <div class="badge">
@@ -58,11 +58,11 @@
58
58
  </div>
59
59
  <lr-progress-bar class="progress-bar" set="value: progressValue; visible: progressVisible;"> </lr-progress-bar>
60
60
  </div>
61
- `;we.activeInstances=new Set;class Qt extends k{constructor(){super();u(this,"_handleBackdropClick",()=>{this._closeDialog()});u(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});u(this,"_handleDialogClose",()=>{this._closeDialog()});u(this,"_handleDialogMouseDown",e=>{this._mouseDownTarget=e.target});u(this,"_handleDialogMouseUp",e=>{e.target===this.ref.dialog&&e.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 e=document.createElement("div");e.className="backdrop",this.appendChild(e),e.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",e=>{this.$.isOpen!==e&&(this.$.isOpen=e),e&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",e=>{e?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",e=>{e?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)}}u(Qt,"StateConsumerScope","modal");Qt.template=`
61
+ `;we.activeInstances=new Set;class Qt extends ${constructor(){super();u(this,"_handleBackdropClick",()=>{this._closeDialog()});u(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});u(this,"_handleDialogClose",()=>{this._closeDialog()});u(this,"_handleDialogMouseDown",e=>{this._mouseDownTarget=e.target});u(this,"_handleDialogMouseUp",e=>{e.target===this.ref.dialog&&e.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 e=document.createElement("div");e.className="backdrop",this.appendChild(e),e.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",e=>{this.$.isOpen!==e&&(this.$.isOpen=e),e&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",e=>{e?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",e=>{e?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)}}u(Qt,"StateConsumerScope","modal");Qt.template=`
62
62
  <dialog ref="dialog">
63
63
  <slot></slot>
64
64
  </dialog>
65
- `;const Fs=(s,i)=>{let e,t,r;const n=(...o)=>{e?(clearTimeout(t),t=setTimeout(()=>{Date.now()-r>=i&&(s(...o),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...o),r=Date.now(),e=!0)};return Object.defineProperty(n,"cancel",{configurable:!1,writable:!1,enumerable:!1,value:()=>{clearTimeout(t)}}),n};class Ns extends ${constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",b.activities.UPLOAD_LIST);u(this,"_throttledHandleCollectionUpdate",Fs(()=>{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(x.UPLOAD_CLICK),this.uploadAll(),this._throttledHandleCollectionUpdate()},onDone:()=>{this.emit(x.DONE_CLICK,this.getOutputCollectionState()),this.doneFlow()},onCancel:()=>{this.uploadCollection.clearAll()}}}_updateUploadsState(){const e=this.getOutputCollectionState(),t={total:e.totalCount,succeed:e.successCount,uploading:e.uploadingCount,failed:e.failedCount},r=!e.errors.some(f=>f.type==="TOO_MANY_FILES"||f.type==="TOO_FEW_FILES"),n=e.errors.some(f=>f.type==="TOO_MANY_FILES"),o=e.totalCount===(this.cfg.multiple?this.cfg.multipleMax:1),l=t.failed===0;let a=!1,c=!1,h=!1;t.total-t.succeed-t.uploading-t.failed>0&&r?a=!0:(c=!0,h=t.total===t.succeed&&r&&l),this.set$({doneBtnVisible:c,doneBtnEnabled:h,uploadBtnVisible:a,addMoreBtnEnabled:t.total===0||!n&&!o,addMoreBtnVisible:!o||this.cfg.multiple,headerText:this._getHeaderText(t)})}_getHeaderText(e){const t=r=>{const n=e[r];return this.l10n(`header-${r}`,{count:n})};return e.uploading>0?t("uploading"):e.failed>0?t("failed"):e.succeed>0?t("succeed"):t("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",e=>{!this.couldOpenActivity&&e===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._throttledHandleCollectionUpdate),this.sub("*uploadList",e=>{this._throttledHandleCollectionUpdate(),this.set$({hasFiles:e.length>0}),this.cfg.confirmUpload||this.uploadAll()},!1),this.sub("*collectionErrors",e=>{const t=e.filter(r=>r.type!=="SOME_FILES_HAS_ERRORS")[0];if(!t){this.set$({commonErrorMessage:null});return}this.set$({commonErrorMessage:t.message})})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._throttledHandleCollectionUpdate)}}Ns.template=`
65
+ `;const Ns=(s,i)=>{let e,t,r;const n=(...o)=>{e?(clearTimeout(t),t=setTimeout(()=>{Date.now()-r>=i&&(s(...o),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...o),r=Date.now(),e=!0)};return Object.defineProperty(n,"cancel",{configurable:!1,writable:!1,enumerable:!1,value:()=>{clearTimeout(t)}}),n};class zs extends x{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",_.activities.UPLOAD_LIST);u(this,"_throttledHandleCollectionUpdate",Ns(()=>{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(I.UPLOAD_CLICK),this.uploadAll(),this._throttledHandleCollectionUpdate()},onDone:()=>{this.emit(I.DONE_CLICK,this.getOutputCollectionState()),this.doneFlow()},onCancel:()=>{this.uploadCollection.clearAll()}}}_updateUploadsState(){const e=this.getOutputCollectionState(),t={total:e.totalCount,succeed:e.successCount,uploading:e.uploadingCount,failed:e.failedCount},r=!e.errors.some(f=>f.type==="TOO_MANY_FILES"||f.type==="TOO_FEW_FILES"),n=e.errors.some(f=>f.type==="TOO_MANY_FILES"),o=e.totalCount===(this.cfg.multiple?this.cfg.multipleMax:1),l=t.failed===0;let a=!1,c=!1,h=!1;t.total-t.succeed-t.uploading-t.failed>0&&r?a=!0:(c=!0,h=t.total===t.succeed&&r&&l),this.set$({doneBtnVisible:c,doneBtnEnabled:h,uploadBtnVisible:a,addMoreBtnEnabled:t.total===0||!n&&!o,addMoreBtnVisible:!o||this.cfg.multiple}),this.bindL10n("headerText",()=>this._getHeaderText(t))}_getHeaderText(e){const t=r=>{const n=e[r];return this.l10n(`header-${r}`,{count:n})};return e.uploading>0?t("uploading"):e.failed>0?t("failed"):e.succeed>0?t("succeed"):t("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",e=>{!this.couldOpenActivity&&e===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observeProperties(this._throttledHandleCollectionUpdate),this.sub("*uploadList",e=>{this._throttledHandleCollectionUpdate(),this.set$({hasFiles:e.length>0}),this.cfg.confirmUpload||this.uploadAll()},!1),this.sub("*collectionErrors",e=>{const t=e.filter(r=>r.type!=="SOME_FILES_HAS_ERRORS")[0];if(!t){this.set$({commonErrorMessage:null});return}this.set$({commonErrorMessage:t.message})})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserveProperties(this._throttledHandleCollectionUpdate)}}zs.template=`
66
66
  <lr-activity-header>
67
67
  <span class="header-text">{{headerText}}</span>
68
68
  <button type="button" class="mini-btn close-btn" set="onclick: *closeModal">
@@ -103,7 +103,7 @@
103
103
  </div>
104
104
 
105
105
  <lr-drop-area ghost></lr-drop-area>
106
- `;class Ds extends ${constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.URL);u(this,"init$",{...this.init$,importDisabled:!0,onUpload:e=>{e.preventDefault();let t=this.ref.input.value;this.addFileFromUrl(t,{source:Q.URL_TAB}),this.$["*currentActivity"]=b.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:e=>{let t=e.target.value;this.set$({importDisabled:!t})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}}Ds.template=`
106
+ `;class Vs extends x{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"activityType",_.activities.URL);u(this,"init$",{...this.init$,importDisabled:!0,onUpload:e=>{e.preventDefault();let t=this.ref.input.value;this.addFileFromUrl(t,{source:Z.URL_TAB}),this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:e=>{let t=e.target.value;this.set$({importDisabled:!t})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}}Vs.template=`
107
107
  <lr-activity-header>
108
108
  <button type="button" class="mini-btn" set="onclick: *historyBack">
109
109
  <lr-icon name="back"></lr-icon>
@@ -122,9 +122,10 @@
122
122
  type="submit"
123
123
  class="url-upload-btn primary-btn"
124
124
  set="onclick: onUpload; @disabled: importDisabled"
125
+ l10n="upload-url"
125
126
  ></button>
126
127
  </form>
127
- `;const Fi=()=>typeof navigator.permissions<"u";class zs extends ${constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.CAMERA);u(this,"_unsubPermissions",null);u(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Fi(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:e=>{this._selectedCameraId=e.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});u(this,"_onActivate",()=>{Fi()&&this._subscribePermissions(),this._capture()});u(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});u(this,"_handlePermissionsChange",()=>{this._capture()});u(this,"_setPermissionsState",H(e=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",e==="granted"),e==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):e==="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(e){console.log("Failed to use permissions API. Fallback to manual request mode.",e),this._capture()}}async _capture(){let e={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(e.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let t=await navigator.mediaDevices.getUserMedia(e);t.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=t,this._capturing=!0,this._setPermissionsState("granted")}catch(t){this._setPermissionsState("denied"),this.$.originalErrorMessage=t.message}}_stopCapture(){var e;this._capturing&&((e=this.$.video)==null||e.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);const e=Date.now(),t=`camera-${e}.jpeg`,r="image/jpeg";this._canvas.toBlob(n=>{let o=new File([n],t,{lastModified:e,type:r});this.addFileFromObject(o,{source:Q.CAMERA}),this.set$({"*currentActivity":b.activities.UPLOAD_LIST})},r)}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",e=>{this.$.videoTransformCss=e?"scaleX(-1)":null});try{let t=(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}));t.length>1&&(this.$.cameraSelectOptions=t,this.$.cameraSelectHidden=!1)}catch{}}}zs.template=`
128
+ `;const Di=()=>typeof navigator.permissions<"u";class Bs extends x{constructor(){super(...arguments);u(this,"couldBeCtxOwner",!0);u(this,"activityType",_.activities.CAMERA);u(this,"_unsubPermissions",null);u(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Di(),cameraSelectOptions:null,cameraSelectHidden:!0,l10nMessage:"",onCameraSelectChange:e=>{this._selectedCameraId=e.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});u(this,"_onActivate",()=>{Di()&&this._subscribePermissions(),this._capture()});u(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});u(this,"_handlePermissionsChange",()=>{this._capture()});u(this,"_setPermissionsState",H(e=>{this.classList.toggle("initialized",e==="granted"),e==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):e==="prompt"?(this.$.l10nMessage="camera-permissions-prompt",this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage="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(e){console.log("Failed to use permissions API. Fallback to manual request mode.",e),this._capture()}}async _capture(){let e={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(e.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let t=await navigator.mediaDevices.getUserMedia(e);t.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=t,this._capturing=!0,this._setPermissionsState("granted")}catch(t){this._setPermissionsState("denied"),console.error("Failed to capture camera",t)}}_stopCapture(){var e;this._capturing&&((e=this.$.video)==null||e.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);const e=Date.now(),t=`camera-${e}.jpeg`,r="image/jpeg";this._canvas.toBlob(n=>{let o=new File([n],t,{lastModified:e,type:r});this.addFileFromObject(o,{source:Z.CAMERA}),this.set$({"*currentActivity":_.activities.UPLOAD_LIST})},r)}async initCallback(){var e;super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let r=(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput").map((n,o)=>({text:n.label.trim()||`${this.l10n("caption-camera")} ${o+1}`,value:n.deviceId}));r.length>1&&(this.$.cameraSelectOptions=r,this.$.cameraSelectHidden=!1),this._selectedCameraId=(e=r[0])==null?void 0:e.value}catch{}}}Bs.template=`
128
129
  <lr-activity-header>
129
130
  <button type="button" class="mini-btn" set="onclick: *historyBack">
130
131
  <lr-icon name="back"></lr-icon>
@@ -150,8 +151,7 @@
150
151
  ref="video"
151
152
  ></video>
152
153
  <div class="message-box" set="@hidden: messageHidden">
153
- <span>{{l10nMessage}}</span>
154
- <span>{{originalErrorMessage}}</span>
154
+ <span l10n="l10nMessage"></span>
155
155
  <button
156
156
  type="button"
157
157
  set="onclick: onRequestPermissions; @hidden: requestBtnHidden"
@@ -162,61 +162,7 @@
162
162
  <lr-icon name="camera"></lr-icon>
163
163
  </button>
164
164
  </div>
165
- `;class Vs extends ${constructor(){super(...arguments);u(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}}Vs.EventType=x;const ct=Vs;class Bs extends ${constructor(){super(...arguments);u(this,"activityType",b.activities.DETAILS);u(this,"pauseRender",!0);u(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"]=b.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let e=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),t=Mt(e,108,108);this.ref.filePreview.setImageUrl(t),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",e=>{if(!e)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=e;let t=e.getValue("file");if(t){this._file=t;let n=Rt(this._file);n&&!e.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=>{const 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=V(n,le("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}}Bs.template=`
166
- <lr-activity-header>
167
- <button type="button" class="mini-btn" set="onclick: *historyBack">
168
- <lr-icon name="back"></lr-icon>
169
- </button>
170
- <span l10n="caption-edit-file"></span>
171
- <button type="button" class="mini-btn close-btn" set="onclick: *closeModal">
172
- <lr-icon name="close"></lr-icon>
173
- </button>
174
- </lr-activity-header>
175
- <div class="content">
176
- <lr-tabs tab-list="tab-view, tab-details">
177
- <div tab-ctx="tab-details" class="details">
178
- <div class="info-block">
179
- <div class="info-block_name" l10n="file-name"></div>
180
- <input
181
- name="name-input"
182
- ref="file_name_input"
183
- set="value: fileName; oninput: onNameInput; @disabled: !!cdnUrl"
184
- type="text"
185
- />
186
- </div>
187
-
188
- <div class="info-block">
189
- <div class="info-block_name" l10n="file-size"></div>
190
- <div>{{fileSize}}</div>
191
- </div>
192
-
193
- <div class="info-block">
194
- <div class="info-block_name" l10n="cdn-url"></div>
195
- <a class="cdn-link" target="_blank" set="@href: cdnUrl; @disabled: !cdnUrl">{{cdnUrl}}</a>
196
- </div>
197
-
198
- <div>{{errorTxt}}</div>
199
- </div>
200
-
201
- <lr-file-preview tab-ctx="tab-view" set="@checkerboard: checkerboard;" ref="filePreview"> </lr-file-preview>
202
- </lr-tabs>
203
-
204
- <div class="toolbar" set="@edit-disabled: cloudEditBtnHidden">
205
- <button type="button" class="edit-btn secondary-btn" set="onclick: onCloudEdit; @hidden: cloudEditBtnHidden;">
206
- <lr-icon name="edit"></lr-icon>
207
- <span l10n="edit-image"></span>
208
- </button>
209
- <button type="button" class="remove-btn secondary-btn" set="onclick: onRemove">
210
- <lr-icon name="remove"></lr-icon>
211
- <span l10n="remove-from-list"></span>
212
- </button>
213
- <div></div>
214
- <button type="button" class="back-btn primary-btn" set="onclick: onBack">
215
- <span l10n="ok"></span>
216
- </button>
217
- </div>
218
- </div>
219
- `;class Il{constructor(){u(this,"captionL10nStr","confirm-your-action");u(this,"messageL10Str","are-you-sure");u(this,"confirmL10nStr","yes");u(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}}class js extends b{constructor(){super(...arguments);u(this,"activityType",b.activities.CONFIRMATION);u(this,"_defaults",new Il);u(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",e=>{e&&this.set$({"*currentActivity":b.activities.CONFIRMATION,activityCaption:this.l10n(e.captionL10nStr),messageTxt:this.l10n(e.messageL10Str),confirmBtnTxt:this.l10n(e.confirmL10nStr),denyBtnTxt:this.l10n(e.denyL10nStr),onDeny:()=>{e.denyAction()},onConfirm:()=>{e.confirmAction()}})})}}js.template=`
165
+ `;class js extends x{constructor(){super(...arguments);u(this,"requireCtxName",!0)}initCallback(){super.initCallback(),this.$["*eventEmitter"].bindTarget(this)}destroyCallback(){super.destroyCallback(),this.$["*eventEmitter"].unbindTarget(this)}}js.EventType=I;const lt=js;class Fl{constructor(){u(this,"captionL10nStr","confirm-your-action");u(this,"messageL10Str","are-you-sure");u(this,"confirmL10nStr","yes");u(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}}class Hs extends _{constructor(){super(...arguments);u(this,"activityType",_.activities.CONFIRMATION);u(this,"_defaults",new Fl);u(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",e=>{e&&this.set$({"*currentActivity":_.activities.CONFIRMATION,activityCaption:this.l10n(e.captionL10nStr),messageTxt:this.l10n(e.messageL10Str),confirmBtnTxt:this.l10n(e.confirmL10nStr),denyBtnTxt:this.l10n(e.denyL10nStr),onDeny:()=>{e.denyAction()},onConfirm:()=>{e.confirmAction()}})})}}Hs.template=`
220
166
  <lr-activity-header>
221
167
  <button type="button" class="mini-btn" set="onclick: *historyBack">
222
168
  <lr-icon name="back"></lr-icon>
@@ -232,7 +178,7 @@
232
178
  <button type="button" class="deny-btn secondary-btn" set="onclick: onDeny">{{denyBtnTxt}}</button>
233
179
  <button type="button" class="confirm-btn primary-btn" set="onclick: onConfirm">{{confirmBtnTxt}}</button>
234
180
  </div>
235
- `;class Hs extends ${constructor(){super(...arguments);u(this,"init$",{...this.init$,visible:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let e=this.uploadCollection.items().some(t=>this.uploadCollection.read(t).getValue("isUploading"));this.$.visible=e}),this.sub("visible",e=>{e?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",e=>{this.$.value=e})}destroyCallback(){var e;super.destroyCallback(),(e=this._unobserveCollection)==null||e.call(this)}}Hs.template=' <lr-progress-bar set="visible: visible; value: value"></lr-progress-bar> ';class Ws extends k{constructor(){super(...arguments);u(this,"_value",0);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",e=>{if(e===void 0)return;const t=this._value;if(this._value=e,e===0&&t>0){this.ref.line.addEventListener("transitionend",()=>{this.style.setProperty("--l-width",this._value.toString())});return}this.style.setProperty("--l-width",this._value.toString())}),this.defineAccessor("visible",e=>{this.ref.line.classList.toggle("progress--hidden",!e)})}}Ws.template=' <div ref="line" class="progress"></div> ';const pe="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";class ei extends k{constructor(){super();u(this,"init$",{...this.init$,checkerboard:!1,src:pe})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${Tl()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(e){this.$.src=e.src}setImageFile(e){let t=URL.createObjectURL(e);this.$.src=t,this._lastObjectUrl=t}setImageUrl(e){this.$.src=e}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=pe}}ei.template=' <lr-img class="img-view" ref="img" set="@src: src; style.aa: src;" /> ';ei.bindAttributes({checkerboard:"checkerboard"});const Ni="--cfg-ctx-name";class be extends k{get cfgCssCtxName(){return this.getCssData(Ni,!0)}get cfgCtxName(){var e;const i=((e=this.getAttribute("ctx-name"))==null?void 0:e.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){const e=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();e&&this.style.setProperty(Ni,`'${e}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:T.getCtx(this.cfgCtxName)}}get debugCtxName(){return this.cfgCtxName}}function qs(...s){return s.reduce((i,e)=>{if(typeof e=="string")return i[e]=!0,i;for(let t of Object.keys(e))i[t]=e[t];return i},{})}function X(...s){let i=qs(...s);return Object.keys(i).reduce((e,t)=>(i[t]&&e.push(t),e),[]).join(" ")}function kl(s,...i){let e=qs(...i);for(let t of Object.keys(e))s.classList.toggle(t,e[t])}const Ol=s=>{if(!s)return ee;const i=ro(s).filter(e=>ee.includes(e));return i.length===0?ee:i};function Pl(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":ee,"*tabId":L.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:pe,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Wt(ee),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let e of i){let t=e.src;e.src=pe,e.src=t}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let e=s.$["*originalUrl"],t=le(_t(i),"preview"),r=V(e,t),n={originalUrl:e,cdnUrlModifiers:t,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}))}}}const Ll=`
181
+ `;class Ws extends x{constructor(){super(...arguments);u(this,"init$",{...this.init$,visible:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this._unobserveCollection=this.uploadCollection.observeProperties(()=>{let e=this.uploadCollection.items().some(t=>this.uploadCollection.read(t).getValue("isUploading"));this.$.visible=e}),this.sub("visible",e=>{e?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",e=>{this.$.value=e})}destroyCallback(){var e;super.destroyCallback(),(e=this._unobserveCollection)==null||e.call(this)}}Ws.template=' <lr-progress-bar set="visible: visible; value: value"></lr-progress-bar> ';class qs extends ${constructor(){super(...arguments);u(this,"_value",0);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",e=>{if(e===void 0)return;const t=this._value;if(this._value=e,e===0&&t>0){this.ref.line.addEventListener("transitionend",()=>{this.style.setProperty("--l-width",this._value.toString())});return}this.style.setProperty("--l-width",this._value.toString())}),this.defineAccessor("visible",e=>{this.ref.line.classList.toggle("progress--hidden",!e)})}}qs.template=' <div ref="line" class="progress"></div> ';const me="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";class ei extends ${constructor(){super();u(this,"init$",{...this.init$,checkerboard:!1,src:me})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${Pl()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(e){this.$.src=e.src}setImageFile(e){let t=URL.createObjectURL(e);this.$.src=t,this._lastObjectUrl=t}setImageUrl(e){this.$.src=e}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=me}}ei.template=' <lr-img class="img-view" ref="img" set="@src: src; style.aa: src;" /> ';ei.bindAttributes({checkerboard:"checkerboard"});function Gs(...s){return s.reduce((i,e)=>{if(typeof e=="string")return i[e]=!0,i;for(let t of Object.keys(e))i[t]=e[t];return i},{})}function G(...s){let i=Gs(...s);return Object.keys(i).reduce((e,t)=>(i[t]&&e.push(t),e),[]).join(" ")}function Dl(s,...i){let e=Gs(...i);for(let t of Object.keys(e))s.classList.toggle(t,e[t])}const Nl=s=>{if(!s)return Q;const i=to(s).filter(e=>Q.includes(e));return i.length===0?Q:i};function zl(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":Q,"*tabId":P.CROP,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:me,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:qt(Q),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let e of i){let t=e.src;e.src=me,e.src=t}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let e=s.$["*originalUrl"],t=pe(mt(i),"preview"),r=j(e,t),n={originalUrl:e,cdnUrlModifiers:t,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}))}}}const Vl=`
236
182
  <div class="wrapper wrapper_desktop">
237
183
  <lr-presence-toggle class="network_problems_splash" set="visible: presence.networkProblems;">
238
184
  <div class="network_problems_content">
@@ -250,7 +196,7 @@
250
196
  <div class="file_type">{{fileType}}</div>
251
197
  </div>
252
198
  <div class="image_container" ref="img-container-el">
253
- <img src="${pe}" class="image image_visible_from_editor" ref="img-el" />
199
+ <img src="${me}" class="image image_visible_from_editor" ref="img-el" />
254
200
  <lr-editor-image-cropper ref="cropper-el"></lr-editor-image-cropper>
255
201
  <lr-editor-image-fader ref="fader-el"></lr-editor-image-fader>
256
202
  </div>
@@ -263,23 +209,23 @@
263
209
  </div>
264
210
  </div>
265
211
  </div>
266
- `;class Fe extends be{constructor(){super();u(this,"_debouncedShowLoader",H(this._showLoader.bind(this),300));this.init$={...this.init$,...Pl(this)}}get ctxName(){return this.autoCtxName}_showLoader(e){this.$.showLoader=e}_waitForSize(){return new Promise((t,r)=>{const 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&&(t(),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){const e=oo(this.$.cdnUrl),t=We(this.$.cdnUrl,e);if(t===this.$["*originalUrl"])return;this.$["*originalUrl"]=t;const r=lo(this.$.cdnUrl),n=To(r);this.$["*editorTransformations"]=n}else if(this.$.uuid){const e=We(this.cfg.cdnCname,this.$.uuid);if(e===this.$["*originalUrl"])return;this.$["*originalUrl"]=e,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{const e=V(this.$["*originalUrl"],le("json")),t=await fetch(e).then(o=>o.json()),{width:r,height:n}=t;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===L.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(e){e&&console.error("Failed to load image info",e)}}}async initEditor(){try{await this._waitForSize()}catch(e){this.isConnected&&console.error(e.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==pe&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",e=>{let t=this.ref["img-el"];t.src!==e&&(this._imgLoading=!0,t.src=e||pe)}),this.sub("cropPreset",e=>{this.$["*cropPresetList"]=ps(e)}),this.sub("tabs",e=>{this.$["*tabList"]=Ol(e)}),this.sub("*tabId",e=>{this.ref["img-el"].className=X("image",{image_hidden_to_cropper:e===L.CROP,image_hidden_effects:e!==L.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",e=>{this.$["presence.networkProblems"]=e,this.$["presence.modalCaption"]=!e}),this.sub("*editorTransformations",e=>{if(Object.keys(e).length===0)return;let t=this.$["*originalUrl"],r=le(_t(e),"preview"),n=V(t,r),o={originalUrl:t,cdnUrlModifiers:r,cdnUrl:n,transformations:e};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",e=>e&&this.updateImage()),this.sub("cdnUrl",e=>e&&this.updateImage())}}u(Fe,"className","cloud-image-editor");Fe.template=Ll;Fe.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});class Gs extends be{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 e=this.$["*imageBox"];if(!e)return;if(i===""&&e.height<=v&&e.width<=v)return!0;let t=e.height<=v&&(i.includes("n")||i.includes("s")),r=e.width<=v&&(i.includes("e")||i.includes("w"));return t||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:e,y:t,width:r,height:n}=i,o=this.ref["svg-el"],l=q("mask",{id:"backdrop-mask"}),a=q("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=q("rect",{x:e,y:t,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let h=q("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(h),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:e,y:t,width:r,height:n}=i;this._backdropMaskInner&&Ie(this._backdropMaskInner,{x:e,y:t,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let e of Object.values(this._frameThumbs)){let{direction:t,pathNode:r,interactionNode:n,groupNode:o}=e,l=t==="",a=t.length===2,{x:c,y:h,width:d,height:f}=i;if(l){const p={x:c+d/3,y:h+f/3,width:d/3,height:f/3};Ie(n,p)}else{const p=ke(Math.min(d,f)/(Lt*2+je)/2,0,1);let{d:g,center:A}=a?Vn(i,t,p):Bn(i,t,p);const w=Math.max(Ai*ke(Math.min(d,f)/Ai/3,0,1),zn);Ie(n,{x:A[0]-w,y:A[1]-w,width:w*2,height:w*2}),Ie(r,{d:g})}let m=this._shouldThumbBeDisabled(t);o.setAttribute("class",X("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ie(this._frameGuides,{x:i.x-ye*.5,y:i.y-ye*.5,width:i.width+ye,height:i.height+ye})}}_createThumbs(){const i={};for(let e=0;e<3;e++)for(let t=0;t<3;t++){let r=`${["n","","s"][e]}${["w","","e"][t]}`,n=q("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=q("rect",{fill:"transparent"}),l=q("path",{stroke:"currentColor",fill:"none","stroke-width":fs});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=q("svg"),e=q("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":ye,"stroke-opacity":.5});i.appendChild(e);for(let t=1;t<=2;t++){let r=q("line",{x1:`${Ye*t}%`,y1:"0%",x2:`${Ye*t}%`,y2:"100%",stroke:"#000000","stroke-width":ye,"stroke-opacity":.3});i.appendChild(r)}for(let t=1;t<=2;t++){let r=q("line",{x1:"0%",y1:`${Ye*t}%`,x2:"100%",y2:`${Ye*t}%`,stroke:"#000000","stroke-width":ye,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],e=document.createDocumentFragment(),t=this._createGuides();e.appendChild(t);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))e.appendChild(n);i.appendChild(e),this._frameThumbs=r,this._frameGuides=t}_handlePointerDown(i,e){if(!this._frameThumbs)return;let t=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=e.x-n,a=e.y-o;this.$.dragging=!0,this._draggingThumb=t,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 e=this.ref["svg-el"],{x:t,y:r}=e.getBoundingClientRect(),n=i.x-t,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb;const h=this._calcCropBox(c,[l,a]);h&&(this.$["*cropBox"]=h)}_calcCropBox(i,e){var c;const[t,r]=e;let n=this.$["*imageBox"],o=this._dragStartCrop??this.$["*cropBox"];const l=(c=this.$["*cropPresetList"])==null?void 0:c[0],a=l?l.width/l.height:void 0;if(i===""?o=Hn({rect:o,delta:[t,r],imageBox:n}):o=Qn({rect:o,delta:[t,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(h=>Number.isFinite(h)&&h>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return ot(it(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let e=Object.values(this._frameThumbs).find(t=>{if(this._shouldThumbBeDisabled(t.direction))return!1;let n=t.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return eo(o,[i.x,i.y])});this._hoverThumb=e,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?jn(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:e})=>e).forEach(e=>{e.setAttribute("class",X("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<=v||i.width<=v,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",X({"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)}}Gs.template=' <svg class="svg" ref="svg-el" xmlns="http://www.w3.org/2000/svg"></svg> ';class vt extends be{constructor(){super(...arguments);u(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",e=>{this._titleEl&&(this._titleEl.style.display=e?"block":"none")}),this.sub("active",e=>{this.className=X({active:e,not_active:!e})}),this.sub("on.click",e=>{this.onclick=e})}}vt.template=`
212
+ `;class Me extends ${constructor(){super();u(this,"ctxOwner",!0);u(this,"_debouncedShowLoader",H(this._showLoader.bind(this),300));this.init$={...this.init$,...zl(this)}}_showLoader(e){this.$.showLoader=e}_waitForSize(){return new Promise((t,r)=>{const 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&&(t(),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){const e=Wn(this.$.cdnUrl),t=He(this.$.cdnUrl,e);if(t===this.$["*originalUrl"])return;this.$["*originalUrl"]=t;const r=qn(this.$.cdnUrl),n=Jn(r);this.$["*editorTransformations"]=n}else if(this.$.uuid){const e=He(this.cfg.cdnCname,this.$.uuid);if(e===this.$["*originalUrl"])return;this.$["*originalUrl"]=e,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{const e=j(this.$["*originalUrl"],pe("json")),t=await fetch(e).then(o=>o.json()),{width:r,height:n}=t;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===P.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(e){e&&console.error("Failed to load image info",e)}}}async initEditor(){try{await this._waitForSize()}catch(e){this.isConnected&&console.error(e.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==me&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",e=>{let t=this.ref["img-el"];t.src!==e&&(this._imgLoading=!0,t.src=e||me)}),this.sub("cropPreset",e=>{this.$["*cropPresetList"]=ws(e)}),this.sub("tabs",e=>{this.$["*tabList"]=Nl(e)}),this.sub("*tabId",e=>{this.ref["img-el"].className=G("image",{image_hidden_to_cropper:e===P.CROP,image_hidden_effects:e!==P.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",e=>{this.$["presence.networkProblems"]=e,this.$["presence.modalCaption"]=!e}),this.sub("*editorTransformations",e=>{if(Object.keys(e).length===0)return;let t=this.$["*originalUrl"],r=pe(mt(e),"preview"),n=j(t,r),o={originalUrl:t,cdnUrlModifiers:r,cdnUrl:n,transformations:e};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",e=>e&&this.updateImage()),this.sub("cdnUrl",e=>e&&this.updateImage())}}u(Me,"className","cloud-image-editor");Me.template=Vl;Me.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});class Xs extends ${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 e=this.$["*imageBox"];if(!e)return;if(i===""&&e.height<=C&&e.width<=C)return!0;let t=e.height<=C&&(i.includes("n")||i.includes("s")),r=e.width<=C&&(i.includes("e")||i.includes("w"));return t||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:e,y:t,width:r,height:n}=i,o=this.ref["svg-el"],l=q("mask",{id:"backdrop-mask"}),a=q("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=q("rect",{x:e,y:t,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let h=q("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(h),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:e,y:t,width:r,height:n}=i;this._backdropMaskInner&&Ie(this._backdropMaskInner,{x:e,y:t,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let e of Object.values(this._frameThumbs)){let{direction:t,pathNode:r,interactionNode:n,groupNode:o}=e,l=t==="",a=t.length===2,{x:c,y:h,width:d,height:f}=i;if(l){const p={x:c+d/3,y:h+f/3,width:d/3,height:f/3};Ie(n,p)}else{const p=Oe(Math.min(d,f)/(Lt*2+Be)/2,0,1);let{d:g,center:w}=a?lo(i,t,p):ao(i,t,p);const E=Math.max(wi*Oe(Math.min(d,f)/wi/3,0,1),oo);Ie(n,{x:w[0]-E,y:w[1]-E,width:E*2,height:E*2}),Ie(r,{d:g})}let m=this._shouldThumbBeDisabled(t);o.setAttribute("class",G("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Ie(this._frameGuides,{x:i.x-ve*.5,y:i.y-ve*.5,width:i.width+ve,height:i.height+ve})}}_createThumbs(){const i={};for(let e=0;e<3;e++)for(let t=0;t<3;t++){let r=`${["n","","s"][e]}${["w","","e"][t]}`,n=q("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=q("rect",{fill:"transparent"}),l=q("path",{stroke:"currentColor",fill:"none","stroke-width":Cs});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=q("svg"),e=q("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":ve,"stroke-opacity":.5});i.appendChild(e);for(let t=1;t<=2;t++){let r=q("line",{x1:`${Ye*t}%`,y1:"0%",x2:`${Ye*t}%`,y2:"100%",stroke:"#000000","stroke-width":ve,"stroke-opacity":.3});i.appendChild(r)}for(let t=1;t<=2;t++){let r=q("line",{x1:"0%",y1:`${Ye*t}%`,x2:"100%",y2:`${Ye*t}%`,stroke:"#000000","stroke-width":ve,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],e=document.createDocumentFragment(),t=this._createGuides();e.appendChild(t);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))e.appendChild(n);i.appendChild(e),this._frameThumbs=r,this._frameGuides=t}_handlePointerDown(i,e){if(!this._frameThumbs)return;let t=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=e.x-n,a=e.y-o;this.$.dragging=!0,this._draggingThumb=t,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 e=this.ref["svg-el"],{x:t,y:r}=e.getBoundingClientRect(),n=i.x-t,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb;const h=this._calcCropBox(c,[l,a]);h&&(this.$["*cropBox"]=h)}_calcCropBox(i,e){var c;const[t,r]=e;let n=this.$["*imageBox"],o=this._dragStartCrop??this.$["*cropBox"];const l=(c=this.$["*cropPresetList"])==null?void 0:c[0],a=l?l.width/l.height:void 0;if(i===""?o=ho({rect:o,delta:[t,r],imageBox:n}):o=yo({rect:o,delta:[t,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(h=>Number.isFinite(h)&&h>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return nt(tt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let e=Object.values(this._frameThumbs).find(t=>{if(this._shouldThumbBeDisabled(t.direction))return!1;let n=t.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Co(o,[i.x,i.y])});this._hoverThumb=e,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?co(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:e})=>e).forEach(e=>{e.setAttribute("class",G("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<=C||i.width<=C,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",G({"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)}}Xs.template=' <svg class="svg" ref="svg-el" xmlns="http://www.w3.org/2000/svg"></svg> ';class _t extends ${constructor(){super(...arguments);u(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",e=>{this._titleEl&&(this._titleEl.style.display=e?"block":"none")}),this.sub("active",e=>{this.className=G({active:e,not_active:!e})}),this.sub("on.click",e=>{this.onclick=e})}}_t.template=`
267
213
  <div class="before"></div>
268
214
  <lr-icon size="20" set="@name: icon;"></lr-icon>
269
215
  <div class="title" ref="title-el">{{title}}</div>
270
- `;function Ul(s){let i=s+90;return i=i>=360?0:i,i}function Rl(s,i){return s==="rotate"?Ul(i):["mirror","flip"].includes(s)?!i:null}class Xs extends vt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let e=this.$["*cropperEl"].getValue(this._operation),t=Rl(this._operation,e);this.$["*cropperEl"].setValue(this._operation,t)}}}const Ve={FILTER:"filter",COLOR_OPERATION:"color_operation"},de="original";class Ks extends be{constructor(){super(...arguments);u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":e=>{this.$["*faderEl"].set(e),this.$.value=e}})}setOperation(e,t){this._controlType=e==="filter"?Ve.FILTER:Ve.COLOR_OPERATION,this._operation=e,this._iconName=e,this._title=e.toUpperCase(),this._filter=t,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===de?void 0:this.$.value,filter:this._filter===de?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:e,zero:t}=Le[this._operation],[r,n]=e;this.$.min=r,this.$.max=n,this.$.zero=t;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===Ve.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===Ve.COLOR_OPERATION){let l=typeof o<"u"?o:t;this.$.value=l,this.$.defaultValue=l}}apply(){let e;this._controlType===Ve.FILTER?this._filter===de?e=null:e={name:this._filter,amount:this.$.value}:e=this.$.value;let t={...this.$["*editorTransformations"],[this._operation]:e};this.$["*editorTransformations"]=t}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",e=>{this._originalUrl=e}),this.sub("value",e=>{let t=`${this._filter||this._operation} ${e}`;this.$["*operationTooltip"]=t})}}Ks.template=`
216
+ `;function Bl(s){let i=s+90;return i=i>=360?0:i,i}function jl(s,i){return s==="rotate"?Bl(i):["mirror","flip"].includes(s)?!i:null}class Ys extends _t{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let e=this.$["*cropperEl"].getValue(this._operation),t=jl(this._operation,e);this.$["*cropperEl"].setValue(this._operation,t)}}}const ze={FILTER:"filter",COLOR_OPERATION:"color_operation"},de="original";class Ks extends ${constructor(){super(...arguments);u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":e=>{this.$["*faderEl"].set(e),this.$.value=e}})}setOperation(e,t){this._controlType=e==="filter"?ze.FILTER:ze.COLOR_OPERATION,this._operation=e,this._iconName=e,this._title=e.toUpperCase(),this._filter=t,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===de?void 0:this.$.value,filter:this._filter===de?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:e,zero:t}=Le[this._operation],[r,n]=e;this.$.min=r,this.$.max=n,this.$.zero=t;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===ze.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===ze.COLOR_OPERATION){let l=typeof o<"u"?o:t;this.$.value=l,this.$.defaultValue=l}}apply(){let e;this._controlType===ze.FILTER?this._filter===de?e=null:e={name:this._filter,amount:this.$.value}:e=this.$.value;let t={...this.$["*editorTransformations"],[this._operation]:e};this.$["*editorTransformations"]=t}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",e=>{this._originalUrl=e}),this.sub("value",e=>{let t=`${this._filter||this._operation} ${e}`;this.$["*operationTooltip"]=t})}}Ks.template=`
271
217
  <lr-slider-ui
272
218
  ref="slider-el"
273
219
  set="disabled: disabled; min: min; max: max; defaultValue: defaultValue; zero: zero; onInput: on.input;"
274
220
  ></lr-slider-ui>
275
- `;function ti(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=pe)}}}function Ft(s){let i=[];for(let n of s){let o=ti(n);i.push(o)}let e=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:e,cancel:()=>{i.forEach(n=>{n.cancel()})}}}class ii extends vt{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let e=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),t=window.devicePixelRatio,r=Math.ceil(t*e),n=t>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==de?{name:this._filter,amount:o}:void 0,V(this._originalUrl,le(Es,_t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(e,t){if(e[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=ti(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",""),t.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=t=>{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",t=>{this._operation="filter",this._filter=t,this.$.isOriginal=t===de,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let e=this.$["*originalUrl"];this._originalUrl=e,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",t=>{this.$.active=t&&t===this._filter}),this.sub("isOriginal",t=>{this.$.iconSize=t?40:20}),this.sub("active",t=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=t?"1":"0";let n=this.ref["preview-el"];t?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",t=>{if(!t){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 e;super.destroyCallback(),(e=this._observer)==null||e.disconnect(),this._cancelPreload&&this._cancelPreload()}}ii.template=`
221
+ `;function ti(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=me)}}}function Ut(s){let i=[];for(let n of s){let o=ti(n);i.push(o)}let e=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:e,cancel:()=>{i.forEach(n=>{n.cancel()})}}}class ii extends _t{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let e=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),t=window.devicePixelRatio,r=Math.ceil(t*e),n=t>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==de?{name:this._filter,amount:o}:void 0,j(this._originalUrl,pe(ys,mt(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(e,t){if(e[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=ti(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",""),t.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=t=>{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",t=>{this._operation="filter",this._filter=t,this.$.isOriginal=t===de,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let e=this.$["*originalUrl"];this._originalUrl=e,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",t=>{this.$.active=t&&t===this._filter}),this.sub("isOriginal",t=>{this.$.iconSize=t?40:20}),this.sub("active",t=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=t?"1":"0";let n=this.ref["preview-el"];t?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",t=>{if(!t){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 e;super.destroyCallback(),(e=this._observer)==null||e.disconnect(),this._cancelPreload&&this._cancelPreload()}}ii.template=`
276
222
  <div class="before"></div>
277
223
  <div class="preview" ref="preview-el"></div>
278
224
  <lr-icon size="40" ref="icon-el" set="@name: icon; @size: iconSize;"></lr-icon>
279
- `;class Ys extends vt{constructor(){super(...arguments);u(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",e=>{e&&(this._operation=e,this.$.icon=e,this.$.title=this.l10n(e))}),this.sub("*editorTransformations",e=>{if(!this._operation)return;let{zero:t}=Le[this._operation],r=e[this._operation],n=typeof r<"u"?r!==t:!1;this.$.active=n})}}function Ml(s,i){let e={};for(let t of i){let r=s[t];(s.hasOwnProperty(t)||r!==void 0)&&(e[t]=r)}return e}function si(s,i,e){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return V(s,le(Es,_t(e),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Fl(s){return s?[({dimensions:e,coords:t})=>[...e,...t].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:e,coords:t})=>e.every(r=>r>0)&&t.every(r=>r>=0)].every(e=>e(s)):!0}class Js extends be{constructor(){super(),this.init$={...this.init$,image:null,"*padding":Dn,"*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=H(this._commit.bind(this),300),this._handleResizeThrottled=Fs(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"],e=Ml(i,Object.keys(this.$["*operations"])),t={...this.$["*operations"],...e};this.$["*operations"]=t}_initCanvas(){let i=this.ref["canvas-el"],e=i.getContext("2d"),t=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${t}px`,i.style.height=`${r}px`,i.width=t*n,i.height=r*n,e==null||e.scale(n,n),this._canvas=i,this._ctx=e}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,e=this.$["*padding"],t=this.$["*operations"],{rotate:r}=t,n={width:this.offsetWidth,height:this.offsetHeight},o=De({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-e*2||o.height>n.height-e*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let h=n.width-e*2,d=h/a,f=0+e,m=e+(n.height-e*2)/2-d/2;l={x:f,y:m,width:h,height:d}}else{let h=n.height-e*2,d=h*a,f=e+(n.width-e*2)/2-d/2,m=0+e;l={x:f,y:m,width:d,height:h}}}else{let{width:a,height:c}=o,h=e+(n.width-e*2)/2-a/2,d=e+(n.height-e*2)/2-c/2;l={x:h,y:d,width:a,height:c}}this.$["*imageBox"]=it(l)}_alignCrop(){var d;let i=this.$["*cropBox"],e=this.$["*imageBox"],t=this.$["*operations"],{rotate:r}=t,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[f,m],coords:[p,g]}=n,{width:A}=De(this._imageSize,r),w=o/A;i=ot(it({x:l+p*w,y:a+g*w,width:f*w,height:m*w}),this.$["*imageBox"])}const c=(d=this.$["*cropPresetList"])==null?void 0:d[0],h=c?c.width/c.height:void 0;if(!to(i,e)||h&&!io(i,h)){const f=e.width/e.height;let m=e.width,p=e.height;h&&(f>h?m=Math.min(e.height*h,e.width):p=Math.min(e.width/h,e.height)),i={x:e.x+e.width/2-m/2,y:e.y+e.height/2-p/2,width:m,height:p}}this.$["*cropBox"]=ot(it(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let e=this.$.image,t=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=De({width:t.width,height:t.height},l);i.save(),i.translate(t.x+t.width/2,t.y+t.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(e,-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=X({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],e=this.$["*imageBox"],t=this.$["*operations"],{rotate:r}=t,{width:n,height:o}=e,{width:l,height:a}=De(this._imageSize,r),{width:c,height:h}=i,d=n/l,f=o/a;return[ke(Math.round(c/d),1,l),ke(Math.round(h/f),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],e=this.$["*imageBox"],t=this.$["*operations"],{rotate:r}=t,{width:n,height:o,x:l,y:a}=e,{width:c,height:h}=De(this._imageSize,r),{x:d,y:f}=i,m=n/c,p=o/h,g=this._getCropDimensions(),A={dimensions:g,coords:[ke(Math.round((d-l)/m),0,c-g[0]),ke(Math.round((f-a)/p),0,h-g[1])]};if(!Fl(A)){console.error("Cropper is trying to create invalid crop object",{payload:A});return}if(!(g[0]===c&&g[1]===h))return A}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:e,mirror:t,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:e,mirror:t,flip:r};this.$["*editorTransformations"]=l}setValue(i,e){this.$["*operations"]={...this.$["*operations"],[i]:e},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:e}={}){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:e})}catch(t){console.error("Failed to activate cropper",{error:t})}this._observer=new ResizeObserver(([t])=>{t.contentRect.width>0&&t.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var e;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=X({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}),(e=this._observer)==null||e.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),e=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,t=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(e,t),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,e=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${e}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,e){let t=this.offsetWidth;e={...e,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(si(i,t,e)),{promise:n,cancel:o,image:l}=ti(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 e="crop",t=this.$["*loadingOperations"];return t.get(e)||t.set(e,new Map),t.get(e).get(i)||(t.set(e,t.get(e).set(i,!0)),this.$["*loadingOperations"]=t),()=>{var r;(r=t==null?void 0:t.get(e))!=null&&r.has(i)&&(t.get(e).delete(i),this.$["*loadingOperations"]=t)}}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()}}Js.template=`
225
+ `;class Js extends _t{constructor(){super(...arguments);u(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",e=>{e&&(this._operation=e,this.$.icon=e,this.bindL10n("title",()=>this.l10n(e)))}),this.sub("*editorTransformations",e=>{if(!this._operation)return;let{zero:t}=Le[this._operation],r=e[this._operation],n=typeof r<"u"?r!==t:!1;this.$.active=n})}}function Hl(s,i){let e={};for(let t of i){let r=s[t];(s.hasOwnProperty(t)||r!==void 0)&&(e[t]=r)}return e}function si(s,i,e){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return j(s,pe(ys,mt(e),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Wl(s){return s?[({dimensions:e,coords:t})=>[...e,...t].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:e,coords:t})=>e.every(r=>r>0)&&t.every(r=>r>=0)].every(e=>e(s)):!0}class Zs extends ${constructor(){super();u(this,"ctxOwner",!0);this.init$={...this.init$,image:null,"*padding":no,"*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=H(this._commit.bind(this),300),this._handleResizeThrottled=Ns(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 e=this.$["*editorTransformations"],t=Hl(e,Object.keys(this.$["*operations"])),r={...this.$["*operations"],...t};this.$["*operations"]=r}_initCanvas(){let e=this.ref["canvas-el"],t=e.getContext("2d"),r=this.offsetWidth,n=this.offsetHeight,o=window.devicePixelRatio;e.style.width=`${r}px`,e.style.height=`${n}px`,e.width=r*o,e.height=n*o,t==null||t.scale(o,o),this._canvas=e,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let e=this.$.image,t=this.$["*padding"],r=this.$["*operations"],{rotate:n}=r,o={width:this.offsetWidth,height:this.offsetHeight},l=De({width:e.naturalWidth,height:e.naturalHeight},n),a;if(l.width>o.width-t*2||l.height>o.height-t*2){let c=l.width/l.height,h=o.width/o.height;if(c>h){let d=o.width-t*2,f=d/c,m=0+t,p=t+(o.height-t*2)/2-f/2;a={x:m,y:p,width:d,height:f}}else{let d=o.height-t*2,f=d*c,m=t+(o.width-t*2)/2-f/2,p=0+t;a={x:m,y:p,width:f,height:d}}}else{let{width:c,height:h}=l,d=t+(o.width-t*2)/2-c/2,f=t+(o.height-t*2)/2-h/2;a={x:d,y:f,width:c,height:h}}this.$["*imageBox"]=tt(a)}_alignCrop(){var f;let e=this.$["*cropBox"],t=this.$["*imageBox"],r=this.$["*operations"],{rotate:n}=r,o=this.$["*editorTransformations"].crop,{width:l,x:a,y:c}=this.$["*imageBox"];if(o){let{dimensions:[m,p],coords:[g,w]}=o,{width:E}=De(this._imageSize,n),b=l/E;e=nt(tt({x:a+g*b,y:c+w*b,width:m*b,height:p*b}),this.$["*imageBox"])}const h=(f=this.$["*cropPresetList"])==null?void 0:f[0],d=h?h.width/h.height:void 0;if(!wo(e,t)||d&&!Eo(e,d)){const m=t.width/t.height;let p=t.width,g=t.height;d&&(m>d?p=Math.min(t.height*d,t.width):g=Math.min(t.width/d,t.height)),e={x:t.x+t.width/2-p/2,y:t.y+t.height/2-g/2,width:p,height:g}}this.$["*cropBox"]=nt(tt(e),this.$["*imageBox"])}_drawImage(){let e=this._ctx;if(!e)return;let t=this.$.image,r=this.$["*imageBox"],n=this.$["*operations"],{mirror:o,flip:l,rotate:a}=n,c=De({width:r.width,height:r.height},a);e.save(),e.translate(r.x+r.width/2,r.y+r.height/2),e.rotate(a*Math.PI*-1/180),e.scale(o?-1:1,l?-1:1),e.drawImage(t,-c.width/2,-c.height/2,c.width,c.height),e.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let e=this._canvas;this._ctx.clearRect(0,0,e.width,e.height),this._drawImage()}_animateIn({fromViewer:e}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=G({active_from_viewer:e,active_from_editor:!e,inactive_to_editor:!1})}))}_getCropDimensions(){let e=this.$["*cropBox"],t=this.$["*imageBox"],r=this.$["*operations"],{rotate:n}=r,{width:o,height:l}=t,{width:a,height:c}=De(this._imageSize,n),{width:h,height:d}=e,f=o/a,m=l/c;return[Oe(Math.round(h/f),1,a),Oe(Math.round(d/m),1,c)]}_getCropTransformation(){let e=this.$["*cropBox"],t=this.$["*imageBox"],r=this.$["*operations"],{rotate:n}=r,{width:o,height:l,x:a,y:c}=t,{width:h,height:d}=De(this._imageSize,n),{x:f,y:m}=e,p=o/h,g=l/d,w=this._getCropDimensions(),E={dimensions:w,coords:[Oe(Math.round((f-a)/p),0,h-w[0]),Oe(Math.round((m-c)/g),0,d-w[1])]};if(!Wl(E)){console.error("Cropper is trying to create invalid crop object",{payload:E});return}if(!(w[0]===h&&w[1]===d))return E}_commit(){if(!this.isConnected)return;let e=this.$["*operations"],{rotate:t,mirror:r,flip:n}=e,o=this._getCropTransformation(),a={...this.$["*editorTransformations"],crop:o,rotate:t,mirror:r,flip:n};this.$["*editorTransformations"]=a}setValue(e,t){this.$["*operations"]={...this.$["*operations"],[e]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(e){return this.$["*operations"][e]}async activate(e,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=e,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(r){console.error("Failed to activate cropper",{error:r})}this._observer=new ResizeObserver(([r])=>{r.contentRect.width>0&&r.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:e=!1}={}){var t;this._isActive&&(!e&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=G({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 e=this._getCropDimensions(),t=Math.min(this.offsetWidth,e[0])/this.$["*cropBox"].width,r=Math.min(this.offsetHeight,e[1])/this.$["*cropBox"].height,n=Math.min(t,r),o=this.$["*cropBox"].x+this.$["*cropBox"].width/2,l=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${n}) translate(${(this.offsetWidth/2-o)/n}px, ${(this.offsetHeight/2-l)/n}px)`,this.style.transformOrigin=`${o}px ${l}px`}_transitionToImage(){let e=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${e}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(e,t){let r=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let n=this.proxyUrl(si(e,r,t)),{promise:o,cancel:l,image:a}=ti(n),c=this._handleImageLoading(n);return a.addEventListener("load",c,{once:!0}),a.addEventListener("error",c,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=l,o.then(()=>a).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(a)))}_handleImageLoading(e){let t="crop",r=this.$["*loadingOperations"];return r.get(t)||r.set(t,new Map),r.get(t).get(e)||(r.set(t,r.get(t).set(e,!0)),this.$["*loadingOperations"]=r),()=>{var n;(n=r==null?void 0:r.get(t))!=null&&n.has(e)&&(r.get(t).delete(e),this.$["*loadingOperations"]=r)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",e=>{e||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var e;super.destroyCallback(),(e=this._observer)==null||e.disconnect()}}Zs.template=`
280
226
  <canvas class="canvas" ref="canvas-el"></canvas>
281
227
  <lr-crop-frame ref="frame-el"></lr-crop-frame>
282
- `;function Di(s,i,e){let t=Array(e);e--;for(let r=e;r>=0;r--)t[r]=Math.ceil((r*i+(e-r)*s)/e);return t}function Nl(s){return s.reduce((i,e,t)=>t<s.length-1?[...i,[e,s[t+1]]]:i,[])}function Dl(s,i,e){let t=Nl(s).find(([r,n])=>r<=i&&i<=n);return s.map(r=>{let n=Math.abs(t[0]-t[1]),o=Math.abs(i-t[0])/n;return t[0]===r?i>e?1:1-o:t[1]===r?i>=e?o:1:0})}function zl(s,i){return s.map((e,t)=>e<i?s.length-t:t)}function zi(s,i){let e=Le[s].keypointsNumber,{range:t,zero:r}=Le[s];return[...new Set([...Di(t[0],r,e+1),...Di(r,t[1],e+1),r,i])].sort((n,o)=>n-o)}class Vl extends be{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=H(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let e=this._operation,t=this.$["*loadingOperations"];return t.get(e)||t.set(e,new Map),t.get(e).get(i)||(t.set(e,t.get(e).set(i,!0)),this.$["*loadingOperations"]=t),()=>{var r;(r=t==null?void 0:t.get(e))!=null&&r.has(i)&&(t.get(e).delete(i),this.$["*loadingOperations"]=t)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:e}=i;e&&(e.style.opacity=i.opacity.toString(),e.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:e=this._filter,operation:t,value:r}={}){let n={...this._transformations};t&&(n[t]=e?{name:e,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(si(i,o,n))}_constructKeypoint(i,e){return{src:this._imageSrc({operation:i,value:e}),image:null,opacity:0,zIndex:0,value:e}}_isSame(i,e){return this._operation===i&&this._filter===e}_addKeypoint(i,e,t){let r=()=>!this._isSame(i,e)||this._value!==t||!!this._keypoints.find(a=>a.value===t);if(r())return;let n=this._constructKeypoint(i,t),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>t),h=c<a.length?a[c].image:null;!this._container||h&&!this._container.contains(h)||(a.splice(c,0,n),this._container.insertBefore(o,h),this._update(i,t))},{once:!0}),o.addEventListener("error",()=>{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,e){this._operation=i,this._value=e;let{zero:t}=Le[i],r=this._keypoints.map(l=>l.value),n=Dl(r,e,t),o=zl(r,t);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 e=document.createElement("div");i.appendChild(e);let t=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Ft(t);r.forEach(c=>{let h=this._handleImageLoading(c.src);c.addEventListener("load",h),c.addEventListener("error",h)}),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=e,this._keypoints.forEach((c,h)=>{let d=r[h];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 e=this._imageSrc(),t=this._handleImageLoading(e);this._previewImage.src=e,this._previewImage.addEventListener("load",t,{once:!0}),this._previewImage.addEventListener("error",t,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:e,operation:t,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=zi(t,r).map(a=>this._imageSrc({url:i,filter:e,operation:t,value:a})),{cancel:l}=Ft(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let e=this._previewImage||this._createPreviewImage();if(!this.contains(e)&&this.appendChild(e),this._previewImage=e,e.src===i){e.style.opacity="1",e.style.transform="scale(1)",this.className=X({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}e.style.opacity="0";let t=this._handleImageLoading(i);e.addEventListener("error",t,{once:!0}),e.src=i,e.addEventListener("load",()=>{t(),e&&(e.style.opacity="1",e.style.transform="scale(1)",this.className=X({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),e.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:e,value:t,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=e||"initial",this._value=t,this._filter=r,this._fromViewer=n,typeof t!="number"&&!r){let l=this._imageSrc({operation:e,value:t});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=zi(e,t).map(l=>this._constructKeypoint(e,l)),this._update(e,t),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=X({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()}}const Bl=1;class Zs extends be{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:e,deltaX:t}=i;Math.abs(t)>Bl?this.scrollLeft+=t:this.scrollLeft+=e})}}Zs.template=" <slot></slot> ";function jl(s){return`
228
+ `;function Ni(s,i,e){let t=Array(e);e--;for(let r=e;r>=0;r--)t[r]=Math.ceil((r*i+(e-r)*s)/e);return t}function ql(s){return s.reduce((i,e,t)=>t<s.length-1?[...i,[e,s[t+1]]]:i,[])}function Gl(s,i,e){let t=ql(s).find(([r,n])=>r<=i&&i<=n);return s.map(r=>{let n=Math.abs(t[0]-t[1]),o=Math.abs(i-t[0])/n;return t[0]===r?i>e?1:1-o:t[1]===r?i>=e?o:1:0})}function Xl(s,i){return s.map((e,t)=>e<i?s.length-t:t)}function zi(s,i){let e=Le[s].keypointsNumber,{range:t,zero:r}=Le[s];return[...new Set([...Ni(t[0],r,e+1),...Ni(r,t[1],e+1),r,i])].sort((n,o)=>n-o)}class Yl extends ${constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=H(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let e=this._operation,t=this.$["*loadingOperations"];return t.get(e)||t.set(e,new Map),t.get(e).get(i)||(t.set(e,t.get(e).set(i,!0)),this.$["*loadingOperations"]=t),()=>{var r;(r=t==null?void 0:t.get(e))!=null&&r.has(i)&&(t.get(e).delete(i),this.$["*loadingOperations"]=t)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:e}=i;e&&(e.style.opacity=i.opacity.toString(),e.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:e=this._filter,operation:t,value:r}={}){let n={...this._transformations};t&&(n[t]=e?{name:e,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(si(i,o,n))}_constructKeypoint(i,e){return{src:this._imageSrc({operation:i,value:e}),image:null,opacity:0,zIndex:0,value:e}}_isSame(i,e){return this._operation===i&&this._filter===e}_addKeypoint(i,e,t){let r=()=>!this._isSame(i,e)||this._value!==t||!!this._keypoints.find(a=>a.value===t);if(r())return;let n=this._constructKeypoint(i,t),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>t),h=c<a.length?a[c].image:null;!this._container||h&&!this._container.contains(h)||(a.splice(c,0,n),this._container.insertBefore(o,h),this._update(i,t))},{once:!0}),o.addEventListener("error",()=>{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,e){this._operation=i,this._value=e;let{zero:t}=Le[i],r=this._keypoints.map(l=>l.value),n=Gl(r,e,t),o=Xl(r,t);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 e=document.createElement("div");i.appendChild(e);let t=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Ut(t);r.forEach(c=>{let h=this._handleImageLoading(c.src);c.addEventListener("load",h),c.addEventListener("error",h)}),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=e,this._keypoints.forEach((c,h)=>{let d=r[h];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 e=this._imageSrc(),t=this._handleImageLoading(e);this._previewImage.src=e,this._previewImage.addEventListener("load",t,{once:!0}),this._previewImage.addEventListener("error",t,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:e,operation:t,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=zi(t,r).map(a=>this._imageSrc({url:i,filter:e,operation:t,value:a})),{cancel:l}=Ut(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let e=this._previewImage||this._createPreviewImage();if(!this.contains(e)&&this.appendChild(e),this._previewImage=e,e.src===i){e.style.opacity="1",e.style.transform="scale(1)",this.className=G({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}e.style.opacity="0";let t=this._handleImageLoading(i);e.addEventListener("error",t,{once:!0}),e.src=i,e.addEventListener("load",()=>{t(),e&&(e.style.opacity="1",e.style.transform="scale(1)",this.className=G({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),e.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:e,value:t,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=e||"initial",this._value=t,this._filter=r,this._fromViewer=n,typeof t!="number"&&!r){let l=this._imageSrc({operation:e,value:t});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=zi(e,t).map(l=>this._constructKeypoint(e,l)),this._update(e,t),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=G({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()}}const Kl=1;class Qs extends ${initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:e,deltaX:t}=i;Math.abs(t)>Kl?this.scrollLeft+=t:this.scrollLeft+=e})}}Qs.template=" <slot></slot> ";function Jl(s){return`
283
229
  <lr-presence-toggle class="tab-toggle" set="visible: presence.tabToggle.${s}; styles: presence.tabToggleStyles;">
284
230
  <lr-btn-ui
285
231
  theme="boring"
@@ -291,7 +237,7 @@
291
237
  >
292
238
  </lr-btn-ui>
293
239
  </lr-presence-toggle>
294
- `}function Hl(s){return`
240
+ `}function Zl(s){return`
295
241
  <lr-presence-toggle class="tab-content" set="visible: presence.tabContent.${s}; styles: presence.tabContentStyles">
296
242
  <lr-editor-scroller hidden-scrollbar>
297
243
  <div class="controls-list_align">
@@ -299,7 +245,7 @@
299
245
  </div>
300
246
  </lr-editor-scroller>
301
247
  </lr-presence-toggle>
302
- `}class Qs extends be{constructor(){super();u(this,"_updateInfoTooltip",H(()=>{var o,l;const e=this.$["*editorTransformations"],t=this.$["*currentOperation"];let r="",n=!1;if(this.$["*tabId"]===L.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=e==null?void 0:e.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=e==null?void 0:e.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(de);else if(this.$["*tabId"]===L.TUNING&&t){n=!0;let a=(e==null?void 0:e[t])||Le[t].zero;r=t+" "+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":de,"*currentOperation":null,showLoader:!1,filters:So,colorOperations:$o,cropOperations:xo,"*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":e=>{const t=e.currentTarget.getAttribute("data-id");t&&this._activateTab(t,{fromViewer:!1})}},this._debouncedShowLoader=H(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===L.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(e){let t=new Ys;return t.operation=e,t}_createFilterControl(e){let t=new ii;return t.filter=e,t}_createToggleControl(e){let t=new Xs;return t.operation=e,t}_renderControlsList(e){let t=this.ref[`controls-list-${e}`],r=document.createDocumentFragment();e===L.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):e===L.FILTERS?[de,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):e===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")}),t.innerHTML="",t.appendChild(r)}_activateTab(e,{fromViewer:t}){this.$["*tabId"]=e,e===L.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:t})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:t}),this.$["*cropperEl"].deactivate());for(let r of ee){let n=r===e,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(e),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(e){let t=this.ref[`controls-list-${e}`];t&&(t.innerHTML="")}_syncTabIndicator(){let e=this.ref[`tab-toggle-${this.$["*tabId"]}`],t=this.ref["tabs-indicator"];t.style.transform=`translateX(${e.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let e=this.$["*imgContainerEl"].offsetWidth,t=this.proxyUrl(si(this.$["*originalUrl"],e,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Ft([t]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(e){this.$.showLoader=e}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",e=>{e&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",e=>{var r;let t=(r=e==null?void 0:e.filter)==null?void 0:r.name;this.$["*currentFilter"]!==t&&(this.$["*currentFilter"]=t)}),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",e=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(e)}),this.sub("*loadingOperations",e=>{let t=!1;for(let[,r]of e.entries()){if(t)break;for(let[,n]of r.entries())if(n){t=!0;break}}this._debouncedShowLoader(t)}),this.sub("*showSlider",e=>{this.$["presence.subToolbar"]=e,this.$["presence.mainToolbar"]=!e}),this.sub("*tabList",e=>{this.$["presence.tabToggles"]=e.length>1;for(const t of ee){this.$[`presence.tabToggle.${t}`]=e.includes(t);const r=this.ref[`tab-toggle-${t}`];r.style.gridColumn=e.indexOf(t)+1}e.includes(this.$["*tabId"])||this._activateTab(e[0],{fromViewer:!1})}),this._updateInfoTooltip()}}Qs.template=`
248
+ `}class er extends ${constructor(){super();u(this,"_updateInfoTooltip",H(()=>{var o,l;const e=this.$["*editorTransformations"],t=this.$["*currentOperation"];let r="",n=!1;if(this.$["*tabId"]===P.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=e==null?void 0:e.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=e==null?void 0:e.filter)==null?void 0:l.amount)||100;r=this.$["*currentFilter"]+" "+a}else r=this.l10n(de);else if(this.$["*tabId"]===P.TUNING&&t){n=!0;let a=(e==null?void 0:e[t])||Le[t].zero;r=this.l10n(t)+" "+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":de,"*currentOperation":null,showLoader:!1,filters:Qn,colorOperations:Zn,cropOperations:eo,"*operationTooltip":null,"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":e=>{const t=e.currentTarget.getAttribute("data-id");t&&this._activateTab(t,{fromViewer:!1})}},this._debouncedShowLoader=H(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===P.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(e){let t=new Js;return t.operation=e,t}_createFilterControl(e){let t=new ii;return t.filter=e,t}_createToggleControl(e){let t=new Ys;return t.operation=e,t}_renderControlsList(e){let t=this.ref[`controls-list-${e}`],r=document.createDocumentFragment();e===P.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):e===P.FILTERS?[de,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):e===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")}),t.innerHTML="",t.appendChild(r)}_activateTab(e,{fromViewer:t}){this.$["*tabId"]=e,e===P.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:t})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:t}),this.$["*cropperEl"].deactivate());for(let r of Q){let n=r===e,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(e),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(e){let t=this.ref[`controls-list-${e}`];t&&(t.innerHTML="")}_syncTabIndicator(){let e=this.ref[`tab-toggle-${this.$["*tabId"]}`],t=this.ref["tabs-indicator"];t.style.transform=`translateX(${e.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let e=this.$["*imgContainerEl"].offsetWidth,t=this.proxyUrl(si(this.$["*originalUrl"],e,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Ut([t]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(e){this.$.showLoader=e}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",e=>{e&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",e=>{var r;let t=(r=e==null?void 0:e.filter)==null?void 0:r.name;this.$["*currentFilter"]!==t&&(this.$["*currentFilter"]=t)}),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",e=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(e)}),this.sub("*loadingOperations",e=>{let t=!1;for(let[,r]of e.entries()){if(t)break;for(let[,n]of r.entries())if(n){t=!0;break}}this._debouncedShowLoader(t)}),this.sub("*showSlider",e=>{this.$["presence.subToolbar"]=e,this.$["presence.mainToolbar"]=!e}),this.sub("*tabList",e=>{this.$["presence.tabToggles"]=e.length>1;for(const t of Q){this.$[`presence.tabToggle.${t}`]=e.includes(t);const r=this.ref[`tab-toggle-${t}`];r.style.gridColumn=e.indexOf(t)+1}e.includes(this.$["*tabId"])||this._activateTab(e[0],{fromViewer:!1})}),this._updateInfoTooltip()}}er.template=`
303
249
  <lr-line-loader-ui set="active: showLoader"></lr-line-loader-ui>
304
250
  <div class="info-tooltip_container">
305
251
  <div class="info-tooltip_wrapper">
@@ -308,12 +254,12 @@
308
254
  </div>
309
255
  <div class="toolbar-container">
310
256
  <lr-presence-toggle class="sub-toolbar" set="visible: presence.mainToolbar; styles: presence.subTopToolbarStyles">
311
- <div class="tab-content-row">${ee.map(Hl).join("")}</div>
257
+ <div class="tab-content-row">${Q.map(Zl).join("")}</div>
312
258
  <div class="controls-row">
313
259
  <lr-btn-ui theme="boring" icon="closeMax" set="onclick: on.cancel"> </lr-btn-ui>
314
260
  <lr-presence-toggle class="tab-toggles" set="visible: presence.tabToggles; styles: presence.tabTogglesStyles">
315
261
  <div ref="tabs-indicator" class="tab-toggles_indicator"></div>
316
- ${ee.map(jl).join("")}
262
+ ${Q.map(Jl).join("")}
317
263
  </lr-presence-toggle>
318
264
  <lr-btn-ui theme="primary" icon="done" set="onclick: on.apply"> </lr-btn-ui>
319
265
  </div>
@@ -323,19 +269,19 @@
323
269
  <lr-editor-slider ref="slider-el"></lr-editor-slider>
324
270
  </div>
325
271
  <div class="controls-row">
326
- <lr-btn-ui theme="boring" set="@text: l10n.cancel; onclick: on.cancelSlider;"> </lr-btn-ui>
327
- <lr-btn-ui theme="primary" set="@text: l10n.apply; onclick: on.applySlider;"> </lr-btn-ui>
272
+ <lr-btn-ui theme="boring" set="onclick: on.cancelSlider;" l10n="@text:cancel"> </lr-btn-ui>
273
+ <lr-btn-ui theme="primary" set="onclick: on.applySlider;" l10n="@text:apply"> </lr-btn-ui>
328
274
  </div>
329
275
  </lr-presence-toggle>
330
276
  </div>
331
- `;class ri extends k{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 X("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)}}ri.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ri.template=`
277
+ `;class ri extends ${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 G("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)}}ri.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ri.template=`
332
278
  <lr-icon size="20" set="className: iconCss; @name: icon;"></lr-icon>
333
279
  <div class="text">{{text}}</div>
334
- `;class er extends k{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(),e=this.ref["line-el"];e.style.transition="transform 1s",e.style.opacity="1",e.style.transform=`translateX(${i}px)`,e.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}}er.template=`
280
+ `;class tr extends ${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(),e=this.ref["line-el"];e.style.transition="transform 1s",e.style.opacity="1",e.style.transform=`translateX(${i}px)`,e.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}}tr.template=`
335
281
  <div class="inner">
336
282
  <div class="line" ref="line-el"></div>
337
283
  </div>
338
- `;const et={transition:"transition",visible:"visible",hidden:"hidden"};class tr extends k{constructor(){super(),this._visible=!1,this._visibleStyle=et.visible,this._hiddenStyle=et.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",kl(this,{[et.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(et.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}}tr.template=" <slot></slot> ";class ir extends k{constructor(){super();u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e),this.$.onInput&&this.$.onInput(e)},"on.sliderChange":()=>{let e=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(e)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",t=>{this.$.disabled=t}),this.defineAccessor("min",t=>{this.$.min=t}),this.defineAccessor("max",t=>{this.$.max=t}),this.defineAccessor("defaultValue",t=>{this.$.defaultValue=t,this.ref["input-el"].value=t,this._updateValue(t)}),this.defineAccessor("zero",t=>{this._zero=t}),this.defineAccessor("onInput",t=>{t&&(this.$.onInput=t)}),this.defineAccessor("onChange",t=>{t&&(this.$.onChange=t)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t)},0),this.sub("disabled",t=>{let r=this.ref["input-el"];t?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let e=this.ref["input-el"];e.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),e.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(e){this._updateZeroDot(e);let{width:t}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(e-this.$.min)*(t-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(e){if(!this._zeroDotEl)return;e===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:t}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(t-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let t=this.ref["steps-el"],{width:r}=t.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<o;d++)l.appendChild(a.cloneNode());l.appendChild(c.cloneNode());for(let d=0;d<o;d++)l.appendChild(a.cloneNode());l.appendChild(c.cloneNode());let h=document.createElement("div");h.className="zero-dot",l.appendChild(h),this._zeroDotEl=h,t.innerHTML="",t.appendChild(l),this._stepsCount=o}destroyCallback(){var e;(e=this._observer)==null||e.disconnect()}}ir.template=`
284
+ `;const Qe={transition:"transition",visible:"visible",hidden:"hidden"};class ir extends ${constructor(){super(),this._visible=!1,this._visibleStyle=Qe.visible,this._hiddenStyle=Qe.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",Dl(this,{[Qe.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(Qe.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}}ir.template=" <slot></slot> ";class sr extends ${constructor(){super();u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e),this.$.onInput&&this.$.onInput(e)},"on.sliderChange":()=>{let e=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(e)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",t=>{this.$.disabled=t}),this.defineAccessor("min",t=>{this.$.min=t}),this.defineAccessor("max",t=>{this.$.max=t}),this.defineAccessor("defaultValue",t=>{this.$.defaultValue=t,this.ref["input-el"].value=t,this._updateValue(t)}),this.defineAccessor("zero",t=>{this._zero=t}),this.defineAccessor("onInput",t=>{t&&(this.$.onInput=t)}),this.defineAccessor("onChange",t=>{t&&(this.$.onChange=t)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t)},0),this.sub("disabled",t=>{let r=this.ref["input-el"];t?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let e=this.ref["input-el"];e.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),e.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(e){this._updateZeroDot(e);let{width:t}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(e-this.$.min)*(t-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(e){if(!this._zeroDotEl)return;e===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:t}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(t-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let t=this.ref["steps-el"],{width:r}=t.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<o;d++)l.appendChild(a.cloneNode());l.appendChild(c.cloneNode());for(let d=0;d<o;d++)l.appendChild(a.cloneNode());l.appendChild(c.cloneNode());let h=document.createElement("div");h.className="zero-dot",l.appendChild(h),this._zeroDotEl=h,t.innerHTML="",t.appendChild(l),this._stepsCount=o}destroyCallback(){var e;(e=this._observer)==null||e.disconnect()}}sr.template=`
339
285
  <div class="steps" ref="steps-el"></div>
340
286
  <div ref="thumb-el" class="thumb"></div>
341
287
  <input
@@ -345,7 +291,7 @@
345
291
  tabindex="0"
346
292
  set="oninput: on.sliderInput; onchange: on.sliderChange; @min: min; @max: max; @value: defaultValue;"
347
293
  />
348
- `;class Wl extends ${constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.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",e=>{e&&(this.entry=e,this.entry.subscribe("cdnUrl",t=>{t&&(this.$.cdnUrl=t)}))}),this.subConfigValue("cropPreset",e=>{this._instance&&this._instance.getAttribute("crop-preset")!==e&&this._instance.setAttribute("crop-preset",e)}),this.subConfigValue("cloudImageEditorTabs",e=>{this._instance&&this._instance.getAttribute("tabs")!==e&&this._instance.setAttribute("tabs",e)})}handleApply(e){if(!this.entry)return;let t=e.detail;this.entry.setMultipleValues({cdnUrl:t.cdnUrl,cdnUrlModifiers:t.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){const e=new Fe,t=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;e.setAttribute("ctx-name",this.ctxName),e.setAttribute("cdn-url",t),r&&e.setAttribute("crop-preset",r),n&&e.setAttribute("tabs",n),e.addEventListener("apply",o=>{const l=o;this.handleApply(l),this.debugPrint('editor event "apply"',l.detail)}),e.addEventListener("cancel",o=>{const l=o;this.handleCancel(),this.debugPrint('editor event "cancel"',l.detail)}),e.addEventListener("change",o=>{const l=o;this.debugPrint('editor event "change"',l.detail)}),this.innerHTML="",this.appendChild(e),this._mounted=!0,this._instance=e}unmountEditor(){this._instance=void 0,this.innerHTML=""}}const ql=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Gl=function(s,i="i"){const e=s.split("*").map(ql);return new RegExp("^"+e.join(".+")+"$",i)};let Xl=s=>Object.keys(s).reduce((e,t)=>{let r=s[t],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return e+`${t}{${n}}`},"");function Kl({textColor:s,backgroundColor:i,linkColor:e,linkColorHover:t,shadeColor:r}){let n=`solid 1px ${r}`;return Xl({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:e},".bread-crumbs a:hover":{color:t},".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:e},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:t},".side-bar-menu a":{color:e},".side-bar-menu a:hover":{color:t},".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:t},".source-vk .side-bar-menu a":{color:e},".source-vk .side-bar-menu a:hover":{color:t,background:"none"}})}let fe={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in fe){let e=fe[i.type];for(let[t,r]of e)s.source===t&&r(i)}});const Yl=function(s,i,e){s in fe||(fe[s]=[]),fe[s].push([i,e])},Jl=function(s,i){s in fe&&(fe[s]=fe[s].filter(e=>e[0]!==i))};function Zl(s){let i=[];for(let[e,t]of Object.entries(s))t==null||typeof t=="string"&&t.length===0||i.push(`${e}=${encodeURIComponent(t)}`);return i.join("&")}class sr extends ${constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"activityType",b.activities.EXTERNAL);u(this,"_iframe",null);u(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});u(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,multiple:!1,onDone:()=>{for(const e of this.$.selectedList){const t=this.extractUrlFromMessage(e),{filename:r}=e,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(t,{fileName:r,source:n})}this.$["*currentActivity"]=b.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:e}=this.activityParams;this.set$({activityCaption:`${e==null?void 0:e[0].toUpperCase()}${e==null?void 0:e.slice(1)}`,activityIcon:e}),this.mountIframe()}}),this.sub("*currentActivity",e=>{e!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",e=>{this.$.counter=e.length}),this.subConfigValue("multiple",e=>{this.$.multiple=e})}extractUrlFromMessage(e){if(e.alternatives){const t=ae(this.cfg.externalSourcesPreferredTypes);for(const r of t){const n=Gl(r);for(const[o,l]of Object.entries(e.alternatives))if(n.test(o))return l}}return e.url}sendMessage(e){var t,r;(r=(t=this._iframe)==null?void 0:t.contentWindow)==null||r.postMessage(JSON.stringify(e),"*")}async handleFileSelected(e){!this.$.multiple&&this.$.selectedList.length||(this.$.selectedList=[...this.$.selectedList,e],this.$.multiple||this.$.onDone())}handleIframeLoad(){this.applyStyles()}getCssValue(e){return window.getComputedStyle(this).getPropertyValue(e).trim()}applyStyles(){let e={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:Kl(e)})}remoteUrl(){var l,a;let e=this.cfg.pubkey,t="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:e,images_only:t,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Zl(n),o.toString()}mountIframe(){let e=Dt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});e.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(e),Yl("file-selected",e.contentWindow,this.handleFileSelected.bind(this)),this._iframe=e,this.$.selectedList=[]}unmountIframe(){this._iframe&&Jl("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}}sr.template=`
294
+ `;class Ql extends x{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"activityType",_.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",e=>{e&&(this.entry=e,this.entry.subscribe("cdnUrl",t=>{t&&(this.$.cdnUrl=t)}))}),this.subConfigValue("cropPreset",e=>{this._instance&&this._instance.getAttribute("crop-preset")!==e&&this._instance.setAttribute("crop-preset",e)}),this.subConfigValue("cloudImageEditorTabs",e=>{this._instance&&this._instance.getAttribute("tabs")!==e&&this._instance.setAttribute("tabs",e)})}handleApply(e){if(!this.entry)return;let t=e.detail;this.entry.setMultipleValues({cdnUrl:t.cdnUrl,cdnUrlModifiers:t.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){const e=new Me,t=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;e.setAttribute("ctx-name",this.ctxName),e.setAttribute("cdn-url",t),r&&e.setAttribute("crop-preset",r),n&&e.setAttribute("tabs",n),e.addEventListener("apply",o=>{const l=o;this.handleApply(l),this.debugPrint('editor event "apply"',l.detail)}),e.addEventListener("cancel",o=>{const l=o;this.handleCancel(),this.debugPrint('editor event "cancel"',l.detail)}),e.addEventListener("change",o=>{const l=o;this.debugPrint('editor event "change"',l.detail)}),this.innerHTML="",this.appendChild(e),this._mounted=!0,this._instance=e}unmountEditor(){this._instance=void 0,this.innerHTML=""}}const ea=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},ta=function(s,i="i"){const e=s.split("*").map(ea);return new RegExp("^"+e.join(".+")+"$",i)};let ia=s=>Object.keys(s).reduce((e,t)=>{let r=s[t],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return e+`${t}{${n}}`},"");function sa({textColor:s,backgroundColor:i,linkColor:e,linkColorHover:t,shadeColor:r}){let n=`solid 1px ${r}`;return ia({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:e},".bread-crumbs a:hover":{color:t},".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:e},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:t},".side-bar-menu a":{color:e},".side-bar-menu a:hover":{color:t},".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:t},".source-vk .side-bar-menu a":{color:e},".source-vk .side-bar-menu a:hover":{color:t,background:"none"}})}let fe={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in fe){let e=fe[i.type];for(let[t,r]of e)s.source===t&&r(i)}});const ra=function(s,i,e){s in fe||(fe[s]=[]),fe[s].push([i,e])},na=function(s,i){s in fe&&(fe[s]=fe[s].filter(e=>e[0]!==i))};function oa(s){let i=[];for(let[e,t]of Object.entries(s))t==null||typeof t=="string"&&t.length===0||i.push(`${e}=${encodeURIComponent(t)}`);return i.join("&")}class rr extends x{constructor(){super();u(this,"couldBeCtxOwner",!0);u(this,"activityType",_.activities.EXTERNAL);u(this,"_iframe",null);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,multiple:!1,onDone:()=>{for(const e of this.$.selectedList){const t=this.extractUrlFromMessage(e),{filename:r}=e,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(t,{fileName:r,source:n})}this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:e}=this.activityParams;this.set$({activityCaption:`${e==null?void 0:e[0].toUpperCase()}${e==null?void 0:e.slice(1)}`,activityIcon:e}),this.mountIframe()}}),this.sub("*currentActivity",e=>{e!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",e=>{this.$.counter=e.length}),this.subConfigValue("multiple",e=>{this.$.multiple=e})}extractUrlFromMessage(e){if(e.alternatives){const t=le(this.cfg.externalSourcesPreferredTypes);for(const r of t){const n=ta(r);for(const[o,l]of Object.entries(e.alternatives))if(n.test(o))return l}}return e.url}sendMessage(e){var t,r;(r=(t=this._iframe)==null?void 0:t.contentWindow)==null||r.postMessage(JSON.stringify(e),"*")}async handleFileSelected(e){!this.$.multiple&&this.$.selectedList.length||(this.$.selectedList=[...this.$.selectedList,e],this.$.multiple||this.$.onDone())}handleIframeLoad(){this.applyStyles()}getCssValue(e){return window.getComputedStyle(this).getPropertyValue(e).trim()}applyStyles(){let e={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:sa(e)})}remoteUrl(){var c,h;const{pubkey:e,remoteTabSessionKey:t,socialBaseUrl:r}=this.cfg,{externalSourceType:n}=this.activityParams,l={lang:((h=(c=this.l10n("social-source-lang"))==null?void 0:c.split("-"))==null?void 0:h[0])||"en",public_key:e,images_only:"false",pass_window_open:!1,session_key:t},a=new URL(`/window3/${n}`,r);return a.search=oa(l),a.toString()}mountIframe(){let e=Mt({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});e.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(e),ra("file-selected",e.contentWindow,this.handleFileSelected.bind(this)),this._iframe=e,this.$.selectedList=[]}unmountIframe(){this._iframe&&na("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}}rr.template=`
349
295
  <lr-activity-header>
350
296
  <button type="button" class="mini-btn" set="onclick: *historyBack">
351
297
  <lr-icon name="back"></lr-icon>
@@ -369,18 +315,18 @@
369
315
  </button>
370
316
  </div>
371
317
  </div>
372
- `;class ni extends k{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(t=>{t.getAttribute("tab-ctx")===i?t.removeAttribute("hidden"):t.setAttribute("hidden","")});for(let t in this._tabMap)t===i?this._tabMap[t].setAttribute("current",""):this._tabMap[t].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;ae(i).forEach(t=>{let r=Dt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(t)}}});r.textContent=this.l10n(t),this.ref.row.appendChild(r),this._tabMap[t]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}}ni.bindAttributes({"tab-list":null,default:null});ni.template=`
318
+ `;class ni extends ${setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(t=>{t.getAttribute("tab-ctx")===i?t.removeAttribute("hidden"):t.setAttribute("hidden","")});for(let t in this._tabMap)t===i?this._tabMap[t].setAttribute("current",""):this._tabMap[t].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;le(i).forEach(t=>{let r=Mt({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(t)}}});r.textContent=this.l10n(t),this.ref.row.appendChild(r),this._tabMap[t]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}}ni.bindAttributes({"tab-list":null,default:null});ni.template=`
373
319
  <div ref="row" class="tabs-row"></div>
374
320
  <div ref="context" class="tabs-context">
375
321
  <slot></slot>
376
322
  </div>
377
- `;class Ql extends ${constructor(){super(...arguments);u(this,"requireCtxName",!0)}_createValidationInput(){const e=document.createElement("input");return e.type="text",e.name=this.ctxName,e.required=this.cfg.multipleMin>0,e.tabIndex=-1,Gi(e,{opacity:0,height:0,width:0}),e}initCallback(){super.initCallback(),this._validationInputElement=this._createValidationInput(),this.appendChild(this._validationInputElement),this.sub("*collectionState",e=>{var t;{if(this._dynamicInputsContainer||(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer)),!this._validationInputElement){const l=this._createValidationInput();this.appendChild(l),this._validationInputElement=l}if(this._dynamicInputsContainer.innerHTML="",e.status==="uploading"||e.status==="idle"){this._validationInputElement.value="",this._validationInputElement.setCustomValidity("");return}if(e.status==="failed"){const l=(t=e.errors[0])==null?void 0:t.message;this._validationInputElement.value="",this._validationInputElement.setCustomValidity(l);return}const r=e.group?e.group:null;if(r){this._validationInputElement.value=r.cdnUrl,this._validationInputElement.setCustomValidity("");return}const n=e.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;const o=new DocumentFragment;for(let l of n){const a=document.createElement("input");a.type="hidden",a.name=`${this.ctxName}[]`,a.value=l,o.appendChild(a)}this._dynamicInputsContainer.replaceChildren(o)}},!1)}}class ea extends b{}class rr extends k{constructor(){super(...arguments);u(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:e=>{var t;e.preventDefault(),e.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((t=this.$.options.find(r=>r.value==this.value))==null?void 0:t.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",e=>{var r;this.$.currentText=((r=e==null?void 0:e[0])==null?void 0:r.text)||"";let t="";e==null||e.forEach(n=>{t+=`<option value="${n.value}">${n.text}</option>`}),this.$.selectHtml=t})}}rr.template=`
323
+ `;class la extends x{constructor(){super(...arguments);u(this,"requireCtxName",!0)}_createValidationInput(){const e=document.createElement("input");return e.type="text",e.name=this.ctxName,e.required=this.cfg.multipleMin>0,e.tabIndex=-1,Gi(e,{opacity:0,height:0,width:0}),e}initCallback(){super.initCallback(),this._validationInputElement=this._createValidationInput(),this.appendChild(this._validationInputElement),this.sub("*collectionState",e=>{var t;{if(this._dynamicInputsContainer||(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer)),!this._validationInputElement){const l=this._createValidationInput();this.appendChild(l),this._validationInputElement=l}if(this._dynamicInputsContainer.innerHTML="",e.status==="uploading"||e.status==="idle"){this._validationInputElement.value="",this._validationInputElement.setCustomValidity("");return}if(e.status==="failed"){const l=(t=e.errors[0])==null?void 0:t.message;this._validationInputElement.value="",this._validationInputElement.setCustomValidity(l);return}const r=e.group?e.group:null;if(r){this._validationInputElement.value=r.cdnUrl,this._validationInputElement.setCustomValidity("");return}const n=e.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;const o=new DocumentFragment;for(let l of n){const a=document.createElement("input");a.type="hidden",a.name=`${this.ctxName}[]`,a.value=l,o.appendChild(a)}this._dynamicInputsContainer.replaceChildren(o)}},!1)}}class aa extends _{}class nr extends ${constructor(){super(...arguments);u(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:e=>{var t;e.preventDefault(),e.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((t=this.$.options.find(r=>r.value==this.value))==null?void 0:t.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",e=>{var r;this.$.currentText=((r=e==null?void 0:e[0])==null?void 0:r.text)||"";let t="";e==null||e.forEach(n=>{t+=`<option value="${n.value}">${n.text}</option>`}),this.$.selectHtml=t})}}nr.template=`
378
324
  <button>
379
325
  {{currentText}}
380
326
  <lr-icon name="select"></lr-icon>
381
327
  <select ref="select" set="innerHTML: selectHtml; onchange: onSelect"></select>
382
328
  </button>
383
- `;const M={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"},Vi={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}};class ne extends k{constructor(){super(...arguments);u(this,"init$",{...this.init$,src:"",ppIcon:M.PLAY,fsIcon:M.FS_ON,volIcon:M.VOL_ON,capIcon:M.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:e=>{let t=parseFloat(e.currentTarget.$.value);this.setVolume(t)},progressClicked:e=>{let t=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(e.offsetX/t.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Vi.exitFullscreen():Vi.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===M.CAP_OFF?(this.$.capIcon=M.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(ne.is+":captions","1")):(this.$.capIcon=M.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(ne.is+":captions"))}toggleSound(){this.$.volIcon===M.VOL_ON?(this.$.volIcon=M.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=M.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(e){window.localStorage.setItem(ne.is+":volume",e);let t=e?e/100:0;this._video.volume=t}get progress(){return this.ref.progress}_getUrl(e){return e.includes("/")?e:`https://ucarecdn.com/${e}/`}_desc2attrs(e){let t=[];for(let r in e){let n=r==="src"?this._getUrl(e[r]):e[r];t.push(`${r}="${n}"`)}return t.join(" ")}_timeFmt(e){let t=new Date(Math.round(e)*1e3);return[t.getMinutes(),t.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(e=>{e.mode="hidden"}),window.localStorage.getItem(ne.is+":captions")&&this.toggleCaptions()}_castAttributes(){let e=["autoplay","loop","muted"];[...this.attributes].forEach(t=>{e.includes(t.name)&&this._video.setAttribute(t.name,t.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=M.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=M.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",t=>{console.log(t),document.fullscreenElement===this?this.$.fsIcon=M.FS_OFF:this.$.fsIcon=M.FS_ON}),this.sub("src",t=>{if(!t)return;let r=this._getUrl(t);this._video.src=r}),this.sub("video",async t=>{if(!t)return;let r=await(await window.fetch(this._getUrl(t))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=`<source ${this._desc2attrs(o)} />`}),r.tracks&&(r.tracks.forEach(o=>{n+=`<track ${this._desc2attrs(o)} />`}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",t=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",t=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let e=window.localStorage.getItem(ne.is+":volume");if(e){let t=parseFloat(e);this.setVolume(t),this.$.volumeValue=t}}}ne.template=`
329
+ `;const M={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"},Vi={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}};class ne extends ${constructor(){super(...arguments);u(this,"init$",{...this.init$,src:"",ppIcon:M.PLAY,fsIcon:M.FS_ON,volIcon:M.VOL_ON,capIcon:M.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:e=>{let t=parseFloat(e.currentTarget.$.value);this.setVolume(t)},progressClicked:e=>{let t=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(e.offsetX/t.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Vi.exitFullscreen():Vi.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===M.CAP_OFF?(this.$.capIcon=M.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(ne.is+":captions","1")):(this.$.capIcon=M.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(ne.is+":captions"))}toggleSound(){this.$.volIcon===M.VOL_ON?(this.$.volIcon=M.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=M.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(e){window.localStorage.setItem(ne.is+":volume",e);let t=e?e/100:0;this._video.volume=t}get progress(){return this.ref.progress}_getUrl(e){return e.includes("/")?e:`https://ucarecdn.com/${e}/`}_desc2attrs(e){let t=[];for(let r in e){let n=r==="src"?this._getUrl(e[r]):e[r];t.push(`${r}="${n}"`)}return t.join(" ")}_timeFmt(e){let t=new Date(Math.round(e)*1e3);return[t.getMinutes(),t.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(e=>{e.mode="hidden"}),window.localStorage.getItem(ne.is+":captions")&&this.toggleCaptions()}_castAttributes(){let e=["autoplay","loop","muted"];[...this.attributes].forEach(t=>{e.includes(t.name)&&this._video.setAttribute(t.name,t.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=M.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=M.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",t=>{console.log(t),document.fullscreenElement===this?this.$.fsIcon=M.FS_OFF:this.$.fsIcon=M.FS_ON}),this.sub("src",t=>{if(!t)return;let r=this._getUrl(t);this._video.src=r}),this.sub("video",async t=>{if(!t)return;let r=await(await window.fetch(this._getUrl(t))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=`<source ${this._desc2attrs(o)} />`}),r.tracks&&(r.tracks.forEach(o=>{n+=`<track ${this._desc2attrs(o)} />`}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",t=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",t=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let e=window.localStorage.getItem(ne.is+":volume");if(e){let t=parseFloat(e);this.setVolume(t),this.$.volumeValue=t}}}ne.template=`
384
330
  <div class="video-wrapper">
385
331
  <video ref="video" preload="metadata" crossorigin="anonymous"></video>
386
332
  </div>
@@ -413,14 +359,14 @@
413
359
  </button>
414
360
  </div>
415
361
  </div>
416
- `;ne.bindAttributes({video:"video",src:"src"});const ta="css-src";function oi(s){return class extends s{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0);u(this,"requireCtxName",!0)}shadowReadyCallback(){}async _waitForShadowStylesLoad(){if(!this.shadowRoot)return;const e=this.constructor.__shadowStylesUrl,t=this.shadowRoot.querySelector(`link[href="${e}"]`);t&&await new Promise((r,n)=>{t.addEventListener("load",r),t.addEventListener("error",n)})}initCallback(){super.initCallback(),this.setAttribute("hidden",""),Zi({element:this,attribute:ta,onSuccess:e=>{this.attachShadow({mode:"open"});let t=document.createElement("link");t.rel="stylesheet",t.type="text/css",t.href=e,t.onload=()=>{window.requestAnimationFrame(async()=>{this.render(),await this._waitForShadowStylesLoad(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(t)},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/")}})}}}class nr extends oi(k){}class or extends k{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}}u(or,"template",`
362
+ `;ne.bindAttributes({video:"video",src:"src"});class or extends ${initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}}u(or,"template",`
417
363
  <a
418
364
  href="https://uploadcare.com/?utm_source=copyright&utm_medium=referral&utm_campaign=v4"
419
365
  target="_blank noopener"
420
366
  class="credits"
421
367
  >Powered by Uploadcare</a
422
368
  >
423
- `);class li extends nr{constructor(){super(...arguments);u(this,"requireCtxName",!0);u(this,"init$",ds(this));u(this,"_template",null)}static set template(e){this._template=e+"<slot></slot>"}static get template(){return this._template}}let ai=class extends li{shadowReadyCallback(){super.shadowReadyCallback(),this.sub("*modalActive",i=>{this._lastModalActive!==i&&this.emit(i?x.MODAL_OPEN:x.MODAL_CLOSE,void 0,{debounce:!0}),this._lastModalActive=i},!1)}};ai.template=`
369
+ `);class oi extends ${constructor(){super(...arguments);u(this,"requireCtxName",!0);u(this,"init$",us(this));u(this,"_template",null)}static set template(e){this._template=e+"<slot></slot>"}static get template(){return this._template}}let li=class extends oi{initCallback(){super.initCallback(),this.sub("*modalActive",i=>{this._lastModalActive!==i&&this.emit(i?I.MODAL_OPEN:I.MODAL_CLOSE,void 0,{debounce:!0}),this._lastModalActive=i},!1)}};li.template=`
424
370
  <lr-simple-btn></lr-simple-btn>
425
371
 
426
372
  <lr-modal strokes block-body-scrolling>
@@ -438,13 +384,13 @@
438
384
  </lr-modal>
439
385
 
440
386
  <lr-progress-bar-common></lr-progress-bar-common>
441
- `;let Ct=class extends li{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){const e=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=e.initActivity||b.activities.START_FROM)}),this.sub("*uploadList",t=>{(t==null?void 0:t.length)>0?this.$["*currentActivity"]=b.activities.UPLOAD_LIST:this.$["*currentActivity"]=e.initActivity||b.activities.START_FROM}),this.subConfigValue("sourceList",t=>{t!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",t=>{t!==!1&&(this.cfg.confirmUpload=!1)})}};Ct.template=`
387
+ `;let vt=class extends oi{initCallback(){super.initCallback();const i=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=i.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=_.activities.UPLOAD_LIST:this.$["*currentActivity"]=i.initActivity||_.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};vt.template=`
442
388
  <lr-start-from>
443
389
  <lr-drop-area clickable l10n="choose-file"></lr-drop-area>
444
390
  <lr-copyright></lr-copyright>
445
391
  </lr-start-from>
446
392
  <lr-upload-list ref="uBlock"></lr-upload-list>
447
- `;let lr=class extends li{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=b.activities.UPLOAD_LIST)}}}get couldHistoryBack(){const i=this.$["*history"];return i.length>1&&i[i.length-1]!==b.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}shadowReadyCallback(){const i=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=i.initActivity||b.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0&&this.$["*currentActivity"]===(i.initActivity||b.activities.START_FROM)&&(this.$["*currentActivity"]=b.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};lr.template=` <lr-start-from>
393
+ `;let lr=class extends oi{constructor(){super(),this.init$={...this.init$,couldCancel:!1,cancel:()=>{this.couldHistoryBack?this.$["*historyBack"]():this.couldShowList&&(this.$["*currentActivity"]=_.activities.UPLOAD_LIST)}}}get couldHistoryBack(){const i=this.$["*history"];return i.length>1&&i[i.length-1]!==_.activities.START_FROM}get couldShowList(){return this.cfg.showEmptyList||this.$["*uploadList"].length>0}initCallback(){super.initCallback();const i=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=i.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0&&this.$["*currentActivity"]===(i.initActivity||_.activities.START_FROM)&&(this.$["*currentActivity"]=_.activities.UPLOAD_LIST)}),this.sub("*history",()=>{this.$.couldCancel=this.couldHistoryBack||this.couldShowList})}};lr.template=` <lr-start-from>
448
394
  <lr-drop-area with-icon clickable></lr-drop-area>
449
395
  <lr-source-list wrap></lr-source-list>
450
396
  <button
@@ -460,4 +406,4 @@
460
406
  <lr-url-source></lr-url-source>
461
407
  <lr-external-source></lr-external-source>
462
408
  <lr-progress-bar></lr-progress-bar>
463
- <lr-cloud-image-editor-activity></lr-cloud-image-editor-activity>`;class ia extends oi(Fe){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 Xe(s){for(let i in s){let e=[...i].reduce((t,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),t+=r),"");e.startsWith("-")&&(e=e.replace("-","")),e.startsWith("lr-")||(e="lr-"+e),s[i].reg&&s[i].reg(e)}}const It="LR";async function sa(s,i=!1){return new Promise((e,t)=>{if(typeof document!="object"){e(null);return}if(typeof window=="object"&&window[It]){e(window[It]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{t()},r.onload=()=>{let n=window[It];i&&Xe(n),e(n)},document.head.appendChild(r)})}const ci=Object.freeze(Object.defineProperty({__proto__:null,ActivityBlock:b,ActivityHeader:ea,BaseComponent:ht,Block:k,CameraSource:zs,CloudImageEditor:ia,CloudImageEditorActivity:Wl,CloudImageEditorBlock:Fe,Config:As,ConfirmationDialog:js,Copyright:or,CropFrame:Gs,Data:T,DropArea:Jt,EditorCropButtonControl:Xs,EditorFilterControl:ii,EditorImageCropper:Js,EditorImageFader:Vl,EditorOperationControl:Ys,EditorScroller:Zs,EditorSlider:Ks,EditorToolbar:Qs,ExternalSource:sr,FileItem:we,FilePreview:ei,FileUploaderInline:lr,FileUploaderMinimal:Ct,FileUploaderRegular:ai,FormInput:Ql,Icon:Kt,Img:Wo,LineLoaderUi:er,LrBtnUi:ri,Modal:Qt,PACKAGE_NAME:qt,PACKAGE_VERSION:bt,PresenceToggle:tr,ProgressBar:Ws,ProgressBarCommon:Hs,Select:rr,ShadowWrapper:nr,SimpleBtn:Yt,SliderUi:ir,SourceBtn:Zt,SourceList:Zo,StartFrom:$s,Tabs:ni,UID:Ae,UploadCtxProvider:ct,UploadDetails:Bs,UploadList:Ns,UploaderBlock:$,UrlSource:Ds,Video:ne,connectBlocksFrom:sa,registerBlocks:Xe,shadowed:oi,toKebabCase:Ce},Symbol.toStringTag,{value:"Module"})),ra=new Set(["children","ref","style","className"]),na=(s={})=>Object==null?void 0:Object.keys(s).reduce((i,e)=>{var t,r;const n=s==null?void 0:s[e],o=`on${(r=(t=n==null?void 0:n.split("-"))==null?void 0:t.map(l=>l.charAt(0).toUpperCase()+l.slice(1)))==null?void 0:r.join("")}`;return i[o]=n,i},{}),Bi=new WeakMap,oa=s=>{let i=Bi.get(s);return i||(i=new Map,Bi.set(s,i)),i},ji=({node:s,nameProp:i,valueProp:e,prevValueProp:t,event:r})=>{if(r!==void 0&&e!==t){const n=oa(s),o=n.has(r);if(e){const l={handleEvent:e};o||s.addEventListener(r,l),n.set(r,l)}else if(o){const l=n.get(r);s.removeEventListener(r,l),n.delete(r)}return}s[i]=e,e==null&&i in HTMLElement.prototype&&s.removeAttribute(i)},la=(s,i,e)=>{const t={},r={};return Object.entries(s).forEach(([n,o])=>{ra.has(n)?t[n==="className"?"class":n]=o:i.has(n)||n in e.prototype?r[n]=o:t[n]=o}),{reactProps:t,customElProps:r}},Ke=({react:s,tag:i,elClass:e,schemaEvents:t})=>{const r=na(t),n=new Set(Object.keys(r??{})),o=s.forwardRef((l,a)=>{const c=s.useRef(new Map),h=s.useRef(null),{reactProps:d,customElProps:f}=la(l,n,e);return s.useLayoutEffect(()=>{if(h.current===null)return;const m=new Map;for(const p in f)ji({node:h.current,nameProp:p,valueProp:f[p],prevValueProp:c.current.get(p),event:r[p]}),c.current.delete(p),m.set(p,l[p]);for(const[p,g]of c.current)ji({node:h.current,nameProp:p,valueProp:void 0,prevValueProp:g,event:r[p]});c.current=m}),s.createElement(i??e.__tag,{...d,ref:s.useCallback(m=>{h.current=m,typeof a=="function"?a(m):a!==null&&(a.current=m)},[a])})});return o.displayName=e.name,o},hi=Ke({react:S,tag:"lr-config",elClass:As}),ui=Ke({react:S,tag:"lr-upload-ctx-provider",elClass:ct,schemaEvents:ct.EventType}),di=s=>`https://cdn.jsdelivr.net/npm/@uploadcare/blocks@${bt}/web/lr-file-uploader-${s}.min.css`,fi=s=>{const i={},e={};return Object.entries(s).forEach(([t,r])=>{t.startsWith("on")?i[t]=r:e[t]=r}),{eventHandlers:i,config:e}},aa="0.3.0-alpha.0",ca="React-Uploader",pi=()=>`${ca}/${aa}`;Xe(ci);const ha=Ke({react:S,tag:"lr-file-uploader-regular",elClass:ai}),ua=di("regular"),da=({ctxName:s,className:i,apiRef:e,...t})=>{const r=S.useMemo(()=>s??Ae.generate(),[s]),{eventHandlers:n,config:o}=S.useMemo(()=>fi(t),[t]);return S.createElement("div",{className:i},S.createElement(hi,{userAgentIntegration:pi(),"ctx-name":r,...o}),S.createElement(ui,{ref:e,"ctx-name":r,...n}),S.createElement(ha,{"ctx-name":r,"css-src":ua}))};Xe(ci);const fa=Ke({react:S,tag:"lr-file-uploader-minimal",elClass:Ct}),pa=di("minimal"),ma=({ctxName:s,className:i,apiRef:e,...t})=>{const r=S.useMemo(()=>s??Ae.generate(),[s]),{eventHandlers:n,config:o}=S.useMemo(()=>fi(t),[t]);return S.createElement("div",{className:i},S.createElement(hi,{userAgentIntegration:pi(),"ctx-name":r,...o}),S.createElement(ui,{ref:e,"ctx-name":r,...n}),S.createElement(fa,{"ctx-name":r,"css-src":pa}))};Xe(ci);const ga=Ke({react:S,tag:"lr-file-uploader-inline",elClass:Ct}),ba=di("inline"),_a=({ctxName:s,className:i,apiRef:e,...t})=>{const r=S.useMemo(()=>s??Ae.generate(),[s]),{eventHandlers:n,config:o}=S.useMemo(()=>fi(t),[t]);return S.createElement("div",{className:i},S.createElement(hi,{userAgentIntegration:pi(),"ctx-name":r,...o}),S.createElement(ui,{ref:e,"ctx-name":r,...n}),S.createElement(ga,{"ctx-name":r,"css-src":ba}))};exports.FileUploaderInline=_a;exports.FileUploaderMinimal=ma;exports.FileUploaderRegular=da;exports.UploadCtxProvider=ct;
409
+ <lr-cloud-image-editor-activity></lr-cloud-image-editor-activity>`;class ca extends Me{initCallback(){super.initCallback(),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 Ge(s){for(let i in s){let e=[...i].reduce((t,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),t+=r),"");e.startsWith("-")&&(e=e.replace("-","")),e.startsWith("lr-")||(e="lr-"+e),s[i].reg&&s[i].reg(e)}}const St="LR";async function ha(s,i=!1){return new Promise((e,t)=>{if(typeof document!="object"){e(null);return}if(typeof window=="object"&&window[St]){e(window[St]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{t()},r.onload=()=>{let n=window[St];i&&Ge(n),e(n)},document.head.appendChild(r)})}const ai=Object.freeze(Object.defineProperty({__proto__:null,ActivityBlock:_,ActivityHeader:aa,BaseComponent:at,Block:$,CameraSource:Bs,CloudImageEditor:ca,CloudImageEditorActivity:Ql,CloudImageEditorBlock:Me,Config:$s,ConfirmationDialog:Hs,Copyright:or,CropFrame:Xs,Data:T,DropArea:Jt,EditorCropButtonControl:Ys,EditorFilterControl:ii,EditorImageCropper:Zs,EditorImageFader:Yl,EditorOperationControl:Js,EditorScroller:Qs,EditorSlider:Ks,EditorToolbar:er,ExternalSource:rr,FileItem:we,FilePreview:ei,FileUploaderInline:lr,FileUploaderMinimal:vt,FileUploaderRegular:li,FormInput:la,Icon:Yt,Img:Qo,LineLoaderUi:tr,LrBtnUi:ri,Modal:Qt,PACKAGE_NAME:jt,PACKAGE_VERSION:Ht,PresenceToggle:ir,ProgressBar:qs,ProgressBarCommon:Ws,Select:nr,SimpleBtn:Kt,SliderUi:sr,SourceBtn:Zt,SourceList:ol,StartFrom:xs,Tabs:ni,UID:Ae,UploadCtxProvider:lt,UploadList:zs,UploaderBlock:x,UrlSource:Vs,Video:ne,connectBlocksFrom:ha,defineLocale:fs,registerBlocks:Ge,toKebabCase:gt},Symbol.toStringTag,{value:"Module"})),ua=new Set(["children","ref","style","className"]),da=(s={})=>Object==null?void 0:Object.keys(s).reduce((i,e)=>{var t,r;const n=s==null?void 0:s[e],o=`on${(r=(t=n==null?void 0:n.split("-"))==null?void 0:t.map(l=>l.charAt(0).toUpperCase()+l.slice(1)))==null?void 0:r.join("")}`;return i[o]=n,i},{}),Bi=new WeakMap,fa=s=>{let i=Bi.get(s);return i||(i=new Map,Bi.set(s,i)),i},ji=({node:s,nameProp:i,valueProp:e,prevValueProp:t,event:r})=>{if(r!==void 0&&e!==t){const n=fa(s),o=n.has(r);if(e){const l={handleEvent:e};o||s.addEventListener(r,l),n.set(r,l)}else if(o){const l=n.get(r);s.removeEventListener(r,l),n.delete(r)}return}s[i]=e,e==null&&i in HTMLElement.prototype&&s.removeAttribute(i)},pa=(s,i,e)=>{const t={},r={};return Object.entries(s).forEach(([n,o])=>{ua.has(n)?t[n==="className"?"class":n]=o:i.has(n)||n in e.prototype?r[n]=o:t[n]=o}),{reactProps:t,customElProps:r}},Xe=({react:s,tag:i,elClass:e,schemaEvents:t})=>{const r=da(t),n=new Set(Object.keys(r??{})),o=s.forwardRef((l,a)=>{const c=s.useRef(new Map),h=s.useRef(null),{reactProps:d,customElProps:f}=pa(l,n,e);return s.useLayoutEffect(()=>{if(h.current===null)return;const m=new Map;for(const p in f)ji({node:h.current,nameProp:p,valueProp:f[p],prevValueProp:c.current.get(p),event:r[p]}),c.current.delete(p),m.set(p,l[p]);for(const[p,g]of c.current)ji({node:h.current,nameProp:p,valueProp:void 0,prevValueProp:g,event:r[p]});c.current=m}),s.createElement(i??e.__tag,{...d,ref:s.useCallback(m=>{h.current=m,typeof a=="function"?a(m):a!==null&&(a.current=m)},[a])})});return o.displayName=e.name,o},ci=Xe({react:S,tag:"lr-config",elClass:$s}),hi=Xe({react:S,tag:"lr-upload-ctx-provider",elClass:lt,schemaEvents:lt.EventType}),ui=s=>{const i={},e={};return Object.entries(s).forEach(([t,r])=>{t.startsWith("on")?i[t]=r:e[t]=r}),{eventHandlers:i,config:e}},ma="0.3.0-alpha.2",ga="React-Uploader",di=()=>`${ga}/${ma}`;Ge(ai);const ba=Xe({react:S,tag:"lr-file-uploader-regular",elClass:li}),_a=({ctxName:s,className:i,apiRef:e,...t})=>{const r=S.useMemo(()=>s??Ae.generate(),[s]),{eventHandlers:n,config:o}=S.useMemo(()=>ui(t),[t]);return S.createElement("div",{className:i},S.createElement(ci,{userAgentIntegration:di(),"ctx-name":r,...o}),S.createElement(hi,{ref:e,"ctx-name":r,...n}),S.createElement(ba,{"ctx-name":r}))};Ge(ai);const va=Xe({react:S,tag:"lr-file-uploader-minimal",elClass:vt}),ya=({ctxName:s,className:i,apiRef:e,...t})=>{const r=S.useMemo(()=>s??Ae.generate(),[s]),{eventHandlers:n,config:o}=S.useMemo(()=>ui(t),[t]);return S.createElement("div",{className:i},S.createElement(ci,{userAgentIntegration:di(),"ctx-name":r,...o}),S.createElement(hi,{ref:e,"ctx-name":r,...n}),S.createElement(va,{"ctx-name":r}))};Ge(ai);const Ca=Xe({react:S,tag:"lr-file-uploader-inline",elClass:vt}),wa=({ctxName:s,className:i,apiRef:e,...t})=>{const r=S.useMemo(()=>s??Ae.generate(),[s]),{eventHandlers:n,config:o}=S.useMemo(()=>ui(t),[t]);return S.createElement("div",{className:i},S.createElement(ci,{userAgentIntegration:di(),"ctx-name":r,...o}),S.createElement(hi,{ref:e,"ctx-name":r,...n}),S.createElement(Ca,{"ctx-name":r}))};exports.FileUploaderInline=wa;exports.FileUploaderMinimal=ya;exports.FileUploaderRegular=_a;exports.UploadCtxProvider=lt;