UNPKG

@uploadcare/file-uploader

Version:

Building blocks for Uploadcare products integration

29 lines 133 kB
/** * @license * MIT License * * Copyright (c) 2025 Uploadcare (hello@uploadcare.com). All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ var qr=Object.defineProperty,Yr=(r,e,t)=>e in r?qr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,rt=(r,e,t)=>(Yr(r,typeof e!="symbol"?e+"":e,t),t);function Zr(r){let e=t=>{var i;for(let s in t)((i=t[s])==null?void 0:i.constructor)===Object&&(t[s]=e(t[s]));return{...t}};return e(r)}var T=class{constructor(r){r.constructor===Object?this.store=Zr(r):(this._storeIsProxy=!0,this.store=r),this.callbackMap=Object.create(null)}static warn(r,e){console.warn(`Symbiote Data: cannot ${r}. Prop name: `+e)}read(r){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(T.warn("read",r),null):this.store[r]}has(r){return this._storeIsProxy?this.store[r]!==void 0:this.store.hasOwnProperty(r)}add(r,e,t=!1){!t&&Object.keys(this.store).includes(r)||(this.store[r]=e,this.notify(r))}pub(r,e){if(!this._storeIsProxy&&!this.store.hasOwnProperty(r)){T.warn("publish",r);return}this.store[r]=e,this.notify(r)}multiPub(r){for(let e in r)this.pub(e,r[e])}notify(r){this.callbackMap[r]&&this.callbackMap[r].forEach(e=>{e(this.store[r])})}sub(r,e,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(T.warn("subscribe",r),null):(this.callbackMap[r]||(this.callbackMap[r]=new Set),this.callbackMap[r].add(e),t&&e(this.store[r]),{remove:()=>{this.callbackMap[r].delete(e),this.callbackMap[r].size||delete this.callbackMap[r]},callback:e})}static registerCtx(r,e=Symbol()){let t=T.globalStore.get(e);return t?console.warn('State: context UID "'+e+'" already in use'):(t=new T(r),T.globalStore.set(e,t)),t}static deleteCtx(r){T.globalStore.delete(r)}static getCtx(r,e=!0){return T.globalStore.get(r)||(e&&console.warn('State: wrong context UID - "'+r+'"'),null)}};T.globalStore=new Map;var m=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"}),Lt="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Jr=Lt.length-1,it=class{static generate(r="XXXXXXXXX-XXX"){let e="";for(let t=0;t<r.length;t++)e+=r[t]==="-"?r[t]:Lt.charAt(Math.random()*Jr);return e}};function Mt(r,e,t){let i=!0,s,o=e.split(".");return o.forEach((n,a)=>{a<o.length-1?r=r[n]:s=n}),r?r[s]=t:i=!1,i}function Qr(r){return r.split("-").map((e,t)=>e&&t?e[0].toUpperCase()+e.slice(1):e).join("").split("_").map((e,t)=>e&&t?e.toUpperCase():e).join("")}function ei(r,e){[...r.querySelectorAll(`[${m.REPEAT_ATTR}]`)].forEach(t=>{let i=t.getAttribute(m.REPEAT_ITEM_TAG_ATTR),s;if(i&&(s=window.customElements.get(i)),!s){s=class extends e.BaseComponent{constructor(){super(),i||(this.style.display="contents")}};let n=t.innerHTML;s.template=n,s.reg(i)}for(;t.firstChild;)t.firstChild.remove();let o=t.getAttribute(m.REPEAT_ATTR);e.sub(o,n=>{if(!n){for(;t.firstChild;)t.firstChild.remove();return}let a=[...t.children],l,c=u=>{u.forEach((p,h)=>{if(a[h])if(a[h].set$)setTimeout(()=>{a[h].set$(p)});else for(let g in p)a[h][g]=p[g];else{l||(l=new DocumentFragment);let g=new s;Object.assign(g.init$,p),l.appendChild(g)}}),l&&t.appendChild(l);let d=a.slice(u.length,a.length);for(let p of d)p.remove()};if(n.constructor===Array)c(n);else if(n.constructor===Object){let u=[];for(let d in n){let p=n[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),t.removeAttribute(m.REPEAT_ATTR),t.removeAttribute(m.REPEAT_ITEM_TAG_ATTR)})}var It="__default__";function ti(r,e){if(e.shadowRoot)return;let t=[...r.querySelectorAll("slot")];if(!t.length)return;let i={};t.forEach(s=>{let o=s.getAttribute("name")||It;i[o]={slot:s,fr:document.createDocumentFragment()}}),e.initChildren.forEach(s=>{var o;let n=It;s instanceof Element&&s.hasAttribute("slot")&&(n=s.getAttribute("slot"),s.removeAttribute("slot")),(o=i[n])==null||o.fr.appendChild(s)}),Object.values(i).forEach(s=>{if(s.fr.childNodes.length)s.slot.parentNode.replaceChild(s.fr,s.slot);else if(s.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...s.slot.childNodes),s.slot.parentNode.replaceChild(o,s.slot)}else s.slot.remove()})}function ri(r,e){[...r.querySelectorAll(`[${m.EL_REF_ATTR}]`)].forEach(t=>{let i=t.getAttribute(m.EL_REF_ATTR);e.ref[i]=t,t.removeAttribute(m.EL_REF_ATTR)})}function ii(r,e){[...r.querySelectorAll(`[${m.BIND_ATTR}]`)].forEach(t=>{let s=t.getAttribute(m.BIND_ATTR).split(";");[...t.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=Qr(o.name.replace("-",""));s.push(n+":"+o.value),t.removeAttribute(o.name)}}),s.forEach(o=>{if(!o)return;let n=o.split(":").map(u=>u.trim()),a=n[0],l;a.indexOf(m.ATTR_BIND_PRFX)===0&&(l=!0,a=a.replace(m.ATTR_BIND_PRFX,""));let c=n[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),e.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),l?p?.constructor===Boolean?p?t.setAttribute(a,""):t.removeAttribute(a):t.setAttribute(a,p):Mt(t,a,p)||(t[m.SET_LATER_KEY]||(t[m.SET_LATER_KEY]=Object.create(null)),t[m.SET_LATER_KEY][a]=p)})}}),t.removeAttribute(m.BIND_ATTR)})}var Se="{{",ue="}}",si="skip-text";function oi(r){let e,t=[],i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,{acceptNode:s=>{var o;return!((o=s.parentElement)!=null&&o.hasAttribute(si))&&s.textContent.includes(Se)&&s.textContent.includes(ue)&&1}});for(;e=i.nextNode();)t.push(e);return t}var ni=function(r,e){oi(r).forEach(i=>{let s=[],o;for(;i.textContent.includes(ue);)i.textContent.startsWith(Se)?(o=i.textContent.indexOf(ue)+ue.length,i.splitText(o),s.push(i)):(o=i.textContent.indexOf(Se),i.splitText(o)),i=i.nextSibling;s.forEach(n=>{let a=n.textContent.replace(Se,"").replace(ue,"");n.textContent="",e.sub(a,l=>{n.textContent=l})})})},ai=[ei,ti,ri,ii,ni],ke="'",Q='"',li=/\\([0-9a-fA-F]{1,6} ?)/g;function ci(r){return(r[0]===Q||r[0]===ke)&&(r[r.length-1]===Q||r[r.length-1]===ke)}function ui(r){return(r[0]===Q||r[0]===ke)&&(r=r.slice(1)),(r[r.length-1]===Q||r[r.length-1]===ke)&&(r=r.slice(0,-1)),r}function di(r){let e="",t="";for(var i=0;i<r.length;i++){let s=r[i+1];r[i]==="\\"&&s==='"'?(e+='\\"',i++):r[i]==='"'&&t!=="\\"?e+='\\"':e+=r[i],t=r[i]}return e}function pi(r){let e=r;ci(r)&&(e=ui(e),e=e.replace(li,(t,i)=>String.fromCodePoint(parseInt(i.trim(),16))),e=e.replaceAll(`\\ `,"\\n"),e=di(e),e=Q+e+Q);try{return JSON.parse(e)}catch{throw new Error(`Failed to parse CSS property value: ${e}. Original input: ${r}`)}}var Rt=0,J=null,U=null,B=class extends HTMLElement{constructor(){super(),rt(this,"updateCssData",()=>{var r;this.dropCssDataCache(),(r=this.__boundCssProps)==null||r.forEach(e=>{let t=this.getCssData(this.__extractCssName(e),!0);t!==null&&this.$[e]!==t&&(this.$[e]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return B}initCallback(){}__initCallback(){var r;this.__initialized||(this.__initialized=!0,(r=this.initCallback)==null||r.call(this))}render(r,e=this.renderShadow){let t;if((e||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(m.USE_TPL);if(s){let o=this.getRootNode(),n=o?.querySelector(s)||document.querySelector(s);n?r=n.content.cloneNode(!0):console.warn(`Symbiote template "${s}" is not found...`)}}if(this.processInnerHtml)for(let s of this.tplProcessors)s(this,this);if(r||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),r?.constructor===DocumentFragment)t=r;else if(r?.constructor===String){let s=document.createElement("template");s.innerHTML=r,t=s.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(t,this)}let i=()=>{t&&(e&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){e=!0;let s=document.createElement("link");s.rel="stylesheet",s.href=this.constructor.__shadowStylesUrl,s.onload=i,this.shadowRoot.prepend(s)}else i()}addTemplateProcessor(r){this.tplProcessors.add(r)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=it.generate(),this.style.setProperty(m.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(m.CSS_CTX_PROP,!0)}get ctxName(){var r;let e=((r=this.getAttribute(m.CTX_NAME_ATTR))==null?void 0:r.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=e,e}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(r,e){let t,i;if(r.startsWith(m.EXT_DATA_CTX_PRFX))t=e.nodeCtx,i=r.replace(m.EXT_DATA_CTX_PRFX,"");else if(r.includes(m.NAMED_DATA_CTX_SPLTR)){let s=r.split(m.NAMED_DATA_CTX_SPLTR);t=T.getCtx(s[0]),i=s[1]}else t=e.localCtx,i=r;return{ctx:t,name:i}}sub(r,e,t=!0){let i=o=>{this.isConnected&&e(o)},s=B.__parseProp(r,this);s.ctx.has(s.name)?this.allSubs.add(s.ctx.sub(s.name,i,t)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,i,t))})}notify(r){let e=B.__parseProp(r,this);e.ctx.notify(e.name)}has(r){let e=B.__parseProp(r,this);return e.ctx.has(e.name)}add(r,e,t=!1){let i=B.__parseProp(r,this);i.ctx.add(i.name,e,t)}add$(r,e=!1){for(let t in r)this.add(t,r[t],e)}get $(){if(!this.__stateProxy){let r=Object.create(null);this.__stateProxy=new Proxy(r,{set:(e,t,i)=>{let s=B.__parseProp(t,this);return s.ctx.pub(s.name,i),!0},get:(e,t)=>{let i=B.__parseProp(t,this);return i.ctx.read(i.name)}})}return this.__stateProxy}set$(r,e=!1){for(let t in r){let i=r[t];e||![String,Number,Boolean].includes(i?.constructor)?this.$[t]=i:this.$[t]!==i&&(this.$[t]=i)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(m.CTX_OWNER_ATTR)&&this.getAttribute(m.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let r=this.constructor.__attrDesc;if(r)for(let e of Object.values(r))Object.keys(this.init$).includes(e)||(this.init$[e]="");for(let e in this.init$)if(e.startsWith(m.EXT_DATA_CTX_PRFX))this.nodeCtx.add(e.replace(m.EXT_DATA_CTX_PRFX,""),this.init$[e],this.__ctxOwner);else if(e.includes(m.NAMED_DATA_CTX_SPLTR)){let t=e.split(m.NAMED_DATA_CTX_SPLTR),i=t[0].trim(),s=t[1].trim();if(i&&s){let o=T.getCtx(i,!1);o||(o=T.registerCtx({},i)),o.add(s,this.init$[e])}}else this.localCtx.add(e,this.init$[e]);for(let e in this.cssInit$)this.bindCssData(e,this.cssInit$[e]);this.__dataCtxInitialized=!0}connectedCallback(){var r;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let e=(r=this.getAttribute(m.CTX_NAME_ATTR))==null?void 0:r.trim();if(e&&this.style.setProperty(m.CSS_CTX_PROP,`'${e}'`),this.__initDataCtx(),this[m.SET_LATER_KEY]){for(let t in this[m.SET_LATER_KEY])Mt(this,t,this[m.SET_LATER_KEY][t]);delete this[m.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of ai)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t?.querySelector(`link[${m.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(m.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(s):t.prepend(s)}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 r of this.allSubs)r.remove(),this.allSubs.delete(r);for(let r of this.tplProcessors)this.tplProcessors.delete(r);U?.delete(this.updateCssData),U?.size||(J?.disconnect(),J=null,U=null)},100)))}static reg(r,e=!1){r||(Rt++,r=`${m.AUTO_TAG_PRFX}-${Rt}`),this.__tag=r;let t=window.customElements.get(r);if(t){!e&&t!==this&&console.warn([`Element with tag name "${r}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(r,e?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(r){this.observedAttributes=Object.keys(r),this.__attrDesc=r}attributeChangedCallback(r,e,t){var i;if(e===t)return;let s=(i=this.constructor.__attrDesc)==null?void 0:i[r];s?this.__dataCtxInitialized?this.$[s]=t:this.init$[s]=t:this[r]=t}getCssData(r,e=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(r)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(r).trim();try{this.__cssDataCache[r]=pi(t)}catch{!e&&console.warn(`CSS Data error: ${r}`),this.__cssDataCache[r]=null}}return this.__cssDataCache[r]}__extractCssName(r){return r.split("--").map((e,t)=>t===0?"":e).join("--")}__initStyleAttrObserver(){U||(U=new Set),U.add(this.updateCssData),J||(J=new MutationObserver(r=>{r[0].type==="attributes"&&U.forEach(e=>{e()})}),J.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(r,e=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(r);let t=this.getCssData(this.__extractCssName(r),!0);t===null&&(t=e),this.add(r,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(r,e,t){let i="__"+r;this[i]=this[r],Object.defineProperty(this,r,{set:s=>{this[i]=s,t?window.setTimeout(()=>{e?.(s)}):e?.(s)},get:()=>this[i]}),this[r]=this[i]}static set shadowStyles(r){let e=new Blob([r],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(e)}static set rootStyles(r){if(!this.__rootStylesLink){let e=new Blob([r],{type:"text/css"}),t=URL.createObjectURL(e),i=document.createElement("link");i.href=t,i.rel="stylesheet",this.__rootStylesLink=i}}},st=B;rt(st,"template");var tt=class{static _print(r){console.warn(r)}static setDefaultTitle(r){this.defaultTitle=r}static setRoutingMap(r){Object.assign(this.appMap,r);for(let e in this.appMap)!this.defaultRoute&&this.appMap[e].default===!0?this.defaultRoute=e:!this.errorRoute&&this.appMap[e].error===!0&&(this.errorRoute=e)}static set routingEventName(r){this.__routingEventName=r}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let r={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))r.route=t.replace("?","");else if(t.includes("=")){let i=t.split("=");r.options[i[0]]=decodeURI(i[1])}else r.options[t]=!0}),r}static notify(){let r=this.readAddressBar(),e=this.appMap[r.route];if(e&&e.title&&(document.title=e.title),r.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!e&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!e&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!e){this._print(`Route "${r.route}" not found...`);return}let t=new CustomEvent(tt.routingEventName,{detail:{route:r.route,options:Object.assign(e||{},r.options)}});window.dispatchEvent(t)}static reflect(r,e={}){let t=this.appMap[r];if(!t){this._print("Wrong route: "+r);return}let i="?"+r;for(let o in e)e[o]===!0?i+=this.separator+o:i+=this.separator+o+`=${e[o]}`;let s=t.title||this.defaultTitle||"";window.history.pushState(null,s,i),document.title=s}static applyRoute(r,e={}){this.reflect(r,e),this.notify()}static setSeparator(r){this._separator=r}static get separator(){return this._separator||"&"}static createRouterData(r,e){this.setRoutingMap(e);let t=T.registerCtx({route:null,options:null,title:null},r);return window.addEventListener(this.routingEventName,i=>{var s;t.multiPub({route:i.detail.route,options:i.detail.options,title:((s=i.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),tt.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};tt.appMap=Object.create(null);var Pt="idb-store-ready",hi="symbiote-db",fi="symbiote-idb-update_",mi=class{_notifyWhenReady(r=null){window.dispatchEvent(new CustomEvent(Pt,{detail:{dbName:this.name,storeName:this.storeName,event:r}}))}get _updEventName(){return fi+this.name}_getUpdateEvent(r){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:r}})}_notifySubscribers(r){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,r),window.dispatchEvent(this._getUpdateEvent(r))}constructor(r,e){this.name=r,this.storeName=e,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(e,{keyPath:"_key"}),this.objStore.transaction.oncomplete=i=>{this._notifyWhenReady(i)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async s=>{s(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(r){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(r);return new Promise((i,s)=>{t.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?i(o.target.result._value):(i(null),console.warn(`IDB: cannot read "${r}"`))},t.onerror=o=>{s(o)}})}write(r,e,t=!1){let i={_key:r,_value:e},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(i);return new Promise((n,a)=>{o.onsuccess=l=>{t||this._notifySubscribers(r),n(l.target.result)},o.onerror=l=>{a(l)}})}delete(r,e=!1){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(r);return new Promise((s,o)=>{i.onsuccess=n=>{e||this._notifySubscribers(r),s(n)},i.onerror=n=>{o(n)}})}getAll(){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,i)=>{e.onsuccess=s=>{let o=s.target.result;t(o.map(n=>n._value))},e.onerror=s=>{i(s)}})}subscribe(r,e){this._subscriptionsMap[r]||(this._subscriptionsMap[r]=new Set);let t=this._subscriptionsMap[r];return t.add(e),{remove:()=>{t.delete(e),t.size||delete this._subscriptionsMap[r]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,$t.clear(this.name)}},$t=class{static get readyEventName(){return Pt}static open(r=hi,e="store"){let t=r+"/"+e;return this._reg[t]||(this._reg[t]=new mi(r,e)),this._reg[t]}static clear(r){window.indexedDB.deleteDatabase(r);for(let e in this._reg)e.split("/")[0]===r&&delete this._reg[e]}};rt($t,"_reg",Object.create(null));var W=r=>r?r.split(",").map(e=>e.trim()).filter(Boolean):[],q=r=>r.join(",");var Nt=r=>{if(typeof r!="string"||!r)return"";let e=r.trim();return e.startsWith("-/")?e=e.slice(2):e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,e.length-1)),e},Oe=(...r)=>r.filter(e=>typeof e=="string"&&!!e).map(e=>Nt(e)).join("/-/"),F=(...r)=>{let e=Oe(...r);return e?`-/${e}/`:""};function Ie(r){let e=new URL(r),t=e.pathname+e.search+e.hash,i=t.lastIndexOf("http"),s=t.lastIndexOf("/"),o="";return i>=0?o=t.slice(i):s>=0&&(o=t.slice(s+1)),o}function Re(r){let e=new URL(r),{pathname:t}=e,i=t.indexOf("/"),s=t.indexOf("/",i+1);return t.substring(i+1,s)}function ot(r){let e=Dt(r),t=new URL(e),i=t.pathname.indexOf("/-/");return i===-1?"":t.pathname.substring(i).slice(1)}function nt(r){return ot(r).split("/-/").filter(Boolean).map(t=>Nt(t))}function Dt(r){let e=new URL(r),t=Ie(r),i=Ut(t)?Ft(t).pathname:t;return e.pathname=e.pathname.replace(i,""),e.search="",e.hash="",e.toString()}function Ut(r){return r.startsWith("http")}function Ft(r){let e=new URL(r);return{pathname:`${e.origin}${e.pathname??""}`,search:e.search??"",hash:e.hash??""}}var z=(r,e,t)=>{let i=new URL(Dt(r)),s=t??Ie(r),o=e??"";if(i.pathname.startsWith("//")&&(i.pathname=i.pathname.replace("//","/")),s&&Ut(s)){let n=Ft(s);i.pathname=`${i.pathname}${o}${n.pathname||""}`,i.search=n.search,i.hash=n.hash}else i.pathname=`${i.pathname}${o}${s||""}`;return i.toString()},at=(r,e)=>{let t=new URL(r);return t.pathname=`${e}/`,t.toString()};var de=(r,e=",")=>r.trim().split(e).map(t=>t.trim()).filter(t=>t.length>0);var pe=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}),jt=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function gi(r,e){if(typeof e=="number"){let t=e;return pe[r]!==t?`${r}/${t}`:""}if(typeof e=="boolean"){let t=e;return pe[r]!==t?`${r}`:""}if(r==="filter"&&e){let{name:t,amount:i}=e;return pe.filter===i?"":`${r}/${t}/${i}`}if(r==="crop"&&e){let{dimensions:t,coords:i}=e;return`${r}/${t.join("x")}/${i.join(",")}`}return""}function K(r){return Oe(...jt.filter(e=>typeof r[e]<"u"&&r[e]!==null).map(e=>{let t=r[e];return gi(e,t)}).filter(e=>!!e))}var Le=Oe("format/auto","progressive/yes"),j=([r])=>typeof r<"u"?Number(r):void 0,zt=()=>!0,yi=([r,e])=>({name:r,amount:typeof e<"u"?Number(e):100}),bi=([r,e])=>{if(!/\d+x\d+/.test(r)||!/\d+,\d+/.test(e))throw new Error("Crop by aspect ratio, percentage or alignment shortcuts is not supported.");return{dimensions:de(r,"x").map(Number),coords:de(e).map(Number)}},vi=Object.freeze({enhance:j,brightness:j,exposure:j,gamma:j,contrast:j,saturation:j,vibrance:j,warmth:j,filter:yi,mirror:zt,flip:zt,rotate:j,crop:r=>{let[e,t]=r,{dimensions:i,coords:s}=bi([e,t]);return{dimensions:i,coords:s}}});function lt(r){let e={};for(let t of r){let[i,...s]=t.split("/");if(!i||!jt.includes(i))continue;let o=i,n=vi[o];try{let a=n(s);e[o]=a}catch(a){console.warn([`Failed to parse URL operation "${t}". It will be ignored.`,a instanceof Error?`Error message: "${a.message}"`:a,"If you need this functionality, please feel free to open an issue at https://github.com/uploadcare/blocks/issues/new"].join(` `))}}return e}var b=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),I=Object.freeze([b.CROP,b.TUNING,b.FILTERS]),Vt=Object.freeze(["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"]),Bt=Object.freeze(["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"]),Kt=Object.freeze(["rotate","mirror","flip"]),V=pe,M=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}});var ct="https://ucarecdn.com",_i="https://upload.uploadcare.com",Ti="https://social.uploadcare.com",Ei="https://ucarecd.net",wi={pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",externalSourcesEmbedCss:"",store:"auto",cameraMirror:!1,cameraCapture:"",sourceList:"local, url, camera, dropbox, gdrive",topLevelOrigin:"",cloudImageEditorTabs:q(I),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:ct,cdnCnamePrefixed:Ei,baseUrl:_i,socialBaseUrl:Ti,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:10,retryNetworkErrorMaxTimes:3,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,secureUploadsExpireThreshold:600*1e3,secureUploadsSignatureResolver:null,secureDeliveryProxyUrlResolver:null,iconHrefResolver:null,fileValidators:[],collectionValidators:[],validationTimeout:15*1e3,validationConcurrency:100,cameraModes:"photo, video",defaultCameraMode:null,enableAudioRecording:!0,enableVideoRecording:null,maxVideoRecordingDuration:null,mediaRecorderOptions:null,filesViewMode:"list",gridShowFileNames:!1,cloudImageEditorAutoOpen:!1,cloudImageEditorMaskHref:null,testMode:!1,qualityInsights:!0},R=Object.freeze(wi);var ut=Object.freeze({INIT_SOLUTION:"init-solution",CHANGE_CONFIG:"change-config"}),A=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",...ut}),Me=class{_timeoutStore=new Map;_targets=new Set;_debugPrint=null;constructor(e){this._debugPrint=e}bindTarget(e){this._targets.add(e)}unbindTarget(e){this._targets.delete(e)}_dispatch(e,t){for(let i of this._targets)i.dispatchEvent(new CustomEvent(e,{detail:t}));this._debugPrint?.(()=>{let i=t&&typeof t=="object"?{...t}:t;return[`event "${e}"`,i]})}emit(e,t,i={}){let{debounce:s}=i;if(typeof s!="number"&&!s){this._dispatch(e,typeof t=="function"?t():t);return}this._timeoutStore.has(e)&&window.clearTimeout(this._timeoutStore.get(e));let o=typeof s=="number"?s:20,n=window.setTimeout(()=>{this._dispatch(e,typeof t=="function"?t():t),this._timeoutStore.delete(e)},o);this._timeoutStore.set(e,n)}};var Ht=r=>{let e=new Intl.Locale(r),t="ltr",i=e.getTextInfo?.().direction;return i?t=i:e.textInfo?.direction&&(t=e.textInfo.direction),t};var Gt=(r,e)=>new Intl.PluralRules(r).select(e);var Ci=r=>r;var Xt="plural:";function dt(r,e={},t={}){let{openToken:i="{{",closeToken:s="}}",transform:o=Ci}=t;for(let n in e){let a=e[n],l=a?.toString(),c=typeof l=="string"?o(l):String(l);r=r.replaceAll(i+n+s,c)}return r}function Wt(r){let e=[],t=r.indexOf("{{");for(;t!==-1;){let i=r.indexOf("}}",t);if(i===-1)break;let s=r.substring(t+2,i);if(s.startsWith(Xt)){let o=r.substring(t+2,i).replace(Xt,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));e.push({variable:s,pluralKey:n,countVariable:a})}t=r.indexOf("{{",i)}return e}function S(r,e){let t,i=((...s)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...s),e)});return i.cancel=()=>{t&&clearTimeout(t)},i}var qt="--uploadcare-blocks-window-height",he=class r{static clientsRegistry=new Set;static flush=S(()=>{document.documentElement.style.setProperty(qt,`${window.innerHeight}px`)},100);static registerClient(e){r.clientsRegistry.size===0&&r.attachTracker(),r.clientsRegistry.add(e)}static unregisterClient(e){r.clientsRegistry.delete(e),r.clientsRegistry.size===0&&r.detachTracker()}static attachTracker(){window.addEventListener("resize",r.flush,{passive:!0,capture:!0}),r.flush()}static detachTracker(){window.removeEventListener("resize",r.flush,{capture:!0}),document.documentElement.style.removeProperty(qt)}};var Yt=({element:r,attribute:e,onSuccess:t,onTimeout:i,timeout:s=300})=>{let o=r.getAttribute(e);if(o!==null){t(o);return}let n=new MutationObserver(c=>{let u=c[c.length-1];u&&l(u)});n.observe(r,{attributes:!0,attributeFilter:[e]});let a=window.setTimeout(()=>{n.disconnect(),i()},s),l=c=>{let u=r.getAttribute(e);c.type==="attributes"&&c.attributeName===e&&u!==null&&(window.clearTimeout(a),n.disconnect(),t(u))}};var Gs={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"};var Zt;(function(r){r.Token="token",r.FileInfo="file_info"})(Zt||(Zt={}));var Jt;(function(r){r.Unknown="unknown",r.Waiting="waiting",r.Progress="progress",r.Error="error",r.Success="success"})(Jt||(Jt={}));var Xs=window.WebSocket;var Pe=class{_concurrency=1;_pending=[];_running=0;_resolvers=new Map;_rejectors=new Map;constructor(e){this._concurrency=e}run(){let e=this._concurrency-this._running;for(let t=0;t<e;t++){let i=this._pending.shift();if(!i)return;let s=this._resolvers.get(i),o=this._rejectors.get(i);if(!s||!o)throw new Error("Unexpected behavior: resolver or rejector is undefined");this._running+=1,i().finally(()=>{this._resolvers.delete(i),this._rejectors.delete(i),this._running-=1,this.run()}).then(n=>s(n)).catch(n=>o(n))}}add(e,{autoRun:t}={autoRun:!0}){return new Promise((i,s)=>{this._resolvers.set(e,i),this._rejectors.set(e,s),this._pending.push(e),t&&this.run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(e){this._concurrency=e,this.run()}get concurrency(){return this._concurrency}};var Qt=()=>({});var fe={"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":"{{count}} of {{total}} selected","select-all":"Select all","deselect-all":"Deselect all","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-mobile-video-camera":"Video","src-type-mobile-photo-camera":"Photo","src-type-draw":"Draw","src-type-facebook":"Facebook","src-type-dropbox":"Dropbox","src-type-gdrive":"Google Drive","src-type-ngdrive":"Google Drive","src-type-gphotos":"Google Photos","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\u2019ve chosen {{total}} {{plural:file(total)}}. At least {{min}} {{plural:file(min)}} required.","files-count-limit-error-too-many":"You\u2019ve 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 occurred. 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.","file-item-edit-button":"Edit","file-item-remove-button":"Remove","a11y-editor-tab-filters":"Filters","a11y-editor-tab-tuning":"Tuning","a11y-editor-tab-crop":"Crop","a11y-activity-header-button-close":"Close",flip:"Flip",mirror:"Mirror","a11y-cloud-editor-apply-filter":"Apply {{name}} filter","a11y-cloud-editor-apply-crop":"Apply {{name}} operation","a11y-cloud-editor-apply-tuning":"Apply {{name}} tuning","a11y-cloud-editor-apply-aspect-ratio":"Apply operation {{name}} {{value}}",finished:"Finished",failed:"Failed",uploading:"Uploading",idle:"Idle","a11y-file-item-status":"File {{fileName}} in status {{status}}","waiting-for":"Waiting for {{source}}","queued-uploading":"Queued for upload","queued-validation":"Queued for validation",validation:"Validating","crop-to-shape":"Crop to {{value}}",custom:"Freeform","freeform-crop":"Freeform crop"};var $e=new Map,pt=new Map,er=(r,e)=>{$e.has(r)&&console.log(`Locale ${r} is already defined. Overwriting...`),$e.set(r,{...fe,...e})},xi=(r,e)=>{pt.set(r,e)},Ai=(r,e)=>{typeof e=="function"?xi(r,e):er(r,e)},tr=async r=>{if(!$e.has(r)){if(!pt.has(r))throw new Error(`Locale ${r} is not defined`);let t=await pt.get(r)();er(r,t)}return $e.get(r)};Ai("en",fe);var P=r=>`*l10n/${r}`,Si="en",Ne=class{_blockInstance=null;_localeName="";_callbacks=new Set;_boundBlocks=new Map;constructor(e){this._blockInstance=e;for(let[t,i]of Object.entries(fe)){let s=this._blockInstance.has(P(t))?!this._blockInstance.$[P(t)]:!0;this._blockInstance.add(P(t),i,s)}setTimeout(()=>{e.subConfigValue("localeName",async t=>{if(!this._blockInstance||!t)return;this._localeName=t;let i=await tr(t);if(t!==Si&&this._localeName!==t)return;let s=this._blockInstance.cfg.localeDefinitionOverride?.[t];for(let[o,n]of Object.entries(i)){let a=s?.[o];this._blockInstance.add(P(o),a??n,!0);for(let l of this._callbacks)l()}}),e.subConfigValue("localeDefinitionOverride",t=>{if(!t)return;let i=t[this._localeName];if(i)for(let[s,o]of Object.entries(i)){this._blockInstance?.add(P(s),o,!0);for(let n of this._callbacks)n()}})})}onLocaleChange(e){let t=S(e,0);return this._callbacks.add(t),()=>{this._callbacks.delete(t)}}bindL10n(e,t,i){e.$[t]=i(),this._boundBlocks.has(e)||this._boundBlocks.set(e,new Map),this._boundBlocks.get(e)?.get(t)?.();let s=this.onLocaleChange(()=>{e.$[t]=i()});this._boundBlocks.get(e)?.set(t,s)}destroyL10nBindings(e){let t=this._boundBlocks.get(e);if(t){for(let i of t.values())i();this._boundBlocks.delete(e)}}destroy(){this._callbacks.clear()}};function rr(r,e){[...r.querySelectorAll("[l10n]")].forEach(t=>{let i=t.getAttribute("l10n");if(!i)return;let s=i.split(";");for(let o of s)o&&ki(t,o,e)})}var ki=(r,e,t)=>{let i="textContent",s=!1;if(e.includes(":")){let a=e.split(":");if(a.length!==2){console.warn(`l10n attribute value should be in format "property:key" or "key". Found: ${e}`);return}let l=a;i=l[0],e=l[1],i.startsWith("@")&&(i=i.slice(1),s=!0)}let o=e;t.has(o)&&t.sub(o,a=>{if(!a)return;t.l10nProcessorSubs.has(o)||t.l10nProcessorSubs.set(o,new Set);let l=t.l10nProcessorSubs.get(o);l?.forEach(d=>{d.remove(),l.delete(d),t.allSubs.delete(d)});let c=P(a).replace("*","");t.nodeCtx.has(c)||t.nodeCtx.add(c,a);let u=t.nodeCtx.sub(c,()=>{r[i]=t.l10n(a)});l?.add(u),t.allSubs.add(u),r.removeAttribute("l10n")});let n=P(e);t.has(n)||t.add(n,""),t.sub(n,()=>{s?r.setAttribute(i,t.l10n(e)):r[i]=t.l10n(e)}),r.removeAttribute("l10n")};var Oi={button:["toolbar"],checkbox:["toolbar"],menuitem:["menu","menubar"],option:["listbox"],tab:["tablist"]};function me(r,e){e.tabIndex=0,e.focus(),r.tabIndex=-1}function ht(r){let e=r.role||r.type||r.tagName;if(!e)return null;let t=Oi[e.toLowerCase()];if(!t)return null;for(let i of t){let s=r.closest(`[role=${i}]`);if(s)return s}}function ft(r,e){return e.role==="toolbar"?Ii(e):e.querySelectorAll(`[role=${r.role}]`)}function Ii(r){return[...r.querySelectorAll("*")].filter(t=>t.role==="button"||t.type==="button"||t.role==="checkbox"||t.type==="checkbox")}function Ri(r){let e=r.getAttribute("aria-orientation");if(e==="vertical")return!1;if(e==="horizontal")return!0;let t=r.role;return t==="menubar"||t==="tablist"||t==="toolbar"}function ir(r){return e=>{let t=!1,i=r?.searchDelayMs||300,s=0,o="";function n(d){let p=ht(d.target);if(!p){a();return}let h=ft(d.target,p),g=Array.from(h).indexOf(d.target),E="ArrowDown",w="ArrowUp";if(Ri(p)&&(e.document.dir==="rtl"?(E="ArrowLeft",w="ArrowRight"):(E="ArrowRight",w="ArrowLeft")),d.key===E)d.preventDefault(),me(d.target,h[g+1]||h[0]);else if(d.key===w)d.preventDefault(),me(d.target,h[g-1]||h[h.length-1]);else if(d.key==="Home")d.preventDefault(),me(d.target,h[0]);else if(d.key==="End")d.preventDefault(),me(d.target,h[h.length-1]);else if(d.key.length===1&&p.role!=="tablist"){let X=Date.now();X-s<=i?o+=d.key.toLowerCase():o=d.key.toLowerCase(),s=X;let Ot=Array.from(h).find(Wr=>Wr.textContent?.trim()?.toLowerCase()?.startsWith(o));Ot&&(d.preventDefault(),me(d.target,Ot))}}function a(){t=!1,e.removeEventListener("keydown",n)}function l(d){let p=ht(d.target);if(p){t||(t=!0,e.addEventListener("keydown",n));let h=ft(d.target,p);for(let g of h)g!==d.target&&g.setAttribute("tabindex",-1)}else t&&a()}function c(d){(!d.relatedTarget||d.relatedTarget===e.document)&&a()}function u(d){let p=ht(d.target);if(p){let h=ft(d.target,p);for(let g of h)g!==d.target&&g.setAttribute("tabindex",-1);d.target.setAttribute("tabindex",0)}}return e.addEventListener("click",u),e.addEventListener("focusin",l),e.addEventListener("focusout",c),()=>{a(),e.removeEventListener("click",u),e.removeEventListener("focusin",l),e.removeEventListener("focusout",c)}}}function sr(){return r=>{let e,t;function i(o){if(o.target.getAttribute("aria-hidden")==="true"){e=o.target,e.setAttribute("aria-hidden","false"),t=e.hidden,t&&(e.hidden=!1);let n=o.target.querySelector('a, button, select, textarea, input:not([type=radio]), [type=radio]:checked, [tabindex]:not([tabindex="-1"])');n&&(n.tabIndex=0)}}function s(o){e&&e.contains(o.target)&&(!o.relatedTarget||!e.contains(o.relatedTarget))&&(o.target.tabIndex=-1,e.setAttribute("aria-hidden","true"),t&&(e.hidden=!0),e=null)}return r.addEventListener("keyuxJump",i),r.addEventListener("focusout",s),()=>{r.removeEventListener("keyuxJump",i),r.removeEventListener("focusout",s)}}}function or(){return r=>{let e=[];function t(l){let c=r.document.activeElement;c&&c!==r.document.body&&e.push(new WeakRef(c)),l.focus({focusVisible:!0})}function i(){let l=e.pop();if(!l){r.document.activeElement.blur();return}let c=l.deref();c&&c.isConnected?c.focus():i()}let s=0,o;function n(l){clearInterval(o);let c=l.getAttribute("aria-controls");o=setInterval(()=>{if(s++>50){clearInterval(o);return}let u=r.document.getElementById(c);if(u){let d=u.querySelector('a, button, select, textarea, input:not([type=radio]), [type=radio]:checked, [tabindex]:not([tabindex="-1"])');d&&(clearInterval(o),u.dispatchEvent(new r.CustomEvent("keyuxJump",{bubbles:!0})),t(d))}},50)}function a(l){l.target.getAttribute("aria-controls")&&l.key==="Enter"&&n(l.target),l.key==="Escape"&&i()}return r.addEventListener("keydown",a),()=>{r.removeEventListener("keydown",a)}}}function nr(r){let e,t=r.split(" "),i;function s(a){a.key==="Enter"&&(a.target.tagName==="BUTTON"||a.target.tagName==="A")&&(o(),a.target.classList.add(...t),e=a.target,i=a.target)}function o(){e&&e.classList.remove(...t),i=null}function n(a){a.clientX===0&&a.clientY===0&&i!==a.target&&(o(),a.target.classList.add(...t),e=a.target)}return a=>(a.addEventListener("click",n),a.addEventListener("keydown",s),a.addEventListener("keyup",o),()=>{a.removeEventListener("click",n),a.removeEventListener("keydown",s),a.removeEventListener("keyup",o)})}function ar(r,e){let t=e.map(i=>i(r));return()=>{t.forEach(i=>i())}}var mt=class{_listeners=new Map;_scope=[];addEventListener(e,t){let i=s=>{let o=s.target;o instanceof Node&&this._scope.some(n=>n===o||n.contains(o))&&t(s)};this._listeners.set(t,i),window.addEventListener(e,i)}removeEventListener(e,t){let i=this._listeners.get(t);i&&window.removeEventListener(e,i),this._listeners.delete(t)}get CustomEvent(){return window.CustomEvent}get document(){return window.document}get navigator(){return window.navigator}registerScope(e){this._scope.push(e)}destroy(){this._scope=[];for(let e of this._listeners.values())window.removeEventListener("keydown",e),window.removeEventListener("keyup",e);this._listeners.clear()}},De=class{_destroyKeyUX;_scopedWindow;constructor(){this._scopedWindow=new mt,this._destroyKeyUX=ar(this._scopedWindow,[ir(),nr("is-pressed"),or(),sr()])}registerBlock(e){this._scopedWindow.registerScope(e)}destroy(){this._destroyKeyUX?.(),this._scopedWindow.destroy()}};var ee=Object.freeze({ADD:"modal:add",DELETE:"modal:delete",OPEN:"modal:open",CLOSE:"modal:close",CLOSE_ALL:"modal:closeAll",DESTROY:"modal:destroy"}),Ue=class{_modals=new Map;_activeModals=new Set;_subscribers=new Map;_block;constructor(e){this._block=e}_debugPrint(...e){this._block.debugPrint("[modal-manager]",...e)}registerModal(e,t){this._modals.set(e,t),this._notify(ee.ADD,{id:e,modal:t})}deleteModal(e){if(!this._modals.has(e))return!1;let t=this._modals.get(e);return this._modals.delete(e),this._activeModals.delete(e),this._notify(ee.DELETE,{id:e,modal:t}),!0}open(e){if(!this._modals.has(e))return this._debugPrint(`Modal with ID "${e}" not found`),!1;let t=this._modals.get(e);return this._activeModals.add(e),this._notify(ee.OPEN,{modal:t,id:e}),!0}close(e){if(!this._modals.has(e)||!this._activeModals.has(e))return this._debugPrint(`Modal with ID "${e}" not found or not active`),!1;let t=this._modals.get(e);return this._activeModals.delete(e),this._notify(ee.CLOSE,{id:e,modal:t}),!0}toggle(e){return this._modals.has(e)?this._activeModals.has(e)?this.close(e):this.open(e):(this._debugPrint(`Modal with ID "${e}" not found`),!1)}get hasActiveModals(){return this._activeModals.size>0}back(){if(this._activeModals.size===0)return this._debugPrint("No active modals to go back from"),!1;let e=Array.from(this._activeModals).pop();return e?this.close(e):!1}closeAll(){let e=this._activeModals.size;return this._activeModals.clear(),this._notify(ee.CLOSE_ALL,{}),e}subscribe(e,t){return this._subscribers.has(e)||this._subscribers.set(e,new Set),this._subscribers.get(e)?.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){this._subscribers.has(e)&&this._subscribers.get(e)?.delete(t)}_notify(e,t){if(this._subscribers.has(e))for(let i of this._subscribers.get(e)??new Set)try{i(t)}catch(s){this._block.telemetryManager.sendEventError(s,"modal subscriber"),this._debugPrint("Error in modal subscriber:",s)}}destroy(){this.closeAll(),this._modals.clear(),this._subscribers.clear(),this._notify(ee.DESTROY,{})}};function Li(r){return r.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`).replace(/__/g,"_")}function yt(r){return Array.isArray(r)?r.map(e=>typeof e=="object"&&e!==null?yt(e):e):typeof r!="object"||r===null?r:Object.fromEntries(Object.entries(r).map(([e,t])=>{let i=Li(e);return typeof t=="object"&&t!==null?[i,yt(t)]:[i,t]}))}function Mi(r){return{ok:!0,value:r}}function gt(r){return{ok:!1,error:r}}var Pi="https://tlm.uploadcare.com/api/",bt=class{constructor(e=Pi){this.baseUrl=e}async base(e,t={}){let i=`${this.baseUrl}${e}`;try{let s=await fetch(i,t);if(!s.ok)return gt(new Error(`Got non-200 response from "${i}". Status: ${s.status.toString()}`));try{let o=await s.json();return Mi(o)}catch(o){return gt(new Error(`Error parsing JSON from "${i}". Error: ${o}`))}}catch(s){return gt(new Error(`Error fetching data from "${i}". Error: ${s}`))}}async post(e,t,i={}){return await this.base(e,{...i,method:"POST",body:JSON.stringify(yt(t)),headers:{"Content-Type":"application/json",...i.headers||{}}})}async get(e,t={}){return await this.base(e,{method:"GET",...t})}},$i=async(r,e)=>({success:!0,data:e}),Fe=class extends bt{constructor(){super()}async sendEvent(e,t){let i=await $i(void 0,e);if(!i.success)throw console.error("TelemetryAPIService: events: body is invalid",i.error),new Error("TelemetryAPIService: events: body is invalid");return this.post("v1/events",e,t)}};var lr="1.24.0";var ze="blocks",je=lr;var Ve=class{_sessionId=crypto.randomUUID();_telemetryInstance;_block;_config=structuredClone(R);_initialized=!1;_lastPayload=null;_queue;constructor(e){this._block=e,this._telemetryInstance=new Fe,this._queue=new Pe(10);for(let t of Object.keys(this._config))this._block.subConfigValue(t,i=>{this._initialized&&this._config[t]!==i&&this._block.emit(A.CHANGE_CONFIG,void 0),this._setConfig(t,i)})}_init(e){e===A.INIT_SOLUTION&&!this._initialized&&(this._initialized=!0)}_setConfig(e,t){this._config[e]!==t&&(this._config[e]=t)}_formattingPayload(e){let t=e.payload?{...e.payload}:{};t.activity&&(t.activity=void 0);let i={...e};return(e.eventType===A.INIT_SOLUTION||e.eventType===A.CHANGE_CONFIG)&&(i.config=this._config),{...i,appVersion:je,appName:ze,sessionId:this._sessionId,component:this._solution,activity:this._activity,projectPubkey:this._config.pubkey,userAgent:navigator.userAgent,eventType:i.eventType??"",eventTimestamp:this._timestamp,payload:{...t}}}_excludedEvents(e){return!!(e&&[A.CHANGE,A.COMMON_UPLOAD_PROGRESS,A.FILE_ADDED,A.FILE_REMOVED,A.FILE_UPLOAD_START,A.FILE_UPLOAD_PROGRESS,A.FILE_UPLOAD_SUCCESS,A.FILE_UPLOAD_FAILED,A.FILE_URL_CHANGED,A.GROUP_CREATED].includes(e))}sendEvent(e){let t=this._formattingPayload({eventType:e.eventType,payload:e.payload,config:e.config});this._init(e.eventType),!(this._excludedEvents(e.eventType)||this._lastPayload&&this._checkObj(this._lastPayload,t))&&this._queue.add(async()=>{this._lastPayload=t,await this._telemetryInstance.sendEvent(t)})}sendEventError(e,t="unknown"){this.sendEvent({payload:{metadata:{event:"error",text:`Error in ${t}`,error:e.message}}})}sendEventCloudImageEditor(e,t,i={}){this.sendEvent({payload:{metadata:{tabId:t,node:e.currentTarget?.tagName,event:e.type,...i}}})}_checkObj(e,t){if(JSON.stringify(e)===JSON.stringify(t))return!0;if(typeof e!="object"||typeof t!="object"||e==null||t==null)return!1;let i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(let o of i)if(!Object.hasOwn(t,o)||!this._checkObj(e[o],t[o]))return!1;return!0}get _timestamp(){return Date.now()}get _solution(){if(!this._block.has("*solution"))return null;let e=this._block.$["*solution"];return e?e.toLowerCase():null}get _activity(){return this._block.has("*currentActivity")?this._block.$["*currentActivity"]??null:null}};var k=r=>`*cfg/${r}`;function cr(r,e){let t=r.querySelectorAll("[data-testid]");if(t.length===0)return;let i=new WeakMap;for(let s of t){let o=s.getAttribute("data-testid");o&&i.set(s,o)}e.subConfigValue("testMode",s=>{if(!s){for(let n of t)n.removeAttribute("data-testid");return}let o=e.testId;for(let n of t){let a=i.get(n);a&&n.setAttri