@codingfactory/mediables-vue 2.13.0 → 2.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ "use strict";var kt=Object.defineProperty;var St=(a,e,t)=>e in a?kt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var Fe=(a,e,t)=>St(a,typeof e!="symbol"?e+"":e,t);const Ft=require("pixi-filters"),Mt=require("pixi.js");function tt(a){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const t in a)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>a[t]})}}return e.default=a,Object.freeze(e)}const v=tt(Ft),O=tt(Mt);class ne{constructor(){this._events=new Map}on(e,t){return this._events.has(e)||this._events.set(e,new Set),this._events.get(e).add(t),()=>this.off(e,t)}off(e,t){const r=this._events.get(e);r&&r.delete(t)}emit(e,...t){const r=this._events.get(e);r&&r.forEach(i=>{try{i(...t)}catch{}})}once(e,t){const r=(...i)=>{this.off(e,r),t(...i)};return this.on(e,r)}removeAllListeners(e){e?this._events.delete(e):this._events.clear()}}const rt=Object.freeze(["Inter","Arial","Helvetica","Georgia","Times New Roman","Courier New","Verdana"]),Oe=Object.freeze(["normal","multiply","screen","overlay"]),de=Object.freeze({x:.2,y:.2,width:.6,height:.18}),H=Object.freeze({fontFamily:"Inter",fontSize:64,fontWeight:700,fontStyle:"normal",fill:"#ffffff",align:"center",lineHeight:1.2,letterSpacing:0}),E=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 Pt extends ne{constructor(){super(),this._state={hasImage:!1,imageUrl:null,mode:"filters",zoom:1,fitScale:1,activeFilters:new Set,filterValues:{},selectedFilter:null,selectedCategory:"adjust",crop:{shape:"free",aspect:"free",rect:null,dirty:!1},transform:{rotation:0},editorDocument:null,editorDocumentId:null,editorDocumentRevisionId:null,editorDocumentRevisionNumber:null,layers:[],activeLayerId:null,theme:"auto",isDarkMode:!1,backgroundRemovalAvailable:!1,isProcessing:!1,isSaving:!1}}get(e){if(e.includes(".")){const t=e.split(".");let r=this._state;for(const i of t){if(r==null)return;r=r[i]}return r}return this._state[e]}set(e,t){const r=this.get(e);if(e.includes(".")){const i=e.split("."),s=i.pop();let n=this._state;for(const o of i)n[o]===void 0&&(n[o]={}),n=n[o];n[s]=t}else this._state[e]=t;this.emit(`change:${e}`,{value:t,old:r}),this.emit("change",{key:e,value:t,old:r})}getAll(){return{...this._state}}_clonePlain(e){return e==null?e:JSON.parse(JSON.stringify(e))}getSerializableState(){var r;const e=[];if(this._state.activeFilters)for(const i of this._state.activeFilters){const s=this._state.filterValues[i];e.push({id:i,enabled:!0,values:s?{...s}:{}})}const t=this._state.crop;return{version:1,crop:{rect:t!=null&&t.rect?{...t.rect}:null,aspectRatio:(t==null?void 0:t.aspect)||"free",shape:(t==null?void 0:t.shape)||"free"},transform:{rotation:Number((r=this._state.transform)==null?void 0:r.rotation)||0},filters:e}}setEditorDocument(e,t={}){var n;if(!e||e.version!==2||!Array.isArray(e.layers)){this.clearEditorDocument();return}const r=this._clonePlain(e),i=this._clonePlain(r.layers).map(o=>this._normalizeLayerForState(o)),s=typeof r.activeLayerId=="string"?r.activeLayerId:((n=i[0])==null?void 0:n.id)??null;this._state.editorDocument={...r,layers:i,activeLayerId:s},this._state.editorDocumentId=t.documentId??r.id??null,this._state.editorDocumentRevisionId=t.documentRevisionId??null,this._state.editorDocumentRevisionNumber=t.documentRevisionNumber??r.revision??null,this._state.layers=i,this._state.activeLayerId=s,this.emit("change:editorDocument",{value:this.getSerializableDocument()}),this.emit("change:layers",{value:this._clonePlain(i)}),this.emit("change:activeLayerId",{value:s}),this._syncFilterStateFromActiveLayer()}clearEditorDocument(){this._state.editorDocument=null,this._state.editorDocumentId=null,this._state.editorDocumentRevisionId=null,this._state.editorDocumentRevisionNumber=null,this._state.layers=[],this._state.activeLayerId=null,this._state.activeFilters=new Set,this._state.filterValues={},this._state.selectedFilter=null,this.emit("change:editorDocument",{value:null}),this.emit("change:layers",{value:[]}),this.emit("change:activeLayerId",{value:null}),this.emit("change:activeFilters",{value:this._state.activeFilters}),this.emit("change:filterValues",this._state.filterValues),this.emit("change:selectedFilter",{value:null})}getSerializableDocument(){var r;if(!this._state.editorDocument)return null;const e=this._clonePlain(this._state.editorDocument);e.layers=this._clonePlain(this._state.layers),e.activeLayerId=this._state.activeLayerId;const t=e.layers.findIndex(i=>i&&(i.role==="subject"||i.type==="image"&&i.role!=="overlay"));if(t!==-1){const i=e.layers[t],s=this._normalizeDegrees(((r=this._state.transform)==null?void 0:r.rotation)??0),n=i.transform&&typeof i.transform=="object"?i.transform:{x:0,y:0,scaleX:1,scaleY:1,rotation:0};i.transform={...n,rotation:s};const o=this._state.crop&&typeof this._state.crop=="object"?this._state.crop:null,l=o!=null&&o.appliedRect&&typeof o.appliedRect=="object"?o.appliedRect:null;l&&(i.crop={rect:{...l},shape:o.appliedShape||"free",aspect:o.appliedAspect||"free"}),e.layers[t]=i}return e}getEditorDocumentBinding(){return this._state.editorDocument?{documentId:this._state.editorDocumentId,documentRevisionId:this._state.editorDocumentRevisionId,documentRevisionNumber:this._state.editorDocumentRevisionNumber}:null}_findLayerIndex(e){return this._state.layers.findIndex(t=>(t==null?void 0:t.id)===e)}_layerLocked(e){return(e==null?void 0:e.locked)===!0}_backgroundLayerLocked(e=this._state.layers){const t=this._backgroundLayerIndex(e);return t!==-1&&this._layerLocked(e[t])}isBackgroundLayerLocked(){return this._backgroundLayerLocked()}_uniqueLayerId(e){const t=new Set(this._state.layers.map(i=>i==null?void 0:i.id).filter(Boolean)),r=String(e||"layer").replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"layer";if(!t.has(r))return r;for(let i=2;i<1e4;i+=1){const s=`${r}-${i}`;if(!t.has(s))return s}return`${r}-${Date.now()}`}_normalizeLayerForState(e){return!e||typeof e!="object"?e:e.type!=="text"&&e.role!=="text"?{...e,filters:this._normalizeLayerFilters(e.filters)}:this._normalizeTextLayer({...e,id:typeof e.id=="string"&&e.id.trim()!==""?e.id:this._uniqueLayerId("text-layer"),name:typeof e.name=="string"&&e.name.trim()!==""?e.name:"Text"},e)}_normalizeLayerFilters(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&typeof t.id=="string"&&t.id.trim()!=="").map(t=>({id:t.id.trim(),enabled:t.enabled!==!1,values:t.values&&typeof t.values=="object"?this._clonePlain(t.values):{}})):[]}_layerSupportsFilters(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}_activeFilterLayerIndex(){const e=this._state.activeLayerId;if(!e||!Array.isArray(this._state.layers))return-1;const t=this._findLayerIndex(e);return t!==-1&&this._layerSupportsFilters(this._state.layers[t])?t:-1}getActiveFilterLayerId(){var t;const e=this._activeFilterLayerIndex();return e!==-1?((t=this._state.layers[e])==null?void 0:t.id)??null:null}_matchesExpectedFilterLayer(e){if(!this._state.editorDocument||e===void 0)return!0;if(e===null)return this.getActiveFilterLayerId()===null;const t=typeof e=="string"?e.trim():"";return t===""?!1:this.getActiveFilterLayerId()===t}_syncFilterStateFromActiveLayer(){var s;if(!this._state.editorDocument)return;const e=this._activeFilterLayerIndex(),t=new Set,r={};if(e!==-1)for(const n of this._normalizeLayerFilters((s=this._state.layers[e])==null?void 0:s.filters))n.enabled!==!1&&(t.add(n.id),r[n.id]=this._clonePlain(n.values||{}));const i=this._state.selectedFilter;this._state.activeFilters=t,this._state.filterValues=r,i&&!t.has(i)&&(this._state.selectedFilter=null),this.emit("change:activeFilters",{value:this._state.activeFilters}),this.emit("change:filterValues",this._state.filterValues),this._state.selectedFilter!==i&&this.emit("change:selectedFilter",{value:this._state.selectedFilter,old:i})}_clampNumber(e,t,r,i){const s=Number(e);return Number.isFinite(s)?Math.max(t,Math.min(r,s)):i}_normalizeDegrees(e){const t=Number(e);if(!Number.isFinite(t))return 0;const r=t%360;return r<0?r+360:r}_isSupportedTextColor(e){return typeof e=="string"&&/^#[0-9a-f]{6}$/i.test(e)}_normalizeTextColor(e,t){return this._isSupportedTextColor(e)?e:this._isSupportedTextColor(t)?t:"#000000"}_normalizeBoolean(e,t=!1){return typeof e=="boolean"?e:t===!0}_normalizeBlendMode(e,t="normal"){return Oe.includes(e)?e:Oe.includes(t)?t:"normal"}_normalizeTextFontFamily(e){const t=typeof e=="string"?e.trim():"";return rt.includes(t)?t:H.fontFamily}_normalizeTextFontWeight(e,t=H.fontWeight){if(e==="normal")return 400;if(e==="bold")return 700;const r=Number(e);return!Number.isFinite(r)||r<100||r>900||r%100!==0?t:r}_normalizeTextBox(e,t=null){const r=t&&typeof t=="object"?t:de,i=e&&typeof e=="object"?e:{};return{x:this._clampNumber(i.x,0,1,this._clampNumber(r.x,0,1,de.x)),y:this._clampNumber(i.y,0,1,this._clampNumber(r.y,0,1,de.y)),width:this._clampNumber(i.width,.05,1,this._clampNumber(r.width,.05,1,de.width)),height:this._clampNumber(i.height,.05,1,this._clampNumber(r.height,.05,1,de.height))}}_normalizeTextStyle(e,t=null){const r={...H,...t&&typeof t=="object"?t:{}},i=e&&typeof e=="object"?e:{},n=!!i.fontSource||!!i.source||!!i.url?H.fontFamily:this._normalizeTextFontFamily(i.fontFamily??r.fontFamily),o=["normal","italic"].includes(i.fontStyle)?i.fontStyle:["normal","italic"].includes(r.fontStyle)?r.fontStyle:H.fontStyle,l=["left","center","right"].includes(i.align)?i.align:["left","center","right"].includes(r.align)?r.align:H.align,c=this._isSupportedTextColor(i.fill)?i.fill:this._isSupportedTextColor(r.fill)?r.fill:H.fill;return{fontFamily:n,fontSize:this._clampNumber(i.fontSize,8,400,this._clampNumber(r.fontSize,8,400,H.fontSize)),fontWeight:this._normalizeTextFontWeight(i.fontWeight,this._normalizeTextFontWeight(r.fontWeight,H.fontWeight)),fontStyle:o,fill:c,align:l,lineHeight:this._clampNumber(i.lineHeight,.8,3,this._clampNumber(r.lineHeight,.8,3,H.lineHeight)),letterSpacing:this._clampNumber(i.letterSpacing,-100,100,this._clampNumber(r.letterSpacing,-100,100,H.letterSpacing))}}_normalizeTextEffects(e,t=null){const r=e&&typeof e=="object"?e:{},i=t&&typeof t=="object"?t:{},s={stroke:{...E.stroke,...i.stroke&&typeof i.stroke=="object"?i.stroke:{}},shadow:{...E.shadow,...i.shadow&&typeof i.shadow=="object"?i.shadow:{}},glow:{...E.glow,...i.glow&&typeof i.glow=="object"?i.glow:{}},backdrop:{...E.backdrop,...i.backdrop&&typeof i.backdrop=="object"?i.backdrop:{}}},n=r.stroke&&typeof r.stroke=="object"?r.stroke:{},o=r.shadow&&typeof r.shadow=="object"?r.shadow:{},l=r.glow&&typeof r.glow=="object"?r.glow:{},c=r.backdrop&&typeof r.backdrop=="object"?r.backdrop:{};return{stroke:{enabled:this._normalizeBoolean(n.enabled,s.stroke.enabled),color:this._normalizeTextColor(n.color,s.stroke.color),width:this._clampNumber(n.width,0,80,this._clampNumber(s.stroke.width,0,80,E.stroke.width))},shadow:{enabled:this._normalizeBoolean(o.enabled,s.shadow.enabled),color:this._normalizeTextColor(o.color,s.shadow.color),alpha:this._clampNumber(o.alpha,0,1,this._clampNumber(s.shadow.alpha,0,1,E.shadow.alpha)),blur:this._clampNumber(o.blur,0,120,this._clampNumber(s.shadow.blur,0,120,E.shadow.blur)),distance:this._clampNumber(o.distance,0,200,this._clampNumber(s.shadow.distance,0,200,E.shadow.distance)),angle:this._normalizeDegrees(o.angle??s.shadow.angle??E.shadow.angle)},glow:{enabled:this._normalizeBoolean(l.enabled,s.glow.enabled),color:this._normalizeTextColor(l.color,s.glow.color),alpha:this._clampNumber(l.alpha,0,1,this._clampNumber(s.glow.alpha,0,1,E.glow.alpha)),blur:this._clampNumber(l.blur,0,120,this._clampNumber(s.glow.blur,0,120,E.glow.blur))},backdrop:{enabled:this._normalizeBoolean(c.enabled,s.backdrop.enabled),color:this._normalizeTextColor(c.color,s.backdrop.color),opacity:this._clampNumber(c.opacity,0,1,this._clampNumber(s.backdrop.opacity,0,1,E.backdrop.opacity)),padding:this._clampNumber(c.padding,0,200,this._clampNumber(s.backdrop.padding,0,200,E.backdrop.padding)),radius:this._clampNumber(c.radius,0,200,this._clampNumber(s.backdrop.radius,0,200,E.backdrop.radius)),blur:this._clampNumber(c.blur,0,80,this._clampNumber(s.backdrop.blur,0,80,E.backdrop.blur))}}}_normalizeLayerTransform(e,t=null){const r=t&&typeof t=="object"?t:{},i=e&&typeof e=="object"?e:{};return{x:this._clampNumber(i.x,-1e5,1e5,this._clampNumber(r.x,-1e5,1e5,0)),y:this._clampNumber(i.y,-1e5,1e5,this._clampNumber(r.y,-1e5,1e5,0)),scaleX:this._clampNumber(i.scaleX,.01,100,this._clampNumber(r.scaleX,.01,100,1)),scaleY:this._clampNumber(i.scaleY,.01,100,this._clampNumber(r.scaleY,.01,100,1)),rotation:this._normalizeDegrees(i.rotation??r.rotation??0)}}_normalizeTextPayload(e={},t=null){var c,d,h,u;const r=e&&typeof e=="object"?e:{},i=t!=null&&t.text&&typeof t.text=="object"?t.text:t,s=r.content??((c=r.text)==null?void 0:c.content)??(i==null?void 0:i.content)??"Add text",n=r.box??((d=r.text)==null?void 0:d.box),o=r.style??((h=r.text)==null?void 0:h.style),l=((u=r.text)==null?void 0:u.effects)??(r.effects&&!Array.isArray(r.effects)?r.effects:void 0);return{content:s==null?"":String(s),box:this._normalizeTextBox(n,i==null?void 0:i.box),style:this._normalizeTextStyle(o,i==null?void 0:i.style),effects:this._normalizeTextEffects(l,i==null?void 0:i.effects)}}_normalizeTextLayer(e={},t=null){const r=e&&typeof e=="object"?e:{};return{id:typeof r.id=="string"&&r.id.trim()!==""?r.id:this._uniqueLayerId("text-layer"),type:"text",role:"text",name:typeof r.name=="string"&&r.name.trim()!==""?r.name.trim():"Text",visible:r.visible!==!1,locked:r.locked===!0,opacity:this._clampNumber(r.opacity,0,1,1),blendMode:this._normalizeBlendMode(r.blendMode,t==null?void 0:t.blendMode),transform:this._normalizeLayerTransform(r.transform,t==null?void 0:t.transform),effects:Array.isArray(r.effects)?this._clonePlain(r.effects):[],metadata:r.metadata&&typeof r.metadata=="object"?this._clonePlain(r.metadata):{},text:this._normalizeTextPayload(r,t),crop:null,filters:Array.isArray(r.filters)?this._clonePlain(r.filters):[]}}_nearestEditableLayerId(e,t){var r,i;if(!e.length)return null;for(let s=0;s<e.length;s+=1){const n=t+s;if(n<e.length&&!this._layerLocked(e[n])&&((r=e[n])==null?void 0:r.visible)!==!1)return e[n].id??null;const o=t-s-1;if(o>=0&&!this._layerLocked(e[o])&&((i=e[o])==null?void 0:i.visible)!==!1)return e[o].id??null}return null}_moveCrossesLockedLayer(e,t,r){const i=Math.min(t,r),s=Math.max(t,r);for(let n=i;n<=s;n+=1)if(n!==t&&this._layerLocked(e[n]))return!0;return!1}getLayer(e){const t=this._state.layers.find(r=>(r==null?void 0:r.id)===e);return t?this._clonePlain(t):null}setActiveLayer(e){if(e!==null&&this._findLayerIndex(e)===-1)return!1;const t=this._state.activeLayerId;return this._state.activeLayerId=e,this._state.editorDocument&&(this._state.editorDocument.activeLayerId=e),this.emit("change:activeLayerId",{value:e,old:t}),this._syncFilterStateFromActiveLayer(),!0}isActiveLayerLocked(){const e=this._state.activeLayerId;if(!e)return!1;const t=this._state.layers.find(r=>(r==null?void 0:r.id)===e);return!!(t!=null&&t.locked)}setLayerVisibility(e,t){const r=this._findLayerIndex(e);if(r===-1)return!1;const i=this._clonePlain(this._state.layers);return this._layerLocked(i[r])?!1:(i[r].visible=!!t,this._state.layers=i,this._state.editorDocument&&(this._state.editorDocument.layers=this._clonePlain(i)),this.emit("change:layers",{value:this._clonePlain(i)}),this.emit("change:layerVisibility",{layerId:e,visible:!!t}),!0)}renameLayer(e,t){const r=this._findLayerIndex(e);if(r===-1)return!1;const i=this._clonePlain(this._state.layers);if(this._layerLocked(i[r]))return!1;const s=String(t??"").trim();if(s==="")return!1;const n=i[r].name??"";return i[r].name=s,this._commitLayers(i,"change:layerRenamed",{layerId:e,name:s,oldName:n}),!0}duplicateLayer(e){const t=this._findLayerIndex(e);if(t===-1)return null;const r=this._clonePlain(this._state.layers),i=r[t];if(this._layerLocked(i))return null;const s=this._clonePlain(i);s.id=this._uniqueLayerId(`${i.id||"layer"}-copy`),s.name=`${String(i.name||"Layer").trim()||"Layer"} copy`,s.locked=!1,s.metadata={...s.metadata&&typeof s.metadata=="object"?s.metadata:{},duplicatedFromLayerId:i.id??null,duplicatedAt:new Date().toISOString()},r.splice(t+1,0,s);const n=this._state.activeLayerId;return this._state.activeLayerId=s.id,this._state.editorDocument&&(this._state.editorDocument.activeLayerId=s.id),this._commitLayers(r,"change:layerDuplicated",{layerId:e,duplicateLayerId:s.id}),this.emit("change:activeLayerId",{value:s.id,old:n}),s.id}deleteLayer(e){const t=this._findLayerIndex(e);if(t===-1||this._state.layers.length<=1)return!1;const r=this._clonePlain(this._state.layers);if(this._layerLocked(r[t]))return!1;const[i]=r.splice(t,1);let s=this._state.activeLayerId;if(s===e||!r.some(n=>(n==null?void 0:n.id)===s)){s=this._nearestEditableLayerId(r,t);const n=this._state.activeLayerId;this._state.activeLayerId=s,this._state.editorDocument&&(this._state.editorDocument.activeLayerId=s),this.emit("change:activeLayerId",{value:s,old:n})}return this._commitLayers(r,"change:layerDeleted",{layerId:(i==null?void 0:i.id)??e}),!0}moveLayer(e,t){const r=this._findLayerIndex(e);if(r===-1)return!1;const i=this._clonePlain(this._state.layers);if(this._layerLocked(i[r]))return!1;let s=r;switch(t){case"up":case"bring-forward":s=Math.min(i.length-1,r+1);break;case"down":case"send-backward":s=Math.max(0,r-1);break;case"front":case"bring-to-front":s=i.length-1;break;case"back":case"send-to-back":s=0;break;default:return!1}if(s===r||this._moveCrossesLockedLayer(i,r,s))return!1;const[n]=i.splice(r,1);return i.splice(s,0,n),this._commitLayers(i,"change:layerMoved",{layerId:e,fromIndex:r,toIndex:s,direction:t}),!0}setLayerLocked(e,t){const r=this._findLayerIndex(e);if(r===-1)return!1;const i=this._clonePlain(this._state.layers);return i[r].locked=!!t,this._state.layers=i,this._state.editorDocument&&(this._state.editorDocument.layers=this._clonePlain(i)),this.emit("change:layers",{value:this._clonePlain(i)}),this.emit("change:layerLocked",{layerId:e,locked:!!t}),!0}replaceLayerSource(e,t){const r=this._findLayerIndex(e);if(r===-1||!t||typeof t!="object")return!1;const i=this._clonePlain(this._state.layers);return this._layerLocked(i[r])?!1:(i[r].source=this._clonePlain(t),this._state.layers=i,this._state.editorDocument&&(this._state.editorDocument.layers=this._clonePlain(i),this._state.editorDocument.updatedAt=new Date().toISOString()),this.emit("change:layers",{value:this._clonePlain(i)}),this.emit("change:layerSource",{layerId:e,source:this._clonePlain(t)}),!0)}addTextLayer(e={}){if(!this._state.editorDocument||!Array.isArray(this._state.layers))return null;const t=this._clonePlain(this._state.layers),r=this._normalizeTextLayer({...e&&typeof e=="object"?e:{},id:this._uniqueLayerId((e==null?void 0:e.id)||"text-layer")});t.push(r);const i=this._state.activeLayerId;return this._state.activeLayerId=r.id,this._state.editorDocument&&(this._state.editorDocument.activeLayerId=r.id),this._commitLayers(t,"change:textLayer",{action:"created",layerId:r.id}),this.emit("change:activeLayerId",{value:r.id,old:i}),r.id}updateTextLayer(e,t={}){var l;const r=this._findLayerIndex(e);if(r===-1||!t||typeof t!="object")return!1;const i=this._clonePlain(this._state.layers),s=i[r];if(this._layerLocked(s)||s.type!=="text"&&s.role!=="text")return!1;const n=t.text&&typeof t.text=="object"?t.text:{},o=this._normalizeTextLayer({...s,transform:t.transform&&typeof t.transform=="object"?{...s.transform,...t.transform}:s.transform,text:{...s.text&&typeof s.text=="object"?s.text:{},...n,..."content"in t?{content:t.content}:{},..."box"in t?{box:t.box}:{},..."style"in t?{style:{...((l=s.text)==null?void 0:l.style)||{},...t.style||{}}}:{},..."effects"in t?{effects:t.effects}:{}},...t.name!==void 0?{name:t.name}:{},...t.opacity!==void 0?{opacity:t.opacity}:{},...t.blendMode!==void 0?{blendMode:t.blendMode}:{}},s);return i[r]=o,this._commitLayers(i,"change:textLayer",{action:"updated",layerId:e,text:this._clonePlain(o.text)}),!0}_commitLayers(e,t=null,r={}){this._state.layers=e,this._state.editorDocument&&(this._state.editorDocument.layers=this._clonePlain(e),this._state.editorDocument.updatedAt=new Date().toISOString()),this.emit("change:layers",{value:this._clonePlain(e)}),t&&this.emit(t,r)}_backgroundLayerIndex(e=this._state.layers){return e.findIndex(t=>(t==null?void 0:t.type)==="background"||(t==null?void 0:t.role)==="background")}_defaultBackgroundLayer(e={kind:"transparent"}){const t=new Set(this._state.layers.map(i=>i==null?void 0:i.id).filter(Boolean));let r="background-layer";return t.has(r)&&(r=`background-layer-${Date.now()}`),{id:r,type:"background",role:"background",name:"Background",visible:!0,locked:!1,opacity:1,blendMode:"normal",transform:{x:0,y:0,scaleX:1,scaleY:1,rotation:0},effects:[],metadata:{},fill:this._clonePlain(e),crop:null,filters:[]}}_normalizeBackgroundFill(e){if(!e||typeof e!="object")return{kind:"transparent"};const t=["cover","contain","stretch","tile"].includes(e.fit)?e.fit:void 0;if(e.kind==="color")return{kind:"color",value:typeof e.value=="string"?e.value:typeof e.color=="string"?e.color:"#ffffff",...t?{fit:t}:{}};if(e.kind==="gradient"){const r=Array.isArray(e.stops)&&e.stops.length>0?e.stops.filter(i=>i&&typeof i=="object"&&typeof i.color=="string").map(i=>({offset:Number.isFinite(Number(i.offset))?Math.max(0,Math.min(1,Number(i.offset))):0,color:i.color})):[{offset:0,color:"#111827"},{offset:1,color:"#f59e0b"}];return{kind:"gradient",gradientType:["linear","radial"].includes(e.gradientType)?e.gradientType:"linear",angle:Number.isFinite(Number(e.angle))?Number(e.angle):135,stops:r,fit:t||"cover"}}return e.kind==="media"&&e.source&&typeof e.source=="object"?{kind:"media",source:this._clonePlain(e.source),fit:t||"cover"}:{kind:"transparent"}}ensureBackgroundLayer(e={kind:"transparent"}){const t=this._clonePlain(this._state.layers),r=this._backgroundLayerIndex(t);if(r!==-1)return this._layerLocked(t[r])?null:t[r].id;const i=this._defaultBackgroundLayer(this._normalizeBackgroundFill(e)),s=t.findIndex(o=>(o==null?void 0:o.role)==="subject"||(o==null?void 0:o.type)==="image"),n=s>=0?s:0;return t.splice(n,0,i),this._commitLayers(t,"change:backgroundLayer",{layerId:i.id,action:"created"}),i.id}setBackgroundFill(e){var o;const t=this._normalizeBackgroundFill(e),r=this.ensureBackgroundLayer(t);if(!r)return null;const i=this._clonePlain(this._state.layers),s=this._backgroundLayerIndex(i);if(s===-1||this._layerLocked(i[s]))return null;const n=(o=i[s].fill)==null?void 0:o.fit;return i[s].fill=this._clonePlain({...t,...!t.fit&&n&&t.kind!=="transparent"?{fit:n}:{}}),this._commitLayers(i,"change:backgroundFill",{layerId:r,fill:this._clonePlain(i[s].fill)}),r}setBackgroundFit(e){if(!["cover","contain","stretch","tile"].includes(e))return!1;const t=this.ensureBackgroundLayer();if(!t)return!1;const r=this._clonePlain(this._state.layers),i=this._backgroundLayerIndex(r);if(i===-1||this._layerLocked(r[i]))return!1;const s=r[i].fill&&typeof r[i].fill=="object"?r[i].fill:{kind:"transparent"};return r[i].fill={...s,fit:e},this._commitLayers(r,"change:backgroundFit",{layerId:t,fit:e}),!0}setBackgroundBlur(e){const t=Number.isFinite(Number(e))?Math.max(0,Math.min(100,Number(e))):0,r=this.ensureBackgroundLayer();if(!r)return!1;const i=this._clonePlain(this._state.layers),s=this._backgroundLayerIndex(i);if(s===-1||this._layerLocked(i[s]))return!1;const n=Array.isArray(i[s].effects)?i[s].effects.filter(o=>(o==null?void 0:o.id)!=="background-blur"):[];return t>0&&n.push({id:"background-blur",type:"blur",params:{amount:t}}),i[s].effects=n,this._commitLayers(i,"change:backgroundBlur",{layerId:r,amount:t}),!0}removeBackgroundLayer(){const e=this._clonePlain(this._state.layers),t=this._backgroundLayerIndex(e);if(t===-1||this._layerLocked(e[t]))return!1;const[r]=e.splice(t,1);if(r!=null&&r.id&&this._state.activeLayerId===r.id){const i=this._nearestEditableLayerId(e,t);this._state.activeLayerId=i,this._state.editorDocument&&(this._state.editorDocument.activeLayerId=i),this.emit("change:activeLayerId",{value:i,old:r.id})}return this._commitLayers(e,"change:backgroundLayer",{layerId:(r==null?void 0:r.id)??null,action:"removed"}),!0}toggleFilter(e,t,r=void 0){if(this._state.editorDocument){if(!this._matchesExpectedFilterLayer(r))return!1;const s=this._activeFilterLayerIndex();if(s===-1)return this._syncFilterStateFromActiveLayer(),!1;const n=typeof e=="string"?e.trim():"";if(n==="")return!1;const o=this._clonePlain(this._state.layers),l=o[s],c=this._normalizeLayerFilters(l.filters),d=c.findIndex(h=>h.id===n);return t?d===-1?c.push({id:n,enabled:!0,values:{}}):c[d].enabled=!0:d!==-1&&c.splice(d,1),l.filters=c,this._commitLayers(o,"change:layerFilters",{layerId:l.id,filterId:n,enabled:!!t}),this._syncFilterStateFromActiveLayer(),!0}const i=new Set(this._state.activeFilters);return t?i.add(e):(i.delete(e),delete this._state.filterValues[e]),this.set("activeFilters",i),!0}setFilterValue(e,t,r,i=void 0){var s,n;if(this._state.editorDocument){if(!this._matchesExpectedFilterLayer(i))return!1;const o=this._activeFilterLayerIndex();if(o===-1)return this._syncFilterStateFromActiveLayer(),!1;const l=typeof e=="string"?e.trim():"";if(l===""||!((n=(s=this._state.activeFilters)==null?void 0:s.has)!=null&&n.call(s,l)))return!1;const c=this._clonePlain(this._state.layers),d=c[o],h=this._normalizeLayerFilters(d.filters),u=h.findIndex(p=>p.id===l&&p.enabled!==!1);return u===-1?!1:(h[u].values={...h[u].values&&typeof h[u].values=="object"?h[u].values:{},[t]:this._clonePlain(r)},d.filters=h,this._commitLayers(c,"change:layerFilters",{layerId:d.id,filterId:l,controlId:t,value:this._clonePlain(r)}),this._syncFilterStateFromActiveLayer(),this.emit("change:filterValue",{filterId:l,controlId:t,value:r}),!0)}return this._state.filterValues[e]||(this._state.filterValues[e]={}),this._state.filterValues[e][t]=r,this.emit("change:filterValue",{filterId:e,controlId:t,value:r}),this.emit("change:filterValues",this._state.filterValues),!0}getFilterValues(e){return this._state.filterValues[e]||{}}initFilterValues(e,t,r=void 0){if(this._state.editorDocument){if(!this._matchesExpectedFilterLayer(r))return!1;const i=this.getFilterValues(e);return t.forEach(s=>{s.id in i||this.setFilterValue(e,s.id,s.default,r)}),!0}return this._state.filterValues[e]||(this._state.filterValues[e]={}),t.forEach(i=>{i.id in this._state.filterValues[e]||(this._state.filterValues[e][i.id]=i.default)}),this.emit("change:filterValues",this._state.filterValues),!0}resetFilters(e=void 0){if(this._state.editorDocument){if(!this._matchesExpectedFilterLayer(e))return!1;const t=this._activeFilterLayerIndex();if(t===-1)return this._syncFilterStateFromActiveLayer(),this.emit("filtersReset"),!1;const r=this._clonePlain(this._state.layers);return r[t].filters=[],this._commitLayers(r,"change:layerFilters",{layerId:r[t].id,action:"reset"}),this._syncFilterStateFromActiveLayer(),this.emit("filtersReset"),!0}return this._state.activeFilters=new Set,this._state.filterValues={},this._state.selectedFilter=null,this.emit("change:activeFilters",{value:this._state.activeFilters}),this.emit("change:filterValues",this._state.filterValues),this.emit("change:selectedFilter",{value:null}),this.emit("filtersReset"),!0}detectTheme(){if(this._state.theme==="auto"){const e=window.matchMedia("(prefers-color-scheme: dark)").matches;this.set("isDarkMode",e)}else this.set("isDarkMode",this._state.theme==="dark")}}function it(){return new Pt}const At=Object.freeze(["normal","multiply","screen","overlay"]),I=Object.freeze({stroke:Object.freeze({enabled:!1,color:"#000000",width:0}),shadow:Object.freeze({enabled:!1,color:"#000000",alpha:.5,blur:0,distance:0,angle:45}),glow:Object.freeze({enabled:!1,color:"#ffffff",alpha:.5,blur:0}),backdrop:Object.freeze({enabled:!1,color:"#000000",opacity:.5,padding:0,radius:0,blur:0})});class st extends ne{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 i,s,n,o,l,c;const e=(s=(i=this.app)==null?void 0:i.renderer)==null?void 0:s.canvas,t=(e==null?void 0:e.clientWidth)??((o=(n=this.app)==null?void 0:n.screen)==null?void 0:o.width)??0,r=(e==null?void 0:e.clientHeight)??((c=(l=this.app)==null?void 0:l.screen)==null?void 0:c.height)??0;return{w:t,h:r}}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 r=!1,i=0;const s=()=>{r||(r=!0,window.clearTimeout(i),t())};if(i=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:r}=this._getCssSize();if(t<=1||r<=1)return 1;let i=Math.min(t/e.width,r/e.height)*.9;return(!Number.isFinite(i)||i<=0)&&(i=1),i}applyViewTransform(e={}){if(!this.app||!this.sprite||!this.originalTexture)return;const t=this.fitScale*this.zoom,{w:r,h:i}=this._getCssSize(),s=e.keepCenter?{x:this.sprite.x+this.sprite.width/2,y:this.sprite.y+this.sprite.height/2}:e.center??{x:r/2,y:i/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,r={}){if(!e)return;this._destroyed=!1,this._container=e;const i=++this._mountToken,s=async()=>{var u;const n=window.PIXI;if(!n)throw new Error("PIXI.js not found. Please ensure PIXI is loaded globally.");(u=n.Assets)!=null&&u.setPreferences&&n.Assets.setPreferences({crossOrigin:"anonymous"});const o=e.clientWidth||600,l=e.clientHeight||400,c=typeof r.backgroundAlpha=="number"?r.backgroundAlpha:1,d=new n.Application;if(this.app=d,await d.init({width:o,height:l,backgroundColor:t,backgroundAlpha:c,antialias:!0,autoDensity:!0,resolution:window.devicePixelRatio||1}),this._destroyed||this._mountToken!==i||this.app!==d){try{d.destroy(!0,{children:!0,texture:!0})}catch{}return!1}e.appendChild(d.canvas);const h=d.canvas;return h.classList.add("pixi-canvas"),h.style.width="100%",h.style.height="100%",h.style.transform="translateZ(0)",h.style.willChange="transform",h.setAttribute("role","img"),h.setAttribute("aria-label","Image editor canvas — use toolbar controls to edit the image"),this.emit("mounted",{width:o,height:l}),!0};return this._mountPromise=s(),await this._mountPromise}async loadTexture(e,t={}){var d,h,u;const r=()=>typeof t.isCurrent!="function"||t.isCurrent()!==!1;if(this._mountPromise&&await this._mountPromise,!((d=this.app)!=null&&d.renderer)||!r())return!1;const i=window.PIXI,s=await this._loadImageElement(e);if(!s||!((h=this.app)!=null&&h.renderer)||!r()||(await this._waitForNextFrame(),!((u=this.app)!=null&&u.renderer)||!r()))return!1;const n=i.Texture.from(s);if(!n)return!1;this.originalTexture=n,this.baseTexture=n,this._loadedTextureUrl=typeof e=="string"?e:null,this.sprite&&(this.app.stage.removeChild(this.sprite),this.sprite.destroy()),this.sprite=new i.Sprite(n),this.app.stage.addChild(this.sprite),this.fitScale=this.getFitScaleFor(n),this.zoom=1;const{w:o,h:l}=this._getCssSize();this.applyViewTransform({center:{x:o/2,y:l/2}});const c=this.getFitScaleFor(n);return Math.abs(c-this.fitScale)/Math.max(1e-6,c)>.02&&(this.fitScale=c,this.applyViewTransform({center:{x:o/2,y:l/2}})),this.render(),this.emit("textureLoaded",{width:n.width,height:n.height}),!0}async renderLayerDocument(e){var n;if(!((n=this.app)!=null&&n.stage)||!this.sprite||!e||!Array.isArray(e.layers))return!1;const t=window.PIXI;if(!t)return!1;const r=++this._layerRenderToken,i=()=>r===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 o of this._layerDocument.layers){if(!o||o.visible===!1){(o==null?void 0:o.role)==="subject"&&(this.sprite.visible=!1,this.sprite.__layerId=o.id,s=!0);continue}if(this._isSubjectLayer(o)){const c=await this._createSubjectDisplayObjectForLayer(t,o);if(!i())return this._destroyTransientDisplayObject(c),!1;if(c){this.sprite.visible=!1,c.__layerId=o.id,c.visible=!0,c.alpha=this._layerOpacity(o),this._layerDisplayObjects.set(o.id,{layer:o,displayObject:c}),this._syncLayerDisplayObject(o,c),this.app.stage.addChild(c),this._renderableLayerIds.push(o.id),s=!0;continue}this.sprite.__layerId=o.id,this.sprite.visible=!0,this.sprite.alpha=this._layerOpacity(o),this._applyLayerFilterInstances(this.sprite,o),this.app.stage.addChild(this.sprite),this._renderableLayerIds.push(o.id),s=!0;continue}const l=await this._createDisplayObjectForLayer(t,o);if(!i())return this._destroyTransientDisplayObject(l),!1;l&&(l.__layerId=o.id,l.visible=!0,l.alpha=this._layerOpacity(o),this._layerDisplayObjects.set(o.id,{layer:o,displayObject:l}),this._syncLayerDisplayObject(o,l),this.app.stage.addChild(l),this._renderableLayerIds.push(o.id))}return s||(this.sprite.visible=!1),i()?(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 r of this._layerDocument.layers){if(!r)continue;const i=this._layerDisplayObjects.get(r.id)||null;i&&(i.layer=r);let s=(i==null?void 0:i.displayObject)||null;!s&&this._isSubjectLayer(r)&&((t=this.sprite)==null?void 0:t.__layerId)===r.id&&(s=this.sprite),s&&this._applyLayerFilterInstances(s,r)}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,r={}){if(!e||!this._layerSupportsImageFilters(t))return;let i=[];if(this._layerFilterFactory)try{i=this._layerFilterFactory(t,{displayObject:e,forExport:r.forExport===!0,previewToNativeScale:r.previewToNativeScale||1,sourceWidth:r.sourceWidth,sourceHeight:r.sourceHeight})||[]}catch{i=[]}const s=Array.isArray(i)?i.filter(Boolean):[];for(const l of s)if(!(!l||typeof l!="object"&&typeof l!="function"))try{Object.defineProperty(l,"__mediablesLayerImageFilter",{value:!0,configurable:!0})}catch{try{l.__mediablesLayerImageFilter=!0}catch{}}const o=[...Array.isArray(e.filters)?e.filters.filter(l=>(l==null?void 0:l.__mediablesLayerImageFilter)!==!0):[],...s];e.filters=o.length>0?o:null}async _createDisplayObjectForLayer(e,t){var n,o;const r=this._createTextDisplayObjectForLayer(e,t);if(r)return r;const i=await this._createImageDisplayObjectForLayer(e,t);if(i)return i;const s=this._backgroundFillForLayer(t);if((s==null?void 0:s.kind)==="media"){const l=await this._textureForLayerSource(e,s.source);if(!l)return null;const c=this._createBackgroundSprite(e,l,s.fit);return c.__sourceWidth=Number((n=s.source)==null?void 0:n.originalWidth)||l.width||1,c.__sourceHeight=Number((o=s.source)==null?void 0:o.originalHeight)||l.height||1,this._applyLayerEffects(e,c,t),this._applyLayerFilterInstances(c,t),c}if((s==null?void 0:s.kind)==="gradient"){const l=this._createGradientTexture(e,s,512,512);if(!l||typeof e.Sprite!="function")return null;const c=new e.Sprite(l);return c.__ownsTexture=!0,c.__sourceWidth=512,c.__sourceHeight=512,this._applyLayerEffects(e,c,t),c}if(this._backgroundColorForLayer(t)&&typeof e.Graphics=="function"){const l=new e.Graphics;return this._applyLayerEffects(e,l,t),l}return null}_isTextLayer(e){return(e==null?void 0:e.type)==="text"||(e==null?void 0:e.role)==="text"}_normalizeTextBox(e){var r;const t=(r=e==null?void 0:e.text)!=null&&r.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,r,i){const s=Number(e);return Number.isFinite(s)?Math.max(t,Math.min(r,s)):i}_supportedTextFontFamily(e){const t=["Inter","Arial","Helvetica","Georgia","Times New Roman","Courier New","Verdana"],r=typeof e=="string"?e.trim():"";return t.includes(r)?r:"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 At.includes(t)?t:"normal"}_textContentForLayer(e){var r;const t=(r=e==null?void 0:e.text)==null?void 0:r.content;return t==null?"":String(t)}_textStyleForLayer(e,t=1,r=1,i={}){var g;const s=(g=e==null?void 0:e.text)!=null&&g.style&&typeof e.text.style=="object"?e.text.style:{},n=this._textEffectsForLayer(e),o=this._clampNumber(s.fontSize,8,400,64),l=this._clampNumber(s.lineHeight,.8,3,1.2),c=this._clampNumber(s.letterSpacing,-100,100,0),d=this._normalizeTextFontWeight(s.fontWeight),h=["normal","italic"].includes(s.fontStyle)?s.fontStyle:"normal",u=["left","center","right"].includes(s.align)?s.align:"center",p=i.fill||(typeof s.fill=="string"&&/^#[0-9a-f]{6}$/i.test(s.fill)?s.fill:"#ffffff"),m={fontFamily:this._supportedTextFontFamily(s.fontFamily),fontSize:o*t,fontWeight:d,fontStyle:h,fill:p,align:u,lineHeight:o*l*t,letterSpacing:c*t,wordWrap:!0,wordWrapWidth:Math.max(1,r),breakWords:!0};return i.stroke!==!1&&n.stroke.enabled&&n.stroke.width>0&&(m.stroke={color:n.stroke.color,width:n.stroke.width*t}),m}_normalizeTextFontWeight(e){if(e==="normal")return 400;if(e==="bold")return 700;const t=Number(e);return!Number.isFinite(t)||t<100||t>900||t%100!==0?700:t}_textEffectsForLayer(e){var o;const t=(o=e==null?void 0:e.text)!=null&&o.effects&&typeof e.text.effects=="object"?e.text.effects:{},r=t.stroke&&typeof t.stroke=="object"?t.stroke:{},i=t.shadow&&typeof t.shadow=="object"?t.shadow:{},s=t.glow&&typeof t.glow=="object"?t.glow:{},n=t.backdrop&&typeof t.backdrop=="object"?t.backdrop:{};return{stroke:{enabled:r.enabled===!0,color:this._supportedTextColor(r.color,I.stroke.color),width:this._clampNumber(r.width,0,80,I.stroke.width)},shadow:{enabled:i.enabled===!0,color:this._supportedTextColor(i.color,I.shadow.color),alpha:this._clampNumber(i.alpha,0,1,I.shadow.alpha),blur:this._clampNumber(i.blur,0,120,I.shadow.blur),distance:this._clampNumber(i.distance,0,200,I.shadow.distance),angle:this._normalizeDegrees(i.angle??I.shadow.angle)},glow:{enabled:s.enabled===!0,color:this._supportedTextColor(s.color,I.glow.color),alpha:this._clampNumber(s.alpha,0,1,I.glow.alpha),blur:this._clampNumber(s.blur,0,120,I.glow.blur)},backdrop:{enabled:n.enabled===!0,color:this._supportedTextColor(n.color,I.backdrop.color),opacity:this._clampNumber(n.opacity,0,1,I.backdrop.opacity),padding:this._clampNumber(n.padding,0,200,I.backdrop.padding),radius:this._clampNumber(n.radius,0,200,I.backdrop.radius),blur:this._clampNumber(n.blur,0,80,I.backdrop.blur)}}}_createTextBlurFilter(e,t){if(t<=0||typeof(e==null?void 0:e.BlurFilter)!="function")return null;try{let r;try{r=new e.BlurFilter({strength:t,quality:4})}catch{r=new e.BlurFilter(t)}return typeof r.blur=="number"&&(r.blur=t),typeof r.strength=="number"&&(r.strength=t),r.padding=Math.max(Number(r.padding)||0,Math.ceil(t*2)),r}catch{return null}}_textEffectPadding(e,t){const r=e.stroke.enabled?e.stroke.width*t:0,i=e.shadow.enabled?(e.shadow.distance+e.shadow.blur*2)*t:0,s=e.glow.enabled?e.glow.blur*2*t:0,n=e.backdrop.enabled?(e.backdrop.padding+e.backdrop.blur*2)*t:0;return Math.ceil(Math.max(r,i,s,n,0))}_createTextDisplayObjectForLayer(e,t){if(!this._isTextLayer(t)||typeof(e==null?void 0:e.Text)!="function")return null;const r=this._createTextPrimitive(e,t);if(!r)return null;if(typeof e.Container!="function"||typeof e.Graphics!="function")return r;const i=new e.Container,s=new e.Graphics,n=new e.Graphics,o=new e.Graphics,l=this._createTextPrimitive(e,t),c=this._createTextPrimitive(e,t);return i.__isTextLayerContainer=!0,i.__textObject=r,i.__textMask=s,i.__textEffectMask=n,i.__textBackdrop=o,i.__textShadow=l,i.__textGlow=c,o.visible=!1,l&&(l.visible=!1),c&&(c.visible=!1),r.mask=s,i.addChild(o),l&&i.addChild(l),c&&i.addChild(c),i.addChild(r),i.addChild(n),i.addChild(s),i}_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 r=this._sourceUrlForLayerSource(t==null?void 0:t.source);return!r||r===this._loadedTextureUrl?null:this._createImageDisplayObjectForLayer(e,t)}async _createImageDisplayObjectForLayer(e,t){var s,n;if((t==null?void 0:t.type)!=="image")return null;const r=await this._textureForLayerSource(e,t.source);if(!r||typeof e.Sprite!="function")return null;const i=new e.Sprite(r);return i.__sourceWidth=Number((s=t.source)==null?void 0:s.originalWidth)||r.width||1,i.__sourceHeight=Number((n=t.source)==null?void 0:n.originalHeight)||r.height||1,this._applyLayerEffects(e,i,t),this._applyLayerFilterInstances(i,t),i}_backgroundFillForLayer(e){const t=e==null?void 0:e.fill;if(t&&typeof t=="object")return t;const r=e==null?void 0:e.source;return(r==null?void 0:r.kind)==="color"&&typeof r.color=="string"?{kind:"color",value:r.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 r=e==null?void 0:e.fill;return(r==null?void 0:r.kind)==="color"&&typeof r.value=="string"?r.value:null}_sourceUrlForLayerSource(e){if(!e||typeof e!="object")return null;for(const t of["previewUrl","sourceUrl","url"]){const r=e[t];if(typeof r=="string"&&r.trim()!=="")return r}return null}async _textureForLayerSource(e,t){const r=this._sourceUrlForLayerSource(t);if(!r)return null;const i=await this._loadImageElement(r);return i?e.Texture.from(i):null}_createBackgroundSprite(e,t,r="cover"){if(r==="tile"&&typeof e.TilingSprite=="function")try{const i=new e.TilingSprite({texture:t,width:1,height:1});return i.__isTilingBackground=!0,i}catch{try{const s=new e.TilingSprite(t,1,1);return s.__isTilingBackground=!0,s}catch{}}return new e.Sprite(t)}_createGradientTexture(e,t,r,i){var c;if(typeof document>"u"||!((c=e==null?void 0:e.Texture)!=null&&c.from))return null;const s=document.createElement("canvas");s.width=Math.max(1,Math.round(r)),s.height=Math.max(1,Math.round(i));const n=s.getContext("2d");if(!n)return null;const o=Array.isArray(t==null?void 0:t.stops)&&t.stops.length>0?t.stops:[{offset:0,color:"#111827"},{offset:1,color:"#f59e0b"}];let l;if((t==null?void 0:t.gradientType)==="radial"){const d=Math.max(s.width,s.height)/2;l=n.createRadialGradient(s.width/2,s.height/2,0,s.width/2,s.height/2,d)}else{const d=(Number(t==null?void 0:t.angle)||0)*Math.PI/180,h=s.width/2,u=s.height/2,p=Math.sqrt(s.width**2+s.height**2)/2,m=Math.cos(d)*p,g=Math.sin(d)*p;l=n.createLinearGradient(h-m,u-g,h+m,u+g)}for(const d of o){if(!d||typeof d.color!="string")continue;const h=Number.isFinite(Number(d.offset))?Math.max(0,Math.min(1,Number(d.offset))):0;l.addColorStop(h,d.color)}return n.fillStyle=l,n.fillRect(0,0,s.width,s.height),e.Texture.from(s)}_backgroundBlurAmount(e){var s;const r=(Array.isArray(e==null?void 0:e.effects)?e.effects:[]).find(n=>(n==null?void 0:n.id)==="background-blur"||(n==null?void 0:n.type)==="blur"),i=Number((s=r==null?void 0:r.params)==null?void 0:s.amount);return Number.isFinite(i)?Math.max(0,i):0}_applyLayerEffects(e,t,r){const i=this._backgroundBlurAmount(r);if(!(i<=0||typeof(e==null?void 0:e.BlurFilter)!="function"))try{let s;try{s=new e.BlurFilter({strength:i,quality:4})}catch{s=new e.BlurFilter(i)}typeof s.blur=="number"&&(s.blur=i),typeof s.strength=="number"&&(s.strength=i),s.padding=Math.max(Number(s.padding)||0,Math.ceil(i*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 r=this._backgroundColorForLayer(e);if(r&&typeof t.clear=="function"){t.clear(),t.rect(this.sprite.x,this.sprite.y,this.sprite.width,this.sprite.height).fill(r);return}this._fitDisplayObjectToRect(t,e,{x:this.sprite.x,y:this.sprite.y,width:this.sprite.width,height:this.sprite.height})}_fillTextEffectGraphics(e,t,r=1){if(!(!e||typeof e.fill!="function"))try{e.fill({color:t,alpha:r})}catch{e.fill(t),e.alpha=r}}_syncTextEffectPrimitive(e,t,r,i,s,n,o,l){if(!t)return;const c=i[s];if(t.visible=(c==null?void 0:c.enabled)===!0,t.filters=null,t.mask=t.visible?l:null,!!t.visible){if(t.text=this._textContentForLayer(r),t.rotation=0,s==="shadow"){const d=c.angle*Math.PI/180;t.x=Math.cos(d)*c.distance*n,t.y=Math.sin(d)*c.distance*n,t.alpha=c.alpha,t.style=this._textStyleForLayer(r,n,o,{fill:c.color,stroke:!1});const h=this._createTextBlurFilter(e,c.blur*n);t.filters=h?[h]:null;return}if(s==="glow"){t.x=0,t.y=0,t.alpha=c.alpha,t.style=this._textStyleForLayer(r,n,o,{fill:c.color,stroke:!1});const d=this._createTextBlurFilter(e,c.blur*n);t.filters=d?[d]:null}}}_syncTextBackdrop(e,t,r,i,s,n,o){if(!t)return;const l=r.backdrop;if(t.visible=l.enabled===!0,t.filters=null,t.mask=t.visible?o:null,t.alpha=1,typeof t.clear=="function"&&t.clear(),!t.visible)return;const c=l.padding*i,d=l.radius*i,h=-c,u=-c,p=s+c*2,m=n+c*2;d>0&&typeof t.roundRect=="function"?t.roundRect(h,u,p,m,d):typeof t.rect=="function"&&t.rect(h,u,p,m),this._fillTextEffectGraphics(t,l.color,l.opacity);const g=this._createTextBlurFilter(e,l.blur*i);t.filters=g?[g]:null}_fitTextDisplayObjectToRect(e,t,r){var g,_;const i=this._normalizeTextBox(t),s=r.x+i.x*r.width,n=r.y+i.y*r.height,o=i.width*r.width,l=i.height*r.height,c=Number((g=this.originalTexture)==null?void 0:g.width)||r.width,d=c>0?r.width/c:1,h=this._textEffectsForLayer(t);e.x=s,e.y=n,e.rotation=this._normalizeDegrees(Number((_=t==null?void 0:t.transform)==null?void 0:_.rotation)||0)*Math.PI/180,e.blendMode=this._textBlendMode(t),e.__textBox=i,e.__textLayout={x:s,y:n,width:o,height:l,scale:d};const u=e.__textObject||e,p=e.__textMask||null,m=e.__textEffectMask||null;if(u.text=this._textContentForLayer(t),u.style=this._textStyleForLayer(t,d,o),u.x=0,u.y=0,u.rotation=0,p&&typeof p.clear=="function"&&typeof p.rect=="function"&&typeof p.fill=="function"&&(p.clear(),p.rect(0,0,o,l).fill(16777215),u.mask=p),m&&typeof m.clear=="function"&&typeof m.rect=="function"&&typeof m.fill=="function"){const C=this._textEffectPadding(h,d);m.clear(),m.rect(-C,-C,o+C*2,l+C*2).fill(16777215)}this._syncTextBackdrop(window.PIXI,e.__textBackdrop,h,d,o,l,m),this._syncTextEffectPrimitive(window.PIXI,e.__textShadow,t,h,"shadow",d,o,m),this._syncTextEffectPrimitive(window.PIXI,e.__textGlow,t,h,"glow",d,o,m)}_fitDisplayObjectToRect(e,t,r){var h,u,p,m,g,_,C,k;const i=this._backgroundFillForLayer(t),s=(i==null?void 0:i.fit)||"cover";if(e.__isTilingBackground){e.x=r.x,e.y=r.y,e.width=r.width,e.height=r.height,(u=(h=e.tilePosition)==null?void 0:h.set)==null||u.call(h,0,0),(m=(p=e.tileScale)==null?void 0:p.set)==null||m.call(p,1,1);return}if(s==="stretch"||(i==null?void 0:i.kind)==="gradient"||(i==null?void 0:i.kind)==="color"){e.x=r.x,e.y=r.y,e.width=r.width,e.height=r.height;return}const n=Number(e.__sourceWidth||((g=i==null?void 0:i.source)==null?void 0:g.originalWidth)||((_=e.texture)==null?void 0:_.width)||r.width),o=Number(e.__sourceHeight||((C=i==null?void 0:i.source)==null?void 0:C.originalHeight)||((k=e.texture)==null?void 0:k.height)||r.height);if(!Number.isFinite(n)||!Number.isFinite(o)||n<=0||o<=0){e.x=r.x,e.y=r.y,e.width=r.width,e.height=r.height;return}const l=s==="contain"?Math.min(r.width/n,r.height/o):Math.max(r.width/n,r.height/o),c=n*l,d=o*l;e.x=r.x+(r.width-c)/2,e.y=r.y+(r.height-d)/2,e.width=c,e.height=d}_destroyLayerDisplayObjects(){var e,t,r,i,s;if((e=this._layerDisplayObjects)!=null&&e.size){for(const{displayObject:n}of this._layerDisplayObjects.values()){try{(i=(r=(t=this.app)==null?void 0:t.stage)==null?void 0:r.removeChild)==null||i.call(r,n)}catch{}const o=(n==null?void 0:n.__ownsTexture)===!0;(s=n==null?void 0:n.destroy)==null||s.call(n,{children:!0,texture:o,textureSource:o})}this._layerDisplayObjects.clear(),this._renderableLayerIds=[]}}_destroyTransientDisplayObject(e){var r,i,s,n;if(!e)return;try{(s=(i=(r=this.app)==null?void 0:r.stage)==null?void 0:i.removeChild)==null||s.call(i,e)}catch{}const t=(e==null?void 0:e.__ownsTexture)===!0;(n=e==null?void 0:e.destroy)==null||n.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,r){const i=this._normalizeDegrees(r);if(i===0)return{width:Math.max(1,Math.round(e)),height:Math.max(1,Math.round(t))};const s=i*Math.PI/180,n=Math.abs(Math.cos(s)),o=Math.abs(Math.sin(s)),l=n<1e-10?0:n,c=o<1e-10?0:o;return{width:Math.max(1,Math.ceil(e*l+t*c)),height:Math.max(1,Math.ceil(e*c+t*l))}}rotateBy(e){var g,_,C;const t=this._normalizeDegrees(e);if(t===0)return!0;if(!((g=this.app)!=null&&g.renderer)||!this.originalTexture||!this.sprite)return!1;const r=window.PIXI,i=Math.round(this.originalTexture.width),s=Math.round(this.originalTexture.height);if(i<=0||s<=0)return!1;const{width:n,height:o}=this.getRotatedBounds(i,s,t),l=t*Math.PI/180,c=new r.Container,d=new r.Sprite(this.originalTexture);(C=(_=d.anchor)==null?void 0:_.set)==null||C.call(_,.5),d.x=n/2,d.y=o/2,d.rotation=l,c.addChild(d);const h=r.RenderTexture.create({width:n,height:o,resolution:1});try{this.app.renderer.render({container:c,target:h,clear:!0,clearColor:[0,0,0,0]})}catch{return h.destroy(!0),!1}finally{c.removeChildren(),d.destroy({children:!1,texture:!1,textureSource:!1}),c.destroy({children:!1})}const u=this.originalTexture,p=Array.isArray(this.sprite.filters)?[...this.sprite.filters]:null;u&&u!==this.baseTexture&&u.destroy(!0),this.originalTexture=h,this._lastExportDimensions=null,this.app.stage.removeChild(this.sprite),this.sprite.destroy({children:!1,texture:!1,textureSource:!1});const m=new r.Sprite(h);return p!=null&&p.length&&(m.filters=p),this.app.stage.addChild(m),this.sprite=m,this.fitScale=this.getFitScaleFor(h),this.zoom=1,this.applyViewTransform({keepCenter:!1}),this.render(),this.emit("textureRotated",{width:n,height:o,degrees:t}),!0}exportImage(e="png",t=.92,r=0,i=!0,s=0){var N;if(!((N=this.app)!=null&&N.renderer)||!this.originalTexture||!this.sprite)return null;const n=window.PIXI,o=Math.round(this.originalTexture.width),l=Math.round(this.originalTexture.height);if(o<=0||l<=0)return null;const c=this.sprite.width,d=this.sprite.height;if(c<=0||d<=0)return null;const h=c/o,u=h>0?1/h:1,p=this._layerDocument,m=p&&Array.isArray(p.layers),g=[];if(!m&&Array.isArray(this.sprite.filters)){for(const x of this.sprite.filters)if(x)if(typeof x.createExportFilter=="function"){const S=x.createExportFilter({previewToNativeScale:u});S&&g.push(S)}else g.push(x)}let _=0;for(const x of g){const S=typeof x.getExportPadding=="function"?Number(x.getExportPadding())||0:typeof x._exportPadding=="number"?x._exportPadding:typeof x.padding=="number"?x.padding:0;S>0&&(_+=S)}const C=Math.max(Math.ceil(_),64),k=x=>{var fe,me,j,ge;const S=Math.ceil(o+2*x),T=Math.ceil(l+2*x),F=new n.Container,B=[],V=(b=null)=>{const w=new n.Sprite(this.originalTexture);w.x=x,w.y=x,w.scale.set(1,1),w.alpha=b?this._layerOpacity(b):1,b&&this._applyLayerFilterInstances(w,b,{forExport:!0,previewToNativeScale:u,sourceWidth:o,sourceHeight:l}),g.length>0&&(w.filters=g,w.filterArea=new n.Rectangle(0,0,o,l)),F.addChild(w),B.push(w)},M=b=>{var z,ce,he;const w=(z=this._layerDisplayObjects.get(b.id))==null?void 0:z.displayObject,G=(w==null?void 0:w.texture)||(this._isSubjectLayer(b)?this.originalTexture:null);if(!G||typeof n.Sprite!="function")return!1;const Y=new n.Sprite(G);return Y.__sourceWidth=Number(((ce=b.source)==null?void 0:ce.originalWidth)||(w==null?void 0:w.__sourceWidth)||G.width||o),Y.__sourceHeight=Number(((he=b.source)==null?void 0:he.originalHeight)||(w==null?void 0:w.__sourceHeight)||G.height||l),this._fitDisplayObjectToRect(Y,b,{x,y:x,width:o,height:l}),Y.alpha=this._layerOpacity(b),!m&&this._isSubjectLayer(b)&&g.length>0&&(Y.filters=g,Y.filterArea=new n.Rectangle(0,0,o,l)),this._applyLayerEffects(n,Y,b),this._applyLayerFilterInstances(Y,b,{forExport:!0,previewToNativeScale:u,sourceWidth:o,sourceHeight:l}),F.addChild(Y),B.push(Y),!0},L=b=>{var ce,he,De;const w=this._backgroundFillForLayer(b),G=this._backgroundColorForLayer(b),Y={x,y:x,width:o,height:l};let z=null;if(G&&typeof n.Graphics=="function")z=new n.Graphics,z.rect(x,x,o,l).fill(G);else if((w==null?void 0:w.kind)==="gradient"&&typeof n.Sprite=="function"){const $=this._createGradientTexture(n,w,o,l);if(!$)return!1;z=new n.Sprite($),z.__ownsTexture=!0,z.__sourceWidth=o,z.__sourceHeight=l,this._fitDisplayObjectToRect(z,b,Y)}else if((w==null?void 0:w.kind)==="media"){const $=(ce=this._layerDisplayObjects.get(b.id))==null?void 0:ce.displayObject,be=$==null?void 0:$.texture;if(!be)return!1;z=this._createBackgroundSprite(n,be,w.fit),z.__sourceWidth=Number(((he=w.source)==null?void 0:he.originalWidth)||$.__sourceWidth||be.width||1),z.__sourceHeight=Number(((De=w.source)==null?void 0:De.originalHeight)||$.__sourceHeight||be.height||1),this._fitDisplayObjectToRect(z,b,Y)}return z?(z.alpha=this._layerOpacity(b),this._applyLayerEffects(n,z,b),this._applyLayerFilterInstances(z,b,{forExport:!0,previewToNativeScale:u,sourceWidth:o,sourceHeight:l}),F.addChild(z),B.push(z),!0):!1},U=b=>{const w=this._createTextDisplayObjectForLayer(n,b);return w?(this._fitTextDisplayObjectToRect(w,b,{x,y:x,width:o,height:l}),w.alpha=this._layerOpacity(b),F.addChild(w),B.push(w),!0):!1},ee=p,oe=m;if(oe){for(const b of ee.layers)if(!(!b||b.visible===!1)){if(this._isTextLayer(b)){U(b);continue}if(b.type==="image"){!M(b)&&this._isSubjectLayer(b)&&V(b);continue}if(this._isSubjectLayer(b)){M(b)||V(b);continue}L(b)}}else V();!oe&&((fe=F.children)==null?void 0:fe.length)===0&&V();const le=n.RenderTexture.create({width:S,height:T,resolution:1}),Se=((me=F.children)==null?void 0:me.length)??0;try{this.app.renderer.render({container:F,target:le,clear:!0,clearColor:[0,0,0,0]});const b=(ge=(j=this.app.renderer.extract)==null?void 0:j.canvas)==null?void 0:ge.call(j,le);return b?{canvas:b,width:S,height:T,margin:x,childCount:Se}:null}finally{for(const b of B)b.filters=null;F.removeChildren();for(const b of B){const w=(b==null?void 0:b.__ownsTexture)===!0;b.destroy({children:!1,texture:w,textureSource:w})}F.destroy({children:!1}),le.destroy(!0)}},A=(x,S,T)=>{const F=typeof x.getContext=="function"?x.getContext("2d"):null;if(!F)return null;let B;try{B=F.getImageData(0,0,S,T).data}catch{return null}const V=1;let M=S,L=T,U=-1,ee=-1;const oe=4,le=S*oe;for(let j=0;j<T;j++){const ge=j*le;for(let b=0;b<S;b++)B[ge+b*oe+3]>=V&&(b<M&&(M=b),b>U&&(U=b),j<L&&(L=j),j>ee&&(ee=j))}if(U<0)return null;const Se=U-M+1,fe=ee-L+1,me=M===0||L===0||U===S-1||ee===T-1;return{x:M,y:L,width:Se,height:fe,touchesEdge:me}};let P=null;try{let x=k(C);if(!x)return null;let S=A(x.canvas,x.width,x.height);if(!S)if(m&&x.childCount===0)S={x:x.margin,y:x.margin,width:o,height:l,touchesEdge:!1};else return null;if(S.touchesEdge&&C<o&&C<l){const M=Math.max(C*4,256),L=k(M);if(L){const U=A(L.canvas,L.width,L.height);U&&!U.touchesEdge?(x=L,S=U):(x=L,S=U??S)}}let T=S.width,F=S.height;if(r>0){const M=Math.max(T,F);let L=r/M;i&&(L=Math.min(1,L)),T=Math.max(1,Math.round(T*L)),F=Math.max(1,Math.round(F*L))}if(s>0&&T*F>s){const M=Math.sqrt(s/(T*F));T=Math.max(1,Math.floor(T*M)),F=Math.max(1,Math.floor(F*M))}const B=document.createElement("canvas");B.width=T,B.height=F;const V=B.getContext("2d");return V?(V.drawImage(x.canvas,S.x,S.y,S.width,S.height,0,0,T,F),P=B.toDataURL(`image/${e}`,t),this._lastExportDimensions={width:T,height:F},P||null):null}catch{return null}}getExportDimensions(){var n;if(this._lastExportDimensions)return{...this._lastExportDimensions};const e=this.originalTexture,t=Math.round((e==null?void 0:e.width)||0),r=Math.round((e==null?void 0:e.height)||0);let i=0;const s=(n=this.sprite)==null?void 0:n.filters;if(Array.isArray(s))for(const o of s){if(!o)continue;const l=typeof o._exportPadding=="number"?o._exportPadding:typeof o.padding=="number"?o.padding:0;l>i&&(i=l)}return{width:t+2*i,height:r+2*i}}async exportBlob(e="png",t=.92,r={}){const i=this.exportImage(e,t,r.maxEdge??0,r.dontUpscale!==!1,r.maxPixels??0);if(!i)return null;const n=await(await fetch(i)).blob(),o=this.getExportDimensions();return{blob:n,width:o.width,height:o.height}}resizeTo(e){var i;if(!((i=this.app)!=null&&i.renderer)||!e)return;const t=e.clientWidth,r=e.clientHeight;if(!(t===Math.round(this.app.screen.width)&&r===Math.round(this.app.screen.height))&&!(t<=0||r<=0)&&(this.app.renderer.resize(t,r),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,r;(r=(t=this.app)==null?void 0:t.renderer)!=null&&r.background&&(this.app.renderer.background.color=e)}_loadImageElement(e){return new Promise(t=>{const r=new Image;typeof e=="string"&&/^https?:\/\//.test(e)&&(r.crossOrigin="anonymous"),r.onload=()=>t(r),r.onerror=()=>{t(null)},r.src=e})}destroy(){if(this._destroyed=!0,this._mountToken+=1,this._mountPromise=null,this._destroyLayerDisplayObjects(),this.app){try{this.app.destroy(!0,{children:!0,texture:!0})}catch{}this.app=null}this.sprite=null,this.originalTexture=null,this.baseTexture=null,this._container=null,this.removeAllListeners()}}const Te='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="48" d="M328 112L184 256l144 144"/></svg>',ze='<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>',Nt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="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>',Tt='<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>',zt='<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>',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="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>',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="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>',Bt='<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>',Et='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="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>',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="M176 112l80-80 80 80M255.98 32l.02 448M176 400l80 80 80-80M400 176l80 80-80 80M112 176l-80 80 80 80M32 256h448"/></svg>',It='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="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>',Dt='<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>',nt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="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>',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="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>',Ce='<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>',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="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>',jt='<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>',Yt='<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>',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="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>',Xt='<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>',we='<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>',ct='<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>',Ut='<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>',Vt='<svg viewBox="0 0 512 512" width="20" height="20"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="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>',Ht='<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>',Wt='<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>',qt='<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>',$t='<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>',Gt='<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>',Zt='<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>',Kt='<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>',Jt='<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>',je='<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>',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="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>',Qt='<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>',er='<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>',ke=[{id:"adjust",name:"Adjust",icon:Lt,registryCategories:["adjust","advanced"]},{id:"blur",name:"Blur",icon:Rt,registryCategories:["blur"]},{id:"color",name:"Color",icon:Bt,registryCategories:["color"]},{id:"effects",name:"Effects",icon:Et,registryCategories:["effects"]},{id:"distortion",name:"Distortion",icon:at,registryCategories:["distortion"]},{id:"light",name:"Light",icon:Dt,registryCategories:["light"]},{id:"stylize",name:"Stylize",icon:Qt,registryCategories:["stylize"]},{id:"text",name:"Text",icon:Gt},{id:"background",name:"Background",icon:It},{id:"layers",name:"Layers",icon:ct},{id:"crop",name:"Crop",icon:nt}],tr=Object.fromEntries(ke.filter(a=>Array.isArray(a.registryCategories)&&a.registryCategories.length>0).map(a=>[a.id,a.registryCategories])),ht=Object.fromEntries(ke.filter(a=>Array.isArray(a.registryCategories)).flatMap(a=>a.registryCategories.map(e=>[e,a.id])));function rr(a){return tr[a]||[a]}class dt extends ne{constructor(e,t){super(),this.state=e,this.renderer=t,this.instances={},this._filterRegistry=null}setRegistry(e){var t,r;this._filterRegistry=e,(r=(t=this.renderer)==null?void 0:t.setLayerFilterFactory)==null||r.call(t,(i,s)=>this.createFiltersForLayer(i,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=rr(e),r=[],i=new Set;for(const s of t){const n=this._filterRegistry.getFiltersByCategory(s)||[];for(const o of n)i.has(o.id)||(i.add(o.id),r.push(o))}return r}_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 r=t.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean);let i=e;for(const s of r){if(i==null)return;i=i[s]}return i}_setDeepProp(e,t,r){if(!e||!t)return;if(!t.includes(".")&&!t.includes("[")){e[t]=r;return}const i=t.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean);let s=e;for(let o=0;o<i.length-1;o++){const l=i[o];if(!(l in s)||(s=s[l],s==null))return}const n=i[i.length-1];s[n]=r}initializeValues(e,t=void 0){const r=this.getFilterDef(e);if(!r)return;const i=this.state.getFilterValues(e),s=new Set((r.controls||[]).map(n=>n.id));if(r.defaultParams)for(const[n,o]of Object.entries(r.defaultParams))!s.has(n)&&!(n in i)&&this.state.setFilterValue(e,n,o,t);r.controls&&r.controls.forEach(n=>{n.id in i||this.state.setFilterValue(e,n.id,n.default,t)})}resetValues(e,t=void 0){const r=this.getFilterDef(e);if(!r)return;const i=new Set((r.controls||[]).map(s=>s.id));if(r.defaultParams)for(const[s,n]of Object.entries(r.defaultParams))i.has(s)||this.state.setFilterValue(e,s,n,t);r.controls&&r.controls.forEach(s=>{this.state.setFilterValue(e,s.id,s.default,t)})}toggle(e,t,r=void 0){return this.state.toggleFilter(e,t,r)===!1?!1:(t?this.initializeValues(e,r):delete this.instances[e],this.applyFilters(),this.emit("filterToggled",{filterId:e,enabled:t}),!0)}updateValue(e,t,r,i=void 0){const s=this._normalizeValue(r);if(!this._matchesExpectedFilterLayer(i))return!1;const n=this.getFilterDef(e),o=n==null?void 0:n.controls.find(u=>u.id===t),l=!o&&(t.includes("[")||t.includes("."));if(!l&&this.state.setFilterValue(e,t,s,i)===!1)return!1;const c=this.instances[e];if(!c)return!1;const d=(o==null?void 0:o.property)||t;if(typeof c.updateUIParam=="function"){if(c.updateUIParam(d,s),l&&typeof c.getSerializableParams=="function"){const u=c.getSerializableParams();for(const[p,m]of Object.entries(u))this.state.setFilterValue(e,p,m,i)}return!0}const h=this._getDeepProp(c,d);return typeof h=="function"?!1:c.uniforms&&d in c.uniforms?(c.uniforms[d]=s,!0):h!==void 0?(this._setDeepProp(c,d,s),!0):!1}performFilterAction(e,t,r=void 0){if(!this._matchesExpectedFilterLayer(r))return!1;const i=this.instances[e];if(!i||typeof i.updateUIParam!="function")return!1;if(i.updateUIParam(t,!0),typeof i.getSerializableParams=="function"){const s=i.getSerializableParams();for(const[n,o]of Object.entries(s))this.state.setFilterValue(e,n,o,r)}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 r=typeof e=="string"?e.trim():"";return r===""?!1:typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId()===r:this.state.get("activeLayerId")===r}_layerDocument(){var t,r;const e=(r=(t=this.state).getSerializableDocument)==null?void 0:r.call(t);return e&&e.version===2&&Array.isArray(e.layers)?e:null}_sourceDimensionsForLayer(e,t={}){var i,s,n,o,l,c,d,h,u;const r=(e==null?void 0:e.source)||((i=e==null?void 0:e.fill)==null?void 0:i.source)||null;return{width:Math.round(Number(t.sourceWidth||(r==null?void 0:r.originalWidth)||((n=(s=this.renderer)==null?void 0:s.originalTexture)==null?void 0:n.width)||((l=(o=this.renderer)==null?void 0:o.sprite)==null?void 0:l.width)||0)),height:Math.round(Number(t.sourceHeight||(r==null?void 0:r.originalHeight)||((d=(c=this.renderer)==null?void 0:c.originalTexture)==null?void 0:d.height)||((u=(h=this.renderer)==null?void 0:h.sprite)==null?void 0:u.height)||0))}}_paramsForFilterState(e,t,r){const i=t!=null&&t.values&&typeof t.values=="object"?t.values:{},s=e.defaultParams?{...e.defaultParams}:{};e.controls&&Array.isArray(e.controls)&&e.controls.forEach(o=>{const l=o.property||o.id;s[l]=i[o.id]??o.default});const n=new Set((e.controls||[]).map(o=>o.id));for(const[o,l]of Object.entries(i))n.has(o)||(s[o]=l);return s._sourceWidth=r.width,s._sourceHeight=r.height,s}createFiltersForLayer(e,t={}){if(!Array.isArray(e==null?void 0:e.filters)||e.filters.length===0)return[];const r=[],i=this.state.get("activeLayerId"),s=e.id===i&&t.forExport!==!0,n=this._sourceDimensionsForLayer(e,t);for(const o of e.filters)if(!(!o||o.enabled===!1||typeof o.id!="string"))try{const l=this.getFilterDef(o.id);if(!(l!=null&&l.createFilter)||typeof l.createFilter!="function")continue;const c=l.createFilter(this._paramsForFilterState(l,o,n));if(!c)continue;let d=c;t.forExport===!0&&typeof c.createExportFilter=="function"&&(d=c.createExportFilter({previewToNativeScale:t.previewToNativeScale||1})||c),r.push(d),s&&(this.instances[o.id]=c)}catch{}return r}applyFilters(){var n,o,l,c,d,h,u;const e=this._layerDocument();if(e){for(const m in this.instances)delete this.instances[m];(o=(n=this.renderer)==null?void 0:n.setLayerFilterFactory)==null||o.call(n,(m,g)=>this.createFiltersForLayer(m,g));const p=(c=(l=this.renderer)==null?void 0:l.applyLayerFilters)==null?void 0:c.call(l,e);this.emit("filtersApplied",{count:((d=this.state.get("activeFilters"))==null?void 0:d.size)??0,failed:[],scopedToLayer:!0}),p||(u=(h=this.renderer)==null?void 0:h.render)==null||u.call(h);return}const t=this.renderer.sprite;if(!t)return;for(const p in this.instances)delete this.instances[p];const r=[],i=[];this.state.get("activeFilters").forEach(p=>{try{const m=this.getFilterDef(p);if(!m||!m.createFilter||typeof m.createFilter!="function")return;const g=this.state.getFilterValues(p),_=m.defaultParams?{...m.defaultParams}:{};m.controls&&Array.isArray(m.controls)&&m.controls.forEach(N=>{const pe=N.property||N.id;_[pe]=g[N.id]??N.default});const C=new Set((m.controls||[]).map(N=>N.id));for(const[N,pe]of Object.entries(g))C.has(N)||(_[N]=pe);const k=this.renderer.sprite,A=this.renderer.originalTexture;_._sourceWidth=Math.round((A==null?void 0:A.width)||(k==null?void 0:k.width)||0),_._sourceHeight=Math.round((A==null?void 0:A.height)||(k==null?void 0:k.height)||0);const P=m.createFilter(_);P&&(r.push(P),this.instances[p]=P)}catch{i.push(p)}});try{t.filters=null,t.filters=r.length?r:null,this.renderer.render(),this.emit("filtersApplied",{count:r.length,failed:i})}catch(p){try{t.filters=null,this.renderer.render()}catch{}this.emit("filtersError",{error:p,failedFilters:i})}i.length>0}resetAll(e=void 0){for(const i in this.instances)delete this.instances[i];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 J=class J extends ne{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 r=e.split(":");if(r.length===2){const i=parseFloat(r[0]),s=parseFloat(r[1]);if(Number.isFinite(i)&&Number.isFinite(s)&&s>0)return i/s}return null}applyAspectRatio(){const e=this.state.get("crop.rect"),t=this.state.get("crop.aspect");if(!e||t==="free")return;const r=this._getAspectRatio(t);if(!r)return;const i=e.width/e.height;Math.abs(i-r)<.01||(i>r?e.width=e.height*r:e.height=e.width/r,this.state.set("crop.rect",e))}constrainCropRect(){const e=this.state.get("crop.rect");if(!e)return;const t=this.renderer.sprite,r=this.renderer.app;if(!t||!r)return;const i=this.state.get("crop.shape"),s={x:0,y:0,w:r.screen.width,h:r.screen.height};if(e.x=Math.max(s.x,Math.min(e.x,s.x+s.w-e.width)),e.y=Math.max(s.y,Math.min(e.y,s.y+s.h-e.height)),e.width=Math.min(e.width,s.w),e.height=Math.min(e.height,s.h),i!=="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,r,i,s,n,o){if(!e||!i||!s||!n)return null;const l=e.width>t,c=e.height>r;if(!l&&!c)return null;const d=J.AUTO_ZOOM_PADDING;let h=o;if(l){const u=e.width/(d*i*n);h=Math.min(h,u)}if(c){const u=e.height/(d*s*n);h=Math.min(h,u)}return h=Math.max(.1,h),h>=o-.01?null:h}_checkAutoZoom(){if(!this.state.get("autoZoomOnCropOverflow"))return;const e=Date.now();if(e-this._lastAutoZoomCheck<J.AUTO_ZOOM_THROTTLE_MS)return;this._lastAutoZoomCheck=e;const t=this.state.get("crop.rect"),r=this.renderer.sprite,i=this.renderer.originalTexture;if(!t||!r||!i)return;const s=J.calcAutoZoom(t,r.width,r.height,i.width,i.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 r=t.canvas,i=r.clientWidth,s=r.clientHeight,n=window.devicePixelRatio||1;(e.width!==Math.max(1,Math.floor(i*n))||e.height!==Math.max(1,Math.floor(s*n)))&&(e.width=Math.max(1,Math.floor(i*n)),e.height=Math.max(1,Math.floor(s*n)),e.style.width=i+"px",e.style.height=s+"px");const o=e.getContext("2d");if(!o)return;o.setTransform(n,0,0,n,0,0),o.clearRect(0,0,i,s),o.fillStyle="rgba(0, 0, 0, 0.5)",o.fillRect(0,0,i,s);const l=this.state.get("crop.rect");if(!l)return;const c=this.state.get("crop.shape");if(o.save(),c==="circle"){const _=l.x+l.width/2,C=l.y+l.height/2,k=Math.min(l.width,l.height)/2;o.beginPath(),o.arc(_,C,k,0,Math.PI*2),o.clip()}else o.beginPath(),o.rect(l.x,l.y,l.width,l.height),o.clip();o.clearRect(l.x,l.y,l.width,l.height),o.restore(),o.strokeStyle="#ffffff",o.lineWidth=2,o.setLineDash([5,5]),c==="circle"?(o.beginPath(),o.arc(l.x+l.width/2,l.y+l.height/2,Math.min(l.width,l.height)/2,0,Math.PI*2),o.stroke()):o.strokeRect(l.x,l.y,l.width,l.height),o.setLineDash([]),o.strokeStyle="rgba(255,255,255,0.3)",o.lineWidth=1;const d=l.width/3,h=l.height/3;for(let _=1;_<=2;_++)o.beginPath(),o.moveTo(l.x+d*_,l.y),o.lineTo(l.x+d*_,l.y+l.height),o.stroke(),o.beginPath(),o.moveTo(l.x,l.y+h*_),o.lineTo(l.x+l.width,l.y+h*_),o.stroke();const u=this.HANDLE_SIZE,p=[{x:l.x,y:l.y,m:"resize-nw"},{x:l.x+l.width,y:l.y,m:"resize-ne"},{x:l.x,y:l.y+l.height,m:"resize-sw"},{x:l.x+l.width,y:l.y+l.height,m:"resize-se"}],m=[{x:l.x+l.width/2,y:l.y,m:"n"},{x:l.x+l.width/2,y:l.y+l.height,m:"s"},{x:l.x,y:l.y+l.height/2,m:"w"},{x:l.x+l.width,y:l.y+l.height/2,m:"e"}],g=[...p,...m];for(const _ of g){const C=this._hoverMode===_.m,k=C?u+4:u;o.beginPath(),o.rect(_.x-k/2,_.y-k/2,k,k),o.fillStyle=C?"#4da3ff":"#ffffff",o.strokeStyle="rgba(0,0,0,0.6)",o.lineWidth=1,o.fill(),o.stroke()}}_hitHandle(e,t){const r=this.state.get("crop.rect");if(!r)return null;const i=(s,n,o,l,c)=>Math.abs(s-o)<=c&&Math.abs(n-l)<=c;return i(e,t,r.x,r.y,this.HANDLE_SIZE)?"resize-nw":i(e,t,r.x+r.width,r.y,this.HANDLE_SIZE)?"resize-ne":i(e,t,r.x,r.y+r.height,this.HANDLE_SIZE)?"resize-sw":i(e,t,r.x+r.width,r.y+r.height,this.HANDLE_SIZE)?"resize-se":Math.abs(t-r.y)<=this.EDGE_HIT_PAD&&e>=r.x&&e<=r.x+r.width?"n":Math.abs(t-(r.y+r.height))<=this.EDGE_HIT_PAD&&e>=r.x&&e<=r.x+r.width?"s":Math.abs(e-r.x)<=this.EDGE_HIT_PAD&&t>=r.y&&t<=r.y+r.height?"w":Math.abs(e-(r.x+r.width))<=this.EDGE_HIT_PAD&&t>=r.y&&t<=r.y+r.height?"e":e>=r.x&&e<=r.x+r.width&&t>=r.y&&t<=r.y+r.height?"move":null}_handlePointerDown(e){const t=this.state.get("crop.rect");if(!t)return;const r=e.global;this._dragMode=this._hitHandle(r.x,r.y),this._dragMode&&(this._isDragging=!0,this._dragStart={x:r.x,y:r.y},this._startRect={...t},this._lastAutoZoomCheck=0)}_handlePointerMove(e){var l,c,d,h;const t=this.renderer.app;if(!t)return;const r=e.global;if(!this._isDragging||!this._dragStart||!this._startRect){this._hoverMode=this._hitHandle(r.x,r.y),t.stage.cursor=this._hoverMode==="move"?"move":this._hoverMode==="n"||this._hoverMode==="s"?"ns-resize":this._hoverMode==="e"||this._hoverMode==="w"?"ew-resize":(l=this._hoverMode)!=null&&l.endsWith("nw")||(c=this._hoverMode)!=null&&c.endsWith("se")?"nwse-resize":(d=this._hoverMode)!=null&&d.endsWith("ne")||(h=this._hoverMode)!=null&&h.endsWith("sw")?"nesw-resize":"crosshair",this.drawOverlay();return}const i=this.state.get("crop.rect");if(!i)return;const s=r.x-this._dragStart.x,n=r.y-this._dragStart.y;switch(this._dragMode){case"move":i.x=this._startRect.x+s,i.y=this._startRect.y+n;break;case"n":i.y=this._startRect.y+n,i.height=this._startRect.height-n;break;case"s":i.height=this._startRect.height+n;break;case"w":i.x=this._startRect.x+s,i.width=this._startRect.width-s;break;case"e":i.width=this._startRect.width+s;break;case"resize-nw":i.x=this._startRect.x+s,i.y=this._startRect.y+n,i.width=this._startRect.width-s,i.height=this._startRect.height-n;break;case"resize-ne":i.y=this._startRect.y+n,i.width=this._startRect.width+s,i.height=this._startRect.height-n;break;case"resize-sw":i.x=this._startRect.x+s,i.width=this._startRect.width-s,i.height=this._startRect.height+n;break;case"resize-se":i.width=this._startRect.width+s,i.height=this._startRect.height+n;break}i.width=Math.max(50,i.width),i.height=Math.max(50,i.height),this.state.set("crop.rect",i),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 r=this.state.get("crop.rect");if(!r){this.state.get("crop.shape")==="circle"&&this.state.set("crop.aspect","1:1");const n=this.state.get("crop.aspect"),o=this._getAspectRatio(n);let l,c;if(o){const u=t.width*.9,p=t.height*.9;u/p>o?(c=p,l=c*o):(l=u,c=l/o)}else{const u=Math.min(e.screen.width,e.screen.height)*.7;l=u,c=u}const d=t.x+(t.width-l)/2,h=t.y+(t.height-c)/2;r={x:d,y:h,width:l,height:c},this.state.set("crop.rect",r),n!=="free"&&this.constrainCropRect()}this.state.set("crop.dirty",!1);const i=e.stage;i.eventMode="static",i.hitArea=e.screen,i.cursor="crosshair",i.on("pointerdown",this._onPointerDown),i.on("pointermove",this._onPointerMove),i.on("pointerup",this._onPointerUp),i.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 r=this._overlayCanvas.getContext("2d");r==null||r.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,r=this.renderer.originalTexture,i=this.state.get("crop.rect");if(!i||!t||!e||!r)return null;const s=window.PIXI,n=this.renderer.zoom,o=r.width/t.width,l=r.height/t.height,c=(i.x-t.x)*o,d=(i.y-t.y)*l;let h=Math.round(Math.max(1,i.width*o)),u=Math.round(Math.max(1,i.height*l)),p=Math.round(c),m=Math.round(d);if(h<=0||u<=0)return null;const g=new s.Container,_=new s.Sprite(r);if(this.state.get("crop.shape")==="circle"){const F=Math.round(Math.max(h,u)),B=p+h/2,V=m+u/2;p=Math.round(B-F/2),m=Math.round(V-F/2),h=u=F;const M=new s.Graphics;typeof M.circle=="function"&&typeof M.fill=="function"?M.circle(h/2,u/2,h/2).fill(16777215):(M.beginFill(16777215,1),M.drawCircle(h/2,u/2,h/2),M.endFill()),_.mask=M,g.addChild(M)}_.x=-p,_.y=-m,g.addChild(_);const k=s.RenderTexture.create({width:h,height:u});e.renderer.render({container:g,target:k,clear:!0}),g.destroy({children:!0});const A=this.renderer.originalTexture;A&&A!==this.renderer.baseTexture&&A.destroy(!0),this.renderer.originalTexture=k,e.stage.removeChild(t),t.destroy();const P=new s.Sprite(k);e.stage.addChild(P),this.renderer.sprite=P,this.renderer.fitScale=this.renderer.getFitScaleFor(k),this.renderer.setZoom(n,{keepCenter:!1}),this.renderer.applyViewTransform(),this.renderer.render();const N=this.state.get("crop.appliedRect"),x=N&&Number.isFinite(N.x)&&Number.isFinite(N.y)&&Number.isFinite(N.width)&&Number.isFinite(N.height)?{x:Math.round(N.x+p),y:Math.round(N.y+m),width:h,height:u}:{x:p,y:m,width:h,height:u},S=this.state.get("crop.shape")||"free",T=this.state.get("crop.aspect")||"free";return this.disable(),this.state.set("crop.appliedRect",x),this.state.set("crop.appliedShape",S),this.state.set("crop.appliedAspect",T),this.state.set("crop.dirty",!1),this.emit("applied",{width:h,height:u}),{texture:k,preservedZoom:n}}applyFromPixelRect(e,t="free"){const r=this.renderer.app,i=this.renderer.sprite,s=this.renderer.originalTexture;if(!e||!i||!r||!s)return null;const n=window.PIXI,o=this.renderer.zoom;let l=Math.round(Math.max(1,e.width)),c=Math.round(Math.max(1,e.height)),d=Math.round(e.x),h=Math.round(e.y);if(l<=0||c<=0)return null;const u=new n.Container,p=new n.Sprite(s);if(t==="circle"){const C=Math.round(Math.max(l,c)),k=d+l/2,A=h+c/2;d=Math.round(k-C/2),h=Math.round(A-C/2),l=c=C;const P=new n.Graphics;typeof P.circle=="function"&&typeof P.fill=="function"?P.circle(l/2,c/2,l/2).fill(16777215):(P.beginFill(16777215,1),P.drawCircle(l/2,c/2,l/2),P.endFill()),p.mask=P,u.addChild(P)}p.x=-d,p.y=-h,u.addChild(p);const m=n.RenderTexture.create({width:l,height:c});r.renderer.render({container:u,target:m,clear:!0}),u.destroy({children:!0});const g=this.renderer.originalTexture;g&&g!==this.renderer.baseTexture&&g.destroy(!0),this.renderer.originalTexture=m,r.stage.removeChild(i),i.destroy();const _=new n.Sprite(m);return r.stage.addChild(_),this.renderer.sprite=_,this.renderer.fitScale=this.renderer.getFitScaleFor(m),this.renderer.setZoom(o,{keepCenter:!1}),this.renderer.applyViewTransform(),this.renderer.render(),{texture:m,preservedZoom:o}}cancel(){this.disable(),this.emit("cancelled")}setShape(e){this.state.get("lockCropShape")||(this.state.set("crop.shape",e),this.state.set("crop.dirty",!0),(e==="circle"||e==="square")&&this.state.set("crop.aspect","1:1"),this.applyAspectRatio(),this.constrainCropRect(),this.drawOverlay())}setAspect(e){if(this.state.get("lockAspectRatio"))return;if(this.state.get("crop.shape")!=="free"){if(this.state.get("lockCropShape"))return;this.state.set("crop.shape","free")}this.state.set("crop.aspect",e),this.state.set("crop.dirty",!0),this.applyAspectRatio(),this.constrainCropRect(),this.drawOverlay()}};Fe(J,"AUTO_ZOOM_PADDING",1.1),Fe(J,"AUTO_ZOOM_THROTTLE_MS",100);let ve=J;class ut{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 r of t)r.signal.aborted||r.abort(e);return t.length}async preparePreviewRequest(e,t={}){const r=typeof e=="string"?await this._dataUrlToBlob(e):e;return{...t,blob:r,operationId:t.operationId||this._uuid(),sessionKey:t.sessionKey||this._uuid(),sourceHash:t.sourceHash||await this._sha256Hex(r),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 r=typeof Blob<"u"&&t.blob instanceof Blob?t:await this.preparePreviewRequest(e,t),i=r.blob,s=r.operationId,n=r.sessionKey,o=r.sourceHash,l=new FormData;l.append("image_file",i,"image.png"),l.append("operation_id",s),l.append("session_key",n),l.append("source_hash",o),l.append("tier",r.tier||"balanced"),r.targetRef&&l.append("target_ref",r.targetRef),r.model&&l.append("model",r.model),r.alpha_matting&&(l.append("alpha_matting","true"),l.append("alpha_f",String(r.alpha_f??10)),l.append("alpha_fr",String(r.alpha_fr??15)),l.append("alpha_erode_size",String(r.alpha_erode_size??10))),r.max_megapixels!==void 0&&l.append("max_megapixels",String(r.max_megapixels));let c,d;const h=this._createAbortController(),u=p=>h?{...p,signal:h.signal}:p;try{try{c=await fetch(this._endpoint,u({method:"POST",body:l,credentials:"include"}))}catch(g){if(h!=null&&h.signal.aborted)throw g;d=g}if((!c||!c.ok)&&this._fallbackEndpoint)try{c=await fetch(this._fallbackEndpoint,u({method:"POST",body:l}))}catch(g){if(h!=null&&h.signal.aborted)throw g;d||(d=g)}if(!c)throw d||new Error("Network error: Unable to connect to background removal service");if(!c.ok){let g=`Background removal failed (HTTP ${c.status})`;try{const _=await c.text();_&&(g+=`: ${_}`)}catch{}throw new Error(g)}const p=await c.blob();return{dataUrl:await this._blobToDataUrl(p),model:c.headers.get("X-Model-Used")||"unknown",processMs:c.headers.get("X-Process-Ms")||"0",operationId:c.headers.get("X-Operation-Id")||s,sessionKey:c.headers.get("X-Session-Key")||n,sourceHash:c.headers.get("X-Source-Hash")||o,targetRef:c.headers.get("X-Target-Ref")||r.targetRef||null}}finally{this._releaseAbortController(h)}}async removeSavedMediaBackground(e){const t=this._savedEndpoint.replace("{media}",encodeURIComponent(e.targetMediaUuid)),r={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&&(r.model=e.model),e.alpha_matting!==void 0&&(r.alpha_matting=!!e.alpha_matting),e.max_megapixels!==void 0&&(r.max_megapixels=Number(e.max_megapixels));const i=this._createAbortController();let s;try{if(s=await fetch(t,{method:"POST",body:JSON.stringify(r),credentials:"include",headers:{Accept:"application/json","Content-Type":"application/json"},...i?{signal:i.signal}:{}}),!s.ok){let n=`Background removal failed (HTTP ${s.status})`;try{const o=await s.json();o!=null&&o.message&&(n+=`: ${o.message}`)}catch{}throw new Error(n)}return await s.json()}finally{this._releaseAbortController(i)}}async _dataUrlToBlob(e){if(e.startsWith("data:")){const[r,i]=e.split(","),s=r.match(/:(.*?);/),n=s?s[1]:"image/png",o=atob(i),l=new Uint8Array(o.length);for(let c=0;c<o.length;c++)l[c]=o.charCodeAt(c);return new Blob([l],{type:n})}return(await fetch(e)).blob()}_blobToDataUrl(e){return new Promise((t,r)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>r(new Error("Failed to read blob as data URL")),i.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 r=Math.floor(Math.random()*16);return(t==="x"?r:r&3|8).toString(16)})}async _sha256Hex(e){const t=await e.arrayBuffer(),r=await globalThis.crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("")}}function f(a,e={},...t){const r=document.createElement(a);for(const[i,s]of Object.entries(e))if(s!=null)if(i==="className")r.className=s;else if(i==="style"&&typeof s=="object")Object.assign(r.style,s);else if(i.startsWith("on")&&typeof s=="function"){const n=i.slice(2).toLowerCase();r.addEventListener(n,s)}else i==="dataset"&&typeof s=="object"?Object.assign(r.dataset,s):r.setAttribute(i,s);for(const i of t)typeof i=="string"?r.appendChild(document.createTextNode(i)):i instanceof HTMLElement&&r.appendChild(i);return r}function Le({id:a,label:e,min:t=0,max:r=1,step:i=.01,value:s=.5,onChange:n}){const o=a.includes("-")?a.split("-").slice(1).join("-"):a,l=f("div",{className:"slider-control slider-wrapper","data-control":o,"data-testid":`slider-${o}`}),c=f("div",{className:"slider-header"},f("label",{for:a,className:"slider-label"},e),f("span",{className:"slider-value",id:`${a}-value`},Me(s))),d=f("input",{type:"range",id:a,className:"slider-input",min:String(t),max:String(r),step:String(i),value:String(s),onInput:h=>{const u=parseFloat(h.target.value),p=l.querySelector(".slider-value");p&&(p.textContent=Me(u)),n==null||n(u)}});return l.appendChild(c),l.appendChild(d),l.setValue=h=>{d.value=String(h);const u=l.querySelector(".slider-value");u&&(u.textContent=Me(h))},l}function Me(a){return Number.isInteger(a)?String(a):a.toFixed(2)}function Re({id:a,label:e,checked:t=!1,onChange:r}){const i=f("div",{className:"toggle-control"}),s=f("label",{className:"toggle-label",for:a},e),n=f("input",{type:"checkbox",id:a,className:"toggle-input",checked:t?"checked":void 0,onChange:c=>r==null?void 0:r(c.target.checked)}),o=f("div",{className:"toggle-switch",onClick:c=>{c.target!==n&&(n.checked=!n.checked,r==null||r(n.checked))}}),l=f("span",{className:"toggle-slider"});return o.appendChild(n),o.appendChild(l),i.appendChild(s),i.appendChild(o),i.setChecked=c=>{n.checked=c},i}function Be({id:a,label:e,value:t="#000000",onChange:r}){const i=f("div",{className:"color-control"}),s=f("label",{className:"color-label",for:a},e),n=f("input",{type:"color",id:a,className:"color-input",value:t,onInput:o=>r==null?void 0:r(o.target.value)});return i.appendChild(s),i.appendChild(n),i.setValue=o=>{n.value=o},i}function Ee({id:a,label:e,value:t="",placeholder:r="",onCommit:i}){const s=f("div",{className:"text-control","data-control":a,"data-testid":`text-${a}`}),n=f("label",{className:"text-label",for:a},e);let o=t;const l=f("input",{type:"text",id:a,className:"text-input",value:t,placeholder:r,onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),c(),l.blur())},onBlur:()=>c()});function c(){const d=l.value;d!==o&&(o=d,i==null||i(d))}return s.appendChild(n),s.appendChild(l),s.setValue=d=>{const h=d==null?"":String(d);l.value=h,o=h},s}function Ie({id:a,label:e,options:t=[],value:r,onChange:i}){const s=f("div",{className:"select-control"}),n=f("label",{className:"select-label",for:a},e),o=f("select",{id:a,className:"select-input",onChange:l=>i==null?void 0:i(l.target.value)});for(const l of t){const c=f("option",{value:l.value},l.label);l.value===r&&(c.selected=!0),o.appendChild(c)}return s.appendChild(n),s.appendChild(o),s.setValue=l=>{o.value=l},s}function D({label:a,className:e="",onClick:t,icon:r=null,disabled:i=!1}){const s=f("button",{type:"button",className:`btn ${e}`.trim(),onClick:t,disabled:i?"disabled":void 0});if(r){const n=f("span",{className:"btn-icon"});n.innerHTML=r;const o=n.querySelector("svg");o&&o.setAttribute("aria-hidden","true"),s.appendChild(n)}return a&&s.appendChild(document.createTextNode(a)),s}function R({icon:a,title:e,className:t="",onClick:r,disabled:i=!1,testId:s=null,ariaLabel:n=null}){const o={type:"button",className:`icon-btn ${t}`.trim(),title:e,"aria-label":n||e,onClick:r,disabled:i?"disabled":void 0};s&&(o.dataset={testid:s});const l=f("button",o);l.innerHTML=a;const c=l.querySelector("svg");return c&&c.setAttribute("aria-hidden","true"),l}function xe({label:a,icon:e,active:t=!1,onClick:r}){const i=f("button",{type:"button",className:`chip ${t?"active":""}`.trim(),onClick:r});if(e){const s=f("span",{className:"chip-icon"});s.innerHTML=e;const n=s.querySelector("svg");n&&n.setAttribute("aria-hidden","true"),i.appendChild(s)}return i.appendChild(f("span",{className:"chip-label"},a)),i.setActive=s=>{i.classList.toggle("active",s)},i}class pt{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=f("div",{className:"editor-toolbar"});const e=f("div",{className:"toolbar-section toolbar-left"}),t=R({icon:Xt,title:"Open Image",className:"toolbar-btn",testId:"btn-open-image",ariaLabel:"Open image file",onClick:()=>this.editor.openFilePicker()});e.appendChild(t);const r=f("div",{className:"toolbar-section toolbar-center"}),i=R({icon:Tt,title:"Zoom Out",className:"toolbar-btn",testId:"btn-zoom-out",ariaLabel:"Zoom out",onClick:()=>{const u=this.state.get("zoom");this.editor.setZoom(u-.25)}});this._zoomLabel=f("span",{className:"zoom-label","aria-live":"polite","aria-atomic":"true",role:"status"},"100%");const s=R({icon:Nt,title:"Zoom In",className:"toolbar-btn",testId:"btn-zoom-in",ariaLabel:"Zoom in",onClick:()=>{const u=this.state.get("zoom");this.editor.setZoom(u+.25)}}),n=R({icon:zt,title:"Fit to Screen",className:"toolbar-btn",testId:"btn-fit-screen",ariaLabel:"Fit to screen",onClick:()=>this.editor.fitToScreen()});r.appendChild(i),r.appendChild(this._zoomLabel),r.appendChild(s),r.appendChild(n);const o=f("div",{className:"toolbar-section toolbar-right"});this._themeBtn=R({icon:this.state.get("isDarkMode")?je:Ye,title:"Toggle Theme",className:"toolbar-btn toolbar-btn-theme",testId:"btn-toggle-theme",ariaLabel:"Toggle theme",onClick:()=>this.editor.toggleTheme()}),this._cropBtn=R({icon:nt,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 l=f("div",{className:"remove-bg-control"});this._removeBgTierSelect=f("select",{className:"remove-bg-tier-select",title:"Background removal quality","aria-label":"Background removal quality",dataset:{testid:"select-remove-background-tier"},onChange:u=>{this._removeBgTier=u.target.value}});for(const u of[["fast","Fast"],["balanced","Balanced"],["best","Best"]]){const p=f("option",{value:u[0]},u[1]);u[0]===this._removeBgTier&&(p.selected=!0),this._removeBgTierSelect.appendChild(p)}this._removeBgBtn=R({icon:er,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=f("span",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true"}),l.appendChild(this._removeBgTierSelect),l.appendChild(this._removeBgBtn),l.appendChild(this._removeBgStatus);const c=R({icon:ot,title:"Reset All",className:"toolbar-btn",testId:"btn-reset-all",ariaLabel:"Reset all changes",onClick:()=>this.editor.resetAll()}),d=R({icon:Ot,title:"Save Image",className:"toolbar-btn toolbar-btn-primary",testId:"btn-save-edit",ariaLabel:"Save image",onClick:()=>this.editor.save()}),h=R({icon:Ce,title:"Close",className:"toolbar-btn",testId:"btn-cancel-edit",ariaLabel:"Close editor",onClick:()=>this.editor.close()});return o.appendChild(this._themeBtn),o.appendChild(this._cropBtn),o.appendChild(l),o.appendChild(c),o.appendChild(d),o.appendChild(h),this.element.appendChild(e),this.element.appendChild(r),this.element.appendChild(o),this._subscribeToState(),this.element}_subscribeToState(){const e=this.state.on("change:zoom",({value:d})=>{this._zoomLabel.textContent=`${Math.round(d*100)}%`});this._unsubscribers.push(e);const t=this.state.on("change:isDarkMode",({value:d})=>{this._themeBtn.innerHTML=d?je:Ye});this._unsubscribers.push(t);const r=this.state.on("change:mode",({value:d})=>{this._cropBtn&&this._cropBtn.classList.toggle("toolbar-btn-primary",d==="crop")});this._unsubscribers.push(r);const i=this.state.on("change:hasImage",()=>this._updateRemoveBgButton());this._unsubscribers.push(i);const s=this.state.on("change:isProcessing",()=>this._updateRemoveBgButton());this._unsubscribers.push(s);const n=this.state.on("change:backgroundRemovalAvailable",()=>this._updateRemoveBgButton());this._unsubscribers.push(n);const o=this.state.on("change:editorDocument",()=>this._updateRemoveBgButton());this._unsubscribers.push(o);const l=this.state.on("change:layers",()=>this._updateRemoveBgButton());this._unsubscribers.push(l);const c=this.state.on("change:activeLayerId",()=>this._updateRemoveBgButton());this._unsubscribers.push(c)}_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)}updateZoom(e){this._zoomLabel&&(this._zoomLabel.textContent=`${Math.round(e*100)}%`)}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(e=this.element)==null||e.remove(),this.element=null}}const _e=ke;class ir{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=f("div",{className:"category-carousel-container","data-testid":"category-carousel"}),this._leftBtn=R({icon:Te,title:"Previous categories",className:"carousel-nav carousel-nav-left",onClick:()=>this._scrollLeft()}),this._carousel=f("div",{className:"category-carousel"}),_e.forEach(r=>{const i=xe({label:r.name,icon:r.icon,active:this.state.get("selectedCategory")===r.id,onClick:()=>this._selectCategory(r.id)});i.dataset.categoryId=r.id,i.dataset.category=r.id,i.dataset.testid=`category-${r.id}`,this._chips.set(r.id,i),this._carousel.appendChild(i)}),this._rightBtn=R({icon:ze,title:"Next categories",className:"carousel-nav carousel-nav-right",onClick:()=>this._scrollRight()}),this._pagination=f("div",{className:"carousel-pagination",role:"tablist","aria-label":"Category pages"});const t=Math.ceil(_e.length/3);for(let r=0;r<t;r++){const i=f("button",{type:"button",className:`pagination-dot ${r===0?"active":""}`,role:"tab","aria-label":`Page ${r+1} of ${t}`,"aria-selected":r===0?"true":"false",onClick:()=>this._scrollToPage(r)});this._pagination.appendChild(i)}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((r,i)=>{r.setActive(i===t)})});this._unsubscribers.push(e)}_selectCategory(e){var i;this.state.set("selectedCategory",e);const t=this.state.get("mode");e==="crop"?t!=="crop"&&this.editor.setMode("crop"):t!=="filters"&&this.editor.setMode("filters");const r=this._chips.get(e);r&&this._carousel&&r.scrollIntoView({behavior:"smooth",inline:"center",block:"nearest"}),(i=this._onSelect)==null||i.call(this,e)}_scrollLeft(){this._scrollIndex>0&&(this._scrollIndex--,this._scrollCarousel())}_scrollRight(){this._scrollIndex<_e.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>=_e.length-3)}_updatePagination(){if(this._pagination){const e=this._pagination.querySelectorAll(".pagination-dot"),t=Math.floor(this._scrollIndex/3);e.forEach((r,i)=>{const s=i===t;r.classList.toggle("active",s),r.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 sr{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=f("div",{className:"filter-carousel-container"}),this._leftBtn=R({icon:Te,title:"Previous filters",className:"carousel-nav carousel-nav-left",onClick:()=>this._scrollLeft()}),this._carousel=f("div",{className:"filter-carousel"}),this._rightBtn=R({icon:ze,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 r=this.state.on("change:selectedFilter",()=>{this._updateSelectedState()});this._unsubscribers.push(r)}_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),r=this.state.get("activeFilters"),i=this.state.get("selectedFilter");t.forEach(s=>{const n=this._createFilterCard(s,{isActive:r.has(s.id),isSelected:i===s.id});this._filterCards.set(s.id,n),this._carousel.appendChild(n)}),this._updateNavButtons()}_createFilterCard(e,{isActive:t,isSelected:r}){const i=f("div",{className:`filter-card ${t?"active":""} ${r?"selected":""}`,"data-filter":e.id,"data-testid":`filter-${e.id}`,onClick:()=>this._handleCardClick(e.id)}),s=f("div",{className:"filter-preview"}),n=f("span",{className:"filter-preview-text"},e.name.charAt(0));s.appendChild(n);const o=f("span",{className:"filter-name",title:e.name},e.name),l=f("button",{className:`filter-toggle ${t?"active":""}`,onClick:c=>{var u;c.stopPropagation();const h=!this.state.get("activeFilters").has(e.id);this._handleToggle(e.id,h),h&&(this.state.set("selectedFilter",e.id),(u=this._onSelect)==null||u.call(this,e.id))}});return l.innerHTML=t?we:"",i.appendChild(s),i.appendChild(o),i.appendChild(l),i._toggle=l,i._isActive=t,i}_handleCardClick(e){var r;this.state.get("activeFilters").has(e)||this._handleToggle(e,!0),this.state.set("selectedFilter",e),(r=this._onSelect)==null||r.call(this,e)}_handleToggle(e,t){var r;(r=this._onToggle)==null||r.call(this,e,t)}_updateActiveStates(){const e=this.state.get("activeFilters");this._filterCards.forEach((t,r)=>{const i=e.has(r);t.classList.toggle("active",i),t._toggle.classList.toggle("active",i),t._toggle.innerHTML=i?we:"",t._isActive=i})}_updateSelectedState(){const e=this.state.get("selectedFilter");this._filterCards.forEach((t,r)=>{t.classList.toggle("selected",r===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 ar{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:r}){return this._onChange=e,this._onReset=t,this._onAction=r,this.element=f("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(f("div",{className:"no-filter-selected"},"Select a filter to adjust"));return}const t=this.filterManager.getFilterDef(e);if(!t){this.element.appendChild(f("div",{className:"no-filter-selected"},"Filter not found"));return}const r=f("div",{className:"adjustments-header"});r.appendChild(f("span",{className:"adjustments-title"},t.name)),r.appendChild(D({label:"Reset",className:"btn-text",onClick:()=>this._handleReset(e)})),this.element.appendChild(r);const i=f("div",{className:"adjustments-grid"}),s=this.state.getFilterValues(e);(t.controls||[]).forEach(o=>{const l=s[o.id]??o.default,c=this._createControl(e,o,l);c&&(this._controls.set(o.id,c),i.appendChild(c))});const n=this.filterManager.getInstance(e);if(n&&typeof n.getDynamicControls=="function"){let o=[];try{o=n.getDynamicControls()||[]}catch{}o.forEach(l=>{const c=l.property||l.id,d=s[c]??l.default,h=this._createControl(e,l,d);h&&(this._controls.set(l.id,h),i.appendChild(h))})}this.element.appendChild(i)}_createControl(e,t,r){if(t.hidden)return null;const i=t.label||t.id,s=this._normalizeControlType(t.type),n=t.property||t.id;switch(s){case"slider":return Le({id:`${e}-${t.id}`,label:i,min:t.min??0,max:t.max??1,step:t.step??.01,value:typeof r=="number"?r:t.default??0,onChange:c=>this._handleChange(e,n,c)});case"toggle":return Re({id:`${e}-${t.id}`,label:i,checked:!!r,onChange:c=>this._handleChange(e,n,c)});case"color":return Be({id:`${e}-${t.id}`,label:i,value:typeof r=="string"&&r.startsWith("#")?r:t.default||"#000000",onChange:c=>this._handleChange(e,n,c)});case"select":const o=this._normalizeOptions(t.options);return Ie({id:`${e}-${t.id}`,label:i,options:o,value:r??t.default,onChange:c=>this._handleChange(e,n,c)});case"text":return Ee({id:`${e}-${t.id}`,label:i,value:typeof r=="string"?r:t.default??"",placeholder:t.placeholder||"",onCommit:c=>this._handleChange(e,n,c)});case"button":const l=f("div",{className:"button-control"});return l.appendChild(D({label:i,className:"btn-secondary",onClick:()=>this._handleAction(e,t.action||t.id)})),l;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,r){var i;(i=this._onChange)==null||i.call(this,e,t,r)}_handleReset(e){var t;(t=this._onReset)==null||t.call(this,e),this._renderControls()}_handleAction(e,t){var r;(r=this._onAction)==null||r.call(this,e,t),this._renderControls()}_updateValues(){const e=this.state.get("selectedFilter");if(!e)return;const t=this.state.getFilterValues(e),r=this.filterManager.getFilterDef(e);r&&r.controls.forEach(i=>{const s=this._controls.get(i.id);if(s&&typeof s.setValue=="function"){const n=t[i.id]??i.default;s.setValue(n)}})}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 nr{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:r,onRemove:i,onAction:s}){this._onChange=t,this._onReset=r,this._onRemove=i,this._onAction=s,this._container=e,this._drawer=f("div",{className:"mobile-filter-drawer"});const n=f("div",{className:"drawer-header"});this._titleEl=f("span",{className:"drawer-title"},"Filter");const o=f("div",{className:"drawer-header-actions"}),l=D({label:"Reset",className:"btn-text",onClick:()=>{var h;this._currentFilterId&&((h=this._onReset)==null||h.call(this,this._currentFilterId),this._renderControls())}}),c=D({label:"Remove",className:"btn-text btn-danger",onClick:()=>{var h;this._currentFilterId&&((h=this._onRemove)==null||h.call(this,this._currentFilterId),this.close())}}),d=R({icon:Ce,title:"Close",className:"btn-icon-sm",ariaLabel:"Close drawer",onClick:()=>this.close()});o.appendChild(l),o.appendChild(c),o.appendChild(d),n.appendChild(this._titleEl),n.appendChild(o),this._drawer.appendChild(n),this._body=f("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=f("div",{className:"adjustments-grid"}),r=this.state.getFilterValues(this._currentFilterId);(e.controls||[]).forEach(s=>{if(s.hidden)return;const n=this._createControl(this._currentFilterId,s,r[s.id]??s.default);n&&(this._controls.set(s.id,n),t.appendChild(n))});const i=this.filterManager.getInstance(this._currentFilterId);if(i&&typeof i.getDynamicControls=="function"){let s=[];try{s=i.getDynamicControls()||[]}catch{}s.forEach(n=>{const o=n.property||n.id,l=r[o]??n.default,c=this._createControl(this._currentFilterId,n,l);c&&(this._controls.set(n.id,c),t.appendChild(c))})}this._body.appendChild(t)}_createControl(e,t,r){if(t.hidden)return null;const i=t.label||t.id,s=this._normalizeControlType(t.type),n=t.property||t.id;switch(s){case"slider":return Le({id:`drawer-${e}-${t.id}`,label:i,min:t.min??0,max:t.max??1,step:t.step??.01,value:typeof r=="number"?r:t.default??0,onChange:o=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,n,o)}});case"toggle":return Re({id:`drawer-${e}-${t.id}`,label:i,checked:!!r,onChange:o=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,n,o)}});case"color":return Be({id:`drawer-${e}-${t.id}`,label:i,value:typeof r=="string"&&r.startsWith("#")?r:t.default||"#000000",onChange:o=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,n,o)}});case"select":{const o=this._normalizeOptions(t.options);return Ie({id:`drawer-${e}-${t.id}`,label:i,options:o,value:r??t.default,onChange:l=>{var c;return(c=this._onChange)==null?void 0:c.call(this,e,n,l)}})}case"text":return Ee({id:`drawer-${e}-${t.id}`,label:i,value:typeof r=="string"?r:t.default??"",placeholder:t.placeholder||"",onCommit:o=>{var l;return(l=this._onChange)==null?void 0:l.call(this,e,n,o)}});case"button":{const o=f("div",{className:"button-control"});return o.appendChild(D({label:i,className:"btn-secondary",onClick:()=>{var l;(l=this._onAction)==null||l.call(this,e,t.action||t.id),this._renderControls()}})),o}default:return null}}_normalizeControlType(e){return{slider:"slider",range:"slider",toggle:"toggle",checkbox:"toggle",color:"color",select:"select",dropdown:"select",button:"button",text:"text"}[e]||e}_normalizeOptions(e){return!e||!Array.isArray(e)?[]:e.map(t=>typeof t=="object"&&t.value!==void 0?{value:t.value,label:t.label||String(t.value)}:typeof t=="string"?{value:t,label:t}:typeof t=="number"?{value:t,label:String(t)}:{value:t,label:String(t)})}destroy(){var e;this._controls.clear(),(e=this._drawer)==null||e.remove(),this._drawer=null,this._isOpen=!1,this._currentFilterId=null,this._container=null}}class or{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=f("div",{className:"mobile-active-filters","data-testid":"mobile-active-filters"}),this._scrollContainer=f("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=f("div",{className:"active-filter-placeholder"},"No active filters");this._scrollContainer.appendChild(t);return}e.forEach(t=>{const r=this.filterManager.getFilterDef(t);if(!r)return;const i=this._createChip(t,r);this._chips.set(t,i),this._scrollContainer.appendChild(i)}),this._updateSelectedState()}_createChip(e,t){const r=f("div",{className:"active-filter-chip","data-filter-id":e,"data-testid":`active-chip-${e}`}),i=f("span",{className:"active-filter-chip-label",onClick:n=>{var o;n.stopPropagation(),(o=this._onSelect)==null||o.call(this,e)}},t.name),s=f("button",{className:"active-filter-chip-check","aria-label":`Remove ${t.name} filter`,onClick:n=>{var o;n.stopPropagation(),(o=this._onToggle)==null||o.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>',r.appendChild(i),r.appendChild(s),r}_updateSelectedState(){const e=this.state.get("selectedFilter");this._chips.forEach((t,r)=>{t.classList.toggle("selected",r===e)})}destroy(){var e;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._chips.clear(),(e=this.element)==null||e.remove(),this.element=null}}const lr=[{id:"free",name:"Free",icon:Jt},{id:"square",name:"Square",icon:Zt},{id:"circle",name:"Circle",icon:Kt}],cr=[{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"}],hr=[{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 te(a){if(!Number.isFinite(Number(a)))return 0;const e=Number(a)%360;return e<0?e+360:e}class ft{constructor(e,t,r=null){this.state=e,this.cropManager=t,this.editor=r,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=f("div",{className:"crop-controls","data-testid":"crop-controls"}),this.element.appendChild(this._renderRotationSection());const e=f("div",{className:"crop-section"});e.appendChild(f("label",{className:"section-label"},"Shape"));const t=f("div",{className:"chip-row"}),r=this.state.get("crop.shape");lr.forEach(c=>{const d=xe({label:c.name,icon:c.icon,active:r===c.id,onClick:()=>this._selectShape(c.id)});d.dataset.shape=c.id,d.dataset.testid=`crop-shape-${c.id}`,this._shapeChips.set(c.id,d),t.appendChild(d)}),e.appendChild(t),this.element.appendChild(e),this.state.get("lockCropShape")&&(e.style.display="none"),this._shapeSection=e,this._aspectSection=f("div",{className:"crop-section"}),this._aspectSection.appendChild(f("label",{className:"section-label"},"Aspect Ratio"));const i=f("div",{className:"chip-row aspect-row"}),s=this.state.get("crop.aspect");cr.forEach(c=>{const d=xe({label:c.name,active:s===c.id,onClick:()=>this._selectAspect(c.id)});d.dataset.ratio=c.id,d.dataset.testid=`crop-ratio-${c.id}`,this._aspectChips.set(c.id,d),i.appendChild(d)}),this._aspectSection.appendChild(i),this.element.appendChild(this._aspectSection),this._updateAspectVisibility();const n=f("div",{className:"crop-actions"}),o=D({label:"Cancel",className:"btn-secondary crop-cancel-btn",icon:Ce,onClick:()=>this.cropManager.cancel()});o.dataset.testid="cancel-crop";const l=D({label:"Apply Crop",className:"btn-primary crop-apply-btn",icon:we,onClick:()=>this._applyCropAndReturnToFilters()});return l.dataset.testid="apply-crop",n.appendChild(o),n.appendChild(l),this.element.appendChild(n),this._subscribeToState(),this.element}_renderRotationSection(){const e=f("div",{className:"crop-section rotation-section"});e.appendChild(f("label",{className:"section-label"},"Rotate"));const t=f("div",{className:"rotation-action-row"}),r=D({label:"Left 90°",className:"btn-secondary rotation-action-btn",icon:jt,onClick:()=>this._rotateBy(-90)});r.dataset.testid="rotate-left-90";const i=D({label:"Right 90°",className:"btn-secondary rotation-action-btn",icon:Yt,onClick:()=>this._rotateBy(90)});i.dataset.testid="rotate-right-90";const s=D({label:"Rotate 180°",className:"btn-secondary rotation-action-btn",onClick:()=>this._rotateBy(180)});s.dataset.testid="rotate-180";const n=D({label:"Rotate 270°",className:"btn-secondary rotation-action-btn",onClick:()=>this._rotateBy(270)});n.dataset.testid="rotate-270",t.appendChild(r),t.appendChild(i),t.appendChild(s),t.appendChild(n),e.appendChild(t);const o=f("div",{className:"chip-row rotation-preset-row"}),l=te(this.state.get("transform.rotation")??0);hr.forEach(p=>{const m=xe({label:p.label,active:Math.round(l)===p.angle,onClick:()=>this._setRotation(p.angle)});m.dataset.angle=p.id,m.dataset.testid=`rotation-preset-${p.id}`,this._rotationPresetChips.set(p.id,m),o.appendChild(m)}),e.appendChild(o);const c=f("div",{className:"rotation-arbitrary"}),d=f("div",{className:"rotation-angle-header"},f("label",{className:"rotation-angle-label",for:"image-editor-rotation-angle"},"Angle"),f("span",{className:"rotation-angle-value"},this._formatAngle(l)));this._rotationValue=d.querySelector(".rotation-angle-value"),this._rotationRange=f("input",{id:"image-editor-rotation-angle",type:"range",className:"slider-input rotation-range",min:"0",max:"360",step:"1",value:String(Math.round(l)),"aria-label":"Rotation angle",onInput:p=>this._previewAngleValue(p.target.value),onChange:p=>this._setRotation(Number(p.target.value))}),this._rotationNumber=f("input",{type:"number",className:"text-input rotation-number-input",min:"-360",max:"360",step:"1",value:this._formatPlainAngle(l),"aria-label":"Rotation angle in degrees",onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),this._setRotation(Number(p.target.value)),p.target.blur())},onBlur:p=>this._setRotation(Number(p.target.value))});const h=f("div",{className:"rotation-angle-row"},this._rotationRange,this._rotationNumber);c.appendChild(d),c.appendChild(h);const u=D({label:"Reset rotation",className:"btn-text rotation-reset-btn",onClick:()=>this._setRotation(0)});return u.dataset.testid="reset-rotation",c.appendChild(u),e.appendChild(c),e}_subscribeToState(){const e=this.state.on("change:crop.shape",({value:i})=>{this._shapeChips.forEach((s,n)=>{s.setActive(n===i)}),this._updateAspectVisibility()});this._unsubscribers.push(e);const t=this.state.on("change:crop.aspect",({value:i})=>{this._aspectChips.forEach((s,n)=>{s.setActive(n===i)})});this._unsubscribers.push(t);const r=this.state.on("change:transform.rotation",({value:i})=>{this._syncRotationControls(i)});this._unsubscribers.push(r)}_rotateBy(e){var r,i;((i=(r=this.editor)==null?void 0:r.rotateBy)==null?void 0:i.call(r,e))!==!1&&this._syncRotationControls(this.state.get("transform.rotation")??0)}_setRotation(e){var i,s;const t=te(e);if(((s=(i=this.editor)==null?void 0:i.setRotationAngle)==null?void 0:s.call(i,t))===!1){this._syncRotationControls(this.state.get("transform.rotation")??0);return}this._syncRotationControls(t)}_previewAngleValue(e){const t=te(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=te(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(te(e))%360;this._rotationPresetChips.forEach((r,i)=>{r.setActive(Number(i)===t)})}_formatAngle(e){return`${this._formatPlainAngle(e)}°`}_formatPlainAngle(e){const t=te(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 dr{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:r,onUpdateValue:i,onSelect:s}){this._onRemove=e,this._onReset=t,this._onClearAll=r,this._onUpdateValue=i,this._onSelect=s,this.element=f("div",{className:"active-filters-panel","data-testid":"active-filters-panel"});const n=f("div",{className:"panel-header"});n.appendChild(f("h3",{className:"panel-title"},"Active Filters"));const o=D({label:"Clear All",className:"btn-text btn-danger",onClick:()=>this._handleClearAll()});return o.dataset.testid="clear-all-filters",n.appendChild(o),this.element.appendChild(n),this._listContainer=f("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 r=this.state.on("change:selectedFilter",()=>{this._updateSelectedState()});this._unsubscribers.push(r)}_updateSelectedState(){const e=this.state.get("selectedFilter");this._filterItems.forEach((t,r)=>{t.classList.toggle("selected",r===e)})}_renderFilterList(){this._listContainer.innerHTML="",this._filterItems.clear();const e=this.state.get("activeFilters");if(e.size===0){this._listContainer.appendChild(f("div",{className:"no-filters-message"},"No filters active"));return}e.forEach(t=>{const r=this.filterManager.getFilterDef(t);if(!r)return;const i=this._createFilterItem(t,r);this._filterItems.set(t,i),this._listContainer.appendChild(i)})}_createFilterItem(e,t){const i=this.state.get("selectedFilter")===e,s=f("div",{className:`active-filter-item ${i?"selected":""}`,"data-active-filter":e,"data-testid":`active-filter-${e}`,onClick:p=>{p.target.closest(".filter-item-actions")||this._handleSelect(e)}}),n=f("div",{className:"filter-item-header"}),o=f("span",{className:"filter-item-name"},t.name),l=f("div",{className:"filter-item-actions"}),c=R({icon:ot,title:"Reset filter",className:"btn-icon-sm",onClick:()=>this._handleReset(e)}),d=R({icon:lt,title:"Remove filter",className:"btn-icon-sm btn-danger",onClick:()=>this._handleRemove(e)});l.appendChild(c),l.appendChild(d),n.appendChild(o),n.appendChild(l),s.appendChild(n);const h=this.state.getFilterValues(e),u=f("div",{className:"filter-item-summary"});return u.textContent=this._getValuesSummary(t,h),s.appendChild(u),s._summaryEl=u,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 r=[];return e.controls.forEach(i=>{const s=this._normalizeControlType(i.type);if(s==="button")return;const n=i.label||i.id,o=t[i.id]??i.default;o!==i.default&&(s==="slider"?r.push(`${n}: ${this._formatValue(o)}`):s==="toggle"?o&&r.push(n):s==="color"?r.push(`${n}: ${o}`):s==="select"&&r.push(`${n}: ${o}`))}),r.length>0?r.join(", "):"Default values"}_formatValue(e){return typeof e!="number"||Number.isInteger(e)?String(e):e.toFixed(2)}_updateValuesDisplay(){this._filterItems.forEach((e,t)=>{const r=this.filterManager.getFilterDef(t);if(!r||!e._summaryEl)return;const i=this.state.getFilterValues(t);e._summaryEl.textContent=this._getValuesSummary(r,i)})}_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 ie={name:"free",initialMode:"filters",cropShape:"free",aspectRatio:"free",autoZoomOnCropOverflow:!1,lockCropShape:!1,lockAspectRatio:!1,showFilters:!0,showCropControls:!0,maxExportWidth:void 0,maxExportHeight:void 0},Pe={free:{...ie},avatar:{...ie,name:"avatar",initialMode:"crop",cropShape:"circle",aspectRatio:"1:1",autoZoomOnCropOverflow:!0,lockCropShape:!0,lockAspectRatio:!0},banner:{...ie,name:"banner",initialMode:"crop",cropShape:"square",aspectRatio:"16:9",autoZoomOnCropOverflow:!1,lockCropShape:!1,lockAspectRatio:!0},cover:{...ie,name:"cover",initialMode:"crop",cropShape:"free",aspectRatio:"24:5",autoZoomOnCropOverflow:!0,lockCropShape:!0,lockAspectRatio:!0},product:{...ie,name:"product",initialMode:"filters",cropShape:"square",aspectRatio:"1:1",autoZoomOnCropOverflow:!1,lockCropShape:!1,lockAspectRatio:!1}};function mt(a){if(!a)return{...Pe.free};if(typeof a=="object"&&a!==null)return{...ie,...a};const e=Pe[a];return e?{...e}:{...Pe.free}}function ae(a){if(!Number.isFinite(Number(a)))return 0;const e=Number(a)%360;return e<0?e+360:e}function ur(a,e){const t=ae(a);return(ae(e)-t+540)%360-180}class pr extends ne{constructor(e,t={}){var s,n,o,l;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 r=t.preset?mt(t.preset):null,i=r?{initialMode:r.initialMode==="crop"?"crop":"adjust",cropShape:r.cropShape,initialAspectRatio:r.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},...i,...t},this._preset=r,this._state=it(),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 st,this._filterManager=new dt(this._state,this._renderer),this._cropManager=new ve(this._state,this._renderer),this._removeBgManager=null,this._backgroundRemovalAvailable=!1,((s=this._options.backgroundRemoval)==null?void 0:s.enabled)!==!1&&(this._removeBgManager=new ut({endpoint:(n=this._options.backgroundRemoval)==null?void 0:n.endpoint,optionsEndpoint:(o=this._options.backgroundRemoval)==null?void 0:o.optionsEndpoint,fallbackEndpoint:(l=this._options.backgroundRemoval)==null?void 0:l.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(c=>{this._destroyed||this.emit("error",c instanceof Error?c:new Error(String(c)))})}async _init(){this._state.detectTheme(),this._buildDOM(),!(!await this._renderer.mount(this._canvasContainer,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=f("div",{className:`vanilla-image-editor ${this._state.get("isDarkMode")?"dark":"light"}`});const e=f("div",{className:"editor-toolbar-container"});this._editorEl.appendChild(e),this._toolbarContainer=e;const t=f("div",{className:"editor-content"}),r=f("div",{className:"canvas-section"});this._canvasContainer=f("div",{className:"canvas-container"}),this._cropOverlay=f("canvas",{className:"crop-overlay","aria-hidden":"true"}),r.appendChild(this._canvasContainer),r.appendChild(this._cropOverlay),t.appendChild(r),this._controlsSection=f("div",{className:"controls-section"}),t.appendChild(this._controlsSection),this._editorEl.appendChild(t),this._fileInput=f("input",{type:"file",accept:"image/*",className:"hidden-file-input","aria-label":"Choose image file to edit",onChange:i=>this._handleFileSelect(i)}),this._editorEl.appendChild(this._fileInput),this._container.appendChild(this._editorEl)}_initUI(){this._toolbar=new pt(this._state,this),this._toolbarContainer.appendChild(this._toolbar.render()),this._filterControlsEl=f("div",{className:"filter-controls-container"}),this._categoryCarousel=new ir(this._state,this),this._filterControlsEl.appendChild(this._categoryCarousel.render(i=>{}));const e=f("div",{className:"filter-layout"}),t=f("div",{className:"filter-left-column"});this._filterCarousel=new sr(this._state,this._filterManager),t.appendChild(this._filterCarousel.render({onToggle:(i,s)=>this._handleFilterToggle(i,s),onSelect:i=>{this._handleFilterSelect(i),this._isMobile&&this._mobileFilterDrawer&&this._mobileFilterDrawer.open(i)}})),this._filterAdjustments=new ar(this._state,this._filterManager),t.appendChild(this._filterAdjustments.render({onChange:(i,s,n)=>this._handleFilterChange(i,s,n),onReset:i=>this._handleFilterReset(i),onAction:(i,s)=>this._handleFilterAction(i,s)})),e.appendChild(t);const r=f("div",{className:"filter-right-column"});this._activeFiltersPanel=new dr(this._state,this._filterManager),r.appendChild(this._activeFiltersPanel.render({onRemove:i=>this._handleFilterToggle(i,!1),onReset:i=>this._handleFilterReset(i),onClearAll:()=>this.resetAll(),onSelect:i=>this._handleFilterSelect(i)})),e.appendChild(r),this._filterControlsEl.appendChild(e),this._mobileActiveFilters=new or(this._state,this._filterManager),this._filterControlsEl.appendChild(this._mobileActiveFilters.render({onToggle:(i,s)=>this._handleFilterToggle(i,s),onSelect:i=>{this._handleFilterSelect(i),this._isMobile&&this._mobileFilterDrawer&&this._mobileFilterDrawer.open(i)}})),this._cropControls=new ft(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 nr(this._state,this._filterManager),this._mobileFilterDrawer.build(this._controlsSection,{onChange:(i,s,n)=>this._handleFilterChange(i,s,n),onReset:i=>this._handleFilterReset(i),onRemove:i=>{this._handleFilterToggle(i,!1),this._state.set("selectedFilter",null)},onAction:(i,s)=>this._handleFilterAction(i,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 r;const t=(r=e.target.files)==null?void 0:r[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,r){this._filterManager.updateValue(e,t,r)||this._filterManager.applyFilters(),this._renderer.render()}_handleFilterReset(e){this._filterManager.resetValues(e),this._filterManager.applyFilters()}_handleFilterAction(e,t){this._filterManager.performFilterAction(e,t)}_revokeObjectUrl(e){!e||!this._objectUrls.has(e)||(URL.revokeObjectURL(e),this._objectUrls.delete(e),this._activeObjectUrl===e&&(this._activeObjectUrl=null))}_replaceActiveObjectUrl(e){const t=this._activeObjectUrl;this._activeObjectUrl=e,this._objectUrls.add(e),t&&t!==e&&this._revokeObjectUrl(t)}_clearActiveObjectUrl(){this._activeObjectUrl&&this._revokeObjectUrl(this._activeObjectUrl)}setFilterRegistry(e){this._filterManager.setRegistry(e)}async loadImage(e,t={}){var o,l;if(this._destroyed)return;(l=(o=this._removeBgManager)==null?void 0:o.cancelActiveRequests)==null||l.call(o,"image-load");const r=++this._loadVersion;let i=e,s=null;this._resetEditorState(),this._state.set("hasImage",!1),this._state.set("imageUrl",null),e instanceof Blob&&(i=URL.createObjectURL(e),s=i,this._objectUrls.add(i));const n=await this._renderer.loadTexture(i,{isCurrent:()=>!this._destroyed&&this._loadVersion===r});if(this._destroyed||this._loadVersion!==r){this._revokeObjectUrl(s);return}if(!n){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",i),t.state&&this._hydrateState(t.state),this._options.initialMode==="crop"&&this.setMode("crop"),this.emit("imageLoaded",{url:i})}_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 r;if(!e||e.version!==1)return;const t=ae(((r=e.transform)==null?void 0:r.rotation)??0);if(t!==0&&this._renderer.rotateBy(t)&&this._state.set("transform.rotation",t),e.crop){const i=e.crop.shape||"free",s=e.crop.aspectRatio||"free";e.crop.rect&&(this._cropManager.applyFromPixelRect(e.crop.rect,i),this._state.set("crop.appliedRect",{...e.crop.rect}),this._state.set("crop.appliedShape",i),this._state.set("crop.appliedAspect",s)),this._state.set("crop.shape",i),this._state.set("crop.aspect",s)}if(Array.isArray(e.filters)){let i=null;for(const s of e.filters)if(s.enabled&&(i===null&&(i=s.id),this._state.toggleFilter(s.id,!0),this._filterManager.initializeValues(s.id),s.values))for(const[n,o]of Object.entries(s.values))this._state.setFilterValue(s.id,n,o);if(i!==null){this._state.set("selectedFilter",i);const s=this._filterManager.getFilterDef(i);if(typeof(s==null?void 0:s.category)=="string"){const n=ht[s.category]??s.category;this._state.set("selectedCategory",n)}}this._filterManager.applyFilters()}}openFilePicker(){var e;(e=this._fileInput)==null||e.click()}exportImage(e="png",t=.92,r={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditor.exportImage")?null:this._renderer.exportImage(e,t,r.maxEdge??0,r.dontUpscale!==!1,r.maxPixels??0)}async exportBlob(e="png",t=.92,r={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditor.exportBlob")?null:this._renderer.exportBlob(e,t,r)}_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 r=document.createElement("a");e=URL.createObjectURL(t.blob),r.href=e,r.download=`edited-image-${Date.now()}.png`,document.body.appendChild(r),r.click(),document.body.removeChild(r),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 n of e){const o=this._state.getFilterValues(n);t.push({id:n,enabled:!0,values:{...o}})}const r=this._state.get("crop.appliedRect"),i=this._state.get("crop.rect"),s=r||i;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:ae(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=ae(this._state.get("transform.rotation")??0),r=ae(e),i=ur(t,r),s=this._state.get("mode")==="crop";if(Math.abs(i)>.001){if(s&&this._cropManager.disable(),!this._renderer.rotateBy(i))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",r),this.emit("transformChanged",{rotation:r}),!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,r;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 i=this.exportImage("png");if(!i)throw new Error("Failed to export image for background removal");const s=await this._removeBgManager.preparePreviewRequest(i,e),n=this._buildPreviewBackgroundRemovalContext(s),o=await this._removeBgManager.removeBackground(s.blob,s);return await this._isCurrentPreviewBackgroundRemovalContext(n,o)?(await this.loadImage(o.dataUrl),this.emit("background-removed",{model:o.model,processMs:o.processMs}),{model:o.model,processMs:o.processMs}):(this.emit("background-removal-stale",{operationId:n.operationId,sourceHash:n.sourceHash}),{stale:!0})}catch(i){throw this.emit("error",{error:i,context:"background-removal"}),i}finally{(r=(t=this._state)==null?void 0:t.set)==null||r.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 r=this.exportImage("png");return r?await this._removeBgManager.computeImageDataHash(r)===e.sourceHash:!1}_showLoadingOverlay(e){var r;if(!this._loadingOverlay)this._loadingOverlay=f("div",{className:"editor-loading-overlay"},[f("div",{className:"editor-loading-spinner"}),f("div",{className:"editor-loading-text"},e)]);else{const i=this._loadingOverlay.querySelector(".editor-loading-text");i&&(i.textContent=e)}const t=(r=this._canvasContainer)==null?void 0:r.parentElement;t&&!this._loadingOverlay.parentElement&&t.appendChild(this._loadingOverlay)}_hideLoadingOverlay(){var e;(e=this._loadingOverlay)==null||e.remove()}destroy(){var e,t,r,i,s,n,o,l,c,d,h,u;this._destroyed=!0,(t=(e=this._removeBgManager)==null?void 0:e.cancelActiveRequests)==null||t.call(e,"editor-destroy");for(const p of this._objectUrls)try{URL.revokeObjectURL(p)}catch{}this._objectUrls.clear(),this._activeObjectUrl=null,(r=this._resizeObserver)==null||r.disconnect(),this._renderer.destroy(),this._cropManager.disable(),this._handleWindowResize&&window.removeEventListener("resize",this._handleWindowResize),(i=this._toolbar)==null||i.destroy(),(s=this._categoryCarousel)==null||s.destroy(),(n=this._filterCarousel)==null||n.destroy(),(o=this._filterAdjustments)==null||o.destroy(),(l=this._mobileFilterDrawer)==null||l.destroy(),(c=this._mobileActiveFilters)==null||c.destroy(),(d=this._cropControls)==null||d.destroy(),(h=this._activeFiltersPanel)==null||h.destroy(),(u=this._editorEl)==null||u.remove(),this._container=null,this._state=null,this.emit("destroyed"),this.removeAllListeners()}}const X=new Map,Q=new Map;function fr(a,e){return!Array.isArray(a.mediaTargets)||a.mediaTargets.length===0?!0:a.mediaTargets.includes(e)}function y(a){var e;return X.has(a.id),X.set(a.id,a),Q.has(a.category)||Q.set(a.category,[]),(e=Q.get(a.category))==null||e.push(a.id),a}function gt(a){return X.get(a)}function ue(){return Array.from(X.values())}function bt(){ue().map(t=>t.id),Object.entries(v).filter(t=>/Filter$/.test(t[0])&&typeof t[1]=="function").forEach(([t,r])=>{const i=t.replace(/Filter$/,"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();X.has(i)||y({id:i,name:t.replace(/Filter$/,""),category:"unlisted",mediaTargets:["image"],defaultParams:{},controls:[],createFilter:(s={})=>{try{return new r(s)}catch{return null}}})})}function _t(a){return(Q.get(a)||[]).map(t=>X.get(t)).filter(Boolean)}function yt(){return Array.from(Q.keys())}function mr(a){return X.has(a)}function gr(a){const e=X.get(a);if(!e)return!1;X.delete(a);const t=Q.get(e.category);if(t){const r=t.indexOf(a);r!==-1&&t.splice(r,1),t.length===0&&Q.delete(e.category)}return!0}function br(a,e){const t=X.get(a);return t?fr(t,e):!1}function xt(){return Array.from(X.values()).map(a=>({id:a.id,name:a.name,category:a.category,controls:a.controls}))}if(typeof window<"u"){window.__DEBUG_FILTERS_LIST=Array.from(X.keys()),window.getAllFilters=ue,window.getFilter=gt,window.getFiltersByCategory=_t,window.getRegisteredFilters=xt;const a=y;window.registerFilter=e=>{const t=a(e);return window.__DEBUG_FILTERS_LIST=Array.from(X.keys()),t}}typeof window<"u"&&(window.initializeFilterRegistry=window.initializeFilterRegistry||function(){return[]});const{AdjustmentFilter:_r}=v,{ColorMatrixFilter:yr}=O,W={gamma:1,saturation:1,contrast:1,brightness:1,red:1,green:1,blue:1,alpha:1},xr=new Set(["gamma","saturation","contrast","brightness","red","green","blue","alpha"]);function q(a,e){if(typeof a=="number"&&Number.isFinite(a))return a;if(typeof a=="string"){const t=Number(a);if(Number.isFinite(t))return t}return e}function Xe(a){return xr.has(a)}function wr(a){return{gamma:q(a.gamma,W.gamma),saturation:q(a.saturation,W.saturation),contrast:q(a.contrast,W.contrast),brightness:q(a.brightness,W.brightness),red:q(a.red,W.red),green:q(a.green,W.green),blue:q(a.blue,W.blue),alpha:q(a.alpha,W.alpha)}}function Ue(a,e){a.reset(),a.brightness(e.brightness,!0),a.contrast(e.contrast,!0),a.saturate(e.saturation,!0)}y({id:"adjustment",name:"Adjustment",category:"adjust",description:"Adjust basic image properties like brightness, contrast, and saturation",createFilter:a=>{try{const e=wr(a??{}),t={...e};try{const r=new _r(t),i=r;return i._customParams={...e},i.updateUIParam=function(n,o){try{if(!Xe(n))return;const l=this._customParams??{...W},c=q(o,l[n]);l[n]=c,this._customParams=l;const d=this;n in d&&(d[n]=c)}catch{}},r}catch{const i=new yr,s=i;return s._customParams={...e},Ue(i,e),s.updateUIParam=function(o,l){try{if(!Xe(o))return;const c=this._customParams??{...W},d=q(l,c[o]);c[o]=d,this._customParams=c,Ue(this,c)}catch{}},i}}catch{return null}},defaultParams:{gamma:1,saturation:1,contrast:1,brightness:1,red:1,green:1,blue:1,alpha:1},controls:[{id:"brightness",type:"slider",label:"Brightness",property:"brightness",min:0,max:5,step:.01,default:1},{id:"contrast",type:"slider",label:"Contrast",property:"contrast",min:0,max:5,step:.01,default:1},{id:"saturation",type:"slider",label:"Saturation",property:"saturation",min:0,max:5,step:.01,default:1},{id:"gamma",type:"slider",label:"Gamma",property:"gamma",min:0,max:5,step:.01,default:1},{id:"red",type:"slider",label:"Red",property:"red",min:0,max:5,step:.01,default:1},{id:"green",type:"slider",label:"Green",property:"green",min:0,max:5,step:.01,default:1},{id:"blue",type:"slider",label:"Blue",property:"blue",min:0,max:5,step:.01,default:1},{id:"alpha",type:"slider",label:"Alpha",property:"alpha",min:0,max:1,step:.01,default:1}]});const{ColorMatrixFilter:vr}=O,K={brightness:1,contrast:1,saturation:1,hue:0,sepia:0,negative:!1},Cr=new Set(["brightness","contrast","saturation","hue","sepia","negative"]);function kr(a){return Cr.has(a)}function se(a,e){if(typeof a=="number"&&Number.isFinite(a))return a;if(typeof a=="string"){const t=Number(a);if(Number.isFinite(t))return t}return e}function wt(a,e){if(typeof a=="boolean")return a;if(typeof a=="string"){if(a==="true")return!0;if(a==="false")return!1}return e}function Sr(a){return{brightness:se(a.brightness,K.brightness),contrast:se(a.contrast,K.contrast),saturation:se(a.saturation,K.saturation),hue:se(a.hue,K.hue),sepia:se(a.sepia,K.sepia),negative:wt(a.negative,K.negative)}}function Ve(a,e){a.reset(),e.brightness!==1&&a.brightness(e.brightness,!0),e.contrast!==1&&a.contrast(e.contrast,!0),e.saturation!==1&&a.saturate(e.saturation,!0),e.hue!==0&&a.hue(e.hue,!0),e.sepia>0&&a.sepia(!0),e.negative&&a.negative(!0)}y({id:"adjustment-advanced",name:"Advanced Adjustment",category:"adjust",description:"Comprehensive image adjustments including brightness, contrast, saturation, hue, and more",createFilter:a=>{try{const e=Sr(a??{}),t=new vr,r=t;return r._customParams={...e},Ve(t,e),r.updateUIParam=function(s,n){try{if(!kr(s))return;const o=this._customParams??{...K};if(s==="negative")o.negative=wt(n,o.negative);else{const l=s;o[l]=se(n,o[l])}this._customParams=o,Ve(this,o)}catch{}},t}catch{return null}},defaultParams:{brightness:1,contrast:1,saturation:1,hue:0,sepia:0,negative:!1},controls:[{id:"brightness",type:"slider",label:"Brightness",property:"brightness",min:0,max:2,step:.01,default:1},{id:"contrast",type:"slider",label:"Contrast",property:"contrast",min:0,max:2,step:.01,default:1},{id:"saturation",type:"slider",label:"Saturation",property:"saturation",min:0,max:2,step:.01,default:1},{id:"hue",type:"slider",label:"Hue Rotation",property:"hue",min:0,max:360,step:1,default:0},{id:"sepia",type:"slider",label:"Sepia",property:"sepia",min:0,max:1,step:.01,default:0},{id:"negative",type:"toggle",label:"Negative",property:"negative",default:!1}]});const He=a=>Math.max(0,Math.min(1,a));y({id:"alpha",name:"Alpha",category:"adjust",description:"Adjust the opacity of the image",createFilter:a=>{const e=He(a.alpha!==void 0?Number(a.alpha):1),t=new O.AlphaFilter(e);return t.updateUIParam=function(r,i){r==="alpha"&&(this.alpha=He(Number(i)))},t},defaultParams:{alpha:1},controls:[{id:"alpha",type:"slider",label:"Opacity",property:"alpha",min:0,max:1,step:.01,default:1}]});y({id:"blur",name:"Blur",category:"blur",description:"Apply a smooth blur effect to the entire image",createFilter:a=>{try{const e=new O.BlurFilter({strength:a.blur||8,quality:a.quality||4});return e._customParams={...a},e.updateUIParam=function(t,r){const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"blur":this.strength=r;break;case"quality":this.quality=r;break;default:t in this&&(this[t]=r);break}return!0},e}catch{return null}},defaultParams:{blur:8,quality:4},controls:[{id:"blur",type:"slider",label:"Blur",property:"blur",min:0,max:100,step:.1,default:8},{id:"quality",type:"slider",label:"Quality",property:"quality",min:1,max:10,step:1,default:4}]});function We(a,e){typeof a.reset=="function"&&a.reset(),e.brightness!==1&&a.brightness(e.brightness,!1),e.contrast!==1&&a.contrast(e.contrast,!1),e.saturation!==1&&a.saturate(e.saturation,!1),e.hue!==0&&a.hue(e.hue,!1),e.sepia&&a.sepia(!1),e.negative&&a.negative(!1)}function qe(a){return{brightness:Number(a.brightness??1),contrast:Number(a.contrast??1),saturation:Number(a.saturation??1),hue:Number(a.hue??0),sepia:!!a.sepia,negative:!!a.negative}}y({id:"color-matrix",name:"Color Matrix",category:"advanced",description:"Advanced color adjustments including sepia, hue rotation, and negative",createFilter:a=>{const e=O.ColorMatrixFilter;if(!e)return null;const t=new e,r=qe(a);return t._customParams={...r},We(t,r),t.updateUIParam=function(i,s){const n=this._customParams??qe({});switch(i){case"brightness":case"contrast":case"saturation":case"hue":n[i]=Number(s);break;case"sepia":case"negative":n[i]=!!s;break;default:return}this._customParams=n,We(this,n)},t},defaultParams:{brightness:1,contrast:1,saturation:1,hue:0,sepia:!1,negative:!1},controls:[{id:"brightness",type:"slider",label:"Brightness",property:"brightness",min:0,max:5,step:.1,default:1},{id:"contrast",type:"slider",label:"Contrast",property:"contrast",min:0,max:5,step:.1,default:1},{id:"saturation",type:"slider",label:"Saturation",property:"saturation",min:0,max:5,step:.1,default:1},{id:"hue",type:"slider",label:"Hue Rotation",property:"hue",min:-180,max:180,step:1,default:0},{id:"sepia",type:"toggle",label:"Sepia",property:"sepia",default:!1},{id:"negative",type:"toggle",label:"Negative",property:"negative",default:!1}]});const{ColorOverlayFilter:Fr}=v;y({id:"colorOverlay",name:"Color Overlay",category:"color",description:"Apply a colored tint or overlay to the entire image",createFilter:a=>{try{let e=16711680;a.color&&(typeof a.color=="string"?e=parseInt(a.color.replace("#","0x"),16):typeof a.color=="number"&&(e=a.color));const t=new Fr({color:e,alpha:a.alpha||.5});return t._customParams={...a},t.updateUIParam=function(r,i){const s=this._customParams||{};switch(this._customParams=s,s[r]=i,r){case"color":let n;typeof i=="string"?n=parseInt(i.replace("#","0x"),16):n=Number(i),this.color=n,this.uniforms&&(this.uniforms.uColor=n);break;case"alpha":this.alpha=Number(i),this.uniforms&&(this.uniforms.uAlpha=Number(i));break;default:r in this&&(this[r]=i);break}return!0},t}catch{return null}},defaultParams:{color:"#ff0000",alpha:.5},controls:[{id:"color",type:"color",label:"Color",property:"color",default:"#ff0000"},{id:"alpha",type:"slider",label:"Opacity",property:"alpha",min:0,max:1,step:.01,default:.5}]});y({id:"drop-shadow",name:"Drop Shadow",category:"effects",description:"Add a soft drop shadow to the image",createFilter:a=>{try{const e=a.color?a.color.replace("#","0x"):"0x000000",t=a.distance!==void 0?a.distance:5,r=a.angle!==void 0?a.angle:90,i=a.blur!==void 0?a.blur:2,s=a.quality!==void 0?a.quality:3,n={x:t*Math.cos(r*Math.PI/180),y:t*Math.sin(r*Math.PI/180)},o=new v.DropShadowFilter({offset:n,color:parseInt(e,16),alpha:a.alpha!==void 0?a.alpha:.5,blur:i,quality:s,shadowOnly:a.shadowOnly!==void 0?a.shadowOnly:!1,pixelSize:{x:a.pixelSizeX!==void 0?a.pixelSizeX:1,y:a.pixelSizeY!==void 0?a.pixelSizeY:1}}),l=(h,u,p,m)=>{const g=h*u*2,_=Math.sqrt(p*p+m*m);return Math.ceil(g+_+2)};o._exportPadding=l(i,s,n.x,n.y),o.padding=Math.max(o.padding??0,o._exportPadding),o._customParams={...a,_offset:n,_distance:t,_angle:r};const c=(h,u)=>{const p=Number(h._distance??h.distance??5)*u,m=Number(h._angle??h.angle??90),g=Number(h.blur??2)*u,_=Number(h.quality??3),C={x:p*Math.cos(m*Math.PI/180),y:p*Math.sin(m*Math.PI/180)},k=h.color?String(h.color).replace("#","0x"):"0x000000",A=new v.DropShadowFilter({offset:C,color:parseInt(k,16),alpha:h.alpha!==void 0?Number(h.alpha):.5,blur:g,quality:_,shadowOnly:h.shadowOnly!==void 0?!!h.shadowOnly:!1,pixelSize:{x:h.pixelSizeX!==void 0?Number(h.pixelSizeX):1,y:h.pixelSizeY!==void 0?Number(h.pixelSizeY):1}}),P=l(g,_,C.x,C.y);return A._exportPadding=P,A.padding=Math.max(A.padding??0,P),A};o.createExportFilter=function(h={}){const u=Number.isFinite(h.previewToNativeScale)?Math.max(1,Number(h.previewToNativeScale)):1,p=this._customParams||a;return c(p,u)},o.getExportPadding=function(){return Number(this._exportPadding||this.padding||0)};const d=h=>{var _;const u=((_=h._customParams)==null?void 0:_._offset)??{x:0,y:0},p=Number(h.blur??0),m=Number(h.quality??1),g=l(p,m,u.x,u.y);h._exportPadding=g,h.padding=Math.max(h.padding??0,g)};return o.updateUIParam=function(h,u){try{const p=this._customParams||{};switch(this._customParams=p,p[h]=u,h){case"color":typeof u=="string"&&(this.color=parseInt(u.replace("#","0x"),16));break;case"alpha":this.alpha=Number(u);break;case"blur":this.blur=Number(u),d(this);break;case"quality":this.quality=Number(u),d(this);break;case"shadowOnly":this.shadowOnly=!!u;break;case"pixelSizeX":this.pixelSizeX=Number(u),p.pixelSizeX=Number(u);break;case"pixelSizeY":this.pixelSizeY=Number(u),p.pixelSizeY=Number(u);break;case"distance":case"angle":{h==="distance"?(p._distance=Number(u),p.distance=Number(u)):(p._angle=Number(u),p.angle=Number(u));const m={x:p._distance*Math.cos(p._angle*Math.PI/180),y:p._distance*Math.sin(p._angle*Math.PI/180)};p._offset=m,this.offset=m,d(this);break}default:h in this&&(this[h]=u);break}return!0}catch{return this._customParams&&(this._customParams[h]=u),!1}},o}catch{return null}},defaultParams:{alpha:.5,blur:2,color:"#000000",distance:5,angle:90,quality:3,shadowOnly:!1,pixelSizeX:1,pixelSizeY:1},controls:[{id:"alpha",type:"slider",label:"Opacity",property:"alpha",min:0,max:1,step:.01,default:.5},{id:"blur",type:"slider",label:"Blur",property:"blur",min:0,max:20,step:.1,default:2},{id:"color",type:"color",label:"Color",property:"color",default:"#000000"},{id:"distance",type:"slider",label:"Distance",property:"distance",min:0,max:50,step:1,default:5},{id:"angle",type:"slider",label:"Angle",property:"angle",min:0,max:360,step:1,default:90},{id:"quality",type:"slider",label:"Quality",property:"quality",min:0,max:20,step:1,default:3},{id:"shadowOnly",type:"toggle",label:"Shadow Only",property:"shadowOnly",default:!1},{id:"pixelSizeX",type:"slider",label:"Pixel Size X",property:"pixelSizeX",min:.5,max:8,step:.5,default:1},{id:"pixelSizeY",type:"slider",label:"Pixel Size Y",property:"pixelSizeY",min:.5,max:8,step:.5,default:1}]});const{ColorMatrixFilter:Mr}=O;y({id:"grayscale",name:"Grayscale",category:"color",description:"Convert the image to black and white with adjustable intensity",createFilter:a=>{try{const e=new Mr;e._customParams={...a};const t=a.intensity!==void 0?a.intensity:1;return $e(e,t),e.updateUIParam=function(r,i){const s=this._customParams||{};switch(this._customParams=s,s[r]=i,r){case"intensity":$e(this,i);break;default:r in this&&(this[r]=i);break}return!0},e}catch{return null}},defaultParams:{intensity:.35},controls:[{id:"intensity",type:"slider",label:"Intensity",property:"intensity",min:0,max:1,step:.01,default:.35}]});function $e(a,e){a.reset(),a.greyscale(e)}const{HslAdjustmentFilter:Pr}=v;y({id:"hsl-adjustment",name:"HSL Adjustment",category:"color",description:"Control hue, saturation, and lightness independently",createFilter:a=>{try{const e=new Pr({hue:a.hue!==void 0?a.hue:0,saturation:a.saturation!==void 0?a.saturation:0,lightness:a.lightness!==void 0?a.lightness:0,colorize:a.colorize!==void 0?a.colorize:!1,alpha:a.alpha!==void 0?a.alpha:1});return e._customParams={...a},e.updateUIParam=function(t,r){try{const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"hue":this.hue=Number(r),this.uniforms&&(this.uniforms.uHue=Number(r));break;case"saturation":this.saturation=Number(r),this.uniforms&&(this.uniforms.uSaturation=Number(r));break;case"lightness":this.lightness=Number(r),this.uniforms&&(this.uniforms.uLightness=Number(r));break;case"colorize":this.colorize=!!r,this.uniforms&&(this.uniforms.uColorize=r?1:0);break;case"alpha":this.alpha=Number(r),this.uniforms&&(this.uniforms.uAlpha=Number(r));break;default:t in this&&(this[t]=r);break}return!0}catch{return this._customParams&&(this._customParams[t]=r),!1}},e}catch{return null}},defaultParams:{hue:0,saturation:0,lightness:0,colorize:!1,alpha:1},controls:[{id:"hue",type:"slider",label:"Hue",property:"hue",min:-180,max:180,step:1,default:0},{id:"saturation",type:"slider",label:"Saturation",property:"saturation",min:-1,max:1,step:.01,default:0},{id:"lightness",type:"slider",label:"Lightness",property:"lightness",min:-1,max:1,step:.01,default:0},{id:"colorize",type:"toggle",label:"Colorize",property:"colorize",default:!1},{id:"alpha",type:"slider",label:"Alpha",property:"alpha",min:0,max:1,step:.01,default:1}]});const{KawaseBlurFilter:Ar}=v;y({id:"kawase-blur",name:"Kawase Blur",category:"blur",description:"A more optimized blur algorithm that is faster than standard blur",createFilter:a=>{try{const e=new Ar({strength:a.strength||4,quality:a.quality||3,clamp:a.clamp||!1,pixelSize:a.pixelSize||1});return e._customParams={...a},e.updateUIParam=function(t,r){const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"strength":this.strength=r;break;case"quality":this.quality=r;break;case"clamp":this.clamp=r;break;case"pixelSize":typeof r=="number"?this.pixelSize=r:typeof r=="object"&&r!==null&&"x"in r&&"y"in r&&(this.pixelSize=r);break;case"pixelSizeX":this.pixelSizeX=r;break;case"pixelSizeY":this.pixelSizeY=r;break;default:t in this&&(this[t]=r);break}return!0},e}catch{return null}},defaultParams:{strength:4,quality:3,clamp:!1,pixelSize:1},controls:[{id:"strength",type:"slider",label:"Strength",property:"strength",min:0,max:20,step:.1,default:4},{id:"quality",type:"slider",label:"Quality",property:"quality",min:1,max:20,step:1,default:3},{id:"clamp",type:"toggle",label:"Clamp Edges",property:"clamp",default:!1},{id:"pixelSize",type:"slider",label:"Pixel Size",property:"pixelSize",min:.5,max:10,step:.5,default:1},{id:"pixelSizeX",type:"slider",label:"Pixel Size X",property:"pixelSizeX",min:0,max:10,step:.1,default:1},{id:"pixelSizeY",type:"slider",label:"Pixel Size Y",property:"pixelSizeY",min:0,max:10,step:.1,default:1}]});const{MotionBlurFilter:Nr}=v;y({id:"motion-blur",name:"Motion Blur",category:"blur",description:"Creates a directional blur effect simulating motion",createFilter:a=>{try{const e=new Nr({velocity:{x:a.velocityX!==void 0?a.velocityX:0,y:a.velocityY!==void 0?a.velocityY:0},kernelSize:a.kernelSize||5,offset:a.offset!==void 0?a.offset:0});return e._customParams={...a},e.updateUIParam=function(t,r){const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"velocityX":this.velocityX=r;break;case"velocityY":this.velocityY=r;break;case"kernelSize":this.kernelSize=r;break;case"offset":this.offset=r;break;default:t in this&&(this[t]=r);break}return!0},e}catch{return null}},defaultParams:{velocityX:0,velocityY:0,kernelSize:5,offset:0},controls:[{id:"velocityX",type:"slider",label:"Velocity X",property:"velocityX",min:-90,max:90,step:1,default:0},{id:"velocityY",type:"slider",label:"Velocity Y",property:"velocityY",min:-90,max:90,step:1,default:0},{id:"kernelSize",type:"select",label:"Kernel Size",property:"kernelSize",options:[{label:"3",value:3},{label:"5",value:5},{label:"7",value:7},{label:"9",value:9},{label:"11",value:11},{label:"13",value:13},{label:"15",value:15},{label:"17",value:17},{label:"19",value:19},{label:"21",value:21},{label:"23",value:23},{label:"25",value:25}],default:5},{id:"offset",type:"slider",label:"Offset",property:"offset",min:-150,max:150,step:1,default:0}]});const{RadialBlurFilter:Tr}=v;y({id:"radial-blur",name:"Radial Blur",category:"blur",description:"Creates a circular blur effect emanating from a center point",createFilter:a=>{try{const e=new Tr({angle:a.angle??20,center:{x:a.centerX??0,y:a.centerY??0},kernelSize:a.kernelSize??15,radius:a.radius??300});return e._customParams={centerX:a.centerX??0,centerY:a.centerY??0},e.updateUIParam=function(t,r){try{switch(t){case"angle":this.angle=Number(r);break;case"centerX":this._customParams.centerX=Number(r),this.center={x:Number(r),y:this._customParams.centerY};break;case"centerY":this._customParams.centerY=Number(r),this.center={x:this._customParams.centerX,y:Number(r)};break;case"kernelSize":this.kernelSize=Number(r);break;case"radius":this.radius=Number(r);break;default:}}catch{}},e}catch{return null}},defaultParams:{angle:20,centerX:0,centerY:0,kernelSize:15,radius:300},controls:[{id:"angle",type:"slider",label:"Angle",property:"angle",min:-180,max:180,step:1,default:20},{id:"centerX",type:"slider",label:"Center X",property:"centerX",min:-1,max:1,step:.01,default:0},{id:"centerY",type:"slider",label:"Center Y",property:"centerY",min:-1,max:1,step:.01,default:0},{id:"kernelSize",type:"select",label:"Kernel Size",property:"kernelSize",options:[{label:"3",value:3},{label:"5",value:5},{label:"7",value:7},{label:"9",value:9},{label:"11",value:11},{label:"13",value:13},{label:"15",value:15},{label:"17",value:17},{label:"19",value:19},{label:"21",value:21},{label:"23",value:23},{label:"25",value:25}],default:15},{id:"radius",type:"slider",label:"Radius",property:"radius",min:-1,max:1e3,step:10,default:300}]});const{TiltShiftFilter:zr}=v;y({id:"tilt-shift",name:"Tilt Shift",category:"blur",description:"Creates a depth-of-field effect simulating miniature photography",createFilter:a=>{try{const e=typeof a.blur=="number"?a.blur:100,t=typeof a.gradientBlur=="number"?a.gradientBlur:600,r=typeof a.startX=="number"?a.startX:0,i=typeof a.startY=="number"?a.startY:.5,s=typeof a.endX=="number"?a.endX:1,n=typeof a.endY=="number"?a.endY:.5,o=new zr({blur:Number(e),gradientBlur:Number(t),start:{x:Number(r),y:Number(i)},end:{x:Number(s),y:Number(n)}});return o._customParams={blur:e,gradientBlur:t,startX:r,startY:i,endX:s,endY:n},o.updateUIParam=function(l,c){try{const d=Number(c),h=this._customParams||{};switch(this._customParams=h,h[l]=d,l){case"blur":this.blur=d;break;case"gradientBlur":this.gradientBlur=d;break;case"startX":this.start&&typeof this.start=="object"&&(this.start.x=d);break;case"startY":this.start&&typeof this.start=="object"&&(this.start.y=d);break;case"endX":this.end&&typeof this.end=="object"&&(this.end.x=d);break;case"endY":this.end&&typeof this.end=="object"&&(this.end.y=d);break;default:l in this&&(this[l]=d);break}}catch{}},o}catch{return null}},defaultParams:{blur:100,gradientBlur:600,startX:0,startY:.5,endX:1,endY:.5},controls:[{id:"blur",type:"slider",label:"Blur Strength",property:"blur",min:0,max:200,step:1,default:100},{id:"gradientBlur",type:"slider",label:"Gradient Width",property:"gradientBlur",min:0,max:1e3,step:10,default:600},{id:"startX",type:"slider",label:"Start X",property:"startX",min:0,max:1,step:.01,default:0},{id:"startY",type:"slider",label:"Start Y",property:"startY",min:0,max:1,step:.01,default:.5},{id:"endX",type:"slider",label:"End X",property:"endX",min:0,max:1,step:.01,default:1},{id:"endY",type:"slider",label:"End Y",property:"endY",min:0,max:1,step:.01,default:.5}]});const{ZoomBlurFilter:Lr}=v;y({id:"zoom-blur",name:"Zoom Blur",category:"blur",description:"Creates a zoom blur effect from a center point",createFilter:a=>{try{const e=new Lr({strength:a.strength||.1,center:{x:a.centerX!==void 0?a.centerX:.5,y:a.centerY!==void 0?a.centerY:.5},innerRadius:a.innerRadius||80,radius:a.radius!==void 0?a.radius:-1,maxKernelSize:a.maxKernelSize||32});return e._customParams={...a},e.updateUIParam=function(t,r){const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"strength":this.strength=r;break;case"centerX":this.centerX=r;break;case"centerY":this.centerY=r;break;case"innerRadius":this.innerRadius=r;break;case"radius":this.radius=r;break;default:t in this&&(this[t]=r);break}return!0},e}catch{return null}},defaultParams:{strength:.1,centerX:.5,centerY:.5,innerRadius:80,radius:-1,maxKernelSize:32},controls:[{id:"strength",type:"slider",label:"Strength",property:"strength",min:0,max:.5,step:.01,default:.1},{id:"centerX",type:"slider",label:"Center X",property:"centerX",min:0,max:1,step:.01,default:.5},{id:"centerY",type:"slider",label:"Center Y",property:"centerY",min:0,max:1,step:.01,default:.5},{id:"innerRadius",type:"slider",label:"Inner Radius",property:"innerRadius",min:0,max:1e3,step:1,default:80},{id:"radius",type:"slider",label:"Outer Radius",property:"radius",min:-1,max:1e3,step:10,default:-1},{id:"maxKernelSize",type:"select",label:"Quality",property:"maxKernelSize",options:[{label:"Low",value:16},{label:"Medium",value:32},{label:"High",value:48},{label:"Very High",value:64}],default:32}]});const{ColorGradientFilter:Ge}=v;function vt(a){return parseInt(a.replace("#","0x"),16)}function Rr(a){return"#"+a.toString(16).padStart(6,"0")}function Ze(a){return{offset:Number(a.offset),color:typeof a.color=="string"?vt(a.color):Number(a.color),alpha:Number(a.alpha)}}function Ke(a){return{offset:a.offset,color:typeof a.color=="number"?Rr(a.color):a.color,alpha:a.alpha}}y({id:"color-gradient",name:"Color Gradient",category:"color",description:"Applies a linear, radial or conic color gradient over the image with multiple color stops",createFilter:a=>{let t=(a.colorStops||[{offset:0,color:"#ff0000",alpha:1},{offset:1,color:"#0000ff",alpha:1}]).map(Ze);t.length<2&&(t=[{offset:0,color:16711680,alpha:1},{offset:1,color:255,alpha:1}]),t.sort((i,s)=>i.offset-s.offset);const r=new Ge({type:a.gradientType,stops:t,angle:a.angle,alpha:a.alpha,maxColors:a.maxColors||0,replace:a.replace});return r._customParams={cssGradient:a.cssGradient||""},r.getSerializableParams=function(){var s;const i=Array.isArray(this.stops)?this.stops.map(Ke):[];return{gradientType:this.type,colorStops:i,angle:this.angle,alpha:this.alpha,maxColors:this.maxColors,replace:this.replace,cssGradient:((s=this._customParams)==null?void 0:s.cssGradient)??""}},r.getColorStopsForUI=function(){return Array.isArray(this.stops)?this.stops.map(Ke):[]},r.getDynamicControls=function(){const i=this.getColorStopsForUI(),s=[];return i.forEach((n,o)=>{s.push({id:`colorStop-${o}-color`,type:"color",label:`Stop ${o+1} Color`,property:`colorStops[${o}].color`,default:n.color}),s.push({id:`colorStop-${o}-offset`,type:"slider",label:`Stop ${o+1} Position`,property:`colorStops[${o}].offset`,min:0,max:1,step:.01,default:n.offset}),s.push({id:`colorStop-${o}-alpha`,type:"slider",label:`Stop ${o+1} Alpha`,property:`colorStops[${o}].alpha`,min:0,max:1,step:.01,default:n.alpha})}),s},r.handleButtonAction=function(i){(i==="addColorStop"||i==="removeColorStop")&&this.updateUIParam(i,!0)},r.updateUIParam=function(i,s){const n=this._customParams??{};switch(this._customParams=n,i){case"gradientType":this.type=Number(s);return;case"angle":case"alpha":case"maxColors":this[i]=Number(s);return;case"replace":this.replace=!!s;return;case"addColorStop":{const o=Array.isArray(this.stops)?[...this.stops]:[],l=Math.floor(Math.random()*255)<<16|Math.floor(Math.random()*255)<<8|Math.floor(Math.random()*255);if(o.length>0)for(const d of o)d.offset*=.8;o.push({offset:1,color:l,alpha:1}),o.sort((c,d)=>c.offset-d.offset),this.stops=o;return}case"removeColorStop":{const o=Array.isArray(this.stops)?[...this.stops]:[];o.length>2&&(o.pop(),this.stops=o);return}case"cssGradient":{const o=typeof s=="string"?s.trim():"";if(n.cssGradient=o,!o)return;try{const l=new Ge({css:o});this.type=l.type,this.angle=l.angle,this.stops=[...l.stops]}catch{}return}case"colorStops":{if(!Array.isArray(s))return;const o=s.map(Ze);o.sort((l,c)=>l.offset-c.offset),this.stops=o;return}default:{const o=/^colorStops\[(\d+)\]\.(offset|color|alpha)$/.exec(i);if(o){const[,l,c]=o,d=Number(l),h=Array.isArray(this.stops)?[...this.stops]:[];if(d<0||d>=h.length)return;c==="color"?h[d].color=typeof s=="string"?vt(s):Number(s):(c==="offset"||c==="alpha")&&(h[d][c]=Number(s)),this.stops=h}}}},r},defaultParams:{gradientType:0,colorStops:[{offset:0,color:"#ff0000",alpha:1},{offset:1,color:"#0000ff",alpha:1}],cssGradient:"",angle:90,alpha:.75,maxColors:0,replace:!1},controls:[{id:"gradientType",type:"select",label:"Gradient Type",property:"gradientType",options:[{label:"Linear",value:0},{label:"Radial",value:1},{label:"Conic",value:2}],default:0},{id:"angle",type:"slider",label:"Angle",property:"angle",min:0,max:360,step:1,default:90},{id:"alpha",type:"slider",label:"Overall Alpha",property:"alpha",min:0,max:1,step:.01,default:.75},{id:"maxColors",type:"slider",label:"Max Colors",property:"maxColors",min:0,max:24,step:1,default:0},{id:"replace",type:"toggle",label:"Replace Original Colors",property:"replace",default:!1},{id:"addColorStop",type:"button",label:"Add New Color Stop",action:"addColorStop"},{id:"removeColorStop",type:"button",label:"Remove Last Color Stop",action:"removeColorStop"},{id:"cssGradient",type:"text",label:"CSS Gradient",property:"cssGradient",default:"",placeholder:"e.g. linear-gradient(to right, red, blue)"}]});y({id:"color-map",name:"Color Map",category:"color",description:"Maps colors using a reference texture as a lookup table",createFilter:a=>{try{const e=v.ColorMapFilter;if(!e)return null;let t=null;a.texturePath?t=O.Texture.from(a.texturePath):t=O.Texture.from("/examples/filters-main/examples/images/colormap.png");const r=new e({colorMap:t,nearest:a.nearest,mix:a.mix});return r._customParams={...a},r.updateUIParam=function(i,s){const n=this._customParams||{};switch(this._customParams=n,n[i]=s,i){case"texturePath":s&&(this.colorMap=O.Texture.from(s));break;case"mix":this.mix=s;break;case"nearest":this.nearest=s;break;default:i in this&&(this[i]=s);break}return!0},r}catch{return null}},defaultParams:{texturePath:"",mix:1,nearest:!1},controls:[{id:"texturePath",type:"select",label:"Color Map",property:"texturePath",options:[{label:"Default",value:"/examples/filters-main/examples/images/colormap.png"},{label:"Grayscale",value:"/examples/filters-main/examples/images/colormap-grayscale.png"},{label:"Sepia",value:"/examples/filters-main/examples/images/colormap-sepia.png"}],default:"/examples/filters-main/examples/images/colormap.png"},{id:"mix",type:"slider",label:"Mix",property:"mix",min:0,max:1,step:.01,default:1},{id:"nearest",type:"toggle",label:"Nearest Neighbor Sampling",property:"nearest",default:!1}]});const Br=v.ColorReplaceFilter;y({id:"color-replace",name:"Color Replace",category:"color",description:"Replaces a specific color in the image with another color",createFilter:a=>{try{let e=16711680;a.originalColor&&(typeof a.originalColor=="string"?e=parseInt(a.originalColor.replace("#","0x"),16):typeof a.originalColor=="number"&&(e=a.originalColor));let t=255;a.targetColor&&(typeof a.targetColor=="string"?t=parseInt(a.targetColor.replace("#","0x"),16):typeof a.targetColor=="number"&&(t=a.targetColor));const r=new Br({originalColor:e,targetColor:t,tolerance:a.tolerance||.4});return r._customParams={...a},r.updateUIParam=function(i,s){const n=this._customParams||{};switch(this._customParams=n,n[i]=s,i){case"originalColor":typeof s=="string"?this.originalColor=parseInt(s.replace("#","0x"),16):typeof s=="number"&&(this.originalColor=s);break;case"targetColor":typeof s=="string"?this.targetColor=parseInt(s.replace("#","0x"),16):typeof s=="number"&&(this.targetColor=s);break;case"tolerance":this.tolerance=s;break;default:i in this&&(this[i]=s);break}return!0},r}catch{return null}},defaultParams:{originalColor:"#ff0000",targetColor:"#0000ff",tolerance:.4},controls:[{id:"originalColor",type:"color",label:"Original Color",property:"originalColor",default:"#ff0000"},{id:"targetColor",type:"color",label:"Target Color",property:"targetColor",default:"#0000ff"},{id:"tolerance",type:"slider",label:"Tolerance",property:"tolerance",min:0,max:1,step:.01,default:.4}]});const Er=v.MultiColorReplaceFilter;y({id:"multi-color-replace",name:"Multi-Color Replace",category:"color",description:"Replaces multiple colors in the image with different target colors",createFilter:a=>{try{const e=[];if(a.originalColor1&&a.targetColor1){const r=typeof a.originalColor1=="string"?parseInt(a.originalColor1.replace("#","0x"),16):a.originalColor1,i=typeof a.targetColor1=="string"?parseInt(a.targetColor1.replace("#","0x"),16):a.targetColor1;e.push([r,i])}if(a.originalColor2&&a.targetColor2){const r=typeof a.originalColor2=="string"?parseInt(a.originalColor2.replace("#","0x"),16):a.originalColor2,i=typeof a.targetColor2=="string"?parseInt(a.targetColor2.replace("#","0x"),16):a.targetColor2;e.push([r,i])}if(a.enableThirdPair&&a.originalColor3&&a.targetColor3){const r=typeof a.originalColor3=="string"?parseInt(a.originalColor3.replace("#","0x"),16):a.originalColor3,i=typeof a.targetColor3=="string"?parseInt(a.targetColor3.replace("#","0x"),16):a.targetColor3;e.push([r,i])}const t=new Er(e,a.tolerance||.05,3);return t._customParams={...a},t.updateUIParam=function(r,i){const s=this._customParams||{};if(this._customParams=s,s[r]=i,r==="originalColor1"||r==="targetColor1"||r==="originalColor2"||r==="targetColor2"||r==="originalColor3"||r==="targetColor3"||r==="enableThirdPair"){const n=[];if(s.originalColor1&&s.targetColor1){const o=typeof s.originalColor1=="string"?parseInt(s.originalColor1.replace("#","0x"),16):s.originalColor1,l=typeof s.targetColor1=="string"?parseInt(s.targetColor1.replace("#","0x"),16):s.targetColor1;n.push([o,l])}if(s.originalColor2&&s.targetColor2){const o=typeof s.originalColor2=="string"?parseInt(s.originalColor2.replace("#","0x"),16):s.originalColor2,l=typeof s.targetColor2=="string"?parseInt(s.targetColor2.replace("#","0x"),16):s.targetColor2;n.push([o,l])}if(s.enableThirdPair&&s.originalColor3&&s.targetColor3){const o=typeof s.originalColor3=="string"?parseInt(s.originalColor3.replace("#","0x"),16):s.originalColor3,l=typeof s.targetColor3=="string"?parseInt(s.targetColor3.replace("#","0x"),16):s.targetColor3;n.push([o,l])}this.replacements=n,this.refresh()}else r==="tolerance"?this.tolerance=i:r in this&&(this[r]=i);return!0},t}catch{return null}},defaultParams:{originalColor1:"#ff0000",targetColor1:"#0000ff",originalColor2:"#00ff00",targetColor2:"#ffff00",enableThirdPair:!1,originalColor3:"#ff00ff",targetColor3:"#00ffff",tolerance:.05},controls:[{id:"originalColor1",type:"color",label:"Original Color 1",property:"originalColor1",default:"#ff0000"},{id:"targetColor1",type:"color",label:"Target Color 1",property:"targetColor1",default:"#0000ff"},{id:"originalColor2",type:"color",label:"Original Color 2",property:"originalColor2",default:"#00ff00"},{id:"targetColor2",type:"color",label:"Target Color 2",property:"targetColor2",default:"#ffff00"},{id:"enableThirdPair",type:"toggle",label:"Enable Third Color Pair",property:"enableThirdPair",default:!1},{id:"originalColor3",type:"color",label:"Original Color 3",property:"originalColor3",default:"#ff00ff"},{id:"targetColor3",type:"color",label:"Target Color 3",property:"targetColor3",default:"#00ffff"},{id:"tolerance",type:"slider",label:"Tolerance",property:"tolerance",min:0,max:.5,step:.01,default:.05}]});const{RGBSplitFilter:Ir}=v;y({id:"rgb-split",name:"RGB Split",category:"color",description:"Shifts the red, green, and blue channels to create a retro 3D or glitch effect",createFilter:a=>{try{const e={x:a.redX!==void 0?a.redX:-10,y:a.redY!==void 0?a.redY:0},t={x:a.greenX!==void 0?a.greenX:0,y:a.greenY!==void 0?a.greenY:10},r={x:a.blueX!==void 0?a.blueX:0,y:a.blueY!==void 0?a.blueY:0},i=new Ir({red:e,green:t,blue:r});return i._customParams={...a},i.updateUIParam=function(s,n){try{const o=this._customParams||{};switch(this._customParams=o,o[s]=n,s){case"redX":this.redX=Number(n);break;case"redY":this.redY=Number(n);break;case"greenX":this.greenX=Number(n);break;case"greenY":this.greenY=Number(n);break;case"blueX":this.blueX=Number(n);break;case"blueY":this.blueY=Number(n);break;default:s in this&&(this[s]=n);break}return!0}catch{return this._customParams&&(this._customParams[s]=n),!1}},i}catch{return null}},defaultParams:{redX:-10,redY:0,greenX:0,greenY:10,blueX:0,blueY:0},controls:[{id:"redX",type:"slider",label:"Red X Offset",property:"redX",min:-20,max:20,step:1,default:-10},{id:"redY",type:"slider",label:"Red Y Offset",property:"redY",min:-20,max:20,step:1,default:0},{id:"greenX",type:"slider",label:"Green X Offset",property:"greenX",min:-20,max:20,step:1,default:0},{id:"greenY",type:"slider",label:"Green Y Offset",property:"greenY",min:-20,max:20,step:1,default:10},{id:"blueX",type:"slider",label:"Blue X Offset",property:"blueX",min:-20,max:20,step:1,default:0},{id:"blueY",type:"slider",label:"Blue Y Offset",property:"blueY",min:-20,max:20,step:1,default:0}]});const{AdvancedBloomFilter:Dr}=v;y({id:"advanced-bloom",name:"Advanced Bloom",category:"light",description:"Adds a sophisticated bloom/glow effect with fine-grained control",createFilter:a=>{try{const e=new Dr({threshold:a.threshold||.5,bloomScale:a.bloomScale||1,brightness:a.brightness||1,blur:a.blur||8,quality:a.quality||4,pixelSize:{x:a.pixelSizeX||1,y:a.pixelSizeY||1}});return e._customParams={pixelSizeX:a.pixelSizeX||1,pixelSizeY:a.pixelSizeY||1},e.updateUIParam=function(t,r){try{const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"threshold":this.threshold=Number(r);break;case"bloomScale":this.bloomScale=Number(r);break;case"brightness":this.brightness=Number(r);break;case"blur":this.blur=Number(r);break;case"quality":this.quality=Number(r);break;case"pixelSizeX":i.pixelSizeX=Number(r),this.pixelSize={x:Number(r),y:i.pixelSizeY};break;case"pixelSizeY":i.pixelSizeY=Number(r),this.pixelSize={x:i.pixelSizeX,y:Number(r)};break;default:t in this&&(this[t]=r);break}}catch{}},e}catch{return null}},defaultParams:{threshold:.5,bloomScale:1,brightness:1,blur:8,quality:4,pixelSizeX:1,pixelSizeY:1},controls:[{id:"threshold",type:"slider",label:"Threshold",property:"threshold",min:0,max:1,step:.01,default:.5},{id:"bloomScale",type:"slider",label:"Bloom Intensity",property:"bloomScale",min:0,max:3,step:.1,default:1},{id:"brightness",type:"slider",label:"Brightness",property:"brightness",min:0,max:3,step:.1,default:1},{id:"blur",type:"slider",label:"Blur Strength",property:"blur",min:0,max:20,step:1,default:8},{id:"quality",type:"slider",label:"Quality",property:"quality",min:1,max:10,step:1,default:4},{id:"pixelSizeX",type:"slider",label:"Pixel Size X",property:"pixelSizeX",min:.5,max:10,step:.5,default:1},{id:"pixelSizeY",type:"slider",label:"Pixel Size Y",property:"pixelSizeY",min:.5,max:10,step:.5,default:1}]});const Or=v.AsciiFilter;y({id:"ascii",name:"ASCII",category:"stylize",description:"Convert image to ASCII text characters",createFilter:a=>{try{const e=typeof a.size=="number"?a.size:8;let t=a.color;typeof t=="string"&&t.startsWith("#")&&(t=parseInt(t.replace("#","0x"),16));const r=a.replaceColor===!0,i=new Or({size:e,color:t,replaceColor:r});return i._customParams={size:e,color:t,replaceColor:r},i.updateUIParam=function(s,n){try{const o=this._customParams||{};switch(this._customParams=o,o[s]=n,s){case"size":this.size=Number(n);break;case"color":typeof n=="string"&&n.startsWith("#")?(o.color=n,this.color=parseInt(n.replace("#","0x"),16)):this.color=n;break;case"replaceColor":this.replaceColor=!!n;break;default:s in this&&(this[s]=n);break}}catch{}},i}catch{return null}},defaultParams:{size:8,color:"#ffffff",replaceColor:!1},controls:[{id:"size",type:"slider",label:"Character Size",property:"size",min:2,max:20,step:1,default:8},{id:"color",type:"color",label:"Character Color",property:"color",default:"#ffffff"},{id:"replaceColor",type:"toggle",label:"Replace Original Colors",property:"replaceColor",default:!1}]});const jr=v.BackdropBlurFilter;y({id:"backdrop-blur",name:"Backdrop Blur",category:"blur",description:"Blurs what is behind the object, creating a glass-like effect",createFilter:a=>{try{const e=new jr({strength:a.strength||20,quality:a.quality||4,resolution:a.resolution||.5,kernelSize:a.kernelSize||9});return e._customParams={...a},e.updateUIParam=function(t,r){try{const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"strength":this.strength=Number(r),this.blur=Number(r)/4;break;case"quality":this.quality=Number(r);break;case"resolution":this.resolution=Number(r);break;case"kernelSize":const s=Number(r);this.blurXFilter&&this.blurYFilter?(this.blurXFilter.kernelSize=s,this.blurYFilter.kernelSize=s):this.kernelSize=s;break;default:t in this&&(this[t]=r);break}}catch{}},e}catch{return null}},defaultParams:{strength:20,quality:4,resolution:.5,kernelSize:9},controls:[{id:"strength",type:"slider",label:"Strength",property:"strength",min:0,max:50,step:1,default:20},{id:"quality",type:"slider",label:"Quality",property:"quality",min:1,max:10,step:1,default:4},{id:"resolution",type:"slider",label:"Resolution",property:"resolution",min:.1,max:1,step:.1,default:.5},{id:"kernelSize",type:"select",label:"Kernel Size",property:"kernelSize",options:[{label:"5",value:5},{label:"7",value:7},{label:"9",value:9},{label:"11",value:11},{label:"13",value:13},{label:"15",value:15}],default:9}]});const{BevelFilter:Yr}=v;y({id:"bevel",name:"Bevel",category:"effects",description:"Add a 3D-like beveled edge effect to the image",createFilter:a=>{try{const e=a.lightColor?a.lightColor.replace("#","0x"):"0xffffff",t=a.shadowColor?a.shadowColor.replace("#","0x"):"0x000000",r=new Yr({rotation:a.rotation!==void 0?a.rotation:45,thickness:a.thickness!==void 0?a.thickness:2,lightColor:parseInt(e,16),lightAlpha:a.lightAlpha!==void 0?a.lightAlpha:.7,shadowColor:parseInt(t,16),shadowAlpha:a.shadowAlpha!==void 0?a.shadowAlpha:.7});return r._customParams={...a},r.updateUIParam=function(i,s){try{const n=this._customParams||{};switch(this._customParams=n,n[i]=s,i){case"rotation":this.rotation=Number(s);break;case"thickness":this.thickness=Number(s);break;case"lightColor":if(typeof s=="string"){const o=parseInt(s.replace("#","0x"),16);this.lightColor=o}break;case"lightAlpha":this.lightAlpha=Number(s);break;case"shadowColor":if(typeof s=="string"){const o=parseInt(s.replace("#","0x"),16);this.shadowColor=o}break;case"shadowAlpha":this.shadowAlpha=Number(s);break;default:i in this&&(this[i]=s);break}return!0}catch{return this._customParams&&(this._customParams[i]=s),!1}},r}catch{return null}},defaultParams:{rotation:45,thickness:2,lightColor:"#ffffff",lightAlpha:.7,shadowColor:"#000000",shadowAlpha:.7},controls:[{id:"rotation",type:"slider",label:"Angle",property:"rotation",min:0,max:360,step:1,default:45},{id:"thickness",type:"slider",label:"Thickness",property:"thickness",min:0,max:10,step:.1,default:2},{id:"lightColor",type:"color",label:"Light Color",property:"lightColor",default:"#ffffff"},{id:"lightAlpha",type:"slider",label:"Light Opacity",property:"lightAlpha",min:0,max:1,step:.01,default:.7},{id:"shadowColor",type:"color",label:"Shadow Color",property:"shadowColor",default:"#000000"},{id:"shadowAlpha",type:"slider",label:"Shadow Opacity",property:"shadowAlpha",min:0,max:1,step:.01,default:.7}]});const{BloomFilter:Xr}=v;y({id:"bloom",name:"Bloom/Glow",category:"light",description:"Add a subtle glow effect to bright areas of the image",createFilter:a=>{try{const e=typeof a.strengthX=="number"?a.strengthX:2,t=typeof a.strengthY=="number"?a.strengthY:2,r=typeof a.quality=="number"?a.quality:4,i=typeof a.resolution=="number"?a.resolution:1,s=typeof a.kernelSize=="number"?a.kernelSize:5,n=new Xr({strength:{x:Number(e),y:Number(t)},quality:Number(r),resolution:Number(i),kernelSize:Number(s)});return n._customParams={strengthX:e,strengthY:t,quality:r,resolution:i,kernelSize:s},n.updateUIParam=function(o,l){var c,d;try{const h=Number(l),u=this._customParams||{};switch(this._customParams=u,u[o]=h,o){case"strengthX":this.strength&&typeof this.strength=="object"&&(this.strength.x=h,(c=this._updateStrength)==null||c.call(this));break;case"strengthY":this.strength&&typeof this.strength=="object"&&(this.strength.y=h,(d=this._updateStrength)==null||d.call(this));break;case"quality":this.quality=h;break;case"resolution":this.resolution=h;break;case"kernelSize":this.kernelSize=h;break;default:o in this&&(this[o]=h);break}}catch{}},n}catch{return null}},defaultParams:{strengthX:2,strengthY:2,quality:4,resolution:1,kernelSize:5},controls:[{id:"strengthX",type:"slider",label:"Horizontal Strength",property:"strengthX",min:0,max:20,step:.1,default:2},{id:"strengthY",type:"slider",label:"Vertical Strength",property:"strengthY",min:0,max:20,step:.1,default:2},{id:"quality",type:"slider",label:"Quality",property:"quality",min:1,max:10,step:1,default:4},{id:"kernelSize",type:"select",label:"Kernel Size",property:"kernelSize",options:[{label:"5",value:5},{label:"7",value:7},{label:"9",value:9},{label:"11",value:11},{label:"13",value:13},{label:"15",value:15}],default:5}]});const{BulgePinchFilter:Je}=v,Ae=a=>{const e=Math.max(0,Number(a)||0);return Math.ceil(e+2)};y({id:"bulge-pinch",name:"Bulge/Pinch",category:"distortion",description:"Creates a bulge or pinch effect in a circular area",createFilter:a=>{try{const e=a.centerX??.5,t=a.centerY??.5,r=a.radius??100,i=a.strength??1,s=new Je({center:{x:e,y:t},radius:r,strength:i}),n=Ae(r);s.padding=Math.max(s.padding??0,n),s._exportPadding=n,s._customParams={...a};const o=l=>{var h;const c=Number(((h=l._customParams)==null?void 0:h.radius)??l.radius??0),d=Ae(c);l._exportPadding=d,l.padding=Math.max(l.padding??0,d)};return s.updateUIParam=function(l,c){const d=this._customParams||{};switch(this._customParams=d,d[l]=c,l){case"centerX":this.center||(this.center={x:.5,y:.5}),this.center.x=c;break;case"centerY":this.center||(this.center={x:.5,y:.5}),this.center.y=c;break;case"radius":this.radius=Number(c),o(this);break;case"strength":this.strength=Number(c);break;default:l in this&&(this[l]=c);break}return!0},s.createExportFilter=function(l={}){const c=Number.isFinite(l.previewToNativeScale)?Math.max(1,Number(l.previewToNativeScale)):1,d=this._customParams||a,h=Number(d.radius??100)*c,u=new Je({center:{x:Number(d.centerX??.5),y:Number(d.centerY??.5)},radius:h,strength:Number(d.strength??1)}),p=Ae(h);return u._exportPadding=p,u.padding=Math.max(u.padding??0,p),u},s.getExportPadding=function(){return Number(this._exportPadding||this.padding||0)},s}catch{return null}},defaultParams:{centerX:.5,centerY:.5,radius:100,strength:1},controls:[{id:"centerX",type:"slider",label:"Center X",property:"centerX",min:0,max:1,step:.01,default:.5},{id:"centerY",type:"slider",label:"Center Y",property:"centerY",min:0,max:1,step:.01,default:.5},{id:"radius",type:"slider",label:"Radius",property:"radius",min:0,max:1e3,step:1,default:100},{id:"strength",type:"slider",label:"Strength",property:"strength",min:-1,max:1,step:.01,default:1}]});const{ConvolutionFilter:Ur}=v,re={normal:[0,0,0,0,1,0,0,0,0],gaussianBlur:[.045,.122,.045,.122,.332,.122,.045,.122,.045],boxBlur:[1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9],edgeDetection:[-1,-1,-1,-1,8,-1,-1,-1,-1],edgeEnhance:[0,0,0,-1,1,0,0,0,0],emboss:[-2,-1,0,-1,1,1,0,1,2],sharpen:[0,-1,0,-1,5,-1,0,-1,0],sobelHorizontal:[1,2,1,0,0,0,-1,-2,-1],sobelVertical:[1,0,-1,2,0,-2,1,0,-1]};y({id:"convolution",name:"Convolution Matrix",category:"effects",description:"Apply custom image effects using matrix convolution",createFilter:a=>{try{let e;if(a.customMatrix)e=[a.m00,a.m01,a.m02,a.m10,a.m11,a.m12,a.m20,a.m21,a.m22];else{const r=a.preset;e=re[r]||re.normal}const t=new Ur(e,a.width||200,a.height||200);return t._customParams={...a},t.updateUIParam=function(r,i){const s=this._customParams||{};switch(this._customParams=s,s[r]=i,r){case"preset":if(!s.customMatrix){const n=i;re[n]&&(this.matrix=re[n])}break;case"customMatrix":if(i){const n=this.matrix;s.m00=n[0],s.m01=n[1],s.m02=n[2],s.m10=n[3],s.m11=n[4],s.m12=n[5],s.m20=n[6],s.m21=n[7],s.m22=n[8]}else{const n=s.preset;this.matrix=re[n]||re.normal}break;case"m00":case"m01":case"m02":case"m10":case"m11":case"m12":case"m20":case"m21":case"m22":if(s.customMatrix){const n=[...this.matrix],l={m00:0,m01:1,m02:2,m10:3,m11:4,m12:5,m20:6,m21:7,m22:8}[r];l!==void 0&&(n[l]=i,this.matrix=n)}break;case"width":this.width=i;break;case"height":this.height=i;break;default:r in this&&(this[r]=i);break}},t}catch{return null}},defaultParams:{preset:"normal",customMatrix:!1,m00:0,m01:0,m02:0,m10:0,m11:1,m12:0,m20:0,m21:0,m22:0,width:200,height:200},controls:[{id:"preset",type:"select",label:"Effect Preset",property:"preset",options:[{value:"normal",label:"Normal"},{value:"gaussianBlur",label:"Gaussian Blur"},{value:"boxBlur",label:"Box Blur"},{value:"edgeDetection",label:"Edge Detection"},{value:"edgeEnhance",label:"Edge Enhance"},{value:"emboss",label:"Emboss"},{value:"sharpen",label:"Sharpen"},{value:"sobelHorizontal",label:"Sobel Horizontal"},{value:"sobelVertical",label:"Sobel Vertical"}],default:"normal"},{id:"customMatrix",type:"toggle",label:"Use Custom Matrix",property:"customMatrix",default:!1},{id:"width",type:"slider",label:"Width",property:"width",min:50,max:500,step:10,default:200},{id:"height",type:"slider",label:"Height",property:"height",min:50,max:500,step:10,default:200},{id:"m00",type:"slider",label:"Matrix [0,0]",property:"m00",min:-5,max:5,step:.1,default:0},{id:"m01",type:"slider",label:"Matrix [0,1]",property:"m01",min:-5,max:5,step:.1,default:0},{id:"m02",type:"slider",label:"Matrix [0,2]",property:"m02",min:-5,max:5,step:.1,default:0},{id:"m10",type:"slider",label:"Matrix [1,0]",property:"m10",min:-5,max:5,step:.1,default:0},{id:"m11",type:"slider",label:"Matrix [1,1]",property:"m11",min:-5,max:5,step:.1,default:1},{id:"m12",type:"slider",label:"Matrix [1,2]",property:"m12",min:-5,max:5,step:.1,default:0},{id:"m20",type:"slider",label:"Matrix [2,0]",property:"m20",min:-5,max:5,step:.1,default:0},{id:"m21",type:"slider",label:"Matrix [2,1]",property:"m21",min:-5,max:5,step:.1,default:0},{id:"m22",type:"slider",label:"Matrix [2,2]",property:"m22",min:-5,max:5,step:.1,default:0}]});const{CrossHatchFilter:Vr}=v;y({id:"cross-hatch",name:"Cross Hatch",category:"stylize",description:"Creates a crosshatching effect like in a pencil drawing",createFilter:a=>{try{const e=new Vr;return e.updateUIParam=function(t,r){return!0},e}catch{return null}},defaultParams:{},controls:[]});y({id:"crt",name:"CRT Screen",category:"stylize",description:"Simulates an old CRT screen with scan lines and noise",createFilter:a=>{try{const e={lineWidth:typeof a.lineWidth=="number"?a.lineWidth:1,noise:typeof a.noise=="number"?a.noise:.3,curvature:typeof a.curvature=="number"?a.curvature:1,lineContrast:typeof a.lineContrast=="number"?a.lineContrast:.25,verticalLine:a.verticalLine===!0,noiseSize:typeof a.noiseSize=="number"?a.noiseSize:1,vignetting:typeof a.vignetting=="number"?a.vignetting:.3,vignettingAlpha:typeof a.vignettingAlpha=="number"?a.vignettingAlpha:1,vignettingBlur:typeof a.vignettingBlur=="number"?a.vignettingBlur:.3,time:typeof a.time=="number"?a.time:0,seed:typeof a.seed=="number"?a.seed:Math.random()},t=new v.CRTFilter(e);return t._customParams={...e},t.updateUIParam=function(r,i){try{const s=this._customParams||{};switch(this._customParams=s,s[r]=i,r){case"lineWidth":this.lineWidth=Number(i);break;case"noise":this.noise=Number(i);break;case"curvature":this.curvature=Number(i);break;case"lineContrast":this.lineContrast=Number(i);break;case"verticalLine":this.verticalLine=!!i;break;case"noiseSize":this.noiseSize=Number(i);break;case"vignetting":this.vignetting=Number(i);break;case"vignettingAlpha":this.vignettingAlpha=Number(i);break;case"vignettingBlur":this.vignettingBlur=Number(i);break;case"time":this.time=Number(i);break;case"seed":this.seed=Number(i);break;default:r in this&&(this[r]=i);break}}catch{}},t}catch{return null}},defaultParams:{lineWidth:1,noise:.3,curvature:1,lineContrast:.25,verticalLine:!1,noiseSize:1,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3,time:0,seed:1},controls:[{id:"lineWidth",type:"slider",label:"Scan Line Width",property:"lineWidth",min:0,max:5,step:.1,default:1},{id:"noise",type:"slider",label:"Noise Amount",property:"noise",min:0,max:1,step:.01,default:.3},{id:"curvature",type:"slider",label:"Screen Curvature",property:"curvature",min:0,max:10,step:.1,default:1},{id:"lineContrast",type:"slider",label:"Line Contrast",property:"lineContrast",min:0,max:1,step:.01,default:.25},{id:"verticalLine",type:"toggle",label:"Vertical Lines",property:"verticalLine",default:!1},{id:"noiseSize",type:"slider",label:"Noise Size",property:"noiseSize",min:.5,max:5,step:.1,default:1},{id:"vignetting",type:"slider",label:"Vignette Size",property:"vignetting",min:0,max:1,step:.01,default:.3},{id:"vignettingAlpha",type:"slider",label:"Vignette Opacity",property:"vignettingAlpha",min:0,max:1,step:.01,default:1},{id:"vignettingBlur",type:"slider",label:"Vignette Blur",property:"vignettingBlur",min:0,max:1,step:.01,default:.3},{id:"time",type:"slider",label:"Animation Time",property:"time",min:0,max:10,step:.1,default:0}]});const Hr=O.DisplacementFilter,Wr=O.Sprite,Ne=O.Texture;y({id:"displacement",name:"Displacement Map",category:"distortion",description:"Distorts the image using a displacement map texture",createFilter:a=>{try{const e=a.mapTexture||"/assets/images/displacement_map.png";let t;try{t=Ne.from(e),t.source.addressMode="repeat"}catch{const n=document.createElement("canvas");n.width=256,n.height=256;const o=n.getContext("2d");if(o){o.fillStyle="#ffffff",o.fillRect(0,0,n.width,n.height),o.fillStyle="#000000";for(let l=0;l<10;l++)for(let c=0;c<10;c++)(l+c)%2===0&&o.fillRect(l*25,c*25,25,25)}t=Ne.from(n)}const r=new Wr(t),i=new Hr(r,a.scale||50);return i.scale.x=a.scaleX||50,i.scale.y=a.scaleY||50,i._customParams={...a},i._displacementSprite=r,i.updateUIParam=function(s,n){const o=this._customParams||{};switch(this._customParams=o,o[s]=n,s){case"scaleX":this.scale.x=n;break;case"scaleY":this.scale.y=n;break;case"mapTexture":try{const l=this._displacementSprite;if(l){const c=Ne.from(n);c.source.addressMode="repeat",l.texture=c}}catch{}break;default:s in this?this[s]=n:s in this.scale&&(this.scale[s]=n);break}return!0},i}catch{return null}},defaultParams:{mapTexture:"/assets/images/displacement_map.png",scale:50,scaleX:50,scaleY:50},controls:[{id:"mapTexture",type:"select",label:"Displacement Map",property:"mapTexture",options:[{label:"Default",value:"/assets/images/displacement_map.png"},{label:"Clouds",value:"/assets/images/clouds.png"},{label:"Ripple",value:"/assets/images/ripple.png"}],default:"/assets/images/displacement_map.png"},{id:"scaleX",type:"slider",label:"Scale X",property:"scaleX",min:1,max:200,step:1,default:50},{id:"scaleY",type:"slider",label:"Scale Y",property:"scaleY",min:1,max:200,step:1,default:50}]});y({id:"dot",name:"Dot Screen",category:"stylize",description:"Simulates a halftone printing pattern with dots",createFilter:a=>{try{const e={scale:typeof a.scale=="number"?a.scale:1,angle:typeof a.angle=="number"?a.angle:5,grayscale:a.grayscale===!0},t=new v.DotFilter(e);return t._customParams={...e},t.updateUIParam=function(r,i){try{const s=this._customParams||{};switch(this._customParams=s,s[r]=i,r){case"scale":this.scale=Number(i);break;case"angle":this.angle=Number(i);break;case"grayscale":this.grayscale=!!i;break;default:r in this&&(this[r]=i);break}}catch{}},t}catch{return null}},defaultParams:{scale:1,angle:5,grayscale:!0},controls:[{id:"scale",type:"slider",label:"Dot Scale",property:"scale",min:.5,max:10,step:.1,default:1},{id:"angle",type:"slider",label:"Dot Angle",property:"angle",min:0,max:10,step:.1,default:5},{id:"grayscale",type:"toggle",label:"Grayscale",property:"grayscale",default:!0}]});const{EmbossFilter:qr}=v;y({id:"emboss",name:"Emboss",category:"stylize",description:"Creates an embossed relief effect",createFilter:a=>{try{const e=typeof a.strength=="number"?a.strength:5,t=new qr(e);return t._customParams={strength:e},t.updateUIParam=function(r,i){try{const s=this._customParams||{};switch(this._customParams=s,s[r]=i,r){case"strength":const n=Number(i);s.strength=n,this.strength=n;break;default:r in this&&(this[r]=i);break}}catch{}},t}catch{return null}},defaultParams:{strength:5},controls:[{id:"strength",type:"slider",label:"Strength",property:"strength",min:0,max:20,step:.5,default:5}]});const{GlitchFilter:$r}=v,Z={TRANSPARENT:0,ORIGINAL:1,LOOP:2,CLAMP:3,MIRROR:4};y({id:"glitch",name:"Glitch",category:"effects",description:"Apply digital distortion and glitch effects",createFilter:a=>{try{const e={x:a.redX,y:a.redY},t={x:a.greenX,y:a.greenY},r={x:a.blueX,y:a.blueY},i=new $r({slices:a.slices,offset:a.offset,direction:a.direction,fillMode:a.fillMode,seed:a.seed,average:a.average,minSize:a.minSize,sampleSize:a.sampleSize,red:e,green:t,blue:r});i.animating=a.animating||!1,i._customParams={...a},typeof i.refresh=="function"&&i.refresh();let s=null;const n=()=>{i.animating&&(i.seed=Math.random()),s=requestAnimationFrame(n)};return i.animating&&(s=requestAnimationFrame(n)),i._stopAnimation=()=>{s!==null&&(cancelAnimationFrame(s),s=null)},i.updateUIParam=function(o,l){const c=this._customParams||{};switch(this._customParams=c,c[o]=l,o){case"animating":this.animating=l,l&&!s&&(s=requestAnimationFrame(n));break;case"slices":this.slices=Math.round(l);break;case"redX":case"redY":const d=this.red;o==="redX"?d.x=l:d.y=l,this.red=d;break;case"greenX":case"greenY":const h=this.green;o==="greenX"?h.x=l:h.y=l,this.green=h;break;case"blueX":case"blueY":const u=this.blue;o==="blueX"?u.x=l:u.y=l,this.blue=u;break;case"seed":this.animating||(this.seed=l);break;case"randomizeSeed":l&&!c.animating&&(this.seed=Math.random());break;case"refresh":if(l)try{this.refresh()}catch{}break;case"offset":case"direction":case"fillMode":case"average":case"minSize":case"sampleSize":o in this&&(this[o]=l);break;default:o in this&&(this[o]=l);break}},i}catch{return null}},defaultParams:{slices:10,offset:100,direction:0,fillMode:Z.LOOP,seed:.5,average:!1,minSize:8,sampleSize:512,redX:2,redY:2,greenX:-10,greenY:4,blueX:10,blueY:-4,animating:!1,randomizeSeed:!1,refresh:!1},controls:[{id:"animating",type:"toggle",label:"Animate Automatically",property:"animating",default:!1},{id:"slices",type:"slider",label:"Slices",property:"slices",min:2,max:20,step:1,default:10},{id:"offset",type:"slider",label:"Offset Amount",property:"offset",min:-400,max:400,step:1,default:100},{id:"direction",type:"slider",label:"Direction",property:"direction",min:-180,max:180,step:1,default:0},{id:"fillMode",type:"select",label:"Fill Mode",property:"fillMode",options:[{value:Z.TRANSPARENT,label:"Transparent"},{value:Z.ORIGINAL,label:"Original"},{value:Z.LOOP,label:"Loop"},{value:Z.CLAMP,label:"Clamp"},{value:Z.MIRROR,label:"Mirror"}],default:Z.LOOP},{id:"seed",type:"slider",label:"Seed",property:"seed",min:0,max:1,step:.01,default:.5},{id:"randomizeSeed",type:"button",label:"Randomize Seed",action:"randomizeSeed"},{id:"refresh",type:"button",label:"Refresh Filter",action:"refresh"},{id:"average",type:"toggle",label:"Average Slices",property:"average",default:!1},{id:"redX",type:"slider",label:"Red X Offset",property:"redX",min:-50,max:50,step:.5,default:2},{id:"redY",type:"slider",label:"Red Y Offset",property:"redY",min:-50,max:50,step:.5,default:2},{id:"greenX",type:"slider",label:"Green X Offset",property:"greenX",min:-50,max:50,step:.5,default:-10},{id:"greenY",type:"slider",label:"Green Y Offset",property:"greenY",min:-50,max:50,step:.5,default:4},{id:"blueX",type:"slider",label:"Blue X Offset",property:"blueX",min:-50,max:50,step:.5,default:10},{id:"blueY",type:"slider",label:"Blue Y Offset",property:"blueY",min:-50,max:50,step:.5,default:-4}]});const{GlowFilter:Gr}=v;y({id:"glow",name:"Glow",category:"light",description:"Adds a customizable glow effect around the image",createFilter:a=>{try{const e=parseInt(a.color.replace("#","0x"),16),t=new Gr({distance:a.distance||10,outerStrength:a.outerStrength||4,innerStrength:a.innerStrength||0,color:e,alpha:a.alpha??1,quality:a.quality||.1,knockout:a.knockout||!1});return t._customParams={color:a.color||"#ffffff",...a},t.updateUIParam=function(r,i){try{const s=this._customParams||{};switch(this._customParams=s,s[r]=i,r){case"distance":this.distance=Number(i);break;case"outerStrength":this.outerStrength=Number(i);break;case"innerStrength":this.innerStrength=Number(i);break;case"color":s.color=i,this.color=parseInt(i.replace("#","0x"),16);break;case"alpha":this.alpha=Number(i);break;case"quality":this.quality=Number(i);break;case"knockout":this.knockout=!!i;break;default:r in this&&(this[r]=i);break}}catch{}},t}catch{return null}},defaultParams:{distance:10,outerStrength:4,innerStrength:0,color:"#ffffff",alpha:1,quality:.1,knockout:!1},controls:[{id:"distance",type:"slider",label:"Distance",property:"distance",min:0,max:20,step:1,default:10},{id:"outerStrength",type:"slider",label:"Outer Strength",property:"outerStrength",min:0,max:20,step:.1,default:4},{id:"innerStrength",type:"slider",label:"Inner Strength",property:"innerStrength",min:0,max:20,step:.1,default:0},{id:"color",type:"color",label:"Color",property:"color",default:"#ffffff"},{id:"alpha",type:"slider",label:"Alpha",property:"alpha",min:0,max:1,step:.01,default:1},{id:"quality",type:"slider",label:"Quality",property:"quality",min:.01,max:1,step:.01,default:.1},{id:"knockout",type:"toggle",label:"Show Glow Only",property:"knockout",default:!1}]});const{GodrayFilter:Zr}=v;y({id:"godray",name:"Godray",category:"light",description:"Creates volumetric light-ray effects (crepuscular rays)",createFilter:a=>{try{const e=new Zr({angle:a.angle||30,parallel:a.parallel??!0,center:{x:a.centerX||0,y:a.centerY||0},gain:a.gain||.5,lacunarity:a.lacunarity||2.5,time:a.time||0,alpha:a.alpha||1});return e._customParams={centerX:a.centerX||0,centerY:a.centerY||0,...a},e.updateUIParam=function(t,r){try{const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"angle":this.angle=Number(r);break;case"parallel":this.parallel=!!r;break;case"centerX":i.centerX=Number(r),this.center={x:Number(r),y:i.centerY};break;case"centerY":i.centerY=Number(r),this.center={x:i.centerX,y:Number(r)};break;case"gain":this.gain=Number(r);break;case"lacunarity":this.lacunarity=Number(r);break;case"time":this.time=Number(r);break;case"alpha":this.alpha=Number(r);break;default:t in this&&(this[t]=r);break}}catch{}},e}catch{return null}},defaultParams:{angle:30,parallel:!0,centerX:0,centerY:0,gain:.5,lacunarity:2.5,time:0,alpha:1},controls:[{id:"angle",type:"slider",label:"Angle",property:"angle",min:0,max:360,step:1,default:30},{id:"parallel",type:"toggle",label:"Parallel Rays",property:"parallel",default:!0},{id:"centerX",type:"slider",label:"Light Source X",property:"centerX",min:-1,max:1,step:.01,default:0},{id:"centerY",type:"slider",label:"Light Source Y",property:"centerY",min:-1,max:1,step:.01,default:0},{id:"gain",type:"slider",label:"Gain/Intensity",property:"gain",min:0,max:1,step:.01,default:.5},{id:"lacunarity",type:"slider",label:"Density",property:"lacunarity",min:.1,max:10,step:.1,default:2.5},{id:"time",type:"slider",label:"Time",property:"time",min:0,max:10,step:.1,default:0},{id:"alpha",type:"slider",label:"Alpha",property:"alpha",min:0,max:1,step:.01,default:1}]});const Kr=v.SimpleLightmapFilter,Qe=O.Texture;y({id:"lightmap",name:"Lightmap",category:"light",description:"Applies lighting effects using a reference texture as a light map",createFilter:a=>{try{const e=a.textureType||"default",t=a.color||"#000000",r=typeof a.alpha=="number"?a.alpha:1,i=document.createElement("canvas");i.width=256,i.height=256;const s=i.getContext("2d");if(!s)throw new Error("Canvas 2D context not available");if(e==="spotlight"){s.fillStyle="black",s.fillRect(0,0,256,256);const c=s.createRadialGradient(128,128,5,128,128,80);c.addColorStop(0,"white"),c.addColorStop(.5,"rgba(255, 255, 255, 0.5)"),c.addColorStop(1,"rgba(0, 0, 0, 0)"),s.fillStyle=c,s.beginPath(),s.arc(128,128,100,0,Math.PI*2),s.fill()}else if(e==="softlight"){const c=s.createLinearGradient(0,0,256,256);c.addColorStop(0,"white"),c.addColorStop(.3,"rgba(220, 220, 220, 1)"),c.addColorStop(.7,"rgba(150, 150, 150, 1)"),c.addColorStop(1,"rgba(80, 80, 80, 1)"),s.fillStyle=c,s.fillRect(0,0,256,256)}else{const c=s.createRadialGradient(128,128,10,128,128,160);c.addColorStop(0,"white"),c.addColorStop(.3,"rgba(220, 220, 220, 1)"),c.addColorStop(.6,"rgba(150, 150, 150, 1)"),c.addColorStop(1,"black"),s.fillStyle=c,s.fillRect(0,0,256,256)}const n=Qe.from(i);let o;try{typeof t=="string"&&t.startsWith("#")?o=parseInt(t.replace("#","0x"),16):o=0}catch{o=0}const l=new Kr(n,o,r);return l._customParams={textureType:e,color:t,alpha:r},l.updateUIParam=function(c,d){try{const h=this._customParams||{};switch(this._customParams=h,h[c]=d,c){case"textureType":h.textureType=d;const u=document.createElement("canvas");u.width=256,u.height=256;const p=u.getContext("2d");if(p){if(d==="spotlight"){p.fillStyle="black",p.fillRect(0,0,256,256);const g=p.createRadialGradient(128,128,5,128,128,80);g.addColorStop(0,"white"),g.addColorStop(.5,"rgba(255, 255, 255, 0.5)"),g.addColorStop(1,"rgba(0, 0, 0, 0)"),p.fillStyle=g,p.beginPath(),p.arc(128,128,100,0,Math.PI*2),p.fill()}else if(d==="softlight"){const g=p.createLinearGradient(0,0,256,256);g.addColorStop(0,"white"),g.addColorStop(.3,"rgba(220, 220, 220, 1)"),g.addColorStop(.7,"rgba(150, 150, 150, 1)"),g.addColorStop(1,"rgba(80, 80, 80, 1)"),p.fillStyle=g,p.fillRect(0,0,256,256)}else{const g=p.createRadialGradient(128,128,10,128,128,160);g.addColorStop(0,"white"),g.addColorStop(.3,"rgba(220, 220, 220, 1)"),g.addColorStop(.6,"rgba(150, 150, 150, 1)"),g.addColorStop(1,"black"),p.fillStyle=g,p.fillRect(0,0,256,256)}const m=Qe.from(u);if(this.lightMap=m,this.enabled!==void 0){const g=this.enabled;this.enabled=!1,setTimeout(()=>{this.enabled=g},0)}}break;case"color":h.color=d;try{typeof d=="string"&&d.startsWith("#")?this.color=parseInt(d.replace("#","0x"),16):this.color=0}catch{this.color=0}break;case"alpha":this.alpha=Number(d);break;default:c in this&&(this[c]=d);break}}catch{}},l}catch{return null}},defaultParams:{textureType:"default",color:"#000000",alpha:1},controls:[{id:"textureType",type:"select",label:"Light Map Type",property:"textureType",options:[{label:"Default",value:"default"},{label:"Spotlight",value:"spotlight"},{label:"Soft Light",value:"softlight"}],default:"default"},{id:"color",type:"color",label:"Ambient Color",property:"color",default:"#000000"},{id:"alpha",type:"slider",label:"Intensity",property:"alpha",min:0,max:1,step:.01,default:1}]});const{NoiseFilter:Jr}=O;y({id:"noise",name:"Noise",category:"effects",description:"Add random noise to the image",createFilter:a=>{try{const e=new Jr({noise:a.noise||.5,seed:a.seed||Math.random()});e.animating=a.animating||!1,e._customParams={...a};let t=null;const r=()=>{e.animating&&(e.seed=Math.random()),t=requestAnimationFrame(r)};return e.animating&&(t=requestAnimationFrame(r)),e._stopAnimation=()=>{t!==null&&(cancelAnimationFrame(t),t=null)},e.updateUIParam=function(i,s){const n=this._customParams||{};switch(this._customParams=n,n[i]=s,i){case"animating":this.animating=s,s&&!t&&(t=requestAnimationFrame(r));break;case"noise":this.noise=Math.max(0,Math.min(1,s));break;case"seed":this.animating||(this.seed=s);break;case"randomizeSeed":s&&(this.seed=Math.random());break;default:i in this&&(this[i]=s);break}},e}catch{return null}},defaultParams:{noise:.5,seed:.5,animating:!1,randomizeSeed:!1},controls:[{id:"animating",type:"toggle",label:"Animate Noise",property:"animating",default:!1},{id:"noise",type:"slider",label:"Noise Amount",property:"noise",min:0,max:1,step:.01,default:.5},{id:"seed",type:"slider",label:"Random Seed",property:"seed",min:0,max:1,step:.01,default:.5},{id:"randomizeSeed",type:"button",label:"Randomize Seed",action:"randomizeSeed"}]});const{OldFilmFilter:Qr}=v;y({id:"old-film",name:"Old Film",category:"effects",description:"Apply a vintage film effect with scratches and grain",createFilter:a=>{try{const e=new Qr({sepia:a.sepia,noise:a.noise,noiseSize:a.noiseSize,scratch:a.scratch,scratchDensity:a.scratchDensity,scratchWidth:a.scratchWidth,vignetting:a.vignetting,vignettingAlpha:a.vignettingAlpha,vignettingBlur:a.vignettingBlur,seed:a.seed||Math.random()});e.animating=a.animating||!1,e._customParams={...a};let t=null;const r=()=>{e.animating&&(e.seed=Math.random()),t=requestAnimationFrame(r)};return e.animating&&(t=requestAnimationFrame(r)),e._stopAnimation=()=>{t!==null&&(cancelAnimationFrame(t),t=null)},e.updateUIParam=function(i,s){const n=this._customParams||{};switch(this._customParams=n,n[i]=s,i){case"animating":this.animating=s,s&&!t&&(t=requestAnimationFrame(r));break;case"seed":this.animating||(this.seed=s);break;case"randomizeSeed":s&&(this.seed=Math.random());break;case"sepia":case"noise":case"noiseSize":case"scratch":case"scratchDensity":case"scratchWidth":case"vignetting":case"vignettingAlpha":case"vignettingBlur":i in this&&(this[i]=s);break;default:i in this&&(this[i]=s);break}},e}catch{return null}},defaultParams:{sepia:.3,noise:.3,noiseSize:1,scratch:.5,scratchDensity:.3,scratchWidth:1,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3,seed:.5,animating:!1,randomizeSeed:!1},controls:[{id:"animating",type:"toggle",label:"Animate Film",property:"animating",default:!1},{id:"sepia",type:"slider",label:"Sepia Tone",property:"sepia",min:0,max:1,step:.01,default:.3},{id:"noise",type:"slider",label:"Noise Amount",property:"noise",min:0,max:1,step:.01,default:.3},{id:"noiseSize",type:"slider",label:"Noise Size",property:"noiseSize",min:1,max:10,step:.1,default:1},{id:"scratch",type:"slider",label:"Scratch Amount",property:"scratch",min:-1,max:1,step:.01,default:.5},{id:"scratchDensity",type:"slider",label:"Scratch Density",property:"scratchDensity",min:0,max:1,step:.01,default:.3},{id:"scratchWidth",type:"slider",label:"Scratch Width",property:"scratchWidth",min:1,max:20,step:1,default:1},{id:"vignetting",type:"slider",label:"Vignette Size",property:"vignetting",min:0,max:1,step:.01,default:.3},{id:"vignettingAlpha",type:"slider",label:"Vignette Opacity",property:"vignettingAlpha",min:0,max:1,step:.01,default:1},{id:"vignettingBlur",type:"slider",label:"Vignette Blur",property:"vignettingBlur",min:0,max:1,step:.01,default:.3},{id:"seed",type:"slider",label:"Random Seed",property:"seed",min:0,max:1,step:.01,default:.5},{id:"randomizeSeed",type:"button",label:"Randomize Seed",action:"randomizeSeed"}]});const{OutlineFilter:ei}=v;y({id:"outline",name:"Outline",category:"effects",description:"Add an outline or stroke around the image",createFilter:a=>{try{let e=a.color;typeof e=="string"&&(e=parseInt(e.replace("#","0x"),16));const t=new ei({thickness:a.thickness||4,color:e,alpha:a.alpha||1,quality:a.quality||.1,knockout:a.knockout||!1});return t._customParams={...a},t.updateUIParam=function(r,i){const s=this._customParams||{};switch(this._customParams=s,s[r]=i,r){case"thickness":this.thickness=Math.max(0,i);break;case"color":typeof i=="string"?(this.color=parseInt(i.replace("#","0x"),16),s.color=i):this.color=i;break;case"alpha":this.alpha=Math.max(0,Math.min(1,i));break;case"quality":this.quality=Math.max(.01,Math.min(1,i));break;case"knockout":this.knockout=!!i;break;default:r in this&&(this[r]=i);break}},t}catch{return null}},defaultParams:{thickness:4,color:"#000000",alpha:1,quality:.1,knockout:!1},controls:[{id:"thickness",type:"slider",label:"Thickness",property:"thickness",min:0,max:20,step:.1,default:4},{id:"color",type:"color",label:"Color",property:"color",default:"#000000"},{id:"alpha",type:"slider",label:"Alpha",property:"alpha",min:0,max:1,step:.01,default:1},{id:"quality",type:"slider",label:"Quality",property:"quality",min:.01,max:1,step:.01,default:.1,tooltip:"Higher values give better quality but slower performance"},{id:"knockout",type:"toggle",label:"Outline Only",property:"knockout",default:!1,tooltip:"Only show the outline, not the image content"}]});const{PixelateFilter:ti}=v;y({id:"pixelate",name:"Pixelate",category:"effects",description:"Create a pixelated or mosaic effect",createFilter:a=>{try{const e=new ti(a.useUniform?Math.max(4,a.size||10):[Math.max(4,a.sizeX||10),Math.max(4,a.sizeY||10)]);return e._customParams={...a},e.updateUIParam=function(t,r){const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"useUniform":if(i.useUniform=r,r){const s=Math.round((this.sizeX+this.sizeY)/2);this.size=Math.max(4,s),i.size=s}else{const s=Array.isArray(this.size)?this.size[0]:this.size;this.sizeX=Math.max(4,s),this.sizeY=Math.max(4,s),i.sizeX=this.sizeX,i.sizeY=this.sizeY}break;case"size":i.useUniform&&(this.size=Math.max(4,r));break;case"sizeX":i.useUniform||(this.sizeX=Math.max(4,r));break;case"sizeY":i.useUniform||(this.sizeY=Math.max(4,r));break;default:t in this&&(this[t]=r);break}},e}catch{return null}},defaultParams:{useUniform:!0,size:10,sizeX:10,sizeY:10},controls:[{id:"useUniform",type:"toggle",label:"Uniform Pixels",property:"useUniform",default:!0,tooltip:"Use the same size for both X and Y dimensions"},{id:"size",type:"slider",label:"Pixel Size",property:"size",min:4,max:40,step:1,default:10,tooltip:"Size of the pixels in both dimensions"},{id:"sizeX",type:"slider",label:"Horizontal Size",property:"sizeX",min:4,max:40,step:1,default:10,tooltip:"Size of the pixels in the horizontal direction"},{id:"sizeY",type:"slider",label:"Vertical Size",property:"sizeY",min:4,max:40,step:1,default:10,tooltip:"Size of the pixels in the vertical direction"}]});const{ReflectionFilter:ri}=v;y({id:"reflection",name:"Reflection",category:"distortion",description:"Creates a water reflection effect with configurable waves",createFilter:a=>{try{const e={mirror:a.mirror??!0,boundary:a.boundary??.5,amplitude:new Float32Array([a.amplitudeStart??0,a.amplitudeEnd??20]),waveLength:new Float32Array([a.wavelengthStart??30,a.wavelengthEnd??100]),alpha:new Float32Array([a.alphaStart??1,a.alphaEnd??1]),time:a.time??0},t=new ri(e);return t._customParams={...a},t.animating=a.animating??!1,t.updateUIParam=function(r,i){const s=this._customParams||{};switch(this._customParams=s,s[r]=i,r){case"mirror":case"boundary":case"time":this[r]=i;break;case"amplitudeStart":Array.isArray(this.amplitude)||(this.amplitude=[0,this._customParams.amplitudeEnd||20]),this.amplitude[0]=i;break;case"amplitudeEnd":Array.isArray(this.amplitude)||(this.amplitude=[this._customParams.amplitudeStart||0,20]),this.amplitude[1]=i;break;case"wavelengthStart":Array.isArray(this.waveLength)||(this.waveLength=[30,this._customParams.wavelengthEnd||100]),this.waveLength[0]=i;break;case"wavelengthEnd":Array.isArray(this.waveLength)||(this.waveLength=[this._customParams.wavelengthStart||30,100]),this.waveLength[1]=i;break;case"alphaStart":Array.isArray(this.alpha)||(this.alpha=[1,this._customParams.alphaEnd||1]),this.alpha[0]=i;break;case"alphaEnd":Array.isArray(this.alpha)||(this.alpha=[this._customParams.alphaStart||1,1]),this.alpha[1]=i;break;case"animating":this.animating=i;break;default:r in this&&(this[r]=i);break}return!0},t}catch{return null}},defaultParams:{mirror:!0,boundary:.5,amplitudeStart:0,amplitudeEnd:20,wavelengthStart:30,wavelengthEnd:100,alphaStart:1,alphaEnd:1,time:0,animating:!1},controls:[{id:"mirror",type:"toggle",label:"Mirror Image",property:"mirror",default:!0},{id:"boundary",type:"slider",label:"Boundary Line",property:"boundary",min:0,max:1,step:.01,default:.5},{id:"amplitudeStart",type:"slider",label:"Wave Height (Start)",property:"amplitudeStart",min:0,max:50,step:1,default:0},{id:"amplitudeEnd",type:"slider",label:"Wave Height (End)",property:"amplitudeEnd",min:0,max:50,step:1,default:20},{id:"wavelengthStart",type:"slider",label:"Wave Length (Start)",property:"wavelengthStart",min:10,max:200,step:1,default:30},{id:"wavelengthEnd",type:"slider",label:"Wave Length (End)",property:"wavelengthEnd",min:10,max:200,step:1,default:100},{id:"alphaStart",type:"slider",label:"Opacity (Start)",property:"alphaStart",min:0,max:1,step:.01,default:1},{id:"alphaEnd",type:"slider",label:"Opacity (End)",property:"alphaEnd",min:0,max:1,step:.01,default:1},{id:"time",type:"slider",label:"Animation Time",property:"time",min:0,max:10,step:.1,default:0},{id:"animating",type:"toggle",label:"Auto Animate",property:"animating",default:!1}]});const{ShockwaveFilter:ii}=v;y({id:"shockwave",name:"Shockwave",category:"distortion",description:"Creates a rippling shockwave or blast wave effect",createFilter:a=>{try{const e=a.centerX??.5,t=a.centerY??.5,r={x:e,y:t},i=a.amplitude??30,s=a.wavelength??160,n=a.speed??500,o=a.brightness??1,l=a.radius??-1,c=a.time??0,d=new ii({center:r,amplitude:i,wavelength:s,speed:n,brightness:o,radius:l,time:c});return d._customParams={...a},d.animating=a.animating??!1,d.updateUIParam=function(h,u){const p=this._customParams||{};switch(this._customParams=p,p[h]=u,h){case"centerX":this.center||(this.center={x:.5,y:.5}),this.center.x=u;break;case"centerY":this.center||(this.center={x:.5,y:.5}),this.center.y=u;break;case"amplitude":case"wavelength":case"speed":case"brightness":case"radius":case"time":this[h]=u;break;case"animating":this.animating=u;break;default:h in this&&(this[h]=u);break}return!0},d}catch{return null}},defaultParams:{centerX:.5,centerY:.5,amplitude:30,wavelength:160,speed:500,brightness:1,radius:-1,time:0,animating:!1},controls:[{id:"centerX",type:"slider",label:"Center X",property:"centerX",min:0,max:1,step:.01,default:.5},{id:"centerY",type:"slider",label:"Center Y",property:"centerY",min:0,max:1,step:.01,default:.5},{id:"amplitude",type:"slider",label:"Amplitude",property:"amplitude",min:0,max:100,step:1,default:30},{id:"wavelength",type:"slider",label:"Wavelength",property:"wavelength",min:10,max:500,step:1,default:160},{id:"speed",type:"slider",label:"Speed",property:"speed",min:1,max:1e3,step:10,default:500},{id:"brightness",type:"slider",label:"Brightness",property:"brightness",min:0,max:5,step:.1,default:1},{id:"radius",type:"slider",label:"Max Radius",property:"radius",min:-1,max:1e3,step:10,default:-1},{id:"time",type:"slider",label:"Time",property:"time",min:0,max:5,step:.1,default:0},{id:"animating",type:"toggle",label:"Auto Animate",property:"animating",default:!1}]});const{SimplexNoiseFilter:si}=v;y({id:"simplex-noise",name:"Simplex Noise",category:"effects",description:"Apply procedural noise to create texture effects",createFilter:a=>{try{const e=a.animating?0:a.offsetZ||0,t=new si({strength:a.strength,noiseScale:a.noiseScale,offsetX:a.offsetX,offsetY:a.offsetY,offsetZ:e,step:a.step});t.animating=a.animating||!1,t.animationSpeed=a.animationSpeed||.01,t._customParams={...a};let r=null,i=0;const s=()=>{t.animating&&(i+=t.animationSpeed,t.offsetZ=i),r=requestAnimationFrame(s)};return t.animating&&(r=requestAnimationFrame(s)),t._stopAnimation=()=>{r!==null&&(cancelAnimationFrame(r),r=null)},t.updateUIParam=function(n,o){const l=this._customParams||{};switch(this._customParams=l,l[n]=o,n){case"animating":this.animating=o,o&&!r&&(r=requestAnimationFrame(s));break;case"animationSpeed":this.animationSpeed=o;break;case"offsetZ":this.animating||(this.offsetZ=o);break;case"randomizeSeed":if(o){const c=()=>Math.random()*100-50;this.offsetX=c(),this.offsetY=c(),this.offsetZ=c(),l.offsetX=this.offsetX,l.offsetY=this.offsetY,l.offsetZ=this.offsetZ}break;case"strength":case"noiseScale":case"offsetX":case"offsetY":case"step":n in this&&(this[n]=o);break;default:n in this&&(this[n]=o);break}},t}catch{return null}},defaultParams:{strength:.5,noiseScale:10,offsetX:0,offsetY:0,offsetZ:0,step:-1,animating:!1,animationSpeed:.01,randomizeSeed:!1},controls:[{id:"strength",type:"slider",label:"Noise Strength",property:"strength",min:0,max:1,step:.01,default:.5},{id:"noiseScale",type:"slider",label:"Noise Scale",property:"noiseScale",min:1,max:50,step:.5,default:10},{id:"offsetX",type:"slider",label:"X Offset",property:"offsetX",min:-50,max:50,step:.5,default:0},{id:"offsetY",type:"slider",label:"Y Offset",property:"offsetY",min:-50,max:50,step:.5,default:0},{id:"offsetZ",type:"slider",label:"Z Offset",property:"offsetZ",min:-50,max:50,step:.5,default:0},{id:"step",type:"slider",label:"Step Threshold",property:"step",min:-1,max:1,step:.01,default:-1,tooltip:"Values above 0 create a blocky effect"},{id:"animating",type:"toggle",label:"Animate Noise",property:"animating",default:!1},{id:"animationSpeed",type:"slider",label:"Animation Speed",property:"animationSpeed",min:.001,max:.05,step:.001,default:.01},{id:"randomizeSeed",type:"button",label:"Randomize Pattern",action:"randomizeSeed"}]});const{TwistFilter:ai}=v,Ct=a=>Math.ceil(Math.max(0,Number(a)||0)+2),et=(a,e=1)=>{const t=Math.max(1,Number(a._sourceWidth??0)),r=Math.max(1,Number(a._sourceHeight??0)),i=Math.min(t,r),s=Number(a.centerX??.5),n=Number(a.centerY??.5),o=Number(a.radius??.25),l=Number(a.angle??4),c=s*t*e,d=n*r*e,h=o*i*e,u=new ai({offset:{x:c,y:d},radius:h,angle:l}),p=Ct(h);return u.padding=Math.max(u.padding??0,p),u._exportPadding=p,u};y({id:"twist",name:"Twist",category:"distortion",description:"Creates a twisting distortion effect around a central point",createFilter:a=>{try{const e={centerX:a.centerX??.5,centerY:a.centerY??.5,radius:a.radius??.25,angle:a.angle??4,_sourceWidth:a._sourceWidth,_sourceHeight:a._sourceHeight},t=et(e,1);return t._customParams={...e},t.updateUIParam=function(r,i){const s=this._customParams||{};this._customParams=s,s[r]=i;const n=Math.max(1,Number(s._sourceWidth??0)),o=Math.max(1,Number(s._sourceHeight??0)),l=Math.min(n,o),c=Number(s.centerX??.5),d=Number(s.centerY??.5),h=Number(s.radius??.25),u=Number(s.angle??4);this.offset&&(this.offset.x=c*n,this.offset.y=d*o),this.radius=h*l,this.angle=u;const p=Ct(this.radius);return this._exportPadding=p,this.padding=Math.max(this.padding??0,p),!0},t.createExportFilter=function(r={}){const i=Number.isFinite(r.previewToNativeScale)?Math.max(1,Number(r.previewToNativeScale)):1,s=this._customParams||e;return et(s,i)},t.getExportPadding=function(){return Number(this._exportPadding||this.padding||0)},t}catch{return null}},defaultParams:{centerX:.5,centerY:.5,radius:.25,angle:4},controls:[{id:"angle",type:"slider",label:"Angle",property:"angle",min:-10,max:10,step:.1,default:4,tooltip:"Amount of twisting (positive is clockwise)"},{id:"radius",type:"slider",label:"Radius",property:"radius",min:.05,max:.75,step:.01,default:.25,tooltip:"Size of the twist effect (relative to image)"},{id:"centerX",type:"slider",label:"Center X",property:"centerX",min:0,max:1,step:.01,default:.5,tooltip:"Horizontal position of twist center"},{id:"centerY",type:"slider",label:"Center Y",property:"centerY",min:0,max:1,step:.01,default:.5,tooltip:"Vertical position of twist center"}]});const{AdjustmentFilter:ni}=v;function ye(a){const e=typeof a=="string"?parseInt(a.replace("#","0x"),16):a;return[(e>>16&255)/255,(e>>8&255)/255,(e&255)/255]}class oi extends ni{constructor(e={}){super({brightness:1,contrast:1,saturation:1,alpha:1}),this._radius=.8,this._strength=1,this._colorRgb=[0,0,0],this._colorValue="#000000",this._radius=e.radius??.8,this._strength=e.strength??1,e.color!==void 0&&(typeof e.color=="string"?(this._colorValue=e.color,this._colorRgb=ye(e.color)):(this._colorValue="#"+e.color.toString(16).padStart(6,"0"),this._colorRgb=ye(e.color))),this.updateVignette()}updateVignette(){const e=1-this._radius/2,t=this._strength*e;this.brightness=Math.max(.5,1-t*.5),this.contrast=1+t*.2,(this._colorRgb[0]>0||this._colorRgb[1]>0||this._colorRgb[2]>0)&&(this.saturation=1-t*.3)}get radius(){return this._radius}set radius(e){this._radius=Math.max(.1,Math.min(1.5,e)),this.updateVignette()}get strength(){return this._strength}set strength(e){this._strength=Math.max(0,Math.min(2,e)),this.updateVignette()}get color(){return this._colorValue}set color(e){typeof e=="string"?(this._colorValue=e,this._colorRgb=ye(e)):(this._colorValue="#"+e.toString(16).padStart(6,"0"),this._colorRgb=ye(e)),this.updateVignette()}}y({id:"vignette",name:"Vignette",category:"effects",description:"Add a classic darkened border effect to the image",createFilter:a=>{try{const e=new oi({radius:a.radius||.8,strength:a.strength||1,color:a.color||"#000000"});return e._customParams={...a},e.updateUIParam=function(t,r){const i=this._customParams||{};switch(this._customParams=i,i[t]=r,t){case"radius":this.radius=Math.max(.1,Math.min(1.5,r));break;case"strength":this.strength=Math.max(0,r);break;case"color":this.color=r,typeof r=="string"&&(i.color=r);break;default:t in this&&(this[t]=r);break}},e}catch{return null}},defaultParams:{radius:.8,strength:1,color:"#000000"},controls:[{id:"radius",type:"slider",label:"Radius",property:"radius",min:.1,max:1.5,step:.01,default:.8,tooltip:"Size of the vignette effect (larger values create a smaller vignette)"},{id:"strength",type:"slider",label:"Strength",property:"strength",min:0,max:2,step:.01,default:1,tooltip:"Intensity of the vignette effect"},{id:"color",type:"color",label:"Color",property:"color",default:"#000000",tooltip:"Color of the vignette (usually black)"}]});function li(a){try{let e=[],t=[];try{e=ue(),e.length===0&&bt()}catch{}const r=a==null?void 0:a.disabled;if(Array.isArray(r)&&r.length>0){let i=0;for(const s of r)gr(s)&&i++;i>0}try{e=ue(),t=yt()}catch{e||(e=[]),t||(t=[])}return e.length,e}catch{return[]}}exports.CropControls=ft;exports.CropManager=ve;exports.EDITOR_CATEGORIES=ke;exports.EventEmitter=ne;exports.FilterManager=dt;exports.PixiRenderer=st;exports.REGISTRY_TO_UI=ht;exports.RemoveBgManager=ut;exports.TEXT_LAYER_FONT_FAMILIES=rt;exports.Toolbar=pt;exports.VanillaImageEditor=pr;exports.checkmark=we;exports.chevronLeft=Te;exports.chevronRight=ze;exports.close=Ce;exports.createButton=D;exports.createColorPicker=Be;exports.createSelect=Ie;exports.createSlider=Le;exports.createState=it;exports.createTextInput=Ee;exports.createToggle=Re;exports.duplicate=$t;exports.el=f;exports.eye=Ut;exports.eyeOff=Vt;exports.getAllCategories=yt;exports.getAllFilters=ue;exports.getFilter=gt;exports.getFiltersByCategory=_t;exports.getPreset=mt;exports.getRegisteredFilters=xt;exports.hasFilter=mr;exports.initializeFilterRegistry=li;exports.isFilterCompatibleWithMedia=br;exports.layers=ct;exports.lockClosed=Ht;exports.lockOpen=Wt;exports.move=at;exports.pencil=qt;exports.registerCorePixiFilters=bt;exports.registerFilter=y;exports.trash=lt;
2
+ //# sourceMappingURL=editor-DLvndiXG.cjs.map