UNPKG

@uploadcare/file-uploader

Version:

Building blocks for Uploadcare products integration

29 lines (28 loc) 29.3 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 nt=e=>{if(typeof e!="string"||!e)return"";let t=e.trim();return t.startsWith("-/")?t=t.slice(2):t.startsWith("/")&&(t=t.slice(1)),t.endsWith("/")&&(t=t.slice(0,t.length-1)),t},ot=(...e)=>e.filter(t=>typeof t=="string"&&!!t).map(t=>nt(t)).join("/-/"),F=(...e)=>{let t=ot(...e);return t?`-/${t}/`:""};function X(e){let t=new URL(e),s=t.pathname+t.search+t.hash,i=s.lastIndexOf("http"),r=s.lastIndexOf("/"),n="";return i>=0?n=s.slice(i):r>=0&&(n=s.slice(r+1)),n}function at(e){let t=new URL(e),s=X(e),i=K(s)?z(s).pathname:s;return t.pathname=t.pathname.replace(i,""),t.search="",t.hash="",t.toString()}function K(e){return e.startsWith("http")}function z(e){let t=new URL(e);return{pathname:`${t.origin}${t.pathname??""}`,search:t.search??"",hash:t.hash??""}}var g=(e,t,s)=>{let i=new URL(at(e)),r=s??X(e),n=t??"";if(i.pathname.startsWith("//")&&(i.pathname=i.pathname.replace("//","/")),r&&K(r)){let o=z(r);i.pathname=`${i.pathname}${n}${o.pathname||""}`,i.search=o.search,i.hash=o.hash}else i.pathname=`${i.pathname}${n}${r||""}`;return i.toString()},I=(e,t)=>{let s=new URL(e);return s.pathname=`${t}/`,s.toString()};var W=(e,t=",")=>e.trim().split(t).map(s=>s.trim()).filter(s=>s.length>0);var lt=e=>e;function q(e,t={},s={}){let{openToken:i="{{",closeToken:r="}}",transform:n=lt}=s;for(let o in t){let l=t[o],u=l?.toString(),f=typeof u=="string"?n(u):String(u);e=e.replaceAll(i+o+r,f)}return e}var H=e=>[...new Set(e)];var b="--uc-img-",D="unresolved";var N=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),j=3e3,k=5e3,L=Object.freeze({PREVIEW:"PREVIEW",MAIN:"MAIN"});var ct=Object.defineProperty,ut=(e,t,s)=>t in e?ct(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,M=(e,t,s)=>(ut(e,typeof t!="symbol"?t+"":t,s),s);function ht(e){let t=s=>{var i;for(let r in s)((i=s[r])==null?void 0:i.constructor)===Object&&(s[r]=t(s[r]));return{...s}};return t(e)}var h=class{constructor(e){e.constructor===Object?this.store=ht(e):(this._storeIsProxy=!0,this.store=e),this.callbackMap=Object.create(null)}static warn(e,t){console.warn(`Symbiote Data: cannot ${e}. Prop name: `+t)}read(e){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(h.warn("read",e),null):this.store[e]}has(e){return this._storeIsProxy?this.store[e]!==void 0:this.store.hasOwnProperty(e)}add(e,t,s=!1){!s&&Object.keys(this.store).includes(e)||(this.store[e]=t,this.notify(e))}pub(e,t){if(!this._storeIsProxy&&!this.store.hasOwnProperty(e)){h.warn("publish",e);return}this.store[e]=t,this.notify(e)}multiPub(e){for(let t in e)this.pub(t,e[t])}notify(e){this.callbackMap[e]&&this.callbackMap[e].forEach(t=>{t(this.store[e])})}sub(e,t,s=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(h.warn("subscribe",e),null):(this.callbackMap[e]||(this.callbackMap[e]=new Set),this.callbackMap[e].add(t),s&&t(this.store[e]),{remove:()=>{this.callbackMap[e].delete(t),this.callbackMap[e].size||delete this.callbackMap[e]},callback:t})}static registerCtx(e,t=Symbol()){let s=h.globalStore.get(t);return s?console.warn('State: context UID "'+t+'" already in use'):(s=new h(e),h.globalStore.set(t,s)),s}static deleteCtx(e){h.globalStore.delete(e)}static getCtx(e,t=!0){return h.globalStore.get(e)||(t&&console.warn('State: wrong context UID - "'+e+'"'),null)}};h.globalStore=new Map;var a=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"}),Y="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",dt=Y.length-1,pt=class{static generate(e="XXXXXXXXX-XXX"){let t="";for(let s=0;s<e.length;s++)t+=e[s]==="-"?e[s]:Y.charAt(Math.random()*dt);return t}};function J(e,t,s){let i=!0,r,n=t.split(".");return n.forEach((o,l)=>{l<n.length-1?e=e[o]:r=o}),e?e[r]=s:i=!1,i}function _t(e){return e.split("-").map((t,s)=>t&&s?t[0].toUpperCase()+t.slice(1):t).join("").split("_").map((t,s)=>t&&s?t.toUpperCase():t).join("")}function mt(e,t){[...e.querySelectorAll(`[${a.REPEAT_ATTR}]`)].forEach(s=>{let i=s.getAttribute(a.REPEAT_ITEM_TAG_ATTR),r;if(i&&(r=window.customElements.get(i)),!r){r=class extends t.BaseComponent{constructor(){super(),i||(this.style.display="contents")}};let o=s.innerHTML;r.template=o,r.reg(i)}for(;s.firstChild;)s.firstChild.remove();let n=s.getAttribute(a.REPEAT_ATTR);t.sub(n,o=>{if(!o){for(;s.firstChild;)s.firstChild.remove();return}let l=[...s.children],u,f=d=>{d.forEach((c,x)=>{if(l[x])if(l[x].set$)setTimeout(()=>{l[x].set$(c)});else for(let T in c)l[x][T]=c[T];else{u||(u=new DocumentFragment);let T=new r;Object.assign(T.init$,c),u.appendChild(T)}}),u&&s.appendChild(u);let p=l.slice(d.length,l.length);for(let c of p)c.remove()};if(o.constructor===Array)f(o);else if(o.constructor===Object){let d=[];for(let p in o){let c=o[p];Object.defineProperty(c,"_KEY_",{value:p,enumerable:!0}),d.push(c)}f(d)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),s.removeAttribute(a.REPEAT_ATTR),s.removeAttribute(a.REPEAT_ITEM_TAG_ATTR)})}var V="__default__";function ft(e,t){if(t.shadowRoot)return;let s=[...e.querySelectorAll("slot")];if(!s.length)return;let i={};s.forEach(r=>{let n=r.getAttribute("name")||V;i[n]={slot:r,fr:document.createDocumentFragment()}}),t.initChildren.forEach(r=>{var n;let o=V;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=i[o])==null||n.fr.appendChild(r)}),Object.values(i).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 gt(e,t){[...e.querySelectorAll(`[${a.EL_REF_ATTR}]`)].forEach(s=>{let i=s.getAttribute(a.EL_REF_ATTR);t.ref[i]=s,s.removeAttribute(a.EL_REF_ATTR)})}function bt(e,t){[...e.querySelectorAll(`[${a.BIND_ATTR}]`)].forEach(s=>{let r=s.getAttribute(a.BIND_ATTR).split(";");[...s.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=_t(n.name.replace("-",""));r.push(o+":"+n.value),s.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(d=>d.trim()),l=o[0],u;l.indexOf(a.ATTR_BIND_PRFX)===0&&(u=!0,l=l.replace(a.ATTR_BIND_PRFX,""));let f=o[1].split(",").map(d=>d.trim());for(let d of f){let p;d.startsWith("!!")?(p="double",d=d.replace("!!","")):d.startsWith("!")&&(p="single",d=d.replace("!","")),t.sub(d,c=>{p==="double"?c=!!c:p==="single"&&(c=!c),u?c?.constructor===Boolean?c?s.setAttribute(l,""):s.removeAttribute(l):s.setAttribute(l,c):J(s,l,c)||(s[a.SET_LATER_KEY]||(s[a.SET_LATER_KEY]=Object.create(null)),s[a.SET_LATER_KEY][l]=c)})}}),s.removeAttribute(a.BIND_ATTR)})}var C="{{",E="}}",yt="skip-text";function wt(e){let t,s=[],i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(yt))&&r.textContent.includes(C)&&r.textContent.includes(E)&&1}});for(;t=i.nextNode();)s.push(t);return s}var Tt=function(e,t){wt(e).forEach(i=>{let r=[],n;for(;i.textContent.includes(E);)i.textContent.startsWith(C)?(n=i.textContent.indexOf(E)+E.length,i.splitText(n),r.push(i)):(n=i.textContent.indexOf(C),i.splitText(n)),i=i.nextSibling;r.forEach(o=>{let l=o.textContent.replace(C,"").replace(E,"");o.textContent="",t.sub(l,u=>{o.textContent=u})})})},Et=[mt,ft,gt,bt,Tt],A="'",w='"',vt=/\\([0-9a-fA-F]{1,6} ?)/g;function xt(e){return(e[0]===w||e[0]===A)&&(e[e.length-1]===w||e[e.length-1]===A)}function Ct(e){return(e[0]===w||e[0]===A)&&(e=e.slice(1)),(e[e.length-1]===w||e[e.length-1]===A)&&(e=e.slice(0,-1)),e}function At(e){let t="",s="";for(var i=0;i<e.length;i++){let r=e[i+1];e[i]==="\\"&&r==='"'?(t+='\\"',i++):e[i]==='"'&&s!=="\\"?t+='\\"':t+=e[i],s=e[i]}return t}function St(e){let t=e;xt(e)&&(t=Ct(t),t=t.replace(vt,(s,i)=>String.fromCodePoint(parseInt(i.trim(),16))),t=t.replaceAll(`\\ `,"\\n"),t=At(t),t=w+t+w);try{return JSON.parse(t)}catch{throw new Error(`Failed to parse CSS property value: ${t}. Original input: ${e}`)}}var G=0,y=null,_=null,m=class extends HTMLElement{constructor(){super(),M(this,"updateCssData",()=>{var e;this.dropCssDataCache(),(e=this.__boundCssProps)==null||e.forEach(t=>{let s=this.getCssData(this.__extractCssName(t),!0);s!==null&&this.$[t]!==s&&(this.$[t]=s)})}),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 m}initCallback(){}__initCallback(){var e;this.__initialized||(this.__initialized=!0,(e=this.initCallback)==null||e.call(this))}render(e,t=this.renderShadow){let s;if((t||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(a.USE_TPL);if(r){let n=this.getRootNode(),o=n?.querySelector(r)||document.querySelector(r);o?e=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(e||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),e?.constructor===DocumentFragment)s=e;else if(e?.constructor===String){let r=document.createElement("template");r.innerHTML=e,s=r.content.cloneNode(!0)}else this.constructor.__tpl&&(s=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(s,this)}let i=()=>{s&&(t&&this.shadowRoot.appendChild(s)||this.appendChild(s)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){t=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=i,this.shadowRoot.prepend(r)}else i()}addTemplateProcessor(e){this.tplProcessors.add(e)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=pt.generate(),this.style.setProperty(a.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(a.CSS_CTX_PROP,!0)}get ctxName(){var e;let t=((e=this.getAttribute(a.CTX_NAME_ATTR))==null?void 0:e.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=t,t}get localCtx(){return this.__localCtx||(this.__localCtx=h.registerCtx({},this)),this.__localCtx}get nodeCtx(){return h.getCtx(this.ctxName,!1)||h.registerCtx({},this.ctxName)}static __parseProp(e,t){let s,i;if(e.startsWith(a.EXT_DATA_CTX_PRFX))s=t.nodeCtx,i=e.replace(a.EXT_DATA_CTX_PRFX,"");else if(e.includes(a.NAMED_DATA_CTX_SPLTR)){let r=e.split(a.NAMED_DATA_CTX_SPLTR);s=h.getCtx(r[0]),i=r[1]}else s=t.localCtx,i=e;return{ctx:s,name:i}}sub(e,t,s=!0){let i=n=>{this.isConnected&&t(n)},r=m.__parseProp(e,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,i,s)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,i,s))})}notify(e){let t=m.__parseProp(e,this);t.ctx.notify(t.name)}has(e){let t=m.__parseProp(e,this);return t.ctx.has(t.name)}add(e,t,s=!1){let i=m.__parseProp(e,this);i.ctx.add(i.name,t,s)}add$(e,t=!1){for(let s in e)this.add(s,e[s],t)}get $(){if(!this.__stateProxy){let e=Object.create(null);this.__stateProxy=new Proxy(e,{set:(t,s,i)=>{let r=m.__parseProp(s,this);return r.ctx.pub(r.name,i),!0},get:(t,s)=>{let i=m.__parseProp(s,this);return i.ctx.read(i.name)}})}return this.__stateProxy}set$(e,t=!1){for(let s in e){let i=e[s];t||![String,Number,Boolean].includes(i?.constructor)?this.$[s]=i:this.$[s]!==i&&(this.$[s]=i)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(a.CTX_OWNER_ATTR)&&this.getAttribute(a.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let e=this.constructor.__attrDesc;if(e)for(let t of Object.values(e))Object.keys(this.init$).includes(t)||(this.init$[t]="");for(let t in this.init$)if(t.startsWith(a.EXT_DATA_CTX_PRFX))this.nodeCtx.add(t.replace(a.EXT_DATA_CTX_PRFX,""),this.init$[t],this.__ctxOwner);else if(t.includes(a.NAMED_DATA_CTX_SPLTR)){let s=t.split(a.NAMED_DATA_CTX_SPLTR),i=s[0].trim(),r=s[1].trim();if(i&&r){let n=h.getCtx(i,!1);n||(n=h.registerCtx({},i)),n.add(r,this.init$[t])}}else this.localCtx.add(t,this.init$[t]);for(let t in this.cssInit$)this.bindCssData(t,this.cssInit$[t]);this.__dataCtxInitialized=!0}connectedCallback(){var e;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let t=(e=this.getAttribute(a.CTX_NAME_ATTR))==null?void 0:e.trim();if(t&&this.style.setProperty(a.CSS_CTX_PROP,`'${t}'`),this.__initDataCtx(),this[a.SET_LATER_KEY]){for(let s in this[a.SET_LATER_KEY])J(this,s,this[a.SET_LATER_KEY][s]);delete this[a.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let s of Et)this.addTemplateProcessor(s);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let s=this.getRootNode();if(!s)return;if(s?.querySelector(`link[${a.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(a.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},s.nodeType===Node.DOCUMENT_NODE?s.head.appendChild(r):s.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 e of this.allSubs)e.remove(),this.allSubs.delete(e);for(let e of this.tplProcessors)this.tplProcessors.delete(e);_?.delete(this.updateCssData),_?.size||(y?.disconnect(),y=null,_=null)},100)))}static reg(e,t=!1){e||(G++,e=`${a.AUTO_TAG_PRFX}-${G}`),this.__tag=e;let s=window.customElements.get(e);if(s){!t&&s!==this&&console.warn([`Element with tag name "${e}" 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(e,t?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(e){this.observedAttributes=Object.keys(e),this.__attrDesc=e}attributeChangedCallback(e,t,s){var i;if(t===s)return;let r=(i=this.constructor.__attrDesc)==null?void 0:i[e];r?this.__dataCtxInitialized?this.$[r]=s:this.init$[r]=s:this[e]=s}getCssData(e,t=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(e)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let s=this.__computedStyle.getPropertyValue(e).trim();try{this.__cssDataCache[e]=St(s)}catch{!t&&console.warn(`CSS Data error: ${e}`),this.__cssDataCache[e]=null}}return this.__cssDataCache[e]}__extractCssName(e){return e.split("--").map((t,s)=>s===0?"":t).join("--")}__initStyleAttrObserver(){_||(_=new Set),_.add(this.updateCssData),y||(y=new MutationObserver(e=>{e[0].type==="attributes"&&_.forEach(t=>{t()})}),y.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(e,t=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(e);let s=this.getCssData(this.__extractCssName(e),!0);s===null&&(s=t),this.add(e,s),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(e,t,s){let i="__"+e;this[i]=this[e],Object.defineProperty(this,e,{set:r=>{this[i]=r,s?window.setTimeout(()=>{t?.(r)}):t?.(r)},get:()=>this[i]}),this[e]=this[i]}static set shadowStyles(e){let t=new Blob([e],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(t)}static set rootStyles(e){if(!this.__rootStylesLink){let t=new Blob([e],{type:"text/css"}),s=URL.createObjectURL(t),i=document.createElement("link");i.href=s,i.rel="stylesheet",this.__rootStylesLink=i}}},B=m;M(B,"template");var U=class{static _print(e){console.warn(e)}static setDefaultTitle(e){this.defaultTitle=e}static setRoutingMap(e){Object.assign(this.appMap,e);for(let t in this.appMap)!this.defaultRoute&&this.appMap[t].default===!0?this.defaultRoute=t:!this.errorRoute&&this.appMap[t].error===!0&&(this.errorRoute=t)}static set routingEventName(e){this.__routingEventName=e}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let e={route:null,options:{}};return window.location.search.split(this.separator).forEach(s=>{if(s.includes("?"))e.route=s.replace("?","");else if(s.includes("=")){let i=s.split("=");e.options[i[0]]=decodeURI(i[1])}else e.options[s]=!0}),e}static notify(){let e=this.readAddressBar(),t=this.appMap[e.route];if(t&&t.title&&(document.title=t.title),e.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!t&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!t&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!t){this._print(`Route "${e.route}" not found...`);return}let s=new CustomEvent(U.routingEventName,{detail:{route:e.route,options:Object.assign(t||{},e.options)}});window.dispatchEvent(s)}static reflect(e,t={}){let s=this.appMap[e];if(!s){this._print("Wrong route: "+e);return}let i="?"+e;for(let n in t)t[n]===!0?i+=this.separator+n:i+=this.separator+n+`=${t[n]}`;let r=s.title||this.defaultTitle||"";window.history.pushState(null,r,i),document.title=r}static applyRoute(e,t={}){this.reflect(e,t),this.notify()}static setSeparator(e){this._separator=e}static get separator(){return this._separator||"&"}static createRouterData(e,t){this.setRoutingMap(t);let s=h.registerCtx({route:null,options:null,title:null},e);return window.addEventListener(this.routingEventName,i=>{var r;s.multiPub({route:i.detail.route,options:i.detail.options,title:((r=i.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),U.notify(),this.initPopstateListener(),s}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};U.appMap=Object.create(null);var Q="idb-store-ready",Pt="symbiote-db",$t="symbiote-idb-update_",Rt=class{_notifyWhenReady(e=null){window.dispatchEvent(new CustomEvent(Q,{detail:{dbName:this.name,storeName:this.storeName,event:e}}))}get _updEventName(){return $t+this.name}_getUpdateEvent(e){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:e}})}_notifySubscribers(e){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,e),window.dispatchEvent(this._getUpdateEvent(e))}constructor(e,t){this.name=e,this.storeName=t,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=s=>{this.db=s.target.result,this.objStore=this.db.createObjectStore(t,{keyPath:"_key"}),this.objStore.transaction.oncomplete=i=>{this._notifyWhenReady(i)}},this.request.onsuccess=s=>{this.db=s.target.result,this._notifyWhenReady(s)},this.request.onerror=s=>{console.error(s)},this._subscriptionsMap={},this._updateHandler=s=>{s.key===this.name&&this._subscriptionsMap[s.newValue]&&this._subscriptionsMap[s.newValue].forEach(async r=>{r(await this.read(s.newValue))})},this._localUpdateHandler=s=>{this._updateHandler(s.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(e){let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(e);return new Promise((i,r)=>{s.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?i(n.target.result._value):(i(null),console.warn(`IDB: cannot read "${e}"`))},s.onerror=n=>{r(n)}})}write(e,t,s=!1){let i={_key:e,_value:t},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(i);return new Promise((o,l)=>{n.onsuccess=u=>{s||this._notifySubscribers(e),o(u.target.result)},n.onerror=u=>{l(u)}})}delete(e,t=!1){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);return new Promise((r,n)=>{i.onsuccess=o=>{t||this._notifySubscribers(e),r(o)},i.onerror=o=>{n(o)}})}getAll(){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((s,i)=>{t.onsuccess=r=>{let n=r.target.result;s(n.map(o=>o._value))},t.onerror=r=>{i(r)}})}subscribe(e,t){this._subscriptionsMap[e]||(this._subscriptionsMap[e]=new Set);let s=this._subscriptionsMap[e];return s.add(t),{remove:()=>{s.delete(t),s.size||delete this._subscriptionsMap[e]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Z.clear(this.name)}},Z=class{static get readyEventName(){return Q}static open(e=Pt,t="store"){let s=e+"/"+t;return this._reg[s]||(this._reg[s]=new Rt(e,t)),this._reg[s]}static clear(e){window.indexedDB.deleteDatabase(e);for(let t in this._reg)t.split("/")[0]===e&&delete this._reg[t]}};M(Z,"_reg",Object.create(null));var tt="1.24.1";var et="blocks",st=tt;var It="https://ucarecdn.com",v=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:It},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{},"cdn-operations":{},progressive:{},quality:{},"is-background-for":{},"is-preview-blur":{default:1}});var it=Object.create(null);for(let e in v)it[b+e]=v[e]?.default||"";var S=class extends B{cssInit$=it;$$(t){return this.$[b+t]}set$$(t){for(let s in t)this.$[b+s]=t[s]}sub$$(t,s){this.sub(b+t,i=>{i===null||i===""||s(i)})}analyticsParams(){return`-/@clib/${et}/${st}/uc-img/`}initAttributes(t){[...this.attributes].forEach(s=>{v[s.name]||t.setAttribute(s.name,s.value)})}initIntersection(t,s){let i={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(r=>{r.forEach(n=>{n.isIntersecting&&(s(),this._isnObserver.unobserve(t))})},i),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null),h.deleteCtx(this)}static get observedAttributes(){return Object.keys(v)}attributeChangedCallback(t,s,i){window.setTimeout(()=>{this.$[b+t]=i})}};var rt=e=>Object.entries(e).filter(([t,s])=>s!==void 0&&s!=="").map(([t,s])=>t==="cdn-operations"||t==="analytics"?s:`${t}/${s}`);var R=class extends S{_img=new Image;_imgPreview=new Image;_fmtAbs(t){return!t.includes("//")&&!N&&(t=new URL(t,document.baseURI).href),t}_validateSize(t){if(t?.trim()!==""){let s=t.match(/\d+/)[0],i=t.match(/[a-zA-Z]+/)[0],r=parseInt(s,10);if(Number(r)>k&&this.hasFormatJPG)return k+i;if(Number(r)>j&&!this.hasFormatJPG)return j+i}return t}_getCdnModifiers(t,s){let i={format:this.$$("format"),quality:this.$$("quality"),resize:this._validateSize(t),blur:s,"cdn-operations":this.$$("cdn-operations"),analytics:this.analyticsParams()};return F(...rt(i))}_getUrlBase(t="",s=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(N&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let i=this._getCdnModifiers(t,s);if(this.$$("src").startsWith(this.$$("cdn-cname")))return g(this.$$("src"),i);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(g(I(this.$$("cdn-cname"),this.$$("uuid")),i));if(this.$$("uuid"))return this._proxyUrl(g(I(this.$$("cdn-cname"),this.$$("uuid")),i));if(this.$$("proxy-cname"))return this._proxyUrl(g(this.$$("proxy-cname"),i,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(g(`https://${this.$$("pubkey")}.ucr.io/`,i,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?q(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:i=>window.encodeURIComponent(i)}):t}_getElSize(t,s=1,i=!0){let r=t.getBoundingClientRect(),n=s*Math.round(r.width),o=i?"":s*Math.round(r.height);return n||o?`${n||""}x${o||""}`:null}_setupEventProxy(t){let s=r=>{r.stopPropagation();let n=new Event(r.type,r);this.dispatchEvent(n)},i=["load","error"];for(let r of i)t.addEventListener(r,s)}get img(){return this.hasPreviewImage||(this._setupConfigForImage({elNode:this._img}),this.appendChild(this._img)),this._img}get currentImg(){return this.hasPreviewImage?{type:L.PREVIEW,img:this._imgPreview}:{type:L.MAIN,img:this.img}}get hasPreviewImage(){return this.$$("is-preview-blur")}get bgSelector(){return this.$$("is-background-for")}get breakpoints(){if(this.$$("breakpoints")){let t=W(this.$$("breakpoints"));return H(t.map(s=>parseInt(s,10)))}else return null}get hasFormatJPG(){return this.$$("format").toLowerCase()==="jpeg"}renderBg(t){let s=new Set;s.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&s.add(`url("${this._getUrlBase(this._getElSize(t,2))}") ${2}x`),this.$$("ultra-res-support")&&s.add(`url("${this._getUrlBase(this._getElSize(t,3))}") ${3}x`);let i=`image-set(${[...s].join(", ")})`;t.style.setProperty("background-image",i),t.style.setProperty("background-image","-webkit-"+i)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(s=>{t.add(this._getUrlBase(s+"x")+` ${this._validateSize(s+"w")}`),this.$$("hi-res-support")&&t.add(this._getUrlBase(s*2+"x")+` ${this._validateSize(s*2+"w")}`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(s*3+"x")+` ${this._validateSize(s*3+"w")}`)}):(t.add(this._getUrlBase(this._getElSize(this.currentImg.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.currentImg.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.currentImg.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}get srcUrlPreview(){return this._getUrlBase("100x","100")}renderBackground(){[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)})}_appendURL({elNode:t,src:s,srcset:i}){s&&(t.src=s),i&&(t.srcset=i)}_setupConfigForImage({elNode:t}){this._setupEventProxy(t),this.initAttributes(t)}loaderImage({src:t,srcset:s,elNode:i}){return new Promise((r,n)=>{this._setupConfigForImage({elNode:i}),i.setAttribute(D,""),i.addEventListener("load",()=>{i.removeAttribute(D),r(i)}),i.addEventListener("error",()=>{n(!1)}),this._appendURL({elNode:i,src:t,srcset:s})})}async renderImage(){if(this.$$("intersection")){this.hasPreviewImage&&(this._setupConfigForImage({elNode:this._imgPreview}),this.appendChild(this._imgPreview)),this.initIntersection(this.currentImg.img,async()=>{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 this._imgPreview?.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 this._imgPreview?.remove(),this.appendChild(this._img)}catch{this.hasPreviewImage&&await this._imgPreview?.remove(),this.appendChild(this._img)}}init(){this.bgSelector?this.renderBackground():this.renderImage()}};var O=class extends R{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",t=>{!this.$$("is-background-for")&&!this.$$("is-preview-blur")&&(this.img.loading=t?"lazy":"eager")})}};O.reg("uc-img");export{O as Img};