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