@codingfactory/mediables-vue 2.19.2 → 2.20.0
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.
- package/dist/{PixiFrameExporter-CRe8z6ua.js → PixiFrameExporter-CGQJH9OE.js} +2 -2
- package/dist/{PixiFrameExporter-CRe8z6ua.js.map → PixiFrameExporter-CGQJH9OE.js.map} +1 -1
- package/dist/{PixiFrameExporter-R6iQjzVw.cjs → PixiFrameExporter-CfUbYDmD.cjs} +2 -2
- package/dist/{PixiFrameExporter-R6iQjzVw.cjs.map → PixiFrameExporter-CfUbYDmD.cjs.map} +1 -1
- package/dist/editor-v2-CFLWp7RZ.cjs +2 -0
- package/dist/editor-v2-CFLWp7RZ.cjs.map +1 -0
- package/dist/editor-v2-DjhJBaCS.js +7187 -0
- package/dist/editor-v2-DjhJBaCS.js.map +1 -0
- package/dist/filters/index.d.ts +1 -0
- package/dist/filters/recipeToCssFilter.d.ts +71 -0
- package/dist/index-Dae8SHT7.js.map +1 -1
- package/dist/index-QOKC8XA_.cjs.map +1 -1
- package/dist/index-ST4ukv22.cjs +357 -0
- package/dist/index-ST4ukv22.cjs.map +1 -0
- package/dist/index-rw6mdaKW.js +38906 -0
- package/dist/index-rw6mdaKW.js.map +1 -0
- package/dist/index.d.ts +3 -2
- package/dist/mediables-vanilla.cjs +1 -1
- package/dist/mediables-vanilla.mjs +10 -9
- package/dist/mediables-vue.cjs +1 -1
- package/dist/mediables-vue.mjs +97 -87
- package/dist/style.css +1 -1
- package/dist/utils/videoRecipeCapabilities.d.ts +15 -0
- package/dist/vanilla-exports.d.ts +2 -1
- package/package.json +1 -1
- package/dist/editor-BQ_nY4P6.js +0 -4302
- package/dist/editor-BQ_nY4P6.js.map +0 -1
- package/dist/editor-CUV1pIsV.cjs +0 -2
- package/dist/editor-CUV1pIsV.cjs.map +0 -1
- package/dist/index-B8LxZ37n.js +0 -41633
- package/dist/index-B8LxZ37n.js.map +0 -1
- package/dist/index-DutUeSES.cjs +0 -357
- package/dist/index-DutUeSES.cjs.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var Ge=Object.defineProperty;var Ze=(_,e,t)=>e in _?Ge(_,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):_[e]=t;var me=(_,e,t)=>Ze(_,typeof e!="symbol"?e+"":e,t);const U=require("./index-QOKC8XA_.cjs"),Ke=Object.freeze(["normal","multiply","screen","overlay"]),I=Object.freeze({stroke:Object.freeze({enabled:!1,color:"#000000",width:0}),shadow:Object.freeze({enabled:!1,color:"#000000",alpha:.5,blur:0,distance:0,angle:45}),glow:Object.freeze({enabled:!1,color:"#ffffff",alpha:.5,blur:0}),backdrop:Object.freeze({enabled:!1,color:"#000000",opacity:.5,padding:0,radius:0,blur:0})});class Le extends U.EventEmitter{constructor(){super(),this.app=null,this.sprite=null,this.originalTexture=null,this.baseTexture=null,this.fitScale=1,this.zoom=1,this._container=null,this._lastExportDimensions=null,this._mountPromise=null,this._mountToken=0,this._destroyed=!1,this._layerDocument=null,this._layerDisplayObjects=new Map,this._renderableLayerIds=[],this._loadedTextureUrl=null,this._layerRenderToken=0,this._layerFilterFactory=null}get isReady(){var e;return!!((e=this.app)!=null&&e.renderer)}_getCssSize(){var s,r,a,o,n,l;const e=(r=(s=this.app)==null?void 0:s.renderer)==null?void 0:r.canvas,t=(e==null?void 0:e.clientWidth)??((o=(a=this.app)==null?void 0:a.screen)==null?void 0:o.width)??0,i=(e==null?void 0:e.clientHeight)??((l=(n=this.app)==null?void 0:n.screen)==null?void 0:l.height)??0;return{w:t,h:i}}render(){var e,t;try{(e=this.app)!=null&&e.renderer&&((t=this.app)!=null&&t.stage)&&this.app.renderer.render(this.app.stage)}catch{}}_waitForNextFrame(e=32){return new Promise(t=>{if(typeof window>"u"){t();return}let i=!1,s=0;const r=()=>{i||(i=!0,window.clearTimeout(s),t())};if(s=window.setTimeout(r,e),typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(()=>r());return}r()})}getFitScaleFor(e){if(!this.app||!e)return 1;const{w:t,h:i}=this._getCssSize();if(t<=1||i<=1)return 1;let s=Math.min(t/e.width,i/e.height)*.9;return(!Number.isFinite(s)||s<=0)&&(s=1),s}applyViewTransform(e={}){if(!this.app||!this.sprite||!this.originalTexture)return;const t=this.fitScale*this.zoom,{w:i,h:s}=this._getCssSize(),r=e.keepCenter?{x:this.sprite.x+this.sprite.width/2,y:this.sprite.y+this.sprite.height/2}:e.center??{x:i/2,y:s/2};this.sprite.width=this.originalTexture.width*t,this.sprite.height=this.originalTexture.height*t,this.sprite.x=r.x-this.sprite.width/2,this.sprite.y=r.y-this.sprite.height/2,this._syncLayerDisplayObjects(),this.render()}setZoom(e,t={}){this.zoom=Math.max(.1,Math.min(8,e)),this.applyViewTransform({keepCenter:t.keepCenter??!0}),this.emit("zoomChange",this.zoom)}fitToScreen(){this.originalTexture&&(this.fitScale=this.getFitScaleFor(this.originalTexture),this.setZoom(1,{keepCenter:!1}))}async mount(e,t=16777215,i={}){if(!e)return;this._destroyed=!1,this._container=e;const s=++this._mountToken,r=async()=>{var p;const a=window.PIXI;if(!a)throw new Error("PIXI.js not found. Please ensure PIXI is loaded globally.");(p=a.Assets)!=null&&p.setPreferences&&a.Assets.setPreferences({crossOrigin:"anonymous"});const o=e.clientWidth||600,n=e.clientHeight||400,l=typeof i.backgroundAlpha=="number"?i.backgroundAlpha:1,c=new a.Application;if(this.app=c,await c.init({width:o,height:n,backgroundColor:t,backgroundAlpha:l,antialias:!0,autoDensity:!0,resolution:window.devicePixelRatio||1}),this._destroyed||this._mountToken!==s||this.app!==c){try{c.destroy(!0,{children:!0,texture:!0})}catch{}return!1}e.appendChild(c.canvas);const d=c.canvas;return d.classList.add("pixi-canvas"),d.style.width="100%",d.style.height="100%",d.style.transform="translateZ(0)",d.style.willChange="transform",d.setAttribute("role","img"),d.setAttribute("aria-label","Image editor canvas — use toolbar controls to edit the image"),this.emit("mounted",{width:o,height:n}),!0};return this._mountPromise=r(),await this._mountPromise}async loadTexture(e,t={}){var c,d,p;const i=()=>typeof t.isCurrent!="function"||t.isCurrent()!==!1;if(this._mountPromise&&await this._mountPromise,!((c=this.app)!=null&&c.renderer)||!i())return!1;const s=window.PIXI,r=await this._loadImageElement(e);if(!r||!((d=this.app)!=null&&d.renderer)||!i()||(await this._waitForNextFrame(),!((p=this.app)!=null&&p.renderer)||!i()))return!1;const a=s.Texture.from(r);if(!a)return!1;this.originalTexture=a,this.baseTexture=a,this._loadedTextureUrl=typeof e=="string"?e:null,this.sprite&&(this.app.stage.removeChild(this.sprite),this.sprite.destroy()),this.sprite=new s.Sprite(a),this.app.stage.addChild(this.sprite),this.fitScale=this.getFitScaleFor(a),this.zoom=1;const{w:o,h:n}=this._getCssSize();this.applyViewTransform({center:{x:o/2,y:n/2}});const l=this.getFitScaleFor(a);return Math.abs(l-this.fitScale)/Math.max(1e-6,l)>.02&&(this.fitScale=l,this.applyViewTransform({center:{x:o/2,y:n/2}})),this.render(),this.emit("textureLoaded",{width:a.width,height:a.height}),!0}async renderLayerDocument(e){var a;if(!((a=this.app)!=null&&a.stage)||!this.sprite||!e||!Array.isArray(e.layers))return!1;const t=window.PIXI;if(!t)return!1;const i=++this._layerRenderToken,s=()=>i===this._layerRenderToken;this._destroyLayerDisplayObjects(),this._layerDocument=JSON.parse(JSON.stringify(e)),this._renderableLayerIds=[];try{this.app.stage.removeChild(this.sprite)}catch{}let r=!1;for(const o of this._layerDocument.layers){if(!o||o.visible===!1){(o==null?void 0:o.role)==="subject"&&(this.sprite.visible=!1,this.sprite.__layerId=o.id,r=!0);continue}if(this._isSubjectLayer(o)){const l=await this._createSubjectDisplayObjectForLayer(t,o);if(!s())return this._destroyTransientDisplayObject(l),!1;if(l){this.sprite.visible=!1,l.__layerId=o.id,l.visible=!0,l.alpha=this._layerOpacity(o),this._layerDisplayObjects.set(o.id,{layer:o,displayObject:l}),this._syncLayerDisplayObject(o,l),this.app.stage.addChild(l),this._renderableLayerIds.push(o.id),r=!0;continue}this.sprite.__layerId=o.id,this.sprite.visible=!0,this.sprite.alpha=this._layerOpacity(o),this._applyLayerFilterInstances(this.sprite,o),this.app.stage.addChild(this.sprite),this._renderableLayerIds.push(o.id),r=!0;continue}const n=await this._createDisplayObjectForLayer(t,o);if(!s())return this._destroyTransientDisplayObject(n),!1;n&&(n.__layerId=o.id,n.visible=!0,n.alpha=this._layerOpacity(o),this._layerDisplayObjects.set(o.id,{layer:o,displayObject:n}),this._syncLayerDisplayObject(o,n),this.app.stage.addChild(n),this._renderableLayerIds.push(o.id))}return r||(this.sprite.visible=!1),s()?(this.render(),!0):!1}getRenderableLayerIds(){return[...this._renderableLayerIds]}setLayerFilterFactory(e){this._layerFilterFactory=typeof e=="function"?e:null}applyLayerFilters(e=this._layerDocument){var t;if(!e||!Array.isArray(e.layers))return!1;this._layerDocument=JSON.parse(JSON.stringify(e));for(const i of this._layerDocument.layers){if(!i)continue;const s=this._layerDisplayObjects.get(i.id)||null;s&&(s.layer=i);let r=(s==null?void 0:s.displayObject)||null;!r&&this._isSubjectLayer(i)&&((t=this.sprite)==null?void 0:t.__layerId)===i.id&&(r=this.sprite),r&&this._applyLayerFilterInstances(r,i)}return this.render(),!0}_isSubjectLayer(e){return(e==null?void 0:e.role)==="subject"||(e==null?void 0:e.id)==="subject-layer"}_layerSupportsImageFilters(e){var t;return!e||typeof e!="object"?!1:e.type==="image"?!0:e.type==="background"||e.role==="background"?((t=e.fill)==null?void 0:t.kind)==="media":!1}_layerOpacity(e){const t=Number(e==null?void 0:e.opacity);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):1}_applyLayerFilterInstances(e,t,i={}){if(!e||!this._layerSupportsImageFilters(t))return;let s=[];if(this._layerFilterFactory)try{s=this._layerFilterFactory(t,{displayObject:e,forExport:i.forExport===!0,previewToNativeScale:i.previewToNativeScale||1,sourceWidth:i.sourceWidth,sourceHeight:i.sourceHeight})||[]}catch{s=[]}const r=Array.isArray(s)?s.filter(Boolean):[];for(const n of r)if(!(!n||typeof n!="object"&&typeof n!="function"))try{Object.defineProperty(n,"__mediablesLayerImageFilter",{value:!0,configurable:!0})}catch{try{n.__mediablesLayerImageFilter=!0}catch{}}const o=[...Array.isArray(e.filters)?e.filters.filter(n=>(n==null?void 0:n.__mediablesLayerImageFilter)!==!0):[],...r];e.filters=o.length>0?o:null}async _createDisplayObjectForLayer(e,t){var a,o;const i=this._createTextDisplayObjectForLayer(e,t);if(i)return i;const s=await this._createImageDisplayObjectForLayer(e,t);if(s)return s;const r=this._backgroundFillForLayer(t);if((r==null?void 0:r.kind)==="media"){const n=await this._textureForLayerSource(e,r.source);if(!n)return null;const l=this._createBackgroundSprite(e,n,r.fit);return l.__sourceWidth=Number((a=r.source)==null?void 0:a.originalWidth)||n.width||1,l.__sourceHeight=Number((o=r.source)==null?void 0:o.originalHeight)||n.height||1,this._applyLayerEffects(e,l,t),this._applyLayerFilterInstances(l,t),l}if((r==null?void 0:r.kind)==="gradient"){const n=this._createGradientTexture(e,r,512,512);if(!n||typeof e.Sprite!="function")return null;const l=new e.Sprite(n);return l.__ownsTexture=!0,l.__sourceWidth=512,l.__sourceHeight=512,this._applyLayerEffects(e,l,t),l}if(this._backgroundColorForLayer(t)&&typeof e.Graphics=="function"){const n=new e.Graphics;return this._applyLayerEffects(e,n,t),n}return null}_isTextLayer(e){return(e==null?void 0:e.type)==="text"||(e==null?void 0:e.role)==="text"}_normalizeTextBox(e){var i;const t=(i=e==null?void 0:e.text)!=null&&i.box&&typeof e.text.box=="object"?e.text.box:{};return{x:this._clampNumber(t.x,0,1,.2),y:this._clampNumber(t.y,0,1,.2),width:this._clampNumber(t.width,.05,1,.6),height:this._clampNumber(t.height,.05,1,.18)}}_clampNumber(e,t,i,s){const r=Number(e);return Number.isFinite(r)?Math.max(t,Math.min(i,r)):s}_supportedTextFontFamily(e){const t=["Inter","Arial","Helvetica","Georgia","Times New Roman","Courier New","Verdana"],i=typeof e=="string"?e.trim():"";return t.includes(i)?i:"Inter"}_supportedTextColor(e,t="#000000"){return typeof e=="string"&&/^#[0-9a-f]{6}$/i.test(e)?e:t}_textBlendMode(e){const t=e==null?void 0:e.blendMode;return Ke.includes(t)?t:"normal"}_textContentForLayer(e){var i;const t=(i=e==null?void 0:e.text)==null?void 0:i.content;return t==null?"":String(t)}_textStyleForLayer(e,t=1,i=1,s={}){var m;const r=(m=e==null?void 0:e.text)!=null&&m.style&&typeof e.text.style=="object"?e.text.style:{},a=this._textEffectsForLayer(e),o=this._clampNumber(r.fontSize,8,400,64),n=this._clampNumber(r.lineHeight,.8,3,1.2),l=this._clampNumber(r.letterSpacing,-100,100,0),c=this._normalizeTextFontWeight(r.fontWeight),d=["normal","italic"].includes(r.fontStyle)?r.fontStyle:"normal",p=["left","center","right"].includes(r.align)?r.align:"center",u=s.fill||(typeof r.fill=="string"&&/^#[0-9a-f]{6}$/i.test(r.fill)?r.fill:"#ffffff"),g={fontFamily:this._supportedTextFontFamily(r.fontFamily),fontSize:o*t,fontWeight:c,fontStyle:d,fill:u,align:p,lineHeight:o*n*t,letterSpacing:l*t,wordWrap:!0,wordWrapWidth:Math.max(1,i),breakWords:!0};return s.stroke!==!1&&a.stroke.enabled&&a.stroke.width>0&&(g.stroke={color:a.stroke.color,width:a.stroke.width*t}),g}_normalizeTextFontWeight(e){if(e==="normal")return 400;if(e==="bold")return 700;const t=Number(e);return!Number.isFinite(t)||t<100||t>900||t%100!==0?700:t}_textEffectsForLayer(e){var o;const t=(o=e==null?void 0:e.text)!=null&&o.effects&&typeof e.text.effects=="object"?e.text.effects:{},i=t.stroke&&typeof t.stroke=="object"?t.stroke:{},s=t.shadow&&typeof t.shadow=="object"?t.shadow:{},r=t.glow&&typeof t.glow=="object"?t.glow:{},a=t.backdrop&&typeof t.backdrop=="object"?t.backdrop:{};return{stroke:{enabled:i.enabled===!0,color:this._supportedTextColor(i.color,I.stroke.color),width:this._clampNumber(i.width,0,80,I.stroke.width)},shadow:{enabled:s.enabled===!0,color:this._supportedTextColor(s.color,I.shadow.color),alpha:this._clampNumber(s.alpha,0,1,I.shadow.alpha),blur:this._clampNumber(s.blur,0,120,I.shadow.blur),distance:this._clampNumber(s.distance,0,200,I.shadow.distance),angle:this._normalizeDegrees(s.angle??I.shadow.angle)},glow:{enabled:r.enabled===!0,color:this._supportedTextColor(r.color,I.glow.color),alpha:this._clampNumber(r.alpha,0,1,I.glow.alpha),blur:this._clampNumber(r.blur,0,120,I.glow.blur)},backdrop:{enabled:a.enabled===!0,color:this._supportedTextColor(a.color,I.backdrop.color),opacity:this._clampNumber(a.opacity,0,1,I.backdrop.opacity),padding:this._clampNumber(a.padding,0,200,I.backdrop.padding),radius:this._clampNumber(a.radius,0,200,I.backdrop.radius),blur:this._clampNumber(a.blur,0,80,I.backdrop.blur)}}}_createTextBlurFilter(e,t){if(t<=0||typeof(e==null?void 0:e.BlurFilter)!="function")return null;try{let i;try{i=new e.BlurFilter({strength:t,quality:4})}catch{i=new e.BlurFilter(t)}return typeof i.blur=="number"&&(i.blur=t),typeof i.strength=="number"&&(i.strength=t),i.padding=Math.max(Number(i.padding)||0,Math.ceil(t*2)),i}catch{return null}}_textEffectPadding(e,t){const i=e.stroke.enabled?e.stroke.width*t:0,s=e.shadow.enabled?(e.shadow.distance+e.shadow.blur*2)*t:0,r=e.glow.enabled?e.glow.blur*2*t:0,a=e.backdrop.enabled?(e.backdrop.padding+e.backdrop.blur*2)*t:0;return Math.ceil(Math.max(i,s,r,a,0))}_createTextDisplayObjectForLayer(e,t){if(!this._isTextLayer(t)||typeof(e==null?void 0:e.Text)!="function")return null;const i=this._createTextPrimitive(e,t);if(!i)return null;if(typeof e.Container!="function"||typeof e.Graphics!="function")return i;const s=new e.Container,r=new e.Graphics,a=new e.Graphics,o=new e.Graphics,n=this._createTextPrimitive(e,t),l=this._createTextPrimitive(e,t);return s.__isTextLayerContainer=!0,s.__textObject=i,s.__textMask=r,s.__textEffectMask=a,s.__textBackdrop=o,s.__textShadow=n,s.__textGlow=l,o.visible=!1,n&&(n.visible=!1),l&&(l.visible=!1),i.mask=r,s.addChild(o),n&&s.addChild(n),l&&s.addChild(l),s.addChild(i),s.addChild(a),s.addChild(r),s}_createTextPrimitive(e,t){try{return new e.Text({text:this._textContentForLayer(t),style:this._textStyleForLayer(t)})}catch{try{return new e.Text(this._textContentForLayer(t),this._textStyleForLayer(t))}catch{return null}}}async _createSubjectDisplayObjectForLayer(e,t){const i=this._sourceUrlForLayerSource(t==null?void 0:t.source);return!i||i===this._loadedTextureUrl?null:this._createImageDisplayObjectForLayer(e,t)}async _createImageDisplayObjectForLayer(e,t){var r,a;if((t==null?void 0:t.type)!=="image")return null;const i=await this._textureForLayerSource(e,t.source);if(!i||typeof e.Sprite!="function")return null;const s=new e.Sprite(i);return s.__sourceWidth=Number((r=t.source)==null?void 0:r.originalWidth)||i.width||1,s.__sourceHeight=Number((a=t.source)==null?void 0:a.originalHeight)||i.height||1,this._applyLayerEffects(e,s,t),this._applyLayerFilterInstances(s,t),s}_backgroundFillForLayer(e){const t=e==null?void 0:e.fill;if(t&&typeof t=="object")return t;const i=e==null?void 0:e.source;return(i==null?void 0:i.kind)==="color"&&typeof i.color=="string"?{kind:"color",value:i.color}:null}_backgroundColorForLayer(e){const t=e==null?void 0:e.source;if((t==null?void 0:t.kind)==="color"&&typeof t.color=="string")return t.color;const i=e==null?void 0:e.fill;return(i==null?void 0:i.kind)==="color"&&typeof i.value=="string"?i.value:null}_sourceUrlForLayerSource(e){if(!e||typeof e!="object")return null;for(const t of["previewUrl","sourceUrl","url"]){const i=e[t];if(typeof i=="string"&&i.trim()!=="")return i}return null}async _textureForLayerSource(e,t){const i=this._sourceUrlForLayerSource(t);if(!i)return null;const s=await this._loadImageElement(i);return s?e.Texture.from(s):null}_createBackgroundSprite(e,t,i="cover"){if(i==="tile"&&typeof e.TilingSprite=="function")try{const s=new e.TilingSprite({texture:t,width:1,height:1});return s.__isTilingBackground=!0,s}catch{try{const r=new e.TilingSprite(t,1,1);return r.__isTilingBackground=!0,r}catch{}}return new e.Sprite(t)}_createGradientTexture(e,t,i,s){var l;if(typeof document>"u"||!((l=e==null?void 0:e.Texture)!=null&&l.from))return null;const r=document.createElement("canvas");r.width=Math.max(1,Math.round(i)),r.height=Math.max(1,Math.round(s));const a=r.getContext("2d");if(!a)return null;const o=Array.isArray(t==null?void 0:t.stops)&&t.stops.length>0?t.stops:[{offset:0,color:"#111827"},{offset:1,color:"#f59e0b"}];let n;if((t==null?void 0:t.gradientType)==="radial"){const c=Math.max(r.width,r.height)/2;n=a.createRadialGradient(r.width/2,r.height/2,0,r.width/2,r.height/2,c)}else{const c=(Number(t==null?void 0:t.angle)||0)*Math.PI/180,d=r.width/2,p=r.height/2,u=Math.sqrt(r.width**2+r.height**2)/2,g=Math.cos(c)*u,m=Math.sin(c)*u;n=a.createLinearGradient(d-g,p-m,d+g,p+m)}for(const c of o){if(!c||typeof c.color!="string")continue;const d=Number.isFinite(Number(c.offset))?Math.max(0,Math.min(1,Number(c.offset))):0;n.addColorStop(d,c.color)}return a.fillStyle=n,a.fillRect(0,0,r.width,r.height),e.Texture.from(r)}_backgroundBlurAmount(e){var r;const i=(Array.isArray(e==null?void 0:e.effects)?e.effects:[]).find(a=>(a==null?void 0:a.id)==="background-blur"||(a==null?void 0:a.type)==="blur"),s=Number((r=i==null?void 0:i.params)==null?void 0:r.amount);return Number.isFinite(s)?Math.max(0,s):0}_applyLayerEffects(e,t,i){const s=this._backgroundBlurAmount(i);if(!(s<=0||typeof(e==null?void 0:e.BlurFilter)!="function"))try{let r;try{r=new e.BlurFilter({strength:s,quality:4})}catch{r=new e.BlurFilter(s)}typeof r.blur=="number"&&(r.blur=s),typeof r.strength=="number"&&(r.strength=s),r.padding=Math.max(Number(r.padding)||0,Math.ceil(s*2)),t.filters=Array.isArray(t.filters)?[...t.filters,r]:[r]}catch{}}_syncLayerDisplayObjects(){if(this.sprite)for(const{layer:e,displayObject:t}of this._layerDisplayObjects.values())this._syncLayerDisplayObject(e,t)}_syncLayerDisplayObject(e,t){if(!this.sprite||!t)return;if(this._isTextLayer(e)){this._fitTextDisplayObjectToRect(t,e,{x:this.sprite.x,y:this.sprite.y,width:this.sprite.width,height:this.sprite.height});return}const i=this._backgroundColorForLayer(e);if(i&&typeof t.clear=="function"){t.clear(),t.rect(this.sprite.x,this.sprite.y,this.sprite.width,this.sprite.height).fill(i);return}this._fitDisplayObjectToRect(t,e,{x:this.sprite.x,y:this.sprite.y,width:this.sprite.width,height:this.sprite.height})}_fillTextEffectGraphics(e,t,i=1){if(!(!e||typeof e.fill!="function"))try{e.fill({color:t,alpha:i})}catch{e.fill(t),e.alpha=i}}_syncTextEffectPrimitive(e,t,i,s,r,a,o,n){if(!t)return;const l=s[r];if(t.visible=(l==null?void 0:l.enabled)===!0,t.filters=null,t.mask=t.visible?n:null,!!t.visible){if(t.text=this._textContentForLayer(i),t.rotation=0,r==="shadow"){const c=l.angle*Math.PI/180;t.x=Math.cos(c)*l.distance*a,t.y=Math.sin(c)*l.distance*a,t.alpha=l.alpha,t.style=this._textStyleForLayer(i,a,o,{fill:l.color,stroke:!1});const d=this._createTextBlurFilter(e,l.blur*a);t.filters=d?[d]:null;return}if(r==="glow"){t.x=0,t.y=0,t.alpha=l.alpha,t.style=this._textStyleForLayer(i,a,o,{fill:l.color,stroke:!1});const c=this._createTextBlurFilter(e,l.blur*a);t.filters=c?[c]:null}}}_syncTextBackdrop(e,t,i,s,r,a,o){if(!t)return;const n=i.backdrop;if(t.visible=n.enabled===!0,t.filters=null,t.mask=t.visible?o:null,t.alpha=1,typeof t.clear=="function"&&t.clear(),!t.visible)return;const l=n.padding*s,c=n.radius*s,d=-l,p=-l,u=r+l*2,g=a+l*2;c>0&&typeof t.roundRect=="function"?t.roundRect(d,p,u,g,c):typeof t.rect=="function"&&t.rect(d,p,u,g),this._fillTextEffectGraphics(t,n.color,n.opacity);const m=this._createTextBlurFilter(e,n.blur*s);t.filters=m?[m]:null}_fitTextDisplayObjectToRect(e,t,i){var m,f;const s=this._normalizeTextBox(t),r=i.x+s.x*i.width,a=i.y+s.y*i.height,o=s.width*i.width,n=s.height*i.height,l=Number((m=this.originalTexture)==null?void 0:m.width)||i.width,c=l>0?i.width/l:1,d=this._textEffectsForLayer(t);e.x=r,e.y=a,e.rotation=this._normalizeDegrees(Number((f=t==null?void 0:t.transform)==null?void 0:f.rotation)||0)*Math.PI/180,e.blendMode=this._textBlendMode(t),e.__textBox=s,e.__textLayout={x:r,y:a,width:o,height:n,scale:c};const p=e.__textObject||e,u=e.__textMask||null,g=e.__textEffectMask||null;if(p.text=this._textContentForLayer(t),p.style=this._textStyleForLayer(t,c,o),p.x=0,p.y=0,p.rotation=0,u&&typeof u.clear=="function"&&typeof u.rect=="function"&&typeof u.fill=="function"&&(u.clear(),u.rect(0,0,o,n).fill(16777215),p.mask=u),g&&typeof g.clear=="function"&&typeof g.rect=="function"&&typeof g.fill=="function"){const v=this._textEffectPadding(d,c);g.clear(),g.rect(-v,-v,o+v*2,n+v*2).fill(16777215)}this._syncTextBackdrop(window.PIXI,e.__textBackdrop,d,c,o,n,g),this._syncTextEffectPrimitive(window.PIXI,e.__textShadow,t,d,"shadow",c,o,g),this._syncTextEffectPrimitive(window.PIXI,e.__textGlow,t,d,"glow",c,o,g)}_fitDisplayObjectToRect(e,t,i){var d,p,u,g,m,f,v,k;const s=this._backgroundFillForLayer(t),r=(s==null?void 0:s.fit)||"cover";if(e.__isTilingBackground){e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height,(p=(d=e.tilePosition)==null?void 0:d.set)==null||p.call(d,0,0),(g=(u=e.tileScale)==null?void 0:u.set)==null||g.call(u,1,1);return}if(r==="stretch"||(s==null?void 0:s.kind)==="gradient"||(s==null?void 0:s.kind)==="color"){e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height;return}const a=Number(e.__sourceWidth||((m=s==null?void 0:s.source)==null?void 0:m.originalWidth)||((f=e.texture)==null?void 0:f.width)||i.width),o=Number(e.__sourceHeight||((v=s==null?void 0:s.source)==null?void 0:v.originalHeight)||((k=e.texture)==null?void 0:k.height)||i.height);if(!Number.isFinite(a)||!Number.isFinite(o)||a<=0||o<=0){e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height;return}const n=r==="contain"?Math.min(i.width/a,i.height/o):Math.max(i.width/a,i.height/o),l=a*n,c=o*n;e.x=i.x+(i.width-l)/2,e.y=i.y+(i.height-c)/2,e.width=l,e.height=c}_destroyLayerDisplayObjects(){var e,t,i,s,r;if((e=this._layerDisplayObjects)!=null&&e.size){for(const{displayObject:a}of this._layerDisplayObjects.values()){try{(s=(i=(t=this.app)==null?void 0:t.stage)==null?void 0:i.removeChild)==null||s.call(i,a)}catch{}const o=(a==null?void 0:a.__ownsTexture)===!0;(r=a==null?void 0:a.destroy)==null||r.call(a,{children:!0,texture:o,textureSource:o})}this._layerDisplayObjects.clear(),this._renderableLayerIds=[]}}_destroyTransientDisplayObject(e){var i,s,r,a;if(!e)return;try{(r=(s=(i=this.app)==null?void 0:i.stage)==null?void 0:s.removeChild)==null||r.call(s,e)}catch{}const t=(e==null?void 0:e.__ownsTexture)===!0;(a=e==null?void 0:e.destroy)==null||a.call(e,{children:!0,texture:t,textureSource:t})}_normalizeDegrees(e){if(!Number.isFinite(e))return 0;const t=e%360;return t<0?t+360:t}getRotatedBounds(e,t,i){const s=this._normalizeDegrees(i);if(s===0)return{width:Math.max(1,Math.round(e)),height:Math.max(1,Math.round(t))};const r=s*Math.PI/180,a=Math.abs(Math.cos(r)),o=Math.abs(Math.sin(r)),n=a<1e-10?0:a,l=o<1e-10?0:o;return{width:Math.max(1,Math.ceil(e*n+t*l)),height:Math.max(1,Math.ceil(e*l+t*n))}}rotateBy(e){var m,f,v;const t=this._normalizeDegrees(e);if(t===0)return!0;if(!((m=this.app)!=null&&m.renderer)||!this.originalTexture||!this.sprite)return!1;const i=window.PIXI,s=Math.round(this.originalTexture.width),r=Math.round(this.originalTexture.height);if(s<=0||r<=0)return!1;const{width:a,height:o}=this.getRotatedBounds(s,r,t),n=t*Math.PI/180,l=new i.Container,c=new i.Sprite(this.originalTexture);(v=(f=c.anchor)==null?void 0:f.set)==null||v.call(f,.5),c.x=a/2,c.y=o/2,c.rotation=n,l.addChild(c);const d=i.RenderTexture.create({width:a,height:o,resolution:1});try{this.app.renderer.render({container:l,target:d,clear:!0,clearColor:[0,0,0,0]})}catch{return d.destroy(!0),!1}finally{l.removeChildren(),c.destroy({children:!1,texture:!1,textureSource:!1}),l.destroy({children:!1})}const p=this.originalTexture,u=Array.isArray(this.sprite.filters)?[...this.sprite.filters]:null;p&&p!==this.baseTexture&&p.destroy(!0),this.originalTexture=d,this._lastExportDimensions=null,this.app.stage.removeChild(this.sprite),this.sprite.destroy({children:!1,texture:!1,textureSource:!1});const g=new i.Sprite(d);return u!=null&&u.length&&(g.filters=u),this.app.stage.addChild(g),this.sprite=g,this.fitScale=this.getFitScaleFor(d),this.zoom=1,this.applyViewTransform({keepCenter:!1}),this.render(),this.emit("textureRotated",{width:a,height:o,degrees:t}),!0}exportImage(e="png",t=.92,i=0,s=!0,r=0){var F;if(!((F=this.app)!=null&&F.renderer)||!this.originalTexture||!this.sprite)return null;const a=window.PIXI,o=Math.round(this.originalTexture.width),n=Math.round(this.originalTexture.height);if(o<=0||n<=0)return null;const l=this.sprite.width,c=this.sprite.height;if(l<=0||c<=0)return null;const d=l/o,p=d>0?1/d:1,u=this._layerDocument,g=u&&Array.isArray(u.layers),m=[];if(!g&&Array.isArray(this.sprite.filters)){for(const y of this.sprite.filters)if(y)if(typeof y.createExportFilter=="function"){const x=y.createExportFilter({previewToNativeScale:p});x&&m.push(x)}else m.push(y)}let f=0;for(const y of m){const x=typeof y.getExportPadding=="function"?Number(y.getExportPadding())||0:typeof y._exportPadding=="number"?y._exportPadding:typeof y.padding=="number"?y.padding:0;x>0&&(f+=x)}const v=Math.max(Math.ceil(f),64),k=y=>{var ne,ae,D,oe;const x=Math.ceil(o+2*y),E=Math.ceil(n+2*y),M=new a.Container,T=[],O=(b=null)=>{const C=new a.Sprite(this.originalTexture);C.x=y,C.y=y,C.scale.set(1,1),C.alpha=b?this._layerOpacity(b):1,b&&this._applyLayerFilterInstances(C,b,{forExport:!0,previewToNativeScale:p,sourceWidth:o,sourceHeight:n}),m.length>0&&(C.filters=m,C.filterArea=new a.Rectangle(0,0,o,n)),M.addChild(C),T.push(C)},R=b=>{var ee,P,$;const C=(ee=this._layerDisplayObjects.get(b.id))==null?void 0:ee.displayObject,H=this._isSubjectLayer(b),V=(C==null?void 0:C.texture)||(H?this.originalTexture:null);if(!V||typeof a.Sprite!="function")return!1;const S=new a.Sprite(V),le=(C==null?void 0:C.__sourceWidth)||(H?null:(P=b.source)==null?void 0:P.originalWidth)||V.width||o,he=(C==null?void 0:C.__sourceHeight)||(H?null:($=b.source)==null?void 0:$.originalHeight)||V.height||n;return S.__sourceWidth=Number(le),S.__sourceHeight=Number(he),this._fitDisplayObjectToRect(S,b,{x:y,y,width:o,height:n}),S.alpha=this._layerOpacity(b),!g&&H&&m.length>0&&(S.filters=m,S.filterArea=new a.Rectangle(0,0,o,n)),this._applyLayerEffects(a,S,b),this._applyLayerFilterInstances(S,b,{forExport:!0,previewToNativeScale:p,sourceWidth:o,sourceHeight:n}),M.addChild(S),T.push(S),!0},A=b=>{var le,he,ee;const C=this._backgroundFillForLayer(b),H=this._backgroundColorForLayer(b),V={x:y,y,width:o,height:n};let S=null;if(H&&typeof a.Graphics=="function")S=new a.Graphics,S.rect(y,y,o,n).fill(H);else if((C==null?void 0:C.kind)==="gradient"&&typeof a.Sprite=="function"){const P=this._createGradientTexture(a,C,o,n);if(!P)return!1;S=new a.Sprite(P),S.__ownsTexture=!0,S.__sourceWidth=o,S.__sourceHeight=n,this._fitDisplayObjectToRect(S,b,V)}else if((C==null?void 0:C.kind)==="media"){const P=(le=this._layerDisplayObjects.get(b.id))==null?void 0:le.displayObject,$=P==null?void 0:P.texture;if(!$)return!1;S=this._createBackgroundSprite(a,$,C.fit),S.__sourceWidth=Number(((he=C.source)==null?void 0:he.originalWidth)||P.__sourceWidth||$.width||1),S.__sourceHeight=Number(((ee=C.source)==null?void 0:ee.originalHeight)||P.__sourceHeight||$.height||1),this._fitDisplayObjectToRect(S,b,V)}return S?(S.alpha=this._layerOpacity(b),this._applyLayerEffects(a,S,b),this._applyLayerFilterInstances(S,b,{forExport:!0,previewToNativeScale:p,sourceWidth:o,sourceHeight:n}),M.addChild(S),T.push(S),!0):!1},z=b=>{const C=this._createTextDisplayObjectForLayer(a,b);return C?(this._fitTextDisplayObjectToRect(C,b,{x:y,y,width:o,height:n}),C.alpha=this._layerOpacity(b),M.addChild(C),T.push(C),!0):!1},q=u,Q=g;if(Q){for(const b of q.layers)if(!(!b||b.visible===!1)){if(this._isTextLayer(b)){z(b);continue}if(b.type==="image"){!R(b)&&this._isSubjectLayer(b)&&O(b);continue}if(this._isSubjectLayer(b)){R(b)||O(b);continue}A(b)}}else O();!Q&&((ne=M.children)==null?void 0:ne.length)===0&&O();const X=a.RenderTexture.create({width:x,height:E,resolution:1}),fe=((ae=M.children)==null?void 0:ae.length)??0;try{this.app.renderer.render({container:M,target:X,clear:!0,clearColor:[0,0,0,0]});const b=(oe=(D=this.app.renderer.extract)==null?void 0:D.canvas)==null?void 0:oe.call(D,X);return b?{canvas:b,width:x,height:E,margin:y,childCount:fe}:null}finally{for(const b of T)b.filters=null;M.removeChildren();for(const b of T){const C=(b==null?void 0:b.__ownsTexture)===!0;b.destroy({children:!1,texture:C,textureSource:C})}M.destroy({children:!1}),X.destroy(!0)}},L=(y,x,E)=>{const M=typeof y.getContext=="function"?y.getContext("2d"):null;if(!M)return null;let T;try{T=M.getImageData(0,0,x,E).data}catch{return null}const O=1;let R=x,A=E,z=-1,q=-1;const Q=4,X=x*Q;for(let D=0;D<E;D++){const oe=D*X;for(let b=0;b<x;b++)T[oe+b*Q+3]>=O&&(b<R&&(R=b),b>z&&(z=b),D<A&&(A=D),D>q&&(q=D))}if(z<0)return null;const fe=z-R+1,ne=q-A+1,ae=R===0||A===0||z===x-1||q===E-1;return{x:R,y:A,width:fe,height:ne,touchesEdge:ae}};let w=null;try{let y=k(v);if(!y)return null;let x=L(y.canvas,y.width,y.height);if(!x)if(g&&y.childCount===0)x={x:y.margin,y:y.margin,width:o,height:n,touchesEdge:!1};else return null;if(x.touchesEdge&&v<o&&v<n){const R=Math.max(v*4,256),A=k(R);if(A){const z=L(A.canvas,A.width,A.height);z&&!z.touchesEdge?(y=A,x=z):(y=A,x=z??x)}}let E=x.width,M=x.height;if(i>0){const R=Math.max(E,M);let A=i/R;s&&(A=Math.min(1,A)),E=Math.max(1,Math.round(E*A)),M=Math.max(1,Math.round(M*A))}if(r>0&&E*M>r){const R=Math.sqrt(r/(E*M));E=Math.max(1,Math.floor(E*R)),M=Math.max(1,Math.floor(M*R))}const T=document.createElement("canvas");T.width=E,T.height=M;const O=T.getContext("2d");return O?(O.drawImage(y.canvas,x.x,x.y,x.width,x.height,0,0,E,M),w=T.toDataURL(`image/${e}`,t),this._lastExportDimensions={width:E,height:M},w||null):null}catch{return null}}getExportDimensions(){var a;if(this._lastExportDimensions)return{...this._lastExportDimensions};const e=this.originalTexture,t=Math.round((e==null?void 0:e.width)||0),i=Math.round((e==null?void 0:e.height)||0);let s=0;const r=(a=this.sprite)==null?void 0:a.filters;if(Array.isArray(r))for(const o of r){if(!o)continue;const n=typeof o._exportPadding=="number"?o._exportPadding:typeof o.padding=="number"?o.padding:0;n>s&&(s=n)}return{width:t+2*s,height:i+2*s}}async exportBlob(e="png",t=.92,i={}){const s=this.exportImage(e,t,i.maxEdge??0,i.dontUpscale!==!1,i.maxPixels??0);if(!s)return null;const a=await(await fetch(s)).blob(),o=this.getExportDimensions();return{blob:a,width:o.width,height:o.height}}resizeTo(e){var s;if(!((s=this.app)!=null&&s.renderer)||!e)return;const t=e.clientWidth,i=e.clientHeight;if(!(t===Math.round(this.app.screen.width)&&i===Math.round(this.app.screen.height))&&!(t<=0||i<=0)&&(this.app.renderer.resize(t,i),this.originalTexture&&this.sprite)){const r={x:this.sprite.x+this.sprite.width/2,y:this.sprite.y+this.sprite.height/2};this.fitScale=this.getFitScaleFor(this.originalTexture),this.applyViewTransform({center:r})}}setBackgroundColor(e){var t,i;(i=(t=this.app)==null?void 0:t.renderer)!=null&&i.background&&(this.app.renderer.background.color=e)}_loadImageElement(e){return new Promise(t=>{const i=new Image;typeof e=="string"&&/^https?:\/\//.test(e)&&(i.crossOrigin="anonymous"),i.onload=()=>t(i),i.onerror=()=>{t(null)},i.src=e})}destroy(){if(this._destroyed=!0,this._mountToken+=1,this._mountPromise=null,this._destroyLayerDisplayObjects(),this.app){try{this.app.destroy(!0,{children:!0,texture:!0})}catch{}this.app=null}this.sprite=null,this.originalTexture=null,this.baseTexture=null,this._container=null,this.removeAllListeners()}}const te='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="48" d="M328 112L184 256l144 144"/></svg>',ie='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="48" d="M184 112l144 144-144 144"/></svg>',Ye='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M221.09 64a157.09 157.09 0 10157.09 157.09A157.1 157.1 0 00221.09 64z"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M338.29 338.29L448 448M256 184v74m-37-37h74"/></svg>',Je='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M221.09 64a157.09 157.09 0 10157.09 157.09A157.1 157.1 0 00221.09 64z"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M338.29 338.29L448 448M184 221h74"/></svg>',Qe='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M432 320v112H320M80 192V80h112M320 80h112v112M192 432H80V320"/></svg>',Xe='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M262.29 192.31a64 64 0 1057.4 57.4 64.13 64.13 0 00-57.4-57.4z"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M416.39 256a154.34 154.34 0 01-1.53 20.79l45.21 35.46a10.81 10.81 0 012.45 13.75l-42.77 74a10.81 10.81 0 01-13.14 4.59l-44.9-18.08a16.11 16.11 0 00-15.17 1.75A164.48 164.48 0 01325 400.8a15.94 15.94 0 00-8.82 12.14l-6.73 47.89a11.08 11.08 0 01-10.68 9.17h-85.54a11.11 11.11 0 01-10.69-8.87l-6.72-47.82a16.07 16.07 0 00-9-12.22 155.3 155.3 0 01-21.46-12.57 16 16 0 00-15.11-1.71l-44.89 18.07a10.81 10.81 0 01-13.14-4.58l-42.77-74a10.8 10.8 0 012.45-13.75l38.21-30a16.05 16.05 0 006-14.08c-.36-4.17-.58-8.33-.58-12.5s.21-8.27.58-12.35a16 16 0 00-6.07-13.94l-38.19-30A10.81 10.81 0 0149.48 186l42.77-74a10.81 10.81 0 0113.14-4.59l44.9 18.08a16.11 16.11 0 0015.17-1.75A164.48 164.48 0 01187 111.2a15.94 15.94 0 008.82-12.14l6.73-47.89A11.08 11.08 0 01213.23 42h85.54a11.11 11.11 0 0110.69 8.87l6.72 47.82a16.07 16.07 0 009 12.22 155.3 155.3 0 0121.46 12.57 16 16 0 0015.11 1.71l44.89-18.07a10.81 10.81 0 0113.14 4.58l42.77 74a10.8 10.8 0 01-2.45 13.75l-38.21 30a16.05 16.05 0 00-6.05 14.08c.33 4.14.55 8.3.55 12.47z"/></svg>',et='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M400 320c0 88.37-55.63 144-144 144s-144-55.63-144-144c0-94.83 103.23-222.85 134.89-259.88a12 12 0 0118.23 0C296.77 97.15 400 225.17 400 320z"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M344 328a72 72 0 01-72 72"/></svg>',tt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32" d="M430.11 347.9c-6.6-6.1-16.3-7.6-24.6-9-11.5-1.9-15.9-4-22.6-10-14.3-12.7-14.3-31.1 0-43.8l30.3-26.9c46.4-41 46.4-108.2 0-149.2-34.2-30.1-80.1-45-127.8-45-55.7 0-113.9 20.3-158.8 60.1-83.5 73.8-83.5 194.7 0 268.5 41.5 36.7 97.5 55 152.9 55.4h1.7c55.4 0 110-17.9 148.8-52.4 14.4-12.7 11.99-36.6.1-47.7z"/><circle cx="144" cy="208" r="32"/><circle cx="152" cy="311" r="32"/><circle cx="224" cy="144" r="32"/><circle cx="256" cy="367" r="32"/><circle cx="328" cy="144" r="32"/></svg>',it='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M259.92 262.91L216.4 149.77a9 9 0 00-16.8 0l-43.52 113.14a9 9 0 01-5.17 5.17L37.77 311.6a9 9 0 000 16.8l113.14 43.52a9 9 0 015.17 5.17l43.52 113.14a9 9 0 0016.8 0l43.52-113.14a9 9 0 015.17-5.17l113.14-43.52a9 9 0 000-16.8l-113.14-43.52a9 9 0 01-5.17-5.17zM108 68L88 16 68 68 16 88l52 20 20 52 20-52 52-20-52-20zM426.67 117.33L400 48l-26.67 69.33L304 144l69.33 26.67L400 240l26.67-69.33L496 144l-69.33-26.67z"/></svg>',Ee='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M176 112l80-80 80 80M255.98 32l.02 448M176 400l80 80 80-80M400 176l80 80-80 80M112 176l-80 80 80 80M32 256h448"/></svg>',st='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M452.37 59.63h0a40.49 40.49 0 00-57.26 0L184 294.74c23.08 4.7 46.12 27.29 49.26 49.26l219.11-227.11a40.49 40.49 0 000-57.26z"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M138 336c-29.88 0-54 24.5-54 54.86 0 23.95-20.67 36.57-34 44.78 15.08 8.08 32.23 12.36 50 12.36 48.49 0 88-38.89 88-88 0-30.36-24.12-54-50-54z"/></svg>',rt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M315.27 33L96 304h128l-31.51 173.23a2.36 2.36 0 002.33 2.77h0a2.36 2.36 0 001.89-.95L416 208H288l31.66-173.25a2.45 2.45 0 00-2.44-2.75h0a2.42 2.42 0 00-1.95 1z"/></svg>',Ae='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M144 48v272a48 48 0 0048 48h272"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M368 464V192a48 48 0 00-48-48H48"/></svg>',Te='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M380.93 57.37A32 32 0 00358.3 48H94.22A46.21 46.21 0 0048 94.22v323.56A46.21 46.21 0 0094.22 464h323.56A46.36 46.36 0 00464 417.78V153.7a32 32 0 00-9.37-22.63zM256 416a64 64 0 1164-64 63.92 63.92 0 01-64 64zm48-224H112a16 16 0 01-16-16v-64a16 16 0 0116-16h192a16 16 0 0116 16v64a16 16 0 01-16 16z"/></svg>',se='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M368 368L144 144M368 144L144 368"/></svg>',Be='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M320 146s24.36-12-64-12a160 160 0 10160 160"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M256 58l80 80-80 80"/></svg>',nt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M176 112l-64 64 64 64"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M112 176h176a112 112 0 110 224H160"/></svg>',at='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M336 112l64 64-64 64"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M400 176H224a112 112 0 100 224h128"/></svg>',Ne='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M112 112l20 320c.95 18.49 14.4 32 32 32h184c17.67 0 30.87-13.51 32-32l20-320"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="32" d="M80 112h352"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M192 112V72h0a23.93 23.93 0 0124-24h80a23.93 23.93 0 0124 24h0v40M256 176v224M184 176l8 224M328 176l-8 224"/></svg>',ot='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M64 192v-72a40 40 0 0140-40h75.89a40 40 0 0122.19 6.72l27.84 18.56a40 40 0 0022.19 6.72H408a40 40 0 0140 40v40"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M479.9 226.55L463.68 392a40 40 0 01-39.93 40H88.25a40 40 0 01-39.93-40L32.1 226.55A32 32 0 0164 192h384.1a32 32 0 0131.8 34.55z"/></svg>',_e='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M416 128L192 384l-96-96"/></svg>',Ie='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32" d="M48 256l208 112 208-112-208-112L48 256z"/><path fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32" d="M48 336l208 112 208-112M48 176L256 64l208 112"/></svg>',lt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32" d="M48 256s80-144 208-144 208 144 208 144-80 144-208 144S48 256 48 256z"/><circle cx="256" cy="256" r="64" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32"/></svg>',ht='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M432 448L80 64M160 160c-67.2 36.8-112 96-112 96s80 144 208 144c35.8 0 68.4-11.3 96-28.1M224.4 113.8A199.6 199.6 0 01256 112c128 0 208 144 208 144a334.2 334.2 0 01-65.1 78.6"/><path fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32" d="M213.3 213.3A64 64 0 10298.7 298.7"/></svg>',ct='<svg viewBox="0 0 512 512" width="20" height="20"><rect x="96" y="208" width="320" height="240" rx="32" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M160 208v-64a96 96 0 01192 0v64"/></svg>',dt='<svg viewBox="0 0 512 512" width="20" height="20"><rect x="96" y="208" width="320" height="240" rx="32" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M160 208v-64a96 96 0 01168-63.7"/></svg>',ut='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32" d="M96 352l-32 96 96-32L421.5 154.5a45.3 45.3 0 000-64h0a45.3 45.3 0 00-64 0L96 352z"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M320 128l64 64"/></svg>',pt='<svg viewBox="0 0 512 512" width="20" height="20"><rect x="144" y="144" width="288" height="288" rx="32" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32"/><path fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32" d="M80 368V112a32 32 0 0132-32h256"/></svg>',_t='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M96 112V80h320v32M256 80v352M184 432h144"/></svg>',gt='<svg viewBox="0 0 512 512" width="20" height="20"><rect x="64" y="64" width="384" height="384" rx="48" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32"/></svg>',ft='<svg viewBox="0 0 512 512" width="20" height="20"><circle cx="256" cy="256" r="208" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/></svg>',mt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M80 96h64l64 320h64l64-160h96"/></svg>',Me='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="32" d="M256 48v48M256 416v48M403.08 108.92l-33.94 33.94M142.86 369.14l-33.94 33.94M464 256h-48M96 256H48M403.08 403.08l-33.94-33.94M142.86 142.86l-33.94-33.94"/><circle cx="256" cy="256" r="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="32"/></svg>',Fe='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M160 136c0-30.62 4.51-61.61 16-88C99.57 81.27 48 159.32 48 248c0 119.29 96.71 216 216 216 88.68 0 166.73-51.57 200-128-26.39 11.49-57.38 16-88 16-119.29 0-216-96.71-216-216z"/></svg>',bt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M436 80H76a44.05 44.05 0 00-44 44v264a44.05 44.05 0 0044 44h360a44.05 44.05 0 0044-44V124a44.05 44.05 0 00-44-44z"/><circle cx="256" cy="256" r="80" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M220 80v56M292 80v56M220 376v56M292 376v56M80 144h56M80 224h56M80 304h56M376 144h56M376 224h56M376 304h56"/></svg>',vt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M344 144c-3.92 52.87-44 96-88 96s-84.15-43.12-88-96c-4-55 35-96 88-96s92 42 88 96z"/><path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32" d="M256 304c-87 0-175.3 48-191.64 138.6C62.39 453.52 68.57 464 80 464h352c11.44 0 17.62-10.48 15.65-21.4C431.3 352 343 304 256 304z"/></svg>',re=[{id:"adjust",name:"Adjust",icon:Xe,registryCategories:["adjust","advanced"]},{id:"blur",name:"Blur",icon:et,registryCategories:["blur"]},{id:"color",name:"Color",icon:tt,registryCategories:["color"]},{id:"effects",name:"Effects",icon:it,registryCategories:["effects"]},{id:"distortion",name:"Distortion",icon:Ee,registryCategories:["distortion"]},{id:"light",name:"Light",icon:rt,registryCategories:["light"]},{id:"stylize",name:"Stylize",icon:bt,registryCategories:["stylize"]},{id:"text",name:"Text",icon:_t},{id:"background",name:"Background",icon:st},{id:"layers",name:"Layers",icon:Ie},{id:"crop",name:"Crop",icon:Ae}],yt=Object.fromEntries(re.filter(_=>Array.isArray(_.registryCategories)&&_.registryCategories.length>0).map(_=>[_.id,_.registryCategories])),ye=Object.fromEntries(re.filter(_=>Array.isArray(_.registryCategories)).flatMap(_=>_.registryCategories.map(e=>[e,_.id])));function wt(_){return yt[_]||[_]}class De extends U.EventEmitter{constructor(e,t){super(),this.state=e,this.renderer=t,this.instances={},this._filterRegistry=null}setRegistry(e){var t,i;this._filterRegistry=e,(i=(t=this.renderer)==null?void 0:t.setLayerFilterFactory)==null||i.call(t,(s,r)=>this.createFiltersForLayer(s,r))}getFilterDef(e){return this._filterRegistry?this._filterRegistry.getFilter(e):null}getAllFilters(){var e;return((e=this._filterRegistry)==null?void 0:e.getAllFilters())||[]}getFiltersByCategory(e){if(!this._filterRegistry)return[];const t=wt(e),i=[],s=new Set;for(const r of t){const a=this._filterRegistry.getFiltersByCategory(r)||[];for(const o of a)s.has(o.id)||(s.add(o.id),i.push(o))}return i}_normalizeValue(e){return Array.isArray(e)?e.length>0&&typeof e[0]=="object"?e:Number(e[0]??0):typeof e=="string"?e.startsWith("#")?e:e.trim()===""?0:Number(e):e}_getDeepProp(e,t){if(!e||!t)return;if(!t.includes(".")&&!t.includes("["))return e[t];const i=t.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean);let s=e;for(const r of i){if(s==null)return;s=s[r]}return s}_setDeepProp(e,t,i){if(!e||!t)return;if(!t.includes(".")&&!t.includes("[")){e[t]=i;return}const s=t.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean);let r=e;for(let o=0;o<s.length-1;o++){const n=s[o];if(!(n in r)||(r=r[n],r==null))return}const a=s[s.length-1];r[a]=i}initializeValues(e,t=void 0){const i=this.getFilterDef(e);if(!i)return;const s=this.state.getFilterValues(e),r=new Set((i.controls||[]).map(a=>a.id));if(i.defaultParams)for(const[a,o]of Object.entries(i.defaultParams))!r.has(a)&&!(a in s)&&this.state.setFilterValue(e,a,o,t);i.controls&&i.controls.forEach(a=>{a.id in s||this.state.setFilterValue(e,a.id,a.default,t)})}resetValues(e,t=void 0){const i=this.getFilterDef(e);if(!i)return;const s=new Set((i.controls||[]).map(r=>r.id));if(i.defaultParams)for(const[r,a]of Object.entries(i.defaultParams))s.has(r)||this.state.setFilterValue(e,r,a,t);i.controls&&i.controls.forEach(r=>{this.state.setFilterValue(e,r.id,r.default,t)})}toggle(e,t,i=void 0){return this.state.toggleFilter(e,t,i)===!1?!1:(t?this.initializeValues(e,i):delete this.instances[e],this.applyFilters(),this.emit("filterToggled",{filterId:e,enabled:t}),!0)}updateValue(e,t,i,s=void 0){const r=this._normalizeValue(i);if(!this._matchesExpectedFilterLayer(s))return!1;const a=this.getFilterDef(e),o=a==null?void 0:a.controls.find(p=>p.id===t),n=!o&&(t.includes("[")||t.includes("."));if(!n&&this.state.setFilterValue(e,t,r,s)===!1)return!1;const l=this.instances[e];if(!l)return!1;const c=(o==null?void 0:o.property)||t;if(typeof l.updateUIParam=="function"){if(l.updateUIParam(c,r),n&&typeof l.getSerializableParams=="function"){const p=l.getSerializableParams();for(const[u,g]of Object.entries(p))this.state.setFilterValue(e,u,g,s)}return!0}const d=this._getDeepProp(l,c);return typeof d=="function"?!1:l.uniforms&&c in l.uniforms?(l.uniforms[c]=r,!0):d!==void 0?(this._setDeepProp(l,c,r),!0):!1}performFilterAction(e,t,i=void 0){if(!this._matchesExpectedFilterLayer(i))return!1;const s=this.instances[e];if(!s||typeof s.updateUIParam!="function")return!1;if(s.updateUIParam(t,!0),typeof s.getSerializableParams=="function"){const r=s.getSerializableParams();for(const[a,o]of Object.entries(r))this.state.setFilterValue(e,a,o,i)}return this.applyFilters(),this.emit("filterActionPerformed",{filterId:e,action:t}),!0}_matchesExpectedFilterLayer(e){if(e===void 0||!this._layerDocument())return!0;if(e===null)return typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId()===null:this.state.get("activeLayerId")===null;const i=typeof e=="string"?e.trim():"";return i===""?!1:typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId()===i:this.state.get("activeLayerId")===i}_layerDocument(){var t,i;const e=(i=(t=this.state).getSerializableDocument)==null?void 0:i.call(t);return e&&e.version===2&&Array.isArray(e.layers)?e:null}_sourceDimensionsForLayer(e,t={}){var s,r,a,o,n,l,c,d,p;const i=(e==null?void 0:e.source)||((s=e==null?void 0:e.fill)==null?void 0:s.source)||null;return{width:Math.round(Number(t.sourceWidth||(i==null?void 0:i.originalWidth)||((a=(r=this.renderer)==null?void 0:r.originalTexture)==null?void 0:a.width)||((n=(o=this.renderer)==null?void 0:o.sprite)==null?void 0:n.width)||0)),height:Math.round(Number(t.sourceHeight||(i==null?void 0:i.originalHeight)||((c=(l=this.renderer)==null?void 0:l.originalTexture)==null?void 0:c.height)||((p=(d=this.renderer)==null?void 0:d.sprite)==null?void 0:p.height)||0))}}_paramsForFilterState(e,t,i){const s=t!=null&&t.values&&typeof t.values=="object"?t.values:{},r=e.defaultParams?{...e.defaultParams}:{};e.controls&&Array.isArray(e.controls)&&e.controls.forEach(o=>{const n=o.property||o.id;r[n]=s[o.id]??o.default});const a=new Set((e.controls||[]).map(o=>o.id));for(const[o,n]of Object.entries(s))a.has(o)||(r[o]=n);return r._sourceWidth=i.width,r._sourceHeight=i.height,r}createFiltersForLayer(e,t={}){if(!Array.isArray(e==null?void 0:e.filters)||e.filters.length===0)return[];const i=[],s=this.state.get("activeLayerId"),r=e.id===s&&t.forExport!==!0,a=this._sourceDimensionsForLayer(e,t);for(const o of e.filters)if(!(!o||o.enabled===!1||typeof o.id!="string"))try{const n=this.getFilterDef(o.id);if(!(n!=null&&n.createFilter)||typeof n.createFilter!="function")continue;const l=n.createFilter(this._paramsForFilterState(n,o,a));if(!l)continue;let c=l;t.forExport===!0&&typeof l.createExportFilter=="function"&&(c=l.createExportFilter({previewToNativeScale:t.previewToNativeScale||1})||l),i.push(c),r&&(this.instances[o.id]=l)}catch{}return i}applyFilters(){var a,o,n,l,c,d,p;const e=this._layerDocument();if(e){for(const g in this.instances)delete this.instances[g];(o=(a=this.renderer)==null?void 0:a.setLayerFilterFactory)==null||o.call(a,(g,m)=>this.createFiltersForLayer(g,m));const u=(l=(n=this.renderer)==null?void 0:n.applyLayerFilters)==null?void 0:l.call(n,e);this.emit("filtersApplied",{count:((c=this.state.get("activeFilters"))==null?void 0:c.size)??0,failed:[],scopedToLayer:!0}),u||(p=(d=this.renderer)==null?void 0:d.render)==null||p.call(d);return}const t=this.renderer.sprite;if(!t)return;for(const u in this.instances)delete this.instances[u];const i=[],s=[];this.state.get("activeFilters").forEach(u=>{try{const g=this.getFilterDef(u);if(!g||!g.createFilter||typeof g.createFilter!="function")return;const m=this.state.getFilterValues(u),f=g.defaultParams?{...g.defaultParams}:{};g.controls&&Array.isArray(g.controls)&&g.controls.forEach(F=>{const j=F.property||F.id;f[j]=m[F.id]??F.default});const v=new Set((g.controls||[]).map(F=>F.id));for(const[F,j]of Object.entries(m))v.has(F)||(f[F]=j);const k=this.renderer.sprite,L=this.renderer.originalTexture;f._sourceWidth=Math.round((L==null?void 0:L.width)||(k==null?void 0:k.width)||0),f._sourceHeight=Math.round((L==null?void 0:L.height)||(k==null?void 0:k.height)||0);const w=g.createFilter(f);w&&(i.push(w),this.instances[u]=w)}catch{s.push(u)}});try{t.filters=null,t.filters=i.length?i:null,this.renderer.render(),this.emit("filtersApplied",{count:i.length,failed:s})}catch(u){try{t.filters=null,this.renderer.render()}catch{}this.emit("filtersError",{error:u,failedFilters:s})}s.length>0}resetAll(e=void 0){for(const s in this.instances)delete this.instances[s];return this.state.resetFilters(e)===!1?!1:this._layerDocument()?(this.applyFilters(),this.emit("filtersReset"),!0):(this.renderer.sprite&&(this.renderer.sprite.filters=null),this.renderer.render(),this.emit("filtersReset"),!0)}getInstance(e){return this.instances[e]||null}}const W=class W extends U.EventEmitter{constructor(e,t){super(),this.state=e,this.renderer=t,this._overlayCanvas=null,this._isDragging=!1,this._dragStart=null,this._dragMode=null,this._startRect=null,this._hoverMode=null,this._lastAutoZoomCheck=0,this.HANDLE_SIZE=14,this.EDGE_HIT_PAD=10,this._onPointerDown=this._handlePointerDown.bind(this),this._onPointerMove=this._handlePointerMove.bind(this),this._onPointerUp=this._handlePointerUp.bind(this)}setOverlayCanvas(e){this._overlayCanvas=e}_getAspectRatio(e){if(!e||e==="free")return null;const t={"1:1":1,"4:3":4/3,"16:9":16/9,"3:2":3/2,"2:3":2/3};if(t[e]!==void 0)return t[e];const i=e.split(":");if(i.length===2){const s=parseFloat(i[0]),r=parseFloat(i[1]);if(Number.isFinite(s)&&Number.isFinite(r)&&r>0)return s/r}return null}_getEffectiveTargetAspect(){const e=this.state.get("crop.shape");if(e==="circle"||e==="square")return 1;const t=this.state.get("crop.aspect");return!t||t==="free"?null:this._getAspectRatio(t)}applyAspectRatio(){const e=this.state.get("crop.rect");if(!e)return;const t=this._getEffectiveTargetAspect();if(!t)return;const i=e.width/e.height;Math.abs(i-t)<.01||(i>t?e.width=e.height*t:e.height=e.width/t,this.state.set("crop.rect",e))}constrainCropRect(){const e=this.state.get("crop.rect");if(!e)return;const t=this.renderer.sprite,i=this.renderer.app;if(!t||!i)return;const s=this.state.get("crop.shape"),r={x:0,y:0,w:i.screen.width,h:i.screen.height};if(e.x=Math.max(r.x,Math.min(e.x,r.x+r.w-e.width)),e.y=Math.max(r.y,Math.min(e.y,r.y+r.h-e.height)),e.width=Math.min(e.width,r.w),e.height=Math.min(e.height,r.h),s!=="free"||this.state.get("crop.aspect")==="1:1"){const a=Math.min(e.width,e.height);e.width=a,e.height=a}this.state.set("crop.rect",e)}static calcAutoZoom(e,t,i,s,r,a,o){if(!e||!s||!r||!a)return null;const n=e.width>t,l=e.height>i;if(!n&&!l)return null;const c=W.AUTO_ZOOM_PADDING;let d=o;if(n){const p=e.width/(c*s*a);d=Math.min(d,p)}if(l){const p=e.height/(c*r*a);d=Math.min(d,p)}return d=Math.max(.1,d),d>=o-.01?null:d}_checkAutoZoom(){if(!this.state.get("autoZoomOnCropOverflow"))return;const e=Date.now();if(e-this._lastAutoZoomCheck<W.AUTO_ZOOM_THROTTLE_MS)return;this._lastAutoZoomCheck=e;const t=this.state.get("crop.rect"),i=this.renderer.sprite,s=this.renderer.originalTexture;if(!t||!i||!s)return;const r=W.calcAutoZoom(t,i.width,i.height,s.width,s.height,this.renderer.fitScale,this.renderer.zoom);r!==null&&this.renderer.setZoom(r,{keepCenter:!0})}drawOverlay(){const e=this._overlayCanvas;if(!e)return;const t=this.renderer.app;if(!t)return;const i=t.canvas,s=i.clientWidth,r=i.clientHeight,a=window.devicePixelRatio||1;(e.width!==Math.max(1,Math.floor(s*a))||e.height!==Math.max(1,Math.floor(r*a)))&&(e.width=Math.max(1,Math.floor(s*a)),e.height=Math.max(1,Math.floor(r*a)),e.style.width=s+"px",e.style.height=r+"px");const o=e.getContext("2d");if(!o)return;o.setTransform(a,0,0,a,0,0),o.clearRect(0,0,s,r),o.fillStyle="rgba(0, 0, 0, 0.5)",o.fillRect(0,0,s,r);const n=this.state.get("crop.rect");if(!n)return;const l=this.state.get("crop.shape");if(o.save(),l==="circle"){const f=n.x+n.width/2,v=n.y+n.height/2,k=Math.min(n.width,n.height)/2;o.beginPath(),o.arc(f,v,k,0,Math.PI*2),o.clip()}else o.beginPath(),o.rect(n.x,n.y,n.width,n.height),o.clip();o.clearRect(n.x,n.y,n.width,n.height),o.restore(),o.strokeStyle="#ffffff",o.lineWidth=2,o.setLineDash([5,5]),l==="circle"?(o.beginPath(),o.arc(n.x+n.width/2,n.y+n.height/2,Math.min(n.width,n.height)/2,0,Math.PI*2),o.stroke()):o.strokeRect(n.x,n.y,n.width,n.height),o.setLineDash([]),o.strokeStyle="rgba(255,255,255,0.3)",o.lineWidth=1;const c=n.width/3,d=n.height/3;for(let f=1;f<=2;f++)o.beginPath(),o.moveTo(n.x+c*f,n.y),o.lineTo(n.x+c*f,n.y+n.height),o.stroke(),o.beginPath(),o.moveTo(n.x,n.y+d*f),o.lineTo(n.x+n.width,n.y+d*f),o.stroke();const p=this.HANDLE_SIZE,u=[{x:n.x,y:n.y,m:"resize-nw"},{x:n.x+n.width,y:n.y,m:"resize-ne"},{x:n.x,y:n.y+n.height,m:"resize-sw"},{x:n.x+n.width,y:n.y+n.height,m:"resize-se"}],g=[{x:n.x+n.width/2,y:n.y,m:"n"},{x:n.x+n.width/2,y:n.y+n.height,m:"s"},{x:n.x,y:n.y+n.height/2,m:"w"},{x:n.x+n.width,y:n.y+n.height/2,m:"e"}],m=[...u,...g];for(const f of m){const v=this._hoverMode===f.m,k=v?p+4:p;o.beginPath(),o.rect(f.x-k/2,f.y-k/2,k,k),o.fillStyle=v?"#4da3ff":"#ffffff",o.strokeStyle="rgba(0,0,0,0.6)",o.lineWidth=1,o.fill(),o.stroke()}}_hitHandle(e,t){const i=this.state.get("crop.rect");if(!i)return null;const s=(r,a,o,n,l)=>Math.abs(r-o)<=l&&Math.abs(a-n)<=l;return s(e,t,i.x,i.y,this.HANDLE_SIZE)?"resize-nw":s(e,t,i.x+i.width,i.y,this.HANDLE_SIZE)?"resize-ne":s(e,t,i.x,i.y+i.height,this.HANDLE_SIZE)?"resize-sw":s(e,t,i.x+i.width,i.y+i.height,this.HANDLE_SIZE)?"resize-se":Math.abs(t-i.y)<=this.EDGE_HIT_PAD&&e>=i.x&&e<=i.x+i.width?"n":Math.abs(t-(i.y+i.height))<=this.EDGE_HIT_PAD&&e>=i.x&&e<=i.x+i.width?"s":Math.abs(e-i.x)<=this.EDGE_HIT_PAD&&t>=i.y&&t<=i.y+i.height?"w":Math.abs(e-(i.x+i.width))<=this.EDGE_HIT_PAD&&t>=i.y&&t<=i.y+i.height?"e":e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height?"move":null}_handlePointerDown(e){const t=this.state.get("crop.rect");if(!t)return;const i=e.global;this._dragMode=this._hitHandle(i.x,i.y),this._dragMode&&(this._isDragging=!0,this._dragStart={x:i.x,y:i.y},this._startRect={...t},this._lastAutoZoomCheck=0)}_handlePointerMove(e){var l,c,d,p;const t=this.renderer.app;if(!t)return;const i=e.global;if(!this._isDragging||!this._dragStart||!this._startRect){this._hoverMode=this._hitHandle(i.x,i.y),t.stage.cursor=this._hoverMode==="move"?"move":this._hoverMode==="n"||this._hoverMode==="s"?"ns-resize":this._hoverMode==="e"||this._hoverMode==="w"?"ew-resize":(l=this._hoverMode)!=null&&l.endsWith("nw")||(c=this._hoverMode)!=null&&c.endsWith("se")?"nwse-resize":(d=this._hoverMode)!=null&&d.endsWith("ne")||(p=this._hoverMode)!=null&&p.endsWith("sw")?"nesw-resize":"crosshair",this.drawOverlay();return}const s=this.state.get("crop.rect");if(!s)return;const r=i.x-this._dragStart.x,a=i.y-this._dragStart.y,o=this._getEffectiveTargetAspect();switch(this._dragMode){case"move":s.x=this._startRect.x+r,s.y=this._startRect.y+a;break;case"n":{const u=this._startRect.height-a;if(s.y=this._startRect.y+a,s.height=u,o){const g=u*o;s.x=this._startRect.x+(this._startRect.width-g)/2,s.width=g}break}case"s":{const u=this._startRect.height+a;if(s.height=u,o){const g=u*o;s.x=this._startRect.x+(this._startRect.width-g)/2,s.width=g}break}case"w":{const u=this._startRect.width-r;if(s.x=this._startRect.x+r,s.width=u,o){const g=u/o;s.y=this._startRect.y+(this._startRect.height-g)/2,s.height=g}break}case"e":{const u=this._startRect.width+r;if(s.width=u,o){const g=u/o;s.y=this._startRect.y+(this._startRect.height-g)/2,s.height=g}break}case"resize-nw":s.x=this._startRect.x+r,s.y=this._startRect.y+a,s.width=this._startRect.width-r,s.height=this._startRect.height-a;break;case"resize-ne":s.y=this._startRect.y+a,s.width=this._startRect.width+r,s.height=this._startRect.height-a;break;case"resize-sw":s.x=this._startRect.x+r,s.width=this._startRect.width-r,s.height=this._startRect.height+a;break;case"resize-se":s.width=this._startRect.width+r,s.height=this._startRect.height+a;break}s.width=Math.max(50,s.width),s.height=Math.max(50,s.height),this.state.set("crop.rect",s),this.state.set("crop.dirty",!0),this.state.get("crop.shape")==="circle"&&this.state.get("crop.aspect")!=="1:1"&&this.state.set("crop.aspect","1:1"),this.applyAspectRatio(),this._dragMode!=="move"&&this._checkAutoZoom(),this.constrainCropRect(),this.drawOverlay()}_handlePointerUp(){this._isDragging=!1,this._dragMode=null,this._dragStart=null,this._startRect=null}enable(){const e=this.renderer.app,t=this.renderer.sprite;if(!e||!t)return;let i=this.state.get("crop.rect");if(!i){this.state.get("crop.shape")==="circle"&&this.state.set("crop.aspect","1:1");const a=this.state.get("crop.aspect"),o=this._getAspectRatio(a);let n,l;if(o){const p=t.width*.9,u=t.height*.9;p/u>o?(l=u,n=l*o):(n=p,l=n/o)}else{const p=Math.min(e.screen.width,e.screen.height)*.7;n=p,l=p}const c=t.x+(t.width-n)/2,d=t.y+(t.height-l)/2;i={x:c,y:d,width:n,height:l},this.state.set("crop.rect",i),a!=="free"&&this.constrainCropRect()}this.state.set("crop.dirty",!1);const s=e.stage;s.eventMode="static",s.hitArea=e.screen,s.cursor="crosshair",s.on("pointerdown",this._onPointerDown),s.on("pointermove",this._onPointerMove),s.on("pointerup",this._onPointerUp),s.on("pointerupoutside",this._onPointerUp),this.state.set("mode","crop"),this.drawOverlay(),this.emit("enabled")}disable(){const e=this.renderer.app;if(!e)return;const t=e.stage;if(t.off("pointerdown",this._onPointerDown),t.off("pointermove",this._onPointerMove),t.off("pointerup",this._onPointerUp),t.off("pointerupoutside",this._onPointerUp),t.eventMode="auto",t.cursor="default",this.state.set("crop.rect",null),this.state.set("crop.dirty",!1),this._overlayCanvas){const i=this._overlayCanvas.getContext("2d");i==null||i.clearRect(0,0,this._overlayCanvas.width,this._overlayCanvas.height)}this.state.set("mode","filters"),this.emit("disabled")}apply(){const e=this.renderer.app,t=this.renderer.sprite,i=this.renderer.originalTexture,s=this.state.get("crop.rect");if(!s||!t||!e||!i)return null;const r=window.PIXI,a=this.renderer.zoom,o=i.width/t.width,n=i.height/t.height,l=(s.x-t.x)*o,c=(s.y-t.y)*n;let d=Math.round(Math.max(1,s.width*o)),p=Math.round(Math.max(1,s.height*n)),u=Math.round(l),g=Math.round(c);if(d<=0||p<=0)return null;const m=new r.Container,f=new r.Sprite(i);if(this.state.get("crop.shape")==="circle"){const M=Math.round(Math.max(d,p)),T=u+d/2,O=g+p/2;u=Math.round(T-M/2),g=Math.round(O-M/2),d=p=M;const R=new r.Graphics;typeof R.circle=="function"&&typeof R.fill=="function"?R.circle(d/2,p/2,d/2).fill(16777215):(R.beginFill(16777215,1),R.drawCircle(d/2,p/2,d/2),R.endFill()),f.mask=R,m.addChild(R)}f.x=-u,f.y=-g,m.addChild(f);const k=r.RenderTexture.create({width:d,height:p});e.renderer.render({container:m,target:k,clear:!0}),m.destroy({children:!0});const L=this.renderer.originalTexture;L&&L!==this.renderer.baseTexture&&L.destroy(!0),this.renderer.originalTexture=k,e.stage.removeChild(t),t.destroy();const w=new r.Sprite(k);e.stage.addChild(w),this.renderer.sprite=w,this.renderer.fitScale=this.renderer.getFitScaleFor(k),this.renderer.setZoom(a,{keepCenter:!1}),this.renderer.applyViewTransform(),this.renderer.render();const F=this.state.get("crop.appliedRect"),y=F&&Number.isFinite(F.x)&&Number.isFinite(F.y)&&Number.isFinite(F.width)&&Number.isFinite(F.height)?{x:Math.round(F.x+u),y:Math.round(F.y+g),width:d,height:p}:{x:u,y:g,width:d,height:p},x=this.state.get("crop.shape")||"free",E=this.state.get("crop.aspect")||"free";return this.disable(),this.state.set("crop.appliedRect",y),this.state.set("crop.appliedShape",x),this.state.set("crop.appliedAspect",E),this.state.set("crop.dirty",!1),this.emit("applied",{width:d,height:p}),{texture:k,preservedZoom:a}}applyFromPixelRect(e,t="free"){const i=this.renderer.app,s=this.renderer.sprite,r=this.renderer.originalTexture;if(!e||!s||!i||!r)return null;const a=window.PIXI,o=this.renderer.zoom;let n=Math.round(Math.max(1,e.width)),l=Math.round(Math.max(1,e.height)),c=Math.round(e.x),d=Math.round(e.y);if(n<=0||l<=0)return null;const p=new a.Container,u=new a.Sprite(r);if(t==="circle"){const v=Math.round(Math.max(n,l)),k=c+n/2,L=d+l/2;c=Math.round(k-v/2),d=Math.round(L-v/2),n=l=v;const w=new a.Graphics;typeof w.circle=="function"&&typeof w.fill=="function"?w.circle(n/2,l/2,n/2).fill(16777215):(w.beginFill(16777215,1),w.drawCircle(n/2,l/2,n/2),w.endFill()),u.mask=w,p.addChild(w)}u.x=-c,u.y=-d,p.addChild(u);const g=a.RenderTexture.create({width:n,height:l});i.renderer.render({container:p,target:g,clear:!0}),p.destroy({children:!0});const m=this.renderer.originalTexture;m&&m!==this.renderer.baseTexture&&m.destroy(!0),this.renderer.originalTexture=g,i.stage.removeChild(s),s.destroy();const f=new a.Sprite(g);return i.stage.addChild(f),this.renderer.sprite=f,this.renderer.fitScale=this.renderer.getFitScaleFor(g),this.renderer.setZoom(o,{keepCenter:!1}),this.renderer.applyViewTransform(),this.renderer.render(),{texture:g,preservedZoom:o}}cancel(){this.disable(),this.emit("cancelled")}setShape(e){this.state.get("lockCropShape")||(this.state.set("crop.shape",e),this.state.set("crop.dirty",!0),(e==="circle"||e==="square")&&this.state.set("crop.aspect","1:1"),this.applyAspectRatio(),this.constrainCropRect(),this.drawOverlay())}setAspect(e){if(this.state.get("lockAspectRatio"))return;if(this.state.get("crop.shape")!=="free"){if(this.state.get("lockCropShape"))return;this.state.set("crop.shape","free")}this.state.set("crop.aspect",e),this.state.set("crop.dirty",!0),this.applyAspectRatio(),this.constrainCropRect(),this.drawOverlay()}};me(W,"AUTO_ZOOM_PADDING",1.1),me(W,"AUTO_ZOOM_THROTTLE_MS",100);let ge=W;class ze{constructor(e={}){this._endpoint=e.endpoint||"/api/v1/media/background-removal/preview",this._optionsEndpoint=e.optionsEndpoint||"/api/v1/media/background-removal/options",this._savedEndpoint=e.savedEndpoint||"/api/v1/media/{media}/background-removal",this._fallbackEndpoint=e.fallbackEndpoint||null,this._activeControllers=new Set}_createAbortController(){if(typeof AbortController>"u")return null;const e=new AbortController;return this._activeControllers.add(e),e}_releaseAbortController(e){e&&this._activeControllers.delete(e)}cancelActiveRequests(e="cancelled"){const t=Array.from(this._activeControllers);this._activeControllers.clear();for(const i of t)i.signal.aborted||i.abort(e);return t.length}async preparePreviewRequest(e,t={}){const i=typeof e=="string"?await this._dataUrlToBlob(e):e;return{...t,blob:i,operationId:t.operationId||this._uuid(),sessionKey:t.sessionKey||this._uuid(),sourceHash:t.sourceHash||await this._sha256Hex(i),targetRef:t.targetRef||null,tier:t.tier||"balanced"}}async computeImageDataHash(e){const t=typeof e=="string"?await this._dataUrlToBlob(e):e;return this._sha256Hex(t)}async removeBackground(e,t={}){const i=typeof Blob<"u"&&t.blob instanceof Blob?t:await this.preparePreviewRequest(e,t),s=i.blob,r=i.operationId,a=i.sessionKey,o=i.sourceHash,n=new FormData;n.append("image_file",s,"image.png"),n.append("operation_id",r),n.append("session_key",a),n.append("source_hash",o),n.append("tier",i.tier||"balanced"),i.targetRef&&n.append("target_ref",i.targetRef),i.model&&n.append("model",i.model),i.alpha_matting&&(n.append("alpha_matting","true"),n.append("alpha_f",String(i.alpha_f??10)),n.append("alpha_fr",String(i.alpha_fr??15)),n.append("alpha_erode_size",String(i.alpha_erode_size??10))),i.max_megapixels!==void 0&&n.append("max_megapixels",String(i.max_megapixels));let l,c;const d=this._createAbortController(),p=u=>d?{...u,signal:d.signal}:u;try{try{l=await fetch(this._endpoint,p({method:"POST",body:n,credentials:"include"}))}catch(m){if(d!=null&&d.signal.aborted)throw m;c=m}if((!l||!l.ok)&&this._fallbackEndpoint)try{l=await fetch(this._fallbackEndpoint,p({method:"POST",body:n}))}catch(m){if(d!=null&&d.signal.aborted)throw m;c||(c=m)}if(!l)throw c||new Error("Network error: Unable to connect to background removal service");if(!l.ok){let m=`Background removal failed (HTTP ${l.status})`;try{const f=await l.text();f&&(m+=`: ${f}`)}catch{}throw new Error(m)}const u=await l.blob();return{dataUrl:await this._blobToDataUrl(u),model:l.headers.get("X-Model-Used")||"unknown",processMs:l.headers.get("X-Process-Ms")||"0",operationId:l.headers.get("X-Operation-Id")||r,sessionKey:l.headers.get("X-Session-Key")||a,sourceHash:l.headers.get("X-Source-Hash")||o,targetRef:l.headers.get("X-Target-Ref")||i.targetRef||null}}finally{this._releaseAbortController(d)}}async removeSavedMediaBackground(e){const t=this._savedEndpoint.replace("{media}",encodeURIComponent(e.targetMediaUuid)),i={operation_id:e.operationId,document_id:e.documentId,document_revision_id:e.documentRevisionId,target_layer_id:e.targetLayerId,expected_source_hash:e.expectedSourceHash,tier:e.tier||"balanced"};e.model&&(i.model=e.model),e.alpha_matting!==void 0&&(i.alpha_matting=!!e.alpha_matting),e.max_megapixels!==void 0&&(i.max_megapixels=Number(e.max_megapixels));const s=this._createAbortController();let r;try{if(r=await fetch(t,{method:"POST",body:JSON.stringify(i),credentials:"include",headers:{Accept:"application/json","Content-Type":"application/json"},...s?{signal:s.signal}:{}}),!r.ok){let a=`Background removal failed (HTTP ${r.status})`;try{const o=await r.json();o!=null&&o.message&&(a+=`: ${o.message}`)}catch{}throw new Error(a)}return await r.json()}finally{this._releaseAbortController(s)}}async _dataUrlToBlob(e){if(e.startsWith("data:")){const[i,s]=e.split(","),r=i.match(/:(.*?);/),a=r?r[1]:"image/png",o=atob(s),n=new Uint8Array(o.length);for(let l=0;l<o.length;l++)n[l]=o.charCodeAt(l);return new Blob([n],{type:a})}return(await fetch(e)).blob()}_blobToDataUrl(e){return new Promise((t,i)=>{const s=new FileReader;s.onload=()=>t(s.result),s.onerror=()=>i(new Error("Failed to read blob as data URL")),s.readAsDataURL(e)})}async isAvailable(){var t;const e=await this.getOptions();return e.enabled===!0&&((t=e.service)==null?void 0:t.available)===!0}async getOptions(){try{const e=await fetch(this._optionsEndpoint,{method:"GET",credentials:"include"});if(!e.ok)return{enabled:!1,service:{available:!1}};const t=await e.json();return t&&typeof t=="object"?t:{enabled:!1,service:{available:!1}}}catch{if(this._fallbackEndpoint)try{const t=await fetch(this._fallbackEndpoint,{method:"OPTIONS"});return{enabled:t.ok,service:{available:t.ok}}}catch{}return{enabled:!1,service:{available:!1}}}}_uuid(){var e;return(e=globalThis.crypto)!=null&&e.randomUUID?globalThis.crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const i=Math.floor(Math.random()*16);return(t==="x"?i:i&3|8).toString(16)})}async _sha256Hex(e){const t=await e.arrayBuffer(),i=await globalThis.crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(i)].map(s=>s.toString(16).padStart(2,"0")).join("")}}function h(_,e={},...t){const i=document.createElement(_);for(const[s,r]of Object.entries(e))if(r!=null)if(s==="className")i.className=r;else if(s==="style"&&typeof r=="object")Object.assign(i.style,r);else if(s.startsWith("on")&&typeof r=="function"){const a=s.slice(2).toLowerCase();i.addEventListener(a,r)}else s==="dataset"&&typeof r=="object"?Object.assign(i.dataset,r):i.setAttribute(s,r);for(const s of t)typeof s=="string"?i.appendChild(document.createTextNode(s)):s instanceof HTMLElement&&i.appendChild(s);return i}function we({id:_,label:e,min:t=0,max:i=1,step:s=.01,value:r=.5,onChange:a}){const o=_.includes("-")?_.split("-").slice(1).join("-"):_,n=h("div",{className:"slider-control slider-wrapper","data-control":o,"data-testid":`slider-${o}`}),l=h("div",{className:"slider-header"},h("label",{for:_,className:"slider-label"},e),h("span",{className:"slider-value",id:`${_}-value`},be(r))),c=h("input",{type:"range",id:_,className:"slider-input",min:String(t),max:String(i),step:String(s),value:String(r),onInput:d=>{const p=parseFloat(d.target.value),u=n.querySelector(".slider-value");u&&(u.textContent=be(p)),a==null||a(p)}});return n.appendChild(l),n.appendChild(c),n.setValue=d=>{c.value=String(d);const p=n.querySelector(".slider-value");p&&(p.textContent=be(d))},n}function be(_){return Number.isInteger(_)?String(_):_.toFixed(2)}function Ce({id:_,label:e,checked:t=!1,onChange:i}){const s=h("div",{className:"toggle-control"}),r=h("label",{className:"toggle-label",for:_},e),a=h("input",{type:"checkbox",id:_,className:"toggle-input",checked:t?"checked":void 0,onChange:l=>i==null?void 0:i(l.target.checked)}),o=h("div",{className:"toggle-switch",onClick:l=>{l.target!==a&&(a.checked=!a.checked,i==null||i(a.checked))}}),n=h("span",{className:"toggle-slider"});return o.appendChild(a),o.appendChild(n),s.appendChild(r),s.appendChild(o),s.setChecked=l=>{a.checked=l},s}function ke({id:_,label:e,value:t="#000000",onChange:i}){const s=h("div",{className:"color-control"}),r=h("label",{className:"color-label",for:_},e),a=h("input",{type:"color",id:_,className:"color-input",value:t,onInput:o=>i==null?void 0:i(o.target.value)});return s.appendChild(r),s.appendChild(a),s.setValue=o=>{a.value=o},s}function xe({id:_,label:e,value:t="",placeholder:i="",onCommit:s}){const r=h("div",{className:"text-control","data-control":_,"data-testid":`text-${_}`}),a=h("label",{className:"text-label",for:_},e);let o=t;const n=h("input",{type:"text",id:_,className:"text-input",value:t,placeholder:i,onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),l(),n.blur())},onBlur:()=>l()});function l(){const c=n.value;c!==o&&(o=c,s==null||s(c))}return r.appendChild(a),r.appendChild(n),r.setValue=c=>{const d=c==null?"":String(c);n.value=d,o=d},r}function Se({id:_,label:e,options:t=[],value:i,onChange:s}){const r=h("div",{className:"select-control"}),a=h("label",{className:"select-label",for:_},e),o=h("select",{id:_,className:"select-input",onChange:n=>s==null?void 0:s(n.target.value)});for(const n of t){const l=h("option",{value:n.value},n.label);n.value===i&&(l.selected=!0),o.appendChild(l)}return r.appendChild(a),r.appendChild(o),r.setValue=n=>{o.value=n},r}function B({label:_,className:e="",onClick:t,icon:i=null,disabled:s=!1}){const r=h("button",{type:"button",className:`btn ${e}`.trim(),onClick:t,disabled:s?"disabled":void 0});if(i){const a=h("span",{className:"btn-icon"});a.innerHTML=i;const o=a.querySelector("svg");o&&o.setAttribute("aria-hidden","true"),r.appendChild(a)}return _&&r.appendChild(document.createTextNode(_)),r}function N({icon:_,title:e,className:t="",onClick:i,disabled:s=!1,testId:r=null,ariaLabel:a=null}){const o={type:"button",className:`icon-btn ${t}`.trim(),title:e,"aria-label":a||e,onClick:i,disabled:s?"disabled":void 0};r&&(o.dataset={testid:r});const n=h("button",o);n.innerHTML=_;const l=n.querySelector("svg");return l&&l.setAttribute("aria-hidden","true"),n}function pe({label:_,icon:e,active:t=!1,onClick:i}){const s=h("button",{type:"button",className:`chip ${t?"active":""}`.trim(),onClick:i});if(e){const r=h("span",{className:"chip-icon"});r.innerHTML=e;const a=r.querySelector("svg");a&&a.setAttribute("aria-hidden","true"),s.appendChild(r)}return s.appendChild(h("span",{className:"chip-label"},_)),s.setActive=r=>{s.classList.toggle("active",r)},s}class Oe{constructor(e,t){this.state=e,this.editor=t,this.element=null,this._removeBgBtn=null,this._removeBgTierSelect=null,this._removeBgStatus=null,this._removeBgTier="balanced",this._unsubscribers=[]}render(){this.element=h("div",{className:"editor-toolbar"});const e=h("div",{className:"toolbar-section toolbar-left"}),t=N({icon:ot,title:"Open Image",className:"toolbar-btn",testId:"btn-open-image",ariaLabel:"Open image file",onClick:()=>this.editor.openFilePicker()});e.appendChild(t);const i=h("div",{className:"toolbar-section toolbar-right"});this._themeBtn=N({icon:this.state.get("isDarkMode")?Me:Fe,title:"Toggle Theme",className:"toolbar-btn toolbar-btn-theme",testId:"btn-toggle-theme",ariaLabel:"Toggle theme",onClick:()=>this.editor.toggleTheme()}),this._cropBtn=N({icon:Ae,title:"Crop",className:"toolbar-btn toolbar-btn-crop",testId:"btn-crop",ariaLabel:"Crop image",onClick:()=>{this.state.get("mode")==="crop"?this.editor.setMode("filters"):this.editor.setMode("crop")}});const s=h("div",{className:"remove-bg-control"});this._removeBgTierSelect=h("select",{className:"remove-bg-tier-select",title:"Background removal quality","aria-label":"Background removal quality",dataset:{testid:"select-remove-background-tier"},onChange:c=>{this._removeBgTier=c.target.value}});for(const c of[["fast","Fast"],["balanced","Balanced"],["best","Best"]]){const d=h("option",{value:c[0]},c[1]);c[0]===this._removeBgTier&&(d.selected=!0),this._removeBgTierSelect.appendChild(d)}this._removeBgBtn=N({icon:vt,title:"Remove Background",className:"toolbar-btn toolbar-btn-remove-bg",testId:"btn-remove-background",ariaLabel:"Remove background",disabled:!this._canRemoveBackground(),onClick:async()=>{if(this._canRemoveBackground()){this._setRemoveBgStatus("Removing background...");try{await this.editor.removeBackground({tier:this._removeBgTier}),this._setRemoveBgStatus("Background removed")}catch{this._setRemoveBgStatus("Background removal failed")}finally{this._updateRemoveBgButton()}}}}),this._removeBgStatus=h("span",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true"}),s.appendChild(this._removeBgTierSelect),s.appendChild(this._removeBgBtn),s.appendChild(this._removeBgStatus);const r=N({icon:Be,title:"Reset All",className:"toolbar-btn",testId:"btn-reset-all",ariaLabel:"Reset all changes",onClick:()=>this.editor.resetAll()}),a=h("button",{type:"button",className:"icon-btn toolbar-btn toolbar-btn-primary toolbar-save-labeled",title:"Save Image","aria-label":"Save image",dataset:{testid:"btn-save-edit"},onClick:()=>this.editor.save()}),o=h("span",{className:"btn-icon"});o.innerHTML=Te;const n=o.querySelector("svg");n&&n.setAttribute("aria-hidden","true"),a.appendChild(o),a.appendChild(h("span",{className:"toolbar-save-label"},"Save"));const l=N({icon:se,title:"Close",className:"toolbar-btn",testId:"btn-cancel-edit",ariaLabel:"Close editor",onClick:()=>this.editor.close()});return i.appendChild(this._themeBtn),i.appendChild(this._cropBtn),i.appendChild(s),i.appendChild(r),i.appendChild(a),i.appendChild(l),this.element.appendChild(e),this.element.appendChild(i),this._subscribeToState(),this.element}_subscribeToState(){const e=this.state.on("change:isDarkMode",({value:l})=>{this._themeBtn.innerHTML=l?Me:Fe});this._unsubscribers.push(e);const t=this.state.on("change:mode",({value:l})=>{this._cropBtn&&this._cropBtn.classList.toggle("toolbar-btn-primary",l==="crop")});this._unsubscribers.push(t);const i=this.state.on("change:hasImage",()=>this._updateRemoveBgButton());this._unsubscribers.push(i);const s=this.state.on("change:isProcessing",()=>this._updateRemoveBgButton());this._unsubscribers.push(s);const r=this.state.on("change:backgroundRemovalAvailable",()=>this._updateRemoveBgButton());this._unsubscribers.push(r);const a=this.state.on("change:editorDocument",()=>this._updateRemoveBgButton());this._unsubscribers.push(a);const o=this.state.on("change:layers",()=>this._updateRemoveBgButton());this._unsubscribers.push(o);const n=this.state.on("change:activeLayerId",()=>this._updateRemoveBgButton());this._unsubscribers.push(n)}_canRemoveBackground(){return typeof this.editor.canRemoveBackground=="function"?this.editor.canRemoveBackground():!!this.state.get("hasImage")&&typeof this.editor.removeBackground=="function"}_updateRemoveBgButton(){if(!this._removeBgBtn)return;const e=this.state.get("isProcessing")===!0,t=!this._canRemoveBackground()||e;this._removeBgBtn.disabled=t,this._removeBgBtn.setAttribute("aria-disabled",t?"true":"false"),this._removeBgBtn.setAttribute("aria-busy",e?"true":"false"),this._removeBgTierSelect&&(this._removeBgTierSelect.disabled=t,this._removeBgTierSelect.setAttribute("aria-disabled",t?"true":"false"))}_setRemoveBgStatus(e){this._removeBgStatus&&(this._removeBgStatus.textContent=e)}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(e=this.element)==null||e.remove(),this.element=null}}const ce=re;class Ct{constructor(e,t){this.state=e,this.editor=t,this.element=null,this._chips=new Map,this._scrollIndex=0,this._unsubscribers=[]}render(e){this._onSelect=e,this.element=h("div",{className:"category-carousel-container","data-testid":"category-carousel"}),this._leftBtn=N({icon:te,title:"Previous categories",className:"carousel-nav carousel-nav-left",onClick:()=>this._scrollLeft()}),this._carousel=h("div",{className:"category-carousel"}),ce.forEach(i=>{const s=pe({label:i.name,icon:i.icon,active:this.state.get("selectedCategory")===i.id,onClick:()=>this._selectCategory(i.id)});s.dataset.categoryId=i.id,s.dataset.category=i.id,s.dataset.testid=`category-${i.id}`,this._chips.set(i.id,s),this._carousel.appendChild(s)}),this._rightBtn=N({icon:ie,title:"Next categories",className:"carousel-nav carousel-nav-right",onClick:()=>this._scrollRight()}),this._pagination=h("div",{className:"carousel-pagination",role:"tablist","aria-label":"Category pages"});const t=Math.ceil(ce.length/3);for(let i=0;i<t;i++){const s=h("button",{type:"button",className:`pagination-dot ${i===0?"active":""}`,role:"tab","aria-label":`Page ${i+1} of ${t}`,"aria-selected":i===0?"true":"false",onClick:()=>this._scrollToPage(i)});this._pagination.appendChild(s)}return this.element.appendChild(this._leftBtn),this.element.appendChild(this._carousel),this.element.appendChild(this._rightBtn),this.element.appendChild(this._pagination),this._subscribeToState(),this._updateNavButtons(),this.element}_subscribeToState(){const e=this.state.on("change:selectedCategory",({value:t})=>{this._chips.forEach((i,s)=>{i.setActive(s===t)})});this._unsubscribers.push(e)}_selectCategory(e){var s;this.state.set("selectedCategory",e);const t=this.state.get("mode");e==="crop"?t!=="crop"&&this.editor.setMode("crop"):t!=="filters"&&this.editor.setMode("filters");const i=this._chips.get(e);i&&this._carousel&&i.scrollIntoView({behavior:"smooth",inline:"center",block:"nearest"}),(s=this._onSelect)==null||s.call(this,e)}_scrollLeft(){this._scrollIndex>0&&(this._scrollIndex--,this._scrollCarousel())}_scrollRight(){this._scrollIndex<ce.length-3&&(this._scrollIndex++,this._scrollCarousel())}_scrollToPage(e){this._scrollIndex=e*3,this._scrollCarousel()}_scrollCarousel(){if(this._carousel){const e=this._carousel.querySelector(".chip"),t=(e==null?void 0:e.clientWidth)||100;this._carousel.scrollTo({left:this._scrollIndex*(t+8),behavior:"smooth"})}this._updateNavButtons(),this._updatePagination()}_updateNavButtons(){this._leftBtn&&(this._leftBtn.disabled=this._scrollIndex===0),this._rightBtn&&(this._rightBtn.disabled=this._scrollIndex>=ce.length-3)}_updatePagination(){if(this._pagination){const e=this._pagination.querySelectorAll(".pagination-dot"),t=Math.floor(this._scrollIndex/3);e.forEach((i,s)=>{const r=s===t;i.classList.toggle("active",r),i.setAttribute("aria-selected",r?"true":"false")})}}setSelected(e){this._selectCategory(e)}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._chips.clear(),(e=this.element)==null||e.remove(),this.element=null}}class kt{constructor(e,t){this.state=e,this.filterManager=t,this.element=null,this._filterCards=new Map,this._scrollIndex=0,this._unsubscribers=[],this._onToggle=null,this._onSelect=null}render({onToggle:e,onSelect:t}){return this._onToggle=e,this._onSelect=t,this.element=h("div",{className:"filter-carousel-container"}),this._leftBtn=N({icon:te,title:"Previous filters",className:"carousel-nav carousel-nav-left",onClick:()=>this._scrollLeft()}),this._carousel=h("div",{className:"filter-carousel"}),this._rightBtn=N({icon:ie,title:"Next filters",className:"carousel-nav carousel-nav-right",onClick:()=>this._scrollRight()}),this.element.appendChild(this._leftBtn),this.element.appendChild(this._carousel),this.element.appendChild(this._rightBtn),this._subscribeToState(),this._renderFilters(),this.element}_subscribeToState(){const e=this.state.on("change:selectedCategory",()=>{this._renderFilters()});this._unsubscribers.push(e);const t=this.state.on("change:activeFilters",()=>{this._updateActiveStates()});this._unsubscribers.push(t);const i=this.state.on("change:selectedFilter",()=>{this._updateSelectedState()});this._unsubscribers.push(i)}_renderFilters(){this._carousel.innerHTML="",this._filterCards.clear(),this._scrollIndex=0;const e=this.state.get("selectedCategory");if(e==="crop")return;const t=this.filterManager.getFiltersByCategory(e),i=this.state.get("activeFilters"),s=this.state.get("selectedFilter");t.forEach(r=>{const a=this._createFilterCard(r,{isActive:i.has(r.id),isSelected:s===r.id});this._filterCards.set(r.id,a),this._carousel.appendChild(a)}),this._updateNavButtons()}_createFilterCard(e,{isActive:t,isSelected:i}){const s=h("div",{className:`filter-card ${t?"active":""} ${i?"selected":""}`,"data-filter":e.id,"data-testid":`filter-${e.id}`,onClick:()=>this._handleCardClick(e.id)}),r=h("div",{className:"filter-preview"}),a=h("span",{className:"filter-preview-text"},e.name.charAt(0));r.appendChild(a);const o=h("span",{className:"filter-name",title:e.name},e.name),n=h("button",{className:`filter-toggle ${t?"active":""}`,onClick:l=>{var p;l.stopPropagation();const d=!this.state.get("activeFilters").has(e.id);this._handleToggle(e.id,d),d&&(this.state.set("selectedFilter",e.id),(p=this._onSelect)==null||p.call(this,e.id))}});return n.innerHTML=t?_e:"",s.appendChild(r),s.appendChild(o),s.appendChild(n),s._toggle=n,s._isActive=t,s}_handleCardClick(e){var i;this.state.get("activeFilters").has(e)||this._handleToggle(e,!0),this.state.set("selectedFilter",e),(i=this._onSelect)==null||i.call(this,e)}_handleToggle(e,t){var i;(i=this._onToggle)==null||i.call(this,e,t)}_updateActiveStates(){const e=this.state.get("activeFilters");this._filterCards.forEach((t,i)=>{const s=e.has(i);t.classList.toggle("active",s),t._toggle.classList.toggle("active",s),t._toggle.innerHTML=s?_e:"",t._isActive=s})}_updateSelectedState(){const e=this.state.get("selectedFilter");this._filterCards.forEach((t,i)=>{t.classList.toggle("selected",i===e)})}_scrollLeft(){this._scrollIndex>0&&(this._scrollIndex--,this._scrollCarousel())}_scrollRight(){const e=Math.max(0,this._filterCards.size-3);this._scrollIndex<e&&(this._scrollIndex++,this._scrollCarousel())}_scrollCarousel(){if(this._carousel){const e=this._carousel.querySelector(".filter-card"),t=(e==null?void 0:e.clientWidth)||120;this._carousel.scrollTo({left:this._scrollIndex*(t+8),behavior:"smooth"})}this._updateNavButtons()}_updateNavButtons(){const e=Math.max(0,this._filterCards.size-3);this._leftBtn&&(this._leftBtn.disabled=this._scrollIndex===0),this._rightBtn&&(this._rightBtn.disabled=this._scrollIndex>=e)}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._filterCards.clear(),(e=this.element)==null||e.remove(),this.element=null}}class xt{constructor(e,t){this.state=e,this.filterManager=t,this.element=null,this._controls=new Map,this._onChange=null,this._onReset=null,this._onAction=null,this._unsubscribers=[]}render({onChange:e,onReset:t,onAction:i}){return this._onChange=e,this._onReset=t,this._onAction=i,this.element=h("div",{className:"filter-adjustments"}),this._subscribeToState(),this._renderControls(),this.element}_subscribeToState(){const e=this.state.on("change:selectedFilter",()=>{this._renderControls()});this._unsubscribers.push(e);const t=this.state.on("change:filterValues",()=>{this._updateValues()});this._unsubscribers.push(t)}_renderControls(){this.element.innerHTML="",this._controls.clear();const e=this.state.get("selectedFilter");if(!e){this.element.appendChild(h("div",{className:"no-filter-selected"},"Select a filter to adjust"));return}const t=this.filterManager.getFilterDef(e);if(!t){this.element.appendChild(h("div",{className:"no-filter-selected"},"Filter not found"));return}const i=h("div",{className:"adjustments-header"});i.appendChild(h("span",{className:"adjustments-title"},t.name)),i.appendChild(B({label:"Reset",className:"btn-text",onClick:()=>this._handleReset(e)})),this.element.appendChild(i);const s=h("div",{className:"adjustments-grid"}),r=this.state.getFilterValues(e);(t.controls||[]).forEach(o=>{const n=r[o.id]??o.default,l=this._createControl(e,o,n);l&&(this._controls.set(o.id,l),s.appendChild(l))});const a=this.filterManager.getInstance(e);if(a&&typeof a.getDynamicControls=="function"){let o=[];try{o=a.getDynamicControls()||[]}catch{}o.forEach(n=>{const l=n.property||n.id,c=r[l]??n.default,d=this._createControl(e,n,c);d&&(this._controls.set(n.id,d),s.appendChild(d))})}this.element.appendChild(s)}_createControl(e,t,i){if(t.hidden)return null;const s=t.label||t.id,r=this._normalizeControlType(t.type),a=t.property||t.id;switch(r){case"slider":return we({id:`${e}-${t.id}`,label:s,min:t.min??0,max:t.max??1,step:t.step??.01,value:typeof i=="number"?i:t.default??0,onChange:l=>this._handleChange(e,a,l)});case"toggle":return Ce({id:`${e}-${t.id}`,label:s,checked:!!i,onChange:l=>this._handleChange(e,a,l)});case"color":return ke({id:`${e}-${t.id}`,label:s,value:typeof i=="string"&&i.startsWith("#")?i:t.default||"#000000",onChange:l=>this._handleChange(e,a,l)});case"select":const o=this._normalizeOptions(t.options);return Se({id:`${e}-${t.id}`,label:s,options:o,value:i??t.default,onChange:l=>this._handleChange(e,a,l)});case"text":return xe({id:`${e}-${t.id}`,label:s,value:typeof i=="string"?i:t.default??"",placeholder:t.placeholder||"",onCommit:l=>this._handleChange(e,a,l)});case"button":const n=h("div",{className:"button-control"});return n.appendChild(B({label:s,className:"btn-secondary",onClick:()=>this._handleAction(e,t.action||t.id)})),n;default:return null}}_normalizeControlType(e){return{slider:"slider",range:"slider",toggle:"toggle",checkbox:"toggle",color:"color",select:"select",dropdown:"select",button:"button",text:"text"}[e]||e}_normalizeOptions(e){return!e||!Array.isArray(e)?[]:e.map(t=>typeof t=="object"&&t.value!==void 0?{value:t.value,label:t.label||String(t.value)}:typeof t=="string"?{value:t,label:t}:typeof t=="number"?{value:t,label:String(t)}:{value:t,label:String(t)})}_handleChange(e,t,i){var s;(s=this._onChange)==null||s.call(this,e,t,i)}_handleReset(e){var t;(t=this._onReset)==null||t.call(this,e),this._renderControls()}_handleAction(e,t){var i;(i=this._onAction)==null||i.call(this,e,t),this._renderControls()}_updateValues(){const e=this.state.get("selectedFilter");if(!e)return;const t=this.state.getFilterValues(e),i=this.filterManager.getFilterDef(e);i&&i.controls.forEach(s=>{const r=this._controls.get(s.id);if(r&&typeof r.setValue=="function"){const a=t[s.id]??s.default;r.setValue(a)}})}show(){this.element&&(this.element.style.display="")}hide(){this.element&&(this.element.style.display="none")}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._controls.clear(),(e=this.element)==null||e.remove(),this.element=null}}class St{constructor(e,t){this.state=e,this.filterManager=t,this._drawer=null,this._body=null,this._titleEl=null,this._isOpen=!1,this._currentFilterId=null,this._controls=new Map,this._onChange=null,this._onReset=null,this._onRemove=null,this._onAction=null,this._container=null}build(e,{onChange:t,onReset:i,onRemove:s,onAction:r}){this._onChange=t,this._onReset=i,this._onRemove=s,this._onAction=r,this._container=e,this._drawer=h("div",{className:"mobile-filter-drawer"});const a=h("div",{className:"drawer-header"});this._titleEl=h("span",{className:"drawer-title"},"Filter");const o=h("div",{className:"drawer-header-actions"}),n=B({label:"Reset",className:"btn-text",onClick:()=>{var d;this._currentFilterId&&((d=this._onReset)==null||d.call(this,this._currentFilterId),this._renderControls())}}),l=B({label:"Remove",className:"btn-text btn-danger",onClick:()=>{var d;this._currentFilterId&&((d=this._onRemove)==null||d.call(this,this._currentFilterId),this.close())}}),c=N({icon:se,title:"Close",className:"btn-icon-sm",ariaLabel:"Close drawer",onClick:()=>this.close()});o.appendChild(n),o.appendChild(l),o.appendChild(c),a.appendChild(this._titleEl),a.appendChild(o),this._drawer.appendChild(a),this._body=h("div",{className:"drawer-body"}),this._drawer.appendChild(this._body),e.appendChild(this._drawer)}open(e){this._isOpen&&this._currentFilterId===e||(this._currentFilterId=e,this._renderControls(),this._isOpen||(this._isOpen=!0,this._sizeToContainer(),this._animateOpen()))}close(){this._isOpen&&(this._isOpen=!1,this._animateClose(),this._currentFilterId=null)}get isOpen(){return this._isOpen}_sizeToContainer(){if(!this._container||!this._drawer)return;const e=this._container.offsetHeight;e>0&&(this._drawer.style.height=e+"px")}_animateOpen(){this._drawer.style.transition="none",this._drawer.style.transform="translateY(100%)",this._drawer.offsetHeight,this._drawer.style.transition="transform 0.25s cubic-bezier(0.33, 1, 0.68, 1)",this._drawer.style.transform="translateY(0)"}_animateClose(){this._drawer.style.transition="transform 0.2s cubic-bezier(0.32, 0, 0.67, 0)",this._drawer.style.transform="translateY(100%)"}_renderControls(){if(this._body.innerHTML="",this._controls.clear(),!this._currentFilterId)return;const e=this.filterManager.getFilterDef(this._currentFilterId);if(!e)return;this._titleEl.textContent=e.name;const t=h("div",{className:"adjustments-grid"}),i=this.state.getFilterValues(this._currentFilterId);(e.controls||[]).forEach(r=>{if(r.hidden)return;const a=this._createControl(this._currentFilterId,r,i[r.id]??r.default);a&&(this._controls.set(r.id,a),t.appendChild(a))});const s=this.filterManager.getInstance(this._currentFilterId);if(s&&typeof s.getDynamicControls=="function"){let r=[];try{r=s.getDynamicControls()||[]}catch{}r.forEach(a=>{const o=a.property||a.id,n=i[o]??a.default,l=this._createControl(this._currentFilterId,a,n);l&&(this._controls.set(a.id,l),t.appendChild(l))})}this._body.appendChild(t)}_createControl(e,t,i){if(t.hidden)return null;const s=t.label||t.id,r=this._normalizeControlType(t.type),a=t.property||t.id;switch(r){case"slider":return we({id:`drawer-${e}-${t.id}`,label:s,min:t.min??0,max:t.max??1,step:t.step??.01,value:typeof i=="number"?i:t.default??0,onChange:o=>{var n;return(n=this._onChange)==null?void 0:n.call(this,e,a,o)}});case"toggle":return Ce({id:`drawer-${e}-${t.id}`,label:s,checked:!!i,onChange:o=>{var n;return(n=this._onChange)==null?void 0:n.call(this,e,a,o)}});case"color":return ke({id:`drawer-${e}-${t.id}`,label:s,value:typeof i=="string"&&i.startsWith("#")?i:t.default||"#000000",onChange:o=>{var n;return(n=this._onChange)==null?void 0:n.call(this,e,a,o)}});case"select":{const o=this._normalizeOptions(t.options);return Se({id:`drawer-${e}-${t.id}`,label:s,options:o,value:i??t.default,onChange:n=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,a,n)}})}case"text":return xe({id:`drawer-${e}-${t.id}`,label:s,value:typeof i=="string"?i:t.default??"",placeholder:t.placeholder||"",onCommit:o=>{var n;return(n=this._onChange)==null?void 0:n.call(this,e,a,o)}});case"button":{const o=h("div",{className:"button-control"});return o.appendChild(B({label:s,className:"btn-secondary",onClick:()=>{var n;(n=this._onAction)==null||n.call(this,e,t.action||t.id),this._renderControls()}})),o}default:return null}}_normalizeControlType(e){return{slider:"slider",range:"slider",toggle:"toggle",checkbox:"toggle",color:"color",select:"select",dropdown:"select",button:"button",text:"text"}[e]||e}_normalizeOptions(e){return!e||!Array.isArray(e)?[]:e.map(t=>typeof t=="object"&&t.value!==void 0?{value:t.value,label:t.label||String(t.value)}:typeof t=="string"?{value:t,label:t}:typeof t=="number"?{value:t,label:String(t)}:{value:t,label:String(t)})}destroy(){var e;this._controls.clear(),(e=this._drawer)==null||e.remove(),this._drawer=null,this._isOpen=!1,this._currentFilterId=null,this._container=null}}class Mt{constructor(e,t){this.state=e,this.filterManager=t,this.element=null,this._scrollContainer=null,this._chips=new Map,this._unsubscribers=[],this._onToggle=null,this._onSelect=null}render({onToggle:e,onSelect:t}){return this._onToggle=e,this._onSelect=t,this.element=h("div",{className:"mobile-active-filters","data-testid":"mobile-active-filters"}),this._scrollContainer=h("div",{className:"mobile-active-filters-scroll"}),this.element.appendChild(this._scrollContainer),this._subscribeToState(),this._renderChips(),this.element}_subscribeToState(){const e=this.state.on("change:activeFilters",()=>{this._renderChips()});this._unsubscribers.push(e);const t=this.state.on("change:selectedFilter",()=>{this._updateSelectedState()});this._unsubscribers.push(t)}_renderChips(){this._scrollContainer.innerHTML="",this._chips.clear();const e=this.state.get("activeFilters");if(!e||e.size===0){const t=h("div",{className:"active-filter-placeholder"},"No active filters");this._scrollContainer.appendChild(t);return}e.forEach(t=>{const i=this.filterManager.getFilterDef(t);if(!i)return;const s=this._createChip(t,i);this._chips.set(t,s),this._scrollContainer.appendChild(s)}),this._updateSelectedState()}_createChip(e,t){const i=h("div",{className:"active-filter-chip","data-filter-id":e,"data-testid":`active-chip-${e}`}),s=h("span",{className:"active-filter-chip-label",onClick:a=>{var o;a.stopPropagation(),(o=this._onSelect)==null||o.call(this,e)}},t.name),r=h("button",{className:"active-filter-chip-check","aria-label":`Remove ${t.name} filter`,onClick:a=>{var o;a.stopPropagation(),(o=this._onToggle)==null||o.call(this,e,!1)}});return r.innerHTML='<svg width="10" height="10" viewBox="0 0 12 12"><path d="M2 6l3 3 5-5" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>',i.appendChild(s),i.appendChild(r),i}_updateSelectedState(){const e=this.state.get("selectedFilter");this._chips.forEach((t,i)=>{t.classList.toggle("selected",i===e)})}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._chips.clear(),(e=this.element)==null||e.remove(),this.element=null}}const Ft=[{id:"free",name:"Free",icon:mt},{id:"square",name:"Square",icon:gt},{id:"circle",name:"Circle",icon:ft}],Rt=[{id:"free",name:"Free"},{id:"1:1",name:"1:1"},{id:"4:3",name:"4:3"},{id:"16:9",name:"16:9"},{id:"3:2",name:"3:2"},{id:"2:3",name:"2:3"}],Lt=[{id:"0",label:"0°",angle:0},{id:"90",label:"90°",angle:90},{id:"180",label:"180°",angle:180},{id:"270",label:"270°",angle:270}];function G(_){if(!Number.isFinite(Number(_)))return 0;const e=Number(_)%360;return e<0?e+360:e}class Pe{constructor(e,t,i=null){this.state=e,this.cropManager=t,this.editor=i,this.element=null,this._shapeChips=new Map,this._aspectChips=new Map,this._rotationPresetChips=new Map,this._rotationRange=null,this._rotationNumber=null,this._rotationValue=null,this._unsubscribers=[]}_applyCropAndReturnToFilters(){this.cropManager.apply()===null&&typeof this.cropManager.disable=="function"&&this.cropManager.disable(),this.state.set("selectedCategory","adjust")}render(){this.element=h("div",{className:"crop-controls","data-testid":"crop-controls"}),this.element.appendChild(this._renderRotationSection());const e=h("div",{className:"crop-section"});e.appendChild(h("label",{className:"section-label"},"Shape"));const t=h("div",{className:"chip-row"}),i=this.state.get("crop.shape");Ft.forEach(l=>{const c=pe({label:l.name,icon:l.icon,active:i===l.id,onClick:()=>this._selectShape(l.id)});c.dataset.shape=l.id,c.dataset.testid=`crop-shape-${l.id}`,this._shapeChips.set(l.id,c),t.appendChild(c)}),e.appendChild(t),this.element.appendChild(e),this.state.get("lockCropShape")&&(e.style.display="none"),this._shapeSection=e,this._aspectSection=h("div",{className:"crop-section"}),this._aspectSection.appendChild(h("label",{className:"section-label"},"Aspect Ratio"));const s=h("div",{className:"chip-row aspect-row"}),r=this.state.get("crop.aspect");Rt.forEach(l=>{const c=pe({label:l.name,active:r===l.id,onClick:()=>this._selectAspect(l.id)});c.dataset.ratio=l.id,c.dataset.testid=`crop-ratio-${l.id}`,this._aspectChips.set(l.id,c),s.appendChild(c)}),this._aspectSection.appendChild(s),this.element.appendChild(this._aspectSection),this._updateAspectVisibility();const a=h("div",{className:"crop-actions"}),o=B({label:"Cancel",className:"btn-secondary crop-cancel-btn",icon:se,onClick:()=>this.cropManager.cancel()});o.dataset.testid="cancel-crop";const n=B({label:"Apply Crop",className:"btn-primary crop-apply-btn",icon:_e,onClick:()=>this._applyCropAndReturnToFilters()});return n.dataset.testid="apply-crop",a.appendChild(o),a.appendChild(n),this.element.appendChild(a),this._subscribeToState(),this.element}_renderRotationSection(){const e=h("div",{className:"crop-section rotation-section"});e.appendChild(h("label",{className:"section-label"},"Rotate"));const t=h("div",{className:"rotation-action-row"}),i=B({label:"Left 90°",className:"btn-secondary rotation-action-btn",icon:nt,onClick:()=>this._rotateBy(-90)});i.dataset.testid="rotate-left-90";const s=B({label:"Right 90°",className:"btn-secondary rotation-action-btn",icon:at,onClick:()=>this._rotateBy(90)});s.dataset.testid="rotate-right-90";const r=B({label:"Rotate 180°",className:"btn-secondary rotation-action-btn",onClick:()=>this._rotateBy(180)});r.dataset.testid="rotate-180";const a=B({label:"Rotate 270°",className:"btn-secondary rotation-action-btn",onClick:()=>this._rotateBy(270)});a.dataset.testid="rotate-270",t.appendChild(i),t.appendChild(s),t.appendChild(r),t.appendChild(a),e.appendChild(t);const o=h("div",{className:"chip-row rotation-preset-row"}),n=G(this.state.get("transform.rotation")??0);Lt.forEach(u=>{const g=pe({label:u.label,active:Math.round(n)===u.angle,onClick:()=>this._setRotation(u.angle)});g.dataset.angle=u.id,g.dataset.testid=`rotation-preset-${u.id}`,this._rotationPresetChips.set(u.id,g),o.appendChild(g)}),e.appendChild(o);const l=h("div",{className:"rotation-arbitrary"}),c=h("div",{className:"rotation-angle-header"},h("label",{className:"rotation-angle-label",for:"image-editor-rotation-angle"},"Angle"),h("span",{className:"rotation-angle-value"},this._formatAngle(n)));this._rotationValue=c.querySelector(".rotation-angle-value"),this._rotationRange=h("input",{id:"image-editor-rotation-angle",type:"range",className:"slider-input rotation-range",min:"0",max:"360",step:"1",value:String(Math.round(n)),"aria-label":"Rotation angle",onInput:u=>this._previewAngleValue(u.target.value),onChange:u=>this._setRotation(Number(u.target.value))}),this._rotationNumber=h("input",{type:"number",className:"text-input rotation-number-input",min:"-360",max:"360",step:"1",value:this._formatPlainAngle(n),"aria-label":"Rotation angle in degrees",onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),this._setRotation(Number(u.target.value)),u.target.blur())},onBlur:u=>this._setRotation(Number(u.target.value))});const d=h("div",{className:"rotation-angle-row"},this._rotationRange,this._rotationNumber);l.appendChild(c),l.appendChild(d);const p=B({label:"Reset rotation",className:"btn-text rotation-reset-btn",onClick:()=>this._setRotation(0)});return p.dataset.testid="reset-rotation",l.appendChild(p),e.appendChild(l),e}_subscribeToState(){const e=this.state.on("change:crop.shape",({value:s})=>{this._shapeChips.forEach((r,a)=>{r.setActive(a===s)}),this._updateAspectVisibility()});this._unsubscribers.push(e);const t=this.state.on("change:crop.aspect",({value:s})=>{this._aspectChips.forEach((r,a)=>{r.setActive(a===s)})});this._unsubscribers.push(t);const i=this.state.on("change:transform.rotation",({value:s})=>{this._syncRotationControls(s)});this._unsubscribers.push(i)}_rotateBy(e){var i,s;((s=(i=this.editor)==null?void 0:i.rotateBy)==null?void 0:s.call(i,e))!==!1&&this._syncRotationControls(this.state.get("transform.rotation")??0)}_setRotation(e){var s,r;const t=G(e);if(((r=(s=this.editor)==null?void 0:s.setRotationAngle)==null?void 0:r.call(s,t))===!1){this._syncRotationControls(this.state.get("transform.rotation")??0);return}this._syncRotationControls(t)}_previewAngleValue(e){const t=G(Number(e));this._rotationValue&&(this._rotationValue.textContent=this._formatAngle(t)),this._rotationNumber&&(this._rotationNumber.value=this._formatPlainAngle(t)),this._refreshPresetChips(t)}_syncRotationControls(e){const t=G(e);this._rotationValue&&(this._rotationValue.textContent=this._formatAngle(t)),this._rotationRange&&(this._rotationRange.value=String(Math.round(t))),this._rotationNumber&&(this._rotationNumber.value=this._formatPlainAngle(t)),this._refreshPresetChips(t)}_refreshPresetChips(e){const t=Math.round(G(e))%360;this._rotationPresetChips.forEach((i,s)=>{i.setActive(Number(s)===t)})}_formatAngle(e){return`${this._formatPlainAngle(e)}°`}_formatPlainAngle(e){const t=G(e);return Number.isInteger(t)?String(t):t.toFixed(1)}_selectShape(e){this.cropManager.setShape(e)}_selectAspect(e){this.cropManager.setAspect(e)}_updateAspectVisibility(){const e=this.state.get("crop.shape"),t=this.state.get("lockAspectRatio");this._aspectSection&&(this._aspectSection.style.display=e==="free"&&!t?"":"none")}show(){this.element&&(this.element.style.display="")}hide(){this.element&&(this.element.style.display="none")}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._shapeChips.clear(),this._aspectChips.clear(),this._rotationPresetChips.clear(),(e=this.element)==null||e.remove(),this.element=null}}class Et{constructor(e,t){this.state=e,this.filterManager=t,this.element=null,this._filterItems=new Map,this._unsubscribers=[],this._onRemove=null,this._onReset=null,this._onClearAll=null,this._onUpdateValue=null,this._onSelect=null}render({onRemove:e,onReset:t,onClearAll:i,onUpdateValue:s,onSelect:r}){this._onRemove=e,this._onReset=t,this._onClearAll=i,this._onUpdateValue=s,this._onSelect=r,this.element=h("div",{className:"active-filters-panel","data-testid":"active-filters-panel"});const a=h("div",{className:"panel-header"});a.appendChild(h("h3",{className:"panel-title"},"Active Filters"));const o=B({label:"Clear All",className:"btn-text btn-danger",onClick:()=>this._handleClearAll()});return o.dataset.testid="clear-all-filters",a.appendChild(o),this.element.appendChild(a),this._listContainer=h("div",{className:"active-filters-list"}),this.element.appendChild(this._listContainer),this._subscribeToState(),this._renderFilterList(),this.element}_subscribeToState(){const e=this.state.on("change:activeFilters",()=>{this._renderFilterList()});this._unsubscribers.push(e);const t=this.state.on("change:filterValues",()=>{this._updateValuesDisplay()});this._unsubscribers.push(t);const i=this.state.on("change:selectedFilter",()=>{this._updateSelectedState()});this._unsubscribers.push(i)}_updateSelectedState(){const e=this.state.get("selectedFilter");this._filterItems.forEach((t,i)=>{t.classList.toggle("selected",i===e)})}_renderFilterList(){this._listContainer.innerHTML="",this._filterItems.clear();const e=this.state.get("activeFilters");if(e.size===0){this._listContainer.appendChild(h("div",{className:"no-filters-message"},"No filters active"));return}e.forEach(t=>{const i=this.filterManager.getFilterDef(t);if(!i)return;const s=this._createFilterItem(t,i);this._filterItems.set(t,s),this._listContainer.appendChild(s)})}_createFilterItem(e,t){const s=this.state.get("selectedFilter")===e,r=h("div",{className:`active-filter-item ${s?"selected":""}`,"data-active-filter":e,"data-testid":`active-filter-${e}`,onClick:u=>{u.target.closest(".filter-item-actions")||this._handleSelect(e)}}),a=h("div",{className:"filter-item-header"}),o=h("span",{className:"filter-item-name"},t.name),n=h("div",{className:"filter-item-actions"}),l=N({icon:Be,title:"Reset filter",className:"btn-icon-sm",onClick:()=>this._handleReset(e)}),c=N({icon:Ne,title:"Remove filter",className:"btn-icon-sm btn-danger",onClick:()=>this._handleRemove(e)});n.appendChild(l),n.appendChild(c),a.appendChild(o),a.appendChild(n),r.appendChild(a);const d=this.state.getFilterValues(e),p=h("div",{className:"filter-item-summary"});return p.textContent=this._getValuesSummary(t,d),r.appendChild(p),r._summaryEl=p,r}_normalizeControlType(e){return{slider:"slider",range:"slider",toggle:"toggle",checkbox:"toggle",color:"color",select:"select",dropdown:"select",button:"button"}[e]||e}_getValuesSummary(e,t){if(!e.controls||!Array.isArray(e.controls))return"Default values";const i=[];return e.controls.forEach(s=>{const r=this._normalizeControlType(s.type);if(r==="button")return;const a=s.label||s.id,o=t[s.id]??s.default;o!==s.default&&(r==="slider"?i.push(`${a}: ${this._formatValue(o)}`):r==="toggle"?o&&i.push(a):r==="color"?i.push(`${a}: ${o}`):r==="select"&&i.push(`${a}: ${o}`))}),i.length>0?i.join(", "):"Default values"}_formatValue(e){return typeof e!="number"||Number.isInteger(e)?String(e):e.toFixed(2)}_updateValuesDisplay(){this._filterItems.forEach((e,t)=>{const i=this.filterManager.getFilterDef(t);if(!i||!e._summaryEl)return;const s=this.state.getFilterValues(t);e._summaryEl.textContent=this._getValuesSummary(i,s)})}_handleRemove(e){var t;(t=this._onRemove)==null||t.call(this,e)}_handleReset(e){var t;(t=this._onReset)==null||t.call(this,e)}_handleClearAll(){var e;(e=this._onClearAll)==null||e.call(this)}_handleSelect(e){var t;this.state.set("selectedFilter",e),(t=this._onSelect)==null||t.call(this,e)}show(){this.element&&(this.element.style.display="")}hide(){this.element&&(this.element.style.display="none")}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._filterItems.clear(),(e=this.element)==null||e.remove(),this.element=null}}const K={name:"free",initialMode:"filters",cropShape:"free",aspectRatio:"free",autoZoomOnCropOverflow:!1,lockCropShape:!1,lockAspectRatio:!1,showFilters:!0,showCropControls:!0,maxExportWidth:void 0,maxExportHeight:void 0},ve={free:{...K},avatar:{...K,name:"avatar",initialMode:"crop",cropShape:"circle",aspectRatio:"1:1",autoZoomOnCropOverflow:!0,lockCropShape:!0,lockAspectRatio:!0},banner:{...K,name:"banner",initialMode:"crop",cropShape:"square",aspectRatio:"16:9",autoZoomOnCropOverflow:!1,lockCropShape:!1,lockAspectRatio:!0},cover:{...K,name:"cover",initialMode:"crop",cropShape:"free",aspectRatio:"24:5",autoZoomOnCropOverflow:!0,lockCropShape:!0,lockAspectRatio:!0},product:{...K,name:"product",initialMode:"filters",cropShape:"square",aspectRatio:"1:1",autoZoomOnCropOverflow:!1,lockCropShape:!1,lockAspectRatio:!1}};function je(_){if(!_)return{...ve.free};if(typeof _=="object"&&_!==null)return{...K,..._};const e=ve[_];return e?{...e}:{...ve.free}}function Y(_){if(!Number.isFinite(Number(_)))return 0;const e=Number(_)%360;return e<0?e+360:e}function At(_,e){const t=Y(_);return(Y(e)-t+540)%360-180}class Tt extends U.EventEmitter{constructor(e,t={}){var r,a,o,n;if(super(),!e)throw new Error("VanillaImageEditor: container element is required");this._container=e,this._destroyed=!1,this._loadVersion=0,this._objectUrls=new Set,this._activeObjectUrl=null;const i=t.preset?je(t.preset):null,s=i?{initialMode:i.initialMode==="crop"?"crop":"adjust",cropShape:i.cropShape,initialAspectRatio:i.aspectRatio}:{};this._options={theme:"auto",initialImage:null,initialMode:"adjust",cropShape:"free",initialAspectRatio:"free",backgroundRemoval:{enabled:!0,endpoint:"/api/v1/media/background-removal/preview",optionsEndpoint:"/api/v1/media/background-removal/options",fallbackEndpoint:null},...s,...t},this._preset=i,this._state=U.createState(),this._state.set("theme",this._options.theme),this._state.set("crop.shape",this._options.cropShape),this._state.set("crop.aspect",this._options.initialAspectRatio),this._preset&&(this._state.set("lockCropShape",!!this._preset.lockCropShape),this._state.set("lockAspectRatio",!!this._preset.lockAspectRatio),this._state.set("showFilters",this._preset.showFilters!==!1),this._state.set("showCropControls",this._preset.showCropControls!==!1),this._state.set("autoZoomOnCropOverflow",!!this._preset.autoZoomOnCropOverflow)),this._renderer=new Le,this._filterManager=new De(this._state,this._renderer),this._cropManager=new ge(this._state,this._renderer),this._removeBgManager=null,this._backgroundRemovalAvailable=!1,((r=this._options.backgroundRemoval)==null?void 0:r.enabled)!==!1&&(this._removeBgManager=new ze({endpoint:(a=this._options.backgroundRemoval)==null?void 0:a.endpoint,optionsEndpoint:(o=this._options.backgroundRemoval)==null?void 0:o.optionsEndpoint,fallbackEndpoint:(n=this._options.backgroundRemoval)==null?void 0:n.fallbackEndpoint})),this._loadingOverlay=null,this._isMobile=typeof window<"u"?window.innerWidth<=768:!1,this._toolbar=null,this._categoryCarousel=null,this._filterCarousel=null,this._filterAdjustments=null,this._mobileFilterDrawer=null,this._mobileActiveFilters=null,this._cropControls=null,this._activeFiltersPanel=null,this._editorEl=null,this._canvasContainer=null,this._cropOverlay=null,this._controlsSection=null,this._filterControlsEl=null,this._fileInput=null,this._resizeObserver=null,this._initPromise=Promise.resolve(this._init()).catch(l=>{this._destroyed||this.emit("error",l instanceof Error?l:new Error(String(l)))})}async _init(){this._state.detectTheme(),this._buildDOM(),!(!await this._renderer.mount(this._canvasContainer,this._state.get("isDarkMode")?657930:16777215)||this._destroyed)&&(this._cropManager.setOverlayCanvas(this._cropOverlay),this._initUI(),this._setupResizeObserver(),this._setupWindowResize(),this._subscribeToState(),this._refreshBackgroundRemovalAvailability(),this._options.initialImage&&await this.loadImage(this._options.initialImage),this.emit("ready"))}_buildDOM(){this._container.innerHTML="",this._editorEl=h("div",{className:`vanilla-image-editor ${this._state.get("isDarkMode")?"dark":"light"}`});const e=h("div",{className:"editor-toolbar-container"});this._editorEl.appendChild(e),this._toolbarContainer=e;const t=h("div",{className:"editor-content"}),i=h("div",{className:"canvas-section"});this._canvasContainer=h("div",{className:"canvas-container"}),this._cropOverlay=h("canvas",{className:"crop-overlay","aria-hidden":"true"}),i.appendChild(this._canvasContainer),i.appendChild(this._cropOverlay),t.appendChild(i),this._controlsSection=h("div",{className:"controls-section"}),t.appendChild(this._controlsSection),this._editorEl.appendChild(t),this._fileInput=h("input",{type:"file",accept:"image/*",className:"hidden-file-input","aria-label":"Choose image file to edit",onChange:s=>this._handleFileSelect(s)}),this._editorEl.appendChild(this._fileInput),this._container.appendChild(this._editorEl)}_initUI(){this._toolbar=new Oe(this._state,this),this._toolbarContainer.appendChild(this._toolbar.render()),this._filterControlsEl=h("div",{className:"filter-controls-container"}),this._categoryCarousel=new Ct(this._state,this),this._filterControlsEl.appendChild(this._categoryCarousel.render(s=>{}));const e=h("div",{className:"filter-layout"}),t=h("div",{className:"filter-left-column"});this._filterCarousel=new kt(this._state,this._filterManager),t.appendChild(this._filterCarousel.render({onToggle:(s,r)=>this._handleFilterToggle(s,r),onSelect:s=>{this._handleFilterSelect(s),this._isMobile&&this._mobileFilterDrawer&&this._mobileFilterDrawer.open(s)}})),this._filterAdjustments=new xt(this._state,this._filterManager),t.appendChild(this._filterAdjustments.render({onChange:(s,r,a)=>this._handleFilterChange(s,r,a),onReset:s=>this._handleFilterReset(s),onAction:(s,r)=>this._handleFilterAction(s,r)})),e.appendChild(t);const i=h("div",{className:"filter-right-column"});this._activeFiltersPanel=new Et(this._state,this._filterManager),i.appendChild(this._activeFiltersPanel.render({onRemove:s=>this._handleFilterToggle(s,!1),onReset:s=>this._handleFilterReset(s),onClearAll:()=>this.resetAll(),onSelect:s=>this._handleFilterSelect(s)})),e.appendChild(i),this._filterControlsEl.appendChild(e),this._mobileActiveFilters=new Mt(this._state,this._filterManager),this._filterControlsEl.appendChild(this._mobileActiveFilters.render({onToggle:(s,r)=>this._handleFilterToggle(s,r),onSelect:s=>{this._handleFilterSelect(s),this._isMobile&&this._mobileFilterDrawer&&this._mobileFilterDrawer.open(s)}})),this._cropControls=new Pe(this._state,this._cropManager,this),this._cropControlsEl=this._cropControls.render(),this._cropControlsEl.style.display="none",this._controlsSection.appendChild(this._filterControlsEl),this._controlsSection.appendChild(this._cropControlsEl),this._mobileFilterDrawer=new St(this._state,this._filterManager),this._mobileFilterDrawer.build(this._controlsSection,{onChange:(s,r,a)=>this._handleFilterChange(s,r,a),onReset:s=>this._handleFilterReset(s),onRemove:s=>{this._handleFilterToggle(s,!1),this._state.set("selectedFilter",null)},onAction:(s,r)=>this._handleFilterAction(s,r)})}_setupResizeObserver(){let e=null;this._resizeObserver=new ResizeObserver(()=>{clearTimeout(e),e=setTimeout(()=>{this._canvasContainer&&(this._renderer.resizeTo(this._canvasContainer),this._state.get("mode")==="crop"&&this._cropManager.drawOverlay())},50)}),this._resizeObserver.observe(this._canvasContainer)}_setupWindowResize(){this._handleWindowResize=()=>{var e;this._isMobile=window.innerWidth<=768,!this._isMobile&&((e=this._mobileFilterDrawer)!=null&&e.isOpen)&&this._mobileFilterDrawer.close()},window.addEventListener("resize",this._handleWindowResize)}_subscribeToState(){this._state.on("change:mode",({value:e})=>{this._updateModeUI(e),e==="filters"&&this._filterManager.applyFilters()}),this._state.on("change:isDarkMode",({value:e})=>{this._editorEl.classList.toggle("dark",e),this._editorEl.classList.toggle("light",!e),this._renderer.setBackgroundColor(e?657930:16777215)}),this._state.on("change:hasImage",({value:e})=>{this._editorEl.classList.toggle("has-image",e)}),this._renderer.on("zoomChange",e=>{this._state.set("zoom",e)})}_updateModeUI(e){var t;e==="crop"?(this._filterControlsEl.style.display="none",this._cropControlsEl.style.display="",(t=this._mobileFilterDrawer)!=null&&t.isOpen&&this._mobileFilterDrawer.close()):(this._filterControlsEl.style.display="",this._cropControlsEl.style.display="none")}async _handleFileSelect(e){var i;const t=(i=e.target.files)==null?void 0:i[0];t&&await this.loadImage(t),this._fileInput.value=""}_handleFilterToggle(e,t){this._filterManager.toggle(e,t)}_handleFilterSelect(e){this._state.set("selectedFilter",e)}_handleFilterChange(e,t,i){this._filterManager.updateValue(e,t,i)||this._filterManager.applyFilters(),this._renderer.render()}_handleFilterReset(e){this._filterManager.resetValues(e),this._filterManager.applyFilters()}_handleFilterAction(e,t){this._filterManager.performFilterAction(e,t)}_revokeObjectUrl(e){!e||!this._objectUrls.has(e)||(URL.revokeObjectURL(e),this._objectUrls.delete(e),this._activeObjectUrl===e&&(this._activeObjectUrl=null))}_replaceActiveObjectUrl(e){const t=this._activeObjectUrl;this._activeObjectUrl=e,this._objectUrls.add(e),t&&t!==e&&this._revokeObjectUrl(t)}_clearActiveObjectUrl(){this._activeObjectUrl&&this._revokeObjectUrl(this._activeObjectUrl)}setFilterRegistry(e){this._filterManager.setRegistry(e)}async loadImage(e,t={}){var o,n;if(this._destroyed)return;(n=(o=this._removeBgManager)==null?void 0:o.cancelActiveRequests)==null||n.call(o,"image-load");const i=++this._loadVersion;let s=e,r=null;this._resetEditorState(),this._state.set("hasImage",!1),this._state.set("imageUrl",null),e instanceof Blob&&(s=URL.createObjectURL(e),r=s,this._objectUrls.add(s));const a=await this._renderer.loadTexture(s,{isCurrent:()=>!this._destroyed&&this._loadVersion===i});if(this._destroyed||this._loadVersion!==i){this._revokeObjectUrl(r);return}if(!a){this._revokeObjectUrl(r),this.emit("error",new Error("Failed to load image"));return}r?this._replaceActiveObjectUrl(r):this._clearActiveObjectUrl(),this._state.set("hasImage",!0),this._state.set("imageUrl",s),t.state&&this._hydrateState(t.state),this._options.initialMode==="crop"&&this.setMode("crop"),this.emit("imageLoaded",{url:s})}_resetEditorState(){this._filterManager.resetAll(),this._state.set("crop.rect",null),this._state.set("crop.appliedRect",null),this._state.set("crop.appliedShape",null),this._state.set("crop.appliedAspect",null),this._state.set("crop.dirty",!1),this._state.set("crop.shape",this._options.cropShape||"free"),this._state.set("crop.aspect",this._options.initialAspectRatio||"free"),this._state.set("transform.rotation",0),this._state.get("mode")==="crop"&&(this._cropManager.disable(),this._state.set("mode","filters"))}_hydrateState(e){var i;if(!e||e.version!==1)return;const t=Y(((i=e.transform)==null?void 0:i.rotation)??0);if(t!==0&&this._renderer.rotateBy(t)&&this._state.set("transform.rotation",t),e.crop){const s=e.crop.shape||"free",r=e.crop.aspectRatio||"free";e.crop.rect&&(this._cropManager.applyFromPixelRect(e.crop.rect,s),this._state.set("crop.appliedRect",{...e.crop.rect}),this._state.set("crop.appliedShape",s),this._state.set("crop.appliedAspect",r)),this._state.set("crop.shape",s),this._state.set("crop.aspect",r)}if(Array.isArray(e.filters)){let s=null;for(const r of e.filters)if(r.enabled&&(s===null&&(s=r.id),this._state.toggleFilter(r.id,!0),this._filterManager.initializeValues(r.id),r.values))for(const[a,o]of Object.entries(r.values))this._state.setFilterValue(r.id,a,o);if(s!==null){this._state.set("selectedFilter",s);const r=this._filterManager.getFilterDef(s);if(typeof(r==null?void 0:r.category)=="string"){const a=ye[r.category]??r.category;this._state.set("selectedCategory",a)}}this._filterManager.applyFilters()}}openFilePicker(){var e;(e=this._fileInput)==null||e.click()}exportImage(e="png",t=.92,i={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditor.exportImage")?null:this._renderer.exportImage(e,t,i.maxEdge??0,i.dontUpscale!==!1,i.maxPixels??0)}async exportBlob(e="png",t=.92,i={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditor.exportBlob")?null:this._renderer.exportBlob(e,t,i)}_applyPendingCropBeforeExport(e){return!(this._state.get("crop.rect")&&!this._cropManager.apply())}async save(){if(!this._state.get("hasImage"))return;this._state.set("isSaving",!0);let e=null;try{const t=await this.exportBlob("png",.92);if(!t)throw new Error("Failed to export image");const i=document.createElement("a");e=URL.createObjectURL(t.blob),i.href=e,i.download=`edited-image-${Date.now()}.png`,document.body.appendChild(i),i.click(),document.body.removeChild(i),this.emit("save",{blob:t.blob,mimeType:t.blob.type||"image/png",dimensions:{width:t.width,height:t.height},state:this.getSerializableState()})}catch(t){this.emit("error",{error:t})}finally{e&&URL.revokeObjectURL(e),this._state.set("isSaving",!1)}}getSerializableState(){const e=this._state.get("activeFilters"),t=[];if(e)for(const a of e){const o=this._state.getFilterValues(a);t.push({id:a,enabled:!0,values:{...o}})}const i=this._state.get("crop.appliedRect"),s=this._state.get("crop.rect"),r=i||s;return{version:1,crop:{rect:r?{...r}:null,aspectRatio:this._state.get("crop.appliedAspect")||this._state.get("crop.aspect")||"free",shape:this._state.get("crop.appliedShape")||this._state.get("crop.shape")||"free"},transform:{rotation:Y(this._state.get("transform.rotation")??0)},filters:t}}close(){this.emit("cancel")}setZoom(e){this._renderer.setZoom(e)}fitToScreen(){this._renderer.fitToScreen()}resetAll(){this._filterManager.resetAll()}rotateBy(e){const t=this._state.get("transform.rotation")??0;return this.setRotationAngle(Number(t)+Number(e))}setRotationAngle(e){if(!this._state.get("hasImage"))return!1;const t=Y(this._state.get("transform.rotation")??0),i=Y(e),s=At(t,i),r=this._state.get("mode")==="crop";if(Math.abs(s)>.001){if(r&&this._cropManager.disable(),!this._renderer.rotateBy(s))return r&&this._cropManager.enable(),!1;this._filterManager.applyFilters(),this._state.set("crop.rect",null),this._state.set("crop.dirty",!1),r&&this._cropManager.enable()}return this._state.set("transform.rotation",i),this.emit("transformChanged",{rotation:i}),!0}resetRotation(){return this.setRotationAngle(0)}toggleTheme(){const e=this._state.get("isDarkMode");this._state.set("isDarkMode",!e)}setTheme(e){this._state.set("theme",e),this._state.detectTheme()}setMode(e){e==="crop"?this._cropManager.enable():this._cropManager.disable(),this._state.set("mode",e)}getState(){return this._state.getAll()}async removeBackground(e={}){var t,i;if(!this._removeBgManager)throw new Error("Background removal is not enabled");if(!this._state.get("hasImage"))throw new Error("No image loaded");if(!this.canRemoveBackground())throw new Error("Background removal is not available for the current editor state");this._state.set("isProcessing",!0),this._showLoadingOverlay("Removing background...");try{const s=this.exportImage("png");if(!s)throw new Error("Failed to export image for background removal");const r=await this._removeBgManager.preparePreviewRequest(s,e),a=this._buildPreviewBackgroundRemovalContext(r),o=await this._removeBgManager.removeBackground(r.blob,r);return await this._isCurrentPreviewBackgroundRemovalContext(a,o)?(await this.loadImage(o.dataUrl),this.emit("background-removed",{model:o.model,processMs:o.processMs}),{model:o.model,processMs:o.processMs}):(this.emit("background-removal-stale",{operationId:a.operationId,sourceHash:a.sourceHash}),{stale:!0})}catch(s){throw this.emit("error",{error:s,context:"background-removal"}),s}finally{(i=(t=this._state)==null?void 0:t.set)==null||i.call(t,"isProcessing",!1),this._hideLoadingOverlay()}}async isBackgroundRemovalAvailable(){return this._removeBgManager?this._refreshBackgroundRemovalAvailability():!1}canRemoveBackground(){return!!this._removeBgManager&&this._state.get("hasImage")===!0&&this._backgroundRemovalAvailable===!0}async _refreshBackgroundRemovalAvailability(){if(!this._removeBgManager)return this._backgroundRemovalAvailable=!1,this._state.set("backgroundRemovalAvailable",!1),!1;const e=await this._removeBgManager.isAvailable();return this._destroyed?!1:(this._backgroundRemovalAvailable=e,this._state.set("backgroundRemovalAvailable",e),e)}_buildPreviewBackgroundRemovalContext(e){return{loadVersion:this._loadVersion,imageUrl:this._state.get("imageUrl")??null,operationId:e.operationId,sessionKey:e.sessionKey,sourceHash:e.sourceHash,targetRef:e.targetRef??null}}async _isCurrentPreviewBackgroundRemovalContext(e,t=null){if(this._destroyed||this._loadVersion!==e.loadVersion||this._state.get("hasImage")!==!0||(this._state.get("imageUrl")??null)!==e.imageUrl||t&&(t.operationId&&t.operationId!==e.operationId||t.sessionKey&&t.sessionKey!==e.sessionKey||t.sourceHash&&t.sourceHash!==e.sourceHash||t.targetRef&&e.targetRef&&t.targetRef!==e.targetRef))return!1;const i=this.exportImage("png");return i?await this._removeBgManager.computeImageDataHash(i)===e.sourceHash:!1}_showLoadingOverlay(e){var i;if(!this._loadingOverlay)this._loadingOverlay=h("div",{className:"editor-loading-overlay"},[h("div",{className:"editor-loading-spinner"}),h("div",{className:"editor-loading-text"},e)]);else{const s=this._loadingOverlay.querySelector(".editor-loading-text");s&&(s.textContent=e)}const t=(i=this._canvasContainer)==null?void 0:i.parentElement;t&&!this._loadingOverlay.parentElement&&t.appendChild(this._loadingOverlay)}_hideLoadingOverlay(){var e;(e=this._loadingOverlay)==null||e.remove()}destroy(){var e,t,i,s,r,a,o,n,l,c,d,p;this._destroyed=!0,(t=(e=this._removeBgManager)==null?void 0:e.cancelActiveRequests)==null||t.call(e,"editor-destroy");for(const u of this._objectUrls)try{URL.revokeObjectURL(u)}catch{}this._objectUrls.clear(),this._activeObjectUrl=null,(i=this._resizeObserver)==null||i.disconnect(),this._renderer.destroy(),this._cropManager.disable(),this._handleWindowResize&&window.removeEventListener("resize",this._handleWindowResize),(s=this._toolbar)==null||s.destroy(),(r=this._categoryCarousel)==null||r.destroy(),(a=this._filterCarousel)==null||a.destroy(),(o=this._filterAdjustments)==null||o.destroy(),(n=this._mobileFilterDrawer)==null||n.destroy(),(l=this._mobileActiveFilters)==null||l.destroy(),(c=this._cropControls)==null||c.destroy(),(d=this._activeFiltersPanel)==null||d.destroy(),(p=this._editorEl)==null||p.remove(),this._container=null,this._state=null,this.emit("destroyed"),this.removeAllListeners()}}class Ue{constructor(e,t){this.state=e,this.editor=t,this.element=null,this._tabs=new Map,this._unsubscribers=[],this._onSelect=null}render({onSelect:e}={}){return this._onSelect=e,this.element=h("div",{className:"panel-tabs",role:"tablist","aria-label":"Filter categories","data-testid":"v2-category-tabs"}),re.forEach(t=>{const i=h("button",{type:"button",className:`panel-tab ${this._isSelected(t.id)?"active":""}`,role:"tab","aria-selected":this._isSelected(t.id)?"true":"false","data-category":t.id,"data-testid":`v2-category-${t.id}`,onClick:()=>this._selectCategory(t.id)});if(t.icon){const s=h("span",{className:"panel-tab-icon","aria-hidden":"true"});s.innerHTML=t.icon,i.appendChild(s)}i.appendChild(h("span",{className:"panel-tab-label"},t.name)),this._tabs.set(t.id,i),this.element.appendChild(i)}),this._unsubscribers.push(this.state.on("change:selectedCategory",()=>this._refreshActive())),this.element}_isSelected(e){const t=this.state.get("selectedCategory");return e==="crop"?this.state.get("mode")==="crop":t===e&&this.state.get("mode")!=="crop"}_selectCategory(e){var i;this.state.set("selectedCategory",e);const t=this.state.get("mode");e==="crop"?t!=="crop"&&this.editor.setMode("crop"):t!=="filters"&&this.editor.setMode("filters"),this._refreshActive(),(i=this._onSelect)==null||i.call(this,e)}_refreshActive(){this._tabs.forEach((e,t)=>{const i=this._isSelected(t);e.classList.toggle("active",i),e.setAttribute("aria-selected",i?"true":"false")})}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._tabs.clear(),(e=this.element)==null||e.remove(),this.element=null}}class He{constructor(e,t){this.state=e,this.filterManager=t,this.element=null,this._unsubscribers=[],this._onToggle=null,this._onSelect=null}render({onToggle:e,onSelect:t}={}){return this._onToggle=e,this._onSelect=t,this.element=h("div",{className:"filter-list",role:"listbox","aria-label":"Filters","data-testid":"v2-filter-list"}),this._renderRows(),this._unsubscribers.push(this.state.on("change:selectedCategory",()=>this._renderRows()),this.state.on("change:activeFilters",()=>this._renderRows()),this.state.on("change:selectedFilter",()=>this._renderRows()),this.state.on("change:filterValues",()=>this._refreshSummaries())),this.element}_renderRows(){this.element.innerHTML="";const e=this.state.get("selectedCategory");if(!e||e==="crop")return;const t=this.filterManager.getFiltersByCategory(e),i=this.state.get("activeFilters"),s=this.state.get("selectedFilter"),r=typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId");t.forEach(a=>{var l;const o=((l=i==null?void 0:i.has)==null?void 0:l.call(i,a.id))??!1,n=s===a.id;this.element.appendChild(this._renderRow(a,o,n,r))})}_renderRow(e,t,i,s=null){const r=h("button",{type:"button",className:`filter-row ${i?"selected":""}`,role:"option","aria-selected":i?"true":"false","data-filter":e.id,"data-testid":`v2-filter-${e.id}`,onClick:()=>{var c;return(c=this._onSelect)==null?void 0:c.call(this,e.id,s)}}),a=h("button",{type:"button",className:`filter-row-toggle ${t?"active":""}`,"aria-label":`${t?"Disable":"Enable"} ${e.name}`,"aria-pressed":t?"true":"false","data-testid":`v2-filter-toggle-${e.id}`,onClick:c=>{var p,u,g,m;c.stopPropagation();const d=!((u=(p=this.state.get("activeFilters"))==null?void 0:p.has)!=null&&u.call(p,e.id));(g=this._onToggle)==null||g.call(this,e.id,d,s),d&&((m=this._onSelect)==null||m.call(this,e.id,s))}});t&&(a.innerHTML=_e),r.appendChild(a);const o=h("div",{className:"filter-row-body"});o.appendChild(h("span",{className:"filter-row-name"},e.name));const n=this._buildSummary(e,t);n&&o.appendChild(h("span",{className:"filter-row-summary"},n)),r.appendChild(o);const l=h("span",{className:"filter-row-chevron","aria-hidden":"true"});return l.innerHTML=ie,r.appendChild(l),r}_buildSummary(e,t){if(!t)return e.description||"";const i=this.state.getFilterValues(e.id);if(!i||Object.keys(i).length===0)return e.description||"Active";const s=[];for(const r of(e.controls||[]).slice(0,4)){const a=i[r.id];if(!(a===void 0||a===r.default)&&(s.push(this._formatControlValue(r,a)),s.length>=2))break}return s.length===0?"Active":s.join(" · ")}_formatControlValue(e,t){return e.type==="toggle"?e.label:typeof t=="number"?(e.max??1)<=1&&(e.min??0)>=0?`${e.label} ${Math.round(t*100)}%`:Number.isInteger(t)?`${e.label} ${t}`:`${e.label} ${t.toFixed(2)}`:typeof t=="string"?`${e.label}`:e.label}_refreshSummaries(){var s;const e=this.state.get("selectedCategory");if(!e||e==="crop")return;const t=this.filterManager.getFiltersByCategory(e),i=this.state.get("activeFilters");for(const r of t){const a=this.element.querySelector(`[data-filter="${r.id}"]`);if(!a)continue;const o=((s=i==null?void 0:i.has)==null?void 0:s.call(i,r.id))??!1,n=this._buildSummary(r,o),l=a.querySelector(".filter-row-summary");if(n&&l)l.textContent=n;else if(n&&!l){const c=a.querySelector(".filter-row-body");c==null||c.appendChild(h("span",{className:"filter-row-summary"},n))}else!n&&l&&l.remove()}}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(e=this.element)==null||e.remove(),this.element=null}}class Ve{constructor(e,t){this.state=e,this.filterManager=t,this.element=null,this._unsubscribers=[],this._onChange=null,this._onReset=null,this._onAction=null}render({onChange:e,onReset:t,onAction:i}={}){return this._onChange=e,this._onReset=t,this._onAction=i,this.element=h("div",{className:"controls-section","data-testid":"v2-controls-section"}),this._renderControls(),this._unsubscribers.push(this.state.on("change:selectedFilter",()=>this._renderControls()),this.state.on("change:activeFilters",()=>this._renderControls())),this.element}_renderControls(){this.element.innerHTML="";const e=this.state.get("selectedFilter");if(!e){this.element.appendChild(h("div",{className:"no-filter-selected"},"Select a filter to adjust"));return}const t=typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId"),i=this.filterManager.getFilterDef(e);if(!i){this.element.appendChild(h("div",{className:"no-filter-selected"},"Filter not found"));return}const s=h("div",{className:"controls-header"});s.appendChild(h("span",{className:"controls-title"},i.name)),s.appendChild(B({label:"Reset",className:"btn-text",onClick:()=>this._handleReset(e,t)})),this.element.appendChild(s);const r=h("div",{className:"controls-grid"}),a=this.state.getFilterValues(e);(i.controls||[]).forEach(n=>{if(n.hidden)return;const l=this._createControl(e,n,a[n.id]??n.default,t);l&&r.appendChild(l)});const o=this.filterManager.getInstance(e);if(o&&typeof o.getDynamicControls=="function"){let n=[];try{n=o.getDynamicControls()||[]}catch{}n.forEach(l=>{const c=l.property||l.id,d=a[c]??l.default,p=this._createControl(e,l,d,t);p&&r.appendChild(p)})}this.element.appendChild(r)}_createControl(e,t,i,s=null){if(t.hidden)return null;const r=t.label||t.id,a=this._normalizeControlType(t.type),o=t.property||t.id;switch(a){case"slider":return we({id:`v2-${e}-${t.id}`,label:r,min:t.min??0,max:t.max??1,step:t.step??.01,value:typeof i=="number"?i:t.default??0,onChange:n=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,o,n,s)}});case"toggle":return Ce({id:`v2-${e}-${t.id}`,label:r,checked:!!i,onChange:n=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,o,n,s)}});case"color":return ke({id:`v2-${e}-${t.id}`,label:r,value:typeof i=="string"&&i.startsWith("#")?i:t.default||"#000000",onChange:n=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,o,n,s)}});case"select":{const n=(t.options||[]).map(l=>typeof l=="object"&&l.value!==void 0?{value:l.value,label:l.label||String(l.value)}:{value:l,label:String(l)});return Se({id:`v2-${e}-${t.id}`,label:r,options:n,value:i??t.default,onChange:l=>{var c;return(c=this._onChange)==null?void 0:c.call(this,e,o,l,s)}})}case"text":return xe({id:`v2-${e}-${t.id}`,label:r,value:typeof i=="string"?i:t.default??"",placeholder:t.placeholder||"",onCommit:n=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,o,n,s)}});case"button":{const n=h("div",{className:"button-control"});return n.appendChild(B({label:r,className:"btn-secondary",onClick:()=>{var l;(l=this._onAction)==null||l.call(this,e,t.action||t.id,s),this._renderControls()}})),n}default:return null}}_normalizeControlType(e){return{slider:"slider",range:"slider",toggle:"toggle",checkbox:"toggle",color:"color",select:"select",dropdown:"select",button:"button",text:"text"}[e]||e}_handleReset(e,t=null){var i;(i=this._onReset)==null||i.call(this,e,t),this._renderControls()}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(e=this.element)==null||e.remove(),this.element=null}}class Bt{constructor(e,t){this.state=e,this.filterManager=t,this.element=null,this._unsubscribers=[],this._onRemove=null,this._onSelect=null,this._onClearAll=null}render({onRemove:e,onSelect:t,onClearAll:i}={}){return this._onRemove=e,this._onSelect=t,this._onClearAll=i,this.element=h("div",{className:"panel-section","data-testid":"v2-active-stack"}),this._renderContents(),this._unsubscribers.push(this.state.on("change:activeFilters",()=>this._renderContents()),this.state.on("change:selectedFilter",()=>this._refreshSelection())),this.element}_renderContents(){this.element.innerHTML="";const e=this.state.get("activeFilters"),t=(e==null?void 0:e.size)??0,i=this._activeFilterLayerId(),s=h("div",{className:"panel-section-title"});if(s.appendChild(h("span",{},`Active (${t})`)),t>0&&this._onClearAll&&s.appendChild(h("button",{type:"button",className:"btn btn-text",style:{padding:"2px 8px",fontSize:"11px"},"data-testid":"v2-clear-all",onClick:()=>{var o;return(o=this._onClearAll)==null?void 0:o.call(this,i)}},"Clear all")),this.element.appendChild(s),t===0){this.element.appendChild(h("div",{className:"active-empty"},"No filters applied"));return}const r=h("div",{className:"active-stack"}),a=this.state.get("selectedFilter");for(const o of e){const n=this.filterManager.getFilterDef(o);n&&r.appendChild(this._renderChip(n,o===a,i))}this.element.appendChild(r)}_renderChip(e,t,i=null){const s=h("div",{className:`active-chip ${t?"selected":""}`,"data-filter":e.id,"data-testid":`v2-active-${e.id}`});s.appendChild(h("button",{type:"button",className:"active-chip-name","aria-label":`Select ${e.name}`,onClick:()=>{var a;return(a=this._onSelect)==null?void 0:a.call(this,e.id,i)}},e.name));const r=h("button",{type:"button",className:"active-chip-remove","aria-label":`Remove ${e.name}`,"data-testid":`v2-active-remove-${e.id}`,onClick:()=>{var a;return(a=this._onRemove)==null?void 0:a.call(this,e.id,i)}});return r.innerHTML=se,s.appendChild(r),s}_activeFilterLayerId(){return typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId")}_refreshSelection(){var i;const e=this.state.get("selectedFilter"),t=(i=this.element)==null?void 0:i.querySelectorAll(".active-chip");t&&t.forEach(s=>{const r=s.getAttribute("data-filter");s.classList.toggle("selected",r===e)})}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(e=this.element)==null||e.remove(),this.element=null}}const Z=["collapsed","half","full"];class Nt{constructor(e={}){this._onSnapChange=e.onSnapChange||null,this._ariaLabel=e.ariaLabel||"Filter controls drawer",this.element=null,this._handle=null,this._body=null,this._headerSlot=null,this._snap="half",this._dragging=!1,this._dragStartY=0,this._dragStartHeight=0,this._dragPointerId=null,this._containerHeight=0}build({header:e,body:t}={}){this.element=h("div",{className:"editor-v2-drawer",role:"dialog","aria-label":this._ariaLabel,"data-testid":"v2-bottom-drawer","data-snap":this._snap}),this._handle=h("button",{type:"button",className:"drawer-handle","aria-label":"Drag to resize filters drawer","aria-expanded":this._snap==="full"?"true":"false","data-testid":"v2-drawer-handle"});const i=h("span",{className:"drawer-handle-grip","aria-hidden":"true"});return this._handle.appendChild(i),this._handle.addEventListener("click",s=>{if(this._wasDragging){this._wasDragging=!1,s.preventDefault();return}this._cycleSnap()}),this._handle.addEventListener("pointerdown",s=>this._onPointerDown(s)),this._handle.addEventListener("pointermove",s=>this._onPointerMove(s)),this._handle.addEventListener("pointerup",s=>this._onPointerEnd(s)),this._handle.addEventListener("pointercancel",s=>this._onPointerEnd(s)),this.element.appendChild(this._handle),this._headerSlot=h("div",{className:"drawer-header"}),e&&this._headerSlot.appendChild(e),this.element.appendChild(this._headerSlot),this._body=h("div",{className:"drawer-body"}),t&&this._body.appendChild(t),this.element.appendChild(this._body),this.element}updateContainerHeight(e){this._containerHeight=Math.max(0,Number(e)||0),this._applySnap(this._snap,{animate:!1})}snapTo(e,t={}){Z.includes(e)&&this._applySnap(e,{animate:t.animate!==!1})}get snap(){return this._snap}setBodyContent(e){this._body&&(this._body.innerHTML="",e&&this._body.appendChild(e))}setHeaderContent(e){this._headerSlot&&(this._headerSlot.innerHTML="",e&&this._headerSlot.appendChild(e))}_onPointerDown(e){var t,i,s;if(!(e.button!==void 0&&e.button!==0)){this._dragging=!0,this._wasDragging=!1,this._dragPointerId=e.pointerId,this._dragStartY=e.clientY,this._dragStartHeight=((t=this.element)==null?void 0:t.offsetHeight)||0;try{(s=(i=this._handle)==null?void 0:i.setPointerCapture)==null||s.call(i,e.pointerId)}catch{}this.element&&(this.element.style.transition="none")}}_onPointerMove(e){if(!this._dragging||e.pointerId!==this._dragPointerId)return;const t=e.clientY-this._dragStartY,i=this._dragStartHeight-t;this._containerHeight||window.innerHeight;const s=this._heightForSnap("collapsed"),r=this._heightForSnap("full"),a=Math.max(s,Math.min(r,i));this.element&&(this.element.style.height=`${a}px`),Math.abs(t)>4&&(this._wasDragging=!0),e.preventDefault()}_onPointerEnd(e){var s,r,a;if(!this._dragging)return;this._dragging=!1;try{(r=(s=this._handle)==null?void 0:s.releasePointerCapture)==null||r.call(s,e.pointerId)}catch{}this._dragPointerId=null;const t=((a=this.element)==null?void 0:a.offsetHeight)||0,i=this._nearestSnap(t);this._applySnap(i,{animate:!0})}_cycleSnap(){const e=Z.indexOf(this._snap),t=Z[(e+1)%Z.length];this._applySnap(t,{animate:!0})}_heightForSnap(e){const t=this._containerHeight||window.innerHeight||600;switch(e){case"collapsed":return 80;case"half":return Math.round(t*.45);case"full":return Math.round(t*.85);default:return Math.round(t*.45)}}_nearestSnap(e){let t=Z[0],i=1/0;for(const s of Z){const r=this._heightForSnap(s),a=Math.abs(r-e);a<i&&(i=a,t=s)}return t}_applySnap(e,{animate:t}){var r,a;if(!this.element)return;const i=this._snap;this._snap=e;const s=typeof window<"u"&&((r=window.matchMedia)==null?void 0:r.call(window,"(prefers-reduced-motion: reduce)").matches);t&&!s?this.element.style.transition="height 0.25s cubic-bezier(0.33, 1, 0.68, 1)":this.element.style.transition="none",this.element.style.height=`${this._heightForSnap(e)}px`,this.element.dataset.snap=e,this._handle&&this._handle.setAttribute("aria-expanded",e==="full"?"true":"false"),e!==i&&((a=this._onSnapChange)==null||a.call(this,e,i))}destroy(){var e;(e=this.element)==null||e.remove(),this.element=null,this._handle=null,this._body=null,this._headerSlot=null}}const It=[{id:"warm",label:"Warm",ariaLabel:"Apply warm gradient background",style:"linear-gradient(135deg, #101820 0%, #f2aa4c 100%)",fill:{gradientType:"linear",angle:135,stops:[{offset:0,color:"#101820"},{offset:1,color:"#f2aa4c"}]}},{id:"cool",label:"Cool",ariaLabel:"Apply cool gradient background",style:"linear-gradient(135deg, #0f766e 0%, #38bdf8 100%)",fill:{gradientType:"linear",angle:135,stops:[{offset:0,color:"#0f766e"},{offset:1,color:"#38bdf8"}]}},{id:"neutral",label:"Neutral",ariaLabel:"Apply neutral gradient background",style:"linear-gradient(135deg, #27272a 0%, #d4d4d8 100%)",fill:{gradientType:"linear",angle:135,stops:[{offset:0,color:"#27272a"},{offset:1,color:"#d4d4d8"}]}}];class $e{constructor(e,t){this.state=e,this.editor=t,this.element=null,this._errorMessage=null,this._unsubscribers=[]}render(){return this.element=h("div",{className:"background-panel","data-testid":"v2-background-panel"}),this._render(),this._unsubscribers.push(this.state.on("change:layers",()=>this._render())),this.element}_render(){var u,g,m;if(!this.element)return;this.element.innerHTML="";const e=this._backgroundLayer(),t=e!=null&&e.fill&&typeof e.fill=="object"?e.fill:{kind:"transparent"},i=typeof t.fit=="string"?t.fit:"cover",s=this._backgroundBlur(e),r=(e==null?void 0:e.locked)===!0,a=t.kind==="color"&&typeof t.value=="string"?t.value:"#ffffff";this.element.appendChild(h("div",{className:"panel-section-title"},h("span",{},"Background"))),this._errorMessage&&this.element.appendChild(h("p",{className:"background-panel-error",role:"alert","data-testid":"v2-background-error"},this._errorMessage));const o=h("input",{type:"color",className:"color-input",value:a,disabled:r?"disabled":void 0,"aria-label":"Background color","data-testid":"v2-background-color",onInput:f=>{this._runAction(this.editor.setBackgroundColor(f.target.value))}});this.element.appendChild(this._field("Color",o));const n=h("div",{className:"background-gradient-grid"});for(const f of It){const v=h("button",{type:"button",className:"background-gradient-swatch",style:{background:f.style},"aria-label":f.ariaLabel,disabled:r?"disabled":void 0,"data-testid":`v2-background-gradient-${f.id}`,onClick:()=>{this._runAction(this.editor.setBackgroundGradient(f.fill))}},h("span",{className:"background-gradient-label"},f.label));n.appendChild(v)}this.element.appendChild(this._field("Gradient",n));const l=h("input",{type:"file",accept:"image/*",className:"background-upload-input",disabled:r?"disabled":void 0,"aria-label":"Upload background image","data-testid":"v2-background-upload",onChange:f=>{var k;const v=(k=f.target.files)==null?void 0:k[0];v&&this._runAction(this.editor.setBackgroundImageFromFile(v,{fit:i})),f.target.value=""}});this.element.appendChild(this._field("Upload",l));const c=(m=(g=(u=this.editor)==null?void 0:u._options)==null?void 0:g.backgroundReplacement)==null?void 0:m.mediaChoices;if(Array.isArray(c)&&c.length>0){const f=h("div",{className:"background-media-grid"});for(const v of c)v!=null&&v.source&&f.appendChild(h("button",{type:"button",className:"background-media-choice","aria-label":`Use ${v.label||"media"} as background`,disabled:r?"disabled":void 0,"data-testid":`v2-background-media-${v.id||v.source.mediaUuid||"choice"}`,onClick:()=>{this._runAction(this.editor.setBackgroundMediaSource(v.source,{fit:v.fit||i}))}},v.label||"Media"));this.element.appendChild(this._field("Media",f))}const d=h("select",{className:"select-input",disabled:r?"disabled":void 0,"aria-label":"Background image fit","data-testid":"v2-background-fit",onChange:f=>{this._runAction(this.editor.setBackgroundFit(f.target.value))}},this._option("cover","Cover",i),this._option("contain","Contain",i),this._option("stretch","Stretch",i),this._option("tile","Tile",i));this.element.appendChild(this._field("Fit",d));const p=h("input",{type:"range",min:"0",max:"40",step:"1",value:String(s),className:"range-input",disabled:r?"disabled":void 0,"aria-label":"Background blur","data-testid":"v2-background-blur",onInput:f=>{this._runAction(this.editor.setBackgroundBlur(Number(f.target.value)))}});this.element.appendChild(this._field("Blur",p)),this.element.appendChild(h("button",{type:"button",className:"btn btn-secondary background-remove-btn","aria-label":"Remove background layer",disabled:r?"disabled":void 0,"data-testid":"v2-background-remove",onClick:()=>{this._runAction(this.editor.removeBackgroundLayer())}},"Remove"))}_runAction(e){this._errorMessage=null,Promise.resolve(e).catch(t=>{var s,r;const i=t instanceof Error?t:new Error(String(t));this._errorMessage=i.message||"Background update failed",(r=(s=this.editor)==null?void 0:s.emit)==null||r.call(s,"error",i),this._render()})}_field(e,t){return h("label",{className:"background-field"},h("span",{className:"background-field-label"},e),t)}_option(e,t,i){return h("option",{value:e,selected:i===e?"selected":void 0},t)}_backgroundLayer(){const e=this.state.get("layers");return Array.isArray(e)?e.find(t=>(t==null?void 0:t.type)==="background"||(t==null?void 0:t.role)==="background")??null:null}_backgroundBlur(e){var r;const i=(Array.isArray(e==null?void 0:e.effects)?e.effects:[]).find(a=>(a==null?void 0:a.id)==="background-blur"),s=Number((r=i==null?void 0:i.params)==null?void 0:r.amount);return Number.isFinite(s)?s:0}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(e=this.element)==null||e.remove(),this.element=null}}class We{constructor(e,t){this.state=e,this.editor=t,this.element=null,this._listEl=null,this._unsubscribers=[]}render(){return this.element=h("section",{className:"layer-stack-panel",role:"region","aria-label":"Layers","data-order":"bottom-to-top","data-testid":"v2-layer-stack-panel"}),this.element.appendChild(h("div",{className:"layer-stack-header"},h("span",{className:"layer-stack-title"},"Layers"),h("span",{className:"layer-stack-order"},"Bottom to top"))),this._listEl=h("div",{className:"layer-stack-list",role:"listbox","aria-label":"Layer order, bottom to top"}),this.element.appendChild(this._listEl),this._renderRows(),this._unsubscribers.push(this.state.on("change:layers",()=>this._renderRows()),this.state.on("change:activeLayerId",()=>this._renderRows())),this.element}_layers(){const e=this.state.get("layers");return Array.isArray(e)?e:[]}_renderRows(){if(!this._listEl)return;this._listEl.innerHTML="";const e=this._layers();if(!e.length){this._listEl.appendChild(h("div",{className:"layer-stack-empty",role:"status"},"No layers"));return}e.forEach((t,i)=>{this._listEl.appendChild(this._row(t,i,e.length))})}_row(e,t,i){const s=String((e==null?void 0:e.id)??""),r=this._layerName(e),a=(e==null?void 0:e.visible)!==!1,o=(e==null?void 0:e.locked)===!0,n=this.state.get("activeLayerId")===s,l=[n?"active":null,a?"visible":"hidden",o?"locked":"unlocked"].filter(Boolean).join(", "),c=h("div",{className:`layer-row${n?" active":""}${a?"":" hidden"}${o?" locked":""}`,role:"option","aria-selected":n?"true":"false","aria-label":`${r}, ${this._layerTypeLabel(e)}, ${l}`,"data-layer-id":s,"data-testid":`v2-layer-row-${s}`});c.appendChild(this._button({testId:`v2-layer-select-${s}`,label:`Select ${r}`,className:"layer-row-select",onClick:()=>this._runAction(()=>{var p,u;return(u=(p=this.editor).selectLayer)==null?void 0:u.call(p,s)})},this._thumbnail(e))),c.appendChild(h("div",{className:"layer-row-main"},h("span",{className:"layer-row-name"},r),h("span",{className:"layer-row-meta"},this._layerTypeLabel(e))));const d=h("div",{className:"layer-row-actions"});return d.appendChild(this._iconButton({testId:`v2-layer-${a?"hide":"show"}-${s}`,label:`${a?"Hide":"Show"} ${r}`,icon:a?lt:ht,disabled:o,onClick:()=>this._runAction(()=>{var p,u;return(u=(p=this.editor).setLayerVisibility)==null?void 0:u.call(p,s,!a)})})),d.appendChild(this._iconButton({testId:`v2-layer-${o?"unlock":"lock"}-${s}`,label:`${o?"Unlock":"Lock"} ${r}`,icon:o?ct:dt,onClick:()=>this._runAction(()=>{var p,u;return(u=(p=this.editor).setLayerLocked)==null?void 0:u.call(p,s,!o)})})),d.appendChild(this._iconButton({testId:`v2-layer-move-up-${s}`,label:`Move ${r} up`,icon:ie,disabled:o,onClick:()=>this._runAction(()=>{var p,u;return(u=(p=this.editor).moveLayer)==null?void 0:u.call(p,s,"up")})})),d.appendChild(this._iconButton({testId:`v2-layer-move-down-${s}`,label:`Move ${r} down`,icon:te,disabled:o,onClick:()=>this._runAction(()=>{var p,u;return(u=(p=this.editor).moveLayer)==null?void 0:u.call(p,s,"down")})})),d.appendChild(this._iconButton({testId:`v2-layer-bring-front-${s}`,label:`Bring ${r} to front`,icon:ie,disabled:o,onClick:()=>this._runAction(()=>{var p,u;return(u=(p=this.editor).moveLayer)==null?void 0:u.call(p,s,"front")})})),d.appendChild(this._iconButton({testId:`v2-layer-send-back-${s}`,label:`Send ${r} to back`,icon:te,disabled:o,onClick:()=>this._runAction(()=>{var p,u;return(u=(p=this.editor).moveLayer)==null?void 0:u.call(p,s,"back")})})),d.appendChild(this._iconButton({testId:`v2-layer-rename-${s}`,label:`Rename ${r}`,icon:ut,disabled:o,onClick:()=>this._renameLayer(s,r)})),d.appendChild(this._iconButton({testId:`v2-layer-duplicate-${s}`,label:`Duplicate ${r}`,icon:pt,disabled:o,onClick:()=>this._runAction(()=>{var p,u;return(u=(p=this.editor).duplicateLayer)==null?void 0:u.call(p,s)})})),d.appendChild(this._iconButton({testId:`v2-layer-delete-${s}`,label:`Delete ${r}`,icon:Ne,disabled:o||i<=1,onClick:()=>this._runAction(()=>{var p,u;return(u=(p=this.editor).deleteLayer)==null?void 0:u.call(p,s)})})),c.appendChild(d),c}_thumbnail(e){const t=h("span",{className:"layer-thumb","aria-hidden":"true"}),i=e==null?void 0:e.fill;if((i==null?void 0:i.kind)==="color")t.style.background=i.value||i.color||"#ffffff";else if((i==null?void 0:i.kind)==="gradient"&&Array.isArray(i.stops)){const s=i.stops.map(r=>`${r.color} ${Math.round(Number(r.offset||0)*100)}%`).join(", ");t.style.background=`linear-gradient(${Number(i.angle||135)}deg, ${s})`}else t.innerHTML=(e==null?void 0:e.type)==="background"?Ie:Ee;return t}_button({testId:e,label:t,...i},s){const r=h("button",{type:"button","aria-label":t,"data-testid":e,...i});return s&&r.appendChild(s),r}_iconButton({testId:e,label:t,icon:i,disabled:s=!1,onClick:r}){const a=h("button",{type:"button",className:"layer-action-btn","aria-label":t,title:t,disabled:s?"disabled":void 0,"data-testid":e,onClick:r});return a.innerHTML=i,a}_renameLayer(e,t){var s;const i=(s=window.prompt)==null?void 0:s.call(window,"Layer name",t);typeof i=="string"&&this._runAction(()=>{var r,a;return(a=(r=this.editor).renameLayer)==null?void 0:a.call(r,e,i)})}_runAction(e){var t,i;try{Promise.resolve(e()).catch(s=>{var r,a;return(a=(r=this.editor).emit)==null?void 0:a.call(r,"error",{error:s,context:"layer-stack"})})}catch(s){(i=(t=this.editor).emit)==null||i.call(t,"error",{error:s,context:"layer-stack"})}}_layerName(e){return(typeof(e==null?void 0:e.name)=="string"?e.name.trim():"")||"Layer"}_layerTypeLabel(e){return(e==null?void 0:e.type)==="background"||(e==null?void 0:e.role)==="background"?"Background":(e==null?void 0:e.role)==="subject"?"Subject":(e==null?void 0:e.type)==="text"?"Text":"Image"}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(e=this.element)==null||e.remove(),this.element=null,this._listEl=null}}const Dt=[{value:"400",label:"Regular"},{value:"500",label:"Medium"},{value:"600",label:"Semibold"},{value:"700",label:"Bold"},{value:"800",label:"Heavy"}],zt=[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}],Ot=[{value:"normal",label:"Normal"},{value:"multiply",label:"Multiply"},{value:"screen",label:"Screen"},{value:"overlay",label:"Overlay"}],de={stroke:{enabled:!1,color:"#000000",width:0},shadow:{enabled:!1,color:"#000000",alpha:.5,blur:0,distance:0,angle:45},glow:{enabled:!1,color:"#ffffff",alpha:.5,blur:0},backdrop:{enabled:!1,color:"#000000",opacity:.5,padding:0,radius:0,blur:0}};class qe{constructor(e,t){this.state=e,this.editor=t,this.element=null,this._errorMessage=null,this._unsubscribers=[]}render(){return this.element=h("div",{className:"text-panel","data-testid":"v2-text-panel"}),this._render(),this._unsubscribers.push(this.state.on("change:layers",()=>this._render()),this.state.on("change:activeLayerId",()=>this._render())),this.element}_render(){if(!this.element)return;this.element.innerHTML="";const e=this._activeTextLayer(),t=(e==null?void 0:e.locked)===!0;if(this.element.appendChild(h("div",{className:"text-panel-header"},h("div",{className:"panel-section-title"},h("span",{},"Text")),h("button",{type:"button",className:"btn btn-secondary","data-testid":"v2-text-add",onClick:()=>{var n,l;return this._runAction((l=(n=this.editor).addTextLayer)==null?void 0:l.call(n))}},"Add text"))),this._errorMessage&&this.element.appendChild(h("p",{className:"text-panel-error",role:"alert","data-testid":"v2-text-error"},this._errorMessage)),!e){this.element.appendChild(h("p",{className:"text-panel-empty"},"Select or add a text layer."));return}const i=e.text&&typeof e.text=="object"?e.text:{},s=i.style&&typeof i.style=="object"?i.style:{},r=i.box&&typeof i.box=="object"?i.box:{},a=e.transform&&typeof e.transform=="object"?e.transform:{},o=this._textEffects(i.effects);this.element.appendChild(this._contentControl(e.id,i.content??"",t)),this.element.appendChild(this._controlGrid([this._numberField({label:"Opacity",testId:"v2-text-opacity",value:e.opacity??1,min:0,max:1,step:.05,disabled:t,onInput:n=>{var l,c;return this._runAction((c=(l=this.editor).updateTextLayer)==null?void 0:c.call(l,e.id,{opacity:n}))}}),this._selectField({label:"Blend",testId:"v2-text-blend-mode",value:e.blendMode||"normal",options:Ot,disabled:t,onChange:n=>{var l,c;return this._runAction((c=(l=this.editor).updateTextLayer)==null?void 0:c.call(l,e.id,{blendMode:n}))}})])),this.element.appendChild(this._selectField({label:"Font",testId:"v2-text-font-family",value:s.fontFamily||"Inter",options:U.TEXT_LAYER_FONT_FAMILIES.map(n=>({value:n,label:n})),disabled:t,onChange:n=>this._updateStyle(e.id,{fontFamily:n})})),this.element.appendChild(this._controlGrid([this._numberField({label:"Size",testId:"v2-text-font-size",value:s.fontSize??64,min:8,max:400,step:1,disabled:t,onInput:n=>this._updateStyle(e.id,{fontSize:n})}),this._selectField({label:"Weight",testId:"v2-text-font-weight",value:String(s.fontWeight??700),options:Dt,disabled:t,onChange:n=>this._updateStyle(e.id,{fontWeight:Number(n)})}),this._selectField({label:"Style",testId:"v2-text-font-style",value:s.fontStyle||"normal",options:[{value:"normal",label:"Normal"},{value:"italic",label:"Italic"}],disabled:t,onChange:n=>this._updateStyle(e.id,{fontStyle:n})}),this._selectField({label:"Align",testId:"v2-text-align",value:s.align||"center",options:zt,disabled:t,onChange:n=>this._updateStyle(e.id,{align:n})})])),this.element.appendChild(this._controlGrid([this._colorField({label:"Fill",testId:"v2-text-fill",value:s.fill||"#ffffff",disabled:t,onInput:n=>this._updateStyle(e.id,{fill:n})}),this._numberField({label:"Line",testId:"v2-text-line-height",value:s.lineHeight??1.2,min:.8,max:3,step:.05,disabled:t,onInput:n=>this._updateStyle(e.id,{lineHeight:n})}),this._numberField({label:"Track",testId:"v2-text-letter-spacing",value:s.letterSpacing??0,min:-100,max:100,step:.5,disabled:t,onInput:n=>this._updateStyle(e.id,{letterSpacing:n})})])),this.element.appendChild(this._controlGrid([this._numberField({label:"X",testId:"v2-text-box-x",value:r.x??.2,min:0,max:1,step:.01,disabled:t,onInput:n=>this._updateBox(e.id,{x:n})}),this._numberField({label:"Y",testId:"v2-text-box-y",value:r.y??.2,min:0,max:1,step:.01,disabled:t,onInput:n=>this._updateBox(e.id,{y:n})}),this._numberField({label:"W",testId:"v2-text-box-width",value:r.width??.6,min:.05,max:1,step:.01,disabled:t,onInput:n=>this._updateBox(e.id,{width:n})}),this._numberField({label:"H",testId:"v2-text-box-height",value:r.height??.18,min:.05,max:1,step:.01,disabled:t,onInput:n=>this._updateBox(e.id,{height:n})}),this._numberField({label:"Rotate",testId:"v2-text-rotation",value:a.rotation??0,min:0,max:360,step:1,disabled:t,onInput:n=>{var l,c;return this._runAction((c=(l=this.editor).updateTextLayer)==null?void 0:c.call(l,e.id,{transform:{rotation:n}}))}})])),this.element.appendChild(this._effectSection("Stroke",[this._checkboxField({label:"Stroke",testId:"v2-text-stroke-enabled",checked:o.stroke.enabled,disabled:t,onChange:n=>this._updateEffects(e.id,{stroke:{enabled:n}})}),this._colorField({label:"Stroke Color",testId:"v2-text-stroke-color",value:o.stroke.color,disabled:t,onInput:n=>this._updateEffects(e.id,{stroke:{color:n}})}),this._numberField({label:"Stroke Width",testId:"v2-text-stroke-width",value:o.stroke.width,min:0,max:80,step:1,disabled:t,onInput:n=>this._updateEffects(e.id,{stroke:{width:n}})})])),this.element.appendChild(this._effectSection("Shadow",[this._checkboxField({label:"Shadow",testId:"v2-text-shadow-enabled",checked:o.shadow.enabled,disabled:t,onChange:n=>this._updateEffects(e.id,{shadow:{enabled:n}})}),this._colorField({label:"Shadow Color",testId:"v2-text-shadow-color",value:o.shadow.color,disabled:t,onInput:n=>this._updateEffects(e.id,{shadow:{color:n}})}),this._numberField({label:"Shadow Alpha",testId:"v2-text-shadow-alpha",value:o.shadow.alpha,min:0,max:1,step:.05,disabled:t,onInput:n=>this._updateEffects(e.id,{shadow:{alpha:n}})}),this._numberField({label:"Shadow Blur",testId:"v2-text-shadow-blur",value:o.shadow.blur,min:0,max:120,step:1,disabled:t,onInput:n=>this._updateEffects(e.id,{shadow:{blur:n}})}),this._numberField({label:"Shadow Distance",testId:"v2-text-shadow-distance",value:o.shadow.distance,min:0,max:200,step:1,disabled:t,onInput:n=>this._updateEffects(e.id,{shadow:{distance:n}})}),this._numberField({label:"Shadow Angle",testId:"v2-text-shadow-angle",value:o.shadow.angle,min:0,max:360,step:1,disabled:t,onInput:n=>this._updateEffects(e.id,{shadow:{angle:n}})})])),this.element.appendChild(this._effectSection("Glow",[this._checkboxField({label:"Glow",testId:"v2-text-glow-enabled",checked:o.glow.enabled,disabled:t,onChange:n=>this._updateEffects(e.id,{glow:{enabled:n}})}),this._colorField({label:"Glow Color",testId:"v2-text-glow-color",value:o.glow.color,disabled:t,onInput:n=>this._updateEffects(e.id,{glow:{color:n}})}),this._numberField({label:"Glow Alpha",testId:"v2-text-glow-alpha",value:o.glow.alpha,min:0,max:1,step:.05,disabled:t,onInput:n=>this._updateEffects(e.id,{glow:{alpha:n}})}),this._numberField({label:"Glow Blur",testId:"v2-text-glow-blur",value:o.glow.blur,min:0,max:120,step:1,disabled:t,onInput:n=>this._updateEffects(e.id,{glow:{blur:n}})})])),this.element.appendChild(this._effectSection("Backdrop",[this._checkboxField({label:"Backdrop",testId:"v2-text-backdrop-enabled",checked:o.backdrop.enabled,disabled:t,onChange:n=>this._updateEffects(e.id,{backdrop:{enabled:n}})}),this._colorField({label:"Backdrop Color",testId:"v2-text-backdrop-color",value:o.backdrop.color,disabled:t,onInput:n=>this._updateEffects(e.id,{backdrop:{color:n}})}),this._numberField({label:"Backdrop Opacity",testId:"v2-text-backdrop-opacity",value:o.backdrop.opacity,min:0,max:1,step:.05,disabled:t,onInput:n=>this._updateEffects(e.id,{backdrop:{opacity:n}})}),this._numberField({label:"Backdrop Padding",testId:"v2-text-backdrop-padding",value:o.backdrop.padding,min:0,max:200,step:1,disabled:t,onInput:n=>this._updateEffects(e.id,{backdrop:{padding:n}})}),this._numberField({label:"Backdrop Radius",testId:"v2-text-backdrop-radius",value:o.backdrop.radius,min:0,max:200,step:1,disabled:t,onInput:n=>this._updateEffects(e.id,{backdrop:{radius:n}})}),this._numberField({label:"Backdrop Blur",testId:"v2-text-backdrop-blur",value:o.backdrop.blur,min:0,max:80,step:1,disabled:t,onInput:n=>this._updateEffects(e.id,{backdrop:{blur:n}})})]))}_contentControl(e,t,i){const s=h("div",{className:"text-field text-content-field"});s.appendChild(h("label",{className:"text-field-label",for:"v2-text-content"},"Content"));let r=t==null?"":String(t);const a=h("textarea",{id:"v2-text-content",className:"text-area-input",rows:"4",disabled:i?"disabled":void 0,"data-testid":"v2-text-content",onInput:n=>{r=n.target.value},onBlur:()=>{var n,l;r!==t&&this._runAction((l=(n=this.editor).updateTextLayer)==null?void 0:l.call(n,e,{content:r}))},onKeyDown:n=>{var l,c;if(n.key==="Escape"){n.preventDefault(),r=t==null?"":String(t),a.value=r,a.blur();return}n.key==="Enter"&&(n.metaKey||n.ctrlKey)&&(n.preventDefault(),this._runAction((c=(l=this.editor).updateTextLayer)==null?void 0:c.call(l,e,{content:r})),a.blur())}});a.value=r,s.appendChild(a);const o=h("div",{className:"text-content-actions"});return o.appendChild(h("button",{type:"button",className:"btn btn-text",disabled:i?"disabled":void 0,"data-testid":"v2-text-cancel",onClick:()=>{r=t==null?"":String(t),a.value=r}},"Cancel")),o.appendChild(h("button",{type:"button",className:"btn btn-secondary",disabled:i?"disabled":void 0,"data-testid":"v2-text-commit",onClick:()=>{var n,l;return this._runAction((l=(n=this.editor).updateTextLayer)==null?void 0:l.call(n,e,{content:r}))}},"Commit")),s.appendChild(o),s}_controlGrid(e){const t=h("div",{className:"text-control-grid"});for(const i of e)t.appendChild(i);return t}_effectSection(e,t){return h("div",{className:"text-effect-section"},h("div",{className:"text-effect-title"},e),this._controlGrid(t))}_selectField({label:e,testId:t,value:i,options:s,disabled:r,onChange:a}){const o=h("select",{className:"select-input",disabled:r?"disabled":void 0,"data-testid":t,onChange:n=>a(n.target.value)});for(const n of s)o.appendChild(h("option",{value:n.value,selected:String(i)===String(n.value)?"selected":void 0},n.label));return this._field(e,o)}_numberField({label:e,testId:t,value:i,min:s,max:r,step:a,disabled:o,onInput:n}){const l=h("input",{type:"number",className:"text-number-input",min:String(s),max:String(r),step:String(a),value:String(i),disabled:o?"disabled":void 0,"data-testid":t,onInput:c=>n(Number(c.target.value))});return this._field(e,l)}_colorField({label:e,testId:t,value:i,disabled:s,onInput:r}){const a=h("input",{type:"color",className:"color-input",value:i,disabled:s?"disabled":void 0,"data-testid":t,onInput:o=>r(o.target.value)});return this._field(e,a)}_checkboxField({label:e,testId:t,checked:i,disabled:s,onChange:r}){const a=h("input",{type:"checkbox",className:"text-checkbox-input",checked:i?"checked":void 0,disabled:s?"disabled":void 0,"data-testid":t,onChange:o=>r(o.target.checked===!0)});return h("label",{className:"text-field text-checkbox-field"},h("span",{className:"text-field-label"},e),a)}_field(e,t){return h("label",{className:"text-field"},h("span",{className:"text-field-label"},e),t)}_updateStyle(e,t){var i,s;this._runAction((s=(i=this.editor).updateTextLayer)==null?void 0:s.call(i,e,{style:t}))}_updateBox(e,t){var i,s;this._runAction((s=(i=this.editor).updateTextLayer)==null?void 0:s.call(i,e,{box:t}))}_updateEffects(e,t){var i,s;this._runAction((s=(i=this.editor).updateTextLayer)==null?void 0:s.call(i,e,{effects:t}))}_textEffects(e){const t=e&&typeof e=="object"?e:{};return{stroke:{...de.stroke,...t.stroke&&typeof t.stroke=="object"?t.stroke:{}},shadow:{...de.shadow,...t.shadow&&typeof t.shadow=="object"?t.shadow:{}},glow:{...de.glow,...t.glow&&typeof t.glow=="object"?t.glow:{}},backdrop:{...de.backdrop,...t.backdrop&&typeof t.backdrop=="object"?t.backdrop:{}}}}_runAction(e){this._errorMessage=null,Promise.resolve(e).catch(t=>{var s,r;const i=t instanceof Error?t:new Error(String(t));this._errorMessage=i.message||"Text update failed",(r=(s=this.editor)==null?void 0:s.emit)==null||r.call(s,"error",i),this._render()})}_activeTextLayer(){const e=this.state.get("activeLayerId"),t=this.state.get("layers");return!e||!Array.isArray(t)?null:t.find(i=>(i==null?void 0:i.id)===e&&(i.type==="text"||i.role==="text"))??null}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(e=this.element)==null||e.remove(),this.element=null}}class Pt{constructor(e,t,i){this.state=e,this.filterManager=t,this.editor=i,this.element=null,this._headerEl=null,this._bodyEl=null,this._view="categories",this._onNavigate=null,this._callbacks=null,this._unsubscribers=[],this._categoryTabs=null,this._filterListView=null,this._filterControlsView=null,this._backgroundPanel=null,this._layerStackPanel=null,this._textPanel=null}build(e){return this._callbacks=e,this._onNavigate=e.onViewChange||null,this.element=h("div",{className:"drawer-nav","data-testid":"v2-mobile-nav"}),this._headerEl=h("div",{className:"drawer-nav-header"}),this.element.appendChild(this._headerEl),this._bodyEl=h("div",{className:"drawer-nav-body"}),this.element.appendChild(this._bodyEl),this._buildViews(),this._unsubscribers.push(this.state.on("change:selectedFilter",({value:t})=>{t&&this._view!=="controls"&&this.navigateTo("controls")}),this.state.on("change:selectedCategory",()=>{}),this.state.on("change:mode",({value:t})=>{t==="filters"&&this._view!=="categories"&&!this.state.get("selectedFilter")&&this.navigateTo("categories")})),this.navigateTo("categories"),this.element}_buildViews(){this._categoryTabs=new Ue(this.state,this.editor),this._categoryTabsEl=this._categoryTabs.render({onSelect:e=>{if(e==="background"||e==="layers"||e==="text"){this.navigateTo(e);return}this.navigateTo("filters")}}),this._filterListView=new He(this.state,this.filterManager),this._filterListEl=this._filterListView.render({onToggle:(e,t,i)=>this._callbacks.onFilterToggle(e,t,i),onSelect:(e,t)=>{this._callbacks.onFilterSelect(e,t),this.navigateTo("controls")}}),this._filterControlsView=new Ve(this.state,this.filterManager),this._filterControlsEl=this._filterControlsView.render({onChange:(e,t,i,s)=>this._callbacks.onFilterChange(e,t,i,s),onReset:(e,t)=>this._callbacks.onFilterReset(e,t),onAction:(e,t,i)=>this._callbacks.onFilterAction(e,t,i)}),this._backgroundPanel=new $e(this.state,this.editor),this._backgroundPanelEl=this._backgroundPanel.render(),this._layerStackPanel=new We(this.state,this.editor),this._layerStackPanelEl=this._layerStackPanel.render(),this._textPanel=new qe(this.state,this.editor),this._textPanelEl=this._textPanel.render()}navigateTo(e){var i;if(!this.element)return;this._view=e,this._renderHeader(),this._bodyEl.innerHTML="";let t=null;switch(e){case"categories":t=this._categoryTabsEl;break;case"filters":t=this._filterListEl;break;case"controls":t=this._filterControlsEl;break;case"background":t=this._backgroundPanelEl;break;case"layers":t=this._layerStackPanelEl;break;case"text":t=this._textPanelEl;break;default:t=this._categoryTabsEl}t&&this._bodyEl.appendChild(t),(i=this._onNavigate)==null||i.call(this,e)}_renderHeader(){if(!this._headerEl)return;if(this._headerEl.innerHTML="",this._view!=="categories"){const i=h("button",{type:"button",className:"drawer-back-btn","aria-label":"Go back","data-testid":"v2-drawer-back",onClick:()=>this._goBack()});i.innerHTML=te,this._headerEl.appendChild(i)}const t=this._titleForView(this._view);if(this._headerEl.appendChild(h("h2",{className:"drawer-nav-title"},t)),this._view==="controls"){const i=this.state.get("selectedFilter");if(i){const s=this._activeFilterLayerId();this._headerEl.appendChild(B({label:"Reset",className:"btn-text",onClick:()=>this._callbacks.onFilterReset(i,s)}))}}}_activeFilterLayerId(){return typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId")}_titleForView(e){switch(e){case"categories":return"Filters";case"filters":{const t=this.state.get("selectedCategory");return this._categoryLabel(t)||"Filters"}case"background":return"Background";case"layers":return"Layers";case"text":return"Text";case"controls":{const t=this.state.get("selectedFilter"),i=t?this.filterManager.getFilterDef(t):null;return(i==null?void 0:i.name)||"Filter"}default:return""}}_categoryLabel(e){var t;return e&&((t=re.find(i=>i.id===e))==null?void 0:t.name)||null}_goBack(){this._view==="controls"?(this.state.set("selectedFilter",null),this.navigateTo("filters")):(this._view==="filters"||this._view==="background"||this._view==="layers"||this._view==="text")&&this.navigateTo("categories")}get currentView(){return this._view}destroy(){var e,t,i,s,r,a,o;this._unsubscribers.forEach(n=>n()),this._unsubscribers=[],(e=this._categoryTabs)==null||e.destroy(),(t=this._filterListView)==null||t.destroy(),(i=this._filterControlsView)==null||i.destroy(),(s=this._backgroundPanel)==null||s.destroy(),(r=this._layerStackPanel)==null||r.destroy(),(a=this._textPanel)==null||a.destroy(),(o=this.element)==null||o.remove(),this.element=null}}class jt{constructor(e,t){this.state=e,this.filterManager=t,this.element=null,this._onSelect=null,this._onRemove=null,this._unsubscribers=[]}render({onSelect:e,onRemove:t}={}){return this._onSelect=e,this._onRemove=t,this.element=h("div",{className:"mobile-active-chips",role:"region","aria-label":"Active filters","data-testid":"v2-mobile-active-chips"}),this._renderChips(),this._unsubscribers.push(this.state.on("change:activeFilters",()=>this._renderChips()),this.state.on("change:selectedFilter",()=>this._refreshSelection())),this.element}_renderChips(){this.element.innerHTML="";const e=this.state.get("activeFilters");if(((e==null?void 0:e.size)??0)===0){this.element.style.display="none";return}this.element.style.display="";const i=h("div",{className:"mobile-active-track"}),s=this.state.get("selectedFilter"),r=this._activeFilterLayerId();for(const a of e){const o=this.filterManager.getFilterDef(a);o&&i.appendChild(this._renderChip(o,a===s,r))}this.element.appendChild(i)}_renderChip(e,t,i=null){const s=h("div",{className:`mobile-active-chip ${t?"selected":""}`,"data-filter":e.id,"data-testid":`v2-mobile-chip-${e.id}`});s.appendChild(h("button",{type:"button",className:"mobile-active-chip-name","aria-label":`Edit ${e.name}`,onClick:()=>{var a;return(a=this._onSelect)==null?void 0:a.call(this,e.id,i)}},e.name));const r=h("button",{type:"button",className:"mobile-active-chip-remove","aria-label":`Remove ${e.name}`,"data-testid":`v2-mobile-chip-remove-${e.id}`,onClick:a=>{var o;a.stopPropagation(),(o=this._onRemove)==null||o.call(this,e.id,i)}});return r.innerHTML=se,s.appendChild(r),s}_activeFilterLayerId(){return typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId")}_refreshSelection(){var i;const e=this.state.get("selectedFilter"),t=(i=this.element)==null?void 0:i.querySelectorAll(".mobile-active-chip");t==null||t.forEach(s=>{const r=s.getAttribute("data-filter");s.classList.toggle("selected",r===e)})}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(e=this.element)==null||e.remove(),this.element=null}}const Re="(max-width: 900px)";class Ut{constructor(e,t,i){this.state=e,this.filterManager=t,this.editor=i,this.root=null,this.canvasSection=null,this.canvasContainer=null,this.cropOverlay=null,this._callbacks=null,this._isMobile=!1,this._panel=null,this._categoryTabs=null,this._filterListView=null,this._filterControlsView=null,this._activeStack=null,this._backgroundPanel=null,this._layerStackPanel=null,this._textPanel=null,this._desktopBackgroundSection=null,this._desktopLayerSection=null,this._desktopTextSection=null,this._desktopFilterListSection=null,this._desktopCropWrapper=null,this._mobileChips=null,this._mobileDrawer=null,this._mobileNav=null,this._mobileCropWrapper=null,this._cropControlsEl=null,this._unsubscribers=[],this._mql=null,this._mqlHandler=null,this._resizeObserver=null}build(e){var t;return this._callbacks=e,this.root=h("div",{className:"editor-v2-body"}),this.canvasSection=h("div",{className:"editor-v2-canvas"}),this.canvasContainer=h("div",{className:"canvas-container"}),this.cropOverlay=h("canvas",{className:"crop-overlay","aria-hidden":"true"}),this.canvasSection.appendChild(this.canvasContainer),this.canvasSection.appendChild(this.cropOverlay),this._zoomOverlay=this._buildCanvasZoomOverlay(),this.canvasSection.appendChild(this._zoomOverlay),this.root.appendChild(this.canvasSection),this._isMobile=typeof window<"u"&&((t=window.matchMedia)==null?void 0:t.call(window,Re).matches)===!0,this._isMobile?this._buildMobileShell():this._buildDesktopShell(),typeof window<"u"&&window.matchMedia&&(this._mql=window.matchMedia(Re),this._mqlHandler=i=>this._handleBreakpointChange(i.matches),this._mql.addEventListener?this._mql.addEventListener("change",this._mqlHandler):this._mql.addListener&&this._mql.addListener(this._mqlHandler)),this._unsubscribers.push(this.state.on("change:mode",({value:i})=>this._applyMode(i)),this.state.on("change:selectedCategory",()=>this._applyMode(this.state.get("mode")))),{root:this.root,canvasContainer:this.canvasContainer,cropOverlay:this.cropOverlay}}mountCropControls(e){this._cropControlsEl=e,this._mountCropControlsInActiveShell()}_buildDesktopShell(){this._panel=h("div",{className:"editor-v2-panel","data-testid":"v2-inspector-panel"}),this._categoryTabs=new Ue(this.state,this.editor),this._panel.appendChild(this._categoryTabs.render({onSelect:()=>this._handleDesktopCategoryChange()}));const e=h("div",{className:"panel-body"});this._desktopFilterListSection=h("div",{className:"panel-section"}),this._desktopFilterListSection.appendChild(h("div",{className:"panel-section-title"},h("span",{},"Filters"))),this._filterListView=new He(this.state,this.filterManager),this._desktopFilterListSection.appendChild(this._filterListView.render({onToggle:(t,i,s)=>this._callbacks.onFilterToggle(t,i,s),onSelect:(t,i)=>this._callbacks.onFilterSelect(t,i)})),e.appendChild(this._desktopFilterListSection),this._filterControlsView=new Ve(this.state,this.filterManager),e.appendChild(this._filterControlsView.render({onChange:(t,i,s,r)=>this._callbacks.onFilterChange(t,i,s,r),onReset:(t,i)=>this._callbacks.onFilterReset(t,i),onAction:(t,i,s)=>this._callbacks.onFilterAction(t,i,s)})),this._desktopCropWrapper=h("div",{className:"crop-controls-wrapper",style:{display:"none"}}),e.appendChild(this._desktopCropWrapper),this._activeStack=new Bt(this.state,this.filterManager),e.appendChild(this._activeStack.render({onRemove:(t,i)=>this._callbacks.onFilterToggle(t,!1,i),onSelect:(t,i)=>this._callbacks.onFilterSelect(t,i),onClearAll:t=>{var i,s;return(s=(i=this._callbacks).onClearAll)==null?void 0:s.call(i,t)}})),this._desktopBackgroundSection=h("div",{className:"panel-section",style:{display:"none"}}),this._backgroundPanel=new $e(this.state,this.editor),this._desktopBackgroundSection.appendChild(this._backgroundPanel.render()),e.appendChild(this._desktopBackgroundSection),this._desktopLayerSection=h("div",{className:"panel-section",style:{display:"none"}}),this._layerStackPanel=new We(this.state,this.editor),this._desktopLayerSection.appendChild(this._layerStackPanel.render()),e.appendChild(this._desktopLayerSection),this._desktopTextSection=h("div",{className:"panel-section",style:{display:"none"}}),this._textPanel=new qe(this.state,this.editor),this._desktopTextSection.appendChild(this._textPanel.render()),e.appendChild(this._desktopTextSection),this._panel.appendChild(e),this.root.appendChild(this._panel),this._mountCropControlsInActiveShell(),this._applyMode(this.state.get("mode"))}_buildMobileShell(){this._mobileChips=new jt(this.state,this.filterManager);const e=this._mobileChips.render({onSelect:(r,a)=>{var o,n;this._callbacks.onFilterSelect(r,a),(o=this._mobileDrawer)==null||o.snapTo("full"),(n=this._mobileNav)==null||n.navigateTo("controls")},onRemove:(r,a)=>this._callbacks.onFilterToggle(r,!1,a)});this.root.appendChild(e),this._mobileDrawer=new Nt({onSnapChange:r=>{this.canvasContainer&&window.dispatchEvent(new Event("resize"))}}),this._mobileNav=new Pt(this.state,this.filterManager,this.editor);const t=this._mobileNav.build({onFilterToggle:this._callbacks.onFilterToggle,onFilterSelect:this._callbacks.onFilterSelect,onFilterChange:this._callbacks.onFilterChange,onFilterReset:this._callbacks.onFilterReset,onFilterAction:this._callbacks.onFilterAction,onViewChange:r=>{var a;r==="controls"&&((a=this._mobileDrawer)==null?void 0:a.snap)==="collapsed"&&this._mobileDrawer.snapTo("half")}});this._mobileCropWrapper=h("div",{className:"crop-controls-wrapper",style:{display:"none"}});const i=h("div",{className:"drawer-content"});i.appendChild(t),i.appendChild(this._mobileCropWrapper);const s=this._mobileDrawer.build({body:i});this.root.appendChild(s),this._wireDrawerSizing(),this._mountCropControlsInActiveShell(),this._applyMode(this.state.get("mode"))}_wireDrawerSizing(){if(!this.root||!this._mobileDrawer)return;const e=()=>{const t=this.root.getBoundingClientRect().height;this._mobileDrawer.updateContainerHeight(t)};e(),this._resizeObserver=new ResizeObserver(()=>e()),this._resizeObserver.observe(this.root)}_destroyDesktopShell(){var e,t,i,s,r,a,o,n,l,c;(e=this._categoryTabs)==null||e.destroy(),this._categoryTabs=null,(t=this._filterListView)==null||t.destroy(),this._filterListView=null,(i=this._filterControlsView)==null||i.destroy(),this._filterControlsView=null,(s=this._activeStack)==null||s.destroy(),this._activeStack=null,(r=this._backgroundPanel)==null||r.destroy(),this._backgroundPanel=null,(a=this._layerStackPanel)==null||a.destroy(),this._layerStackPanel=null,(o=this._textPanel)==null||o.destroy(),this._textPanel=null,this._desktopBackgroundSection=null,this._desktopLayerSection=null,this._desktopTextSection=null,this._desktopFilterListSection=null,(n=this._desktopCropWrapper)!=null&&n.parentElement&&((l=this._cropControlsEl)==null?void 0:l.parentElement)===this._desktopCropWrapper&&this._desktopCropWrapper.removeChild(this._cropControlsEl),this._desktopCropWrapper=null,(c=this._panel)==null||c.remove(),this._panel=null}_destroyMobileShell(){var e,t,i,s,r;(e=this._resizeObserver)==null||e.disconnect(),this._resizeObserver=null,(t=this._mobileNav)==null||t.destroy(),this._mobileNav=null,(i=this._mobileChips)==null||i.destroy(),this._mobileChips=null,this._mobileCropWrapper&&((s=this._cropControlsEl)==null?void 0:s.parentElement)===this._mobileCropWrapper&&this._mobileCropWrapper.removeChild(this._cropControlsEl),this._mobileCropWrapper=null,(r=this._mobileDrawer)==null||r.destroy(),this._mobileDrawer=null}_handleBreakpointChange(e){e!==this._isMobile&&(this._isMobile=e,e?(this._destroyDesktopShell(),this._buildMobileShell()):(this._destroyMobileShell(),this._buildDesktopShell()))}_mountCropControlsInActiveShell(){if(!this._cropControlsEl)return;this._cropControlsEl.remove();const e=this._isMobile?this._mobileCropWrapper:this._desktopCropWrapper;e==null||e.appendChild(this._cropControlsEl)}_handleDesktopCategoryChange(){if(this.state.get("mode")==="crop"||["background","layers","text"].includes(this.state.get("selectedCategory")))return;const t=this.state.get("selectedFilter");if(!t)return;this.filterManager.getFiltersByCategory(this.state.get("selectedCategory")).some(s=>s.id===t)||this.state.set("selectedFilter",null)}_applyMode(e){var o,n,l;const t=e==="crop",i=!t&&this.state.get("selectedCategory")==="background",s=!t&&this.state.get("selectedCategory")==="layers",r=!t&&this.state.get("selectedCategory")==="text",a=i||s||r;this._desktopFilterListSection&&(this._desktopFilterListSection.style.display=t||a?"none":""),(o=this._filterControlsView)!=null&&o.element&&(this._filterControlsView.element.style.display=t||a?"none":""),(n=this._activeStack)!=null&&n.element&&(this._activeStack.element.style.display=t||a?"none":""),this._desktopBackgroundSection&&(this._desktopBackgroundSection.style.display=i?"":"none"),this._desktopLayerSection&&(this._desktopLayerSection.style.display=s?"":"none"),this._desktopTextSection&&(this._desktopTextSection.style.display=r?"":"none"),this._desktopCropWrapper&&(this._desktopCropWrapper.style.display=t?"":"none"),(l=this._mobileNav)!=null&&l.element&&(this._mobileNav.element.style.display=t?"none":""),this._mobileCropWrapper&&(this._mobileCropWrapper.style.display=t?"":"none"),t&&this._mobileDrawer&&this._mobileDrawer.snapTo("half")}_buildCanvasZoomOverlay(){const e=h("div",{className:"canvas-zoom-overlay",role:"group","aria-label":"Zoom controls"}),t=N({icon:Je,title:"Zoom Out",className:"canvas-zoom-btn",testId:"btn-zoom-out",ariaLabel:"Zoom out",onClick:()=>{const a=this.state.get("zoom");this.editor.setZoom(a-.25)}}),i=h("span",{className:"canvas-zoom-label","aria-live":"polite","aria-atomic":"true",role:"status"},`${Math.round((this.state.get("zoom")??1)*100)}%`),s=N({icon:Ye,title:"Zoom In",className:"canvas-zoom-btn",testId:"btn-zoom-in",ariaLabel:"Zoom in",onClick:()=>{const a=this.state.get("zoom");this.editor.setZoom(a+.25)}}),r=N({icon:Qe,title:"Fit to Screen",className:"canvas-zoom-btn",testId:"btn-fit-screen",ariaLabel:"Fit to screen",onClick:()=>this.editor.fitToScreen()});return e.appendChild(t),e.appendChild(i),e.appendChild(s),e.appendChild(r),this._unsubscribers.push(this.state.on("change:zoom",({value:a})=>{i.textContent=`${Math.round(a*100)}%`})),e}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._mql&&this._mqlHandler&&(this._mql.removeEventListener?this._mql.removeEventListener("change",this._mqlHandler):this._mql.removeListener&&this._mql.removeListener(this._mqlHandler),this._mql=null,this._mqlHandler=null),this._destroyDesktopShell(),this._destroyMobileShell(),(e=this.root)==null||e.remove(),this.root=null,this.canvasSection=null,this.canvasContainer=null,this.cropOverlay=null}}function J(_){if(!Number.isFinite(Number(_)))return 0;const e=Number(_)%360;return e<0?e+360:e}function Ht(_,e){const t=J(_);return(J(e)-t+540)%360-180}function Vt(){return new Date().toISOString()}function ue(_){return typeof _=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(_)}class $t extends U.EventEmitter{constructor(e,t={}){var r,a,o,n,l;if(super(),!e)throw new Error("VanillaImageEditorV2: container element is required");this._container=e,this._destroyed=!1,this._loadVersion=0,this._objectUrls=new Set,this._activeObjectUrl=null;const i=t.preset?je(t.preset):null,s=i?{initialMode:i.initialMode==="crop"?"crop":"adjust",cropShape:i.cropShape,initialAspectRatio:i.aspectRatio}:{};this._options={theme:"auto",initialImage:null,initialMode:"adjust",cropShape:"free",initialAspectRatio:"free",layout:"split-panel",backgroundRemoval:{enabled:!0,endpoint:"/api/v1/media/background-removal/preview",optionsEndpoint:"/api/v1/media/background-removal/options",savedEndpoint:"/api/v1/media/{media}/background-removal",fallbackEndpoint:null},backgroundReplacement:{assetEndpoint:null,materializeEndpoint:null,targetMediaUuid:null,mediaChoices:[]},...s,...t},this._preset=i,this._state=U.createState(),this._state.set("theme",this._options.theme),this._state.set("crop.shape",this._options.cropShape),this._state.set("crop.aspect",this._options.initialAspectRatio),this._preset&&(this._state.set("lockCropShape",!!this._preset.lockCropShape),this._state.set("lockAspectRatio",!!this._preset.lockAspectRatio),this._state.set("showFilters",this._preset.showFilters!==!1),this._state.set("showCropControls",this._preset.showCropControls!==!1),this._state.set("autoZoomOnCropOverflow",!!this._preset.autoZoomOnCropOverflow)),this._renderer=new Le,this._filterManager=new De(this._state,this._renderer),this._cropManager=new ge(this._state,this._renderer),this._removeBgManager=null,this._backgroundRemovalAvailable=!1,((r=this._options.backgroundRemoval)==null?void 0:r.enabled)!==!1&&(this._removeBgManager=new ze({endpoint:(a=this._options.backgroundRemoval)==null?void 0:a.endpoint,optionsEndpoint:(o=this._options.backgroundRemoval)==null?void 0:o.optionsEndpoint,savedEndpoint:(n=this._options.backgroundRemoval)==null?void 0:n.savedEndpoint,fallbackEndpoint:(l=this._options.backgroundRemoval)==null?void 0:l.fallbackEndpoint})),this._loadingOverlay=null,this._toolbar=null,this._layout=null,this._cropControls=null,this._editorEl=null,this._toolbarContainer=null,this._canvasContainer=null,this._cropOverlay=null,this._fileInput=null,this._mobileSaveBar=null,this._mobileSaveBtn=null,this._mobileSaveUnsub=null,this._resizeObserver=null,this._initPromise=Promise.resolve(this._init()).catch(c=>{this._destroyed||this.emit("error",c instanceof Error?c:new Error(String(c)))})}async _init(){this._state.detectTheme(),this._buildDOM(),!(!await this._renderer.mount(this._canvasContainer,0,{backgroundAlpha:0})||this._destroyed)&&(this._cropManager.setOverlayCanvas(this._cropOverlay),this._initUI(),this._setupResizeObserver(),this._setupWindowResize(),this._subscribeToState(),this._refreshBackgroundRemovalAvailability(),this._options.initialImage&&await this.loadImage(this._options.initialImage),this.emit("ready"))}_buildDOM(){this._container.innerHTML="",this._editorEl=h("div",{className:`vanilla-image-editor-v2 ${this._state.get("isDarkMode")?"dark":"light"}`}),this._toolbarContainer=h("div",{className:"editor-v2-toolbar"}),this._editorEl.appendChild(this._toolbarContainer),this._layout=new Ut(this._state,this._filterManager,this);const{root:e,canvasContainer:t,cropOverlay:i}=this._layout.build({onFilterToggle:(s,r,a)=>this._handleFilterToggle(s,r,a),onFilterSelect:(s,r)=>this._handleFilterSelect(s,r),onFilterChange:(s,r,a,o)=>this._handleFilterChange(s,r,a,o),onFilterReset:(s,r)=>this._handleFilterReset(s,r),onFilterAction:(s,r,a)=>this._handleFilterAction(s,r,a),onClearAll:s=>this.resetAll(s)});this._canvasContainer=t,this._cropOverlay=i,this._editorEl.appendChild(e),this._buildMobileSaveBar(),this._mobileSaveBar&&this._editorEl.appendChild(this._mobileSaveBar),this._fileInput=h("input",{type:"file",accept:"image/*",className:"hidden-file-input",style:{display:"none"},"aria-label":"Choose image file to edit",onChange:s=>this._handleFileSelect(s)}),this._editorEl.appendChild(this._fileInput),this._container.appendChild(this._editorEl)}_initUI(){this._toolbar=new Oe(this._state,this),this._toolbarContainer.appendChild(this._toolbar.render()),this._cropControls=new Pe(this._state,this._cropManager,this);const e=this._cropControls.render();this._layout.mountCropControls(e)}_setupResizeObserver(){if(!this._canvasContainer)return;let e=null;this._resizeObserver=new ResizeObserver(()=>{clearTimeout(e),e=setTimeout(()=>{var t,i;this._destroyed||!this._canvasContainer||(this._renderer.resizeTo(this._canvasContainer),this._state.get("mode")==="crop"&&((i=(t=this._cropManager).drawOverlay)==null||i.call(t)))},50)}),this._resizeObserver.observe(this._canvasContainer)}_setupWindowResize(){this._handleWindowResize=()=>{},window.addEventListener("resize",this._handleWindowResize)}_subscribeToState(){this._state.on("change:isDarkMode",({value:e})=>{var t,i;(t=this._editorEl)==null||t.classList.toggle("dark",e),(i=this._editorEl)==null||i.classList.toggle("light",!e)})}async _handleFileSelect(e){var i;const t=(i=e.target.files)==null?void 0:i[0];t&&await this.loadImage(t),this._fileInput.value=""}_matchesExpectedFilterLayer(e){if(e===void 0)return!0;if(e===null)return typeof this._state.getActiveFilterLayerId=="function"?this._state.getActiveFilterLayerId()===null:this._state.get("activeLayerId")===null;const t=typeof e=="string"?e.trim():"";return t===""?!1:typeof this._state.getActiveFilterLayerId=="function"?this._state.getActiveFilterLayerId()===t:this._state.get("activeLayerId")===t}_handleFilterToggle(e,t,i=void 0){this._filterManager.toggle(e,t,i)!==!1&&(t?this._state.set("selectedFilter",e):this._state.get("selectedFilter")===e&&this._state.set("selectedFilter",null))}_handleFilterSelect(e,t=void 0){var r;if(!this._matchesExpectedFilterLayer(t))return;const i=this._state.get("activeFilters");if(!((r=i==null?void 0:i.has)!=null&&r.call(i,e))&&this._filterManager.toggle(e,!0,t)===!1)return;this._state.set("selectedFilter",e);const s=this._filterManager.getFilterDef(e);if(typeof(s==null?void 0:s.category)=="string"){const a=ye[s.category]||s.category;this._state.get("selectedCategory")!==a&&this._state.set("selectedCategory",a)}}_handleFilterChange(e,t,i,s=void 0){this._filterManager.updateValue(e,t,i,s)||this._filterManager.applyFilters(),this._renderer.render()}_handleFilterReset(e,t=void 0){var i,s;this._filterManager.resetValues(e,t),(s=(i=this._filterManager)==null?void 0:i.applyFilters)==null||s.call(i)}_handleFilterAction(e,t,i=void 0){this._filterManager.performFilterAction(e,t,i)}_revokeObjectUrl(e){!e||!this._objectUrls.has(e)||(URL.revokeObjectURL(e),this._objectUrls.delete(e),this._activeObjectUrl===e&&(this._activeObjectUrl=null))}_replaceActiveObjectUrl(e){const t=this._activeObjectUrl;this._activeObjectUrl=e,this._objectUrls.add(e),t&&t!==e&&this._revokeObjectUrl(t)}_clearActiveObjectUrl(){this._activeObjectUrl&&this._revokeObjectUrl(this._activeObjectUrl)}async _renderCurrentDocument(){var e,t;return(t=(e=this._renderer).renderLayerDocument)==null?void 0:t.call(e,this._state.getSerializableDocument(),{fallbackImageUrl:this._state.get("imageUrl")??null})}async setBackgroundFill(e){var i;const t=this._state.setBackgroundFill(e);return await this._renderCurrentDocument(),this.emit("background-changed",{layerId:t,fill:((i=this._state.getLayer(t))==null?void 0:i.fill)??null}),t}async setBackgroundColor(e){return this.setBackgroundFill({kind:"color",value:typeof e=="string"&&e.trim()!==""?e:"#ffffff"})}async setBackgroundGradient(e={}){return this.setBackgroundFill({kind:"gradient",gradientType:e.gradientType||"linear",angle:Number.isFinite(Number(e.angle))?Number(e.angle):135,stops:Array.isArray(e.stops)?e.stops:[{offset:0,color:"#111827"},{offset:1,color:"#f59e0b"}],fit:e.fit||"cover"})}async setBackgroundMediaSource(e,t={}){if(!e||typeof e!="object")throw new Error("Background source is required");return this.setBackgroundFill({kind:"media",source:e,fit:t.fit||"cover"})}async setBackgroundImageFromFile(e,t={}){var s,r;if(!(e instanceof Blob))throw new Error("Background image file is required");const i=URL.createObjectURL(e);this._objectUrls.add(i);try{if(((r=(s=this._state).isBackgroundLayerLocked)==null?void 0:r.call(s))===!0)throw new Error("Background layer is locked");const a=this._captureEditorDocumentContext(),o=await this._probeImageDimensions(i);if(!this._isCurrentEditorDocumentContext(a))return URL.revokeObjectURL(i),this._objectUrls.delete(i),null;const n=this._state.ensureBackgroundLayer();if(!n)throw new Error("Background layer is locked");let l=null,c=this._captureEditorDocumentContext(n);if(this._canUploadBackgroundAsset()){if(!await this._materializeBackgroundLayerForUpload(n))return URL.revokeObjectURL(i),this._objectUrls.delete(i),null;if(c=this._captureEditorDocumentContext(n),l=await this._uploadBackgroundAsset(e,n,i),!this._isCurrentEditorDocumentContext(c))return URL.revokeObjectURL(i),this._objectUrls.delete(i),null}return l||(l={kind:"runtime",runtimeRef:`background-${Date.now()}`,originalWidth:o.width,originalHeight:o.height,sourceHash:null,previewUrl:i}),this._isCurrentEditorDocumentContext(c)?this.setBackgroundMediaSource(l,{fit:t.fit||"cover"}):(URL.revokeObjectURL(i),this._objectUrls.delete(i),null)}catch(a){throw URL.revokeObjectURL(i),this._objectUrls.delete(i),a}}async setBackgroundFit(e){if(!this._state.setBackgroundFit(e))return!1;const i=this._backgroundLayerId();await this._renderCurrentDocument();const s=i?this._state.getLayer(i):null;return s&&this.emit("background-changed",{layerId:i,fill:s.fill??null}),!0}async setBackgroundBlur(e){if(!this._state.setBackgroundBlur(e))return!1;const i=this._backgroundLayerId();await this._renderCurrentDocument();const s=i?this._state.getLayer(i):null;return s&&this.emit("background-changed",{layerId:i,effects:s.effects??[]}),!0}_backgroundLayerId(){const e=this._state.getSerializableDocument(),t=Array.isArray(e==null?void 0:e.layers)?e.layers.find(i=>(i==null?void 0:i.type)==="background"||(i==null?void 0:i.role)==="background"):null;return typeof(t==null?void 0:t.id)=="string"?t.id:null}async removeBackgroundLayer(){return this._state.removeBackgroundLayer()?(await this._renderCurrentDocument(),this.emit("background-changed",{layerId:null,fill:null}),!0):!1}async selectLayer(e){var i,s;return this._state.setActiveLayer(e)?((s=(i=this._filterManager)==null?void 0:i.applyFilters)==null||s.call(i),this.emit("layer-changed",{action:"select",layerId:e}),!0):!1}async renameLayer(e,t){var s;return this._state.renameLayer(e,t)?(this.emit("layer-changed",{action:"rename",layerId:e,name:((s=this._state.getLayer(e))==null?void 0:s.name)??null}),!0):!1}async duplicateLayer(e){const t=this._state.duplicateLayer(e);return t?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"duplicate",layerId:e,duplicateLayerId:t}),t):null}async deleteLayer(e){return this._state.deleteLayer(e)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"delete",layerId:e,activeLayerId:this._state.get("activeLayerId")}),!0):!1}async moveLayer(e,t){return this._state.moveLayer(e,t)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"move",layerId:e,direction:t}),!0):!1}async setLayerVisibility(e,t){return this._state.setLayerVisibility(e,t)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"visibility",layerId:e,visible:!!t}),!0):!1}async setLayerLocked(e,t){return this._state.setLayerLocked(e,t)?(this.emit("layer-changed",{action:"lock",layerId:e,locked:!!t}),!0):!1}async addTextLayer(e={}){const t=this._state.addTextLayer(e);return t?(this._state.set("selectedCategory","text"),await this._renderCurrentDocument(),this.emit("layer-changed",{action:"text-add",layerId:t}),t):null}async updateTextLayer(e,t={}){return this._state.updateTextLayer(e,t)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"text-update",layerId:e,patch:t}),!0):!1}_canUploadBackgroundAsset(){var r,a;const e=(a=(r=this._options)==null?void 0:r.backgroundReplacement)==null?void 0:a.assetEndpoint,t=this._state.getEditorDocumentBinding(),i=this._state.getSerializableDocument(),s=this._backgroundTargetMediaUuid(i);return typeof e=="string"&&e.trim()!==""&&!!(t!=null&&t.documentId)&&!!i&&typeof s=="string"&&s.trim()!==""}async _materializeBackgroundLayerForUpload(e){return this._materializeCurrentDocument("Background layer materialization failed",e)}_documentMaterializationSignature(e){try{return JSON.stringify(e??null)}catch{return null}}_captureDocumentMaterializationContext(e,t,i=null){return{loadVersion:this._loadVersion,documentId:(t==null?void 0:t.documentId)??null,documentRevisionId:(t==null?void 0:t.documentRevisionId)??null,documentRevisionNumber:(t==null?void 0:t.documentRevisionNumber)??null,documentSignature:this._documentMaterializationSignature(e),requiredLayerId:i}}_captureEditorDocumentContext(e=null){return{loadVersion:this._loadVersion,documentSignature:this._documentMaterializationSignature(this._state.getSerializableDocument()),requiredLayerId:e}}_isCurrentEditorDocumentContext(e){return!(!e||this._destroyed||this._loadVersion!==e.loadVersion||this._documentMaterializationSignature(this._state.getSerializableDocument())!==e.documentSignature||e.requiredLayerId&&!this._state.getLayer(e.requiredLayerId))}_isCurrentDocumentMaterializationContext(e){if(!e||this._destroyed||this._loadVersion!==e.loadVersion)return!1;const t=this._state.getEditorDocumentBinding();if(!t||(t.documentId??null)!==e.documentId||(t.documentRevisionId??null)!==e.documentRevisionId||(t.documentRevisionNumber??null)!==e.documentRevisionNumber)return!1;const i=this._state.getSerializableDocument();return!(this._documentMaterializationSignature(i)!==e.documentSignature||e.requiredLayerId&&!this._state.getLayer(e.requiredLayerId))}async _materializeCurrentDocument(e="Editor document materialization failed",t=null){const i=this._backgroundMaterializeEndpoint(),s=this._state.getEditorDocumentBinding(),r=this._state.getSerializableDocument();if(!i||!(s!=null&&s.documentId)||!r||t!==null&&!t)return!1;const a=this._resolveBackgroundEndpoint(i,r);if(!a)return!1;const o=this._captureDocumentMaterializationContext(r,s,t),n=ue(s.documentId)?s.documentId:null,l=await fetch(a,{method:"POST",credentials:"include",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({document_id:n,base_document_revision:n===null?null:s.documentRevisionNumber,document:r})});let c=null;try{c=await l.json()}catch{c=null}if(!l.ok){const d=(c==null?void 0:c.message)||e;throw new Error(d)}return this._isCurrentDocumentMaterializationContext(o)?(c!=null&&c.document&&this._state.setEditorDocument(c.document,{documentId:c.document_id??s.documentId,documentRevisionId:c.document_revision_id??s.documentRevisionId,documentRevisionNumber:typeof c.document_revision_number=="number"?c.document_revision_number:s.documentRevisionNumber}),!0):!1}async _uploadBackgroundAsset(e,t,i){var u,g,m;const s=(g=(u=this._options)==null?void 0:u.backgroundReplacement)==null?void 0:g.assetEndpoint,r=this._state.getEditorDocumentBinding(),a=this._state.getSerializableDocument();if(!s||!(r!=null&&r.documentId)||!a)return null;const o=this._resolveBackgroundEndpoint(s,a);if(!o)return null;const n=await this._sha256File(e),l=new FormData;l.append("asset_file",e,e instanceof File&&e.name?e.name:"background.png"),l.append("asset_kind","background-upload"),l.append("document_id",r.documentId),l.append("layer_id",t),l.append("client_hash",n);const c=await fetch(o,{method:"POST",credentials:"include",headers:{Accept:"application/json"},body:l});if(!c.ok)throw new Error("Background upload failed");const d=await c.json(),p=(m=d==null?void 0:d.asset)==null?void 0:m.source;if(!p||typeof p!="object")throw new Error("Background upload did not return a usable layer source");return{...p,previewUrl:i}}_backgroundMaterializeEndpoint(){var s,r,a,o,n,l;const e=(r=(s=this._options)==null?void 0:s.backgroundReplacement)==null?void 0:r.materializeEndpoint;if(typeof e=="string"&&e.trim()!=="")return e;const t=(o=(a=this._options)==null?void 0:a.backgroundReplacement)==null?void 0:o.assetEndpoint;if(typeof t=="string"&&t.trim()!=="")return t.replace(/\/editor-assets\/?$/,"/editor-documents/materialize");const i=(l=(n=this._options)==null?void 0:n.backgroundRemoval)==null?void 0:l.savedEndpoint;return typeof i=="string"&&i.trim()!==""?i.replace(/\/background-removal\/?$/,"/editor-documents/materialize"):null}_resolveBackgroundEndpoint(e,t){if(typeof e!="string"||e.trim()==="")return null;const i=this._backgroundTargetMediaUuid(t);return e.includes("{media}")?typeof i!="string"||i.trim()===""?null:e.replace("{media}",encodeURIComponent(i)):e}_backgroundTargetMediaUuid(e){var i,s;const t=(s=(i=this._options)==null?void 0:i.backgroundReplacement)==null?void 0:s.targetMediaUuid;return typeof t=="string"&&t.trim()!==""?t:typeof(e==null?void 0:e.sourceMediaUuid)=="string"&&e.sourceMediaUuid.trim()!==""?e.sourceMediaUuid:null}async _sha256File(e){var s,r,a;const t=await e.arrayBuffer(),i=await((a=(r=(s=globalThis.crypto)==null?void 0:s.subtle)==null?void 0:r.digest)==null?void 0:a.call(r,"SHA-256",t));if(!i)throw new Error("Background upload hashing is unavailable");return Array.from(new Uint8Array(i)).map(o=>o.toString(16).padStart(2,"0")).join("")}_probeImageDimensions(e){return new Promise(t=>{const i=new Image;i.onload=()=>t({width:Math.max(1,Math.round(i.naturalWidth||i.width||1)),height:Math.max(1,Math.round(i.naturalHeight||i.height||1))}),i.onerror=()=>t({width:1,height:1}),i.src=e})}setFilterRegistry(e){this._filterManager.setRegistry(e)}async loadImage(e,t={}){var o,n,l,c;if(this._destroyed)return;(n=(o=this._removeBgManager)==null?void 0:o.cancelActiveRequests)==null||n.call(o,"image-load");const i=++this._loadVersion;let s=e,r=null;this._resetEditorState(),this._state.set("hasImage",!1),this._state.set("imageUrl",null),e instanceof Blob&&(s=URL.createObjectURL(e),r=s,this._objectUrls.add(s));const a=await this._renderer.loadTexture(s,{isCurrent:()=>!this._destroyed&&this._loadVersion===i});if(this._destroyed||this._loadVersion!==i){this._revokeObjectUrl(r);return}if(!a){this._revokeObjectUrl(r),this.emit("error",new Error("Failed to load image"));return}r?this._replaceActiveObjectUrl(r):this._clearActiveObjectUrl(),this._state.set("hasImage",!0),this._state.set("imageUrl",s),t.document?await this._hydrateDocument(t.document,{documentId:t.documentId??(ue((l=t.document)==null?void 0:l.id)?t.document.id:null),documentRevisionId:t.documentRevisionId??null,documentRevisionNumber:t.documentRevisionNumber??((c=t.document)==null?void 0:c.revision)??null,fallbackImageUrl:s}):this._initializeDefaultDocument(s),t.state&&this._hydrateState(t.state),this._options.initialMode==="crop"&&this.setMode("crop"),this.emit("imageLoaded",{url:s})}_resetEditorState(){this._filterManager.resetAll(),this._state.set("crop.rect",null),this._state.set("crop.appliedRect",null),this._state.set("crop.appliedShape",null),this._state.set("crop.appliedAspect",null),this._state.set("crop.dirty",!1),this._state.set("crop.shape",this._options.cropShape||"free"),this._state.set("crop.aspect",this._options.initialAspectRatio||"free"),this._state.set("transform.rotation",0),this._state.clearEditorDocument(),this._state.get("mode")==="crop"&&(this._cropManager.disable(),this._state.set("mode","filters"))}_initializeDefaultDocument(e){var l,c,d,p;const t=this._renderer.originalTexture,i=Math.max(1,Math.round((t==null?void 0:t.width)||1)),s=Math.max(1,Math.round((t==null?void 0:t.height)||1)),r=Vt(),a=typeof((c=(l=this._options)==null?void 0:l.backgroundReplacement)==null?void 0:c.targetMediaUuid)=="string"&&this._options.backgroundReplacement.targetMediaUuid.trim()!==""?this._options.backgroundReplacement.targetMediaUuid.trim():null,o=a?{kind:"media",mediaUuid:a,originalWidth:i,originalHeight:s,sourceHash:null}:{kind:"runtime",runtimeRef:"source-image",originalWidth:i,originalHeight:s,sourceHash:null,previewUrl:typeof e=="string"?e:null},n={version:2,id:`client-doc-${Date.now()}`,sourceMediaUuid:a,canvas:{width:i,height:s,backgroundPreviewColor:null},revision:0,layers:[{id:"subject-layer",type:"image",role:"subject",name:"Subject",visible:!0,locked:!1,opacity:1,blendMode:"normal",transform:{x:0,y:0,scaleX:1,scaleY:1,rotation:0},effects:[],metadata:{},source:o,crop:null,filters:[]}],activeLayerId:"subject-layer",export:{mimeType:"image/png",quality:null,preserveTransparency:!0,matteColor:null,trimTransparentBounds:!1},createdAt:r,updatedAt:r};this._state.setEditorDocument(n,{documentId:null,documentRevisionId:null,documentRevisionNumber:0}),(p=(d=this._renderer).renderLayerDocument)==null||p.call(d,n,{fallbackImageUrl:typeof e=="string"?e:null})}async _hydrateDocument(e,t={}){var i,s;!e||e.version!==2||(this._state.setEditorDocument(e,{documentId:t.documentId??(ue(e.id)?e.id:null),documentRevisionId:t.documentRevisionId??null,documentRevisionNumber:t.documentRevisionNumber??e.revision??null}),await((s=(i=this._renderer).renderLayerDocument)==null?void 0:s.call(i,this._state.getSerializableDocument(),{fallbackImageUrl:t.fallbackImageUrl??this._state.get("imageUrl")??null})))}_hydrateState(e){var i;if(!e||e.version!==1)return;const t=J(((i=e.transform)==null?void 0:i.rotation)??0);if(t!==0&&this._renderer.rotateBy(t)&&this._state.set("transform.rotation",t),e.crop){const s=e.crop.shape||"free",r=e.crop.aspectRatio||"free";e.crop.rect&&(this._cropManager.applyFromPixelRect(e.crop.rect,s),this._state.set("crop.appliedRect",{...e.crop.rect}),this._state.set("crop.appliedShape",s),this._state.set("crop.appliedAspect",r)),this._state.set("crop.shape",s),this._state.set("crop.aspect",r)}if(Array.isArray(e.filters)){let s=null;for(const r of e.filters)if(r.enabled&&(s===null&&(s=r.id),this._state.toggleFilter(r.id,!0),this._filterManager.initializeValues(r.id),r.values))for(const[a,o]of Object.entries(r.values))this._state.setFilterValue(r.id,a,o);if(s!==null){this._state.set("selectedFilter",s);const r=this._filterManager.getFilterDef(s);if(typeof(r==null?void 0:r.category)=="string"){const a=ye[r.category]??r.category;this._state.set("selectedCategory",a)}}this._filterManager.applyFilters()}}openFilePicker(){var e;(e=this._fileInput)==null||e.click()}exportImage(e="png",t=.92,i={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditorV2.exportImage")?null:this._renderer.exportImage(e,t,i.maxEdge??0,i.dontUpscale!==!1,i.maxPixels??0)}async exportBlob(e="png",t=.92,i={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditorV2.exportBlob")?null:this._renderer.exportBlob(e,t,i)}_applyPendingCropBeforeExport(e){return!(this._state.get("crop.rect")&&!this._cropManager.apply())}async save(){if(!this._state.get("hasImage"))return;this._state.set("isSaving",!0);let e=null;try{const t=await this.exportBlob("png",.92);if(!t)throw new Error("Failed to export image");const i=s.createElement("a");e=URL.createObjectURL(t.blob),i.href=e,i.download=`edited-image-${Date.now()}.png`,s.body.appendChild(i),i.click(),s.body.removeChild(i);const s=this.getSerializableDocument(),r=this.getEditorDocumentBinding();this.emit("save",{blob:t.blob,mimeType:t.blob.type||"image/png",dimensions:{width:t.width,height:t.height},state:this.getSerializableState(),document:s,documentId:(r==null?void 0:r.documentId)??(ue(s==null?void 0:s.id)?s.id:null),documentRevisionId:(r==null?void 0:r.documentRevisionId)??null,documentRevisionNumber:(r==null?void 0:r.documentRevisionNumber)??(s==null?void 0:s.revision)??null})}catch(t){this.emit("error",{error:t})}finally{e&&URL.revokeObjectURL(e),this._state.set("isSaving",!1)}}getSerializableState(){const e=this._state.get("activeFilters"),t=[];if(e)for(const a of e){const o=this._state.getFilterValues(a);t.push({id:a,enabled:!0,values:{...o}})}const i=this._state.get("crop.appliedRect"),s=this._state.get("crop.rect"),r=i||s;return{version:1,crop:{rect:r?{...r}:null,aspectRatio:this._state.get("crop.appliedAspect")||this._state.get("crop.aspect")||"free",shape:this._state.get("crop.appliedShape")||this._state.get("crop.shape")||"free"},transform:{rotation:J(this._state.get("transform.rotation")??0)},filters:t}}getSerializableDocument(){return this._state.getSerializableDocument()}getEditorDocumentBinding(){return this._state.getEditorDocumentBinding()}close(){this.emit("cancel")}setZoom(e){this._renderer.setZoom(e)}fitToScreen(){this._renderer.fitToScreen()}resetAll(e=void 0){this._filterManager.resetAll(e)}rotateBy(e){const t=this._state.get("transform.rotation")??0;return this.setRotationAngle(Number(t)+Number(e))}setRotationAngle(e){if(!this._state.get("hasImage"))return!1;const t=J(this._state.get("transform.rotation")??0),i=J(e),s=Ht(t,i),r=this._state.get("mode")==="crop";if(Math.abs(s)>.001){if(r&&this._cropManager.disable(),!this._renderer.rotateBy(s))return r&&this._cropManager.enable(),!1;this._filterManager.applyFilters(),this._state.set("crop.rect",null),this._state.set("crop.dirty",!1),r&&this._cropManager.enable()}return this._state.set("transform.rotation",i),this.emit("transformChanged",{rotation:i}),!0}resetRotation(){return this.setRotationAngle(0)}toggleTheme(){const e=this._state.get("isDarkMode");this._state.set("isDarkMode",!e)}setTheme(e){this._state.set("theme",e),this._state.detectTheme()}setMode(e){e==="crop"?this._cropManager.enable():this._cropManager.disable(),this._state.set("mode",e)}getState(){return this._state.getAll()}async removeBackground(e={}){var t,i,s,r,a,o,n,l,c,d;if(!this._removeBgManager)throw new Error("Background removal is not enabled");if(!this._state.get("hasImage"))throw new Error("No image loaded");if(!this.canRemoveBackground())throw new Error("Background removal is not available for the current editor state");this._state.set("isProcessing",!0),this._showLoadingOverlay("Removing background...");try{const p=this._activeBackgroundRemovalLayer();if(this._hasSavedEditorDocumentBinding()&&p!==null&&this._backgroundMaterializeEndpoint()&&!await this._materializeCurrentDocument("Background removal materialization failed"))return this.emit("background-removal-stale",{operationId:e.operationId??null,targetLayerId:p.id}),{stale:!0};const u=this._buildSavedBackgroundRemovalContext(e);if(u){const w=await this._removeBgManager.removeSavedMediaBackground(u.request);if(!this._isCurrentBackgroundRemovalContext(u,w))return this.emit("background-removal-stale",{operationId:u.request.operationId,targetLayerId:u.request.targetLayerId}),{stale:!0};const F=(t=w==null?void 0:w.result)==null?void 0:t.source;if(!F||F.kind!=="edit-asset")throw new Error("Background removal did not return a persisted layer source");const j=(i=w==null?void 0:w.result)==null?void 0:i.previewDataUrl;return typeof j=="string"&&j.startsWith("data:image/")&&(!await this._renderer.loadTexture(j,{isCurrent:()=>!this._destroyed&&this._isCurrentBackgroundRemovalContext(u,w)})||!this._isCurrentBackgroundRemovalContext(u,w))?(this.emit("background-removal-stale",{operationId:u.request.operationId,targetLayerId:u.request.targetLayerId}),{stale:!0}):this._isCurrentBackgroundRemovalContext(u,w)?(this._state.replaceLayerSource(u.request.targetLayerId,F),await((r=(s=this._renderer).renderLayerDocument)==null?void 0:r.call(s,this._state.getSerializableDocument(),{fallbackImageUrl:this._state.get("imageUrl")??null})),this.emit("background-removed",{model:(a=w==null?void 0:w.result)==null?void 0:a.model,processMs:(o=w==null?void 0:w.result)==null?void 0:o.process_ms,source:F,operationId:u.request.operationId,targetLayerId:u.request.targetLayerId}),{model:(n=w==null?void 0:w.result)==null?void 0:n.model,processMs:(l=w==null?void 0:w.result)==null?void 0:l.process_ms,source:F}):(this.emit("background-removal-stale",{operationId:u.request.operationId,targetLayerId:u.request.targetLayerId}),{stale:!0})}const g=this._buildPreviewBackgroundRemovalInput(e);if(!g)throw new Error("Failed to export image for background removal");const m=this._buildPreviewBackgroundRemovalContext(g.options),f=await this._removeBgManager.preparePreviewRequest(g.imageData,g.options),v=this._resolvePreviewBackgroundRemovalContext(m,f);if(!await this._isCurrentPreviewBackgroundRemovalContext(v))return this.emit("background-removal-stale",{operationId:v.operationId,sourceHash:v.sourceHash,targetLayerId:v.activeLayerId??null}),{stale:!0};const k=await this._removeBgManager.removeBackground(f.blob,f);if(!await this._isCurrentPreviewBackgroundRemovalContext(v,k))return this.emit("background-removal-stale",{operationId:v.operationId,sourceHash:v.sourceHash}),{stale:!0};const L=await this._applyPreviewBackgroundRemovalResult(v,k);return L?(this.emit("background-removed",{model:k.model,processMs:k.processMs,operationId:v.operationId,targetLayerId:v.activeLayerId??null,source:L.source}),{model:k.model,processMs:k.processMs,...L.source?{source:L.source}:{}}):(this.emit("background-removal-stale",{operationId:v.operationId,sourceHash:v.sourceHash,targetLayerId:v.activeLayerId??null}),{stale:!0})}catch(p){throw this.emit("error",{error:p,context:"background-removal"}),p}finally{(d=(c=this._state)==null?void 0:c.set)==null||d.call(c,"isProcessing",!1),this._hideLoadingOverlay()}}async isBackgroundRemovalAvailable(){return this._removeBgManager?this._refreshBackgroundRemovalAvailability():!1}canRemoveBackground(){if(!this._removeBgManager||this._state.get("hasImage")!==!0||this._backgroundRemovalAvailable!==!0)return!1;const e=this._state.getSerializableDocument();return(e==null?void 0:e.version)===2&&Array.isArray(e.layers)?this._activeBackgroundRemovalLayer({requireSourceHash:this._hasSavedEditorDocumentBinding()})!==null:!0}async _refreshBackgroundRemovalAvailability(){if(!this._removeBgManager)return this._backgroundRemovalAvailable=!1,this._state.set("backgroundRemovalAvailable",!1),!1;const e=await this._removeBgManager.isAvailable();return this._destroyed?!1:(this._backgroundRemovalAvailable=e,this._state.set("backgroundRemovalAvailable",e),e)}_hasSavedEditorDocumentBinding(){const e=this._state.getEditorDocumentBinding();return!!(e!=null&&e.documentId)&&!!(e!=null&&e.documentRevisionId)}_activeBackgroundRemovalLayer(e={}){var a;const t=e.requireSourceHash!==!1,i=this._state.get("activeLayerId");if(!i)return null;const s=this._state.getLayer(i);if(!s||s.type!=="image"||s.locked===!0||s.visible===!1)return null;const r=(a=s==null?void 0:s.source)==null?void 0:a.sourceHash;return t&&(typeof r!="string"||!/^[a-f0-9]{64}$/i.test(r))?null:s}_buildSavedBackgroundRemovalContext(e={}){var c,d,p,u,g;const t=this._state.getSerializableDocument(),i=this._state.getEditorDocumentBinding();if(!t||!(i!=null&&i.documentId)||!(i!=null&&i.documentRevisionId))return null;const s=typeof t.sourceMediaUuid=="string"&&t.sourceMediaUuid!==""?t.sourceMediaUuid:null;if(!s)return null;const r=this._activeBackgroundRemovalLayer({requireSourceHash:!0}),a=r==null?void 0:r.id,o=(c=r==null?void 0:r.source)==null?void 0:c.sourceHash;if(!a||typeof o!="string"||!/^[a-f0-9]{64}$/i.test(o))return null;const n=e.operationId||((p=(d=globalThis.crypto)==null?void 0:d.randomUUID)==null?void 0:p.call(d))||`op-${Date.now()}-${Math.random().toString(16).slice(2)}`,l={loadVersion:this._loadVersion,activeLayerId:a,documentRevisionId:i.documentRevisionId,documentSignature:this._documentMaterializationSignature(t),sourceHash:o,request:{targetMediaUuid:s,operationId:n,documentId:i.documentId,documentRevisionId:i.documentRevisionId,targetLayerId:a,expectedSourceHash:o,tier:e.tier||((g=(u=this._options)==null?void 0:u.backgroundRemoval)==null?void 0:g.defaultTier)||"balanced"}};return e.model&&(l.request.model=e.model),e.alpha_matting!==void 0&&(l.request.alpha_matting=e.alpha_matting),e.max_megapixels!==void 0&&(l.request.max_megapixels=e.max_megapixels),l}_buildPreviewBackgroundRemovalContext(e){const t=this._state.getSerializableDocument(),i=(t==null?void 0:t.version)===2&&Array.isArray(t.layers),s=i?this._activeBackgroundRemovalLayer({requireSourceHash:!1}):null;return{loadVersion:this._loadVersion,activeLayerId:i?(s==null?void 0:s.id)??null:null,documentSignature:i?this._documentMaterializationSignature(t):null,imageUrl:this._state.get("imageUrl")??null,operationId:e.operationId,sessionKey:e.sessionKey,sourceHash:e.sourceHash,targetRef:e.targetRef??null}}_resolvePreviewBackgroundRemovalContext(e,t){return{...e,operationId:t.operationId,sessionKey:t.sessionKey,sourceHash:t.sourceHash,targetRef:t.targetRef??e.targetRef??null}}_buildPreviewBackgroundRemovalInput(e={}){const t=this._state.getSerializableDocument();if((t==null?void 0:t.version)===2&&Array.isArray(t.layers)){const s=this._activeBackgroundRemovalLayer({requireSourceHash:!1}),r=this._sourceUrlForLayerSource(s==null?void 0:s.source);return!s||!r?null:{imageData:r,options:{...e,targetRef:s.id}}}const i=this.exportImage("png");return i?{imageData:i,options:e}:null}_sourceUrlForLayerSource(e){if(!e||typeof e!="object")return null;for(const t of["previewUrl","sourceUrl","url"]){const i=e[t];if(typeof i=="string"&&i.trim()!=="")return i}return null}async _applyPreviewBackgroundRemovalResult(e,t){var r,a;if(e.documentSignature===null||!e.activeLayerId)return await this.loadImage(t.dataUrl),{source:null};const i=await this._probeImageDimensions(t.dataUrl);if(!await this._isCurrentPreviewBackgroundRemovalContext(e,t))return null;const s={kind:"runtime",runtimeRef:`background-removal-${e.operationId||Date.now()}`,originalWidth:i.width,originalHeight:i.height,sourceHash:null,previewUrl:t.dataUrl};return this._state.replaceLayerSource(e.activeLayerId,s)?(await((a=(r=this._renderer).renderLayerDocument)==null?void 0:a.call(r,this._state.getSerializableDocument(),{fallbackImageUrl:this._state.get("imageUrl")??null})),{source:s}):null}async _isCurrentPreviewBackgroundRemovalContext(e,t=null){if(this._destroyed||this._loadVersion!==e.loadVersion||this._state.get("hasImage")!==!0||(this._state.get("imageUrl")??null)!==e.imageUrl)return!1;if(t){if(t.operationId&&t.operationId!==e.operationId||t.sessionKey&&t.sessionKey!==e.sessionKey||t.sourceHash&&t.sourceHash!==e.sourceHash)return!1;if(e.documentSignature!==null){if(!e.targetRef||e.targetRef!==e.activeLayerId||t.targetRef!==e.targetRef)return!1}else if(t.targetRef&&e.targetRef&&t.targetRef!==e.targetRef)return!1}if(e.documentSignature!==null){const s=this._state.getSerializableDocument();if(this._documentMaterializationSignature(s)!==e.documentSignature)return!1;const r=this._activeBackgroundRemovalLayer({requireSourceHash:!1});return!(!r||r.id!==e.activeLayerId)}const i=this.exportImage("png");return i?await this._removeBgManager.computeImageDataHash(i)===e.sourceHash:!1}_isCurrentBackgroundRemovalContext(e,t=null){var a;if(this._destroyed||this._loadVersion!==e.loadVersion)return!1;const i=this._state.getEditorDocumentBinding();if(!i||i.documentRevisionId!==e.documentRevisionId)return!1;const s=this._state.getSerializableDocument();if(this._documentMaterializationSignature(s)!==e.documentSignature||this._state.get("activeLayerId")!==e.activeLayerId)return!1;const r=this._state.getLayer(e.request.targetLayerId);return!(!r||((a=r==null?void 0:r.source)==null?void 0:a.sourceHash)!==e.sourceHash||r.locked===!0||r.visible===!1||t&&(t.operation_id&&t.operation_id!==e.request.operationId||t.target_layer_id&&t.target_layer_id!==e.request.targetLayerId||t.document_revision_id&&t.document_revision_id!==e.request.documentRevisionId||t.source_hash&&t.source_hash!==e.request.expectedSourceHash))}_showLoadingOverlay(e){var i;if(!this._loadingOverlay)this._loadingOverlay=h("div",{className:"editor-loading-overlay"},h("div",{className:"editor-loading-spinner"}),h("div",{className:"editor-loading-text"},e));else{const s=this._loadingOverlay.querySelector(".editor-loading-text");s&&(s.textContent=e)}const t=(i=this._canvasContainer)==null?void 0:i.parentElement;t&&!this._loadingOverlay.parentElement&&t.appendChild(this._loadingOverlay)}_hideLoadingOverlay(){var e;(e=this._loadingOverlay)==null||e.remove()}_buildMobileSaveBar(){var a,o;this._mobileSaveBar=h("div",{className:"editor-v2-mobile-save-bar",role:"region","aria-label":"Save bar"}),this._mobileSaveBtn=h("button",{type:"button",className:"mobile-save-btn",title:"Save Image","aria-label":"Save image",dataset:{testid:"btn-save-edit-mobile"},onClick:()=>this.save()});const e=h("span",{className:"mobile-save-icon"});e.innerHTML=Te;const t=e.querySelector("svg");t&&t.setAttribute("aria-hidden","true"),this._mobileSaveBtn.appendChild(e),this._mobileSaveBtn.appendChild(h("span",{className:"mobile-save-label"},"Save")),this._mobileSaveBar.appendChild(this._mobileSaveBtn);const i=()=>{var d,p;if(!this._mobileSaveBtn)return;const n=((d=this._state)==null?void 0:d.get("hasImage"))===!0,l=((p=this._state)==null?void 0:p.get("isProcessing"))===!0,c=!n||l;this._mobileSaveBtn.disabled=c,this._mobileSaveBtn.setAttribute("aria-disabled",c?"true":"false")};i();const s=(a=this._state)==null?void 0:a.on("change:hasImage",i),r=(o=this._state)==null?void 0:o.on("change:isProcessing",i);this._mobileSaveUnsub=()=>{try{s==null||s()}catch{}try{r==null||r()}catch{}}}destroy(){var e,t,i,s,r,a,o,n;this._destroyed=!0,(t=(e=this._removeBgManager)==null?void 0:e.cancelActiveRequests)==null||t.call(e,"editor-destroy");for(const l of this._objectUrls)try{URL.revokeObjectURL(l)}catch{}this._objectUrls.clear(),this._activeObjectUrl=null,(i=this._resizeObserver)==null||i.disconnect(),this._renderer.destroy(),this._cropManager.disable(),this._handleWindowResize&&window.removeEventListener("resize",this._handleWindowResize),(s=this._toolbar)==null||s.destroy(),(r=this._cropControls)==null||r.destroy(),(a=this._layout)==null||a.destroy(),(o=this._mobileSaveUnsub)==null||o.call(this),this._mobileSaveUnsub=null,this._mobileSaveBtn=null,this._mobileSaveBar=null,(n=this._editorEl)==null||n.remove(),this._container=null,this._state=null,this.emit("destroyed"),this.removeAllListeners()}}exports.VanillaImageEditor=Tt;exports.VanillaImageEditorV2=$t;
|
|
2
|
+
//# sourceMappingURL=editor-v2-CFLWp7RZ.cjs.map
|