@uploadcare/file-uploader 1.25.0-alpha.1 → 1.25.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,9 +24,9 @@
24
24
  *
25
25
  */
26
26
  var Ut=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var nr=Object.getOwnPropertyNames;var ar=Object.prototype.hasOwnProperty;var Dt=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of nr(i))!ar.call(s,r)&&r!==e&&Ut(s,r,{get:()=>i[r],enumerable:!(t=Ft(i,r))||t.enumerable});return s},u=(s,i,e)=>(Dt(s,i,"default"),e&&Dt(e,i,"default"));var p=(s,i,e,t)=>{for(var r=t>1?void 0:t?Ft(i,e):i,o=s.length-1,n;o>=0;o--)(n=s[o])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&Ut(i,e,r),r};var m={};u(m,_s);u(m,Ts);import"@lit/reactive-element";import"lit-html";import*as _s from"lit-element/lit-element.js";import*as Ts from"lit-html/is-server.js";var c={};u(c,ws);u(c,Cs);u(c,Es);u(c,xs);u(c,Ss);u(c,ks);u(c,Rs);u(c,Os);u(c,As);import*as ws from"@lit/reactive-element/decorators/custom-element.js";import*as Cs from"@lit/reactive-element/decorators/property.js";import*as Es from"@lit/reactive-element/decorators/state.js";import*as xs from"@lit/reactive-element/decorators/event-options.js";import*as Ss from"@lit/reactive-element/decorators/query.js";import*as ks from"@lit/reactive-element/decorators/query-all.js";import*as Rs from"@lit/reactive-element/decorators/query-async.js";import*as Os from"@lit/reactive-element/decorators/query-assigned-elements.js";import*as As from"@lit/reactive-element/decorators/query-assigned-nodes.js";var g={};u(g,Is);import*as Is from"lit-html/directives/ref.js";var fe={};u(fe,Ps);import*as Ps from"lit-html/directives/unsafe-svg.js";var O={BIND_ATTR:"bind",ATTR_BIND_PX:"@",SHARED_CTX_PX:"*",PARENT_CTX_PX:"^",NAMED_CTX_SPLTR:"/",COMPUTED_PX:"+",CSS_DATA_PX:"--",CTX_NAME_ATTR:"ctx",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx",EL_REF_ATTR:"ref",AUTO_TAG_PX:"sym",LIST_ATTR:"itemize",LIST_ITEM_TAG_ATTR:"item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL_ATTR:"use-template",DEFAULT_SLOT_KEY:"__default__",TEXT_NODE_SKIP_ATTR:"skip-text-nodes",TEXT_NODE_OPEN_TOKEN:"{{",TEXT_NODE_CLOSE_TOKEN:"}}"};function lr(s){let i=e=>{for(let t in e)e[t]?.constructor===Object&&(e[t]=i(e[t]));return{...e}};return i(s)}var X=class s{#i;#r;#e;constructor(i){i.constructor===Object?this.store=lr(i):(this.#e=!0,this.store=i),this.callbackMap=Object.create(null)}static#t(i,e){console.warn(`Symbiote PubSub: cannot ${i}. Prop name: `+e)}read(i){if(!this.#e&&!this.store.hasOwnProperty(i))return s.#t("read",i),null;if(typeof i=="string"&&i.startsWith(O.COMPUTED_PX)){let e=this.store[i];if(e?.constructor!==Function){s.#t("compute",i);return}this.__computedMap||(this.__computedMap={});let t=e();return Object.keys(this.__computedMap).includes(i)||(this.__computedMap[i]=t,this.notify(i)),t}else return this.store[i]}has(i){return this.#e?this.store[i]!==void 0:this.store.hasOwnProperty(i)}add(i,e,t=!1){!t&&Object.keys(this.store).includes(i)||(this.store[i]=e,this.notify(i))}pub(i,e){if(!this.#e&&!this.store.hasOwnProperty(i)){s.#t("publish",i);return}if(i?.startsWith(O.COMPUTED_PX)&&e.constructor!==Function){s.#t("publish computed",i);return}!(this.store[i]===null||e===null)&&typeof this.store[i]!=typeof e&&console.warn(`Symbiote PubSub: type warning for "${i}" [${typeof this.store[i]} -> ${typeof e}]`),this.store[i]=e,this.notify(i)}get proxy(){if(!this.#r){let i=Object.create(null);this.#r=new Proxy(i,{set:(e,t,r)=>(this.pub(t,r),!0),get:(e,t)=>{this.read(t)}})}return this.#r}multiPub(i){for(let e in i)this.pub(e,i[e])}static#s(i,e){this.globalStore.forEach(t=>{t.__computedMap&&Object.keys(t.__computedMap).forEach(r=>{if(t===i&&e===r)return;let o=`__${r}_timeout`;t[o]&&window.clearTimeout(t[o]),t[o]=window.setTimeout(()=>{let n=t.read(r);n!==t.__computedMap[r]&&(t.__computedMap[r]=n,t.notify(r))})})})}notify(i){let e=i?.startsWith(O.COMPUTED_PX);if(this.callbackMap[i]){let t=this.read(i);this.callbackMap[i].forEach(r=>{r(t)}),e&&(this.__computedMap[i]=t)}!e&&s.#s(this,i)}sub(i,e,t=!0){return!this.#e&&!this.store.hasOwnProperty(i)?(s.#t("subscribe",i),null):(this.callbackMap[i]||(this.callbackMap[i]=new Set),this.callbackMap[i].add(e),t&&e(this.read(i)),{remove:()=>{this.callbackMap[i].delete(e),this.callbackMap[i].size||delete this.callbackMap[i]},callback:e})}set uid(i){!this.#i&&(this.#i=i)}get uid(){return this.#i}static registerCtx(i,e=Symbol()){let t=s.globalStore.get(e);return t?console.warn('PubSub: context UID "'+e+'" is already in use'):(t=new s(i),t.uid=e,s.globalStore.set(e,t)),t}static deleteCtx(i){s.globalStore.delete(i)}static getCtx(i,e=!0){return s.globalStore.get(i)||(e&&console.warn('PubSub: wrong context UID - "'+i+'"'),null)}};X.globalStore=new Map;var Vt="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",cr=Vt.length-1,me=class{static generate(i="XXXXXXXXX-XXX"){let e="";for(let t=0;t<i.length;t++)e+=i[t]==="-"?i[t]:Vt.charAt(Math.random()*cr);return e}};var qs=[O.LIST_ATTR,O.LIST_ITEM_TAG_ATTR,O.EL_REF_ATTR,O.USE_TPL_ATTR,O.CTX_NAME_ATTR,O.CTX_OWNER_ATTR];function z(s,...i){let e="",t=new CSSStyleSheet;return s.forEach((r,o)=>{e+=r+i[o]}),z.processors.forEach(r=>{e=r(e)}),z.clearProcessors(),t.replaceSync(e),t}z.processors=[];z.clearProcessors=function(){z.processors=[]};z.useProcessor=function(...s){return z.processors=[...z.processors,...s],z};var Uo={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"};var jt;(function(s){s.Token="token",s.FileInfo="file_info"})(jt||(jt={}));var Kt;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(Kt||(Kt={}));var Fo=window.WebSocket;var De=class{_concurrency=1;_pending=[];_running=0;_resolvers=new Map;_rejectors=new Map;constructor(i){this._concurrency=i}run(){let i=this._concurrency-this._running;for(let e=0;e<i;e++){let t=this._pending.shift();if(!t)return;let r=this._resolvers.get(t),o=this._rejectors.get(t);if(!r||!o)throw new Error("Unexpected behavior: resolver or rejector is undefined");this._running+=1,t().finally(()=>{this._resolvers.delete(t),this._rejectors.delete(t),this._running-=1,this.run()}).then(n=>r(n)).catch(n=>o(n))}}add(i,{autoRun:e}={autoRun:!0}){return new Promise((t,r)=>{this._resolvers.set(i,t),this._rejectors.set(i,r),this._pending.push(i),e&&this.run()})}get pending(){return this._pending.length}get running(){return this._running}set concurrency(i){this._concurrency=i,this.run()}get concurrency(){return this._concurrency}};var Ht=()=>({});var hr={button:["toolbar"],checkbox:["toolbar"],menuitem:["menu","menubar"],option:["listbox"],tab:["tablist"]};function xe(s,i){i.tabIndex=0,i.focus(),s.tabIndex=-1}function pt(s){let i=s.role||s.type||s.tagName;if(!i)return null;let e=hr[i.toLowerCase()];if(!e)return null;for(let t of e){let r=s.closest(`[role=${t}]`);if(r)return r}}function ft(s,i){return i.role==="toolbar"?pr(i):i.querySelectorAll(`[role=${s.role}]`)}function pr(s){return[...s.querySelectorAll("*")].filter(e=>e.role==="button"||e.type==="button"||e.role==="checkbox"||e.type==="checkbox")}function fr(s){let i=s.getAttribute("aria-orientation");if(i==="vertical")return!1;if(i==="horizontal")return!0;let e=s.role;return e==="menubar"||e==="tablist"||e==="toolbar"}function Bt(s){return i=>{let e=!1,t=s?.searchDelayMs||300,r=0,o="";function n(h){let y=pt(h.target);if(!y){a();return}let b=ft(h.target,y),_=Array.from(b).indexOf(h.target),I="ArrowDown",R="ArrowUp";if(fr(y)&&(i.document.dir==="rtl"?(I="ArrowLeft",R="ArrowRight"):(I="ArrowRight",R="ArrowLeft")),h.key===I)h.preventDefault(),xe(h.target,b[_+1]||b[0]);else if(h.key===R)h.preventDefault(),xe(h.target,b[_-1]||b[b.length-1]);else if(h.key==="Home")h.preventDefault(),xe(h.target,b[0]);else if(h.key==="End")h.preventDefault(),xe(h.target,b[b.length-1]);else if(h.key.length===1&&y.role!=="tablist"){let P=Date.now();P-r<=t?o+=h.key.toLowerCase():o=h.key.toLowerCase(),r=P;let le=Array.from(b).find(or=>or.textContent?.trim()?.toLowerCase()?.startsWith(o));le&&(h.preventDefault(),xe(h.target,le))}}function a(){e=!1,i.removeEventListener("keydown",n)}function l(h){let y=pt(h.target);if(y){e||(e=!0,i.addEventListener("keydown",n));let b=ft(h.target,y);for(let _ of b)_!==h.target&&_.setAttribute("tabindex",-1)}else e&&a()}function d(h){(!h.relatedTarget||h.relatedTarget===i.document)&&a()}function f(h){let y=pt(h.target);if(y){let b=ft(h.target,y);for(let _ of b)_!==h.target&&_.setAttribute("tabindex",-1);h.target.setAttribute("tabindex",0)}}return i.addEventListener("click",f),i.addEventListener("focusin",l),i.addEventListener("focusout",d),()=>{a(),i.removeEventListener("click",f),i.removeEventListener("focusin",l),i.removeEventListener("focusout",d)}}}function Gt(){return s=>{let i,e;function t(o){if(o.target.getAttribute("aria-hidden")==="true"){i=o.target,i.setAttribute("aria-hidden","false"),e=i.hidden,e&&(i.hidden=!1);let n=o.target.querySelector('a, button, select, textarea, input:not([type=radio]), [type=radio]:checked, [tabindex]:not([tabindex="-1"])');n&&(n.tabIndex=0)}}function r(o){i&&i.contains(o.target)&&(!o.relatedTarget||!i.contains(o.relatedTarget))&&(o.target.tabIndex=-1,i.setAttribute("aria-hidden","true"),e&&(i.hidden=!0),i=null)}return s.addEventListener("keyuxJump",t),s.addEventListener("focusout",r),()=>{s.removeEventListener("keyuxJump",t),s.removeEventListener("focusout",r)}}}function Xt(){return s=>{let i=[];function e(l){let d=s.document.activeElement;d&&d!==s.document.body&&i.push(new WeakRef(d)),l.focus({focusVisible:!0})}function t(){let l=i.pop();if(!l){s.document.activeElement.blur();return}let d=l.deref();d&&d.isConnected?d.focus():t()}let r=0,o;function n(l){clearInterval(o);let d=l.getAttribute("aria-controls");o=setInterval(()=>{if(r++>50){clearInterval(o);return}let f=s.document.getElementById(d);if(f){let h=f.querySelector('a, button, select, textarea, input:not([type=radio]), [type=radio]:checked, [tabindex]:not([tabindex="-1"])');h&&(clearInterval(o),f.dispatchEvent(new s.CustomEvent("keyuxJump",{bubbles:!0})),e(h))}},50)}function a(l){l.target.getAttribute("aria-controls")&&l.key==="Enter"&&n(l.target),l.key==="Escape"&&t()}return s.addEventListener("keydown",a),()=>{s.removeEventListener("keydown",a)}}}function qt(s){let i,e=s.split(" "),t;function r(a){a.key==="Enter"&&(a.target.tagName==="BUTTON"||a.target.tagName==="A")&&(o(),a.target.classList.add(...e),i=a.target,t=a.target)}function o(){i&&i.classList.remove(...e),t=null}function n(a){a.clientX===0&&a.clientY===0&&t!==a.target&&(o(),a.target.classList.add(...e),i=a.target)}return a=>(a.addEventListener("click",n),a.addEventListener("keydown",r),a.addEventListener("keyup",o),()=>{a.removeEventListener("click",n),a.removeEventListener("keydown",r),a.removeEventListener("keyup",o)})}function Wt(s,i){let e=i.map(t=>t(s));return()=>{e.forEach(t=>t())}}var mt=class{constructor(){this._listeners=new Map;this._scope=[]}addEventListener(i,e){let t=r=>{let o=r.target;o instanceof Node&&this._scope.some(n=>n===o||n.contains(o))&&e(r)};this._listeners.set(e,t),window.addEventListener(i,t)}removeEventListener(i,e){let t=this._listeners.get(e);t&&window.removeEventListener(i,t),this._listeners.delete(e)}get CustomEvent(){return window.CustomEvent}get document(){return window.document}get navigator(){return window.navigator}registerScope(i){this._scope.push(i)}destroy(){this._scope=[];for(let i of this._listeners.values())window.removeEventListener("keydown",i),window.removeEventListener("keyup",i);this._listeners.clear()}},Ue=class{constructor(){this._scopedWindow=new mt,this._destroyKeyUX=Wt(this._scopedWindow,[Bt(),qt("is-pressed"),Xt(),Gt()])}registerBlock(i){this._scopedWindow.registerScope(i)}destroy(){this._destroyKeyUX?.(),this._scopedWindow.destroy()}};var Se={"locale-id":"en","social-source-lang":"en","upload-file":"Upload file","upload-files":"Upload files","choose-file":"Choose file","choose-files":"Choose files","drop-files-here":"Drop files here","select-file-source":"Select file source",selected:"Selected",upload:"Upload","add-more":"Add more",cancel:"Cancel","start-from-cancel":"Cancel",clear:"Clear","camera-shot":"Shot","upload-url":"Import","upload-url-placeholder":"Paste link here","edit-image":"Edit image","edit-detail":"Details",back:"Back",done:"Done",ok:"Ok","remove-from-list":"Remove",no:"No",yes:"Yes","confirm-your-action":"Confirm your action","are-you-sure":"Are you sure?","selected-count":"{{count}} of {{total}} selected","select-all":"Select all","deselect-all":"Deselect all","upload-error":"Upload error","validation-error":"Validation error","no-files":"No files selected",browse:"Browse","not-uploaded-yet":"Not uploaded yet...",file__one:"file",file__other:"files",error__one:"error",error__other:"errors","header-uploading":"Uploading {{count}} {{plural:file(count)}}","header-failed":"{{count}} {{plural:error(count)}}","header-succeed":"{{count}} {{plural:file(count)}} uploaded","header-total":"{{count}} {{plural:file(count)}} selected","src-type-local":"From device","src-type-from-url":"From link","src-type-camera":"Camera","src-type-mobile-video-camera":"Video","src-type-mobile-photo-camera":"Photo","src-type-draw":"Draw","src-type-facebook":"Facebook","src-type-dropbox":"Dropbox","src-type-gdrive":"Google Drive","src-type-ngdrive":"Google Drive","src-type-gphotos":"Google Photos","src-type-flickr":"Flickr","src-type-vk":"VK","src-type-evernote":"Evernote","src-type-box":"Box","src-type-onedrive":"OneDrive","src-type-huddle":"Huddle","src-type-other":"Other","caption-from-url":"Import from link","caption-camera":"Camera","caption-draw":"Draw","caption-edit-file":"Edit file","file-no-name":"No name...","toggle-fullscreen":"Toggle fullscreen","toggle-guides":"Toggle guides",rotate:"Rotate","flip-vertical":"Flip vertical","flip-horizontal":"Flip horizontal",apply:"Apply",brightness:"Brightness",contrast:"Contrast",saturation:"Saturation",exposure:"Exposure",gamma:"Gamma",vibrance:"Vibrance",warmth:"Warmth",enhance:"Enhance",original:"Original",resize:"Resize image",crop:"Crop","select-color":"Select color",text:"Text",draw:"Draw","cancel-edit":"Cancel edit","tab-view":"Preview","tab-details":"Details","file-name":"Name","file-size":"Size","cdn-url":"CDN URL","file-size-unknown":"Unknown","camera-permissions-denied":"Camera access denied","camera-permissions-prompt":"Please allow access to the camera","camera-permissions-request":"Request access","files-count-limit-error-title":"Files count limit overflow","files-count-limit-error-too-few":"You\u2019ve chosen {{total}} {{plural:file(total)}}. At least {{min}} {{plural:file(min)}} required.","files-count-limit-error-too-many":"You\u2019ve chosen too many files. {{max}} {{plural:file(max)}} is maximum.","files-max-size-limit-error":"File is too big. Max file size is {{maxFileSize}}.","has-validation-errors":"File validation error occurred. Please, check your files before upload.","images-only-accepted":"Only image files are accepted.","file-type-not-allowed":"Uploading of these file types is not allowed.","some-files-were-not-uploaded":"Some files were not uploaded.","file-item-edit-button":"Edit","file-item-remove-button":"Remove","a11y-editor-tab-filters":"Filters","a11y-editor-tab-tuning":"Tuning","a11y-editor-tab-crop":"Crop","a11y-activity-header-button-close":"Close",flip:"Flip",mirror:"Mirror","a11y-cloud-editor-apply-filter":"Apply {{name}} filter","a11y-cloud-editor-apply-crop":"Apply {{name}} operation","a11y-cloud-editor-apply-tuning":"Apply {{name}} tuning","a11y-cloud-editor-apply-aspect-ratio":"Apply operation {{name}} {{value}}",finished:"Finished",failed:"Failed",uploading:"Uploading",idle:"Idle","a11y-file-item-status":"File {{fileName}} in status {{status}}","waiting-for":"Waiting for {{source}}","queued-uploading":"Queued for upload","queued-validation":"Queued for validation",validation:"Validating","crop-to-shape":"Crop to {{value}}",custom:"Freeform","freeform-crop":"Freeform crop"};var Fe=new Map,gt=new Map,Yt=(s,i)=>{Fe.has(s)&&console.log(`Locale ${s} is already defined. Overwriting...`),Fe.set(s,{...Se,...i})},mr=(s,i)=>{gt.set(s,i)},gr=(s,i)=>{typeof i=="function"?mr(s,i):Yt(s,i)},Qt=async s=>{if(!Fe.has(s)){if(!gt.has(s))throw new Error(`Locale ${s} is not defined`);let e=await gt.get(s)();Yt(s,e)}return Fe.get(s)};gr("en",Se);var te=s=>`*l10n/${s}`,yr="en",Ve=class{constructor(i){this._blockInstance=null;this._localeName="";this._blockInstance=i;for(let[e,t]of Object.entries(Se)){let r=this._blockInstance.has(te(e))?!this._blockInstance.$[te(e)]:!0;this._blockInstance.add(te(e),t,r)}setTimeout(()=>{i.subConfigValue("localeName",async e=>{if(!this._blockInstance||!e)return;this._localeName=e;let t=await Qt(e);if(e!==yr&&this._localeName!==e)return;let r=this._blockInstance.cfg.localeDefinitionOverride?.[e];for(let[o,n]of Object.entries(t)){let a=r?.[o];this._blockInstance.add(te(o),a??n,!0)}}),i.subConfigValue("localeDefinitionOverride",e=>{if(!e)return;let t=e[this._localeName];if(t)for(let[r,o]of Object.entries(t))this._blockInstance?.add(te(r),o,!0)})})}};var ge=Object.freeze({ADD:"modal:add",DELETE:"modal:delete",OPEN:"modal:open",CLOSE:"modal:close",CLOSE_ALL:"modal:closeAll",DESTROY:"modal:destroy"}),ze=class{constructor(i){this._modals=new Map;this._activeModals=new Set;this._subscribers=new Map;this._block=i}_debugPrint(...i){this._block.debugPrint("[modal-manager]",...i)}registerModal(i,e){this._modals.set(i,e),this._notify(ge.ADD,{id:i,modal:e})}deleteModal(i){if(!this._modals.has(i))return!1;let e=this._modals.get(i);return this._modals.delete(i),this._activeModals.delete(i),this._notify(ge.DELETE,{id:i,modal:e}),!0}open(i){if(!this._modals.has(i))return this._debugPrint(`Modal with ID "${i}" not found`),!1;let e=this._modals.get(i);return this._activeModals.add(i),this._notify(ge.OPEN,{modal:e,id:i}),!0}close(i){if(!this._modals.has(i)||!this._activeModals.has(i))return this._debugPrint(`Modal with ID "${i}" not found or not active`),!1;let e=this._modals.get(i);return this._activeModals.delete(i),this._notify(ge.CLOSE,{id:i,modal:e}),!0}toggle(i){return this._modals.has(i)?this._activeModals.has(i)?this.close(i):this.open(i):(this._debugPrint(`Modal with ID "${i}" not found`),!1)}get hasActiveModals(){return this._activeModals.size>0}back(){if(this._activeModals.size===0)return this._debugPrint("No active modals to go back from"),!1;let i=Array.from(this._activeModals).pop();return i?this.close(i):!1}closeAll(){let i=this._activeModals.size;return this._activeModals.clear(),this._notify(ge.CLOSE_ALL,{}),i}subscribe(i,e){return this._subscribers.has(i)||this._subscribers.set(i,new Set),this._subscribers.get(i)?.add(e),()=>this.unsubscribe(i,e)}unsubscribe(i,e){this._subscribers.has(i)&&this._subscribers.get(i)?.delete(e)}_notify(i,e){if(this._subscribers.has(i))for(let t of this._subscribers.get(i)??new Set)try{t(e)}catch(r){this._block.telemetryManager.sendEventError(r,"modal subscriber"),this._debugPrint("Error in modal subscriber:",r)}}destroy(){this.closeAll(),this._modals.clear(),this._subscribers.clear(),this._notify(ge.DESTROY,{})}};function br(s){return s.replace(/[A-Z]/g,i=>`_${i.toLowerCase()}`).replace(/__/g,"_")}function bt(s){return Array.isArray(s)?s.map(i=>typeof i=="object"&&i!==null?bt(i):i):typeof s!="object"||s===null?s:Object.fromEntries(Object.entries(s).map(([i,e])=>{let t=br(i);return typeof e=="object"&&e!==null?[t,bt(e)]:[t,e]}))}function vr(s){return{ok:!0,value:s}}function yt(s){return{ok:!1,error:s}}var _r="https://tlm.uploadcare.com/api/",vt=class{constructor(i=_r){this.baseUrl=i}async base(i,e={}){let t=`${this.baseUrl}${i}`;try{let r=await fetch(t,e);if(!r.ok)return yt(new Error(`Got non-200 response from "${t}". Status: ${r.status.toString()}`));try{let o=await r.json();return vr(o)}catch(o){return yt(new Error(`Error parsing JSON from "${t}". Error: ${o}`))}}catch(r){return yt(new Error(`Error fetching data from "${t}". Error: ${r}`))}}async post(i,e,t={}){return await this.base(i,{...t,method:"POST",body:JSON.stringify(bt(e)),headers:{"Content-Type":"application/json",...t.headers||{}}})}async get(i,e={}){return await this.base(i,{method:"GET",...e})}},Tr=async(s,i)=>({success:!0,data:i}),je=class extends vt{constructor(){super()}async sendEvent(i,e){let t=await Tr(void 0,i);if(!t.success)throw console.error("TelemetryAPIService: events: body is invalid",t.error),new Error("TelemetryAPIService: events: body is invalid");return this.post("v1/events",i,e)}};var ce=s=>s?s.split(",").map(i=>i.trim()).filter(Boolean):[],de=s=>s.join(",");var Zt=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},Ke=(...s)=>s.filter(i=>typeof i=="string"&&!!i).map(i=>Zt(i)).join("/-/"),q=(...s)=>{let i=Ke(...s);return i?`-/${i}/`:""};function He(s){let i=new URL(s),e=i.pathname+i.search+i.hash,t=e.lastIndexOf("http"),r=e.lastIndexOf("/"),o="";return t>=0?o=e.slice(t):r>=0&&(o=e.slice(r+1)),o}function Be(s){let i=new URL(s),{pathname:e}=i,t=e.indexOf("/"),r=e.indexOf("/",t+1);return e.substring(t+1,r)}function _t(s){let i=Jt(s),e=new URL(i),t=e.pathname.indexOf("/-/");return t===-1?"":e.pathname.substring(t).slice(1)}function Tt(s){return _t(s).split("/-/").filter(Boolean).map(e=>Zt(e))}function Jt(s){let i=new URL(s),e=He(s),t=ei(e)?ti(e).pathname:e;return i.pathname=i.pathname.replace(t,""),i.search="",i.hash="",i.toString()}function ei(s){return s.startsWith("http")}function ti(s){let i=new URL(s);return{pathname:`${i.origin}${i.pathname??""}`,search:i.search??"",hash:i.hash??""}}var W=(s,i,e)=>{let t=new URL(Jt(s)),r=e??He(s),o=i??"";if(t.pathname.startsWith("//")&&(t.pathname=t.pathname.replace("//","/")),r&&ei(r)){let n=ti(r);t.pathname=`${t.pathname}${o}${n.pathname||""}`,t.search=n.search,t.hash=n.hash}else t.pathname=`${t.pathname}${o}${r||""}`;return t.toString()},wt=(s,i)=>{let e=new URL(s);return e.pathname=`${i}/`,e.toString()};var ke=(s,i=",")=>s.trim().split(i).map(e=>e.trim()).filter(e=>e.length>0);var Re=Object.freeze({brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0,mirror:!1,flip:!1,crop:void 0}),ri=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function wr(s,i){if(typeof i=="number"){let e=i;return Re[s]!==e?`${s}/${e}`:""}if(typeof i=="boolean"){let e=i;return Re[s]!==e?`${s}`:""}if(s==="filter"&&i){let{name:e,amount:t}=i;return Re.filter===t?"":`${s}/${e}/${t}`}if(s==="crop"&&i){let{dimensions:e,coords:t}=i;return`${s}/${e.join("x")}/${t.join(",")}`}return""}function ie(s){return Ke(...ri.filter(i=>typeof s[i]<"u"&&s[i]!==null).map(i=>{let e=s[i];return wr(i,e)}).filter(i=>!!i))}var Ge=Ke("format/auto","progressive/yes"),Y=([s])=>typeof s<"u"?Number(s):void 0,ii=()=>!0,Cr=([s,i])=>({name:s,amount:typeof i<"u"?Number(i):100}),Er=([s,i])=>{if(!/\d+x\d+/.test(s)||!/\d+,\d+/.test(i))throw new Error("Crop by aspect ratio, percentage or alignment shortcuts is not supported.");return{dimensions:ke(s,"x").map(Number),coords:ke(i).map(Number)}},xr=Object.freeze({enhance:Y,brightness:Y,exposure:Y,gamma:Y,contrast:Y,saturation:Y,vibrance:Y,warmth:Y,filter:Cr,mirror:ii,flip:ii,rotate:Y,crop:s=>{let[i,e]=s,{dimensions:t,coords:r}=Er([i,e]);return{dimensions:t,coords:r}}});function Ct(s){let i={};for(let e of s){let[t,...r]=e.split("/");if(!t||!ri.includes(t))continue;let o=t,n=xr[o];try{let a=n(r);i[o]=a}catch(a){console.warn([`Failed to parse URL operation "${e}". It will be ignored.`,a instanceof Error?`Error message: "${a.message}"`:a,"If you need this functionality, please feel free to open an issue at https://github.com/uploadcare/blocks/issues/new"].join(`
27
- `))}}return i}var E=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),L=Object.freeze([E.CROP,E.TUNING,E.FILTERS]),si=Object.freeze(["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"]),oi=Object.freeze(["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"]),ni=Object.freeze(["rotate","mirror","flip"]),Q=Re,j=Object.freeze({brightness:{zero:Q.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Q.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Q.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Q.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Q.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Q.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Q.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Q.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Q.filter,range:[0,100],keypointsNumber:1}});var Et="https://ucarecdn.com",Sr="https://upload.uploadcare.com",kr="https://social.uploadcare.com",Rr="https://ucarecd.net",Or={pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",externalSourcesEmbedCss:"",store:"auto",cameraMirror:!1,cameraCapture:"",sourceList:"local, url, camera, dropbox, gdrive",topLevelOrigin:"",cloudImageEditorTabs:de(L),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Et,cdnCnamePrefixed:Rr,baseUrl:Sr,socialBaseUrl:kr,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:10,retryNetworkErrorMaxTimes:3,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",debug:!1,metadata:null,localeName:"en",localeDefinitionOverride:null,secureUploadsExpireThreshold:600*1e3,secureUploadsSignatureResolver:null,secureDeliveryProxyUrlResolver:null,iconHrefResolver:null,fileValidators:[],collectionValidators:[],validationTimeout:15*1e3,validationConcurrency:100,cameraModes:"photo, video",defaultCameraMode:null,enableAudioRecording:!0,enableVideoRecording:null,maxVideoRecordingDuration:null,mediaRecorderOptions:null,filesViewMode:"list",gridShowFileNames:!1,cloudImageEditorAutoOpen:!1,cloudImageEditorMaskHref:null,testMode:!1,qualityInsights:!0},N=Object.freeze(Or);var Z=Object.freeze({INIT_SOLUTION:"init-solution",CHANGE_CONFIG:"change-config",ACTION_EVENT:"action-event",ERROR_EVENT:"error-event"}),J=Object.freeze({FILE_ADDED:"file-added",FILE_REMOVED:"file-removed",FILE_UPLOAD_START:"file-upload-start",FILE_UPLOAD_PROGRESS:"file-upload-progress",FILE_UPLOAD_SUCCESS:"file-upload-success",FILE_UPLOAD_FAILED:"file-upload-failed",FILE_URL_CHANGED:"file-url-changed",MODAL_OPEN:"modal-open",MODAL_CLOSE:"modal-close",DONE_CLICK:"done-click",UPLOAD_CLICK:"upload-click",ACTIVITY_CHANGE:"activity-change",COMMON_UPLOAD_START:"common-upload-start",COMMON_UPLOAD_PROGRESS:"common-upload-progress",COMMON_UPLOAD_SUCCESS:"common-upload-success",COMMON_UPLOAD_FAILED:"common-upload-failed",CHANGE:"change",GROUP_CREATED:"group-created"}),Xe=class{constructor(i){this._timeoutStore=new Map;this._targets=new Set;this._debugPrint=null;this._debugPrint=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,e){for(let t of this._targets)t.dispatchEvent(new CustomEvent(i,{detail:e}));this._debugPrint?.(()=>{let t=e&&typeof e=="object"?{...e}:e;return[`event "${i}"`,t]})}emit(i,e,t={}){let{debounce:r}=t;if(typeof r!="number"&&!r){this._dispatch(i,typeof e=="function"?e():e);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let o=typeof r=="number"?r:20,n=window.setTimeout(()=>{this._dispatch(i,typeof e=="function"?e():e),this._timeoutStore.delete(i)},o);this._timeoutStore.set(i,n)}};var ai="1.25.0-alpha.1";var qe="blocks",We=ai;var Ye=class{constructor(i){this._sessionId=crypto.randomUUID();this._config=structuredClone(N);this._initialized=!1;this._lastPayload=null;this._block=i,this._telemetryInstance=new je,this._queue=new De(10);for(let e of Object.keys(this._config))this._block.subConfigValue(e,t=>{this._initialized&&this._config[e]!==t&&this.sendEvent({eventType:Z.CHANGE_CONFIG}),this._setConfig(e,t)})}_init(i){i===Z.INIT_SOLUTION&&!this._initialized&&(this._initialized=!0)}_setConfig(i,e){this._config[i]!==e&&(this._config[i]=e)}_formattingPayload(i){let e=i.payload?{...i.payload}:{};e.activity&&(e.activity=void 0);let t={...i};return(i.eventType===Z.INIT_SOLUTION||i.eventType===Z.CHANGE_CONFIG)&&(t.config=this._config),{...t,appVersion:We,appName:qe,sessionId:this._sessionId,component:this._solution,activity:this._activity,projectPubkey:this._config.pubkey,userAgent:navigator.userAgent,eventType:t.eventType??"",eventTimestamp:this._timestamp,payload:{location:this._location,...e}}}_excludedEvents(i){return!!(i&&[J.CHANGE,J.COMMON_UPLOAD_PROGRESS,J.FILE_ADDED,J.FILE_REMOVED,J.FILE_UPLOAD_START,J.FILE_UPLOAD_PROGRESS,J.FILE_UPLOAD_SUCCESS,J.FILE_UPLOAD_FAILED].includes(i))}sendEvent(i){let e=this._formattingPayload({eventType:i.eventType,payload:i.payload,config:i.config});this._init(i.eventType),!(this._excludedEvents(i.eventType)||this._lastPayload&&this._checkObj(this._lastPayload,e))&&this._queue.add(async()=>{this._lastPayload=e,await this._telemetryInstance.sendEvent(e)})}sendEventError(i,e="unknown"){this.sendEvent({eventType:Z.ERROR_EVENT,payload:{metadata:{event:"error",text:`Error in ${e}`,error:i.message}}})}sendEventCloudImageEditor(i,e,t={}){this.sendEvent({eventType:Z.ACTION_EVENT,payload:{metadata:{tabId:e,node:i.currentTarget?.tagName,event:i.type,...t}}})}_checkObj(i,e){if(JSON.stringify(i)===JSON.stringify(e))return!0;if(typeof i!="object"||typeof e!="object"||i==null||e==null)return!1;let t=Object.keys(i),r=Object.keys(e);if(t.length!==r.length)return!1;for(let o of t)if(!Object.hasOwn(e,o)||!this._checkObj(i[o],e[o]))return!1;return!0}get _timestamp(){return Date.now()}get _solution(){if(!this._block.has("*solution"))return null;let i=this._block.$["*solution"];return i?i.toLowerCase():null}get _activity(){return this._block.has("*currentActivity")?this._block.$["*currentActivity"]??null:null}get _location(){return location.origin}};var k=s=>`*cfg/${s}`;var li=s=>{let i=new Intl.Locale(s),e="ltr",t=i.getTextInfo?.().direction;return t?e=t:i.textInfo?.direction&&(e=i.textInfo.direction),e};var ci=(s,i)=>new Intl.PluralRules(s).select(i);var Ir=s=>s;var di="plural:";function xt(s,i={},e={}){let{openToken:t="{{",closeToken:r="}}",transform:o=Ir}=e;for(let n in i){let a=i[n],l=a?.toString(),d=typeof l=="string"?o(l):String(l);s=s.replaceAll(t+n+r,d)}return s}function ui(s){let i=[],e=s.indexOf("{{");for(;e!==-1;){let t=s.indexOf("}}",e);if(t===-1)break;let r=s.substring(e+2,t);if(r.startsWith(di)){let o=s.substring(e+2,t).replace(di,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));i.push({variable:r,pluralKey:n,countVariable:a})}e=s.indexOf("{{",t)}return i}function M(s,i){let e,t=((...r)=>{e&&clearTimeout(e),e=setTimeout(()=>s(...r),i)});return t.cancel=()=>{e&&clearTimeout(e)},t}var hi="--uploadcare-blocks-window-height",Oe=class s{static{this.clientsRegistry=new Set}static{this.flush=M(()=>{document.documentElement.style.setProperty(hi,`${window.innerHeight}px`)},100)}static registerClient(i){s.clientsRegistry.size===0&&s.attachTracker(),s.clientsRegistry.add(i)}static unregisterClient(i){s.clientsRegistry.delete(i),s.clientsRegistry.size===0&&s.detachTracker()}static attachTracker(){window.addEventListener("resize",s.flush,{passive:!0,capture:!0}),s.flush()}static detachTracker(){window.removeEventListener("resize",s.flush,{capture:!0}),document.documentElement.style.removeProperty(hi)}};var Pr=/\\([0-9a-fA-F]{1,6} ?)/g;function Lr(s){return s.length<2?!1:(s[0]==='"'||s[0]==="'")&&(s[s.length-1]==='"'||s[s.length-1]==="'")}function Mr(s){let i=s;return(i[0]==='"'||i[0]==="'")&&(i=i.slice(1)),(i[i.length-1]==='"'||i[i.length-1]==="'")&&(i=i.slice(0,-1)),i}function $r(s){let i="",e="";for(let t=0;t<s.length;t++){let r=s[t+1];s[t]==="\\"&&r==='"'?(i+='\\"',t++):s[t]==='"'&&e!=="\\"?i+='\\"':i+=s[t],e=s[t]??""}return i}function pi(s){let i=s;Lr(s)&&(i=Mr(i),i=i.replace(Pr,(e,t)=>String.fromCodePoint(parseInt(t.trim(),16))),i=i.replaceAll(`\\
27
+ `))}}return i}var E=Object.freeze({CROP:"crop",TUNING:"tuning",FILTERS:"filters"}),L=Object.freeze([E.CROP,E.TUNING,E.FILTERS]),si=Object.freeze(["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"]),oi=Object.freeze(["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"]),ni=Object.freeze(["rotate","mirror","flip"]),Q=Re,j=Object.freeze({brightness:{zero:Q.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Q.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Q.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Q.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Q.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Q.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Q.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Q.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Q.filter,range:[0,100],keypointsNumber:1}});var Et="https://ucarecdn.com",Sr="https://upload.uploadcare.com",kr="https://social.uploadcare.com",Rr="https://ucarecd.net",Or={pubkey:"",multiple:!0,multipleMin:0,multipleMax:Number.MAX_SAFE_INTEGER,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",externalSourcesEmbedCss:"",store:"auto",cameraMirror:!1,cameraCapture:"",sourceList:"local, url, camera, dropbox, gdrive",topLevelOrigin:"",cloudImageEditorTabs:de(L),maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",imageShrink:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Et,cdnCnamePrefixed:Rr,baseUrl:Sr,socialBaseUrl:kr,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:10,retryNetworkErrorMaxTimes:3,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",debug:!1,metadata:null,localeName:"en",localeDefinitionOverride:null,secureUploadsExpireThreshold:600*1e3,secureUploadsSignatureResolver:null,secureDeliveryProxyUrlResolver:null,iconHrefResolver:null,fileValidators:[],collectionValidators:[],validationTimeout:15*1e3,validationConcurrency:100,cameraModes:"photo, video",defaultCameraMode:null,enableAudioRecording:!0,enableVideoRecording:null,maxVideoRecordingDuration:null,mediaRecorderOptions:null,filesViewMode:"list",gridShowFileNames:!1,cloudImageEditorAutoOpen:!1,cloudImageEditorMaskHref:null,testMode:!1,qualityInsights:!0},N=Object.freeze(Or);var Z=Object.freeze({INIT_SOLUTION:"init-solution",CHANGE_CONFIG:"change-config",ACTION_EVENT:"action-event",ERROR_EVENT:"error-event"}),J=Object.freeze({FILE_ADDED:"file-added",FILE_REMOVED:"file-removed",FILE_UPLOAD_START:"file-upload-start",FILE_UPLOAD_PROGRESS:"file-upload-progress",FILE_UPLOAD_SUCCESS:"file-upload-success",FILE_UPLOAD_FAILED:"file-upload-failed",FILE_URL_CHANGED:"file-url-changed",MODAL_OPEN:"modal-open",MODAL_CLOSE:"modal-close",DONE_CLICK:"done-click",UPLOAD_CLICK:"upload-click",ACTIVITY_CHANGE:"activity-change",COMMON_UPLOAD_START:"common-upload-start",COMMON_UPLOAD_PROGRESS:"common-upload-progress",COMMON_UPLOAD_SUCCESS:"common-upload-success",COMMON_UPLOAD_FAILED:"common-upload-failed",CHANGE:"change",GROUP_CREATED:"group-created"}),Xe=class{constructor(i){this._timeoutStore=new Map;this._targets=new Set;this._debugPrint=null;this._debugPrint=i}bindTarget(i){this._targets.add(i)}unbindTarget(i){this._targets.delete(i)}_dispatch(i,e){for(let t of this._targets)t.dispatchEvent(new CustomEvent(i,{detail:e}));this._debugPrint?.(()=>{let t=e&&typeof e=="object"?{...e}:e;return[`event "${i}"`,t]})}emit(i,e,t={}){let{debounce:r}=t;if(typeof r!="number"&&!r){this._dispatch(i,typeof e=="function"?e():e);return}this._timeoutStore.has(i)&&window.clearTimeout(this._timeoutStore.get(i));let o=typeof r=="number"?r:20,n=window.setTimeout(()=>{this._dispatch(i,typeof e=="function"?e():e),this._timeoutStore.delete(i)},o);this._timeoutStore.set(i,n)}};var ai="1.25.0-alpha.2";var qe="blocks",We=ai;var Ye=class{constructor(i){this._sessionId=crypto.randomUUID();this._config=structuredClone(N);this._initialized=!1;this._lastPayload=null;this._block=i,this._telemetryInstance=new je,this._queue=new De(10);for(let e of Object.keys(this._config))this._block.subConfigValue(e,t=>{this._initialized&&this._config[e]!==t&&this.sendEvent({eventType:Z.CHANGE_CONFIG}),this._setConfig(e,t)})}_init(i){i===Z.INIT_SOLUTION&&!this._initialized&&(this._initialized=!0)}_setConfig(i,e){this._config[i]!==e&&(this._config[i]=e)}_formattingPayload(i){let e=i.payload?{...i.payload}:{};e.activity&&(e.activity=void 0);let t={...i};return(i.eventType===Z.INIT_SOLUTION||i.eventType===Z.CHANGE_CONFIG)&&(t.config=this._config),{...t,appVersion:We,appName:qe,sessionId:this._sessionId,component:this._solution,activity:this._activity,projectPubkey:this._config.pubkey,userAgent:navigator.userAgent,eventType:t.eventType??"",eventTimestamp:this._timestamp,payload:{location:this._location,...e}}}_excludedEvents(i){return!!(i&&[J.CHANGE,J.COMMON_UPLOAD_PROGRESS,J.FILE_ADDED,J.FILE_REMOVED,J.FILE_UPLOAD_START,J.FILE_UPLOAD_PROGRESS,J.FILE_UPLOAD_SUCCESS,J.FILE_UPLOAD_FAILED].includes(i))}sendEvent(i){let e=this._formattingPayload({eventType:i.eventType,payload:i.payload,config:i.config});this._init(i.eventType),!(this._excludedEvents(i.eventType)||this._lastPayload&&this._checkObj(this._lastPayload,e))&&this._queue.add(async()=>{this._lastPayload=e,await this._telemetryInstance.sendEvent(e)})}sendEventError(i,e="unknown"){this.sendEvent({eventType:Z.ERROR_EVENT,payload:{metadata:{event:"error",text:`Error in ${e}`,error:i.message}}})}sendEventCloudImageEditor(i,e,t={}){this.sendEvent({eventType:Z.ACTION_EVENT,payload:{metadata:{tabId:e,node:i.currentTarget?.tagName,event:i.type,...t}}})}_checkObj(i,e){if(JSON.stringify(i)===JSON.stringify(e))return!0;if(typeof i!="object"||typeof e!="object"||i==null||e==null)return!1;let t=Object.keys(i),r=Object.keys(e);if(t.length!==r.length)return!1;for(let o of t)if(!Object.hasOwn(e,o)||!this._checkObj(i[o],e[o]))return!1;return!0}get _timestamp(){return Date.now()}get _solution(){if(!this._block.has("*solution"))return null;let i=this._block.$["*solution"];return i?i.toLowerCase():null}get _activity(){return this._block.has("*currentActivity")?this._block.$["*currentActivity"]??null:null}get _location(){return location.origin}};var k=s=>`*cfg/${s}`;var li=s=>{let i=new Intl.Locale(s),e="ltr",t=i.getTextInfo?.().direction;return t?e=t:i.textInfo?.direction&&(e=i.textInfo.direction),e};var ci=(s,i)=>new Intl.PluralRules(s).select(i);var Ir=s=>s;var di="plural:";function xt(s,i={},e={}){let{openToken:t="{{",closeToken:r="}}",transform:o=Ir}=e;for(let n in i){let a=i[n],l=a?.toString(),d=typeof l=="string"?o(l):String(l);s=s.replaceAll(t+n+r,d)}return s}function ui(s){let i=[],e=s.indexOf("{{");for(;e!==-1;){let t=s.indexOf("}}",e);if(t===-1)break;let r=s.substring(e+2,t);if(r.startsWith(di)){let o=s.substring(e+2,t).replace(di,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));i.push({variable:r,pluralKey:n,countVariable:a})}e=s.indexOf("{{",t)}return i}function M(s,i){let e,t=((...r)=>{e&&clearTimeout(e),e=setTimeout(()=>s(...r),i)});return t.cancel=()=>{e&&clearTimeout(e)},t}var hi="--uploadcare-blocks-window-height",Oe=class s{static{this.clientsRegistry=new Set}static{this.flush=M(()=>{document.documentElement.style.setProperty(hi,`${window.innerHeight}px`)},100)}static registerClient(i){s.clientsRegistry.size===0&&s.attachTracker(),s.clientsRegistry.add(i)}static unregisterClient(i){s.clientsRegistry.delete(i),s.clientsRegistry.size===0&&s.detachTracker()}static attachTracker(){window.addEventListener("resize",s.flush,{passive:!0,capture:!0}),s.flush()}static detachTracker(){window.removeEventListener("resize",s.flush,{capture:!0}),document.documentElement.style.removeProperty(hi)}};var Pr=/\\([0-9a-fA-F]{1,6} ?)/g;function Lr(s){return s.length<2?!1:(s[0]==='"'||s[0]==="'")&&(s[s.length-1]==='"'||s[s.length-1]==="'")}function Mr(s){let i=s;return(i[0]==='"'||i[0]==="'")&&(i=i.slice(1)),(i[i.length-1]==='"'||i[i.length-1]==="'")&&(i=i.slice(0,-1)),i}function $r(s){let i="",e="";for(let t=0;t<s.length;t++){let r=s[t+1];s[t]==="\\"&&r==='"'?(i+='\\"',t++):s[t]==='"'&&e!=="\\"?i+='\\"':i+=s[t],e=s[t]??""}return i}function pi(s){let i=s;Lr(s)&&(i=Mr(i),i=i.replace(Pr,(e,t)=>String.fromCodePoint(parseInt(t.trim(),16))),i=i.replaceAll(`\\
28
28
  `,"\\n"),i=$r(i),i='"'+i+'"');try{return JSON.parse(i)}catch{return}}function fi(s){class i extends s{constructor(){super(...arguments);this.cssDataCache=null;this.computedStyle=null}getCssData(r,o=!1){let n=this.cssDataCache??Object.create(null);if(!Object.keys(n).includes(r)||!n[r]){this.computedStyle||(this.computedStyle=window.getComputedStyle(this));let a=this.computedStyle.getPropertyValue(r).trim();try{n[r]=pi(a)}catch(l){o||console.warn(`CSS Data error: ${r}`,l),n[r]=null}}return this.cssDataCache=n,n[r]}}return i}function mi(s){class i extends s{constructor(){super(...arguments);this.__slots={};this.__willYield=!0;this.__initialLightDomChildren=null;this.__hasAdoptedChildren=!1}createRenderRoot(){return this}connectedCallback(){this.__initialLightDomChildren||(this.__initialLightDomChildren=Array.from(this.childNodes)),super.connectedCallback()}__adoptChildren(){if(this.__hasAdoptedChildren)return;this.__hasAdoptedChildren=!0,this.__slots={};let r=Array.from(this.childNodes),o=r.length?r:this.__initialLightDomChildren??[];for(let n of o){let a=this.__getSlotNameForChild(n),l=this.__slots[a]??[];n instanceof Element&&(n.removeAttribute("slot"),n.removeAttribute("content-for")),l.push(n),this.__slots[a]=l}this.__initialLightDomChildren=null}__getSlotNameForChild(r){return r instanceof Comment&&r.nextSibling instanceof Element?this.__getSlotNameForChild(r.nextSibling):"contentFor"in r?r.contentFor||"":r instanceof Element&&r.hasAttribute("content-for")&&r.getAttribute("content-for")||""}__isTextNodeEmpty(r){return!r.textContent||!r.textContent.trim()}__isSlotEmpty(r){let o=this.__slots[r];return!o||o.every(n=>n instanceof Comment||n instanceof Text&&this.__isTextNodeEmpty(n))}update(r){!this.hasUpdated&&this.__willYield&&this.__adoptChildren(),super.update(r)}yield(r,o){if(r===""&&!this.__slots[r]&&!this.__hasAdoptedChildren&&this.__initialLightDomChildren?.length){let a=[];for(let l of this.__initialLightDomChildren)l instanceof Element&&(l.removeAttribute("slot"),l.removeAttribute("content-for")),a.push(l);this.__slots[r]=a,this.__hasAdoptedChildren=!0,this.__initialLightDomChildren=null}let n=this.__slots[r];return m.html`
29
29
  ${n}
30
30
  ${this.__isSlotEmpty(r)?o:void 0}
31
31
  `}}return i}function gi(s){class i extends s{static reg(t){let r=this,o=window.customElements.get(t);if(o){o!==r&&console.warn([`Element with tag name "${t}" 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(`
32
- `));return}window.customElements.define(t,r)}}return i}var re=class extends Event{constructor(i,e,t,r){super("context-request",{bubbles:!0,composed:!0}),this.context=i,this.contextTarget=e,this.callback=t,this.subscribe=r??!1}};var ye=class{constructor(i,e,t,r){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(o,n)=>{this.unsubscribe&&(this.unsubscribe!==n&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=o,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(o,n)),this.unsubscribe=n},this.host=i,e.context!==void 0){let o=e;this.context=o.context,this.callback=o.callback,this.subscribe=o.subscribe??!1}else this.context=e,this.callback=t,this.subscribe=r??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new re(this.context,this.host,this.t,this.subscribe))}};var Qe=class{get value(){return this.o}set value(i){this.setValue(i)}setValue(i,e=!1){let t=e||!Object.is(i,this.o);this.o=i,t&&this.updateObservers()}constructor(i){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:t}]of this.subscriptions)e(this.o,t)},i!==void 0&&(this.value=i)}addCallback(i,e,t){if(!t)return void i(this.value);this.subscriptions.has(i)||this.subscriptions.set(i,{disposer:()=>{this.subscriptions.delete(i)},consumerHost:e});let{disposer:r}=this.subscriptions.get(i);i(this.value,r)}clearCallbacks(){this.subscriptions.clear()}};var St=class extends Event{constructor(i,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=i,this.contextTarget=e}},be=class extends Qe{constructor(i,e,t){super(e.context!==void 0?e.initialValue:t),this.onContextRequest=r=>{if(r.context!==this.context)return;let o=r.contextTarget??r.composedPath()[0];o!==this.host&&(r.stopPropagation(),this.addCallback(r.callback,o,r.subscribe))},this.onProviderRequest=r=>{if(r.context!==this.context||(r.contextTarget??r.composedPath()[0])===this.host)return;let o=new Set;for(let[n,{consumerHost:a}]of this.subscriptions)o.has(n)||(o.add(n),a.dispatchEvent(new re(this.context,a,n,!0)));r.stopPropagation()},this.host=i,e.context!==void 0?this.context=e.context:this.context=e,this.attachListeners(),this.host.addController?.(this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new St(this.context,this.host))}};var yi="ctx-name-context";function bi(s){class i extends s{constructor(...r){super(...r);this._symbioteSharedPubSub=null;this._symbioteFirstUpdated=!1;this._needsReconnectInit=!1;this._ctxNameProvider=void 0;this._warnedAboutLocalState=!1;this._pendingSharedAdds=new Map;this.init$={};this.ctxOwner=!1;this._ctxNameAttr=void 0;this._pendingCtxInitOnConnect=!1;this.ctxName=this.effectiveCtxName;this.isInitialized=!1;this._ctxNameAttr=this.getAttribute("ctx-name")||void 0,this.ctxName=this.effectiveCtxName,this._ctxNameConsumer=new ye(this,{context:yi,callback:o=>{if(!o){console.error("SymbioteMixin: Received invalid ctx-name from context");return}this._ctxNameFromContext=o,this._handleCtxNameSourceChange()},subscribe:!0})}get ctxNameAttr(){return this._ctxNameAttr}set ctxNameAttr(r){let o=r??void 0;this._ctxNameAttr!==o&&(this._ctxNameAttr=o,this._handleCtxNameSourceChange())}shouldUpdate(r){return this.isInitialized?super.shouldUpdate(r):!1}get effectiveCtxName(){return this.ctxNameAttr||this._ctxNameFromContext||void 0}_handleCtxNameSourceChange(){if(this.ctxName=this.effectiveCtxName,!(!this.ctxName||this._symbioteFirstUpdated)){if(this.isConnected){this._performInitialization();return}this._pendingCtxInitOnConnect=!0}}willUpdate(r){super.willUpdate(r),this.ctxName=this.effectiveCtxName,this.ctxName&&(this._ctxNameProvider?this._ctxNameProvider.setValue(this.ctxName):this._ctxNameProvider=new be(this,{context:yi,initialValue:this.ctxName}))}_getSharedInitEntries(){let r=Object.entries(this.init$||{}),o=[],n=[];for(let[a,l]of r)a.startsWith("*")?o.push([a,l]):n.push(a);return n.length>0&&!this._warnedAboutLocalState&&(console.warn("SymbioteMixin: Local state entries are no longer supported and will be ignored:",n),this._warnedAboutLocalState=!0),o}_getSharedInitSchema(){return Object.fromEntries(this._getSharedInitEntries())}_ensureSharedSchema(){if(!Object.hasOwn(this,"_sharedSchema")){let r=Object.fromEntries(this._getSharedInitEntries().map(([o,n])=>[o.slice(1),n]));Object.defineProperty(this,"_sharedSchema",{value:r,writable:!0,configurable:!0})}}_getSharedSchemaRecord(){return this._ensureSharedSchema(),this._sharedSchema??{}}_requireSharedKey(r){if(!r.startsWith("*"))throw new Error(`SymbioteMixin: Local state key "${r}" is no longer supported. Use shared keys prefixed with "*".`);return r.slice(1)}_applyPendingSharedAdds(){if(!(!this._symbioteSharedPubSub||this._pendingSharedAdds.size===0)){for(let[r,{value:o,rewrite:n}]of this._pendingSharedAdds)this._symbioteSharedPubSub.add(r,o,n);this._pendingSharedAdds.clear()}}_getSharedPubSub(){return!this._symbioteSharedPubSub&&this.effectiveCtxName&&this._initSharedContext(),this._symbioteSharedPubSub&&this._applyPendingSharedAdds(),this._symbioteSharedPubSub}_requireSharedPubSub(){let r=this._getSharedPubSub();if(!r)throw new Error("SymbioteMixin: Shared context is not initialized.");return r}_initSharedContext(){let r=this._getSharedSchemaRecord(),o=this.effectiveCtxName;if(!o){console.error("SymbioteMixin: ctx-name is required for components with shared properties (*)");return}if(!this._symbioteSharedPubSub){this._symbioteSharedPubSub=X.getCtx(o,!1),this._symbioteSharedPubSub||(this._symbioteSharedPubSub=X.registerCtx(r,o));for(let[n,a]of Object.entries(r))this._symbioteSharedPubSub.add(n,a,this.ctxOwner);this._applyPendingSharedAdds()}}get sharedCtx(){return this._requireSharedPubSub()}get $(){return this.effectiveCtxName&&this._initSharedContext(),new Proxy({},{get:(r,o)=>{if(typeof o!="string")return;let n=this._requireSharedKey(o);return this._symbioteSharedPubSub?.read(n)},set:(r,o,n)=>{if(typeof o!="string")return!0;let a=this._requireSharedKey(o);return this._symbioteSharedPubSub?.pub(a,n),!0}})}sub(r,o,n=!0){let a=this._requireSharedKey(r),l=this._requireSharedPubSub().sub(a,o,n);return l?l.remove:()=>{}}pub(r,o){let n=this._requireSharedKey(r);this._requireSharedPubSub().pub(n,o)}set$(r){for(let[o,n]of Object.entries(r))this.pub(o,n)}has(r){let o=this._requireSharedKey(r);return this._symbioteSharedPubSub?.has(o)??!1}add(r,o,n=!1){let a=this._requireSharedKey(r),l=this._getSharedPubSub();if(!l){if(!n&&this._pendingSharedAdds.has(a))return;this._pendingSharedAdds.set(a,{value:o,rewrite:n});return}this._pendingSharedAdds.delete(a),l.add(a,o,n)}add$(r,o=!1){for(let[n,a]of Object.entries(r))this.add(n,a,o)}connectedCallback(){super.connectedCallback(),this._symbioteFirstUpdated?this.isInitialized&&this._needsReconnectInit&&(this._needsReconnectInit=!1,this.initCallback()):this.ctxName?(this._pendingCtxInitOnConnect=!1,this._performInitialization()):this._pendingCtxInitOnConnect&&this.effectiveCtxName&&(this._pendingCtxInitOnConnect=!1,this._performInitialization())}_performInitialization(){if(this._symbioteFirstUpdated)return;this._symbioteFirstUpdated=!0,this._initSharedContext();let r=this._getSharedInitSchema();if(Object.keys(r).length>0){let o=this._requireSharedPubSub();for(let[n,a]of Object.entries(r)){let l=this._requireSharedKey(n);o.read(l)===void 0&&o.pub(l,a),this.sub(n,M(async()=>{await this.updateComplete,this.requestUpdate()},0),!1)}}this.initCallback(),this.isInitialized=!0,this.requestUpdate()}firstUpdated(r){super.firstUpdated(r)}updated(r){super.updated(r);let o=this._getSharedInitSchema();Object.keys(o).length>0&&r.forEach((n,a)=>{if(typeof a=="string"&&Object.hasOwn(o,a)){let l=this._requireSharedKey(a),d=this[a],f=this._symbioteSharedPubSub;f&&f.read(l)!==d&&f.pub(l,d)}})}disconnectedCallback(){super.disconnectedCallback(),this._symbioteFirstUpdated&&(this._needsReconnectInit=!0)}initCallback(){}}return p([(0,c.property)({type:String,attribute:"ctx-name",noAccessor:!0})],i.prototype,"ctxNameAttr",1),p([(0,c.state)()],i.prototype,"_ctxNameFromContext",2),p([(0,c.state)()],i.prototype,"ctxName",2),p([(0,c.state)()],i.prototype,"isInitialized",2),i}var Dr=s=>s.tagName?.includes("-")??!1,Ze=class{constructor(i){this.host=i;this.trackedElements=new Set;this.originalValues=new Map;this.enabled=!1;this.host.addController(this)}hostDisconnected(){this.unsubscribe?.(),this.unsubscribe=void 0,this.trackedElements.clear(),this.originalValues.clear()}hostUpdated(){if(!this.unsubscribe&&this.host.has(k("testMode"))){let i=this.host.subConfigValue("testMode",e=>{this.enabled=!!e,this.applyTestMode()});this.unsubscribe=i}this.collectElements(),this.applyTestMode()}collectElements(){let i=this.host,e=i.renderRoot??i;if(!e)return;let t=this.host,r=t.tagName?.toLowerCase(),o=Array.from(e.querySelectorAll("[data-testid]")).filter(n=>!Dr(n));for(let n of o)if(!(r&&n.closest(r)!==t)&&!this.trackedElements.has(n)){let a=n.getAttribute("data-testid");if(!a)continue;this.trackedElements.add(n),this.originalValues.set(n,a)}for(let n of Array.from(this.trackedElements))(!n.isConnected||r&&n.closest(r)!==t)&&(this.trackedElements.delete(n),this.originalValues.delete(n))}applyTestMode(){if(!this.trackedElements.size)return;let i=this.host.testId||"";for(let e of this.trackedElements){let t=this.originalValues.get(e);t&&(this.enabled?e.setAttribute("data-testid",`${i}--${t}`):e.removeAttribute("data-testid"))}}};var Ur=gi(bi(fi(mi(m.LitElement)))),T=class extends Ur{constructor(){super();this.activityType=null;this.init$=Ht();new Ze(this)}static{this.styleAttrs=[]}l10n(e,t={}){if(!e)return"";let r=this.$[te(e)]||e,o=ui(r);for(let a of o)t[a.variable]=this.pluralize(a.pluralKey,Number(t[a.countVariable]));return xt(r,t)}pluralize(e,t){let r=this.l10n("locale-id")||"en",o=ci(r,t);return this.l10n(`${e}__${o}`)}emit(e,t,r){let o=this.has("*eventEmitter")?this.$["*eventEmitter"]:void 0;if(!o)return;o.emit(e,t,r);let n=typeof t=="function"?t():t;this.telemetryManager.sendEvent({eventType:e,payload:n??void 0})}hasBlockInCtx(e){for(let t of this.blocksRegistry)if(e(t))return!0;return!1}setOrAddState(e,t){this.add$({[e]:t},!0)}connectedCallback(){this.constructor.styleAttrs.forEach(t=>{this.setAttribute(t,"")}),super.connectedCallback(),Oe.registerClient(this)}initCallback(){this.has("*blocksRegistry")||this.add("*blocksRegistry",new Set),this.$["*blocksRegistry"].add(this),this.has("*eventEmitter")||this.add("*eventEmitter",new Xe(this.debugPrint.bind(this))),this.has("*localeManager")||this.add("*localeManager",new Ve(this)),this.cfg.qualityInsights&&!this.has("*telemetryManager")&&this.add("*telemetryManager",new Ye(this)),this.has("*a11y")||this.add("*a11y",new Ue),this.has("*modalManager")||this.add("*modalManager",new ze(this)),this.sub(te("locale-id"),t=>{let r=li(t);this.style.direction=r==="ltr"?"":r,this.requestUpdate()}),this.subConfigValue("testMode",t=>{if(!t||!this.testId){this.removeAttribute("data-testid");return}this.setAttribute("data-testid",this.testId)})}get testId(){return window.customElements.getName(this.constructor)}get modalManager(){return this.has("*modalManager")?this.$["*modalManager"]:void 0}get telemetryManager(){return this.cfg.qualityInsights?this.has("*telemetryManager")&&this.$["*telemetryManager"]:{sendEvent:()=>{},sendEventCloudImageEditor:()=>{},sendEventError:()=>{}}}get localeManager(){return this.has("*localeManager")?this.$["*localeManager"]:null}get a11y(){return this.has("*a11y")?this.$["*a11y"]:null}get blocksRegistry(){return this.$["*blocksRegistry"]}disconnectedCallback(){super.disconnectedCallback(),Oe.unregisterClient(this);let e=this.blocksRegistry;e?.delete(this),e?.size===0&&setTimeout(()=>{this.destroyCtxCallback()},0)}destroyCtxCallback(){X.deleteCtx(this.ctxName),this.modalManager?.destroy()}async proxyUrl(e){if(this.cfg.secureDeliveryProxy&&this.cfg.secureDeliveryProxyUrlResolver&&console.warn("Both secureDeliveryProxy and secureDeliveryProxyUrlResolver are set. The secureDeliveryProxyUrlResolver will be used."),this.cfg.secureDeliveryProxyUrlResolver)try{return await this.cfg.secureDeliveryProxyUrlResolver(e,{uuid:Be(e),cdnUrlModifiers:_t(e),fileName:He(e)})}catch(t){return console.error("Failed to resolve secure delivery proxy URL. Falling back to the default URL.",t),this.telemetryManager.sendEventError(t,"secureDeliveryProxyUrlResolver. Failed to resolve secure delivery proxy URL. Falling back to the default URL."),e}return this.cfg.secureDeliveryProxy?xt(this.cfg.secureDeliveryProxy,{previewUrl:e},{transform:t=>window.encodeURIComponent(t)}):e}get cfg(){if(!this.__cfgProxy){let e={};this.__cfgProxy=new Proxy(e,{set:(t,r,o)=>{if(typeof r!="string"||!(r in N))return!1;let n=r,a=k(n);return this.has(a)||this.add(a,N[n]),this.$[a]=o,!0},get:(t,r)=>{let o=k(r);return this.has(o)||this.add(o,N[r]),this.$[o]}})}return this.__cfgProxy}subConfigValue(e,t){let r=k(e);return this.has(r)||this.add(r,N[e]),this.sub(r,t)}debugPrint(...e){if(!this.cfg.debug)return;let t=e;if(typeof e?.[0]=="function"){let r=e[0];t=r()}console.log(`[${this.ctxName}]`,...t)}};var se="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";function vi(...s){return s.reduce((i,e)=>{if(typeof e=="string")return i[e]=!0,i;for(let t of Object.keys(e))i[t]=e[t];return i},{})}function U(...s){let i=vi(...s);return Object.keys(i).reduce((e,t)=>(i[t]&&e.push(t),e),[]).join(" ")}function _i(s,...i){let e=vi(...i);for(let t of Object.keys(e))s.classList.toggle(t,!!e[t])}var Ae=["free"],Ti=s=>{let i=ke(s);if(!i||i.length===0)return[];let e=[];for(let t of i){let r=t.trim();if(!r)continue;let o=r.indexOf(":");if(o===-1&&!Ae.includes(r)){console.warn(`Invalid crop preset: ${r}`);continue}let n=Number(r.slice(0,o)),a=Number(r.slice(o+1));if((!Number.isFinite(n)||!Number.isFinite(a)||n<=0||a<=0)&&!Ae.includes(r)){console.warn(`Invalid crop preset: ${r}`);continue}e.push({id:me.generate(),type:"aspect-ratio",width:Ae.includes(r)?0:n,height:Ae.includes(r)?0:a,hasFreeform:Ae.includes(r)})}return e},wi=(s,i,e,t=.1)=>{let r=s/i,o=null,n=1/0;for(let a of e){let[l,d]=[a.width,a.height],f=l/d,h=Math.abs(r-f);h<n&&(n=h,o=a)}if(o){let[a,l]=[o.width,o.height],d=a/l;if(Math.abs(r-d)/d>t)return null}return o};var Fr=s=>L.includes(s),Ci=s=>{if(!s)return L;let i=ce(s).filter(Fr);return i.length===0?L:i};function Ei(s){return{"*originalUrl":null,"*loadingOperations":new Map,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*currentAspectRatio":null,"*tabList":L,"*tabId":E.CROP,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let e of i){let t=e.src;e.src=se,e.src=t}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let e=s.$["*originalUrl"],t=q(ie(i),"preview"),r=W(e,t),o={originalUrl:e,cdnUrlModifiers:t,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:o,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var xi="<svg width='0' height='0' style='position:absolute'><symbol fill='none' viewBox='0 0 9 6' id='uc-icon-arrow-dropdown' xmlns='http://www.w3.org/2000/svg'><path stroke='currentColor' d='m1.5 1.667 3 2.666 3-2.666' opacity='.5'/></symbol><symbol viewBox='0 0 24 24' id='uc-icon-aspect-ratio' xmlns='http://www.w3.org/2000/svg'/><symbol viewBox='0 0 20 20' id='uc-icon-brightness' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M15 10a5 5 0 0 1-5 5m5-5a5 5 0 0 0-5-5m5 5h-5m0 5a5 5 0 0 1 0-10m0 10V5m0 15v-3M2.93 2.929 5.05 5.05M0 10h3m-.07 7.071 2.12-2.121M10 0v3m7.07 14.071-2.12-2.121M20 10h-3m.07-7.071L14.95 5.05m-.626 2.45H10m4.324 5H10'/></symbol><symbol fill='currentColor' viewBox='0 0 20 20' id='uc-icon-closeMax' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' d='M8.232 10 3.585 5.353l1.768-1.768L10 8.232l4.648-4.647 1.767 1.768L11.768 10l4.647 4.648-1.767 1.767L10 11.768l-4.647 4.647-1.768-1.767L8.232 10Z' clip-rule='evenodd'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-contrast' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M2 10a8 8 0 1 0 16 0 8 8 0 1 0-16 0m8-8v16m8-8h-8m7.598 2.5H10m6.24 2.5H10m7.6-7.5H10M16.242 5H10'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-crop' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M20 14H7.005C6.45 14 6 13.55 6 12.995V0M0 6h13.067c.515 0 .933.418.933.933V20M14.5.4 13 2l1.5 1.6M13 2h2a3 3 0 0 1 3 3v2M5.5 19.6 7 18l-1.5-1.6M7 18H5a3 3 0 0 1-3-3v-2'/></symbol><symbol fill='currentColor' viewBox='0 0 20 20' id='uc-icon-done' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' d='m18.057 6.333-9.365 9.125a1.25 1.25 0 0 1-1.768-.023L1.92 10.296l1.791-1.744 4.132 4.243 8.47-8.253 1.744 1.79Z' clip-rule='evenodd'/></symbol><symbol fill='currentColor' viewBox='0 0 25 24' id='uc-icon-edit-file' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' d='M18.558 2.804a.78.78 0 0 0-.557.235l-.008.007-2.472 2.46 3.847 3.848 2.46-2.473.004-.003a.78.78 0 0 0 0-1.108l-.004-.003-2.712-2.728a.78.78 0 0 0-.558-.235Zm-.248 7.613-3.852-3.852-8.93 8.887-1.516 5.41 5.41-1.515 8.888-8.93Zm-.636-8.934a2.28 2.28 0 0 1 2.512.505l2.702 2.717.002.002a2.278 2.278 0 0 1 0 3.234l-.002.002-12.541 12.602a.75.75 0 0 1-.33.193l-6.884 1.928a.75.75 0 0 1-.925-.924l1.928-6.885a.75.75 0 0 1 .193-.33l12.603-12.54a2.28 2.28 0 0 1 .742-.504Z' clip-rule='evenodd'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-enhance' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M19 13h-2m0 0a4 4 0 0 1-4-4m4 4a4 4 0 0 0-4 4m0-8V7m0 2a4 4 0 0 1-4 4m-2 0h2m0 0a4 4 0 0 1 4 4m0 0v2M8 8.5H6.5m0 0a2 2 0 0 1-2-2m2 2a2 2 0 0 0-2 2m0-4V5m0 1.5a2 2 0 0 1-2 2M1 8.5h1.5m0 0a2 2 0 0 1 2 2m0 0V12M12 3h-1m0 0a1 1 0 0 1-1-1m1 1a1 1 0 0 0-1 1m0-2V1m0 1a1 1 0 0 1-1 1M8 3h1m0 0a1 1 0 0 1 1 1m0 0v1'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-exposure' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M10 20v-3M2.93 2.929 5.05 5.05M0 10h3m-.07 7.071 2.12-2.121M10 0v3m7.07 14.071-2.12-2.121M20 10h-3m.07-7.071L14.95 5.05M5 10a5 5 0 1 0 10 0 5 5 0 1 0-10 0'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-filters' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M4.5 6.5a5.5 5.5 0 1 0 11 0 5.5 5.5 0 1 0-11 0m-3.5 6a5.5 5.5 0 1 0 11 0 5.5 5.5 0 1 0-11 0m7 0a5.5 5.5 0 1 0 11 0 5.5 5.5 0 1 0-11 0'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-flip' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M19.6 5 18 3.5 16.4 5m3.2 10L18 16.5 16.4 15M18 3.523v12.954M3.3 8.5h10.654c.301 0 .415-.395.159-.554L3.459 1.286A.3.3 0 0 0 3 1.542V8.2a.3.3 0 0 0 .3.3zm0 3h10.654c.301 0 .415.395.159.554l-10.654 6.66A.3.3 0 0 1 3 18.458v-6.66a.3.3 0 0 1 .3-.3z'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-gamma' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M17 3C9 6 2.5 11.5 2.5 17.5m0 0h1m-1 0v-1m14 1h1m-3 0h1m-3 0h1m-3 0h1m-3 0h1m-3 0h1m-3 0h1m-3-14v-1m0 3v-1m0 3v-1m0 3v-1m0 3v-1m0 3v-1m0 3v-1'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-mirror' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M5 .4 3.5 2 5 3.6M15 .4 16.5 2 15 3.6M3.52 2h12.957M8.5 16.7V6.046c0-.301-.394-.415-.554-.159L1.287 16.541a.3.3 0 0 0 .255.459H8.2a.3.3 0 0 0 .3-.3zm3 0V6.046c0-.301.395-.415.555-.159l6.659 10.654a.3.3 0 0 1-.255.459H11.8a.3.3 0 0 1-.3-.3z'/></symbol><symbol viewBox='0 0 40 40' id='uc-icon-original' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.5' d='M0 40 40 0'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-rotate' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M13.5.4 12 2l1.5 1.6M12.023 2H14.4A3.6 3.6 0 0 1 18 5.6V8M4 17h9a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1z'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-sad' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M2 17c4.418-4 11.582-4 16 0M16.5 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-11 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-saturation' xmlns='http://www.w3.org/2000/svg'><defs><linearGradient id='ruc-icon-id__a' x1='10.001' y1='1' x2='10.001' y2='19' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient></defs><circle cx='10.001' cy='10' r='9' transform='rotate(90 10 10)' fill='url(#ruc-icon-id__a)'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-slider' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M0 10h11m0 0a2 2 0 1 0 4 0m-4 0a2 2 0 1 1 4 0m0 0h5'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-tuning' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M8 10h11M1 10h4M1 4.5h11m3 0h4m-18 11h11m3 0h4m-7-11a1.5 1.5 0 1 0 3 0 1.5 1.5 0 1 0-3 0M5 10a1.5 1.5 0 1 0 3 0 1.5 1.5 0 1 0-3 0m7 5.5a1.5 1.5 0 1 0 3 0 1.5 1.5 0 1 0-3 0'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-vibrance' xmlns='http://www.w3.org/2000/svg'><path d='M2.125 5.64A8.96 8.96 0 0 0 1.001 10a8.96 8.96 0 0 0 1.124 4.36V5.64z' fill='url(#uuc-icon-id__a)'/><path d='M2.875 15.499V4.502a9.053 9.053 0 0 1 1.75-1.72v14.437a9.05 9.05 0 0 1-1.75-1.72z' fill='url(#uuc-icon-id__b)'/><path d='M5.375 17.722c.548.33 1.134.601 1.75.809V1.469a8.956 8.956 0 0 0-1.75.81v15.443z' fill='url(#uuc-icon-id__c)'/><path d='M7.875 1.253v17.495c.564.136 1.15.22 1.75.244V1.008a9 9 0 0 0-1.75.245z' fill='url(#uuc-icon-id__d)'/><path d='M10.375 1.008v17.984a9 9 0 0 0 1.75-.244V1.252a9 9 0 0 0-1.75-.244z' fill='url(#uuc-icon-id__e)'/><path d='M12.875 1.469V18.53a8.957 8.957 0 0 0 1.75-.808V2.277a8.957 8.957 0 0 0-1.75-.808z' fill='url(#uuc-icon-id__f)'/><path d='M15.375 2.78v14.44a9.053 9.053 0 0 0 1.75-1.72v-11a9.054 9.054 0 0 0-1.75-1.72z' fill='url(#uuc-icon-id__g)'/><path d='M17.875 5.638v8.724A8.959 8.959 0 0 0 19.001 10a8.96 8.96 0 0 0-1.126-4.362z' fill='url(#uuc-icon-id__h)'/><defs><linearGradient id='uuc-icon-id__a' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__b' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__c' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__d' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__e' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__f' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__g' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__h' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient></defs></symbol><symbol viewBox='0 0 20 20' id='uc-icon-warmth' xmlns='http://www.w3.org/2000/svg'><path d='m7.5 13.05.429.42.171-.175v-.244h-.6zm5 0h-.6v.245l.172.175.428-.42zM8.1 3.5c0-1.05.85-1.9 1.9-1.9V.4a3.1 3.1 0 0 0-3.1 3.1h1.2zm0 9.55V3.5H6.9v9.55h1.2zm-1 2.45c0-.79.315-1.506.829-2.03l-.858-.84A4.088 4.088 0 0 0 5.9 15.5h1.2zm2.9 2.9a2.9 2.9 0 0 1-2.9-2.9H5.9a4.1 4.1 0 0 0 4.1 4.1v-1.2zm2.9-2.9a2.9 2.9 0 0 1-2.9 2.9v1.2a4.1 4.1 0 0 0 4.1-4.1h-1.2zm-.829-2.03c.514.524.829 1.24.829 2.03h1.2c0-1.117-.447-2.13-1.171-2.87l-.858.84zM11.9 3.5v9.55h1.2V3.5h-1.2zM10 1.6c1.05 0 1.9.85 1.9 1.9h1.2A3.1 3.1 0 0 0 10 .4v1.2z' fill='currentColor'/><path d='M10 14V8' stroke='currentColor' stroke-width='1.2' stroke-linecap='round'/><path d='M14 3h3m-3 3h3m-3 3h3m-8 6.5a1 1 0 1 0 2 0 1 1 0 1 0-2 0' stroke='currentColor' stroke-width='1.2'/></symbol></svg>";var ue={};u(ue,ol);import*as ol from"lit-html/directives/when.js";var Si=de([...L]),x=class extends T{constructor(){super(...arguments);this.ctxOwner=!0;this.entry=null;this.extension=null;this.editorMode=!1;this.modalCaption="";this.isImage=!1;this.msg="";this.src=se;this.fileType="";this.showLoader=!1;this.uuid=null;this.cdnUrl=null;this.cropPreset="";this.tabs=Si;this.presenceNetworkProblems=!1;this.presenceModalCaption=!0;this.presenceEditorToolbar=!1;this.presenceViewerToolbar=!0;this.isInitialized=!1;this.pendingInitUpdate=null;this._debouncedShowLoader=M(e=>{this.showLoader=e},300);this.imgRef=(0,g.createRef)();this.cropperRef=(0,g.createRef)();this.faderRef=(0,g.createRef)();this.imgContainerRef=(0,g.createRef)();this.handleImageLoad=()=>{this._debouncedShowLoader(!1),this.src!==se&&(this.$["*networkProblems"]=!1)};this.handleImageError=()=>{this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0};this.handleRetryNetwork=()=>{let e=this.$["*on.retryNetwork"];e?.()};this.init$={...this.init$,...Ei(this)}}static{this.styleAttrs=["uc-cloud-image-editor"]}scheduleInitialization(){this.isInitialized||this.pendingInitUpdate||(this.pendingInitUpdate=this.updateComplete.then(()=>{this.pendingInitUpdate=null,this.isInitialized=!0}))}initCallback(){super.initCallback(),this.syncTabListFromProp(),this.syncCropPresetState()}assignSharedElements(){let e=this.faderRef.value;e&&(this.$["*faderEl"]=e);let t=this.cropperRef.value;t&&(this.$["*cropperEl"]=t);let r=this.imgContainerRef.value;r&&(this.$["*imgContainerEl"]=r);let o=this.imgRef.value;o&&(this.$["*imgEl"]=o)}attachImageListeners(){let e=this.imgRef.value;e&&(e.addEventListener("load",this.handleImageLoad),e.addEventListener("error",this.handleImageError))}detachImageListeners(){let e=this.imgRef.value;e&&(e.removeEventListener("load",this.handleImageLoad),e.removeEventListener("error",this.handleImageError))}get imageClassName(){let e=this.$["*tabId"];return U("uc-image",{"uc-image_hidden_to_cropper":e===E.CROP,"uc-image_hidden_effects":e!==E.CROP})}_waitForSize(){return new Promise((t,r)=>{let o=window.setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),n=new ResizeObserver(a=>{let[l]=a;l&&l.contentRect.width>0&&l.contentRect.height>0&&(window.clearTimeout(o),n.disconnect(),window.setTimeout(()=>t(),0))});n.observe(this)})}firstUpdated(e){super.firstUpdated(e),this.assignSharedElements(),this.attachImageListeners(),this.initEditor();let t=!!(this.uuid||this.cdnUrl),r=e.has("uuid")||e.has("cdnUrl");t&&!r&&this.updateImage()}disconnectedCallback(){this.detachImageListeners(),super.disconnectedCallback()}render(){let e=this.fileType??"",t=this.msg??"",r=this.src||se,o=this.showLoader,n=this.presenceNetworkProblems;return m.html`${(0,fe.unsafeSVG)(xi)} <div class="uc-wrapper uc-wrapper_desktop"><uc-presence-toggle class="uc-network_problems_splash" .visible=${n}><div class="uc-network_problems_content"><div class="uc-network_problems_icon"><uc-icon name="sad"></uc-icon></div><div class="uc-network_problems_text">Network error</div></div><div class="uc-network_problems_footer"><uc-btn-ui theme="primary" text="Retry" @click=${this.handleRetryNetwork}></uc-btn-ui></div></uc-presence-toggle><div class="uc-viewport"><div class="uc-file_type_outer"><div class="uc-file_type">${e}</div></div><div class="uc-image_container" ${(0,g.ref)(this.imgContainerRef)}><img src=${r} class=${this.imageClassName} ${(0,g.ref)(this.imgRef)} /> ${(0,ue.when)(this.isInitialized,()=>m.html`<uc-editor-image-cropper ${(0,g.ref)(this.cropperRef)}></uc-editor-image-cropper>`)} <uc-editor-image-fader ${(0,g.ref)(this.faderRef)}></uc-editor-image-fader></div><div class="uc-info_pan">${t}</div></div><div class="uc-toolbar"><uc-line-loader-ui .active=${o}></uc-line-loader-ui><div class="uc-toolbar_content uc-toolbar_content__editor"> ${(0,ue.when)(this.isInitialized,()=>m.html`<uc-editor-toolbar></uc-editor-toolbar>`)} </div></div></div>`}updated(e){super.updated(e),e.has("uuid")&&this.uuid&&this.updateImage(),e.has("cdnUrl")&&this.cdnUrl&&this.updateImage(),e.has("tabs")&&this.syncTabListFromProp(),(e.has("cropPreset")||e.has("cdnUrl"))&&this.syncCropPresetState()}syncTabListFromProp(){let e=this.tabs||Si;this.$["*tabList"]=Ci(e)}syncCropPresetState(){let e=Ti(this.cropPreset??""),t=null;if(this.cdnUrl){let r=Tt(this.cdnUrl),o=Ct(r);if(Array.isArray(o?.crop?.dimensions)){let[n,a]=o.crop.dimensions;t=wi(n,a,e,.1)}}this.$["*cropPresetList"]=e,this.$["*currentAspectRatio"]=t??e?.[0]??null}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.cdnUrl){let e=this.cdnUrl,t=Be(e),r=wt(e,t);if(r===this.$["*originalUrl"])return;this.$["*originalUrl"]=r;let o=Tt(e),n=Ct(o);this.$["*editorTransformations"]=n}else if(this.uuid){let e=wt(this.cfg.cdnCname,this.uuid);if(e===this.$["*originalUrl"])return;this.$["*originalUrl"]=e,this.$["*editorTransformations"]={}}else throw new Error("No UUID nor CDN URL provided");this.$["*tabId"]===E.CROP?this.$["*cropperEl"]?.deactivate({reset:!0}):this.$["*faderEl"]?.deactivate();try{let e=this.$["*originalUrl"],t=await this.proxyUrl(W(e,q("json"))),r=await fetch(t).then(a=>a.json()),{width:o,height:n}=r;this.$["*imageSize"]={width:o,height:n},this.$["*tabId"]===E.CROP?this.$["*cropperEl"]?.activate(this.$["*imageSize"]):this.$["*faderEl"]?.activate({url:e})}catch(e){e&&(this.telemetryManager.sendEventError(e,"cloud editor image. Failed to load image info"),console.error("Failed to load image info",e))}this.scheduleInitialization()}}async initEditor(){try{await this._waitForSize()}catch(e){this.isConnected&&console.error(e.message);return}this.classList.add("uc-editor_ON"),this.sub("*networkProblems",e=>{let t=!!e;this.presenceNetworkProblems=t,this.presenceModalCaption=!t}),this.sub("*editorTransformations",e=>{if(Object.keys(e).length===0)return;let t=this.$["*originalUrl"],r=q(ie(e),"preview"),o=W(t,r),n={originalUrl:t,cdnUrlModifiers:r,cdnUrl:o,transformations:e};this.dispatchEvent(new CustomEvent("change",{detail:n,bubbles:!0,composed:!0}))},!1)}};p([(0,c.property)({attribute:!1})],x.prototype,"entry",2),p([(0,c.property)({attribute:!1})],x.prototype,"extension",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"editorMode",2),p([(0,c.property)({type:String,attribute:!1})],x.prototype,"modalCaption",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"isImage",2),p([(0,c.property)({type:String,attribute:!1})],x.prototype,"msg",2),p([(0,c.property)({type:String,attribute:!1})],x.prototype,"src",2),p([(0,c.property)({type:String,attribute:!1})],x.prototype,"fileType",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"showLoader",2),p([(0,c.property)({type:String,reflect:!0})],x.prototype,"uuid",2),p([(0,c.property)({type:String,attribute:"cdn-url",reflect:!0})],x.prototype,"cdnUrl",2),p([(0,c.property)({type:String,attribute:"crop-preset",reflect:!0})],x.prototype,"cropPreset",2),p([(0,c.property)({type:String,reflect:!0})],x.prototype,"tabs",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"presenceNetworkProblems",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"presenceModalCaption",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"presenceEditorToolbar",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"presenceViewerToolbar",2),p([(0,c.state)()],x.prototype,"isInitialized",2);var Ie=33.333333333333336,v=1,kt=24,ki=6;function oe(s,i){for(let[e,t]of Object.entries(i))s.setAttributeNS(null,e,t.toString())}function F(s,i={}){let e=document.createElementNS("http://www.w3.org/2000/svg",s);return oe(e,i),e}function Ri(s,i,e){let{x:t,y:r,width:o,height:n}=s,a=i.includes("w")?0:1,l=i.includes("n")?0:1,d=a===0?-1:1,f=l===0?-1:1,h=[t+a*o+1.5*d,r+l*n+1.5*f-24*e*f],y=[t+a*o+1.5*d,r+l*n+1.5*f],b=[t+a*o-24*e*d+1.5*d,r+l*n+1.5*f],_=`M ${h[0]} ${h[1]} L ${y[0]} ${y[1]} L ${b[0]} ${b[1]}`,I=[y[0],y[1]];return{d:_,center:I}}function Oi(s,i,e){let{x:t,y:r,width:o,height:n}=s,a=i==="n"||i==="s",l=i==="w"||i==="e",d=a?.5:i==="w"?0:1,f=l?.5:i==="n"?0:1,h=i==="w"?-1:i==="e"?1:0,y=i==="n"?-1:i==="s"?1:0,b,_;a?(b=[t+d*o-34*e/2,r+f*n+1.5*y],_=[t+d*o+34*e/2,r+f*n+1.5*y]):(b=[t+d*o+1.5*h,r+f*n-34*e/2],_=[t+d*o+1.5*h,r+f*n+34*e/2]);let I=`M ${b[0]} ${b[1]} L ${_[0]} ${_[1]}`,R=[(b[0]+_[0])/2,(b[1]+_[1])/2];return{d:I,center:R}}function Ai(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 Ii({rect:s,delta:[i,e],imageBox:t}){return _e({...s,x:s.x+i,y:s.y+e},t)}function _e(s,i){let{x:e}=s,{y:t}=s;return s.x<i.x?e=i.x:s.x+s.width>i.x+i.width&&(e=i.x+i.width-s.width),s.y<i.y?t=i.y:s.y+s.height>i.y+i.height&&(t=i.y+i.height-s.height),{...s,x:e,y:t}}function Vr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[,r]=i,{y:o,width:n,height:a}=s;o+=r,a-=r,e&&(n=a*e);let l=s.x+s.width/2-n/2;return o<=t.y&&(o=t.y,a=s.y+s.height-o,e&&(n=a*e,l=s.x+s.width/2-n/2)),l<=t.x&&(l=t.x,o=s.y+s.height-a),l+n>=t.x+t.width&&(l=Math.max(t.x,t.x+t.width-n),n=t.x+t.width-l,e&&(a=n/e),o=s.y+s.height-a),a<v&&(a=v,e&&(n=a*e,l=s.x+s.width/2-n/2),o=s.y+s.height-a),n<v&&(n=v,e&&(a=n/e,l=s.x+s.width/2-n/2),o=s.y+s.height-a),{x:l,y:o,width:n,height:a}}function zr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r]=i,{x:o,width:n,height:a}=s;o+=r,n-=r,e&&(a=n/e);let l=s.y+s.height/2-a/2;return o<=t.x&&(o=t.x,n=s.x+s.width-o,e&&(a=n/e,l=s.y+s.height/2-a/2)),l<=t.y&&(l=t.y,o=s.x+s.width-n),l+a>=t.y+t.height&&(l=Math.max(t.y,t.y+t.height-a),a=t.y+t.height-l,e&&(n=a*e),o=s.x+s.width-n),a<v&&(a=v,e&&(n=a*e),l=s.y+s.height/2-a/2,o=s.x+s.width-n),n<v&&(n=v,e&&(a=n/e),l=s.y+s.height/2-a/2,o=s.x+s.width-n),{x:o,y:l,width:n,height:a}}function jr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[,r]=i,{y:o,width:n,height:a}=s;a+=r,e&&(n=a*e);let l=s.x+s.width/2-n/2;return o+a>=t.y+t.height&&(a=t.y+t.height-o,e&&(n=a*e),l=s.x+s.width/2-n/2),l<=t.x&&(l=t.x,o=s.y),l+n>=t.x+t.width&&(l=Math.max(t.x,t.x+t.width-n),n=t.x+t.width-l,e&&(a=n/e),o=s.y),a<v&&(a=v,e&&(n=a*e),l=s.x+s.width/2-n/2),n<v&&(n=v,e&&(a=n/e),l=s.x+s.width/2-n/2),{x:l,y:o,width:n,height:a}}function Kr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r]=i,{x:o,width:n,height:a}=s;n+=r,e&&(a=n/e);let l=s.y+s.height/2-a/2;return o+n>=t.x+t.width&&(n=t.x+t.width-o,e&&(a=n/e),l=s.y+s.height/2-a/2),l<=t.y&&(l=t.y,o=s.x),l+a>=t.y+t.height&&(l=Math.max(t.y,t.y+t.height-a),a=t.y+t.height-l,e&&(n=a*e),o=s.x),a<v&&(a=v,e&&(n=a*e),l=s.y+s.height/2-a/2),n<v&&(n=v,e&&(a=n/e),l=s.y+s.height/2-a/2),{x:o,y:l,width:n,height:a}}function Hr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,o]=i,{x:n,y:a,width:l,height:d}=s;return n+r<t.x&&(r=t.x-n),a+o<t.y&&(o=t.y-a),n+=r,l-=r,a+=o,d-=o,e&&Math.abs(l/d)>e?(o=l/e-d,d+=o,a-=o,a<=t.y&&(d=d-(t.y-a),l=d*e,n=s.x+s.width-l,a=t.y)):e&&(r=d*e-l,l=l+r,n-=r,n<=t.x&&(l=l-(t.x-n),d=l/e,n=t.x,a=s.y+s.height-d)),d<v&&(d=v,e&&(l=d*e),n=s.x+s.width-l,a=s.y+s.height-d),l<v&&(l=v,e&&(d=l/e),n=s.x+s.width-l,a=s.y+s.height-d),{x:n,y:a,width:l,height:d}}function Br({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,o]=i,{x:n,y:a,width:l,height:d}=s;return n+l+r>t.x+t.width&&(r=t.x+t.width-n-l),a+o<t.y&&(o=t.y-a),l+=r,a+=o,d-=o,e&&Math.abs(l/d)>e?(o=l/e-d,d+=o,a-=o,a<=t.y&&(d=d-(t.y-a),l=d*e,n=s.x,a=t.y)):e&&(r=d*e-l,l+=r,n+l>=t.x+t.width&&(l=t.x+t.width-n,d=l/e,n=t.x+t.width-l,a=s.y+s.height-d)),d<v&&(d=v,e&&(l=d*e),a=s.y+s.height-d),l<v&&(l=v,e&&(d=l/e),a=s.y+s.height-d),{x:n,y:a,width:l,height:d}}function Gr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,o]=i,{x:n,y:a,width:l,height:d}=s;return n+r<t.x&&(r=t.x-n),a+d+o>t.y+t.height&&(o=t.y+t.height-a-d),n+=r,l-=r,d+=o,e&&Math.abs(l/d)>e?(o=l/e-d,d+=o,a+d>=t.y+t.height&&(d=t.y+t.height-a,l=d*e,n=s.x+s.width-l,a=t.y+t.height-d)):e&&(r=d*e-l,l+=r,n-=r,n<=t.x&&(l=l-(t.x-n),d=l/e,n=t.x,a=s.y)),d<v&&(d=v,e&&(l=d*e),n=s.x+s.width-l),l<v&&(l=v,e&&(d=l/e),n=s.x+s.width-l),{x:n,y:a,width:l,height:d}}function Xr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,o]=i,{x:n,y:a,width:l,height:d}=s;return n+l+r>t.x+t.width&&(r=t.x+t.width-n-l),a+d+o>t.y+t.height&&(o=t.y+t.height-a-d),l+=r,d+=o,e&&Math.abs(l/d)>e?(o=l/e-d,d+=o,a+d>=t.y+t.height&&(d=t.y+t.height-a,l=d*e,n=s.x,a=t.y+t.height-d)):e&&(r=d*e-l,l+=r,n+l>=t.x+t.width&&(l=t.x+t.width-n,d=l/e,n=t.x+t.width-l,a=s.y)),d<v&&(d=v,e&&(l=d*e)),l<v&&(l=v,e&&(d=l/e)),{x:n,y:a,width:l,height:d}}function Pi({direction:s,...i}){switch(s){case"n":return Vr(i);case"w":return zr(i);case"s":return jr(i);case"e":return Kr(i);case"nw":return Hr(i);case"ne":return Br(i);case"sw":return Gr(i);case"se":return Xr(i);default:return i.rect}}function Li(s,[i,e]){return s.x<=i&&i<=s.x+s.width&&s.y<=e&&e<=s.y+s.height}function Mi(s,i){return s.x>=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function $i(s,i){return Math.abs(s.width/s.height-i)<.1}function Te({width:s,height:i},e){let t=e/90%2!==0;return{width:t?i:s,height:t?s:i}}function we(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function ne(s,i,e){return Math.min(Math.max(s,i),e)}var et=class extends T{constructor(){super(...arguments);this._guidesHidden=!1;this._dragging=!1;this.svgRef=(0,g.createRef)();this._svgReady=!1;this._pendingMaskHref=null;this._handlePointerUp=e=>{this._updateCursor(),this.dragging&&(e.stopPropagation(),e.preventDefault(),this.dragging=!1)};this._handlePointerMove=e=>{if(!this.dragging||!this._dragStartPoint||!this._draggingThumb)return;e.stopPropagation(),e.preventDefault();let t=this._svgElement;if(!t)return;let{x:r,y:o}=t.getBoundingClientRect(),n=e.x-r,a=e.y-o,l=n-this._dragStartPoint[0],d=a-this._dragStartPoint[1],{direction:f}=this._draggingThumb,h=this._calcCropBox(f,[l,d]);h&&(this.$["*cropBox"]=h)};this._handleSvgPointerMove=e=>{if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(r=>{if(!r||this._shouldThumbBeDisabled(r.direction))return!1;let n=r.interactionNode.getBoundingClientRect(),a={x:n.x,y:n.y,width:n.width,height:n.height};return Li(a,[e.x,e.y])});this._hoverThumb=t,this._updateCursor()}}get _svgElement(){return this.svgRef.value??null}get dragging(){return this._dragging}set dragging(e){this._dragging!==e&&(this._dragging=e,this._applyGuidesDragState())}_applyGuidesDragState(){this._frameGuides&&this._frameGuides.setAttribute("class",U({"uc-guides--hidden":this._guidesHidden,"uc-guides--visible":!this._guidesHidden&&this._dragging,"uc-guides--semi-hidden":!this._guidesHidden&&!this._dragging}))}_shouldThumbBeDisabled(e){let t=this.$["*imageBox"];if(!t)return!1;if(e===""&&t.height<=v&&t.width<=v)return!0;let r=t.height<=v&&(e.includes("n")||e.includes("s")),o=t.width<=v&&(e.includes("e")||e.includes("w"));return r||o}_createBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:t,y:r,width:o,height:n}=e,a=this._svgElement;if(!a)return;let l=F("mask",{id:"backdrop-mask"}),d=F("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),f=F("rect",{x:t,y:r,width:o,height:n,fill:"black"});l.appendChild(d),l.appendChild(f);let h=F("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});a.appendChild(h),a.appendChild(l),this._backdropMask=l,this._backdropMaskInner=f}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:t,y:r,width:o,height:n}=e;this._backdropMaskInner&&oe(this._backdropMaskInner,{x:t,y:r,width:o,height:n})}_updateFrame(){let e=this.$["*cropBox"];if(!(!e||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){if(!t)continue;let{direction:r,pathNode:o,interactionNode:n,groupNode:a}=t,l=r==="",d=r.length===2,{x:f,y:h,width:y,height:b}=e;if(l)oe(n,{x:f,y:h,width:y,height:b});else{let I=ne(Math.min(y,b)/82/2,0,1),R=d?Ri(e,r,I):Oi(e,r,I),P=R.center;if(!P)continue;let le=Math.max(kt*ne(Math.min(y,b)/kt/3,0,1),ki);oe(n,{x:P[0]-le,y:P[1]-le,width:le*2,height:le*2}),oe(o,{d:R.d})}let _=this._shouldThumbBeDisabled(r);a.setAttribute("class",U("uc-thumb",{"uc-thumb--hidden":_,"uc-thumb--visible":!_}))}oe(this._frameGuides,{x:e.x-1*.5,y:e.y-1*.5,width:e.width+1,height:e.height+1})}}_createThumb(e,t){let r=F("g");r.classList.add("uc-thumb"),r.setAttribute("with-effects","");let o=F("rect",{fill:"transparent"}),n=F("path",{stroke:"currentColor",fill:"none","stroke-width":3});r.appendChild(n),r.appendChild(o),e[t]={direction:t,pathNode:n,interactionNode:o,groupNode:r},t===""&&(r.style.cursor="move"),o.addEventListener("pointerdown",this._handlePointerDown.bind(this,t))}_createThumbs(){let e={};for(let t=0;t<3;t++)for(let r=0;r<3;r++){let o=`${["n","","s"][t]}${["w","","e"][r]}`;o!==""&&this._createThumb(e,o)}return this._createThumb(e,""),e}_createGuides(){let e=F("svg"),t=F("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"currentColor","stroke-width":1,"stroke-opacity":.5});e.appendChild(t);for(let r=1;r<=2;r++){let o=F("line",{x1:`${Ie*r}%`,y1:"0%",x2:`${Ie*r}%`,y2:"100%",stroke:"currentColor","stroke-width":1,"stroke-opacity":.3});e.appendChild(o)}for(let r=1;r<=2;r++){let o=F("line",{x1:"0%",y1:`${Ie*r}%`,x2:"100%",y2:`${Ie*r}%`,stroke:"currentColor","stroke-width":1,"stroke-opacity":.3});e.appendChild(o)}return e.classList.add("uc-guides","uc-guides--semi-hidden"),e}_createFrame(){let e=this._svgElement;if(!e)return;let t=document.createDocumentFragment(),r=this._createGuides();t.appendChild(r);let o=this._createThumbs();for(let{groupNode:n}of Object.values(o))t.appendChild(n);e.appendChild(t),this._frameThumbs=o,this._frameGuides=r,this._applyGuidesDragState()}_handlePointerDown(e,t){if(!this._frameThumbs)return;let r=this._frameThumbs[e];if(!r||this._shouldThumbBeDisabled(e))return;let o=this.$["*cropBox"],n=this._svgElement;if(!n)return;let{x:a,y:l}=n.getBoundingClientRect(),d=t.x-a,f=t.y-l;this.dragging=!0,this._draggingThumb=r,this._dragStartPoint=[d,f],this._dragStartCrop={...o}}_calcCropBox(e,t){let[r,o]=t,n=this.$["*imageBox"],a=this._dragStartCrop??this.$["*cropBox"],l=this.$["*currentAspectRatio"],d=l?l.width/l.height:void 0;if(e===""?a=Ii({rect:a,delta:[r,o],imageBox:n}):a=Pi({rect:a,delta:[r,o],direction:e,aspectRatio:d,imageBox:n}),!Object.values(a).every(f=>Number.isFinite(f)&&f>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:a});return}return _e(we(a),n)}_updateCursor(){let e=this._hoverThumb,t=this._svgElement;t&&(t.style.cursor=e?Ai(e.direction):"initial")}_createMask(e){if(this._frameImage){this._frameImage.setAttribute("href",e);return}let t=this._svgElement;if(!t){this._pendingMaskHref=e;return}this._pendingMaskHref=null;let r=document.createDocumentFragment(),o=F("image",{href:e});o.setAttribute("class","uc-cloud-mask"),r.appendChild(o),t.appendChild(r),this._frameImage=o}_updateMask(){let e=this.$["*cropBox"];if(!e||!this._frameImage)return;let{x:t,y:r,width:o,height:n}=e;oe(this._frameImage,{x:t,y:r,height:n,width:o})}_render(){this._svgReady&&(this._updateBackdrop(),this._updateFrame(),this._updateMask())}toggleThumbs(e){if(this._frameThumbs)for(let t of Object.values(this._frameThumbs)){if(!t)continue;let{groupNode:r}=t;r.setAttribute("class",U("uc-thumb",{"uc-thumb--hidden":!e,"uc-thumb--visible":e}))}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._resizeBackdrop(),this._svgReady&&window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",e=>{e&&(this._guidesHidden=e.height<=v||e.width<=v,this._applyGuidesDragState(),this._svgReady&&window.requestAnimationFrame(()=>{this._render()}))}),this.subConfigValue("cloudImageEditorMaskHref",e=>{e&&this._createMask(e)}),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}firstUpdated(e){super.firstUpdated(e),this._initializeSvg()}_initializeSvg(){let e=this._svgElement;if(!(!e||this._svgReady)){if(this._createBackdrop(),this._createFrame(),this._svgReady=!0,e.addEventListener("pointermove",this._handleSvgPointerMove,!0),this._pendingMaskHref){let t=this._pendingMaskHref;this._pendingMaskHref=null,this._createMask(t)}this._render()}}disconnectedCallback(){super.disconnectedCallback(),this._svgElement?.removeEventListener("pointermove",this._handleSvgPointerMove,!0),document.removeEventListener("pointermove",this._handlePointerMove,!0),document.removeEventListener("pointerup",this._handlePointerUp,!0)}render(){return m.html`<svg class="uc-svg" xmlns="http://www.w3.org/2000/svg" ${(0,g.ref)(this.svgRef)}></svg>`}};p([(0,c.state)()],et.prototype,"_dragging",2);var D={};u(D,Dl);import*as Dl from"lit-html/directives/class-map.js";var C={};u(C,Ul);import*as Ul from"lit-html/directives/if-defined.js";var $=class extends T{constructor(){super(...arguments);this.active=!1;this.title="";this.icon="";this.titleProp=""}get buttonClasses(){let e=this.active;return{"uc-active":e,"uc-not_active":!e}}updateHostStateClasses(){let e=this.buttonClasses;for(let[t,r]of Object.entries(e))this.classList.toggle(t,r)}onClick(e){}connectedCallback(){super.connectedCallback(),this.updateHostStateClasses()}updated(e){super.updated(e),e.has("active")&&this.updateHostStateClasses()}render(){let e=this.onClick,t=this.title;return m.html`<button role="option" type="button" aria-label=${(0,C.ifDefined)(this.titleProp)} title=${(0,C.ifDefined)(this.titleProp)} @click=${e} ><uc-icon name=${this.icon}></uc-icon><div class="uc-title" ?hidden=${!t}>${t}</div></button>`}};p([(0,c.state)()],$.prototype,"active",2),p([(0,c.state)()],$.prototype,"title",2),p([(0,c.state)()],$.prototype,"icon",2),p([(0,c.state)()],$.prototype,"titleProp",2);var tt=12,it=16,Wr=s=>{let i=12,e=12;return s.width/s.height>=1?(i=tt,e=Math.round(tt*s.height/s.width)):(e=tt,i=Math.round(tt*s.width/s.height)),{width:i,height:e}},Rt=class extends ${initCallback(){super.initCallback(),this.icon="arrow-dropdown",this.sub("*currentAspectRatio",i=>{let e=this.computeTitle(i);this.title=e,this.titleProp=e})}onClick(){this.$["*showListAspectRatio"]=!0}computeTitle(i){return i?i.hasFreeform?this.l10n("freeform-crop"):this.l10n("crop-to-shape",{value:`${i.width}:${i.height}`}):""}render(){let i=this.onClick,e=this.title;return m.html`<button role="option" type="button" class=${(0,D.classMap)(this.buttonClasses)} aria-label=${(0,C.ifDefined)(this.titleProp)} title=${(0,C.ifDefined)(this.titleProp)} @click=${i} ><div class="uc-title" ?hidden=${!e}>${e}</div><uc-icon name=${this.icon}></uc-icon></button>`}},rt=class extends ${get aspectRatio(){return this._aspectRatio}set aspectRatio(i){if(this._aspectRatio===i)return;let e=this._aspectRatio;this._aspectRatio=i,this.requestUpdate("aspectRatio",e),i?this.updateAspectRatioPresentation(i):(this.removeAttribute("uc-aspect-ratio-freeform"),this.title="",this.titleProp="")}initCallback(){super.initCallback(),this._aspectRatio&&this.updateAspectRatioPresentation(this._aspectRatio),this.sub("*currentAspectRatio",i=>{this.active=i&&i.id===this._aspectRatio?.id||i?.width===this._aspectRatio?.width&&i?.height===this._aspectRatio?.height})}onClick(){this.$["*currentAspectRatio"]?.id!==this._aspectRatio?.id&&(this.$["*currentAspectRatio"]=this._aspectRatio)}updateAspectRatioPresentation(i){let e=!!i.hasFreeform;this.toggleAttribute("uc-aspect-ratio-freeform",e);let t=()=>{let o=e?this.l10n("custom"):`${i.width}:${i.height}`;return this.title=o,o},r=()=>{let o=this.l10n("a11y-cloud-editor-apply-aspect-ratio",{name:e?this.l10n("custom").toLowerCase():this.l10n("crop-to-shape",{value:`${i.width}:${i.height}`}).toLowerCase(),value:""});return this.titleProp=o,o};t(),r(),e||this.requestUpdate()}renderIcon(){let i=this._aspectRatio;if(!i||i.hasFreeform)return m.html`<uc-icon name=${this.icon}></uc-icon>`;let{width:e,height:t}=Wr(i),r=(it-e)/2,o=(it-t)/2;return m.html`<svg viewBox="0 0 ${it} ${it}" aria-hidden="true" focusable="false" ><rect x=${r} y=${o} width=${e} height=${t} rx="2" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round" ></rect></svg>`}render(){let i=this.onClick,e=this.title;return m.html`<button role="option" type="button" class=${(0,D.classMap)(this.buttonClasses)} aria-label=${(0,C.ifDefined)(this.titleProp)} title=${(0,C.ifDefined)(this.titleProp)} @click=${i} ><uc-icon>${this.renderIcon()}</uc-icon><div class="uc-title" ?hidden=${!e}>${e}</div></button>`}};p([(0,c.property)({attribute:!1})],rt.prototype,"aspectRatio",1);function Yr(s){let i=s+90;return i=i>=360?0:i,i}function Qr(s,i){if(s==="rotate")return Yr(typeof i=="number"?i:0);if(s==="mirror"||s==="flip")return!i;throw new Error(`Unsupported operation: ${s}`)}var st=class extends ${constructor(){super(...arguments);this.operation=void 0}willUpdate(e){super.willUpdate(e),this.operation?(this.titleProp=this.l10n("a11y-cloud-editor-apply-crop",{name:this.l10n(this.operation).toLowerCase()}),this.icon=this.operation):(this.icon="",this.titleProp="")}onClick(e){if(!this.operation)return;let t=this.$["*cropperEl"],r=t.getValue(this.operation),o=Qr(this.operation,r);this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{operation:this.operation,next:o,prev:r}),t.setValue(this.operation,o)}};p([(0,c.property)({type:String})],st.prototype,"operation",2);var B={};u(B,ic);import*as ic from"lit-html/directives/style-map.js";function Pe(s){let i=new Image;return{promise:new Promise((r,o)=>{i.src=s,i.onload=()=>r(),i.onerror=n=>o(n)}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=se)}}}function Le(s){let i=[];for(let o of s){let n=Pe(o);i.push(n)}let e=i.map(o=>o.image);return{promise:Promise.allSettled(i.map(o=>o.promise)),images:e,cancel:()=>{i.forEach(o=>{o.cancel()})}}}var G="original",ot=class extends T{constructor(){super(...arguments);this.state={operation:"filter",filter:void 0,originalUrl:"",disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0};this.handleInput=e=>{let{value:t}=e.detail;this.$["*faderEl"]?.set(t),this.state={...this.state,value:t}}}setOperation(e,t){this.state={...this.state,operation:e,filter:t},this._initializeValues();let r=this.$["*faderEl"],o=this.state.originalUrl||this.$["*originalUrl"];r&&o&&r.activate({url:o,operation:this.state.operation,value:this.state.filter===G?void 0:this.state.value,filter:this.state.filter===G?void 0:this.state.filter,fromViewer:!1})}_initializeValues(){let e=this.state.operation,{range:t,zero:r}=j[e],[o,n]=t;this.state={...this.state,min:o,max:n,zero:r};let l=this.$["*editorTransformations"][e];if(e==="filter"){let f=Number(n),h=l;if(h){let{name:y,amount:b}=h;f=y===this.state.filter?b:n}this.state={...this.state,value:f,defaultValue:f};return}let d=typeof l<"u"?l:r;this.state={...this.state,value:d,defaultValue:d}}apply(){let t={...this.$["*editorTransformations"]};this.state.operation==="filter"?!this.state.filter||this.state.filter===G?delete t.filter:t.filter={name:this.state.filter,amount:this.state.value}:t[this.state.operation]=this.state.value,this.$["*editorTransformations"]=t}cancel(){this.$["*faderEl"]?.deactivate({hide:!1})}initCallback(){this.sub("*originalUrl",e=>{this.state={...this.state,originalUrl:e}})}updated(e){if(super.updated(e),e.has("state")){let t=`${this.state.filter??this.state.operation} ${this.state.value}`;this.$["*operationTooltip"]=t}}render(){return m.html`<uc-slider-ui .disabled=${this.state.disabled} .min=${this.state.min} .max=${this.state.max} .defaultValue=${this.state.defaultValue} .zero=${this.state.zero} @slider-input=${this.handleInput} ></uc-slider-ui>`}};p([(0,c.state)()],ot.prototype,"state",2);function Ce(s){let i=s.match(/^([A-Za-z]+)\s+(\d+)$/);if(!i)return null;let[,e,t]=i;return!e||typeof t>"u"?null:{filter:e,value:Number(t)}}var ae=class extends ${constructor(){super(...arguments);this._operation="";this._filter="";this._originalUrl="";this._lastPreviewRequestId=0;this.previewImage=null;this.previewLoaded=!1;this.isOriginal=!1;this.iconSize=20}get filter(){return this._filter}set filter(e){let t=e??"";if(this._filter===t)return;let r=this._filter;this._filter=t,this._operation="filter",this.isOriginal=t===G,this.icon=this.isOriginal?"original":"slider",this.iconSize=this.isOriginal?40:20,this.requestUpdate("filter",r),this.updateFilterLabels(t)}onClick(e){if(this.active)this.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0);else{let t=this.$["*sliderEl"];t.setOperation(this._operation,this._filter),t.apply()}this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{operation:Ce(this.$["*operationTooltip"])}),this.$["*currentFilter"]=this._filter}_previewSrc(){let e=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),t=Number.isFinite(e)&&e>0?e:this.iconSize||32,r=window.devicePixelRatio,o=Math.ceil(r*t),n=r>=2?"lightest":"normal",a=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==G?{name:this._filter,amount:a}:void 0,W(this._originalUrl,q(Ge,ie(l),`quality/${n}`,`scale_crop/${o}x${o}/center`))}async _observerCallback(e,t){e[0]?.isIntersecting?await this.loadPreview(t):this._cancelPreload?.()}initCallback(){super.initCallback(),"IntersectionObserver"in window&&(this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]}));let e=this.$["*originalUrl"];this._originalUrl=e??"",this.sub("*originalUrl",t=>{this._originalUrl=t??"",!this.isOriginal&&this._originalUrl&&this.isConnected&&!this.previewImage&&(this._observer?.observe(this),this.schedulePreviewVisibilityCheck())}),this.isOriginal||(this._observer?.observe(this),this.schedulePreviewVisibilityCheck()),this._filter&&this.updateFilterLabels(this._filter),this.sub("*currentFilter",t=>{this.active=!!(t&&t===this._filter)}),this.sub("*networkProblems",async t=>{t||(this.previewImage?await this.loadPreview():this.schedulePreviewVisibilityCheck())})}disconnectedCallback(){super.disconnectedCallback(),this._observer?.disconnect(),this._cancelPreload?.(),this.clearPreviewVisibilityChecks()}updated(e){super.updated(e),e.has("isOriginal")&&(this.isOriginal?this._observer?.unobserve(this):(this._observer?.observe(this),this.schedulePreviewVisibilityCheck()))}updateFilterLabels(e){if(!e){this.titleProp="";return}let t=this.l10n("a11y-cloud-editor-apply-filter",{name:e.toLowerCase()});this.titleProp=t}async loadPreview(e){if(!this.isConnected){e?.unobserve(this),this._cancelPreload?.(),this._cancelPreload=void 0;return}if(!this._originalUrl){!this.previewVisibilityCheckTimeout&&!this.previewVisibilityCheckRaf&&this.schedulePreviewVisibilityCheck();return}let t=++this._lastPreviewRequestId,r="";try{r=await this.proxyUrl(this._previewSrc())}catch(a){this.$["*networkProblems"]=!0,console.error("Failed to resolve preview URL",{error:a});return}this.previewLoaded=!1,this._cancelPreload?.();let{promise:o,cancel:n}=Pe(r);this._cancelPreload=()=>{n(),this._lastPreviewRequestId===t&&(this._cancelPreload=void 0)};try{if(await o,this._lastPreviewRequestId!==t||!this.isConnected)return;this.previewImage=r,this.previewLoaded=!0,this.clearPreviewVisibilityChecks(),(e??this._observer)?.unobserve(this)}catch(a){this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:a}),this.schedulePreviewVisibilityCheck()}finally{this._lastPreviewRequestId===t&&(this._cancelPreload=void 0)}}schedulePreviewVisibilityCheck(){if(!this.isConnected||this.previewImage||this.previewLoaded||this.isOriginal){this.clearPreviewVisibilityChecks();return}this.previewVisibilityCheckRaf&&cancelAnimationFrame(this.previewVisibilityCheckRaf),this.previewVisibilityCheckRaf=requestAnimationFrame(()=>{if(this.previewVisibilityCheckRaf=void 0,!this.isConnected||this.previewImage||this.previewLoaded||this.isOriginal){this.clearPreviewVisibilityChecks();return}let e=this.getBoundingClientRect(),t=e.width>0&&e.height>0,r=window.innerWidth||document.documentElement.clientWidth,o=window.innerHeight||document.documentElement.clientHeight;if(t&&e.bottom>0&&e.right>0&&e.top<o&&e.left<r){this.loadPreview();return}this.previewVisibilityCheckTimeout=window.setTimeout(()=>{this.previewVisibilityCheckTimeout=void 0,this.schedulePreviewVisibilityCheck()},500)})}clearPreviewVisibilityChecks(){this.previewVisibilityCheckRaf&&(cancelAnimationFrame(this.previewVisibilityCheckRaf),this.previewVisibilityCheckRaf=void 0),this.previewVisibilityCheckTimeout&&(window.clearTimeout(this.previewVisibilityCheckTimeout),this.previewVisibilityCheckTimeout=void 0)}get shouldShowPreview(){return!!(this.previewLoaded&&!this.active&&!this.isOriginal)}render(){let e=this.onClick,t={opacity:this.shouldShowPreview?"1":"0"};this.previewImage&&(t.backgroundImage=`url(${this.previewImage})`);let r={opacity:this.shouldShowPreview?"0":"1"};return m.html`<button role="option" type="button" class=${(0,D.classMap)(this.buttonClasses)} aria-label=${(0,C.ifDefined)(this.titleProp)} title=${(0,C.ifDefined)(this.titleProp)} @click=${e} ><div class="uc-preview" ?loaded=${this.previewLoaded} style=${(0,B.styleMap)(t)}></div><uc-icon class=${(0,D.classMap)({"uc-original-icon":this.isOriginal})} name=${this.icon} style=${(0,B.styleMap)(r)} ></uc-icon></button>`}};p([(0,c.state)()],ae.prototype,"previewImage",2),p([(0,c.state)()],ae.prototype,"previewLoaded",2),p([(0,c.property)({type:Boolean,reflect:!0})],ae.prototype,"isOriginal",2),p([(0,c.property)({type:Number})],ae.prototype,"iconSize",2),p([(0,c.property)({type:String})],ae.prototype,"filter",1);var Ni=(s,i)=>{let e=!1,t,r=0,o=((...n)=>{e?(t&&clearTimeout(t),t=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),e=!0)});return Object.defineProperty(o,"cancel",{configurable:!1,writable:!1,enumerable:!1,value:()=>{t&&clearTimeout(t)}}),o};function Di(s,i){let e={};for(let t of i){let r=s[t];(Object.hasOwn(s,t)||r!==void 0)&&(e[t]=r)}return e}function Ee(s,i,e){let r=window.devicePixelRatio,o=Math.min(Math.ceil(i*r),3e3),n=r>=2?"lightest":"normal";return W(s,q(Ge,ie(e),`quality/${n}`,`stretch/off/-/resize/${o}x`,`@clib/${qe}/${We}/uc-cloud-image-editor/`))}function Zr(s){return s?[({dimensions:e,coords:t})=>[...e,...t].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:e,coords:t})=>e.every(r=>r>0)&&t.every(r=>r>=0)].every(e=>e(s)):!0}var nt=class extends T{constructor(){super();this.ctxOwner=!0;this._imageSize={width:0,height:0};this._ctx=null;this._isActive=!1;this._image=null;this.canvasRef=(0,g.createRef)();this.frameRef=(0,g.createRef)();this.init$={...this.init$,"*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=M(this._commit.bind(this),300),this._handleResizeThrottled=Ni(()=>{!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())},100)}firstUpdated(e){super.firstUpdated(e),this._initCanvas()}_syncTransformations(){let e=this.$["*editorTransformations"],t=Di(e,Object.keys(this.$["*operations"])),r={...this.$["*operations"],...t};this.$["*operations"]=r}_initCanvas(){let e=this.canvasRef.value;if(!e)return;let t=e.getContext("2d"),r=this.offsetWidth,o=this.offsetHeight,n=window.devicePixelRatio;e.style.width=`${r}px`,e.style.height=`${o}px`,e.width=r*n,e.height=o*n,t?.scale(n,n),this._canvas=e,this._ctx=t}_alignImage(){if(!this._isActive||!this._image)return;let e=this._image,t=this.$["*padding"],r=this.$["*operations"],{rotate:o}=r,n={width:this.offsetWidth,height:this.offsetHeight},a=Te({width:e.naturalWidth,height:e.naturalHeight},o),l;if(a.width>n.width-t*2||a.height>n.height-t*2){let d=a.width/a.height,f=n.width/n.height;if(d>f){let h=n.width-t*2,y=h/d,b=0+t,_=t+(n.height-t*2)/2-y/2;l={x:b,y:_,width:h,height:y}}else{let h=n.height-t*2,y=h*d,b=t+(n.width-t*2)/2-y/2,_=0+t;l={x:b,y:_,width:y,height:h}}}else{let{width:d,height:f}=a,h=t+(n.width-t*2)/2-d/2,y=t+(n.height-t*2)/2-f/2;l={x:h,y,width:d,height:f}}this.$["*imageBox"]=we(l)}_alignCrop(){let e=this.$["*cropBox"],t=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,n=this.$["*editorTransformations"].crop,{width:a,x:l,y:d}=t;if(n){let{dimensions:[y,b],coords:[_,I]}=n,{width:R}=Te(this._imageSize,o),P=a/R;e=_e(we({x:l+_*P,y:d+I*P,width:y*P,height:b*P}),t)}let f=this.$["*currentAspectRatio"],h=f?f.width/f.height:void 0;if(!Mi(e,t)||h&&!$i(e,h)){let y=t.width/t.height,b=t.width,_=t.height;h&&(y>h?b=Math.min(t.height*h,t.width):_=Math.min(t.width/h,t.height)),e={x:t.x+t.width/2-b/2,y:t.y+t.height/2-_/2,width:b,height:_}}this.$["*cropBox"]=_e(we(e),t)}_drawImage(){let e=this._ctx;if(!e)return;let t=this._image;if(!t)return;let r=this.$["*imageBox"],o=this.$["*operations"],{mirror:n,flip:a,rotate:l}=o,d=Te({width:r.width,height:r.height},l);e.save(),e.translate(r.x+r.width/2,r.y+r.height/2),e.rotate(l*Math.PI*-1/180),e.scale(n?-1:1,a?-1:1),e.drawImage(t,-d.width/2,-d.height/2,d.width,d.height),e.restore()}_draw(){if(!this._isActive||!this._image||!this._canvas||!this._ctx)return;let e=this._canvas;this._ctx.clearRect(0,0,e.width,e.height),this._drawImage()}_animateIn({fromViewer:e}){this._image&&(this.frameRef.value?.toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=U({"uc-active_from_viewer":e,"uc-active_from_editor":!e,"uc-inactive_to_editor":!1})}))}_getCropDimensions(){let e=this.$["*cropBox"],t=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a}=t,{width:l,height:d}=Te(this._imageSize,o),{width:f,height:h}=e,y=n/l,b=a/d;return[ne(Math.round(f/y),1,l),ne(Math.round(h/b),1,d)]}_getCropTransformation(){let e=this.$["*cropBox"],t=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a,x:l,y:d}=t,{width:f,height:h}=Te(this._imageSize,o),{x:y,y:b}=e,_=n/f,I=a/h,R=this._getCropDimensions(),P={dimensions:R,coords:[ne(Math.round((y-l)/_),0,f-R[0]),ne(Math.round((b-d)/I),0,h-R[1])]};if(!Zr(P)){console.error("Cropper is trying to create invalid crop object",{payload:P});return}if(!(R[0]===f&&R[1]===h))return P}_commit(){if(!this.isConnected||!this._imageSize)return;let e=this.$["*operations"],{rotate:t,mirror:r,flip:o}=e,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:r,flip:o};this.$["*editorTransformations"]=l}setValue(e,t){this.$["*operations"]={...this.$["*operations"],[e]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(e){return this.$["*operations"][e]}async activate(e,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,await this.updateComplete,this._initCanvas(),this._imageSize=e,this.removeEventListener("transitionend",this._reset);try{let r=this.$["*originalUrl"],o=this.$["*editorTransformations"];this._image=await this._waitForImage(r,o),this._syncTransformations(),this._handleResizeThrottled(),this._animateIn({fromViewer:t})}catch(r){console.error("Failed to activate cropper",{error:r}),this.telemetryManager.sendEventError(r,"cloud editor image. Failed to activate cropper")}this._observer=new ResizeObserver(r=>{let[o]=r;if(!o)return;o.contentRect.width>0&&o.contentRect.height>0&&this._isActive&&this._image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:e=!1}={}){this._isActive&&(!e&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=U({"uc-active_from_viewer":!1,"uc-active_from_editor":!1,"uc-inactive_to_editor":!0}),this.frameRef.value?.toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),this._observer?.disconnect())}_transitionToCrop(){let e=this._getCropDimensions(),t=this.$["*cropBox"],r=Math.min(this.offsetWidth,e[0])/t.width,o=Math.min(this.offsetHeight,e[1])/t.height,n=Math.min(r,o),a=t.x+t.width/2,l=t.y+t.height/2;this.style.transform=`scale(${n}) translate(${(this.offsetWidth/2-a)/n}px, ${(this.offsetHeight/2-l)/n}px)`,this.style.transformOrigin=`${a}px ${l}px`}_transitionToImage(){let e=this.$["*cropBox"],t=e.x+e.width/2,r=e.y+e.height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${t}px ${r}px`}_reset(){this._isActive||(this._image=null)}async _waitForImage(e,t){let r=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let o=await this.proxyUrl(Ee(e,r,t)),{promise:n,cancel:a,image:l}=Pe(o),d=this._handleImageLoading(o);return l.addEventListener("load",d,{once:!0}),l.addEventListener("error",d,{once:!0}),this._cancelPreload?.(),this._cancelPreload=a,n.then(()=>l).catch(f=>(console.error("Failed to load image",{error:f}),this.$["*networkProblems"]=!0,l))}_handleImageLoading(e){let t="crop",r=this.$["*loadingOperations"],o=r.get(t);return o||(o=new Map,r.set(t,o)),o.get(e)||(o.set(e,!0),this.$["*loadingOperations"]=r),()=>{let n=r.get(t);n?.has(e)&&(n.delete(e),this.$["*loadingOperations"]=r)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this._image&&this._commitDebounced()}),this.sub("*currentAspectRatio",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",e=>{e||this._isActive&&this._imageSize&&this.activate(this._imageSize,{fromViewer:!1})})},0)}disconnectedCallback(){super.disconnectedCallback(),this._observer?.disconnect(),this._image&&(this._image=null)}render(){return m.html`<canvas class="uc-canvas" ${(0,g.ref)(this.canvasRef)}></canvas><uc-crop-frame ${(0,g.ref)(this.frameRef)}></uc-crop-frame>`}};p([(0,c.state)()],nt.prototype,"_image",2);function Ot(s,i,e){let t=e,r=e-1,o=new Array(t);for(let n=r;n>=0;n-=1)o[n]=Math.ceil((n*i+(r-n)*s)/r);return o}function Jr(s){return typeof s=="string"&&s in j}function es(s){let i=[];for(let e=0;e<s.length-1;e+=1){let t=s[e],r=s[e+1];typeof t=="number"&&typeof r=="number"&&i.push([t,r])}return i}function ts(s,i,e){let t=es(s).find(([n,a])=>n<=i&&i<=a);if(!t)return s.map(()=>0);let[r,o]=t;return s.map(n=>{let a=Math.abs(r-o)||1,l=Math.abs(i-r)/a;return r===n?i>e?1:1-l:o===n?i>=e?l:1:0})}function is(s,i){return s.map((e,t)=>e<i?s.length-t:t)}function Ui(s,i){let e=j[s].keypointsNumber,{range:t,zero:r}=j[s];return[...new Set([...Ot(t[0],r,e+1),...Ot(r,t[1],e+1),r,i])].sort((o,n)=>o-n)}var At=class extends T{constructor(){super();this._isActive=!1;this._hidden=!0;this._operation="initial";this._transformations={};this._keypoints=[];this._raf=0;this._previewHostRef=(0,g.createRef)();this._layersHostRef=(0,g.createRef)();this.classList.add("uc-inactive_to_cropper"),this._addKeypointDebounced=M(async(e,t,r)=>{let o=()=>!this._isSame(e,t)||this._value!==r||!!this._keypoints.find(d=>d.value===r);if(o())return;let n=await this._constructKeypoint(e,r),a=new Image;a.src=n.src;let l=this._handleImageLoading(n.src);a.addEventListener("load",l,{once:!0}),a.addEventListener("error",l,{once:!0}),n.image=a,a.classList.add("uc-fader-image"),a.addEventListener("load",()=>{if(o())return;let d=this._keypoints,f=d.findIndex(_=>_.value>r);f===-1&&(f=d.length);let y=d[f]?.image,b=this._layersHostRef.value;!b||y&&!b.contains(y)||(d.splice(f,0,n),y?b.insertBefore(a,y):b.appendChild(a),this._update(e,r))},{once:!0}),a.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})},600)}_handleImageLoading(e){let t=this._operation,r=this.$["*loadingOperations"];r.has(t)||r.set(t,new Map);let o=r.get(t);return o&&!o.get(e)&&(o.set(e,!0),this.$["*loadingOperations"]=r),()=>{let n=r.get(t);n?.has(e)&&(n.delete(e),this.$["*loadingOperations"]=r)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let e of this._keypoints){let{image:t}=e;t&&(t.style.opacity=e.opacity.toString(),t.style.zIndex=e.zIndex.toString())}})}_imageSrc({url:e=this._url,filter:t=this._filter??void 0,operation:r,value:o}={}){if(!e)throw new Error("URL is not defined");let n={...this._transformations};r&&(r==="filter"?t&&typeof o=="number"&&(n.filter={name:t,amount:o}):typeof o=="number"&&(n[r]=o));let a=this.offsetWidth;return this.proxyUrl(Ee(e,a,n))}async _constructKeypoint(e,t){return{src:await this._imageSrc({operation:e,value:t}),image:void 0,opacity:0,zIndex:0,value:t}}_isSame(e,t){return this._operation===e&&this._filter===t}set(e){let t=typeof e=="string"?parseInt(e,10):e;!Jr(this._operation)||!Number.isFinite(t)||(this._update(this._operation,t),this._addKeypointDebounced(this._operation,this._filter,t))}_update(e,t){this._operation=e,this._value=t;let{zero:r}=j[e],o=this._keypoints.map(l=>l.value),n=ts(o,t,r),a=is(o,r);this._keypoints.forEach((l,d)=>{let f=n[d],h=a[d];typeof f=="number"&&(l.opacity=f),typeof h=="number"&&(l.zIndex=h)}),this._flush()}_createPreviewImage(){let e=new Image;return e.classList.add("uc-fader-image","uc-fader-image--preview"),e.style.opacity="0",e}async _initNodes(){this._previewImage=this._previewImage||this._createPreviewImage();let e=this._previewImage;e&&this._ensurePreviewAttached(e);let t=this._keypoints.map(d=>d.src),{images:r,promise:o,cancel:n}=Le(t);r.forEach(d=>{let f=this._handleImageLoading(d.src);d.addEventListener("load",f),d.addEventListener("error",f)}),this._cancelLastImages=()=>{n(),this._cancelLastImages=void 0};let a=this._operation,l=this._filter;if(await o,this._isActive&&this._isSame(a,l)){let d=this._layersHostRef.value;if(!d)return;d.replaceChildren(),this._keypoints.forEach((f,h)=>{let y=r[h];y&&(y.classList.add("uc-fader-image"),f.image=y,d.appendChild(y))}),this._flush()}}async setTransformations(e){if(this._transformations=e,this._previewImage){let t=await this._imageSrc(),r=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",r,{once:!0}),this._previewImage.addEventListener("error",r,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}async preload({url:e,filter:t,operation:r,value:o}){if(!r||typeof o!="number")return;this._cancelBatchPreload?.();let n=Ui(r,o),a=await Promise.all(n.map(d=>this._imageSrc({url:e,filter:t,operation:r,value:d}))),{cancel:l}=Le(a);this._cancelBatchPreload=l}_setOriginalSrc(e){let t=this._previewImage||this._createPreviewImage();if(this._ensurePreviewAttached(t),this._previewImage=t,t.src===e){t.style.opacity="1",t.style.transform="scale(1)",this.className=U({"uc-active_from_viewer":this._fromViewer,"uc-active_from_cropper":!this._fromViewer,"uc-inactive_to_cropper":!1});return}t.style.opacity="0";let r=this._handleImageLoading(e);t.addEventListener("error",r,{once:!0}),t.src=e,t.addEventListener("load",()=>{r(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=U({"uc-active_from_viewer":this._fromViewer,"uc-active_from_cropper":!this._fromViewer,"uc-inactive_to_cropper":!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}async activate({url:e,operation:t,value:r,filter:o,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,await this.updateComplete,this._url=e,this._operation=t??"initial",this._value=r,this._filter=o,this._fromViewer=n,typeof r!="number"&&!o){let l=await this._imageSrc({operation:t,value:r});this._setOriginalSrc(l),this._clearLayersHost();return}!t||typeof r!="number"||(this._keypoints=await Promise.all(Ui(t,r).map(l=>this._constructKeypoint(t,l))),this._update(t,r),this._initNodes())}deactivate({hide:e=!0}={}){this._isActive=!1,this._cancelLastImages?.(),this._cancelBatchPreload?.(),e&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=U({"uc-active_from_viewer":!1,"uc-active_from_cropper":!1,"uc-inactive_to_cropper":!0}),this.addEventListener("transitionend",()=>{this._clearLayersHost()},{once:!0})):this._clearLayersHost()}_ensurePreviewAttached(e){let t=this._previewHostRef.value;t&&(t.contains(e)||t.appendChild(e))}_clearLayersHost(){this._layersHostRef.value?.replaceChildren()}render(){return m.html`<div class="uc-fader-preview-host" ${(0,g.ref)(this._previewHostRef)}></div><div class="uc-fader-layers-host" ${(0,g.ref)(this._layersHostRef)}></div>`}};var at=class extends ${constructor(){super(...arguments);this._operation=""}get operation(){return this._operation}set operation(e){let t=e??"";if(this._operation===t)return;let r=this._operation;this._operation=t,this.requestUpdate("operation",r),t&&this.updateOperationMetadata(t)}updateOperationMetadata(e){this.icon=e;let t=()=>{let o=this.l10n("a11y-cloud-editor-apply-tuning",{name:this.l10n(e).toLowerCase()});return this.titleProp=o,o},r=()=>{let o=this.l10n(e);return this.title=o,o};t(),r()}initCallback(){super.initCallback(),this._operation&&this.updateOperationMetadata(this._operation),this.sub("*editorTransformations",e=>{if(!this._operation)return;let{zero:t}=j[this._operation],r=e[this._operation],o=typeof r<"u"?r!==t:!1;this.active=o})}onClick(e){this.$["*sliderEl"]?.setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation,this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{operation:Ce(this.$["*operationTooltip"])})}};p([(0,c.property)({type:String})],at.prototype,"operation",1);var rs=1,Fi=()=>{},It=class extends T{constructor(){super(...arguments);this.handleWheel=e=>{e.preventDefault();let{deltaY:t,deltaX:r}=e;if(Math.abs(r)>rs){this.scrollLeft+=r;return}this.scrollLeft+=t}}connectedCallback(){super.connectedCallback(),this.addEventListener("wheel",this.handleWheel,{passive:!1}),this.addEventListener("scroll",Fi,{passive:!0})}disconnectedCallback(){this.removeEventListener("wheel",this.handleWheel),this.removeEventListener("scroll",Fi),super.disconnectedCallback()}};var V=class extends T{constructor(){super(...arguments);this.showLoader=!1;this.showMainToolbar=!0;this.showSubToolbar=!1;this.showTabToggles=!0;this.tabList=[...L];this.activeTab=E.CROP;this.useSliderPanel=!0;this.tooltipVisible=!1;this.operationTooltip=null;this.tabIndicatorOffset=0;this.tabIndicatorWidth=0;this.sliderRef=(0,g.createRef)();this.tabIndicatorRef=(0,g.createRef)();this.tabToggleRefs={[E.CROP]:(0,g.createRef)(),[E.TUNING]:(0,g.createRef)(),[E.FILTERS]:(0,g.createRef)()};this.handleWindowResize=()=>{this._syncTabIndicator()};this.cropPresets=[];this._debouncedShowLoader=M(e=>{this.showLoader=e},500);this._updateInfoTooltip=M(()=>{let e=this.$["*editorTransformations"],t=this.$["*currentOperation"],r="",o=!1;if(this.$["*tabId"]===E.FILTERS)if(o=!0,this.$["*currentFilter"]&&e?.filter?.name===this.$["*currentFilter"]){let n=e?.filter?.amount||100;r=`${this.$["*currentFilter"]} ${n}`}else r=this.l10n(G);else if(this.showSubToolbar&&this.$["*tabId"]===E.TUNING&&t){o=!0;let n=e?.[t]||j[t].zero;r=`${this.l10n(t)} ${n}`}o&&(this.$["*operationTooltip"]=r),this.tooltipVisible=o},0);this.subTopToolbarStyles={hidden:"uc-sub-toolbar--top-hidden",visible:"uc-sub-toolbar--visible"};this.subBottomToolbarStyles={hidden:"uc-sub-toolbar--bottom-hidden",visible:"uc-sub-toolbar--visible"};this.tabContentStyles={hidden:"uc-tab-content--hidden",visible:"uc-tab-content--visible"};this.tabToggleStyles={hidden:"uc-tab-toggle--hidden",visible:"uc-tab-toggle--visible"};this.tabTogglesStyles={hidden:"uc-tab-toggles--hidden",visible:"uc-tab-toggles--visible"};this.init$={...this.init$,"*sliderEl":null,"*showSlider":!1,"*showListAspectRatio":!1,"*currentFilter":G,"*currentOperation":null,"*operationTooltip":null};this.handleCancel=e=>{this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{action:"cancel"}),this._cancelPreload?.();let t=this.$["*on.cancel"];t?.()};this.handleApply=e=>{this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{action:"apply"});let t=this.$["*on.apply"];t?.(this.$["*editorTransformations"])};this.handleApplySlider=e=>{this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{action:"apply-slider",operation:Ce(this.$["*operationTooltip"])}),this.sliderRef.value?.apply(),this._onSliderClose()};this.handleCancelSlider=e=>{this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{action:"cancel-slider"}),this.sliderRef.value?.cancel(),this._onSliderClose()};this.handleTabClick=e=>{let r=e.currentTarget?.getAttribute("data-id");r&&(this.telemetryManager.sendEventCloudImageEditor(e,r),this._activateTab(r,{fromViewer:!1}))}}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===E.CROP&&(this.$["*showListAspectRatio"]=!1),this.$["*tabId"]===E.TUNING&&(this.tooltipVisible=!1)}_activateTab(e,{fromViewer:t=!1,force:r=!1}={}){this.$["*tabId"]!==e&&(this.$["*tabId"]=e),this.applyTabState(e,{fromViewer:t,force:r})}applyTabState(e,{fromViewer:t,force:r=!1}){if(!r&&this.activeTab===e){this._syncTabIndicator();return}this.activeTab=e;let o=this.$["*faderEl"],n=this.$["*cropperEl"];e===E.CROP?(o?.deactivate(),this.$["*imageSize"]&&n?.activate(this.$["*imageSize"],{fromViewer:t})):(o?.activate({url:this.$["*originalUrl"],fromViewer:t}),n?.deactivate());for(let a of L){let l=a===e,f=this.tabToggleRefs[a]?.value;f&&(f.active=l),l&&this._syncTabIndicator()}}_syncTabIndicator(){let t=this.tabToggleRefs[this.activeTab]?.value,r=this.tabIndicatorRef.value;if(!t||!r)return;let o=t.offsetLeft,n=t.offsetWidth||Number(getComputedStyle(t).width.replace("px",""));(this.tabIndicatorOffset!==o||this.tabIndicatorWidth!==n)&&(this.tabIndicatorOffset=o,this.tabIndicatorWidth=n,r.style.transform=`translateX(${o}px)`,r.style.width=`${n}px`)}get hasAspectRatioPicker(){return this.cropPresets.length>=3}renderControlsByTab(e){switch(e){case E.CROP:return this.renderCropTabControls();case E.FILTERS:return this.renderFilterTabControls();case E.TUNING:return this.renderTuningTabControls();default:return[]}}renderCropTabControls(){let e=[];if(this.hasAspectRatioPicker)e.push(()=>this.renderFreeformControl());else for(let t of this.cropPresets)e.push(()=>this.renderAspectRatioControl(t));for(let t of ni)e.push(()=>this.renderCropOperationControl(t));return this.renderControlGroup(e)}renderFilterTabControls(){let t=[G,...oi].map(r=>()=>this.renderFilterControl(r));return this.renderControlGroup(t)}renderTuningTabControls(){let e=si.map(t=>()=>this.renderOperationControl(t));return this.renderControlGroup(e)}renderControlGroup(e){return e.length?e.map(r=>r()):[]}renderFreeformControl(){return m.html`<uc-editor-freeform-button-control></uc-editor-freeform-button-control>`}renderAspectRatioControl(e){return m.html`<uc-editor-aspect-ratio-button-control .aspectRatio=${e}></uc-editor-aspect-ratio-button-control>`}renderCropOperationControl(e){return m.html`<uc-editor-crop-button-control .operation=${e}></uc-editor-crop-button-control>`}renderFilterControl(e){return m.html`<uc-editor-filter-control .filter=${e}></uc-editor-filter-control>`}renderOperationControl(e){return m.html`<uc-editor-operation-control .operation=${e}></uc-editor-operation-control>`}renderAspectRatioList(){return this.hasAspectRatioPicker?this.cropPresets.map(e=>this.renderAspectRatioControl(e)):[]}async _preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let e=this.$["*imgContainerEl"].offsetWidth,t=await this.proxyUrl(Ee(this.$["*originalUrl"],e,this.$["*editorTransformations"]));this._cancelPreload?.();let{cancel:r}=Le([t]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}initCallback(){super.initCallback();let e=this.$["*cropPresetList"]??[];this.cropPresets=[...e],this.sub("*cropPresetList",t=>{this.cropPresets=[...t??[]]}),this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{let r=t?.filter?.name;this.$["*currentFilter"]!==r&&(this.$["*currentFilter"]=r??"")}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",t=>{this.applyTabState(t,{fromViewer:!1,force:!0}),this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]?.deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]?.setTransformations(t)}),this.sub("*loadingOperations",t=>{let r=!1;for(let[,o]of t.entries()){if(r)break;for(let[,n]of o.entries())if(n){r=!0;break}}this._debouncedShowLoader(r)}),this.sub("*showSlider",t=>{t?(this.showSubToolbar=!0,this.showMainToolbar=!1,this.useSliderPanel=!0):this.$["*showListAspectRatio"]||(this.showSubToolbar=!1,this.showMainToolbar=!0)}),this.sub("*showListAspectRatio",t=>{t?(this.showSubToolbar=!0,this.showMainToolbar=!1,this.useSliderPanel=!1):this.$["*showSlider"]||(this.showSubToolbar=!1,this.showMainToolbar=!0)}),this.sub("*tabList",t=>{if(this.tabList=t,this.showTabToggles=t.length>1,!t.includes(this.$["*tabId"])&&t.length>0){let[r]=t;r&&this._activateTab(r,{fromViewer:!1});return}this._syncTabIndicator()}),this.sub("*operationTooltip",t=>{this.operationTooltip=t}),this._updateInfoTooltip()}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.handleWindowResize)}firstUpdated(e){super.firstUpdated(e),this.assignSharedElements(),this._syncTabIndicator()}updated(e){super.updated(e),(e.has("activeTab")||e.has("tabList"))&&this.updateComplete.then(()=>this._syncTabIndicator()),(e.has("showSubToolbar")||e.has("showMainToolbar"))&&this.assignSharedElements()}disconnectedCallback(){window.removeEventListener("resize",this.handleWindowResize),super.disconnectedCallback(),this.$["*showSlider"]=!1,this.$["*showListAspectRatio"]=!1}assignSharedElements(){let e=this.sliderRef.value;e&&(this.$["*sliderEl"]=e)}renderTabToggle(e){let t=this.tabList.includes(e),r=this.activeTab===e,o=this.tabList.indexOf(e),n=o>=0?(0,B.styleMap)({gridColumn:`${o+1}`}):m.nothing;return m.html` <uc-presence-toggle class="uc-tab-toggle" .visible=${t} .styles=${this.tabToggleStyles}><uc-btn-ui theme="tab" data-id=${e} icon=${e} role="tab" aria-controls=${`tab_${e}`} aria-selected=${r?"true":"false"} title-prop=${`a11y-editor-tab-${e}`} .active=${r} style=${n} @click=${this.handleTabClick} ${(0,g.ref)(this.tabToggleRefs[e])} ></uc-btn-ui></uc-presence-toggle>`}renderTabContent(e){let t=this.activeTab===e,r=this.renderControlsByTab(e);return m.html` <uc-presence-toggle id=${`tab_${e}`} class="uc-tab-content" .visible=${t} .styles=${this.tabContentStyles} ><uc-editor-scroller hidden-scrollbar><div class="uc-controls-list_align"><div role="listbox" aria-orientation="horizontal" class="uc-controls-list_inner"> ${r.length?r:m.nothing} </div></div></uc-editor-scroller></uc-presence-toggle>`}render(){let e=["uc-info-tooltip",this.tooltipVisible?"uc-info-tooltip_visible":"uc-info-tooltip_hidden"].join(" "),t=this.hasAspectRatioPicker;return m.html`<uc-line-loader-ui .active=${this.showLoader}></uc-line-loader-ui><div class="uc-info-tooltip_container"><div class="uc-info-tooltip_wrapper"><div class=${e}>${this.operationTooltip??""}</div></div></div><div class="uc-toolbar-container"><uc-presence-toggle role="tablist" class="uc-sub-toolbar" .visible=${this.showMainToolbar} .styles=${this.subTopToolbarStyles} ><div class="uc-tab-content-row"> ${L.map(r=>this.renderTabContent(r))} </div><div class="uc-controls-row"><uc-presence-toggle class="uc-tab-toggles" .visible=${this.showTabToggles} .styles=${this.tabTogglesStyles} @initial-render=${()=>this._syncTabIndicator()} ><div class="uc-tab-toggles_indicator" ${(0,g.ref)(this.tabIndicatorRef)} ></div> ${L.map(r=>this.renderTabToggle(r))} </uc-presence-toggle><uc-btn-ui style="order: -1" theme="secondary-icon" icon="closeMax" title-prop="cancel" @click=${this.handleCancel} ></uc-btn-ui><uc-btn-ui theme="primary-icon" icon="done" title-prop="apply" @click=${this.handleApply}></uc-btn-ui></div></uc-presence-toggle><uc-presence-toggle class="uc-sub-toolbar" .visible=${this.showSubToolbar} .styles=${this.subBottomToolbarStyles}><div class="uc-slider" ?hidden=${!this.useSliderPanel}><uc-editor-slider ${(0,g.ref)(this.sliderRef)}></uc-editor-slider></div><div class="uc-list-aspect-ratio-container" ?hidden=${this.useSliderPanel||!t}> ${t?m.html`<div class="uc-list-aspect-ratio">${this.renderAspectRatioList()}</div>`:m.nothing} </div><div class="uc-controls-row"><uc-btn-ui theme="secondary" @click=${this.handleCancelSlider} text=${this.l10n("cancel")}></uc-btn-ui><uc-btn-ui theme="primary" @click=${this.handleApplySlider} text=${this.l10n("apply")}></uc-btn-ui></div></uc-presence-toggle></div>`}};p([(0,c.state)()],V.prototype,"showLoader",2),p([(0,c.state)()],V.prototype,"showMainToolbar",2),p([(0,c.state)()],V.prototype,"showSubToolbar",2),p([(0,c.state)()],V.prototype,"showTabToggles",2),p([(0,c.state)()],V.prototype,"tabList",2),p([(0,c.state)()],V.prototype,"activeTab",2),p([(0,c.state)()],V.prototype,"useSliderPanel",2),p([(0,c.state)()],V.prototype,"tooltipVisible",2),p([(0,c.state)()],V.prototype,"operationTooltip",2),p([(0,c.state)()],V.prototype,"cropPresets",2);var K=class extends T{constructor(){super(...arguments);this.text="";this.icon="";this.active=!1;this.reverse=!1;this.theme="default";this.ariaRole="";this.ariaControls="";this.titleProp=""}firstUpdated(e){super.firstUpdated(e),this.applyReverse(),this.applyThemeClass()}updated(e){super.updated(e),e.has("reverse")&&this.applyReverse(),e.has("theme")&&this.applyThemeClass()}applyReverse(){this.style.flexDirection=this.reverse?"row-reverse":""}applyThemeClass(){this.theme&&this.theme!=="custom"&&(this.className=`uc-${this.theme}`)}get iconClassMap(){let e=this.computedIconHidden;return{"uc-icon":!0,"uc-icon_left":!this.reverse,"uc-icon_right":this.reverse,"uc-icon_hidden":e,"uc-icon_single":this.computedIconSingle}}get computedIconHidden(){return!this.icon}get computedIconSingle(){return!this.text&&!this.computedIconHidden}render(){return m.html`<button type="button" role=${(0,C.ifDefined)(this.ariaRole||void 0)} aria-controls=${(0,C.ifDefined)(this.ariaControls||void 0)} aria-label=${(0,C.ifDefined)(this.l10n(this.titleProp))} title=${(0,C.ifDefined)(this.l10n(this.titleProp))} ><uc-icon class=${(0,D.classMap)(this.iconClassMap)} name=${(0,C.ifDefined)(this.icon||void 0)} ?hidden=${this.computedIconHidden} ></uc-icon><div class="uc-text">${this.text}</div></button>`}};p([(0,c.property)({type:String})],K.prototype,"text",2),p([(0,c.property)({type:String})],K.prototype,"icon",2),p([(0,c.property)({type:Boolean,reflect:!0})],K.prototype,"active",2),p([(0,c.property)({type:Boolean,reflect:!0})],K.prototype,"reverse",2),p([(0,c.property)({type:String,reflect:!0})],K.prototype,"theme",2),p([(0,c.property)({attribute:"aria-role"})],K.prototype,"ariaRole",2),p([(0,c.property)({attribute:"aria-controls"})],K.prototype,"ariaControls",2),p([(0,c.property)({attribute:"title-prop"})],K.prototype,"titleProp",2);var lt=class extends T{constructor(){super(...arguments);this.active=!1;this.lineRef=(0,g.createRef)();this._isAnimating=!1;this.handleTransitionEndRight=()=>{let e=this.lineRef.value;e&&(this.resetLine(e),this._isAnimating&&this.active&&this.start())}}firstUpdated(e){super.firstUpdated(e),this.active&&this.start()}updated(e){super.updated(e),e.has("active")&&(this.active?this.start():this.stop())}start(){let e=this.lineRef.value;if(!e)return;this._isAnimating=!0;let{width:t}=this.getBoundingClientRect();e.removeEventListener("transitionend",this.handleTransitionEndRight),e.style.transition="transform 1s",e.style.opacity="1",e.style.transform=`translateX(${t}px)`,e.addEventListener("transitionend",this.handleTransitionEndRight,{once:!0})}stop(){let e=this.lineRef.value;e&&(this._isAnimating=!1,e.removeEventListener("transitionend",this.handleTransitionEndRight),this.resetLine(e))}resetLine(e){e.style.transition="initial",e.style.opacity="0",e.style.transform="translateX(-101%)"}render(){return m.html`<div class="uc-inner"><div class="uc-line" ${(0,g.ref)(this.lineRef)}></div></div>`}};p([(0,c.property)({type:Boolean,reflect:!0})],lt.prototype,"active",2);var pe={transition:"uc-transition",visible:"uc-visible",hidden:"uc-hidden"},Me=class extends T{constructor(){super(...arguments);this._visible=!1;this._styles=pe;this._visibleStyle=pe.visible;this._hiddenStyle=pe.hidden;this._externalTransitions=!1;this.initialRenderComplete=!1}set visible(e){this._visible=e,this._handleVisible()}get visible(){return this._visible}set styles(e){this._styles=e,this._externalTransitions=!0,this._visibleStyle=e.visible??pe.visible,this._hiddenStyle=e.hidden??pe.hidden}get styles(){return this._styles}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",_i(this,{[pe.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.toggleAttribute("inert",!this._visible)}dispatchInitialRenderEvent(){this.initialRenderComplete||(this.initialRenderComplete=!0,this.dispatchEvent(new CustomEvent("initial-render",{bubbles:!0,composed:!0})))}initCallback(){super.initCallback(),this.classList.toggle("uc-initial",!0),this._externalTransitions||this.classList.add(pe.transition),this._handleVisible(),setTimeout(()=>{this.classList.toggle("uc-initial",!1),this.dispatchInitialRenderEvent()},0)}};p([(0,c.property)({type:Boolean})],Me.prototype,"visible",1),p([(0,c.property)({attribute:!1})],Me.prototype,"styles",1);var ee=class extends T{constructor(){super();this._thumbSize=0;this.inputRef=(0,g.createRef)();this.thumbRef=(0,g.createRef)();this.stepsRef=(0,g.createRef)();this.disabled=!1;this.min=0;this.max=100;this.defaultValue=0;this.zero=0;this._currentValue=0;this.handleSliderInput=e=>{e.stopPropagation();let t=this._extractEventValue(e);t!==null&&(this._setCurrentValue(t),this.emitSliderEvent("slider-input",t))};this.handleSliderChange=e=>{e.stopPropagation();let t=this._extractEventValue(e);t!==null&&(this._setCurrentValue(t),this.emitSliderEvent("slider-change",t))};this.handleInputFocus=()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")};this.handleInputBlur=()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")};this.setAttribute("with-effects","")}emitSliderEvent(e,t){this.dispatchEvent(new CustomEvent(e,{detail:{value:t},bubbles:!0,composed:!0}))}firstUpdated(e){super.firstUpdated(e),this._thumbSize=Number.parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10)||0,this._syncInputValue(this._currentValue),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps(),this._updateValue(this._currentValue)}),this._observer.observe(this);let t=this.inputRef.value;t?.addEventListener("focus",this.handleInputFocus),t?.addEventListener("blur",this.handleInputBlur),window.setTimeout(()=>{this._updateValue(this._currentValue)},0)}willUpdate(e){super.willUpdate(e),e.has("defaultValue")&&this.defaultValue!==this._currentValue&&this._setCurrentValue(this.defaultValue),(e.has("min")||e.has("max"))&&this.hasUpdated&&(this._updateSteps(),this._updateValue(this._currentValue)),e.has("zero")&&this.hasUpdated&&this._updateZeroDot(this._currentValue)}_updateValue(e){this._updateZeroDot(e);let t=this.max-this.min;if(t===0)return;let{width:r}=this.getBoundingClientRect(),a=100/t*(e-this.min)*(r-this._thumbSize)/100;window.requestAnimationFrame(()=>{let l=this.thumbRef.value;l&&(l.style.transform=`translateX(${a}px)`)})}_updateZeroDot(e){if(!this._zeroDotEl)return;let t=this.max-this.min;if(t===0)return;this._zeroDotEl.style.opacity=e===this.zero?"0":"1";let{width:r}=this.getBoundingClientRect(),a=100/t*(this.zero-this.min)*(r-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl&&(this._zeroDotEl.style.transform=`translateX(${a}px)`)})}_updateSteps(){let t=this.stepsRef.value;if(!t)return;let{width:r}=t.getBoundingClientRect(),o=Math.ceil(r/2),n=Math.ceil(o/15)-2;if(this._stepsCount===n)return;let a=document.createDocumentFragment(),l=document.createElement("div"),d=document.createElement("div");l.className="uc-minor-step",d.className="uc-border-step",a.appendChild(d);for(let h=0;h<n;h+=1)a.appendChild(l.cloneNode());a.appendChild(d.cloneNode());for(let h=0;h<n;h+=1)a.appendChild(l.cloneNode());a.appendChild(d.cloneNode());let f=document.createElement("div");f.className="uc-zero-dot",a.appendChild(f),this._zeroDotEl=f,t.innerHTML="",t.appendChild(a),this._stepsCount=n}disconnectedCallback(){super.disconnectedCallback();let e=this.inputRef.value;e?.removeEventListener("focus",this.handleInputFocus),e?.removeEventListener("blur",this.handleInputBlur),this._observer?.disconnect(),this._observer=void 0}_setCurrentValue(e){Number.isFinite(e)&&(this._currentValue=e,this.hasUpdated&&(this._syncInputValue(e),this._updateValue(e)))}_syncInputValue(e){let t=this.inputRef.value;t&&(t.value=String(e))}_extractEventValue(e){let t=e.currentTarget;if(!t)return null;let r=Number.parseInt(t.value,10);return Number.isFinite(r)?r:null}render(){return m.html`<div class="uc-steps" ${(0,g.ref)(this.stepsRef)}></div><div class="uc-thumb" ${(0,g.ref)(this.thumbRef)}></div><input class="uc-input" type="range" ${(0,g.ref)(this.inputRef)} .min=${String(this.min)} .max=${String(this.max)} .value=${String(this._currentValue)} ?disabled=${this.disabled} @input=${this.handleSliderInput} @change=${this.handleSliderChange} />`}};p([(0,c.property)({type:Boolean,reflect:!0})],ee.prototype,"disabled",2),p([(0,c.property)({type:Number})],ee.prototype,"min",2),p([(0,c.property)({type:Number})],ee.prototype,"max",2),p([(0,c.property)({type:Number,attribute:!1})],ee.prototype,"defaultValue",2),p([(0,c.property)({type:Number})],ee.prototype,"zero",2),p([(0,c.state)()],ee.prototype,"_currentValue",2);var Vi=class extends x{static{this.styleAttrs=[...super.styleAttrs,"uc-wgt-common"]}constructor(){super(),this.init$={...this.init$,"*solution":this.tagName}}initCallback(){super.initCallback(),this.telemetryManager.sendEvent({eventType:Z.INIT_SOLUTION}),this.a11y?.registerBlock(this)}};var ss=["UploaderBlock","ActivityBlock","Block","SolutionBlock"];function os(s){for(let i in s){if(ss.includes(i))continue;let e=[...i].reduce((t,r)=>(r.toUpperCase()===r&&(r=`-${r.toLowerCase()}`),t+=r,t),"");e.startsWith("-")&&(e=e.replace("-","")),e.startsWith("uc-")||(e=`uc-${e}`),s[i].reg&&s[i].reg(e)}}var ct=s=>s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)?.map(i=>i.toLowerCase()).join("-");var zi=new Set;function ji(s){zi.has(s)||(zi.add(s),console.warn(s))}var ns=[{test:s=>!!s.accept&&!!s.imgOnly,message:"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."},{test:s=>s.enableVideoRecording!==null,message:"The `enableVideoRecording` parameter is deprecated and will be removed in the next major release.\nPlease use the `cameraModes` parameter instead."},{test:s=>s.defaultCameraMode!==null,message:"The `defaultCameraMode` parameter is deprecated and will be removed in the next major release.\nPlease use the `cameraModes` parameter instead."}],Ki=M(s=>{for(let{test:i,message:e}of ns)i(s)&&ji(e)},0);var Hi=(s,i)=>{let e=new URL(i);return e.hostname=`${s}.${e.hostname}`,e.toString().replace(/\/$/,"")},as="0123456789abcdefghijklmnopqrstuvwxyz",Bi=s=>{if(s<=0n)return"0";let i="";for(;s>0n;){let e=s%36n;i=as[Number(e)]+i,s=s/36n}return i},Pt=(s,i)=>{try{let e=new URL(s),t=new URL(i);return e.hostname.endsWith(t.hostname)}catch{return!1}};var ls=async s=>{let i=new TextEncoder().encode(s),e=await window.crypto.subtle.digest("SHA-256",i),t=Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("");return BigInt(`0x${t}`)},cs=10,ds=async s=>{let i=await ls(s);return Bi(i).slice(0,cs)},Gi=async(s,i)=>{let e=await ds(s);return Hi(e,i)};var Xi=s=>s instanceof Promise||!!(s&&typeof s=="object"&&"then"in s&&typeof s.then=="function");var Lt=s=>s,us=[Lt({key:"cameraModes",deps:["enableVideoRecording"],fn:({cameraModes:s,enableVideoRecording:i})=>{if(i===null)return s;let e=ce(s);return i&&!e.includes("video")?e=e.concat("video"):i||(e=e.filter(t=>t!=="video")),de(e)}}),Lt({key:"cameraModes",deps:["defaultCameraMode"],fn:({cameraModes:s,defaultCameraMode:i})=>{if(i===null)return s;let e=ce(s);return e=e.sort((t,r)=>t===i?-1:r===i?1:0),de(e)}}),Lt({key:"cdnCname",deps:["pubkey","cdnCnamePrefixed"],fn:({pubkey:s,cdnCname:i,cdnCnamePrefixed:e})=>s&&(i===Et||Pt(i,e))?Gi(s,e):i})],qi=({key:s,setValue:i,getValue:e,computationControllers:t})=>{for(let r of us)if(r.deps.includes(s)){let o={[r.key]:e(r.key)};for(let l of r.deps)o[l]=e(l);let n=new AbortController;t.get(r.key)?.abort(),t.set(r.key,n);let a;try{a=r.fn(o,{signal:n.signal})}catch(l){t.get(r.key)===n&&t.delete(r.key),console.error(`Failed to compute value for "${r.key}"`,l);return}Xi(a)?a.then(l=>{n.signal.aborted||i(r.key,l)}).catch(l=>{n.signal.aborted||console.error(`Failed to compute value for "${r.key}"`,l)}).finally(()=>{t.get(r.key)===n&&t.delete(r.key)}):i(r.key,a)}};var Mt=Object.freeze({PHOTO:"photo",VIDEO:"video"}),Au=Object.freeze({IDLE:"idle",SHOT:"shot",PLAY:"play",PAUSE:"pause",RESUME:"resume",STOP:"stop",RETAKE:"retake",ACCEPT:"accept"});var w=s=>String(s),A=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},S=s=>{if(typeof s>"u"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},Wi=s=>s==="auto"?s:S(s),Yi=s=>{let i=w(s);if(i!=="user"&&i!=="environment"&&i!=="")throw new Error(`Invalid value: "${i}"`);return i},Qi=s=>{let i=w(s);if(!Object.values(Mt).includes(i))throw new Error(`Invalid value: "${i}"`);return i},Zi=s=>{let i=w(s),e=ce(i);if(e.some(t=>!Object.values(Mt).includes(t)))throw new Error(`Invalid value: "${JSON.stringify(e)}"`);return i},Ji=s=>{if(typeof s=="object"&&!Array.isArray(s)||typeof s=="function")return s;throw new Error("Invalid metadata value. Must be an object or function.")},$t=s=>{if(typeof s=="object")return s;throw new Error("Invalid value. Must be an object.")},dt=s=>{if(typeof s=="function")return s;throw new Error("Invalid value. Must be a function.")},Nt=s=>{if(Array.isArray(s))return s;throw new Error("Must be an array.")},er=s=>{let i=w(s);if(["grid","list"].includes(i))return i;throw new Error(`Invalid value: "${i}"`)};var hs={pubkey:w,multiple:S,multipleMin:A,multipleMax:A,confirmUpload:S,imgOnly:S,accept:w,externalSourcesPreferredTypes:w,externalSourcesEmbedCss:w,store:Wi,cameraMirror:S,cameraCapture:Yi,sourceList:w,topLevelOrigin:w,maxLocalFileSizeBytes:A,thumbSize:A,showEmptyList:S,useLocalImageEditor:S,useCloudImageEditor:S,cloudImageEditorTabs:w,removeCopyright:S,cropPreset:w,imageShrink:w,modalScrollLock:S,modalBackdropStrokes:S,sourceListWrap:S,remoteTabSessionKey:w,cdnCname:w,cdnCnamePrefixed:w,baseUrl:w,socialBaseUrl:w,secureSignature:w,secureExpire:w,secureDeliveryProxy:w,retryThrottledRequestMaxTimes:A,retryNetworkErrorMaxTimes:A,multipartMinFileSize:A,multipartChunkSize:A,maxConcurrentRequests:A,multipartMaxConcurrentRequests:A,multipartMaxAttempts:A,checkForUrlDuplicates:S,saveUrlForRecurrentUploads:S,groupOutput:S,userAgentIntegration:w,debug:S,localeName:w,metadata:Ji,secureUploadsExpireThreshold:A,localeDefinitionOverride:s=>$t(s),secureUploadsSignatureResolver:s=>dt(s),secureDeliveryProxyUrlResolver:s=>dt(s),iconHrefResolver:s=>dt(s),fileValidators:Nt,collectionValidators:Nt,validationTimeout:A,validationConcurrency:A,cameraModes:Zi,defaultCameraMode:Qi,enableAudioRecording:S,enableVideoRecording:S,mediaRecorderOptions:$t,maxVideoRecordingDuration:A,filesViewMode:er,gridShowFileNames:S,cloudImageEditorAutoOpen:S,cloudImageEditorMaskHref:w,testMode:S,qualityInsights:S},tr=(s,i)=>{if(!(typeof i>"u"||i===null))try{return hs[s](i)}catch(e){return console.error(`Invalid value for config key "${s}".`,e),N[s]}};var ut=[...new Set(["debug",...Object.keys(N)])],ps=["metadata","localeDefinitionOverride","secureUploadsSignatureResolver","secureDeliveryProxyUrlResolver","iconHrefResolver","fileValidators","collectionValidators","mediaRecorderOptions"],sr=s=>ps.includes(s),$e=ut.filter(s=>!sr(s)),ir={...Object.fromEntries($e.map(s=>[ct(s),s])),...Object.fromEntries($e.map(s=>[s.toLowerCase(),s]))},fs={...Object.fromEntries($e.map(s=>[ct(s),k(s)])),...Object.fromEntries($e.map(s=>[s.toLowerCase(),k(s)]))},rr=s=>`__${s}`,ht=class extends T{constructor(){super(...arguments);this.init$={...this.init$,...Object.fromEntries(Object.entries(N).map(([e,t])=>[k(e),t]))};this.computationControllers=new Map}_flushValueToAttribute(e,t){if(!sr(e)){let r=[...new Set([ct(e),e.toLowerCase()])];for(let o of r)typeof t>"u"||t===null?this.removeAttribute(o):this.getAttribute(o)!==t.toString()&&this.setAttribute(o,t.toString())}}_flushValueToState(e,t){this.$[k(e)]!==t&&(typeof t>"u"||t===null?this.$[k(e)]=N[e]:this.$[k(e)]=t)}_setValue(e,t){let r=this,o=tr(e,t),n=rr(e);r[n]!==o&&(this._assertSameValueDifferentReference(e,r[n],o),r[n]=o,this._flushValueToAttribute(e,o),this._flushValueToState(e,o),this.debugPrint(`[uc-config] "${e}"`,o),Ki(this.cfg))}_getValue(e){let t=this,r=rr(e);return t[r]??this.$[k(e)]}_assertSameValueDifferentReference(e,t,r){this.cfg.debug&&r!==t&&typeof r=="object"&&typeof t=="object"&&JSON.stringify(r)===JSON.stringify(t)&&(console.warn(`[uc-config] Option "${e}" value is the same as the previous one but the reference is different`),console.warn("[uc-config] You should avoid changing the reference of the object to prevent unnecessary calculations"),console.warn(`[uc-config] "${e}" previous value:`,t),console.warn(`[uc-config] "${e}" new value:`,r))}initCallback(){super.initCallback();let e=this;for(let t of $e)this.sub(k(t),r=>{this._setValue(t,r)},!1);for(let t of ut){let r=e[t]??this.$[k(t)];r!==N[t]&&this._setValue(t,r),Object.defineProperty(this,t,{set:o=>{this._setValue(t,o)},get:()=>this._getValue(t)})}for(let t of ut)this.sub(k(t),()=>{qi({key:t,setValue:this._setValue.bind(this),getValue:this._getValue.bind(this),computationControllers:this.computationControllers})})}attributeChangedCallback(e,t,r){if(super.attributeChangedCallback(e,t,r),t===r)return;let o=this,n=ir[e];n&&(o[n]=r),fs[e]&&(this[e]=r)}static get observedAttributes(){return[...super.observedAttributes,...Object.keys(ir)]}};for(let s of ut)ht.prototype[s]=void 0;var Ne=class extends T{constructor(){super(...arguments);this.name="";this.resolvedHref="";this.iconHrefResolver=null}initCallback(){super.initCallback(),this.setAttribute("aria-hidden","true"),this.subConfigValue("iconHrefResolver",e=>{this.iconHrefResolver=e,this.updateResolvedHref()})}willUpdate(e){super.willUpdate(e),e.has("name")&&this.updateResolvedHref()}updateResolvedHref(){if(!this.name){this.resolvedHref="";return}let e=`#uc-icon-${this.name}`,t=this.iconHrefResolver?.(this.name);this.resolvedHref=t??e}render(){return m.html` ${this.yield("",m.html`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><use href=${this.resolvedHref}></use></svg>`)} `}};p([(0,c.property)({type:String})],Ne.prototype,"name",2),p([(0,c.state)()],Ne.prototype,"resolvedHref",2);export{K as BtnUi,Vi as CloudImageEditor,x as CloudImageEditorBlock,ht as Config,et as CropFrame,rt as EditorAspectRatioButtonControl,st as EditorCropButtonControl,ae as EditorFilterControl,Rt as EditorFreeformButtonControl,nt as EditorImageCropper,At as EditorImageFader,at as EditorOperationControl,It as EditorScroller,ot as EditorSlider,V as EditorToolbar,Ne as Icon,lt as LineLoaderUi,Me as PresenceToggle,ee as SliderUi,os as defineComponents}; /*! Bundled license information: @lit/context/lib/context-request-event.js: @lit/context/lib/create-context.js: @lit/context/lib/controllers/context-consumer.js: @lit/context/lib/value-notifier.js: @lit/context/lib/controllers/context-provider.js: @lit/context/lib/context-root.js: (** * @license * Copyright 2021 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/context/lib/decorators/provide.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/context/lib/decorators/consume.js: (** * @license * Copyright 2022 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) */
32
+ `));return}window.customElements.define(t,r)}}return i}var re=class extends Event{constructor(i,e,t,r){super("context-request",{bubbles:!0,composed:!0}),this.context=i,this.contextTarget=e,this.callback=t,this.subscribe=r??!1}};var ye=class{constructor(i,e,t,r){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(o,n)=>{this.unsubscribe&&(this.unsubscribe!==n&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=o,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(o,n)),this.unsubscribe=n},this.host=i,e.context!==void 0){let o=e;this.context=o.context,this.callback=o.callback,this.subscribe=o.subscribe??!1}else this.context=e,this.callback=t,this.subscribe=r??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new re(this.context,this.host,this.t,this.subscribe))}};var Qe=class{get value(){return this.o}set value(i){this.setValue(i)}setValue(i,e=!1){let t=e||!Object.is(i,this.o);this.o=i,t&&this.updateObservers()}constructor(i){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:t}]of this.subscriptions)e(this.o,t)},i!==void 0&&(this.value=i)}addCallback(i,e,t){if(!t)return void i(this.value);this.subscriptions.has(i)||this.subscriptions.set(i,{disposer:()=>{this.subscriptions.delete(i)},consumerHost:e});let{disposer:r}=this.subscriptions.get(i);i(this.value,r)}clearCallbacks(){this.subscriptions.clear()}};var St=class extends Event{constructor(i,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=i,this.contextTarget=e}},be=class extends Qe{constructor(i,e,t){super(e.context!==void 0?e.initialValue:t),this.onContextRequest=r=>{if(r.context!==this.context)return;let o=r.contextTarget??r.composedPath()[0];o!==this.host&&(r.stopPropagation(),this.addCallback(r.callback,o,r.subscribe))},this.onProviderRequest=r=>{if(r.context!==this.context||(r.contextTarget??r.composedPath()[0])===this.host)return;let o=new Set;for(let[n,{consumerHost:a}]of this.subscriptions)o.has(n)||(o.add(n),a.dispatchEvent(new re(this.context,a,n,!0)));r.stopPropagation()},this.host=i,e.context!==void 0?this.context=e.context:this.context=e,this.attachListeners(),this.host.addController?.(this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new St(this.context,this.host))}};var yi="ctx-name-context";function bi(s){class i extends s{constructor(...r){super(...r);this._symbioteSharedPubSub=null;this._symbioteFirstUpdated=!1;this._needsReconnectInit=!1;this._ctxNameProvider=void 0;this._warnedAboutLocalState=!1;this._pendingSharedAdds=new Map;this._symbioteSubscriptions=new Set;this.init$={};this.ctxOwner=!1;this._ctxNameAttr=void 0;this._pendingCtxInitOnConnect=!1;this.ctxName=this.effectiveCtxName;this.isInitialized=!1;this._ctxNameAttr=this.getAttribute("ctx-name")||void 0,this.ctxName=this.effectiveCtxName,this._ctxNameConsumer=new ye(this,{context:yi,callback:o=>{if(!o){console.error("SymbioteMixin: Received invalid ctx-name from context");return}this._ctxNameFromContext=o,this._handleCtxNameSourceChange()},subscribe:!0})}get ctxNameAttr(){return this._ctxNameAttr}set ctxNameAttr(r){let o=r??void 0;this._ctxNameAttr!==o&&(this._ctxNameAttr=o,this._handleCtxNameSourceChange())}shouldUpdate(r){return this.isInitialized?super.shouldUpdate(r):!1}get effectiveCtxName(){return this.ctxNameAttr||this._ctxNameFromContext||void 0}_handleCtxNameSourceChange(){if(this.ctxName=this.effectiveCtxName,!(!this.ctxName||this._symbioteFirstUpdated)){if(this.isConnected){this._performInitialization();return}this._pendingCtxInitOnConnect=!0}}willUpdate(r){super.willUpdate(r),this.ctxName=this.effectiveCtxName,this.ctxName&&(this._ctxNameProvider?this._ctxNameProvider.setValue(this.ctxName):this._ctxNameProvider=new be(this,{context:yi,initialValue:this.ctxName}))}_getSharedInitEntries(){let r=Object.entries(this.init$||{}),o=[],n=[];for(let[a,l]of r)a.startsWith("*")?o.push([a,l]):n.push(a);return n.length>0&&!this._warnedAboutLocalState&&(console.warn("SymbioteMixin: Local state entries are no longer supported and will be ignored:",n),this._warnedAboutLocalState=!0),o}_getSharedInitSchema(){return Object.fromEntries(this._getSharedInitEntries())}_ensureSharedSchema(){if(!Object.hasOwn(this,"_sharedSchema")){let r=Object.fromEntries(this._getSharedInitEntries().map(([o,n])=>[o.slice(1),n]));Object.defineProperty(this,"_sharedSchema",{value:r,writable:!0,configurable:!0})}}_getSharedSchemaRecord(){return this._ensureSharedSchema(),this._sharedSchema??{}}_requireSharedKey(r){if(!r.startsWith("*"))throw new Error(`SymbioteMixin: Local state key "${r}" is no longer supported. Use shared keys prefixed with "*".`);return r.slice(1)}_applyPendingSharedAdds(){if(!(!this._symbioteSharedPubSub||this._pendingSharedAdds.size===0)){for(let[r,{value:o,rewrite:n}]of this._pendingSharedAdds)this._symbioteSharedPubSub.add(r,o,n);this._pendingSharedAdds.clear()}}_getSharedPubSub(){return!this._symbioteSharedPubSub&&this.effectiveCtxName&&this._initSharedContext(),this._symbioteSharedPubSub&&this._applyPendingSharedAdds(),this._symbioteSharedPubSub}_requireSharedPubSub(){let r=this._getSharedPubSub();if(!r)throw new Error("SymbioteMixin: Shared context is not initialized.");return r}_initSharedContext(){let r=this._getSharedSchemaRecord(),o=this.effectiveCtxName;if(!o){console.error("SymbioteMixin: ctx-name is required for components with shared properties (*)");return}if(!this._symbioteSharedPubSub){this._symbioteSharedPubSub=X.getCtx(o,!1),this._symbioteSharedPubSub||(this._symbioteSharedPubSub=X.registerCtx(r,o));for(let[n,a]of Object.entries(r))this._symbioteSharedPubSub.add(n,a,this.ctxOwner);this._applyPendingSharedAdds()}}get sharedCtx(){return this._requireSharedPubSub()}get $(){return this.effectiveCtxName&&this._initSharedContext(),new Proxy({},{get:(r,o)=>{if(typeof o!="string")return;let n=this._requireSharedKey(o);return this._symbioteSharedPubSub?.read(n)},set:(r,o,n)=>{if(typeof o!="string")return!0;let a=this._requireSharedKey(o);return this._symbioteSharedPubSub?.pub(a,n),!0}})}sub(r,o,n=!0){let a=this._requireSharedKey(r),l=this._requireSharedPubSub().sub(a,o,n);if(!l||typeof l.remove!="function")return()=>{};let d=l.remove.bind(l),f=!1,h=()=>{f||(f=!0,d(),this._symbioteSubscriptions.delete(h))};return this._symbioteSubscriptions.add(h),h}pub(r,o){let n=this._requireSharedKey(r);this._requireSharedPubSub().pub(n,o)}set$(r){for(let[o,n]of Object.entries(r))this.pub(o,n)}has(r){let o=this._requireSharedKey(r);return this._symbioteSharedPubSub?.has(o)??!1}add(r,o,n=!1){let a=this._requireSharedKey(r),l=this._getSharedPubSub();if(!l){if(!n&&this._pendingSharedAdds.has(a))return;this._pendingSharedAdds.set(a,{value:o,rewrite:n});return}this._pendingSharedAdds.delete(a),l.add(a,o,n)}add$(r,o=!1){for(let[n,a]of Object.entries(r))this.add(n,a,o)}connectedCallback(){super.connectedCallback(),this._symbioteFirstUpdated?this.isInitialized&&this._needsReconnectInit&&(this._needsReconnectInit=!1,this.initCallback()):this.ctxName?(this._pendingCtxInitOnConnect=!1,this._performInitialization()):this._pendingCtxInitOnConnect&&this.effectiveCtxName&&(this._pendingCtxInitOnConnect=!1,this._performInitialization())}_performInitialization(){if(this._symbioteFirstUpdated)return;this._symbioteFirstUpdated=!0,this._initSharedContext();let r=this._getSharedInitSchema();if(Object.keys(r).length>0){let o=this._requireSharedPubSub();for(let[n,a]of Object.entries(r)){let l=this._requireSharedKey(n);o.read(l)===void 0&&o.pub(l,a),this.sub(n,M(async()=>{await this.updateComplete,this.requestUpdate()},0),!1)}}this.initCallback(),this.isInitialized=!0,this.requestUpdate()}firstUpdated(r){super.firstUpdated(r)}updated(r){super.updated(r);let o=this._getSharedInitSchema();Object.keys(o).length>0&&r.forEach((n,a)=>{if(typeof a=="string"&&Object.hasOwn(o,a)){let l=this._requireSharedKey(a),d=this[a],f=this._symbioteSharedPubSub;f&&f.read(l)!==d&&f.pub(l,d)}})}disconnectedCallback(){this._cleanupSymbioteSubscriptions(),super.disconnectedCallback(),this._symbioteFirstUpdated&&(this._needsReconnectInit=!0)}_cleanupSymbioteSubscriptions(){if(this._symbioteSubscriptions.size!==0){for(let r of[...this._symbioteSubscriptions])r();this._symbioteSubscriptions.clear()}}initCallback(){}}return p([(0,c.property)({type:String,attribute:"ctx-name",noAccessor:!0})],i.prototype,"ctxNameAttr",1),p([(0,c.state)()],i.prototype,"_ctxNameFromContext",2),p([(0,c.state)()],i.prototype,"ctxName",2),p([(0,c.state)()],i.prototype,"isInitialized",2),i}var Dr=s=>s.tagName?.includes("-")??!1,Ze=class{constructor(i){this.host=i;this.trackedElements=new Set;this.originalValues=new Map;this.enabled=!1;this.host.addController(this)}hostDisconnected(){this.unsubscribe?.(),this.unsubscribe=void 0,this.trackedElements.clear(),this.originalValues.clear()}hostUpdated(){if(!this.unsubscribe&&this.host.has(k("testMode"))){let i=this.host.subConfigValue("testMode",e=>{this.enabled=!!e,this.applyTestMode()});this.unsubscribe=i}this.collectElements(),this.applyTestMode()}collectElements(){let i=this.host,e=i.renderRoot??i;if(!e)return;let t=this.host,r=t.tagName?.toLowerCase(),o=Array.from(e.querySelectorAll("[data-testid]")).filter(n=>!Dr(n));for(let n of o)if(!(r&&n.closest(r)!==t)&&!this.trackedElements.has(n)){let a=n.getAttribute("data-testid");if(!a)continue;this.trackedElements.add(n),this.originalValues.set(n,a)}for(let n of Array.from(this.trackedElements))(!n.isConnected||r&&n.closest(r)!==t)&&(this.trackedElements.delete(n),this.originalValues.delete(n))}applyTestMode(){if(!this.trackedElements.size)return;let i=this.host.testId||"";for(let e of this.trackedElements){let t=this.originalValues.get(e);t&&(this.enabled?e.setAttribute("data-testid",`${i}--${t}`):e.removeAttribute("data-testid"))}}};var Ur=gi(bi(fi(mi(m.LitElement)))),T=class extends Ur{constructor(){super();this.activityType=null;this.init$=Ht();new Ze(this)}static{this.styleAttrs=[]}l10n(e,t={}){if(!e)return"";let r=this.$[te(e)]||e,o=ui(r);for(let a of o)t[a.variable]=this.pluralize(a.pluralKey,Number(t[a.countVariable]));return xt(r,t)}pluralize(e,t){let r=this.l10n("locale-id")||"en",o=ci(r,t);return this.l10n(`${e}__${o}`)}emit(e,t,r){let o=this.has("*eventEmitter")?this.$["*eventEmitter"]:void 0;if(!o)return;o.emit(e,t,r);let n=typeof t=="function"?t():t;this.telemetryManager.sendEvent({eventType:e,payload:n??void 0})}hasBlockInCtx(e){for(let t of this.blocksRegistry)if(e(t))return!0;return!1}setOrAddState(e,t){this.add$({[e]:t},!0)}connectedCallback(){this.constructor.styleAttrs.forEach(t=>{this.setAttribute(t,"")}),super.connectedCallback(),Oe.registerClient(this)}initCallback(){this.has("*blocksRegistry")||this.add("*blocksRegistry",new Set),this.$["*blocksRegistry"].add(this),this.has("*eventEmitter")||this.add("*eventEmitter",new Xe(this.debugPrint.bind(this))),this.has("*localeManager")||this.add("*localeManager",new Ve(this)),this.cfg.qualityInsights&&!this.has("*telemetryManager")&&this.add("*telemetryManager",new Ye(this)),this.has("*a11y")||this.add("*a11y",new Ue),this.has("*modalManager")||this.add("*modalManager",new ze(this)),this.sub(te("locale-id"),t=>{let r=li(t);this.style.direction=r==="ltr"?"":r,this.requestUpdate()}),this.subConfigValue("testMode",t=>{if(!t||!this.testId){this.removeAttribute("data-testid");return}this.setAttribute("data-testid",this.testId)})}get testId(){return window.customElements.getName(this.constructor)}get modalManager(){return this.has("*modalManager")?this.$["*modalManager"]:void 0}get telemetryManager(){return this.cfg.qualityInsights?this.has("*telemetryManager")&&this.$["*telemetryManager"]:{sendEvent:()=>{},sendEventCloudImageEditor:()=>{},sendEventError:()=>{}}}get localeManager(){return this.has("*localeManager")?this.$["*localeManager"]:null}get a11y(){return this.has("*a11y")?this.$["*a11y"]:null}get blocksRegistry(){return this.$["*blocksRegistry"]}disconnectedCallback(){super.disconnectedCallback(),Oe.unregisterClient(this);let e=this.blocksRegistry;e?.delete(this),e?.size===0&&setTimeout(()=>{this.destroyCtxCallback()},0)}destroyCtxCallback(){X.deleteCtx(this.ctxName),this.modalManager?.destroy()}async proxyUrl(e){if(this.cfg.secureDeliveryProxy&&this.cfg.secureDeliveryProxyUrlResolver&&console.warn("Both secureDeliveryProxy and secureDeliveryProxyUrlResolver are set. The secureDeliveryProxyUrlResolver will be used."),this.cfg.secureDeliveryProxyUrlResolver)try{return await this.cfg.secureDeliveryProxyUrlResolver(e,{uuid:Be(e),cdnUrlModifiers:_t(e),fileName:He(e)})}catch(t){return console.error("Failed to resolve secure delivery proxy URL. Falling back to the default URL.",t),this.telemetryManager.sendEventError(t,"secureDeliveryProxyUrlResolver. Failed to resolve secure delivery proxy URL. Falling back to the default URL."),e}return this.cfg.secureDeliveryProxy?xt(this.cfg.secureDeliveryProxy,{previewUrl:e},{transform:t=>window.encodeURIComponent(t)}):e}get cfg(){if(!this.__cfgProxy){let e={};this.__cfgProxy=new Proxy(e,{set:(t,r,o)=>{if(typeof r!="string"||!(r in N))return!1;let n=r,a=k(n);return this.has(a)||this.add(a,N[n]),this.$[a]=o,!0},get:(t,r)=>{let o=k(r);return this.has(o)||this.add(o,N[r]),this.$[o]}})}return this.__cfgProxy}subConfigValue(e,t){let r=k(e);return this.has(r)||this.add(r,N[e]),this.sub(r,t)}debugPrint(...e){if(!this.cfg.debug)return;let t=e;if(typeof e?.[0]=="function"){let r=e[0];t=r()}console.log(`[${this.ctxName}]`,...t)}};var se="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";function vi(...s){return s.reduce((i,e)=>{if(typeof e=="string")return i[e]=!0,i;for(let t of Object.keys(e))i[t]=e[t];return i},{})}function U(...s){let i=vi(...s);return Object.keys(i).reduce((e,t)=>(i[t]&&e.push(t),e),[]).join(" ")}function _i(s,...i){let e=vi(...i);for(let t of Object.keys(e))s.classList.toggle(t,!!e[t])}var Ae=["free"],Ti=s=>{let i=ke(s);if(!i||i.length===0)return[];let e=[];for(let t of i){let r=t.trim();if(!r)continue;let o=r.indexOf(":");if(o===-1&&!Ae.includes(r)){console.warn(`Invalid crop preset: ${r}`);continue}let n=Number(r.slice(0,o)),a=Number(r.slice(o+1));if((!Number.isFinite(n)||!Number.isFinite(a)||n<=0||a<=0)&&!Ae.includes(r)){console.warn(`Invalid crop preset: ${r}`);continue}e.push({id:me.generate(),type:"aspect-ratio",width:Ae.includes(r)?0:n,height:Ae.includes(r)?0:a,hasFreeform:Ae.includes(r)})}return e},wi=(s,i,e,t=.1)=>{let r=s/i,o=null,n=1/0;for(let a of e){let[l,d]=[a.width,a.height],f=l/d,h=Math.abs(r-f);h<n&&(n=h,o=a)}if(o){let[a,l]=[o.width,o.height],d=a/l;if(Math.abs(r-d)/d>t)return null}return o};var Fr=s=>L.includes(s),Ci=s=>{if(!s)return L;let i=ce(s).filter(Fr);return i.length===0?L:i};function Ei(s){return{"*originalUrl":null,"*loadingOperations":new Map,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],"*currentAspectRatio":null,"*tabList":L,"*tabId":E.CROP,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let e of i){let t=e.src;e.src=se,e.src=t}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let e=s.$["*originalUrl"],t=q(ie(i),"preview"),r=W(e,t),o={originalUrl:e,cdnUrlModifiers:t,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:o,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var xi="<svg width='0' height='0' style='position:absolute'><symbol fill='none' viewBox='0 0 9 6' id='uc-icon-arrow-dropdown' xmlns='http://www.w3.org/2000/svg'><path stroke='currentColor' d='m1.5 1.667 3 2.666 3-2.666' opacity='.5'/></symbol><symbol viewBox='0 0 24 24' id='uc-icon-aspect-ratio' xmlns='http://www.w3.org/2000/svg'/><symbol viewBox='0 0 20 20' id='uc-icon-brightness' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M15 10a5 5 0 0 1-5 5m5-5a5 5 0 0 0-5-5m5 5h-5m0 5a5 5 0 0 1 0-10m0 10V5m0 15v-3M2.93 2.929 5.05 5.05M0 10h3m-.07 7.071 2.12-2.121M10 0v3m7.07 14.071-2.12-2.121M20 10h-3m.07-7.071L14.95 5.05m-.626 2.45H10m4.324 5H10'/></symbol><symbol fill='currentColor' viewBox='0 0 20 20' id='uc-icon-closeMax' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' d='M8.232 10 3.585 5.353l1.768-1.768L10 8.232l4.648-4.647 1.767 1.768L11.768 10l4.647 4.648-1.767 1.767L10 11.768l-4.647 4.647-1.768-1.767L8.232 10Z' clip-rule='evenodd'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-contrast' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M2 10a8 8 0 1 0 16 0 8 8 0 1 0-16 0m8-8v16m8-8h-8m7.598 2.5H10m6.24 2.5H10m7.6-7.5H10M16.242 5H10'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-crop' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M20 14H7.005C6.45 14 6 13.55 6 12.995V0M0 6h13.067c.515 0 .933.418.933.933V20M14.5.4 13 2l1.5 1.6M13 2h2a3 3 0 0 1 3 3v2M5.5 19.6 7 18l-1.5-1.6M7 18H5a3 3 0 0 1-3-3v-2'/></symbol><symbol fill='currentColor' viewBox='0 0 20 20' id='uc-icon-done' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' d='m18.057 6.333-9.365 9.125a1.25 1.25 0 0 1-1.768-.023L1.92 10.296l1.791-1.744 4.132 4.243 8.47-8.253 1.744 1.79Z' clip-rule='evenodd'/></symbol><symbol fill='currentColor' viewBox='0 0 25 24' id='uc-icon-edit-file' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' d='M18.558 2.804a.78.78 0 0 0-.557.235l-.008.007-2.472 2.46 3.847 3.848 2.46-2.473.004-.003a.78.78 0 0 0 0-1.108l-.004-.003-2.712-2.728a.78.78 0 0 0-.558-.235Zm-.248 7.613-3.852-3.852-8.93 8.887-1.516 5.41 5.41-1.515 8.888-8.93Zm-.636-8.934a2.28 2.28 0 0 1 2.512.505l2.702 2.717.002.002a2.278 2.278 0 0 1 0 3.234l-.002.002-12.541 12.602a.75.75 0 0 1-.33.193l-6.884 1.928a.75.75 0 0 1-.925-.924l1.928-6.885a.75.75 0 0 1 .193-.33l12.603-12.54a2.28 2.28 0 0 1 .742-.504Z' clip-rule='evenodd'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-enhance' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M19 13h-2m0 0a4 4 0 0 1-4-4m4 4a4 4 0 0 0-4 4m0-8V7m0 2a4 4 0 0 1-4 4m-2 0h2m0 0a4 4 0 0 1 4 4m0 0v2M8 8.5H6.5m0 0a2 2 0 0 1-2-2m2 2a2 2 0 0 0-2 2m0-4V5m0 1.5a2 2 0 0 1-2 2M1 8.5h1.5m0 0a2 2 0 0 1 2 2m0 0V12M12 3h-1m0 0a1 1 0 0 1-1-1m1 1a1 1 0 0 0-1 1m0-2V1m0 1a1 1 0 0 1-1 1M8 3h1m0 0a1 1 0 0 1 1 1m0 0v1'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-exposure' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M10 20v-3M2.93 2.929 5.05 5.05M0 10h3m-.07 7.071 2.12-2.121M10 0v3m7.07 14.071-2.12-2.121M20 10h-3m.07-7.071L14.95 5.05M5 10a5 5 0 1 0 10 0 5 5 0 1 0-10 0'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-filters' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M4.5 6.5a5.5 5.5 0 1 0 11 0 5.5 5.5 0 1 0-11 0m-3.5 6a5.5 5.5 0 1 0 11 0 5.5 5.5 0 1 0-11 0m7 0a5.5 5.5 0 1 0 11 0 5.5 5.5 0 1 0-11 0'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-flip' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M19.6 5 18 3.5 16.4 5m3.2 10L18 16.5 16.4 15M18 3.523v12.954M3.3 8.5h10.654c.301 0 .415-.395.159-.554L3.459 1.286A.3.3 0 0 0 3 1.542V8.2a.3.3 0 0 0 .3.3zm0 3h10.654c.301 0 .415.395.159.554l-10.654 6.66A.3.3 0 0 1 3 18.458v-6.66a.3.3 0 0 1 .3-.3z'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-gamma' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M17 3C9 6 2.5 11.5 2.5 17.5m0 0h1m-1 0v-1m14 1h1m-3 0h1m-3 0h1m-3 0h1m-3 0h1m-3 0h1m-3 0h1m-3-14v-1m0 3v-1m0 3v-1m0 3v-1m0 3v-1m0 3v-1m0 3v-1'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-mirror' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M5 .4 3.5 2 5 3.6M15 .4 16.5 2 15 3.6M3.52 2h12.957M8.5 16.7V6.046c0-.301-.394-.415-.554-.159L1.287 16.541a.3.3 0 0 0 .255.459H8.2a.3.3 0 0 0 .3-.3zm3 0V6.046c0-.301.395-.415.555-.159l6.659 10.654a.3.3 0 0 1-.255.459H11.8a.3.3 0 0 1-.3-.3z'/></symbol><symbol viewBox='0 0 40 40' id='uc-icon-original' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.5' d='M0 40 40 0'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-rotate' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M13.5.4 12 2l1.5 1.6M12.023 2H14.4A3.6 3.6 0 0 1 18 5.6V8M4 17h9a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1z'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-sad' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M2 17c4.418-4 11.582-4 16 0M16.5 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-11 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-saturation' xmlns='http://www.w3.org/2000/svg'><defs><linearGradient id='ruc-icon-id__a' x1='10.001' y1='1' x2='10.001' y2='19' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient></defs><circle cx='10.001' cy='10' r='9' transform='rotate(90 10 10)' fill='url(#ruc-icon-id__a)'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-slider' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M0 10h11m0 0a2 2 0 1 0 4 0m-4 0a2 2 0 1 1 4 0m0 0h5'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-tuning' xmlns='http://www.w3.org/2000/svg'><path stroke-linejoin='round' fill='none' stroke='currentColor' stroke-width='1.2' d='M8 10h11M1 10h4M1 4.5h11m3 0h4m-18 11h11m3 0h4m-7-11a1.5 1.5 0 1 0 3 0 1.5 1.5 0 1 0-3 0M5 10a1.5 1.5 0 1 0 3 0 1.5 1.5 0 1 0-3 0m7 5.5a1.5 1.5 0 1 0 3 0 1.5 1.5 0 1 0-3 0'/></symbol><symbol viewBox='0 0 20 20' id='uc-icon-vibrance' xmlns='http://www.w3.org/2000/svg'><path d='M2.125 5.64A8.96 8.96 0 0 0 1.001 10a8.96 8.96 0 0 0 1.124 4.36V5.64z' fill='url(#uuc-icon-id__a)'/><path d='M2.875 15.499V4.502a9.053 9.053 0 0 1 1.75-1.72v14.437a9.05 9.05 0 0 1-1.75-1.72z' fill='url(#uuc-icon-id__b)'/><path d='M5.375 17.722c.548.33 1.134.601 1.75.809V1.469a8.956 8.956 0 0 0-1.75.81v15.443z' fill='url(#uuc-icon-id__c)'/><path d='M7.875 1.253v17.495c.564.136 1.15.22 1.75.244V1.008a9 9 0 0 0-1.75.245z' fill='url(#uuc-icon-id__d)'/><path d='M10.375 1.008v17.984a9 9 0 0 0 1.75-.244V1.252a9 9 0 0 0-1.75-.244z' fill='url(#uuc-icon-id__e)'/><path d='M12.875 1.469V18.53a8.957 8.957 0 0 0 1.75-.808V2.277a8.957 8.957 0 0 0-1.75-.808z' fill='url(#uuc-icon-id__f)'/><path d='M15.375 2.78v14.44a9.053 9.053 0 0 0 1.75-1.72v-11a9.054 9.054 0 0 0-1.75-1.72z' fill='url(#uuc-icon-id__g)'/><path d='M17.875 5.638v8.724A8.959 8.959 0 0 0 19.001 10a8.96 8.96 0 0 0-1.126-4.362z' fill='url(#uuc-icon-id__h)'/><defs><linearGradient id='uuc-icon-id__a' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__b' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__c' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__d' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__e' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__f' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__g' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient><linearGradient id='uuc-icon-id__h' x1='19.001' y1='10' x2='1.001' y2='10' gradientUnits='userSpaceOnUse'><stop stop-color='#DE15FF'/><stop offset='.203' stop-color='#0029FF'/><stop offset='.479' stop-color='#2AE4F0'/><stop offset='.604' stop-color='#15EF11'/><stop offset='.75' stop-color='#FAE528'/><stop offset='1' stop-color='#EB2A2A'/></linearGradient></defs></symbol><symbol viewBox='0 0 20 20' id='uc-icon-warmth' xmlns='http://www.w3.org/2000/svg'><path d='m7.5 13.05.429.42.171-.175v-.244h-.6zm5 0h-.6v.245l.172.175.428-.42zM8.1 3.5c0-1.05.85-1.9 1.9-1.9V.4a3.1 3.1 0 0 0-3.1 3.1h1.2zm0 9.55V3.5H6.9v9.55h1.2zm-1 2.45c0-.79.315-1.506.829-2.03l-.858-.84A4.088 4.088 0 0 0 5.9 15.5h1.2zm2.9 2.9a2.9 2.9 0 0 1-2.9-2.9H5.9a4.1 4.1 0 0 0 4.1 4.1v-1.2zm2.9-2.9a2.9 2.9 0 0 1-2.9 2.9v1.2a4.1 4.1 0 0 0 4.1-4.1h-1.2zm-.829-2.03c.514.524.829 1.24.829 2.03h1.2c0-1.117-.447-2.13-1.171-2.87l-.858.84zM11.9 3.5v9.55h1.2V3.5h-1.2zM10 1.6c1.05 0 1.9.85 1.9 1.9h1.2A3.1 3.1 0 0 0 10 .4v1.2z' fill='currentColor'/><path d='M10 14V8' stroke='currentColor' stroke-width='1.2' stroke-linecap='round'/><path d='M14 3h3m-3 3h3m-3 3h3m-8 6.5a1 1 0 1 0 2 0 1 1 0 1 0-2 0' stroke='currentColor' stroke-width='1.2'/></symbol></svg>";var ue={};u(ue,ol);import*as ol from"lit-html/directives/when.js";var Si=de([...L]),x=class extends T{constructor(){super(...arguments);this.ctxOwner=!0;this.entry=null;this.extension=null;this.editorMode=!1;this.modalCaption="";this.isImage=!1;this.msg="";this.src=se;this.fileType="";this.showLoader=!1;this.uuid=null;this.cdnUrl=null;this.cropPreset="";this.tabs=Si;this.presenceNetworkProblems=!1;this.presenceModalCaption=!0;this.presenceEditorToolbar=!1;this.presenceViewerToolbar=!0;this.isInitialized=!1;this.pendingInitUpdate=null;this._debouncedShowLoader=M(e=>{this.showLoader=e},300);this.imgRef=(0,g.createRef)();this.cropperRef=(0,g.createRef)();this.faderRef=(0,g.createRef)();this.imgContainerRef=(0,g.createRef)();this.handleImageLoad=()=>{this._debouncedShowLoader(!1),this.src!==se&&(this.$["*networkProblems"]=!1)};this.handleImageError=()=>{this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0};this.handleRetryNetwork=()=>{let e=this.$["*on.retryNetwork"];e?.()};this.init$={...this.init$,...Ei(this)}}static{this.styleAttrs=["uc-cloud-image-editor"]}scheduleInitialization(){this.isInitialized||this.pendingInitUpdate||(this.pendingInitUpdate=this.updateComplete.then(()=>{this.pendingInitUpdate=null,this.isInitialized=!0}))}initCallback(){super.initCallback(),this.syncTabListFromProp(),this.syncCropPresetState()}assignSharedElements(){let e=this.faderRef.value;e&&(this.$["*faderEl"]=e);let t=this.cropperRef.value;t&&(this.$["*cropperEl"]=t);let r=this.imgContainerRef.value;r&&(this.$["*imgContainerEl"]=r);let o=this.imgRef.value;o&&(this.$["*imgEl"]=o)}attachImageListeners(){let e=this.imgRef.value;e&&(e.addEventListener("load",this.handleImageLoad),e.addEventListener("error",this.handleImageError))}detachImageListeners(){let e=this.imgRef.value;e&&(e.removeEventListener("load",this.handleImageLoad),e.removeEventListener("error",this.handleImageError))}get imageClassName(){let e=this.$["*tabId"];return U("uc-image",{"uc-image_hidden_to_cropper":e===E.CROP,"uc-image_hidden_effects":e!==E.CROP})}_waitForSize(){return new Promise((t,r)=>{let o=window.setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),n=new ResizeObserver(a=>{let[l]=a;l&&l.contentRect.width>0&&l.contentRect.height>0&&(window.clearTimeout(o),n.disconnect(),window.setTimeout(()=>t(),0))});n.observe(this)})}firstUpdated(e){super.firstUpdated(e),this.assignSharedElements(),this.attachImageListeners(),this.initEditor();let t=!!(this.uuid||this.cdnUrl),r=e.has("uuid")||e.has("cdnUrl");t&&!r&&this.updateImage()}disconnectedCallback(){this.detachImageListeners(),super.disconnectedCallback()}render(){let e=this.fileType??"",t=this.msg??"",r=this.src||se,o=this.showLoader,n=this.presenceNetworkProblems;return m.html`${(0,fe.unsafeSVG)(xi)} <div class="uc-wrapper uc-wrapper_desktop"><uc-presence-toggle class="uc-network_problems_splash" .visible=${n}><div class="uc-network_problems_content"><div class="uc-network_problems_icon"><uc-icon name="sad"></uc-icon></div><div class="uc-network_problems_text">Network error</div></div><div class="uc-network_problems_footer"><uc-btn-ui theme="primary" text="Retry" @click=${this.handleRetryNetwork}></uc-btn-ui></div></uc-presence-toggle><div class="uc-viewport"><div class="uc-file_type_outer"><div class="uc-file_type">${e}</div></div><div class="uc-image_container" ${(0,g.ref)(this.imgContainerRef)}><img src=${r} class=${this.imageClassName} ${(0,g.ref)(this.imgRef)} /> ${(0,ue.when)(this.isInitialized,()=>m.html`<uc-editor-image-cropper ${(0,g.ref)(this.cropperRef)}></uc-editor-image-cropper>`)} <uc-editor-image-fader ${(0,g.ref)(this.faderRef)}></uc-editor-image-fader></div><div class="uc-info_pan">${t}</div></div><div class="uc-toolbar"><uc-line-loader-ui .active=${o}></uc-line-loader-ui><div class="uc-toolbar_content uc-toolbar_content__editor"> ${(0,ue.when)(this.isInitialized,()=>m.html`<uc-editor-toolbar></uc-editor-toolbar>`)} </div></div></div>`}updated(e){super.updated(e),e.has("uuid")&&this.uuid&&this.updateImage(),e.has("cdnUrl")&&this.cdnUrl&&this.updateImage(),e.has("tabs")&&this.syncTabListFromProp(),(e.has("cropPreset")||e.has("cdnUrl"))&&this.syncCropPresetState()}syncTabListFromProp(){let e=this.tabs||Si;this.$["*tabList"]=Ci(e)}syncCropPresetState(){let e=Ti(this.cropPreset??""),t=null;if(this.cdnUrl){let r=Tt(this.cdnUrl),o=Ct(r);if(Array.isArray(o?.crop?.dimensions)){let[n,a]=o.crop.dimensions;t=wi(n,a,e,.1)}}this.$["*cropPresetList"]=e,this.$["*currentAspectRatio"]=t??e?.[0]??null}async updateImage(){if(this.isConnected){if(await this._waitForSize(),this.cdnUrl){let e=this.cdnUrl,t=Be(e),r=wt(e,t);if(r===this.$["*originalUrl"])return;this.$["*originalUrl"]=r;let o=Tt(e),n=Ct(o);this.$["*editorTransformations"]=n}else if(this.uuid){let e=wt(this.cfg.cdnCname,this.uuid);if(e===this.$["*originalUrl"])return;this.$["*originalUrl"]=e,this.$["*editorTransformations"]={}}else throw new Error("No UUID nor CDN URL provided");this.$["*tabId"]===E.CROP?this.$["*cropperEl"]?.deactivate({reset:!0}):this.$["*faderEl"]?.deactivate();try{let e=this.$["*originalUrl"],t=await this.proxyUrl(W(e,q("json"))),r=await fetch(t).then(a=>a.json()),{width:o,height:n}=r;this.$["*imageSize"]={width:o,height:n},this.$["*tabId"]===E.CROP?this.$["*cropperEl"]?.activate(this.$["*imageSize"]):this.$["*faderEl"]?.activate({url:e})}catch(e){e&&(this.telemetryManager.sendEventError(e,"cloud editor image. Failed to load image info"),console.error("Failed to load image info",e))}this.scheduleInitialization()}}async initEditor(){try{await this._waitForSize()}catch(e){this.isConnected&&console.error(e.message);return}this.classList.add("uc-editor_ON"),this.sub("*networkProblems",e=>{let t=!!e;this.presenceNetworkProblems=t,this.presenceModalCaption=!t}),this.sub("*editorTransformations",e=>{if(Object.keys(e).length===0)return;let t=this.$["*originalUrl"],r=q(ie(e),"preview"),o=W(t,r),n={originalUrl:t,cdnUrlModifiers:r,cdnUrl:o,transformations:e};this.dispatchEvent(new CustomEvent("change",{detail:n,bubbles:!0,composed:!0}))},!1)}};p([(0,c.property)({attribute:!1})],x.prototype,"entry",2),p([(0,c.property)({attribute:!1})],x.prototype,"extension",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"editorMode",2),p([(0,c.property)({type:String,attribute:!1})],x.prototype,"modalCaption",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"isImage",2),p([(0,c.property)({type:String,attribute:!1})],x.prototype,"msg",2),p([(0,c.property)({type:String,attribute:!1})],x.prototype,"src",2),p([(0,c.property)({type:String,attribute:!1})],x.prototype,"fileType",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"showLoader",2),p([(0,c.property)({type:String,reflect:!0})],x.prototype,"uuid",2),p([(0,c.property)({type:String,attribute:"cdn-url",reflect:!0})],x.prototype,"cdnUrl",2),p([(0,c.property)({type:String,attribute:"crop-preset",reflect:!0})],x.prototype,"cropPreset",2),p([(0,c.property)({type:String,reflect:!0})],x.prototype,"tabs",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"presenceNetworkProblems",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"presenceModalCaption",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"presenceEditorToolbar",2),p([(0,c.property)({type:Boolean,attribute:!1})],x.prototype,"presenceViewerToolbar",2),p([(0,c.state)()],x.prototype,"isInitialized",2);var Ie=33.333333333333336,v=1,kt=24,ki=6;function oe(s,i){for(let[e,t]of Object.entries(i))s.setAttributeNS(null,e,t.toString())}function F(s,i={}){let e=document.createElementNS("http://www.w3.org/2000/svg",s);return oe(e,i),e}function Ri(s,i,e){let{x:t,y:r,width:o,height:n}=s,a=i.includes("w")?0:1,l=i.includes("n")?0:1,d=a===0?-1:1,f=l===0?-1:1,h=[t+a*o+1.5*d,r+l*n+1.5*f-24*e*f],y=[t+a*o+1.5*d,r+l*n+1.5*f],b=[t+a*o-24*e*d+1.5*d,r+l*n+1.5*f],_=`M ${h[0]} ${h[1]} L ${y[0]} ${y[1]} L ${b[0]} ${b[1]}`,I=[y[0],y[1]];return{d:_,center:I}}function Oi(s,i,e){let{x:t,y:r,width:o,height:n}=s,a=i==="n"||i==="s",l=i==="w"||i==="e",d=a?.5:i==="w"?0:1,f=l?.5:i==="n"?0:1,h=i==="w"?-1:i==="e"?1:0,y=i==="n"?-1:i==="s"?1:0,b,_;a?(b=[t+d*o-34*e/2,r+f*n+1.5*y],_=[t+d*o+34*e/2,r+f*n+1.5*y]):(b=[t+d*o+1.5*h,r+f*n-34*e/2],_=[t+d*o+1.5*h,r+f*n+34*e/2]);let I=`M ${b[0]} ${b[1]} L ${_[0]} ${_[1]}`,R=[(b[0]+_[0])/2,(b[1]+_[1])/2];return{d:I,center:R}}function Ai(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 Ii({rect:s,delta:[i,e],imageBox:t}){return _e({...s,x:s.x+i,y:s.y+e},t)}function _e(s,i){let{x:e}=s,{y:t}=s;return s.x<i.x?e=i.x:s.x+s.width>i.x+i.width&&(e=i.x+i.width-s.width),s.y<i.y?t=i.y:s.y+s.height>i.y+i.height&&(t=i.y+i.height-s.height),{...s,x:e,y:t}}function Vr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[,r]=i,{y:o,width:n,height:a}=s;o+=r,a-=r,e&&(n=a*e);let l=s.x+s.width/2-n/2;return o<=t.y&&(o=t.y,a=s.y+s.height-o,e&&(n=a*e,l=s.x+s.width/2-n/2)),l<=t.x&&(l=t.x,o=s.y+s.height-a),l+n>=t.x+t.width&&(l=Math.max(t.x,t.x+t.width-n),n=t.x+t.width-l,e&&(a=n/e),o=s.y+s.height-a),a<v&&(a=v,e&&(n=a*e,l=s.x+s.width/2-n/2),o=s.y+s.height-a),n<v&&(n=v,e&&(a=n/e,l=s.x+s.width/2-n/2),o=s.y+s.height-a),{x:l,y:o,width:n,height:a}}function zr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r]=i,{x:o,width:n,height:a}=s;o+=r,n-=r,e&&(a=n/e);let l=s.y+s.height/2-a/2;return o<=t.x&&(o=t.x,n=s.x+s.width-o,e&&(a=n/e,l=s.y+s.height/2-a/2)),l<=t.y&&(l=t.y,o=s.x+s.width-n),l+a>=t.y+t.height&&(l=Math.max(t.y,t.y+t.height-a),a=t.y+t.height-l,e&&(n=a*e),o=s.x+s.width-n),a<v&&(a=v,e&&(n=a*e),l=s.y+s.height/2-a/2,o=s.x+s.width-n),n<v&&(n=v,e&&(a=n/e),l=s.y+s.height/2-a/2,o=s.x+s.width-n),{x:o,y:l,width:n,height:a}}function jr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[,r]=i,{y:o,width:n,height:a}=s;a+=r,e&&(n=a*e);let l=s.x+s.width/2-n/2;return o+a>=t.y+t.height&&(a=t.y+t.height-o,e&&(n=a*e),l=s.x+s.width/2-n/2),l<=t.x&&(l=t.x,o=s.y),l+n>=t.x+t.width&&(l=Math.max(t.x,t.x+t.width-n),n=t.x+t.width-l,e&&(a=n/e),o=s.y),a<v&&(a=v,e&&(n=a*e),l=s.x+s.width/2-n/2),n<v&&(n=v,e&&(a=n/e),l=s.x+s.width/2-n/2),{x:l,y:o,width:n,height:a}}function Kr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r]=i,{x:o,width:n,height:a}=s;n+=r,e&&(a=n/e);let l=s.y+s.height/2-a/2;return o+n>=t.x+t.width&&(n=t.x+t.width-o,e&&(a=n/e),l=s.y+s.height/2-a/2),l<=t.y&&(l=t.y,o=s.x),l+a>=t.y+t.height&&(l=Math.max(t.y,t.y+t.height-a),a=t.y+t.height-l,e&&(n=a*e),o=s.x),a<v&&(a=v,e&&(n=a*e),l=s.y+s.height/2-a/2),n<v&&(n=v,e&&(a=n/e),l=s.y+s.height/2-a/2),{x:o,y:l,width:n,height:a}}function Hr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,o]=i,{x:n,y:a,width:l,height:d}=s;return n+r<t.x&&(r=t.x-n),a+o<t.y&&(o=t.y-a),n+=r,l-=r,a+=o,d-=o,e&&Math.abs(l/d)>e?(o=l/e-d,d+=o,a-=o,a<=t.y&&(d=d-(t.y-a),l=d*e,n=s.x+s.width-l,a=t.y)):e&&(r=d*e-l,l=l+r,n-=r,n<=t.x&&(l=l-(t.x-n),d=l/e,n=t.x,a=s.y+s.height-d)),d<v&&(d=v,e&&(l=d*e),n=s.x+s.width-l,a=s.y+s.height-d),l<v&&(l=v,e&&(d=l/e),n=s.x+s.width-l,a=s.y+s.height-d),{x:n,y:a,width:l,height:d}}function Br({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,o]=i,{x:n,y:a,width:l,height:d}=s;return n+l+r>t.x+t.width&&(r=t.x+t.width-n-l),a+o<t.y&&(o=t.y-a),l+=r,a+=o,d-=o,e&&Math.abs(l/d)>e?(o=l/e-d,d+=o,a-=o,a<=t.y&&(d=d-(t.y-a),l=d*e,n=s.x,a=t.y)):e&&(r=d*e-l,l+=r,n+l>=t.x+t.width&&(l=t.x+t.width-n,d=l/e,n=t.x+t.width-l,a=s.y+s.height-d)),d<v&&(d=v,e&&(l=d*e),a=s.y+s.height-d),l<v&&(l=v,e&&(d=l/e),a=s.y+s.height-d),{x:n,y:a,width:l,height:d}}function Gr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,o]=i,{x:n,y:a,width:l,height:d}=s;return n+r<t.x&&(r=t.x-n),a+d+o>t.y+t.height&&(o=t.y+t.height-a-d),n+=r,l-=r,d+=o,e&&Math.abs(l/d)>e?(o=l/e-d,d+=o,a+d>=t.y+t.height&&(d=t.y+t.height-a,l=d*e,n=s.x+s.width-l,a=t.y+t.height-d)):e&&(r=d*e-l,l+=r,n-=r,n<=t.x&&(l=l-(t.x-n),d=l/e,n=t.x,a=s.y)),d<v&&(d=v,e&&(l=d*e),n=s.x+s.width-l),l<v&&(l=v,e&&(d=l/e),n=s.x+s.width-l),{x:n,y:a,width:l,height:d}}function Xr({rect:s,delta:i,aspectRatio:e,imageBox:t}){let[r,o]=i,{x:n,y:a,width:l,height:d}=s;return n+l+r>t.x+t.width&&(r=t.x+t.width-n-l),a+d+o>t.y+t.height&&(o=t.y+t.height-a-d),l+=r,d+=o,e&&Math.abs(l/d)>e?(o=l/e-d,d+=o,a+d>=t.y+t.height&&(d=t.y+t.height-a,l=d*e,n=s.x,a=t.y+t.height-d)):e&&(r=d*e-l,l+=r,n+l>=t.x+t.width&&(l=t.x+t.width-n,d=l/e,n=t.x+t.width-l,a=s.y)),d<v&&(d=v,e&&(l=d*e)),l<v&&(l=v,e&&(d=l/e)),{x:n,y:a,width:l,height:d}}function Pi({direction:s,...i}){switch(s){case"n":return Vr(i);case"w":return zr(i);case"s":return jr(i);case"e":return Kr(i);case"nw":return Hr(i);case"ne":return Br(i);case"sw":return Gr(i);case"se":return Xr(i);default:return i.rect}}function Li(s,[i,e]){return s.x<=i&&i<=s.x+s.width&&s.y<=e&&e<=s.y+s.height}function Mi(s,i){return s.x>=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function $i(s,i){return Math.abs(s.width/s.height-i)<.1}function Te({width:s,height:i},e){let t=e/90%2!==0;return{width:t?i:s,height:t?s:i}}function we(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function ne(s,i,e){return Math.min(Math.max(s,i),e)}var et=class extends T{constructor(){super(...arguments);this._guidesHidden=!1;this._dragging=!1;this.svgRef=(0,g.createRef)();this._svgReady=!1;this._pendingMaskHref=null;this._handlePointerUp=e=>{this._updateCursor(),this.dragging&&(e.stopPropagation(),e.preventDefault(),this.dragging=!1)};this._handlePointerMove=e=>{if(!this.dragging||!this._dragStartPoint||!this._draggingThumb)return;e.stopPropagation(),e.preventDefault();let t=this._svgElement;if(!t)return;let{x:r,y:o}=t.getBoundingClientRect(),n=e.x-r,a=e.y-o,l=n-this._dragStartPoint[0],d=a-this._dragStartPoint[1],{direction:f}=this._draggingThumb,h=this._calcCropBox(f,[l,d]);h&&(this.$["*cropBox"]=h)};this._handleSvgPointerMove=e=>{if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(r=>{if(!r||this._shouldThumbBeDisabled(r.direction))return!1;let n=r.interactionNode.getBoundingClientRect(),a={x:n.x,y:n.y,width:n.width,height:n.height};return Li(a,[e.x,e.y])});this._hoverThumb=t,this._updateCursor()}}get _svgElement(){return this.svgRef.value??null}get dragging(){return this._dragging}set dragging(e){this._dragging!==e&&(this._dragging=e,this._applyGuidesDragState())}_applyGuidesDragState(){this._frameGuides&&this._frameGuides.setAttribute("class",U({"uc-guides--hidden":this._guidesHidden,"uc-guides--visible":!this._guidesHidden&&this._dragging,"uc-guides--semi-hidden":!this._guidesHidden&&!this._dragging}))}_shouldThumbBeDisabled(e){let t=this.$["*imageBox"];if(!t)return!1;if(e===""&&t.height<=v&&t.width<=v)return!0;let r=t.height<=v&&(e.includes("n")||e.includes("s")),o=t.width<=v&&(e.includes("e")||e.includes("w"));return r||o}_createBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:t,y:r,width:o,height:n}=e,a=this._svgElement;if(!a)return;let l=F("mask",{id:"backdrop-mask"}),d=F("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),f=F("rect",{x:t,y:r,width:o,height:n,fill:"black"});l.appendChild(d),l.appendChild(f);let h=F("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});a.appendChild(h),a.appendChild(l),this._backdropMask=l,this._backdropMaskInner=f}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:t,y:r,width:o,height:n}=e;this._backdropMaskInner&&oe(this._backdropMaskInner,{x:t,y:r,width:o,height:n})}_updateFrame(){let e=this.$["*cropBox"];if(!(!e||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){if(!t)continue;let{direction:r,pathNode:o,interactionNode:n,groupNode:a}=t,l=r==="",d=r.length===2,{x:f,y:h,width:y,height:b}=e;if(l)oe(n,{x:f,y:h,width:y,height:b});else{let I=ne(Math.min(y,b)/82/2,0,1),R=d?Ri(e,r,I):Oi(e,r,I),P=R.center;if(!P)continue;let le=Math.max(kt*ne(Math.min(y,b)/kt/3,0,1),ki);oe(n,{x:P[0]-le,y:P[1]-le,width:le*2,height:le*2}),oe(o,{d:R.d})}let _=this._shouldThumbBeDisabled(r);a.setAttribute("class",U("uc-thumb",{"uc-thumb--hidden":_,"uc-thumb--visible":!_}))}oe(this._frameGuides,{x:e.x-1*.5,y:e.y-1*.5,width:e.width+1,height:e.height+1})}}_createThumb(e,t){let r=F("g");r.classList.add("uc-thumb"),r.setAttribute("with-effects","");let o=F("rect",{fill:"transparent"}),n=F("path",{stroke:"currentColor",fill:"none","stroke-width":3});r.appendChild(n),r.appendChild(o),e[t]={direction:t,pathNode:n,interactionNode:o,groupNode:r},t===""&&(r.style.cursor="move"),o.addEventListener("pointerdown",this._handlePointerDown.bind(this,t))}_createThumbs(){let e={};for(let t=0;t<3;t++)for(let r=0;r<3;r++){let o=`${["n","","s"][t]}${["w","","e"][r]}`;o!==""&&this._createThumb(e,o)}return this._createThumb(e,""),e}_createGuides(){let e=F("svg"),t=F("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"currentColor","stroke-width":1,"stroke-opacity":.5});e.appendChild(t);for(let r=1;r<=2;r++){let o=F("line",{x1:`${Ie*r}%`,y1:"0%",x2:`${Ie*r}%`,y2:"100%",stroke:"currentColor","stroke-width":1,"stroke-opacity":.3});e.appendChild(o)}for(let r=1;r<=2;r++){let o=F("line",{x1:"0%",y1:`${Ie*r}%`,x2:"100%",y2:`${Ie*r}%`,stroke:"currentColor","stroke-width":1,"stroke-opacity":.3});e.appendChild(o)}return e.classList.add("uc-guides","uc-guides--semi-hidden"),e}_createFrame(){let e=this._svgElement;if(!e)return;let t=document.createDocumentFragment(),r=this._createGuides();t.appendChild(r);let o=this._createThumbs();for(let{groupNode:n}of Object.values(o))t.appendChild(n);e.appendChild(t),this._frameThumbs=o,this._frameGuides=r,this._applyGuidesDragState()}_handlePointerDown(e,t){if(!this._frameThumbs)return;let r=this._frameThumbs[e];if(!r||this._shouldThumbBeDisabled(e))return;let o=this.$["*cropBox"],n=this._svgElement;if(!n)return;let{x:a,y:l}=n.getBoundingClientRect(),d=t.x-a,f=t.y-l;this.dragging=!0,this._draggingThumb=r,this._dragStartPoint=[d,f],this._dragStartCrop={...o}}_calcCropBox(e,t){let[r,o]=t,n=this.$["*imageBox"],a=this._dragStartCrop??this.$["*cropBox"],l=this.$["*currentAspectRatio"],d=l?l.width/l.height:void 0;if(e===""?a=Ii({rect:a,delta:[r,o],imageBox:n}):a=Pi({rect:a,delta:[r,o],direction:e,aspectRatio:d,imageBox:n}),!Object.values(a).every(f=>Number.isFinite(f)&&f>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:a});return}return _e(we(a),n)}_updateCursor(){let e=this._hoverThumb,t=this._svgElement;t&&(t.style.cursor=e?Ai(e.direction):"initial")}_createMask(e){if(this._frameImage){this._frameImage.setAttribute("href",e);return}let t=this._svgElement;if(!t){this._pendingMaskHref=e;return}this._pendingMaskHref=null;let r=document.createDocumentFragment(),o=F("image",{href:e});o.setAttribute("class","uc-cloud-mask"),r.appendChild(o),t.appendChild(r),this._frameImage=o}_updateMask(){let e=this.$["*cropBox"];if(!e||!this._frameImage)return;let{x:t,y:r,width:o,height:n}=e;oe(this._frameImage,{x:t,y:r,height:n,width:o})}_render(){this._svgReady&&(this._updateBackdrop(),this._updateFrame(),this._updateMask())}toggleThumbs(e){if(this._frameThumbs)for(let t of Object.values(this._frameThumbs)){if(!t)continue;let{groupNode:r}=t;r.setAttribute("class",U("uc-thumb",{"uc-thumb--hidden":!e,"uc-thumb--visible":e}))}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._resizeBackdrop(),this._svgReady&&window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",e=>{e&&(this._guidesHidden=e.height<=v||e.width<=v,this._applyGuidesDragState(),this._svgReady&&window.requestAnimationFrame(()=>{this._render()}))}),this.subConfigValue("cloudImageEditorMaskHref",e=>{e&&this._createMask(e)}),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}firstUpdated(e){super.firstUpdated(e),this._initializeSvg()}_initializeSvg(){let e=this._svgElement;if(!(!e||this._svgReady)){if(this._createBackdrop(),this._createFrame(),this._svgReady=!0,e.addEventListener("pointermove",this._handleSvgPointerMove,!0),this._pendingMaskHref){let t=this._pendingMaskHref;this._pendingMaskHref=null,this._createMask(t)}this._render()}}disconnectedCallback(){super.disconnectedCallback(),this._svgElement?.removeEventListener("pointermove",this._handleSvgPointerMove,!0),document.removeEventListener("pointermove",this._handlePointerMove,!0),document.removeEventListener("pointerup",this._handlePointerUp,!0)}render(){return m.html`<svg class="uc-svg" xmlns="http://www.w3.org/2000/svg" ${(0,g.ref)(this.svgRef)}></svg>`}};p([(0,c.state)()],et.prototype,"_dragging",2);var D={};u(D,Dl);import*as Dl from"lit-html/directives/class-map.js";var C={};u(C,Ul);import*as Ul from"lit-html/directives/if-defined.js";var $=class extends T{constructor(){super(...arguments);this.active=!1;this.title="";this.icon="";this.titleProp=""}get buttonClasses(){let e=this.active;return{"uc-active":e,"uc-not_active":!e}}updateHostStateClasses(){let e=this.buttonClasses;for(let[t,r]of Object.entries(e))this.classList.toggle(t,r)}onClick(e){}connectedCallback(){super.connectedCallback(),this.updateHostStateClasses()}updated(e){super.updated(e),e.has("active")&&this.updateHostStateClasses()}render(){let e=this.onClick,t=this.title;return m.html`<button role="option" type="button" aria-label=${(0,C.ifDefined)(this.titleProp)} title=${(0,C.ifDefined)(this.titleProp)} @click=${e} ><uc-icon name=${this.icon}></uc-icon><div class="uc-title" ?hidden=${!t}>${t}</div></button>`}};p([(0,c.state)()],$.prototype,"active",2),p([(0,c.state)()],$.prototype,"title",2),p([(0,c.state)()],$.prototype,"icon",2),p([(0,c.state)()],$.prototype,"titleProp",2);var tt=12,it=16,Wr=s=>{let i=12,e=12;return s.width/s.height>=1?(i=tt,e=Math.round(tt*s.height/s.width)):(e=tt,i=Math.round(tt*s.width/s.height)),{width:i,height:e}},Rt=class extends ${initCallback(){super.initCallback(),this.icon="arrow-dropdown",this.sub("*currentAspectRatio",i=>{let e=this.computeTitle(i);this.title=e,this.titleProp=e})}onClick(){this.$["*showListAspectRatio"]=!0}computeTitle(i){return i?i.hasFreeform?this.l10n("freeform-crop"):this.l10n("crop-to-shape",{value:`${i.width}:${i.height}`}):""}render(){let i=this.onClick,e=this.title;return m.html`<button role="option" type="button" class=${(0,D.classMap)(this.buttonClasses)} aria-label=${(0,C.ifDefined)(this.titleProp)} title=${(0,C.ifDefined)(this.titleProp)} @click=${i} ><div class="uc-title" ?hidden=${!e}>${e}</div><uc-icon name=${this.icon}></uc-icon></button>`}},rt=class extends ${get aspectRatio(){return this._aspectRatio}set aspectRatio(i){if(this._aspectRatio===i)return;let e=this._aspectRatio;this._aspectRatio=i,this.requestUpdate("aspectRatio",e),i?this.updateAspectRatioPresentation(i):(this.removeAttribute("uc-aspect-ratio-freeform"),this.title="",this.titleProp="")}initCallback(){super.initCallback(),this._aspectRatio&&this.updateAspectRatioPresentation(this._aspectRatio),this.sub("*currentAspectRatio",i=>{this.active=i&&i.id===this._aspectRatio?.id||i?.width===this._aspectRatio?.width&&i?.height===this._aspectRatio?.height})}onClick(){this.$["*currentAspectRatio"]?.id!==this._aspectRatio?.id&&(this.$["*currentAspectRatio"]=this._aspectRatio)}updateAspectRatioPresentation(i){let e=!!i.hasFreeform;this.toggleAttribute("uc-aspect-ratio-freeform",e);let t=()=>{let o=e?this.l10n("custom"):`${i.width}:${i.height}`;return this.title=o,o},r=()=>{let o=this.l10n("a11y-cloud-editor-apply-aspect-ratio",{name:e?this.l10n("custom").toLowerCase():this.l10n("crop-to-shape",{value:`${i.width}:${i.height}`}).toLowerCase(),value:""});return this.titleProp=o,o};t(),r(),e||this.requestUpdate()}renderIcon(){let i=this._aspectRatio;if(!i||i.hasFreeform)return m.html`<uc-icon name=${this.icon}></uc-icon>`;let{width:e,height:t}=Wr(i),r=(it-e)/2,o=(it-t)/2;return m.html`<svg viewBox="0 0 ${it} ${it}" aria-hidden="true" focusable="false" ><rect x=${r} y=${o} width=${e} height=${t} rx="2" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round" ></rect></svg>`}render(){let i=this.onClick,e=this.title;return m.html`<button role="option" type="button" class=${(0,D.classMap)(this.buttonClasses)} aria-label=${(0,C.ifDefined)(this.titleProp)} title=${(0,C.ifDefined)(this.titleProp)} @click=${i} ><uc-icon>${this.renderIcon()}</uc-icon><div class="uc-title" ?hidden=${!e}>${e}</div></button>`}};p([(0,c.property)({attribute:!1})],rt.prototype,"aspectRatio",1);function Yr(s){let i=s+90;return i=i>=360?0:i,i}function Qr(s,i){if(s==="rotate")return Yr(typeof i=="number"?i:0);if(s==="mirror"||s==="flip")return!i;throw new Error(`Unsupported operation: ${s}`)}var st=class extends ${constructor(){super(...arguments);this.operation=void 0}willUpdate(e){super.willUpdate(e),this.operation?(this.titleProp=this.l10n("a11y-cloud-editor-apply-crop",{name:this.l10n(this.operation).toLowerCase()}),this.icon=this.operation):(this.icon="",this.titleProp="")}onClick(e){if(!this.operation)return;let t=this.$["*cropperEl"],r=t.getValue(this.operation),o=Qr(this.operation,r);this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{operation:this.operation,next:o,prev:r}),t.setValue(this.operation,o)}};p([(0,c.property)({type:String})],st.prototype,"operation",2);var B={};u(B,ic);import*as ic from"lit-html/directives/style-map.js";function Pe(s){let i=new Image;return{promise:new Promise((r,o)=>{i.src=s,i.onload=()=>r(),i.onerror=n=>o(n)}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=se)}}}function Le(s){let i=[];for(let o of s){let n=Pe(o);i.push(n)}let e=i.map(o=>o.image);return{promise:Promise.allSettled(i.map(o=>o.promise)),images:e,cancel:()=>{i.forEach(o=>{o.cancel()})}}}var G="original",ot=class extends T{constructor(){super(...arguments);this.state={operation:"filter",filter:void 0,originalUrl:"",disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0};this.handleInput=e=>{let{value:t}=e.detail;this.$["*faderEl"]?.set(t),this.state={...this.state,value:t}}}setOperation(e,t){this.state={...this.state,operation:e,filter:t},this._initializeValues();let r=this.$["*faderEl"],o=this.state.originalUrl||this.$["*originalUrl"];r&&o&&r.activate({url:o,operation:this.state.operation,value:this.state.filter===G?void 0:this.state.value,filter:this.state.filter===G?void 0:this.state.filter,fromViewer:!1})}_initializeValues(){let e=this.state.operation,{range:t,zero:r}=j[e],[o,n]=t;this.state={...this.state,min:o,max:n,zero:r};let l=this.$["*editorTransformations"][e];if(e==="filter"){let f=Number(n),h=l;if(h){let{name:y,amount:b}=h;f=y===this.state.filter?b:n}this.state={...this.state,value:f,defaultValue:f};return}let d=typeof l<"u"?l:r;this.state={...this.state,value:d,defaultValue:d}}apply(){let t={...this.$["*editorTransformations"]};this.state.operation==="filter"?!this.state.filter||this.state.filter===G?delete t.filter:t.filter={name:this.state.filter,amount:this.state.value}:t[this.state.operation]=this.state.value,this.$["*editorTransformations"]=t}cancel(){this.$["*faderEl"]?.deactivate({hide:!1})}initCallback(){this.sub("*originalUrl",e=>{this.state={...this.state,originalUrl:e}})}updated(e){if(super.updated(e),e.has("state")){let t=`${this.state.filter??this.state.operation} ${this.state.value}`;this.$["*operationTooltip"]=t}}render(){return m.html`<uc-slider-ui .disabled=${this.state.disabled} .min=${this.state.min} .max=${this.state.max} .defaultValue=${this.state.defaultValue} .zero=${this.state.zero} @slider-input=${this.handleInput} ></uc-slider-ui>`}};p([(0,c.state)()],ot.prototype,"state",2);function Ce(s){let i=s.match(/^([A-Za-z]+)\s+(\d+)$/);if(!i)return null;let[,e,t]=i;return!e||typeof t>"u"?null:{filter:e,value:Number(t)}}var ae=class extends ${constructor(){super(...arguments);this._operation="";this._filter="";this._originalUrl="";this._lastPreviewRequestId=0;this.previewImage=null;this.previewLoaded=!1;this.isOriginal=!1;this.iconSize=20}get filter(){return this._filter}set filter(e){let t=e??"";if(this._filter===t)return;let r=this._filter;this._filter=t,this._operation="filter",this.isOriginal=t===G,this.icon=this.isOriginal?"original":"slider",this.iconSize=this.isOriginal?40:20,this.requestUpdate("filter",r),this.updateFilterLabels(t)}onClick(e){if(this.active)this.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0);else{let t=this.$["*sliderEl"];t.setOperation(this._operation,this._filter),t.apply()}this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{operation:Ce(this.$["*operationTooltip"])}),this.$["*currentFilter"]=this._filter}_previewSrc(){let e=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),t=Number.isFinite(e)&&e>0?e:this.iconSize||32,r=window.devicePixelRatio,o=Math.ceil(r*t),n=r>=2?"lightest":"normal",a=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==G?{name:this._filter,amount:a}:void 0,W(this._originalUrl,q(Ge,ie(l),`quality/${n}`,`scale_crop/${o}x${o}/center`))}async _observerCallback(e,t){e[0]?.isIntersecting?await this.loadPreview(t):this._cancelPreload?.()}initCallback(){super.initCallback(),"IntersectionObserver"in window&&(this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]}));let e=this.$["*originalUrl"];this._originalUrl=e??"",this.sub("*originalUrl",t=>{this._originalUrl=t??"",!this.isOriginal&&this._originalUrl&&this.isConnected&&!this.previewImage&&(this._observer?.observe(this),this.schedulePreviewVisibilityCheck())}),this.isOriginal||(this._observer?.observe(this),this.schedulePreviewVisibilityCheck()),this._filter&&this.updateFilterLabels(this._filter),this.sub("*currentFilter",t=>{this.active=!!(t&&t===this._filter)}),this.sub("*networkProblems",async t=>{t||(this.previewImage?await this.loadPreview():this.schedulePreviewVisibilityCheck())})}disconnectedCallback(){super.disconnectedCallback(),this._observer?.disconnect(),this._cancelPreload?.(),this.clearPreviewVisibilityChecks()}updated(e){super.updated(e),e.has("isOriginal")&&(this.isOriginal?this._observer?.unobserve(this):(this._observer?.observe(this),this.schedulePreviewVisibilityCheck()))}updateFilterLabels(e){if(!e){this.titleProp="";return}let t=this.l10n("a11y-cloud-editor-apply-filter",{name:e.toLowerCase()});this.titleProp=t}async loadPreview(e){if(!this.isConnected){e?.unobserve(this),this._cancelPreload?.(),this._cancelPreload=void 0;return}if(!this._originalUrl){!this.previewVisibilityCheckTimeout&&!this.previewVisibilityCheckRaf&&this.schedulePreviewVisibilityCheck();return}let t=++this._lastPreviewRequestId,r="";try{r=await this.proxyUrl(this._previewSrc())}catch(a){this.$["*networkProblems"]=!0,console.error("Failed to resolve preview URL",{error:a});return}this.previewLoaded=!1,this._cancelPreload?.();let{promise:o,cancel:n}=Pe(r);this._cancelPreload=()=>{n(),this._lastPreviewRequestId===t&&(this._cancelPreload=void 0)};try{if(await o,this._lastPreviewRequestId!==t||!this.isConnected)return;this.previewImage=r,this.previewLoaded=!0,this.clearPreviewVisibilityChecks(),(e??this._observer)?.unobserve(this)}catch(a){this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:a}),this.schedulePreviewVisibilityCheck()}finally{this._lastPreviewRequestId===t&&(this._cancelPreload=void 0)}}schedulePreviewVisibilityCheck(){if(!this.isConnected||this.previewImage||this.previewLoaded||this.isOriginal){this.clearPreviewVisibilityChecks();return}this.previewVisibilityCheckRaf&&cancelAnimationFrame(this.previewVisibilityCheckRaf),this.previewVisibilityCheckRaf=requestAnimationFrame(()=>{if(this.previewVisibilityCheckRaf=void 0,!this.isConnected||this.previewImage||this.previewLoaded||this.isOriginal){this.clearPreviewVisibilityChecks();return}let e=this.getBoundingClientRect(),t=e.width>0&&e.height>0,r=window.innerWidth||document.documentElement.clientWidth,o=window.innerHeight||document.documentElement.clientHeight;if(t&&e.bottom>0&&e.right>0&&e.top<o&&e.left<r){this.loadPreview();return}this.previewVisibilityCheckTimeout=window.setTimeout(()=>{this.previewVisibilityCheckTimeout=void 0,this.schedulePreviewVisibilityCheck()},500)})}clearPreviewVisibilityChecks(){this.previewVisibilityCheckRaf&&(cancelAnimationFrame(this.previewVisibilityCheckRaf),this.previewVisibilityCheckRaf=void 0),this.previewVisibilityCheckTimeout&&(window.clearTimeout(this.previewVisibilityCheckTimeout),this.previewVisibilityCheckTimeout=void 0)}get shouldShowPreview(){return!!(this.previewLoaded&&!this.active&&!this.isOriginal)}render(){let e=this.onClick,t={opacity:this.shouldShowPreview?"1":"0"};this.previewImage&&(t.backgroundImage=`url(${this.previewImage})`);let r={opacity:this.shouldShowPreview?"0":"1"};return m.html`<button role="option" type="button" class=${(0,D.classMap)(this.buttonClasses)} aria-label=${(0,C.ifDefined)(this.titleProp)} title=${(0,C.ifDefined)(this.titleProp)} @click=${e} ><div class="uc-preview" ?loaded=${this.previewLoaded} style=${(0,B.styleMap)(t)}></div><uc-icon class=${(0,D.classMap)({"uc-original-icon":this.isOriginal})} name=${this.icon} style=${(0,B.styleMap)(r)} ></uc-icon></button>`}};p([(0,c.state)()],ae.prototype,"previewImage",2),p([(0,c.state)()],ae.prototype,"previewLoaded",2),p([(0,c.property)({type:Boolean,reflect:!0})],ae.prototype,"isOriginal",2),p([(0,c.property)({type:Number})],ae.prototype,"iconSize",2),p([(0,c.property)({type:String})],ae.prototype,"filter",1);var Ni=(s,i)=>{let e=!1,t,r=0,o=((...n)=>{e?(t&&clearTimeout(t),t=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),e=!0)});return Object.defineProperty(o,"cancel",{configurable:!1,writable:!1,enumerable:!1,value:()=>{t&&clearTimeout(t)}}),o};function Di(s,i){let e={};for(let t of i){let r=s[t];(Object.hasOwn(s,t)||r!==void 0)&&(e[t]=r)}return e}function Ee(s,i,e){let r=window.devicePixelRatio,o=Math.min(Math.ceil(i*r),3e3),n=r>=2?"lightest":"normal";return W(s,q(Ge,ie(e),`quality/${n}`,`stretch/off/-/resize/${o}x`,`@clib/${qe}/${We}/uc-cloud-image-editor/`))}function Zr(s){return s?[({dimensions:e,coords:t})=>[...e,...t].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:e,coords:t})=>e.every(r=>r>0)&&t.every(r=>r>=0)].every(e=>e(s)):!0}var nt=class extends T{constructor(){super();this.ctxOwner=!0;this._imageSize={width:0,height:0};this._ctx=null;this._isActive=!1;this._image=null;this.canvasRef=(0,g.createRef)();this.frameRef=(0,g.createRef)();this.init$={...this.init$,"*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=M(this._commit.bind(this),300),this._handleResizeThrottled=Ni(()=>{!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())},100)}firstUpdated(e){super.firstUpdated(e),this._initCanvas()}_syncTransformations(){let e=this.$["*editorTransformations"],t=Di(e,Object.keys(this.$["*operations"])),r={...this.$["*operations"],...t};this.$["*operations"]=r}_initCanvas(){let e=this.canvasRef.value;if(!e)return;let t=e.getContext("2d"),r=this.offsetWidth,o=this.offsetHeight,n=window.devicePixelRatio;e.style.width=`${r}px`,e.style.height=`${o}px`,e.width=r*n,e.height=o*n,t?.scale(n,n),this._canvas=e,this._ctx=t}_alignImage(){if(!this._isActive||!this._image)return;let e=this._image,t=this.$["*padding"],r=this.$["*operations"],{rotate:o}=r,n={width:this.offsetWidth,height:this.offsetHeight},a=Te({width:e.naturalWidth,height:e.naturalHeight},o),l;if(a.width>n.width-t*2||a.height>n.height-t*2){let d=a.width/a.height,f=n.width/n.height;if(d>f){let h=n.width-t*2,y=h/d,b=0+t,_=t+(n.height-t*2)/2-y/2;l={x:b,y:_,width:h,height:y}}else{let h=n.height-t*2,y=h*d,b=t+(n.width-t*2)/2-y/2,_=0+t;l={x:b,y:_,width:y,height:h}}}else{let{width:d,height:f}=a,h=t+(n.width-t*2)/2-d/2,y=t+(n.height-t*2)/2-f/2;l={x:h,y,width:d,height:f}}this.$["*imageBox"]=we(l)}_alignCrop(){let e=this.$["*cropBox"],t=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,n=this.$["*editorTransformations"].crop,{width:a,x:l,y:d}=t;if(n){let{dimensions:[y,b],coords:[_,I]}=n,{width:R}=Te(this._imageSize,o),P=a/R;e=_e(we({x:l+_*P,y:d+I*P,width:y*P,height:b*P}),t)}let f=this.$["*currentAspectRatio"],h=f?f.width/f.height:void 0;if(!Mi(e,t)||h&&!$i(e,h)){let y=t.width/t.height,b=t.width,_=t.height;h&&(y>h?b=Math.min(t.height*h,t.width):_=Math.min(t.width/h,t.height)),e={x:t.x+t.width/2-b/2,y:t.y+t.height/2-_/2,width:b,height:_}}this.$["*cropBox"]=_e(we(e),t)}_drawImage(){let e=this._ctx;if(!e)return;let t=this._image;if(!t)return;let r=this.$["*imageBox"],o=this.$["*operations"],{mirror:n,flip:a,rotate:l}=o,d=Te({width:r.width,height:r.height},l);e.save(),e.translate(r.x+r.width/2,r.y+r.height/2),e.rotate(l*Math.PI*-1/180),e.scale(n?-1:1,a?-1:1),e.drawImage(t,-d.width/2,-d.height/2,d.width,d.height),e.restore()}_draw(){if(!this._isActive||!this._image||!this._canvas||!this._ctx)return;let e=this._canvas;this._ctx.clearRect(0,0,e.width,e.height),this._drawImage()}_animateIn({fromViewer:e}){this._image&&(this.frameRef.value?.toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=U({"uc-active_from_viewer":e,"uc-active_from_editor":!e,"uc-inactive_to_editor":!1})}))}_getCropDimensions(){let e=this.$["*cropBox"],t=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a}=t,{width:l,height:d}=Te(this._imageSize,o),{width:f,height:h}=e,y=n/l,b=a/d;return[ne(Math.round(f/y),1,l),ne(Math.round(h/b),1,d)]}_getCropTransformation(){let e=this.$["*cropBox"],t=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a,x:l,y:d}=t,{width:f,height:h}=Te(this._imageSize,o),{x:y,y:b}=e,_=n/f,I=a/h,R=this._getCropDimensions(),P={dimensions:R,coords:[ne(Math.round((y-l)/_),0,f-R[0]),ne(Math.round((b-d)/I),0,h-R[1])]};if(!Zr(P)){console.error("Cropper is trying to create invalid crop object",{payload:P});return}if(!(R[0]===f&&R[1]===h))return P}_commit(){if(!this.isConnected||!this._imageSize)return;let e=this.$["*operations"],{rotate:t,mirror:r,flip:o}=e,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:r,flip:o};this.$["*editorTransformations"]=l}setValue(e,t){this.$["*operations"]={...this.$["*operations"],[e]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(e){return this.$["*operations"][e]}async activate(e,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,await this.updateComplete,this._initCanvas(),this._imageSize=e,this.removeEventListener("transitionend",this._reset);try{let r=this.$["*originalUrl"],o=this.$["*editorTransformations"];this._image=await this._waitForImage(r,o),this._syncTransformations(),this._handleResizeThrottled(),this._animateIn({fromViewer:t})}catch(r){console.error("Failed to activate cropper",{error:r}),this.telemetryManager.sendEventError(r,"cloud editor image. Failed to activate cropper")}this._observer=new ResizeObserver(r=>{let[o]=r;if(!o)return;o.contentRect.width>0&&o.contentRect.height>0&&this._isActive&&this._image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:e=!1}={}){this._isActive&&(!e&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=U({"uc-active_from_viewer":!1,"uc-active_from_editor":!1,"uc-inactive_to_editor":!0}),this.frameRef.value?.toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),this._observer?.disconnect())}_transitionToCrop(){let e=this._getCropDimensions(),t=this.$["*cropBox"],r=Math.min(this.offsetWidth,e[0])/t.width,o=Math.min(this.offsetHeight,e[1])/t.height,n=Math.min(r,o),a=t.x+t.width/2,l=t.y+t.height/2;this.style.transform=`scale(${n}) translate(${(this.offsetWidth/2-a)/n}px, ${(this.offsetHeight/2-l)/n}px)`,this.style.transformOrigin=`${a}px ${l}px`}_transitionToImage(){let e=this.$["*cropBox"],t=e.x+e.width/2,r=e.y+e.height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${t}px ${r}px`}_reset(){this._isActive||(this._image=null)}async _waitForImage(e,t){let r=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let o=await this.proxyUrl(Ee(e,r,t)),{promise:n,cancel:a,image:l}=Pe(o),d=this._handleImageLoading(o);return l.addEventListener("load",d,{once:!0}),l.addEventListener("error",d,{once:!0}),this._cancelPreload?.(),this._cancelPreload=a,n.then(()=>l).catch(f=>(console.error("Failed to load image",{error:f}),this.$["*networkProblems"]=!0,l))}_handleImageLoading(e){let t="crop",r=this.$["*loadingOperations"],o=r.get(t);return o||(o=new Map,r.set(t,o)),o.get(e)||(o.set(e,!0),this.$["*loadingOperations"]=r),()=>{let n=r.get(t);n?.has(e)&&(n.delete(e),this.$["*loadingOperations"]=r)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this._image&&this._commitDebounced()}),this.sub("*currentAspectRatio",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",e=>{e||this._isActive&&this._imageSize&&this.activate(this._imageSize,{fromViewer:!1})})},0)}disconnectedCallback(){super.disconnectedCallback(),this._observer?.disconnect(),this._image&&(this._image=null)}render(){return m.html`<canvas class="uc-canvas" ${(0,g.ref)(this.canvasRef)}></canvas><uc-crop-frame ${(0,g.ref)(this.frameRef)}></uc-crop-frame>`}};p([(0,c.state)()],nt.prototype,"_image",2);function Ot(s,i,e){let t=e,r=e-1,o=new Array(t);for(let n=r;n>=0;n-=1)o[n]=Math.ceil((n*i+(r-n)*s)/r);return o}function Jr(s){return typeof s=="string"&&s in j}function es(s){let i=[];for(let e=0;e<s.length-1;e+=1){let t=s[e],r=s[e+1];typeof t=="number"&&typeof r=="number"&&i.push([t,r])}return i}function ts(s,i,e){let t=es(s).find(([n,a])=>n<=i&&i<=a);if(!t)return s.map(()=>0);let[r,o]=t;return s.map(n=>{let a=Math.abs(r-o)||1,l=Math.abs(i-r)/a;return r===n?i>e?1:1-l:o===n?i>=e?l:1:0})}function is(s,i){return s.map((e,t)=>e<i?s.length-t:t)}function Ui(s,i){let e=j[s].keypointsNumber,{range:t,zero:r}=j[s];return[...new Set([...Ot(t[0],r,e+1),...Ot(r,t[1],e+1),r,i])].sort((o,n)=>o-n)}var At=class extends T{constructor(){super();this._isActive=!1;this._hidden=!0;this._operation="initial";this._transformations={};this._keypoints=[];this._raf=0;this._previewHostRef=(0,g.createRef)();this._layersHostRef=(0,g.createRef)();this.classList.add("uc-inactive_to_cropper"),this._addKeypointDebounced=M(async(e,t,r)=>{let o=()=>!this._isSame(e,t)||this._value!==r||!!this._keypoints.find(d=>d.value===r);if(o())return;let n=await this._constructKeypoint(e,r),a=new Image;a.src=n.src;let l=this._handleImageLoading(n.src);a.addEventListener("load",l,{once:!0}),a.addEventListener("error",l,{once:!0}),n.image=a,a.classList.add("uc-fader-image"),a.addEventListener("load",()=>{if(o())return;let d=this._keypoints,f=d.findIndex(_=>_.value>r);f===-1&&(f=d.length);let y=d[f]?.image,b=this._layersHostRef.value;!b||y&&!b.contains(y)||(d.splice(f,0,n),y?b.insertBefore(a,y):b.appendChild(a),this._update(e,r))},{once:!0}),a.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})},600)}_handleImageLoading(e){let t=this._operation,r=this.$["*loadingOperations"];r.has(t)||r.set(t,new Map);let o=r.get(t);return o&&!o.get(e)&&(o.set(e,!0),this.$["*loadingOperations"]=r),()=>{let n=r.get(t);n?.has(e)&&(n.delete(e),this.$["*loadingOperations"]=r)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let e of this._keypoints){let{image:t}=e;t&&(t.style.opacity=e.opacity.toString(),t.style.zIndex=e.zIndex.toString())}})}_imageSrc({url:e=this._url,filter:t=this._filter??void 0,operation:r,value:o}={}){if(!e)throw new Error("URL is not defined");let n={...this._transformations};r&&(r==="filter"?t&&typeof o=="number"&&(n.filter={name:t,amount:o}):typeof o=="number"&&(n[r]=o));let a=this.offsetWidth;return this.proxyUrl(Ee(e,a,n))}async _constructKeypoint(e,t){return{src:await this._imageSrc({operation:e,value:t}),image:void 0,opacity:0,zIndex:0,value:t}}_isSame(e,t){return this._operation===e&&this._filter===t}set(e){let t=typeof e=="string"?parseInt(e,10):e;!Jr(this._operation)||!Number.isFinite(t)||(this._update(this._operation,t),this._addKeypointDebounced(this._operation,this._filter,t))}_update(e,t){this._operation=e,this._value=t;let{zero:r}=j[e],o=this._keypoints.map(l=>l.value),n=ts(o,t,r),a=is(o,r);this._keypoints.forEach((l,d)=>{let f=n[d],h=a[d];typeof f=="number"&&(l.opacity=f),typeof h=="number"&&(l.zIndex=h)}),this._flush()}_createPreviewImage(){let e=new Image;return e.classList.add("uc-fader-image","uc-fader-image--preview"),e.style.opacity="0",e}async _initNodes(){this._previewImage=this._previewImage||this._createPreviewImage();let e=this._previewImage;e&&this._ensurePreviewAttached(e);let t=this._keypoints.map(d=>d.src),{images:r,promise:o,cancel:n}=Le(t);r.forEach(d=>{let f=this._handleImageLoading(d.src);d.addEventListener("load",f),d.addEventListener("error",f)}),this._cancelLastImages=()=>{n(),this._cancelLastImages=void 0};let a=this._operation,l=this._filter;if(await o,this._isActive&&this._isSame(a,l)){let d=this._layersHostRef.value;if(!d)return;d.replaceChildren(),this._keypoints.forEach((f,h)=>{let y=r[h];y&&(y.classList.add("uc-fader-image"),f.image=y,d.appendChild(y))}),this._flush()}}async setTransformations(e){if(this._transformations=e,this._previewImage){let t=await this._imageSrc(),r=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",r,{once:!0}),this._previewImage.addEventListener("error",r,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}async preload({url:e,filter:t,operation:r,value:o}){if(!r||typeof o!="number")return;this._cancelBatchPreload?.();let n=Ui(r,o),a=await Promise.all(n.map(d=>this._imageSrc({url:e,filter:t,operation:r,value:d}))),{cancel:l}=Le(a);this._cancelBatchPreload=l}_setOriginalSrc(e){let t=this._previewImage||this._createPreviewImage();if(this._ensurePreviewAttached(t),this._previewImage=t,t.src===e){t.style.opacity="1",t.style.transform="scale(1)",this.className=U({"uc-active_from_viewer":this._fromViewer,"uc-active_from_cropper":!this._fromViewer,"uc-inactive_to_cropper":!1});return}t.style.opacity="0";let r=this._handleImageLoading(e);t.addEventListener("error",r,{once:!0}),t.src=e,t.addEventListener("load",()=>{r(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=U({"uc-active_from_viewer":this._fromViewer,"uc-active_from_cropper":!this._fromViewer,"uc-inactive_to_cropper":!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}async activate({url:e,operation:t,value:r,filter:o,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,await this.updateComplete,this._url=e,this._operation=t??"initial",this._value=r,this._filter=o,this._fromViewer=n,typeof r!="number"&&!o){let l=await this._imageSrc({operation:t,value:r});this._setOriginalSrc(l),this._clearLayersHost();return}!t||typeof r!="number"||(this._keypoints=await Promise.all(Ui(t,r).map(l=>this._constructKeypoint(t,l))),this._update(t,r),this._initNodes())}deactivate({hide:e=!0}={}){this._isActive=!1,this._cancelLastImages?.(),this._cancelBatchPreload?.(),e&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=U({"uc-active_from_viewer":!1,"uc-active_from_cropper":!1,"uc-inactive_to_cropper":!0}),this.addEventListener("transitionend",()=>{this._clearLayersHost()},{once:!0})):this._clearLayersHost()}_ensurePreviewAttached(e){let t=this._previewHostRef.value;t&&(t.contains(e)||t.appendChild(e))}_clearLayersHost(){this._layersHostRef.value?.replaceChildren()}render(){return m.html`<div class="uc-fader-preview-host" ${(0,g.ref)(this._previewHostRef)}></div><div class="uc-fader-layers-host" ${(0,g.ref)(this._layersHostRef)}></div>`}};var at=class extends ${constructor(){super(...arguments);this._operation=""}get operation(){return this._operation}set operation(e){let t=e??"";if(this._operation===t)return;let r=this._operation;this._operation=t,this.requestUpdate("operation",r),t&&this.updateOperationMetadata(t)}updateOperationMetadata(e){this.icon=e;let t=()=>{let o=this.l10n("a11y-cloud-editor-apply-tuning",{name:this.l10n(e).toLowerCase()});return this.titleProp=o,o},r=()=>{let o=this.l10n(e);return this.title=o,o};t(),r()}initCallback(){super.initCallback(),this._operation&&this.updateOperationMetadata(this._operation),this.sub("*editorTransformations",e=>{if(!this._operation)return;let{zero:t}=j[this._operation],r=e[this._operation],o=typeof r<"u"?r!==t:!1;this.active=o})}onClick(e){this.$["*sliderEl"]?.setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation,this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{operation:Ce(this.$["*operationTooltip"])})}};p([(0,c.property)({type:String})],at.prototype,"operation",1);var rs=1,Fi=()=>{},It=class extends T{constructor(){super(...arguments);this.handleWheel=e=>{e.preventDefault();let{deltaY:t,deltaX:r}=e;if(Math.abs(r)>rs){this.scrollLeft+=r;return}this.scrollLeft+=t}}connectedCallback(){super.connectedCallback(),this.addEventListener("wheel",this.handleWheel,{passive:!1}),this.addEventListener("scroll",Fi,{passive:!0})}disconnectedCallback(){this.removeEventListener("wheel",this.handleWheel),this.removeEventListener("scroll",Fi),super.disconnectedCallback()}};var V=class extends T{constructor(){super(...arguments);this.showLoader=!1;this.showMainToolbar=!0;this.showSubToolbar=!1;this.showTabToggles=!0;this.tabList=[...L];this.activeTab=E.CROP;this.useSliderPanel=!0;this.tooltipVisible=!1;this.operationTooltip=null;this.tabIndicatorOffset=0;this.tabIndicatorWidth=0;this.sliderRef=(0,g.createRef)();this.tabIndicatorRef=(0,g.createRef)();this.tabToggleRefs={[E.CROP]:(0,g.createRef)(),[E.TUNING]:(0,g.createRef)(),[E.FILTERS]:(0,g.createRef)()};this.handleWindowResize=()=>{this._syncTabIndicator()};this.cropPresets=[];this._debouncedShowLoader=M(e=>{this.showLoader=e},500);this._updateInfoTooltip=M(()=>{let e=this.$["*editorTransformations"],t=this.$["*currentOperation"],r="",o=!1;if(this.$["*tabId"]===E.FILTERS)if(o=!0,this.$["*currentFilter"]&&e?.filter?.name===this.$["*currentFilter"]){let n=e?.filter?.amount||100;r=`${this.$["*currentFilter"]} ${n}`}else r=this.l10n(G);else if(this.showSubToolbar&&this.$["*tabId"]===E.TUNING&&t){o=!0;let n=e?.[t]||j[t].zero;r=`${this.l10n(t)} ${n}`}o&&(this.$["*operationTooltip"]=r),this.tooltipVisible=o},0);this.subTopToolbarStyles={hidden:"uc-sub-toolbar--top-hidden",visible:"uc-sub-toolbar--visible"};this.subBottomToolbarStyles={hidden:"uc-sub-toolbar--bottom-hidden",visible:"uc-sub-toolbar--visible"};this.tabContentStyles={hidden:"uc-tab-content--hidden",visible:"uc-tab-content--visible"};this.tabToggleStyles={hidden:"uc-tab-toggle--hidden",visible:"uc-tab-toggle--visible"};this.tabTogglesStyles={hidden:"uc-tab-toggles--hidden",visible:"uc-tab-toggles--visible"};this.init$={...this.init$,"*sliderEl":null,"*showSlider":!1,"*showListAspectRatio":!1,"*currentFilter":G,"*currentOperation":null,"*operationTooltip":null};this.handleCancel=e=>{this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{action:"cancel"}),this._cancelPreload?.();let t=this.$["*on.cancel"];t?.()};this.handleApply=e=>{this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{action:"apply"});let t=this.$["*on.apply"];t?.(this.$["*editorTransformations"])};this.handleApplySlider=e=>{this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{action:"apply-slider",operation:Ce(this.$["*operationTooltip"])}),this.sliderRef.value?.apply(),this._onSliderClose()};this.handleCancelSlider=e=>{this.telemetryManager.sendEventCloudImageEditor(e,this.$["*tabId"],{action:"cancel-slider"}),this.sliderRef.value?.cancel(),this._onSliderClose()};this.handleTabClick=e=>{let r=e.currentTarget?.getAttribute("data-id");r&&(this.telemetryManager.sendEventCloudImageEditor(e,r),this._activateTab(r,{fromViewer:!1}))}}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===E.CROP&&(this.$["*showListAspectRatio"]=!1),this.$["*tabId"]===E.TUNING&&(this.tooltipVisible=!1)}_activateTab(e,{fromViewer:t=!1,force:r=!1}={}){this.$["*tabId"]!==e&&(this.$["*tabId"]=e),this.applyTabState(e,{fromViewer:t,force:r})}applyTabState(e,{fromViewer:t,force:r=!1}){if(!r&&this.activeTab===e){this._syncTabIndicator();return}this.activeTab=e;let o=this.$["*faderEl"],n=this.$["*cropperEl"];e===E.CROP?(o?.deactivate(),this.$["*imageSize"]&&n?.activate(this.$["*imageSize"],{fromViewer:t})):(o?.activate({url:this.$["*originalUrl"],fromViewer:t}),n?.deactivate());for(let a of L){let l=a===e,f=this.tabToggleRefs[a]?.value;f&&(f.active=l),l&&this._syncTabIndicator()}}_syncTabIndicator(){let t=this.tabToggleRefs[this.activeTab]?.value,r=this.tabIndicatorRef.value;if(!t||!r)return;let o=t.offsetLeft,n=t.offsetWidth||Number(getComputedStyle(t).width.replace("px",""));(this.tabIndicatorOffset!==o||this.tabIndicatorWidth!==n)&&(this.tabIndicatorOffset=o,this.tabIndicatorWidth=n,r.style.transform=`translateX(${o}px)`,r.style.width=`${n}px`)}get hasAspectRatioPicker(){return this.cropPresets.length>=3}renderControlsByTab(e){switch(e){case E.CROP:return this.renderCropTabControls();case E.FILTERS:return this.renderFilterTabControls();case E.TUNING:return this.renderTuningTabControls();default:return[]}}renderCropTabControls(){let e=[];if(this.hasAspectRatioPicker)e.push(()=>this.renderFreeformControl());else for(let t of this.cropPresets)e.push(()=>this.renderAspectRatioControl(t));for(let t of ni)e.push(()=>this.renderCropOperationControl(t));return this.renderControlGroup(e)}renderFilterTabControls(){let t=[G,...oi].map(r=>()=>this.renderFilterControl(r));return this.renderControlGroup(t)}renderTuningTabControls(){let e=si.map(t=>()=>this.renderOperationControl(t));return this.renderControlGroup(e)}renderControlGroup(e){return e.length?e.map(r=>r()):[]}renderFreeformControl(){return m.html`<uc-editor-freeform-button-control></uc-editor-freeform-button-control>`}renderAspectRatioControl(e){return m.html`<uc-editor-aspect-ratio-button-control .aspectRatio=${e}></uc-editor-aspect-ratio-button-control>`}renderCropOperationControl(e){return m.html`<uc-editor-crop-button-control .operation=${e}></uc-editor-crop-button-control>`}renderFilterControl(e){return m.html`<uc-editor-filter-control .filter=${e}></uc-editor-filter-control>`}renderOperationControl(e){return m.html`<uc-editor-operation-control .operation=${e}></uc-editor-operation-control>`}renderAspectRatioList(){return this.hasAspectRatioPicker?this.cropPresets.map(e=>this.renderAspectRatioControl(e)):[]}async _preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let e=this.$["*imgContainerEl"].offsetWidth,t=await this.proxyUrl(Ee(this.$["*originalUrl"],e,this.$["*editorTransformations"]));this._cancelPreload?.();let{cancel:r}=Le([t]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}initCallback(){super.initCallback();let e=this.$["*cropPresetList"]??[];this.cropPresets=[...e],this.sub("*cropPresetList",t=>{this.cropPresets=[...t??[]]}),this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{let r=t?.filter?.name;this.$["*currentFilter"]!==r&&(this.$["*currentFilter"]=r??"")}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",t=>{this.applyTabState(t,{fromViewer:!1,force:!0}),this._updateInfoTooltip()}),this.sub("*originalUrl",()=>{this.$["*faderEl"]?.deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]?.setTransformations(t)}),this.sub("*loadingOperations",t=>{let r=!1;for(let[,o]of t.entries()){if(r)break;for(let[,n]of o.entries())if(n){r=!0;break}}this._debouncedShowLoader(r)}),this.sub("*showSlider",t=>{t?(this.showSubToolbar=!0,this.showMainToolbar=!1,this.useSliderPanel=!0):this.$["*showListAspectRatio"]||(this.showSubToolbar=!1,this.showMainToolbar=!0)}),this.sub("*showListAspectRatio",t=>{t?(this.showSubToolbar=!0,this.showMainToolbar=!1,this.useSliderPanel=!1):this.$["*showSlider"]||(this.showSubToolbar=!1,this.showMainToolbar=!0)}),this.sub("*tabList",t=>{if(this.tabList=t,this.showTabToggles=t.length>1,!t.includes(this.$["*tabId"])&&t.length>0){let[r]=t;r&&this._activateTab(r,{fromViewer:!1});return}this._syncTabIndicator()}),this.sub("*operationTooltip",t=>{this.operationTooltip=t}),this._updateInfoTooltip()}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.handleWindowResize)}firstUpdated(e){super.firstUpdated(e),this.assignSharedElements(),this._syncTabIndicator()}updated(e){super.updated(e),(e.has("activeTab")||e.has("tabList"))&&this.updateComplete.then(()=>this._syncTabIndicator()),(e.has("showSubToolbar")||e.has("showMainToolbar"))&&this.assignSharedElements()}disconnectedCallback(){window.removeEventListener("resize",this.handleWindowResize),super.disconnectedCallback(),this.$["*showSlider"]=!1,this.$["*showListAspectRatio"]=!1}assignSharedElements(){let e=this.sliderRef.value;e&&(this.$["*sliderEl"]=e)}renderTabToggle(e){let t=this.tabList.includes(e),r=this.activeTab===e,o=this.tabList.indexOf(e),n=o>=0?(0,B.styleMap)({gridColumn:`${o+1}`}):m.nothing;return m.html` <uc-presence-toggle class="uc-tab-toggle" .visible=${t} .styles=${this.tabToggleStyles}><uc-btn-ui theme="tab" data-id=${e} icon=${e} role="tab" aria-controls=${`tab_${e}`} aria-selected=${r?"true":"false"} title-prop=${`a11y-editor-tab-${e}`} .active=${r} style=${n} @click=${this.handleTabClick} ${(0,g.ref)(this.tabToggleRefs[e])} ></uc-btn-ui></uc-presence-toggle>`}renderTabContent(e){let t=this.activeTab===e,r=this.renderControlsByTab(e);return m.html` <uc-presence-toggle id=${`tab_${e}`} class="uc-tab-content" .visible=${t} .styles=${this.tabContentStyles} ><uc-editor-scroller hidden-scrollbar><div class="uc-controls-list_align"><div role="listbox" aria-orientation="horizontal" class="uc-controls-list_inner"> ${r.length?r:m.nothing} </div></div></uc-editor-scroller></uc-presence-toggle>`}render(){let e=["uc-info-tooltip",this.tooltipVisible?"uc-info-tooltip_visible":"uc-info-tooltip_hidden"].join(" "),t=this.hasAspectRatioPicker;return m.html`<uc-line-loader-ui .active=${this.showLoader}></uc-line-loader-ui><div class="uc-info-tooltip_container"><div class="uc-info-tooltip_wrapper"><div class=${e}>${this.operationTooltip??""}</div></div></div><div class="uc-toolbar-container"><uc-presence-toggle role="tablist" class="uc-sub-toolbar" .visible=${this.showMainToolbar} .styles=${this.subTopToolbarStyles} ><div class="uc-tab-content-row"> ${L.map(r=>this.renderTabContent(r))} </div><div class="uc-controls-row"><uc-presence-toggle class="uc-tab-toggles" .visible=${this.showTabToggles} .styles=${this.tabTogglesStyles} @initial-render=${()=>this._syncTabIndicator()} ><div class="uc-tab-toggles_indicator" ${(0,g.ref)(this.tabIndicatorRef)} ></div> ${L.map(r=>this.renderTabToggle(r))} </uc-presence-toggle><uc-btn-ui style="order: -1" theme="secondary-icon" icon="closeMax" title-prop="cancel" @click=${this.handleCancel} ></uc-btn-ui><uc-btn-ui theme="primary-icon" icon="done" title-prop="apply" @click=${this.handleApply}></uc-btn-ui></div></uc-presence-toggle><uc-presence-toggle class="uc-sub-toolbar" .visible=${this.showSubToolbar} .styles=${this.subBottomToolbarStyles}><div class="uc-slider" ?hidden=${!this.useSliderPanel}><uc-editor-slider ${(0,g.ref)(this.sliderRef)}></uc-editor-slider></div><div class="uc-list-aspect-ratio-container" ?hidden=${this.useSliderPanel||!t}> ${t?m.html`<div class="uc-list-aspect-ratio">${this.renderAspectRatioList()}</div>`:m.nothing} </div><div class="uc-controls-row"><uc-btn-ui theme="secondary" @click=${this.handleCancelSlider} text=${this.l10n("cancel")}></uc-btn-ui><uc-btn-ui theme="primary" @click=${this.handleApplySlider} text=${this.l10n("apply")}></uc-btn-ui></div></uc-presence-toggle></div>`}};p([(0,c.state)()],V.prototype,"showLoader",2),p([(0,c.state)()],V.prototype,"showMainToolbar",2),p([(0,c.state)()],V.prototype,"showSubToolbar",2),p([(0,c.state)()],V.prototype,"showTabToggles",2),p([(0,c.state)()],V.prototype,"tabList",2),p([(0,c.state)()],V.prototype,"activeTab",2),p([(0,c.state)()],V.prototype,"useSliderPanel",2),p([(0,c.state)()],V.prototype,"tooltipVisible",2),p([(0,c.state)()],V.prototype,"operationTooltip",2),p([(0,c.state)()],V.prototype,"cropPresets",2);var K=class extends T{constructor(){super(...arguments);this.text="";this.icon="";this.active=!1;this.reverse=!1;this.theme="default";this.ariaRole="";this.ariaControls="";this.titleProp=""}firstUpdated(e){super.firstUpdated(e),this.applyReverse(),this.applyThemeClass()}updated(e){super.updated(e),e.has("reverse")&&this.applyReverse(),e.has("theme")&&this.applyThemeClass()}applyReverse(){this.style.flexDirection=this.reverse?"row-reverse":""}applyThemeClass(){this.theme&&this.theme!=="custom"&&(this.className=`uc-${this.theme}`)}get iconClassMap(){let e=this.computedIconHidden;return{"uc-icon":!0,"uc-icon_left":!this.reverse,"uc-icon_right":this.reverse,"uc-icon_hidden":e,"uc-icon_single":this.computedIconSingle}}get computedIconHidden(){return!this.icon}get computedIconSingle(){return!this.text&&!this.computedIconHidden}render(){return m.html`<button type="button" role=${(0,C.ifDefined)(this.ariaRole||void 0)} aria-controls=${(0,C.ifDefined)(this.ariaControls||void 0)} aria-label=${(0,C.ifDefined)(this.l10n(this.titleProp))} title=${(0,C.ifDefined)(this.l10n(this.titleProp))} ><uc-icon class=${(0,D.classMap)(this.iconClassMap)} name=${(0,C.ifDefined)(this.icon||void 0)} ?hidden=${this.computedIconHidden} ></uc-icon><div class="uc-text">${this.text}</div></button>`}};p([(0,c.property)({type:String})],K.prototype,"text",2),p([(0,c.property)({type:String})],K.prototype,"icon",2),p([(0,c.property)({type:Boolean,reflect:!0})],K.prototype,"active",2),p([(0,c.property)({type:Boolean,reflect:!0})],K.prototype,"reverse",2),p([(0,c.property)({type:String,reflect:!0})],K.prototype,"theme",2),p([(0,c.property)({attribute:"aria-role"})],K.prototype,"ariaRole",2),p([(0,c.property)({attribute:"aria-controls"})],K.prototype,"ariaControls",2),p([(0,c.property)({attribute:"title-prop"})],K.prototype,"titleProp",2);var lt=class extends T{constructor(){super(...arguments);this.active=!1;this.lineRef=(0,g.createRef)();this._isAnimating=!1;this.handleTransitionEndRight=()=>{let e=this.lineRef.value;e&&(this.resetLine(e),this._isAnimating&&this.active&&this.start())}}firstUpdated(e){super.firstUpdated(e),this.active&&this.start()}updated(e){super.updated(e),e.has("active")&&(this.active?this.start():this.stop())}start(){let e=this.lineRef.value;if(!e)return;this._isAnimating=!0;let{width:t}=this.getBoundingClientRect();e.removeEventListener("transitionend",this.handleTransitionEndRight),e.style.transition="transform 1s",e.style.opacity="1",e.style.transform=`translateX(${t}px)`,e.addEventListener("transitionend",this.handleTransitionEndRight,{once:!0})}stop(){let e=this.lineRef.value;e&&(this._isAnimating=!1,e.removeEventListener("transitionend",this.handleTransitionEndRight),this.resetLine(e))}resetLine(e){e.style.transition="initial",e.style.opacity="0",e.style.transform="translateX(-101%)"}render(){return m.html`<div class="uc-inner"><div class="uc-line" ${(0,g.ref)(this.lineRef)}></div></div>`}};p([(0,c.property)({type:Boolean,reflect:!0})],lt.prototype,"active",2);var pe={transition:"uc-transition",visible:"uc-visible",hidden:"uc-hidden"},Me=class extends T{constructor(){super(...arguments);this._visible=!1;this._styles=pe;this._visibleStyle=pe.visible;this._hiddenStyle=pe.hidden;this._externalTransitions=!1;this.initialRenderComplete=!1}set visible(e){this._visible=e,this._handleVisible()}get visible(){return this._visible}set styles(e){this._styles=e,this._externalTransitions=!0,this._visibleStyle=e.visible??pe.visible,this._hiddenStyle=e.hidden??pe.hidden}get styles(){return this._styles}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",_i(this,{[pe.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.toggleAttribute("inert",!this._visible)}dispatchInitialRenderEvent(){this.initialRenderComplete||(this.initialRenderComplete=!0,this.dispatchEvent(new CustomEvent("initial-render",{bubbles:!0,composed:!0})))}initCallback(){super.initCallback(),this.classList.toggle("uc-initial",!0),this._externalTransitions||this.classList.add(pe.transition),this._handleVisible(),setTimeout(()=>{this.classList.toggle("uc-initial",!1),this.dispatchInitialRenderEvent()},0)}};p([(0,c.property)({type:Boolean})],Me.prototype,"visible",1),p([(0,c.property)({attribute:!1})],Me.prototype,"styles",1);var ee=class extends T{constructor(){super();this._thumbSize=0;this.inputRef=(0,g.createRef)();this.thumbRef=(0,g.createRef)();this.stepsRef=(0,g.createRef)();this.disabled=!1;this.min=0;this.max=100;this.defaultValue=0;this.zero=0;this._currentValue=0;this.handleSliderInput=e=>{e.stopPropagation();let t=this._extractEventValue(e);t!==null&&(this._setCurrentValue(t),this.emitSliderEvent("slider-input",t))};this.handleSliderChange=e=>{e.stopPropagation();let t=this._extractEventValue(e);t!==null&&(this._setCurrentValue(t),this.emitSliderEvent("slider-change",t))};this.handleInputFocus=()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")};this.handleInputBlur=()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")};this.setAttribute("with-effects","")}emitSliderEvent(e,t){this.dispatchEvent(new CustomEvent(e,{detail:{value:t},bubbles:!0,composed:!0}))}firstUpdated(e){super.firstUpdated(e),this._thumbSize=Number.parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10)||0,this._syncInputValue(this._currentValue),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps(),this._updateValue(this._currentValue)}),this._observer.observe(this);let t=this.inputRef.value;t?.addEventListener("focus",this.handleInputFocus),t?.addEventListener("blur",this.handleInputBlur),window.setTimeout(()=>{this._updateValue(this._currentValue)},0)}willUpdate(e){super.willUpdate(e),e.has("defaultValue")&&this.defaultValue!==this._currentValue&&this._setCurrentValue(this.defaultValue),(e.has("min")||e.has("max"))&&this.hasUpdated&&(this._updateSteps(),this._updateValue(this._currentValue)),e.has("zero")&&this.hasUpdated&&this._updateZeroDot(this._currentValue)}_updateValue(e){this._updateZeroDot(e);let t=this.max-this.min;if(t===0)return;let{width:r}=this.getBoundingClientRect(),a=100/t*(e-this.min)*(r-this._thumbSize)/100;window.requestAnimationFrame(()=>{let l=this.thumbRef.value;l&&(l.style.transform=`translateX(${a}px)`)})}_updateZeroDot(e){if(!this._zeroDotEl)return;let t=this.max-this.min;if(t===0)return;this._zeroDotEl.style.opacity=e===this.zero?"0":"1";let{width:r}=this.getBoundingClientRect(),a=100/t*(this.zero-this.min)*(r-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl&&(this._zeroDotEl.style.transform=`translateX(${a}px)`)})}_updateSteps(){let t=this.stepsRef.value;if(!t)return;let{width:r}=t.getBoundingClientRect(),o=Math.ceil(r/2),n=Math.ceil(o/15)-2;if(this._stepsCount===n)return;let a=document.createDocumentFragment(),l=document.createElement("div"),d=document.createElement("div");l.className="uc-minor-step",d.className="uc-border-step",a.appendChild(d);for(let h=0;h<n;h+=1)a.appendChild(l.cloneNode());a.appendChild(d.cloneNode());for(let h=0;h<n;h+=1)a.appendChild(l.cloneNode());a.appendChild(d.cloneNode());let f=document.createElement("div");f.className="uc-zero-dot",a.appendChild(f),this._zeroDotEl=f,t.innerHTML="",t.appendChild(a),this._stepsCount=n}disconnectedCallback(){super.disconnectedCallback();let e=this.inputRef.value;e?.removeEventListener("focus",this.handleInputFocus),e?.removeEventListener("blur",this.handleInputBlur),this._observer?.disconnect(),this._observer=void 0}_setCurrentValue(e){Number.isFinite(e)&&(this._currentValue=e,this.hasUpdated&&(this._syncInputValue(e),this._updateValue(e)))}_syncInputValue(e){let t=this.inputRef.value;t&&(t.value=String(e))}_extractEventValue(e){let t=e.currentTarget;if(!t)return null;let r=Number.parseInt(t.value,10);return Number.isFinite(r)?r:null}render(){return m.html`<div class="uc-steps" ${(0,g.ref)(this.stepsRef)}></div><div class="uc-thumb" ${(0,g.ref)(this.thumbRef)}></div><input class="uc-input" type="range" ${(0,g.ref)(this.inputRef)} .min=${String(this.min)} .max=${String(this.max)} .value=${String(this._currentValue)} ?disabled=${this.disabled} @input=${this.handleSliderInput} @change=${this.handleSliderChange} />`}};p([(0,c.property)({type:Boolean,reflect:!0})],ee.prototype,"disabled",2),p([(0,c.property)({type:Number})],ee.prototype,"min",2),p([(0,c.property)({type:Number})],ee.prototype,"max",2),p([(0,c.property)({type:Number,attribute:!1})],ee.prototype,"defaultValue",2),p([(0,c.property)({type:Number})],ee.prototype,"zero",2),p([(0,c.state)()],ee.prototype,"_currentValue",2);var Vi=class extends x{static{this.styleAttrs=[...super.styleAttrs,"uc-wgt-common"]}constructor(){super(),this.init$={...this.init$,"*solution":this.tagName}}initCallback(){super.initCallback(),this.telemetryManager.sendEvent({eventType:Z.INIT_SOLUTION}),this.a11y?.registerBlock(this)}};var ss=["UploaderBlock","ActivityBlock","Block","SolutionBlock"];function os(s){for(let i in s){if(ss.includes(i))continue;let e=[...i].reduce((t,r)=>(r.toUpperCase()===r&&(r=`-${r.toLowerCase()}`),t+=r,t),"");e.startsWith("-")&&(e=e.replace("-","")),e.startsWith("uc-")||(e=`uc-${e}`),s[i].reg&&s[i].reg(e)}}var ct=s=>s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)?.map(i=>i.toLowerCase()).join("-");var zi=new Set;function ji(s){zi.has(s)||(zi.add(s),console.warn(s))}var ns=[{test:s=>!!s.accept&&!!s.imgOnly,message:"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."},{test:s=>s.enableVideoRecording!==null,message:"The `enableVideoRecording` parameter is deprecated and will be removed in the next major release.\nPlease use the `cameraModes` parameter instead."},{test:s=>s.defaultCameraMode!==null,message:"The `defaultCameraMode` parameter is deprecated and will be removed in the next major release.\nPlease use the `cameraModes` parameter instead."}],Ki=M(s=>{for(let{test:i,message:e}of ns)i(s)&&ji(e)},0);var Hi=(s,i)=>{let e=new URL(i);return e.hostname=`${s}.${e.hostname}`,e.toString().replace(/\/$/,"")},as="0123456789abcdefghijklmnopqrstuvwxyz",Bi=s=>{if(s<=0n)return"0";let i="";for(;s>0n;){let e=s%36n;i=as[Number(e)]+i,s=s/36n}return i},Pt=(s,i)=>{try{let e=new URL(s),t=new URL(i);return e.hostname.endsWith(t.hostname)}catch{return!1}};var ls=async s=>{let i=new TextEncoder().encode(s),e=await window.crypto.subtle.digest("SHA-256",i),t=Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("");return BigInt(`0x${t}`)},cs=10,ds=async s=>{let i=await ls(s);return Bi(i).slice(0,cs)},Gi=async(s,i)=>{let e=await ds(s);return Hi(e,i)};var Xi=s=>s instanceof Promise||!!(s&&typeof s=="object"&&"then"in s&&typeof s.then=="function");var Lt=s=>s,us=[Lt({key:"cameraModes",deps:["enableVideoRecording"],fn:({cameraModes:s,enableVideoRecording:i})=>{if(i===null)return s;let e=ce(s);return i&&!e.includes("video")?e=e.concat("video"):i||(e=e.filter(t=>t!=="video")),de(e)}}),Lt({key:"cameraModes",deps:["defaultCameraMode"],fn:({cameraModes:s,defaultCameraMode:i})=>{if(i===null)return s;let e=ce(s);return e=e.sort((t,r)=>t===i?-1:r===i?1:0),de(e)}}),Lt({key:"cdnCname",deps:["pubkey","cdnCnamePrefixed"],fn:({pubkey:s,cdnCname:i,cdnCnamePrefixed:e})=>s&&(i===Et||Pt(i,e))?Gi(s,e):i})],qi=({key:s,setValue:i,getValue:e,computationControllers:t})=>{for(let r of us)if(r.deps.includes(s)){let o={[r.key]:e(r.key)};for(let l of r.deps)o[l]=e(l);let n=new AbortController;t.get(r.key)?.abort(),t.set(r.key,n);let a;try{a=r.fn(o,{signal:n.signal})}catch(l){t.get(r.key)===n&&t.delete(r.key),console.error(`Failed to compute value for "${r.key}"`,l);return}Xi(a)?a.then(l=>{n.signal.aborted||i(r.key,l)}).catch(l=>{n.signal.aborted||console.error(`Failed to compute value for "${r.key}"`,l)}).finally(()=>{t.get(r.key)===n&&t.delete(r.key)}):i(r.key,a)}};var Mt=Object.freeze({PHOTO:"photo",VIDEO:"video"}),Au=Object.freeze({IDLE:"idle",SHOT:"shot",PLAY:"play",PAUSE:"pause",RESUME:"resume",STOP:"stop",RETAKE:"retake",ACCEPT:"accept"});var w=s=>String(s),A=s=>{let i=Number(s);if(Number.isNaN(i))throw new Error(`Invalid number: "${s}"`);return i},S=s=>{if(typeof s>"u"||s===null)return!1;if(typeof s=="boolean")return s;if(s==="true"||s==="")return!0;if(s==="false")return!1;throw new Error(`Invalid boolean: "${s}"`)},Wi=s=>s==="auto"?s:S(s),Yi=s=>{let i=w(s);if(i!=="user"&&i!=="environment"&&i!=="")throw new Error(`Invalid value: "${i}"`);return i},Qi=s=>{let i=w(s);if(!Object.values(Mt).includes(i))throw new Error(`Invalid value: "${i}"`);return i},Zi=s=>{let i=w(s),e=ce(i);if(e.some(t=>!Object.values(Mt).includes(t)))throw new Error(`Invalid value: "${JSON.stringify(e)}"`);return i},Ji=s=>{if(typeof s=="object"&&!Array.isArray(s)||typeof s=="function")return s;throw new Error("Invalid metadata value. Must be an object or function.")},$t=s=>{if(typeof s=="object")return s;throw new Error("Invalid value. Must be an object.")},dt=s=>{if(typeof s=="function")return s;throw new Error("Invalid value. Must be a function.")},Nt=s=>{if(Array.isArray(s))return s;throw new Error("Must be an array.")},er=s=>{let i=w(s);if(["grid","list"].includes(i))return i;throw new Error(`Invalid value: "${i}"`)};var hs={pubkey:w,multiple:S,multipleMin:A,multipleMax:A,confirmUpload:S,imgOnly:S,accept:w,externalSourcesPreferredTypes:w,externalSourcesEmbedCss:w,store:Wi,cameraMirror:S,cameraCapture:Yi,sourceList:w,topLevelOrigin:w,maxLocalFileSizeBytes:A,thumbSize:A,showEmptyList:S,useLocalImageEditor:S,useCloudImageEditor:S,cloudImageEditorTabs:w,removeCopyright:S,cropPreset:w,imageShrink:w,modalScrollLock:S,modalBackdropStrokes:S,sourceListWrap:S,remoteTabSessionKey:w,cdnCname:w,cdnCnamePrefixed:w,baseUrl:w,socialBaseUrl:w,secureSignature:w,secureExpire:w,secureDeliveryProxy:w,retryThrottledRequestMaxTimes:A,retryNetworkErrorMaxTimes:A,multipartMinFileSize:A,multipartChunkSize:A,maxConcurrentRequests:A,multipartMaxConcurrentRequests:A,multipartMaxAttempts:A,checkForUrlDuplicates:S,saveUrlForRecurrentUploads:S,groupOutput:S,userAgentIntegration:w,debug:S,localeName:w,metadata:Ji,secureUploadsExpireThreshold:A,localeDefinitionOverride:s=>$t(s),secureUploadsSignatureResolver:s=>dt(s),secureDeliveryProxyUrlResolver:s=>dt(s),iconHrefResolver:s=>dt(s),fileValidators:Nt,collectionValidators:Nt,validationTimeout:A,validationConcurrency:A,cameraModes:Zi,defaultCameraMode:Qi,enableAudioRecording:S,enableVideoRecording:S,mediaRecorderOptions:$t,maxVideoRecordingDuration:A,filesViewMode:er,gridShowFileNames:S,cloudImageEditorAutoOpen:S,cloudImageEditorMaskHref:w,testMode:S,qualityInsights:S},tr=(s,i)=>{if(!(typeof i>"u"||i===null))try{return hs[s](i)}catch(e){return console.error(`Invalid value for config key "${s}".`,e),N[s]}};var ut=[...new Set(["debug",...Object.keys(N)])],ps=["metadata","localeDefinitionOverride","secureUploadsSignatureResolver","secureDeliveryProxyUrlResolver","iconHrefResolver","fileValidators","collectionValidators","mediaRecorderOptions"],sr=s=>ps.includes(s),$e=ut.filter(s=>!sr(s)),ir={...Object.fromEntries($e.map(s=>[ct(s),s])),...Object.fromEntries($e.map(s=>[s.toLowerCase(),s]))},fs={...Object.fromEntries($e.map(s=>[ct(s),k(s)])),...Object.fromEntries($e.map(s=>[s.toLowerCase(),k(s)]))},rr=s=>`__${s}`,ht=class extends T{constructor(){super(...arguments);this.init$={...this.init$,...Object.fromEntries(Object.entries(N).map(([e,t])=>[k(e),t]))};this.computationControllers=new Map}_flushValueToAttribute(e,t){if(!sr(e)){let r=[...new Set([ct(e),e.toLowerCase()])];for(let o of r)typeof t>"u"||t===null?this.removeAttribute(o):this.getAttribute(o)!==t.toString()&&this.setAttribute(o,t.toString())}}_flushValueToState(e,t){this.$[k(e)]!==t&&(typeof t>"u"||t===null?this.$[k(e)]=N[e]:this.$[k(e)]=t)}_setValue(e,t){let r=this,o=tr(e,t),n=rr(e);r[n]!==o&&(this._assertSameValueDifferentReference(e,r[n],o),r[n]=o,this._flushValueToAttribute(e,o),this._flushValueToState(e,o),this.debugPrint(`[uc-config] "${e}"`,o),Ki(this.cfg))}_getValue(e){let t=this,r=rr(e);return t[r]??this.$[k(e)]}_assertSameValueDifferentReference(e,t,r){this.cfg.debug&&r!==t&&typeof r=="object"&&typeof t=="object"&&JSON.stringify(r)===JSON.stringify(t)&&(console.warn(`[uc-config] Option "${e}" value is the same as the previous one but the reference is different`),console.warn("[uc-config] You should avoid changing the reference of the object to prevent unnecessary calculations"),console.warn(`[uc-config] "${e}" previous value:`,t),console.warn(`[uc-config] "${e}" new value:`,r))}initCallback(){super.initCallback();let e=this;for(let t of $e)this.sub(k(t),r=>{this._setValue(t,r)},!1);for(let t of ut){let r=e[t]??this.$[k(t)];r!==N[t]&&this._setValue(t,r),Object.defineProperty(this,t,{set:o=>{this._setValue(t,o)},get:()=>this._getValue(t)})}for(let t of ut)this.sub(k(t),()=>{qi({key:t,setValue:this._setValue.bind(this),getValue:this._getValue.bind(this),computationControllers:this.computationControllers})})}attributeChangedCallback(e,t,r){if(super.attributeChangedCallback(e,t,r),t===r)return;let o=this,n=ir[e];n&&(o[n]=r),fs[e]&&(this[e]=r)}static get observedAttributes(){return[...super.observedAttributes,...Object.keys(ir)]}};for(let s of ut)ht.prototype[s]=void 0;var Ne=class extends T{constructor(){super(...arguments);this.name="";this.resolvedHref="";this.iconHrefResolver=null}initCallback(){super.initCallback(),this.setAttribute("aria-hidden","true"),this.subConfigValue("iconHrefResolver",e=>{this.iconHrefResolver=e,this.updateResolvedHref()})}willUpdate(e){super.willUpdate(e),e.has("name")&&this.updateResolvedHref()}updateResolvedHref(){if(!this.name){this.resolvedHref="";return}let e=`#uc-icon-${this.name}`,t=this.iconHrefResolver?.(this.name);this.resolvedHref=t??e}render(){return m.html` ${this.yield("",m.html`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><use href=${this.resolvedHref}></use></svg>`)} `}};p([(0,c.property)({type:String})],Ne.prototype,"name",2),p([(0,c.state)()],Ne.prototype,"resolvedHref",2);export{K as BtnUi,Vi as CloudImageEditor,x as CloudImageEditorBlock,ht as Config,et as CropFrame,rt as EditorAspectRatioButtonControl,st as EditorCropButtonControl,ae as EditorFilterControl,Rt as EditorFreeformButtonControl,nt as EditorImageCropper,At as EditorImageFader,at as EditorOperationControl,It as EditorScroller,ot as EditorSlider,V as EditorToolbar,Ne as Icon,lt as LineLoaderUi,Me as PresenceToggle,ee as SliderUi,os as defineComponents}; /*! Bundled license information: @lit/context/lib/context-request-event.js: @lit/context/lib/create-context.js: @lit/context/lib/controllers/context-consumer.js: @lit/context/lib/value-notifier.js: @lit/context/lib/controllers/context-provider.js: @lit/context/lib/context-root.js: (** * @license * Copyright 2021 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/context/lib/decorators/provide.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/context/lib/decorators/consume.js: (** * @license * Copyright 2022 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) */