diff --git a/abstract/UploaderBlock.js b/abstract/UploaderBlock.js index 26ff97e65..90a370eb2 100644 --- a/abstract/UploaderBlock.js +++ b/abstract/UploaderBlock.js @@ -165,9 +165,9 @@ export class UploaderBlock extends ActivityBlock { /** * @param {File} file - * @param {{ silent?: boolean; fileName?: string; source?: string }} [options] + * @param {{ silent?: boolean; fileName?: string; source?: string; fullPath?: string }} [options] */ - addFileFromObject(file, { silent, fileName, source } = {}) { + addFileFromObject(file, { silent, fileName, source, fullPath } = {}) { this.uploadCollection.add({ file, isImage: fileIsImage(file), @@ -176,6 +176,7 @@ export class UploaderBlock extends ActivityBlock { fileSize: file.size, silentUpload: silent ?? false, source: source ?? UploadSource.API, + fullPath, }); } diff --git a/abstract/uploadEntrySchema.js b/abstract/uploadEntrySchema.js index 30d380e99..62ebc73e8 100644 --- a/abstract/uploadEntrySchema.js +++ b/abstract/uploadEntrySchema.js @@ -122,4 +122,9 @@ export const uploadEntrySchema = Object.freeze({ value: false, nullable: true, }, + fullPath: { + type: String, + value: null, + nullable: true, + }, }); diff --git a/blocks/DropArea/DropArea.js b/blocks/DropArea/DropArea.js index a6e509fa8..eb977ce91 100644 --- a/blocks/DropArea/DropArea.js +++ b/blocks/DropArea/DropArea.js @@ -1,23 +1,28 @@ -import { UploaderBlock } from '../../abstract/UploaderBlock.js'; +// @ts-check + import { ActivityBlock } from '../../abstract/ActivityBlock.js'; -import { DropzoneState, addDropzone } from './addDropzone.js'; -import { Modal } from '../Modal/Modal.js'; +import { UploaderBlock } from '../../abstract/UploaderBlock.js'; import { stringToArray } from '../../utils/stringToArray.js'; -import { UploadSource } from '../utils/UploadSource.js'; import { asBoolean } from '../Config/normalizeConfigValue.js'; +import { UploadSource } from '../utils/UploadSource.js'; +import { DropzoneState, addDropzone } from './addDropzone.js'; export class DropArea extends UploaderBlock { - init$ = { - ...this.init$, - state: DropzoneState.INACTIVE, - withIcon: false, - isClickable: false, - isFullscreen: false, - isEnabled: true, - isVisible: true, - text: this.l10n('drop-files-here'), - 'lr-drop-area/targets': null, - }; + constructor() { + super(); + + this.init$ = { + ...this.init$, + state: DropzoneState.INACTIVE, + withIcon: false, + isClickable: false, + isFullscreen: false, + isEnabled: true, + isVisible: true, + text: this.l10n('drop-files-here'), + 'lr-drop-area/targets': null, + }; + } isActive() { if (!this.$.isEnabled) { @@ -36,6 +41,7 @@ export class DropArea extends UploaderBlock { return hasSize && visible && isInViewport; } + initCallback() { super.initCallback(); @@ -44,46 +50,62 @@ export class DropArea extends UploaderBlock { } this.$['lr-drop-area/targets'].add(this); - this.defineAccessor('disabled', (value) => { - this.set$({ isEnabled: !asBoolean(value) }); - }); - this.defineAccessor('clickable', (value) => { - this.set$({ isClickable: asBoolean(value) }); - }); - this.defineAccessor('with-icon', (value) => { - this.set$({ withIcon: asBoolean(value) }); - }); - this.defineAccessor('fullscreen', (value) => { - this.set$({ isFullscreen: asBoolean(value) }); - }); - - this.defineAccessor('text', (value) => { - if (value) { - this.set$({ text: this.l10n(value) || value }); - } else { - this.set$({ text: this.l10n('drop-files-here') }); + this.defineAccessor( + 'disabled', + /** @param {unknown} value */ (value) => { + this.set$({ isEnabled: !asBoolean(value) }); } - }); + ); + this.defineAccessor( + 'clickable', + /** @param {unknown} value */ (value) => { + this.set$({ isClickable: asBoolean(value) }); + } + ); + this.defineAccessor( + 'with-icon', + /** @param {unknown} value */ (value) => { + this.set$({ withIcon: asBoolean(value) }); + } + ); + this.defineAccessor( + 'fullscreen', + /** @param {unknown} value */ (value) => { + this.set$({ isFullscreen: asBoolean(value) }); + } + ); + + this.defineAccessor( + 'text', + /** @param {unknown} value */ (value) => { + if (typeof value === 'string') { + this.set$({ text: this.l10n(value) || value }); + } else { + this.set$({ text: this.l10n('drop-files-here') }); + } + } + ); /** @private */ this._destroyDropzone = addDropzone({ element: this, shouldIgnore: () => this._shouldIgnore(), + /** @param {DropzoneState} state */ onChange: (state) => { this.$.state = state; }, - /** @param {(File | String)[]} items */ + /** @param {import('./getDropItems.js').DropItem[]} items */ onItems: (items) => { if (!items.length) { return; } - items.forEach((/** @type {File | String} */ item) => { - if (typeof item === 'string') { - this.addFileFromUrl(item, { source: UploadSource.DROP_AREA }); - return; + items.forEach((/** @type {import('./getDropItems.js').DropItem} */ item) => { + if (item.type === 'url') { + this.addFileFromUrl(item.url, { source: UploadSource.DROP_AREA }); + } else if (item.type === 'file') { + this.addFileFromObject(item.file, { source: UploadSource.DROP_AREA, fullPath: item.fullPath }); } - this.addFileFromObject(item, { source: UploadSource.DROP_AREA }); }); if (this.uploadCollection.size) { this.set$({ @@ -98,6 +120,7 @@ export class DropArea extends UploaderBlock { if (contentWrapperEl) { this._destroyContentWrapperDropzone = addDropzone({ element: contentWrapperEl, + /** @param {DropzoneState} state */ onChange: (state) => { const stateText = Object.entries(DropzoneState) .find(([, value]) => value === state)?.[0] @@ -206,9 +229,14 @@ DropArea.template = /* HTML */ ` `; DropArea.bindAttributes({ + // @ts-expect-error TODO: fix types inside symbiote 'with-icon': null, + // @ts-expect-error TODO: fix types inside symbiote clickable: null, + // @ts-expect-error TODO: fix types inside symbiote text: null, + // @ts-expect-error TODO: fix types inside symbiote fullscreen: null, + // @ts-expect-error TODO: fix types inside symbiote disabled: null, }); diff --git a/blocks/DropArea/getDropItems.js b/blocks/DropArea/getDropItems.js index 13bb65280..49fa0c550 100644 --- a/blocks/DropArea/getDropItems.js +++ b/blocks/DropArea/getDropItems.js @@ -1,3 +1,17 @@ +// @ts-check + +/** + * @typedef {| { + * type: 'file'; + * file: File; + * fullPath?: string; + * } + * | { + * type: 'url'; + * url: string; + * }} DropItem + */ + /** * @param {File} file * @returns {Promise} @@ -13,6 +27,7 @@ function checkIsDirectory(file) { reader.onerror = () => { resolve(true); }; + /** @param {Event} e */ let onLoad = (e) => { if (e.type !== 'loadend') { reader.abort(); @@ -29,33 +44,45 @@ function checkIsDirectory(file) { }); } +/** + * @param {FileSystemEntry} webkitEntry + * @param {string} dataTransferItemType + * @returns {Promise} + */ function readEntryContentAsync(webkitEntry, dataTransferItemType) { return new Promise((resolve) => { let reading = 0; - let contents = []; + /** @type {DropItem[]} */ + const dropItems = []; - let readEntry = (entry) => { + /** @param {FileSystemEntry} entry */ + const readEntry = (entry) => { if (!entry) { console.warn('Unexpectedly received empty content entry', { scope: 'drag-and-drop' }); resolve(null); } if (entry.isFile) { reading++; - entry.file((file) => { + /** @type {FileSystemFileEntry} */ (entry).file((file) => { reading--; // webkitGetAsEntry don't provide type for HEIC images at least, so we use type value from dataTransferItem const clonedFile = new File([file], file.name, { type: file.type || dataTransferItemType }); - contents.push(clonedFile); + dropItems.push({ + type: 'file', + file: clonedFile, + fullPath: entry.fullPath, + }); if (reading === 0) { - resolve(contents); + resolve(dropItems); } }); } else if (entry.isDirectory) { - readReaderContent(entry.createReader()); + readReaderContent(/** @type {FileSystemDirectoryEntry} */ (entry).createReader()); } }; + /** @param {FileSystemDirectoryReader} reader */ let readReaderContent = (reader) => { reading++; @@ -66,7 +93,7 @@ function readEntryContentAsync(webkitEntry, dataTransferItemType) { } if (reading === 0) { - resolve(contents); + resolve(dropItems); } }); }; @@ -79,11 +106,12 @@ function readEntryContentAsync(webkitEntry, dataTransferItemType) { * Note: dataTransfer will be destroyed outside of the call stack. So, do not try to process it asynchronous. * * @param {DataTransfer} dataTransfer - * @returns {Promise<(File | String)[]>} + * @returns {Promise} */ export function getDropItems(dataTransfer) { - let files = []; - let promises = []; + /** @type {DropItem[]} */ + const dropItems = []; + const promises = []; for (let i = 0; i < dataTransfer.items.length; i++) { let item = dataTransfer.items[i]; if (!item) { @@ -97,34 +125,43 @@ export function getDropItems(dataTransfer) { ? item.webkitGetAsEntry() : /** @type {any} */ (item).getAsEntry(); promises.push( - readEntryContentAsync(entry, itemType).then((entryContent) => { - files.push(...entryContent); + readEntryContentAsync(entry, itemType).then((items) => { + if (items) { + dropItems.push(...items); + } }) ); continue; } - let file = item.getAsFile(); - promises.push( - checkIsDirectory(file).then((isDirectory) => { - if (isDirectory) { - // we can't get directory files, so we'll skip it - } else { - files.push(file); - } - }) - ); + const file = item.getAsFile(); + file && + promises.push( + checkIsDirectory(file).then((isDirectory) => { + if (isDirectory) { + // we can't get directory files, so we'll skip it + } else { + dropItems.push({ + type: 'file', + file, + }); + } + }) + ); } else if (item.kind === 'string' && item.type.match('^text/uri-list')) { promises.push( new Promise((resolve) => { item.getAsString((value) => { - files.push(value); - resolve(); + dropItems.push({ + type: 'url', + url: value, + }); + resolve(undefined); }); }) ); } } - return Promise.all(promises).then(() => files); + return Promise.all(promises).then(() => dropItems); } diff --git a/web/blocks.iife.min.js b/web/blocks.iife.min.js index 98061dfa4..e5fb93429 100644 --- a/web/blocks.iife.min.js +++ b/web/blocks.iife.min.js @@ -24,4 +24,4 @@ * */ "use strict";var LR=(()=>{var De=Object.defineProperty;var jr=Object.getOwnPropertyDescriptor;var Hr=Object.getOwnPropertyNames;var Wr=Object.prototype.hasOwnProperty;var Xr=(s,i,t)=>i in s?De(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var l=(s,i)=>De(s,"name",{value:i,configurable:!0});var Gr=(s,i)=>{for(var t in i)De(s,t,{get:i[t],enumerable:!0})},qr=(s,i,t,e)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Hr(i))!Wr.call(s,r)&&r!==t&&De(s,r,{get:()=>i[r],enumerable:!(e=jr(i,r))||e.enumerable});return s};var Kr=s=>qr(De({},"__esModule",{value:!0}),s);var u=(s,i,t)=>(Xr(s,typeof i!="symbol"?i+"":i,t),t),Bi=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var z=(s,i,t)=>(Bi(s,i,"read from private field"),t?t.call(s):i.get(s)),Rt=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},Fe=(s,i,t,e)=>(Bi(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var gi=(s,i,t)=>(Bi(s,i,"access private method"),t);var nl={};Gr(nl,{ActivityBlock:()=>_,ActivityHeader:()=>pi,BaseComponent:()=>Pt,Block:()=>y,CameraSource:()=>be,CloudImageEditor:()=>mi,CloudImageEditorActivity:()=>di,CloudImageEditorBlock:()=>rt,Config:()=>de,ConfirmationDialog:()=>ve,Copyright:()=>Re,CropFrame:()=>Te,Data:()=>A,DataOutput:()=>Lt,DropArea:()=>Gt,EditorCropButtonControl:()=>Zt,EditorFilterControl:()=>It,EditorImageCropper:()=>Ae,EditorImageFader:()=>ui,EditorOperationControl:()=>Jt,EditorScroller:()=>$e,EditorSlider:()=>xe,EditorToolbar:()=>Se,ExternalSource:()=>Le,FileItem:()=>nt,FilePreview:()=>Kt,FileUploaderInline:()=>Ne,FileUploaderMinimal:()=>Me,FileUploaderRegular:()=>Pe,Icon:()=>Ht,Img:()=>ii,LineLoaderUi:()=>ke,LrBtnUi:()=>Qt,MessageBox:()=>me,Modal:()=>Vt,PACKAGE_NAME:()=>ns,PACKAGE_VERSION:()=>os,PresenceToggle:()=>Ie,ProgressBar:()=>we,ProgressBarCommon:()=>Ce,Select:()=>Ue,ShadowWrapper:()=>ee,SimpleBtn:()=>Xt,SliderUi:()=>Oe,SourceBtn:()=>qt,SourceList:()=>ri,StartFrom:()=>si,Tabs:()=>te,UploadCtxProvider:()=>li,UploadDetails:()=>ye,UploadList:()=>ge,UploaderBlock:()=>v,UrlSource:()=>_e,Video:()=>Q,connectBlocksFrom:()=>Br,registerBlocks:()=>Fi,shadowed:()=>fi,toKebabCase:()=>ot});var Yr=Object.defineProperty,Zr=l((s,i,t)=>i in s?Yr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,"__defNormalProp"),ji=l((s,i,t)=>(Zr(s,typeof i!="symbol"?i+"":i,t),t),"__publicField");function Jr(s){let i=l(t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}},"clone");return i(s)}l(Jr,"cloneObj");var A=l(class{constructor(s){s.constructor===Object?this.store=Jr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(A.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){A.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(A.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=A.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new A(s),A.globalStore.set(i,t)),t}static deleteCtx(s){A.globalStore.delete(s)}static getCtx(s,i=!0){return A.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}},"Data");A.globalStore=new Map;var w=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"}),_s="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Qr=_s.length-1,Be=l(class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{ai&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}l(tn,"kebabToCamel");function en(s,i){[...s.querySelectorAll(`[${w.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(w.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=l(class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}},"itemClass");let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(w.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let a=[...t.children],c,h=l(d=>{d.forEach((f,g)=>{if(a[g])if(a[g].set$)setTimeout(()=>{a[g].set$(f)});else for(let m in f)a[g][m]=f[m];else{c||(c=new DocumentFragment);let m=new r;Object.assign(m.init$,f),c.appendChild(m)}}),c&&t.appendChild(c);let p=a.slice(d.length,a.length);for(let f of p)f.remove()},"fillItems");if(o.constructor===Array)h(o);else if(o.constructor===Object){let d=[];for(let p in o){let f=o[p];Object.defineProperty(f,"_KEY_",{value:p,enumerable:!0}),d.push(f)}h(d)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(w.REPEAT_ATTR),t.removeAttribute(w.REPEAT_ITEM_TAG_ATTR)})}l(en,"repeatProcessor");var ms="__default__";function sn(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||ms;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=ms;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).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()})}l(sn,"slotProcessor");function rn(s,i){[...s.querySelectorAll(`[${w.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(w.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(w.EL_REF_ATTR)})}l(rn,"refProcessor");function nn(s,i){[...s.querySelectorAll(`[${w.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(w.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=tn(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(d=>d.trim()),a=o[0],c;a.indexOf(w.ATTR_BIND_PRFX)===0&&(c=!0,a=a.replace(w.ATTR_BIND_PRFX,""));let h=o[1].split(",").map(d=>d.trim());for(let d of h){let p;d.startsWith("!!")?(p="double",d=d.replace("!!","")):d.startsWith("!")&&(p="single",d=d.replace("!","")),i.sub(d,f=>{p==="double"?f=!!f:p==="single"&&(f=!f),c?(f==null?void 0:f.constructor)===Boolean?f?t.setAttribute(a,""):t.removeAttribute(a):t.setAttribute(a,f):bs(t,a,f)||(t[w.SET_LATER_KEY]||(t[w.SET_LATER_KEY]=Object.create(null)),t[w.SET_LATER_KEY][a]=f)})}}),t.removeAttribute(w.BIND_ATTR)})}l(nn,"domSetProcessor");var _i="{{",Ve="}}",on="skip-text";function ln(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(on))&&r.textContent.includes(_i)&&r.textContent.includes(Ve)&&1}});for(;i=e.nextNode();)t.push(i);return t}l(ln,"getTextNodesWithTokens");var an=l(function(s,i){ln(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(Ve);)e.textContent.startsWith(_i)?(n=e.textContent.indexOf(Ve)+Ve.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(_i),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let a=o.textContent.replace(_i,"").replace(Ve,"");o.textContent="",i.sub(a,c=>{o.textContent=c})})})},"txtNodesProcessor"),cn=[en,sn,rn,nn,an],bi="'",se='"',hn=/\\([0-9a-fA-F]{1,6} ?)/g;function un(s){return(s[0]===se||s[0]===bi)&&(s[s.length-1]===se||s[s.length-1]===bi)}l(un,"hasLeadingTrailingQuotes");function dn(s){return(s[0]===se||s[0]===bi)&&(s=s.slice(1)),(s[s.length-1]===se||s[s.length-1]===bi)&&(s=s.slice(0,-1)),s}l(dn,"trimQuotes");function pn(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=pn(i),i=se+i+se);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}l(fn,"parseCssPropertyValue");var gs=0,ie=null,_t=null,xt=l(class extends HTMLElement{constructor(){super(),ji(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return xt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(w.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=l(()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()},"addFr");if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Be.generate(),this.style.setProperty(w.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(w.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=A.registerCtx({},this)),this.__localCtx}get nodeCtx(){return A.getCtx(this.ctxName,!1)||A.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(w.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(w.EXT_DATA_CTX_PRFX,"");else if(s.includes(w.NAMED_DATA_CTX_SPLTR)){let r=s.split(w.NAMED_DATA_CTX_SPLTR);t=A.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=l(n=>{this.isConnected&&i(n)},"subCb"),r=xt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=xt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=xt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=xt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=xt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=xt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(w.CTX_OWNER_ATTR)&&this.getAttribute(w.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(w.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(w.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(w.NAMED_DATA_CTX_SPLTR)){let t=i.split(w.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=A.getCtx(e,!1);n||(n=A.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(w.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[w.SET_LATER_KEY]){for(let t in this[w.SET_LATER_KEY])bs(this,t,this[w.SET_LATER_KEY][t]);delete this[w.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of cn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${w.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(w.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);_t==null||_t.delete(this.updateCssData),_t!=null&&_t.size||(ie==null||ie.disconnect(),ie=null,_t=null)},100)))}static reg(s,i=!1){s||(gs++,s=`${w.AUTO_TAG_PRFX}-${gs}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=fn(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){_t||(_t=new Set),_t.add(this.updateCssData),ie||(ie=new MutationObserver(s=>{s[0].type==="attributes"&&_t.forEach(i=>{i()})}),ie.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},"_BaseComponent"),Pt=xt;ji(Pt,"template");var zi=l(class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(zi.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=A.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),zi.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}},"AppRouter");zi.appMap=Object.create(null);function mn(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}l(mn,"applyStyles");function gn(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}l(gn,"applyAttributes");function ze(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&gn(i,s.attributes),s.styles&&mn(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=ze(t);i.appendChild(e)}),i}l(ze,"create");var ys="idb-store-ready",_n="symbiote-db",bn="symbiote-idb-update_",yn=l(class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ys,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return bn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,a)=>{n.onsuccess=c=>{t||this._notifySubscribers(s),o(c.target.result)},n.onerror=c=>{a(c)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,vs.clear(this.name)}},"DbInstance"),vs=l(class{static get readyEventName(){return ys}static open(s=_n,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new yn(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}},"IDB");ji(vs,"_reg",Object.create(null));function k(s,i){let t,e=l((...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)},"debounced");return e.cancel=()=>{clearTimeout(t)},e}l(k,"debounce");var vn="--uploadcare-blocks-window-height",yi="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Hi(){return typeof window[yi]=="undefined"?!1:!!window[yi]}l(Hi,"getIsWindowHeightTracked");function Cs(){if(Hi())return;let s=l(()=>{document.documentElement.style.setProperty(vn,`${window.innerHeight}px`),window[yi]=!0},"callback"),i=k(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[yi]=!1,window.removeEventListener("resize",i)}}l(Cs,"createWindowHeightTracker");var Cn=l(s=>s,"DEFAULT_TRANSFORMER"),Wi="{{",Ts="}}",ws="plural:";function je(s,i,t={}){var o;let{openToken:e=Wi,closeToken:r=Ts,transform:n=Cn}=t;for(let a in i){let c=(o=i[a])==null?void 0:o.toString();s=s.replaceAll(e+a+r,typeof c=="string"?n(c):c)}return s}l(je,"applyTemplateData");function xs(s){let i=[],t=s.indexOf(Wi);for(;t!==-1;){let e=s.indexOf(Ts,t),r=s.substring(t+2,e);if(r.startsWith(ws)){let n=s.substring(t+2,e).replace(ws,""),o=n.substring(0,n.indexOf("(")),a=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:a})}t=s.indexOf(Wi,e)}return i}l(xs,"getPluralObjects");function Es(s){return Object.prototype.toString.call(s)==="[object Object]"}l(Es,"isObject");var wn=/\W|_/g;function Tn(s){return s.split(wn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}l(Tn,"camelizeString");function As(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>Ct(t,{ignoreKeys:i})):s}l(As,"camelizeArrayItems");function Ct(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return As(s,{ignoreKeys:i});if(!Es(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Es(r)?r=Ct(r,{ignoreKeys:i}):Array.isArray(r)&&(r=As(r,{ignoreKeys:i})),t[Tn(e)]=r}return t}l(Ct,"camelizeKeys");var xn=l(s=>new Promise(i=>setTimeout(i,s)),"delay");function Ki({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),a=[n,r].filter(Boolean).join("; ");return`${o} (${a})`}l(Ki,"getUserAgent$1");var En={factor:2,time:100};function An(s,i=En){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l(a=>xn(a!=null?a:n).then(()=>(t+=1,e(r))),"retry")})}return l(e,"runAttempt"),e(s)}l(An,"retrier");var Dt=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Dt.prototype),this.originalProgressEvent=t}};l(Dt,"UploadcareNetworkError");var xi=l((s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},"onCancel"),bt=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,bt.prototype)}};l(bt,"CancelError");var $n=500,Ss=l(({check:s,interval:i=$n,timeout:t,signal:e})=>new Promise((r,n)=>{let o,a;xi(e,()=>{o&&clearTimeout(o),n(new bt("Poll cancelled"))}),t&&(a=setTimeout(()=>{o&&clearTimeout(o),n(new bt("Timed out"))},t));let c=l(()=>{try{Promise.resolve(s(e)).then(h=>{h?(a&&clearTimeout(a),r(h)):o=setTimeout(c,i)}).catch(h=>{a&&clearTimeout(a),n(h)})}catch(h){a&&clearTimeout(a),n(h)}},"tick");o=setTimeout(c,0)}),"poll"),E={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Ei="application/octet-stream",ks="original",Et=l(({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,a)=>{let c=new XMLHttpRequest,h=(s==null?void 0:s.toUpperCase())||"GET",d=!1;c.open(h,i,!0),e&&Object.entries(e).forEach(p=>{let[f,g]=p;typeof g!="undefined"&&!Array.isArray(g)&&c.setRequestHeader(f,g)}),c.responseType="text",xi(r,()=>{d=!0,c.abort(),a(new bt)}),c.onload=()=>{if(c.status!=200)a(new Error(`Error ${c.status}: ${c.statusText}`));else{let p={method:h,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},f=c.getAllResponseHeaders().trim().split(/[\r\n]+/),g={};f.forEach(function(S){let $=S.split(": "),x=$.shift(),T=$.join(": ");x&&typeof x!="undefined"&&(g[x]=T)});let m=c.response,b=c.status;o({request:p,data:m,headers:g,status:b})}},c.onerror=p=>{d||a(new Dt(p))},n&&typeof n=="function"&&(c.upload.onprogress=p=>{p.lengthComputable?n({isComputable:!0,value:p.loaded/p.total}):n({isComputable:!1})}),t?c.send(t):c.send()}),"request");function Sn(s,...i){return s}l(Sn,"identity");var kn=l(({name:s})=>s?[s]:[],"getFileOptions"),In=Sn,On=l(()=>new FormData,"getFormData"),Is=l(s=>!1,"isBuffer"),Ai=l(s=>typeof Blob!="undefined"&&s instanceof Blob,"isBlob"),$i=l(s=>typeof File!="undefined"&&s instanceof File,"isFile"),Si=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string","isReactNativeAsset"),We=l(s=>Ai(s)||$i(s)||Is()||Si(s),"isFileData"),Ln=l(s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined","isSimpleValue"),Un=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s),"isObjectValue"),Rn=l(s=>!!s&&typeof s=="object"&&"data"in s&&We(s.data),"isFileValue");function Pn(s,i,t){if(Rn(t)){let{name:e,contentType:r}=t,n=In(t.data,e,r!=null?r:Ei),o=kn({name:e,contentType:r});s.push([i,n,...o])}else if(Un(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else Ln(t)&&t&&s.push([i,t.toString()])}l(Pn,"collectParams");function Mn(s){let i=[];for(let[t,e]of Object.entries(s))Pn(i,t,e);return i}l(Mn,"getFormDataParams");function Yi(s){let i=On(),t=Mn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}l(Yi,"buildFormData");var P=class extends Error{constructor(t,e,r,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}};l(P,"UploadClientError");var Nn=l(s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},"buildSearchParams"),vt=l((s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=Nn(t)),e.toString()},"getUrl"),Dn="6.6.1",Fn="UploadcareUploadClient",Vn=Dn;function Ft(s){return Ki({libraryName:Fn,libraryVersion:Vn,...s})}l(Ft,"getUserAgent");var Bn="RequestThrottledError",$s=15e3,zn=1e3;function jn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return $s;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:$s}l(jn,"getTimeoutFromThrottledRequest");function At(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return An(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Bn&&r{let i="";return(Ai(s)||$i(s)||Si(s))&&(i=s.type),i||Ei},"getContentType"),Ls=l(s=>{let i="";return $i(s)&&s.name?i=s.name:Ai(s)||Is()?i="":Si(s)&&s.name&&(i=s.name),i||ks},"getFileName");function Zi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}l(Zi,"getStoreValue");function Hn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=E.baseURL,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=E.retryNetworkErrorMaxTimes,metadata:b}){return At(()=>Et({method:"POST",url:vt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:p,userAgent:f})},data:Yi({file:{data:s,name:t||Ls(s),contentType:e||Os(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Zi(a),signature:n,expire:o,source:d,metadata:b}),signal:c,onProgress:h}).then(({data:S,headers:$,request:x})=>{let T=Ct(JSON.parse(S));if("error"in T)throw new P(T.error.content,T.error.errorCode,x,T,$);return T}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(Hn,"base");var qi;(function(s){s.Token="token",s.FileInfo="file_info"})(qi||(qi={}));function Wn(s,{publicKey:i,baseURL:t=E.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,source:h="url",signal:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=E.retryNetworkErrorMaxTimes,metadata:b}){return At(()=>Et({method:"POST",headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:p,userAgent:f})},url:vt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Zi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:a,expire:c,source:h,metadata:b}),signal:d}).then(({data:S,headers:$,request:x})=>{let T=Ct(JSON.parse(S));if("error"in T)throw new P(T.error.content,T.error.errorCode,x,T,$);return T}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(Wn,"fromUrl");var G;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(G||(G={}));var Xn=l(s=>"status"in s&&s.status===G.Error,"isErrorResponse");function Gn(s,{publicKey:i,baseURL:t=E.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=E.retryNetworkErrorMaxTimes}={}){return At(()=>Et({method:"GET",headers:i?{"X-UC-User-Agent":Ft({publicKey:i,integration:r,userAgent:n})}:void 0,url:vt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:c,headers:h,request:d})=>{let p=Ct(JSON.parse(c));if("error"in p&&!Xn(p))throw new P(p.error.content,void 0,d,p,h);return p}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:o})}l(Gn,"fromUrlStatus");function qn(s,{publicKey:i,baseURL:t=E.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:a,integration:c,userAgent:h,retryThrottledRequestMaxTimes:d=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=E.retryNetworkErrorMaxTimes}){return At(()=>Et({method:"POST",headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:c,userAgent:h})},url:vt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:a}),signal:o}).then(({data:f,headers:g,request:m})=>{let b=Ct(JSON.parse(f));if("error"in b)throw new P(b.error.content,b.error.errorCode,m,b,g);return b}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:d})}l(qn,"group");function Us(s,{publicKey:i,baseURL:t=E.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=E.retryNetworkErrorMaxTimes}){return At(()=>Et({method:"GET",headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:n,userAgent:o})},url:vt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:h,headers:d,request:p})=>{let f=Ct(JSON.parse(h));if("error"in f)throw new P(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Us,"info");function Kn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=E.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:a,store:c,signal:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=E.retryNetworkErrorMaxTimes,metadata:b}){return At(()=>Et({method:"POST",url:vt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:p,userAgent:f})},data:Yi({filename:e||ks,size:s,content_type:t||Ei,part_size:r,UPLOADCARE_STORE:Zi(c),UPLOADCARE_PUB_KEY:i,signature:o,expire:a,source:d,metadata:b}),signal:h}).then(({data:S,headers:$,request:x})=>{let T=Ct(JSON.parse(S));if("error"in T)throw new P(T.error.content,T.error.errorCode,x,T,$);return T.parts=Object.keys(T.parts).map(W=>T.parts[W]),T}),{retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})}l(Kn,"multipartStart");function Yn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=E.retryNetworkErrorMaxTimes}){return At(()=>Et({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Ei}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}l(Yn,"multipartUpload");function Zn(s,{publicKey:i,baseURL:t=E.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=E.retryNetworkErrorMaxTimes}){return At(()=>Et({method:"POST",url:vt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:n,userAgent:o})},data:Yi({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:h,headers:d,request:p})=>{let f=Ct(JSON.parse(h));if("error"in f)throw new P(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Zn,"multipartComplete");function Ji({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a,signal:c,onProgress:h}){return Ss({check:d=>Us(s,{publicKey:i,baseURL:t,signal:d,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a}).then(p=>p.isReady?p:(h&&h({isComputable:!0,value:1}),!1)),signal:c})}l(Ji,"isReadyPoll");var yt=class{constructor(i,{baseCDN:t=E.baseCDN,fileName:e}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=vt(t,`${r}/`),a=n?vt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=a}};l(yt,"UploadcareFile");var Jn=l((s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:S})=>Hn(s,{publicKey:i,fileName:t,contentType:a,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:S}).then(({file:$})=>Ji({file:$,publicKey:i,baseURL:e,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then($=>new yt($,{baseCDN:b})),"uploadDirect"),Qn=l((s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d,baseCDN:p})=>Us(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d}).then(f=>new yt(f,{baseCDN:p,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),"uploadFromUploaded"),to=l((s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=l(o=>()=>{e=o,r.forEach((a,c)=>c!==o&&a.abort())},"createStopRaceCallback");return xi(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,a)=>{let c=n(a);return Promise.resolve().then(()=>o({stopRace:c,signal:r[a].signal})).then(h=>(c(),h)).catch(h=>(t=h,null))})).then(o=>{if(e===null)throw t;return o[e]})},"race"),eo=window.WebSocket,vi=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}};l(vi,"Events");var io=l((s,i)=>s==="success"?{status:G.Success,...i}:s==="progress"?{status:G.Progress,...i}:{status:G.Error,...i},"response"),Ci=class{constructor(i,t=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new vi);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new eo(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,io(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=l(()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1},"actualDisconect");this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}};l(Ci,"Pusher");var Xi=null,Qi=l(s=>{if(!Xi){let i=typeof window=="undefined"?0:3e4;Xi=new Ci(s,i)}return Xi},"getPusher"),so=l(s=>{Qi(s).connect()},"preconnect");function ro({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:a,signal:c}){return Ss({check:h=>Gn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:h}).then(d=>{switch(d.status){case G.Error:return new P(d.error,d.errorCode);case G.Waiting:return!1;case G.Unknown:return new P(`Token "${s}" was not found.`);case G.Progress:return a&&(d.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:d.done/d.total})),!1;case G.Success:return a&&a({isComputable:!0,value:d.done/d.total}),d;default:throw new Error("Unknown status")}}),signal:c})}l(ro,"pollStrategy");var no=l(({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Qi(i),a=o.onError(n),c=l(()=>{a(),o.unsubscribe(s)},"destroy");xi(t,()=>{c(),n(new bt("pusher cancelled"))}),o.subscribe(s,h=>{switch(h.status){case G.Progress:{e&&(h.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:h.done/h.total}));break}case G.Success:{c(),e&&e({isComputable:!0,value:h.done/h.total}),r(h);break}case G.Error:c(),n(new P(h.msg,h.error_code))}})}),"pushStrategy"),oo=l((s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,onProgress:p,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,pusherKey:S=E.pusherKey,metadata:$})=>Promise.resolve(so(S)).then(()=>Wn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,metadata:$})).catch(x=>{let T=Qi(S);return T==null||T.disconnect(),Promise.reject(x)}).then(x=>x.type===qi.FileInfo?x:to([({signal:T})=>ro({token:x.token,publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:p,signal:T}),({signal:T})=>no({token:x.token,pusherKey:S,signal:T,onProgress:p})],{signal:d})).then(x=>{if(x instanceof P)throw x;return x}).then(x=>Ji({file:x.uuid,publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:p,signal:d})).then(x=>new yt(x,{baseCDN:r})),"uploadFromUrl"),Gi=new WeakMap,lo=l(async s=>{if(Gi.has(s))return Gi.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Gi.set(s,i),i},"getBlobFromReactNativeAsset"),Rs=l(async s=>{if($i(s)||Ai(s))return s.size;if(Si(s))return(await lo(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},"getFileSize"),ao=l((s,i=E.multipartMinFileSize)=>s>=i,"isMultipart"),Ps=l(s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!We(s)&&t.test(s)},"isUuid"),Ms=l(s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!We(s)&&t.test(s)},"isUrl"),co=l((s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,a=[...i],c=l(()=>{let h=i.length-a.length,d=a.shift();d&&d().then(p=>{n||(r[h]=p,o-=1,o?c():t(r))}).catch(p=>{n=!0,e(p)})},"run");for(let h=0;h{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},"sliceChunk"),uo=l(async(s,i,t)=>e=>ho(s,e,i,t),"prepareChunks"),po=l((s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})=>Yn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c}),"uploadPart"),fo=l(async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,contentType:b,multipartChunkSize:S=E.multipartChunkSize,maxConcurrentRequests:$=E.maxConcurrentRequests,baseCDN:x,metadata:T})=>{let W=e!=null?e:await Rs(s),ft,Ut=l((N,tt)=>{if(!h)return;ft||(ft=Array(N).fill(0));let mt=l(X=>X.reduce((gt,Vi)=>gt+Vi,0),"sum");return X=>{X.isComputable&&(ft[tt]=X.value,h({isComputable:!0,value:mt(ft)/N}))}},"createProgressHandler");return b||(b=Os(s)),Kn(W,{publicKey:i,contentType:b,fileName:t||Ls(s),baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:T}).then(async({uuid:N,parts:tt})=>{let mt=await uo(s,W,S);return Promise.all([N,co($,tt.map((X,gt)=>()=>po(mt(gt),X,{publicKey:i,contentType:b,onProgress:Ut(tt.length,gt),signal:c,integration:p,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})))])}).then(([N])=>Zn(N,{publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})).then(N=>N.isReady?N:Ji({file:N.uuid,publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then(N=>new yt(N,{baseCDN:x}))},"uploadMultipart");async function ts(s,{publicKey:i,fileName:t,baseURL:e=E.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartMinFileSize:b,multipartChunkSize:S,maxConcurrentRequests:$,baseCDN:x=E.baseCDN,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:W,pusherKey:ft,metadata:Ut}){if(We(s)){let N=await Rs(s);return ao(N,b)?fo(s,{publicKey:i,contentType:m,multipartChunkSize:S,fileSize:N,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,maxConcurrentRequests:$,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x,metadata:Ut}):Jn(s,{publicKey:i,fileName:t,contentType:m,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x,metadata:Ut})}if(Ms(s))return oo(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:x,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:W,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,pusherKey:ft,metadata:Ut});if(Ps(s))return Qn(s,{publicKey:i,fileName:t,baseURL:e,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x});throw new TypeError(`File uploading from "${s}" is not supported`)}l(ts,"uploadFile");var wi=class{constructor(i,t){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}};l(wi,"UploadcareGroup");var mo=l(s=>{for(let i of s)if(!We(i))return!1;return!0},"isFileDataArray"),go=l(s=>{for(let i of s)if(!Ps(i))return!1;return!0},"isUuidArray"),_o=l(s=>{for(let i of s)if(!Ms(i))return!1;return!0},"isUrlArray");function Ns(s,{publicKey:i,fileName:t,baseURL:e=E.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:b=E.multipartChunkSize,baseCDN:S=E.baseCDN,checkForUrlDuplicates:$,saveUrlForRecurrentUploads:x,jsonpCallback:T}){if(!mo(s)&&!_o(s)&&!go(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let W,ft=!0,Ut=s.length,N=l((tt,mt)=>{if(!c)return;W||(W=Array(tt).fill(0));let X=l(gt=>gt.reduce((Vi,zr)=>Vi+zr)/tt,"normalize");return gt=>{if(!gt.isComputable||!ft){ft=!1,c({isComputable:!1});return}W[mt]=gt.value,c({isComputable:!0,value:X(W)})}},"createProgressHandler");return Promise.all(s.map((tt,mt)=>ts(tt,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:N(Ut,mt),source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:b,baseCDN:S,checkForUrlDuplicates:$,saveUrlForRecurrentUploads:x}))).then(tt=>{let mt=tt.map(X=>X.uuid);return qn(mt,{publicKey:i,baseURL:e,jsonpCallback:T,secureSignature:r,secureExpire:n,signal:a,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g}).then(X=>new wi(X,tt)).then(X=>(c&&c({isComputable:!0,value:1}),X))})}l(Ns,"uploadFileGroup");var Mt,re,Nt,ne,oe,le,Ti,He=class{constructor(i){Rt(this,le);Rt(this,Mt,1);Rt(this,re,[]);Rt(this,Nt,0);Rt(this,ne,new WeakMap);Rt(this,oe,new WeakMap);Fe(this,Mt,i)}add(i){return new Promise((t,e)=>{z(this,ne).set(i,t),z(this,oe).set(i,e),z(this,re).push(i),gi(this,le,Ti).call(this)})}get pending(){return z(this,re).length}get running(){return z(this,Nt)}set concurrency(i){Fe(this,Mt,i),gi(this,le,Ti).call(this)}get concurrency(){return z(this,Mt)}};l(He,"Queue"),Mt=new WeakMap,re=new WeakMap,Nt=new WeakMap,ne=new WeakMap,oe=new WeakMap,le=new WeakSet,Ti=l(function(){let i=z(this,Mt)-z(this,Nt);for(let t=0;t{z(this,ne).delete(e),z(this,oe).delete(e),Fe(this,Nt,z(this,Nt)-1),gi(this,le,Ti).call(this)}).then(o=>r(o)).catch(o=>n(o))}},"#run");var es=l(()=>({"*blocksRegistry":new Set}),"blockCtx"),is=l(s=>({...es(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),"activityBlockCtx"),ki=l(s=>({...is(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new He(1)}),"uploaderBlockCtx");function Ds(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}l(Ds,"l10nProcessor");var et=l(s=>`*cfg/${s}`,"sharedConfigKey");var ot=l(s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")},"toKebabCase");var Fs=new Set;function Ii(s){Fs.has(s)||(Fs.add(s),console.warn(s))}l(Ii,"warnOnce");var Oi=l((s,i)=>new Intl.PluralRules(s).select(i),"getPluralForm");var ss="lr-",y=class extends Pt{constructor(){super();u(this,"allowCustomTemplate",!0);u(this,"init$",es());u(this,"updateCtxCssData",l(()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()},"updateCtxCssData"));this.activityType=null,this.addTemplateProcessor(Ds),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=xs(r);for(let a of n)e[a.variable]=this.pluralize(a.pluralKey,Number(e[a.countVariable]));return je(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Oi(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${ss}${t}`,!0),Hi()||(this._destroyInnerHeightTracker=Cs()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=l(h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h,"getUnit");if(t===0)return`0 ${n(r[0])}`;let o=1024,a=e<0?0:e,c=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**c).toFixed(a))+" "+n(r[c])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?je(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=et(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Ii("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ot(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(et(t));r.ctx.has(r.name)?this.sub(et(t),e):(this.bindCssData(`--cfg-${ot(t)}`),this.sub(`--cfg-${ot(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(ss)?t:ss+t)}};l(y,"Block"),u(y,"StateConsumerScope",null),u(y,"className","");var Vt=class extends y{constructor(){super();u(this,"_handleBackdropClick",l(()=>{this._closeDialog()},"_handleBackdropClick"));u(this,"_closeDialog",l(()=>{this.setOrAddState("*modalActive",!1)},"_closeDialog"));u(this,"_handleDialogClose",l(()=>{this._closeDialog()},"_handleDialogClose"));u(this,"_handleDialogPointerUp",l(t=>{t.target===this.ref.dialog&&this._closeDialog()},"_handleDialogPointerUp"));this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}};l(Vt,"Modal"),u(Vt,"StateConsumerScope","modal");Vt.template=``;var Vs="active",Xe="___ACTIVITY_IS_ACTIVE___",lt=class extends y{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",is(this));u(this,"_debouncedHistoryFlush",k(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=lt._activityRegistry[this.activityKey];this[Xe]=!1,this.removeAttribute(Vs),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=lt._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[Xe]=!0,this.setAttribute(Vs,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[Xe]?this._deactivate():this.activityType===t&&!this[Xe]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!lt._activityRegistry[this.activityKey]}get isActivityActive(){return this[Xe]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;lt._activityRegistry||(lt._activityRegistry=Object.create(null)),lt._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),lt._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(lt._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setOrAddState("*modalActive",!1)}}},_=lt;l(_,"ActivityBlock"),u(_,"_activityRegistry",Object.create(null));_.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var Ge=33.333333333333336,C=1,rs=24,Bs=6;function Bt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}l(Bt,"setSvgNodeAttrs");function it(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Bt(t,i),t}l(it,"createSvgNode");function zs(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=i.includes("w")?0:1,c=i.includes("n")?0:1,h=[-1,1][a],d=[-1,1][c],p=[e+a*n+1.5*h,r+c*o+1.5*d-24*t*d],f=[e+a*n+1.5*h,r+c*o+1.5*d],g=[e+a*n-24*t*h+1.5*h,r+c*o+1.5*d];return{d:`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]} L ${g[0]} ${g[1]}`,center:f}}l(zs,"cornerPath");function js(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=["n","s"].includes(i)?.5:{w:0,e:1}[i],c=["w","e"].includes(i)?.5:{n:0,s:1}[i],h=[-1,1][a],d=[-1,1][c],p,f;["n","s"].includes(i)?(p=[e+a*n-34*t/2,r+c*o+1.5*d],f=[e+a*n+34*t/2,r+c*o+1.5*d]):(p=[e+a*n+1.5*h,r+c*o-34*t/2],f=[e+a*n+1.5*h,r+c*o+34*t/2]);let g=`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]}`,m=[f[0]-(f[0]-p[0])/2,f[1]-(f[1]-p[1])/2];return{d:g,center:m}}l(js,"sidePath");function Hs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}l(Hs,"thumbCursor");function Ws({rect:s,delta:[i,t],imageBox:e}){return ce({...s,x:s.x+i,y:s.y+t},e)}l(Ws,"moveRect");function ce(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}l(ce,"constraintRect");function bo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:a}=s;n+=r,a-=r,t&&(o=a*t);let c=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,a=s.y+s.height-n,t&&(o=a*t,c=s.x+s.width/2-o/2)),c<=e.x&&(c=e.x,n=s.y+s.height-a),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y+s.height-a),a=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x+s.width-o),a=e.y+e.height&&(a=e.y+e.height-n,t&&(o=a*t),c=s.x+s.width/2-o/2),c<=e.x&&(c=e.x,n=s.y),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y),a=e.x+e.width&&(o=e.x+e.width-n,t&&(a=o/t),c=s.y+s.height/2-a/2),c<=e.y&&(c=e.y,n=s.x),c+a>=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x),at?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x+s.width-c,a=e.y)):t&&(r=h*t-c,c=c+r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y+s.height-h)),he.x+e.width&&(r=e.x+e.width-o-c),a+nt?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x,a=e.y)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y+s.height-h)),he.y+e.height&&(n=e.y+e.height-a-h),o+=r,c-=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x+s.width-c,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y)),he.x+e.width&&(r=e.x+e.width-o-c),a+h+n>e.y+e.height&&(n=e.y+e.height-a-h),c+=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y)),h=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}l(qs,"isRectInsideRect");function he({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}l(he,"rotateSize");function Ks(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),a=Math.round((i-n)/2);return o+r>s&&(r=s-o),a+n>i&&(n=i-a),{x:o,y:a,width:r,height:n}}l(Ks,"calculateMaxCenteredCropFrame");function ue(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}l(ue,"roundRect");function $t(s,i,t){return Math.min(Math.max(s,i),t)}l($t,"clamp");var Ui=l(s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]},"parseCropPreset");var st=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var ns="blocks",os="0.27.1";function Ys(s){return Ki({...s,libraryName:ns,libraryVersion:os})}l(Ys,"customUserAgent");var Zs=l(s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},"normalizeCdnOperation"),Ri=l((...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Zs(i)).join("/-/"),"joinCdnOperations"),L=l((...s)=>{let i=Ri(...s);return i?`-/${i}/`:""},"createCdnUrlModifiers");function Js(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}l(Js,"extractFilename");function Qs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}l(Qs,"extractUuid");function tr(s){let i=er(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Zs(n))}l(tr,"extractOperations");function er(s){let i=new URL(s),t=Js(s),e=ir(t)?sr(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}l(er,"trimFilename");function ir(s){return s.startsWith("http")}l(ir,"isFileUrl");function sr(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}l(sr,"splitFileUrl");var O=l((s,i,t)=>{let e=new URL(er(s));if(t=t||Js(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),ir(t)){let r=sr(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},"createCdnUrl"),St=l((s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()},"createOriginalUrl");var D=l((s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0),"stringToArray");var qe=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],ls=l(s=>s?s.filter(i=>typeof i=="string").map(i=>D(i)).flat():[],"mergeFileTypes"),as=l((s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),"matchMimeType"),rr=l((s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),"matchExtension"),Ke=l(s=>{let i=s==null?void 0:s.type;return i?as(i,qe):!1},"fileIsImage");var ct=1e3,zt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),Ye=l(s=>Math.ceil(s*100)/100,"round"),nr=l((s,i=zt.AUTO)=>{let t=i===zt.AUTO;if(i===zt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))},"dispatch");if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};l(U,"EventManager"),u(U,"_timeoutStore",Object.create(null));var or="[Typed State] Wrong property name: ",Ao="[Typed State] Wrong property type: ",Ze=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||Be.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=A.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(or+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(Ao+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(or+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){A.deleteCtx(this.__ctxId)}};l(Ze,"TypedData");var Je=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Be.generate(),this.__data=A.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Ze(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){A.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};l(Je,"TypedCollection");var lr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:yt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var ar=l(s=>s?s.split(",").map(i=>i.trim()):[],"deserealizeCsv"),jt=l(s=>s?s.join(","):"","serializeCsv");var v=class extends _{constructor(){super(...arguments);u(this,"couldBeUploadCollectionOwner",!1);u(this,"isUploadCollectionOwner",!1);u(this,"init$",ki(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",k(this._runValidators.bind(this),100));u(this,"_handleCollectionUpdate",l(t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(c=>!c.getValue("uploadError"));o.forEach(c=>{n+=e.readProp(c,"uploadProgress")});let a=Math.round(n/o.length);this.$["*commonProgress"]=a,U.emit(new F({type:M.UPLOAD_PROGRESS,ctx:this.ctxName,data:a}),void 0,a===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(a=>!!a.getValue("fileInfo")),o=e.findItems(a=>!!a.getValue("uploadError")||!!a.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let a=this.getOutputData(c=>!!c.getValue("fileInfo")&&!c.getValue("silentUpload"));a.length>0&&U.emit(new F({type:M.UPLOAD_FINISH,ctx:this.ctxName,data:a}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{U.emit(new F({type:M.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{U.emit(new F({type:M.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{U.emit(new F({type:M.CDN_MODIFICATION,ctx:this.ctxName,data:A.getCtx(o).store}),void 0,!1)})},"_handleCollectionUpdate"))}setUploadMetadata(t){Ii("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Je({typedSchema:lr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=l(()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1),"hasUploadCollectionOwner");this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let a of n)(o=a==null?void 0:a.getValue("abortController"))==null||o.abort(),a==null||a.setValue("abortController",null),URL.revokeObjectURL(a==null?void 0:a.getValue("thumbUrl"));this.$["*uploadList"]=e.map(a=>({uid:a}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:st.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:st.API})}addFileFromObject(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:Ke(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:st.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:Ke(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=jt(ls([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?qe:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=jt(qe)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:st.LOCAL})),this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=D(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":_.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":_.activities.START_FROM}),this.setOrAddState("*modalActive",!0);U.emit(new F({type:M.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),U.emit(new F({type:M.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=ls([...e?qe:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),a=t.getValue("fileName");if(!o||!a)return;let c=as(o,n),h=rr(a,n);if(!c&&!h)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:nr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Ui(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:a,height:c}=o.imageInfo,h=e.width/e.height,d=Ks(a,c,h),p=L(`crop/${d.width}x${d.height}/${d.x},${d.y}`);n.setMultipleValues({cdnUrlModifiers:p,cdnUrl:O(n.getValue("cdnUrl"),p)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===_.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Ys,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=A.getCtx(n).store,a=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},c={...a,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||a.cdnUrl};e.push(c)}),e}};l(v,"UploaderBlock");v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(M).forEach(s=>{let i=U.eName(s),t=k(e=>{if([M.UPLOAD_FINISH,M.REMOVE,M.CDN_MODIFICATION].includes(e.detail.type)){let n=A.getCtx(e.detail.ctx),o=n.read("uploadCollection"),a=[];o.items().forEach(c=>{let h=A.getCtx(c).store,d=h.fileInfo;if(d){let p={...d,cdnUrlModifiers:h.cdnUrlModifiers,cdnUrl:h.cdnUrl||d.cdnUrl};a.push(p)}}),U.emit(new F({type:M.DATA_OUTPUT,ctx:e.detail.ctx,data:a})),n.pub("outputData",a)}},0);window.addEventListener(i,t)});var Z={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function $o(s,i){if(typeof i=="number")return Z[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Z[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Z[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}l($o,"transformationToStr");var hr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function kt(s){return Ri(...hr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return $o(i,t)}).filter(i=>!!i))}l(kt,"transformationsToOperations");var Pi=Ri("format/auto","progressive/yes"),wt=l(([s])=>typeof s!="undefined"?Number(s):void 0,"asNumber"),cr=l(()=>!0,"asBoolean"),So=l(([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),"asFilter"),ko=l(([s,i])=>({dimensions:D(s,"x").map(Number),coords:D(i).map(Number)}),"asCrop"),Io={enhance:wt,brightness:wt,exposure:wt,gamma:wt,contrast:wt,saturation:wt,vibrance:wt,warmth:wt,filter:So,mirror:cr,flip:cr,rotate:wt,crop:ko};function ur(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!hr.includes(e))continue;let n=Io[e],o=n(r);i[e]=o}return i}l(ur,"operationsToTransformations");var V=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),q=[V.CROP,V.TUNING,V.FILTERS],dr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],pr=["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"],fr=["rotate","mirror","flip"],ht=Object.freeze({brightness:{zero:Z.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Z.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Z.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Z.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Z.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Z.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Z.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Z.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Z.filter,range:[0,100],keypointsNumber:1}});var Oo="https://ucarecdn.com",Lo="https://upload.uploadcare.com",Uo="https://social.uploadcare.com",Qe={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:jt(q),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Oo,baseUrl:Lo,socialBaseUrl:Uo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var K=l(s=>String(s),"asString"),ut=l(s=>Number(s),"asNumber"),I=l(s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,"asBoolean"),Ro=l(s=>s==="auto"?s:I(s),"asStore"),Po={pubkey:K,multiple:I,multipleMin:ut,multipleMax:ut,confirmUpload:I,imgOnly:I,accept:K,externalSourcesPreferredTypes:K,store:Ro,cameraMirror:I,sourceList:K,maxLocalFileSizeBytes:ut,thumbSize:ut,showEmptyList:I,useLocalImageEditor:I,useCloudImageEditor:I,cloudImageEditorTabs:K,removeCopyright:I,cropPreset:K,modalScrollLock:I,modalBackdropStrokes:I,sourceListWrap:I,remoteTabSessionKey:K,cdnCname:K,baseUrl:K,socialBaseUrl:K,secureSignature:K,secureExpire:K,secureDeliveryProxy:K,retryThrottledRequestMaxTimes:ut,multipartMinFileSize:ut,multipartChunkSize:ut,maxConcurrentRequests:ut,multipartMaxConcurrentRequests:ut,multipartMaxAttempts:ut,checkForUrlDuplicates:I,saveUrlForRecurrentUploads:I,groupOutput:I,userAgentIntegration:K},mr=l((s,i)=>{if(!(typeof i=="undefined"||i===null))return Po[s](i)},"normalizeConfigValue");var Mi=Object.keys(Qe),Mo=["metadata"],No=l(s=>Mo.includes(s),"isComplexKey"),cs=Mi.filter(s=>!No(s)),Do={...Object.fromEntries(cs.map(s=>[ot(s),s])),...Object.fromEntries(cs.map(s=>[s.toLowerCase(),s]))},Fo={...Object.fromEntries(Mi.map(s=>[ot(s),et(s)])),...Object.fromEntries(Mi.map(s=>[s.toLowerCase(),et(s)]))},de=class extends y{constructor(){super();u(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Qe).map(([t,e])=>[et(t),e]))}}initCallback(){super.initCallback();for(let t of Mi){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,cs.includes(t)){let o=[...new Set([ot(t),t.toLowerCase()])];for(let a of o)typeof n=="undefined"||n===null?this.removeAttribute(a):this.setAttribute(a,n.toString())}this.$[et(t)]!==n&&(typeof n=="undefined"||n===null?this.$[et(t)]=Qe[t]:this.$[et(t)]=n)},get:()=>this.$[et(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Do[t],o=mr(n,r),a=o!=null?o:Qe[n],c=this;c[n]=a}};l(de,"Config");de.bindAttributes(Fo);var Ht=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};l(Ht,"Icon");Ht.template=``;Ht.bindAttributes({name:"name",size:"size"});var Vo="https://ucarecdn.com",Wt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Vo},"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 gr=l(s=>[...new Set(s)],"uniqueArray");var ti="--lr-img-",_r="unresolved",pe=2,fe=3,br=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),vr=Object.create(null),yr;for(let s in Wt)vr[ti+s]=((yr=Wt[s])==null?void 0:yr.default)||"";var ei=class extends Pt{constructor(){super(...arguments);u(this,"cssInit$",vr)}$$(t){return this.$[ti+t]}set$$(t){for(let e in t)this.$[ti+e]=t[e]}sub$$(t,e){this.sub(ti+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!br&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return L(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Wt.format.default}`,`quality/${this.$$("quality")||Wt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(br&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return O(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(O(St(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(O(St(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(O(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(O(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?je(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),a=r?"":e*Math.round(n.height);return o||a?`${o||""}x${a||""}`:null}_setupEventProxy(t){let e=l(n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},"proxifyEvent"),r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(_r,""),this.img.onload=()=>{this.img.removeAttribute(_r)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Wt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?gr(D(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*pe+"x")}") ${n*pe}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*fe+"x")}") ${n*fe}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,pe))}") ${pe}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,fe))}") ${fe}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*pe+"x")+` ${e*pe}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*fe+"x")+` ${e*fe}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):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(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),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)}static get observedAttributes(){return Object.keys(Wt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[ti+t]=r})}};l(ei,"ImgBase");var ii=class extends ei{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};l(ii,"Img");var Xt=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",i=>{typeof i!="undefined"&&(this.$.withDropZone=I(i))}),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};l(Xt,"SimpleBtn");Xt.template=``;Xt.bindAttributes({dropzone:null});var si=class extends _{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};l(si,"StartFrom");function Bo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=l(r=>{r.type!=="loadend"&&t.abort(),i(!1)},"onLoad");t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}l(Bo,"checkIsDirectory");function zo(s,i){return new Promise(t=>{let e=0,r=[],n=l(a=>{a||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),a.isFile?(e++,a.file(c=>{e--;let h=new File([c],c.name,{type:c.type||i});r.push(h),e===0&&t(r)})):a.isDirectory&&o(a.createReader())},"readEntry"),o=l(a=>{e++,a.readEntries(c=>{e--;for(let h of c)n(h);e===0&&t(r)})},"readReaderContent");n(s)})}l(zo,"readEntryContentAsync");function Cr(s){let i=[],t=[];for(let e=0;e{i.push(...c)}));continue}let o=r.getAsFile();t.push(Bo(o).then(a=>{a||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}l(Cr,"getDropItems");var j={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},wr=["focus"],jo=100,hs=new Map;function Ho(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}l(Ho,"distance");function us(s){let i=0,t=document.body,e=new Set,r=l(m=>e.add(m),"handleSwitch"),n=j.INACTIVE,o=l(m=>{s.shouldIgnore()&&m!==j.INACTIVE||(n!==m&&e.forEach(b=>b(m)),n=m)},"setState"),a=l(()=>i>0,"isDragging");r(m=>s.onChange(m));let c=l(()=>{i=0,o(j.INACTIVE)},"onResetEvent"),h=l(()=>{i+=1,n===j.INACTIVE&&o(j.ACTIVE)},"onDragEnter"),d=l(()=>{i-=1,a()||o(j.INACTIVE)},"onDragLeave"),p=l(m=>{m.preventDefault(),i=0,o(j.INACTIVE)},"onDrop"),f=l(m=>{if(s.shouldIgnore())return;a()||(i+=1);let b=[m.x,m.y],S=s.element.getBoundingClientRect(),$=Math.floor(Ho(b,S)),x=${if(s.shouldIgnore())return;m.preventDefault();let b=await Cr(m.dataTransfer);s.onItems(b),o(j.INACTIVE)},"onElementDrop");return t.addEventListener("drop",p),t.addEventListener("dragleave",d),t.addEventListener("dragenter",h),t.addEventListener("dragover",f),s.element.addEventListener("drop",g),wr.forEach(m=>{window.addEventListener(m,c)}),()=>{hs.delete(s.element),t.removeEventListener("drop",p),t.removeEventListener("dragleave",d),t.removeEventListener("dragenter",h),t.removeEventListener("dragover",f),s.element.removeEventListener("drop",g),wr.forEach(m=>{window.removeEventListener(m,c)})}}l(us,"addDropzone");var Gt=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,state:j.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return e&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!I(e)})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:I(e)})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:I(e)})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:I(e)})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=us({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:st.DROP_AREA});return}this.addFileFromObject(r,{source:st.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=us({element:t,onChange:e=>{var n;let r=(n=Object.entries(j).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var n;let r=(n=Object.entries(j).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=D(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,n;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};l(Gt,"DropArea");Gt.template=`
{{text}}
`;Gt.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Wo="src-type-",qt=class extends v{constructor(){super(...arguments);u(this,"_registeredTypes",{});u(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:_.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:_.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:_.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:_.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:a,activityParams:c={}}=e;this.applyL10nKey("src-type",`${Wo}${r}`),this.$.iconName=n,this.onclick=h=>{(a?a(h):!!o)&&this.set$({"*currentActivityParams":c,"*currentActivity":o})}}};l(qt,"SourceBtn");qt.template=`
`;qt.bindAttributes({type:null});var ri=class extends y{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=D(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};l(ri,"SourceList");function Tr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}l(Tr,"createSvgBlobUrl");function xr(s="#fff",i="rgba(0, 0, 0, .1)"){return Tr(``)}l(xr,"checkerboardCssBg");function ni(s="hsl(209, 21%, 65%)",i=32,t=32){return Tr(``)}l(ni,"fileCssBg");function Er(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,a)=>{r.onload=()=>{let c=r.height/r.width;c>1?(t.width=i,t.height=i*c):(t.height=i,t.width=i/c),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(h=>{if(!h){a();return}let d=URL.createObjectURL(h);o(d)})},r.onerror=c=>{a(c)}});return r.src=URL.createObjectURL(s),n}l(Er,"generateThumb");var H=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),nt=class extends v{constructor(){super();u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",k(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",k(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:H.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===_.activities.DETAILS)?this.$["*currentActivity"]=_.activities.DETAILS:this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);U.emit(new F({type:M.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=H.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=H.FAILED:t.getValue("validationMultipleLimitMsg")?e=H.LIMIT_OVERFLOW:t.getValue("isUploading")?e=H.UPLOADING:t.getValue("fileInfo")&&(e=H.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(O(St(this.cfg.cdnCname,this._entry.getValue("uuid")),L(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Er(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ni(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ni(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{nt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),nt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===H.FAILED,isLimitOverflow:t===H.LIMIT_OVERFLOW,isUploading:t===H.UPLOADING,isFinished:t===H.FINISHED,progressVisible:t===H.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===H.FAILED||t===H.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===H.FINISHED&&(this.$.badgeIcon="badge-success"),t===H.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),nt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,a;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(c=>!c.getValue("fileInfo"));U.emit(new F({type:M.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let c=new AbortController;t.setValue("abortController",c);let h=l(async()=>{let p=await this.getUploadClientOptions();return ts(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...p,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let g=f.value*100;t.setValue("uploadProgress",g)}this.$.progressUnknown=!f.isComputable},signal:c.signal})},"uploadTask"),d=await this.$["*uploadQueue"].add(h);t.setMultipleValues({fileInfo:d,isUploading:!1,fileName:d.originalFilename,fileSize:d.size,isImage:d.isImage,mimeType:(a=(o=(n=d.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?a:d.mimeType,uuid:d.uuid,cdnUrl:d.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(c){console.warn("Upload error",c),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),c instanceof P?c.isCancel||t.setValue("uploadError",c):t.setValue("uploadError",new Error("Unexpected error"))}}};l(nt,"FileItem");nt.template=`
{{itemName}}{{errorText}}
`;nt.activeInstances=new Set;var oi=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}};l(oi,"UiMessage");var me=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};l(me,"MessageBox");me.template=`
{{captionTxt}}
{{msgTxt}}
`;var ge=class extends v{constructor(){super();u(this,"couldBeUploadCollectionOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",_.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",k(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));U.emit(new F({type:M.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var d,p;let t=!!this.cfg.multiple,e=t?(d=this.cfg.multipleMin)!=null?d:0:1,r=t?(p=this.cfg.multipleMax)!=null?p:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!a,tooFew:o,tooMany:a,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new oi,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let g of t){let m=this.uploadCollection.read(g);m.getValue("fileInfo")&&!m.getValue("validationErrorMsg")&&(r.succeed+=1),m.getValue("isUploading")&&(r.uploading+=1),(m.getValue("validationErrorMsg")||m.getValue("uploadError"))&&(r.failed+=1),m.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:a}=this._validateFilesCount(),c=r.failed===0&&r.limitOverflow===0,h=!1,d=!1,p=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?h=!0:(d=!0,p=r.total===r.succeed&&n&&c),this.set$({doneBtnVisible:d,doneBtnEnabled:p,uploadBtnVisible:h,addMoreBtnEnabled:r.total===0||!o&&!a,addMoreBtnVisible:!a||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=l(r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})},"localizedText");return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};l(ge,"UploadList");ge.template=`{{headerText}}
`;var _e=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.URL);u(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:st.URL_TAB}),this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};l(_e,"UrlSource");_e.template=`
`;var ds=l(()=>typeof navigator.permissions!="undefined","canUsePermissionsApi");var be=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.CAMERA);u(this,"_unsubPermissions",null);u(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:ds(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});u(this,"_onActivate",l(()=>{ds()&&this._subscribePermissions(),this._capture()},"_onActivate"));u(this,"_onDeactivate",l(()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()},"_onDeactivate"));u(this,"_handlePermissionsChange",l(()=>{this._capture()},"_handlePermissionsChange"));u(this,"_setPermissionsState",k(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:st.CAMERA}),this.set$({"*currentActivity":_.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};l(be,"CameraSource");be.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var li=class extends v{};l(li,"UploadCtxProvider");var ye=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.DETAILS);u(this,"pauseRender",!0);u(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ni(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=Ke(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=l((n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))},"tmpSub");r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let a=O(n,L("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(a))}})})}};l(ye,"UploadDetails");ye.template=`
{{fileSize}}
{{errorTxt}}
`;var Ni=class{constructor(){u(this,"captionL10nStr","confirm-your-action");u(this,"messageL10Str","are-you-sure");u(this,"confirmL10nStr","yes");u(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}};l(Ni,"UiConfirmation");var ve=class extends _{constructor(){super(...arguments);u(this,"activityType",_.activities.CONFIRMATION);u(this,"_defaults",new Ni);u(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":_.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};l(ve,"ConfirmationDialog");ve.template=`{{activityCaption}}
{{messageTxt}}
`;var Ce=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};l(Ce,"ProgressBarCommon");Ce.template=``;var we=class extends y{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};l(we,"ProgressBar");we.template='
';var J="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var Kt=class extends y{constructor(){super();u(this,"init$",{...this.init$,checkerboard:!1,src:J})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${xr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=J}};l(Kt,"FilePreview");Kt.template='';Kt.bindAttributes({checkerboard:"checkerboard"});var Ar="--cfg-ctx-name",R=class extends y{get cfgCssCtxName(){return this.getCssData(Ar,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(Ar,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:A.getCtx(this.cfgCtxName)}}};l(R,"CloudImageEditorBase");function $r(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}l($r,"normalize");function B(...s){let i=$r(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}l(B,"classNames");function Sr(s,...i){let t=$r(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}l(Sr,"applyClassNames");var kr=l(s=>{if(!s)return q;let i=ar(s).filter(t=>q.includes(t));return i.length===0?q:i},"parseTabs");function Ir(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":q,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:J,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:jt(q),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=J,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=L(kt(i)),r=O(t,L(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}l(Ir,"initState");var Or=`
Network error
{{fileType}}
{{msg}}
`;var rt=class extends R{constructor(){super();u(this,"_debouncedShowLoader",k(this._showLoader.bind(this),300));this.init$={...this.init$,...Ir(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([a])=>{a.contentRect.width>0&&a.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===V.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Qs(this.$.cdnUrl);this.$["*originalUrl"]=St(this.$.cdnUrl,t);let e=tr(this.$.cdnUrl),r=ur(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=St(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=O(this.$["*originalUrl"],L("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===V.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==J&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||J)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Ui(t)}),this.sub("tabs",t=>{this.$["*tabList"]=kr(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=B("image",{image_hidden_to_cropper:t===V.CROP,image_hidden_effects:t!==V.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=L(kt(t)),n=O(e,L(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};l(rt,"CloudImageEditorBlock"),u(rt,"className","cloud-image-editor");rt.template=Or;rt.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var Te=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=C&&t.width<=C)return!0;let e=t.height<=C&&(i.includes("n")||i.includes("s")),r=t.width<=C&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],a=it("mask",{id:"backdrop-mask"}),c=it("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=it("rect",{x:t,y:e,width:r,height:n,fill:"black"});a.appendChild(c),a.appendChild(h);let d=it("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(d),o.appendChild(a),this._backdropMask=a,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Bt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,a=e==="",c=e.length===2,{x:h,y:d,width:p,height:f}=i;if(a){let m={x:h+p/3,y:d+f/3,width:p/3,height:f/3};Bt(n,m)}else{let m=$t(Math.min(p,f)/(24*2+34)/2,0,1),{d:b,center:S}=c?zs(i,e,m):js(i,e,m),$=Math.max(rs*$t(Math.min(p,f)/rs/3,0,1),Bs);Bt(n,{x:S[0]-$,y:S[1]-$,width:$*2,height:$*2}),Bt(r,{d:b})}let g=this._shouldThumbBeDisabled(e);o.setAttribute("class",B("thumb",{"thumb--hidden":g,"thumb--visible":!g}))}Bt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=it("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=it("rect",{fill:"transparent"}),a=it("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(a),n.appendChild(o),i[r]={direction:r,pathNode:a,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=it("svg"),t=it("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=it("line",{x1:`${Ge*e}%`,y1:"0%",x2:`${Ge*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=it("line",{x1:"0%",y1:`${Ge*e}%`,x2:"100%",y2:`${Ge*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),a=t.x-n,c=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[a,c],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,a=n-this._dragStartPoint[0],c=o-this._dragStartPoint[1],{direction:h}=this._draggingThumb,d=this._calcCropBox(h,[a,c]);d&&(this.$["*cropBox"]=d)}_calcCropBox(i,t){var h,d;let[e,r]=t,n=this.$["*imageBox"],o=(h=this._dragStartCrop)!=null?h:this.$["*cropBox"],a=(d=this.$["*cropPresetList"])==null?void 0:d[0],c=a?a.width/a.height:void 0;if(i===""?o=Ws({rect:o,delta:[e,r],imageBox:n}):o=Xs({rect:o,delta:[e,r],direction:i,aspectRatio:c,imageBox:n}),!Object.values(o).every(p=>Number.isFinite(p)&&p>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return ce(ue(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Gs(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Hs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",B("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=C||i.width<=C,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",B({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};l(Te,"CropFrame");Te.template='';var dt=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=B({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};l(dt,"EditorButtonControl");dt.template=`
{{title}}
`;function Go(s){let i=s+90;return i=i>=360?0:i,i}l(Go,"nextAngle");function qo(s,i){return s==="rotate"?Go(i):["mirror","flip"].includes(s)?!i:null}l(qo,"nextValue");var Zt=class extends dt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=qo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};l(Zt,"EditorCropButtonControl");var ai={FILTER:"filter",COLOR_OPERATION:"color_operation"},pt="original",xe=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?ai.FILTER:ai.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===pt?void 0:this.$.value,filter:this._filter===pt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ht[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===ai.FILTER){let a=n;if(o){let{name:c,amount:h}=o;a=c===this._filter?h:n}this.$.value=a,this.$.defaultValue=a}if(this._controlType===ai.COLOR_OPERATION){let a=typeof o!="undefined"?o:e;this.$.value=a,this.$.defaultValue=a}}apply(){let t;this._controlType===ai.FILTER?this._filter===pt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};l(xe,"EditorSlider");xe.template=``;function ci(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:l(()=>{i.naturalWidth===0&&(i.src=J)},"cancel")}}l(ci,"preloadImage");function hi(s){let i=[];for(let n of s){let o=ci(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:l(()=>{i.forEach(n=>{n.cancel()})},"cancel")}}l(hi,"batchPreloadImages");var It=class extends dt{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,a={...this.$["*editorTransformations"]};return a[this._operation]=this._filter!==pt?{name:this._filter,amount:o}:void 0,O(this._originalUrl,L(Pi,kt(a),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:a,cancel:c}=ci(n);this._cancelPreload=c,a.catch(h=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:h})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{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",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===pt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};l(It,"EditorFilterControl");It.template=`
`;var Jt=class extends dt{constructor(){super(...arguments);u(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ht[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};l(Jt,"EditorOperationControl");var Lr=l((s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}},"throttle");function Ur(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}l(Ur,"pick");function Ee(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return O(s,L(Pi,kt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}l(Ee,"viewerImageSrc");function Ko(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}l(Ko,"validateCrop");var Ae=class extends R{constructor(){super(),this.init$={...this.init$,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=k(this._commit.bind(this),300),this._handleResizeThrottled=Lr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Ur(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=he({width:i.naturalWidth,height:i.naturalHeight},r),a;if(o.width>n.width-t*2||o.height>n.height-t*2){let c=o.width/o.height,h=n.width/n.height;if(c>h){let d=n.width-t*2,p=d/c,f=0+t,g=t+(n.height-t*2)/2-p/2;a={x:f,y:g,width:d,height:p}}else{let d=n.height-t*2,p=d*c,f=t+(n.width-t*2)/2-p/2,g=0+t;a={x:f,y:g,width:p,height:d}}}else{let{width:c,height:h}=o,d=t+(n.width-t*2)/2-c/2,p=t+(n.height-t*2)/2-h/2;a={x:d,y:p,width:c,height:h}}this.$["*imageBox"]=ue(a)}_alignCrop(){var h;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:a,y:c}=this.$["*imageBox"];if(n){let{dimensions:[d,p],coords:[f,g]}=n,{width:m}=he(this._imageSize,r),b=o/m;i=ce(ue({x:a+f*b,y:c+g*b,width:d*b,height:p*b}),this.$["*imageBox"])}if(!n||!qs(i,t)){let d=(h=this.$["*cropPresetList"])==null?void 0:h[0],p=d?d.width/d.height:void 0,f=t.width/t.height,g=t.width,m=t.height;p&&(f>p?g=Math.min(t.height*p,t.width):m=Math.min(t.width/p,t.height)),i={x:t.x+t.width/2-g/2,y:t.y+t.height/2-m/2,width:g,height:m}}this.$["*cropBox"]=ce(ue(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:a}=r,c=he({width:e.width,height:e.height},a);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(a*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-c.width/2,-c.height/2,c.width,c.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=B({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:a,height:c}=he(this._imageSize,r),{width:h,height:d}=i,p=n/a,f=o/c;return[$t(Math.round(h/p),1,a),$t(Math.round(d/f),1,c)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:a,y:c}=t,{width:h,height:d}=he(this._imageSize,r),{x:p,y:f}=i,g=n/h,m=o/d,b=this._getCropDimensions(),S={dimensions:b,coords:[$t(Math.round((p-a)/g),0,h-b[0]),$t(Math.round((f-c)/m),0,d-b[1])]};if(!Ko(S)){console.error("Cropper is trying to create invalid crop object",{payload:S});return}if(!(b[0]===h&&b[1]===d))return S}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),a={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=a}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=B({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(Ee(i,e,t)),{promise:n,cancel:o,image:a}=ci(r),c=this._handleImageLoading(r);return a.addEventListener("load",c,{once:!0}),a.addEventListener("error",c,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>a).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(a)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};l(Ae,"EditorImageCropper");Ae.template=``;function ps(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}l(ps,"linspace");function Yo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}l(Zo,"calculateOpacities");function Jo(s,i){return s.map((t,e)=>tn-o)}l(Rr,"keypointsRange");var ui=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=k(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(Ee(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=l(()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(c=>c.value===e),"shouldSkip");if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let a=this._handleImageLoading(n.src);o.addEventListener("load",a,{once:!0}),o.addEventListener("error",a,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let c=this._keypoints,h=c.findIndex(p=>p.value>e),d=h{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ht[i],r=this._keypoints.map(a=>a.value),n=Zo(r,t,e),o=Jo(r,e);for(let[a,c]of Object.entries(this._keypoints))c.opacity=n[a],c.zIndex=o[a];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(h=>h.src),{images:r,promise:n,cancel:o}=hi(e);r.forEach(h=>{let d=this._handleImageLoading(h.src);h.addEventListener("load",d),h.addEventListener("error",d)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let a=this._operation,c=this._filter;await n,this._isActive&&this._isSame(a,c)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((h,d)=>{let p=r[d];p.classList.add("fader-image"),h.image=p,this._container.appendChild(p)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Rr(e,r).map(c=>this._imageSrc({url:i,filter:t,operation:e,value:c})),{cancel:a}=hi(o);this._cancelBatchPreload=a}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=B({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=B({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let a=this._imageSrc({operation:t,value:e});this._setOriginalSrc(a),this._container&&this._container.remove();return}this._keypoints=Rr(t,e).map(a=>this._constructKeypoint(t,a)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=B({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};l(ui,"EditorImageFader");var Qo=1,$e=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Qo?this.scrollLeft+=e:this.scrollLeft+=t})}};l($e,"EditorScroller");$e.template=" ";function tl(s){return``}l(tl,"renderTabToggle");function el(s){return`
`}l(el,"renderTabContent");var Se=class extends R{constructor(){super();u(this,"_updateInfoTooltip",k(()=>{var o,a;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===V.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let c=((a=t==null?void 0:t.filter)==null?void 0:a.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+c}else r=this.l10n(pt);else if(this.$["*tabId"]===V.TUNING&&e){n=!0;let c=(t==null?void 0:t[e])||ht[e].zero;r=e+" "+c}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":pt,"*currentOperation":null,"*tabId":V.CROP,showLoader:!1,filters:pr,colorOperations:dr,cropOperations:fr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=k(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===V.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new Jt;return e.operation=t,e}_createFilterControl(t){let e=new It;return e.filter=t,e}_createToggleControl(t){let e=new Zt;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===V.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===V.FILTERS?[pt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===V.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===V.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of q){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Ee(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=hi([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1,this.$["*tabId"]=t[0];for(let e of q){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}}),this._updateInfoTooltip()}};l(Se,"EditorToolbar");Se.template=`
{{*operationTooltip}}
${q.map(el).join("")}
${q.map(tl).join("")}
`;var Qt=class extends y{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return B("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};l(Qt,"LrBtnUi");Qt.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Qt.template=`
{{text}}
`;var ke=class extends y{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};l(ke,"LineLoaderUi");ke.template=`
`;var Di={transition:"transition",visible:"visible",hidden:"hidden"},Ie=class extends y{constructor(){super(),this._visible=!1,this._visibleStyle=Di.visible,this._hiddenStyle=Di.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Sr(this,{[Di.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(Di.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};l(Ie,"PresenceToggle");Ie.template=" ";var Oe=class extends y{constructor(){super();u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let a=document.createDocumentFragment(),c=document.createElement("div"),h=document.createElement("div");c.className="minor-step",h.className="border-step",a.appendChild(h);for(let p=0;p
`;var di=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.CLOUD_IMG_EDIT);u(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new rt,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};l(di,"CloudImageEditorActivity");var il=l(function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},"escapeRegExp"),Pr=l(function(s,i="i"){let t=s.split("*").map(il);return new RegExp("^"+t.join(".+")+"$",i)},"wildcardRegexp");var sl=l(s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,a)=>{let c=r[a];return o+`${a}: ${c};`},"");return t+`${e}{${n}}`},""),"styleToCss");function Mr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return sl({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}l(Mr,"buildStyles");var Ot={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in Ot){let t=Ot[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Nr=l(function(s,i,t){s in Ot||(Ot[s]=[]),Ot[s].push([i,t])},"registerMessage"),Dr=l(function(s,i){s in Ot&&(Ot[s]=Ot[s].filter(t=>t[0]!==i))},"unregisterMessage");function Fr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}l(Fr,"queryString");var Le=class extends v{constructor(){super();u(this,"activityType",_.activities.EXTERNAL);u(this,"_iframe",null);u(this,"updateCssData",l(()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())},"updateCssData"));u(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=D(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Pr(r);for(let[o,a]of Object.entries(t.alternatives))if(n.test(o))return a}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Mr(t)})}remoteUrl(){var a,c;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((c=(a=this.getCssData("--l10n-locale-name"))==null?void 0:a.split("-"))==null?void 0:c[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Fr(n),o.toString()}mountIframe(){let t=ze({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Nr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Dr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};l(Le,"ExternalSource");Le.template=`
{{activityCaption}}
{{counter}}
`;var te=class extends y{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;D(i).forEach(e=>{let r=ze({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};l(te,"Tabs");te.bindAttributes({"tab-list":null,default:null});te.template=`
`;var Lt=class extends v{constructor(){super(...arguments);u(this,"processInnerHtml",!0);u(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Lt.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Ns(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};l(Lt,"DataOutput");Lt.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var pi=class extends _{};l(pi,"ActivityHeader");var Ue=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};l(Ue,"Select");Ue.template=``;var Y={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Vr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Q=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,src:"",ppIcon:Y.PLAY,fsIcon:Y.FS_ON,volIcon:Y.VOL_ON,capIcon:Y.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Vr.exitFullscreen():Vr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===Y.CAP_OFF?(this.$.capIcon=Y.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Q.is+":captions","1")):(this.$.capIcon=Y.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Q.is+":captions"))}toggleSound(){this.$.volIcon===Y.VOL_ON?(this.$.volIcon=Y.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=Y.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Q.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Q.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=Y.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=Y.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=Y.FS_OFF:this.$.fsIcon=Y.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Q.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};l(Q,"Video");Q.template=`
{{currentTime}} / {{totalTime}}
`;Q.bindAttributes({video:"video",src:"src"});var rl="css-src";function fi(s){return class extends s{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(rl);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}l(fi,"shadowed");var ee=class extends fi(y){};l(ee,"ShadowWrapper");var Re=class extends y{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};l(Re,"Copyright"),u(Re,"template",`Powered by Uploadcare`);var Tt=class extends ee{constructor(){super(...arguments);u(this,"init$",ki(this));u(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};l(Tt,"SolutionBlock");var Pe=class extends Tt{};l(Pe,"FileUploaderRegular");Pe.template=``;var Me=class extends Tt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=_.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||_.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};l(Me,"FileUploaderMinimal");Me.template=``;var Ne=class extends Tt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||_.activities.START_FROM)&&(this.$["*currentActivity"]=_.activities.UPLOAD_LIST)})}};l(Ne,"FileUploaderInline");Ne.template=``;var mi=class extends fi(rt){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};l(mi,"CloudImageEditor");function Fi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}l(Fi,"registerBlocks");var fs="LR";async function Br(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[fs]){t(window[fs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[fs];i&&Fi(n),t(n)},document.head.appendChild(r)})}l(Br,"connectBlocksFrom");return Kr(nl);})(); \ No newline at end of file +`,"\\n"),i=pn(i),i=se+i+se);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}l(fn,"parseCssPropertyValue");var gs=0,ie=null,_t=null,xt=l(class extends HTMLElement{constructor(){super(),ji(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return xt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(w.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=l(()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()},"addFr");if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Be.generate(),this.style.setProperty(w.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(w.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=A.registerCtx({},this)),this.__localCtx}get nodeCtx(){return A.getCtx(this.ctxName,!1)||A.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(w.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(w.EXT_DATA_CTX_PRFX,"");else if(s.includes(w.NAMED_DATA_CTX_SPLTR)){let r=s.split(w.NAMED_DATA_CTX_SPLTR);t=A.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=l(n=>{this.isConnected&&i(n)},"subCb"),r=xt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=xt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=xt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=xt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=xt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=xt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(w.CTX_OWNER_ATTR)&&this.getAttribute(w.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(w.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(w.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(w.NAMED_DATA_CTX_SPLTR)){let t=i.split(w.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=A.getCtx(e,!1);n||(n=A.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(w.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[w.SET_LATER_KEY]){for(let t in this[w.SET_LATER_KEY])bs(this,t,this[w.SET_LATER_KEY][t]);delete this[w.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of cn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${w.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(w.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);_t==null||_t.delete(this.updateCssData),_t!=null&&_t.size||(ie==null||ie.disconnect(),ie=null,_t=null)},100)))}static reg(s,i=!1){s||(gs++,s=`${w.AUTO_TAG_PRFX}-${gs}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=fn(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){_t||(_t=new Set),_t.add(this.updateCssData),ie||(ie=new MutationObserver(s=>{s[0].type==="attributes"&&_t.forEach(i=>{i()})}),ie.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},"_BaseComponent"),Pt=xt;ji(Pt,"template");var zi=l(class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(zi.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=A.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),zi.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}},"AppRouter");zi.appMap=Object.create(null);function mn(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}l(mn,"applyStyles");function gn(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}l(gn,"applyAttributes");function ze(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&gn(i,s.attributes),s.styles&&mn(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=ze(t);i.appendChild(e)}),i}l(ze,"create");var ys="idb-store-ready",_n="symbiote-db",bn="symbiote-idb-update_",yn=l(class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ys,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return bn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,a)=>{n.onsuccess=c=>{t||this._notifySubscribers(s),o(c.target.result)},n.onerror=c=>{a(c)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,vs.clear(this.name)}},"DbInstance"),vs=l(class{static get readyEventName(){return ys}static open(s=_n,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new yn(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}},"IDB");ji(vs,"_reg",Object.create(null));function k(s,i){let t,e=l((...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)},"debounced");return e.cancel=()=>{clearTimeout(t)},e}l(k,"debounce");var vn="--uploadcare-blocks-window-height",yi="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Hi(){return typeof window[yi]=="undefined"?!1:!!window[yi]}l(Hi,"getIsWindowHeightTracked");function Cs(){if(Hi())return;let s=l(()=>{document.documentElement.style.setProperty(vn,`${window.innerHeight}px`),window[yi]=!0},"callback"),i=k(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[yi]=!1,window.removeEventListener("resize",i)}}l(Cs,"createWindowHeightTracker");var Cn=l(s=>s,"DEFAULT_TRANSFORMER"),Wi="{{",Ts="}}",ws="plural:";function je(s,i,t={}){var o;let{openToken:e=Wi,closeToken:r=Ts,transform:n=Cn}=t;for(let a in i){let c=(o=i[a])==null?void 0:o.toString();s=s.replaceAll(e+a+r,typeof c=="string"?n(c):c)}return s}l(je,"applyTemplateData");function xs(s){let i=[],t=s.indexOf(Wi);for(;t!==-1;){let e=s.indexOf(Ts,t),r=s.substring(t+2,e);if(r.startsWith(ws)){let n=s.substring(t+2,e).replace(ws,""),o=n.substring(0,n.indexOf("(")),a=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:a})}t=s.indexOf(Wi,e)}return i}l(xs,"getPluralObjects");function Es(s){return Object.prototype.toString.call(s)==="[object Object]"}l(Es,"isObject");var wn=/\W|_/g;function Tn(s){return s.split(wn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}l(Tn,"camelizeString");function As(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>Ct(t,{ignoreKeys:i})):s}l(As,"camelizeArrayItems");function Ct(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return As(s,{ignoreKeys:i});if(!Es(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Es(r)?r=Ct(r,{ignoreKeys:i}):Array.isArray(r)&&(r=As(r,{ignoreKeys:i})),t[Tn(e)]=r}return t}l(Ct,"camelizeKeys");var xn=l(s=>new Promise(i=>setTimeout(i,s)),"delay");function Ki({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),a=[n,r].filter(Boolean).join("; ");return`${o} (${a})`}l(Ki,"getUserAgent$1");var En={factor:2,time:100};function An(s,i=En){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l(a=>xn(a!=null?a:n).then(()=>(t+=1,e(r))),"retry")})}return l(e,"runAttempt"),e(s)}l(An,"retrier");var Dt=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Dt.prototype),this.originalProgressEvent=t}};l(Dt,"UploadcareNetworkError");var xi=l((s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},"onCancel"),bt=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,bt.prototype)}};l(bt,"CancelError");var $n=500,Ss=l(({check:s,interval:i=$n,timeout:t,signal:e})=>new Promise((r,n)=>{let o,a;xi(e,()=>{o&&clearTimeout(o),n(new bt("Poll cancelled"))}),t&&(a=setTimeout(()=>{o&&clearTimeout(o),n(new bt("Timed out"))},t));let c=l(()=>{try{Promise.resolve(s(e)).then(h=>{h?(a&&clearTimeout(a),r(h)):o=setTimeout(c,i)}).catch(h=>{a&&clearTimeout(a),n(h)})}catch(h){a&&clearTimeout(a),n(h)}},"tick");o=setTimeout(c,0)}),"poll"),E={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Ei="application/octet-stream",ks="original",Et=l(({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,a)=>{let c=new XMLHttpRequest,h=(s==null?void 0:s.toUpperCase())||"GET",d=!1;c.open(h,i,!0),e&&Object.entries(e).forEach(p=>{let[f,g]=p;typeof g!="undefined"&&!Array.isArray(g)&&c.setRequestHeader(f,g)}),c.responseType="text",xi(r,()=>{d=!0,c.abort(),a(new bt)}),c.onload=()=>{if(c.status!=200)a(new Error(`Error ${c.status}: ${c.statusText}`));else{let p={method:h,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},f=c.getAllResponseHeaders().trim().split(/[\r\n]+/),g={};f.forEach(function(S){let $=S.split(": "),x=$.shift(),T=$.join(": ");x&&typeof x!="undefined"&&(g[x]=T)});let m=c.response,b=c.status;o({request:p,data:m,headers:g,status:b})}},c.onerror=p=>{d||a(new Dt(p))},n&&typeof n=="function"&&(c.upload.onprogress=p=>{p.lengthComputable?n({isComputable:!0,value:p.loaded/p.total}):n({isComputable:!1})}),t?c.send(t):c.send()}),"request");function Sn(s,...i){return s}l(Sn,"identity");var kn=l(({name:s})=>s?[s]:[],"getFileOptions"),In=Sn,On=l(()=>new FormData,"getFormData"),Is=l(s=>!1,"isBuffer"),Ai=l(s=>typeof Blob!="undefined"&&s instanceof Blob,"isBlob"),$i=l(s=>typeof File!="undefined"&&s instanceof File,"isFile"),Si=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string","isReactNativeAsset"),We=l(s=>Ai(s)||$i(s)||Is()||Si(s),"isFileData"),Ln=l(s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined","isSimpleValue"),Un=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s),"isObjectValue"),Rn=l(s=>!!s&&typeof s=="object"&&"data"in s&&We(s.data),"isFileValue");function Pn(s,i,t){if(Rn(t)){let{name:e,contentType:r}=t,n=In(t.data,e,r!=null?r:Ei),o=kn({name:e,contentType:r});s.push([i,n,...o])}else if(Un(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else Ln(t)&&t&&s.push([i,t.toString()])}l(Pn,"collectParams");function Mn(s){let i=[];for(let[t,e]of Object.entries(s))Pn(i,t,e);return i}l(Mn,"getFormDataParams");function Yi(s){let i=On(),t=Mn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}l(Yi,"buildFormData");var P=class extends Error{constructor(t,e,r,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}};l(P,"UploadClientError");var Nn=l(s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},"buildSearchParams"),vt=l((s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=Nn(t)),e.toString()},"getUrl"),Dn="6.6.1",Fn="UploadcareUploadClient",Vn=Dn;function Ft(s){return Ki({libraryName:Fn,libraryVersion:Vn,...s})}l(Ft,"getUserAgent");var Bn="RequestThrottledError",$s=15e3,zn=1e3;function jn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return $s;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:$s}l(jn,"getTimeoutFromThrottledRequest");function At(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return An(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Bn&&r{let i="";return(Ai(s)||$i(s)||Si(s))&&(i=s.type),i||Ei},"getContentType"),Ls=l(s=>{let i="";return $i(s)&&s.name?i=s.name:Ai(s)||Is()?i="":Si(s)&&s.name&&(i=s.name),i||ks},"getFileName");function Zi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}l(Zi,"getStoreValue");function Hn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=E.baseURL,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=E.retryNetworkErrorMaxTimes,metadata:b}){return At(()=>Et({method:"POST",url:vt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:p,userAgent:f})},data:Yi({file:{data:s,name:t||Ls(s),contentType:e||Os(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Zi(a),signature:n,expire:o,source:d,metadata:b}),signal:c,onProgress:h}).then(({data:S,headers:$,request:x})=>{let T=Ct(JSON.parse(S));if("error"in T)throw new P(T.error.content,T.error.errorCode,x,T,$);return T}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(Hn,"base");var qi;(function(s){s.Token="token",s.FileInfo="file_info"})(qi||(qi={}));function Wn(s,{publicKey:i,baseURL:t=E.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,source:h="url",signal:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=E.retryNetworkErrorMaxTimes,metadata:b}){return At(()=>Et({method:"POST",headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:p,userAgent:f})},url:vt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Zi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:a,expire:c,source:h,metadata:b}),signal:d}).then(({data:S,headers:$,request:x})=>{let T=Ct(JSON.parse(S));if("error"in T)throw new P(T.error.content,T.error.errorCode,x,T,$);return T}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(Wn,"fromUrl");var G;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(G||(G={}));var Xn=l(s=>"status"in s&&s.status===G.Error,"isErrorResponse");function Gn(s,{publicKey:i,baseURL:t=E.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=E.retryNetworkErrorMaxTimes}={}){return At(()=>Et({method:"GET",headers:i?{"X-UC-User-Agent":Ft({publicKey:i,integration:r,userAgent:n})}:void 0,url:vt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:c,headers:h,request:d})=>{let p=Ct(JSON.parse(c));if("error"in p&&!Xn(p))throw new P(p.error.content,void 0,d,p,h);return p}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:o})}l(Gn,"fromUrlStatus");function qn(s,{publicKey:i,baseURL:t=E.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:a,integration:c,userAgent:h,retryThrottledRequestMaxTimes:d=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=E.retryNetworkErrorMaxTimes}){return At(()=>Et({method:"POST",headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:c,userAgent:h})},url:vt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:a}),signal:o}).then(({data:f,headers:g,request:m})=>{let b=Ct(JSON.parse(f));if("error"in b)throw new P(b.error.content,b.error.errorCode,m,b,g);return b}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:d})}l(qn,"group");function Us(s,{publicKey:i,baseURL:t=E.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=E.retryNetworkErrorMaxTimes}){return At(()=>Et({method:"GET",headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:n,userAgent:o})},url:vt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:h,headers:d,request:p})=>{let f=Ct(JSON.parse(h));if("error"in f)throw new P(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Us,"info");function Kn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=E.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:a,store:c,signal:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=E.retryNetworkErrorMaxTimes,metadata:b}){return At(()=>Et({method:"POST",url:vt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:p,userAgent:f})},data:Yi({filename:e||ks,size:s,content_type:t||Ei,part_size:r,UPLOADCARE_STORE:Zi(c),UPLOADCARE_PUB_KEY:i,signature:o,expire:a,source:d,metadata:b}),signal:h}).then(({data:S,headers:$,request:x})=>{let T=Ct(JSON.parse(S));if("error"in T)throw new P(T.error.content,T.error.errorCode,x,T,$);return T.parts=Object.keys(T.parts).map(W=>T.parts[W]),T}),{retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})}l(Kn,"multipartStart");function Yn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=E.retryNetworkErrorMaxTimes}){return At(()=>Et({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Ei}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}l(Yn,"multipartUpload");function Zn(s,{publicKey:i,baseURL:t=E.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=E.retryNetworkErrorMaxTimes}){return At(()=>Et({method:"POST",url:vt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ft({publicKey:i,integration:n,userAgent:o})},data:Yi({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:h,headers:d,request:p})=>{let f=Ct(JSON.parse(h));if("error"in f)throw new P(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Zn,"multipartComplete");function Ji({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a,signal:c,onProgress:h}){return Ss({check:d=>Us(s,{publicKey:i,baseURL:t,signal:d,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a}).then(p=>p.isReady?p:(h&&h({isComputable:!0,value:1}),!1)),signal:c})}l(Ji,"isReadyPoll");var yt=class{constructor(i,{baseCDN:t=E.baseCDN,fileName:e}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=vt(t,`${r}/`),a=n?vt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=a}};l(yt,"UploadcareFile");var Jn=l((s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:S})=>Hn(s,{publicKey:i,fileName:t,contentType:a,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:S}).then(({file:$})=>Ji({file:$,publicKey:i,baseURL:e,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then($=>new yt($,{baseCDN:b})),"uploadDirect"),Qn=l((s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d,baseCDN:p})=>Us(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d}).then(f=>new yt(f,{baseCDN:p,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),"uploadFromUploaded"),to=l((s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=l(o=>()=>{e=o,r.forEach((a,c)=>c!==o&&a.abort())},"createStopRaceCallback");return xi(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,a)=>{let c=n(a);return Promise.resolve().then(()=>o({stopRace:c,signal:r[a].signal})).then(h=>(c(),h)).catch(h=>(t=h,null))})).then(o=>{if(e===null)throw t;return o[e]})},"race"),eo=window.WebSocket,vi=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}};l(vi,"Events");var io=l((s,i)=>s==="success"?{status:G.Success,...i}:s==="progress"?{status:G.Progress,...i}:{status:G.Error,...i},"response"),Ci=class{constructor(i,t=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new vi);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new eo(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,io(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=l(()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1},"actualDisconect");this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}};l(Ci,"Pusher");var Xi=null,Qi=l(s=>{if(!Xi){let i=typeof window=="undefined"?0:3e4;Xi=new Ci(s,i)}return Xi},"getPusher"),so=l(s=>{Qi(s).connect()},"preconnect");function ro({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:a,signal:c}){return Ss({check:h=>Gn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:h}).then(d=>{switch(d.status){case G.Error:return new P(d.error,d.errorCode);case G.Waiting:return!1;case G.Unknown:return new P(`Token "${s}" was not found.`);case G.Progress:return a&&(d.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:d.done/d.total})),!1;case G.Success:return a&&a({isComputable:!0,value:d.done/d.total}),d;default:throw new Error("Unknown status")}}),signal:c})}l(ro,"pollStrategy");var no=l(({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Qi(i),a=o.onError(n),c=l(()=>{a(),o.unsubscribe(s)},"destroy");xi(t,()=>{c(),n(new bt("pusher cancelled"))}),o.subscribe(s,h=>{switch(h.status){case G.Progress:{e&&(h.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:h.done/h.total}));break}case G.Success:{c(),e&&e({isComputable:!0,value:h.done/h.total}),r(h);break}case G.Error:c(),n(new P(h.msg,h.error_code))}})}),"pushStrategy"),oo=l((s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,onProgress:p,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,pusherKey:S=E.pusherKey,metadata:$})=>Promise.resolve(so(S)).then(()=>Wn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,metadata:$})).catch(x=>{let T=Qi(S);return T==null||T.disconnect(),Promise.reject(x)}).then(x=>x.type===qi.FileInfo?x:to([({signal:T})=>ro({token:x.token,publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:p,signal:T}),({signal:T})=>no({token:x.token,pusherKey:S,signal:T,onProgress:p})],{signal:d})).then(x=>{if(x instanceof P)throw x;return x}).then(x=>Ji({file:x.uuid,publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:p,signal:d})).then(x=>new yt(x,{baseCDN:r})),"uploadFromUrl"),Gi=new WeakMap,lo=l(async s=>{if(Gi.has(s))return Gi.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Gi.set(s,i),i},"getBlobFromReactNativeAsset"),Rs=l(async s=>{if($i(s)||Ai(s))return s.size;if(Si(s))return(await lo(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},"getFileSize"),ao=l((s,i=E.multipartMinFileSize)=>s>=i,"isMultipart"),Ps=l(s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!We(s)&&t.test(s)},"isUuid"),Ms=l(s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!We(s)&&t.test(s)},"isUrl"),co=l((s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,a=[...i],c=l(()=>{let h=i.length-a.length,d=a.shift();d&&d().then(p=>{n||(r[h]=p,o-=1,o?c():t(r))}).catch(p=>{n=!0,e(p)})},"run");for(let h=0;h{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},"sliceChunk"),uo=l(async(s,i,t)=>e=>ho(s,e,i,t),"prepareChunks"),po=l((s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})=>Yn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c}),"uploadPart"),fo=l(async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,contentType:b,multipartChunkSize:S=E.multipartChunkSize,maxConcurrentRequests:$=E.maxConcurrentRequests,baseCDN:x,metadata:T})=>{let W=e!=null?e:await Rs(s),ft,Ut=l((N,tt)=>{if(!h)return;ft||(ft=Array(N).fill(0));let mt=l(X=>X.reduce((gt,Vi)=>gt+Vi,0),"sum");return X=>{X.isComputable&&(ft[tt]=X.value,h({isComputable:!0,value:mt(ft)/N}))}},"createProgressHandler");return b||(b=Os(s)),Kn(W,{publicKey:i,contentType:b,fileName:t||Ls(s),baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:T}).then(async({uuid:N,parts:tt})=>{let mt=await uo(s,W,S);return Promise.all([N,co($,tt.map((X,gt)=>()=>po(mt(gt),X,{publicKey:i,contentType:b,onProgress:Ut(tt.length,gt),signal:c,integration:p,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})))])}).then(([N])=>Zn(N,{publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})).then(N=>N.isReady?N:Ji({file:N.uuid,publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then(N=>new yt(N,{baseCDN:x}))},"uploadMultipart");async function ts(s,{publicKey:i,fileName:t,baseURL:e=E.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartMinFileSize:b,multipartChunkSize:S,maxConcurrentRequests:$,baseCDN:x=E.baseCDN,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:W,pusherKey:ft,metadata:Ut}){if(We(s)){let N=await Rs(s);return ao(N,b)?fo(s,{publicKey:i,contentType:m,multipartChunkSize:S,fileSize:N,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,maxConcurrentRequests:$,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x,metadata:Ut}):Jn(s,{publicKey:i,fileName:t,contentType:m,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x,metadata:Ut})}if(Ms(s))return oo(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:x,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:W,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,pusherKey:ft,metadata:Ut});if(Ps(s))return Qn(s,{publicKey:i,fileName:t,baseURL:e,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:x});throw new TypeError(`File uploading from "${s}" is not supported`)}l(ts,"uploadFile");var wi=class{constructor(i,t){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}};l(wi,"UploadcareGroup");var mo=l(s=>{for(let i of s)if(!We(i))return!1;return!0},"isFileDataArray"),go=l(s=>{for(let i of s)if(!Ps(i))return!1;return!0},"isUuidArray"),_o=l(s=>{for(let i of s)if(!Ms(i))return!1;return!0},"isUrlArray");function Ns(s,{publicKey:i,fileName:t,baseURL:e=E.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:b=E.multipartChunkSize,baseCDN:S=E.baseCDN,checkForUrlDuplicates:$,saveUrlForRecurrentUploads:x,jsonpCallback:T}){if(!mo(s)&&!_o(s)&&!go(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let W,ft=!0,Ut=s.length,N=l((tt,mt)=>{if(!c)return;W||(W=Array(tt).fill(0));let X=l(gt=>gt.reduce((Vi,zr)=>Vi+zr)/tt,"normalize");return gt=>{if(!gt.isComputable||!ft){ft=!1,c({isComputable:!1});return}W[mt]=gt.value,c({isComputable:!0,value:X(W)})}},"createProgressHandler");return Promise.all(s.map((tt,mt)=>ts(tt,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:N(Ut,mt),source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:b,baseCDN:S,checkForUrlDuplicates:$,saveUrlForRecurrentUploads:x}))).then(tt=>{let mt=tt.map(X=>X.uuid);return qn(mt,{publicKey:i,baseURL:e,jsonpCallback:T,secureSignature:r,secureExpire:n,signal:a,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g}).then(X=>new wi(X,tt)).then(X=>(c&&c({isComputable:!0,value:1}),X))})}l(Ns,"uploadFileGroup");var Mt,re,Nt,ne,oe,le,Ti,He=class{constructor(i){Rt(this,le);Rt(this,Mt,1);Rt(this,re,[]);Rt(this,Nt,0);Rt(this,ne,new WeakMap);Rt(this,oe,new WeakMap);Fe(this,Mt,i)}add(i){return new Promise((t,e)=>{z(this,ne).set(i,t),z(this,oe).set(i,e),z(this,re).push(i),gi(this,le,Ti).call(this)})}get pending(){return z(this,re).length}get running(){return z(this,Nt)}set concurrency(i){Fe(this,Mt,i),gi(this,le,Ti).call(this)}get concurrency(){return z(this,Mt)}};l(He,"Queue"),Mt=new WeakMap,re=new WeakMap,Nt=new WeakMap,ne=new WeakMap,oe=new WeakMap,le=new WeakSet,Ti=l(function(){let i=z(this,Mt)-z(this,Nt);for(let t=0;t{z(this,ne).delete(e),z(this,oe).delete(e),Fe(this,Nt,z(this,Nt)-1),gi(this,le,Ti).call(this)}).then(o=>r(o)).catch(o=>n(o))}},"#run");var es=l(()=>({"*blocksRegistry":new Set}),"blockCtx"),is=l(s=>({...es(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),"activityBlockCtx"),ki=l(s=>({...is(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new He(1)}),"uploaderBlockCtx");function Ds(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}l(Ds,"l10nProcessor");var et=l(s=>`*cfg/${s}`,"sharedConfigKey");var ot=l(s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")},"toKebabCase");var Fs=new Set;function Ii(s){Fs.has(s)||(Fs.add(s),console.warn(s))}l(Ii,"warnOnce");var Oi=l((s,i)=>new Intl.PluralRules(s).select(i),"getPluralForm");var ss="lr-",y=class extends Pt{constructor(){super();u(this,"allowCustomTemplate",!0);u(this,"init$",es());u(this,"updateCtxCssData",l(()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()},"updateCtxCssData"));this.activityType=null,this.addTemplateProcessor(Ds),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=xs(r);for(let a of n)e[a.variable]=this.pluralize(a.pluralKey,Number(e[a.countVariable]));return je(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Oi(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${ss}${t}`,!0),Hi()||(this._destroyInnerHeightTracker=Cs()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=l(h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h,"getUnit");if(t===0)return`0 ${n(r[0])}`;let o=1024,a=e<0?0:e,c=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**c).toFixed(a))+" "+n(r[c])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?je(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=et(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Ii("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ot(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(et(t));r.ctx.has(r.name)?this.sub(et(t),e):(this.bindCssData(`--cfg-${ot(t)}`),this.sub(`--cfg-${ot(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(ss)?t:ss+t)}};l(y,"Block"),u(y,"StateConsumerScope",null),u(y,"className","");var Vt=class extends y{constructor(){super();u(this,"_handleBackdropClick",l(()=>{this._closeDialog()},"_handleBackdropClick"));u(this,"_closeDialog",l(()=>{this.setOrAddState("*modalActive",!1)},"_closeDialog"));u(this,"_handleDialogClose",l(()=>{this._closeDialog()},"_handleDialogClose"));u(this,"_handleDialogPointerUp",l(t=>{t.target===this.ref.dialog&&this._closeDialog()},"_handleDialogPointerUp"));this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}};l(Vt,"Modal"),u(Vt,"StateConsumerScope","modal");Vt.template=``;var Vs="active",Xe="___ACTIVITY_IS_ACTIVE___",lt=class extends y{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",is(this));u(this,"_debouncedHistoryFlush",k(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=lt._activityRegistry[this.activityKey];this[Xe]=!1,this.removeAttribute(Vs),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=lt._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[Xe]=!0,this.setAttribute(Vs,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[Xe]?this._deactivate():this.activityType===t&&!this[Xe]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!lt._activityRegistry[this.activityKey]}get isActivityActive(){return this[Xe]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;lt._activityRegistry||(lt._activityRegistry=Object.create(null)),lt._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),lt._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(lt._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setOrAddState("*modalActive",!1)}}},_=lt;l(_,"ActivityBlock"),u(_,"_activityRegistry",Object.create(null));_.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var Ge=33.333333333333336,C=1,rs=24,Bs=6;function Bt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}l(Bt,"setSvgNodeAttrs");function it(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Bt(t,i),t}l(it,"createSvgNode");function zs(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=i.includes("w")?0:1,c=i.includes("n")?0:1,h=[-1,1][a],d=[-1,1][c],p=[e+a*n+1.5*h,r+c*o+1.5*d-24*t*d],f=[e+a*n+1.5*h,r+c*o+1.5*d],g=[e+a*n-24*t*h+1.5*h,r+c*o+1.5*d];return{d:`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]} L ${g[0]} ${g[1]}`,center:f}}l(zs,"cornerPath");function js(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=["n","s"].includes(i)?.5:{w:0,e:1}[i],c=["w","e"].includes(i)?.5:{n:0,s:1}[i],h=[-1,1][a],d=[-1,1][c],p,f;["n","s"].includes(i)?(p=[e+a*n-34*t/2,r+c*o+1.5*d],f=[e+a*n+34*t/2,r+c*o+1.5*d]):(p=[e+a*n+1.5*h,r+c*o-34*t/2],f=[e+a*n+1.5*h,r+c*o+34*t/2]);let g=`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]}`,m=[f[0]-(f[0]-p[0])/2,f[1]-(f[1]-p[1])/2];return{d:g,center:m}}l(js,"sidePath");function Hs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}l(Hs,"thumbCursor");function Ws({rect:s,delta:[i,t],imageBox:e}){return ce({...s,x:s.x+i,y:s.y+t},e)}l(Ws,"moveRect");function ce(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}l(ce,"constraintRect");function bo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:a}=s;n+=r,a-=r,t&&(o=a*t);let c=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,a=s.y+s.height-n,t&&(o=a*t,c=s.x+s.width/2-o/2)),c<=e.x&&(c=e.x,n=s.y+s.height-a),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y+s.height-a),a=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x+s.width-o),a=e.y+e.height&&(a=e.y+e.height-n,t&&(o=a*t),c=s.x+s.width/2-o/2),c<=e.x&&(c=e.x,n=s.y),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y),a=e.x+e.width&&(o=e.x+e.width-n,t&&(a=o/t),c=s.y+s.height/2-a/2),c<=e.y&&(c=e.y,n=s.x),c+a>=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x),at?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x+s.width-c,a=e.y)):t&&(r=h*t-c,c=c+r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y+s.height-h)),he.x+e.width&&(r=e.x+e.width-o-c),a+nt?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x,a=e.y)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y+s.height-h)),he.y+e.height&&(n=e.y+e.height-a-h),o+=r,c-=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x+s.width-c,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y)),he.x+e.width&&(r=e.x+e.width-o-c),a+h+n>e.y+e.height&&(n=e.y+e.height-a-h),c+=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y)),h=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}l(qs,"isRectInsideRect");function he({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}l(he,"rotateSize");function Ks(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),a=Math.round((i-n)/2);return o+r>s&&(r=s-o),a+n>i&&(n=i-a),{x:o,y:a,width:r,height:n}}l(Ks,"calculateMaxCenteredCropFrame");function ue(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}l(ue,"roundRect");function $t(s,i,t){return Math.min(Math.max(s,i),t)}l($t,"clamp");var Ui=l(s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]},"parseCropPreset");var st=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var ns="blocks",os="0.27.1";function Ys(s){return Ki({...s,libraryName:ns,libraryVersion:os})}l(Ys,"customUserAgent");var Zs=l(s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},"normalizeCdnOperation"),Ri=l((...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Zs(i)).join("/-/"),"joinCdnOperations"),L=l((...s)=>{let i=Ri(...s);return i?`-/${i}/`:""},"createCdnUrlModifiers");function Js(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}l(Js,"extractFilename");function Qs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}l(Qs,"extractUuid");function tr(s){let i=er(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Zs(n))}l(tr,"extractOperations");function er(s){let i=new URL(s),t=Js(s),e=ir(t)?sr(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}l(er,"trimFilename");function ir(s){return s.startsWith("http")}l(ir,"isFileUrl");function sr(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}l(sr,"splitFileUrl");var O=l((s,i,t)=>{let e=new URL(er(s));if(t=t||Js(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),ir(t)){let r=sr(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},"createCdnUrl"),St=l((s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()},"createOriginalUrl");var D=l((s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0),"stringToArray");var qe=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],ls=l(s=>s?s.filter(i=>typeof i=="string").map(i=>D(i)).flat():[],"mergeFileTypes"),as=l((s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),"matchMimeType"),rr=l((s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),"matchExtension"),Ke=l(s=>{let i=s==null?void 0:s.type;return i?as(i,qe):!1},"fileIsImage");var ct=1e3,zt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),Ye=l(s=>Math.ceil(s*100)/100,"round"),nr=l((s,i=zt.AUTO)=>{let t=i===zt.AUTO;if(i===zt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))},"dispatch");if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};l(U,"EventManager"),u(U,"_timeoutStore",Object.create(null));var or="[Typed State] Wrong property name: ",Ao="[Typed State] Wrong property type: ",Ze=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||Be.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=A.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(or+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(Ao+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(or+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){A.deleteCtx(this.__ctxId)}};l(Ze,"TypedData");var Je=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Be.generate(),this.__data=A.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Ze(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){A.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};l(Je,"TypedCollection");var lr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:yt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var ar=l(s=>s?s.split(",").map(i=>i.trim()):[],"deserealizeCsv"),jt=l(s=>s?s.join(","):"","serializeCsv");var v=class extends _{constructor(){super(...arguments);u(this,"couldBeUploadCollectionOwner",!1);u(this,"isUploadCollectionOwner",!1);u(this,"init$",ki(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",k(this._runValidators.bind(this),100));u(this,"_handleCollectionUpdate",l(t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(c=>!c.getValue("uploadError"));o.forEach(c=>{n+=e.readProp(c,"uploadProgress")});let a=Math.round(n/o.length);this.$["*commonProgress"]=a,U.emit(new F({type:M.UPLOAD_PROGRESS,ctx:this.ctxName,data:a}),void 0,a===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(a=>!!a.getValue("fileInfo")),o=e.findItems(a=>!!a.getValue("uploadError")||!!a.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let a=this.getOutputData(c=>!!c.getValue("fileInfo")&&!c.getValue("silentUpload"));a.length>0&&U.emit(new F({type:M.UPLOAD_FINISH,ctx:this.ctxName,data:a}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{U.emit(new F({type:M.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{U.emit(new F({type:M.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{U.emit(new F({type:M.CDN_MODIFICATION,ctx:this.ctxName,data:A.getCtx(o).store}),void 0,!1)})},"_handleCollectionUpdate"))}setUploadMetadata(t){Ii("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Je({typedSchema:lr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=l(()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1),"hasUploadCollectionOwner");this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let a of n)(o=a==null?void 0:a.getValue("abortController"))==null||o.abort(),a==null||a.setValue("abortController",null),URL.revokeObjectURL(a==null?void 0:a.getValue("thumbUrl"));this.$["*uploadList"]=e.map(a=>({uid:a}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:st.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:st.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:Ke(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:st.API,fullPath:o})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:Ke(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=jt(ls([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?qe:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=jt(qe)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:st.LOCAL})),this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=D(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":_.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":_.activities.START_FROM}),this.setOrAddState("*modalActive",!0);U.emit(new F({type:M.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),U.emit(new F({type:M.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=ls([...e?qe:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),a=t.getValue("fileName");if(!o||!a)return;let c=as(o,n),h=rr(a,n);if(!c&&!h)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:nr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Ui(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:a,height:c}=o.imageInfo,h=e.width/e.height,d=Ks(a,c,h),p=L(`crop/${d.width}x${d.height}/${d.x},${d.y}`);n.setMultipleValues({cdnUrlModifiers:p,cdnUrl:O(n.getValue("cdnUrl"),p)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===_.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Ys,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=A.getCtx(n).store,a=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},c={...a,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||a.cdnUrl};e.push(c)}),e}};l(v,"UploaderBlock");v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(M).forEach(s=>{let i=U.eName(s),t=k(e=>{if([M.UPLOAD_FINISH,M.REMOVE,M.CDN_MODIFICATION].includes(e.detail.type)){let n=A.getCtx(e.detail.ctx),o=n.read("uploadCollection"),a=[];o.items().forEach(c=>{let h=A.getCtx(c).store,d=h.fileInfo;if(d){let p={...d,cdnUrlModifiers:h.cdnUrlModifiers,cdnUrl:h.cdnUrl||d.cdnUrl};a.push(p)}}),U.emit(new F({type:M.DATA_OUTPUT,ctx:e.detail.ctx,data:a})),n.pub("outputData",a)}},0);window.addEventListener(i,t)});var Z={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function $o(s,i){if(typeof i=="number")return Z[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Z[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Z[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}l($o,"transformationToStr");var hr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function kt(s){return Ri(...hr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return $o(i,t)}).filter(i=>!!i))}l(kt,"transformationsToOperations");var Pi=Ri("format/auto","progressive/yes"),wt=l(([s])=>typeof s!="undefined"?Number(s):void 0,"asNumber"),cr=l(()=>!0,"asBoolean"),So=l(([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),"asFilter"),ko=l(([s,i])=>({dimensions:D(s,"x").map(Number),coords:D(i).map(Number)}),"asCrop"),Io={enhance:wt,brightness:wt,exposure:wt,gamma:wt,contrast:wt,saturation:wt,vibrance:wt,warmth:wt,filter:So,mirror:cr,flip:cr,rotate:wt,crop:ko};function ur(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!hr.includes(e))continue;let n=Io[e],o=n(r);i[e]=o}return i}l(ur,"operationsToTransformations");var V=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),q=[V.CROP,V.TUNING,V.FILTERS],dr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],pr=["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"],fr=["rotate","mirror","flip"],ht=Object.freeze({brightness:{zero:Z.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Z.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Z.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Z.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Z.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Z.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Z.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Z.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Z.filter,range:[0,100],keypointsNumber:1}});var Oo="https://ucarecdn.com",Lo="https://upload.uploadcare.com",Uo="https://social.uploadcare.com",Qe={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:jt(q),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Oo,baseUrl:Lo,socialBaseUrl:Uo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var K=l(s=>String(s),"asString"),ut=l(s=>Number(s),"asNumber"),I=l(s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,"asBoolean"),Ro=l(s=>s==="auto"?s:I(s),"asStore"),Po={pubkey:K,multiple:I,multipleMin:ut,multipleMax:ut,confirmUpload:I,imgOnly:I,accept:K,externalSourcesPreferredTypes:K,store:Ro,cameraMirror:I,sourceList:K,maxLocalFileSizeBytes:ut,thumbSize:ut,showEmptyList:I,useLocalImageEditor:I,useCloudImageEditor:I,cloudImageEditorTabs:K,removeCopyright:I,cropPreset:K,modalScrollLock:I,modalBackdropStrokes:I,sourceListWrap:I,remoteTabSessionKey:K,cdnCname:K,baseUrl:K,socialBaseUrl:K,secureSignature:K,secureExpire:K,secureDeliveryProxy:K,retryThrottledRequestMaxTimes:ut,multipartMinFileSize:ut,multipartChunkSize:ut,maxConcurrentRequests:ut,multipartMaxConcurrentRequests:ut,multipartMaxAttempts:ut,checkForUrlDuplicates:I,saveUrlForRecurrentUploads:I,groupOutput:I,userAgentIntegration:K},mr=l((s,i)=>{if(!(typeof i=="undefined"||i===null))return Po[s](i)},"normalizeConfigValue");var Mi=Object.keys(Qe),Mo=["metadata"],No=l(s=>Mo.includes(s),"isComplexKey"),cs=Mi.filter(s=>!No(s)),Do={...Object.fromEntries(cs.map(s=>[ot(s),s])),...Object.fromEntries(cs.map(s=>[s.toLowerCase(),s]))},Fo={...Object.fromEntries(Mi.map(s=>[ot(s),et(s)])),...Object.fromEntries(Mi.map(s=>[s.toLowerCase(),et(s)]))},de=class extends y{constructor(){super();u(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Qe).map(([t,e])=>[et(t),e]))}}initCallback(){super.initCallback();for(let t of Mi){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,cs.includes(t)){let o=[...new Set([ot(t),t.toLowerCase()])];for(let a of o)typeof n=="undefined"||n===null?this.removeAttribute(a):this.setAttribute(a,n.toString())}this.$[et(t)]!==n&&(typeof n=="undefined"||n===null?this.$[et(t)]=Qe[t]:this.$[et(t)]=n)},get:()=>this.$[et(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Do[t],o=mr(n,r),a=o!=null?o:Qe[n],c=this;c[n]=a}};l(de,"Config");de.bindAttributes(Fo);var Ht=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};l(Ht,"Icon");Ht.template=``;Ht.bindAttributes({name:"name",size:"size"});var Vo="https://ucarecdn.com",Wt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Vo},"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 gr=l(s=>[...new Set(s)],"uniqueArray");var ti="--lr-img-",_r="unresolved",pe=2,fe=3,br=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),vr=Object.create(null),yr;for(let s in Wt)vr[ti+s]=((yr=Wt[s])==null?void 0:yr.default)||"";var ei=class extends Pt{constructor(){super(...arguments);u(this,"cssInit$",vr)}$$(t){return this.$[ti+t]}set$$(t){for(let e in t)this.$[ti+e]=t[e]}sub$$(t,e){this.sub(ti+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!br&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return L(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Wt.format.default}`,`quality/${this.$$("quality")||Wt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(br&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return O(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(O(St(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(O(St(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(O(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(O(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?je(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),a=r?"":e*Math.round(n.height);return o||a?`${o||""}x${a||""}`:null}_setupEventProxy(t){let e=l(n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},"proxifyEvent"),r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(_r,""),this.img.onload=()=>{this.img.removeAttribute(_r)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Wt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?gr(D(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*pe+"x")}") ${n*pe}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*fe+"x")}") ${n*fe}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,pe))}") ${pe}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,fe))}") ${fe}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*pe+"x")+` ${e*pe}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*fe+"x")+` ${e*fe}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):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(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),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)}static get observedAttributes(){return Object.keys(Wt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[ti+t]=r})}};l(ei,"ImgBase");var ii=class extends ei{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};l(ii,"Img");var Xt=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",i=>{typeof i!="undefined"&&(this.$.withDropZone=I(i))}),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};l(Xt,"SimpleBtn");Xt.template=``;Xt.bindAttributes({dropzone:null});var si=class extends _{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};l(si,"StartFrom");function Bo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=l(r=>{r.type!=="loadend"&&t.abort(),i(!1)},"onLoad");t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}l(Bo,"checkIsDirectory");function zo(s,i){return new Promise(t=>{let e=0,r=[],n=l(a=>{a||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),a.isFile?(e++,a.file(c=>{e--;let h=new File([c],c.name,{type:c.type||i});r.push({type:"file",file:h,fullPath:a.fullPath}),e===0&&t(r)})):a.isDirectory&&o(a.createReader())},"readEntry"),o=l(a=>{e++,a.readEntries(c=>{e--;for(let h of c)n(h);e===0&&t(r)})},"readReaderContent");n(s)})}l(zo,"readEntryContentAsync");function Cr(s){let i=[],t=[];for(let e=0;e{c&&i.push(...c)}));continue}let o=r.getAsFile();o&&t.push(Bo(o).then(a=>{a||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}l(Cr,"getDropItems");var j={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},wr=["focus"],jo=100,hs=new Map;function Ho(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}l(Ho,"distance");function us(s){let i=0,t=document.body,e=new Set,r=l(m=>e.add(m),"handleSwitch"),n=j.INACTIVE,o=l(m=>{s.shouldIgnore()&&m!==j.INACTIVE||(n!==m&&e.forEach(b=>b(m)),n=m)},"setState"),a=l(()=>i>0,"isDragging");r(m=>s.onChange(m));let c=l(()=>{i=0,o(j.INACTIVE)},"onResetEvent"),h=l(()=>{i+=1,n===j.INACTIVE&&o(j.ACTIVE)},"onDragEnter"),d=l(()=>{i-=1,a()||o(j.INACTIVE)},"onDragLeave"),p=l(m=>{m.preventDefault(),i=0,o(j.INACTIVE)},"onDrop"),f=l(m=>{if(s.shouldIgnore())return;a()||(i+=1);let b=[m.x,m.y],S=s.element.getBoundingClientRect(),$=Math.floor(Ho(b,S)),x=${if(s.shouldIgnore())return;m.preventDefault();let b=await Cr(m.dataTransfer);s.onItems(b),o(j.INACTIVE)},"onElementDrop");return t.addEventListener("drop",p),t.addEventListener("dragleave",d),t.addEventListener("dragenter",h),t.addEventListener("dragover",f),s.element.addEventListener("drop",g),wr.forEach(m=>{window.addEventListener(m,c)}),()=>{hs.delete(s.element),t.removeEventListener("drop",p),t.removeEventListener("dragleave",d),t.removeEventListener("dragenter",h),t.removeEventListener("dragover",f),s.element.removeEventListener("drop",g),wr.forEach(m=>{window.removeEventListener(m,c)})}}l(us,"addDropzone");var Gt=class extends v{constructor(){super(),this.init$={...this.init$,state:j.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!I(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:I(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:I(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:I(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=us({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:st.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:st.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=us({element:i,onChange:t=>{var r;let e=(r=Object.entries(j).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(j).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=D(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var i,t,e,r;super.destroyCallback(),(t=(i=this.$["lr-drop-area/targets"])==null?void 0:i.remove)==null||t.call(i,this),(e=this._destroyDropzone)==null||e.call(this),(r=this._destroyContentWrapperDropzone)==null||r.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};l(Gt,"DropArea");Gt.template=`
{{text}}
`;Gt.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Wo="src-type-",qt=class extends v{constructor(){super(...arguments);u(this,"_registeredTypes",{});u(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:_.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:_.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:_.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:_.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:a,activityParams:c={}}=e;this.applyL10nKey("src-type",`${Wo}${r}`),this.$.iconName=n,this.onclick=h=>{(a?a(h):!!o)&&this.set$({"*currentActivityParams":c,"*currentActivity":o})}}};l(qt,"SourceBtn");qt.template=`
`;qt.bindAttributes({type:null});var ri=class extends y{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=D(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};l(ri,"SourceList");function Tr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}l(Tr,"createSvgBlobUrl");function xr(s="#fff",i="rgba(0, 0, 0, .1)"){return Tr(``)}l(xr,"checkerboardCssBg");function ni(s="hsl(209, 21%, 65%)",i=32,t=32){return Tr(``)}l(ni,"fileCssBg");function Er(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,a)=>{r.onload=()=>{let c=r.height/r.width;c>1?(t.width=i,t.height=i*c):(t.height=i,t.width=i/c),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(h=>{if(!h){a();return}let d=URL.createObjectURL(h);o(d)})},r.onerror=c=>{a(c)}});return r.src=URL.createObjectURL(s),n}l(Er,"generateThumb");var H=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),nt=class extends v{constructor(){super();u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",k(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",k(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:H.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===_.activities.DETAILS)?this.$["*currentActivity"]=_.activities.DETAILS:this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);U.emit(new F({type:M.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=H.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=H.FAILED:t.getValue("validationMultipleLimitMsg")?e=H.LIMIT_OVERFLOW:t.getValue("isUploading")?e=H.UPLOADING:t.getValue("fileInfo")&&(e=H.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(O(St(this.cfg.cdnCname,this._entry.getValue("uuid")),L(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Er(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ni(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ni(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{nt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),nt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===H.FAILED,isLimitOverflow:t===H.LIMIT_OVERFLOW,isUploading:t===H.UPLOADING,isFinished:t===H.FINISHED,progressVisible:t===H.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===H.FAILED||t===H.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===H.FINISHED&&(this.$.badgeIcon="badge-success"),t===H.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),nt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,a;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(c=>!c.getValue("fileInfo"));U.emit(new F({type:M.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let c=new AbortController;t.setValue("abortController",c);let h=l(async()=>{let p=await this.getUploadClientOptions();return ts(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...p,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let g=f.value*100;t.setValue("uploadProgress",g)}this.$.progressUnknown=!f.isComputable},signal:c.signal})},"uploadTask"),d=await this.$["*uploadQueue"].add(h);t.setMultipleValues({fileInfo:d,isUploading:!1,fileName:d.originalFilename,fileSize:d.size,isImage:d.isImage,mimeType:(a=(o=(n=d.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?a:d.mimeType,uuid:d.uuid,cdnUrl:d.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(c){console.warn("Upload error",c),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),c instanceof P?c.isCancel||t.setValue("uploadError",c):t.setValue("uploadError",new Error("Unexpected error"))}}};l(nt,"FileItem");nt.template=`
{{itemName}}{{errorText}}
`;nt.activeInstances=new Set;var oi=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}};l(oi,"UiMessage");var me=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};l(me,"MessageBox");me.template=`
{{captionTxt}}
{{msgTxt}}
`;var ge=class extends v{constructor(){super();u(this,"couldBeUploadCollectionOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",_.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",k(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));U.emit(new F({type:M.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var d,p;let t=!!this.cfg.multiple,e=t?(d=this.cfg.multipleMin)!=null?d:0:1,r=t?(p=this.cfg.multipleMax)!=null?p:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!a,tooFew:o,tooMany:a,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new oi,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let g of t){let m=this.uploadCollection.read(g);m.getValue("fileInfo")&&!m.getValue("validationErrorMsg")&&(r.succeed+=1),m.getValue("isUploading")&&(r.uploading+=1),(m.getValue("validationErrorMsg")||m.getValue("uploadError"))&&(r.failed+=1),m.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:a}=this._validateFilesCount(),c=r.failed===0&&r.limitOverflow===0,h=!1,d=!1,p=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?h=!0:(d=!0,p=r.total===r.succeed&&n&&c),this.set$({doneBtnVisible:d,doneBtnEnabled:p,uploadBtnVisible:h,addMoreBtnEnabled:r.total===0||!o&&!a,addMoreBtnVisible:!a||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=l(r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})},"localizedText");return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};l(ge,"UploadList");ge.template=`{{headerText}}
`;var _e=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.URL);u(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:st.URL_TAB}),this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};l(_e,"UrlSource");_e.template=`
`;var ds=l(()=>typeof navigator.permissions!="undefined","canUsePermissionsApi");var be=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.CAMERA);u(this,"_unsubPermissions",null);u(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:ds(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});u(this,"_onActivate",l(()=>{ds()&&this._subscribePermissions(),this._capture()},"_onActivate"));u(this,"_onDeactivate",l(()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()},"_onDeactivate"));u(this,"_handlePermissionsChange",l(()=>{this._capture()},"_handlePermissionsChange"));u(this,"_setPermissionsState",k(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:st.CAMERA}),this.set$({"*currentActivity":_.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};l(be,"CameraSource");be.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var li=class extends v{};l(li,"UploadCtxProvider");var ye=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.DETAILS);u(this,"pauseRender",!0);u(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ni(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=Ke(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=l((n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))},"tmpSub");r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let a=O(n,L("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(a))}})})}};l(ye,"UploadDetails");ye.template=`
{{fileSize}}
{{errorTxt}}
`;var Ni=class{constructor(){u(this,"captionL10nStr","confirm-your-action");u(this,"messageL10Str","are-you-sure");u(this,"confirmL10nStr","yes");u(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}};l(Ni,"UiConfirmation");var ve=class extends _{constructor(){super(...arguments);u(this,"activityType",_.activities.CONFIRMATION);u(this,"_defaults",new Ni);u(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":_.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};l(ve,"ConfirmationDialog");ve.template=`{{activityCaption}}
{{messageTxt}}
`;var Ce=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};l(Ce,"ProgressBarCommon");Ce.template=``;var we=class extends y{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};l(we,"ProgressBar");we.template='
';var J="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var Kt=class extends y{constructor(){super();u(this,"init$",{...this.init$,checkerboard:!1,src:J})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${xr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=J}};l(Kt,"FilePreview");Kt.template='';Kt.bindAttributes({checkerboard:"checkerboard"});var Ar="--cfg-ctx-name",R=class extends y{get cfgCssCtxName(){return this.getCssData(Ar,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(Ar,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:A.getCtx(this.cfgCtxName)}}};l(R,"CloudImageEditorBase");function $r(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}l($r,"normalize");function B(...s){let i=$r(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}l(B,"classNames");function Sr(s,...i){let t=$r(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}l(Sr,"applyClassNames");var kr=l(s=>{if(!s)return q;let i=ar(s).filter(t=>q.includes(t));return i.length===0?q:i},"parseTabs");function Ir(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":q,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:J,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:jt(q),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=J,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=L(kt(i)),r=O(t,L(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}l(Ir,"initState");var Or=`
Network error
{{fileType}}
{{msg}}
`;var rt=class extends R{constructor(){super();u(this,"_debouncedShowLoader",k(this._showLoader.bind(this),300));this.init$={...this.init$,...Ir(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([a])=>{a.contentRect.width>0&&a.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===V.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Qs(this.$.cdnUrl);this.$["*originalUrl"]=St(this.$.cdnUrl,t);let e=tr(this.$.cdnUrl),r=ur(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=St(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=O(this.$["*originalUrl"],L("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===V.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==J&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||J)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Ui(t)}),this.sub("tabs",t=>{this.$["*tabList"]=kr(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=B("image",{image_hidden_to_cropper:t===V.CROP,image_hidden_effects:t!==V.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=L(kt(t)),n=O(e,L(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};l(rt,"CloudImageEditorBlock"),u(rt,"className","cloud-image-editor");rt.template=Or;rt.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var Te=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=C&&t.width<=C)return!0;let e=t.height<=C&&(i.includes("n")||i.includes("s")),r=t.width<=C&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],a=it("mask",{id:"backdrop-mask"}),c=it("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=it("rect",{x:t,y:e,width:r,height:n,fill:"black"});a.appendChild(c),a.appendChild(h);let d=it("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(d),o.appendChild(a),this._backdropMask=a,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Bt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,a=e==="",c=e.length===2,{x:h,y:d,width:p,height:f}=i;if(a){let m={x:h+p/3,y:d+f/3,width:p/3,height:f/3};Bt(n,m)}else{let m=$t(Math.min(p,f)/(24*2+34)/2,0,1),{d:b,center:S}=c?zs(i,e,m):js(i,e,m),$=Math.max(rs*$t(Math.min(p,f)/rs/3,0,1),Bs);Bt(n,{x:S[0]-$,y:S[1]-$,width:$*2,height:$*2}),Bt(r,{d:b})}let g=this._shouldThumbBeDisabled(e);o.setAttribute("class",B("thumb",{"thumb--hidden":g,"thumb--visible":!g}))}Bt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=it("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=it("rect",{fill:"transparent"}),a=it("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(a),n.appendChild(o),i[r]={direction:r,pathNode:a,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=it("svg"),t=it("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=it("line",{x1:`${Ge*e}%`,y1:"0%",x2:`${Ge*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=it("line",{x1:"0%",y1:`${Ge*e}%`,x2:"100%",y2:`${Ge*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),a=t.x-n,c=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[a,c],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,a=n-this._dragStartPoint[0],c=o-this._dragStartPoint[1],{direction:h}=this._draggingThumb,d=this._calcCropBox(h,[a,c]);d&&(this.$["*cropBox"]=d)}_calcCropBox(i,t){var h,d;let[e,r]=t,n=this.$["*imageBox"],o=(h=this._dragStartCrop)!=null?h:this.$["*cropBox"],a=(d=this.$["*cropPresetList"])==null?void 0:d[0],c=a?a.width/a.height:void 0;if(i===""?o=Ws({rect:o,delta:[e,r],imageBox:n}):o=Xs({rect:o,delta:[e,r],direction:i,aspectRatio:c,imageBox:n}),!Object.values(o).every(p=>Number.isFinite(p)&&p>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return ce(ue(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return Gs(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Hs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",B("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=C||i.width<=C,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",B({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};l(Te,"CropFrame");Te.template='';var dt=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=B({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};l(dt,"EditorButtonControl");dt.template=`
{{title}}
`;function Go(s){let i=s+90;return i=i>=360?0:i,i}l(Go,"nextAngle");function qo(s,i){return s==="rotate"?Go(i):["mirror","flip"].includes(s)?!i:null}l(qo,"nextValue");var Zt=class extends dt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=qo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};l(Zt,"EditorCropButtonControl");var ai={FILTER:"filter",COLOR_OPERATION:"color_operation"},pt="original",xe=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?ai.FILTER:ai.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===pt?void 0:this.$.value,filter:this._filter===pt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ht[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===ai.FILTER){let a=n;if(o){let{name:c,amount:h}=o;a=c===this._filter?h:n}this.$.value=a,this.$.defaultValue=a}if(this._controlType===ai.COLOR_OPERATION){let a=typeof o!="undefined"?o:e;this.$.value=a,this.$.defaultValue=a}}apply(){let t;this._controlType===ai.FILTER?this._filter===pt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};l(xe,"EditorSlider");xe.template=``;function ci(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:l(()=>{i.naturalWidth===0&&(i.src=J)},"cancel")}}l(ci,"preloadImage");function hi(s){let i=[];for(let n of s){let o=ci(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:l(()=>{i.forEach(n=>{n.cancel()})},"cancel")}}l(hi,"batchPreloadImages");var It=class extends dt{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,a={...this.$["*editorTransformations"]};return a[this._operation]=this._filter!==pt?{name:this._filter,amount:o}:void 0,O(this._originalUrl,L(Pi,kt(a),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:a,cancel:c}=ci(n);this._cancelPreload=c,a.catch(h=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:h})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{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",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===pt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};l(It,"EditorFilterControl");It.template=`
`;var Jt=class extends dt{constructor(){super(...arguments);u(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ht[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};l(Jt,"EditorOperationControl");var Lr=l((s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}},"throttle");function Ur(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}l(Ur,"pick");function Ee(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return O(s,L(Pi,kt(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}l(Ee,"viewerImageSrc");function Ko(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}l(Ko,"validateCrop");var Ae=class extends R{constructor(){super(),this.init$={...this.init$,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=k(this._commit.bind(this),300),this._handleResizeThrottled=Lr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Ur(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=he({width:i.naturalWidth,height:i.naturalHeight},r),a;if(o.width>n.width-t*2||o.height>n.height-t*2){let c=o.width/o.height,h=n.width/n.height;if(c>h){let d=n.width-t*2,p=d/c,f=0+t,g=t+(n.height-t*2)/2-p/2;a={x:f,y:g,width:d,height:p}}else{let d=n.height-t*2,p=d*c,f=t+(n.width-t*2)/2-p/2,g=0+t;a={x:f,y:g,width:p,height:d}}}else{let{width:c,height:h}=o,d=t+(n.width-t*2)/2-c/2,p=t+(n.height-t*2)/2-h/2;a={x:d,y:p,width:c,height:h}}this.$["*imageBox"]=ue(a)}_alignCrop(){var h;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:a,y:c}=this.$["*imageBox"];if(n){let{dimensions:[d,p],coords:[f,g]}=n,{width:m}=he(this._imageSize,r),b=o/m;i=ce(ue({x:a+f*b,y:c+g*b,width:d*b,height:p*b}),this.$["*imageBox"])}if(!n||!qs(i,t)){let d=(h=this.$["*cropPresetList"])==null?void 0:h[0],p=d?d.width/d.height:void 0,f=t.width/t.height,g=t.width,m=t.height;p&&(f>p?g=Math.min(t.height*p,t.width):m=Math.min(t.width/p,t.height)),i={x:t.x+t.width/2-g/2,y:t.y+t.height/2-m/2,width:g,height:m}}this.$["*cropBox"]=ce(ue(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:a}=r,c=he({width:e.width,height:e.height},a);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(a*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-c.width/2,-c.height/2,c.width,c.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=B({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:a,height:c}=he(this._imageSize,r),{width:h,height:d}=i,p=n/a,f=o/c;return[$t(Math.round(h/p),1,a),$t(Math.round(d/f),1,c)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:a,y:c}=t,{width:h,height:d}=he(this._imageSize,r),{x:p,y:f}=i,g=n/h,m=o/d,b=this._getCropDimensions(),S={dimensions:b,coords:[$t(Math.round((p-a)/g),0,h-b[0]),$t(Math.round((f-c)/m),0,d-b[1])]};if(!Ko(S)){console.error("Cropper is trying to create invalid crop object",{payload:S});return}if(!(b[0]===h&&b[1]===d))return S}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),a={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=a}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=B({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(Ee(i,e,t)),{promise:n,cancel:o,image:a}=ci(r),c=this._handleImageLoading(r);return a.addEventListener("load",c,{once:!0}),a.addEventListener("error",c,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>a).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(a)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};l(Ae,"EditorImageCropper");Ae.template=``;function ps(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}l(ps,"linspace");function Yo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}l(Zo,"calculateOpacities");function Jo(s,i){return s.map((t,e)=>tn-o)}l(Rr,"keypointsRange");var ui=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=k(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(Ee(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=l(()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(c=>c.value===e),"shouldSkip");if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let a=this._handleImageLoading(n.src);o.addEventListener("load",a,{once:!0}),o.addEventListener("error",a,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let c=this._keypoints,h=c.findIndex(p=>p.value>e),d=h{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ht[i],r=this._keypoints.map(a=>a.value),n=Zo(r,t,e),o=Jo(r,e);for(let[a,c]of Object.entries(this._keypoints))c.opacity=n[a],c.zIndex=o[a];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(h=>h.src),{images:r,promise:n,cancel:o}=hi(e);r.forEach(h=>{let d=this._handleImageLoading(h.src);h.addEventListener("load",d),h.addEventListener("error",d)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let a=this._operation,c=this._filter;await n,this._isActive&&this._isSame(a,c)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((h,d)=>{let p=r[d];p.classList.add("fader-image"),h.image=p,this._container.appendChild(p)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Rr(e,r).map(c=>this._imageSrc({url:i,filter:t,operation:e,value:c})),{cancel:a}=hi(o);this._cancelBatchPreload=a}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=B({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=B({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let a=this._imageSrc({operation:t,value:e});this._setOriginalSrc(a),this._container&&this._container.remove();return}this._keypoints=Rr(t,e).map(a=>this._constructKeypoint(t,a)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=B({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};l(ui,"EditorImageFader");var Qo=1,$e=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Qo?this.scrollLeft+=e:this.scrollLeft+=t})}};l($e,"EditorScroller");$e.template=" ";function tl(s){return``}l(tl,"renderTabToggle");function el(s){return`
`}l(el,"renderTabContent");var Se=class extends R{constructor(){super();u(this,"_updateInfoTooltip",k(()=>{var o,a;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===V.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let c=((a=t==null?void 0:t.filter)==null?void 0:a.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+c}else r=this.l10n(pt);else if(this.$["*tabId"]===V.TUNING&&e){n=!0;let c=(t==null?void 0:t[e])||ht[e].zero;r=e+" "+c}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":pt,"*currentOperation":null,"*tabId":V.CROP,showLoader:!1,filters:pr,colorOperations:dr,cropOperations:fr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=k(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===V.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new Jt;return e.operation=t,e}_createFilterControl(t){let e=new It;return e.filter=t,e}_createToggleControl(t){let e=new Zt;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===V.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===V.FILTERS?[pt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===V.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===V.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of q){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Ee(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=hi([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1,this.$["*tabId"]=t[0];for(let e of q){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}}),this._updateInfoTooltip()}};l(Se,"EditorToolbar");Se.template=`
{{*operationTooltip}}
${q.map(el).join("")}
${q.map(tl).join("")}
`;var Qt=class extends y{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return B("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};l(Qt,"LrBtnUi");Qt.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Qt.template=`
{{text}}
`;var ke=class extends y{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};l(ke,"LineLoaderUi");ke.template=`
`;var Di={transition:"transition",visible:"visible",hidden:"hidden"},Ie=class extends y{constructor(){super(),this._visible=!1,this._visibleStyle=Di.visible,this._hiddenStyle=Di.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Sr(this,{[Di.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(Di.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};l(Ie,"PresenceToggle");Ie.template=" ";var Oe=class extends y{constructor(){super();u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let a=document.createDocumentFragment(),c=document.createElement("div"),h=document.createElement("div");c.className="minor-step",h.className="border-step",a.appendChild(h);for(let p=0;p
`;var di=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.CLOUD_IMG_EDIT);u(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new rt,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};l(di,"CloudImageEditorActivity");var il=l(function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},"escapeRegExp"),Pr=l(function(s,i="i"){let t=s.split("*").map(il);return new RegExp("^"+t.join(".+")+"$",i)},"wildcardRegexp");var sl=l(s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,a)=>{let c=r[a];return o+`${a}: ${c};`},"");return t+`${e}{${n}}`},""),"styleToCss");function Mr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return sl({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}l(Mr,"buildStyles");var Ot={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in Ot){let t=Ot[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Nr=l(function(s,i,t){s in Ot||(Ot[s]=[]),Ot[s].push([i,t])},"registerMessage"),Dr=l(function(s,i){s in Ot&&(Ot[s]=Ot[s].filter(t=>t[0]!==i))},"unregisterMessage");function Fr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}l(Fr,"queryString");var Le=class extends v{constructor(){super();u(this,"activityType",_.activities.EXTERNAL);u(this,"_iframe",null);u(this,"updateCssData",l(()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())},"updateCssData"));u(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=D(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Pr(r);for(let[o,a]of Object.entries(t.alternatives))if(n.test(o))return a}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Mr(t)})}remoteUrl(){var a,c;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((c=(a=this.getCssData("--l10n-locale-name"))==null?void 0:a.split("-"))==null?void 0:c[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Fr(n),o.toString()}mountIframe(){let t=ze({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Nr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Dr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};l(Le,"ExternalSource");Le.template=`
{{activityCaption}}
{{counter}}
`;var te=class extends y{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;D(i).forEach(e=>{let r=ze({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};l(te,"Tabs");te.bindAttributes({"tab-list":null,default:null});te.template=`
`;var Lt=class extends v{constructor(){super(...arguments);u(this,"processInnerHtml",!0);u(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Lt.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Ns(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};l(Lt,"DataOutput");Lt.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var pi=class extends _{};l(pi,"ActivityHeader");var Ue=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};l(Ue,"Select");Ue.template=``;var Y={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Vr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Q=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,src:"",ppIcon:Y.PLAY,fsIcon:Y.FS_ON,volIcon:Y.VOL_ON,capIcon:Y.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Vr.exitFullscreen():Vr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===Y.CAP_OFF?(this.$.capIcon=Y.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Q.is+":captions","1")):(this.$.capIcon=Y.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Q.is+":captions"))}toggleSound(){this.$.volIcon===Y.VOL_ON?(this.$.volIcon=Y.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=Y.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Q.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Q.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=Y.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=Y.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=Y.FS_OFF:this.$.fsIcon=Y.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Q.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};l(Q,"Video");Q.template=`
{{currentTime}} / {{totalTime}}
`;Q.bindAttributes({video:"video",src:"src"});var rl="css-src";function fi(s){return class extends s{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(rl);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}l(fi,"shadowed");var ee=class extends fi(y){};l(ee,"ShadowWrapper");var Re=class extends y{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};l(Re,"Copyright"),u(Re,"template",`Powered by Uploadcare`);var Tt=class extends ee{constructor(){super(...arguments);u(this,"init$",ki(this));u(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};l(Tt,"SolutionBlock");var Pe=class extends Tt{};l(Pe,"FileUploaderRegular");Pe.template=``;var Me=class extends Tt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=_.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||_.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};l(Me,"FileUploaderMinimal");Me.template=``;var Ne=class extends Tt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||_.activities.START_FROM)&&(this.$["*currentActivity"]=_.activities.UPLOAD_LIST)})}};l(Ne,"FileUploaderInline");Ne.template=``;var mi=class extends fi(rt){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};l(mi,"CloudImageEditor");function Fi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}l(Fi,"registerBlocks");var fs="LR";async function Br(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[fs]){t(window[fs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[fs];i&&Fi(n),t(n)},document.head.appendChild(r)})}l(Br,"connectBlocksFrom");return Kr(nl);})(); \ No newline at end of file diff --git a/web/blocks.min.js b/web/blocks.min.js index 85e2655ff..56734b0a1 100644 --- a/web/blocks.min.js +++ b/web/blocks.min.js @@ -24,4 +24,4 @@ * */ var Br=Object.defineProperty;var Vr=(s,i,t)=>i in s?Br(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(Vr(s,typeof i!="symbol"?i+"":i,t),t),Ai=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var B=(s,i,t)=>(Ai(s,i,"read from private field"),t?t.call(s):i.get(s)),Ot=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},se=(s,i,t,e)=>(Ai(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var Oe=(s,i,t)=>(Ai(s,i,"access private method"),t);var zr=Object.defineProperty,jr=(s,i,t)=>i in s?zr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,Si=(s,i,t)=>(jr(s,typeof i!="symbol"?i+"":i,t),t);function Hr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=Hr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var C=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"}),ps="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Wr=ps.length-1,ne=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Gr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function qr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||us;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=us;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).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 Kr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function Yr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Xr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):fs(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var Le="{{",re="}}",Zr="skip-text";function Jr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(Zr))&&r.textContent.includes(Le)&&r.textContent.includes(re)&&1}});for(;i=e.nextNode();)t.push(i);return t}var Qr=function(s,i){Jr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(re);)e.textContent.startsWith(Le)?(n=e.textContent.indexOf(re)+re.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(Le),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(Le,"").replace(re,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},tn=[Gr,qr,Kr,Yr,Qr],Ue="'",Vt='"',en=/\\([0-9a-fA-F]{1,6} ?)/g;function sn(s){return(s[0]===Vt||s[0]===Ue)&&(s[s.length-1]===Vt||s[s.length-1]===Ue)}function rn(s){return(s[0]===Vt||s[0]===Ue)&&(s=s.slice(1)),(s[s.length-1]===Vt||s[s.length-1]===Ue)&&(s=s.slice(0,-1)),s}function nn(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=nn(i),i=Vt+i+Vt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Bt=null,pt=null,vt=class extends HTMLElement{constructor(){super(),Si(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return vt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ne.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=vt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=vt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=vt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=vt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=vt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=vt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])fs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of tn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);pt==null||pt.delete(this.updateCssData),pt!=null&&pt.size||(Bt==null||Bt.disconnect(),Bt=null,pt=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${C.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=on(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){pt||(pt=new Set),pt.add(this.updateCssData),Bt||(Bt=new MutationObserver(s=>{s[0].type==="attributes"&&pt.forEach(i=>{i()})}),Bt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=vt;Si(zt,"template");var $i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent($i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),$i.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};$i.appMap=Object.create(null);function ln(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function an(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function oe(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&an(i,s.attributes),s.styles&&ln(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=oe(t);i.appendChild(e)}),i}var ms="idb-store-ready",cn="symbiote-db",hn="symbiote-idb-update_",un=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return hn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=cn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new un(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Si(gs,"_reg",Object.create(null));function S(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var dn="--uploadcare-blocks-window-height",Re="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ki(){return typeof window[Re]=="undefined"?!1:!!window[Re]}function _s(){if(ki())return;let s=()=>{document.documentElement.style.setProperty(dn,`${window.innerHeight}px`),window[Re]=!0},i=S(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[Re]=!1,window.removeEventListener("resize",i)}}var pn=s=>s,Ii="{{",ys="}}",bs="plural:";function le(s,i,t={}){var o;let{openToken:e=Ii,closeToken:r=ys,transform:n=pn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(Ii);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ii,e)}return i}function Cs(s){return Object.prototype.toString.call(s)==="[object Object]"}var fn=/\W|_/g;function mn(s){return s.split(fn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ws(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>mt(t,{ignoreKeys:i})):s}function mt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ws(s,{ignoreKeys:i});if(!Cs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Cs(r)?r=mt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ws(r,{ignoreKeys:i})),t[mn(e)]=r}return t}var gn=s=>new Promise(i=>setTimeout(i,s));function Ni({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var _n={factor:2,time:100};function bn(s,i=_n){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>gn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Gt=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Gt.prototype),this.originalProgressEvent=t}},Ne=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Ct=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,Ct.prototype)}},yn=500,xs=({check:s,interval:i=yn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Ne(e,()=>{o&&clearTimeout(o),n(new Ct("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ct("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),x={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},De="application/octet-stream",Es="original",Tt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Ne(r,()=>{u=!0,a.abort(),l(new Ct)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let A=$.split(": "),T=A.shift(),w=A.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new Gt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function vn(s,...i){return s}var Cn=({name:s})=>s?[s]:[],wn=vn,Tn=()=>new FormData,As=s=>!1,Fe=s=>typeof Blob!="undefined"&&s instanceof Blob,Be=s=>typeof File!="undefined"&&s instanceof File,Ve=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",ae=s=>Fe(s)||Be(s)||As()||Ve(s),xn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",En=s=>!!s&&typeof s=="object"&&!Array.isArray(s),An=s=>!!s&&typeof s=="object"&&"data"in s&&ae(s.data);function $n(s,i,t){if(An(t)){let{name:e,contentType:r}=t,n=wn(t.data,e,r!=null?r:De),o=Cn({name:e,contentType:r});s.push([i,n,...o])}else if(En(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else xn(t)&&t&&s.push([i,t.toString()])}function Sn(s){let i=[];for(let[t,e]of Object.entries(s))$n(i,t,e);return i}function Di(s){let i=Tn(),t=Sn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var M=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,M.prototype)}},kn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=kn(t)),e.toString()},In="6.6.1",On="UploadcareUploadClient",Ln=In;function Rt(s){return Ni({libraryName:On,libraryVersion:Ln,...s})}var Un="RequestThrottledError",Ts=15e3,Rn=1e3;function Pn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return Ts;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Ts}function xt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return bn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Un&&r{let i="";return(Fe(s)||Be(s)||Ve(s))&&(i=s.type),i||De},Ss=s=>{let i="";return Be(s)&&s.name?i=s.name:Fe(s)||As()?i="":Ve(s)&&s.name&&(i=s.name),i||Es};function Fi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Mn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=x.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({file:{data:s,name:t||Ss(s),contentType:e||$s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Fi(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Ui;(function(s){s.Token="token",s.FileInfo="file_info"})(Ui||(Ui={}));function Nn(s,{publicKey:i,baseURL:t=x.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Fi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var X;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(X||(X={}));var Dn=s=>"status"in s&&s.status===X.Error;function Fn(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=x.retryNetworkErrorMaxTimes}={}){return xt(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Rt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=mt(JSON.parse(a));if("error"in d&&!Dn(d))throw new M(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Bn(s,{publicKey:i,baseURL:t=x.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:a,userAgent:c})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=mt(JSON.parse(p));if("error"in _)throw new M(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Vn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=x.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({filename:e||Es,size:s,content_type:t||De,part_size:r,UPLOADCARE_STORE:Fi(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w.parts=Object.keys(w.parts).map(H=>w.parts[H]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function zn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||De}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function jn(s,{publicKey:i,baseURL:t=x.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},data:Di({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Bi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return xs({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}var wt=class{constructor(i,{baseCDN:t=x.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=ft(t,`${r}/`),l=n?ft(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},Hn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:$})=>Mn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:A})=>Bi({file:A,publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new wt(A,{baseCDN:_})),Wn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Xn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Ne(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Gn=window.WebSocket,Ri=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},qn=(s,i)=>s==="success"?{status:X.Success,...i}:s==="progress"?{status:X.Progress,...i}:{status:X.Error,...i},Pi=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ri);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Gn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,qn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Oi=null,Vi=s=>{if(!Oi){let i=typeof window=="undefined"?0:3e4;Oi=new Pi(s,i)}return Oi},Kn=s=>{Vi(s).connect()};function Yn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return xs({check:c=>Fn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case X.Error:return new M(u.error,u.errorCode);case X.Waiting:return!1;case X.Unknown:return new M(`Token "${s}" was not found.`);case X.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case X.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Zn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Vi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Ne(t,()=>{a(),n(new Ct("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case X.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case X.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case X.Error:a(),n(new M(c.msg,c.error_code))}})}),Jn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:$=x.pusherKey,metadata:A})=>Promise.resolve(Kn($)).then(()=>Nn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(T=>{let w=Vi($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===Ui.FileInfo?T:Xn([({signal:w})=>Yn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:w}),({signal:w})=>Zn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof M)throw T;return T}).then(T=>Bi({file:T.uuid,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(T=>new wt(T,{baseCDN:r})),Li=new WeakMap,Qn=async s=>{if(Li.has(s))return Li.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Li.set(s,i),i},Is=async s=>{if(Be(s)||Fe(s))return s.size;if(Ve(s))return(await Qn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},to=(s,i=x.multipartMinFileSize)=>s>=i,Os=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!ae(s)&&t.test(s)},Ls=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!ae(s)&&t.test(s)},eo=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},so=async(s,i,t)=>e=>io(s,e,i,t),ro=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>zn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),no=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:$=x.multipartChunkSize,maxConcurrentRequests:A=x.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let H=e!=null?e:await Is(s),ht,It=(P,J)=>{if(!c)return;ht||(ht=Array(P).fill(0));let ut=W=>W.reduce((dt,Ei)=>dt+Ei,0);return W=>{W.isComputable&&(ht[J]=W.value,c({isComputable:!0,value:ut(ht)/P}))}};return _||(_=$s(s)),Vn(H,{publicKey:i,contentType:_,fileName:t||Ss(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:P,parts:J})=>{let ut=await so(s,H,$);return Promise.all([P,eo(A,J.map((W,dt)=>()=>ro(ut(dt),W,{publicKey:i,contentType:_,onProgress:It(J.length,dt),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([P])=>jn(P,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(P=>P.isReady?P:Bi({file:P.uuid,publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(P=>new wt(P,{baseCDN:T}))};async function zi(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:$,maxConcurrentRequests:A,baseCDN:T=x.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,pusherKey:ht,metadata:It}){if(ae(s)){let P=await Is(s);return to(P,_)?no(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:P,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It}):Hn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It})}if(Ls(s))return Jn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:ht,metadata:It});if(Os(s))return Wn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var Mi=class{constructor(i,t){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},oo=s=>{for(let i of s)if(!ae(i))return!1;return!0},lo=s=>{for(let i of s)if(!Os(i))return!1;return!0},ao=s=>{for(let i of s)if(!Ls(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=x.multipartChunkSize,baseCDN:$=x.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!oo(s)&&!ao(s)&&!lo(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let H,ht=!0,It=s.length,P=(J,ut)=>{if(!a)return;H||(H=Array(J).fill(0));let W=dt=>dt.reduce((Ei,Fr)=>Ei+Fr)/J;return dt=>{if(!dt.isComputable||!ht){ht=!1,a({isComputable:!1});return}H[ut]=dt.value,a({isComputable:!0,value:W(H)})}};return Promise.all(s.map((J,ut)=>zi(J,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:P(It,ut),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:$,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T}))).then(J=>{let ut=J.map(W=>W.uuid);return Bn(ut,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(W=>new Mi(W,J)).then(W=>(a&&a({isComputable:!0,value:1}),W))})}var Lt,jt,Ut,Ht,Wt,Xt,Pe,Me=class{constructor(i){Ot(this,Xt);Ot(this,Lt,1);Ot(this,jt,[]);Ot(this,Ut,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);se(this,Lt,i)}add(i){return new Promise((t,e)=>{B(this,Ht).set(i,t),B(this,Wt).set(i,e),B(this,jt).push(i),Oe(this,Xt,Pe).call(this)})}get pending(){return B(this,jt).length}get running(){return B(this,Ut)}set concurrency(i){se(this,Lt,i),Oe(this,Xt,Pe).call(this)}get concurrency(){return B(this,Lt)}};Lt=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,Pe=function(){let i=B(this,Lt)-B(this,Ut);for(let t=0;t{B(this,Ht).delete(e),B(this,Wt).delete(e),se(this,Ut,B(this,Ut)-1),Oe(this,Xt,Pe).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var ji=()=>({"*blocksRegistry":new Set}),Hi=s=>({...ji(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),ze=s=>({...Hi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Me(1)});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var Q=s=>`*cfg/${s}`;var gt=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ps=new Set;function je(s){Ps.has(s)||(Ps.add(s),console.warn(s))}var He=(s,i)=>new Intl.PluralRules(s).select(i);var Wi="lr-",b=class extends zt{constructor(){super();h(this,"allowCustomTemplate",!0);h(this,"init$",ji());h(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return le(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=He(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Wi}${t}`,!0),ki()||(this._destroyInnerHeightTracker=_s()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?le(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=Q(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(je("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${gt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(Q(t));r.ctx.has(r.name)?this.sub(Q(t),e):(this.bindCssData(`--cfg-${gt(t)}`),this.sub(`--cfg-${gt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Wi)?t:Wi+t)}};h(b,"StateConsumerScope",null),h(b,"className","");var ce=class extends b{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}};h(ce,"StateConsumerScope","modal");ce.template=``;var Ms="active",he="___ACTIVITY_IS_ACTIVE___",st=class extends b{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Hi(this));h(this,"_debouncedHistoryFlush",S(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=st._activityRegistry[this.activityKey];this[he]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=st._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[he]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[he]?this._deactivate():this.activityType===t&&!this[he]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!st._activityRegistry[this.activityKey]}get isActivityActive(){return this[he]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;st._activityRegistry||(st._activityRegistry=Object.create(null)),st._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),st._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(st._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setOrAddState("*modalActive",!1)}}},g=st;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ue=33.333333333333336,y=1,Xi=24,Ns=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function tt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Bs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Vs({rect:s,delta:[i,t],imageBox:e}){return Kt({...s,x:s.x+i,y:s.y+t},e)}function Kt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function co({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Yt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Zt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Et(s,i,t){return Math.min(Math.max(s,i),t)}var Xe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var et=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs="blocks",Gs="0.27.1";function qs(s){return Ni({...s,libraryName:Xs,libraryVersion:Gs})}var Ks=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Ge=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ks(i)).join("/-/"),O=(...s)=>{let i=Ge(...s);return i?`-/${i}/`:""};function Ys(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Js(s){let i=Qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ks(n))}function Qs(s){let i=new URL(s),t=Ys(s),e=tr(t)?er(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function tr(s){return s.startsWith("http")}function er(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var I=(s,i,t)=>{let e=new URL(Qs(s));if(t=t||Ys(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),tr(t)){let r=er(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var de=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Gi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],qi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ir=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),pe=s=>{let i=s==null?void 0:s.type;return i?qi(i,de):!1};var nt=1e3,Mt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),fe=s=>Math.ceil(s*100)/100,sr=(s,i=Mt.AUTO)=>{let t=i===Mt.AUTO;if(i===Mt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};h(L,"_timeoutStore",Object.create(null));var rr="[Typed State] Wrong property name: ",bo="[Typed State] Wrong property type: ",qe=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||ne.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(bo+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Ke=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||ne.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new qe(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var nr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var or=s=>s?s.split(",").map(i=>i.trim()):[],Nt=s=>s?s.join(","):"";var v=class extends g{constructor(){super(...arguments);h(this,"couldBeUploadCollectionOwner",!1);h(this,"isUploadCollectionOwner",!1);h(this,"init$",ze(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",S(this._runValidators.bind(this),100));h(this,"_handleCollectionUpdate",t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,L.emit(new V({type:U.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&L.emit(new V({type:U.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{L.emit(new V({type:U.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{L.emit(new V({type:U.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{L.emit(new V({type:U.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){je("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Ke({typedSchema:nr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromObject(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:pe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:pe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Nt(Gi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?de:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Nt(de)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:et.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);L.emit(new V({type:U.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),L.emit(new V({type:U.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Gi([...e?de:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=qi(o,n),c=ir(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:sr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Xe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=O(`crop/${u.width}x${u.height}/${u.x},${u.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:I(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:qs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};e.push(a)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(U).forEach(s=>{let i=L.eName(s),t=S(e=>{if([U.UPLOAD_FINISH,U.REMOVE,U.CDN_MODIFICATION].includes(e.detail.type)){let n=E.getCtx(e.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let c=E.getCtx(a).store,u=c.fileInfo;if(u){let d={...u,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||u.cdnUrl};l.push(d)}}),L.emit(new V({type:U.DATA_OUTPUT,ctx:e.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var Y={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function yo(s,i){if(typeof i=="number")return Y[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Y[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Y[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var ar=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return Ge(...ar.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yo(i,t)}).filter(i=>!!i))}var Ye=Ge("format/auto","progressive/yes"),_t=([s])=>typeof s!="undefined"?Number(s):void 0,lr=()=>!0,vo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Co=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),wo={enhance:_t,brightness:_t,exposure:_t,gamma:_t,contrast:_t,saturation:_t,vibrance:_t,warmth:_t,filter:vo,mirror:lr,flip:lr,rotate:_t,crop:Co};function cr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!ar.includes(e))continue;let n=wo[e],o=n(r);i[e]=o}return i}var D=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),G=[D.CROP,D.TUNING,D.FILTERS],hr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],ur=["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"],dr=["rotate","mirror","flip"],ot=Object.freeze({brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}});var To="https://ucarecdn.com",xo="https://upload.uploadcare.com",Eo="https://social.uploadcare.com",me={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Nt(G),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:To,baseUrl:xo,socialBaseUrl:Eo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var q=s=>String(s),lt=s=>Number(s),k=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,Ao=s=>s==="auto"?s:k(s),$o={pubkey:q,multiple:k,multipleMin:lt,multipleMax:lt,confirmUpload:k,imgOnly:k,accept:q,externalSourcesPreferredTypes:q,store:Ao,cameraMirror:k,sourceList:q,maxLocalFileSizeBytes:lt,thumbSize:lt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:q,removeCopyright:k,cropPreset:q,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:q,cdnCname:q,baseUrl:q,socialBaseUrl:q,secureSignature:q,secureExpire:q,secureDeliveryProxy:q,retryThrottledRequestMaxTimes:lt,multipartMinFileSize:lt,multipartChunkSize:lt,maxConcurrentRequests:lt,multipartMaxConcurrentRequests:lt,multipartMaxAttempts:lt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:q},pr=(s,i)=>{if(!(typeof i=="undefined"||i===null))return $o[s](i)};var Ze=Object.keys(me),So=["metadata"],ko=s=>So.includes(s),Ki=Ze.filter(s=>!ko(s)),Io={...Object.fromEntries(Ki.map(s=>[gt(s),s])),...Object.fromEntries(Ki.map(s=>[s.toLowerCase(),s]))},Oo={...Object.fromEntries(Ze.map(s=>[gt(s),Q(s)])),...Object.fromEntries(Ze.map(s=>[s.toLowerCase(),Q(s)]))},Je=class extends b{constructor(){super();h(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(me).map(([t,e])=>[Q(t),e]))}}initCallback(){super.initCallback();for(let t of Ze){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,Ki.includes(t)){let o=[...new Set([gt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[Q(t)]!==n&&(typeof n=="undefined"||n===null?this.$[Q(t)]=me[t]:this.$[Q(t)]=n)},get:()=>this.$[Q(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Io[t],o=pr(n,r),l=o!=null?o:me[n],a=this;a[n]=l}};Je.bindAttributes(Oo);var ge=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ge.template=``;ge.bindAttributes({name:"name",size:"size"});var Lo="https://ucarecdn.com",Dt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Lo},"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 fr=s=>[...new Set(s)];var _e="--lr-img-",mr="unresolved",Jt=2,Qt=3,gr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),br=Object.create(null),_r;for(let s in Dt)br[_e+s]=((_r=Dt[s])==null?void 0:_r.default)||"";var Qe=class extends zt{constructor(){super(...arguments);h(this,"cssInit$",br)}$$(t){return this.$[_e+t]}set$$(t){for(let e in t)this.$[_e+e]=t[e]}sub$$(t,e){this.sub(_e+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!gr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return O(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Dt.format.default}`,`quality/${this.$$("quality")||Dt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(gr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return I(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(I(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(I(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?le(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(mr,""),this.img.onload=()=>{this.img.removeAttribute(mr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Dt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?fr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Jt+"x")}") ${n*Jt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Qt+"x")}") ${n*Qt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Jt))}") ${Jt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Qt))}") ${Qt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Jt+"x")+` ${e*Jt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Qt+"x")+` ${e*Qt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):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(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),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)}static get observedAttributes(){return Object.keys(Dt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[_e+t]=r})}};var Yi=class extends Qe{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var be=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",i=>{typeof i!="undefined"&&(this.$.withDropZone=k(i))}),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};be.template=``;be.bindAttributes({dropzone:null});var Zi=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function Uo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function Ro(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push(c),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function yr(s){let i=[],t=[];for(let e=0;e{i.push(...a)}));continue}let o=r.getAsFile();t.push(Uo(o).then(l=>{l||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},vr=["focus"],Po=100,Ji=new Map;function Mo(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Qi(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=z.INACTIVE,o=f=>{s.shouldIgnore()&&f!==z.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(z.INACTIVE)},c=()=>{i+=1,n===z.INACTIVE&&o(z.ACTIVE)},u=()=>{i-=1,l()||o(z.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(z.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let _=[f.x,f.y],$=s.element.getBoundingClientRect(),A=Math.floor(Mo(_,$)),T=A{if(s.shouldIgnore())return;f.preventDefault();let _=await yr(f.dataTransfer);s.onItems(_),o(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),vr.forEach(f=>{window.addEventListener(f,a)}),()=>{Ji.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),vr.forEach(f=>{window.removeEventListener(f,a)})}}var ye=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return e&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!k(e)})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:k(e)})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:k(e)})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:k(e)})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Qi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:et.DROP_AREA});return}this.addFileFromObject(r,{source:et.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Qi({element:t,onChange:e=>{var n;let r=(n=Object.entries(z).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var n;let r=(n=Object.entries(z).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=N(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,n;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ye.template=`
{{text}}
`;ye.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var No="src-type-",ve=class extends v{constructor(){super(...arguments);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${No}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ve.template=`
`;ve.bindAttributes({type:null});var ts=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function Cr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function wr(s="#fff",i="rgba(0, 0, 0, .1)"){return Cr(``)}function Ce(s="hsl(209, 21%, 65%)",i=32,t=32){return Cr(``)}function Tr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var j=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),bt=class extends v{constructor(){super();h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",S(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",S(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:j.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=j.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=j.FAILED:t.getValue("validationMultipleLimitMsg")?e=j.LIMIT_OVERFLOW:t.getValue("isUploading")?e=j.UPLOADING:t.getValue("fileInfo")&&(e=j.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(I(At(this.cfg.cdnCname,this._entry.getValue("uuid")),O(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Tr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{bt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),bt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===j.FAILED,isLimitOverflow:t===j.LIMIT_OVERFLOW,isUploading:t===j.UPLOADING,isFinished:t===j.FINISHED,progressVisible:t===j.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===j.FAILED||t===j.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===j.FINISHED&&(this.$.badgeIcon="badge-success"),t===j.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),bt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));L.emit(new V({type:U.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=await this.getUploadClientOptions();return zi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof M?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};bt.template=`
{{itemName}}{{errorText}}
`;bt.activeInstances=new Set;var ti=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},ei=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};ei.template=`
{{captionTxt}}
{{msgTxt}}
`;var ii=class extends v{constructor(){super();h(this,"couldBeUploadCollectionOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",S(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new ti,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};ii.template=`{{headerText}}
`;var si=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:et.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};si.template=`
`;var es=()=>typeof navigator.permissions!="undefined";var ri=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:es(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{es()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",S(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:et.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ri.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var is=class extends v{};var ni=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=Ce(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=pe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=I(n,O("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ni.template=`
{{fileSize}}
{{errorTxt}}
`;var ss=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},oi=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ss);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};oi.template=`{{activityCaption}}
{{messageTxt}}
`;var li=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};li.template=``;var ai=class extends b{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ai.template='
';var Z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var we=class extends b{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:Z})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${wr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Z}};we.template='';we.bindAttributes({checkerboard:"checkerboard"});var xr="--cfg-ctx-name",R=class extends b{get cfgCssCtxName(){return this.getCssData(xr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(xr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function Er(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function F(...s){let i=Er(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function Ar(s,...i){let t=Er(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var $r=s=>{if(!s)return G;let i=or(s).filter(t=>G.includes(t));return i.length===0?G:i};function Sr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":G,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Z,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Nt(G),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Z,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=O($t(i)),r=I(t,O(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var kr=`
Network error
{{fileType}}
{{msg}}
`;var at=class extends R{constructor(){super();h(this,"_debouncedShowLoader",S(this._showLoader.bind(this),300));this.init$={...this.init$,...Sr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===D.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Zs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Js(this.$.cdnUrl),r=cr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=I(this.$["*originalUrl"],O("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===D.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Z&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Z)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Xe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=$r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=F("image",{image_hidden_to_cropper:t===D.CROP,image_hidden_effects:t!==D.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=O($t(t)),n=I(e,O(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(at,"className","cloud-image-editor");at.template=kr;at.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ci=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=tt("mask",{id:"backdrop-mask"}),a=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=tt("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Pt(n,f)}else{let f=Et(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:$}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(Xi*Et(Math.min(d,p)/Xi/3,0,1),Ns);Pt(n,{x:$[0]-A,y:$[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",F("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=tt("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=tt("rect",{fill:"transparent"}),l=tt("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=tt("svg"),t=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=tt("line",{x1:`${ue*e}%`,y1:"0%",x2:`${ue*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=tt("line",{x1:"0%",y1:`${ue*e}%`,x2:"100%",y2:`${ue*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Vs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Kt(Zt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Bs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",F("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",F({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ci.template='';var yt=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=F({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function Fo(s){let i=s+90;return i=i>=360?0:i,i}function Bo(s,i){return s==="rotate"?Fo(i):["mirror","flip"].includes(s)?!i:null}var Te=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Bo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var xe={FILTER:"filter",COLOR_OPERATION:"color_operation"},ct="original",hi=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?xe.FILTER:xe.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ct?void 0:this.$.value,filter:this._filter===ct?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ot[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===xe.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===xe.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===xe.FILTER?this._filter===ct?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};hi.template=``;function Ee(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=Z)}}}function Ae(s){let i=[];for(let n of s){let o=Ee(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var te=class extends yt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ct?{name:this._filter,amount:o}:void 0,I(this._originalUrl,O(Ye,$t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=Ee(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{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",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ct,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};te.template=`
`;var $e=class extends yt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ot[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Ir=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function Or(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function ee(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return I(s,O(Ye,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Vo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ui=class extends R{constructor(){super(),this.init$={...this.init$,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=S(this._commit.bind(this),300),this._handleResizeThrottled=Ir(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Or(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=Yt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Zt(l)}_alignCrop(){var c;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[u,d],coords:[p,m]}=n,{width:f}=Yt(this._imageSize,r),_=o/f;i=Kt(Zt({x:l+p*_,y:a+m*_,width:u*_,height:d*_}),this.$["*imageBox"])}if(!n||!Hs(i,t)){let u=(c=this.$["*cropPresetList"])==null?void 0:c[0],d=u?u.width/u.height:void 0,p=t.width/t.height,m=t.width,f=t.height;d&&(p>d?m=Math.min(t.height*d,t.width):f=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Kt(Zt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=Yt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=F({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=Yt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[Et(Math.round(c/d),1,l),Et(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=Yt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),$={dimensions:_,coords:[Et(Math.round((d-l)/m),0,c-_[0]),Et(Math.round((p-a)/f),0,u-_[1])]};if(!Vo($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(_[0]===c&&_[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=F({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(ee(i,e,t)),{promise:n,cancel:o,image:l}=Ee(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ui.template=``;function rs(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function zo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Ho(s,i){return s.map((t,e)=>tn-o)}var ns=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=S(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(ee(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ot[i],r=this._keypoints.map(l=>l.value),n=jo(r,t,e),o=Ho(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Ae(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Lr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=Ae(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Lr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=F({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Wo=1,di=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Wo?this.scrollLeft+=e:this.scrollLeft+=t})}};di.template=" ";function Xo(s){return``}function Go(s){return`
`}var pi=class extends R{constructor(){super();h(this,"_updateInfoTooltip",S(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===D.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(ct);else if(this.$["*tabId"]===D.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||ot[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ct,"*currentOperation":null,"*tabId":D.CROP,showLoader:!1,filters:ur,colorOperations:hr,cropOperations:dr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=S(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===D.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new $e;return e.operation=t,e}_createFilterControl(t){let e=new te;return e.filter=t,e}_createToggleControl(t){let e=new Te;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===D.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===D.FILTERS?[ct,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===D.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===D.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of G){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ee(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Ae([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1,this.$["*tabId"]=t[0];for(let e of G){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}}),this._updateInfoTooltip()}};pi.template=`
{{*operationTooltip}}
${G.map(Go).join("")}
${G.map(Xo).join("")}
`;var Se=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return F("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Se.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Se.template=`
{{text}}
`;var fi=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};fi.template=`
`;var mi={transition:"transition",visible:"visible",hidden:"hidden"},gi=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=mi.visible,this._hiddenStyle=mi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Ar(this,{[mi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(mi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};gi.template=" ";var _i=class extends b{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);h(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new at,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var qo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Ur=function(s,i="i"){let t=s.split("*").map(qo);return new RegExp("^"+t.join(".+")+"$",i)};var Ko=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Rr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Ko({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var St={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in St){let t=St[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Pr=function(s,i,t){s in St||(St[s]=[]),St[s].push([i,t])},Mr=function(s,i){s in St&&(St[s]=St[s].filter(t=>t[0]!==i))};function Nr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var bi=class extends v{constructor(){super();h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Ur(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Rr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Nr(n),o.toString()}mountIframe(){let t=oe({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Pr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Mr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};bi.template=`
{{activityCaption}}
{{counter}}
`;var ke=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=oe({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ke.bindAttributes({"tab-list":null,default:null});ke.template=`
`;var ie=class extends v{constructor(){super(...arguments);h(this,"processInnerHtml",!0);h(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return ie.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Us(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};ie.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ls=class extends g{};var yi=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};yi.template=``;var K={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Dr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},it=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:K.PLAY,fsIcon:K.FS_ON,volIcon:K.VOL_ON,capIcon:K.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Dr.exitFullscreen():Dr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===K.CAP_OFF?(this.$.capIcon=K.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(it.is+":captions","1")):(this.$.capIcon=K.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(it.is+":captions"))}toggleSound(){this.$.volIcon===K.VOL_ON?(this.$.volIcon=K.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=K.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(it.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(it.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=K.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=K.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=K.FS_OFF:this.$.fsIcon=K.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(it.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};it.template=`
{{currentTime}} / {{totalTime}}
`;it.bindAttributes({video:"video",src:"src"});var Yo="css-src";function vi(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Yo);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Ie=class extends vi(b){};var Ci=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(Ci,"template",`Powered by Uploadcare`);var kt=class extends Ie{constructor(){super(...arguments);h(this,"init$",ze(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var wi=class extends kt{};wi.template=``;var Ti=class extends kt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};Ti.template=``;var xi=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};xi.template=``;var as=class extends vi(at){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Zo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,zt as BaseComponent,b as Block,ri as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,at as CloudImageEditorBlock,Je as Config,oi as ConfirmationDialog,Ci as Copyright,ci as CropFrame,E as Data,ie as DataOutput,ye as DropArea,Te as EditorCropButtonControl,te as EditorFilterControl,ui as EditorImageCropper,ns as EditorImageFader,$e as EditorOperationControl,di as EditorScroller,hi as EditorSlider,pi as EditorToolbar,bi as ExternalSource,bt as FileItem,we as FilePreview,xi as FileUploaderInline,Ti as FileUploaderMinimal,wi as FileUploaderRegular,ge as Icon,Yi as Img,fi as LineLoaderUi,Se as LrBtnUi,ei as MessageBox,ce as Modal,Xs as PACKAGE_NAME,Gs as PACKAGE_VERSION,gi as PresenceToggle,ai as ProgressBar,li as ProgressBarCommon,yi as Select,Ie as ShadowWrapper,be as SimpleBtn,_i as SliderUi,ve as SourceBtn,ts as SourceList,Zi as StartFrom,ke as Tabs,is as UploadCtxProvider,ni as UploadDetails,ii as UploadList,v as UploaderBlock,si as UrlSource,it as Video,Zo as connectBlocksFrom,cs as registerBlocks,vi as shadowed,gt as toKebabCase}; \ No newline at end of file +`,"\\n"),i=nn(i),i=Vt+i+Vt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Bt=null,pt=null,vt=class extends HTMLElement{constructor(){super(),Si(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return vt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ne.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=vt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=vt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=vt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=vt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=vt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=vt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])fs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of tn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);pt==null||pt.delete(this.updateCssData),pt!=null&&pt.size||(Bt==null||Bt.disconnect(),Bt=null,pt=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${C.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=on(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){pt||(pt=new Set),pt.add(this.updateCssData),Bt||(Bt=new MutationObserver(s=>{s[0].type==="attributes"&&pt.forEach(i=>{i()})}),Bt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=vt;Si(zt,"template");var $i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent($i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),$i.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};$i.appMap=Object.create(null);function ln(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function an(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function oe(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&an(i,s.attributes),s.styles&&ln(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=oe(t);i.appendChild(e)}),i}var ms="idb-store-ready",cn="symbiote-db",hn="symbiote-idb-update_",un=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return hn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=cn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new un(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Si(gs,"_reg",Object.create(null));function S(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var dn="--uploadcare-blocks-window-height",Re="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ki(){return typeof window[Re]=="undefined"?!1:!!window[Re]}function _s(){if(ki())return;let s=()=>{document.documentElement.style.setProperty(dn,`${window.innerHeight}px`),window[Re]=!0},i=S(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[Re]=!1,window.removeEventListener("resize",i)}}var pn=s=>s,Ii="{{",ys="}}",bs="plural:";function le(s,i,t={}){var o;let{openToken:e=Ii,closeToken:r=ys,transform:n=pn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(Ii);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ii,e)}return i}function Cs(s){return Object.prototype.toString.call(s)==="[object Object]"}var fn=/\W|_/g;function mn(s){return s.split(fn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ws(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>mt(t,{ignoreKeys:i})):s}function mt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ws(s,{ignoreKeys:i});if(!Cs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Cs(r)?r=mt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ws(r,{ignoreKeys:i})),t[mn(e)]=r}return t}var gn=s=>new Promise(i=>setTimeout(i,s));function Ni({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var _n={factor:2,time:100};function bn(s,i=_n){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>gn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Gt=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Gt.prototype),this.originalProgressEvent=t}},Ne=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Ct=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,Ct.prototype)}},yn=500,xs=({check:s,interval:i=yn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Ne(e,()=>{o&&clearTimeout(o),n(new Ct("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ct("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),x={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},De="application/octet-stream",Es="original",Tt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Ne(r,()=>{u=!0,a.abort(),l(new Ct)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let A=$.split(": "),T=A.shift(),w=A.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new Gt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function vn(s,...i){return s}var Cn=({name:s})=>s?[s]:[],wn=vn,Tn=()=>new FormData,As=s=>!1,Fe=s=>typeof Blob!="undefined"&&s instanceof Blob,Be=s=>typeof File!="undefined"&&s instanceof File,Ve=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",ae=s=>Fe(s)||Be(s)||As()||Ve(s),xn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",En=s=>!!s&&typeof s=="object"&&!Array.isArray(s),An=s=>!!s&&typeof s=="object"&&"data"in s&&ae(s.data);function $n(s,i,t){if(An(t)){let{name:e,contentType:r}=t,n=wn(t.data,e,r!=null?r:De),o=Cn({name:e,contentType:r});s.push([i,n,...o])}else if(En(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else xn(t)&&t&&s.push([i,t.toString()])}function Sn(s){let i=[];for(let[t,e]of Object.entries(s))$n(i,t,e);return i}function Di(s){let i=Tn(),t=Sn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var M=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,M.prototype)}},kn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=kn(t)),e.toString()},In="6.6.1",On="UploadcareUploadClient",Ln=In;function Rt(s){return Ni({libraryName:On,libraryVersion:Ln,...s})}var Un="RequestThrottledError",Ts=15e3,Rn=1e3;function Pn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return Ts;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Ts}function xt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return bn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Un&&r{let i="";return(Fe(s)||Be(s)||Ve(s))&&(i=s.type),i||De},Ss=s=>{let i="";return Be(s)&&s.name?i=s.name:Fe(s)||As()?i="":Ve(s)&&s.name&&(i=s.name),i||Es};function Fi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Mn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=x.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({file:{data:s,name:t||Ss(s),contentType:e||$s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Fi(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Ui;(function(s){s.Token="token",s.FileInfo="file_info"})(Ui||(Ui={}));function Nn(s,{publicKey:i,baseURL:t=x.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Fi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var X;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(X||(X={}));var Dn=s=>"status"in s&&s.status===X.Error;function Fn(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=x.retryNetworkErrorMaxTimes}={}){return xt(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Rt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=mt(JSON.parse(a));if("error"in d&&!Dn(d))throw new M(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Bn(s,{publicKey:i,baseURL:t=x.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:a,userAgent:c})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=mt(JSON.parse(p));if("error"in _)throw new M(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Vn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=x.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({filename:e||Es,size:s,content_type:t||De,part_size:r,UPLOADCARE_STORE:Fi(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w.parts=Object.keys(w.parts).map(H=>w.parts[H]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function zn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||De}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function jn(s,{publicKey:i,baseURL:t=x.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},data:Di({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Bi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return xs({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}var wt=class{constructor(i,{baseCDN:t=x.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=ft(t,`${r}/`),l=n?ft(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},Hn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:$})=>Mn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:A})=>Bi({file:A,publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new wt(A,{baseCDN:_})),Wn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Xn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Ne(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Gn=window.WebSocket,Ri=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},qn=(s,i)=>s==="success"?{status:X.Success,...i}:s==="progress"?{status:X.Progress,...i}:{status:X.Error,...i},Pi=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ri);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Gn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,qn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Oi=null,Vi=s=>{if(!Oi){let i=typeof window=="undefined"?0:3e4;Oi=new Pi(s,i)}return Oi},Kn=s=>{Vi(s).connect()};function Yn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return xs({check:c=>Fn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case X.Error:return new M(u.error,u.errorCode);case X.Waiting:return!1;case X.Unknown:return new M(`Token "${s}" was not found.`);case X.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case X.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Zn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Vi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Ne(t,()=>{a(),n(new Ct("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case X.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case X.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case X.Error:a(),n(new M(c.msg,c.error_code))}})}),Jn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:$=x.pusherKey,metadata:A})=>Promise.resolve(Kn($)).then(()=>Nn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(T=>{let w=Vi($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===Ui.FileInfo?T:Xn([({signal:w})=>Yn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:w}),({signal:w})=>Zn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof M)throw T;return T}).then(T=>Bi({file:T.uuid,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(T=>new wt(T,{baseCDN:r})),Li=new WeakMap,Qn=async s=>{if(Li.has(s))return Li.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Li.set(s,i),i},Is=async s=>{if(Be(s)||Fe(s))return s.size;if(Ve(s))return(await Qn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},to=(s,i=x.multipartMinFileSize)=>s>=i,Os=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!ae(s)&&t.test(s)},Ls=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!ae(s)&&t.test(s)},eo=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},so=async(s,i,t)=>e=>io(s,e,i,t),ro=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>zn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),no=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:$=x.multipartChunkSize,maxConcurrentRequests:A=x.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let H=e!=null?e:await Is(s),ht,It=(P,J)=>{if(!c)return;ht||(ht=Array(P).fill(0));let ut=W=>W.reduce((dt,Ei)=>dt+Ei,0);return W=>{W.isComputable&&(ht[J]=W.value,c({isComputable:!0,value:ut(ht)/P}))}};return _||(_=$s(s)),Vn(H,{publicKey:i,contentType:_,fileName:t||Ss(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:P,parts:J})=>{let ut=await so(s,H,$);return Promise.all([P,eo(A,J.map((W,dt)=>()=>ro(ut(dt),W,{publicKey:i,contentType:_,onProgress:It(J.length,dt),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([P])=>jn(P,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(P=>P.isReady?P:Bi({file:P.uuid,publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(P=>new wt(P,{baseCDN:T}))};async function zi(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:$,maxConcurrentRequests:A,baseCDN:T=x.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,pusherKey:ht,metadata:It}){if(ae(s)){let P=await Is(s);return to(P,_)?no(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:P,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It}):Hn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It})}if(Ls(s))return Jn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:ht,metadata:It});if(Os(s))return Wn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var Mi=class{constructor(i,t){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},oo=s=>{for(let i of s)if(!ae(i))return!1;return!0},lo=s=>{for(let i of s)if(!Os(i))return!1;return!0},ao=s=>{for(let i of s)if(!Ls(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=x.multipartChunkSize,baseCDN:$=x.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!oo(s)&&!ao(s)&&!lo(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let H,ht=!0,It=s.length,P=(J,ut)=>{if(!a)return;H||(H=Array(J).fill(0));let W=dt=>dt.reduce((Ei,Fr)=>Ei+Fr)/J;return dt=>{if(!dt.isComputable||!ht){ht=!1,a({isComputable:!1});return}H[ut]=dt.value,a({isComputable:!0,value:W(H)})}};return Promise.all(s.map((J,ut)=>zi(J,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:P(It,ut),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:$,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T}))).then(J=>{let ut=J.map(W=>W.uuid);return Bn(ut,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(W=>new Mi(W,J)).then(W=>(a&&a({isComputable:!0,value:1}),W))})}var Lt,jt,Ut,Ht,Wt,Xt,Pe,Me=class{constructor(i){Ot(this,Xt);Ot(this,Lt,1);Ot(this,jt,[]);Ot(this,Ut,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);se(this,Lt,i)}add(i){return new Promise((t,e)=>{B(this,Ht).set(i,t),B(this,Wt).set(i,e),B(this,jt).push(i),Oe(this,Xt,Pe).call(this)})}get pending(){return B(this,jt).length}get running(){return B(this,Ut)}set concurrency(i){se(this,Lt,i),Oe(this,Xt,Pe).call(this)}get concurrency(){return B(this,Lt)}};Lt=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,Pe=function(){let i=B(this,Lt)-B(this,Ut);for(let t=0;t{B(this,Ht).delete(e),B(this,Wt).delete(e),se(this,Ut,B(this,Ut)-1),Oe(this,Xt,Pe).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var ji=()=>({"*blocksRegistry":new Set}),Hi=s=>({...ji(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),ze=s=>({...Hi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Me(1)});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var Q=s=>`*cfg/${s}`;var gt=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ps=new Set;function je(s){Ps.has(s)||(Ps.add(s),console.warn(s))}var He=(s,i)=>new Intl.PluralRules(s).select(i);var Wi="lr-",b=class extends zt{constructor(){super();h(this,"allowCustomTemplate",!0);h(this,"init$",ji());h(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return le(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=He(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Wi}${t}`,!0),ki()||(this._destroyInnerHeightTracker=_s()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?le(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=Q(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(je("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${gt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(Q(t));r.ctx.has(r.name)?this.sub(Q(t),e):(this.bindCssData(`--cfg-${gt(t)}`),this.sub(`--cfg-${gt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Wi)?t:Wi+t)}};h(b,"StateConsumerScope",null),h(b,"className","");var ce=class extends b{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}};h(ce,"StateConsumerScope","modal");ce.template=``;var Ms="active",he="___ACTIVITY_IS_ACTIVE___",st=class extends b{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Hi(this));h(this,"_debouncedHistoryFlush",S(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=st._activityRegistry[this.activityKey];this[he]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=st._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[he]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[he]?this._deactivate():this.activityType===t&&!this[he]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!st._activityRegistry[this.activityKey]}get isActivityActive(){return this[he]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;st._activityRegistry||(st._activityRegistry=Object.create(null)),st._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),st._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(st._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setOrAddState("*modalActive",!1)}}},g=st;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ue=33.333333333333336,y=1,Xi=24,Ns=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function tt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Bs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Vs({rect:s,delta:[i,t],imageBox:e}){return Kt({...s,x:s.x+i,y:s.y+t},e)}function Kt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function co({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Yt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Zt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Et(s,i,t){return Math.min(Math.max(s,i),t)}var Xe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var et=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs="blocks",Gs="0.27.1";function qs(s){return Ni({...s,libraryName:Xs,libraryVersion:Gs})}var Ks=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Ge=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ks(i)).join("/-/"),O=(...s)=>{let i=Ge(...s);return i?`-/${i}/`:""};function Ys(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Js(s){let i=Qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ks(n))}function Qs(s){let i=new URL(s),t=Ys(s),e=tr(t)?er(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function tr(s){return s.startsWith("http")}function er(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var I=(s,i,t)=>{let e=new URL(Qs(s));if(t=t||Ys(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),tr(t)){let r=er(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var de=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Gi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],qi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ir=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),pe=s=>{let i=s==null?void 0:s.type;return i?qi(i,de):!1};var nt=1e3,Mt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),fe=s=>Math.ceil(s*100)/100,sr=(s,i=Mt.AUTO)=>{let t=i===Mt.AUTO;if(i===Mt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};h(L,"_timeoutStore",Object.create(null));var rr="[Typed State] Wrong property name: ",bo="[Typed State] Wrong property type: ",qe=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||ne.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(bo+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Ke=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||ne.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new qe(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var nr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var or=s=>s?s.split(",").map(i=>i.trim()):[],Nt=s=>s?s.join(","):"";var v=class extends g{constructor(){super(...arguments);h(this,"couldBeUploadCollectionOwner",!1);h(this,"isUploadCollectionOwner",!1);h(this,"init$",ze(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",S(this._runValidators.bind(this),100));h(this,"_handleCollectionUpdate",t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,L.emit(new V({type:U.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&L.emit(new V({type:U.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{L.emit(new V({type:U.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{L.emit(new V({type:U.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{L.emit(new V({type:U.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){je("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Ke({typedSchema:nr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:pe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:et.API,fullPath:o})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:pe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Nt(Gi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?de:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Nt(de)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:et.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);L.emit(new V({type:U.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),L.emit(new V({type:U.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Gi([...e?de:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=qi(o,n),c=ir(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:sr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Xe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=O(`crop/${u.width}x${u.height}/${u.x},${u.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:I(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:qs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};e.push(a)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(U).forEach(s=>{let i=L.eName(s),t=S(e=>{if([U.UPLOAD_FINISH,U.REMOVE,U.CDN_MODIFICATION].includes(e.detail.type)){let n=E.getCtx(e.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let c=E.getCtx(a).store,u=c.fileInfo;if(u){let d={...u,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||u.cdnUrl};l.push(d)}}),L.emit(new V({type:U.DATA_OUTPUT,ctx:e.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var Y={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function yo(s,i){if(typeof i=="number")return Y[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Y[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Y[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var ar=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return Ge(...ar.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yo(i,t)}).filter(i=>!!i))}var Ye=Ge("format/auto","progressive/yes"),_t=([s])=>typeof s!="undefined"?Number(s):void 0,lr=()=>!0,vo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Co=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),wo={enhance:_t,brightness:_t,exposure:_t,gamma:_t,contrast:_t,saturation:_t,vibrance:_t,warmth:_t,filter:vo,mirror:lr,flip:lr,rotate:_t,crop:Co};function cr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!ar.includes(e))continue;let n=wo[e],o=n(r);i[e]=o}return i}var D=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),G=[D.CROP,D.TUNING,D.FILTERS],hr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],ur=["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"],dr=["rotate","mirror","flip"],ot=Object.freeze({brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}});var To="https://ucarecdn.com",xo="https://upload.uploadcare.com",Eo="https://social.uploadcare.com",me={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Nt(G),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:To,baseUrl:xo,socialBaseUrl:Eo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var q=s=>String(s),lt=s=>Number(s),k=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,Ao=s=>s==="auto"?s:k(s),$o={pubkey:q,multiple:k,multipleMin:lt,multipleMax:lt,confirmUpload:k,imgOnly:k,accept:q,externalSourcesPreferredTypes:q,store:Ao,cameraMirror:k,sourceList:q,maxLocalFileSizeBytes:lt,thumbSize:lt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:q,removeCopyright:k,cropPreset:q,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:q,cdnCname:q,baseUrl:q,socialBaseUrl:q,secureSignature:q,secureExpire:q,secureDeliveryProxy:q,retryThrottledRequestMaxTimes:lt,multipartMinFileSize:lt,multipartChunkSize:lt,maxConcurrentRequests:lt,multipartMaxConcurrentRequests:lt,multipartMaxAttempts:lt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:q},pr=(s,i)=>{if(!(typeof i=="undefined"||i===null))return $o[s](i)};var Ze=Object.keys(me),So=["metadata"],ko=s=>So.includes(s),Ki=Ze.filter(s=>!ko(s)),Io={...Object.fromEntries(Ki.map(s=>[gt(s),s])),...Object.fromEntries(Ki.map(s=>[s.toLowerCase(),s]))},Oo={...Object.fromEntries(Ze.map(s=>[gt(s),Q(s)])),...Object.fromEntries(Ze.map(s=>[s.toLowerCase(),Q(s)]))},Je=class extends b{constructor(){super();h(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(me).map(([t,e])=>[Q(t),e]))}}initCallback(){super.initCallback();for(let t of Ze){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,Ki.includes(t)){let o=[...new Set([gt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[Q(t)]!==n&&(typeof n=="undefined"||n===null?this.$[Q(t)]=me[t]:this.$[Q(t)]=n)},get:()=>this.$[Q(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Io[t],o=pr(n,r),l=o!=null?o:me[n],a=this;a[n]=l}};Je.bindAttributes(Oo);var ge=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ge.template=``;ge.bindAttributes({name:"name",size:"size"});var Lo="https://ucarecdn.com",Dt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Lo},"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 fr=s=>[...new Set(s)];var _e="--lr-img-",mr="unresolved",Jt=2,Qt=3,gr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),br=Object.create(null),_r;for(let s in Dt)br[_e+s]=((_r=Dt[s])==null?void 0:_r.default)||"";var Qe=class extends zt{constructor(){super(...arguments);h(this,"cssInit$",br)}$$(t){return this.$[_e+t]}set$$(t){for(let e in t)this.$[_e+e]=t[e]}sub$$(t,e){this.sub(_e+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!gr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return O(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Dt.format.default}`,`quality/${this.$$("quality")||Dt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(gr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return I(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(I(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(I(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?le(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(mr,""),this.img.onload=()=>{this.img.removeAttribute(mr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Dt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?fr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Jt+"x")}") ${n*Jt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Qt+"x")}") ${n*Qt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Jt))}") ${Jt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Qt))}") ${Qt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Jt+"x")+` ${e*Jt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Qt+"x")+` ${e*Qt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):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(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),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)}static get observedAttributes(){return Object.keys(Dt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[_e+t]=r})}};var Yi=class extends Qe{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var be=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",i=>{typeof i!="undefined"&&(this.$.withDropZone=k(i))}),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};be.template=``;be.bindAttributes({dropzone:null});var Zi=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function Uo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function Ro(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function yr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Uo(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},vr=["focus"],Po=100,Ji=new Map;function Mo(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Qi(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=z.INACTIVE,o=f=>{s.shouldIgnore()&&f!==z.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(z.INACTIVE)},c=()=>{i+=1,n===z.INACTIVE&&o(z.ACTIVE)},u=()=>{i-=1,l()||o(z.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(z.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let _=[f.x,f.y],$=s.element.getBoundingClientRect(),A=Math.floor(Mo(_,$)),T=A{if(s.shouldIgnore())return;f.preventDefault();let _=await yr(f.dataTransfer);s.onItems(_),o(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),vr.forEach(f=>{window.addEventListener(f,a)}),()=>{Ji.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),vr.forEach(f=>{window.removeEventListener(f,a)})}}var ye=class extends v{constructor(){super(),this.init$={...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!k(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:k(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:k(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:k(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Qi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:et.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:et.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=Qi({element:i,onChange:t=>{var r;let e=(r=Object.entries(z).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(z).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=N(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var i,t,e,r;super.destroyCallback(),(t=(i=this.$["lr-drop-area/targets"])==null?void 0:i.remove)==null||t.call(i,this),(e=this._destroyDropzone)==null||e.call(this),(r=this._destroyContentWrapperDropzone)==null||r.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ye.template=`
{{text}}
`;ye.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var No="src-type-",ve=class extends v{constructor(){super(...arguments);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${No}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ve.template=`
`;ve.bindAttributes({type:null});var ts=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function Cr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function wr(s="#fff",i="rgba(0, 0, 0, .1)"){return Cr(``)}function Ce(s="hsl(209, 21%, 65%)",i=32,t=32){return Cr(``)}function Tr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var j=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),bt=class extends v{constructor(){super();h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",S(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",S(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:j.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=j.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=j.FAILED:t.getValue("validationMultipleLimitMsg")?e=j.LIMIT_OVERFLOW:t.getValue("isUploading")?e=j.UPLOADING:t.getValue("fileInfo")&&(e=j.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(I(At(this.cfg.cdnCname,this._entry.getValue("uuid")),O(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Tr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{bt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),bt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===j.FAILED,isLimitOverflow:t===j.LIMIT_OVERFLOW,isUploading:t===j.UPLOADING,isFinished:t===j.FINISHED,progressVisible:t===j.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===j.FAILED||t===j.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===j.FINISHED&&(this.$.badgeIcon="badge-success"),t===j.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),bt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));L.emit(new V({type:U.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=await this.getUploadClientOptions();return zi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof M?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};bt.template=`
{{itemName}}{{errorText}}
`;bt.activeInstances=new Set;var ti=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},ei=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};ei.template=`
{{captionTxt}}
{{msgTxt}}
`;var ii=class extends v{constructor(){super();h(this,"couldBeUploadCollectionOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",S(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new ti,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};ii.template=`{{headerText}}
`;var si=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:et.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};si.template=`
`;var es=()=>typeof navigator.permissions!="undefined";var ri=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:es(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{es()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",S(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:et.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ri.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var is=class extends v{};var ni=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=Ce(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=pe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=I(n,O("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ni.template=`
{{fileSize}}
{{errorTxt}}
`;var ss=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},oi=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ss);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};oi.template=`{{activityCaption}}
{{messageTxt}}
`;var li=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};li.template=``;var ai=class extends b{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ai.template='
';var Z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var we=class extends b{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:Z})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${wr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Z}};we.template='';we.bindAttributes({checkerboard:"checkerboard"});var xr="--cfg-ctx-name",R=class extends b{get cfgCssCtxName(){return this.getCssData(xr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(xr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function Er(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function F(...s){let i=Er(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function Ar(s,...i){let t=Er(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var $r=s=>{if(!s)return G;let i=or(s).filter(t=>G.includes(t));return i.length===0?G:i};function Sr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":G,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Z,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Nt(G),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Z,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=O($t(i)),r=I(t,O(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var kr=`
Network error
{{fileType}}
{{msg}}
`;var at=class extends R{constructor(){super();h(this,"_debouncedShowLoader",S(this._showLoader.bind(this),300));this.init$={...this.init$,...Sr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===D.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Zs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Js(this.$.cdnUrl),r=cr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=I(this.$["*originalUrl"],O("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===D.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Z&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Z)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Xe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=$r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=F("image",{image_hidden_to_cropper:t===D.CROP,image_hidden_effects:t!==D.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=O($t(t)),n=I(e,O(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(at,"className","cloud-image-editor");at.template=kr;at.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ci=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=tt("mask",{id:"backdrop-mask"}),a=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=tt("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Pt(n,f)}else{let f=Et(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:$}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(Xi*Et(Math.min(d,p)/Xi/3,0,1),Ns);Pt(n,{x:$[0]-A,y:$[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",F("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=tt("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=tt("rect",{fill:"transparent"}),l=tt("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=tt("svg"),t=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=tt("line",{x1:`${ue*e}%`,y1:"0%",x2:`${ue*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=tt("line",{x1:"0%",y1:`${ue*e}%`,x2:"100%",y2:`${ue*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Vs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Kt(Zt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Bs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",F("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",F({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ci.template='';var yt=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=F({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function Fo(s){let i=s+90;return i=i>=360?0:i,i}function Bo(s,i){return s==="rotate"?Fo(i):["mirror","flip"].includes(s)?!i:null}var Te=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Bo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var xe={FILTER:"filter",COLOR_OPERATION:"color_operation"},ct="original",hi=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?xe.FILTER:xe.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ct?void 0:this.$.value,filter:this._filter===ct?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ot[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===xe.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===xe.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===xe.FILTER?this._filter===ct?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};hi.template=``;function Ee(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=Z)}}}function Ae(s){let i=[];for(let n of s){let o=Ee(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var te=class extends yt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ct?{name:this._filter,amount:o}:void 0,I(this._originalUrl,O(Ye,$t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=Ee(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{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",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ct,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};te.template=`
`;var $e=class extends yt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ot[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Ir=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function Or(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function ee(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return I(s,O(Ye,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Vo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ui=class extends R{constructor(){super(),this.init$={...this.init$,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=S(this._commit.bind(this),300),this._handleResizeThrottled=Ir(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Or(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=Yt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Zt(l)}_alignCrop(){var c;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[u,d],coords:[p,m]}=n,{width:f}=Yt(this._imageSize,r),_=o/f;i=Kt(Zt({x:l+p*_,y:a+m*_,width:u*_,height:d*_}),this.$["*imageBox"])}if(!n||!Hs(i,t)){let u=(c=this.$["*cropPresetList"])==null?void 0:c[0],d=u?u.width/u.height:void 0,p=t.width/t.height,m=t.width,f=t.height;d&&(p>d?m=Math.min(t.height*d,t.width):f=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Kt(Zt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=Yt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=F({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=Yt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[Et(Math.round(c/d),1,l),Et(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=Yt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),$={dimensions:_,coords:[Et(Math.round((d-l)/m),0,c-_[0]),Et(Math.round((p-a)/f),0,u-_[1])]};if(!Vo($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(_[0]===c&&_[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=F({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(ee(i,e,t)),{promise:n,cancel:o,image:l}=Ee(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ui.template=``;function rs(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function zo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Ho(s,i){return s.map((t,e)=>tn-o)}var ns=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=S(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(ee(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ot[i],r=this._keypoints.map(l=>l.value),n=jo(r,t,e),o=Ho(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Ae(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Lr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=Ae(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Lr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=F({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Wo=1,di=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Wo?this.scrollLeft+=e:this.scrollLeft+=t})}};di.template=" ";function Xo(s){return``}function Go(s){return`
`}var pi=class extends R{constructor(){super();h(this,"_updateInfoTooltip",S(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===D.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(ct);else if(this.$["*tabId"]===D.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||ot[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ct,"*currentOperation":null,"*tabId":D.CROP,showLoader:!1,filters:ur,colorOperations:hr,cropOperations:dr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=S(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===D.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new $e;return e.operation=t,e}_createFilterControl(t){let e=new te;return e.filter=t,e}_createToggleControl(t){let e=new Te;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===D.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===D.FILTERS?[ct,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===D.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===D.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of G){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ee(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Ae([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1,this.$["*tabId"]=t[0];for(let e of G){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}}),this._updateInfoTooltip()}};pi.template=`
{{*operationTooltip}}
${G.map(Go).join("")}
${G.map(Xo).join("")}
`;var Se=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return F("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Se.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Se.template=`
{{text}}
`;var fi=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};fi.template=`
`;var mi={transition:"transition",visible:"visible",hidden:"hidden"},gi=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=mi.visible,this._hiddenStyle=mi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Ar(this,{[mi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(mi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};gi.template=" ";var _i=class extends b{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);h(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new at,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var qo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Ur=function(s,i="i"){let t=s.split("*").map(qo);return new RegExp("^"+t.join(".+")+"$",i)};var Ko=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Rr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Ko({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var St={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in St){let t=St[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Pr=function(s,i,t){s in St||(St[s]=[]),St[s].push([i,t])},Mr=function(s,i){s in St&&(St[s]=St[s].filter(t=>t[0]!==i))};function Nr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var bi=class extends v{constructor(){super();h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Ur(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Rr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Nr(n),o.toString()}mountIframe(){let t=oe({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Pr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Mr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};bi.template=`
{{activityCaption}}
{{counter}}
`;var ke=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=oe({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ke.bindAttributes({"tab-list":null,default:null});ke.template=`
`;var ie=class extends v{constructor(){super(...arguments);h(this,"processInnerHtml",!0);h(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return ie.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Us(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};ie.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ls=class extends g{};var yi=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};yi.template=``;var K={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Dr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},it=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:K.PLAY,fsIcon:K.FS_ON,volIcon:K.VOL_ON,capIcon:K.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Dr.exitFullscreen():Dr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===K.CAP_OFF?(this.$.capIcon=K.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(it.is+":captions","1")):(this.$.capIcon=K.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(it.is+":captions"))}toggleSound(){this.$.volIcon===K.VOL_ON?(this.$.volIcon=K.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=K.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(it.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(it.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=K.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=K.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=K.FS_OFF:this.$.fsIcon=K.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(it.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};it.template=`
{{currentTime}} / {{totalTime}}
`;it.bindAttributes({video:"video",src:"src"});var Yo="css-src";function vi(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Yo);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Ie=class extends vi(b){};var Ci=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(Ci,"template",`Powered by Uploadcare`);var kt=class extends Ie{constructor(){super(...arguments);h(this,"init$",ze(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var wi=class extends kt{};wi.template=``;var Ti=class extends kt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};Ti.template=``;var xi=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};xi.template=``;var as=class extends vi(at){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Zo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,zt as BaseComponent,b as Block,ri as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,at as CloudImageEditorBlock,Je as Config,oi as ConfirmationDialog,Ci as Copyright,ci as CropFrame,E as Data,ie as DataOutput,ye as DropArea,Te as EditorCropButtonControl,te as EditorFilterControl,ui as EditorImageCropper,ns as EditorImageFader,$e as EditorOperationControl,di as EditorScroller,hi as EditorSlider,pi as EditorToolbar,bi as ExternalSource,bt as FileItem,we as FilePreview,xi as FileUploaderInline,Ti as FileUploaderMinimal,wi as FileUploaderRegular,ge as Icon,Yi as Img,fi as LineLoaderUi,Se as LrBtnUi,ei as MessageBox,ce as Modal,Xs as PACKAGE_NAME,Gs as PACKAGE_VERSION,gi as PresenceToggle,ai as ProgressBar,li as ProgressBarCommon,yi as Select,Ie as ShadowWrapper,be as SimpleBtn,_i as SliderUi,ve as SourceBtn,ts as SourceList,Zi as StartFrom,ke as Tabs,is as UploadCtxProvider,ni as UploadDetails,ii as UploadList,v as UploaderBlock,si as UrlSource,it as Video,Zo as connectBlocksFrom,cs as registerBlocks,vi as shadowed,gt as toKebabCase}; \ No newline at end of file diff --git a/web/lr-file-uploader-inline.min.js b/web/lr-file-uploader-inline.min.js index 85e2655ff..56734b0a1 100644 --- a/web/lr-file-uploader-inline.min.js +++ b/web/lr-file-uploader-inline.min.js @@ -24,4 +24,4 @@ * */ var Br=Object.defineProperty;var Vr=(s,i,t)=>i in s?Br(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(Vr(s,typeof i!="symbol"?i+"":i,t),t),Ai=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var B=(s,i,t)=>(Ai(s,i,"read from private field"),t?t.call(s):i.get(s)),Ot=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},se=(s,i,t,e)=>(Ai(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var Oe=(s,i,t)=>(Ai(s,i,"access private method"),t);var zr=Object.defineProperty,jr=(s,i,t)=>i in s?zr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,Si=(s,i,t)=>(jr(s,typeof i!="symbol"?i+"":i,t),t);function Hr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=Hr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var C=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"}),ps="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Wr=ps.length-1,ne=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Gr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function qr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||us;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=us;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).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 Kr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function Yr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Xr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):fs(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var Le="{{",re="}}",Zr="skip-text";function Jr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(Zr))&&r.textContent.includes(Le)&&r.textContent.includes(re)&&1}});for(;i=e.nextNode();)t.push(i);return t}var Qr=function(s,i){Jr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(re);)e.textContent.startsWith(Le)?(n=e.textContent.indexOf(re)+re.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(Le),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(Le,"").replace(re,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},tn=[Gr,qr,Kr,Yr,Qr],Ue="'",Vt='"',en=/\\([0-9a-fA-F]{1,6} ?)/g;function sn(s){return(s[0]===Vt||s[0]===Ue)&&(s[s.length-1]===Vt||s[s.length-1]===Ue)}function rn(s){return(s[0]===Vt||s[0]===Ue)&&(s=s.slice(1)),(s[s.length-1]===Vt||s[s.length-1]===Ue)&&(s=s.slice(0,-1)),s}function nn(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=nn(i),i=Vt+i+Vt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Bt=null,pt=null,vt=class extends HTMLElement{constructor(){super(),Si(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return vt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ne.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=vt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=vt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=vt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=vt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=vt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=vt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])fs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of tn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);pt==null||pt.delete(this.updateCssData),pt!=null&&pt.size||(Bt==null||Bt.disconnect(),Bt=null,pt=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${C.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=on(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){pt||(pt=new Set),pt.add(this.updateCssData),Bt||(Bt=new MutationObserver(s=>{s[0].type==="attributes"&&pt.forEach(i=>{i()})}),Bt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=vt;Si(zt,"template");var $i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent($i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),$i.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};$i.appMap=Object.create(null);function ln(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function an(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function oe(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&an(i,s.attributes),s.styles&&ln(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=oe(t);i.appendChild(e)}),i}var ms="idb-store-ready",cn="symbiote-db",hn="symbiote-idb-update_",un=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return hn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=cn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new un(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Si(gs,"_reg",Object.create(null));function S(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var dn="--uploadcare-blocks-window-height",Re="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ki(){return typeof window[Re]=="undefined"?!1:!!window[Re]}function _s(){if(ki())return;let s=()=>{document.documentElement.style.setProperty(dn,`${window.innerHeight}px`),window[Re]=!0},i=S(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[Re]=!1,window.removeEventListener("resize",i)}}var pn=s=>s,Ii="{{",ys="}}",bs="plural:";function le(s,i,t={}){var o;let{openToken:e=Ii,closeToken:r=ys,transform:n=pn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(Ii);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ii,e)}return i}function Cs(s){return Object.prototype.toString.call(s)==="[object Object]"}var fn=/\W|_/g;function mn(s){return s.split(fn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ws(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>mt(t,{ignoreKeys:i})):s}function mt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ws(s,{ignoreKeys:i});if(!Cs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Cs(r)?r=mt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ws(r,{ignoreKeys:i})),t[mn(e)]=r}return t}var gn=s=>new Promise(i=>setTimeout(i,s));function Ni({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var _n={factor:2,time:100};function bn(s,i=_n){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>gn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Gt=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Gt.prototype),this.originalProgressEvent=t}},Ne=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Ct=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,Ct.prototype)}},yn=500,xs=({check:s,interval:i=yn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Ne(e,()=>{o&&clearTimeout(o),n(new Ct("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ct("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),x={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},De="application/octet-stream",Es="original",Tt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Ne(r,()=>{u=!0,a.abort(),l(new Ct)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let A=$.split(": "),T=A.shift(),w=A.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new Gt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function vn(s,...i){return s}var Cn=({name:s})=>s?[s]:[],wn=vn,Tn=()=>new FormData,As=s=>!1,Fe=s=>typeof Blob!="undefined"&&s instanceof Blob,Be=s=>typeof File!="undefined"&&s instanceof File,Ve=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",ae=s=>Fe(s)||Be(s)||As()||Ve(s),xn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",En=s=>!!s&&typeof s=="object"&&!Array.isArray(s),An=s=>!!s&&typeof s=="object"&&"data"in s&&ae(s.data);function $n(s,i,t){if(An(t)){let{name:e,contentType:r}=t,n=wn(t.data,e,r!=null?r:De),o=Cn({name:e,contentType:r});s.push([i,n,...o])}else if(En(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else xn(t)&&t&&s.push([i,t.toString()])}function Sn(s){let i=[];for(let[t,e]of Object.entries(s))$n(i,t,e);return i}function Di(s){let i=Tn(),t=Sn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var M=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,M.prototype)}},kn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=kn(t)),e.toString()},In="6.6.1",On="UploadcareUploadClient",Ln=In;function Rt(s){return Ni({libraryName:On,libraryVersion:Ln,...s})}var Un="RequestThrottledError",Ts=15e3,Rn=1e3;function Pn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return Ts;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Ts}function xt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return bn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Un&&r{let i="";return(Fe(s)||Be(s)||Ve(s))&&(i=s.type),i||De},Ss=s=>{let i="";return Be(s)&&s.name?i=s.name:Fe(s)||As()?i="":Ve(s)&&s.name&&(i=s.name),i||Es};function Fi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Mn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=x.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({file:{data:s,name:t||Ss(s),contentType:e||$s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Fi(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Ui;(function(s){s.Token="token",s.FileInfo="file_info"})(Ui||(Ui={}));function Nn(s,{publicKey:i,baseURL:t=x.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Fi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var X;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(X||(X={}));var Dn=s=>"status"in s&&s.status===X.Error;function Fn(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=x.retryNetworkErrorMaxTimes}={}){return xt(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Rt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=mt(JSON.parse(a));if("error"in d&&!Dn(d))throw new M(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Bn(s,{publicKey:i,baseURL:t=x.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:a,userAgent:c})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=mt(JSON.parse(p));if("error"in _)throw new M(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Vn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=x.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({filename:e||Es,size:s,content_type:t||De,part_size:r,UPLOADCARE_STORE:Fi(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w.parts=Object.keys(w.parts).map(H=>w.parts[H]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function zn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||De}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function jn(s,{publicKey:i,baseURL:t=x.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},data:Di({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Bi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return xs({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}var wt=class{constructor(i,{baseCDN:t=x.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=ft(t,`${r}/`),l=n?ft(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},Hn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:$})=>Mn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:A})=>Bi({file:A,publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new wt(A,{baseCDN:_})),Wn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Xn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Ne(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Gn=window.WebSocket,Ri=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},qn=(s,i)=>s==="success"?{status:X.Success,...i}:s==="progress"?{status:X.Progress,...i}:{status:X.Error,...i},Pi=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ri);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Gn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,qn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Oi=null,Vi=s=>{if(!Oi){let i=typeof window=="undefined"?0:3e4;Oi=new Pi(s,i)}return Oi},Kn=s=>{Vi(s).connect()};function Yn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return xs({check:c=>Fn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case X.Error:return new M(u.error,u.errorCode);case X.Waiting:return!1;case X.Unknown:return new M(`Token "${s}" was not found.`);case X.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case X.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Zn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Vi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Ne(t,()=>{a(),n(new Ct("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case X.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case X.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case X.Error:a(),n(new M(c.msg,c.error_code))}})}),Jn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:$=x.pusherKey,metadata:A})=>Promise.resolve(Kn($)).then(()=>Nn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(T=>{let w=Vi($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===Ui.FileInfo?T:Xn([({signal:w})=>Yn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:w}),({signal:w})=>Zn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof M)throw T;return T}).then(T=>Bi({file:T.uuid,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(T=>new wt(T,{baseCDN:r})),Li=new WeakMap,Qn=async s=>{if(Li.has(s))return Li.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Li.set(s,i),i},Is=async s=>{if(Be(s)||Fe(s))return s.size;if(Ve(s))return(await Qn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},to=(s,i=x.multipartMinFileSize)=>s>=i,Os=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!ae(s)&&t.test(s)},Ls=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!ae(s)&&t.test(s)},eo=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},so=async(s,i,t)=>e=>io(s,e,i,t),ro=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>zn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),no=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:$=x.multipartChunkSize,maxConcurrentRequests:A=x.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let H=e!=null?e:await Is(s),ht,It=(P,J)=>{if(!c)return;ht||(ht=Array(P).fill(0));let ut=W=>W.reduce((dt,Ei)=>dt+Ei,0);return W=>{W.isComputable&&(ht[J]=W.value,c({isComputable:!0,value:ut(ht)/P}))}};return _||(_=$s(s)),Vn(H,{publicKey:i,contentType:_,fileName:t||Ss(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:P,parts:J})=>{let ut=await so(s,H,$);return Promise.all([P,eo(A,J.map((W,dt)=>()=>ro(ut(dt),W,{publicKey:i,contentType:_,onProgress:It(J.length,dt),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([P])=>jn(P,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(P=>P.isReady?P:Bi({file:P.uuid,publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(P=>new wt(P,{baseCDN:T}))};async function zi(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:$,maxConcurrentRequests:A,baseCDN:T=x.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,pusherKey:ht,metadata:It}){if(ae(s)){let P=await Is(s);return to(P,_)?no(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:P,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It}):Hn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It})}if(Ls(s))return Jn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:ht,metadata:It});if(Os(s))return Wn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var Mi=class{constructor(i,t){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},oo=s=>{for(let i of s)if(!ae(i))return!1;return!0},lo=s=>{for(let i of s)if(!Os(i))return!1;return!0},ao=s=>{for(let i of s)if(!Ls(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=x.multipartChunkSize,baseCDN:$=x.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!oo(s)&&!ao(s)&&!lo(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let H,ht=!0,It=s.length,P=(J,ut)=>{if(!a)return;H||(H=Array(J).fill(0));let W=dt=>dt.reduce((Ei,Fr)=>Ei+Fr)/J;return dt=>{if(!dt.isComputable||!ht){ht=!1,a({isComputable:!1});return}H[ut]=dt.value,a({isComputable:!0,value:W(H)})}};return Promise.all(s.map((J,ut)=>zi(J,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:P(It,ut),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:$,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T}))).then(J=>{let ut=J.map(W=>W.uuid);return Bn(ut,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(W=>new Mi(W,J)).then(W=>(a&&a({isComputable:!0,value:1}),W))})}var Lt,jt,Ut,Ht,Wt,Xt,Pe,Me=class{constructor(i){Ot(this,Xt);Ot(this,Lt,1);Ot(this,jt,[]);Ot(this,Ut,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);se(this,Lt,i)}add(i){return new Promise((t,e)=>{B(this,Ht).set(i,t),B(this,Wt).set(i,e),B(this,jt).push(i),Oe(this,Xt,Pe).call(this)})}get pending(){return B(this,jt).length}get running(){return B(this,Ut)}set concurrency(i){se(this,Lt,i),Oe(this,Xt,Pe).call(this)}get concurrency(){return B(this,Lt)}};Lt=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,Pe=function(){let i=B(this,Lt)-B(this,Ut);for(let t=0;t{B(this,Ht).delete(e),B(this,Wt).delete(e),se(this,Ut,B(this,Ut)-1),Oe(this,Xt,Pe).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var ji=()=>({"*blocksRegistry":new Set}),Hi=s=>({...ji(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),ze=s=>({...Hi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Me(1)});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var Q=s=>`*cfg/${s}`;var gt=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ps=new Set;function je(s){Ps.has(s)||(Ps.add(s),console.warn(s))}var He=(s,i)=>new Intl.PluralRules(s).select(i);var Wi="lr-",b=class extends zt{constructor(){super();h(this,"allowCustomTemplate",!0);h(this,"init$",ji());h(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return le(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=He(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Wi}${t}`,!0),ki()||(this._destroyInnerHeightTracker=_s()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?le(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=Q(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(je("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${gt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(Q(t));r.ctx.has(r.name)?this.sub(Q(t),e):(this.bindCssData(`--cfg-${gt(t)}`),this.sub(`--cfg-${gt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Wi)?t:Wi+t)}};h(b,"StateConsumerScope",null),h(b,"className","");var ce=class extends b{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}};h(ce,"StateConsumerScope","modal");ce.template=``;var Ms="active",he="___ACTIVITY_IS_ACTIVE___",st=class extends b{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Hi(this));h(this,"_debouncedHistoryFlush",S(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=st._activityRegistry[this.activityKey];this[he]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=st._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[he]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[he]?this._deactivate():this.activityType===t&&!this[he]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!st._activityRegistry[this.activityKey]}get isActivityActive(){return this[he]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;st._activityRegistry||(st._activityRegistry=Object.create(null)),st._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),st._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(st._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setOrAddState("*modalActive",!1)}}},g=st;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ue=33.333333333333336,y=1,Xi=24,Ns=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function tt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Bs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Vs({rect:s,delta:[i,t],imageBox:e}){return Kt({...s,x:s.x+i,y:s.y+t},e)}function Kt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function co({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Yt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Zt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Et(s,i,t){return Math.min(Math.max(s,i),t)}var Xe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var et=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs="blocks",Gs="0.27.1";function qs(s){return Ni({...s,libraryName:Xs,libraryVersion:Gs})}var Ks=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Ge=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ks(i)).join("/-/"),O=(...s)=>{let i=Ge(...s);return i?`-/${i}/`:""};function Ys(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Js(s){let i=Qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ks(n))}function Qs(s){let i=new URL(s),t=Ys(s),e=tr(t)?er(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function tr(s){return s.startsWith("http")}function er(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var I=(s,i,t)=>{let e=new URL(Qs(s));if(t=t||Ys(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),tr(t)){let r=er(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var de=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Gi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],qi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ir=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),pe=s=>{let i=s==null?void 0:s.type;return i?qi(i,de):!1};var nt=1e3,Mt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),fe=s=>Math.ceil(s*100)/100,sr=(s,i=Mt.AUTO)=>{let t=i===Mt.AUTO;if(i===Mt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};h(L,"_timeoutStore",Object.create(null));var rr="[Typed State] Wrong property name: ",bo="[Typed State] Wrong property type: ",qe=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||ne.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(bo+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Ke=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||ne.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new qe(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var nr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var or=s=>s?s.split(",").map(i=>i.trim()):[],Nt=s=>s?s.join(","):"";var v=class extends g{constructor(){super(...arguments);h(this,"couldBeUploadCollectionOwner",!1);h(this,"isUploadCollectionOwner",!1);h(this,"init$",ze(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",S(this._runValidators.bind(this),100));h(this,"_handleCollectionUpdate",t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,L.emit(new V({type:U.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&L.emit(new V({type:U.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{L.emit(new V({type:U.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{L.emit(new V({type:U.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{L.emit(new V({type:U.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){je("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Ke({typedSchema:nr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromObject(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:pe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:pe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Nt(Gi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?de:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Nt(de)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:et.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);L.emit(new V({type:U.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),L.emit(new V({type:U.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Gi([...e?de:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=qi(o,n),c=ir(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:sr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Xe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=O(`crop/${u.width}x${u.height}/${u.x},${u.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:I(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:qs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};e.push(a)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(U).forEach(s=>{let i=L.eName(s),t=S(e=>{if([U.UPLOAD_FINISH,U.REMOVE,U.CDN_MODIFICATION].includes(e.detail.type)){let n=E.getCtx(e.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let c=E.getCtx(a).store,u=c.fileInfo;if(u){let d={...u,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||u.cdnUrl};l.push(d)}}),L.emit(new V({type:U.DATA_OUTPUT,ctx:e.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var Y={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function yo(s,i){if(typeof i=="number")return Y[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Y[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Y[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var ar=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return Ge(...ar.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yo(i,t)}).filter(i=>!!i))}var Ye=Ge("format/auto","progressive/yes"),_t=([s])=>typeof s!="undefined"?Number(s):void 0,lr=()=>!0,vo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Co=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),wo={enhance:_t,brightness:_t,exposure:_t,gamma:_t,contrast:_t,saturation:_t,vibrance:_t,warmth:_t,filter:vo,mirror:lr,flip:lr,rotate:_t,crop:Co};function cr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!ar.includes(e))continue;let n=wo[e],o=n(r);i[e]=o}return i}var D=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),G=[D.CROP,D.TUNING,D.FILTERS],hr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],ur=["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"],dr=["rotate","mirror","flip"],ot=Object.freeze({brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}});var To="https://ucarecdn.com",xo="https://upload.uploadcare.com",Eo="https://social.uploadcare.com",me={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Nt(G),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:To,baseUrl:xo,socialBaseUrl:Eo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var q=s=>String(s),lt=s=>Number(s),k=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,Ao=s=>s==="auto"?s:k(s),$o={pubkey:q,multiple:k,multipleMin:lt,multipleMax:lt,confirmUpload:k,imgOnly:k,accept:q,externalSourcesPreferredTypes:q,store:Ao,cameraMirror:k,sourceList:q,maxLocalFileSizeBytes:lt,thumbSize:lt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:q,removeCopyright:k,cropPreset:q,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:q,cdnCname:q,baseUrl:q,socialBaseUrl:q,secureSignature:q,secureExpire:q,secureDeliveryProxy:q,retryThrottledRequestMaxTimes:lt,multipartMinFileSize:lt,multipartChunkSize:lt,maxConcurrentRequests:lt,multipartMaxConcurrentRequests:lt,multipartMaxAttempts:lt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:q},pr=(s,i)=>{if(!(typeof i=="undefined"||i===null))return $o[s](i)};var Ze=Object.keys(me),So=["metadata"],ko=s=>So.includes(s),Ki=Ze.filter(s=>!ko(s)),Io={...Object.fromEntries(Ki.map(s=>[gt(s),s])),...Object.fromEntries(Ki.map(s=>[s.toLowerCase(),s]))},Oo={...Object.fromEntries(Ze.map(s=>[gt(s),Q(s)])),...Object.fromEntries(Ze.map(s=>[s.toLowerCase(),Q(s)]))},Je=class extends b{constructor(){super();h(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(me).map(([t,e])=>[Q(t),e]))}}initCallback(){super.initCallback();for(let t of Ze){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,Ki.includes(t)){let o=[...new Set([gt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[Q(t)]!==n&&(typeof n=="undefined"||n===null?this.$[Q(t)]=me[t]:this.$[Q(t)]=n)},get:()=>this.$[Q(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Io[t],o=pr(n,r),l=o!=null?o:me[n],a=this;a[n]=l}};Je.bindAttributes(Oo);var ge=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ge.template=``;ge.bindAttributes({name:"name",size:"size"});var Lo="https://ucarecdn.com",Dt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Lo},"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 fr=s=>[...new Set(s)];var _e="--lr-img-",mr="unresolved",Jt=2,Qt=3,gr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),br=Object.create(null),_r;for(let s in Dt)br[_e+s]=((_r=Dt[s])==null?void 0:_r.default)||"";var Qe=class extends zt{constructor(){super(...arguments);h(this,"cssInit$",br)}$$(t){return this.$[_e+t]}set$$(t){for(let e in t)this.$[_e+e]=t[e]}sub$$(t,e){this.sub(_e+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!gr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return O(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Dt.format.default}`,`quality/${this.$$("quality")||Dt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(gr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return I(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(I(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(I(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?le(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(mr,""),this.img.onload=()=>{this.img.removeAttribute(mr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Dt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?fr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Jt+"x")}") ${n*Jt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Qt+"x")}") ${n*Qt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Jt))}") ${Jt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Qt))}") ${Qt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Jt+"x")+` ${e*Jt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Qt+"x")+` ${e*Qt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):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(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),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)}static get observedAttributes(){return Object.keys(Dt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[_e+t]=r})}};var Yi=class extends Qe{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var be=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",i=>{typeof i!="undefined"&&(this.$.withDropZone=k(i))}),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};be.template=``;be.bindAttributes({dropzone:null});var Zi=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function Uo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function Ro(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push(c),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function yr(s){let i=[],t=[];for(let e=0;e{i.push(...a)}));continue}let o=r.getAsFile();t.push(Uo(o).then(l=>{l||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},vr=["focus"],Po=100,Ji=new Map;function Mo(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Qi(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=z.INACTIVE,o=f=>{s.shouldIgnore()&&f!==z.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(z.INACTIVE)},c=()=>{i+=1,n===z.INACTIVE&&o(z.ACTIVE)},u=()=>{i-=1,l()||o(z.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(z.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let _=[f.x,f.y],$=s.element.getBoundingClientRect(),A=Math.floor(Mo(_,$)),T=A{if(s.shouldIgnore())return;f.preventDefault();let _=await yr(f.dataTransfer);s.onItems(_),o(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),vr.forEach(f=>{window.addEventListener(f,a)}),()=>{Ji.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),vr.forEach(f=>{window.removeEventListener(f,a)})}}var ye=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return e&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!k(e)})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:k(e)})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:k(e)})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:k(e)})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Qi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:et.DROP_AREA});return}this.addFileFromObject(r,{source:et.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Qi({element:t,onChange:e=>{var n;let r=(n=Object.entries(z).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var n;let r=(n=Object.entries(z).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=N(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,n;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ye.template=`
{{text}}
`;ye.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var No="src-type-",ve=class extends v{constructor(){super(...arguments);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${No}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ve.template=`
`;ve.bindAttributes({type:null});var ts=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function Cr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function wr(s="#fff",i="rgba(0, 0, 0, .1)"){return Cr(``)}function Ce(s="hsl(209, 21%, 65%)",i=32,t=32){return Cr(``)}function Tr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var j=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),bt=class extends v{constructor(){super();h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",S(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",S(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:j.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=j.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=j.FAILED:t.getValue("validationMultipleLimitMsg")?e=j.LIMIT_OVERFLOW:t.getValue("isUploading")?e=j.UPLOADING:t.getValue("fileInfo")&&(e=j.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(I(At(this.cfg.cdnCname,this._entry.getValue("uuid")),O(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Tr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{bt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),bt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===j.FAILED,isLimitOverflow:t===j.LIMIT_OVERFLOW,isUploading:t===j.UPLOADING,isFinished:t===j.FINISHED,progressVisible:t===j.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===j.FAILED||t===j.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===j.FINISHED&&(this.$.badgeIcon="badge-success"),t===j.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),bt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));L.emit(new V({type:U.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=await this.getUploadClientOptions();return zi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof M?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};bt.template=`
{{itemName}}{{errorText}}
`;bt.activeInstances=new Set;var ti=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},ei=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};ei.template=`
{{captionTxt}}
{{msgTxt}}
`;var ii=class extends v{constructor(){super();h(this,"couldBeUploadCollectionOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",S(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new ti,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};ii.template=`{{headerText}}
`;var si=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:et.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};si.template=`
`;var es=()=>typeof navigator.permissions!="undefined";var ri=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:es(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{es()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",S(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:et.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ri.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var is=class extends v{};var ni=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=Ce(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=pe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=I(n,O("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ni.template=`
{{fileSize}}
{{errorTxt}}
`;var ss=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},oi=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ss);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};oi.template=`{{activityCaption}}
{{messageTxt}}
`;var li=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};li.template=``;var ai=class extends b{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ai.template='
';var Z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var we=class extends b{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:Z})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${wr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Z}};we.template='';we.bindAttributes({checkerboard:"checkerboard"});var xr="--cfg-ctx-name",R=class extends b{get cfgCssCtxName(){return this.getCssData(xr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(xr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function Er(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function F(...s){let i=Er(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function Ar(s,...i){let t=Er(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var $r=s=>{if(!s)return G;let i=or(s).filter(t=>G.includes(t));return i.length===0?G:i};function Sr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":G,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Z,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Nt(G),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Z,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=O($t(i)),r=I(t,O(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var kr=`
Network error
{{fileType}}
{{msg}}
`;var at=class extends R{constructor(){super();h(this,"_debouncedShowLoader",S(this._showLoader.bind(this),300));this.init$={...this.init$,...Sr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===D.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Zs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Js(this.$.cdnUrl),r=cr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=I(this.$["*originalUrl"],O("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===D.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Z&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Z)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Xe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=$r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=F("image",{image_hidden_to_cropper:t===D.CROP,image_hidden_effects:t!==D.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=O($t(t)),n=I(e,O(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(at,"className","cloud-image-editor");at.template=kr;at.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ci=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=tt("mask",{id:"backdrop-mask"}),a=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=tt("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Pt(n,f)}else{let f=Et(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:$}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(Xi*Et(Math.min(d,p)/Xi/3,0,1),Ns);Pt(n,{x:$[0]-A,y:$[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",F("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=tt("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=tt("rect",{fill:"transparent"}),l=tt("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=tt("svg"),t=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=tt("line",{x1:`${ue*e}%`,y1:"0%",x2:`${ue*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=tt("line",{x1:"0%",y1:`${ue*e}%`,x2:"100%",y2:`${ue*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Vs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Kt(Zt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Bs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",F("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",F({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ci.template='';var yt=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=F({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function Fo(s){let i=s+90;return i=i>=360?0:i,i}function Bo(s,i){return s==="rotate"?Fo(i):["mirror","flip"].includes(s)?!i:null}var Te=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Bo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var xe={FILTER:"filter",COLOR_OPERATION:"color_operation"},ct="original",hi=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?xe.FILTER:xe.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ct?void 0:this.$.value,filter:this._filter===ct?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ot[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===xe.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===xe.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===xe.FILTER?this._filter===ct?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};hi.template=``;function Ee(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=Z)}}}function Ae(s){let i=[];for(let n of s){let o=Ee(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var te=class extends yt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ct?{name:this._filter,amount:o}:void 0,I(this._originalUrl,O(Ye,$t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=Ee(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{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",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ct,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};te.template=`
`;var $e=class extends yt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ot[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Ir=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function Or(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function ee(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return I(s,O(Ye,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Vo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ui=class extends R{constructor(){super(),this.init$={...this.init$,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=S(this._commit.bind(this),300),this._handleResizeThrottled=Ir(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Or(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=Yt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Zt(l)}_alignCrop(){var c;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[u,d],coords:[p,m]}=n,{width:f}=Yt(this._imageSize,r),_=o/f;i=Kt(Zt({x:l+p*_,y:a+m*_,width:u*_,height:d*_}),this.$["*imageBox"])}if(!n||!Hs(i,t)){let u=(c=this.$["*cropPresetList"])==null?void 0:c[0],d=u?u.width/u.height:void 0,p=t.width/t.height,m=t.width,f=t.height;d&&(p>d?m=Math.min(t.height*d,t.width):f=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Kt(Zt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=Yt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=F({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=Yt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[Et(Math.round(c/d),1,l),Et(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=Yt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),$={dimensions:_,coords:[Et(Math.round((d-l)/m),0,c-_[0]),Et(Math.round((p-a)/f),0,u-_[1])]};if(!Vo($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(_[0]===c&&_[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=F({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(ee(i,e,t)),{promise:n,cancel:o,image:l}=Ee(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ui.template=``;function rs(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function zo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Ho(s,i){return s.map((t,e)=>tn-o)}var ns=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=S(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(ee(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ot[i],r=this._keypoints.map(l=>l.value),n=jo(r,t,e),o=Ho(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Ae(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Lr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=Ae(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Lr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=F({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Wo=1,di=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Wo?this.scrollLeft+=e:this.scrollLeft+=t})}};di.template=" ";function Xo(s){return``}function Go(s){return`
`}var pi=class extends R{constructor(){super();h(this,"_updateInfoTooltip",S(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===D.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(ct);else if(this.$["*tabId"]===D.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||ot[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ct,"*currentOperation":null,"*tabId":D.CROP,showLoader:!1,filters:ur,colorOperations:hr,cropOperations:dr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=S(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===D.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new $e;return e.operation=t,e}_createFilterControl(t){let e=new te;return e.filter=t,e}_createToggleControl(t){let e=new Te;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===D.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===D.FILTERS?[ct,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===D.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===D.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of G){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ee(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Ae([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1,this.$["*tabId"]=t[0];for(let e of G){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}}),this._updateInfoTooltip()}};pi.template=`
{{*operationTooltip}}
${G.map(Go).join("")}
${G.map(Xo).join("")}
`;var Se=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return F("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Se.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Se.template=`
{{text}}
`;var fi=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};fi.template=`
`;var mi={transition:"transition",visible:"visible",hidden:"hidden"},gi=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=mi.visible,this._hiddenStyle=mi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Ar(this,{[mi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(mi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};gi.template=" ";var _i=class extends b{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);h(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new at,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var qo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Ur=function(s,i="i"){let t=s.split("*").map(qo);return new RegExp("^"+t.join(".+")+"$",i)};var Ko=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Rr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Ko({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var St={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in St){let t=St[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Pr=function(s,i,t){s in St||(St[s]=[]),St[s].push([i,t])},Mr=function(s,i){s in St&&(St[s]=St[s].filter(t=>t[0]!==i))};function Nr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var bi=class extends v{constructor(){super();h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Ur(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Rr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Nr(n),o.toString()}mountIframe(){let t=oe({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Pr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Mr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};bi.template=`
{{activityCaption}}
{{counter}}
`;var ke=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=oe({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ke.bindAttributes({"tab-list":null,default:null});ke.template=`
`;var ie=class extends v{constructor(){super(...arguments);h(this,"processInnerHtml",!0);h(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return ie.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Us(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};ie.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ls=class extends g{};var yi=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};yi.template=``;var K={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Dr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},it=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:K.PLAY,fsIcon:K.FS_ON,volIcon:K.VOL_ON,capIcon:K.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Dr.exitFullscreen():Dr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===K.CAP_OFF?(this.$.capIcon=K.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(it.is+":captions","1")):(this.$.capIcon=K.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(it.is+":captions"))}toggleSound(){this.$.volIcon===K.VOL_ON?(this.$.volIcon=K.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=K.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(it.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(it.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=K.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=K.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=K.FS_OFF:this.$.fsIcon=K.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(it.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};it.template=`
{{currentTime}} / {{totalTime}}
`;it.bindAttributes({video:"video",src:"src"});var Yo="css-src";function vi(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Yo);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Ie=class extends vi(b){};var Ci=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(Ci,"template",`Powered by Uploadcare`);var kt=class extends Ie{constructor(){super(...arguments);h(this,"init$",ze(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var wi=class extends kt{};wi.template=``;var Ti=class extends kt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};Ti.template=``;var xi=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};xi.template=``;var as=class extends vi(at){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Zo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,zt as BaseComponent,b as Block,ri as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,at as CloudImageEditorBlock,Je as Config,oi as ConfirmationDialog,Ci as Copyright,ci as CropFrame,E as Data,ie as DataOutput,ye as DropArea,Te as EditorCropButtonControl,te as EditorFilterControl,ui as EditorImageCropper,ns as EditorImageFader,$e as EditorOperationControl,di as EditorScroller,hi as EditorSlider,pi as EditorToolbar,bi as ExternalSource,bt as FileItem,we as FilePreview,xi as FileUploaderInline,Ti as FileUploaderMinimal,wi as FileUploaderRegular,ge as Icon,Yi as Img,fi as LineLoaderUi,Se as LrBtnUi,ei as MessageBox,ce as Modal,Xs as PACKAGE_NAME,Gs as PACKAGE_VERSION,gi as PresenceToggle,ai as ProgressBar,li as ProgressBarCommon,yi as Select,Ie as ShadowWrapper,be as SimpleBtn,_i as SliderUi,ve as SourceBtn,ts as SourceList,Zi as StartFrom,ke as Tabs,is as UploadCtxProvider,ni as UploadDetails,ii as UploadList,v as UploaderBlock,si as UrlSource,it as Video,Zo as connectBlocksFrom,cs as registerBlocks,vi as shadowed,gt as toKebabCase}; \ No newline at end of file +`,"\\n"),i=nn(i),i=Vt+i+Vt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Bt=null,pt=null,vt=class extends HTMLElement{constructor(){super(),Si(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return vt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ne.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=vt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=vt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=vt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=vt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=vt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=vt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])fs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of tn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);pt==null||pt.delete(this.updateCssData),pt!=null&&pt.size||(Bt==null||Bt.disconnect(),Bt=null,pt=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${C.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=on(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){pt||(pt=new Set),pt.add(this.updateCssData),Bt||(Bt=new MutationObserver(s=>{s[0].type==="attributes"&&pt.forEach(i=>{i()})}),Bt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=vt;Si(zt,"template");var $i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent($i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),$i.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};$i.appMap=Object.create(null);function ln(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function an(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function oe(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&an(i,s.attributes),s.styles&&ln(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=oe(t);i.appendChild(e)}),i}var ms="idb-store-ready",cn="symbiote-db",hn="symbiote-idb-update_",un=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return hn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=cn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new un(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Si(gs,"_reg",Object.create(null));function S(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var dn="--uploadcare-blocks-window-height",Re="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ki(){return typeof window[Re]=="undefined"?!1:!!window[Re]}function _s(){if(ki())return;let s=()=>{document.documentElement.style.setProperty(dn,`${window.innerHeight}px`),window[Re]=!0},i=S(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[Re]=!1,window.removeEventListener("resize",i)}}var pn=s=>s,Ii="{{",ys="}}",bs="plural:";function le(s,i,t={}){var o;let{openToken:e=Ii,closeToken:r=ys,transform:n=pn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(Ii);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ii,e)}return i}function Cs(s){return Object.prototype.toString.call(s)==="[object Object]"}var fn=/\W|_/g;function mn(s){return s.split(fn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ws(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>mt(t,{ignoreKeys:i})):s}function mt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ws(s,{ignoreKeys:i});if(!Cs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Cs(r)?r=mt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ws(r,{ignoreKeys:i})),t[mn(e)]=r}return t}var gn=s=>new Promise(i=>setTimeout(i,s));function Ni({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var _n={factor:2,time:100};function bn(s,i=_n){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>gn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Gt=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Gt.prototype),this.originalProgressEvent=t}},Ne=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Ct=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,Ct.prototype)}},yn=500,xs=({check:s,interval:i=yn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Ne(e,()=>{o&&clearTimeout(o),n(new Ct("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ct("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),x={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},De="application/octet-stream",Es="original",Tt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Ne(r,()=>{u=!0,a.abort(),l(new Ct)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let A=$.split(": "),T=A.shift(),w=A.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new Gt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function vn(s,...i){return s}var Cn=({name:s})=>s?[s]:[],wn=vn,Tn=()=>new FormData,As=s=>!1,Fe=s=>typeof Blob!="undefined"&&s instanceof Blob,Be=s=>typeof File!="undefined"&&s instanceof File,Ve=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",ae=s=>Fe(s)||Be(s)||As()||Ve(s),xn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",En=s=>!!s&&typeof s=="object"&&!Array.isArray(s),An=s=>!!s&&typeof s=="object"&&"data"in s&&ae(s.data);function $n(s,i,t){if(An(t)){let{name:e,contentType:r}=t,n=wn(t.data,e,r!=null?r:De),o=Cn({name:e,contentType:r});s.push([i,n,...o])}else if(En(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else xn(t)&&t&&s.push([i,t.toString()])}function Sn(s){let i=[];for(let[t,e]of Object.entries(s))$n(i,t,e);return i}function Di(s){let i=Tn(),t=Sn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var M=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,M.prototype)}},kn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=kn(t)),e.toString()},In="6.6.1",On="UploadcareUploadClient",Ln=In;function Rt(s){return Ni({libraryName:On,libraryVersion:Ln,...s})}var Un="RequestThrottledError",Ts=15e3,Rn=1e3;function Pn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return Ts;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Ts}function xt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return bn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Un&&r{let i="";return(Fe(s)||Be(s)||Ve(s))&&(i=s.type),i||De},Ss=s=>{let i="";return Be(s)&&s.name?i=s.name:Fe(s)||As()?i="":Ve(s)&&s.name&&(i=s.name),i||Es};function Fi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Mn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=x.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({file:{data:s,name:t||Ss(s),contentType:e||$s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Fi(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Ui;(function(s){s.Token="token",s.FileInfo="file_info"})(Ui||(Ui={}));function Nn(s,{publicKey:i,baseURL:t=x.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Fi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var X;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(X||(X={}));var Dn=s=>"status"in s&&s.status===X.Error;function Fn(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=x.retryNetworkErrorMaxTimes}={}){return xt(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Rt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=mt(JSON.parse(a));if("error"in d&&!Dn(d))throw new M(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Bn(s,{publicKey:i,baseURL:t=x.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:a,userAgent:c})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=mt(JSON.parse(p));if("error"in _)throw new M(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Vn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=x.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({filename:e||Es,size:s,content_type:t||De,part_size:r,UPLOADCARE_STORE:Fi(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w.parts=Object.keys(w.parts).map(H=>w.parts[H]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function zn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||De}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function jn(s,{publicKey:i,baseURL:t=x.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},data:Di({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Bi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return xs({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}var wt=class{constructor(i,{baseCDN:t=x.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=ft(t,`${r}/`),l=n?ft(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},Hn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:$})=>Mn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:A})=>Bi({file:A,publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new wt(A,{baseCDN:_})),Wn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Xn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Ne(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Gn=window.WebSocket,Ri=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},qn=(s,i)=>s==="success"?{status:X.Success,...i}:s==="progress"?{status:X.Progress,...i}:{status:X.Error,...i},Pi=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ri);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Gn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,qn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Oi=null,Vi=s=>{if(!Oi){let i=typeof window=="undefined"?0:3e4;Oi=new Pi(s,i)}return Oi},Kn=s=>{Vi(s).connect()};function Yn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return xs({check:c=>Fn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case X.Error:return new M(u.error,u.errorCode);case X.Waiting:return!1;case X.Unknown:return new M(`Token "${s}" was not found.`);case X.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case X.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Zn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Vi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Ne(t,()=>{a(),n(new Ct("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case X.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case X.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case X.Error:a(),n(new M(c.msg,c.error_code))}})}),Jn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:$=x.pusherKey,metadata:A})=>Promise.resolve(Kn($)).then(()=>Nn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(T=>{let w=Vi($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===Ui.FileInfo?T:Xn([({signal:w})=>Yn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:w}),({signal:w})=>Zn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof M)throw T;return T}).then(T=>Bi({file:T.uuid,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(T=>new wt(T,{baseCDN:r})),Li=new WeakMap,Qn=async s=>{if(Li.has(s))return Li.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Li.set(s,i),i},Is=async s=>{if(Be(s)||Fe(s))return s.size;if(Ve(s))return(await Qn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},to=(s,i=x.multipartMinFileSize)=>s>=i,Os=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!ae(s)&&t.test(s)},Ls=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!ae(s)&&t.test(s)},eo=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},so=async(s,i,t)=>e=>io(s,e,i,t),ro=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>zn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),no=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:$=x.multipartChunkSize,maxConcurrentRequests:A=x.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let H=e!=null?e:await Is(s),ht,It=(P,J)=>{if(!c)return;ht||(ht=Array(P).fill(0));let ut=W=>W.reduce((dt,Ei)=>dt+Ei,0);return W=>{W.isComputable&&(ht[J]=W.value,c({isComputable:!0,value:ut(ht)/P}))}};return _||(_=$s(s)),Vn(H,{publicKey:i,contentType:_,fileName:t||Ss(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:P,parts:J})=>{let ut=await so(s,H,$);return Promise.all([P,eo(A,J.map((W,dt)=>()=>ro(ut(dt),W,{publicKey:i,contentType:_,onProgress:It(J.length,dt),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([P])=>jn(P,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(P=>P.isReady?P:Bi({file:P.uuid,publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(P=>new wt(P,{baseCDN:T}))};async function zi(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:$,maxConcurrentRequests:A,baseCDN:T=x.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,pusherKey:ht,metadata:It}){if(ae(s)){let P=await Is(s);return to(P,_)?no(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:P,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It}):Hn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It})}if(Ls(s))return Jn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:ht,metadata:It});if(Os(s))return Wn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var Mi=class{constructor(i,t){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},oo=s=>{for(let i of s)if(!ae(i))return!1;return!0},lo=s=>{for(let i of s)if(!Os(i))return!1;return!0},ao=s=>{for(let i of s)if(!Ls(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=x.multipartChunkSize,baseCDN:$=x.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!oo(s)&&!ao(s)&&!lo(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let H,ht=!0,It=s.length,P=(J,ut)=>{if(!a)return;H||(H=Array(J).fill(0));let W=dt=>dt.reduce((Ei,Fr)=>Ei+Fr)/J;return dt=>{if(!dt.isComputable||!ht){ht=!1,a({isComputable:!1});return}H[ut]=dt.value,a({isComputable:!0,value:W(H)})}};return Promise.all(s.map((J,ut)=>zi(J,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:P(It,ut),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:$,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T}))).then(J=>{let ut=J.map(W=>W.uuid);return Bn(ut,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(W=>new Mi(W,J)).then(W=>(a&&a({isComputable:!0,value:1}),W))})}var Lt,jt,Ut,Ht,Wt,Xt,Pe,Me=class{constructor(i){Ot(this,Xt);Ot(this,Lt,1);Ot(this,jt,[]);Ot(this,Ut,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);se(this,Lt,i)}add(i){return new Promise((t,e)=>{B(this,Ht).set(i,t),B(this,Wt).set(i,e),B(this,jt).push(i),Oe(this,Xt,Pe).call(this)})}get pending(){return B(this,jt).length}get running(){return B(this,Ut)}set concurrency(i){se(this,Lt,i),Oe(this,Xt,Pe).call(this)}get concurrency(){return B(this,Lt)}};Lt=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,Pe=function(){let i=B(this,Lt)-B(this,Ut);for(let t=0;t{B(this,Ht).delete(e),B(this,Wt).delete(e),se(this,Ut,B(this,Ut)-1),Oe(this,Xt,Pe).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var ji=()=>({"*blocksRegistry":new Set}),Hi=s=>({...ji(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),ze=s=>({...Hi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Me(1)});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var Q=s=>`*cfg/${s}`;var gt=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ps=new Set;function je(s){Ps.has(s)||(Ps.add(s),console.warn(s))}var He=(s,i)=>new Intl.PluralRules(s).select(i);var Wi="lr-",b=class extends zt{constructor(){super();h(this,"allowCustomTemplate",!0);h(this,"init$",ji());h(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return le(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=He(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Wi}${t}`,!0),ki()||(this._destroyInnerHeightTracker=_s()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?le(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=Q(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(je("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${gt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(Q(t));r.ctx.has(r.name)?this.sub(Q(t),e):(this.bindCssData(`--cfg-${gt(t)}`),this.sub(`--cfg-${gt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Wi)?t:Wi+t)}};h(b,"StateConsumerScope",null),h(b,"className","");var ce=class extends b{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}};h(ce,"StateConsumerScope","modal");ce.template=``;var Ms="active",he="___ACTIVITY_IS_ACTIVE___",st=class extends b{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Hi(this));h(this,"_debouncedHistoryFlush",S(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=st._activityRegistry[this.activityKey];this[he]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=st._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[he]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[he]?this._deactivate():this.activityType===t&&!this[he]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!st._activityRegistry[this.activityKey]}get isActivityActive(){return this[he]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;st._activityRegistry||(st._activityRegistry=Object.create(null)),st._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),st._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(st._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setOrAddState("*modalActive",!1)}}},g=st;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ue=33.333333333333336,y=1,Xi=24,Ns=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function tt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Bs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Vs({rect:s,delta:[i,t],imageBox:e}){return Kt({...s,x:s.x+i,y:s.y+t},e)}function Kt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function co({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Yt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Zt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Et(s,i,t){return Math.min(Math.max(s,i),t)}var Xe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var et=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs="blocks",Gs="0.27.1";function qs(s){return Ni({...s,libraryName:Xs,libraryVersion:Gs})}var Ks=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Ge=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ks(i)).join("/-/"),O=(...s)=>{let i=Ge(...s);return i?`-/${i}/`:""};function Ys(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Js(s){let i=Qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ks(n))}function Qs(s){let i=new URL(s),t=Ys(s),e=tr(t)?er(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function tr(s){return s.startsWith("http")}function er(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var I=(s,i,t)=>{let e=new URL(Qs(s));if(t=t||Ys(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),tr(t)){let r=er(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var de=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Gi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],qi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ir=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),pe=s=>{let i=s==null?void 0:s.type;return i?qi(i,de):!1};var nt=1e3,Mt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),fe=s=>Math.ceil(s*100)/100,sr=(s,i=Mt.AUTO)=>{let t=i===Mt.AUTO;if(i===Mt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};h(L,"_timeoutStore",Object.create(null));var rr="[Typed State] Wrong property name: ",bo="[Typed State] Wrong property type: ",qe=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||ne.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(bo+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Ke=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||ne.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new qe(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var nr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var or=s=>s?s.split(",").map(i=>i.trim()):[],Nt=s=>s?s.join(","):"";var v=class extends g{constructor(){super(...arguments);h(this,"couldBeUploadCollectionOwner",!1);h(this,"isUploadCollectionOwner",!1);h(this,"init$",ze(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",S(this._runValidators.bind(this),100));h(this,"_handleCollectionUpdate",t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,L.emit(new V({type:U.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&L.emit(new V({type:U.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{L.emit(new V({type:U.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{L.emit(new V({type:U.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{L.emit(new V({type:U.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){je("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Ke({typedSchema:nr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:pe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:et.API,fullPath:o})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:pe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Nt(Gi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?de:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Nt(de)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:et.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);L.emit(new V({type:U.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),L.emit(new V({type:U.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Gi([...e?de:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=qi(o,n),c=ir(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:sr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Xe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=O(`crop/${u.width}x${u.height}/${u.x},${u.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:I(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:qs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};e.push(a)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(U).forEach(s=>{let i=L.eName(s),t=S(e=>{if([U.UPLOAD_FINISH,U.REMOVE,U.CDN_MODIFICATION].includes(e.detail.type)){let n=E.getCtx(e.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let c=E.getCtx(a).store,u=c.fileInfo;if(u){let d={...u,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||u.cdnUrl};l.push(d)}}),L.emit(new V({type:U.DATA_OUTPUT,ctx:e.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var Y={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function yo(s,i){if(typeof i=="number")return Y[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Y[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Y[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var ar=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return Ge(...ar.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yo(i,t)}).filter(i=>!!i))}var Ye=Ge("format/auto","progressive/yes"),_t=([s])=>typeof s!="undefined"?Number(s):void 0,lr=()=>!0,vo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Co=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),wo={enhance:_t,brightness:_t,exposure:_t,gamma:_t,contrast:_t,saturation:_t,vibrance:_t,warmth:_t,filter:vo,mirror:lr,flip:lr,rotate:_t,crop:Co};function cr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!ar.includes(e))continue;let n=wo[e],o=n(r);i[e]=o}return i}var D=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),G=[D.CROP,D.TUNING,D.FILTERS],hr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],ur=["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"],dr=["rotate","mirror","flip"],ot=Object.freeze({brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}});var To="https://ucarecdn.com",xo="https://upload.uploadcare.com",Eo="https://social.uploadcare.com",me={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Nt(G),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:To,baseUrl:xo,socialBaseUrl:Eo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var q=s=>String(s),lt=s=>Number(s),k=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,Ao=s=>s==="auto"?s:k(s),$o={pubkey:q,multiple:k,multipleMin:lt,multipleMax:lt,confirmUpload:k,imgOnly:k,accept:q,externalSourcesPreferredTypes:q,store:Ao,cameraMirror:k,sourceList:q,maxLocalFileSizeBytes:lt,thumbSize:lt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:q,removeCopyright:k,cropPreset:q,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:q,cdnCname:q,baseUrl:q,socialBaseUrl:q,secureSignature:q,secureExpire:q,secureDeliveryProxy:q,retryThrottledRequestMaxTimes:lt,multipartMinFileSize:lt,multipartChunkSize:lt,maxConcurrentRequests:lt,multipartMaxConcurrentRequests:lt,multipartMaxAttempts:lt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:q},pr=(s,i)=>{if(!(typeof i=="undefined"||i===null))return $o[s](i)};var Ze=Object.keys(me),So=["metadata"],ko=s=>So.includes(s),Ki=Ze.filter(s=>!ko(s)),Io={...Object.fromEntries(Ki.map(s=>[gt(s),s])),...Object.fromEntries(Ki.map(s=>[s.toLowerCase(),s]))},Oo={...Object.fromEntries(Ze.map(s=>[gt(s),Q(s)])),...Object.fromEntries(Ze.map(s=>[s.toLowerCase(),Q(s)]))},Je=class extends b{constructor(){super();h(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(me).map(([t,e])=>[Q(t),e]))}}initCallback(){super.initCallback();for(let t of Ze){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,Ki.includes(t)){let o=[...new Set([gt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[Q(t)]!==n&&(typeof n=="undefined"||n===null?this.$[Q(t)]=me[t]:this.$[Q(t)]=n)},get:()=>this.$[Q(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Io[t],o=pr(n,r),l=o!=null?o:me[n],a=this;a[n]=l}};Je.bindAttributes(Oo);var ge=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ge.template=``;ge.bindAttributes({name:"name",size:"size"});var Lo="https://ucarecdn.com",Dt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Lo},"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 fr=s=>[...new Set(s)];var _e="--lr-img-",mr="unresolved",Jt=2,Qt=3,gr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),br=Object.create(null),_r;for(let s in Dt)br[_e+s]=((_r=Dt[s])==null?void 0:_r.default)||"";var Qe=class extends zt{constructor(){super(...arguments);h(this,"cssInit$",br)}$$(t){return this.$[_e+t]}set$$(t){for(let e in t)this.$[_e+e]=t[e]}sub$$(t,e){this.sub(_e+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!gr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return O(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Dt.format.default}`,`quality/${this.$$("quality")||Dt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(gr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return I(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(I(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(I(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?le(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(mr,""),this.img.onload=()=>{this.img.removeAttribute(mr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Dt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?fr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Jt+"x")}") ${n*Jt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Qt+"x")}") ${n*Qt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Jt))}") ${Jt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Qt))}") ${Qt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Jt+"x")+` ${e*Jt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Qt+"x")+` ${e*Qt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):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(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),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)}static get observedAttributes(){return Object.keys(Dt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[_e+t]=r})}};var Yi=class extends Qe{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var be=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",i=>{typeof i!="undefined"&&(this.$.withDropZone=k(i))}),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};be.template=``;be.bindAttributes({dropzone:null});var Zi=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function Uo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function Ro(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function yr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Uo(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},vr=["focus"],Po=100,Ji=new Map;function Mo(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Qi(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=z.INACTIVE,o=f=>{s.shouldIgnore()&&f!==z.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(z.INACTIVE)},c=()=>{i+=1,n===z.INACTIVE&&o(z.ACTIVE)},u=()=>{i-=1,l()||o(z.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(z.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let _=[f.x,f.y],$=s.element.getBoundingClientRect(),A=Math.floor(Mo(_,$)),T=A{if(s.shouldIgnore())return;f.preventDefault();let _=await yr(f.dataTransfer);s.onItems(_),o(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),vr.forEach(f=>{window.addEventListener(f,a)}),()=>{Ji.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),vr.forEach(f=>{window.removeEventListener(f,a)})}}var ye=class extends v{constructor(){super(),this.init$={...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!k(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:k(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:k(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:k(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Qi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:et.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:et.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=Qi({element:i,onChange:t=>{var r;let e=(r=Object.entries(z).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(z).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=N(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var i,t,e,r;super.destroyCallback(),(t=(i=this.$["lr-drop-area/targets"])==null?void 0:i.remove)==null||t.call(i,this),(e=this._destroyDropzone)==null||e.call(this),(r=this._destroyContentWrapperDropzone)==null||r.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ye.template=`
{{text}}
`;ye.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var No="src-type-",ve=class extends v{constructor(){super(...arguments);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${No}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ve.template=`
`;ve.bindAttributes({type:null});var ts=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function Cr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function wr(s="#fff",i="rgba(0, 0, 0, .1)"){return Cr(``)}function Ce(s="hsl(209, 21%, 65%)",i=32,t=32){return Cr(``)}function Tr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var j=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),bt=class extends v{constructor(){super();h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",S(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",S(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:j.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=j.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=j.FAILED:t.getValue("validationMultipleLimitMsg")?e=j.LIMIT_OVERFLOW:t.getValue("isUploading")?e=j.UPLOADING:t.getValue("fileInfo")&&(e=j.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(I(At(this.cfg.cdnCname,this._entry.getValue("uuid")),O(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Tr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{bt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),bt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===j.FAILED,isLimitOverflow:t===j.LIMIT_OVERFLOW,isUploading:t===j.UPLOADING,isFinished:t===j.FINISHED,progressVisible:t===j.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===j.FAILED||t===j.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===j.FINISHED&&(this.$.badgeIcon="badge-success"),t===j.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),bt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));L.emit(new V({type:U.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=await this.getUploadClientOptions();return zi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof M?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};bt.template=`
{{itemName}}{{errorText}}
`;bt.activeInstances=new Set;var ti=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},ei=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};ei.template=`
{{captionTxt}}
{{msgTxt}}
`;var ii=class extends v{constructor(){super();h(this,"couldBeUploadCollectionOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",S(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new ti,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};ii.template=`{{headerText}}
`;var si=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:et.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};si.template=`
`;var es=()=>typeof navigator.permissions!="undefined";var ri=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:es(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{es()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",S(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:et.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ri.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var is=class extends v{};var ni=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=Ce(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=pe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=I(n,O("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ni.template=`
{{fileSize}}
{{errorTxt}}
`;var ss=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},oi=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ss);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};oi.template=`{{activityCaption}}
{{messageTxt}}
`;var li=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};li.template=``;var ai=class extends b{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ai.template='
';var Z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var we=class extends b{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:Z})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${wr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Z}};we.template='';we.bindAttributes({checkerboard:"checkerboard"});var xr="--cfg-ctx-name",R=class extends b{get cfgCssCtxName(){return this.getCssData(xr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(xr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function Er(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function F(...s){let i=Er(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function Ar(s,...i){let t=Er(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var $r=s=>{if(!s)return G;let i=or(s).filter(t=>G.includes(t));return i.length===0?G:i};function Sr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":G,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Z,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Nt(G),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Z,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=O($t(i)),r=I(t,O(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var kr=`
Network error
{{fileType}}
{{msg}}
`;var at=class extends R{constructor(){super();h(this,"_debouncedShowLoader",S(this._showLoader.bind(this),300));this.init$={...this.init$,...Sr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===D.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Zs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Js(this.$.cdnUrl),r=cr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=I(this.$["*originalUrl"],O("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===D.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Z&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Z)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Xe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=$r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=F("image",{image_hidden_to_cropper:t===D.CROP,image_hidden_effects:t!==D.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=O($t(t)),n=I(e,O(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(at,"className","cloud-image-editor");at.template=kr;at.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ci=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=tt("mask",{id:"backdrop-mask"}),a=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=tt("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Pt(n,f)}else{let f=Et(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:$}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(Xi*Et(Math.min(d,p)/Xi/3,0,1),Ns);Pt(n,{x:$[0]-A,y:$[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",F("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=tt("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=tt("rect",{fill:"transparent"}),l=tt("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=tt("svg"),t=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=tt("line",{x1:`${ue*e}%`,y1:"0%",x2:`${ue*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=tt("line",{x1:"0%",y1:`${ue*e}%`,x2:"100%",y2:`${ue*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Vs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Kt(Zt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Bs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",F("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",F({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ci.template='';var yt=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=F({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function Fo(s){let i=s+90;return i=i>=360?0:i,i}function Bo(s,i){return s==="rotate"?Fo(i):["mirror","flip"].includes(s)?!i:null}var Te=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Bo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var xe={FILTER:"filter",COLOR_OPERATION:"color_operation"},ct="original",hi=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?xe.FILTER:xe.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ct?void 0:this.$.value,filter:this._filter===ct?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ot[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===xe.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===xe.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===xe.FILTER?this._filter===ct?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};hi.template=``;function Ee(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=Z)}}}function Ae(s){let i=[];for(let n of s){let o=Ee(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var te=class extends yt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ct?{name:this._filter,amount:o}:void 0,I(this._originalUrl,O(Ye,$t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=Ee(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{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",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ct,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};te.template=`
`;var $e=class extends yt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ot[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Ir=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function Or(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function ee(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return I(s,O(Ye,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Vo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ui=class extends R{constructor(){super(),this.init$={...this.init$,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=S(this._commit.bind(this),300),this._handleResizeThrottled=Ir(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Or(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=Yt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Zt(l)}_alignCrop(){var c;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[u,d],coords:[p,m]}=n,{width:f}=Yt(this._imageSize,r),_=o/f;i=Kt(Zt({x:l+p*_,y:a+m*_,width:u*_,height:d*_}),this.$["*imageBox"])}if(!n||!Hs(i,t)){let u=(c=this.$["*cropPresetList"])==null?void 0:c[0],d=u?u.width/u.height:void 0,p=t.width/t.height,m=t.width,f=t.height;d&&(p>d?m=Math.min(t.height*d,t.width):f=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Kt(Zt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=Yt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=F({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=Yt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[Et(Math.round(c/d),1,l),Et(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=Yt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),$={dimensions:_,coords:[Et(Math.round((d-l)/m),0,c-_[0]),Et(Math.round((p-a)/f),0,u-_[1])]};if(!Vo($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(_[0]===c&&_[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=F({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(ee(i,e,t)),{promise:n,cancel:o,image:l}=Ee(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ui.template=``;function rs(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function zo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Ho(s,i){return s.map((t,e)=>tn-o)}var ns=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=S(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(ee(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ot[i],r=this._keypoints.map(l=>l.value),n=jo(r,t,e),o=Ho(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Ae(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Lr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=Ae(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Lr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=F({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Wo=1,di=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Wo?this.scrollLeft+=e:this.scrollLeft+=t})}};di.template=" ";function Xo(s){return``}function Go(s){return`
`}var pi=class extends R{constructor(){super();h(this,"_updateInfoTooltip",S(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===D.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(ct);else if(this.$["*tabId"]===D.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||ot[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ct,"*currentOperation":null,"*tabId":D.CROP,showLoader:!1,filters:ur,colorOperations:hr,cropOperations:dr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=S(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===D.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new $e;return e.operation=t,e}_createFilterControl(t){let e=new te;return e.filter=t,e}_createToggleControl(t){let e=new Te;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===D.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===D.FILTERS?[ct,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===D.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===D.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of G){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ee(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Ae([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1,this.$["*tabId"]=t[0];for(let e of G){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}}),this._updateInfoTooltip()}};pi.template=`
{{*operationTooltip}}
${G.map(Go).join("")}
${G.map(Xo).join("")}
`;var Se=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return F("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Se.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Se.template=`
{{text}}
`;var fi=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};fi.template=`
`;var mi={transition:"transition",visible:"visible",hidden:"hidden"},gi=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=mi.visible,this._hiddenStyle=mi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Ar(this,{[mi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(mi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};gi.template=" ";var _i=class extends b{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);h(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new at,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var qo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Ur=function(s,i="i"){let t=s.split("*").map(qo);return new RegExp("^"+t.join(".+")+"$",i)};var Ko=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Rr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Ko({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var St={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in St){let t=St[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Pr=function(s,i,t){s in St||(St[s]=[]),St[s].push([i,t])},Mr=function(s,i){s in St&&(St[s]=St[s].filter(t=>t[0]!==i))};function Nr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var bi=class extends v{constructor(){super();h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Ur(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Rr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Nr(n),o.toString()}mountIframe(){let t=oe({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Pr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Mr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};bi.template=`
{{activityCaption}}
{{counter}}
`;var ke=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=oe({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ke.bindAttributes({"tab-list":null,default:null});ke.template=`
`;var ie=class extends v{constructor(){super(...arguments);h(this,"processInnerHtml",!0);h(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return ie.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Us(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};ie.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ls=class extends g{};var yi=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};yi.template=``;var K={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Dr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},it=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:K.PLAY,fsIcon:K.FS_ON,volIcon:K.VOL_ON,capIcon:K.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Dr.exitFullscreen():Dr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===K.CAP_OFF?(this.$.capIcon=K.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(it.is+":captions","1")):(this.$.capIcon=K.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(it.is+":captions"))}toggleSound(){this.$.volIcon===K.VOL_ON?(this.$.volIcon=K.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=K.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(it.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(it.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=K.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=K.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=K.FS_OFF:this.$.fsIcon=K.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(it.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};it.template=`
{{currentTime}} / {{totalTime}}
`;it.bindAttributes({video:"video",src:"src"});var Yo="css-src";function vi(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Yo);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Ie=class extends vi(b){};var Ci=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(Ci,"template",`Powered by Uploadcare`);var kt=class extends Ie{constructor(){super(...arguments);h(this,"init$",ze(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var wi=class extends kt{};wi.template=``;var Ti=class extends kt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};Ti.template=``;var xi=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};xi.template=``;var as=class extends vi(at){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Zo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,zt as BaseComponent,b as Block,ri as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,at as CloudImageEditorBlock,Je as Config,oi as ConfirmationDialog,Ci as Copyright,ci as CropFrame,E as Data,ie as DataOutput,ye as DropArea,Te as EditorCropButtonControl,te as EditorFilterControl,ui as EditorImageCropper,ns as EditorImageFader,$e as EditorOperationControl,di as EditorScroller,hi as EditorSlider,pi as EditorToolbar,bi as ExternalSource,bt as FileItem,we as FilePreview,xi as FileUploaderInline,Ti as FileUploaderMinimal,wi as FileUploaderRegular,ge as Icon,Yi as Img,fi as LineLoaderUi,Se as LrBtnUi,ei as MessageBox,ce as Modal,Xs as PACKAGE_NAME,Gs as PACKAGE_VERSION,gi as PresenceToggle,ai as ProgressBar,li as ProgressBarCommon,yi as Select,Ie as ShadowWrapper,be as SimpleBtn,_i as SliderUi,ve as SourceBtn,ts as SourceList,Zi as StartFrom,ke as Tabs,is as UploadCtxProvider,ni as UploadDetails,ii as UploadList,v as UploaderBlock,si as UrlSource,it as Video,Zo as connectBlocksFrom,cs as registerBlocks,vi as shadowed,gt as toKebabCase}; \ No newline at end of file diff --git a/web/lr-file-uploader-minimal.min.js b/web/lr-file-uploader-minimal.min.js index 13513cb2f..5acd98567 100644 --- a/web/lr-file-uploader-minimal.min.js +++ b/web/lr-file-uploader-minimal.min.js @@ -23,5 +23,5 @@ * SOFTWARE. * */ -var Li=Object.defineProperty;var Mi=(e,i,t)=>i in e?Li(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t;var u=(e,i,t)=>(Mi(e,typeof i!="symbol"?i+"":i,t),t),ae=(e,i,t)=>{if(!i.has(e))throw TypeError("Cannot "+t)};var L=(e,i,t)=>(ae(e,i,"read from private field"),t?t.call(e):i.get(e)),at=(e,i,t)=>{if(i.has(e))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(e):i.set(e,t)},Tt=(e,i,t,r)=>(ae(e,i,"write to private field"),r?r.call(e,t):i.set(e,t),t);var Mt=(e,i,t)=>(ae(e,i,"access private method"),t);function ki(e){for(let i in e){let t=[...i].reduce((r,s)=>(s.toUpperCase()===s&&(s="-"+s.toLowerCase()),r+=s),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),e[i].reg&&e[i].reg(t)}}var Pi=Object.defineProperty,Ni=(e,i,t)=>i in e?Pi(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t,ce=(e,i,t)=>(Ni(e,typeof i!="symbol"?i+"":i,t),t);function Di(e){let i=t=>{var r;for(let s in t)((r=t[s])==null?void 0:r.constructor)===Object&&(t[s]=i(t[s]));return{...t}};return i(e)}var E=class{constructor(e){e.constructor===Object?this.store=Di(e):(this._storeIsProxy=!0,this.store=e),this.callbackMap=Object.create(null)}static warn(e,i){console.warn(`Symbiote Data: cannot ${e}. Prop name: `+i)}read(e){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(E.warn("read",e),null):this.store[e]}has(e){return this._storeIsProxy?this.store[e]!==void 0:this.store.hasOwnProperty(e)}add(e,i,t=!1){!t&&Object.keys(this.store).includes(e)||(this.store[e]=i,this.notify(e))}pub(e,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(e)){E.warn("publish",e);return}this.store[e]=i,this.notify(e)}multiPub(e){for(let i in e)this.pub(i,e[i])}notify(e){this.callbackMap[e]&&this.callbackMap[e].forEach(i=>{i(this.store[e])})}sub(e,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(E.warn("subscribe",e),null):(this.callbackMap[e]||(this.callbackMap[e]=new Set),this.callbackMap[e].add(i),t&&i(this.store[e]),{remove:()=>{this.callbackMap[e].delete(i),this.callbackMap[e].size||delete this.callbackMap[e]},callback:i})}static registerCtx(e,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(e),E.globalStore.set(i,t)),t}static deleteCtx(e){E.globalStore.delete(e)}static getCtx(e,i=!0){return E.globalStore.get(e)||(i&&console.warn('State: wrong context UID - "'+e+'"'),null)}};E.globalStore=new Map;var _=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),He="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",$i=He.length-1,wt=class{static generate(e="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Vi(e,i){[...e.querySelectorAll(`[${_.REPEAT_ATTR}]`)].forEach(t=>{let r=t.getAttribute(_.REPEAT_ITEM_TAG_ATTR),s;if(r&&(s=window.customElements.get(r)),!s){s=class extends i.BaseComponent{constructor(){super(),r||(this.style.display="contents")}};let o=t.innerHTML;s.template=o,s.reg(r)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(_.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,h=c=>{c.forEach((f,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(f)});else for(let p in f)l[m][p]=f[p];else{a||(a=new DocumentFragment);let p=new s;Object.assign(p.init$,f),a.appendChild(p)}}),a&&t.appendChild(a);let d=l.slice(c.length,l.length);for(let f of d)f.remove()};if(o.constructor===Array)h(o);else if(o.constructor===Object){let c=[];for(let d in o){let f=o[d];Object.defineProperty(f,"_KEY_",{value:d,enumerable:!0}),c.push(f)}h(c)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(_.REPEAT_ATTR),t.removeAttribute(_.REPEAT_ITEM_TAG_ATTR)})}var ze="__default__";function zi(e,i){if(i.shadowRoot)return;let t=[...e.querySelectorAll("slot")];if(!t.length)return;let r={};t.forEach(s=>{let n=s.getAttribute("name")||ze;r[n]={slot:s,fr:document.createDocumentFragment()}}),i.initChildren.forEach(s=>{var n;let o=ze;s instanceof Element&&s.hasAttribute("slot")&&(o=s.getAttribute("slot"),s.removeAttribute("slot")),(n=r[o])==null||n.fr.appendChild(s)}),Object.values(r).forEach(s=>{if(s.fr.childNodes.length)s.slot.parentNode.replaceChild(s.fr,s.slot);else if(s.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...s.slot.childNodes),s.slot.parentNode.replaceChild(n,s.slot)}else s.slot.remove()})}function ji(e,i){[...e.querySelectorAll(`[${_.EL_REF_ATTR}]`)].forEach(t=>{let r=t.getAttribute(_.EL_REF_ATTR);i.ref[r]=t,t.removeAttribute(_.EL_REF_ATTR)})}function Hi(e,i){[...e.querySelectorAll(`[${_.BIND_ATTR}]`)].forEach(t=>{let s=t.getAttribute(_.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Fi(n.name.replace("-",""));s.push(o+":"+n.value),t.removeAttribute(n.name)}}),s.forEach(n=>{if(!n)return;let o=n.split(":").map(c=>c.trim()),l=o[0],a;l.indexOf(_.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(_.ATTR_BIND_PRFX,""));let h=o[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("!","")),i.sub(c,f=>{d==="double"?f=!!f:d==="single"&&(f=!f),a?(f==null?void 0:f.constructor)===Boolean?f?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,f):We(t,l,f)||(t[_.SET_LATER_KEY]||(t[_.SET_LATER_KEY]=Object.create(null)),t[_.SET_LATER_KEY][l]=f)})}}),t.removeAttribute(_.BIND_ATTR)})}var kt="{{",vt="}}",Wi="skip-text";function Xi(e){let i,t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:s=>{var n;return!((n=s.parentElement)!=null&&n.hasAttribute(Wi))&&s.textContent.includes(kt)&&s.textContent.includes(vt)&&1}});for(;i=r.nextNode();)t.push(i);return t}var Bi=function(e,i){Xi(e).forEach(r=>{let s=[],n;for(;r.textContent.includes(vt);)r.textContent.startsWith(kt)?(n=r.textContent.indexOf(vt)+vt.length,r.splitText(n),s.push(r)):(n=r.textContent.indexOf(kt),r.splitText(n)),r=r.nextSibling;s.forEach(o=>{let l=o.textContent.replace(kt,"").replace(vt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Gi=[Vi,zi,ji,Hi,Bi],Pt="'",pt='"',qi=/\\([0-9a-fA-F]{1,6} ?)/g;function Ki(e){return(e[0]===pt||e[0]===Pt)&&(e[e.length-1]===pt||e[e.length-1]===Pt)}function Yi(e){return(e[0]===pt||e[0]===Pt)&&(e=e.slice(1)),(e[e.length-1]===pt||e[e.length-1]===Pt)&&(e=e.slice(0,-1)),e}function Ji(e){let i="",t="";for(var r=0;rString.fromCodePoint(parseInt(r.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=Ji(i),i=pt+i+pt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${e}`)}}var je=0,ft=null,Y=null,tt=class extends HTMLElement{constructor(){super(),ce(this,"updateCssData",()=>{var e;this.dropCssDataCache(),(e=this.__boundCssProps)==null||e.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return tt}initCallback(){}__initCallback(){var e;this.__initialized||(this.__initialized=!0,(e=this.initCallback)==null||e.call(this))}render(e,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(_.USE_TPL);if(s){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(s))||document.querySelector(s);o?e=o.content.cloneNode(!0):console.warn(`Symbiote template "${s}" is not found...`)}}if(this.processInnerHtml)for(let s of this.tplProcessors)s(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==null?void 0:e.constructor)===DocumentFragment)t=e;else if((e==null?void 0:e.constructor)===String){let s=document.createElement("template");s.innerHTML=e,t=s.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(t,this)}let r=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let s=document.createElement("link");s.rel="stylesheet",s.href=this.constructor.__shadowStylesUrl,s.onload=r,this.shadowRoot.prepend(s)}else r()}addTemplateProcessor(e){this.tplProcessors.add(e)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=wt.generate(),this.style.setProperty(_.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(_.CSS_CTX_PROP,!0)}get ctxName(){var e;let i=((e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(e,i){let t,r;if(e.startsWith(_.EXT_DATA_CTX_PRFX))t=i.nodeCtx,r=e.replace(_.EXT_DATA_CTX_PRFX,"");else if(e.includes(_.NAMED_DATA_CTX_SPLTR)){let s=e.split(_.NAMED_DATA_CTX_SPLTR);t=E.getCtx(s[0]),r=s[1]}else t=i.localCtx,r=e;return{ctx:t,name:r}}sub(e,i,t=!0){let r=n=>{this.isConnected&&i(n)},s=tt.__parseProp(e,this);s.ctx.has(s.name)?this.allSubs.add(s.ctx.sub(s.name,r,t)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,r,t))})}notify(e){let i=tt.__parseProp(e,this);i.ctx.notify(i.name)}has(e){let i=tt.__parseProp(e,this);return i.ctx.has(i.name)}add(e,i,t=!1){let r=tt.__parseProp(e,this);r.ctx.add(r.name,i,t)}add$(e,i=!1){for(let t in e)this.add(t,e[t],i)}get $(){if(!this.__stateProxy){let e=Object.create(null);this.__stateProxy=new Proxy(e,{set:(i,t,r)=>{let s=tt.__parseProp(t,this);return s.ctx.pub(s.name,r),!0},get:(i,t)=>{let r=tt.__parseProp(t,this);return r.ctx.read(r.name)}})}return this.__stateProxy}set$(e,i=!1){for(let t in e){let r=e[t];i||![String,Number,Boolean].includes(r==null?void 0:r.constructor)?this.$[t]=r:this.$[t]!==r&&(this.$[t]=r)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(_.CTX_OWNER_ATTR)&&this.getAttribute(_.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let e=this.constructor.__attrDesc;if(e)for(let i of Object.values(e))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(_.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(_.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(_.NAMED_DATA_CTX_SPLTR)){let t=i.split(_.NAMED_DATA_CTX_SPLTR),r=t[0].trim(),s=t[1].trim();if(r&&s){let n=E.getCtx(r,!1);n||(n=E.registerCtx({},r)),n.add(s,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var e;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim();if(i&&this.style.setProperty(_.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[_.SET_LATER_KEY]){for(let t in this[_.SET_LATER_KEY])We(this,t,this[_.SET_LATER_KEY][t]);delete this[_.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Gi)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${_.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(_.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(s):t.prepend(s)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let e of this.allSubs)e.remove(),this.allSubs.delete(e);for(let e of this.tplProcessors)this.tplProcessors.delete(e);Y==null||Y.delete(this.updateCssData),Y!=null&&Y.size||(ft==null||ft.disconnect(),ft=null,Y=null)},100)))}static reg(e,i=!1){e||(je++,e=`${_.AUTO_TAG_PRFX}-${je}`),this.__tag=e;let t=window.customElements.get(e);if(t){!i&&t!==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,i?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,i,t){var r;if(i===t)return;let s=(r=this.constructor.__attrDesc)==null?void 0:r[e];s?this.__dataCtxInitialized?this.$[s]=t:this.init$[s]=t:this[e]=t}getCssData(e,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(e)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(e).trim();try{this.__cssDataCache[e]=Qi(t)}catch{!i&&console.warn(`CSS Data error: ${e}`),this.__cssDataCache[e]=null}}return this.__cssDataCache[e]}__extractCssName(e){return e.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){Y||(Y=new Set),Y.add(this.updateCssData),ft||(ft=new MutationObserver(e=>{e[0].type==="attributes"&&Y.forEach(i=>{i()})}),ft.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(e,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(e);let t=this.getCssData(this.__extractCssName(e),!0);t===null&&(t=i),this.add(e,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(e,i,t){let r="__"+e;this[r]=this[e],Object.defineProperty(this,e,{set:s=>{this[r]=s,t?window.setTimeout(()=>{i==null||i(s)}):i==null||i(s)},get:()=>this[r]}),this[e]=this[r]}static set shadowStyles(e){let i=new Blob([e],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(e){if(!this.__rootStylesLink){let i=new Blob([e],{type:"text/css"}),t=URL.createObjectURL(i),r=document.createElement("link");r.href=t,r.rel="stylesheet",this.__rootStylesLink=r}}},he=tt;ce(he,"template");var ue=class{static _print(e){console.warn(e)}static setDefaultTitle(e){this.defaultTitle=e}static setRoutingMap(e){Object.assign(this.appMap,e);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}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(t=>{if(t.includes("?"))e.route=t.replace("?","");else if(t.includes("=")){let r=t.split("=");e.options[r[0]]=decodeURI(r[1])}else e.options[t]=!0}),e}static notify(){let e=this.readAddressBar(),i=this.appMap[e.route];if(i&&i.title&&(document.title=i.title),e.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${e.route}" not found...`);return}let t=new CustomEvent(ue.routingEventName,{detail:{route:e.route,options:Object.assign(i||{},e.options)}});window.dispatchEvent(t)}static reflect(e,i={}){let t=this.appMap[e];if(!t){this._print("Wrong route: "+e);return}let r="?"+e;for(let n in i)i[n]===!0?r+=this.separator+n:r+=this.separator+n+`=${i[n]}`;let s=t.title||this.defaultTitle||"";window.history.pushState(null,s,r),document.title=s}static applyRoute(e,i={}){this.reflect(e,i),this.notify()}static setSeparator(e){this._separator=e}static get separator(){return this._separator||"&"}static createRouterData(e,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},e);return window.addEventListener(this.routingEventName,r=>{var s;t.multiPub({route:r.detail.route,options:r.detail.options,title:((s=r.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),ue.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};ue.appMap=Object.create(null);var Xe="idb-store-ready",Zi="symbiote-db",tr="symbiote-idb-update_",er=class{_notifyWhenReady(e=null){window.dispatchEvent(new CustomEvent(Xe,{detail:{dbName:this.name,storeName:this.storeName,event:e}}))}get _updEventName(){return tr+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,i){this.name=e,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=r=>{this._notifyWhenReady(r)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async s=>{s(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(e){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(e);return new Promise((r,s)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?r(n.target.result._value):(r(null),console.warn(`IDB: cannot read "${e}"`))},t.onerror=n=>{s(n)}})}write(e,i,t=!1){let r={_key:e,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(r);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(e),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(e,i=!1){let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);return new Promise((s,n)=>{r.onsuccess=o=>{i||this._notifySubscribers(e),s(o)},r.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,r)=>{i.onsuccess=s=>{let n=s.target.result;t(n.map(o=>o._value))},i.onerror=s=>{r(s)}})}subscribe(e,i){this._subscriptionsMap[e]||(this._subscriptionsMap[e]=new Set);let t=this._subscriptionsMap[e];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[e]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Be.clear(this.name)}},Be=class{static get readyEventName(){return Xe}static open(e=Zi,i="store"){let t=e+"/"+i;return this._reg[t]||(this._reg[t]=new er(e,i)),this._reg[t]}static clear(e){window.indexedDB.deleteDatabase(e);for(let i in this._reg)i.split("/")[0]===e&&delete this._reg[i]}};ce(Be,"_reg",Object.create(null));function z(e,i){let t,r=(...s)=>{clearTimeout(t),t=setTimeout(()=>e(...s),i)};return r.cancel=()=>{clearTimeout(t)},r}var ir="--uploadcare-blocks-window-height",Nt="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function de(){return typeof window[Nt]=="undefined"?!1:!!window[Nt]}function Ge(){if(de())return;let e=()=>{document.documentElement.style.setProperty(ir,`${window.innerHeight}px`),window[Nt]=!0},i=z(e,100);return window.addEventListener("resize",i,{passive:!0}),e(),()=>{window[Nt]=!1,window.removeEventListener("resize",i)}}var rr=e=>e,fe="{{",Ke="}}",qe="plural:";function pe(e,i,t={}){var o;let{openToken:r=fe,closeToken:s=Ke,transform:n=rr}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();e=e.replaceAll(r+l+s,typeof a=="string"?n(a):a)}return e}function Ye(e){let i=[],t=e.indexOf(fe);for(;t!==-1;){let r=e.indexOf(Ke,t),s=e.substring(t+2,r);if(s.startsWith(qe)){let n=e.substring(t+2,r).replace(qe,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:s,pluralKey:o,countVariable:l})}t=e.indexOf(fe,r)}return i}function Je(e){return Object.prototype.toString.call(e)==="[object Object]"}var sr=/\W|_/g;function nr(e){return e.split(sr).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Qe(e,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(e)?e.map(t=>Q(t,{ignoreKeys:i})):e}function Q(e,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(e))return Qe(e,{ignoreKeys:i});if(!Je(e))return e;let t={};for(let r of Object.keys(e)){let s=e[r];if(i.includes(r)){t[r]=s;continue}Je(s)?s=Q(s,{ignoreKeys:i}):Array.isArray(s)&&(s=Qe(s,{ignoreKeys:i})),t[nr(r)]=s}return t}var or=e=>new Promise(i=>setTimeout(i,e));function Ee({libraryName:e,libraryVersion:i,userAgent:t,publicKey:r="",integration:s=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:r,libraryName:e,libraryVersion:i,languageName:n,integration:s});let o=[e,i,r].filter(Boolean).join("/"),l=[n,s].filter(Boolean).join("; ");return`${o} (${l})`}var lr={factor:2,time:100};function ar(e,i=lr){let t=0;function r(s){let n=Math.round(i.time*i.factor**t);return s({attempt:t,retry:l=>or(l!=null?l:n).then(()=>(t+=1,r(s)))})}return r(e)}var yt=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,yt.prototype),this.originalProgressEvent=t}},Ft=(e,i)=>{e&&(e.aborted?Promise.resolve().then(i):e.addEventListener("abort",()=>i(),{once:!0}))},et=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,et.prototype)}},ur=500,ti=({check:e,interval:i=ur,timeout:t,signal:r})=>new Promise((s,n)=>{let o,l;Ft(r,()=>{o&&clearTimeout(o),n(new et("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new et("Timed out"))},t));let a=()=>{try{Promise.resolve(e(r)).then(h=>{h?(l&&clearTimeout(l),s(h)):o=setTimeout(a,i)}).catch(h=>{l&&clearTimeout(l),n(h)})}catch(h){l&&clearTimeout(l),n(h)}};o=setTimeout(a,0)}),C={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Vt="application/octet-stream",ei="original",rt=({method:e,url:i,data:t,headers:r={},signal:s,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,h=(e==null?void 0:e.toUpperCase())||"GET",c=!1;a.open(h,i,!0),r&&Object.entries(r).forEach(d=>{let[f,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(f,m)}),a.responseType="text",Ft(s,()=>{c=!0,a.abort(),l(new et)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:h,url:i,data:t,headers:r||void 0,signal:s,onProgress:n},f=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};f.forEach(function(w){let v=w.split(": "),b=v.shift(),g=v.join(": ");b&&typeof b!="undefined"&&(m[b]=g)});let p=a.response,y=a.status;o({request:d,data:p,headers:m,status:y})}},a.onerror=d=>{c||l(new yt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function cr(e,...i){return e}var hr=({name:e})=>e?[e]:[],dr=cr,fr=()=>new FormData,ii=e=>!1,zt=e=>typeof Blob!="undefined"&&e instanceof Blob,jt=e=>typeof File!="undefined"&&e instanceof File,Ht=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&"uri"in e&&typeof e.uri=="string",At=e=>zt(e)||jt(e)||ii()||Ht(e),pr=e=>typeof e=="string"||typeof e=="number"||typeof e=="undefined",mr=e=>!!e&&typeof e=="object"&&!Array.isArray(e),_r=e=>!!e&&typeof e=="object"&&"data"in e&&At(e.data);function gr(e,i,t){if(_r(t)){let{name:r,contentType:s}=t,n=dr(t.data,r,s!=null?s:Vt),o=hr({name:r,contentType:s});e.push([i,n,...o])}else if(mr(t))for(let[r,s]of Object.entries(t))typeof s!="undefined"&&e.push([`${i}[${r}]`,String(s)]);else pr(t)&&t&&e.push([i,t.toString()])}function br(e){let i=[];for(let[t,r]of Object.entries(e))gr(i,t,r);return i}function Te(e){let i=fr(),t=br(e);for(let r of t){let[s,n,...o]=r;i.append(s,n,...o)}return i}var R=class extends Error{constructor(t,r,s,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=r,this.request=s,this.response=n,this.headers=o,Object.setPrototypeOf(this,R.prototype)}},yr=e=>{let i=new URLSearchParams;for(let[t,r]of Object.entries(e))r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(s=>{var n;return(n=s[1])!=null?n:!1}).forEach(s=>i.set(`${t}[${s[0]}]`,String(s[1]))):Array.isArray(r)?r.forEach(s=>{i.append(`${t}[]`,s)}):typeof r=="string"&&r?i.set(t,r):typeof r=="number"&&i.set(t,r.toString());return i.toString()},J=(e,i,t)=>{let r=new URL(e);return r.pathname=(r.pathname+i).replace("//","/"),t&&(r.search=yr(t)),r.toString()},Cr="6.6.1",Er="UploadcareUploadClient",Tr=Cr;function ht(e){return Ee({libraryName:Er,libraryVersion:Tr,...e})}var vr="RequestThrottledError",Ze=15e3,wr=1e3;function Ar(e){let{headers:i}=e||{};if(!i||typeof i["retry-after"]!="string")return Ze;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Ze}function st(e,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:r}=i;return ar(({attempt:s,retry:n})=>e().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===vr&&s{let i="";return(zt(e)||jt(e)||Ht(e))&&(i=e.type),i||Vt},si=e=>{let i="";return jt(e)&&e.name?i=e.name:zt(e)||ii()?i="":Ht(e)&&e.name&&(i=e.name),i||ei};function ve(e){return typeof e=="undefined"||e==="auto"?"auto":e?"1":"0"}function xr(e,{publicKey:i,fileName:t,contentType:r,baseURL:s=C.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:h,source:c="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=C.retryNetworkErrorMaxTimes,metadata:y}){return st(()=>rt({method:"POST",url:J(s,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":ht({publicKey:i,integration:d,userAgent:f})},data:Te({file:{data:e,name:t||si(e),contentType:r||ri(e)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:ve(l),signature:n,expire:o,source:c,metadata:y}),signal:a,onProgress:h}).then(({data:w,headers:v,request:b})=>{let g=Q(JSON.parse(w));if("error"in g)throw new R(g.error.content,g.error.errorCode,b,g,v);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var ge;(function(e){e.Token="token",e.FileInfo="file_info"})(ge||(ge={}));function Sr(e,{publicKey:i,baseURL:t=C.baseURL,store:r,fileName:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:h="url",signal:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=C.retryNetworkErrorMaxTimes,metadata:y}){return st(()=>rt({method:"POST",headers:{"X-UC-User-Agent":ht({publicKey:i,integration:d,userAgent:f})},url:J(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:e,store:ve(r),filename:s,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:h,metadata:y}),signal:c}).then(({data:w,headers:v,request:b})=>{let g=Q(JSON.parse(w));if("error"in g)throw new R(g.error.content,g.error.errorCode,b,g,v);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var $;(function(e){e.Unknown="unknown",e.Waiting="waiting",e.Progress="progress",e.Error="error",e.Success="success"})($||($={}));var Or=e=>"status"in e&&e.status===$.Error;function Ir(e,{publicKey:i,baseURL:t=C.baseURL,signal:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=C.retryNetworkErrorMaxTimes}={}){return st(()=>rt({method:"GET",headers:i?{"X-UC-User-Agent":ht({publicKey:i,integration:s,userAgent:n})}:void 0,url:J(t,"/from_url/status/",{jsonerrors:1,token:e}),signal:r}).then(({data:a,headers:h,request:c})=>{let d=Q(JSON.parse(a));if("error"in d&&!Or(d))throw new R(d.error.content,void 0,c,d,h);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Ur(e,{publicKey:i,baseURL:t=C.baseURL,jsonpCallback:r,secureSignature:s,secureExpire:n,signal:o,source:l,integration:a,userAgent:h,retryThrottledRequestMaxTimes:c=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=C.retryNetworkErrorMaxTimes}){return st(()=>rt({method:"POST",headers:{"X-UC-User-Agent":ht({publicKey:i,integration:a,userAgent:h})},url:J(t,"/group/",{jsonerrors:1,pub_key:i,files:e,callback:r,signature:s,expire:n,source:l}),signal:o}).then(({data:f,headers:m,request:p})=>{let y=Q(JSON.parse(f));if("error"in y)throw new R(y.error.content,y.error.errorCode,p,y,m);return y}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:c})}function ni(e,{publicKey:i,baseURL:t=C.baseURL,signal:r,source:s,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=C.retryNetworkErrorMaxTimes}){return st(()=>rt({method:"GET",headers:{"X-UC-User-Agent":ht({publicKey:i,integration:n,userAgent:o})},url:J(t,"/info/",{jsonerrors:1,pub_key:i,file_id:e,source:s}),signal:r}).then(({data:h,headers:c,request:d})=>{let f=Q(JSON.parse(h));if("error"in f)throw new R(f.error.content,f.error.errorCode,d,f,c);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Rr(e,{publicKey:i,contentType:t,fileName:r,multipartChunkSize:s=C.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:h,source:c="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=C.retryNetworkErrorMaxTimes,metadata:y}){return st(()=>rt({method:"POST",url:J(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":ht({publicKey:i,integration:d,userAgent:f})},data:Te({filename:r||ei,size:e,content_type:t||Vt,part_size:s,UPLOADCARE_STORE:ve(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:c,metadata:y}),signal:h}).then(({data:w,headers:v,request:b})=>{let g=Q(JSON.parse(w));if("error"in g)throw new R(g.error.content,g.error.errorCode,b,g,v);return g.parts=Object.keys(g.parts).map(N=>g.parts[N]),g}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})}function Lr(e,i,{contentType:t,signal:r,onProgress:s,retryThrottledRequestMaxTimes:n=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=C.retryNetworkErrorMaxTimes}){return st(()=>rt({method:"PUT",url:i,data:e,onProgress:s,signal:r,headers:{"Content-Type":t||Vt}}).then(l=>(s&&s({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Mr(e,{publicKey:i,baseURL:t=C.baseURL,source:r="local",signal:s,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=C.retryNetworkErrorMaxTimes}){return st(()=>rt({method:"POST",url:J(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":ht({publicKey:i,integration:n,userAgent:o})},data:Te({uuid:e,UPLOADCARE_PUB_KEY:i,source:r}),signal:s}).then(({data:h,headers:c,request:d})=>{let f=Q(JSON.parse(h));if("error"in f)throw new R(f.error.content,f.error.errorCode,d,f,c);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function we({file:e,publicKey:i,baseURL:t,source:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:h}){return ti({check:c=>ni(e,{publicKey:i,baseURL:t,signal:c,source:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(h&&h({isComputable:!0,value:1}),!1)),signal:a})}var it=class{constructor(i,{baseCDN:t=C.baseCDN,fileName:r}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);let{uuid:s,s3Bucket:n}=i,o=J(t,`${s}/`),l=n?J(`https://${n}.s3.amazonaws.com/`,`${s}/${i.filename}`):null;this.uuid=s,this.name=r||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},kr=(e,{publicKey:i,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,contentType:l,signal:a,onProgress:h,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,baseCDN:y,metadata:w})=>xr(e,{publicKey:i,fileName:t,contentType:l,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:a,onProgress:h,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:w}).then(({file:v})=>we({file:v,publicKey:i,baseURL:r,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:h,signal:a})).then(v=>new it(v,{baseCDN:y})),Pr=(e,{publicKey:i,fileName:t,baseURL:r,signal:s,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:c,baseCDN:d})=>ni(e,{publicKey:i,baseURL:r,signal:s,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:c}).then(f=>new it(f,{baseCDN:d,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),Nr=(e,{signal:i}={})=>{let t=null,r=null,s=e.map(()=>new AbortController),n=o=>()=>{r=o,s.forEach((l,a)=>a!==o&&l.abort())};return Ft(i,()=>{s.forEach(o=>o.abort())}),Promise.all(e.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:s[l].signal})).then(h=>(a(),h)).catch(h=>(t=h,null))})).then(o=>{if(r===null)throw t;return o[r]})},Dr=window.WebSocket,be=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var r;(r=this.events[i])==null||r.forEach(s=>s(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(r=>r!==t):this.events[i]=[]}},$r=(e,i)=>e==="success"?{status:$.Success,...i}:e==="progress"?{status:$.Progress,...i}:{status:$.Error,...i},ye=class{constructor(i,t=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new be);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Dr(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let r=JSON.parse(t.data.toString());switch(r.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(r.channel,$r(r.event,JSON.parse(r.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var s;let r=JSON.stringify({event:i,data:t});(s=this.ws)==null||s.send(r)}subscribe(i,t){this.subscribers+=1,this.connect();let r=`task-status-${i}`,s={event:"pusher:subscribe",data:{channel:r}};this.emmitter.on(r,t),this.isConnected?this.send(s.event,s.data):this.queue.push(s)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,r={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(r.event,r.data):this.queue=this.queue.filter(s=>s.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},me=null,Ae=e=>{if(!me){let i=typeof window=="undefined"?0:3e4;me=new ye(e,i)}return me},Fr=e=>{Ae(e).connect()};function Vr({token:e,publicKey:i,baseURL:t,integration:r,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return ti({check:h=>Ir(e,{publicKey:i,baseURL:t,integration:r,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:h}).then(c=>{switch(c.status){case $.Error:return new R(c.error,c.errorCode);case $.Waiting:return!1;case $.Unknown:return new R(`Token "${e}" was not found.`);case $.Progress:return l&&(c.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:c.done/c.total})),!1;case $.Success:return l&&l({isComputable:!0,value:c.done/c.total}),c;default:throw new Error("Unknown status")}}),signal:a})}var zr=({token:e,pusherKey:i,signal:t,onProgress:r})=>new Promise((s,n)=>{let o=Ae(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(e)};Ft(t,()=>{a(),n(new et("pusher cancelled"))}),o.subscribe(e,h=>{switch(h.status){case $.Progress:{r&&(h.total==="unknown"?r({isComputable:!1}):r({isComputable:!0,value:h.done/h.total}));break}case $.Success:{a(),r&&r({isComputable:!0,value:h.done/h.total}),s(h);break}case $.Error:a(),n(new R(h.msg,h.error_code))}})}),jr=(e,{publicKey:i,fileName:t,baseURL:r,baseCDN:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:h,signal:c,onProgress:d,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,pusherKey:w=C.pusherKey,metadata:v})=>Promise.resolve(Fr(w)).then(()=>Sr(e,{publicKey:i,fileName:t,baseURL:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:h,signal:c,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,metadata:v})).catch(b=>{let g=Ae(w);return g==null||g.disconnect(),Promise.reject(b)}).then(b=>b.type===ge.FileInfo?b:Nr([({signal:g})=>Vr({token:b.token,publicKey:i,baseURL:r,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,onProgress:d,signal:g}),({signal:g})=>zr({token:b.token,pusherKey:w,signal:g,onProgress:d})],{signal:c})).then(b=>{if(b instanceof R)throw b;return b}).then(b=>we({file:b.uuid,publicKey:i,baseURL:r,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,onProgress:d,signal:c})).then(b=>new it(b,{baseCDN:s})),_e=new WeakMap,Hr=async e=>{if(_e.has(e))return _e.get(e);let i=await fetch(e.uri).then(t=>t.blob());return _e.set(e,i),i},oi=async e=>{if(jt(e)||zt(e))return e.size;if(Ht(e))return(await Hr(e)).size;throw new Error("Unknown file type. Cannot determine file size.")},Wr=(e,i=C.multipartMinFileSize)=>e>=i,li=e=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!At(e)&&t.test(e)},ai=e=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!At(e)&&t.test(e)},Xr=(e,i)=>new Promise((t,r)=>{let s=[],n=!1,o=i.length,l=[...i],a=()=>{let h=i.length-l.length,c=l.shift();c&&c().then(d=>{n||(s[h]=d,o-=1,o?a():t(s))}).catch(d=>{n=!0,r(d)})};for(let h=0;h{let s=r*i,n=Math.min(s+r,t);return e.slice(s,n)},Gr=async(e,i,t)=>r=>Br(e,r,i,t),qr=(e,i,{publicKey:t,contentType:r,onProgress:s,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Lr(e,i,{publicKey:t,contentType:r,onProgress:s,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Kr=async(e,{publicKey:i,fileName:t,fileSize:r,baseURL:s,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:h,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,contentType:y,multipartChunkSize:w=C.multipartChunkSize,maxConcurrentRequests:v=C.maxConcurrentRequests,baseCDN:b,metadata:g})=>{let N=r!=null?r:await oi(e),G,lt=(U,V)=>{if(!h)return;G||(G=Array(U).fill(0));let q=D=>D.reduce((K,le)=>K+le,0);return D=>{D.isComputable&&(G[V]=D.value,h({isComputable:!0,value:q(G)/U}))}};return y||(y=ri(e)),Rr(N,{publicKey:i,contentType:y,fileName:t||si(e),baseURL:s,secureSignature:n,secureExpire:o,store:l,signal:a,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:g}).then(async({uuid:U,parts:V})=>{let q=await Gr(e,N,w);return Promise.all([U,Xr(v,V.map((D,K)=>()=>qr(q(K),D,{publicKey:i,contentType:y,onProgress:lt(V.length,K),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})))])}).then(([U])=>Mr(U,{publicKey:i,baseURL:s,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})).then(U=>U.isReady?U:we({file:U.uuid,publicKey:i,baseURL:s,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:h,signal:a})).then(U=>new it(U,{baseCDN:b}))};async function xe(e,{publicKey:i,fileName:t,baseURL:r=C.baseURL,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartMinFileSize:y,multipartChunkSize:w,maxConcurrentRequests:v,baseCDN:b=C.baseCDN,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:N,pusherKey:G,metadata:lt}){if(At(e)){let U=await oi(e);return Wr(U,y)?Kr(e,{publicKey:i,contentType:p,multipartChunkSize:w,fileSize:U,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,maxConcurrentRequests:v,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:lt}):kr(e,{publicKey:i,fileName:t,contentType:p,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:lt})}if(ai(e))return jr(e,{publicKey:i,fileName:t,baseURL:r,baseCDN:b,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:N,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,pusherKey:G,metadata:lt});if(li(e))return Pr(e,{publicKey:i,fileName:t,baseURL:r,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b});throw new TypeError(`File uploading from "${e}" is not supported`)}var Ce=class{constructor(i,t){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((r,s)=>r+s.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Yr=e=>{for(let i of e)if(!At(i))return!1;return!0},Jr=e=>{for(let i of e)if(!li(i))return!1;return!0},Qr=e=>{for(let i of e)if(!ai(i))return!1;return!0};function ui(e,{publicKey:i,fileName:t,baseURL:r=C.baseURL,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:y=C.multipartChunkSize,baseCDN:w=C.baseCDN,checkForUrlDuplicates:v,saveUrlForRecurrentUploads:b,jsonpCallback:g}){if(!Yr(e)&&!Qr(e)&&!Jr(e))throw new TypeError(`Group uploading from "${e}" is not supported`);let N,G=!0,lt=e.length,U=(V,q)=>{if(!a)return;N||(N=Array(V).fill(0));let D=K=>K.reduce((le,Ri)=>le+Ri)/V;return K=>{if(!K.isComputable||!G){G=!1,a({isComputable:!1});return}N[q]=K.value,a({isComputable:!0,value:D(N)})}};return Promise.all(e.map((V,q)=>xe(V,{publicKey:i,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:U(lt,q),source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:y,baseCDN:w,checkForUrlDuplicates:v,saveUrlForRecurrentUploads:b}))).then(V=>{let q=V.map(D=>D.uuid);return Ur(q,{publicKey:i,baseURL:r,jsonpCallback:g,secureSignature:s,secureExpire:n,signal:l,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m}).then(D=>new Ce(D,V)).then(D=>(a&&a({isComputable:!0,value:1}),D))})}var ut,mt,ct,_t,gt,bt,Dt,$t=class{constructor(i){at(this,bt);at(this,ut,1);at(this,mt,[]);at(this,ct,0);at(this,_t,new WeakMap);at(this,gt,new WeakMap);Tt(this,ut,i)}add(i){return new Promise((t,r)=>{L(this,_t).set(i,t),L(this,gt).set(i,r),L(this,mt).push(i),Mt(this,bt,Dt).call(this)})}get pending(){return L(this,mt).length}get running(){return L(this,ct)}set concurrency(i){Tt(this,ut,i),Mt(this,bt,Dt).call(this)}get concurrency(){return L(this,ut)}};ut=new WeakMap,mt=new WeakMap,ct=new WeakMap,_t=new WeakMap,gt=new WeakMap,bt=new WeakSet,Dt=function(){let i=L(this,ut)-L(this,ct);for(let t=0;t{L(this,_t).delete(r),L(this,gt).delete(r),Tt(this,ct,L(this,ct)-1),Mt(this,bt,Dt).call(this)}).then(o=>s(o)).catch(o=>n(o))}};var Se=()=>({"*blocksRegistry":new Set}),Oe=e=>({...Se(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{e.set$({"*modalActive":!1,"*currentActivity":""})}}),Wt=e=>({...Oe(e),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new $t(1)});function ci(e,i){[...e.querySelectorAll("[l10n]")].forEach(t=>{let r=t.getAttribute("l10n"),s="textContent";if(r.includes(":")){let o=r.split(":");s=o[0],r=o[1]}let n="l10n:"+r;i.__l10nKeys.push(n),i.add(n,r),i.sub(n,o=>{t[s]=i.l10n(o)}),t.removeAttribute("l10n")})}var j=e=>`*cfg/${e}`;var nt=e=>{var i;return(i=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var hi=new Set;function Xt(e){hi.has(e)||(hi.add(e),console.warn(e))}var Bt=(e,i)=>new Intl.PluralRules(e).select(i);var Ie="lr-",S=class extends he{constructor(){super();u(this,"allowCustomTemplate",!0);u(this,"init$",Se());u(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let r of t)r.isConnected&&r.updateCssData()});this.activityType=null,this.addTemplateProcessor(ci),this.__l10nKeys=[]}l10n(t,r={}){if(!t)return"";let s=this.getCssData("--l10n-"+t,!0)||t,n=Ye(s);for(let l of n)r[l.variable]=this.pluralize(l.pluralKey,Number(r[l.countVariable]));return pe(s,r)}pluralize(t,r){let s=this.l10n("locale-name")||"en-US",n=Bt(s,r);return this.l10n(`${t}__${n}`)}applyL10nKey(t,r){let s="l10n:"+t;this.$[s]=r,this.__l10nKeys.push(t)}hasBlockInCtx(t){let r=this.$["*blocksRegistry"];for(let s of r)if(t(s))return!0;return!1}setOrAddState(t,r){this.add$({[t]:r},!0)}setActivity(t){if(this.hasBlockInCtx(r=>r.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ie}${t}`,!0),de()||(this._destroyInnerHeightTracker=Ge()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,r=2){let s=["B","KB","MB","GB","TB"],n=h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h;if(t===0)return`0 ${n(s[0])}`;let o=1024,l=r<0?0:r,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(s[a])}proxyUrl(t){let r=this.cfg.secureDeliveryProxy;return r?pe(r,{previewUrl:t},{transform:s=>window.encodeURIComponent(s)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(r,s)=>{let n=j(s),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Xt("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${nt(s)}`))}})}return this.__cfgProxy}subConfigValue(t,r){let s=this.parseCfgProp(j(t));s.ctx.has(s.name)?this.sub(j(t),r):(this.bindCssData(`--cfg-${nt(t)}`),this.sub(`--cfg-${nt(t)}`,r))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ie)?t:Ie+t)}};u(S,"StateConsumerScope",null),u(S,"className","");var di="active",xt="___ACTIVITY_IS_ACTIVE___",H=class extends S{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",Oe(this));u(this,"_debouncedHistoryFlush",z(this._historyFlush.bind(this),10))}_deactivate(){var r;let t=H._activityRegistry[this.activityKey];this[xt]=!1,this.removeAttribute(di),(r=t==null?void 0:t.deactivateCallback)==null||r.call(t)}_activate(){var r;let t=H._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[xt]=!0,this.setAttribute(di,""),(r=t==null?void 0:t.activateCallback)==null||r.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[xt]?this._deactivate():this.activityType===t&&!this[xt]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!H._activityRegistry[this.activityKey]}get isActivityActive(){return this[xt]}registerActivity(t,r={}){let{onActivate:s,onDeactivate:n}=r;H._activityRegistry||(H._activityRegistry=Object.create(null)),H._activityRegistry[this.activityKey]={activateCallback:s,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),H._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(H._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},T=H;u(T,"_activityRegistry",Object.create(null));T.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var Zr="css-src";function ts(e){return class extends e{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Zr);if(t){this.attachShadow({mode:"open"});let r=document.createElement("link");r.rel="stylesheet",r.type="text/css",r.href=t,r.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(r)}else console.error("Attribute `css-src`is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Gt=class extends ts(S){};var qt=class extends Gt{constructor(){super(...arguments);u(this,"init$",Wt(this));u(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var Kt=class extends qt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",r=>{r||(this.$["*currentActivity"]=t.initActivity||T.activities.START_FROM)}),this.sub("*uploadList",r=>{(r==null?void 0:r.length)>0?this.$["*currentActivity"]=T.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||T.activities.START_FROM}),this.subConfigValue("sourceList",r=>{r!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",r=>{r!==!1&&(this.cfg.confirmUpload=!1)})}};Kt.template=``;var Ue=class extends T{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function fi(e,i,t){let r=e/i,s,n;r>t?(s=Math.round(i*t),n=i):(s=e,n=Math.round(e/t));let o=Math.round((e-s)/2),l=Math.round((i-n)/2);return o+s>e&&(s=e-o),l+n>i&&(n=i-l),{x:o,y:l,width:s,height:n}}var pi=e=>{if(!e)return[];let[i,t]=e.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${e}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var ot=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var mi="blocks",_i="0.27.1";function gi(e){return Ee({...e,libraryName:mi,libraryVersion:_i})}var es=e=>{if(typeof e!="string"||!e)return"";let i=e.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Re=(...e)=>e.filter(i=>typeof i=="string"&&i).map(i=>es(i)).join("/-/"),Yt=(...e)=>{let i=Re(...e);return i?`-/${i}/`:""};function bi(e){let i=new URL(e),t=i.pathname+i.search+i.hash,r=t.lastIndexOf("http"),s=t.lastIndexOf("/"),n="";return r>=0?n=t.slice(r):s>=0&&(n=t.slice(s+1)),n}function is(e){let i=new URL(e),t=bi(e),r=yi(t)?Ci(t).pathname:t;return i.pathname=i.pathname.replace(r,""),i.search="",i.hash="",i.toString()}function yi(e){return e.startsWith("http")}function Ci(e){let i=new URL(e);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var Jt=(e,i,t)=>{let r=new URL(is(e));if(t=t||bi(e),r.pathname.startsWith("//")&&(r.pathname=r.pathname.replace("//","/")),yi(t)){let s=Ci(t);r.pathname=r.pathname+(i||"")+(s.pathname||""),r.search=s.search,r.hash=s.hash}else r.pathname=r.pathname+(i||"")+(t||"");return r.toString()},Ei=(e,i)=>{let t=new URL(e);return t.pathname=i+"/",t.toString()};var Ct=(e,i=",")=>e.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var St=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Le=e=>e?e.filter(i=>typeof i=="string").map(i=>Ct(i)).flat():[],Me=(e,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),e.startsWith(t)):e===t),Ti=(e,i)=>i.some(t=>t.startsWith(".")?e.toLowerCase().endsWith(t.toLowerCase()):!1),ke=e=>{let i=e==null?void 0:e.type;return i?Me(i,St):!1};var W=1e3,dt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),Ot=e=>Math.ceil(e*100)/100,vi=(e,i=dt.AUTO)=>{let t=i===dt.AUTO;if(i===dt.BYTE||t&&e{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!r){s();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{s(),delete this._timeoutStore[n]},20)}};u(O,"_timeoutStore",Object.create(null));var wi="[Typed State] Wrong property name: ",rs="[Typed State] Wrong property type: ",Qt=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||wt.generate(),this.__schema=Object.keys(i).reduce((r,s)=>(r[s]=i[s].value,r),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(wi+i);return}let r=this.__typedSchema[i];if((t==null?void 0:t.constructor)===r.type||t instanceof r.type||r.nullable&&t===null){this.__data.pub(i,t);return}console.warn(rs+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(wi+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Zt=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||wt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(r,s)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[r]||(t[r]=new Set),t[r].add(s),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var r;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(r=this.__handler)==null||r.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Qt(this.__typedSchema);for(let r in i)t.setValue(r,i[r]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(r=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(r,()=>{this.__notifyObservers(r,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,r){this.read(i).setValue(t,r)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(r=>{let s=this.read(r);i(s)&&t.push(r)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var Ai=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:it,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var It=e=>e?e.join(","):"";var x=class extends T{constructor(){super(...arguments);u(this,"couldBeUploadCollectionOwner",!1);u(this,"isUploadCollectionOwner",!1);u(this,"init$",Wt(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",z(this._runValidators.bind(this),100));u(this,"_handleCollectionUpdate",t=>{let r=this.uploadCollection,s=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>r.read(n)).filter(Boolean);for(let n of s)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=r.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=r.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,O.emit(new M({type:I.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=r.findItems(l=>!!l.getValue("fileInfo")),o=r.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(r.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&O.emit(new M({type:I.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&r.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{O.emit(new M({type:I.UPLOAD_ERROR,ctx:this.ctxName,data:r.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&r.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{O.emit(new M({type:I.VALIDATION_ERROR,ctx:this.ctxName,data:r.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&r.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{O.emit(new M({type:I.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){Xt("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let r=new Zt({typedSchema:Ai,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",r)}let t=()=>this.hasBlockInCtx(r=>r instanceof x?r.isUploadCollectionOwner&&r.isConnected&&r!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(r,s,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=r.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",r=>{this.$["*uploadQueue"].concurrency=Number(r)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:r,fileName:s,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:s!=null?s:null,silentUpload:r!=null?r:!1,source:n!=null?n:ot.API})}addFileFromUuid(t,{silent:r,fileName:s,source:n}={}){this.uploadCollection.add({uuid:t,fileName:s!=null?s:null,silentUpload:r!=null?r:!1,source:n!=null?n:ot.API})}addFileFromObject(t,{silent:r,fileName:s,source:n}={}){this.uploadCollection.add({file:t,isImage:ke(t),mimeType:t.type,fileName:s!=null?s:t.name,fileSize:t.size,silentUpload:r!=null?r:!1,source:n!=null?n:ot.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(r=>{this.uploadCollection.add({file:r,isImage:ke(r),mimeType:r.type,fileName:r.name,fileSize:r.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var s;let r=It(Le([(s=this.cfg.accept)!=null?s:"",...this.cfg.imgOnly?St:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=It(St)):this.fileInput.accept=r,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:ot.LOCAL})),this.$["*currentActivity"]=T.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=Ct(this.cfg.sourceList)),t}initFlow(t=!1){var r;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":T.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let s=this.sourceList[0];s==="local"?(this.$["*currentActivity"]=T.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(x.extSrcList).includes(s)?this.set$({"*currentActivityParams":{externalSourceType:s},"*currentActivity":T.activities.EXTERNAL}):this.$["*currentActivity"]=s,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":T.activities.START_FROM}),this.setOrAddState("*modalActive",!0);O.emit(new M({type:I.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),O.emit(new M({type:I.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let r=this.cfg.imgOnly,s=this.cfg.accept,n=Le([...r?St:[],s]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Me(o,n),h=Ti(l,n);if(!a&&!h)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let r=this.cfg.maxLocalFileSizeBytes,s=t.getValue("fileSize");if(r&&s&&s>r)return this.l10n("files-max-size-limit-error",{maxFileSize:vi(r)})}_validateMultipleLimit(t){let s=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&s>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let r=this.cfg.imgOnly,s=t.getValue("isImage");if(!(!r||s)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let r of this._validators){let s=r(t);if(s){t.setValue("validationErrorMsg",s);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let r=this.uploadCollection.read(t);r&&this._runValidatorsForEntry(r)})}setInitialCrop(){let t=pi(this.cfg.cropPreset);if(t){let[r]=t,s=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of s){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,h=r.width/r.height,c=fi(l,a,h),d=Yt(`crop/${c.width}x${c.height}/${c.x},${c.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:Jt(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===T.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=T.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var r;let t=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:gi,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let r=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};r.push(a)}),r}};x.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});x.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...x.extSrcList});Object.values(I).forEach(e=>{let i=O.eName(e),t=z(r=>{if([I.UPLOAD_FINISH,I.REMOVE,I.CDN_MODIFICATION].includes(r.detail.type)){let n=E.getCtx(r.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let h=E.getCtx(a).store,c=h.fileInfo;if(c){let d={...c,cdnUrlModifiers:h.cdnUrlModifiers,cdnUrl:h.cdnUrl||c.cdnUrl};l.push(d)}}),O.emit(new M({type:I.DATA_OUTPUT,ctx:r.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});function ss(e){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let r=s=>{s.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=r,t.onprogress=r,t.readAsDataURL(e)}catch{i(!1)}})}function ns(e,i){return new Promise(t=>{let r=0,s=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(r++,l.file(a=>{r--;let h=new File([a],a.name,{type:a.type||i});s.push(h),r===0&&t(s)})):l.isDirectory&&o(l.createReader())},o=l=>{r++,l.readEntries(a=>{r--;for(let h of a)n(h);r===0&&t(s)})};n(e)})}function xi(e){let i=[],t=[];for(let r=0;r{i.push(...a)}));continue}let o=s.getAsFile();t.push(ss(o).then(l=>{l||i.push(o)}))}else s.kind==="string"&&s.type.match("^text/uri-list")&&t.push(new Promise(n=>{s.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}var k={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},Si=["focus"],os=100,Pe=new Map;function ls(e,i){let t=Math.max(Math.min(e[0],i.x+i.width),i.x),r=Math.max(Math.min(e[1],i.y+i.height),i.y);return Math.sqrt((e[0]-t)*(e[0]-t)+(e[1]-r)*(e[1]-r))}function Ne(e){let i=0,t=document.body,r=new Set,s=p=>r.add(p),n=k.INACTIVE,o=p=>{e.shouldIgnore()&&p!==k.INACTIVE||(n!==p&&r.forEach(y=>y(p)),n=p)},l=()=>i>0;s(p=>e.onChange(p));let a=()=>{i=0,o(k.INACTIVE)},h=()=>{i+=1,n===k.INACTIVE&&o(k.ACTIVE)},c=()=>{i-=1,l()||o(k.INACTIVE)},d=p=>{p.preventDefault(),i=0,o(k.INACTIVE)},f=p=>{if(e.shouldIgnore())return;l()||(i+=1);let y=[p.x,p.y],w=e.element.getBoundingClientRect(),v=Math.floor(ls(y,w)),b=v{if(e.shouldIgnore())return;p.preventDefault();let y=await xi(p.dataTransfer);e.onItems(y),o(k.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",c),t.addEventListener("dragenter",h),t.addEventListener("dragover",f),e.element.addEventListener("drop",m),Si.forEach(p=>{window.addEventListener(p,a)}),()=>{Pe.delete(e.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",c),t.removeEventListener("dragenter",h),t.removeEventListener("dragover",f),e.element.removeEventListener("drop",m),Si.forEach(p=>{window.removeEventListener(p,a)})}}var F=e=>String(e),X=e=>Number(e),A=e=>typeof e=="boolean"?e:e==="true"||e===""?!0:e==="false"?!1:!!e,as=e=>e==="auto"?e:A(e),us={pubkey:F,multiple:A,multipleMin:X,multipleMax:X,confirmUpload:A,imgOnly:A,accept:F,externalSourcesPreferredTypes:F,store:as,cameraMirror:A,sourceList:F,maxLocalFileSizeBytes:X,thumbSize:X,showEmptyList:A,useLocalImageEditor:A,useCloudImageEditor:A,cloudImageEditorTabs:F,removeCopyright:A,cropPreset:F,modalScrollLock:A,modalBackdropStrokes:A,sourceListWrap:A,remoteTabSessionKey:F,cdnCname:F,baseUrl:F,socialBaseUrl:F,secureSignature:F,secureExpire:F,secureDeliveryProxy:F,retryThrottledRequestMaxTimes:X,multipartMinFileSize:X,multipartChunkSize:X,maxConcurrentRequests:X,multipartMaxConcurrentRequests:X,multipartMaxAttempts:X,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:A,groupOutput:A,userAgentIntegration:F},Oi=(e,i)=>{if(!(typeof i=="undefined"||i===null))return us[e](i)};var Ut=class extends x{constructor(){super(...arguments);u(this,"init$",{...this.init$,state:k.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),r=t.width>0&&t.height>0,s=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return r&&o&&s}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",r=>{this.set$({isEnabled:!A(r)})}),this.defineAccessor("clickable",r=>{this.set$({isClickable:A(r)})}),this.defineAccessor("with-icon",r=>{this.set$({withIcon:A(r)})}),this.defineAccessor("fullscreen",r=>{this.set$({isFullscreen:A(r)})}),this.defineAccessor("text",r=>{r?this.set$({text:this.l10n(r)||r}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Ne({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:r=>{this.$.state=r},onItems:r=>{r.length&&(r.forEach(s=>{if(typeof s=="string"){this.addFileFromUrl(s,{source:ot.DROP_AREA});return}this.addFileFromObject(s,{source:ot.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":T.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Ne({element:t,onChange:r=>{var n;let s=(n=Object.entries(k).find(([,o])=>o===r))==null?void 0:n[0].toLowerCase();s&&t.setAttribute("drag-state",s)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",r=>{var n;let s=(n=Object.entries(k).find(([,o])=>o===r))==null?void 0:n[0].toLowerCase();s&&this.setAttribute("drag-state",s)}),this.subConfigValue("sourceList",r=>{let s=Ct(r);this.$.isEnabled=s.includes(x.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",r=>{this.toggleAttribute("hidden",!r)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(s=>s!==this).filter(s=>s.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,r=this.cfg.multipleMax,s=this.uploadCollection.size;return!(t&&r&&s>=r||!t&&s>0)}destroyCallback(){var t,r,s,n;super.destroyCallback(),(r=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||r.call(t,this),(s=this._destroyDropzone)==null||s.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};Ut.template=`
{{text}}
`;Ut.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var te=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}},ee=class extends S{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};ee.template=`
{{captionTxt}}
{{msgTxt}}
`;var ie=class extends x{constructor(){super();u(this,"couldBeUploadCollectionOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",T.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",z(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(r=>!!r.getValue("fileInfo"));O.emit(new M({type:I.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var c,d;let t=!!this.cfg.multiple,r=t?(c=this.cfg.multipleMin)!=null?c:0:1,s=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=r?ns:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:r,max:s,exact:s===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,r=this._validateFilesCount();if(t&&!r.passed){let s=new te,n=r.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";s.caption=this.l10n("files-count-limit-error-title"),s.text=this.l10n(n,{min:r.min,max:r.max,total:t}),s.isError=!0,this.set$({"*message":s})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),s={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let p=this.uploadCollection.read(m);p.getValue("fileInfo")&&!p.getValue("validationErrorMsg")&&(s.succeed+=1),p.getValue("isUploading")&&(s.uploading+=1),(p.getValue("validationErrorMsg")||p.getValue("uploadError"))&&(s.failed+=1),p.getValue("validationMultipleLimitMsg")&&(s.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=s.failed===0&&s.limitOverflow===0,h=!1,c=!1,d=!1;s.total-s.succeed-s.uploading-s.failed>0&&n?h=!0:(c=!0,d=s.total===s.succeed&&n&&a),this.set$({doneBtnVisible:c,doneBtnEnabled:d,uploadBtnVisible:h,addMoreBtnEnabled:s.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(s)})}_getHeaderText(t){let r=s=>{let n=t[s];return this.l10n(`header-${s}`,{count:n})};return t.uploading>0?r("uploading"):t.failed>0?r("failed"):t.succeed>0?r("succeed"):r("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var r;((r=this.uploadCollection)==null?void 0:r.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};ie.template=`{{headerText}}
`;function cs(e){let i=new Blob([e],{type:"image/svg+xml"});return URL.createObjectURL(i)}function De(e="hsl(209, 21%, 65%)",i=32,t=32){return cs(``)}function Ii(e,i=40){if(e.type==="image/svg+xml")return URL.createObjectURL(e);let t=document.createElement("canvas"),r=t.getContext("2d"),s=new Image,n=new Promise((o,l)=>{s.onload=()=>{let a=s.height/s.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),r.fillStyle="rgb(240, 240, 240)",r.fillRect(0,0,t.width,t.height),r.drawImage(s,0,0,t.width,t.height),t.toBlob(h=>{if(!h){l();return}let c=URL.createObjectURL(h);o(c)})},s.onerror=a=>{l(a)}});return s.src=URL.createObjectURL(e),n}var P=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),Z=class extends x{constructor(){super();u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",z(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",z(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:P.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===T.activities.DETAILS)?this.$["*currentActivity"]=T.activities.DETAILS:this.$["*currentActivity"]=T.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let r=this.getOutputData(s=>s.getValue("uuid")===t);O.emit(new M({type:I.REMOVE,ctx:this.ctxName,data:r}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[r]=t;this._isIntersecting=r.isIntersecting,r.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),r.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,r=P.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?r=P.FAILED:t.getValue("validationMultipleLimitMsg")?r=P.LIMIT_OVERFLOW:t.getValue("isUploading")?r=P.UPLOADING:t.getValue("fileInfo")&&(r=P.FINISHED),this.$.state=r}async _generateThumbnail(){var r;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let s=this.cfg.thumbSize,n=this.proxyUrl(Jt(Ei(this.cfg.cdnCname,this._entry.getValue("uuid")),Yt(t.getValue("cdnUrlModifiers"),`scale_crop/${s}x${s}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((r=t.getValue("file"))!=null&&r.type.includes("image"))try{let s=await Ii(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",s)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",De(n))}else{let s=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",De(s))}}_subEntry(t,r){let s=this._entry.subscribe(t,n=>{this.isConnected&&r(n)});this._entrySubs.add(s)}_handleEntryId(t){var s;this._reset();let r=(s=this.uploadCollection)==null?void 0:s.read(t);this._entry=r,r&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||r.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=r.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{Z.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),Z.activeInstances.add(this)}_handleState(t){var r,s,n;this.set$({isFailed:t===P.FAILED,isLimitOverflow:t===P.LIMIT_OVERFLOW,isUploading:t===P.UPLOADING,isFinished:t===P.FINISHED,progressVisible:t===P.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((r=this._entry)==null?void 0:r.getValue("isImage"))&&((s=this._entry)==null?void 0:s.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===P.FAILED||t===P.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===P.FINISHED&&(this.$.badgeIcon="badge-success"),t===P.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),Z.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let r=this.cfg.multiple?this.cfg.multipleMax:1;if(r&&this.uploadCollection.size>r)return;let s=this.getOutputData(a=>!a.getValue("fileInfo"));O.emit(new M({type:I.UPLOAD_START,ctx:this.ctxName,data:s})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let h=async()=>{let d=await this.getUploadClientOptions();return xe(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let m=f.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!f.isComputable},signal:a.signal})},c=await this.$["*uploadQueue"].add(h);t.setMultipleValues({fileInfo:c,isUploading:!1,fileName:c.originalFilename,fileSize:c.size,isImage:c.isImage,mimeType:(l=(o=(n=c.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:c.mimeType,uuid:c.uuid,cdnUrl:c.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof R?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};Z.template=`
{{itemName}}{{errorText}}
`;Z.activeInstances=new Set;var Rt=class extends S{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let r=this.getCssData(`--icon-${t}`);r&&(this.$.path=r)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};Rt.template=``;Rt.bindAttributes({name:"name",size:"size"});var re=class extends S{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};re.template='
';var se=class extends S{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};u(se,"template",`Powered by Uploadcare`);var Et=class extends x{constructor(){super(...arguments);u(this,"processInnerHtml",!0);u(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Et.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let r=t.groupData?[t.groupData.cdnUrl]:t.map(s=>s.cdnUrl);for(let s of r){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=s,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=r.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let r=t.map(o=>o.uuid),s=await this.getUploadClientOptions(),n=await ui(r,{...s});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};Et.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var B={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};var rl=Re("format/auto","progressive/yes");var $e=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),Ui=[$e.CROP,$e.TUNING,$e.FILTERS];var ol=Object.freeze({brightness:{zero:B.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:B.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:B.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:B.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:B.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:B.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:B.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:B.enhance,range:[0,100],keypointsNumber:1},filter:{zero:B.filter,range:[0,100],keypointsNumber:1}});var hs="https://ucarecdn.com",ds="https://upload.uploadcare.com",fs="https://social.uploadcare.com",Lt={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:It(Ui),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:hs,baseUrl:ds,socialBaseUrl:fs,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var ne=Object.keys(Lt),ps=["metadata"],ms=e=>ps.includes(e),Fe=ne.filter(e=>!ms(e)),_s={...Object.fromEntries(Fe.map(e=>[nt(e),e])),...Object.fromEntries(Fe.map(e=>[e.toLowerCase(),e]))},gs={...Object.fromEntries(ne.map(e=>[nt(e),j(e)])),...Object.fromEntries(ne.map(e=>[e.toLowerCase(),j(e)]))},oe=class extends S{constructor(){super();u(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Lt).map(([t,r])=>[j(t),r]))}}initCallback(){super.initCallback();for(let t of ne){let r=this,s="__"+t;r[s]=r[t],Object.defineProperty(this,t,{set:n=>{if(r[s]=n,Fe.includes(t)){let o=[...new Set([nt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[j(t)]!==n&&(typeof n=="undefined"||n===null?this.$[j(t)]=Lt[t]:this.$[j(t)]=n)},get:()=>this.$[j(t)]}),typeof r[t]!="undefined"&&r[t]!==null&&(r[t]=r[s])}}attributeChangedCallback(t,r,s){if(r===s)return;let n=_s[t],o=Oi(n,s),l=o!=null?o:Lt[n],a=this;a[n]=l}};oe.bindAttributes(gs);var Ve=class extends x{};export{oe as Config,se as Copyright,Et as DataOutput,Ut as DropArea,Z as FileItem,Kt as FileUploaderMinimal,Rt as Icon,ee as MessageBox,re as ProgressBar,Ue as StartFrom,Ve as UploadCtxProvider,ie as UploadList,ki as registerBlocks}; \ No newline at end of file +var Li=Object.defineProperty;var Mi=(e,i,t)=>i in e?Li(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t;var u=(e,i,t)=>(Mi(e,typeof i!="symbol"?i+"":i,t),t),ae=(e,i,t)=>{if(!i.has(e))throw TypeError("Cannot "+t)};var L=(e,i,t)=>(ae(e,i,"read from private field"),t?t.call(e):i.get(e)),at=(e,i,t)=>{if(i.has(e))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(e):i.set(e,t)},Tt=(e,i,t,r)=>(ae(e,i,"write to private field"),r?r.call(e,t):i.set(e,t),t);var Mt=(e,i,t)=>(ae(e,i,"access private method"),t);function Pi(e){for(let i in e){let t=[...i].reduce((r,s)=>(s.toUpperCase()===s&&(s="-"+s.toLowerCase()),r+=s),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),e[i].reg&&e[i].reg(t)}}var ki=Object.defineProperty,Ni=(e,i,t)=>i in e?ki(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t,ce=(e,i,t)=>(Ni(e,typeof i!="symbol"?i+"":i,t),t);function Di(e){let i=t=>{var r;for(let s in t)((r=t[s])==null?void 0:r.constructor)===Object&&(t[s]=i(t[s]));return{...t}};return i(e)}var E=class{constructor(e){e.constructor===Object?this.store=Di(e):(this._storeIsProxy=!0,this.store=e),this.callbackMap=Object.create(null)}static warn(e,i){console.warn(`Symbiote Data: cannot ${e}. Prop name: `+i)}read(e){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(E.warn("read",e),null):this.store[e]}has(e){return this._storeIsProxy?this.store[e]!==void 0:this.store.hasOwnProperty(e)}add(e,i,t=!1){!t&&Object.keys(this.store).includes(e)||(this.store[e]=i,this.notify(e))}pub(e,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(e)){E.warn("publish",e);return}this.store[e]=i,this.notify(e)}multiPub(e){for(let i in e)this.pub(i,e[i])}notify(e){this.callbackMap[e]&&this.callbackMap[e].forEach(i=>{i(this.store[e])})}sub(e,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(E.warn("subscribe",e),null):(this.callbackMap[e]||(this.callbackMap[e]=new Set),this.callbackMap[e].add(i),t&&i(this.store[e]),{remove:()=>{this.callbackMap[e].delete(i),this.callbackMap[e].size||delete this.callbackMap[e]},callback:i})}static registerCtx(e,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(e),E.globalStore.set(i,t)),t}static deleteCtx(e){E.globalStore.delete(e)}static getCtx(e,i=!0){return E.globalStore.get(e)||(i&&console.warn('State: wrong context UID - "'+e+'"'),null)}};E.globalStore=new Map;var _=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),He="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",$i=He.length-1,wt=class{static generate(e="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Vi(e,i){[...e.querySelectorAll(`[${_.REPEAT_ATTR}]`)].forEach(t=>{let r=t.getAttribute(_.REPEAT_ITEM_TAG_ATTR),s;if(r&&(s=window.customElements.get(r)),!s){s=class extends i.BaseComponent{constructor(){super(),r||(this.style.display="contents")}};let o=t.innerHTML;s.template=o,s.reg(r)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(_.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,h=c=>{c.forEach((f,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(f)});else for(let p in f)l[m][p]=f[p];else{a||(a=new DocumentFragment);let p=new s;Object.assign(p.init$,f),a.appendChild(p)}}),a&&t.appendChild(a);let d=l.slice(c.length,l.length);for(let f of d)f.remove()};if(o.constructor===Array)h(o);else if(o.constructor===Object){let c=[];for(let d in o){let f=o[d];Object.defineProperty(f,"_KEY_",{value:d,enumerable:!0}),c.push(f)}h(c)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(_.REPEAT_ATTR),t.removeAttribute(_.REPEAT_ITEM_TAG_ATTR)})}var ze="__default__";function zi(e,i){if(i.shadowRoot)return;let t=[...e.querySelectorAll("slot")];if(!t.length)return;let r={};t.forEach(s=>{let n=s.getAttribute("name")||ze;r[n]={slot:s,fr:document.createDocumentFragment()}}),i.initChildren.forEach(s=>{var n;let o=ze;s instanceof Element&&s.hasAttribute("slot")&&(o=s.getAttribute("slot"),s.removeAttribute("slot")),(n=r[o])==null||n.fr.appendChild(s)}),Object.values(r).forEach(s=>{if(s.fr.childNodes.length)s.slot.parentNode.replaceChild(s.fr,s.slot);else if(s.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...s.slot.childNodes),s.slot.parentNode.replaceChild(n,s.slot)}else s.slot.remove()})}function ji(e,i){[...e.querySelectorAll(`[${_.EL_REF_ATTR}]`)].forEach(t=>{let r=t.getAttribute(_.EL_REF_ATTR);i.ref[r]=t,t.removeAttribute(_.EL_REF_ATTR)})}function Hi(e,i){[...e.querySelectorAll(`[${_.BIND_ATTR}]`)].forEach(t=>{let s=t.getAttribute(_.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Fi(n.name.replace("-",""));s.push(o+":"+n.value),t.removeAttribute(n.name)}}),s.forEach(n=>{if(!n)return;let o=n.split(":").map(c=>c.trim()),l=o[0],a;l.indexOf(_.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(_.ATTR_BIND_PRFX,""));let h=o[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("!","")),i.sub(c,f=>{d==="double"?f=!!f:d==="single"&&(f=!f),a?(f==null?void 0:f.constructor)===Boolean?f?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,f):We(t,l,f)||(t[_.SET_LATER_KEY]||(t[_.SET_LATER_KEY]=Object.create(null)),t[_.SET_LATER_KEY][l]=f)})}}),t.removeAttribute(_.BIND_ATTR)})}var Pt="{{",vt="}}",Wi="skip-text";function Xi(e){let i,t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:s=>{var n;return!((n=s.parentElement)!=null&&n.hasAttribute(Wi))&&s.textContent.includes(Pt)&&s.textContent.includes(vt)&&1}});for(;i=r.nextNode();)t.push(i);return t}var Bi=function(e,i){Xi(e).forEach(r=>{let s=[],n;for(;r.textContent.includes(vt);)r.textContent.startsWith(Pt)?(n=r.textContent.indexOf(vt)+vt.length,r.splitText(n),s.push(r)):(n=r.textContent.indexOf(Pt),r.splitText(n)),r=r.nextSibling;s.forEach(o=>{let l=o.textContent.replace(Pt,"").replace(vt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Gi=[Vi,zi,ji,Hi,Bi],kt="'",pt='"',qi=/\\([0-9a-fA-F]{1,6} ?)/g;function Ki(e){return(e[0]===pt||e[0]===kt)&&(e[e.length-1]===pt||e[e.length-1]===kt)}function Yi(e){return(e[0]===pt||e[0]===kt)&&(e=e.slice(1)),(e[e.length-1]===pt||e[e.length-1]===kt)&&(e=e.slice(0,-1)),e}function Ji(e){let i="",t="";for(var r=0;rString.fromCodePoint(parseInt(r.trim(),16))),i=i.replaceAll(`\\ +`,"\\n"),i=Ji(i),i=pt+i+pt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${e}`)}}var je=0,ft=null,Y=null,tt=class extends HTMLElement{constructor(){super(),ce(this,"updateCssData",()=>{var e;this.dropCssDataCache(),(e=this.__boundCssProps)==null||e.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return tt}initCallback(){}__initCallback(){var e;this.__initialized||(this.__initialized=!0,(e=this.initCallback)==null||e.call(this))}render(e,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(_.USE_TPL);if(s){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(s))||document.querySelector(s);o?e=o.content.cloneNode(!0):console.warn(`Symbiote template "${s}" is not found...`)}}if(this.processInnerHtml)for(let s of this.tplProcessors)s(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==null?void 0:e.constructor)===DocumentFragment)t=e;else if((e==null?void 0:e.constructor)===String){let s=document.createElement("template");s.innerHTML=e,t=s.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(t,this)}let r=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let s=document.createElement("link");s.rel="stylesheet",s.href=this.constructor.__shadowStylesUrl,s.onload=r,this.shadowRoot.prepend(s)}else r()}addTemplateProcessor(e){this.tplProcessors.add(e)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=wt.generate(),this.style.setProperty(_.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(_.CSS_CTX_PROP,!0)}get ctxName(){var e;let i=((e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(e,i){let t,r;if(e.startsWith(_.EXT_DATA_CTX_PRFX))t=i.nodeCtx,r=e.replace(_.EXT_DATA_CTX_PRFX,"");else if(e.includes(_.NAMED_DATA_CTX_SPLTR)){let s=e.split(_.NAMED_DATA_CTX_SPLTR);t=E.getCtx(s[0]),r=s[1]}else t=i.localCtx,r=e;return{ctx:t,name:r}}sub(e,i,t=!0){let r=n=>{this.isConnected&&i(n)},s=tt.__parseProp(e,this);s.ctx.has(s.name)?this.allSubs.add(s.ctx.sub(s.name,r,t)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,r,t))})}notify(e){let i=tt.__parseProp(e,this);i.ctx.notify(i.name)}has(e){let i=tt.__parseProp(e,this);return i.ctx.has(i.name)}add(e,i,t=!1){let r=tt.__parseProp(e,this);r.ctx.add(r.name,i,t)}add$(e,i=!1){for(let t in e)this.add(t,e[t],i)}get $(){if(!this.__stateProxy){let e=Object.create(null);this.__stateProxy=new Proxy(e,{set:(i,t,r)=>{let s=tt.__parseProp(t,this);return s.ctx.pub(s.name,r),!0},get:(i,t)=>{let r=tt.__parseProp(t,this);return r.ctx.read(r.name)}})}return this.__stateProxy}set$(e,i=!1){for(let t in e){let r=e[t];i||![String,Number,Boolean].includes(r==null?void 0:r.constructor)?this.$[t]=r:this.$[t]!==r&&(this.$[t]=r)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(_.CTX_OWNER_ATTR)&&this.getAttribute(_.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let e=this.constructor.__attrDesc;if(e)for(let i of Object.values(e))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(_.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(_.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(_.NAMED_DATA_CTX_SPLTR)){let t=i.split(_.NAMED_DATA_CTX_SPLTR),r=t[0].trim(),s=t[1].trim();if(r&&s){let n=E.getCtx(r,!1);n||(n=E.registerCtx({},r)),n.add(s,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var e;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim();if(i&&this.style.setProperty(_.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[_.SET_LATER_KEY]){for(let t in this[_.SET_LATER_KEY])We(this,t,this[_.SET_LATER_KEY][t]);delete this[_.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Gi)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${_.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(_.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(s):t.prepend(s)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let e of this.allSubs)e.remove(),this.allSubs.delete(e);for(let e of this.tplProcessors)this.tplProcessors.delete(e);Y==null||Y.delete(this.updateCssData),Y!=null&&Y.size||(ft==null||ft.disconnect(),ft=null,Y=null)},100)))}static reg(e,i=!1){e||(je++,e=`${_.AUTO_TAG_PRFX}-${je}`),this.__tag=e;let t=window.customElements.get(e);if(t){!i&&t!==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,i?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,i,t){var r;if(i===t)return;let s=(r=this.constructor.__attrDesc)==null?void 0:r[e];s?this.__dataCtxInitialized?this.$[s]=t:this.init$[s]=t:this[e]=t}getCssData(e,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(e)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(e).trim();try{this.__cssDataCache[e]=Qi(t)}catch{!i&&console.warn(`CSS Data error: ${e}`),this.__cssDataCache[e]=null}}return this.__cssDataCache[e]}__extractCssName(e){return e.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){Y||(Y=new Set),Y.add(this.updateCssData),ft||(ft=new MutationObserver(e=>{e[0].type==="attributes"&&Y.forEach(i=>{i()})}),ft.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(e,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(e);let t=this.getCssData(this.__extractCssName(e),!0);t===null&&(t=i),this.add(e,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(e,i,t){let r="__"+e;this[r]=this[e],Object.defineProperty(this,e,{set:s=>{this[r]=s,t?window.setTimeout(()=>{i==null||i(s)}):i==null||i(s)},get:()=>this[r]}),this[e]=this[r]}static set shadowStyles(e){let i=new Blob([e],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(e){if(!this.__rootStylesLink){let i=new Blob([e],{type:"text/css"}),t=URL.createObjectURL(i),r=document.createElement("link");r.href=t,r.rel="stylesheet",this.__rootStylesLink=r}}},he=tt;ce(he,"template");var ue=class{static _print(e){console.warn(e)}static setDefaultTitle(e){this.defaultTitle=e}static setRoutingMap(e){Object.assign(this.appMap,e);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}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(t=>{if(t.includes("?"))e.route=t.replace("?","");else if(t.includes("=")){let r=t.split("=");e.options[r[0]]=decodeURI(r[1])}else e.options[t]=!0}),e}static notify(){let e=this.readAddressBar(),i=this.appMap[e.route];if(i&&i.title&&(document.title=i.title),e.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${e.route}" not found...`);return}let t=new CustomEvent(ue.routingEventName,{detail:{route:e.route,options:Object.assign(i||{},e.options)}});window.dispatchEvent(t)}static reflect(e,i={}){let t=this.appMap[e];if(!t){this._print("Wrong route: "+e);return}let r="?"+e;for(let n in i)i[n]===!0?r+=this.separator+n:r+=this.separator+n+`=${i[n]}`;let s=t.title||this.defaultTitle||"";window.history.pushState(null,s,r),document.title=s}static applyRoute(e,i={}){this.reflect(e,i),this.notify()}static setSeparator(e){this._separator=e}static get separator(){return this._separator||"&"}static createRouterData(e,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},e);return window.addEventListener(this.routingEventName,r=>{var s;t.multiPub({route:r.detail.route,options:r.detail.options,title:((s=r.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),ue.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};ue.appMap=Object.create(null);var Xe="idb-store-ready",Zi="symbiote-db",tr="symbiote-idb-update_",er=class{_notifyWhenReady(e=null){window.dispatchEvent(new CustomEvent(Xe,{detail:{dbName:this.name,storeName:this.storeName,event:e}}))}get _updEventName(){return tr+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,i){this.name=e,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=r=>{this._notifyWhenReady(r)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async s=>{s(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(e){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(e);return new Promise((r,s)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?r(n.target.result._value):(r(null),console.warn(`IDB: cannot read "${e}"`))},t.onerror=n=>{s(n)}})}write(e,i,t=!1){let r={_key:e,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(r);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(e),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(e,i=!1){let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);return new Promise((s,n)=>{r.onsuccess=o=>{i||this._notifySubscribers(e),s(o)},r.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,r)=>{i.onsuccess=s=>{let n=s.target.result;t(n.map(o=>o._value))},i.onerror=s=>{r(s)}})}subscribe(e,i){this._subscriptionsMap[e]||(this._subscriptionsMap[e]=new Set);let t=this._subscriptionsMap[e];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[e]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,Be.clear(this.name)}},Be=class{static get readyEventName(){return Xe}static open(e=Zi,i="store"){let t=e+"/"+i;return this._reg[t]||(this._reg[t]=new er(e,i)),this._reg[t]}static clear(e){window.indexedDB.deleteDatabase(e);for(let i in this._reg)i.split("/")[0]===e&&delete this._reg[i]}};ce(Be,"_reg",Object.create(null));function z(e,i){let t,r=(...s)=>{clearTimeout(t),t=setTimeout(()=>e(...s),i)};return r.cancel=()=>{clearTimeout(t)},r}var ir="--uploadcare-blocks-window-height",Nt="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function de(){return typeof window[Nt]=="undefined"?!1:!!window[Nt]}function Ge(){if(de())return;let e=()=>{document.documentElement.style.setProperty(ir,`${window.innerHeight}px`),window[Nt]=!0},i=z(e,100);return window.addEventListener("resize",i,{passive:!0}),e(),()=>{window[Nt]=!1,window.removeEventListener("resize",i)}}var rr=e=>e,fe="{{",Ke="}}",qe="plural:";function pe(e,i,t={}){var o;let{openToken:r=fe,closeToken:s=Ke,transform:n=rr}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();e=e.replaceAll(r+l+s,typeof a=="string"?n(a):a)}return e}function Ye(e){let i=[],t=e.indexOf(fe);for(;t!==-1;){let r=e.indexOf(Ke,t),s=e.substring(t+2,r);if(s.startsWith(qe)){let n=e.substring(t+2,r).replace(qe,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:s,pluralKey:o,countVariable:l})}t=e.indexOf(fe,r)}return i}function Je(e){return Object.prototype.toString.call(e)==="[object Object]"}var sr=/\W|_/g;function nr(e){return e.split(sr).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Qe(e,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(e)?e.map(t=>Q(t,{ignoreKeys:i})):e}function Q(e,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(e))return Qe(e,{ignoreKeys:i});if(!Je(e))return e;let t={};for(let r of Object.keys(e)){let s=e[r];if(i.includes(r)){t[r]=s;continue}Je(s)?s=Q(s,{ignoreKeys:i}):Array.isArray(s)&&(s=Qe(s,{ignoreKeys:i})),t[nr(r)]=s}return t}var or=e=>new Promise(i=>setTimeout(i,e));function Ee({libraryName:e,libraryVersion:i,userAgent:t,publicKey:r="",integration:s=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:r,libraryName:e,libraryVersion:i,languageName:n,integration:s});let o=[e,i,r].filter(Boolean).join("/"),l=[n,s].filter(Boolean).join("; ");return`${o} (${l})`}var lr={factor:2,time:100};function ar(e,i=lr){let t=0;function r(s){let n=Math.round(i.time*i.factor**t);return s({attempt:t,retry:l=>or(l!=null?l:n).then(()=>(t+=1,r(s)))})}return r(e)}var yt=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,yt.prototype),this.originalProgressEvent=t}},Ft=(e,i)=>{e&&(e.aborted?Promise.resolve().then(i):e.addEventListener("abort",()=>i(),{once:!0}))},et=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,et.prototype)}},ur=500,ti=({check:e,interval:i=ur,timeout:t,signal:r})=>new Promise((s,n)=>{let o,l;Ft(r,()=>{o&&clearTimeout(o),n(new et("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new et("Timed out"))},t));let a=()=>{try{Promise.resolve(e(r)).then(h=>{h?(l&&clearTimeout(l),s(h)):o=setTimeout(a,i)}).catch(h=>{l&&clearTimeout(l),n(h)})}catch(h){l&&clearTimeout(l),n(h)}};o=setTimeout(a,0)}),C={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Vt="application/octet-stream",ei="original",rt=({method:e,url:i,data:t,headers:r={},signal:s,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,h=(e==null?void 0:e.toUpperCase())||"GET",c=!1;a.open(h,i,!0),r&&Object.entries(r).forEach(d=>{let[f,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(f,m)}),a.responseType="text",Ft(s,()=>{c=!0,a.abort(),l(new et)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:h,url:i,data:t,headers:r||void 0,signal:s,onProgress:n},f=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};f.forEach(function(w){let v=w.split(": "),b=v.shift(),g=v.join(": ");b&&typeof b!="undefined"&&(m[b]=g)});let p=a.response,y=a.status;o({request:d,data:p,headers:m,status:y})}},a.onerror=d=>{c||l(new yt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function cr(e,...i){return e}var hr=({name:e})=>e?[e]:[],dr=cr,fr=()=>new FormData,ii=e=>!1,zt=e=>typeof Blob!="undefined"&&e instanceof Blob,jt=e=>typeof File!="undefined"&&e instanceof File,Ht=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&"uri"in e&&typeof e.uri=="string",At=e=>zt(e)||jt(e)||ii()||Ht(e),pr=e=>typeof e=="string"||typeof e=="number"||typeof e=="undefined",mr=e=>!!e&&typeof e=="object"&&!Array.isArray(e),_r=e=>!!e&&typeof e=="object"&&"data"in e&&At(e.data);function gr(e,i,t){if(_r(t)){let{name:r,contentType:s}=t,n=dr(t.data,r,s!=null?s:Vt),o=hr({name:r,contentType:s});e.push([i,n,...o])}else if(mr(t))for(let[r,s]of Object.entries(t))typeof s!="undefined"&&e.push([`${i}[${r}]`,String(s)]);else pr(t)&&t&&e.push([i,t.toString()])}function br(e){let i=[];for(let[t,r]of Object.entries(e))gr(i,t,r);return i}function Te(e){let i=fr(),t=br(e);for(let r of t){let[s,n,...o]=r;i.append(s,n,...o)}return i}var R=class extends Error{constructor(t,r,s,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=r,this.request=s,this.response=n,this.headers=o,Object.setPrototypeOf(this,R.prototype)}},yr=e=>{let i=new URLSearchParams;for(let[t,r]of Object.entries(e))r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(s=>{var n;return(n=s[1])!=null?n:!1}).forEach(s=>i.set(`${t}[${s[0]}]`,String(s[1]))):Array.isArray(r)?r.forEach(s=>{i.append(`${t}[]`,s)}):typeof r=="string"&&r?i.set(t,r):typeof r=="number"&&i.set(t,r.toString());return i.toString()},J=(e,i,t)=>{let r=new URL(e);return r.pathname=(r.pathname+i).replace("//","/"),t&&(r.search=yr(t)),r.toString()},Cr="6.6.1",Er="UploadcareUploadClient",Tr=Cr;function ht(e){return Ee({libraryName:Er,libraryVersion:Tr,...e})}var vr="RequestThrottledError",Ze=15e3,wr=1e3;function Ar(e){let{headers:i}=e||{};if(!i||typeof i["retry-after"]!="string")return Ze;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Ze}function st(e,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:r}=i;return ar(({attempt:s,retry:n})=>e().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===vr&&s{let i="";return(zt(e)||jt(e)||Ht(e))&&(i=e.type),i||Vt},si=e=>{let i="";return jt(e)&&e.name?i=e.name:zt(e)||ii()?i="":Ht(e)&&e.name&&(i=e.name),i||ei};function ve(e){return typeof e=="undefined"||e==="auto"?"auto":e?"1":"0"}function xr(e,{publicKey:i,fileName:t,contentType:r,baseURL:s=C.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:h,source:c="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=C.retryNetworkErrorMaxTimes,metadata:y}){return st(()=>rt({method:"POST",url:J(s,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":ht({publicKey:i,integration:d,userAgent:f})},data:Te({file:{data:e,name:t||si(e),contentType:r||ri(e)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:ve(l),signature:n,expire:o,source:c,metadata:y}),signal:a,onProgress:h}).then(({data:w,headers:v,request:b})=>{let g=Q(JSON.parse(w));if("error"in g)throw new R(g.error.content,g.error.errorCode,b,g,v);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var ge;(function(e){e.Token="token",e.FileInfo="file_info"})(ge||(ge={}));function Sr(e,{publicKey:i,baseURL:t=C.baseURL,store:r,fileName:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:h="url",signal:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=C.retryNetworkErrorMaxTimes,metadata:y}){return st(()=>rt({method:"POST",headers:{"X-UC-User-Agent":ht({publicKey:i,integration:d,userAgent:f})},url:J(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:e,store:ve(r),filename:s,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:h,metadata:y}),signal:c}).then(({data:w,headers:v,request:b})=>{let g=Q(JSON.parse(w));if("error"in g)throw new R(g.error.content,g.error.errorCode,b,g,v);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var $;(function(e){e.Unknown="unknown",e.Waiting="waiting",e.Progress="progress",e.Error="error",e.Success="success"})($||($={}));var Or=e=>"status"in e&&e.status===$.Error;function Ir(e,{publicKey:i,baseURL:t=C.baseURL,signal:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=C.retryNetworkErrorMaxTimes}={}){return st(()=>rt({method:"GET",headers:i?{"X-UC-User-Agent":ht({publicKey:i,integration:s,userAgent:n})}:void 0,url:J(t,"/from_url/status/",{jsonerrors:1,token:e}),signal:r}).then(({data:a,headers:h,request:c})=>{let d=Q(JSON.parse(a));if("error"in d&&!Or(d))throw new R(d.error.content,void 0,c,d,h);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Ur(e,{publicKey:i,baseURL:t=C.baseURL,jsonpCallback:r,secureSignature:s,secureExpire:n,signal:o,source:l,integration:a,userAgent:h,retryThrottledRequestMaxTimes:c=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=C.retryNetworkErrorMaxTimes}){return st(()=>rt({method:"POST",headers:{"X-UC-User-Agent":ht({publicKey:i,integration:a,userAgent:h})},url:J(t,"/group/",{jsonerrors:1,pub_key:i,files:e,callback:r,signature:s,expire:n,source:l}),signal:o}).then(({data:f,headers:m,request:p})=>{let y=Q(JSON.parse(f));if("error"in y)throw new R(y.error.content,y.error.errorCode,p,y,m);return y}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:c})}function ni(e,{publicKey:i,baseURL:t=C.baseURL,signal:r,source:s,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=C.retryNetworkErrorMaxTimes}){return st(()=>rt({method:"GET",headers:{"X-UC-User-Agent":ht({publicKey:i,integration:n,userAgent:o})},url:J(t,"/info/",{jsonerrors:1,pub_key:i,file_id:e,source:s}),signal:r}).then(({data:h,headers:c,request:d})=>{let f=Q(JSON.parse(h));if("error"in f)throw new R(f.error.content,f.error.errorCode,d,f,c);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Rr(e,{publicKey:i,contentType:t,fileName:r,multipartChunkSize:s=C.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:h,source:c="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=C.retryNetworkErrorMaxTimes,metadata:y}){return st(()=>rt({method:"POST",url:J(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":ht({publicKey:i,integration:d,userAgent:f})},data:Te({filename:r||ei,size:e,content_type:t||Vt,part_size:s,UPLOADCARE_STORE:ve(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:c,metadata:y}),signal:h}).then(({data:w,headers:v,request:b})=>{let g=Q(JSON.parse(w));if("error"in g)throw new R(g.error.content,g.error.errorCode,b,g,v);return g.parts=Object.keys(g.parts).map(N=>g.parts[N]),g}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})}function Lr(e,i,{contentType:t,signal:r,onProgress:s,retryThrottledRequestMaxTimes:n=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=C.retryNetworkErrorMaxTimes}){return st(()=>rt({method:"PUT",url:i,data:e,onProgress:s,signal:r,headers:{"Content-Type":t||Vt}}).then(l=>(s&&s({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Mr(e,{publicKey:i,baseURL:t=C.baseURL,source:r="local",signal:s,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=C.retryNetworkErrorMaxTimes}){return st(()=>rt({method:"POST",url:J(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":ht({publicKey:i,integration:n,userAgent:o})},data:Te({uuid:e,UPLOADCARE_PUB_KEY:i,source:r}),signal:s}).then(({data:h,headers:c,request:d})=>{let f=Q(JSON.parse(h));if("error"in f)throw new R(f.error.content,f.error.errorCode,d,f,c);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function we({file:e,publicKey:i,baseURL:t,source:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:h}){return ti({check:c=>ni(e,{publicKey:i,baseURL:t,signal:c,source:r,integration:s,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(h&&h({isComputable:!0,value:1}),!1)),signal:a})}var it=class{constructor(i,{baseCDN:t=C.baseCDN,fileName:r}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);let{uuid:s,s3Bucket:n}=i,o=J(t,`${s}/`),l=n?J(`https://${n}.s3.amazonaws.com/`,`${s}/${i.filename}`):null;this.uuid=s,this.name=r||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},Pr=(e,{publicKey:i,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,contentType:l,signal:a,onProgress:h,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,baseCDN:y,metadata:w})=>xr(e,{publicKey:i,fileName:t,contentType:l,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:a,onProgress:h,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:w}).then(({file:v})=>we({file:v,publicKey:i,baseURL:r,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:h,signal:a})).then(v=>new it(v,{baseCDN:y})),kr=(e,{publicKey:i,fileName:t,baseURL:r,signal:s,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:c,baseCDN:d})=>ni(e,{publicKey:i,baseURL:r,signal:s,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:c}).then(f=>new it(f,{baseCDN:d,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),Nr=(e,{signal:i}={})=>{let t=null,r=null,s=e.map(()=>new AbortController),n=o=>()=>{r=o,s.forEach((l,a)=>a!==o&&l.abort())};return Ft(i,()=>{s.forEach(o=>o.abort())}),Promise.all(e.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:s[l].signal})).then(h=>(a(),h)).catch(h=>(t=h,null))})).then(o=>{if(r===null)throw t;return o[r]})},Dr=window.WebSocket,be=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var r;(r=this.events[i])==null||r.forEach(s=>s(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(r=>r!==t):this.events[i]=[]}},$r=(e,i)=>e==="success"?{status:$.Success,...i}:e==="progress"?{status:$.Progress,...i}:{status:$.Error,...i},ye=class{constructor(i,t=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new be);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Dr(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let r=JSON.parse(t.data.toString());switch(r.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(r.channel,$r(r.event,JSON.parse(r.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var s;let r=JSON.stringify({event:i,data:t});(s=this.ws)==null||s.send(r)}subscribe(i,t){this.subscribers+=1,this.connect();let r=`task-status-${i}`,s={event:"pusher:subscribe",data:{channel:r}};this.emmitter.on(r,t),this.isConnected?this.send(s.event,s.data):this.queue.push(s)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,r={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(r.event,r.data):this.queue=this.queue.filter(s=>s.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},me=null,Ae=e=>{if(!me){let i=typeof window=="undefined"?0:3e4;me=new ye(e,i)}return me},Fr=e=>{Ae(e).connect()};function Vr({token:e,publicKey:i,baseURL:t,integration:r,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return ti({check:h=>Ir(e,{publicKey:i,baseURL:t,integration:r,userAgent:s,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:h}).then(c=>{switch(c.status){case $.Error:return new R(c.error,c.errorCode);case $.Waiting:return!1;case $.Unknown:return new R(`Token "${e}" was not found.`);case $.Progress:return l&&(c.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:c.done/c.total})),!1;case $.Success:return l&&l({isComputable:!0,value:c.done/c.total}),c;default:throw new Error("Unknown status")}}),signal:a})}var zr=({token:e,pusherKey:i,signal:t,onProgress:r})=>new Promise((s,n)=>{let o=Ae(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(e)};Ft(t,()=>{a(),n(new et("pusher cancelled"))}),o.subscribe(e,h=>{switch(h.status){case $.Progress:{r&&(h.total==="unknown"?r({isComputable:!1}):r({isComputable:!0,value:h.done/h.total}));break}case $.Success:{a(),r&&r({isComputable:!0,value:h.done/h.total}),s(h);break}case $.Error:a(),n(new R(h.msg,h.error_code))}})}),jr=(e,{publicKey:i,fileName:t,baseURL:r,baseCDN:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:h,signal:c,onProgress:d,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,pusherKey:w=C.pusherKey,metadata:v})=>Promise.resolve(Fr(w)).then(()=>Sr(e,{publicKey:i,fileName:t,baseURL:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:h,signal:c,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,metadata:v})).catch(b=>{let g=Ae(w);return g==null||g.disconnect(),Promise.reject(b)}).then(b=>b.type===ge.FileInfo?b:Nr([({signal:g})=>Vr({token:b.token,publicKey:i,baseURL:r,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,onProgress:d,signal:g}),({signal:g})=>zr({token:b.token,pusherKey:w,signal:g,onProgress:d})],{signal:c})).then(b=>{if(b instanceof R)throw b;return b}).then(b=>we({file:b.uuid,publicKey:i,baseURL:r,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,onProgress:d,signal:c})).then(b=>new it(b,{baseCDN:s})),_e=new WeakMap,Hr=async e=>{if(_e.has(e))return _e.get(e);let i=await fetch(e.uri).then(t=>t.blob());return _e.set(e,i),i},oi=async e=>{if(jt(e)||zt(e))return e.size;if(Ht(e))return(await Hr(e)).size;throw new Error("Unknown file type. Cannot determine file size.")},Wr=(e,i=C.multipartMinFileSize)=>e>=i,li=e=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!At(e)&&t.test(e)},ai=e=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!At(e)&&t.test(e)},Xr=(e,i)=>new Promise((t,r)=>{let s=[],n=!1,o=i.length,l=[...i],a=()=>{let h=i.length-l.length,c=l.shift();c&&c().then(d=>{n||(s[h]=d,o-=1,o?a():t(s))}).catch(d=>{n=!0,r(d)})};for(let h=0;h{let s=r*i,n=Math.min(s+r,t);return e.slice(s,n)},Gr=async(e,i,t)=>r=>Br(e,r,i,t),qr=(e,i,{publicKey:t,contentType:r,onProgress:s,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Lr(e,i,{publicKey:t,contentType:r,onProgress:s,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Kr=async(e,{publicKey:i,fileName:t,fileSize:r,baseURL:s,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:h,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,contentType:y,multipartChunkSize:w=C.multipartChunkSize,maxConcurrentRequests:v=C.maxConcurrentRequests,baseCDN:b,metadata:g})=>{let N=r!=null?r:await oi(e),G,lt=(U,V)=>{if(!h)return;G||(G=Array(U).fill(0));let q=D=>D.reduce((K,le)=>K+le,0);return D=>{D.isComputable&&(G[V]=D.value,h({isComputable:!0,value:q(G)/U}))}};return y||(y=ri(e)),Rr(N,{publicKey:i,contentType:y,fileName:t||si(e),baseURL:s,secureSignature:n,secureExpire:o,store:l,signal:a,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:g}).then(async({uuid:U,parts:V})=>{let q=await Gr(e,N,w);return Promise.all([U,Xr(v,V.map((D,K)=>()=>qr(q(K),D,{publicKey:i,contentType:y,onProgress:lt(V.length,K),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})))])}).then(([U])=>Mr(U,{publicKey:i,baseURL:s,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})).then(U=>U.isReady?U:we({file:U.uuid,publicKey:i,baseURL:s,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:h,signal:a})).then(U=>new it(U,{baseCDN:b}))};async function xe(e,{publicKey:i,fileName:t,baseURL:r=C.baseURL,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartMinFileSize:y,multipartChunkSize:w,maxConcurrentRequests:v,baseCDN:b=C.baseCDN,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:N,pusherKey:G,metadata:lt}){if(At(e)){let U=await oi(e);return Wr(U,y)?Kr(e,{publicKey:i,contentType:p,multipartChunkSize:w,fileSize:U,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,maxConcurrentRequests:v,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:lt}):Pr(e,{publicKey:i,fileName:t,contentType:p,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:lt})}if(ai(e))return jr(e,{publicKey:i,fileName:t,baseURL:r,baseCDN:b,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:N,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,pusherKey:G,metadata:lt});if(li(e))return kr(e,{publicKey:i,fileName:t,baseURL:r,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b});throw new TypeError(`File uploading from "${e}" is not supported`)}var Ce=class{constructor(i,t){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((r,s)=>r+s.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(r=>r.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Yr=e=>{for(let i of e)if(!At(i))return!1;return!0},Jr=e=>{for(let i of e)if(!li(i))return!1;return!0},Qr=e=>{for(let i of e)if(!ai(i))return!1;return!0};function ui(e,{publicKey:i,fileName:t,baseURL:r=C.baseURL,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:y=C.multipartChunkSize,baseCDN:w=C.baseCDN,checkForUrlDuplicates:v,saveUrlForRecurrentUploads:b,jsonpCallback:g}){if(!Yr(e)&&!Qr(e)&&!Jr(e))throw new TypeError(`Group uploading from "${e}" is not supported`);let N,G=!0,lt=e.length,U=(V,q)=>{if(!a)return;N||(N=Array(V).fill(0));let D=K=>K.reduce((le,Ri)=>le+Ri)/V;return K=>{if(!K.isComputable||!G){G=!1,a({isComputable:!1});return}N[q]=K.value,a({isComputable:!0,value:D(N)})}};return Promise.all(e.map((V,q)=>xe(V,{publicKey:i,fileName:t,baseURL:r,secureSignature:s,secureExpire:n,store:o,signal:l,onProgress:U(lt,q),source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:y,baseCDN:w,checkForUrlDuplicates:v,saveUrlForRecurrentUploads:b}))).then(V=>{let q=V.map(D=>D.uuid);return Ur(q,{publicKey:i,baseURL:r,jsonpCallback:g,secureSignature:s,secureExpire:n,signal:l,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m}).then(D=>new Ce(D,V)).then(D=>(a&&a({isComputable:!0,value:1}),D))})}var ut,mt,ct,_t,gt,bt,Dt,$t=class{constructor(i){at(this,bt);at(this,ut,1);at(this,mt,[]);at(this,ct,0);at(this,_t,new WeakMap);at(this,gt,new WeakMap);Tt(this,ut,i)}add(i){return new Promise((t,r)=>{L(this,_t).set(i,t),L(this,gt).set(i,r),L(this,mt).push(i),Mt(this,bt,Dt).call(this)})}get pending(){return L(this,mt).length}get running(){return L(this,ct)}set concurrency(i){Tt(this,ut,i),Mt(this,bt,Dt).call(this)}get concurrency(){return L(this,ut)}};ut=new WeakMap,mt=new WeakMap,ct=new WeakMap,_t=new WeakMap,gt=new WeakMap,bt=new WeakSet,Dt=function(){let i=L(this,ut)-L(this,ct);for(let t=0;t{L(this,_t).delete(r),L(this,gt).delete(r),Tt(this,ct,L(this,ct)-1),Mt(this,bt,Dt).call(this)}).then(o=>s(o)).catch(o=>n(o))}};var Se=()=>({"*blocksRegistry":new Set}),Oe=e=>({...Se(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{e.set$({"*modalActive":!1,"*currentActivity":""})}}),Wt=e=>({...Oe(e),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new $t(1)});function ci(e,i){[...e.querySelectorAll("[l10n]")].forEach(t=>{let r=t.getAttribute("l10n"),s="textContent";if(r.includes(":")){let o=r.split(":");s=o[0],r=o[1]}let n="l10n:"+r;i.__l10nKeys.push(n),i.add(n,r),i.sub(n,o=>{t[s]=i.l10n(o)}),t.removeAttribute("l10n")})}var j=e=>`*cfg/${e}`;var nt=e=>{var i;return(i=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var hi=new Set;function Xt(e){hi.has(e)||(hi.add(e),console.warn(e))}var Bt=(e,i)=>new Intl.PluralRules(e).select(i);var Ie="lr-",S=class extends he{constructor(){super();u(this,"allowCustomTemplate",!0);u(this,"init$",Se());u(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let r of t)r.isConnected&&r.updateCssData()});this.activityType=null,this.addTemplateProcessor(ci),this.__l10nKeys=[]}l10n(t,r={}){if(!t)return"";let s=this.getCssData("--l10n-"+t,!0)||t,n=Ye(s);for(let l of n)r[l.variable]=this.pluralize(l.pluralKey,Number(r[l.countVariable]));return pe(s,r)}pluralize(t,r){let s=this.l10n("locale-name")||"en-US",n=Bt(s,r);return this.l10n(`${t}__${n}`)}applyL10nKey(t,r){let s="l10n:"+t;this.$[s]=r,this.__l10nKeys.push(t)}hasBlockInCtx(t){let r=this.$["*blocksRegistry"];for(let s of r)if(t(s))return!0;return!1}setOrAddState(t,r){this.add$({[t]:r},!0)}setActivity(t){if(this.hasBlockInCtx(r=>r.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ie}${t}`,!0),de()||(this._destroyInnerHeightTracker=Ge()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,r=2){let s=["B","KB","MB","GB","TB"],n=h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h;if(t===0)return`0 ${n(s[0])}`;let o=1024,l=r<0?0:r,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(s[a])}proxyUrl(t){let r=this.cfg.secureDeliveryProxy;return r?pe(r,{previewUrl:t},{transform:s=>window.encodeURIComponent(s)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(r,s)=>{let n=j(s),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Xt("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${nt(s)}`))}})}return this.__cfgProxy}subConfigValue(t,r){let s=this.parseCfgProp(j(t));s.ctx.has(s.name)?this.sub(j(t),r):(this.bindCssData(`--cfg-${nt(t)}`),this.sub(`--cfg-${nt(t)}`,r))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ie)?t:Ie+t)}};u(S,"StateConsumerScope",null),u(S,"className","");var di="active",xt="___ACTIVITY_IS_ACTIVE___",H=class extends S{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",Oe(this));u(this,"_debouncedHistoryFlush",z(this._historyFlush.bind(this),10))}_deactivate(){var r;let t=H._activityRegistry[this.activityKey];this[xt]=!1,this.removeAttribute(di),(r=t==null?void 0:t.deactivateCallback)==null||r.call(t)}_activate(){var r;let t=H._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[xt]=!0,this.setAttribute(di,""),(r=t==null?void 0:t.activateCallback)==null||r.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[xt]?this._deactivate():this.activityType===t&&!this[xt]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!H._activityRegistry[this.activityKey]}get isActivityActive(){return this[xt]}registerActivity(t,r={}){let{onActivate:s,onDeactivate:n}=r;H._activityRegistry||(H._activityRegistry=Object.create(null)),H._activityRegistry[this.activityKey]={activateCallback:s,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),H._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(H._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let r=t.pop();for(;r===this.activityType;)r=t.pop();this.$["*currentActivity"]=r,this.$["*history"]=t,r||this.setOrAddState("*modalActive",!1)}}},T=H;u(T,"_activityRegistry",Object.create(null));T.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var Zr="css-src";function ts(e){return class extends e{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Zr);if(t){this.attachShadow({mode:"open"});let r=document.createElement("link");r.rel="stylesheet",r.type="text/css",r.href=t,r.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(r)}else console.error("Attribute `css-src`is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Gt=class extends ts(S){};var qt=class extends Gt{constructor(){super(...arguments);u(this,"init$",Wt(this));u(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var Kt=class extends qt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",r=>{r||(this.$["*currentActivity"]=t.initActivity||T.activities.START_FROM)}),this.sub("*uploadList",r=>{(r==null?void 0:r.length)>0?this.$["*currentActivity"]=T.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||T.activities.START_FROM}),this.subConfigValue("sourceList",r=>{r!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",r=>{r!==!1&&(this.cfg.confirmUpload=!1)})}};Kt.template=``;var Ue=class extends T{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function fi(e,i,t){let r=e/i,s,n;r>t?(s=Math.round(i*t),n=i):(s=e,n=Math.round(e/t));let o=Math.round((e-s)/2),l=Math.round((i-n)/2);return o+s>e&&(s=e-o),l+n>i&&(n=i-l),{x:o,y:l,width:s,height:n}}var pi=e=>{if(!e)return[];let[i,t]=e.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${e}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var ot=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var mi="blocks",_i="0.27.1";function gi(e){return Ee({...e,libraryName:mi,libraryVersion:_i})}var es=e=>{if(typeof e!="string"||!e)return"";let i=e.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Re=(...e)=>e.filter(i=>typeof i=="string"&&i).map(i=>es(i)).join("/-/"),Yt=(...e)=>{let i=Re(...e);return i?`-/${i}/`:""};function bi(e){let i=new URL(e),t=i.pathname+i.search+i.hash,r=t.lastIndexOf("http"),s=t.lastIndexOf("/"),n="";return r>=0?n=t.slice(r):s>=0&&(n=t.slice(s+1)),n}function is(e){let i=new URL(e),t=bi(e),r=yi(t)?Ci(t).pathname:t;return i.pathname=i.pathname.replace(r,""),i.search="",i.hash="",i.toString()}function yi(e){return e.startsWith("http")}function Ci(e){let i=new URL(e);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var Jt=(e,i,t)=>{let r=new URL(is(e));if(t=t||bi(e),r.pathname.startsWith("//")&&(r.pathname=r.pathname.replace("//","/")),yi(t)){let s=Ci(t);r.pathname=r.pathname+(i||"")+(s.pathname||""),r.search=s.search,r.hash=s.hash}else r.pathname=r.pathname+(i||"")+(t||"");return r.toString()},Ei=(e,i)=>{let t=new URL(e);return t.pathname=i+"/",t.toString()};var Ct=(e,i=",")=>e.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var St=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Le=e=>e?e.filter(i=>typeof i=="string").map(i=>Ct(i)).flat():[],Me=(e,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),e.startsWith(t)):e===t),Ti=(e,i)=>i.some(t=>t.startsWith(".")?e.toLowerCase().endsWith(t.toLowerCase()):!1),Pe=e=>{let i=e==null?void 0:e.type;return i?Me(i,St):!1};var W=1e3,dt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),Ot=e=>Math.ceil(e*100)/100,vi=(e,i=dt.AUTO)=>{let t=i===dt.AUTO;if(i===dt.BYTE||t&&e{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!r){s();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{s(),delete this._timeoutStore[n]},20)}};u(O,"_timeoutStore",Object.create(null));var wi="[Typed State] Wrong property name: ",rs="[Typed State] Wrong property type: ",Qt=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||wt.generate(),this.__schema=Object.keys(i).reduce((r,s)=>(r[s]=i[s].value,r),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(wi+i);return}let r=this.__typedSchema[i];if((t==null?void 0:t.constructor)===r.type||t instanceof r.type||r.nullable&&t===null){this.__data.pub(i,t);return}console.warn(rs+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(wi+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Zt=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||wt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(r,s)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[r]||(t[r]=new Set),t[r].add(s),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var r;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(r=this.__handler)==null||r.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Qt(this.__typedSchema);for(let r in i)t.setValue(r,i[r]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(r=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(r,()=>{this.__notifyObservers(r,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,r){this.read(i).setValue(t,r)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(r=>{let s=this.read(r);i(s)&&t.push(r)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var Ai=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:it,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var It=e=>e?e.join(","):"";var x=class extends T{constructor(){super(...arguments);u(this,"couldBeUploadCollectionOwner",!1);u(this,"isUploadCollectionOwner",!1);u(this,"init$",Wt(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",z(this._runValidators.bind(this),100));u(this,"_handleCollectionUpdate",t=>{let r=this.uploadCollection,s=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>r.read(n)).filter(Boolean);for(let n of s)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=r.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=r.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,O.emit(new M({type:I.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=r.findItems(l=>!!l.getValue("fileInfo")),o=r.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(r.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&O.emit(new M({type:I.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&r.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{O.emit(new M({type:I.UPLOAD_ERROR,ctx:this.ctxName,data:r.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&r.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{O.emit(new M({type:I.VALIDATION_ERROR,ctx:this.ctxName,data:r.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&r.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{O.emit(new M({type:I.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){Xt("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let r=new Zt({typedSchema:Ai,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",r)}let t=()=>this.hasBlockInCtx(r=>r instanceof x?r.isUploadCollectionOwner&&r.isConnected&&r!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(r,s,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=r.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",r=>{this.$["*uploadQueue"].concurrency=Number(r)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:r,fileName:s,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:s!=null?s:null,silentUpload:r!=null?r:!1,source:n!=null?n:ot.API})}addFileFromUuid(t,{silent:r,fileName:s,source:n}={}){this.uploadCollection.add({uuid:t,fileName:s!=null?s:null,silentUpload:r!=null?r:!1,source:n!=null?n:ot.API})}addFileFromObject(t,{silent:r,fileName:s,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:Pe(t),mimeType:t.type,fileName:s!=null?s:t.name,fileSize:t.size,silentUpload:r!=null?r:!1,source:n!=null?n:ot.API,fullPath:o})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(r=>{this.uploadCollection.add({file:r,isImage:Pe(r),mimeType:r.type,fileName:r.name,fileSize:r.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var s;let r=It(Le([(s=this.cfg.accept)!=null?s:"",...this.cfg.imgOnly?St:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=It(St)):this.fileInput.accept=r,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:ot.LOCAL})),this.$["*currentActivity"]=T.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=Ct(this.cfg.sourceList)),t}initFlow(t=!1){var r;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":T.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let s=this.sourceList[0];s==="local"?(this.$["*currentActivity"]=T.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(x.extSrcList).includes(s)?this.set$({"*currentActivityParams":{externalSourceType:s},"*currentActivity":T.activities.EXTERNAL}):this.$["*currentActivity"]=s,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":T.activities.START_FROM}),this.setOrAddState("*modalActive",!0);O.emit(new M({type:I.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),O.emit(new M({type:I.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let r=this.cfg.imgOnly,s=this.cfg.accept,n=Le([...r?St:[],s]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Me(o,n),h=Ti(l,n);if(!a&&!h)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let r=this.cfg.maxLocalFileSizeBytes,s=t.getValue("fileSize");if(r&&s&&s>r)return this.l10n("files-max-size-limit-error",{maxFileSize:vi(r)})}_validateMultipleLimit(t){let s=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&s>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let r=this.cfg.imgOnly,s=t.getValue("isImage");if(!(!r||s)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let r of this._validators){let s=r(t);if(s){t.setValue("validationErrorMsg",s);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let r=this.uploadCollection.read(t);r&&this._runValidatorsForEntry(r)})}setInitialCrop(){let t=pi(this.cfg.cropPreset);if(t){let[r]=t,s=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of s){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,h=r.width/r.height,c=fi(l,a,h),d=Yt(`crop/${c.width}x${c.height}/${c.x},${c.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:Jt(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===T.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=T.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var r;let t=(r=this.cfg.metadata)!=null?r:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:gi,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let r=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};r.push(a)}),r}};x.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});x.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...x.extSrcList});Object.values(I).forEach(e=>{let i=O.eName(e),t=z(r=>{if([I.UPLOAD_FINISH,I.REMOVE,I.CDN_MODIFICATION].includes(r.detail.type)){let n=E.getCtx(r.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let h=E.getCtx(a).store,c=h.fileInfo;if(c){let d={...c,cdnUrlModifiers:h.cdnUrlModifiers,cdnUrl:h.cdnUrl||c.cdnUrl};l.push(d)}}),O.emit(new M({type:I.DATA_OUTPUT,ctx:r.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var F=e=>String(e),X=e=>Number(e),A=e=>typeof e=="boolean"?e:e==="true"||e===""?!0:e==="false"?!1:!!e,ss=e=>e==="auto"?e:A(e),ns={pubkey:F,multiple:A,multipleMin:X,multipleMax:X,confirmUpload:A,imgOnly:A,accept:F,externalSourcesPreferredTypes:F,store:ss,cameraMirror:A,sourceList:F,maxLocalFileSizeBytes:X,thumbSize:X,showEmptyList:A,useLocalImageEditor:A,useCloudImageEditor:A,cloudImageEditorTabs:F,removeCopyright:A,cropPreset:F,modalScrollLock:A,modalBackdropStrokes:A,sourceListWrap:A,remoteTabSessionKey:F,cdnCname:F,baseUrl:F,socialBaseUrl:F,secureSignature:F,secureExpire:F,secureDeliveryProxy:F,retryThrottledRequestMaxTimes:X,multipartMinFileSize:X,multipartChunkSize:X,maxConcurrentRequests:X,multipartMaxConcurrentRequests:X,multipartMaxAttempts:X,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:A,groupOutput:A,userAgentIntegration:F},xi=(e,i)=>{if(!(typeof i=="undefined"||i===null))return ns[e](i)};function os(e){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let r=s=>{s.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=r,t.onprogress=r,t.readAsDataURL(e)}catch{i(!1)}})}function ls(e,i){return new Promise(t=>{let r=0,s=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(r++,l.file(a=>{r--;let h=new File([a],a.name,{type:a.type||i});s.push({type:"file",file:h,fullPath:l.fullPath}),r===0&&t(s)})):l.isDirectory&&o(l.createReader())},o=l=>{r++,l.readEntries(a=>{r--;for(let h of a)n(h);r===0&&t(s)})};n(e)})}function Si(e){let i=[],t=[];for(let r=0;r{a&&i.push(...a)}));continue}let o=s.getAsFile();o&&t.push(os(o).then(l=>{l||i.push({type:"file",file:o})}))}else s.kind==="string"&&s.type.match("^text/uri-list")&&t.push(new Promise(n=>{s.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var P={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},Oi=["focus"],as=100,ke=new Map;function us(e,i){let t=Math.max(Math.min(e[0],i.x+i.width),i.x),r=Math.max(Math.min(e[1],i.y+i.height),i.y);return Math.sqrt((e[0]-t)*(e[0]-t)+(e[1]-r)*(e[1]-r))}function Ne(e){let i=0,t=document.body,r=new Set,s=p=>r.add(p),n=P.INACTIVE,o=p=>{e.shouldIgnore()&&p!==P.INACTIVE||(n!==p&&r.forEach(y=>y(p)),n=p)},l=()=>i>0;s(p=>e.onChange(p));let a=()=>{i=0,o(P.INACTIVE)},h=()=>{i+=1,n===P.INACTIVE&&o(P.ACTIVE)},c=()=>{i-=1,l()||o(P.INACTIVE)},d=p=>{p.preventDefault(),i=0,o(P.INACTIVE)},f=p=>{if(e.shouldIgnore())return;l()||(i+=1);let y=[p.x,p.y],w=e.element.getBoundingClientRect(),v=Math.floor(us(y,w)),b=v{if(e.shouldIgnore())return;p.preventDefault();let y=await Si(p.dataTransfer);e.onItems(y),o(P.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",c),t.addEventListener("dragenter",h),t.addEventListener("dragover",f),e.element.addEventListener("drop",m),Oi.forEach(p=>{window.addEventListener(p,a)}),()=>{ke.delete(e.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",c),t.removeEventListener("dragenter",h),t.removeEventListener("dragover",f),e.element.removeEventListener("drop",m),Oi.forEach(p=>{window.removeEventListener(p,a)})}}var Ut=class extends x{constructor(){super(),this.init$={...this.init$,state:P.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,r=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),s=window.getComputedStyle(this),n=s.visibility!=="hidden"&&s.display!=="none";return t&&n&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!A(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:A(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:A(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:A(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Ne({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(r=>{r.type==="url"?this.addFileFromUrl(r.url,{source:ot.DROP_AREA}):r.type==="file"&&this.addFileFromObject(r.file,{source:ot.DROP_AREA,fullPath:r.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":T.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=Ne({element:i,onChange:t=>{var s;let r=(s=Object.entries(P).find(([,n])=>n===t))==null?void 0:s[0].toLowerCase();r&&i.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var s;let r=(s=Object.entries(P).find(([,n])=>n===t))==null?void 0:s[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",t=>{let r=Ct(t);this.$.isEnabled=r.includes(x.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,r=this.uploadCollection.size;return!(i&&t&&r>=t||!i&&r>0)}destroyCallback(){var i,t,r,s;super.destroyCallback(),(t=(i=this.$["lr-drop-area/targets"])==null?void 0:i.remove)==null||t.call(i,this),(r=this._destroyDropzone)==null||r.call(this),(s=this._destroyContentWrapperDropzone)==null||s.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};Ut.template=`
{{text}}
`;Ut.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var te=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}},ee=class extends S{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};ee.template=`
{{captionTxt}}
{{msgTxt}}
`;var ie=class extends x{constructor(){super();u(this,"couldBeUploadCollectionOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",T.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",z(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(r=>!!r.getValue("fileInfo"));O.emit(new M({type:I.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var c,d;let t=!!this.cfg.multiple,r=t?(c=this.cfg.multipleMin)!=null?c:0:1,s=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=r?ns:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:r,max:s,exact:s===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,r=this._validateFilesCount();if(t&&!r.passed){let s=new te,n=r.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";s.caption=this.l10n("files-count-limit-error-title"),s.text=this.l10n(n,{min:r.min,max:r.max,total:t}),s.isError=!0,this.set$({"*message":s})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),s={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let p=this.uploadCollection.read(m);p.getValue("fileInfo")&&!p.getValue("validationErrorMsg")&&(s.succeed+=1),p.getValue("isUploading")&&(s.uploading+=1),(p.getValue("validationErrorMsg")||p.getValue("uploadError"))&&(s.failed+=1),p.getValue("validationMultipleLimitMsg")&&(s.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=s.failed===0&&s.limitOverflow===0,h=!1,c=!1,d=!1;s.total-s.succeed-s.uploading-s.failed>0&&n?h=!0:(c=!0,d=s.total===s.succeed&&n&&a),this.set$({doneBtnVisible:c,doneBtnEnabled:d,uploadBtnVisible:h,addMoreBtnEnabled:s.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(s)})}_getHeaderText(t){let r=s=>{let n=t[s];return this.l10n(`header-${s}`,{count:n})};return t.uploading>0?r("uploading"):t.failed>0?r("failed"):t.succeed>0?r("succeed"):r("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var r;((r=this.uploadCollection)==null?void 0:r.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};ie.template=`{{headerText}}
`;function cs(e){let i=new Blob([e],{type:"image/svg+xml"});return URL.createObjectURL(i)}function De(e="hsl(209, 21%, 65%)",i=32,t=32){return cs(``)}function Ii(e,i=40){if(e.type==="image/svg+xml")return URL.createObjectURL(e);let t=document.createElement("canvas"),r=t.getContext("2d"),s=new Image,n=new Promise((o,l)=>{s.onload=()=>{let a=s.height/s.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),r.fillStyle="rgb(240, 240, 240)",r.fillRect(0,0,t.width,t.height),r.drawImage(s,0,0,t.width,t.height),t.toBlob(h=>{if(!h){l();return}let c=URL.createObjectURL(h);o(c)})},s.onerror=a=>{l(a)}});return s.src=URL.createObjectURL(e),n}var k=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),Z=class extends x{constructor(){super();u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",z(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",z(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:k.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===T.activities.DETAILS)?this.$["*currentActivity"]=T.activities.DETAILS:this.$["*currentActivity"]=T.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let r=this.getOutputData(s=>s.getValue("uuid")===t);O.emit(new M({type:I.REMOVE,ctx:this.ctxName,data:r}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[r]=t;this._isIntersecting=r.isIntersecting,r.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),r.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,r=k.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?r=k.FAILED:t.getValue("validationMultipleLimitMsg")?r=k.LIMIT_OVERFLOW:t.getValue("isUploading")?r=k.UPLOADING:t.getValue("fileInfo")&&(r=k.FINISHED),this.$.state=r}async _generateThumbnail(){var r;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let s=this.cfg.thumbSize,n=this.proxyUrl(Jt(Ei(this.cfg.cdnCname,this._entry.getValue("uuid")),Yt(t.getValue("cdnUrlModifiers"),`scale_crop/${s}x${s}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((r=t.getValue("file"))!=null&&r.type.includes("image"))try{let s=await Ii(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",s)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",De(n))}else{let s=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",De(s))}}_subEntry(t,r){let s=this._entry.subscribe(t,n=>{this.isConnected&&r(n)});this._entrySubs.add(s)}_handleEntryId(t){var s;this._reset();let r=(s=this.uploadCollection)==null?void 0:s.read(t);this._entry=r,r&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||r.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=r.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{Z.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),Z.activeInstances.add(this)}_handleState(t){var r,s,n;this.set$({isFailed:t===k.FAILED,isLimitOverflow:t===k.LIMIT_OVERFLOW,isUploading:t===k.UPLOADING,isFinished:t===k.FINISHED,progressVisible:t===k.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((r=this._entry)==null?void 0:r.getValue("isImage"))&&((s=this._entry)==null?void 0:s.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===k.FAILED||t===k.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===k.FINISHED&&(this.$.badgeIcon="badge-success"),t===k.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),Z.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let r=this.cfg.multiple?this.cfg.multipleMax:1;if(r&&this.uploadCollection.size>r)return;let s=this.getOutputData(a=>!a.getValue("fileInfo"));O.emit(new M({type:I.UPLOAD_START,ctx:this.ctxName,data:s})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let h=async()=>{let d=await this.getUploadClientOptions();return xe(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let m=f.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!f.isComputable},signal:a.signal})},c=await this.$["*uploadQueue"].add(h);t.setMultipleValues({fileInfo:c,isUploading:!1,fileName:c.originalFilename,fileSize:c.size,isImage:c.isImage,mimeType:(l=(o=(n=c.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:c.mimeType,uuid:c.uuid,cdnUrl:c.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof R?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};Z.template=`
{{itemName}}{{errorText}}
`;Z.activeInstances=new Set;var Rt=class extends S{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let r=this.getCssData(`--icon-${t}`);r&&(this.$.path=r)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};Rt.template=``;Rt.bindAttributes({name:"name",size:"size"});var re=class extends S{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};re.template='
';var se=class extends S{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};u(se,"template",`Powered by Uploadcare`);var Et=class extends x{constructor(){super(...arguments);u(this,"processInnerHtml",!0);u(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Et.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let r=t.groupData?[t.groupData.cdnUrl]:t.map(s=>s.cdnUrl);for(let s of r){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=s,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=r.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let r=t.map(o=>o.uuid),s=await this.getUploadClientOptions(),n=await ui(r,{...s});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};Et.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var B={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};var il=Re("format/auto","progressive/yes");var $e=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),Ui=[$e.CROP,$e.TUNING,$e.FILTERS];var nl=Object.freeze({brightness:{zero:B.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:B.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:B.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:B.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:B.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:B.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:B.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:B.enhance,range:[0,100],keypointsNumber:1},filter:{zero:B.filter,range:[0,100],keypointsNumber:1}});var hs="https://ucarecdn.com",ds="https://upload.uploadcare.com",fs="https://social.uploadcare.com",Lt={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:It(Ui),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:hs,baseUrl:ds,socialBaseUrl:fs,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var ne=Object.keys(Lt),ps=["metadata"],ms=e=>ps.includes(e),Fe=ne.filter(e=>!ms(e)),_s={...Object.fromEntries(Fe.map(e=>[nt(e),e])),...Object.fromEntries(Fe.map(e=>[e.toLowerCase(),e]))},gs={...Object.fromEntries(ne.map(e=>[nt(e),j(e)])),...Object.fromEntries(ne.map(e=>[e.toLowerCase(),j(e)]))},oe=class extends S{constructor(){super();u(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Lt).map(([t,r])=>[j(t),r]))}}initCallback(){super.initCallback();for(let t of ne){let r=this,s="__"+t;r[s]=r[t],Object.defineProperty(this,t,{set:n=>{if(r[s]=n,Fe.includes(t)){let o=[...new Set([nt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[j(t)]!==n&&(typeof n=="undefined"||n===null?this.$[j(t)]=Lt[t]:this.$[j(t)]=n)},get:()=>this.$[j(t)]}),typeof r[t]!="undefined"&&r[t]!==null&&(r[t]=r[s])}}attributeChangedCallback(t,r,s){if(r===s)return;let n=_s[t],o=xi(n,s),l=o!=null?o:Lt[n],a=this;a[n]=l}};oe.bindAttributes(gs);var Ve=class extends x{};export{oe as Config,se as Copyright,Et as DataOutput,Ut as DropArea,Z as FileItem,Kt as FileUploaderMinimal,Rt as Icon,ee as MessageBox,re as ProgressBar,Ue as StartFrom,Ve as UploadCtxProvider,ie as UploadList,Pi as registerBlocks}; \ No newline at end of file diff --git a/web/lr-file-uploader-regular.min.js b/web/lr-file-uploader-regular.min.js index 85e2655ff..56734b0a1 100644 --- a/web/lr-file-uploader-regular.min.js +++ b/web/lr-file-uploader-regular.min.js @@ -24,4 +24,4 @@ * */ var Br=Object.defineProperty;var Vr=(s,i,t)=>i in s?Br(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(Vr(s,typeof i!="symbol"?i+"":i,t),t),Ai=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var B=(s,i,t)=>(Ai(s,i,"read from private field"),t?t.call(s):i.get(s)),Ot=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},se=(s,i,t,e)=>(Ai(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var Oe=(s,i,t)=>(Ai(s,i,"access private method"),t);var zr=Object.defineProperty,jr=(s,i,t)=>i in s?zr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,Si=(s,i,t)=>(jr(s,typeof i!="symbol"?i+"":i,t),t);function Hr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=Hr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var C=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"}),ps="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Wr=ps.length-1,ne=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Gr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function qr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||us;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=us;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).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 Kr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function Yr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Xr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):fs(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var Le="{{",re="}}",Zr="skip-text";function Jr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(Zr))&&r.textContent.includes(Le)&&r.textContent.includes(re)&&1}});for(;i=e.nextNode();)t.push(i);return t}var Qr=function(s,i){Jr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(re);)e.textContent.startsWith(Le)?(n=e.textContent.indexOf(re)+re.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(Le),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(Le,"").replace(re,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},tn=[Gr,qr,Kr,Yr,Qr],Ue="'",Vt='"',en=/\\([0-9a-fA-F]{1,6} ?)/g;function sn(s){return(s[0]===Vt||s[0]===Ue)&&(s[s.length-1]===Vt||s[s.length-1]===Ue)}function rn(s){return(s[0]===Vt||s[0]===Ue)&&(s=s.slice(1)),(s[s.length-1]===Vt||s[s.length-1]===Ue)&&(s=s.slice(0,-1)),s}function nn(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=nn(i),i=Vt+i+Vt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Bt=null,pt=null,vt=class extends HTMLElement{constructor(){super(),Si(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return vt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ne.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=vt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=vt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=vt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=vt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=vt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=vt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])fs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of tn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);pt==null||pt.delete(this.updateCssData),pt!=null&&pt.size||(Bt==null||Bt.disconnect(),Bt=null,pt=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${C.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=on(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){pt||(pt=new Set),pt.add(this.updateCssData),Bt||(Bt=new MutationObserver(s=>{s[0].type==="attributes"&&pt.forEach(i=>{i()})}),Bt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=vt;Si(zt,"template");var $i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent($i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),$i.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};$i.appMap=Object.create(null);function ln(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function an(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function oe(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&an(i,s.attributes),s.styles&&ln(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=oe(t);i.appendChild(e)}),i}var ms="idb-store-ready",cn="symbiote-db",hn="symbiote-idb-update_",un=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return hn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=cn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new un(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Si(gs,"_reg",Object.create(null));function S(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var dn="--uploadcare-blocks-window-height",Re="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ki(){return typeof window[Re]=="undefined"?!1:!!window[Re]}function _s(){if(ki())return;let s=()=>{document.documentElement.style.setProperty(dn,`${window.innerHeight}px`),window[Re]=!0},i=S(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[Re]=!1,window.removeEventListener("resize",i)}}var pn=s=>s,Ii="{{",ys="}}",bs="plural:";function le(s,i,t={}){var o;let{openToken:e=Ii,closeToken:r=ys,transform:n=pn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(Ii);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ii,e)}return i}function Cs(s){return Object.prototype.toString.call(s)==="[object Object]"}var fn=/\W|_/g;function mn(s){return s.split(fn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ws(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>mt(t,{ignoreKeys:i})):s}function mt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ws(s,{ignoreKeys:i});if(!Cs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Cs(r)?r=mt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ws(r,{ignoreKeys:i})),t[mn(e)]=r}return t}var gn=s=>new Promise(i=>setTimeout(i,s));function Ni({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var _n={factor:2,time:100};function bn(s,i=_n){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>gn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Gt=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Gt.prototype),this.originalProgressEvent=t}},Ne=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Ct=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,Ct.prototype)}},yn=500,xs=({check:s,interval:i=yn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Ne(e,()=>{o&&clearTimeout(o),n(new Ct("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ct("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),x={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},De="application/octet-stream",Es="original",Tt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Ne(r,()=>{u=!0,a.abort(),l(new Ct)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let A=$.split(": "),T=A.shift(),w=A.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new Gt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function vn(s,...i){return s}var Cn=({name:s})=>s?[s]:[],wn=vn,Tn=()=>new FormData,As=s=>!1,Fe=s=>typeof Blob!="undefined"&&s instanceof Blob,Be=s=>typeof File!="undefined"&&s instanceof File,Ve=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",ae=s=>Fe(s)||Be(s)||As()||Ve(s),xn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",En=s=>!!s&&typeof s=="object"&&!Array.isArray(s),An=s=>!!s&&typeof s=="object"&&"data"in s&&ae(s.data);function $n(s,i,t){if(An(t)){let{name:e,contentType:r}=t,n=wn(t.data,e,r!=null?r:De),o=Cn({name:e,contentType:r});s.push([i,n,...o])}else if(En(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else xn(t)&&t&&s.push([i,t.toString()])}function Sn(s){let i=[];for(let[t,e]of Object.entries(s))$n(i,t,e);return i}function Di(s){let i=Tn(),t=Sn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var M=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,M.prototype)}},kn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=kn(t)),e.toString()},In="6.6.1",On="UploadcareUploadClient",Ln=In;function Rt(s){return Ni({libraryName:On,libraryVersion:Ln,...s})}var Un="RequestThrottledError",Ts=15e3,Rn=1e3;function Pn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return Ts;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Ts}function xt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return bn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Un&&r{let i="";return(Fe(s)||Be(s)||Ve(s))&&(i=s.type),i||De},Ss=s=>{let i="";return Be(s)&&s.name?i=s.name:Fe(s)||As()?i="":Ve(s)&&s.name&&(i=s.name),i||Es};function Fi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Mn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=x.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({file:{data:s,name:t||Ss(s),contentType:e||$s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Fi(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Ui;(function(s){s.Token="token",s.FileInfo="file_info"})(Ui||(Ui={}));function Nn(s,{publicKey:i,baseURL:t=x.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Fi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var X;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(X||(X={}));var Dn=s=>"status"in s&&s.status===X.Error;function Fn(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=x.retryNetworkErrorMaxTimes}={}){return xt(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Rt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=mt(JSON.parse(a));if("error"in d&&!Dn(d))throw new M(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Bn(s,{publicKey:i,baseURL:t=x.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:a,userAgent:c})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=mt(JSON.parse(p));if("error"in _)throw new M(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Vn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=x.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({filename:e||Es,size:s,content_type:t||De,part_size:r,UPLOADCARE_STORE:Fi(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w.parts=Object.keys(w.parts).map(H=>w.parts[H]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function zn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||De}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function jn(s,{publicKey:i,baseURL:t=x.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},data:Di({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Bi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return xs({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}var wt=class{constructor(i,{baseCDN:t=x.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=ft(t,`${r}/`),l=n?ft(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},Hn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:$})=>Mn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:A})=>Bi({file:A,publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new wt(A,{baseCDN:_})),Wn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Xn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Ne(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Gn=window.WebSocket,Ri=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},qn=(s,i)=>s==="success"?{status:X.Success,...i}:s==="progress"?{status:X.Progress,...i}:{status:X.Error,...i},Pi=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ri);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Gn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,qn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Oi=null,Vi=s=>{if(!Oi){let i=typeof window=="undefined"?0:3e4;Oi=new Pi(s,i)}return Oi},Kn=s=>{Vi(s).connect()};function Yn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return xs({check:c=>Fn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case X.Error:return new M(u.error,u.errorCode);case X.Waiting:return!1;case X.Unknown:return new M(`Token "${s}" was not found.`);case X.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case X.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Zn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Vi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Ne(t,()=>{a(),n(new Ct("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case X.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case X.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case X.Error:a(),n(new M(c.msg,c.error_code))}})}),Jn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:$=x.pusherKey,metadata:A})=>Promise.resolve(Kn($)).then(()=>Nn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(T=>{let w=Vi($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===Ui.FileInfo?T:Xn([({signal:w})=>Yn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:w}),({signal:w})=>Zn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof M)throw T;return T}).then(T=>Bi({file:T.uuid,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(T=>new wt(T,{baseCDN:r})),Li=new WeakMap,Qn=async s=>{if(Li.has(s))return Li.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Li.set(s,i),i},Is=async s=>{if(Be(s)||Fe(s))return s.size;if(Ve(s))return(await Qn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},to=(s,i=x.multipartMinFileSize)=>s>=i,Os=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!ae(s)&&t.test(s)},Ls=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!ae(s)&&t.test(s)},eo=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},so=async(s,i,t)=>e=>io(s,e,i,t),ro=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>zn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),no=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:$=x.multipartChunkSize,maxConcurrentRequests:A=x.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let H=e!=null?e:await Is(s),ht,It=(P,J)=>{if(!c)return;ht||(ht=Array(P).fill(0));let ut=W=>W.reduce((dt,Ei)=>dt+Ei,0);return W=>{W.isComputable&&(ht[J]=W.value,c({isComputable:!0,value:ut(ht)/P}))}};return _||(_=$s(s)),Vn(H,{publicKey:i,contentType:_,fileName:t||Ss(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:P,parts:J})=>{let ut=await so(s,H,$);return Promise.all([P,eo(A,J.map((W,dt)=>()=>ro(ut(dt),W,{publicKey:i,contentType:_,onProgress:It(J.length,dt),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([P])=>jn(P,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(P=>P.isReady?P:Bi({file:P.uuid,publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(P=>new wt(P,{baseCDN:T}))};async function zi(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:$,maxConcurrentRequests:A,baseCDN:T=x.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,pusherKey:ht,metadata:It}){if(ae(s)){let P=await Is(s);return to(P,_)?no(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:P,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It}):Hn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It})}if(Ls(s))return Jn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:ht,metadata:It});if(Os(s))return Wn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var Mi=class{constructor(i,t){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},oo=s=>{for(let i of s)if(!ae(i))return!1;return!0},lo=s=>{for(let i of s)if(!Os(i))return!1;return!0},ao=s=>{for(let i of s)if(!Ls(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=x.multipartChunkSize,baseCDN:$=x.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!oo(s)&&!ao(s)&&!lo(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let H,ht=!0,It=s.length,P=(J,ut)=>{if(!a)return;H||(H=Array(J).fill(0));let W=dt=>dt.reduce((Ei,Fr)=>Ei+Fr)/J;return dt=>{if(!dt.isComputable||!ht){ht=!1,a({isComputable:!1});return}H[ut]=dt.value,a({isComputable:!0,value:W(H)})}};return Promise.all(s.map((J,ut)=>zi(J,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:P(It,ut),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:$,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T}))).then(J=>{let ut=J.map(W=>W.uuid);return Bn(ut,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(W=>new Mi(W,J)).then(W=>(a&&a({isComputable:!0,value:1}),W))})}var Lt,jt,Ut,Ht,Wt,Xt,Pe,Me=class{constructor(i){Ot(this,Xt);Ot(this,Lt,1);Ot(this,jt,[]);Ot(this,Ut,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);se(this,Lt,i)}add(i){return new Promise((t,e)=>{B(this,Ht).set(i,t),B(this,Wt).set(i,e),B(this,jt).push(i),Oe(this,Xt,Pe).call(this)})}get pending(){return B(this,jt).length}get running(){return B(this,Ut)}set concurrency(i){se(this,Lt,i),Oe(this,Xt,Pe).call(this)}get concurrency(){return B(this,Lt)}};Lt=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,Pe=function(){let i=B(this,Lt)-B(this,Ut);for(let t=0;t{B(this,Ht).delete(e),B(this,Wt).delete(e),se(this,Ut,B(this,Ut)-1),Oe(this,Xt,Pe).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var ji=()=>({"*blocksRegistry":new Set}),Hi=s=>({...ji(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),ze=s=>({...Hi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Me(1)});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var Q=s=>`*cfg/${s}`;var gt=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ps=new Set;function je(s){Ps.has(s)||(Ps.add(s),console.warn(s))}var He=(s,i)=>new Intl.PluralRules(s).select(i);var Wi="lr-",b=class extends zt{constructor(){super();h(this,"allowCustomTemplate",!0);h(this,"init$",ji());h(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return le(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=He(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Wi}${t}`,!0),ki()||(this._destroyInnerHeightTracker=_s()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?le(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=Q(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(je("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${gt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(Q(t));r.ctx.has(r.name)?this.sub(Q(t),e):(this.bindCssData(`--cfg-${gt(t)}`),this.sub(`--cfg-${gt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Wi)?t:Wi+t)}};h(b,"StateConsumerScope",null),h(b,"className","");var ce=class extends b{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}};h(ce,"StateConsumerScope","modal");ce.template=``;var Ms="active",he="___ACTIVITY_IS_ACTIVE___",st=class extends b{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Hi(this));h(this,"_debouncedHistoryFlush",S(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=st._activityRegistry[this.activityKey];this[he]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=st._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[he]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[he]?this._deactivate():this.activityType===t&&!this[he]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!st._activityRegistry[this.activityKey]}get isActivityActive(){return this[he]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;st._activityRegistry||(st._activityRegistry=Object.create(null)),st._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),st._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(st._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setOrAddState("*modalActive",!1)}}},g=st;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ue=33.333333333333336,y=1,Xi=24,Ns=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function tt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Bs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Vs({rect:s,delta:[i,t],imageBox:e}){return Kt({...s,x:s.x+i,y:s.y+t},e)}function Kt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function co({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Yt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Zt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Et(s,i,t){return Math.min(Math.max(s,i),t)}var Xe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var et=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs="blocks",Gs="0.27.1";function qs(s){return Ni({...s,libraryName:Xs,libraryVersion:Gs})}var Ks=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Ge=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ks(i)).join("/-/"),O=(...s)=>{let i=Ge(...s);return i?`-/${i}/`:""};function Ys(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Js(s){let i=Qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ks(n))}function Qs(s){let i=new URL(s),t=Ys(s),e=tr(t)?er(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function tr(s){return s.startsWith("http")}function er(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var I=(s,i,t)=>{let e=new URL(Qs(s));if(t=t||Ys(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),tr(t)){let r=er(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var de=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Gi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],qi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ir=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),pe=s=>{let i=s==null?void 0:s.type;return i?qi(i,de):!1};var nt=1e3,Mt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),fe=s=>Math.ceil(s*100)/100,sr=(s,i=Mt.AUTO)=>{let t=i===Mt.AUTO;if(i===Mt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};h(L,"_timeoutStore",Object.create(null));var rr="[Typed State] Wrong property name: ",bo="[Typed State] Wrong property type: ",qe=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||ne.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(bo+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Ke=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||ne.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new qe(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var nr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var or=s=>s?s.split(",").map(i=>i.trim()):[],Nt=s=>s?s.join(","):"";var v=class extends g{constructor(){super(...arguments);h(this,"couldBeUploadCollectionOwner",!1);h(this,"isUploadCollectionOwner",!1);h(this,"init$",ze(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",S(this._runValidators.bind(this),100));h(this,"_handleCollectionUpdate",t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,L.emit(new V({type:U.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&L.emit(new V({type:U.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{L.emit(new V({type:U.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{L.emit(new V({type:U.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{L.emit(new V({type:U.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){je("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Ke({typedSchema:nr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromObject(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:pe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:pe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Nt(Gi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?de:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Nt(de)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:et.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);L.emit(new V({type:U.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),L.emit(new V({type:U.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Gi([...e?de:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=qi(o,n),c=ir(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:sr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Xe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=O(`crop/${u.width}x${u.height}/${u.x},${u.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:I(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:qs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};e.push(a)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(U).forEach(s=>{let i=L.eName(s),t=S(e=>{if([U.UPLOAD_FINISH,U.REMOVE,U.CDN_MODIFICATION].includes(e.detail.type)){let n=E.getCtx(e.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let c=E.getCtx(a).store,u=c.fileInfo;if(u){let d={...u,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||u.cdnUrl};l.push(d)}}),L.emit(new V({type:U.DATA_OUTPUT,ctx:e.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var Y={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function yo(s,i){if(typeof i=="number")return Y[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Y[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Y[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var ar=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return Ge(...ar.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yo(i,t)}).filter(i=>!!i))}var Ye=Ge("format/auto","progressive/yes"),_t=([s])=>typeof s!="undefined"?Number(s):void 0,lr=()=>!0,vo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Co=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),wo={enhance:_t,brightness:_t,exposure:_t,gamma:_t,contrast:_t,saturation:_t,vibrance:_t,warmth:_t,filter:vo,mirror:lr,flip:lr,rotate:_t,crop:Co};function cr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!ar.includes(e))continue;let n=wo[e],o=n(r);i[e]=o}return i}var D=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),G=[D.CROP,D.TUNING,D.FILTERS],hr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],ur=["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"],dr=["rotate","mirror","flip"],ot=Object.freeze({brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}});var To="https://ucarecdn.com",xo="https://upload.uploadcare.com",Eo="https://social.uploadcare.com",me={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Nt(G),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:To,baseUrl:xo,socialBaseUrl:Eo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var q=s=>String(s),lt=s=>Number(s),k=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,Ao=s=>s==="auto"?s:k(s),$o={pubkey:q,multiple:k,multipleMin:lt,multipleMax:lt,confirmUpload:k,imgOnly:k,accept:q,externalSourcesPreferredTypes:q,store:Ao,cameraMirror:k,sourceList:q,maxLocalFileSizeBytes:lt,thumbSize:lt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:q,removeCopyright:k,cropPreset:q,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:q,cdnCname:q,baseUrl:q,socialBaseUrl:q,secureSignature:q,secureExpire:q,secureDeliveryProxy:q,retryThrottledRequestMaxTimes:lt,multipartMinFileSize:lt,multipartChunkSize:lt,maxConcurrentRequests:lt,multipartMaxConcurrentRequests:lt,multipartMaxAttempts:lt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:q},pr=(s,i)=>{if(!(typeof i=="undefined"||i===null))return $o[s](i)};var Ze=Object.keys(me),So=["metadata"],ko=s=>So.includes(s),Ki=Ze.filter(s=>!ko(s)),Io={...Object.fromEntries(Ki.map(s=>[gt(s),s])),...Object.fromEntries(Ki.map(s=>[s.toLowerCase(),s]))},Oo={...Object.fromEntries(Ze.map(s=>[gt(s),Q(s)])),...Object.fromEntries(Ze.map(s=>[s.toLowerCase(),Q(s)]))},Je=class extends b{constructor(){super();h(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(me).map(([t,e])=>[Q(t),e]))}}initCallback(){super.initCallback();for(let t of Ze){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,Ki.includes(t)){let o=[...new Set([gt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[Q(t)]!==n&&(typeof n=="undefined"||n===null?this.$[Q(t)]=me[t]:this.$[Q(t)]=n)},get:()=>this.$[Q(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Io[t],o=pr(n,r),l=o!=null?o:me[n],a=this;a[n]=l}};Je.bindAttributes(Oo);var ge=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ge.template=``;ge.bindAttributes({name:"name",size:"size"});var Lo="https://ucarecdn.com",Dt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Lo},"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 fr=s=>[...new Set(s)];var _e="--lr-img-",mr="unresolved",Jt=2,Qt=3,gr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),br=Object.create(null),_r;for(let s in Dt)br[_e+s]=((_r=Dt[s])==null?void 0:_r.default)||"";var Qe=class extends zt{constructor(){super(...arguments);h(this,"cssInit$",br)}$$(t){return this.$[_e+t]}set$$(t){for(let e in t)this.$[_e+e]=t[e]}sub$$(t,e){this.sub(_e+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!gr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return O(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Dt.format.default}`,`quality/${this.$$("quality")||Dt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(gr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return I(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(I(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(I(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?le(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(mr,""),this.img.onload=()=>{this.img.removeAttribute(mr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Dt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?fr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Jt+"x")}") ${n*Jt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Qt+"x")}") ${n*Qt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Jt))}") ${Jt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Qt))}") ${Qt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Jt+"x")+` ${e*Jt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Qt+"x")+` ${e*Qt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):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(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),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)}static get observedAttributes(){return Object.keys(Dt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[_e+t]=r})}};var Yi=class extends Qe{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var be=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",i=>{typeof i!="undefined"&&(this.$.withDropZone=k(i))}),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};be.template=``;be.bindAttributes({dropzone:null});var Zi=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function Uo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function Ro(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push(c),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function yr(s){let i=[],t=[];for(let e=0;e{i.push(...a)}));continue}let o=r.getAsFile();t.push(Uo(o).then(l=>{l||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},vr=["focus"],Po=100,Ji=new Map;function Mo(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Qi(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=z.INACTIVE,o=f=>{s.shouldIgnore()&&f!==z.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(z.INACTIVE)},c=()=>{i+=1,n===z.INACTIVE&&o(z.ACTIVE)},u=()=>{i-=1,l()||o(z.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(z.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let _=[f.x,f.y],$=s.element.getBoundingClientRect(),A=Math.floor(Mo(_,$)),T=A{if(s.shouldIgnore())return;f.preventDefault();let _=await yr(f.dataTransfer);s.onItems(_),o(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),vr.forEach(f=>{window.addEventListener(f,a)}),()=>{Ji.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),vr.forEach(f=>{window.removeEventListener(f,a)})}}var ye=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return e&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!k(e)})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:k(e)})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:k(e)})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:k(e)})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Qi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:et.DROP_AREA});return}this.addFileFromObject(r,{source:et.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Qi({element:t,onChange:e=>{var n;let r=(n=Object.entries(z).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var n;let r=(n=Object.entries(z).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=N(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,n;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ye.template=`
{{text}}
`;ye.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var No="src-type-",ve=class extends v{constructor(){super(...arguments);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${No}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ve.template=`
`;ve.bindAttributes({type:null});var ts=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function Cr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function wr(s="#fff",i="rgba(0, 0, 0, .1)"){return Cr(``)}function Ce(s="hsl(209, 21%, 65%)",i=32,t=32){return Cr(``)}function Tr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var j=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),bt=class extends v{constructor(){super();h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",S(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",S(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:j.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=j.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=j.FAILED:t.getValue("validationMultipleLimitMsg")?e=j.LIMIT_OVERFLOW:t.getValue("isUploading")?e=j.UPLOADING:t.getValue("fileInfo")&&(e=j.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(I(At(this.cfg.cdnCname,this._entry.getValue("uuid")),O(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Tr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{bt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),bt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===j.FAILED,isLimitOverflow:t===j.LIMIT_OVERFLOW,isUploading:t===j.UPLOADING,isFinished:t===j.FINISHED,progressVisible:t===j.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===j.FAILED||t===j.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===j.FINISHED&&(this.$.badgeIcon="badge-success"),t===j.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),bt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));L.emit(new V({type:U.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=await this.getUploadClientOptions();return zi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof M?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};bt.template=`
{{itemName}}{{errorText}}
`;bt.activeInstances=new Set;var ti=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},ei=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};ei.template=`
{{captionTxt}}
{{msgTxt}}
`;var ii=class extends v{constructor(){super();h(this,"couldBeUploadCollectionOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",S(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new ti,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};ii.template=`{{headerText}}
`;var si=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:et.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};si.template=`
`;var es=()=>typeof navigator.permissions!="undefined";var ri=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:es(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{es()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",S(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:et.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ri.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var is=class extends v{};var ni=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=Ce(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=pe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=I(n,O("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ni.template=`
{{fileSize}}
{{errorTxt}}
`;var ss=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},oi=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ss);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};oi.template=`{{activityCaption}}
{{messageTxt}}
`;var li=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};li.template=``;var ai=class extends b{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ai.template='
';var Z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var we=class extends b{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:Z})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${wr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Z}};we.template='';we.bindAttributes({checkerboard:"checkerboard"});var xr="--cfg-ctx-name",R=class extends b{get cfgCssCtxName(){return this.getCssData(xr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(xr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function Er(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function F(...s){let i=Er(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function Ar(s,...i){let t=Er(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var $r=s=>{if(!s)return G;let i=or(s).filter(t=>G.includes(t));return i.length===0?G:i};function Sr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":G,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Z,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Nt(G),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Z,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=O($t(i)),r=I(t,O(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var kr=`
Network error
{{fileType}}
{{msg}}
`;var at=class extends R{constructor(){super();h(this,"_debouncedShowLoader",S(this._showLoader.bind(this),300));this.init$={...this.init$,...Sr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===D.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Zs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Js(this.$.cdnUrl),r=cr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=I(this.$["*originalUrl"],O("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===D.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Z&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Z)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Xe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=$r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=F("image",{image_hidden_to_cropper:t===D.CROP,image_hidden_effects:t!==D.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=O($t(t)),n=I(e,O(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(at,"className","cloud-image-editor");at.template=kr;at.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ci=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=tt("mask",{id:"backdrop-mask"}),a=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=tt("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Pt(n,f)}else{let f=Et(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:$}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(Xi*Et(Math.min(d,p)/Xi/3,0,1),Ns);Pt(n,{x:$[0]-A,y:$[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",F("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=tt("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=tt("rect",{fill:"transparent"}),l=tt("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=tt("svg"),t=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=tt("line",{x1:`${ue*e}%`,y1:"0%",x2:`${ue*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=tt("line",{x1:"0%",y1:`${ue*e}%`,x2:"100%",y2:`${ue*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Vs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Kt(Zt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Bs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",F("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",F({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ci.template='';var yt=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=F({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function Fo(s){let i=s+90;return i=i>=360?0:i,i}function Bo(s,i){return s==="rotate"?Fo(i):["mirror","flip"].includes(s)?!i:null}var Te=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Bo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var xe={FILTER:"filter",COLOR_OPERATION:"color_operation"},ct="original",hi=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?xe.FILTER:xe.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ct?void 0:this.$.value,filter:this._filter===ct?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ot[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===xe.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===xe.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===xe.FILTER?this._filter===ct?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};hi.template=``;function Ee(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=Z)}}}function Ae(s){let i=[];for(let n of s){let o=Ee(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var te=class extends yt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ct?{name:this._filter,amount:o}:void 0,I(this._originalUrl,O(Ye,$t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=Ee(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{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",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ct,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};te.template=`
`;var $e=class extends yt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ot[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Ir=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function Or(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function ee(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return I(s,O(Ye,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Vo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ui=class extends R{constructor(){super(),this.init$={...this.init$,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=S(this._commit.bind(this),300),this._handleResizeThrottled=Ir(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Or(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=Yt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Zt(l)}_alignCrop(){var c;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[u,d],coords:[p,m]}=n,{width:f}=Yt(this._imageSize,r),_=o/f;i=Kt(Zt({x:l+p*_,y:a+m*_,width:u*_,height:d*_}),this.$["*imageBox"])}if(!n||!Hs(i,t)){let u=(c=this.$["*cropPresetList"])==null?void 0:c[0],d=u?u.width/u.height:void 0,p=t.width/t.height,m=t.width,f=t.height;d&&(p>d?m=Math.min(t.height*d,t.width):f=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Kt(Zt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=Yt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=F({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=Yt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[Et(Math.round(c/d),1,l),Et(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=Yt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),$={dimensions:_,coords:[Et(Math.round((d-l)/m),0,c-_[0]),Et(Math.round((p-a)/f),0,u-_[1])]};if(!Vo($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(_[0]===c&&_[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=F({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(ee(i,e,t)),{promise:n,cancel:o,image:l}=Ee(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ui.template=``;function rs(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function zo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Ho(s,i){return s.map((t,e)=>tn-o)}var ns=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=S(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(ee(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ot[i],r=this._keypoints.map(l=>l.value),n=jo(r,t,e),o=Ho(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Ae(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Lr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=Ae(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Lr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=F({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Wo=1,di=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Wo?this.scrollLeft+=e:this.scrollLeft+=t})}};di.template=" ";function Xo(s){return``}function Go(s){return`
`}var pi=class extends R{constructor(){super();h(this,"_updateInfoTooltip",S(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===D.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(ct);else if(this.$["*tabId"]===D.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||ot[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ct,"*currentOperation":null,"*tabId":D.CROP,showLoader:!1,filters:ur,colorOperations:hr,cropOperations:dr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=S(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===D.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new $e;return e.operation=t,e}_createFilterControl(t){let e=new te;return e.filter=t,e}_createToggleControl(t){let e=new Te;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===D.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===D.FILTERS?[ct,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===D.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===D.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of G){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ee(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Ae([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1,this.$["*tabId"]=t[0];for(let e of G){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}}),this._updateInfoTooltip()}};pi.template=`
{{*operationTooltip}}
${G.map(Go).join("")}
${G.map(Xo).join("")}
`;var Se=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return F("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Se.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Se.template=`
{{text}}
`;var fi=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};fi.template=`
`;var mi={transition:"transition",visible:"visible",hidden:"hidden"},gi=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=mi.visible,this._hiddenStyle=mi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Ar(this,{[mi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(mi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};gi.template=" ";var _i=class extends b{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);h(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new at,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var qo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Ur=function(s,i="i"){let t=s.split("*").map(qo);return new RegExp("^"+t.join(".+")+"$",i)};var Ko=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Rr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Ko({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var St={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in St){let t=St[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Pr=function(s,i,t){s in St||(St[s]=[]),St[s].push([i,t])},Mr=function(s,i){s in St&&(St[s]=St[s].filter(t=>t[0]!==i))};function Nr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var bi=class extends v{constructor(){super();h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Ur(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Rr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Nr(n),o.toString()}mountIframe(){let t=oe({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Pr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Mr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};bi.template=`
{{activityCaption}}
{{counter}}
`;var ke=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=oe({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ke.bindAttributes({"tab-list":null,default:null});ke.template=`
`;var ie=class extends v{constructor(){super(...arguments);h(this,"processInnerHtml",!0);h(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return ie.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Us(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};ie.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ls=class extends g{};var yi=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};yi.template=``;var K={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Dr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},it=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:K.PLAY,fsIcon:K.FS_ON,volIcon:K.VOL_ON,capIcon:K.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Dr.exitFullscreen():Dr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===K.CAP_OFF?(this.$.capIcon=K.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(it.is+":captions","1")):(this.$.capIcon=K.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(it.is+":captions"))}toggleSound(){this.$.volIcon===K.VOL_ON?(this.$.volIcon=K.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=K.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(it.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(it.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=K.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=K.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=K.FS_OFF:this.$.fsIcon=K.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(it.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};it.template=`
{{currentTime}} / {{totalTime}}
`;it.bindAttributes({video:"video",src:"src"});var Yo="css-src";function vi(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Yo);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Ie=class extends vi(b){};var Ci=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(Ci,"template",`Powered by Uploadcare`);var kt=class extends Ie{constructor(){super(...arguments);h(this,"init$",ze(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var wi=class extends kt{};wi.template=``;var Ti=class extends kt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};Ti.template=``;var xi=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};xi.template=``;var as=class extends vi(at){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Zo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,zt as BaseComponent,b as Block,ri as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,at as CloudImageEditorBlock,Je as Config,oi as ConfirmationDialog,Ci as Copyright,ci as CropFrame,E as Data,ie as DataOutput,ye as DropArea,Te as EditorCropButtonControl,te as EditorFilterControl,ui as EditorImageCropper,ns as EditorImageFader,$e as EditorOperationControl,di as EditorScroller,hi as EditorSlider,pi as EditorToolbar,bi as ExternalSource,bt as FileItem,we as FilePreview,xi as FileUploaderInline,Ti as FileUploaderMinimal,wi as FileUploaderRegular,ge as Icon,Yi as Img,fi as LineLoaderUi,Se as LrBtnUi,ei as MessageBox,ce as Modal,Xs as PACKAGE_NAME,Gs as PACKAGE_VERSION,gi as PresenceToggle,ai as ProgressBar,li as ProgressBarCommon,yi as Select,Ie as ShadowWrapper,be as SimpleBtn,_i as SliderUi,ve as SourceBtn,ts as SourceList,Zi as StartFrom,ke as Tabs,is as UploadCtxProvider,ni as UploadDetails,ii as UploadList,v as UploaderBlock,si as UrlSource,it as Video,Zo as connectBlocksFrom,cs as registerBlocks,vi as shadowed,gt as toKebabCase}; \ No newline at end of file +`,"\\n"),i=nn(i),i=Vt+i+Vt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Bt=null,pt=null,vt=class extends HTMLElement{constructor(){super(),Si(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return vt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ne.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=vt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=vt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=vt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=vt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=vt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=vt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])fs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of tn)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);pt==null||pt.delete(this.updateCssData),pt!=null&&pt.size||(Bt==null||Bt.disconnect(),Bt=null,pt=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${C.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=on(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){pt||(pt=new Set),pt.add(this.updateCssData),Bt||(Bt=new MutationObserver(s=>{s[0].type==="attributes"&&pt.forEach(i=>{i()})}),Bt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=vt;Si(zt,"template");var $i=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent($i.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),$i.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};$i.appMap=Object.create(null);function ln(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function an(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function oe(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&an(i,s.attributes),s.styles&&ln(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=oe(t);i.appendChild(e)}),i}var ms="idb-store-ready",cn="symbiote-db",hn="symbiote-idb-update_",un=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return hn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=cn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new un(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Si(gs,"_reg",Object.create(null));function S(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var dn="--uploadcare-blocks-window-height",Re="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ki(){return typeof window[Re]=="undefined"?!1:!!window[Re]}function _s(){if(ki())return;let s=()=>{document.documentElement.style.setProperty(dn,`${window.innerHeight}px`),window[Re]=!0},i=S(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[Re]=!1,window.removeEventListener("resize",i)}}var pn=s=>s,Ii="{{",ys="}}",bs="plural:";function le(s,i,t={}){var o;let{openToken:e=Ii,closeToken:r=ys,transform:n=pn}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(Ii);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(Ii,e)}return i}function Cs(s){return Object.prototype.toString.call(s)==="[object Object]"}var fn=/\W|_/g;function mn(s){return s.split(fn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ws(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>mt(t,{ignoreKeys:i})):s}function mt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ws(s,{ignoreKeys:i});if(!Cs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Cs(r)?r=mt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ws(r,{ignoreKeys:i})),t[mn(e)]=r}return t}var gn=s=>new Promise(i=>setTimeout(i,s));function Ni({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var _n={factor:2,time:100};function bn(s,i=_n){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>gn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var Gt=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Gt.prototype),this.originalProgressEvent=t}},Ne=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Ct=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,Ct.prototype)}},yn=500,xs=({check:s,interval:i=yn,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Ne(e,()=>{o&&clearTimeout(o),n(new Ct("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ct("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),x={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},De="application/octet-stream",Es="original",Tt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Ne(r,()=>{u=!0,a.abort(),l(new Ct)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let A=$.split(": "),T=A.shift(),w=A.join(": ");T&&typeof T!="undefined"&&(m[T]=w)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new Gt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function vn(s,...i){return s}var Cn=({name:s})=>s?[s]:[],wn=vn,Tn=()=>new FormData,As=s=>!1,Fe=s=>typeof Blob!="undefined"&&s instanceof Blob,Be=s=>typeof File!="undefined"&&s instanceof File,Ve=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",ae=s=>Fe(s)||Be(s)||As()||Ve(s),xn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",En=s=>!!s&&typeof s=="object"&&!Array.isArray(s),An=s=>!!s&&typeof s=="object"&&"data"in s&&ae(s.data);function $n(s,i,t){if(An(t)){let{name:e,contentType:r}=t,n=wn(t.data,e,r!=null?r:De),o=Cn({name:e,contentType:r});s.push([i,n,...o])}else if(En(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else xn(t)&&t&&s.push([i,t.toString()])}function Sn(s){let i=[];for(let[t,e]of Object.entries(s))$n(i,t,e);return i}function Di(s){let i=Tn(),t=Sn(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var M=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,M.prototype)}},kn=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=kn(t)),e.toString()},In="6.6.1",On="UploadcareUploadClient",Ln=In;function Rt(s){return Ni({libraryName:On,libraryVersion:Ln,...s})}var Un="RequestThrottledError",Ts=15e3,Rn=1e3;function Pn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return Ts;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Ts}function xt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return bn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Un&&r{let i="";return(Fe(s)||Be(s)||Ve(s))&&(i=s.type),i||De},Ss=s=>{let i="";return Be(s)&&s.name?i=s.name:Fe(s)||As()?i="":Ve(s)&&s.name&&(i=s.name),i||Es};function Fi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Mn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=x.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({file:{data:s,name:t||Ss(s),contentType:e||$s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Fi(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Ui;(function(s){s.Token="token",s.FileInfo="file_info"})(Ui||(Ui={}));function Nn(s,{publicKey:i,baseURL:t=x.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Fi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var X;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(X||(X={}));var Dn=s=>"status"in s&&s.status===X.Error;function Fn(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=x.retryNetworkErrorMaxTimes}={}){return xt(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Rt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=mt(JSON.parse(a));if("error"in d&&!Dn(d))throw new M(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Bn(s,{publicKey:i,baseURL:t=x.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:a,userAgent:c})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=mt(JSON.parse(p));if("error"in _)throw new M(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=x.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Vn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=x.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=x.retryNetworkErrorMaxTimes,metadata:_}){return xt(()=>Tt({method:"POST",url:ft(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Di({filename:e||Es,size:s,content_type:t||De,part_size:r,UPLOADCARE_STORE:Fi(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:$,headers:A,request:T})=>{let w=mt(JSON.parse($));if("error"in w)throw new M(w.error.content,w.error.errorCode,T,w,A);return w.parts=Object.keys(w.parts).map(H=>w.parts[H]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function zn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||De}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function jn(s,{publicKey:i,baseURL:t=x.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=x.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=x.retryNetworkErrorMaxTimes}){return xt(()=>Tt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},data:Di({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new M(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Bi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return xs({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}var wt=class{constructor(i,{baseCDN:t=x.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=ft(t,`${r}/`),l=n?ft(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},Hn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:$})=>Mn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:A})=>Bi({file:A,publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new wt(A,{baseCDN:_})),Wn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Xn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Ne(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Gn=window.WebSocket,Ri=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},qn=(s,i)=>s==="success"?{status:X.Success,...i}:s==="progress"?{status:X.Progress,...i}:{status:X.Error,...i},Pi=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ri);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Gn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,qn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Oi=null,Vi=s=>{if(!Oi){let i=typeof window=="undefined"?0:3e4;Oi=new Pi(s,i)}return Oi},Kn=s=>{Vi(s).connect()};function Yn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return xs({check:c=>Fn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case X.Error:return new M(u.error,u.errorCode);case X.Waiting:return!1;case X.Unknown:return new M(`Token "${s}" was not found.`);case X.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case X.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Zn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Vi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Ne(t,()=>{a(),n(new Ct("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case X.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case X.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case X.Error:a(),n(new M(c.msg,c.error_code))}})}),Jn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:$=x.pusherKey,metadata:A})=>Promise.resolve(Kn($)).then(()=>Nn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(T=>{let w=Vi($);return w==null||w.disconnect(),Promise.reject(T)}).then(T=>T.type===Ui.FileInfo?T:Xn([({signal:w})=>Yn({token:T.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:w}),({signal:w})=>Zn({token:T.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(T=>{if(T instanceof M)throw T;return T}).then(T=>Bi({file:T.uuid,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(T=>new wt(T,{baseCDN:r})),Li=new WeakMap,Qn=async s=>{if(Li.has(s))return Li.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Li.set(s,i),i},Is=async s=>{if(Be(s)||Fe(s))return s.size;if(Ve(s))return(await Qn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},to=(s,i=x.multipartMinFileSize)=>s>=i,Os=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!ae(s)&&t.test(s)},Ls=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!ae(s)&&t.test(s)},eo=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},so=async(s,i,t)=>e=>io(s,e,i,t),ro=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>zn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),no=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:$=x.multipartChunkSize,maxConcurrentRequests:A=x.maxConcurrentRequests,baseCDN:T,metadata:w})=>{let H=e!=null?e:await Is(s),ht,It=(P,J)=>{if(!c)return;ht||(ht=Array(P).fill(0));let ut=W=>W.reduce((dt,Ei)=>dt+Ei,0);return W=>{W.isComputable&&(ht[J]=W.value,c({isComputable:!0,value:ut(ht)/P}))}};return _||(_=$s(s)),Vn(H,{publicKey:i,contentType:_,fileName:t||Ss(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:P,parts:J})=>{let ut=await so(s,H,$);return Promise.all([P,eo(A,J.map((W,dt)=>()=>ro(ut(dt),W,{publicKey:i,contentType:_,onProgress:It(J.length,dt),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([P])=>jn(P,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(P=>P.isReady?P:Bi({file:P.uuid,publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(P=>new wt(P,{baseCDN:T}))};async function zi(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:$,maxConcurrentRequests:A,baseCDN:T=x.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,pusherKey:ht,metadata:It}){if(ae(s)){let P=await Is(s);return to(P,_)?no(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:P,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It}):Hn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T,metadata:It})}if(Ls(s))return Jn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:H,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:ht,metadata:It});if(Os(s))return Wn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}var Mi=class{constructor(i,t){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},oo=s=>{for(let i of s)if(!ae(i))return!1;return!0},lo=s=>{for(let i of s)if(!Os(i))return!1;return!0},ao=s=>{for(let i of s)if(!Ls(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=x.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=x.multipartChunkSize,baseCDN:$=x.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T,jsonpCallback:w}){if(!oo(s)&&!ao(s)&&!lo(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let H,ht=!0,It=s.length,P=(J,ut)=>{if(!a)return;H||(H=Array(J).fill(0));let W=dt=>dt.reduce((Ei,Fr)=>Ei+Fr)/J;return dt=>{if(!dt.isComputable||!ht){ht=!1,a({isComputable:!1});return}H[ut]=dt.value,a({isComputable:!0,value:W(H)})}};return Promise.all(s.map((J,ut)=>zi(J,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:P(It,ut),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:$,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:T}))).then(J=>{let ut=J.map(W=>W.uuid);return Bn(ut,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(W=>new Mi(W,J)).then(W=>(a&&a({isComputable:!0,value:1}),W))})}var Lt,jt,Ut,Ht,Wt,Xt,Pe,Me=class{constructor(i){Ot(this,Xt);Ot(this,Lt,1);Ot(this,jt,[]);Ot(this,Ut,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);se(this,Lt,i)}add(i){return new Promise((t,e)=>{B(this,Ht).set(i,t),B(this,Wt).set(i,e),B(this,jt).push(i),Oe(this,Xt,Pe).call(this)})}get pending(){return B(this,jt).length}get running(){return B(this,Ut)}set concurrency(i){se(this,Lt,i),Oe(this,Xt,Pe).call(this)}get concurrency(){return B(this,Lt)}};Lt=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,Pe=function(){let i=B(this,Lt)-B(this,Ut);for(let t=0;t{B(this,Ht).delete(e),B(this,Wt).delete(e),se(this,Ut,B(this,Ut)-1),Oe(this,Xt,Pe).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var ji=()=>({"*blocksRegistry":new Set}),Hi=s=>({...ji(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),ze=s=>({...Hi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Me(1)});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var Q=s=>`*cfg/${s}`;var gt=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ps=new Set;function je(s){Ps.has(s)||(Ps.add(s),console.warn(s))}var He=(s,i)=>new Intl.PluralRules(s).select(i);var Wi="lr-",b=class extends zt{constructor(){super();h(this,"allowCustomTemplate",!0);h(this,"init$",ji());h(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return le(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=He(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setOrAddState(t,e){this.add$({[t]:e},!0)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Wi}${t}`,!0),ki()||(this._destroyInnerHeightTracker=_s()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?le(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=Q(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(je("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${gt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(Q(t));r.ctx.has(r.name)?this.sub(Q(t),e):(this.bindCssData(`--cfg-${gt(t)}`),this.sub(`--cfg-${gt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Wi)?t:Wi+t)}};h(b,"StateConsumerScope",null),h(b,"className","");var ce=class extends b{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setOrAddState("*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}};h(ce,"StateConsumerScope","modal");ce.template=``;var Ms="active",he="___ACTIVITY_IS_ACTIVE___",st=class extends b{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",Hi(this));h(this,"_debouncedHistoryFlush",S(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=st._activityRegistry[this.activityKey];this[he]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=st._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[he]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[he]?this._deactivate():this.activityType===t&&!this[he]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!st._activityRegistry[this.activityKey]}get isActivityActive(){return this[he]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;st._activityRegistry||(st._activityRegistry=Object.create(null)),st._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),st._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(st._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setOrAddState("*modalActive",!1)}}},g=st;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ue=33.333333333333336,y=1,Xi=24,Ns=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function tt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Bs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Vs({rect:s,delta:[i,t],imageBox:e}){return Kt({...s,x:s.x+i,y:s.y+t},e)}function Kt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function co({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Yt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Zt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Et(s,i,t){return Math.min(Math.max(s,i),t)}var Xe=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var et=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs="blocks",Gs="0.27.1";function qs(s){return Ni({...s,libraryName:Xs,libraryVersion:Gs})}var Ks=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Ge=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ks(i)).join("/-/"),O=(...s)=>{let i=Ge(...s);return i?`-/${i}/`:""};function Ys(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Js(s){let i=Qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ks(n))}function Qs(s){let i=new URL(s),t=Ys(s),e=tr(t)?er(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function tr(s){return s.startsWith("http")}function er(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var I=(s,i,t)=>{let e=new URL(Qs(s));if(t=t||Ys(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),tr(t)){let r=er(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var N=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var de=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Gi=s=>s?s.filter(i=>typeof i=="string").map(i=>N(i)).flat():[],qi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ir=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),pe=s=>{let i=s==null?void 0:s.type;return i?qi(i,de):!1};var nt=1e3,Mt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),fe=s=>Math.ceil(s*100)/100,sr=(s,i=Mt.AUTO)=>{let t=i===Mt.AUTO;if(i===Mt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};h(L,"_timeoutStore",Object.create(null));var rr="[Typed State] Wrong property name: ",bo="[Typed State] Wrong property type: ",qe=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||ne.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(bo+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Ke=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||ne.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new qe(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var nr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0},fullPath:{type:String,value:null,nullable:!0}});var or=s=>s?s.split(",").map(i=>i.trim()):[],Nt=s=>s?s.join(","):"";var v=class extends g{constructor(){super(...arguments);h(this,"couldBeUploadCollectionOwner",!1);h(this,"isUploadCollectionOwner",!1);h(this,"init$",ze(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",S(this._runValidators.bind(this),100));h(this,"_handleCollectionUpdate",t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,L.emit(new V({type:U.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&L.emit(new V({type:U.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{L.emit(new V({type:U.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{L.emit(new V({type:U.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{L.emit(new V({type:U.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){je("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Ke({typedSchema:nr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromObject(t,{silent:e,fileName:r,source:n,fullPath:o}={}){this.uploadCollection.add({file:t,isImage:pe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:et.API,fullPath:o})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:pe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Nt(Gi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?de:[]]));this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Nt(de)):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:et.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setOrAddState("*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=N(this.cfg.sourceList)),t}initFlow(t=!1){var e;if(this.uploadCollection.size>0&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0);else if(((e=this.sourceList)==null?void 0:e.length)===1){let r=this.sourceList[0];r==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(r)?this.set$({"*currentActivityParams":{externalSourceType:r},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=r,this.setOrAddState("*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setOrAddState("*modalActive",!0);L.emit(new V({type:U.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setOrAddState("*modalActive",!1),L.emit(new V({type:U.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=Gi([...e?de:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=qi(o,n),c=ir(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:sr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Xe(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=O(`crop/${u.width}x${u.height}/${u.x},${u.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:I(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:qs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};e.push(a)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(U).forEach(s=>{let i=L.eName(s),t=S(e=>{if([U.UPLOAD_FINISH,U.REMOVE,U.CDN_MODIFICATION].includes(e.detail.type)){let n=E.getCtx(e.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let c=E.getCtx(a).store,u=c.fileInfo;if(u){let d={...u,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||u.cdnUrl};l.push(d)}}),L.emit(new V({type:U.DATA_OUTPUT,ctx:e.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var Y={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function yo(s,i){if(typeof i=="number")return Y[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Y[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Y[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var ar=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return Ge(...ar.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yo(i,t)}).filter(i=>!!i))}var Ye=Ge("format/auto","progressive/yes"),_t=([s])=>typeof s!="undefined"?Number(s):void 0,lr=()=>!0,vo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Co=([s,i])=>({dimensions:N(s,"x").map(Number),coords:N(i).map(Number)}),wo={enhance:_t,brightness:_t,exposure:_t,gamma:_t,contrast:_t,saturation:_t,vibrance:_t,warmth:_t,filter:vo,mirror:lr,flip:lr,rotate:_t,crop:Co};function cr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!ar.includes(e))continue;let n=wo[e],o=n(r);i[e]=o}return i}var D=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),G=[D.CROP,D.TUNING,D.FILTERS],hr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],ur=["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"],dr=["rotate","mirror","flip"],ot=Object.freeze({brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}});var To="https://ucarecdn.com",xo="https://upload.uploadcare.com",Eo="https://social.uploadcare.com",me={pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",cloudImageEditorTabs:Nt(G),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:To,baseUrl:xo,socialBaseUrl:Eo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null};var q=s=>String(s),lt=s=>Number(s),k=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,Ao=s=>s==="auto"?s:k(s),$o={pubkey:q,multiple:k,multipleMin:lt,multipleMax:lt,confirmUpload:k,imgOnly:k,accept:q,externalSourcesPreferredTypes:q,store:Ao,cameraMirror:k,sourceList:q,maxLocalFileSizeBytes:lt,thumbSize:lt,showEmptyList:k,useLocalImageEditor:k,useCloudImageEditor:k,cloudImageEditorTabs:q,removeCopyright:k,cropPreset:q,modalScrollLock:k,modalBackdropStrokes:k,sourceListWrap:k,remoteTabSessionKey:q,cdnCname:q,baseUrl:q,socialBaseUrl:q,secureSignature:q,secureExpire:q,secureDeliveryProxy:q,retryThrottledRequestMaxTimes:lt,multipartMinFileSize:lt,multipartChunkSize:lt,maxConcurrentRequests:lt,multipartMaxConcurrentRequests:lt,multipartMaxAttempts:lt,checkForUrlDuplicates:k,saveUrlForRecurrentUploads:k,groupOutput:k,userAgentIntegration:q},pr=(s,i)=>{if(!(typeof i=="undefined"||i===null))return $o[s](i)};var Ze=Object.keys(me),So=["metadata"],ko=s=>So.includes(s),Ki=Ze.filter(s=>!ko(s)),Io={...Object.fromEntries(Ki.map(s=>[gt(s),s])),...Object.fromEntries(Ki.map(s=>[s.toLowerCase(),s]))},Oo={...Object.fromEntries(Ze.map(s=>[gt(s),Q(s)])),...Object.fromEntries(Ze.map(s=>[s.toLowerCase(),Q(s)]))},Je=class extends b{constructor(){super();h(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(me).map(([t,e])=>[Q(t),e]))}}initCallback(){super.initCallback();for(let t of Ze){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,Ki.includes(t)){let o=[...new Set([gt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[Q(t)]!==n&&(typeof n=="undefined"||n===null?this.$[Q(t)]=me[t]:this.$[Q(t)]=n)},get:()=>this.$[Q(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Io[t],o=pr(n,r),l=o!=null?o:me[n],a=this;a[n]=l}};Je.bindAttributes(Oo);var ge=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ge.template=``;ge.bindAttributes({name:"name",size:"size"});var Lo="https://ucarecdn.com",Dt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Lo},"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 fr=s=>[...new Set(s)];var _e="--lr-img-",mr="unresolved",Jt=2,Qt=3,gr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),br=Object.create(null),_r;for(let s in Dt)br[_e+s]=((_r=Dt[s])==null?void 0:_r.default)||"";var Qe=class extends zt{constructor(){super(...arguments);h(this,"cssInit$",br)}$$(t){return this.$[_e+t]}set$$(t){for(let e in t)this.$[_e+e]=t[e]}sub$$(t,e){this.sub(_e+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!gr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return O(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Dt.format.default}`,`quality/${this.$$("quality")||Dt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(gr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return I(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(I(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(I(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(I(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?le(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(mr,""),this.img.onload=()=>{this.img.removeAttribute(mr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Dt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?fr(N(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Jt+"x")}") ${n*Jt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Qt+"x")}") ${n*Qt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Jt))}") ${Jt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Qt))}") ${Qt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Jt+"x")+` ${e*Jt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Qt+"x")+` ${e*Qt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):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(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),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)}static get observedAttributes(){return Object.keys(Dt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[_e+t]=r})}};var Yi=class extends Qe{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var be=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",withDropZone:!0,onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.defineAccessor("dropzone",i=>{typeof i!="undefined"&&(this.$.withDropZone=k(i))}),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};be.template=``;be.bindAttributes({dropzone:null});var Zi=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function Uo(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function Ro(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push({type:"file",file:c,fullPath:l.fullPath}),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function yr(s){let i=[],t=[];for(let e=0;e{a&&i.push(...a)}));continue}let o=r.getAsFile();o&&t.push(Uo(o).then(l=>{l||i.push({type:"file",file:o})}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push({type:"url",url:o}),n(void 0)})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},vr=["focus"],Po=100,Ji=new Map;function Mo(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Qi(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=z.INACTIVE,o=f=>{s.shouldIgnore()&&f!==z.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(z.INACTIVE)},c=()=>{i+=1,n===z.INACTIVE&&o(z.ACTIVE)},u=()=>{i-=1,l()||o(z.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(z.INACTIVE)},p=f=>{if(s.shouldIgnore())return;l()||(i+=1);let _=[f.x,f.y],$=s.element.getBoundingClientRect(),A=Math.floor(Mo(_,$)),T=A{if(s.shouldIgnore())return;f.preventDefault();let _=await yr(f.dataTransfer);s.onItems(_),o(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),vr.forEach(f=>{window.addEventListener(f,a)}),()=>{Ji.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),vr.forEach(f=>{window.removeEventListener(f,a)})}}var ye=class extends v{constructor(){super(),this.init$={...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null}}isActive(){if(!this.$.isEnabled)return!1;let i=this.getBoundingClientRect(),t=i.width>0&&i.height>0,e=i.top>=0&&i.left>=0&&i.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&i.right<=(window.innerWidth||document.documentElement.clientWidth),r=window.getComputedStyle(this),n=r.visibility!=="hidden"&&r.display!=="none";return t&&n&&e}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",t=>{this.set$({isEnabled:!k(t)})}),this.defineAccessor("clickable",t=>{this.set$({isClickable:k(t)})}),this.defineAccessor("with-icon",t=>{this.set$({withIcon:k(t)})}),this.defineAccessor("fullscreen",t=>{this.set$({isFullscreen:k(t)})}),this.defineAccessor("text",t=>{typeof t=="string"?this.set$({text:this.l10n(t)||t}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Qi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:t=>{this.$.state=t},onItems:t=>{t.length&&(t.forEach(e=>{e.type==="url"?this.addFileFromUrl(e.url,{source:et.DROP_AREA}):e.type==="file"&&this.addFileFromObject(e.file,{source:et.DROP_AREA,fullPath:e.fullPath})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setOrAddState("*modalActive",!0)))}});let i=this.ref["content-wrapper"];i&&(this._destroyContentWrapperDropzone=Qi({element:i,onChange:t=>{var r;let e=(r=Object.entries(z).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&i.setAttribute("drag-state",e)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",t=>{var r;let e=(r=Object.entries(z).find(([,n])=>n===t))==null?void 0:r[0].toLowerCase();e&&this.setAttribute("drag-state",e)}),this.subConfigValue("sourceList",t=>{let e=N(t);this.$.isEnabled=e.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",t=>{this.toggleAttribute("hidden",!t)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(e=>e!==this).filter(e=>e.isActive()).length>0:!1}_couldHandleFiles(){let i=this.cfg.multiple,t=this.cfg.multipleMax,e=this.uploadCollection.size;return!(i&&t&&e>=t||!i&&e>0)}destroyCallback(){var i,t,e,r;super.destroyCallback(),(t=(i=this.$["lr-drop-area/targets"])==null?void 0:i.remove)==null||t.call(i,this),(e=this._destroyDropzone)==null||e.call(this),(r=this._destroyContentWrapperDropzone)==null||r.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};ye.template=`
{{text}}
`;ye.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var No="src-type-",ve=class extends v{constructor(){super(...arguments);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${No}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ve.template=`
`;ve.bindAttributes({type:null});var ts=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=N(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function Cr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function wr(s="#fff",i="rgba(0, 0, 0, .1)"){return Cr(``)}function Ce(s="hsl(209, 21%, 65%)",i=32,t=32){return Cr(``)}function Tr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var j=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),bt=class extends v{constructor(){super();h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",S(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",S(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:j.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=j.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=j.FAILED:t.getValue("validationMultipleLimitMsg")?e=j.LIMIT_OVERFLOW:t.getValue("isUploading")?e=j.UPLOADING:t.getValue("fileInfo")&&(e=j.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(I(At(this.cfg.cdnCname,this._entry.getValue("uuid")),O(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await Tr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Ce(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{bt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),bt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===j.FAILED,isLimitOverflow:t===j.LIMIT_OVERFLOW,isUploading:t===j.UPLOADING,isFinished:t===j.FINISHED,progressVisible:t===j.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===j.FAILED||t===j.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===j.FINISHED&&(this.$.badgeIcon="badge-success"),t===j.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),bt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));L.emit(new V({type:U.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=await this.getUploadClientOptions();return zi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof M?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};bt.template=`
{{itemName}}{{errorText}}
`;bt.activeInstances=new Set;var ti=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},ei=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};ei.template=`
{{captionTxt}}
{{msgTxt}}
`;var ii=class extends v{constructor(){super();h(this,"couldBeUploadCollectionOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",S(()=>{var t;this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage(),((t=this.$["*uploadList"])==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.$["*currentActivity"]===this.activityType&&this.historyBack())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));L.emit(new V({type:U.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new ti,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};ii.template=`{{headerText}}
`;var si=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:et.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};si.template=`
`;var es=()=>typeof navigator.permissions!="undefined";var ri=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:es(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{es()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",S(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:et.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ri.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var is=class extends v{};var ni=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=Ce(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=pe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=I(n,O("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ni.template=`
{{fileSize}}
{{errorTxt}}
`;var ss=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},oi=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ss);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};oi.template=`{{activityCaption}}
{{messageTxt}}
`;var li=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};li.template=``;var ai=class extends b{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ai.template='
';var Z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var we=class extends b{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:Z})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${wr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Z}};we.template='';we.bindAttributes({checkerboard:"checkerboard"});var xr="--cfg-ctx-name",R=class extends b{get cfgCssCtxName(){return this.getCssData(xr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(xr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function Er(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function F(...s){let i=Er(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function Ar(s,...i){let t=Er(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var $r=s=>{if(!s)return G;let i=or(s).filter(t=>G.includes(t));return i.length===0?G:i};function Sr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*tabList":G,entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Z,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"",tabs:Nt(G),"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Z,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=O($t(i)),r=I(t,O(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var kr=`
Network error
{{fileType}}
{{msg}}
`;var at=class extends R{constructor(){super();h(this,"_debouncedShowLoader",S(this._showLoader.bind(this),300));this.init$={...this.init$,...Sr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===D.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Zs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Js(this.$.cdnUrl),r=cr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=I(this.$["*originalUrl"],O("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===D.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Z&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Z)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Xe(t)}),this.sub("tabs",t=>{this.$["*tabList"]=$r(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=F("image",{image_hidden_to_cropper:t===D.CROP,image_hidden_effects:t!==D.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=O($t(t)),n=I(e,O(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(at,"className","cloud-image-editor");at.template=kr;at.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset",tabs:"tabs"});var ci=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=tt("mask",{id:"backdrop-mask"}),a=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=tt("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Pt(n,f)}else{let f=Et(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:$}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(Xi*Et(Math.min(d,p)/Xi/3,0,1),Ns);Pt(n,{x:$[0]-A,y:$[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",F("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=tt("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=tt("rect",{fill:"transparent"}),l=tt("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=tt("svg"),t=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=tt("line",{x1:`${ue*e}%`,y1:"0%",x2:`${ue*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=tt("line",{x1:"0%",y1:`${ue*e}%`,x2:"100%",y2:`${ue*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Vs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Kt(Zt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Bs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",F("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",F({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ci.template='';var yt=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=F({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function Fo(s){let i=s+90;return i=i>=360?0:i,i}function Bo(s,i){return s==="rotate"?Fo(i):["mirror","flip"].includes(s)?!i:null}var Te=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Bo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var xe={FILTER:"filter",COLOR_OPERATION:"color_operation"},ct="original",hi=class extends R{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?xe.FILTER:xe.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ct?void 0:this.$.value,filter:this._filter===ct?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ot[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===xe.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===xe.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===xe.FILTER?this._filter===ct?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};hi.template=``;function Ee(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=Z)}}}function Ae(s){let i=[];for(let n of s){let o=Ee(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var te=class extends yt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ct?{name:this._filter,amount:o}:void 0,I(this._originalUrl,O(Ye,$t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=Ee(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{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",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ct,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};te.template=`
`;var $e=class extends yt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ot[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Ir=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function Or(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function ee(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return I(s,O(Ye,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Vo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var ui=class extends R{constructor(){super(),this.init$={...this.init$,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=S(this._commit.bind(this),300),this._handleResizeThrottled=Ir(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Or(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=Yt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Zt(l)}_alignCrop(){var c;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[u,d],coords:[p,m]}=n,{width:f}=Yt(this._imageSize,r),_=o/f;i=Kt(Zt({x:l+p*_,y:a+m*_,width:u*_,height:d*_}),this.$["*imageBox"])}if(!n||!Hs(i,t)){let u=(c=this.$["*cropPresetList"])==null?void 0:c[0],d=u?u.width/u.height:void 0,p=t.width/t.height,m=t.width,f=t.height;d&&(p>d?m=Math.min(t.height*d,t.width):f=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Kt(Zt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=Yt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=F({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=Yt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[Et(Math.round(c/d),1,l),Et(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=Yt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),$={dimensions:_,coords:[Et(Math.round((d-l)/m),0,c-_[0]),Et(Math.round((p-a)/f),0,u-_[1])]};if(!Vo($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(_[0]===c&&_[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=F({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(ee(i,e,t)),{promise:n,cancel:o,image:l}=Ee(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};ui.template=``;function rs(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function zo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function Ho(s,i){return s.map((t,e)=>tn-o)}var ns=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=S(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(ee(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ot[i],r=this._keypoints.map(l=>l.value),n=jo(r,t,e),o=Ho(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Ae(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Lr(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=Ae(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=F({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Lr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=F({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Wo=1,di=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Wo?this.scrollLeft+=e:this.scrollLeft+=t})}};di.template=" ";function Xo(s){return``}function Go(s){return`
`}var pi=class extends R{constructor(){super();h(this,"_updateInfoTooltip",S(()=>{var o,l;let t=this.$["*editorTransformations"],e=this.$["*currentOperation"],r="",n=!1;if(this.$["*tabId"]===D.FILTERS)if(n=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((l=t==null?void 0:t.filter)==null?void 0:l.amount)||100;r=this.l10n(this.$["*currentFilter"])+" "+a}else r=this.l10n(ct);else if(this.$["*tabId"]===D.TUNING&&e){n=!0;let a=(t==null?void 0:t[e])||ot[e].zero;r=e+" "+a}n&&(this.$["*operationTooltip"]=r),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",n)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ct,"*currentOperation":null,"*tabId":D.CROP,showLoader:!1,filters:ur,colorOperations:hr,cropOperations:dr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabToggles":!0,"presence.tabContent.crop":!1,"presence.tabContent.tuning":!1,"presence.tabContent.filters":!1,"presence.tabToggle.crop":!0,"presence.tabToggle.tuning":!0,"presence.tabToggle.filters":!0,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"presence.tabToggleStyles":{hidden:"tab-toggle--hidden",visible:"tab-toggle--visible"},"presence.tabTogglesStyles":{hidden:"tab-toggles--hidden",visible:"tab-toggles--visible"},"on.cancel":()=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":()=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":()=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":()=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");e&&this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=S(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===D.TUNING&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=new $e;return e.operation=t,e}_createFilterControl(t){let e=new te;return e.filter=t,e}_createToggleControl(t){let e=new Te;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===D.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===D.FILTERS?[ct,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===D.TUNING&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),[...r.children].forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===D.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of G){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ee(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Ae([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this.sub("*tabList",t=>{this.$["presence.tabToggles"]=t.length>1,this.$["*tabId"]=t[0];for(let e of G){this.$[`presence.tabToggle.${e}`]=t.includes(e);let r=this.ref[`tab-toggle-${e}`];r.style.gridColumn=t.indexOf(e)+1}}),this._updateInfoTooltip()}};pi.template=`
{{*operationTooltip}}
${G.map(Go).join("")}
${G.map(Xo).join("")}
`;var Se=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return F("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Se.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Se.template=`
{{text}}
`;var fi=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};fi.template=`
`;var mi={transition:"transition",visible:"visible",hidden:"hidden"},gi=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=mi.visible,this._hiddenStyle=mi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Ar(this,{[mi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(mi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};gi.template=" ";var _i=class extends b{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);h(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new at,e=this.$.cdnUrl,r=this.cfg.cropPreset,n=this.cfg.cloudImageEditorTabs;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),n&&t.setAttribute("tabs",n),t.addEventListener("apply",o=>this.handleApply(o)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var qo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Ur=function(s,i="i"){let t=s.split("*").map(qo);return new RegExp("^"+t.join(".+")+"$",i)};var Ko=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Rr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return Ko({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var St={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in St){let t=St[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Pr=function(s,i,t){s in St||(St[s]=[]),St[s].push([i,t])},Mr=function(s,i){s in St&&(St[s]=St[s].filter(t=>t[0]!==i))};function Nr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var bi=class extends v{constructor(){super();h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=N(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Ur(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Rr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Nr(n),o.toString()}mountIframe(){let t=oe({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Pr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Mr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};bi.template=`
{{activityCaption}}
{{counter}}
`;var ke=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;N(i).forEach(e=>{let r=oe({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};ke.bindAttributes({"tab-list":null,default:null});ke.template=`
`;var ie=class extends v{constructor(){super(...arguments);h(this,"processInnerHtml",!0);h(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return ie.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Us(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};ie.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ls=class extends g{};var yi=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};yi.template=``;var K={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Dr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},it=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:K.PLAY,fsIcon:K.FS_ON,volIcon:K.VOL_ON,capIcon:K.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Dr.exitFullscreen():Dr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===K.CAP_OFF?(this.$.capIcon=K.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(it.is+":captions","1")):(this.$.capIcon=K.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(it.is+":captions"))}toggleSound(){this.$.volIcon===K.VOL_ON?(this.$.volIcon=K.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=K.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(it.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(it.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=K.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=K.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=K.FS_OFF:this.$.fsIcon=K.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(it.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};it.template=`
{{currentTime}} / {{totalTime}}
`;it.bindAttributes({video:"video",src:"src"});var Yo="css-src";function vi(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Yo);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Ie=class extends vi(b){};var Ci=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(Ci,"template",`Powered by Uploadcare`);var kt=class extends Ie{constructor(){super(...arguments);h(this,"init$",ze(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var wi=class extends kt{};wi.template=``;var Ti=class extends kt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};Ti.template=``;var xi=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};xi.template=``;var as=class extends vi(at){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Zo(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,zt as BaseComponent,b as Block,ri as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,at as CloudImageEditorBlock,Je as Config,oi as ConfirmationDialog,Ci as Copyright,ci as CropFrame,E as Data,ie as DataOutput,ye as DropArea,Te as EditorCropButtonControl,te as EditorFilterControl,ui as EditorImageCropper,ns as EditorImageFader,$e as EditorOperationControl,di as EditorScroller,hi as EditorSlider,pi as EditorToolbar,bi as ExternalSource,bt as FileItem,we as FilePreview,xi as FileUploaderInline,Ti as FileUploaderMinimal,wi as FileUploaderRegular,ge as Icon,Yi as Img,fi as LineLoaderUi,Se as LrBtnUi,ei as MessageBox,ce as Modal,Xs as PACKAGE_NAME,Gs as PACKAGE_VERSION,gi as PresenceToggle,ai as ProgressBar,li as ProgressBarCommon,yi as Select,Ie as ShadowWrapper,be as SimpleBtn,_i as SliderUi,ve as SourceBtn,ts as SourceList,Zi as StartFrom,ke as Tabs,is as UploadCtxProvider,ni as UploadDetails,ii as UploadList,v as UploaderBlock,si as UrlSource,it as Video,Zo as connectBlocksFrom,cs as registerBlocks,vi as shadowed,gt as toKebabCase}; \ No newline at end of file