@uploadcare/blocks
Version:
Building blocks for Uploadcare products integration
26 lines • 70.2 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 st=Object.defineProperty;var ot=(r,t,e)=>t in r?st(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var _=(r,t,e)=>(ot(r,typeof t!="symbol"?t+"":t,e),e);var nt=Object.defineProperty,lt=(r,t,e)=>t in r?nt(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,be=(r,t,e)=>(lt(r,typeof t!="symbol"?t+"":t,e),e);function at(r){let t=e=>{var i;for(let s in e)((i=e[s])==null?void 0:i.constructor)===Object&&(e[s]=t(e[s]));return{...e}};return t(r)}var b=class{constructor(r){r.constructor===Object?this.store=at(r):(this._storeIsProxy=!0,this.store=r),this.callbackMap=Object.create(null)}static warn(r,t){console.warn(`Symbiote Data: cannot ${r}. Prop name: `+t)}read(r){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(b.warn("read",r),null):this.store[r]}has(r){return this._storeIsProxy?this.store[r]!==void 0:this.store.hasOwnProperty(r)}add(r,t,e=!1){!e&&Object.keys(this.store).includes(r)||(this.store[r]=t,this.notify(r))}pub(r,t){if(!this._storeIsProxy&&!this.store.hasOwnProperty(r)){b.warn("publish",r);return}this.store[r]=t,this.notify(r)}multiPub(r){for(let t in r)this.pub(t,r[t])}notify(r){this.callbackMap[r]&&this.callbackMap[r].forEach(t=>{t(this.store[r])})}sub(r,t,e=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(b.warn("subscribe",r),null):(this.callbackMap[r]||(this.callbackMap[r]=new Set),this.callbackMap[r].add(t),e&&t(this.store[r]),{remove:()=>{this.callbackMap[r].delete(t),this.callbackMap[r].size||delete this.callbackMap[r]},callback:t})}static registerCtx(r,t=Symbol()){let e=b.globalStore.get(t);return e?console.warn('State: context UID "'+t+'" already in use'):(e=new b(r),b.globalStore.set(t,e)),e}static deleteCtx(r){b.globalStore.delete(r)}static getCtx(r,t=!0){return b.globalStore.get(r)||(t&&console.warn('State: wrong context UID - "'+r+'"'),null)}};b.globalStore=new Map;var p=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"}),Re="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",ht=Re.length-1,ct=class{static generate(r="XXXXXXXXX-XXX"){let t="";for(let e=0;e<r.length;e++)t+=r[e]==="-"?r[e]:Re.charAt(Math.random()*ht);return t}};function Ie(r,t,e){let i=!0,s,o=t.split(".");return o.forEach((n,l)=>{l<o.length-1?r=r[n]:s=n}),r?r[s]=e:i=!1,i}function dt(r){return r.split("-").map((t,e)=>t&&e?t[0].toUpperCase()+t.slice(1):t).join("").split("_").map((t,e)=>t&&e?t.toUpperCase():t).join("")}function ut(r,t){[...r.querySelectorAll(`[${p.REPEAT_ATTR}]`)].forEach(e=>{let i=e.getAttribute(p.REPEAT_ITEM_TAG_ATTR),s;if(i&&(s=window.customElements.get(i)),!s){s=class extends t.BaseComponent{constructor(){super(),i||(this.style.display="contents")}};let n=e.innerHTML;s.template=n,s.reg(i)}for(;e.firstChild;)e.firstChild.remove();let o=e.getAttribute(p.REPEAT_ATTR);t.sub(o,n=>{if(!n){for(;e.firstChild;)e.firstChild.remove();return}let l=[...e.children],a,h=c=>{c.forEach((u,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(u)});else for(let v in u)l[m][v]=u[v];else{a||(a=new DocumentFragment);let v=new s;Object.assign(v.init$,u),a.appendChild(v)}}),a&&e.appendChild(a);let d=l.slice(c.length,l.length);for(let u of d)u.remove()};if(n.constructor===Array)h(n);else if(n.constructor===Object){let c=[];for(let d in n){let u=n[d];Object.defineProperty(u,"_KEY_",{value:d,enumerable:!0}),c.push(u)}h(c)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),e.removeAttribute(p.REPEAT_ATTR),e.removeAttribute(p.REPEAT_ITEM_TAG_ATTR)})}function pt(r,t){if(t.shadowRoot)return;let e=[...r.querySelectorAll("slot")];if(t.initChildren.length&&e.length){let i={};e.forEach(s=>{let o=s.getAttribute("name");o?i[o]={slot:s,fr:document.createDocumentFragment()}:i.__default__={slot:s,fr:document.createDocumentFragment()}}),t.initChildren.forEach(s=>{var o;let n=(o=s.getAttribute)==null?void 0:o.call(s,"slot");n?(s.removeAttribute("slot"),i[n].fr.appendChild(s)):i.__default__&&i.__default__.fr.appendChild(s)}),Object.values(i).forEach(s=>{s.slot.parentNode.insertBefore(s.fr,s.slot),s.slot.remove()})}}function ft(r,t){[...r.querySelectorAll(`[${p.EL_REF_ATTR}]`)].forEach(e=>{let i=e.getAttribute(p.EL_REF_ATTR);t.ref[i]=e,e.removeAttribute(p.EL_REF_ATTR)})}function mt(r,t){[...r.querySelectorAll(`[${p.BIND_ATTR}]`)].forEach(e=>{let s=e.getAttribute(p.BIND_ATTR).split(";");[...e.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=dt(o.name.replace("-",""));s.push(n+":"+o.value),e.removeAttribute(o.name)}}),s.forEach(o=>{if(!o)return;let n=o.split(":").map(c=>c.trim()),l=n[0],a;l.indexOf(p.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(p.ATTR_BIND_PRFX,""));let h=n[1].split(",").map(c=>c.trim());for(let c of h){let d;c.startsWith("!!")?(d="double",c=c.replace("!!","")):c.startsWith("!")&&(d="single",c=c.replace("!","")),t.sub(c,u=>{d==="double"?u=!!u:d==="single"&&(u=!u),a?(u==null?void 0:u.constructor)===Boolean?u?e.setAttribute(l,""):e.removeAttribute(l):e.setAttribute(l,u):Ie(e,l,u)||(e[p.SET_LATER_KEY]||(e[p.SET_LATER_KEY]=Object.create(null)),e[p.SET_LATER_KEY][l]=u)})}}),e.removeAttribute(p.BIND_ATTR)})}var Q="{{",j="}}",_t="skip-text";function gt(r){let t,e=[],i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,{acceptNode:s=>{var o;return!((o=s.parentElement)!=null&&o.hasAttribute(_t))&&s.textContent.includes(Q)&&s.textContent.includes(j)&&1}});for(;t=i.nextNode();)e.push(t);return e}var bt=function(r,t){gt(r).forEach(i=>{let s=[],o;for(;i.textContent.includes(j);)i.textContent.startsWith(Q)?(o=i.textContent.indexOf(j)+j.length,i.splitText(o),s.push(i)):(o=i.textContent.indexOf(Q),i.splitText(o)),i=i.nextSibling;s.forEach(n=>{let l=n.textContent.replace(Q,"").replace(j,"");n.textContent="",t.sub(l,a=>{n.textContent=a})})})},vt=[ut,pt,ft,mt,bt],Se="'",$e='"',wt=/\\([0-9a-fA-F]{1,6} ?)/g,yt=/^'|'$/g;function xt(r){return r.startsWith(Se)&&r.endsWith(Se)||r.startsWith($e)&&r.endsWith($e)}function Tt(r){let t=r;return xt(r)&&(t=t.replace(yt,'"'),t=t.replace(wt,(e,i)=>String.fromCodePoint(parseInt(i.trim(),16)))),t}var Ae=0,F=null,A=null,k=class extends HTMLElement{constructor(){super(),be(this,"updateCssData",()=>{var r;this.dropCssDataCache(),(r=this.__boundCssProps)==null||r.forEach(t=>{let e=this.getCssData(this.__extractCssName(t),!0);e!==null&&this.$[t]!==e&&(this.$[t]=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 k}initCallback(){}__initCallback(){var r;this.__initialized||(this.__initialized=!0,(r=this.initCallback)==null||r.call(this))}render(r,t=this.renderShadow){let e;if((t||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(p.USE_TPL);if(s){let o=this.getRootNode(),n=(o==null?void 0: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==null?void 0:r.constructor)===DocumentFragment)e=r;else if((r==null?void 0:r.constructor)===String){let s=document.createElement("template");s.innerHTML=r,e=s.content.cloneNode(!0)}else this.constructor.__tpl&&(e=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(e,this)}let i=()=>{e&&(t&&this.shadowRoot.appendChild(e)||this.appendChild(e)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){t=!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=ct.generate(),this.style.setProperty(p.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(p.CSS_CTX_PROP,!0)}get ctxName(){var r;let t=((r=this.getAttribute(p.CTX_NAME_ATTR))==null?void 0:r.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=t,t}get localCtx(){return this.__localCtx||(this.__localCtx=b.registerCtx({},this)),this.__localCtx}get nodeCtx(){return b.getCtx(this.ctxName,!1)||b.registerCtx({},this.ctxName)}static __parseProp(r,t){let e,i;if(r.startsWith(p.EXT_DATA_CTX_PRFX))e=t.nodeCtx,i=r.replace(p.EXT_DATA_CTX_PRFX,"");else if(r.includes(p.NAMED_DATA_CTX_SPLTR)){let s=r.split(p.NAMED_DATA_CTX_SPLTR);e=b.getCtx(s[0]),i=s[1]}else e=t.localCtx,i=r;return{ctx:e,name:i}}sub(r,t,e=!0){let i=o=>{!this.isConnected||t(o)},s=k.__parseProp(r,this);s.ctx.has(r)?this.allSubs.add(s.ctx.sub(s.name,i,e)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,i,e))})}notify(r){let t=k.__parseProp(r,this);t.ctx.notify(t.name)}has(r){let t=k.__parseProp(r,this);return t.ctx.has(t.name)}add(r,t,e=!1){let i=k.__parseProp(r,this);i.ctx.add(i.name,t,e)}add$(r,t=!1){for(let e in r)this.add(e,r[e],t)}get $(){if(!this.__stateProxy){let r=Object.create(null);this.__stateProxy=new Proxy(r,{set:(t,e,i)=>{let s=k.__parseProp(e,this);return s.ctx.pub(s.name,i),!0},get:(t,e)=>{let i=k.__parseProp(e,this);return i.ctx.read(i.name)}})}return this.__stateProxy}set$(r,t=!1){for(let e in r){let i=r[e];t||![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(p.CTX_OWNER_ATTR)&&this.getAttribute(p.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let r=this.constructor.__attrDesc;if(r)for(let t of Object.values(r))Object.keys(this.init$).includes(t)||(this.init$[t]="");for(let t in this.init$)if(t.startsWith(p.EXT_DATA_CTX_PRFX))this.nodeCtx.add(t.replace(p.EXT_DATA_CTX_PRFX,""),this.init$[t],this.__ctxOwner);else if(t.includes(p.NAMED_DATA_CTX_SPLTR)){let e=t.split(p.NAMED_DATA_CTX_SPLTR),i=e[0].trim(),s=e[1].trim();if(i&&s){let o=b.getCtx(i,!1);o||(o=b.registerCtx({},i)),o.add(s,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 r;if(!!this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let t=(r=this.getAttribute(p.CTX_NAME_ATTR))==null?void 0:r.trim();if(t&&this.style.setProperty(p.CSS_CTX_PROP,`'${t}'`),this.__initDataCtx(),this[p.SET_LATER_KEY]){for(let e in this[p.SET_LATER_KEY])Ie(this,e,this[p.SET_LATER_KEY][e]);delete this[p.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let e of vt)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[${p.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(p.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},e.nodeType===Node.DOCUMENT_NODE?e.head.appendChild(s):e.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);A==null||A.delete(this.updateCssData),A!=null&&A.size||(F==null||F.disconnect(),F=null,A=null)},100)))}static reg(r,t=!1){if(r||(Ae++,r=`${p.AUTO_TAG_PRFX}-${Ae}`),this.__tag=r,window.customElements.get(r)){console.warn(`${r} - is already in "customElements" registry`);return}window.customElements.define(r,t?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,t,e){var i;if(t===e)return;let s=(i=this.constructor.__attrDesc)==null?void 0:i[r];s?this.__dataCtxInitialized?this.$[s]=e:this.init$[s]=e:this[r]=e}getCssData(r,t=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(r)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let e=this.__computedStyle.getPropertyValue(r).trim();e=Tt(e);try{this.__cssDataCache[r]=JSON.parse(e)}catch{!t&&console.warn(`CSS Data error: ${r}`),this.__cssDataCache[r]=null}}return this.__cssDataCache[r]}__extractCssName(r){return r.split("--").map((t,e)=>e===0?"":t).join("--")}__initStyleAttrObserver(){A||(A=new Set),A.add(this.updateCssData),F||(F=new MutationObserver(r=>{r[0].type==="attributes"&&A.forEach(t=>{t()})}),F.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(r,t=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(r);let e=this.getCssData(this.__extractCssName(r),!0);e===null&&(e=t),this.add(r,e),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(r,t,e){let i="__"+r;this[i]=this[r],Object.defineProperty(this,r,{set:s=>{this[i]=s,e?window.setTimeout(()=>{t==null||t(s)}):t==null||t(s)},get:()=>this[i]}),this[r]=this[i]}static set shadowStyles(r){let t=new Blob([r],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(t)}static set rootStyles(r){if(!this.__rootStylesLink){let t=new Blob([r],{type:"text/css"}),e=URL.createObjectURL(t),i=document.createElement("link");i.href=e,i.rel="stylesheet",this.__rootStylesLink=i}}},ve=k;be(ve,"template");var ge=class{static _print(r){console.warn(r)}static setDefaultTitle(r){this.defaultTitle=r}static setRoutingMap(r){Object.assign(this.appMap,r);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(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(e=>{if(e.includes("?"))r.route=e.replace("?","");else if(e.includes("=")){let i=e.split("=");r.options[i[0]]=decodeURI(i[1])}else r.options[e]=!0}),r}static notify(){let r=this.readAddressBar(),t=this.appMap[r.route];if(t&&t.title&&(document.title=t.title),r.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 "${r.route}" not found...`);return}let e=new CustomEvent(ge.routingEventName,{detail:{route:r.route,options:Object.assign(t||{},r.options)}});window.dispatchEvent(e)}static reflect(r,t={}){let e=this.appMap[r];if(!e){this._print("Wrong route: "+r);return}let i="?"+r;for(let o in t)t[o]===!0?i+=this.separator+o:i+=this.separator+o+`=${t[o]}`;let s=e.title||this.defaultTitle||"";window.history.pushState(null,s,i),document.title=s}static applyRoute(r,t={}){this.reflect(r,t),this.notify()}static setSeparator(r){this._separator=r}static get separator(){return this._separator||"&"}static createRouterData(r,t){this.setRoutingMap(t);let e=b.registerCtx({route:null,options:null,title:null},r);return window.addEventListener(this.routingEventName,i=>{var s;e.multiPub({route:i.detail.route,options:i.detail.options,title:((s=i.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),ge.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}};ge.appMap=Object.create(null);var Pe="idb-store-ready",Ct="symbiote-db",Et="symbiote-idb-update_",St=class{_notifyWhenReady(r=null){window.dispatchEvent(new CustomEvent(Pe,{detail:{dbName:this.name,storeName:this.storeName,event:r}}))}get _updEventName(){return Et+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,t){this.name=r,this.storeName=t,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(t,{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 s=>{s(await this.read(e.newValue))})},this._localUpdateHandler=e=>{this._updateHandler(e.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(r){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(r);return new Promise((i,s)=>{e.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?i(o.target.result._value):(i(null),console.warn(`IDB: cannot read "${r}"`))},e.onerror=o=>{s(o)}})}write(r,t,e=!1){let i={_key:r,_value:t},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(i);return new Promise((n,l)=>{o.onsuccess=a=>{e||this._notifySubscribers(r),n(a.target.result)},o.onerror=a=>{l(a)}})}delete(r,t=!1){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(r);return new Promise((s,o)=>{i.onsuccess=n=>{t||this._notifySubscribers(r),s(n)},i.onerror=n=>{o(n)}})}getAll(){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((e,i)=>{t.onsuccess=s=>{let o=s.target.result;e(o.map(n=>n._value))},t.onerror=s=>{i(s)}})}subscribe(r,t){this._subscriptionsMap[r]||(this._subscriptionsMap[r]=new Set);let e=this._subscriptionsMap[r];return e.add(t),{remove:()=>{e.delete(t),e.size||delete this._subscriptionsMap[r]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,ke.clear(this.name)}},ke=class{static get readyEventName(){return Pe}static open(r=Ct,t="store"){let e=r+"/"+t;return this._reg[e]||(this._reg[e]=new St(r,t)),this._reg[e]}static clear(r){window.indexedDB.deleteDatabase(r);for(let t in this._reg)t.split("/")[0]===r&&delete this._reg[t]}};be(ke,"_reg",Object.create(null));var $t=r=>r;function we(r,t,e={}){var n;let{openToken:i="{{",closeToken:s="}}",transform:o=$t}=e;for(let l in t){let a=(n=t[l])==null?void 0:n.toString();r=r.replaceAll(i+l+s,typeof a=="string"?o(a):a)}return r}function Oe(r,t){[...r.querySelectorAll("[l10n]")].forEach(e=>{let i=e.getAttribute("l10n"),s="textContent";if(i.includes(":")){let n=i.split(":");s=n[0],i=n[1]}let o="l10n:"+i;t.__l10nKeys.push(o),t.add(o,i),t.sub(o,n=>{e[s]=t.l10n(n)}),e.removeAttribute("l10n")})}var Le=()=>({"*ctxTargetsRegistry":new Map});function Ne(r,t){let e,i=(...s)=>{clearTimeout(e),e=setTimeout(()=>r(...s),t)};return i.cancel=()=>{clearTimeout(e)},i}var At="--uploadcare-blocks-window-height",J="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ye(){return typeof window[J]=="undefined"?!1:!!window[J]}function De(){if(ye())return;let r=()=>{document.documentElement.style.setProperty(At,`${window.innerHeight}px`),window[J]=!0},t=Ne(r,100);return window.addEventListener("resize",t,{passive:!0}),r(),()=>{window[J]=!1,window.removeEventListener("resize",t)}}var Me="lr-",f=class extends ve{constructor(){super();_(this,"allowCustomTemplate",!0);_(this,"ctxInit",Le());_(this,"init$",this.ctxInit);this.activityType=null,this.addTemplateProcessor(Oe),this.__l10nKeys=[]}l10n(e,i={}){let s=this.getCssData("--l10n-"+e,!0)||e;return we(s,i)}applyL10nKey(e,i){let s="l10n:"+e;this.$[s]=i,this.__l10nKeys.push(e)}checkCtxTarget(e){let i=this.$["*ctxTargetsRegistry"];return i==null?void 0:i.has(e)}setForCtxTarget(e,i,s){this.checkCtxTarget(e)&&(this.$[i]=s)}connectedCallback(){if(ye()||(this._destroyInnerHeightTracker=De()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),this.isConnected&&this.__ctxOwner){let e=b.getCtx(this.ctxName,!1);e&&(e.store={...this.ctxInit})}super.connectedCallback()}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._destroyInnerHeightTracker)==null||e.call(this)}initCallback(){let e=this.constructor.is,i=this.$["*ctxTargetsRegistry"],s=i.has(e)?i.get(e)+1:1;i.set(e,s),this.$["*ctxTargetsRegistry"]=i}destroyCallback(){let e=this.constructor.is,i=this.$["*ctxTargetsRegistry"],s=i.has(i)?i.get(e)-1:0;s===0?i.delete(e):i.set(e,s),this.$["*ctxTargetsRegistry"]=i}fileSizeFmt(e,i=2){let s=["B","KB","MB","GB","TB"],o=h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h;if(e===0)return`0 ${o(s[0])}`;let n=1024,l=i<0?0:i,a=Math.floor(Math.log(e)/Math.log(n));return parseFloat((e/n**a).toFixed(l))+" "+o(s[a])}proxyUrl(e){let i=this.getCssData("--cfg-secure-delivery-proxy",!0);return i?we(i,{previewUrl:e},{transform:s=>window.encodeURIComponent(s)}):e}static reg(e){if(!e){super.reg();return}super.reg(e.startsWith(Me)?e:Me+e)}};var Rt=r=>{if(typeof r!="string"||!r)return"";let t=r.trim();return t.startsWith("-/")?t=t.slice(2):t.startsWith("/")&&(t=t.slice(1)),t.endsWith("/")&&(t=t.slice(0,t.length-1)),t},ee=(...r)=>r.filter(t=>typeof t=="string"&&t).map(t=>Rt(t)).join("/-/"),R=(...r)=>{let t=ee(...r);return t?`-/${t}/`:""};function Be(r){let t=new URL(r),e=t.pathname+t.search+t.hash,i=e.lastIndexOf("http"),s=e.lastIndexOf("/"),o="";return i>=0?o=e.slice(i):s>=0&&(o=e.slice(s+1)),o}function It(r){let t=new URL(r),e=Be(r),i=Ue(e)?ze(e).pathname:e;return t.pathname=t.pathname.replace(i,""),t.search="",t.hash="",t.toString()}function Ue(r){return r.startsWith("http")}function ze(r){let t=new URL(r);return{pathname:t.origin+t.pathname||"",search:t.search||"",hash:t.hash||""}}var O=(r,t,e)=>{let i=new URL(It(r));if(e=e||Be(r),i.pathname.startsWith("//")&&(i.pathname=i.pathname.replace("//","/")),Ue(e)){let s=ze(e);i.pathname=i.pathname+(t||"")+(s.pathname||""),i.search=s.search,i.hash=s.hash}else i.pathname=i.pathname+(t||"")+(e||"");return i.toString()},Fe=(r,t)=>{let e=new URL(r);return e.pathname=t+"/",e.toString()};function He(...r){return r.reduce((t,e)=>{if(typeof e=="string")return t[e]=!0,t;for(let i of Object.keys(e))t[i]=e[i];return t},{})}function g(...r){let t=He(...r);return Object.keys(t).reduce((e,i)=>(t[i]&&e.push(i),e),[]).join(" ")}function Xe(r,...t){let e=He(...t);for(let i of Object.keys(e))r.classList.toggle(i,e[i])}function I(r,t){let e,i=(...s)=>{clearTimeout(e),e=setTimeout(()=>r(...s),t)};return i.cancel=()=>{clearTimeout(e)},i}var S="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";function D(r){let t=new Image;return{promise:new Promise((s,o)=>{t.src=r,t.onload=s,t.onerror=o}),image:t,cancel:()=>{t.naturalWidth===0&&(t.src=S)}}}function V(r){let t=[];for(let o of r){let n=D(o);t.push(n)}let e=t.map(o=>o.image);return{promise:Promise.allSettled(t.map(o=>o.promise)),images:e,cancel:()=>{t.forEach(o=>{o.cancel()})}}}var x={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function Pt(r,t){if(typeof t=="number")return x[r]!==t?`${r}/${t}`:"";if(typeof t=="boolean")return t&&x[r]!==t?`${r}`:"";if(r==="filter"){if(!t||x[r]===t.amount)return"";let{name:e,amount:i}=t;return`${r}/${e}/${i}`}if(r==="crop"){if(!t)return"";let{dimensions:e,coords:i}=t;return`${r}/${e.join("x")}/${i.join(",")}`}return""}var kt=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function H(r){return ee(...kt.filter(t=>typeof r[t]!="undefined"&&r[t]!==null).map(t=>{let e=r[t];return Pt(t,e)}).filter(t=>!!t))}var te=ee("format/auto","progressive/yes");function We(r){return{"*originalUrl":null,"*tabId":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:S,fileType:"",showLoader:!1,uuid:null,"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let t=r.querySelectorAll("img");for(let e of t){let i=e.src;e.src=S,e.src=i}r.$["*networkProblems"]=!1},"*on.apply":t=>{if(!t)return;let e=r.$["*originalUrl"],i=R(H(t)),s=O(e,R(i,"preview")),o={originalUrl:e,cdnUrlModifiers:i,cdnUrl:s,transformations:t};r.dispatchEvent(new CustomEvent("apply",{detail:o})),r.remove()},"*on.cancel":()=>{r.remove(),r.dispatchEvent(new CustomEvent("cancel"))}}}var je=`<div class="wrapper wrapper_desktop"><lr-presence-toggle class="network_problems_splash" set="visible: presence.networkProblems;"><div class="network_problems_content"><div class="network_problems_icon"><lr-icon size="20" name="sad"></lr-icon></div><div class="network_problems_text">Network error</div></div><div class="network_problems_footer"><lr-btn-ui theme="primary" text="Retry" set="onclick: *on.retryNetwork"></lr-btn-ui></div></lr-presence-toggle><div class="viewport"><div class="file_type_outer"><div class="file_type">{{fileType}}</div></div><div class="image_container" ref="img-container-el"><img src="${S}" class="image image_visible_from_editor" ref="img-el" /><lr-editor-image-cropper ref="cropper-el"></lr-editor-image-cropper><lr-editor-image-fader ref="fader-el"></lr-editor-image-fader></div><div class="info_pan">{{msg}}</div></div><div class="toolbar"><lr-line-loader-ui set="active: showLoader"></lr-line-loader-ui><div class="toolbar_content toolbar_content__editor"><lr-editor-toolbar></lr-editor-toolbar></div></div></div>`;var w={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},ie=[w.CROP,w.SLIDERS,w.FILTERS],Ve=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],Ke=["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"],Ge=["rotate","mirror","flip"],L={brightness:{zero:x.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:x.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:x.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:x.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:x.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:x.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:x.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:x.enhance,range:[0,100],keypointsNumber:1},filter:{zero:x.filter,range:[0,100],keypointsNumber:1}};function N(r,t,e){let s=window.devicePixelRatio,o=Math.min(Math.ceil(t*s),3e3),n=s>=2?"lightest":"normal";return O(r,R(te,H(e),`quality/${n}`,`stretch/off/-/resize/${o}x`))}var K=class extends f{constructor(){super(...arguments);_(this,"init$",{...this.ctxInit,...We(this)});_(this,"_debouncedShowLoader",I(this._showLoader.bind(this),300));_(this,"cssInit$",{"--cfg-cdn-cname":"https://ucarecdn.com"})}get ctxName(){return this.autoCtxName}_showLoader(e){this.$.showLoader=e}_loadImageFromCdn(){this._debouncedShowLoader(!0);let e=this._imageSrc(),{promise:i,cancel:s}=D(e);i.then(()=>{this.$.src=e}).catch(o=>{this.$["*networkProblems"]=!0,this._debouncedShowLoader(!1),this.$.src=e}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=s}_imageSrc(){let{width:e}=this.ref["img-container-el"].getBoundingClientRect();return this.proxyUrl(N(this.$["*originalUrl"],e,{}))}_waitForSize(){return new Promise((e,i)=>{let s=300,o=Date.now(),n=()=>{if(!this.isConnected){clearInterval(l),i();return}if(Date.now()-o>s){clearInterval(l),i(new Error("[cloud-image-editor] timout waiting for non-zero container size"));return}let{width:a,height:h}=this.getBoundingClientRect();a>0&&h>0&&(clearInterval(l),e())},l=setInterval(n,50);n()})}async initCallback(){this.$["*originalUrl"]=Fe(this.localCtx.read("--cfg-cdn-cname"),this.$.uuid),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.classList.add("editor_ON"),this.sub("*networkProblems",e=>{this.$["presence.networkProblems"]=e,this.$["presence.modalCaption"]=!e}),this.ref["img-el"].addEventListener("load",e=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==S&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",e=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",e=>{let i=this.ref["img-el"];i.src!==e&&(this._imgLoading=!0,i.src=e||S)}),this.sub("*tabId",e=>{this.ref["img-el"].className=g("image",{image_hidden_to_cropper:e===w.CROP,image_hidden_effects:e!==w.CROP})});try{fetch(O(this.$["*originalUrl"],R("json"))).then(e=>e.json()).then(({width:e,height:i})=>{this.$["*imageSize"]={width:e,height:i}}),await this._waitForSize(),this._loadImageFromCdn()}catch(e){e&&console.error("Failed to load image info",e)}}};K.template=je;K.bindAttributes({uuid:"uuid"});var G=33.333333333333336,T=24*2+34;function M(r,t){for(let e in t)r.setAttributeNS(null,e,t[e].toString())}function C(r,t={}){let e=document.createElementNS("http://www.w3.org/2000/svg",r);return M(e,t),e}function Ye(r,t){let{x:e,y:i,width:s,height:o}=r,n=t.includes("w")?0:1,l=t.includes("n")?0:1,a=[-1,1][n],h=[-1,1][l],c=[e+n*s+1.5*a,i+l*o+1.5*h-24*h],d=[e+n*s+1.5*a,i+l*o+1.5*h],u=[e+n*s-24*a+1.5*a,i+l*o+1.5*h];return{d:`M ${c[0]} ${c[1]} L ${d[0]} ${d[1]} L ${u[0]} ${u[1]}`,center:d}}function qe(r,t){let{x:e,y:i,width:s,height:o}=r,n=["n","s"].includes(t)?.5:{w:0,e:1}[t],l=["w","e"].includes(t)?.5:{n:0,s:1}[t],a=[-1,1][n],h=[-1,1][l],c,d;["n","s"].includes(t)?(c=[e+n*s-34/2,i+l*o+1.5*h],d=[e+n*s+34/2,i+l*o+1.5*h]):(c=[e+n*s+1.5*a,i+l*o-34/2],d=[e+n*s+1.5*a,i+l*o+34/2]);let u=`M ${c[0]} ${c[1]} L ${d[0]} ${d[1]}`,m=[d[0]-(d[0]-c[0])/2,d[1]-(d[1]-c[1])/2];return{d:u,center:m}}function Ze(r){return r===""?"move":["e","w"].includes(r)?"ew-resize":["n","s"].includes(r)?"ns-resize":["nw","se"].includes(r)?"nwse-resize":"nesw-resize"}function Qe(r,[t,e]){return{...r,x:r.x+t,y:r.y+e}}function re(r,t){let{x:e}=r,{y:i}=r;return r.x<t.x?e=t.x:r.x+r.width>t.x+t.width&&(e=t.x+t.width-r.width),r.y<t.y?i=t.y:r.y+r.height>t.y+t.height&&(i=t.y+t.height-r.height),{...r,x:e,y:i}}function Je(r,[t,e],i){let{x:s,y:o,width:n,height:l}=r;return i.includes("n")&&(o+=e,l-=e),i.includes("s")&&(l+=e),i.includes("w")&&(s+=t,n-=t),i.includes("e")&&(n+=t),{x:s,y:o,width:n,height:l}}function et(r,t){let e=Math.max(r.x,t.x),i=Math.min(r.x+r.width,t.x+t.width),s=Math.max(r.y,t.y),o=Math.min(r.y+r.height,t.y+t.height);return{x:e,y:s,width:i-e,height:o-s}}function se(r,[t,e],i){let{x:s,y:o,width:n,height:l}=r;if(i.includes("n")){let a=l;l=Math.max(e,l),o=o+a-l}if(i.includes("s")&&(l=Math.max(e,l)),i.includes("w")){let a=n;n=Math.max(t,n),s=s+a-n}return i.includes("e")&&(n=Math.max(t,n)),{x:s,y:o,width:n,height:l}}function tt(r,[t,e]){return r.x<=t&&t<=r.x+r.width&&r.y<=e&&e<=r.y+r.height}var oe=class extends f{constructor(){super();_(this,"init$",{...this.ctxInit,dragging:!1});this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(e){let i=this.$["*imageBox"];if(!i)return;if(e===""&&i.height<=T&&i.width<=T)return!0;let s=i.height<=T&&(e.includes("n")||e.includes("s")),o=i.width<=T&&(e.includes("e")||e.includes("w"));return s||o}_createBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:i,y:s,width:o,height:n}=e,l=this.ref["svg-el"],a=C("mask",{id:"backdrop-mask"}),h=C("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=C("rect",{x:i,y:s,width:o,height:n,fill:"black"});a.appendChild(h),a.appendChild(c);let d=C("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});l.appendChild(d),l.appendChild(a),this._backdropMask=a,this._backdropMaskInner=c}_resizeBackdrop(){!this._backdropMask||(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask.style.display="block"}))}_updateBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:i,y:s,width:o,height:n}=e;M(this._backdropMaskInner,{x:i,y:s,width:o,height:n})}_updateFrame(){let e=this.$["*cropBox"];if(!e)return;for(let s of Object.values(this._frameThumbs)){let{direction:o,pathNode:n,interactionNode:l,groupNode:a}=s,h=o==="",c=o.length===2;if(h){let{x:u,y:m,width:v,height:z}=e,y=[u+v/2,m+z/2];M(l,{r:Math.min(v,z)/3,cx:y[0],cy:y[1]})}else{let{d:u,center:m}=c?Ye(e,o):qe(e,o);M(l,{cx:m[0],cy:m[1]}),M(n,{d:u})}let d=this._shouldThumbBeDisabled(o);a.setAttribute("class",g("thumb",{"thumb--hidden":d,"thumb--visible":!d}))}let i=this._frameGuides;M(i,{x:e.x-1*.5,y:e.y-1*.5,width:e.width+1,height:e.height+1})}_createThumbs(){let e={};for(let i=0;i<3;i++)for(let s=0;s<3;s++){let o=`${["n","","s"][i]}${["w","","e"][s]}`,n=C("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let l=C("circle",{r:24+1.5,fill:"transparent"}),a=C("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(a),n.appendChild(l),e[o]={direction:o,pathNode:a,interactionNode:l,groupNode:n},l.addEventListener("pointerdown",this._handlePointerDown.bind(this,o))}return e}_createGuides(){let e=C("svg"),i=C("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});e.appendChild(i);for(let s=1;s<=2;s++){let o=C("line",{x1:`${G*s}%`,y1:"0%",x2:`${G*s}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});e.appendChild(o)}for(let s=1;s<=2;s++){let o=C("line",{x1:"0%",y1:`${G*s}%`,x2:"100%",y2:`${G*s}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});e.appendChild(o)}return e.classList.add("guides","guides--semi-hidden"),e}_createFrame(){let e=this.ref["svg-el"],i=document.createDocumentFragment(),s=this._createGuides();i.appendChild(s);let o=this._createThumbs();for(let{groupNode:n}of Object.values(o))i.appendChild(n);e.appendChild(i),this._frameThumbs=o,this._frameGuides=s}_handlePointerDown(e,i){let s=this._frameThumbs[e];if(this._shouldThumbBeDisabled(e))return;let o=this.$["*cropBox"],{x:n,y:l}=this.ref["svg-el"].getBoundingClientRect(),a=i.x-n,h=i.y-l;this.$.dragging=!0,this._draggingThumb=s,this._dragStartPoint=[a,h],this._dragStartCrop={...o}}_handlePointerUp_(e){this._updateCursor(),this.$.dragging&&(e.stopPropagation(),e.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(e){if(!this.$.dragging)return;e.stopPropagation(),e.preventDefault();let i=this.ref["svg-el"],{x:s,y:o}=i.getBoundingClientRect(),n=e.x-s,l=e.y-o,a=n-this._dragStartPoint[0],h=l-this._dragStartPoint[1],{direction:c}=this._draggingThumb,d=this.$["*imageBox"],u=this._dragStartCrop;c===""?(u=Qe(u,[a,h]),u=re(u,d)):(u=Je(u,[a,h],c),u=et(u,d));let m=[Math.min(d.width,T),Math.min(d.height,T)];if(u=se(u,m,c),!Object.values(u).every(v=>Number.isFinite(v)&&v>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:u});return}this.$["*cropBox"]=u}_handleSvgPointerMove_(e){let i=Object.values(this._frameThumbs).find(s=>{if(this._shouldThumbBeDisabled(s.direction))return!1;let n=s.groupNode.getBoundingClientRect(),l={x:n.x,y:n.y,width:n.width,height:n.height};return tt(l,[e.x,e.y])});this._hoverThumb=i,this._updateCursor()}_updateCursor(){let e=this._hoverThumb;this.ref["svg-el"].style.cursor=e?Ze(e.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(e){Object.values(this._frameThumbs).map(({groupNode:i})=>i).forEach(i=>{i.setAttribute("class",g("thumb",{"thumb--hidden":!e,"thumb--visible":e}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",e=>{!e||(this._guidesHidden=e.height<=T||e.width<=T,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",e=>{this._frameGuides.setAttribute("class",g({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&e,"guides--semi-hidden":!this._guidesHidden&&!e}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};oe.template='<svg class="svg" ref="svg-el" xmlns="http://www.w3.org/2000/svg"></svg>';var P=class extends f{constructor(){super(...arguments);_(this,"init$",{...this.ctxInit,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",e=>{this._titleEl&&(this._titleEl.style.display=e?"block":"none")}),this.sub("active",e=>{this.className=g({active:e,not_active:!e})}),this.sub("on.click",e=>{this.onclick=e})}};P.template=`<div class="before"></div><lr-icon size="20" set="@name: icon;"></lr-icon><div class="title" ref="title-el">{{title}}</div>`;function Lt(r){let t=r+90;return t=t>=360?0:t,t}function Nt(r,t){return r==="rotate"?Lt(t):["mirror","flip"].includes(r)?!t:null}var X=class extends P{initCallback(){super.initCallback(),this.defineAccessor("operation",t=>{!t||(this._operation=t,this.$.icon=t)}),this.$["on.click"]=t=>{let e=this.$["*cropperEl"].getValue(this._operation),i=Nt(this._operation,e);this.$["*cropperEl"].setValue(this._operation,i)}}};var Y={FILTER:"filter",COLOR_OPERATION:"color_operation"},$="original",ne=class extends f{constructor(){super(...arguments);_(this,"init$",{...this.ctxInit,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":e=>{this.$["*faderEl"].set(e),this.$.value=e}})}setOperation(e,i){this._controlType=e==="filter"?Y.FILTER:Y.COLOR_OPERATION,this._operation=e,this._iconName=e,this._title=e.toUpperCase(),this._filter=i,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===$?void 0:this.$.value,filter:this._filter===$?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:e,zero:i}=L[this._operation],[s,o]=e;this.$.min=s,this.$.max=o,this.$.zero=i;let n=this.$["*editorTransformations"][this._operation];if(this._controlType===Y.FILTER){let l=o;if(n){let{name:a,amount:h}=n;l=a===this._filter?h:o}this.$.value=l,this.$.defaultValue=l}if(this._controlType===Y.COLOR_OPERATION){let l=typeof n!="undefined"?n:i;this.$.value=l,this.$.defaultValue=l}}apply(){let e;this._controlType===Y.FILTER?this._filter===$?e=null:e={name:this._filter,amount:this.$.value}:e=this.$.value;let i={...this.$["*editorTransformations"],[this._operation]:e};this.$["*editorTransformations"]=i}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",e=>{this._originalUrl=e}),this.sub("value",e=>{let i=`${this._filter||this._operation} ${e}`;this.$["*operationTooltip"]=i})}};ne.template=`<lr-slider-ui ref="slider-el" set="disabled: disabled; min: min; max: max; defaultValue: defaultValue; zero: zero; onInput: on.input;" ></lr-slider-ui>`;var U=class extends P{constructor(){super(...arguments);_(this,"init$",{...this.ctxInit,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let e=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),i=window.devicePixelRatio,s=Math.ceil(i*e),o=i>=2?"lightest":"normal",n=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==$?{name:this._filter,amount:n}:void 0,O(this._originalUrl,R(te,H(l),`quality/${o}`,`scale_crop/${s}x${s}/center`))}_observerCallback(e,i){if(e[0].isIntersecting){let o=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"],{promise:l,cancel:a}=D(o);this._cancelPreload=a,l.catch(h=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:h})}).finally(()=>{n.style.backgroundImage=`url(${o})`,setTimeout(()=>{n.style.opacity="1"}),i.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=i=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",i=>{this._operation="filter",this._filter=i,this.$.isOriginal=i===$,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let e=this.$["*originalUrl"];this._originalUrl=e,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",i=>{this.$.active=i&&i===this._filter}),this.sub("isOriginal",i=>{this.$.iconSize=i?40:20}),this.sub("active",i=>{if(this.$.isOriginal)return;let s=this.ref["icon-el"];s.style.opacity=i?"1":"0";let o=this.ref["preview-el"];i?o.style.opacity="0":o.style.backgroundImage&&(o.style.opacity="1")}),this.sub("*networkProblems",i=>{if(!i){let s=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"];o.style.backgroundImage&&(o.style.backgroundImage="none",o.style.backgroundImage=`url(${s})`)}})}destroyCallback(){var e;super.destroyCallback(),(e=this._observer)==null||e.disconnect(),this._cancelPreload&&this._cancelPreload()}};U.template=`<div class="before"></div><div class="preview" ref="preview-el"></div><lr-icon size="40" ref="icon-el" set="@name: icon; @size: iconSize;"></lr-icon>`;var W=class extends P{constructor(){super(...arguments);_(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",e=>{e&&(this._operation=e,this.$.icon=e,this.$.title=this.l10n(e))}),this.sub("*editorTransformations",e=>{if(!this._operation)return;let{zero:i}=L[this._operation],s=e[this._operation],o=typeof s!="undefined"?s!==i:!1;this.$.active=o})}};function it(r,t){let e={};for(let i of t){let s=r[i];(r.hasOwnProperty(i)||s!==void 0)&&(e[i]=s)}return e}var le=window.ResizeObserver;function ae(r,t,e){return Math.min(Math.max(r,t),e)}function q({width:r,height:t},e){let i=e/90%2!==0;return{width:i?t:r,height:i?r:t}}function Mt(r){return r?[({dimensions:e,coords:i})=>[...e,...i].every(s=>Number.isInteger(s)&&Number.isFinite(s)),({dimensions:e,coords:i})=>e.every(s=>s>0)&&i.every(s=>s>=0)].every(e=>e(r)):!0}var he=class extends f{constructor(){super();_(this,"init$",{...this.ctxInit,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}});this._commitDebounced=I(this._commit.bind(this),300),this._handleResizeDebounced=I(this._handleResize.bind(this),10)}_handleResize(){!this.isConnected||(this._initCanvas(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let e=this.$["*editorTransformations"],i=it(e,Object.keys(this.$["*operations"])),s={...this.$["*operations"],...i};this.$["*operations"]=s}_initCanvas(){let e=this.ref["canvas-el"],i=e.getContext("2d"),s=this.offsetWidth,o=this.offsetHeight,n=window.devicePixelRatio;e.style.width=`${s}px`,e.style.height=`${o}px`,e.width=s*n,e.height=o*n,i.scale(n,n),this._canvas=e,this._ctx=i}_alignImage(){if(!this._isActive||!this.$.image)return;let e=this.$.image,i=this.$["*padding"],s=this.$["*operations"],{rotate:o}=s,n={width:this.offsetWidth,height:this.offsetHeight},l=q({width:e.naturalWidth,height:e.naturalHeight},o);if(l.width>n.width-i*2||l.height>n.height-i*2){let a=l.width/l.height,h=n.width/n.height;if(a>h){let c=n.width-i*2,d=c/a,u=0+i,m=i+(n.height-i*2)/2-d/2;this.$["*imageBox"]={x:u,y:m,width:c,height:d}}else{let c=n.height-i*2,d=c*a,u=i+(n.width-i*2)/2-d/2,m=0+i;this.$["*imageBox"]={x:u,y:m,width:d,height:c}}}else{let{width:a,height:h}=l,c=i+(n.width-i*2)/2-a/2,d=i+(n.height-i*2)/2-h/2;this.$["*imageBox"]={x:c,y:d,width:a,height:h}}}_alignCrop(){let e=this.$["*cropBox"],i=this.$["*imageBox"],s=this.$["*operations"],{rotate:o}=s,n=this.$["*editorTransformations"].crop;if(n){let{dimensions:[a,h],coords:[c,d]}=n,{width:u,x:m,y:v}=this.$["*imageBox"],{width:z}=q(this._imageSize,o),y=u/z;e={x:m+c*y,y:v+d*y,width:a*y,height:h*y}}else e={x:i.x,y:i.y,width:i.width,height:i.height};let l=[Math.min(i.width,T),Math.min(i.height,T)];e=se(e,l,"se"),e=re(e,i),this.$["*cropBox"]=e}_drawImage(){let e=this.$.image,i=this.$["*imageBox"],s=this.$["*operations"],{mirror:o,flip:n,rotate:l}=s,a=this._ctx,h=q({width:i.width,height:i.height},l);a.save(),a.translate(i.x+i.width/2,i.y+i.height/2),a.rotate(l*Math.PI*-1/180),a.scale(o?-1:1,n?-1:1),a.drawImage(e,-h.width/2,-h.height/2,h.width,h.height),a.restore()}_draw(){if(!this._isActive||!this.$.image)return;let e=this._canvas;this._ctx.clearRect(0,0,e.width,e.height),this._drawImage()}_animateIn({fromViewer:e}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=g({active_from_viewer:e,active_from_editor:!e,inactive_to_editor:!1})}))}_calculateDimensions(){let e=this.$["*cropBox"],i=this.$["*imageBox"],s=this.$["*operations"],{rotate:o}=s,{width:n,height:l}=i,{width:a,height:h}=q(this._imageSize,o),{width:c,height:d}=e,u=n/a,m=l/h;return[ae(Math.round(c/u),1,a),ae(Math.round(d/m),1,h)]}_calculateCrop(){let e=this.$["*cropBox"],i=this.$["*imageBox"],s=this.$["*operations"],{rotate:o}=s,{width:n,height:l,x:a,y:h}=i,{width:c,height:d}=q(this._imageSize,o),{x:u,y:m}=e,v=n/c,z=l/d,y=this._calculateDimensions(),_e={dimensions:y,coords:[ae(Math.round((u-a)/v),0,c-y[0]),ae(Math.round((m-h)/z),0,d-y[1])]};if(!Mt(_e)){console.error("Cropper is trying to create invalid crop object",{payload:_e});return}if(!(y[0]===c&&y[1]===d))return _e}_commit(){if(!this.isConnected)return;let e=this.$["*operations"],{rotate:i,mirror:s,flip:o}=e,n=this._calculateCrop(),a={...this.$["*editorTransformations"],crop:n,rotate:i,mirror:s,flip:o};this.$["*editorTransformations"]=a}setValue(e,i){console.log(`Apply cropper operation [${e}=${i}]`),this.$["*operations"]={...this.$["*operations"],[e]:i},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(e){return this.$["*operations"][e]}async activate(e,{fromViewer:i}){if(!this._isActive){this._isActive=!0,this._imageSize=e,this.removeEventListener("transitionend",this._reset),this._initCanvas();try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw(),this._animateIn({fromViewer:i})}catch(s){console.error("Failed to activate cropper",{error:s})}}}deactivate(){!this._isActive||(this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=g({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}))}_transitionToCrop(){let e=this._calculateDimensions(),i=Math.min(this.offsetWidth,e[0])/this.$["*cropBox"].width,s=Math.min(this.offsetHeight,e[1])/this.$["*cropBox"].height,o=Math.min(i,s),n=this.$["*cropBox"].x+th