@codingfactory/mediables-vue 2.19.0 → 2.19.1

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.
Files changed (54) hide show
  1. package/dist/{PixiFrameExporter-CL1sPbnw.js → PixiFrameExporter-64httBgJ.js} +2 -2
  2. package/dist/{PixiFrameExporter-CL1sPbnw.js.map → PixiFrameExporter-64httBgJ.js.map} +1 -1
  3. package/dist/{PixiFrameExporter-nFehBjPQ.cjs → PixiFrameExporter-DkXTPJWn.cjs} +2 -2
  4. package/dist/{PixiFrameExporter-nFehBjPQ.cjs.map → PixiFrameExporter-DkXTPJWn.cjs.map} +1 -1
  5. package/dist/components/MediaFilterChips.vue.d.ts +10 -0
  6. package/dist/components/MediaInspectorPanel.vue.d.ts +13 -0
  7. package/dist/components/MediaLibraryShell.vue.d.ts +21 -0
  8. package/dist/components/MediaManagementView.vue.d.ts +1 -0
  9. package/dist/components/MediaTrashWorkspace.vue.d.ts +5 -0
  10. package/dist/composables/useMediaDeletion.d.ts +20 -0
  11. package/dist/composables/useMediaLibraryVisibility.d.ts +37 -0
  12. package/dist/composables/useMediaMetadata.d.ts +24 -0
  13. package/dist/editor-CiTXlIVO.js +4327 -0
  14. package/dist/editor-CiTXlIVO.js.map +1 -0
  15. package/dist/editor-P9MyuiTc.cjs +2 -0
  16. package/dist/editor-P9MyuiTc.cjs.map +1 -0
  17. package/dist/imageEditorState-BNQEZoCF.js +81 -0
  18. package/dist/imageEditorState-BNQEZoCF.js.map +1 -0
  19. package/dist/imageEditorState-PrcqbsfM.cjs +2 -0
  20. package/dist/imageEditorState-PrcqbsfM.cjs.map +1 -0
  21. package/dist/index-2jP5K__o.cjs +357 -0
  22. package/dist/index-2jP5K__o.cjs.map +1 -0
  23. package/dist/index-Dae8SHT7.js +6557 -0
  24. package/dist/index-Dae8SHT7.js.map +1 -0
  25. package/dist/{index-BR0szJau.js → index-Dinl1Puu.js} +16860 -15559
  26. package/dist/index-Dinl1Puu.js.map +1 -0
  27. package/dist/index-QOKC8XA_.cjs +2 -0
  28. package/dist/index-QOKC8XA_.cjs.map +1 -0
  29. package/dist/index.d.ts +5 -1
  30. package/dist/mediables-primitives.cjs +2 -0
  31. package/dist/mediables-primitives.cjs.map +1 -0
  32. package/dist/mediables-primitives.mjs +21 -0
  33. package/dist/mediables-primitives.mjs.map +1 -0
  34. package/dist/mediables-vanilla.cjs +1 -1
  35. package/dist/mediables-vanilla.mjs +8 -7
  36. package/dist/mediables-vanilla.mjs.map +1 -1
  37. package/dist/mediables-vue.cjs +1 -1
  38. package/dist/mediables-vue.mjs +74 -70
  39. package/dist/mediables-vue.mjs.map +1 -1
  40. package/dist/primitives-exports.d.ts +37 -0
  41. package/dist/style.css +1 -1
  42. package/dist/types/media.d.ts +2 -0
  43. package/dist/types/mediaLibraryPicker.d.ts +5 -0
  44. package/dist/utils/focus.d.ts +4 -0
  45. package/dist/vanilla-editor/core/EventEmitter.d.ts +8 -8
  46. package/dist/vanilla-editor/core/State.d.ts +441 -95
  47. package/package.json +8 -2
  48. package/dist/editor-D85y_zTO.cjs +0 -2
  49. package/dist/editor-D85y_zTO.cjs.map +0 -1
  50. package/dist/editor-DAJxTvzM.js +0 -10873
  51. package/dist/editor-DAJxTvzM.js.map +0 -1
  52. package/dist/index-BR0szJau.js.map +0 -1
  53. package/dist/index-CKYVSPfs.cjs +0 -357
  54. package/dist/index-CKYVSPfs.cjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ "use strict";var je=Object.defineProperty;var Oe=(g,e,t)=>e in g?je(g,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):g[e]=t;var ce=(g,e,t)=>Oe(g,typeof e!="symbol"?e+"":e,t);const J=require("./index-QOKC8XA_.cjs"),Pe=Object.freeze(["normal","multiply","screen","overlay"]),B=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 Ce extends J.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 r,s,o,n,a,l;const e=(s=(r=this.app)==null?void 0:r.renderer)==null?void 0:s.canvas,t=(e==null?void 0:e.clientWidth)??((n=(o=this.app)==null?void 0:o.screen)==null?void 0:n.width)??0,i=(e==null?void 0:e.clientHeight)??((l=(a=this.app)==null?void 0:a.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,r=0;const s=()=>{i||(i=!0,window.clearTimeout(r),t())};if(r=window.setTimeout(s,e),typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(()=>s());return}s()})}getFitScaleFor(e){if(!this.app||!e)return 1;const{w:t,h:i}=this._getCssSize();if(t<=1||i<=1)return 1;let r=Math.min(t/e.width,i/e.height)*.9;return(!Number.isFinite(r)||r<=0)&&(r=1),r}applyViewTransform(e={}){if(!this.app||!this.sprite||!this.originalTexture)return;const t=this.fitScale*this.zoom,{w:i,h:r}=this._getCssSize(),s=e.keepCenter?{x:this.sprite.x+this.sprite.width/2,y:this.sprite.y+this.sprite.height/2}:e.center??{x:i/2,y:r/2};this.sprite.width=this.originalTexture.width*t,this.sprite.height=this.originalTexture.height*t,this.sprite.x=s.x-this.sprite.width/2,this.sprite.y=s.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 r=++this._mountToken,s=async()=>{var p;const o=window.PIXI;if(!o)throw new Error("PIXI.js not found. Please ensure PIXI is loaded globally.");(p=o.Assets)!=null&&p.setPreferences&&o.Assets.setPreferences({crossOrigin:"anonymous"});const n=e.clientWidth||600,a=e.clientHeight||400,l=typeof i.backgroundAlpha=="number"?i.backgroundAlpha:1,h=new o.Application;if(this.app=h,await h.init({width:n,height:a,backgroundColor:t,backgroundAlpha:l,antialias:!0,autoDensity:!0,resolution:window.devicePixelRatio||1}),this._destroyed||this._mountToken!==r||this.app!==h){try{h.destroy(!0,{children:!0,texture:!0})}catch{}return!1}e.appendChild(h.canvas);const c=h.canvas;return c.classList.add("pixi-canvas"),c.style.width="100%",c.style.height="100%",c.style.transform="translateZ(0)",c.style.willChange="transform",c.setAttribute("role","img"),c.setAttribute("aria-label","Image editor canvas — use toolbar controls to edit the image"),this.emit("mounted",{width:n,height:a}),!0};return this._mountPromise=s(),await this._mountPromise}async loadTexture(e,t={}){var h,c,p;const i=()=>typeof t.isCurrent!="function"||t.isCurrent()!==!1;if(this._mountPromise&&await this._mountPromise,!((h=this.app)!=null&&h.renderer)||!i())return!1;const r=window.PIXI,s=await this._loadImageElement(e);if(!s||!((c=this.app)!=null&&c.renderer)||!i()||(await this._waitForNextFrame(),!((p=this.app)!=null&&p.renderer)||!i()))return!1;const o=r.Texture.from(s);if(!o)return!1;this.originalTexture=o,this.baseTexture=o,this._loadedTextureUrl=typeof e=="string"?e:null,this.sprite&&(this.app.stage.removeChild(this.sprite),this.sprite.destroy()),this.sprite=new r.Sprite(o),this.app.stage.addChild(this.sprite),this.fitScale=this.getFitScaleFor(o),this.zoom=1;const{w:n,h:a}=this._getCssSize();this.applyViewTransform({center:{x:n/2,y:a/2}});const l=this.getFitScaleFor(o);return Math.abs(l-this.fitScale)/Math.max(1e-6,l)>.02&&(this.fitScale=l,this.applyViewTransform({center:{x:n/2,y:a/2}})),this.render(),this.emit("textureLoaded",{width:o.width,height:o.height}),!0}async renderLayerDocument(e){var o;if(!((o=this.app)!=null&&o.stage)||!this.sprite||!e||!Array.isArray(e.layers))return!1;const t=window.PIXI;if(!t)return!1;const i=++this._layerRenderToken,r=()=>i===this._layerRenderToken;this._destroyLayerDisplayObjects(),this._layerDocument=JSON.parse(JSON.stringify(e)),this._renderableLayerIds=[];try{this.app.stage.removeChild(this.sprite)}catch{}let s=!1;for(const n of this._layerDocument.layers){if(!n||n.visible===!1){(n==null?void 0:n.role)==="subject"&&(this.sprite.visible=!1,this.sprite.__layerId=n.id,s=!0);continue}if(this._isSubjectLayer(n)){const l=await this._createSubjectDisplayObjectForLayer(t,n);if(!r())return this._destroyTransientDisplayObject(l),!1;if(l){this.sprite.visible=!1,l.__layerId=n.id,l.visible=!0,l.alpha=this._layerOpacity(n),this._layerDisplayObjects.set(n.id,{layer:n,displayObject:l}),this._syncLayerDisplayObject(n,l),this.app.stage.addChild(l),this._renderableLayerIds.push(n.id),s=!0;continue}this.sprite.__layerId=n.id,this.sprite.visible=!0,this.sprite.alpha=this._layerOpacity(n),this._applyLayerFilterInstances(this.sprite,n),this.app.stage.addChild(this.sprite),this._renderableLayerIds.push(n.id),s=!0;continue}const a=await this._createDisplayObjectForLayer(t,n);if(!r())return this._destroyTransientDisplayObject(a),!1;a&&(a.__layerId=n.id,a.visible=!0,a.alpha=this._layerOpacity(n),this._layerDisplayObjects.set(n.id,{layer:n,displayObject:a}),this._syncLayerDisplayObject(n,a),this.app.stage.addChild(a),this._renderableLayerIds.push(n.id))}return s||(this.sprite.visible=!1),r()?(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 r=this._layerDisplayObjects.get(i.id)||null;r&&(r.layer=i);let s=(r==null?void 0:r.displayObject)||null;!s&&this._isSubjectLayer(i)&&((t=this.sprite)==null?void 0:t.__layerId)===i.id&&(s=this.sprite),s&&this._applyLayerFilterInstances(s,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 r=[];if(this._layerFilterFactory)try{r=this._layerFilterFactory(t,{displayObject:e,forExport:i.forExport===!0,previewToNativeScale:i.previewToNativeScale||1,sourceWidth:i.sourceWidth,sourceHeight:i.sourceHeight})||[]}catch{r=[]}const s=Array.isArray(r)?r.filter(Boolean):[];for(const a of s)if(!(!a||typeof a!="object"&&typeof a!="function"))try{Object.defineProperty(a,"__mediablesLayerImageFilter",{value:!0,configurable:!0})}catch{try{a.__mediablesLayerImageFilter=!0}catch{}}const n=[...Array.isArray(e.filters)?e.filters.filter(a=>(a==null?void 0:a.__mediablesLayerImageFilter)!==!0):[],...s];e.filters=n.length>0?n:null}async _createDisplayObjectForLayer(e,t){var o,n;const i=this._createTextDisplayObjectForLayer(e,t);if(i)return i;const r=await this._createImageDisplayObjectForLayer(e,t);if(r)return r;const s=this._backgroundFillForLayer(t);if((s==null?void 0:s.kind)==="media"){const a=await this._textureForLayerSource(e,s.source);if(!a)return null;const l=this._createBackgroundSprite(e,a,s.fit);return l.__sourceWidth=Number((o=s.source)==null?void 0:o.originalWidth)||a.width||1,l.__sourceHeight=Number((n=s.source)==null?void 0:n.originalHeight)||a.height||1,this._applyLayerEffects(e,l,t),this._applyLayerFilterInstances(l,t),l}if((s==null?void 0:s.kind)==="gradient"){const a=this._createGradientTexture(e,s,512,512);if(!a||typeof e.Sprite!="function")return null;const l=new e.Sprite(a);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 a=new e.Graphics;return this._applyLayerEffects(e,a,t),a}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,r){const s=Number(e);return Number.isFinite(s)?Math.max(t,Math.min(i,s)):r}_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 Pe.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,r={}){var m;const s=(m=e==null?void 0:e.text)!=null&&m.style&&typeof e.text.style=="object"?e.text.style:{},o=this._textEffectsForLayer(e),n=this._clampNumber(s.fontSize,8,400,64),a=this._clampNumber(s.lineHeight,.8,3,1.2),l=this._clampNumber(s.letterSpacing,-100,100,0),h=this._normalizeTextFontWeight(s.fontWeight),c=["normal","italic"].includes(s.fontStyle)?s.fontStyle:"normal",p=["left","center","right"].includes(s.align)?s.align:"center",u=r.fill||(typeof s.fill=="string"&&/^#[0-9a-f]{6}$/i.test(s.fill)?s.fill:"#ffffff"),f={fontFamily:this._supportedTextFontFamily(s.fontFamily),fontSize:n*t,fontWeight:h,fontStyle:c,fill:u,align:p,lineHeight:n*a*t,letterSpacing:l*t,wordWrap:!0,wordWrapWidth:Math.max(1,i),breakWords:!0};return r.stroke!==!1&&o.stroke.enabled&&o.stroke.width>0&&(f.stroke={color:o.stroke.color,width:o.stroke.width*t}),f}_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 n;const t=(n=e==null?void 0:e.text)!=null&&n.effects&&typeof e.text.effects=="object"?e.text.effects:{},i=t.stroke&&typeof t.stroke=="object"?t.stroke:{},r=t.shadow&&typeof t.shadow=="object"?t.shadow:{},s=t.glow&&typeof t.glow=="object"?t.glow:{},o=t.backdrop&&typeof t.backdrop=="object"?t.backdrop:{};return{stroke:{enabled:i.enabled===!0,color:this._supportedTextColor(i.color,B.stroke.color),width:this._clampNumber(i.width,0,80,B.stroke.width)},shadow:{enabled:r.enabled===!0,color:this._supportedTextColor(r.color,B.shadow.color),alpha:this._clampNumber(r.alpha,0,1,B.shadow.alpha),blur:this._clampNumber(r.blur,0,120,B.shadow.blur),distance:this._clampNumber(r.distance,0,200,B.shadow.distance),angle:this._normalizeDegrees(r.angle??B.shadow.angle)},glow:{enabled:s.enabled===!0,color:this._supportedTextColor(s.color,B.glow.color),alpha:this._clampNumber(s.alpha,0,1,B.glow.alpha),blur:this._clampNumber(s.blur,0,120,B.glow.blur)},backdrop:{enabled:o.enabled===!0,color:this._supportedTextColor(o.color,B.backdrop.color),opacity:this._clampNumber(o.opacity,0,1,B.backdrop.opacity),padding:this._clampNumber(o.padding,0,200,B.backdrop.padding),radius:this._clampNumber(o.radius,0,200,B.backdrop.radius),blur:this._clampNumber(o.blur,0,80,B.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,r=e.shadow.enabled?(e.shadow.distance+e.shadow.blur*2)*t:0,s=e.glow.enabled?e.glow.blur*2*t:0,o=e.backdrop.enabled?(e.backdrop.padding+e.backdrop.blur*2)*t:0;return Math.ceil(Math.max(i,r,s,o,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 r=new e.Container,s=new e.Graphics,o=new e.Graphics,n=new e.Graphics,a=this._createTextPrimitive(e,t),l=this._createTextPrimitive(e,t);return r.__isTextLayerContainer=!0,r.__textObject=i,r.__textMask=s,r.__textEffectMask=o,r.__textBackdrop=n,r.__textShadow=a,r.__textGlow=l,n.visible=!1,a&&(a.visible=!1),l&&(l.visible=!1),i.mask=s,r.addChild(n),a&&r.addChild(a),l&&r.addChild(l),r.addChild(i),r.addChild(o),r.addChild(s),r}_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 s,o;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 r=new e.Sprite(i);return r.__sourceWidth=Number((s=t.source)==null?void 0:s.originalWidth)||i.width||1,r.__sourceHeight=Number((o=t.source)==null?void 0:o.originalHeight)||i.height||1,this._applyLayerEffects(e,r,t),this._applyLayerFilterInstances(r,t),r}_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 r=await this._loadImageElement(i);return r?e.Texture.from(r):null}_createBackgroundSprite(e,t,i="cover"){if(i==="tile"&&typeof e.TilingSprite=="function")try{const r=new e.TilingSprite({texture:t,width:1,height:1});return r.__isTilingBackground=!0,r}catch{try{const s=new e.TilingSprite(t,1,1);return s.__isTilingBackground=!0,s}catch{}}return new e.Sprite(t)}_createGradientTexture(e,t,i,r){var l;if(typeof document>"u"||!((l=e==null?void 0:e.Texture)!=null&&l.from))return null;const s=document.createElement("canvas");s.width=Math.max(1,Math.round(i)),s.height=Math.max(1,Math.round(r));const o=s.getContext("2d");if(!o)return null;const n=Array.isArray(t==null?void 0:t.stops)&&t.stops.length>0?t.stops:[{offset:0,color:"#111827"},{offset:1,color:"#f59e0b"}];let a;if((t==null?void 0:t.gradientType)==="radial"){const h=Math.max(s.width,s.height)/2;a=o.createRadialGradient(s.width/2,s.height/2,0,s.width/2,s.height/2,h)}else{const h=(Number(t==null?void 0:t.angle)||0)*Math.PI/180,c=s.width/2,p=s.height/2,u=Math.sqrt(s.width**2+s.height**2)/2,f=Math.cos(h)*u,m=Math.sin(h)*u;a=o.createLinearGradient(c-f,p-m,c+f,p+m)}for(const h of n){if(!h||typeof h.color!="string")continue;const c=Number.isFinite(Number(h.offset))?Math.max(0,Math.min(1,Number(h.offset))):0;a.addColorStop(c,h.color)}return o.fillStyle=a,o.fillRect(0,0,s.width,s.height),e.Texture.from(s)}_backgroundBlurAmount(e){var s;const i=(Array.isArray(e==null?void 0:e.effects)?e.effects:[]).find(o=>(o==null?void 0:o.id)==="background-blur"||(o==null?void 0:o.type)==="blur"),r=Number((s=i==null?void 0:i.params)==null?void 0:s.amount);return Number.isFinite(r)?Math.max(0,r):0}_applyLayerEffects(e,t,i){const r=this._backgroundBlurAmount(i);if(!(r<=0||typeof(e==null?void 0:e.BlurFilter)!="function"))try{let s;try{s=new e.BlurFilter({strength:r,quality:4})}catch{s=new e.BlurFilter(r)}typeof s.blur=="number"&&(s.blur=r),typeof s.strength=="number"&&(s.strength=r),s.padding=Math.max(Number(s.padding)||0,Math.ceil(r*2)),t.filters=Array.isArray(t.filters)?[...t.filters,s]:[s]}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,r,s,o,n,a){if(!t)return;const l=r[s];if(t.visible=(l==null?void 0:l.enabled)===!0,t.filters=null,t.mask=t.visible?a:null,!!t.visible){if(t.text=this._textContentForLayer(i),t.rotation=0,s==="shadow"){const h=l.angle*Math.PI/180;t.x=Math.cos(h)*l.distance*o,t.y=Math.sin(h)*l.distance*o,t.alpha=l.alpha,t.style=this._textStyleForLayer(i,o,n,{fill:l.color,stroke:!1});const c=this._createTextBlurFilter(e,l.blur*o);t.filters=c?[c]:null;return}if(s==="glow"){t.x=0,t.y=0,t.alpha=l.alpha,t.style=this._textStyleForLayer(i,o,n,{fill:l.color,stroke:!1});const h=this._createTextBlurFilter(e,l.blur*o);t.filters=h?[h]:null}}}_syncTextBackdrop(e,t,i,r,s,o,n){if(!t)return;const a=i.backdrop;if(t.visible=a.enabled===!0,t.filters=null,t.mask=t.visible?n:null,t.alpha=1,typeof t.clear=="function"&&t.clear(),!t.visible)return;const l=a.padding*r,h=a.radius*r,c=-l,p=-l,u=s+l*2,f=o+l*2;h>0&&typeof t.roundRect=="function"?t.roundRect(c,p,u,f,h):typeof t.rect=="function"&&t.rect(c,p,u,f),this._fillTextEffectGraphics(t,a.color,a.opacity);const m=this._createTextBlurFilter(e,a.blur*r);t.filters=m?[m]:null}_fitTextDisplayObjectToRect(e,t,i){var m,b;const r=this._normalizeTextBox(t),s=i.x+r.x*i.width,o=i.y+r.y*i.height,n=r.width*i.width,a=r.height*i.height,l=Number((m=this.originalTexture)==null?void 0:m.width)||i.width,h=l>0?i.width/l:1,c=this._textEffectsForLayer(t);e.x=s,e.y=o,e.rotation=this._normalizeDegrees(Number((b=t==null?void 0:t.transform)==null?void 0:b.rotation)||0)*Math.PI/180,e.blendMode=this._textBlendMode(t),e.__textBox=r,e.__textLayout={x:s,y:o,width:n,height:a,scale:h};const p=e.__textObject||e,u=e.__textMask||null,f=e.__textEffectMask||null;if(p.text=this._textContentForLayer(t),p.style=this._textStyleForLayer(t,h,n),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,n,a).fill(16777215),p.mask=u),f&&typeof f.clear=="function"&&typeof f.rect=="function"&&typeof f.fill=="function"){const C=this._textEffectPadding(c,h);f.clear(),f.rect(-C,-C,n+C*2,a+C*2).fill(16777215)}this._syncTextBackdrop(window.PIXI,e.__textBackdrop,c,h,n,a,f),this._syncTextEffectPrimitive(window.PIXI,e.__textShadow,t,c,"shadow",h,n,f),this._syncTextEffectPrimitive(window.PIXI,e.__textGlow,t,c,"glow",h,n,f)}_fitDisplayObjectToRect(e,t,i){var c,p,u,f,m,b,C,x;const r=this._backgroundFillForLayer(t),s=(r==null?void 0:r.fit)||"cover";if(e.__isTilingBackground){e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height,(p=(c=e.tilePosition)==null?void 0:c.set)==null||p.call(c,0,0),(f=(u=e.tileScale)==null?void 0:u.set)==null||f.call(u,1,1);return}if(s==="stretch"||(r==null?void 0:r.kind)==="gradient"||(r==null?void 0:r.kind)==="color"){e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height;return}const o=Number(e.__sourceWidth||((m=r==null?void 0:r.source)==null?void 0:m.originalWidth)||((b=e.texture)==null?void 0:b.width)||i.width),n=Number(e.__sourceHeight||((C=r==null?void 0:r.source)==null?void 0:C.originalHeight)||((x=e.texture)==null?void 0:x.height)||i.height);if(!Number.isFinite(o)||!Number.isFinite(n)||o<=0||n<=0){e.x=i.x,e.y=i.y,e.width=i.width,e.height=i.height;return}const a=s==="contain"?Math.min(i.width/o,i.height/n):Math.max(i.width/o,i.height/n),l=o*a,h=n*a;e.x=i.x+(i.width-l)/2,e.y=i.y+(i.height-h)/2,e.width=l,e.height=h}_destroyLayerDisplayObjects(){var e,t,i,r,s;if((e=this._layerDisplayObjects)!=null&&e.size){for(const{displayObject:o}of this._layerDisplayObjects.values()){try{(r=(i=(t=this.app)==null?void 0:t.stage)==null?void 0:i.removeChild)==null||r.call(i,o)}catch{}const n=(o==null?void 0:o.__ownsTexture)===!0;(s=o==null?void 0:o.destroy)==null||s.call(o,{children:!0,texture:n,textureSource:n})}this._layerDisplayObjects.clear(),this._renderableLayerIds=[]}}_destroyTransientDisplayObject(e){var i,r,s,o;if(!e)return;try{(s=(r=(i=this.app)==null?void 0:i.stage)==null?void 0:r.removeChild)==null||s.call(r,e)}catch{}const t=(e==null?void 0:e.__ownsTexture)===!0;(o=e==null?void 0:e.destroy)==null||o.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 r=this._normalizeDegrees(i);if(r===0)return{width:Math.max(1,Math.round(e)),height:Math.max(1,Math.round(t))};const s=r*Math.PI/180,o=Math.abs(Math.cos(s)),n=Math.abs(Math.sin(s)),a=o<1e-10?0:o,l=n<1e-10?0:n;return{width:Math.max(1,Math.ceil(e*a+t*l)),height:Math.max(1,Math.ceil(e*l+t*a))}}rotateBy(e){var m,b,C;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,r=Math.round(this.originalTexture.width),s=Math.round(this.originalTexture.height);if(r<=0||s<=0)return!1;const{width:o,height:n}=this.getRotatedBounds(r,s,t),a=t*Math.PI/180,l=new i.Container,h=new i.Sprite(this.originalTexture);(C=(b=h.anchor)==null?void 0:b.set)==null||C.call(b,.5),h.x=o/2,h.y=n/2,h.rotation=a,l.addChild(h);const c=i.RenderTexture.create({width:o,height:n,resolution:1});try{this.app.renderer.render({container:l,target:c,clear:!0,clearColor:[0,0,0,0]})}catch{return c.destroy(!0),!1}finally{l.removeChildren(),h.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=c,this._lastExportDimensions=null,this.app.stage.removeChild(this.sprite),this.sprite.destroy({children:!1,texture:!1,textureSource:!1});const f=new i.Sprite(c);return u!=null&&u.length&&(f.filters=u),this.app.stage.addChild(f),this.sprite=f,this.fitScale=this.getFitScaleFor(c),this.zoom=1,this.applyViewTransform({keepCenter:!1}),this.render(),this.emit("textureRotated",{width:o,height:n,degrees:t}),!0}exportImage(e="png",t=.92,i=0,r=!0,s=0){var F;if(!((F=this.app)!=null&&F.renderer)||!this.originalTexture||!this.sprite)return null;const o=window.PIXI,n=Math.round(this.originalTexture.width),a=Math.round(this.originalTexture.height);if(n<=0||a<=0)return null;const l=this.sprite.width,h=this.sprite.height;if(l<=0||h<=0)return null;const c=l/n,p=c>0?1/c:1,u=this._layerDocument,f=u&&Array.isArray(u.layers),m=[];if(!f&&Array.isArray(this.sprite.filters)){for(const y of this.sprite.filters)if(y)if(typeof y.createExportFilter=="function"){const w=y.createExportFilter({previewToNativeScale:p});w&&m.push(w)}else m.push(y)}let b=0;for(const y of m){const w=typeof y.getExportPadding=="function"?Number(y.getExportPadding())||0:typeof y._exportPadding=="number"?y._exportPadding:typeof y.padding=="number"?y.padding:0;w>0&&(b+=w)}const C=Math.max(Math.ceil(b),64),x=y=>{var X,ee,j,te;const w=Math.ceil(n+2*y),S=Math.ceil(a+2*y),k=new o.Container,E=[],z=(_=null)=>{const v=new o.Sprite(this.originalTexture);v.x=y,v.y=y,v.scale.set(1,1),v.alpha=_?this._layerOpacity(_):1,_&&this._applyLayerFilterInstances(v,_,{forExport:!0,previewToNativeScale:p,sourceWidth:n,sourceHeight:a}),m.length>0&&(v.filters=m,v.filterArea=new o.Rectangle(0,0,n,a)),k.addChild(v),E.push(v)},M=_=>{var R,K,Y;const v=(R=this._layerDisplayObjects.get(_.id))==null?void 0:R.displayObject,I=(v==null?void 0:v.texture)||(this._isSubjectLayer(_)?this.originalTexture:null);if(!I||typeof o.Sprite!="function")return!1;const O=new o.Sprite(I);return O.__sourceWidth=Number(((K=_.source)==null?void 0:K.originalWidth)||(v==null?void 0:v.__sourceWidth)||I.width||n),O.__sourceHeight=Number(((Y=_.source)==null?void 0:Y.originalHeight)||(v==null?void 0:v.__sourceHeight)||I.height||a),this._fitDisplayObjectToRect(O,_,{x:y,y,width:n,height:a}),O.alpha=this._layerOpacity(_),!f&&this._isSubjectLayer(_)&&m.length>0&&(O.filters=m,O.filterArea=new o.Rectangle(0,0,n,a)),this._applyLayerEffects(o,O,_),this._applyLayerFilterInstances(O,_,{forExport:!0,previewToNativeScale:p,sourceWidth:n,sourceHeight:a}),k.addChild(O),E.push(O),!0},T=_=>{var K,Y,ve;const v=this._backgroundFillForLayer(_),I=this._backgroundColorForLayer(_),O={x:y,y,width:n,height:a};let R=null;if(I&&typeof o.Graphics=="function")R=new o.Graphics,R.rect(y,y,n,a).fill(I);else if((v==null?void 0:v.kind)==="gradient"&&typeof o.Sprite=="function"){const H=this._createGradientTexture(o,v,n,a);if(!H)return!1;R=new o.Sprite(H),R.__ownsTexture=!0,R.__sourceWidth=n,R.__sourceHeight=a,this._fitDisplayObjectToRect(R,_,O)}else if((v==null?void 0:v.kind)==="media"){const H=(K=this._layerDisplayObjects.get(_.id))==null?void 0:K.displayObject,ie=H==null?void 0:H.texture;if(!ie)return!1;R=this._createBackgroundSprite(o,ie,v.fit),R.__sourceWidth=Number(((Y=v.source)==null?void 0:Y.originalWidth)||H.__sourceWidth||ie.width||1),R.__sourceHeight=Number(((ve=v.source)==null?void 0:ve.originalHeight)||H.__sourceHeight||ie.height||1),this._fitDisplayObjectToRect(R,_,O)}return R?(R.alpha=this._layerOpacity(_),this._applyLayerEffects(o,R,_),this._applyLayerFilterInstances(R,_,{forExport:!0,previewToNativeScale:p,sourceWidth:n,sourceHeight:a}),k.addChild(R),E.push(R),!0):!1},P=_=>{const v=this._createTextDisplayObjectForLayer(o,_);return v?(this._fitTextDisplayObjectToRect(v,_,{x:y,y,width:n,height:a}),v.alpha=this._layerOpacity(_),k.addChild(v),E.push(v),!0):!1},V=u,G=f;if(G){for(const _ of V.layers)if(!(!_||_.visible===!1)){if(this._isTextLayer(_)){P(_);continue}if(_.type==="image"){!M(_)&&this._isSubjectLayer(_)&&z(_);continue}if(this._isSubjectLayer(_)){M(_)||z(_);continue}T(_)}}else z();!G&&((X=k.children)==null?void 0:X.length)===0&&z();const q=o.RenderTexture.create({width:w,height:S,resolution:1}),he=((ee=k.children)==null?void 0:ee.length)??0;try{this.app.renderer.render({container:k,target:q,clear:!0,clearColor:[0,0,0,0]});const _=(te=(j=this.app.renderer.extract)==null?void 0:j.canvas)==null?void 0:te.call(j,q);return _?{canvas:_,width:w,height:S,margin:y,childCount:he}:null}finally{for(const _ of E)_.filters=null;k.removeChildren();for(const _ of E){const v=(_==null?void 0:_.__ownsTexture)===!0;_.destroy({children:!1,texture:v,textureSource:v})}k.destroy({children:!1}),q.destroy(!0)}},N=(y,w,S)=>{const k=typeof y.getContext=="function"?y.getContext("2d"):null;if(!k)return null;let E;try{E=k.getImageData(0,0,w,S).data}catch{return null}const z=1;let M=w,T=S,P=-1,V=-1;const G=4,q=w*G;for(let j=0;j<S;j++){const te=j*q;for(let _=0;_<w;_++)E[te+_*G+3]>=z&&(_<M&&(M=_),_>P&&(P=_),j<T&&(T=j),j>V&&(V=j))}if(P<0)return null;const he=P-M+1,X=V-T+1,ee=M===0||T===0||P===w-1||V===S-1;return{x:M,y:T,width:he,height:X,touchesEdge:ee}};let A=null;try{let y=x(C);if(!y)return null;let w=N(y.canvas,y.width,y.height);if(!w)if(f&&y.childCount===0)w={x:y.margin,y:y.margin,width:n,height:a,touchesEdge:!1};else return null;if(w.touchesEdge&&C<n&&C<a){const M=Math.max(C*4,256),T=x(M);if(T){const P=N(T.canvas,T.width,T.height);P&&!P.touchesEdge?(y=T,w=P):(y=T,w=P??w)}}let S=w.width,k=w.height;if(i>0){const M=Math.max(S,k);let T=i/M;r&&(T=Math.min(1,T)),S=Math.max(1,Math.round(S*T)),k=Math.max(1,Math.round(k*T))}if(s>0&&S*k>s){const M=Math.sqrt(s/(S*k));S=Math.max(1,Math.floor(S*M)),k=Math.max(1,Math.floor(k*M))}const E=document.createElement("canvas");E.width=S,E.height=k;const z=E.getContext("2d");return z?(z.drawImage(y.canvas,w.x,w.y,w.width,w.height,0,0,S,k),A=E.toDataURL(`image/${e}`,t),this._lastExportDimensions={width:S,height:k},A||null):null}catch{return null}}getExportDimensions(){var o;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 r=0;const s=(o=this.sprite)==null?void 0:o.filters;if(Array.isArray(s))for(const n of s){if(!n)continue;const a=typeof n._exportPadding=="number"?n._exportPadding:typeof n.padding=="number"?n.padding:0;a>r&&(r=a)}return{width:t+2*r,height:i+2*r}}async exportBlob(e="png",t=.92,i={}){const r=this.exportImage(e,t,i.maxEdge??0,i.dontUpscale!==!1,i.maxPixels??0);if(!r)return null;const o=await(await fetch(r)).blob(),n=this.getExportDimensions();return{blob:o,width:n.width,height:n.height}}resizeTo(e){var r;if(!((r=this.app)!=null&&r.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 s={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:s})}}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 pe='<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>',fe='<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>',ze='<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>',He='<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>',Ie='<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>',Ue='<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>',Ve='<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>',We='<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>',$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="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>',ke='<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>',Ze='<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>',Ge='<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>',Me='<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>',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="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>',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="M368 368L144 144M368 144L144 368"/></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="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>',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="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>',Ke='<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>',Re='<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>',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="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>',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="M416 128L192 384l-96-96"/></svg>',Te='<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>',Je='<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>',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 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>',Xe='<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>',et='<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>',tt='<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>',it='<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>',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="M96 112V80h320v32M256 80v352M184 432h144"/></svg>',st='<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>',nt='<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>',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="M80 96h64l64 320h64l64-160h96"/></svg>',we='<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>',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="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>',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="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>',lt='<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>',le=[{id:"adjust",name:"Adjust",icon:Ue,registryCategories:["adjust","advanced"]},{id:"blur",name:"Blur",icon:Ve,registryCategories:["blur"]},{id:"color",name:"Color",icon:We,registryCategories:["color"]},{id:"effects",name:"Effects",icon:$e,registryCategories:["effects"]},{id:"distortion",name:"Distortion",icon:ke,registryCategories:["distortion"]},{id:"light",name:"Light",icon:Ge,registryCategories:["light"]},{id:"stylize",name:"Stylize",icon:at,registryCategories:["stylize"]},{id:"text",name:"Text",icon:rt},{id:"background",name:"Background",icon:Ze},{id:"layers",name:"Layers",icon:Te},{id:"crop",name:"Crop",icon:Me}],ht=Object.fromEntries(le.filter(g=>Array.isArray(g.registryCategories)&&g.registryCategories.length>0).map(g=>[g.id,g.registryCategories])),Ae=Object.fromEntries(le.filter(g=>Array.isArray(g.registryCategories)).flatMap(g=>g.registryCategories.map(e=>[e,g.id])));function ct(g){return ht[g]||[g]}class Ee extends J.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,(r,s)=>this.createFiltersForLayer(r,s))}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=ct(e),i=[],r=new Set;for(const s of t){const o=this._filterRegistry.getFiltersByCategory(s)||[];for(const n of o)r.has(n.id)||(r.add(n.id),i.push(n))}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 r=e;for(const s of i){if(r==null)return;r=r[s]}return r}_setDeepProp(e,t,i){if(!e||!t)return;if(!t.includes(".")&&!t.includes("[")){e[t]=i;return}const r=t.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean);let s=e;for(let n=0;n<r.length-1;n++){const a=r[n];if(!(a in s)||(s=s[a],s==null))return}const o=r[r.length-1];s[o]=i}initializeValues(e,t=void 0){const i=this.getFilterDef(e);if(!i)return;const r=this.state.getFilterValues(e),s=new Set((i.controls||[]).map(o=>o.id));if(i.defaultParams)for(const[o,n]of Object.entries(i.defaultParams))!s.has(o)&&!(o in r)&&this.state.setFilterValue(e,o,n,t);i.controls&&i.controls.forEach(o=>{o.id in r||this.state.setFilterValue(e,o.id,o.default,t)})}resetValues(e,t=void 0){const i=this.getFilterDef(e);if(!i)return;const r=new Set((i.controls||[]).map(s=>s.id));if(i.defaultParams)for(const[s,o]of Object.entries(i.defaultParams))r.has(s)||this.state.setFilterValue(e,s,o,t);i.controls&&i.controls.forEach(s=>{this.state.setFilterValue(e,s.id,s.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,r=void 0){const s=this._normalizeValue(i);if(!this._matchesExpectedFilterLayer(r))return!1;const o=this.getFilterDef(e),n=o==null?void 0:o.controls.find(p=>p.id===t),a=!n&&(t.includes("[")||t.includes("."));if(!a&&this.state.setFilterValue(e,t,s,r)===!1)return!1;const l=this.instances[e];if(!l)return!1;const h=(n==null?void 0:n.property)||t;if(typeof l.updateUIParam=="function"){if(l.updateUIParam(h,s),a&&typeof l.getSerializableParams=="function"){const p=l.getSerializableParams();for(const[u,f]of Object.entries(p))this.state.setFilterValue(e,u,f,r)}return!0}const c=this._getDeepProp(l,h);return typeof c=="function"?!1:l.uniforms&&h in l.uniforms?(l.uniforms[h]=s,!0):c!==void 0?(this._setDeepProp(l,h,s),!0):!1}performFilterAction(e,t,i=void 0){if(!this._matchesExpectedFilterLayer(i))return!1;const r=this.instances[e];if(!r||typeof r.updateUIParam!="function")return!1;if(r.updateUIParam(t,!0),typeof r.getSerializableParams=="function"){const s=r.getSerializableParams();for(const[o,n]of Object.entries(s))this.state.setFilterValue(e,o,n,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 r,s,o,n,a,l,h,c,p;const i=(e==null?void 0:e.source)||((r=e==null?void 0:e.fill)==null?void 0:r.source)||null;return{width:Math.round(Number(t.sourceWidth||(i==null?void 0:i.originalWidth)||((o=(s=this.renderer)==null?void 0:s.originalTexture)==null?void 0:o.width)||((a=(n=this.renderer)==null?void 0:n.sprite)==null?void 0:a.width)||0)),height:Math.round(Number(t.sourceHeight||(i==null?void 0:i.originalHeight)||((h=(l=this.renderer)==null?void 0:l.originalTexture)==null?void 0:h.height)||((p=(c=this.renderer)==null?void 0:c.sprite)==null?void 0:p.height)||0))}}_paramsForFilterState(e,t,i){const r=t!=null&&t.values&&typeof t.values=="object"?t.values:{},s=e.defaultParams?{...e.defaultParams}:{};e.controls&&Array.isArray(e.controls)&&e.controls.forEach(n=>{const a=n.property||n.id;s[a]=r[n.id]??n.default});const o=new Set((e.controls||[]).map(n=>n.id));for(const[n,a]of Object.entries(r))o.has(n)||(s[n]=a);return s._sourceWidth=i.width,s._sourceHeight=i.height,s}createFiltersForLayer(e,t={}){if(!Array.isArray(e==null?void 0:e.filters)||e.filters.length===0)return[];const i=[],r=this.state.get("activeLayerId"),s=e.id===r&&t.forExport!==!0,o=this._sourceDimensionsForLayer(e,t);for(const n of e.filters)if(!(!n||n.enabled===!1||typeof n.id!="string"))try{const a=this.getFilterDef(n.id);if(!(a!=null&&a.createFilter)||typeof a.createFilter!="function")continue;const l=a.createFilter(this._paramsForFilterState(a,n,o));if(!l)continue;let h=l;t.forExport===!0&&typeof l.createExportFilter=="function"&&(h=l.createExportFilter({previewToNativeScale:t.previewToNativeScale||1})||l),i.push(h),s&&(this.instances[n.id]=l)}catch{}return i}applyFilters(){var o,n,a,l,h,c,p;const e=this._layerDocument();if(e){for(const f in this.instances)delete this.instances[f];(n=(o=this.renderer)==null?void 0:o.setLayerFilterFactory)==null||n.call(o,(f,m)=>this.createFiltersForLayer(f,m));const u=(l=(a=this.renderer)==null?void 0:a.applyLayerFilters)==null?void 0:l.call(a,e);this.emit("filtersApplied",{count:((h=this.state.get("activeFilters"))==null?void 0:h.size)??0,failed:[],scopedToLayer:!0}),u||(p=(c=this.renderer)==null?void 0:c.render)==null||p.call(c);return}const t=this.renderer.sprite;if(!t)return;for(const u in this.instances)delete this.instances[u];const i=[],r=[];this.state.get("activeFilters").forEach(u=>{try{const f=this.getFilterDef(u);if(!f||!f.createFilter||typeof f.createFilter!="function")return;const m=this.state.getFilterValues(u),b=f.defaultParams?{...f.defaultParams}:{};f.controls&&Array.isArray(f.controls)&&f.controls.forEach(F=>{const Q=F.property||F.id;b[Q]=m[F.id]??F.default});const C=new Set((f.controls||[]).map(F=>F.id));for(const[F,Q]of Object.entries(m))C.has(F)||(b[F]=Q);const x=this.renderer.sprite,N=this.renderer.originalTexture;b._sourceWidth=Math.round((N==null?void 0:N.width)||(x==null?void 0:x.width)||0),b._sourceHeight=Math.round((N==null?void 0:N.height)||(x==null?void 0:x.height)||0);const A=f.createFilter(b);A&&(i.push(A),this.instances[u]=A)}catch{r.push(u)}});try{t.filters=null,t.filters=i.length?i:null,this.renderer.render(),this.emit("filtersApplied",{count:i.length,failed:r})}catch(u){try{t.filters=null,this.renderer.render()}catch{}this.emit("filtersError",{error:u,failedFilters:r})}r.length>0}resetAll(e=void 0){for(const r in this.instances)delete this.instances[r];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 U=class U extends J.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 r=parseFloat(i[0]),s=parseFloat(i[1]);if(Number.isFinite(r)&&Number.isFinite(s)&&s>0)return r/s}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 r=this.state.get("crop.shape"),s=this._getEffectiveTargetAspect(),o=s!==null?{x:t.x,y:t.y,w:t.width,h:t.height}:{x:0,y:0,w:i.screen.width,h:i.screen.height};if(s!==null){const n=o.h*s,a=Math.min(e.width,o.w,n);e.width=a,e.height=a/s}else e.width=Math.min(e.width,o.w),e.height=Math.min(e.height,o.h);if(e.x=Math.max(o.x,Math.min(e.x,o.x+o.w-e.width)),e.y=Math.max(o.y,Math.min(e.y,o.y+o.h-e.height)),r!=="free"||this.state.get("crop.aspect")==="1:1"){const n=Math.min(e.width,e.height);e.width=n,e.height=n}this.state.set("crop.rect",e)}static calcAutoZoom(e,t,i,r,s,o,n){if(!e||!r||!s||!o)return null;const a=e.width>t,l=e.height>i;if(!a&&!l)return null;const h=U.AUTO_ZOOM_PADDING;let c=n;if(a){const p=e.width/(h*r*o);c=Math.min(c,p)}if(l){const p=e.height/(h*s*o);c=Math.min(c,p)}return c=Math.max(.1,c),c>=n-.01?null:c}_checkAutoZoom(){if(!this.state.get("autoZoomOnCropOverflow"))return;const e=Date.now();if(e-this._lastAutoZoomCheck<U.AUTO_ZOOM_THROTTLE_MS)return;this._lastAutoZoomCheck=e;const t=this.state.get("crop.rect"),i=this.renderer.sprite,r=this.renderer.originalTexture;if(!t||!i||!r)return;const s=U.calcAutoZoom(t,i.width,i.height,r.width,r.height,this.renderer.fitScale,this.renderer.zoom);s!==null&&this.renderer.setZoom(s,{keepCenter:!0})}drawOverlay(){const e=this._overlayCanvas;if(!e)return;const t=this.renderer.app;if(!t)return;const i=t.canvas,r=i.clientWidth,s=i.clientHeight,o=window.devicePixelRatio||1;(e.width!==Math.max(1,Math.floor(r*o))||e.height!==Math.max(1,Math.floor(s*o)))&&(e.width=Math.max(1,Math.floor(r*o)),e.height=Math.max(1,Math.floor(s*o)),e.style.width=r+"px",e.style.height=s+"px");const n=e.getContext("2d");if(!n)return;n.setTransform(o,0,0,o,0,0),n.clearRect(0,0,r,s),n.fillStyle="rgba(0, 0, 0, 0.5)",n.fillRect(0,0,r,s);const a=this.state.get("crop.rect");if(!a)return;const l=this.state.get("crop.shape");if(n.save(),l==="circle"){const b=a.x+a.width/2,C=a.y+a.height/2,x=Math.min(a.width,a.height)/2;n.beginPath(),n.arc(b,C,x,0,Math.PI*2),n.clip()}else n.beginPath(),n.rect(a.x,a.y,a.width,a.height),n.clip();n.clearRect(a.x,a.y,a.width,a.height),n.restore(),n.strokeStyle="#ffffff",n.lineWidth=2,n.setLineDash([5,5]),l==="circle"?(n.beginPath(),n.arc(a.x+a.width/2,a.y+a.height/2,Math.min(a.width,a.height)/2,0,Math.PI*2),n.stroke()):n.strokeRect(a.x,a.y,a.width,a.height),n.setLineDash([]),n.strokeStyle="rgba(255,255,255,0.3)",n.lineWidth=1;const h=a.width/3,c=a.height/3;for(let b=1;b<=2;b++)n.beginPath(),n.moveTo(a.x+h*b,a.y),n.lineTo(a.x+h*b,a.y+a.height),n.stroke(),n.beginPath(),n.moveTo(a.x,a.y+c*b),n.lineTo(a.x+a.width,a.y+c*b),n.stroke();const p=this.HANDLE_SIZE,u=[{x:a.x,y:a.y,m:"resize-nw"},{x:a.x+a.width,y:a.y,m:"resize-ne"},{x:a.x,y:a.y+a.height,m:"resize-sw"},{x:a.x+a.width,y:a.y+a.height,m:"resize-se"}],f=[{x:a.x+a.width/2,y:a.y,m:"n"},{x:a.x+a.width/2,y:a.y+a.height,m:"s"},{x:a.x,y:a.y+a.height/2,m:"w"},{x:a.x+a.width,y:a.y+a.height/2,m:"e"}],m=[...u,...f];for(const b of m){const C=this._hoverMode===b.m,x=C?p+4:p;n.beginPath(),n.rect(b.x-x/2,b.y-x/2,x,x),n.fillStyle=C?"#4da3ff":"#ffffff",n.strokeStyle="rgba(0,0,0,0.6)",n.lineWidth=1,n.fill(),n.stroke()}}_hitHandle(e,t){const i=this.state.get("crop.rect");if(!i)return null;const r=(s,o,n,a,l)=>Math.abs(s-n)<=l&&Math.abs(o-a)<=l;return r(e,t,i.x,i.y,this.HANDLE_SIZE)?"resize-nw":r(e,t,i.x+i.width,i.y,this.HANDLE_SIZE)?"resize-ne":r(e,t,i.x,i.y+i.height,this.HANDLE_SIZE)?"resize-sw":r(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,h,c,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")||(h=this._hoverMode)!=null&&h.endsWith("se")?"nwse-resize":(c=this._hoverMode)!=null&&c.endsWith("ne")||(p=this._hoverMode)!=null&&p.endsWith("sw")?"nesw-resize":"crosshair",this.drawOverlay();return}const r=this.state.get("crop.rect");if(!r)return;const s=i.x-this._dragStart.x,o=i.y-this._dragStart.y,n=this._getEffectiveTargetAspect();switch(this._dragMode){case"move":r.x=this._startRect.x+s,r.y=this._startRect.y+o;break;case"n":{const u=this._startRect.height-o;if(r.y=this._startRect.y+o,r.height=u,n){const f=u*n;r.x=this._startRect.x+(this._startRect.width-f)/2,r.width=f}break}case"s":{const u=this._startRect.height+o;if(r.height=u,n){const f=u*n;r.x=this._startRect.x+(this._startRect.width-f)/2,r.width=f}break}case"w":{const u=this._startRect.width-s;if(r.x=this._startRect.x+s,r.width=u,n){const f=u/n;r.y=this._startRect.y+(this._startRect.height-f)/2,r.height=f}break}case"e":{const u=this._startRect.width+s;if(r.width=u,n){const f=u/n;r.y=this._startRect.y+(this._startRect.height-f)/2,r.height=f}break}case"resize-nw":r.x=this._startRect.x+s,r.y=this._startRect.y+o,r.width=this._startRect.width-s,r.height=this._startRect.height-o;break;case"resize-ne":r.y=this._startRect.y+o,r.width=this._startRect.width+s,r.height=this._startRect.height-o;break;case"resize-sw":r.x=this._startRect.x+s,r.width=this._startRect.width-s,r.height=this._startRect.height+o;break;case"resize-se":r.width=this._startRect.width+s,r.height=this._startRect.height+o;break}r.width=Math.max(50,r.width),r.height=Math.max(50,r.height),this.state.set("crop.rect",r),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 o=this.state.get("crop.aspect"),n=this._getAspectRatio(o);let a,l;if(n){const p=t.width*.9,u=t.height*.9;p/u>n?(l=u,a=l*n):(a=p,l=a/n)}else{const p=Math.min(e.screen.width,e.screen.height)*.7;a=p,l=p}const h=t.x+(t.width-a)/2,c=t.y+(t.height-l)/2;i={x:h,y:c,width:a,height:l},this.state.set("crop.rect",i),o!=="free"&&this.constrainCropRect()}this.state.set("crop.dirty",!1);const r=e.stage;r.eventMode="static",r.hitArea=e.screen,r.cursor="crosshair",r.on("pointerdown",this._onPointerDown),r.on("pointermove",this._onPointerMove),r.on("pointerup",this._onPointerUp),r.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,r=this.state.get("crop.rect");if(!r||!t||!e||!i)return null;const s=window.PIXI,o=this.renderer.zoom,n=i.width/t.width,a=i.height/t.height,l=(r.x-t.x)*n,h=(r.y-t.y)*a;let c=Math.round(Math.max(1,r.width*n)),p=Math.round(Math.max(1,r.height*a)),u=Math.round(l),f=Math.round(h);if(c<=0||p<=0)return null;const m=new s.Container,b=new s.Sprite(i);if(this.state.get("crop.shape")==="circle"){const k=Math.round(Math.max(c,p)),E=u+c/2,z=f+p/2;u=Math.round(E-k/2),f=Math.round(z-k/2),c=p=k;const M=new s.Graphics;typeof M.circle=="function"&&typeof M.fill=="function"?M.circle(c/2,p/2,c/2).fill(16777215):(M.beginFill(16777215,1),M.drawCircle(c/2,p/2,c/2),M.endFill()),b.mask=M,m.addChild(M)}b.x=-u,b.y=-f,m.addChild(b);const x=s.RenderTexture.create({width:c,height:p});e.renderer.render({container:m,target:x,clear:!0}),m.destroy({children:!0});const N=this.renderer.originalTexture;N&&N!==this.renderer.baseTexture&&N.destroy(!0),this.renderer.originalTexture=x,e.stage.removeChild(t),t.destroy();const A=new s.Sprite(x);e.stage.addChild(A),this.renderer.sprite=A,this.renderer.fitScale=this.renderer.getFitScaleFor(x),this.renderer.setZoom(o,{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+f),width:c,height:p}:{x:u,y:f,width:c,height:p},w=this.state.get("crop.shape")||"free",S=this.state.get("crop.aspect")||"free";return this.disable(),this.state.set("crop.appliedRect",y),this.state.set("crop.appliedShape",w),this.state.set("crop.appliedAspect",S),this.state.set("crop.dirty",!1),this.emit("applied",{width:c,height:p}),{texture:x,preservedZoom:o}}applyFromPixelRect(e,t="free"){const i=this.renderer.app,r=this.renderer.sprite,s=this.renderer.originalTexture;if(!e||!r||!i||!s)return null;const o=window.PIXI,n=this.renderer.zoom;let a=Math.round(Math.max(1,e.width)),l=Math.round(Math.max(1,e.height)),h=Math.round(e.x),c=Math.round(e.y);if(a<=0||l<=0)return null;const p=new o.Container,u=new o.Sprite(s);if(t==="circle"){const C=Math.round(Math.max(a,l)),x=h+a/2,N=c+l/2;h=Math.round(x-C/2),c=Math.round(N-C/2),a=l=C;const A=new o.Graphics;typeof A.circle=="function"&&typeof A.fill=="function"?A.circle(a/2,l/2,a/2).fill(16777215):(A.beginFill(16777215,1),A.drawCircle(a/2,l/2,a/2),A.endFill()),u.mask=A,p.addChild(A)}u.x=-h,u.y=-c,p.addChild(u);const f=o.RenderTexture.create({width:a,height:l});i.renderer.render({container:p,target:f,clear:!0}),p.destroy({children:!0});const m=this.renderer.originalTexture;m&&m!==this.renderer.baseTexture&&m.destroy(!0),this.renderer.originalTexture=f,i.stage.removeChild(r),r.destroy();const b=new o.Sprite(f);return i.stage.addChild(b),this.renderer.sprite=b,this.renderer.fitScale=this.renderer.getFitScaleFor(f),this.renderer.setZoom(n,{keepCenter:!1}),this.renderer.applyViewTransform(),this.renderer.render(),{texture:f,preservedZoom:n}}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()}};ce(U,"AUTO_ZOOM_PADDING",1.1),ce(U,"AUTO_ZOOM_THROTTLE_MS",100);let oe=U;class Ne{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),r=i.blob,s=i.operationId,o=i.sessionKey,n=i.sourceHash,a=new FormData;a.append("image_file",r,"image.png"),a.append("operation_id",s),a.append("session_key",o),a.append("source_hash",n),a.append("tier",i.tier||"balanced"),i.targetRef&&a.append("target_ref",i.targetRef),i.model&&a.append("model",i.model),i.alpha_matting&&(a.append("alpha_matting","true"),a.append("alpha_f",String(i.alpha_f??10)),a.append("alpha_fr",String(i.alpha_fr??15)),a.append("alpha_erode_size",String(i.alpha_erode_size??10))),i.max_megapixels!==void 0&&a.append("max_megapixels",String(i.max_megapixels));let l,h;const c=this._createAbortController(),p=u=>c?{...u,signal:c.signal}:u;try{try{l=await fetch(this._endpoint,p({method:"POST",body:a,credentials:"include"}))}catch(m){if(c!=null&&c.signal.aborted)throw m;h=m}if((!l||!l.ok)&&this._fallbackEndpoint)try{l=await fetch(this._fallbackEndpoint,p({method:"POST",body:a}))}catch(m){if(c!=null&&c.signal.aborted)throw m;h||(h=m)}if(!l)throw h||new Error("Network error: Unable to connect to background removal service");if(!l.ok){let m=`Background removal failed (HTTP ${l.status})`;try{const b=await l.text();b&&(m+=`: ${b}`)}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")||s,sessionKey:l.headers.get("X-Session-Key")||o,sourceHash:l.headers.get("X-Source-Hash")||n,targetRef:l.headers.get("X-Target-Ref")||i.targetRef||null}}finally{this._releaseAbortController(c)}}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 r=this._createAbortController();let s;try{if(s=await fetch(t,{method:"POST",body:JSON.stringify(i),credentials:"include",headers:{Accept:"application/json","Content-Type":"application/json"},...r?{signal:r.signal}:{}}),!s.ok){let o=`Background removal failed (HTTP ${s.status})`;try{const n=await s.json();n!=null&&n.message&&(o+=`: ${n.message}`)}catch{}throw new Error(o)}return await s.json()}finally{this._releaseAbortController(r)}}async _dataUrlToBlob(e){if(e.startsWith("data:")){const[i,r]=e.split(","),s=i.match(/:(.*?);/),o=s?s[1]:"image/png",n=atob(r),a=new Uint8Array(n.length);for(let l=0;l<n.length;l++)a[l]=n.charCodeAt(l);return new Blob([a],{type:o})}return(await fetch(e)).blob()}_blobToDataUrl(e){return new Promise((t,i)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>i(new Error("Failed to read blob as data URL")),r.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(r=>r.toString(16).padStart(2,"0")).join("")}}function d(g,e={},...t){const i=document.createElement(g);for(const[r,s]of Object.entries(e))if(s!=null)if(r==="className")i.className=s;else if(r==="style"&&typeof s=="object")Object.assign(i.style,s);else if(r.startsWith("on")&&typeof s=="function"){const o=r.slice(2).toLowerCase();i.addEventListener(o,s)}else r==="dataset"&&typeof s=="object"?Object.assign(i.dataset,s):i.setAttribute(r,s);for(const r of t)typeof r=="string"?i.appendChild(document.createTextNode(r)):r instanceof HTMLElement&&i.appendChild(r);return i}function ge({id:g,label:e,min:t=0,max:i=1,step:r=.01,value:s=.5,onChange:o}){const n=g.includes("-")?g.split("-").slice(1).join("-"):g,a=d("div",{className:"slider-control slider-wrapper","data-control":n,"data-testid":`slider-${n}`}),l=d("div",{className:"slider-header"},d("label",{for:g,className:"slider-label"},e),d("span",{className:"slider-value",id:`${g}-value`},de(s))),h=d("input",{type:"range",id:g,className:"slider-input",min:String(t),max:String(i),step:String(r),value:String(s),onInput:c=>{const p=parseFloat(c.target.value),u=a.querySelector(".slider-value");u&&(u.textContent=de(p)),o==null||o(p)}});return a.appendChild(l),a.appendChild(h),a.setValue=c=>{h.value=String(c);const p=a.querySelector(".slider-value");p&&(p.textContent=de(c))},a}function de(g){return Number.isInteger(g)?String(g):g.toFixed(2)}function _e({id:g,label:e,checked:t=!1,onChange:i}){const r=d("div",{className:"toggle-control"}),s=d("label",{className:"toggle-label",for:g},e),o=d("input",{type:"checkbox",id:g,className:"toggle-input",checked:t?"checked":void 0,onChange:l=>i==null?void 0:i(l.target.checked)}),n=d("div",{className:"toggle-switch",onClick:l=>{l.target!==o&&(o.checked=!o.checked,i==null||i(o.checked))}}),a=d("span",{className:"toggle-slider"});return n.appendChild(o),n.appendChild(a),r.appendChild(s),r.appendChild(n),r.setChecked=l=>{o.checked=l},r}function me({id:g,label:e,value:t="#000000",onChange:i}){const r=d("div",{className:"color-control"}),s=d("label",{className:"color-label",for:g},e),o=d("input",{type:"color",id:g,className:"color-input",value:t,onInput:n=>i==null?void 0:i(n.target.value)});return r.appendChild(s),r.appendChild(o),r.setValue=n=>{o.value=n},r}function be({id:g,label:e,value:t="",placeholder:i="",onCommit:r}){const s=d("div",{className:"text-control","data-control":g,"data-testid":`text-${g}`}),o=d("label",{className:"text-label",for:g},e);let n=t;const a=d("input",{type:"text",id:g,className:"text-input",value:t,placeholder:i,onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),l(),a.blur())},onBlur:()=>l()});function l(){const h=a.value;h!==n&&(n=h,r==null||r(h))}return s.appendChild(o),s.appendChild(a),s.setValue=h=>{const c=h==null?"":String(h);a.value=c,n=c},s}function ye({id:g,label:e,options:t=[],value:i,onChange:r}){const s=d("div",{className:"select-control"}),o=d("label",{className:"select-label",for:g},e),n=d("select",{id:g,className:"select-input",onChange:a=>r==null?void 0:r(a.target.value)});for(const a of t){const l=d("option",{value:a.value},a.label);a.value===i&&(l.selected=!0),n.appendChild(l)}return s.appendChild(o),s.appendChild(n),s.setValue=a=>{n.value=a},s}function L({label:g,className:e="",onClick:t,icon:i=null,disabled:r=!1}){const s=d("button",{type:"button",className:`btn ${e}`.trim(),onClick:t,disabled:r?"disabled":void 0});if(i){const o=d("span",{className:"btn-icon"});o.innerHTML=i;const n=o.querySelector("svg");n&&n.setAttribute("aria-hidden","true"),s.appendChild(o)}return g&&s.appendChild(document.createTextNode(g)),s}function D({icon:g,title:e,className:t="",onClick:i,disabled:r=!1,testId:s=null,ariaLabel:o=null}){const n={type:"button",className:`icon-btn ${t}`.trim(),title:e,"aria-label":o||e,onClick:i,disabled:r?"disabled":void 0};s&&(n.dataset={testid:s});const a=d("button",n);a.innerHTML=g;const l=a.querySelector("svg");return l&&l.setAttribute("aria-hidden","true"),a}function se({label:g,icon:e,active:t=!1,onClick:i}){const r=d("button",{type:"button",className:`chip ${t?"active":""}`.trim(),onClick:i});if(e){const s=d("span",{className:"chip-icon"});s.innerHTML=e;const o=s.querySelector("svg");o&&o.setAttribute("aria-hidden","true"),r.appendChild(s)}return r.appendChild(d("span",{className:"chip-label"},g)),r.setActive=s=>{r.classList.toggle("active",s)},r}class Be{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=d("div",{className:"editor-toolbar"});const e=d("div",{className:"toolbar-section toolbar-left"}),t=D({icon:Ye,title:"Open Image",className:"toolbar-btn",testId:"btn-open-image",ariaLabel:"Open image file",onClick:()=>this.editor.openFilePicker()});e.appendChild(t);const i=d("div",{className:"toolbar-section toolbar-right"});this._themeBtn=D({icon:this.state.get("isDarkMode")?we:xe,title:"Toggle Theme",className:"toolbar-btn toolbar-btn-theme",testId:"btn-toggle-theme",ariaLabel:"Toggle theme",onClick:()=>this.editor.toggleTheme()}),this._cropBtn=D({icon:Me,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 r=d("div",{className:"remove-bg-control"});this._removeBgTierSelect=d("select",{className:"remove-bg-tier-select",title:"Background removal quality","aria-label":"Background removal quality",dataset:{testid:"select-remove-background-tier"},onChange:h=>{this._removeBgTier=h.target.value}});for(const h of[["fast","Fast"],["balanced","Balanced"],["best","Best"]]){const c=d("option",{value:h[0]},h[1]);h[0]===this._removeBgTier&&(c.selected=!0),this._removeBgTierSelect.appendChild(c)}this._removeBgBtn=D({icon:lt,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=d("span",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true"}),r.appendChild(this._removeBgTierSelect),r.appendChild(this._removeBgBtn),r.appendChild(this._removeBgStatus);const s=D({icon:Se,title:"Reset All",className:"toolbar-btn",testId:"btn-reset-all",ariaLabel:"Reset all changes",onClick:()=>this.editor.resetAll()}),o=d("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()}),n=d("span",{className:"btn-icon"});n.innerHTML=Fe;const a=n.querySelector("svg");a&&a.setAttribute("aria-hidden","true"),o.appendChild(n),o.appendChild(d("span",{className:"toolbar-save-label"},"Save"));const l=D({icon:ae,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(r),i.appendChild(s),i.appendChild(o),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?we:xe});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 r=this.state.on("change:isProcessing",()=>this._updateRemoveBgButton());this._unsubscribers.push(r);const s=this.state.on("change:backgroundRemovalAvailable",()=>this._updateRemoveBgButton());this._unsubscribers.push(s);const o=this.state.on("change:editorDocument",()=>this._updateRemoveBgButton());this._unsubscribers.push(o);const n=this.state.on("change:layers",()=>this._updateRemoveBgButton());this._unsubscribers.push(n);const a=this.state.on("change:activeLayerId",()=>this._updateRemoveBgButton());this._unsubscribers.push(a)}_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 re=le;class dt{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=d("div",{className:"category-carousel-container","data-testid":"category-carousel"}),this._leftBtn=D({icon:pe,title:"Previous categories",className:"carousel-nav carousel-nav-left",onClick:()=>this._scrollLeft()}),this._carousel=d("div",{className:"category-carousel"}),re.forEach(i=>{const r=se({label:i.name,icon:i.icon,active:this.state.get("selectedCategory")===i.id,onClick:()=>this._selectCategory(i.id)});r.dataset.categoryId=i.id,r.dataset.category=i.id,r.dataset.testid=`category-${i.id}`,this._chips.set(i.id,r),this._carousel.appendChild(r)}),this._rightBtn=D({icon:fe,title:"Next categories",className:"carousel-nav carousel-nav-right",onClick:()=>this._scrollRight()}),this._pagination=d("div",{className:"carousel-pagination",role:"tablist","aria-label":"Category pages"});const t=Math.ceil(re.length/3);for(let i=0;i<t;i++){const r=d("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(r)}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,r)=>{i.setActive(r===t)})});this._unsubscribers.push(e)}_selectCategory(e){var r;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"}),(r=this._onSelect)==null||r.call(this,e)}_scrollLeft(){this._scrollIndex>0&&(this._scrollIndex--,this._scrollCarousel())}_scrollRight(){this._scrollIndex<re.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>=re.length-3)}_updatePagination(){if(this._pagination){const e=this._pagination.querySelectorAll(".pagination-dot"),t=Math.floor(this._scrollIndex/3);e.forEach((i,r)=>{const s=r===t;i.classList.toggle("active",s),i.setAttribute("aria-selected",s?"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 ut{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=d("div",{className:"filter-carousel-container"}),this._leftBtn=D({icon:pe,title:"Previous filters",className:"carousel-nav carousel-nav-left",onClick:()=>this._scrollLeft()}),this._carousel=d("div",{className:"filter-carousel"}),this._rightBtn=D({icon:fe,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"),r=this.state.get("selectedFilter");t.forEach(s=>{const o=this._createFilterCard(s,{isActive:i.has(s.id),isSelected:r===s.id});this._filterCards.set(s.id,o),this._carousel.appendChild(o)}),this._updateNavButtons()}_createFilterCard(e,{isActive:t,isSelected:i}){const r=d("div",{className:`filter-card ${t?"active":""} ${i?"selected":""}`,"data-filter":e.id,"data-testid":`filter-${e.id}`,onClick:()=>this._handleCardClick(e.id)}),s=d("div",{className:"filter-preview"}),o=d("span",{className:"filter-preview-text"},e.name.charAt(0));s.appendChild(o);const n=d("span",{className:"filter-name",title:e.name},e.name),a=d("button",{className:`filter-toggle ${t?"active":""}`,onClick:l=>{var p;l.stopPropagation();const c=!this.state.get("activeFilters").has(e.id);this._handleToggle(e.id,c),c&&(this.state.set("selectedFilter",e.id),(p=this._onSelect)==null||p.call(this,e.id))}});return a.innerHTML=t?ne:"",r.appendChild(s),r.appendChild(n),r.appendChild(a),r._toggle=a,r._isActive=t,r}_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 r=e.has(i);t.classList.toggle("active",r),t._toggle.classList.toggle("active",r),t._toggle.innerHTML=r?ne:"",t._isActive=r})}_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 pt{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=d("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(d("div",{className:"no-filter-selected"},"Select a filter to adjust"));return}const t=this.filterManager.getFilterDef(e);if(!t){this.element.appendChild(d("div",{className:"no-filter-selected"},"Filter not found"));return}const i=d("div",{className:"adjustments-header"});i.appendChild(d("span",{className:"adjustments-title"},t.name)),i.appendChild(L({label:"Reset",className:"btn-text",onClick:()=>this._handleReset(e)})),this.element.appendChild(i);const r=d("div",{className:"adjustments-grid"}),s=this.state.getFilterValues(e);(t.controls||[]).forEach(n=>{const a=s[n.id]??n.default,l=this._createControl(e,n,a);l&&(this._controls.set(n.id,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(a=>{const l=a.property||a.id,h=s[l]??a.default,c=this._createControl(e,a,h);c&&(this._controls.set(a.id,c),r.appendChild(c))})}this.element.appendChild(r)}_createControl(e,t,i){if(t.hidden)return null;const r=t.label||t.id,s=this._normalizeControlType(t.type),o=t.property||t.id;switch(s){case"slider":return ge({id:`${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:l=>this._handleChange(e,o,l)});case"toggle":return _e({id:`${e}-${t.id}`,label:r,checked:!!i,onChange:l=>this._handleChange(e,o,l)});case"color":return me({id:`${e}-${t.id}`,label:r,value:typeof i=="string"&&i.startsWith("#")?i:t.default||"#000000",onChange:l=>this._handleChange(e,o,l)});case"select":const n=this._normalizeOptions(t.options);return ye({id:`${e}-${t.id}`,label:r,options:n,value:i??t.default,onChange:l=>this._handleChange(e,o,l)});case"text":return be({id:`${e}-${t.id}`,label:r,value:typeof i=="string"?i:t.default??"",placeholder:t.placeholder||"",onCommit:l=>this._handleChange(e,o,l)});case"button":const a=d("div",{className:"button-control"});return a.appendChild(L({label:r,className:"btn-secondary",onClick:()=>this._handleAction(e,t.action||t.id)})),a;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 r;(r=this._onChange)==null||r.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(r=>{const s=this._controls.get(r.id);if(s&&typeof s.setValue=="function"){const o=t[r.id]??r.default;s.setValue(o)}})}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 ft{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:r,onAction:s}){this._onChange=t,this._onReset=i,this._onRemove=r,this._onAction=s,this._container=e,this._drawer=d("div",{className:"mobile-filter-drawer"});const o=d("div",{className:"drawer-header"});this._titleEl=d("span",{className:"drawer-title"},"Filter");const n=d("div",{className:"drawer-header-actions"}),a=L({label:"Reset",className:"btn-text",onClick:()=>{var c;this._currentFilterId&&((c=this._onReset)==null||c.call(this,this._currentFilterId),this._renderControls())}}),l=L({label:"Remove",className:"btn-text btn-danger",onClick:()=>{var c;this._currentFilterId&&((c=this._onRemove)==null||c.call(this,this._currentFilterId),this.close())}}),h=D({icon:ae,title:"Close",className:"btn-icon-sm",ariaLabel:"Close drawer",onClick:()=>this.close()});n.appendChild(a),n.appendChild(l),n.appendChild(h),o.appendChild(this._titleEl),o.appendChild(n),this._drawer.appendChild(o),this._body=d("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=d("div",{className:"adjustments-grid"}),i=this.state.getFilterValues(this._currentFilterId);(e.controls||[]).forEach(s=>{if(s.hidden)return;const o=this._createControl(this._currentFilterId,s,i[s.id]??s.default);o&&(this._controls.set(s.id,o),t.appendChild(o))});const r=this.filterManager.getInstance(this._currentFilterId);if(r&&typeof r.getDynamicControls=="function"){let s=[];try{s=r.getDynamicControls()||[]}catch{}s.forEach(o=>{const n=o.property||o.id,a=i[n]??o.default,l=this._createControl(this._currentFilterId,o,a);l&&(this._controls.set(o.id,l),t.appendChild(l))})}this._body.appendChild(t)}_createControl(e,t,i){if(t.hidden)return null;const r=t.label||t.id,s=this._normalizeControlType(t.type),o=t.property||t.id;switch(s){case"slider":return ge({id:`drawer-${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 a;return(a=this._onChange)==null?void 0:a.call(this,e,o,n)}});case"toggle":return _e({id:`drawer-${e}-${t.id}`,label:r,checked:!!i,onChange:n=>{var a;return(a=this._onChange)==null?void 0:a.call(this,e,o,n)}});case"color":return me({id:`drawer-${e}-${t.id}`,label:r,value:typeof i=="string"&&i.startsWith("#")?i:t.default||"#000000",onChange:n=>{var a;return(a=this._onChange)==null?void 0:a.call(this,e,o,n)}});case"select":{const n=this._normalizeOptions(t.options);return ye({id:`drawer-${e}-${t.id}`,label:r,options:n,value:i??t.default,onChange:a=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,o,a)}})}case"text":return be({id:`drawer-${e}-${t.id}`,label:r,value:typeof i=="string"?i:t.default??"",placeholder:t.placeholder||"",onCommit:n=>{var a;return(a=this._onChange)==null?void 0:a.call(this,e,o,n)}});case"button":{const n=d("div",{className:"button-control"});return n.appendChild(L({label:r,className:"btn-secondary",onClick:()=>{var a;(a=this._onAction)==null||a.call(this,e,t.action||t.id),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}_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 gt{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=d("div",{className:"mobile-active-filters","data-testid":"mobile-active-filters"}),this._scrollContainer=d("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=d("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 r=this._createChip(t,i);this._chips.set(t,r),this._scrollContainer.appendChild(r)}),this._updateSelectedState()}_createChip(e,t){const i=d("div",{className:"active-filter-chip","data-filter-id":e,"data-testid":`active-chip-${e}`}),r=d("span",{className:"active-filter-chip-label",onClick:o=>{var n;o.stopPropagation(),(n=this._onSelect)==null||n.call(this,e)}},t.name),s=d("button",{className:"active-filter-chip-check","aria-label":`Remove ${t.name} filter`,onClick:o=>{var n;o.stopPropagation(),(n=this._onToggle)==null||n.call(this,e,!1)}});return s.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(r),i.appendChild(s),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 _t=[{id:"free",name:"Free",icon:ot},{id:"square",name:"Square",icon:st},{id:"circle",name:"Circle",icon:nt}],mt=[{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"}],bt=[{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 W(g){if(!Number.isFinite(Number(g)))return 0;const e=Number(g)%360;return e<0?e+360:e}class Le{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=d("div",{className:"crop-controls","data-testid":"crop-controls"}),this.element.appendChild(this._renderRotationSection());const e=d("div",{className:"crop-section"});e.appendChild(d("label",{className:"section-label"},"Shape"));const t=d("div",{className:"chip-row"}),i=this.state.get("crop.shape");_t.forEach(l=>{const h=se({label:l.name,icon:l.icon,active:i===l.id,onClick:()=>this._selectShape(l.id)});h.dataset.shape=l.id,h.dataset.testid=`crop-shape-${l.id}`,this._shapeChips.set(l.id,h),t.appendChild(h)}),e.appendChild(t),this.element.appendChild(e),this.state.get("lockCropShape")&&(e.style.display="none"),this._shapeSection=e,this._aspectSection=d("div",{className:"crop-section"}),this._aspectSection.appendChild(d("label",{className:"section-label"},"Aspect Ratio"));const r=d("div",{className:"chip-row aspect-row"}),s=this.state.get("crop.aspect");mt.forEach(l=>{const h=se({label:l.name,active:s===l.id,onClick:()=>this._selectAspect(l.id)});h.dataset.ratio=l.id,h.dataset.testid=`crop-ratio-${l.id}`,this._aspectChips.set(l.id,h),r.appendChild(h)}),this._aspectSection.appendChild(r),this.element.appendChild(this._aspectSection),this._updateAspectVisibility();const o=d("div",{className:"crop-actions"}),n=L({label:"Cancel",className:"btn-secondary crop-cancel-btn",icon:ae,onClick:()=>this.cropManager.cancel()});n.dataset.testid="cancel-crop";const a=L({label:"Apply Crop",className:"btn-primary crop-apply-btn",icon:ne,onClick:()=>this._applyCropAndReturnToFilters()});return a.dataset.testid="apply-crop",o.appendChild(n),o.appendChild(a),this.element.appendChild(o),this._subscribeToState(),this.element}_renderRotationSection(){const e=d("div",{className:"crop-section rotation-section"});e.appendChild(d("label",{className:"section-label"},"Rotate"));const t=d("div",{className:"rotation-action-row"}),i=L({label:"Left 90°",className:"btn-secondary rotation-action-btn",icon:qe,onClick:()=>this._rotateBy(-90)});i.dataset.testid="rotate-left-90";const r=L({label:"Right 90°",className:"btn-secondary rotation-action-btn",icon:Ke,onClick:()=>this._rotateBy(90)});r.dataset.testid="rotate-right-90";const s=L({label:"Rotate 180°",className:"btn-secondary rotation-action-btn",onClick:()=>this._rotateBy(180)});s.dataset.testid="rotate-180";const o=L({label:"Rotate 270°",className:"btn-secondary rotation-action-btn",onClick:()=>this._rotateBy(270)});o.dataset.testid="rotate-270",t.appendChild(i),t.appendChild(r),t.appendChild(s),t.appendChild(o),e.appendChild(t);const n=d("div",{className:"chip-row rotation-preset-row"}),a=W(this.state.get("transform.rotation")??0);bt.forEach(u=>{const f=se({label:u.label,active:Math.round(a)===u.angle,onClick:()=>this._setRotation(u.angle)});f.dataset.angle=u.id,f.dataset.testid=`rotation-preset-${u.id}`,this._rotationPresetChips.set(u.id,f),n.appendChild(f)}),e.appendChild(n);const l=d("div",{className:"rotation-arbitrary"}),h=d("div",{className:"rotation-angle-header"},d("label",{className:"rotation-angle-label",for:"image-editor-rotation-angle"},"Angle"),d("span",{className:"rotation-angle-value"},this._formatAngle(a)));this._rotationValue=h.querySelector(".rotation-angle-value"),this._rotationRange=d("input",{id:"image-editor-rotation-angle",type:"range",className:"slider-input rotation-range",min:"0",max:"360",step:"1",value:String(Math.round(a)),"aria-label":"Rotation angle",onInput:u=>this._previewAngleValue(u.target.value),onChange:u=>this._setRotation(Number(u.target.value))}),this._rotationNumber=d("input",{type:"number",className:"text-input rotation-number-input",min:"-360",max:"360",step:"1",value:this._formatPlainAngle(a),"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 c=d("div",{className:"rotation-angle-row"},this._rotationRange,this._rotationNumber);l.appendChild(h),l.appendChild(c);const p=L({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:r})=>{this._shapeChips.forEach((s,o)=>{s.setActive(o===r)}),this._updateAspectVisibility()});this._unsubscribers.push(e);const t=this.state.on("change:crop.aspect",({value:r})=>{this._aspectChips.forEach((s,o)=>{s.setActive(o===r)})});this._unsubscribers.push(t);const i=this.state.on("change:transform.rotation",({value:r})=>{this._syncRotationControls(r)});this._unsubscribers.push(i)}_rotateBy(e){var i,r;((r=(i=this.editor)==null?void 0:i.rotateBy)==null?void 0:r.call(i,e))!==!1&&this._syncRotationControls(this.state.get("transform.rotation")??0)}_setRotation(e){var r,s;const t=W(e);if(((s=(r=this.editor)==null?void 0:r.setRotationAngle)==null?void 0:s.call(r,t))===!1){this._syncRotationControls(this.state.get("transform.rotation")??0);return}this._syncRotationControls(t)}_previewAngleValue(e){const t=W(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=W(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(W(e))%360;this._rotationPresetChips.forEach((i,r)=>{i.setActive(Number(r)===t)})}_formatAngle(e){return`${this._formatPlainAngle(e)}°`}_formatPlainAngle(e){const t=W(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 yt{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:r,onSelect:s}){this._onRemove=e,this._onReset=t,this._onClearAll=i,this._onUpdateValue=r,this._onSelect=s,this.element=d("div",{className:"active-filters-panel","data-testid":"active-filters-panel"});const o=d("div",{className:"panel-header"});o.appendChild(d("h3",{className:"panel-title"},"Active Filters"));const n=L({label:"Clear All",className:"btn-text btn-danger",onClick:()=>this._handleClearAll()});return n.dataset.testid="clear-all-filters",o.appendChild(n),this.element.appendChild(o),this._listContainer=d("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(d("div",{className:"no-filters-message"},"No filters active"));return}e.forEach(t=>{const i=this.filterManager.getFilterDef(t);if(!i)return;const r=this._createFilterItem(t,i);this._filterItems.set(t,r),this._listContainer.appendChild(r)})}_createFilterItem(e,t){const r=this.state.get("selectedFilter")===e,s=d("div",{className:`active-filter-item ${r?"selected":""}`,"data-active-filter":e,"data-testid":`active-filter-${e}`,onClick:u=>{u.target.closest(".filter-item-actions")||this._handleSelect(e)}}),o=d("div",{className:"filter-item-header"}),n=d("span",{className:"filter-item-name"},t.name),a=d("div",{className:"filter-item-actions"}),l=D({icon:Se,title:"Reset filter",className:"btn-icon-sm",onClick:()=>this._handleReset(e)}),h=D({icon:Re,title:"Remove filter",className:"btn-icon-sm btn-danger",onClick:()=>this._handleRemove(e)});a.appendChild(l),a.appendChild(h),o.appendChild(n),o.appendChild(a),s.appendChild(o);const c=this.state.getFilterValues(e),p=d("div",{className:"filter-item-summary"});return p.textContent=this._getValuesSummary(t,c),s.appendChild(p),s._summaryEl=p,s}_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(r=>{const s=this._normalizeControlType(r.type);if(s==="button")return;const o=r.label||r.id,n=t[r.id]??r.default;n!==r.default&&(s==="slider"?i.push(`${o}: ${this._formatValue(n)}`):s==="toggle"?n&&i.push(o):s==="color"?i.push(`${o}: ${n}`):s==="select"&&i.push(`${o}: ${n}`))}),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 r=this.state.getFilterValues(t);e._summaryEl.textContent=this._getValuesSummary(i,r)})}_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 $={name:"free",initialMode:"filters",cropShape:"free",aspectRatio:"free",autoZoomOnCropOverflow:!1,lockCropShape:!1,lockAspectRatio:!1,showFilters:!0,showCropControls:!0,maxExportWidth:void 0,maxExportHeight:void 0},ue={free:{...$},avatar:{...$,name:"avatar",initialMode:"crop",cropShape:"circle",aspectRatio:"1:1",autoZoomOnCropOverflow:!0,lockCropShape:!0,lockAspectRatio:!0},banner:{...$,name:"banner",initialMode:"crop",cropShape:"square",aspectRatio:"16:9",autoZoomOnCropOverflow:!1,lockCropShape:!1,lockAspectRatio:!0},cover:{...$,name:"cover",initialMode:"crop",cropShape:"free",aspectRatio:"24:5",autoZoomOnCropOverflow:!0,lockCropShape:!0,lockAspectRatio:!0},product:{...$,name:"product",initialMode:"filters",cropShape:"square",aspectRatio:"1:1",autoZoomOnCropOverflow:!1,lockCropShape:!1,lockAspectRatio:!1}};function De(g){if(!g)return{...ue.free};if(typeof g=="object"&&g!==null)return{...$,...g};const e=ue[g];return e?{...e}:{...ue.free}}function Z(g){if(!Number.isFinite(Number(g)))return 0;const e=Number(g)%360;return e<0?e+360:e}function vt(g,e){const t=Z(g);return(Z(e)-t+540)%360-180}class wt extends J.EventEmitter{constructor(e,t={}){var s,o,n,a;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?De(t.preset):null,r=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},...r,...t},this._preset=i,this._state=J.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 Ce,this._filterManager=new Ee(this._state,this._renderer),this._cropManager=new oe(this._state,this._renderer),this._removeBgManager=null,this._backgroundRemovalAvailable=!1,((s=this._options.backgroundRemoval)==null?void 0:s.enabled)!==!1&&(this._removeBgManager=new Ne({endpoint:(o=this._options.backgroundRemoval)==null?void 0:o.endpoint,optionsEndpoint:(n=this._options.backgroundRemoval)==null?void 0:n.optionsEndpoint,fallbackEndpoint:(a=this._options.backgroundRemoval)==null?void 0:a.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=d("div",{className:`vanilla-image-editor ${this._state.get("isDarkMode")?"dark":"light"}`});const e=d("div",{className:"editor-toolbar-container"});this._editorEl.appendChild(e),this._toolbarContainer=e;const t=d("div",{className:"editor-content"}),i=d("div",{className:"canvas-section"});this._canvasContainer=d("div",{className:"canvas-container"}),this._cropOverlay=d("canvas",{className:"crop-overlay","aria-hidden":"true"}),i.appendChild(this._canvasContainer),i.appendChild(this._cropOverlay),t.appendChild(i),this._controlsSection=d("div",{className:"controls-section"}),t.appendChild(this._controlsSection),this._editorEl.appendChild(t),this._fileInput=d("input",{type:"file",accept:"image/*",className:"hidden-file-input","aria-label":"Choose image file to edit",onChange:r=>this._handleFileSelect(r)}),this._editorEl.appendChild(this._fileInput),this._container.appendChild(this._editorEl)}_initUI(){this._toolbar=new Be(this._state,this),this._toolbarContainer.appendChild(this._toolbar.render()),this._filterControlsEl=d("div",{className:"filter-controls-container"}),this._categoryCarousel=new dt(this._state,this),this._filterControlsEl.appendChild(this._categoryCarousel.render(r=>{}));const e=d("div",{className:"filter-layout"}),t=d("div",{className:"filter-left-column"});this._filterCarousel=new ut(this._state,this._filterManager),t.appendChild(this._filterCarousel.render({onToggle:(r,s)=>this._handleFilterToggle(r,s),onSelect:r=>{this._handleFilterSelect(r),this._isMobile&&this._mobileFilterDrawer&&this._mobileFilterDrawer.open(r)}})),this._filterAdjustments=new pt(this._state,this._filterManager),t.appendChild(this._filterAdjustments.render({onChange:(r,s,o)=>this._handleFilterChange(r,s,o),onReset:r=>this._handleFilterReset(r),onAction:(r,s)=>this._handleFilterAction(r,s)})),e.appendChild(t);const i=d("div",{className:"filter-right-column"});this._activeFiltersPanel=new yt(this._state,this._filterManager),i.appendChild(this._activeFiltersPanel.render({onRemove:r=>this._handleFilterToggle(r,!1),onReset:r=>this._handleFilterReset(r),onClearAll:()=>this.resetAll(),onSelect:r=>this._handleFilterSelect(r)})),e.appendChild(i),this._filterControlsEl.appendChild(e),this._mobileActiveFilters=new gt(this._state,this._filterManager),this._filterControlsEl.appendChild(this._mobileActiveFilters.render({onToggle:(r,s)=>this._handleFilterToggle(r,s),onSelect:r=>{this._handleFilterSelect(r),this._isMobile&&this._mobileFilterDrawer&&this._mobileFilterDrawer.open(r)}})),this._cropControls=new Le(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 ft(this._state,this._filterManager),this._mobileFilterDrawer.build(this._controlsSection,{onChange:(r,s,o)=>this._handleFilterChange(r,s,o),onReset:r=>this._handleFilterReset(r),onRemove:r=>{this._handleFilterToggle(r,!1),this._state.set("selectedFilter",null)},onAction:(r,s)=>this._handleFilterAction(r,s)})}_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 n,a;if(this._destroyed)return;(a=(n=this._removeBgManager)==null?void 0:n.cancelActiveRequests)==null||a.call(n,"image-load");const i=++this._loadVersion;let r=e,s=null;this._resetEditorState(),this._state.set("hasImage",!1),this._state.set("imageUrl",null),e instanceof Blob&&(r=URL.createObjectURL(e),s=r,this._objectUrls.add(r));const o=await this._renderer.loadTexture(r,{isCurrent:()=>!this._destroyed&&this._loadVersion===i});if(this._destroyed||this._loadVersion!==i){this._revokeObjectUrl(s);return}if(!o){this._revokeObjectUrl(s),this.emit("error",new Error("Failed to load image"));return}s?this._replaceActiveObjectUrl(s):this._clearActiveObjectUrl(),this._state.set("hasImage",!0),this._state.set("imageUrl",r),t.state&&this._hydrateState(t.state),this._options.initialMode==="crop"&&this.setMode("crop"),this.emit("imageLoaded",{url:r})}_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=Z(((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 r=e.crop.shape||"free",s=e.crop.aspectRatio||"free";e.crop.rect&&(this._cropManager.applyFromPixelRect(e.crop.rect,r),this._state.set("crop.appliedRect",{...e.crop.rect}),this._state.set("crop.appliedShape",r),this._state.set("crop.appliedAspect",s)),this._state.set("crop.shape",r),this._state.set("crop.aspect",s)}if(Array.isArray(e.filters)){let r=null;for(const s of e.filters)if(s.enabled&&(r===null&&(r=s.id),this._state.toggleFilter(s.id,!0),this._filterManager.initializeValues(s.id),s.values))for(const[o,n]of Object.entries(s.values))this._state.setFilterValue(s.id,o,n);if(r!==null){this._state.set("selectedFilter",r);const s=this._filterManager.getFilterDef(r);if(typeof(s==null?void 0:s.category)=="string"){const o=Ae[s.category]??s.category;this._state.set("selectedCategory",o)}}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 o of e){const n=this._state.getFilterValues(o);t.push({id:o,enabled:!0,values:{...n}})}const i=this._state.get("crop.appliedRect"),r=this._state.get("crop.rect"),s=i||r;return{version:1,crop:{rect:s?{...s}: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:Z(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=Z(this._state.get("transform.rotation")??0),i=Z(e),r=vt(t,i),s=this._state.get("mode")==="crop";if(Math.abs(r)>.001){if(s&&this._cropManager.disable(),!this._renderer.rotateBy(r))return s&&this._cropManager.enable(),!1;this._filterManager.applyFilters(),this._state.set("crop.rect",null),this._state.set("crop.dirty",!1),s&&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 r=this.exportImage("png");if(!r)throw new Error("Failed to export image for background removal");const s=await this._removeBgManager.preparePreviewRequest(r,e),o=this._buildPreviewBackgroundRemovalContext(s),n=await this._removeBgManager.removeBackground(s.blob,s);return await this._isCurrentPreviewBackgroundRemovalContext(o,n)?(await this.loadImage(n.dataUrl),this.emit("background-removed",{model:n.model,processMs:n.processMs}),{model:n.model,processMs:n.processMs}):(this.emit("background-removal-stale",{operationId:o.operationId,sourceHash:o.sourceHash}),{stale:!0})}catch(r){throw this.emit("error",{error:r,context:"background-removal"}),r}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=d("div",{className:"editor-loading-overlay"},[d("div",{className:"editor-loading-spinner"}),d("div",{className:"editor-loading-text"},e)]);else{const r=this._loadingOverlay.querySelector(".editor-loading-text");r&&(r.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,r,s,o,n,a,l,h,c,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),(r=this._toolbar)==null||r.destroy(),(s=this._categoryCarousel)==null||s.destroy(),(o=this._filterCarousel)==null||o.destroy(),(n=this._filterAdjustments)==null||n.destroy(),(a=this._mobileFilterDrawer)==null||a.destroy(),(l=this._mobileActiveFilters)==null||l.destroy(),(h=this._cropControls)==null||h.destroy(),(c=this._activeFiltersPanel)==null||c.destroy(),(p=this._editorEl)==null||p.remove(),this._container=null,this._state=null,this.emit("destroyed"),this.removeAllListeners()}}exports.CropControls=Le;exports.CropManager=oe;exports.EDITOR_CATEGORIES=le;exports.FilterManager=Ee;exports.PixiRenderer=Ce;exports.REGISTRY_TO_UI=Ae;exports.RemoveBgManager=Ne;exports.Toolbar=Be;exports.VanillaImageEditor=wt;exports.checkmark=ne;exports.chevronLeft=pe;exports.chevronRight=fe;exports.close=ae;exports.createButton=L;exports.createColorPicker=me;exports.createIconButton=D;exports.createSelect=ye;exports.createSlider=ge;exports.createTextInput=be;exports.createToggle=_e;exports.duplicate=it;exports.el=d;exports.expand=Ie;exports.eye=Je;exports.eyeOff=Qe;exports.getPreset=De;exports.layers=Te;exports.lockClosed=Xe;exports.lockOpen=et;exports.move=ke;exports.pencil=tt;exports.save=Fe;exports.trash=Re;exports.zoomIn=ze;exports.zoomOut=He;
2
+ //# sourceMappingURL=editor-P9MyuiTc.cjs.map