@snowcone-app/canvas 0.1.10 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/{CanvasStateV1-BmE5V6me.cjs → CanvasStateV1-C4hC1MCe.cjs} +5 -5
  2. package/dist/{CanvasStateV1-BmE5V6me.cjs.map → CanvasStateV1-C4hC1MCe.cjs.map} +1 -1
  3. package/dist/{CanvasStateV1-CD3Q94F4.js → CanvasStateV1-CJU_xYW5.js} +3 -3
  4. package/dist/{CanvasStateV1-CD3Q94F4.js.map → CanvasStateV1-CJU_xYW5.js.map} +1 -1
  5. package/dist/{HybridHistoryManager-BV6XV0nD.js → HybridHistoryManager-jBBnVim8.js} +54 -54
  6. package/dist/{HybridHistoryManager-BV6XV0nD.js.map → HybridHistoryManager-jBBnVim8.js.map} +1 -1
  7. package/dist/{ElementFactory-Ckv6sSev.js → ImportManager-Oqu2yB54.js} +595 -378
  8. package/dist/ImportManager-Oqu2yB54.js.map +1 -0
  9. package/dist/{ElementFactory-DEjwp-Wg.cjs → ImportManager-W1eWhfyM.cjs} +5 -5
  10. package/dist/ImportManager-W1eWhfyM.cjs.map +1 -0
  11. package/dist/ThemeContext-BMNQKl1c.cjs +2 -0
  12. package/dist/{ThemeContext-4mJ_y0Me.cjs.map → ThemeContext-BMNQKl1c.cjs.map} +1 -1
  13. package/dist/ThemeContext-wj-wSO7J.js +1158 -0
  14. package/dist/{ThemeContext-H0Z-MqqR.js.map → ThemeContext-wj-wSO7J.js.map} +1 -1
  15. package/dist/advanced.js +5 -32
  16. package/dist/advanced.js.map +1 -1
  17. package/dist/advanced.mjs +588 -15069
  18. package/dist/advanced.mjs.map +1 -1
  19. package/dist/components/embed/KitLayout.d.ts +22 -0
  20. package/dist/components/embed/UndoRedoControls.d.ts +3 -0
  21. package/dist/compose-Dqh2f8tS.js +22222 -0
  22. package/dist/compose-Dqh2f8tS.js.map +1 -0
  23. package/dist/compose-HDJp4Z_d.cjs +60 -0
  24. package/dist/compose-HDJp4Z_d.cjs.map +1 -0
  25. package/dist/index.js +1 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +600 -516
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/internals.js +1 -1
  30. package/dist/internals.js.map +1 -1
  31. package/dist/internals.mjs +101 -102
  32. package/dist/internals.mjs.map +1 -1
  33. package/dist/style.css.d.ts +4 -0
  34. package/dist/testing.js +1 -1
  35. package/dist/testing.mjs +11 -11
  36. package/package.json +8 -4
  37. package/dist/ElementFactory-Ckv6sSev.js.map +0 -1
  38. package/dist/ElementFactory-DEjwp-Wg.cjs.map +0 -1
  39. package/dist/ImportManager-64OYjELO.js +0 -222
  40. package/dist/ImportManager-64OYjELO.js.map +0 -1
  41. package/dist/ImportManager-wSzrR-5a.cjs +0 -2
  42. package/dist/ImportManager-wSzrR-5a.cjs.map +0 -1
  43. package/dist/ThemeContext-4mJ_y0Me.cjs +0 -2
  44. package/dist/ThemeContext-H0Z-MqqR.js +0 -1077
  45. package/dist/compose-DHBRwi_A.cjs +0 -33
  46. package/dist/compose-DHBRwi_A.cjs.map +0 -1
  47. package/dist/compose-DIPiisIw.js +0 -7690
  48. package/dist/compose-DIPiisIw.js.map +0 -1
@@ -1,8 +1,8 @@
1
- "use strict";const S=require("./HybridHistoryManager-BXD93pp8.cjs"),rn={canvas:{get selectionColor(){return S.getThemeAccentColor()},snapThreshold:8,snapGuideDash:[5,5],snapGuideWidth:1,selectionPadding:1,spacingIndicatorWidth:1.5,spacingLabelFontSize:11,spacingLabelFontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"}},et=2,Fn=6,tt=16,at=5,rt=5,Le=.5;function ie(i){return et/i}function st(i){return Fn/i}function it(i){return tt/i}function ot(i){return[at/i,rt/i]}function lt(i,n,e,t){i.save();const a=Le/t;i.translate(n,e),i.scale(a,a),i.strokeStyle="#000",i.lineWidth=1.5,i.lineCap="round",i.lineJoin="round",i.translate(-12,-12),i.beginPath(),i.moveTo(21,12),i.arc(12,12,9,0,-Math.PI/2,!0),i.bezierCurveTo(3.5,4.5,4,6,3,8),i.stroke(),i.beginPath(),i.moveTo(3,3),i.lineTo(3,8),i.lineTo(8,8),i.stroke(),i.beginPath(),i.moveTo(3,12),i.arc(12,12,9,Math.PI,Math.PI/2,!0),i.bezierCurveTo(20.5,19.5,20,18,21,16),i.stroke(),i.beginPath(),i.moveTo(16,16),i.lineTo(21,16),i.lineTo(21,21),i.stroke(),i.restore()}function ct(i,n,e,t=1,a="#3b82f6",r=!1){const s=it(t);i.save(),i.fillStyle="#fff",i.strokeStyle=a,i.lineWidth=r?ie(t)*1.25:ie(t),i.beginPath(),i.arc(n,e,s,0,Math.PI*2),i.fill(),i.stroke(),lt(i,n,e,t),i.restore()}const Se=Fn*2;class dt{constructor(){this.resizeHandles=[],this.rotationHandle=null,this.elementRotation=0,this.rotationAnchor={x:0,y:0}}update(n,e=1){const a="isCropping"in n&&n.isCropping?n.getBoundingBox():n.getVisualBoundingBox(),r=n.getRotationAnchor(),s=n.getEnabledAnchors();this.elementRotation=n.rotation,this.rotationAnchor=r;const o=rn.canvas.selectionPadding,l={x:a.x-o,y:a.y-o,width:a.width+o*2,height:a.height+o*2},c=S.calculateResizeHandles(l,n.rotation,r),d=Math.abs(n.rotation%360)>.1;this.resizeHandles=c.filter(f=>!(!s.includes(f.anchor)||d&&f.anchor.includes("middle"))),this.rotationHandle=S.calculateRotationHandlePosition(l,n.rotation,r,e)}render(n,e=!0,t=0,a=!1,r=!1,s=null,o=!1,l=null,c=1,d=!0){this.resizeHandles.forEach(f=>{if(o&&l&&f.anchor!==l.anchor)return;const h=!!(s&&s.anchor===f.anchor),u=!!(o&&l&&l.anchor===f.anchor);this.renderResizeHandle(n,f,h,u,c)}),d&&e&&this.rotationHandle&&!a&&!o&&this.renderRotationHandle(n,this.rotationHandle,r,c),d&&e&&this.rotationHandle&&a&&this.renderRotationTooltip(n,this.rotationHandle,t,c)}renderResizeHandle(n,e,t=!1,a=!1,r=1){n.save();const s=e.x*r,o=e.y*r;if(e.anchor.includes("middle")){const c=e.anchor==="middle-top"||e.anchor==="middle-bottom";n.translate(s,o),n.rotate(-this.elementRotation*Math.PI/180),c&&n.rotate(Math.PI/2),n.translate(-s,-o);const d=Se*.6,f=Se*1.4,h=d/2,u=s-d/2,g=o-f/2;n.fillStyle="#fff",n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=t||a?2.5:2,n.beginPath(),n.roundRect(u,g,d,f,h),n.fill(),n.stroke()}else n.fillStyle="#fff",n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=t||a?2.5:2,n.beginPath(),n.arc(s,o,Fn,0,Math.PI*2),n.fill(),n.stroke();n.restore()}renderRotationHandle(n,e,t=!1,a=1){n.save();const r=e.x*a,s=e.y*a,o=Fn*2.67;n.fillStyle="#fff",n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=t?2.5:2,n.beginPath(),n.arc(r,s,o,0,Math.PI*2),n.fill(),n.stroke();const l=Le;n.translate(r,s),n.scale(l,l),n.strokeStyle="#000",n.lineWidth=1.5,n.lineCap="round",n.lineJoin="round",n.translate(-12,-12),n.beginPath(),n.moveTo(21,12),n.arc(12,12,9,0,-Math.PI/2,!0),n.bezierCurveTo(3.5,4.5,4,6,3,8),n.stroke(),n.beginPath(),n.moveTo(3,3),n.lineTo(3,8),n.lineTo(8,8),n.stroke(),n.beginPath(),n.moveTo(3,12),n.arc(12,12,9,Math.PI,Math.PI/2,!0),n.bezierCurveTo(20.5,19.5,20,18,21,16),n.stroke(),n.beginPath(),n.moveTo(16,16),n.lineTo(21,16),n.lineTo(21,21),n.stroke(),n.restore()}renderRotationTooltip(n,e,t,a=1){n.save();const r=`${Math.round(t)}°`,s=r.length*8+12,o=22,l=e.x*a,c=e.y*a-35;n.shadowColor="rgba(0,0,0,0.3)",n.shadowBlur=3,n.shadowOffsetY=1,n.fillStyle="#333",n.beginPath(),n.roundRect(l-s/2,c,s,o,3),n.fill(),n.shadowColor="transparent",n.shadowBlur=0,n.shadowOffsetY=0,n.fillStyle="#fff",n.font="12px Arial",n.textAlign="center",n.textBaseline="middle",n.fillText(r,l,c+o/2),n.restore()}hitTestResize(n,e,t=1){const a=S.CORNER_HANDLE_HIT_RADIUS/t;for(const r of this.resizeHandles)if(S.hitTestCircle(n,e,r.x,r.y,a))return r;return null}hitTestRotation(n,e,t=1){if(!this.rotationHandle)return!1;const a=(Fn*2.67+2)/t;return S.hitTestCircle(n,e,this.rotationHandle.x,this.rotationHandle.y,a)}getRotationHandlePosition(){return this.rotationHandle}getCursor(n,e){const t=n.anchor.includes("middle")?"edge":"corner";return S.getCursorForWorldPosition(n.x,n.y,this.rotationAnchor.x,this.rotationAnchor.y,t,e,n.anchor)}}class ft{static calculateResize({element:n,handle:e,dx:t,dy:a,startData:r,snapSystem:s}){var D,P,M,W,B;const l=new S.Transform(n).worldDeltaToLocal(t,a),c=l.dx,d=l.dy,f=r.visualWidth??r.width??0,h=r.visualHeight??r.height??0,u=r.width??0,g=r.height??0;let m=f,p=h;e.anchor.includes("right")?m=f+c:e.anchor.includes("left")&&(m=f-c),e.anchor!=="middle-left"&&e.anchor!=="middle-right"&&(e.anchor.includes("bottom")?p=h+d:e.anchor.includes("top")&&(p=h-d));let y,b;if(e.anchor==="middle-left"||e.anchor==="middle-right"){const I=m-f;y=u+I,b=g}else if(e.anchor==="middle-top"||e.anchor==="middle-bottom"){const I=p-h;y=u,b=g+I}else{const I=m/f,H=p/h;y=u*I,b=g*H}const $=m,x=p;let w=!1;if(s&&n.transformType==="image"){const I=e.anchor??"",H=I==="top-left"||I==="top-right"||I==="bottom-left"||I==="bottom-right",q=I.startsWith("crop-");if(H&&!q){const Y=(D=s.activeSnaps)==null?void 0:D.x,nn=(P=s.activeSnaps)==null?void 0:P.y;if(!!Y||!!nn){const R=[Y,nn].find(F=>typeof F=="object"&&F!==null&&"frozenWidth"in F);if(R){const F=n,L=r.transformData,O=R.frozenWidth??((M=F.transformData)==null?void 0:M.width)??u,z=F.imageAspectRatio||(L!=null&&L.width&&(L!=null&&L.height)?L.width/L.height:null);let j=R.frozenHeight;j==null&&(z&&z!==0?j=O/z:(W=F.transformData)!=null&&W.height?j=F.transformData.height:j=g);const cn=u!==0?O/u:1,yn=g!==0?j/g:1;m=f*cn,p=h*yn,y=O,b=j,w=!0}}}}y=Math.max(50,y),b=Math.max(40,b);const v=n.clone(),C=v.resize(e.anchor,y,b,r);if(!e.anchor.includes("middle")&&((B=v.stroke)!=null&&B.enabled)&&r.strokeWidth!==void 0&&r.strokeWidth>0){const I=r.width??1,H=r.height??1,q=Math.sqrt(y/I*(b/H)),Y=Math.max(1,Math.round(r.strokeWidth*q*10)/10);v.stroke={...v.stroke,width:Y}}const T=w||C===!1,E=e.anchor.includes("top")||e.anchor.includes("bottom"),k="isCropping"in v&&v.isCropping,A="isGroup"in v&&v.isGroup;if(E&&!k&&!A){const I=n.getRotationAnchor(),H=this._calculateFixedCornerOffset({element:n,updatedElement:v,handle:e,rotationAnchor:I});v.x+=H.x,v.y+=H.y}return{element:v,isFrozen:T,unfrozenDimensions:w?{width:$,height:x}:void 0}}static _calculateFixedCornerOffset({element:n,updatedElement:e,handle:t,rotationAnchor:a}){const r=new S.Transform(n),{cos:s,sin:o}=r.getRenderingCosSin(),l=n.getVisualBoundingBox(),c=e.getVisualBoundingBox(),d=a,f=e.getRotationAnchor(),h=this._getFixedLocalCoords(t.anchor,l.width,l.height),u=h.x,g=h.y,m=l.x-d.x,p=l.y-d.y,y=m+u,b=p+g,$=y*s-b*o,x=y*o+b*s,w=d.x+$,v=d.y+x,C=this._getFixedLocalCoords(t.anchor,c.width,c.height),_=C.x,T=C.y,E=c.x-f.x,k=c.y-f.y,A=E+_,D=k+T,P=A*s-D*o,M=A*o+D*s,W=f.x+P,B=f.y+M;return{x:w-W,y:v-B}}static _getFixedLocalCoords(n,e,t){const a={x:0,y:0};switch(n){case"top-left":a.x=e,a.y=t;break;case"top-right":a.x=0,a.y=t;break;case"bottom-left":a.x=e,a.y=0;break;case"bottom-right":a.x=0,a.y=0;break;case"middle-left":a.x=e,a.y=t/2;break;case"middle-right":a.x=0,a.y=t/2;break;case"middle-top":a.x=e/2,a.y=t;break;case"middle-bottom":a.x=e/2,a.y=0;break}return a}}class Ne{constructor(){this.hooks={beforeResize:[],afterResize:[],beforePositionUpdate:[],afterPositionUpdate:[]}}addHook(n,e){if(!this.hooks[n])throw new Error(`Invalid hook stage: ${n}`);this.hooks[n].push(e)}removeHook(n,e){if(!this.hooks[n])return;const t=this.hooks[n].indexOf(e);t!==-1&&this.hooks[n].splice(t,1)}clearHooks(n){this.hooks[n]&&(this.hooks[n]=[])}clearAllHooks(){Object.keys(this.hooks).forEach(n=>{this.hooks[n]=[]})}runHooks(n,e){return this.hooks[n]?this.hooks[n].reduce((t,a)=>{const r=a(t);return r!==void 0?r:t},e):e}executeResize(n){const e=this.runHooks("beforeResize",n);let t=ft.calculateResize({...e,snapSystem:n.snapSystem});return t.handle=n.handle,t.startData=n.startData,t=this.runHooks("afterResize",t),t}executePositionUpdate(n,e){const t=this.runHooks("beforePositionUpdate",{position:n,element:e});return this.runHooks("afterPositionUpdate",t).position}}const ut=new Ne;class ht{constructor(n=null){this.state="IDLE",this.context={mode:null,startX:0,startY:0,startData:null,activeHandle:null,element:null},this.snapHandler=null,this.resizePipeline=n}setSnapHandler(n){this.snapHandler=n}setResizePipeline(n){this.resizePipeline=n}getState(){return this.state}getContext(){return this.context}isInteracting(){return this.state!=="IDLE"}startDrag(n,e,t,a=null){this.state="DRAGGING";const r=n.getTransformStartData();let s=r;if(a==="crop-image-drag"&&n.transformData){const o=n.transformData;s={...r,cropX:o.cropX,cropY:o.cropY,cropWidth:o.cropWidth,cropHeight:o.cropHeight}}this.context={mode:"drag",dragMode:a,startX:e,startY:t,startData:s,activeHandle:null,element:n}}getDragMode(){return this.context.dragMode}resetDragStart(n,e){this.state==="DRAGGING"&&(this.context.startX=n,this.context.startY=e)}updateDrag(n,e,t=null){if(this.state!=="DRAGGING")throw new Error("Cannot update drag: not in DRAGGING state");const a=n-this.context.startX,r=e-this.context.startY,s=this.context.startData;let o=s.x+a,l=s.y+r;if(this.snapHandler&&this.snapHandler.snapPosition&&this.context.element){const c=this.snapHandler.snapPosition({x:o,y:l},this.context.element,t);o=c.x,l=c.y}return{x:o,y:l}}startResize(n,e,t,a,r,s){this.state="RESIZING";const o=n.getTransformStartData(),l=n.clone();(e.anchor==="top-left"||e.anchor==="top-right"||e.anchor==="bottom-left"||e.anchor==="bottom-right")&&o.lineCount!==void 0&&l.transformType==="custom"&&(l._lockedLineCount=o.lineCount),this.context={mode:"resize",startX:t,startY:a,startData:{...o,visualX:s.x,visualY:s.y,visualWidth:s.width,visualHeight:s.height,bboxX:r.x,bboxY:r.y},activeHandle:e,element:l}}updateResize(n,e){if(this.state!=="RESIZING")throw new Error("Cannot update resize: not in RESIZING state");const t=n-this.context.startX,a=e-this.context.startY;return{dx:t,dy:a}}adjustResizeStart(n,e){this.state==="RESIZING"&&(this.context.startX+=n,this.context.startY+=e)}getResizeContext(){if(this.state!=="RESIZING")throw new Error("Cannot get resize context: not in RESIZING state");return{element:this.context.element,handle:this.context.activeHandle,startData:this.context.startData}}updateResizeElement(n){this.state==="RESIZING"&&(this.context.element=n)}resetResizeStartData(n,e,t){if(this.state!=="RESIZING")return;const a=n.getBoundingBox(),r=n.getVisualBoundingBox(),s=n.getTransformStartData();this.context.startX=e,this.context.startY=t,this.context.startData={...s,visualX:r.x,visualY:r.y,visualWidth:r.width,visualHeight:r.height,bboxX:a.x,bboxY:a.y}}startRotate(n,e,t,a,r){this.state="ROTATING",this.context={mode:"rotate",startX:e,startY:t,startData:{startAngle:a,currentRotation:r,elementData:n.getTransformStartData()},activeHandle:null,element:n}}updateRotate(n,e,t,a){if(this.state!=="ROTATING")throw new Error("Cannot update rotate: not in ROTATING state");const r=this.context.startData,o=(S.calculateAngle(t,a,n,e)-r.startAngle)*180/Math.PI;let l=r.currentRotation-o;return l=(l%360+360)%360,l>180&&(l-=360),this.snapHandler&&this.snapHandler.snapRotation&&this.context.element?this.snapHandler.snapRotation(l,this.context.element):l}getRotationContext(){if(this.state!=="ROTATING")throw new Error("Cannot get rotation context: not in ROTATING state");const n=this.context.startData;return{startAngle:n.startAngle,currentRotation:n.currentRotation}}startPinch(n,e,t){this.state="PINCHING";const a={x:(e.x+t.x)/2,y:(e.y+t.y)/2},r=t.x-e.x,s=t.y-e.y,o=Math.hypot(r,s),l=Math.atan2(s,r),c={elementData:n.getTransformStartData(),startCentroid:a,startDistance:o,startAngle:l};this.context={mode:"pinch",startX:a.x,startY:a.y,startData:c,activeHandle:null,element:n.clone()}}updatePinch(n,e){if(this.state!=="PINCHING")throw new Error("Cannot update pinch: not in PINCHING state");const t=this.context.startData,a={x:(n.x+e.x)/2,y:(n.y+e.y)/2},r=e.x-n.x,s=e.y-n.y,o=Math.hypot(r,s),l=Math.atan2(s,r),c=Math.max(t.startDistance,1e-4),d=o/c,f=Math.max(d,.05),h=l-t.startAngle;return{scale:f,rotationDelta:h,startCentroid:t.startCentroid,currentCentroid:a}}getPinchContext(){if(this.state!=="PINCHING")throw new Error("Cannot get pinch context: not in PINCHING state");const n=this.context.startData;return{element:this.context.element,startData:n.elementData}}end(){this.state="IDLE",this.context={mode:null,startX:0,startY:0,startData:null,activeHandle:null,element:null}}cancel(){this.end()}getActiveHandle(){return this.context.activeHandle}getMode(){return this.context.mode}}class wn{static resolve(n){return n.getRotationAnchor()}static getSnapAnchors(n){const e=n.getVisualBoundingBox(),t={topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomLeft:{x:e.x,y:e.y+e.height},bottomRight:{x:e.x+e.width,y:e.y+e.height},topCenter:{x:e.x+e.width/2,y:e.y},rightCenter:{x:e.x+e.width,y:e.y+e.height/2},bottomCenter:{x:e.x+e.width/2,y:e.y+e.height},leftCenter:{x:e.x,y:e.y+e.height/2},center:{x:e.x+e.width/2,y:e.y+e.height/2},rotation:this.resolve(n)};if(n.rotation!==0){const a=t.rotation,r=S.RotationUtils.toRadiansInverse(n.rotation);Object.keys(t).forEach(s=>{if(s==="rotation")return;const o=t[s],l=o.x-a.x,c=o.y-a.y,d=l*Math.cos(r)-c*Math.sin(r),f=l*Math.sin(r)+c*Math.cos(r);t[s]={x:a.x+d,y:a.y+f}})}return t}static getEdgeLines(n){const e=this.getSnapAnchors(n);return{top:{start:e.topLeft,end:e.topRight},right:{start:e.topRight,end:e.bottomRight},bottom:{start:e.bottomRight,end:e.bottomLeft},left:{start:e.bottomLeft,end:e.topLeft}}}static getAnchorTypes(){return["topLeft","topCenter","topRight","rightCenter","bottomRight","bottomCenter","bottomLeft","leftCenter","center","rotation"]}static hasCustomRotationAnchor(n){const e=n.getVisualBoundingBox(),t={x:e.x+e.width/2,y:e.y+e.height/2},a=this.resolve(n),r=.001;return Math.abs(a.x-t.x)>r||Math.abs(a.y-t.y)>r}}class Ce{constructor(n){this.cellSize=n,this.cells=new Map,this.idIndex=new Map}clear(){this.cells.clear(),this.idIndex.clear()}insert(n){const e=this.getCellKey(n.x,n.y);let t=this.cells.get(e);t||(t=new Set,this.cells.set(e,t)),t.add(n);let a=this.idIndex.get(n.id);a||(a=new Set,this.idIndex.set(n.id,a)),a.add(e)}removeById(n){const e=this.idIndex.get(n);if(e){for(const t of e){const a=this.cells.get(t);if(a){for(const r of a)r.id===n&&a.delete(r);a.size===0&&this.cells.delete(t)}}this.idIndex.delete(n)}}queryNear(n,e,t,a){const r=[],s=Math.floor((n-t)/this.cellSize),o=Math.floor((n+t)/this.cellSize),l=Math.floor((e-t)/this.cellSize),c=Math.floor((e+t)/this.cellSize);for(let d=s;d<=o;d++)for(let f=l;f<=c;f++){const h=`${d},${f}`,u=this.cells.get(h);if(u)for(const g of u){if(a!==void 0&&g.id===a)continue;const m=g.x-n,p=g.y-e;m*m+p*p<=t*t&&r.push(g)}}return r}queryNearAxis(n,e,t,a){const r=[];if(n==="x"){const s=Math.floor((e-t)/this.cellSize),o=Math.floor((e+t)/this.cellSize);for(const[l,c]of this.cells){const d=l.indexOf(","),f=parseInt(l.substring(0,d),10);if(!(f<s||f>o))for(const h of c)a!==void 0&&h.id===a||Math.abs(h.x-e)<=t&&r.push(h)}}else{const s=Math.floor((e-t)/this.cellSize),o=Math.floor((e+t)/this.cellSize);for(const[l,c]of this.cells){const d=l.indexOf(","),f=parseInt(l.substring(d+1),10);if(!(f<s||f>o))for(const h of c)a!==void 0&&h.id===a||Math.abs(h.y-e)<=t&&r.push(h)}}return r}rebuild(n){this.clear();for(const e of n)this.insert(e)}getCellKey(n,e){return`${Math.floor(n/this.cellSize)},${Math.floor(e/this.cellSize)}`}}function fn(i){const n=i.transformData;if(n&&"width"in n&&typeof n.width=="number")return n.width}function Sn(i){const n=i.transformData;if(n&&"height"in n&&typeof n.height=="number")return n.height}function In(i,n){const e=i.transformData;return e&&"width"in e?(e.width=n,!0):!1}function zn(i,n){const e=i.transformData;return e&&"height"in e?(e.height=n,!0):!1}class pt{constructor(n={}){this._extraSnapRects=[],this.snapThreshold=n.snapThreshold||rn.canvas.snapThreshold,this.enabled=n.enabled!==!1,this.showGuides=n.showGuides!==!1,this.guides=[],this.activeSnaps={x:null,y:null},this.stickyThreshold=n.stickyThreshold||15,this._spatialGrid=new Ce(Math.max(this.snapThreshold*2,16)),this._anchorMetadata=new Map}setEnabled(n){this.enabled=n}setSnapThreshold(n){this.snapThreshold=n,this._spatialGrid=new Ce(Math.max(n*2,16))}getGuides(){return this.guides}clearGuides(){this.guides=[]}clearSnapState(){this.activeSnaps.x=null,this.activeSnaps.y=null}setExtraSnapRects(n){this._extraSnapRects=n}_populateSpatialGrid(n){this._spatialGrid.clear(),this._anchorMetadata.clear();for(const e of n){const t=wn.getSnapAnchors(e);for(const[a,r]of Object.entries(t)){const s=`${e.id}:${a}`,o={x:r.x,y:r.y,id:s};this._spatialGrid.insert(o),this._anchorMetadata.set(s,{elementId:e.id,anchorKey:a,point:r})}}for(const e of this._extraSnapRects){const t=e.x+e.width/2,a=e.y+e.height/2,r=e.x+e.width,s=e.y+e.height,o={topLeft:{x:e.x,y:e.y},topRight:{x:r,y:e.y},bottomLeft:{x:e.x,y:s},bottomRight:{x:r,y:s},topCenter:{x:t,y:e.y},rightCenter:{x:r,y:a},bottomCenter:{x:t,y:s},leftCenter:{x:e.x,y:a},center:{x:t,y:a}},l=`__snap-rect:${e.id}`;for(const[c,d]of Object.entries(o)){const f=`${l}:${c}`;this._spatialGrid.insert({x:d.x,y:d.y,id:f}),this._anchorMetadata.set(f,{elementId:l,anchorKey:c,point:d})}}}snapPosition(n,e,t){if(!this.enabled||!t)return this.clearGuides(),n;const a=e.clone();a.x=n.x,a.y=n.y;const r=wn.getSnapAnchors(a),s=t.filter(b=>b.id!==e.id);this._populateSpatialGrid(s);let o=null,l=null,c=1/0,d=1/0;const f=[],h=[],u=[];for(const[b,$]of Object.entries(r)){const x=this._spatialGrid.queryNearAxis("x",$.x,this.snapThreshold);for(const v of x){const C=this._anchorMetadata.get(v.id);if(!C)continue;const _=C.point,T=C.anchorKey,E=Math.abs($.x-_.x);if(E<this.snapThreshold){const k={snapTo:_.x,offset:$.x-n.x,distance:E,guide:{type:"vertical",x:_.x,y1:Math.min($.y,_.y)-50,y2:Math.max($.y,_.y)+50,movingKey:b,otherKey:T}};f.push(k),E<c&&(c=E,o=k)}}const w=this._spatialGrid.queryNearAxis("y",$.y,this.snapThreshold);for(const v of w){const C=this._anchorMetadata.get(v.id);if(!C)continue;const _=C.point,T=C.anchorKey,E=Math.abs($.y-_.y);if(E<this.snapThreshold){const k={snapTo:_.y,offset:$.y-n.y,distance:E,guide:{type:"horizontal",y:_.y,x1:Math.min($.x,_.x)-50,x2:Math.max($.x,_.x)+50,movingKey:b,otherKey:T}};h.push(k),E<d&&(d=E,l=k)}}}let g=n.x,m=n.y;o&&(g=o.snapTo-o.offset),l&&(m=l.snapTo-l.offset);const p=new Map,y=new Map;for(const b of f){const $=p.get(b.snapTo);(!$||b.distance<$.distance)&&p.set(b.snapTo,b)}for(const b of h){const $=y.get(b.snapTo);(!$||b.distance<$.distance)&&y.set(b.snapTo,b)}for(const b of p.values())u.push(b.guide);for(const b of y.values())u.push(b.guide);return this.guides=u,{x:g,y:m}}_calculateFrozenFontSizeAtSnap(n,e,t,a,r){if(!r)return n.fontSize??0;const s=a!=null&&a.anchor?String(a.anchor):"";if(!(a&&(s.includes("top")||s.includes("bottom"))))return r.fontSize??0;const l=fn(n)??n.width??r.width;let c=l;s.includes("right")&&e!==0?c=l+e:s.includes("left")&&e!==0&&(c=l-e);const d=c/r.width;return(r.fontSize??0)*d}_isPositionBasedSnap(n,e){return e==="x"?!1:e==="y"?!(Sn(n)!==void 0||n.height!==void 0&&typeof n.height=="number"):!1}_getSnapKeysForHandle(n){return!n||!n.anchor?["topLeft","topRight","bottomLeft","bottomRight"]:n.anchor==="top-left"||n.anchor==="topLeft"?["topLeft"]:n.anchor==="top-right"||n.anchor==="topRight"?["topRight"]:n.anchor==="bottom-left"||n.anchor==="bottomLeft"?["bottomLeft"]:n.anchor==="bottom-right"||n.anchor==="bottomRight"?["bottomRight"]:n.anchor.includes("left")?["topLeft","bottomLeft"]:n.anchor.includes("right")?["topRight","bottomRight"]:n.anchor.includes("top")?["topLeft","topRight"]:n.anchor.includes("bottom")?["bottomLeft","bottomRight"]:[]}_getTargetSnapKeys(){return["topLeft","topRight","bottomLeft","bottomRight"]}_findXSnaps(n,e,t,a){const r=[],s=new Set(a);for(const o of t){const l=n[o];if(!l)continue;const c=this._spatialGrid.queryNearAxis("x",l.x,this.snapThreshold);for(const d of c){const f=this._anchorMetadata.get(d.id);if(!f||!s.has(f.anchorKey))continue;const h=f.point,u=f.anchorKey,g=Math.abs(l.x-h.x);g<this.snapThreshold&&r.push({distance:g,snapTo:h.x,currentValue:l.x,guide:{type:"vertical",x:h.x,y1:Math.min(l.y,h.y)-50,y2:Math.max(l.y,h.y)+50,movingKey:o,otherKey:u}})}}return r}_findYSnaps(n,e,t,a){const r=[],s=new Set(a);for(const o of t){const l=n[o];if(!l)continue;const c=this._spatialGrid.queryNearAxis("y",l.y,this.snapThreshold);for(const d of c){const f=this._anchorMetadata.get(d.id);if(!f||!s.has(f.anchorKey))continue;const h=f.point,u=f.anchorKey,g=Math.abs(l.y-h.y);g<this.snapThreshold&&r.push({distance:g,snapTo:h.y,currentValue:l.y,guide:{type:"horizontal",y:h.y,x1:Math.min(l.x,h.x)-50,x2:Math.max(l.x,h.x)+50,movingKey:o,otherKey:u}})}}return r}_prioritizeSnaps(n,e,t){if(!e||!e.anchor){n.sort((a,r)=>a.distance-r.distance);return}t==="x"?e.anchor.includes("left")?n.sort((a,r)=>{const s=a.guide.movingKey.includes("left")?-1e3:0,o=r.guide.movingKey.includes("left")?-1e3:0;return a.distance+s-(r.distance+o)}):e.anchor.includes("right")?n.sort((a,r)=>{const s=a.guide.movingKey.includes("right")?-1e3:0,o=r.guide.movingKey.includes("right")?-1e3:0;return a.distance+s-(r.distance+o)}):n.sort((a,r)=>a.distance-r.distance):t==="y"&&(e.anchor.includes("top")?n.sort((a,r)=>{const s=a.guide.movingKey.includes("top")?-1e3:0,o=r.guide.movingKey.includes("top")?-1e3:0;return a.distance+s-(r.distance+o)}):e.anchor.includes("bottom")?n.sort((a,r)=>{const s=a.guide.movingKey.includes("bottom")?-1e3:0,o=r.guide.movingKey.includes("bottom")?-1e3:0;return a.distance+s-(r.distance+o)}):n.sort((a,r)=>a.distance-r.distance))}_createGuideForSnap(n,e,t,a,r){const s=t[e];if(!s)return null;if(r==="x"){let o=1/0,l=-1/0;for(const c of Object.values(t))Math.abs(c.x-n.snapTo)<5&&(o=Math.min(o,c.y),l=Math.max(l,c.y));for(const c of a){const d=wn.getSnapAnchors(c);for(const f of Object.values(d))Math.abs(f.x-n.snapTo)<5&&(o=Math.min(o,f.y),l=Math.max(l,f.y))}return(!isFinite(o)||!isFinite(l))&&(o=s.y,l=s.y),{snapTo:n.snapTo,currentValue:s.x,distance:0,guide:{type:"vertical",x:n.snapTo,y1:o-50,y2:l+50,movingKey:e,otherKey:"snap"}}}else if(r==="y"){let o=1/0,l=-1/0;for(const c of Object.values(t))Math.abs(c.y-n.snapTo)<5&&(o=Math.min(o,c.x),l=Math.max(l,c.x));for(const c of a){const d=wn.getSnapAnchors(c);for(const f of Object.values(d))Math.abs(f.y-n.snapTo)<5&&(o=Math.min(o,f.x),l=Math.max(l,f.x))}return(!isFinite(o)||!isFinite(l))&&(o=s.x,l=s.x),{snapTo:n.snapTo,currentValue:s.y,distance:0,guide:{type:"horizontal",y:n.snapTo,x1:o-50,x2:l+50,movingKey:e,otherKey:"snap"}}}return null}_getAdjustedStickyThreshold(n,e){const t=e.getVisualBoundingBox(),a=t.width/t.height;let r=this.stickyThreshold;return n==="x"?a>1&&(r=this.stickyThreshold/Math.sqrt(a)):n==="y"&&a<1&&(r=this.stickyThreshold*Math.sqrt(a)),r}_calculateFrozenDimensionsAtSnap(n,e,t,a,r){const s=fn(n)??n.width??0,o=Sn(n)??n.height??0;let l=s,c=o;const d=n.transformType==="image",f=d?n.imageAspectRatio||(s&&o?s/o:null):null,h=a.toLowerCase();return e==="x"?h.includes("right")?(l=s+t,d&&f&&(c=l/f)):h.includes("left")&&(l=s-t,d&&f&&(c=l/f)):e==="y"&&(h.includes("bottom")?(c=o+t,d&&f&&(l=c*f)):h.includes("top")&&(c=o-t,d&&f&&(l=c*f))),{frozenWidth:l,frozenHeight:c}}_processStickySnap(n,e,t,a,r,s,o){const l=this.activeSnaps[n];let c=0,d=null;if(l){const f=e[l.anchorKey];if(f){const h=n==="x"?f.x:f.y,u=Math.abs(h-l.snapTo),g=this._getAdjustedStickyThreshold(n,a);if(u<g){if(c=l.snapTo-h,!(n==="y"&&l.isPositionBasedSnap)){const p=this._calculateFrozenFontSizeAtSnap(a,n==="x"?c:0,n==="y"?c:0,r,s);p!==l.frozenFontSize&&(l.frozenFontSize=p)}d=this._createGuideForSnap(l,l.anchorKey,e,o,n)}else{const m=l;if(this.activeSnaps[n]=null,t.length>0&&t[0].distance<this.snapThreshold){d=t[0],c=d.snapTo-d.currentValue;const p=m&&m.anchorKey===d.guide.movingKey&&Math.abs(m.snapTo-d.snapTo)<1,y=p?m.frozenFontSize:this._calculateFrozenFontSizeAtSnap(a,n==="x"?c:0,n==="y"?c:0,r,s),b=this._isPositionBasedSnap(a,n);let $;p?$=m.frozenPosition:b?$={x:n==="x"?a.x+c:a.x,y:n==="y"?a.y+c:a.y}:$={x:a.x,y:a.y};const x=this._calculateFrozenDimensionsAtSnap(a,n,c,d.guide.movingKey,r);this.activeSnaps[n]={snapTo:d.snapTo,anchorKey:d.guide.movingKey,frozenFontSize:y,frozenWidth:x.frozenWidth,frozenHeight:x.frozenHeight,frozenPosition:$,isPositionBasedSnap:b}}}}else this.activeSnaps[n]=null}else if(t.length>0&&t[0].distance<this.snapThreshold){d=t[0],c=d.snapTo-d.currentValue;const f=this.activeSnaps[n],h=f&&f.anchorKey===d.guide.movingKey&&Math.abs(f.snapTo-d.snapTo)<1,u=h?f.frozenFontSize:this._calculateFrozenFontSizeAtSnap(a,n==="x"?c:0,n==="y"?c:0,r,s),g=this._isPositionBasedSnap(a,n);let m;h?m=f.frozenPosition:g?m={x:n==="x"?a.x+c:a.x,y:n==="y"?a.y+c:a.y}:m={x:a.x,y:a.y};const p=this._calculateFrozenDimensionsAtSnap(a,n,c,d.guide.movingKey,r);this.activeSnaps[n]={snapTo:d.snapTo,anchorKey:d.guide.movingKey,frozenFontSize:u,frozenWidth:p.frozenWidth,frozenHeight:p.frozenHeight,frozenPosition:m,isPositionBasedSnap:g}}return{snapDelta:c,bestSnap:d}}_adjustElementForRightResize(n,e,t){const a=n.getVisualBoundingBox(),r=n.transformType==="image";if(!r){const s=fn(n);s!==void 0?In(n,s+e):n.width!==void 0&&(n.width+=e)}if(t.anchor==="middle-right"){const s=S.RotationUtils.toRadiansInverse(n.rotation),o=Math.cos(s),l=Math.sin(s);n.x+=e/2*o,n.y+=e/2*l}else if(!r){const o=n.getVisualBoundingBox().x-a.x;o!==0&&(n.x-=o)}}_adjustElementForLeftResize(n,e,t){const a=n.getVisualBoundingBox(),r=n.transformType==="image";if(!r){const s=fn(n);s!==void 0?In(n,s-e):n.width!==void 0&&(n.width-=e)}if(t.anchor==="middle-left"){const s=S.RotationUtils.toRadiansInverse(n.rotation),o=Math.cos(s),l=Math.sin(s);n.x+=e/2*o,n.y+=e/2*l}else if(n.x+=e,!r){const s=n.getVisualBoundingBox(),o=s.x+s.width-(a.x+a.width);o!==0&&(n.x-=o)}}_adjustElementForBottomResize(n,e,t){const a=n.getVisualBoundingBox(),r=n.transformType==="image";if(!r){const l=Sn(n);l!==void 0?zn(n,l+e):n.height!==void 0&&(n.height+=e)}const s=n.getVisualBoundingBox(),o=Math.abs(s.height-a.height)>.01;if(t.anchor==="middle-bottom"){const l=S.RotationUtils.toRadiansInverse(n.rotation),c=Math.cos(l),d=Math.sin(l);n.x-=e/2*d,n.y+=e/2*c}else if(!r&&o){const l=s.y-a.y;l!==0&&(n.y-=l)}else r||(n.y+=e)}_adjustElementForTopResize(n,e,t){const a=n.getVisualBoundingBox(),r=n.transformType==="image";if(!r){const l=Sn(n);l!==void 0?zn(n,l-e):n.height!==void 0&&(n.height-=e)}const s=n.getVisualBoundingBox(),o=Math.abs(s.height-a.height)>.01;if(t.anchor==="middle-top"){const l=S.RotationUtils.toRadiansInverse(n.rotation),c=Math.cos(l),d=Math.sin(l);n.x-=e/2*d,n.y+=e/2*c}else{const l=!r&&o;if(n.y+=e,l){const c=n.getVisualBoundingBox(),d=c.y+c.height-(a.y+a.height);d!==0&&(n.y-=d)}}}snapDimensions(n,e,t=null){var v,C,_,T,E;if(!this.enabled||!e)return this.clearGuides(),n;const{element:a}=n,r=n.handle;let s;const o=a.transformType==="image",l=this.activeSnaps.x!==null||this.activeSnaps.y!==null;if(o&&l&&n.isFrozen&&n.unfrozenDimensions){const k=a.clone();if(k.transformData){const A=a.getVisualBoundingBox(),D=A.width,P=A.height,M=(t==null?void 0:t.width)??a.width??0,W=(t==null?void 0:t.height)??a.height??0,B=(t==null?void 0:t.visualWidth)??D,I=(t==null?void 0:t.visualHeight)??P,H=n.unfrozenDimensions.width/B,q=n.unfrozenDimensions.height/I;In(k,M*H),zn(k,W*q)}s=wn.getSnapAnchors(k)}else s=wn.getSnapAnchors(a);const c=e.filter(k=>k.id!==a.id);if(c.length===0)return this.clearGuides(),n;this._populateSpatialGrid(c);const d=this._getSnapKeysForHandle(r),f=this._getTargetSnapKeys(),h=this._findXSnaps(s,c,d,f),u=this._findYSnaps(s,c,d,f);this._prioritizeSnaps(h,r,"x"),this._prioritizeSnaps(u,r,"y");const g=this._processStickySnap("x",s,h,a,r,t,c),m=this._processStickySnap("y",s,u,a,r,t,c),p=g.snapDelta,y=m.snapDelta,b=g.bestSnap,$=m.bestSnap,x=[];b&&x.push(b.guide),$&&x.push($.guide),this.guides=x,x.length>0;const w=r&&(r.anchor==="top-left"||r.anchor==="top-right"||r.anchor==="bottom-left"||r.anchor==="bottom-right");if(o&&w&&(p!==0||y!==0))return n;if(p!==0||y!==0){const k=a.clone(),A=this.activeSnaps.x||this.activeSnaps.y,D=(A==null?void 0:A.frozenFontSize)??a.fontSize??0,P=(A==null?void 0:A.frozenWidth)??fn(a)??a.width??0,M=(A==null?void 0:A.frozenHeight)??Sn(a)??a.height??0,W=(A==null?void 0:A.frozenPosition)??{x:a.x,y:a.y},B=k.isCropping&&!String(r.anchor).startsWith("crop-");if(!B)if(r&&r.anchor){if(p!==0){const R=(v=this.activeSnaps.x)==null?void 0:v.anchorKey,F=R==null?void 0:R.toLowerCase();F&&F.includes("right")?this._adjustElementForRightResize(k,p,r):F&&F.includes("left")?this._adjustElementForLeftResize(k,p,r):k.x+=p}if(y!==0){const R=(C=this.activeSnaps.y)==null?void 0:C.anchorKey,F=R==null?void 0:R.toLowerCase();F&&F.includes("bottom")?this._adjustElementForBottomResize(k,y,r):F&&F.includes("top")?this._adjustElementForTopResize(k,y,r):k.y+=y}}else k.x+=p,k.y+=y;k.fontSize!==void 0&&(k.fontSize=D);const I=k.transformType==="image",H=this.activeSnaps.x!==null||this.activeSnaps.y!==null;if(I&&H){if(fn(k)!==void 0){const R=this.activeSnaps.x||this.activeSnaps.y;let F=P,L=M;R&&(F=R.frozenWidth??F,L=R.frozenHeight??L);const O=fn(a),z=Sn(a),j=k.imageAspectRatio||(O&&z?O/z:null);j&&j!==0&&(L=F/j),In(k,F),zn(k,L),R&&(R.frozenWidth=F,R.frozenHeight=L)}}else(((_=this.activeSnaps.y)==null?void 0:_.isPositionBasedSnap)||!1)&&(fn(k)!==void 0?In(k,P):k.width!==void 0&&(k.width=P));const q=r&&(r.anchor==="middle-left"||r.anchor==="middle-right"),Y=r&&(r.anchor==="middle-top"||r.anchor==="middle-bottom"),nn=((T=this.activeSnaps.x)==null?void 0:T.isPositionBasedSnap)||!1,N=((E=this.activeSnaps.y)==null?void 0:E.isPositionBasedSnap)||!1;return(p===0||nn)&&!q&&!Y&&!B&&(k.x=W.x),(y===0||N)&&!Y&&!q&&!B&&(k.y=W.y),{...n,element:k,snapAdjustment:{dx:p,dy:y},isInStickySnap:!0}}return n}snapRotation(n,e,t){if(!this.enabled)return n;const a=[0,45,90,135,180,225,270,315,360],r=5;for(const s of a)if(S.isNear(n,s,r))return s;return n}}class gt{constructor(n={}){this.lastSnapTarget=null,this.detectionThreshold=n.detectionThreshold||100,this.minDistance=n.minDistance||10,this.enabled=n.enabled!==!1,this.showLabels=n.showLabels!==!1,this.indicators=[]}setEnabled(n){this.enabled=n}setDetectionThreshold(n){this.detectionThreshold=n}getIndicators(){return this.indicators}clearIndicators(){this.indicators=[],this.lastSnapTarget=null}snapToSpacing(n,e,t){if(!this.enabled||!t)return n;const a=S.SPACING_SNAP_THRESHOLD,r=t.filter(p=>p.id!==e.id);if(r.length===0)return n;const s=e.clone();s.x=n.x,s.y=n.y;const o=s.getVisualBoundingBox(),l=o.x-n.x,c=o.y-n.y;let d=n.x,f=n.y,h=!1,u=!1;const g=r.filter(p=>{const y=p.getVisualBoundingBox();return!(o.x+o.width<y.x||o.x>y.x+y.width)});if(g.sort((p,y)=>{const b=p.getVisualBoundingBox(),$=y.getVisualBoundingBox();return b.y-$.y}),g.length>=1){let p=null,y=null;for(const x of g){const w=x.getVisualBoundingBox();w.y+w.height<=o.y?(!p||w.y>p.getVisualBoundingBox().y)&&(p=x):w.y>=o.y+o.height&&(!y||w.y<y.getVisualBoundingBox().y)&&(y=x)}const b=[];for(let x=0;x<g.length-1;x++){const w=g[x].getVisualBoundingBox(),C=g[x+1].getVisualBoundingBox().y-(w.y+w.height);b.push(C)}let $=null;if(p){const x=p.getVisualBoundingBox(),w=o.y-(x.y+x.height);for(const v of b)if(Math.abs(w-v)<=a){$=v;break}}if(!$&&y){const w=y.getVisualBoundingBox().y-(o.y+o.height);for(const v of b)if(Math.abs(w-v)<=a){$=v;break}}if($!==null&&$>0){if(p){const x=p.getVisualBoundingBox(),w=o.y-(x.y+x.height);Math.abs(w-$)<=a&&(f=x.y+x.height+$-c,u=!0)}if(!u&&y){const x=y.getVisualBoundingBox(),w=x.y-(o.y+o.height);Math.abs(w-$)<=a&&(f=x.y-o.height-$-c,u=!0)}}}const m=r.filter(p=>{const y=p.getVisualBoundingBox();return!(o.y+o.height<y.y||o.y>y.y+y.height)});if(m.sort((p,y)=>{const b=p.getVisualBoundingBox(),$=y.getVisualBoundingBox();return b.x-$.x}),m.length>=1){let p=null,y=null;for(const x of m){const w=x.getVisualBoundingBox();w.x+w.width<=o.x?(!p||w.x>p.getVisualBoundingBox().x)&&(p=x):w.x>=o.x+o.width&&(!y||w.x<y.getVisualBoundingBox().x)&&(y=x)}const b=[];for(let x=0;x<m.length-1;x++){const w=m[x].getVisualBoundingBox(),C=m[x+1].getVisualBoundingBox().x-(w.x+w.width);b.push(C)}let $=null;if(p){const x=p.getVisualBoundingBox(),w=o.x-(x.x+x.width);for(const v of b)if(Math.abs(w-v)<=a){$=v;break}}if(!$&&y){const w=y.getVisualBoundingBox().x-(o.x+o.width);for(const v of b)if(Math.abs(w-v)<=a){$=v;break}}if($!==null&&$>0){if(p){const x=p.getVisualBoundingBox(),w=o.x-(x.x+x.width);Math.abs(w-$)<=a&&(d=x.x+x.width+$-l,h=!0)}if(!h&&y){const x=y.getVisualBoundingBox(),w=x.x-(o.x+o.width);Math.abs(w-$)<=a&&(d=x.x-o.width-$-l,h=!0)}}}return this.lastSnapTarget=h||u?{x:d,y:f}:null,{x:d,y:f}}detectSpacing(n,e,t=!1){if(!this.enabled||!e)return this.clearIndicators(),[];const a=e.filter(f=>f.id!==n.id);if(a.length===0)return this.clearIndicators(),[];const r=n.getVisualBoundingBox(),s=[],o=[],l=[],c=[];for(const f of a){const h=f.getVisualBoundingBox(),u=r.x-(h.x+h.width),g=h.x-(r.x+r.width),m=r.y-(h.y+h.height),p=h.y-(r.y+r.height),y=!(r.y+r.height<h.y||r.y>h.y+h.height),b=!(r.x+r.width<h.x||r.x>h.x+h.width);u>=this.minDistance&&u<this.detectionThreshold&&y&&s.push({element:f,distance:u}),g>=this.minDistance&&g<this.detectionThreshold&&y&&o.push({element:f,distance:g}),m>=this.minDistance&&m<this.detectionThreshold&&b&&l.push({element:f,distance:m}),p>=this.minDistance&&p<this.detectionThreshold&&b&&c.push({element:f,distance:p})}s.sort((f,h)=>f.distance-h.distance),o.sort((f,h)=>f.distance-h.distance),l.sort((f,h)=>f.distance-h.distance),c.sort((f,h)=>f.distance-h.distance);const d=[];if(t){const f=this.detectAllMeasurements(n,e);d.push(...f)}else{if(s.length>0){const f=this.detectConsistentSpacing(n,r,s,"left",a);d.push(...f)}if(o.length>0){const f=this.detectConsistentSpacing(n,r,o,"right",a);d.push(...f)}if(l.length>0){const f=this.detectConsistentSpacing(n,r,l,"top",a);d.push(...f)}if(c.length>0){const f=this.detectConsistentSpacing(n,r,c,"bottom",a);d.push(...f)}}return this.indicators=d,d}detectAllMeasurements(n,e){const t=[],a=n.getVisualBoundingBox(),r=e.filter(c=>c.id!==n.id),s=this.detectionThreshold*3;let o=0,l=0;for(const c of r){const d=c.getVisualBoundingBox();if(Math.min(Math.abs(a.x-(d.x+d.width)),Math.abs(d.x-(a.x+a.width)),Math.abs(a.y-(d.y+d.height)),Math.abs(d.y-(a.y+a.height)))>s)continue;let h=0,u=!1,g=0,m=0,p=0;const b=-30*(o%2===0?1:-1);d.x>=a.x+a.width?(h=d.x-(a.x+a.width),h>=this.minDistance&&(u=!0,g=a.x+a.width,m=d.x,p=(a.y+a.height/2+d.y+d.height/2)/2+b)):a.x>=d.x+d.width&&(h=a.x-(d.x+d.width),h>=this.minDistance&&(u=!0,g=d.x+d.width,m=a.x,p=(a.y+a.height/2+d.y+d.height/2)/2+b)),u&&(t.push({type:"horizontal",distance:Math.round(h),x1:g,x2:m,y:p,labelX:(g+m)/2,labelY:p,isAltHover:!0}),o++);let $=0,x=!1,w=0,v=0,C=0;const T=30*(l%2===0?1:-1);d.y>=a.y+a.height?($=d.y-(a.y+a.height),$>=this.minDistance&&(x=!0,w=(a.x+a.width/2+d.x+d.width/2)/2+T,v=a.y+a.height,C=d.y)):a.y>=d.y+d.height&&($=a.y-(d.y+d.height),$>=this.minDistance&&(x=!0,w=(a.x+a.width/2+d.x+d.width/2)/2+T,v=d.y+d.height,C=a.y)),x&&(t.push({type:"vertical",distance:Math.round($),x:w,y1:v,y2:C,labelX:w,labelY:(v+C)/2,isAltHover:!0}),l++)}return t}detectConsistentSpacing(n,e,t,a,r){const s=[],l=t[0],c=l.distance,d=l.element.getVisualBoundingBox(),f=this.checkIfWouldSnap(e,c,a,r);if(this.addIndicatorForDirection(s,e,d,c,a,f),a==="left"||a==="right"){const h=r.filter(u=>{if(u.id===n.id)return!1;const g=u.getVisualBoundingBox();return!(e.y+e.height<g.y||e.y>g.y+g.height)});if(h.sort((u,g)=>{const m=u.getVisualBoundingBox(),p=g.getVisualBoundingBox();return m.x-p.x}),a==="left")for(let u=0;u<h.length-1;u++){const g=h[u],m=h[u+1],p=g.getVisualBoundingBox(),y=m.getVisualBoundingBox(),b=y.x-(p.x+p.width);if(Math.abs(b-c)<=16&&b>=this.minDistance){const $=Math.max(p.y,y.y),x=Math.min(p.y+p.height,y.y+y.height),w=($+x)/2;s.push({type:"horizontal",distance:Math.round(b),x1:p.x+p.width,x2:y.x,y:w,labelX:(p.x+p.width+y.x)/2,labelY:w})}}else for(let u=0;u<h.length-1;u++){const g=h[u],m=h[u+1],p=g.getVisualBoundingBox(),y=m.getVisualBoundingBox(),b=y.x-(p.x+p.width);if(Math.abs(b-c)<=16&&b>=this.minDistance){const $=Math.max(p.y,y.y),x=Math.min(p.y+p.height,y.y+y.height),w=($+x)/2;s.push({type:"horizontal",distance:Math.round(b),x1:p.x+p.width,x2:y.x,y:w,labelX:(p.x+p.width+y.x)/2,labelY:w})}}}else{const h=r.filter(u=>{if(u.id===n.id)return!1;const g=u.getVisualBoundingBox();return!(e.x+e.width<g.x||e.x>g.x+g.width)});if(h.sort((u,g)=>{const m=u.getVisualBoundingBox(),p=g.getVisualBoundingBox();return m.y-p.y}),a==="top")for(let u=0;u<h.length-1;u++){const g=h[u],m=h[u+1],p=g.getVisualBoundingBox(),y=m.getVisualBoundingBox(),b=y.y-(p.y+p.height);if(Math.abs(b-c)<=16&&b>=this.minDistance){const $=Math.max(p.x,y.x),x=Math.min(p.x+p.width,y.x+y.width),w=($+x)/2;s.push({type:"vertical",distance:Math.round(b),x:w,y1:p.y+p.height,y2:y.y,labelX:w,labelY:(p.y+p.height+y.y)/2})}}else for(let u=0;u<h.length-1;u++){const g=h[u],m=h[u+1],p=g.getVisualBoundingBox(),y=m.getVisualBoundingBox(),b=y.y-(p.y+p.height);if(Math.abs(b-c)<=16&&b>=this.minDistance){const $=Math.max(p.x,y.x),x=Math.min(p.x+p.width,y.x+y.width),w=($+x)/2;s.push({type:"vertical",distance:Math.round(b),x:w,y1:p.y+p.height,y2:y.y,labelX:w,labelY:(p.y+p.height+y.y)/2})}}}return s}checkIfWouldSnap(n,e,t,a){const r=S.SPACING_SNAP_THRESHOLD;if(t==="top"||t==="bottom"){const s=a.filter(o=>{const l=o.getVisualBoundingBox();return!(n.x+n.width<l.x||n.x>l.x+l.width)});if(s.length>=1){s.sort((l,c)=>{const d=l.getVisualBoundingBox(),f=c.getVisualBoundingBox();return d.y-f.y});const o=[];for(let l=0;l<s.length-1;l++){const c=s[l].getVisualBoundingBox(),f=s[l+1].getVisualBoundingBox().y-(c.y+c.height);o.push(f)}if(o.length>0){const l=o.reduce((f,h)=>f+h,0)/o.length;return Math.abs(e-l)<=r}}return!1}else{const s=a.filter(o=>{const l=o.getVisualBoundingBox();return!(n.y+n.height<l.y||n.y>l.y+l.height)});if(s.length>=1){s.sort((l,c)=>{const d=l.getVisualBoundingBox(),f=c.getVisualBoundingBox();return d.x-f.x});const o=[];for(let l=0;l<s.length-1;l++){const c=s[l].getVisualBoundingBox(),f=s[l+1].getVisualBoundingBox().x-(c.x+c.width);o.push(f)}if(o.length>0){const l=o.reduce((f,h)=>f+h,0)/o.length;return Math.abs(e-l)<=r}}return!1}}addIndicatorForDirection(n,e,t,a,r,s=!1){if(r==="left"){const o=Math.max(e.y,t.y),l=Math.min(e.y+e.height,t.y+t.height),c=(o+l)/2;n.push({type:"horizontal",distance:Math.round(a),x1:t.x+t.width,x2:e.x,y:c,labelX:(t.x+t.width+e.x)/2,labelY:c,isSnapTarget:s})}else if(r==="right"){const o=Math.max(e.y,t.y),l=Math.min(e.y+e.height,t.y+t.height),c=(o+l)/2;n.push({type:"horizontal",distance:Math.round(a),x1:e.x+e.width,x2:t.x,y:c,labelX:(e.x+e.width+t.x)/2,labelY:c,isSnapTarget:s})}else if(r==="top"){const o=Math.max(e.x,t.x),l=Math.min(e.x+e.width,t.x+t.width),c=(o+l)/2;n.push({type:"vertical",distance:Math.round(a),x:c,y1:t.y+t.height,y2:e.y,labelX:c,labelY:(t.y+t.height+e.y)/2,isSnapTarget:s})}else if(r==="bottom"){const o=Math.max(e.x,t.x),l=Math.min(e.x+e.width,t.x+t.width),c=(o+l)/2;n.push({type:"vertical",distance:Math.round(a),x:c,y1:e.y+e.height,y2:t.y,labelX:c,labelY:(e.y+e.height+t.y)/2,isSnapTarget:s})}}}const bt=S.createLogger("TextureManager"),On=class On{static async loadTexture(n){if(this.cache.has(n))return this.cache.get(n);if(this.loading.has(n))return this.loading.get(n);const e=this.resolveTextureUrl(n),t=new Promise((a,r)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.cache.set(n,s),this.cache.set(e,s),this.loading.delete(n),this.loading.delete(e),a(s)},s.onerror=()=>{bt.error("Failed to load texture:",e),this.loading.delete(n),this.loading.delete(e),r(new Error(`Failed to load texture: ${e}`))},s.src=e});return this.loading.set(n,t),e!==n&&this.loading.set(e,t),t}static getTexture(n){const e=this.resolveTextureUrl(n);return this.cache.get(n)||this.cache.get(e)||null}static async preloadTextures(n){await Promise.all(n.map(e=>this.loadTexture(e)))}static async preloadAllTextures(){await this.preloadTextures(this.TEXTURES.map(n=>n.id))}static clearCache(){this.cache.clear(),this.loading.clear()}static resolveTextureUrl(n){if(n.startsWith("http://")||n.startsWith("https://")||n.startsWith("/")||n.startsWith("data:"))return n;const e=this.TEXTURES.find(t=>t.id===n);return e?e.url:`/textures/${n}`}static getTextureInfo(n){return this.TEXTURES.find(e=>e.id===n)}static getAllTextures(){return[...this.TEXTURES]}static getTexturesByCategory(n){return this.TEXTURES.filter(e=>e.category===n)}static getTexturePresetColor(n){const e=this.TEXTURES.find(t=>t.id===n);return(e==null?void 0:e.presetColor)||"#ffffff"}};On.cache=new Map,On.loading=new Map,On.TEXTURES=[{id:"glass-frame",name:"Glass Frame",url:"/textures/glass-frame.svg",category:"glass",presetColor:"#ccc"}];let sn=On;const te=S.createLogger("ArtboardRenderer"),mt={showLabel:!0,showBorder:!0,borderColor:"",borderWidth:1,labelFontSize:14,labelColor:"",labelPadding:8,selectedBorderColor:"",selectedBorderWidth:2,showPreviewBackground:!0,borderRadius:0};class me{constructor(n={}){this.options={...mt,...n}}render(n,e,t=!1){n.save(),this.renderBackground(n,e),this.options.showBorder&&this.renderBorder(n,e,t),this.options.showLabel&&this.renderLabel(n,e,t),n.restore()}renderBackground(n,e){n.save(),this.applyClipPath(n,e),this.options.showPreviewBackground&&e.previewBackgroundColor&&e.previewBackgroundColor!=="transparent"&&(n.fillStyle=e.previewBackgroundColor,n.fillRect(e.x,e.y,e.width,e.height)),e.backgroundType==="texture"&&e.backgroundTexture?this.renderTextureBackground(n,e):e.backgroundType==="transparent"||e.backgroundColor==="transparent"?this.renderCheckerboard(n,e.x,e.y,e.width,e.height):(n.fillStyle=e.backgroundColor,n.fillRect(e.x,e.y,e.width,e.height)),n.restore()}renderTextureBackground(n,e){const t=sn.getTexture(e.backgroundTexture),a=sn.getTexturePresetColor(e.backgroundTexture);if(n.fillStyle=a,n.fillRect(e.x,e.y,e.width,e.height),!t||!t.complete){sn.loadTexture(e.backgroundTexture).catch(r=>{te.error("Failed to load texture:",r)});return}n.save(),n.beginPath(),n.rect(e.x,e.y,e.width,e.height),n.clip(),n.drawImage(t,e.x,e.y,e.width,e.height),n.restore()}renderCheckerboard(n,e,t,a,r){const o="#ffffff",l="#d0d0d0";n.save(),n.beginPath(),n.rect(e,t,a,r),n.clip(),n.fillStyle=o,n.fillRect(e,t,a,r),n.fillStyle=l;for(let c=0;c<Math.ceil(r/16);c++)for(let d=0;d<Math.ceil(a/16);d++)(c+d)%2===1&&n.fillRect(e+d*16,t+c*16,16,16);n.restore()}renderBorder(n,e,t){const{x:a,y:r,width:s,height:o,clipShape:l}=e,c=this.options.borderColor||S.getThemeArtboardBorderColor(),d=this.options.selectedBorderColor||S.getThemeAccentColor();if(n.strokeStyle=t?d:c,n.lineWidth=t?this.options.selectedBorderWidth:this.options.borderWidth,n.beginPath(),!l||l==="rectangle")if(this.options.borderRadius>0){const f=Math.min(this.options.borderRadius,Math.min(s,o)/2);this.roundedRect(n,a,r,s,o,f)}else n.rect(a,r,s,o);else if(l==="circle"){const f=a+s/2,h=r+o/2,u=Math.min(s,o)/2;n.arc(f,h,u,0,Math.PI*2)}else if(typeof l=="object"&&l.type==="rounded"){const f=Math.min(l.radius,Math.min(s,o)/2);this.roundedRect(n,a,r,s,o,f)}else if(typeof l=="object"&&l.type==="path")try{const f=new Path2D(l.d);n.save(),n.translate(a,r),n.stroke(f),n.restore();return}catch(f){te.warn("Invalid SVG path for border, falling back to rectangle:",f),n.rect(a,r,s,o)}n.stroke()}renderLabel(n,e,t){const a=this.options.labelFontSize,r=this.options.labelPadding,s=`${e.name} (${Math.round(e.width)} × ${Math.round(e.height)})`,o=e.x,l=e.y-r;n.font=`${a}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;const c=this.options.selectedBorderColor||S.getThemeAccentColor(),d=this.options.labelColor||S.getThemeArtboardLabelColor();n.fillStyle=t?c:d,n.textAlign="left",n.textBaseline="bottom",n.fillText(s,o,l)}renderMultiple(n,e,t){e.forEach(a=>{const r=a.id===t;this.render(n,a,r)})}clipToArtboard(n,e){n.save(),this.applyClipPath(n,e)}applyClipPath(n,e){const{x:t,y:a,width:r,height:s,clipShape:o}=e;if(this.options.borderRadius>0,n.beginPath(),!o||o==="rectangle")if(this.options.borderRadius>0){const l=Math.min(this.options.borderRadius,Math.min(r,s)/2);this.roundedRect(n,t,a,r,s,l)}else n.rect(t,a,r,s);else if(o==="circle"){const l=t+r/2,c=a+s/2,d=Math.min(r,s)/2;n.arc(l,c,d,0,Math.PI*2)}else if(typeof o=="object"&&o.type==="rounded"){const l=Math.min(o.radius,Math.min(r,s)/2);this.roundedRect(n,t,a,r,s,l)}else if(typeof o=="object"&&o.type==="path")try{const l=new Path2D(o.d);n.translate(t,a),n.clip(l),n.translate(-t,-a);return}catch(l){te.warn("Invalid SVG path, falling back to rectangle:",l),n.rect(t,a,r,s)}n.clip()}roundedRect(n,e,t,a,r,s){typeof n.roundRect=="function"?n.roundRect(e,t,a,r,s):(n.moveTo(e+s,t),n.lineTo(e+a-s,t),n.arcTo(e+a,t,e+a,t+s,s),n.lineTo(e+a,t+r-s),n.arcTo(e+a,t+r,e+a-s,t+r,s),n.lineTo(e+s,t+r),n.arcTo(e,t+r,e,t+r-s,s),n.lineTo(e,t+s),n.arcTo(e,t,e+s,t,s))}restoreClip(n){n.restore()}renderOutline(n,e,t,a,r,s=!1){n.save(),n.setLineDash([5,5]),n.strokeStyle=s?"#0066cc":"#999",n.lineWidth=1,n.strokeRect(e,t,a,r),n.restore()}renderResizeHandles(n,e){const{x:a,y:r,width:s,height:o}=e,l=[{x:a,y:r},{x:a+s,y:r},{x:a,y:r+o},{x:a+s,y:r+o}];n.save(),l.forEach(c=>{n.fillStyle="#fff",n.strokeStyle="#0066cc",n.lineWidth=2,n.fillRect(c.x-8/2,c.y-8/2,8,8),n.strokeRect(c.x-8/2,c.y-8/2,8,8)}),n.restore()}setOptions(n){this.options={...this.options,...n}}getOptions(){return{...this.options}}static createForExport(n={}){return new me({...n,showPreviewBackground:!1})}willRenderPreviewBackground(n){return!!(this.options.showPreviewBackground&&n.previewBackgroundColor&&n.previewBackgroundColor!=="transparent")}}function yt(i){return i instanceof S.TextElement}function Ue(i){return i instanceof S.ImageElement}function Hn(i){return i instanceof S.GroupElement}function xt(i){return i instanceof S.ShapeElement}function $t(i){return i instanceof S.PathElement}function ye(i,n,e={}){const t=e.mode||"both";switch(i.save(),i.translate(n.x||0,n.y||0),i.rotate(-(n.rotation||0)*Math.PI/180),n.transformType){case"image":wt(i,n,t,e);break;case"shape":St(i,n,t,e);break;case"group":break;default:vt(i,n,t,e);break}i.restore()}function vt(i,n,e,t){var s;const a=n,r=a.text||"";r&&((e==="stroke"||e==="both")&&((s=n.stroke)!=null&&s.enabled)&&(i.save(),S.renderTextStroke(i,n,{...t.renderingContext,positionApplied:!0}),i.restore()),(e==="fill"||e==="both")&&(i.save(),S.renderTextFillOnly(i,{text:r,fontSize:a.fontSize||24,fontFamily:a.fontFamily||"Arial",bold:a.bold||!1,italic:a.italic||!1,textAlign:a.textAlign||"center",color:a.color||"#000000"}),i.restore()))}function wt(i,n,e,t){var r;if(!n.transformData)return;const a=n.transformData;if(e==="fill"||e==="both")if(Et(i,n),t.loadedImage){i.save(),i.clip();const s=a.flipHorizontal?-1:1,o=a.flipVertical?-1:1;i.scale(s,o);const l=a.width??100,c=a.height??100;i.drawImage(t.loadedImage,-l/2,-c/2,l,c),i.restore()}else i.fillStyle="#cccccc",i.fill();(e==="stroke"||e==="both")&&((r=n.stroke)!=null&&r.enabled)&&(i.save(),S.renderImageStroke(i,n,t.renderingContext),i.restore())}function St(i,n,e,t){var s,o;if(!n.transformData)return;const a=n.transformData,r=((s=t.renderingContext)==null?void 0:s.isKnockout)===!0;i.beginPath(),ze(i,a),(e==="fill"||e==="both")&&(i.fillStyle=r?"#000000":a.fillColor||"#3b82f6",i.globalAlpha=r?1:a.fillOpacity??1,i.fill()),(e==="stroke"||e==="both")&&((o=n.stroke)!=null&&o.enabled)&&(i.save(),_t(i,n,t.renderingContext),i.restore())}function ze(i,n){const{shapeType:e}=n,t=n.width??100,a=n.height??100;switch(e){case"rectangle":ke(i,n,t,a);break;case"circle":Ct(i,Math.min(t,a)/2);break;case"ellipse":kt(i,t/2,a/2);break;case"star":Tt(i,n,Math.min(t,a)/2);break;default:ke(i,n,t,a)}}function ke(i,n,e,t){const a=n.borderRadius||0,r=-e/2,s=-t/2;if(a>0){const o=Math.min(a/100*Math.min(e,t),e/2,t/2);i.roundRect(r,s,e,t,o)}else i.rect(r,s,e,t)}function Ct(i,n){i.arc(0,0,n,0,Math.PI*2)}function kt(i,n,e){i.ellipse(0,0,n,e,0,0,Math.PI*2)}function Tt(i,n,e){const t=Math.max(3,Math.min(20,n.points||5)),a=Math.max(.1,Math.min(.9,n.innerRadius||.4)),r=e*a,s=Math.PI/t,o=-Math.PI/2;for(let l=0;l<t*2;l++){const c=o+s*l,d=l%2===0?e:r,f=Math.cos(c)*d,h=Math.sin(c)*d;l===0?i.moveTo(f,h):i.lineTo(f,h)}i.closePath()}function _t(i,n,e){var a;if(!((a=n.stroke)!=null&&a.enabled)||!n.transformData)return;const t=(e==null?void 0:e.isKnockout)===!0;i.save(),t?(i.strokeStyle="#000000",i.lineWidth=n.stroke.width,i.lineCap=n.stroke.lineCap||"butt",i.lineJoin=n.stroke.lineJoin||"miter",i.globalAlpha=1):(i.strokeStyle=n.stroke.color,i.lineWidth=n.stroke.width,i.lineCap=n.stroke.lineCap||"butt",i.lineJoin=n.stroke.lineJoin||"miter",n.stroke.opacity!==void 0&&(i.globalAlpha=n.stroke.opacity)),n.stroke.miterLimit!==void 0&&(i.miterLimit=n.stroke.miterLimit),n.stroke.dashArray&&n.stroke.dashArray.length>0&&i.setLineDash(n.stroke.dashArray),!t&&n.stroke.feather&&n.stroke.feather>0&&"filter"in i&&(i.filter=`blur(${n.stroke.feather}px)`),i.beginPath(),ze(i,n.transformData),i.stroke(),i.restore()}function Et(i,n){if(!n.transformData)return;const{borderRadius:e}=n.transformData,t=n.transformData.width??100,a=n.transformData.height??100,r=-t/2,s=-a/2;if(i.beginPath(),e&&e>0){const o=Math.min(e/100*Math.min(t,a),t/2,a/2);i.roundRect(r,s,t,a,o)}else i.rect(r,s,t,a)}function Gn(i,n,e,t,a,r,s="destination-out"){var $;if(!n.knockoutParts)return;if(!(n.knockoutParts.fill||n.knockoutParts.stroke)){t(i,n);return}const l=i.getTransform();i.save();const c=n.knockoutParts.scope||"group",d=Pt(n,c,e);if(d.length===0&&c==="artboard"){Dt(i,n,t),i.restore();return}if(d.length===0){t(i,n),i.restore();return}const f=i.canvas,u=i.getTransform().a,g=Rt(f.width,f.height),m=g.getContext("2d");if(!m)return;m.scale(u,u),a&&r&&(m.fillStyle=a,m.fillRect(r.x,r.y,r.width,r.height));for(const x of d)t(m,x);n.knockoutParts.fill&&!n.knockoutParts.stroke&&(($=n.stroke)!=null&&$.enabled)&&(m.save(),le(m,n),m.restore()),m.save(),m.globalCompositeOperation=s,n.knockoutParts.fill&&oe(m,n),n.knockoutParts.stroke&&le(m,n),m.restore(),n.knockoutParts.fill||(m.save(),oe(m,n),m.restore());const p=f.width/u,y=f.height/u;i.drawImage(g,0,0,p,y),i.restore();const b=i.getTransform();(Math.abs(b.a-l.a)>.001||Math.abs(b.d-l.d)>.001||Math.abs(b.e-l.e)>.001||Math.abs(b.f-l.f)>.001)&&i.setTransform(l.a,l.b,l.c,l.d,l.e,l.f)}function At(i,n,e,t,a,r){Gn(i,n,e,t,a,r,"destination-out")}function Pt(i,n,e){return n==="artboard"?We(i,e):It(i,e)}function We(i,n){const e=n.findIndex(t=>t.id===i.id);return e===-1?[]:n.slice(0,e)}function It(i,n){const e=He(i,n);if(!e)return We(i,n);if(e.transformType!=="group"||!e.children)return[];const t=e.children.findIndex(a=>a.id===i.id);return t===-1?[]:e.children.slice(0,t)}function He(i,n){for(const e of n)if(e.transformType==="group"&&e.children){if(e.children.some(a=>a.id===i.id))return e;const t=He(i,e.children);if(t)return t}return null}function oe(i,n,e){ye(i,n,{mode:"fill",renderingContext:{isKnockout:!0}})}function le(i,n){var e;(e=n.stroke)!=null&&e.enabled&&ye(i,n,{mode:"stroke",renderingContext:{isKnockout:!0}})}function Dt(i,n,e){var a;const t=n.knockoutParts;if(!t){e(i,n);return}t.fill||(i.save(),oe(i,n),i.restore()),!t.stroke&&((a=n.stroke)!=null&&a.enabled)&&(i.save(),le(i,n),i.restore())}function Rt(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);if(typeof document<"u"){const e=document.createElement("canvas");return e.width=i,e.height=n,e}throw new Error("No canvas context available")}function Te(i,n,e,t,a=0){if(e<=0||t<=0||i<=0||n<=0)return{width:i+a,height:n+a};const r=e/t,s=i/n;let o,l;return s>r?(l=n,o=n*r):(o=i,l=i/r),{width:o+a,height:l+a}}const Dn=64,ae=512;function Mt(i,n){i.beginPath(),i.arc(n/2,n/2,n*.45,0,Math.PI*2),i.fill()}function Ft(i,n){const e=n/2,t=n/2,a=n*.45,r=a*.4,s=5;i.beginPath();for(let o=0;o<s*2;o++){const l=-Math.PI/2+Math.PI/s*o,c=o%2===0?a:r,d=e+Math.cos(l)*c,f=t+Math.sin(l)*c;o===0?i.moveTo(d,f):i.lineTo(d,f)}i.closePath(),i.fill()}function Ot(i,n){const e=n/2,t=n*.42;i.beginPath(),i.moveTo(e,n*.82),i.bezierCurveTo(e-t*1.1,n*.6,e-t*1.3,n*.2,e,n*.35),i.bezierCurveTo(e+t*1.3,n*.2,e+t*1.1,n*.6,e,n*.82),i.closePath(),i.fill()}function Bt(i,n){const e=n/2,t=n/2,a=n*.4,r=n*.48;i.beginPath(),i.moveTo(e,t-r),i.lineTo(e+a,t),i.lineTo(e,t+r),i.lineTo(e-a,t),i.closePath(),i.fill()}function Lt(i,n){const e=n/2,t=n/2,a=n*.44;i.beginPath();for(let r=0;r<6;r++){const s=-Math.PI/2+Math.PI/3*r,o=e+Math.cos(s)*a,l=t+Math.sin(s)*a;r===0?i.moveTo(o,l):i.lineTo(o,l)}i.closePath(),i.fill()}function Nt(i,n){const e=n/2,t=n*.4,a=n*.12;i.beginPath(),i.moveTo(e,a),i.lineTo(e+t,n*.25),i.lineTo(e+t,n*.55),i.quadraticCurveTo(e+t*.3,n*.8,e,n*.9),i.quadraticCurveTo(e-t*.3,n*.8,e-t,n*.55),i.lineTo(e-t,n*.25),i.closePath(),i.fill()}function Ut(i,n){const e=n/2,t=n/2;let a=42;const r=()=>(a=(a*16807+0)%2147483647,a/2147483647);i.beginPath(),i.arc(e,t,n*.28,0,Math.PI*2),i.fill();for(let s=0;s<30;s++){const o=r()*Math.PI*2,l=n*.15+r()*n*.3,c=n*.02+r()*n*.06;i.beginPath(),i.arc(e+Math.cos(o)*l,t+Math.sin(o)*l,c,0,Math.PI*2),i.fill()}}function zt(i,n){let e=123;const t=()=>(e=(e*16807+0)%2147483647,e/2147483647),a=n*.08,r=40;i.beginPath(),i.moveTo(a,a);for(let s=1;s<=r;s++){const o=a+(n-2*a)*(s/r),l=a+(t()-.5)*n*.08;i.lineTo(o,l)}for(let s=1;s<=r;s++){const o=n-a+(t()-.5)*n*.08,l=a+(n-2*a)*(s/r);i.lineTo(o,l)}for(let s=r;s>=0;s--){const o=a+(n-2*a)*(s/r),l=n-a+(t()-.5)*n*.08;i.lineTo(o,l)}for(let s=r;s>=0;s--){const o=a+(t()-.5)*n*.08,l=a+(n-2*a)*(s/r);i.lineTo(o,l)}i.closePath(),i.fill()}function Wt(i,n){let e=77;const t=()=>(e=(e*16807+0)%2147483647,e/2147483647),a=n*.25,r=n*.75,s=n*.1;i.beginPath(),i.moveTo(s,a+t()*n*.05);for(let o=1;o<=10;o++){const l=s+(n-2*s)*(o/10),c=a+(t()-.5)*n*.1;i.lineTo(l,c)}for(let o=10;o>=0;o--){const l=s+(n-2*s)*(o/10),c=r+(t()-.5)*n*.1;i.lineTo(l,c)}i.closePath(),i.fill()}function Ht(i,n){const e=n/2,t=n*.55;i.beginPath(),i.arc(e,t,n*.2,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(e-n*.18,t+n*.02,n*.15,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(e+n*.18,t+n*.02,n*.16,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(e-n*.06,t-n*.14,n*.14,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(e+n*.1,t-n*.12,n*.12,0,Math.PI*2),i.fill()}const Ge=[{id:"circle",name:"Circle",description:"Perfect circle",imageUrl:"builtin-mask:circle",thumbnailUrl:"",category:"geometric",draw:Mt},{id:"star",name:"Star",description:"5-pointed star",imageUrl:"builtin-mask:star",thumbnailUrl:"",category:"geometric",draw:Ft},{id:"heart",name:"Heart",description:"Heart shape",imageUrl:"builtin-mask:heart",thumbnailUrl:"",category:"geometric",draw:Ot},{id:"diamond",name:"Diamond",description:"Diamond/rhombus",imageUrl:"builtin-mask:diamond",thumbnailUrl:"",category:"geometric",draw:Bt},{id:"hexagon",name:"Hexagon",description:"Regular hexagon",imageUrl:"builtin-mask:hexagon",thumbnailUrl:"",category:"geometric",draw:Lt},{id:"shield",name:"Shield",description:"Shield/crest shape",imageUrl:"builtin-mask:shield",thumbnailUrl:"",category:"geometric",draw:Nt},{id:"splatter",name:"Splatter",description:"Ink splatter",imageUrl:"builtin-mask:splatter",thumbnailUrl:"",category:"organic",draw:Ut},{id:"torn-edge",name:"Torn Edge",description:"Rough torn paper edge",imageUrl:"builtin-mask:torn-edge",thumbnailUrl:"",category:"organic",draw:zt},{id:"paint-stroke",name:"Paint Stroke",description:"Horizontal brush stroke",imageUrl:"builtin-mask:paint-stroke",thumbnailUrl:"",category:"organic",draw:Wt},{id:"cloud",name:"Cloud",description:"Soft cloud shape",imageUrl:"builtin-mask:cloud",thumbnailUrl:"",category:"organic",draw:Ht}];let _e=!1;function Ee(i,n){if(typeof document>"u")return null;const e=document.createElement("canvas");return e.width=i,e.height=n,e}function Ve(){if(typeof document>"u"||_e)return;_e=!0;const i=S.ImageCache.getInstance();for(const n of Ge){const e=Ee(ae,ae);if(!e)continue;const t=e.getContext("2d");if(!t)continue;t.fillStyle="white",n.draw(t,ae);const a=e.toDataURL("image/png"),r=i.acquire(n.imageUrl);r.crossOrigin="anonymous",r.src=a;const s=Ee(Dn,Dn);if(s){const o=s.getContext("2d");o&&(o.fillStyle="#1a1a2e",o.fillRect(0,0,Dn,Dn),o.fillStyle="white",n.draw(o,Dn),n.thumbnailUrl=s.toDataURL("image/png"))}}}const Gt=S.createLogger("MaskRenderer"),ce=new Map,Vt=new Map;function jt(i){const n=[];ce.forEach((e,t)=>{t.startsWith(i)&&n.push(t)}),n.forEach(e=>ce.delete(e))}function Xt(){ce.clear()}function mn(i,n,e){if(!n.masks||n.masks.length===0){e(i);return}const t=i.canvas,a=Vn(t.width,t.height),r=a.getContext("2d");if(!r){Gt.error("[renderWithMasks] Failed to get offscreen context");return}const s=i.getTransform();r.setTransform(s),e(r);for(const o of n.masks)qt(r,o,n);i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(a,0,0),i.restore()}function qt(i,n,e){switch(n.type){case"clip":Yt(i,n,e);break;case"alpha":Kt(i,n,e);break;case"luma":Zt(i,n,e);break;case"distress":Jt(i,n,e);break}}function Yt(i,n,e){i.save(),i.globalCompositeOperation=n.inverted?"destination-out":"destination-in",n.opacity!==void 0&&(i.globalAlpha=n.opacity),Zn(i,n.maskElement,e),i.restore()}function Kt(i,n,e){i.save(),i.globalCompositeOperation=n.inverted?"destination-out":"destination-in",n.opacity!==void 0&&(i.globalAlpha=n.opacity),Zn(i,n.maskElement,e),n.feather&&n.feather>0&&je(i,n.feather),i.restore()}function Zt(i,n,e){const t=Vn(i.canvas.width,i.canvas.height),a=t.getContext("2d");if(!a)return;Zn(a,n.maskElement,e);const r=a.getImageData(0,0,t.width,t.height),s=r.data;for(let o=0;o<s.length;o+=4){const l=s[o],c=s[o+1],d=s[o+2],f=.299*l+.587*c+.114*d;s[o+3]=n.inverted?255-f:f}a.putImageData(r,0,0),i.save(),i.globalCompositeOperation="destination-in",n.opacity!==void 0&&(i.globalAlpha=n.opacity),i.drawImage(t,0,0),i.restore()}function Jt(i,n,e){i.save(),i.globalCompositeOperation=n.inverted?"destination-in":"destination-out",n.opacity!==void 0&&(i.globalAlpha=n.opacity),Zn(i,n.maskElement,e),n.feather&&n.feather>0&&je(i,n.feather),i.restore()}function Zn(i,n,e){const t=e.x||0,a=e.y||0,r=n.x||0,s=n.y||0,o={...n,x:t+r,y:a+s,rotation:(n.rotation||0)+(e.rotation||0)},l=4,c=e.transformData,d=e,f=(c==null?void 0:c.width)||d.width||0,h=(c==null?void 0:c.height)||d.height||0,u=n.transformData;f&&h&&u&&(o.transformData={...u,width:f+l,height:h+l});let g,m;if(n.transformType==="image"){const x=n;if(x.imageUrl)if(typeof document<"u"){x.imageUrl.startsWith("builtin-mask:")&&Ve();const w=S.ImageCache.getInstance(),v=w.acquire(x.imageUrl);v.complete&&v.naturalWidth>0&&(g=v),w.release(x.imageUrl)}else m=Vt.get(x.imageUrl)}const p=o.transformData,y=(u==null?void 0:u.width)||0,b=(u==null?void 0:u.height)||0,$=y>0&&b>0&&f>0&&h>0&&Math.abs(y/b-f/h)>.001;if(m){i.save();const x=(p==null?void 0:p.width)||m.width,w=(p==null?void 0:p.height)||m.height;if(i.translate(o.x||0,o.y||0),i.rotate(-(o.rotation||0)*Math.PI/180),$){const v=Te(x,w,y,b,0);i.drawImage(m,-v.width/2,-v.height/2,v.width,v.height)}else i.drawImage(m,-x/2,-w/2,x,w);i.restore()}else if($&&g){const x=(p==null?void 0:p.width)||f,w=(p==null?void 0:p.height)||h,v=Te(x,w,y,b,0);i.save(),i.translate(o.x||0,o.y||0),i.rotate(-(o.rotation||0)*Math.PI/180),i.drawImage(g,-v.width/2,-v.height/2,v.width,v.height),i.restore()}else ye(i,o,{mode:"both",loadedImage:g})}function je(i,n){"filter"in i&&(i.filter=`blur(${n}px)`)}function Vn(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);if(typeof document<"u"){const e=document.createElement("canvas");return e.width=i,e.height=n,e}throw new Error("No canvas context available")}function Xe(i,n,e,t){if(!n.enabled||!n.imageUrl||n.opacity<=0)return;const a=S.ImageCache.getInstance(),r=a.acquire(n.imageUrl);if(!r.complete||r.naturalWidth===0){a.release(n.imageUrl);return}const{x:s,y:o,width:l,height:c}=e,d=i.getTransform(),f=d.a*s+d.e,h=d.d*o+d.f,u=d.a*l,g=d.d*c,m=Math.ceil(u),p=Math.ceil(g);if(m<=0||p<=0){a.release(n.imageUrl);return}const y=Vn(m,p),b=y.getContext("2d");if(!b){a.release(n.imageUrl);return}b.drawImage(i.canvas,f,h,u,g,0,0,m,p);let $;if(n.maskType==="luma"?$="destination-in":$=n.inverted?"destination-out":"destination-in",n.maskType==="luma"){const x=Vn(m,p),w=x.getContext("2d");if(w){w.drawImage(r,0,0,m,p);const v=w.getImageData(0,0,m,p),C=v.data;for(let _=0;_<C.length;_+=4){const T=.299*C[_]+.587*C[_+1]+.114*C[_+2];C[_+3]=n.inverted?255-T:T}w.putImageData(v,0,0),b.globalCompositeOperation="destination-in",b.globalAlpha=n.opacity/100,b.drawImage(x,0,0)}}else b.globalCompositeOperation=$,b.globalAlpha=n.opacity/100,b.drawImage(r,0,0,m,p);b.globalCompositeOperation="source-over",b.globalAlpha=1,i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(f,h,u,g),t&&(i.fillStyle=t,i.fillRect(f,h,u,g)),i.drawImage(y,f,h),i.restore(),a.release(n.imageUrl)}class Qt{constructor(n=Math.random()){this.perm=[];for(let t=0;t<256;t++)this.perm[t]=t;const e=this.seededRandom(n);for(let t=255;t>0;t--){const a=Math.floor(e()*(t+1));[this.perm[t],this.perm[a]]=[this.perm[a],this.perm[t]]}for(let t=0;t<256;t++)this.perm[256+t]=this.perm[t]}seededRandom(n){let e=Math.sin(n++)*1e4;return()=>(e=Math.sin(n++)*1e4,e-Math.floor(e))}fade(n){return n*n*n*(n*(n*6-15)+10)}lerp(n,e,t){return e+n*(t-e)}grad(n,e,t){const a=n&15,r=a<8?e:t,s=a<4?t:a===12||a===14?e:0;return((a&1)===0?r:-r)+((a&2)===0?s:-s)}noise(n,e){const t=Math.floor(n)&255,a=Math.floor(e)&255;n-=Math.floor(n),e-=Math.floor(e);const r=this.fade(n),s=this.fade(e),o=this.perm[t]+a,l=this.perm[t+1]+a;return this.lerp(s,this.lerp(r,this.grad(this.perm[o],n,e),this.grad(this.perm[l],n-1,e)),this.lerp(r,this.grad(this.perm[o+1],n,e-1),this.grad(this.perm[l+1],n-1,e-1)))}}function re(i,n,e,t=Date.now()){const s=Jn(i,n).getContext("2d").createImageData(i,n),o=s.data,l=new Qt(t),c=.02,d=1-e/100;for(let f=0;f<n;f++)for(let h=0;h<i;h++){const u=(f*i+h)*4;let g=0;g+=l.noise(h*c,f*c)*.5,g+=l.noise(h*c*2,f*c*2)*.25,g+=l.noise(h*c*4,f*c*4)*.125,g=(g+1)/2;const m=Math.min(h/i,(i-h)/i)*2,p=Math.min(f/n,(n-f)/n)*2,y=Math.min(m,p);g*=.7+y*.3;const b=g>d?255:0;o[u]=255,o[u+1]=255,o[u+2]=255,o[u+3]=b}return s}function na(i,n,e,t=Date.now()){const r=Jn(i,n).getContext("2d");r.clearRect(0,0,i,n),r.strokeStyle="#000000",r.lineWidth=1+e/50,r.lineCap="round";const s=xe(t),o=Math.floor(e/100*30+5);for(let l=0;l<o;l++){const c=s()*i,d=s()*n;de(r,c,d,s()*Math.PI*2,50+s()*100,s,0)}return r.getImageData(0,0,i,n)}function de(i,n,e,t,a,r,s){if(s>3||a<10)return;const o=n+Math.cos(t)*a,l=e+Math.sin(t)*a;if(i.beginPath(),i.moveTo(n,e),i.lineTo(o,l),i.stroke(),r()>.5){const c=t+(r()-.5)*Math.PI/2;de(i,o,l,c,a*.6,r,s+1)}if(r()>.7){const c=t-(r()-.5)*Math.PI/2;de(i,o,l,c,a*.6,r,s+1)}}function Wn(i,n,e,t=Date.now()){const s=Jn(i,n).getContext("2d").createImageData(i,n),o=s.data,l=xe(t),c=e/100*.5;for(let d=0;d<n;d++)for(let f=0;f<i;f++){const h=(d*i+f)*4,g=l()<c?255:0;o[h]=0,o[h+1]=0,o[h+2]=0,o[h+3]=g}return s}function ea(i,n,e,t=Date.now()){const r=Jn(i,n).getContext("2d");r.fillStyle="#000000";const s=xe(t),o=4+e/100*6,l=o*2;for(let c=0;c<n;c+=l)for(let d=0;d<i;d+=l)if(s()<e/100){const f=o*(.5+s()*.5);r.beginPath(),r.arc(d,c,f/2,0,Math.PI*2),r.fill()}return r.getImageData(0,0,i,n)}function Jn(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);if(typeof document<"u"){const e=document.createElement("canvas");return e.width=i,e.height=n,e}throw new Error("No canvas context available")}function xe(i){let n=Math.sin(i++)*1e4;return()=>(n=Math.sin(i++)*1e4,n-Math.floor(n))}const ln=42,Cn=512,kn=64;function fe(i){const n=i.data;for(let e=0;e<n.length;e+=4)n[e]=255,n[e+1]=255,n[e+2]=255;return i}function ta(i,n){const e=i.data,t=n.data;for(let a=0;a<e.length;a+=4)e[a]=255,e[a+1]=255,e[a+2]=255,e[a+3]=Math.min(255,e[a+3]+t[a+3]);return i}const qe=[{id:"grunge-heavy",name:"Heavy Grunge",textureUrl:"builtin:grunge-heavy",thumbnailUrl:"",description:"Dense random splatters",generate:(i,n)=>Wn(i,n,80,ln)},{id:"grunge-fine",name:"Fine Grunge",textureUrl:"builtin:grunge-fine",thumbnailUrl:"",description:"Sparse fine grain",generate:(i,n)=>Wn(i,n,25,ln+1)},{id:"concrete",name:"Concrete",textureUrl:"builtin:concrete",thumbnailUrl:"",description:"Rough surface via Perlin noise",generate:(i,n)=>re(i,n,55,ln+2)},{id:"paper",name:"Old Paper",textureUrl:"builtin:paper",thumbnailUrl:"",description:"Subtle aging",generate:(i,n)=>re(i,n,20,ln+3)},{id:"rust",name:"Rust",textureUrl:"builtin:rust",thumbnailUrl:"",description:"Noise + splatter combined",generate:(i,n)=>{const e=re(i,n,45,ln+4),t=Wn(i,n,35,ln+5);return ta(fe(e),fe(t))}},{id:"scratches",name:"Scratches",textureUrl:"builtin:scratches",thumbnailUrl:"",description:"Branching crack lines",generate:(i,n)=>na(i,n,55,ln+6)},{id:"halftone",name:"Halftone",textureUrl:"builtin:halftone",thumbnailUrl:"",description:"Dot grid pattern",generate:(i,n)=>ea(i,n,55,ln+7)},{id:"spray",name:"Spray Paint",textureUrl:"builtin:spray",thumbnailUrl:"",description:"Medium random splatter",generate:(i,n)=>Wn(i,n,55,ln+8)}];let Ae=!1;function aa(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);const e=document.createElement("canvas");return e.width=i,e.height=n,e}function Pe(i,n){if(typeof document>"u")return null;const e=document.createElement("canvas");return e.width=i,e.height=n,e}function ra(i){const n=Pe(i.width,i.height);if(!n)return"";const e=n.getContext("2d");if(!e)return"";e.putImageData(i,0,0);const t=Pe(kn,kn);if(!t)return"";const a=t.getContext("2d");if(!a)return"";a.drawImage(n,0,0,i.width,i.height,0,0,kn,kn);const r=a.getImageData(0,0,kn,kn),s=r.data;for(let o=0;o<s.length;o+=4){const l=s[o+3],c=255-Math.round(l/255*195);s[o]=c,s[o+1]=c,s[o+2]=c,s[o+3]=255}return a.putImageData(r,0,0),t.toDataURL("image/png")}function Ye(){if(!Ae){Ae=!0;for(const i of qe){const n=i.generate(Cn,Cn);fe(n);const e=aa(Cn,Cn),t=e.getContext("2d");t&&(t.putImageData(n,0,0),ia(i.textureUrl,e,Cn,Cn)),typeof document<"u"&&(i.thumbnailUrl=ra(n))}}}const hn=new Set,pn=new Map,jn=new Map;function Ie(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);const e=document.createElement("canvas");return e.width=i,e.height=n,e}function De(i){return i.getContext("2d")}function Re(i){const{width:n,height:e}=i,t=Ie(n,e),a=De(t);if(!a)throw new Error("Failed to get 2d context for temp canvas");a.drawImage(i,0,0);const r=a.getImageData(0,0,n,e),s=r.data;for(let c=0;c<s.length;c+=4){const d=s[c],f=s[c+1],h=s[c+2],g=255-(.299*d+.587*f+.114*h);s[c]=255,s[c+1]=255,s[c+2]=255,s[c+3]=g}const o=Ie(n,e),l=De(o);if(!l)throw new Error("Failed to get 2d context for mask canvas");return l.putImageData(r,0,0),{alphaMask:o,width:n,height:e}}function Ke(i){const n=pn.get(i);if(n)return n;if(i.startsWith("builtin:")){Ye();const e=pn.get(i);return e||null}return hn.has(i)||(hn.add(i),Ze(i)),null}function sa(i){return pn.has(i)?Promise.resolve():new Promise(n=>{if(pn.has(i)){n();return}const e=jn.get(i)||[];e.push(n),jn.set(i,e),hn.has(i)||(hn.add(i),Ze(i))})}function ia(i,n,e,t){pn.has(i)||(pn.set(i,{alphaMask:n,width:e,height:t}),Mn(i))}function Mn(i){const n=jn.get(i);n&&(n.forEach(e=>e()),jn.delete(i))}function Ze(i){if(typeof document<"u"){const n=new Image;n.crossOrigin="anonymous",n.onload=()=>{const e=Re(n);pn.set(i,e),hn.delete(i),Mn(i)},n.onerror=()=>{hn.delete(i),Mn(i)},n.src=i}else fetch(i).then(n=>n.blob()).then(n=>createImageBitmap(n)).then(n=>{const e=Re(n);pn.set(i,e),hn.delete(i),Mn(i)}).catch(()=>{hn.delete(i),Mn(i)})}function Je(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);const e=document.createElement("canvas");return e.width=i,e.height=n,e}function Qe(i,n,e,t){if(!n.enabled||!n.textureUrl||n.intensity<=0)return;const a=Ke(n.textureUrl);if(!a)return;const{x:r,y:s,width:o,height:l}=e,c=i.getTransform(),d=c.a*r+c.e,f=c.d*s+c.f,h=c.a*o,u=c.d*l,g=Math.ceil(h),m=Math.ceil(u);if(g<=0||m<=0)return;const p=Je(g,m),y=p.getContext("2d");if(!y)return;y.drawImage(i.canvas,d,f,h,u,0,0,g,m);const b=a.alphaMask.getContext("2d");if(b){const $=n.intensity/100,x=b.getImageData(0,0,a.width,a.height).data,w=a.width,v=a.height,C=y.getImageData(0,0,g,m),_=C.data;for(let T=0;T<m;T++){const E=Math.floor(T/m*v);for(let k=0;k<g;k++){const A=Math.floor(k/g*w),D=x[(E*w+A)*4+3]/255,P=(T*g+k)*4;_[P+3]=Math.round(_[P+3]*(1-D*$))}}y.putImageData(C,0,0)}else y.globalCompositeOperation="destination-out",y.globalAlpha=n.intensity/100,y.drawImage(a.alphaMask,0,0,g,m),y.globalCompositeOperation="source-over";y.globalAlpha=1,i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(d,f,h,u),t&&(i.fillStyle=t,i.fillRect(d,f,h,u)),i.drawImage(p,d,f),i.restore()}function Xn(i,n,e,t){if(!n.enabled||n.style!=="custom"||!n.textureUrl)return;const a=Ke(n.textureUrl);if(!a){t(i);return}const r=n.textureOpacity??n.intensity/100,s=i.getTransform(),o=Math.sqrt(e.width**2+e.height**2),l=(o-e.width)/2,c=(o-e.height)/2,d=20,f=l+d,h=c+d,u={x:e.x-f,y:e.y-h,width:e.width+f*2,height:e.height+h*2},g=s.a*u.x+s.e,m=s.d*u.y+s.f,p=s.a*u.width,y=s.d*u.height,b=Math.ceil(p),$=Math.ceil(y);if(b<=0||$<=0){t(i);return}const x=Je(b,$),w=x.getContext("2d");if(!w){t(i);return}w.setTransform(s.a,s.b,s.c,s.d,s.e-g,s.f-m),t(w),w.setTransform(1,0,0,1,0,0);const v=a.alphaMask.getContext("2d");if(v){const C=v.getImageData(0,0,a.width,a.height).data,_=a.width,T=a.height,E=w.getImageData(0,0,b,$),k=E.data;for(let A=0;A<$;A++){const D=Math.floor(A/$*T);for(let P=0;P<b;P++){const M=Math.floor(P/b*_),W=C[(D*_+M)*4+3]/255,B=(A*b+P)*4;k[B+3]=Math.round(k[B+3]*(1-W*r))}}w.putImageData(E,0,0)}else w.globalCompositeOperation="destination-out",w.globalAlpha=r,w.drawImage(a.alphaMask,0,0,b,$),w.globalCompositeOperation="source-over",w.globalAlpha=1;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(x,g,m),i.restore()}class Tn{static renderSelectionLayer(n,e,t,a=1){if(!e||e.visible===!1||t&&t.getMode()==="drag"||"isGroup"in e&&e.isGroup)return;const s=e.getVisualBoundingBox(),o=e.getRotationAnchor();n.save(),n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=2,n.translate(o.x*a,o.y*a),n.rotate(S.RotationUtils.toRadians(e.rotation)),n.translate(-o.x*a,-o.y*a);const l=rn.canvas.selectionPadding;n.strokeRect((s.x-l)*a,(s.y-l)*a,(s.width+l*2)*a,(s.height+l*2)*a),n.restore()}static renderPositionSizeInfo(n,e,t,a,r=1){if(!e||!(t!=null&&t.rotationHandle)||(a==null?void 0:a.getMode())!=="resize")return;const s=e.getVisualBoundingBox(),o=Math.round(s.width),l=Math.round(s.height),c=`${o} × ${l}`,d=t.rotationHandle,f=d.x*r,h=d.y*r-20;n.save(),n.font="10px system-ui, -apple-system, sans-serif";const g=n.measureText(c).width+12,m=18;n.shadowColor=S.getThemeTooltipShadowColor(n.canvas),n.shadowBlur=4,n.shadowOffsetY=1,n.fillStyle=S.getThemeTooltipBackground(n.canvas),n.beginPath(),n.roundRect(f-g/2,h-m/2,g,m,3),n.fill(),n.shadowColor="transparent",n.shadowBlur=0,n.shadowOffsetY=0,n.fillStyle=S.getThemeTooltipForeground(n.canvas),n.textAlign="center",n.textBaseline="middle",n.fillText(c,f,h+.5),n.restore()}static renderHandlesLayer(n,e,t,a,r,s,o,l=1,c=!0){if(!e||e.visible===!1||o.getMode()==="drag")return;const f=s.type==="rotation-handle",h=s.type==="resize-handle"?s.data:null,u=o.getMode()==="resize",g=u?o.getActiveHandle():null;t.render(n,c,a,r,f,h,u,g,l,!0)}}class ue{static renderHoverLayer(n,e,t,a=!1,r=1,s){if(e.type!=="element"||!e.data||e.data.id===t)return;const o=e.data;n.save();const l=150,c=.5;let d=c;if(e.startTime){const f=performance.now()-e.startTime;d=Math.min(f/l,1)*c}n.strokeStyle=S.getThemeAccentHoverColor(n.canvas),n.globalAlpha=d,n.lineWidth=3,this.renderElementOutline(n,o,r,s),n.restore()}static renderElementOutline(n,e,t=1,a){const r=e.getRotationAnchor();n.translate(r.x*t,r.y*t),n.rotate(S.RotationUtils.toRadians(e.rotation)),n.translate(-r.x*t,-r.y*t),e.transformType==="shape"?this.renderShapeOutline(n,e,t):e.transformType==="image"?this.renderImageOutline(n,e,t):e.transformType==="group"?this.renderGroupOutline(n,e,t):this.renderTextOutline(n,e,t,a)}static renderShapeOutline(n,e,t){const a=e.transformData,r=a.width*t,s=a.height*t,o=2,c=o+o/2;switch(n.save(),n.translate(e.x*t,e.y*t),n.beginPath(),a.shapeType){case"rectangle":{const d=a.borderRadius||0,f=-(r+c*2)/2,h=-(s+c*2)/2,u=r+c*2,g=s+c*2;if(d>0){const m=Math.min(d/100*Math.min(u,g),u/2,g/2);n.roundRect(f,h,u,g,m)}else n.rect(f,h,u,g);break}case"circle":{const d=Math.min(r,s)/2+c;n.arc(0,0,d,0,Math.PI*2);break}case"ellipse":{const d=(a.radiusX??r/2)+c,f=(a.radiusY??s/2)+c;n.ellipse(0,0,d,f,0,0,Math.PI*2);break}case"triangle":{const d=r/2,f=s/2,h=[{x:0,y:-f},{x:d,y:f},{x:-d,y:f}],u=h.map((m,p)=>{const y=h[(p+1)%3],b=y.x-m.x,$=y.y-m.y,x=Math.sqrt(b*b+$*$);return{x:$/x,y:-b/x}}),g=h.map((m,p)=>{const y=u[(p+2)%3],b=u[p],$=y.x+b.x,x=y.y+b.y,w=Math.sqrt($*$+x*x),v=($*y.x+x*y.y)/w,C=c/v;return{x:m.x+$/w*C,y:m.y+x/w*C}});n.moveTo(g[0].x,g[0].y),n.lineTo(g[1].x,g[1].y),n.lineTo(g[2].x,g[2].y),n.closePath();break}case"star":{const d=a.points??5,f=a.innerRadius??.4,h=Math.min(r,s)/2+c,u=h*f;for(let g=0;g<d*2;g++){const m=g*Math.PI/d-Math.PI/2,p=g%2===0?h:u,y=p*Math.cos(m),b=p*Math.sin(m);g===0?n.moveTo(y,b):n.lineTo(y,b)}n.closePath();break}case"polygon":{const d=a.sides??5,f=Math.min(r,s)/2+c;for(let h=0;h<d;h++){const u=h*2*Math.PI/d-Math.PI/2,g=f*Math.cos(u),m=f*Math.sin(u);h===0?n.moveTo(g,m):n.lineTo(g,m)}n.closePath();break}case"line":{const d=r/2+c;n.moveTo(-d,0),n.lineTo(d,0);break}}n.stroke(),n.restore()}static renderImageOutline(n,e,t){var m;const a=e.getVisualBoundingBox(),r=a.width*t,s=a.height*t,o=((m=e.transformData)==null?void 0:m.borderRadius)||0,l=2,d=l+l/2;n.save(),n.translate(e.x*t,e.y*t);const f=-(r+d*2)/2,h=-(s+d*2)/2,u=r+d*2,g=s+d*2;if(n.beginPath(),o>0){const p=Math.min(o/100*Math.min(u,g),u/2,g/2);n.roundRect(f,h,u,g,p)}else n.rect(f,h,u,g);n.stroke(),n.restore()}static renderGroupOutline(n,e,t){const a=e.getVisualBoundingBox(),r=2,o=r+r/2,l=a.x*t-o,c=a.y*t-o,d=a.width*t+o*2,f=a.height*t+o*2;n.save(),n.setLineDash([5,5]),n.beginPath(),n.roundRect(l,c,d,f,8),n.stroke(),n.restore()}static renderTextOutline(n,e,t,a){const r=e.transformType;r==="circle"||r==="wave"||r==="arch"||r==="lean"||r==="ascend"||r==="flag"?this.renderTransformHoverRingEffect(n,e,t):this.renderHoverRingEffect(n,e,t)}static renderHoverRingEffect(n,e,t){n.save(),n.translate(e.x*t,e.y*t),t!==1&&n.scale(t,t);const a=e.fontSize,r=e.fontFamily,s=e.bold||!1,o=e.italic||!1,l=e.textAlign||"center",c=S.getFontMetrics$1(a,r,s,o),d=a*1.2,f=4/t,h=4/t,u=document.createElement("canvas");u.width=n.canvas.width,u.height=n.canvas.height;const g=u.getContext("2d");if(!g){n.restore();return}g.setTransform(n.getTransform()),g.textBaseline="alphabetic",g.lineJoin="round";const m=e.getRichText?e.getRichText():null;if(m){const p=S.splitRichTextIntoLines(m),y=[],b=[];p.forEach(w=>{if(e.transformType==="custom"&&e.transformData){const v=e.transformData.width-S.HORIZONTAL_PADDING*2,C=S.wrapRichTextSpans(w,v,{fontSize:a,fontFamily:r,bold:s,italic:o});C.forEach((_,T)=>{y.push(_),b.push({isParagraphStart:T===0,isParagraphEnd:T===C.length-1})})}else y.push(w),b.push({isParagraphStart:!0,isParagraphEnd:!0})});let $;y.length===0?$=0:y.length===1?$=c.height:$=(y.length-1)*d+c.height;const x=-$/2;y.forEach((w,v)=>{var W,B;const C=b[v].isParagraphStart,_=b[v].isParagraphEnd;let T=0;const E=w.map(I=>I.text).join(""),k=((W=E.match(/^ +/))==null?void 0:W[0].length)||0,A=((B=E.match(/ +$/))==null?void 0:B[0].length)||0;let D=0;w.forEach(I=>{const H=I.style.fontSize!==void 0?I.style.fontSize:a,q=I.style.fontFamily!==void 0?I.style.fontFamily:r,Y=I.style.bold!==void 0?I.style.bold:s,nn=I.style.italic!==void 0?I.style.italic:o;let N=I.text;const R=D,F=D+I.text.length;if(!C&&k>0&&R<k){const L=Math.min(k-R,I.text.length);N=N.substring(L)}if(!_&&A>0){const L=E.length-A;if(F>L){const O=!C&&R<k?Math.min(k-R,I.text.length):0,z=Math.max(0,L-R-O);N=N.substring(0,z)}}N.length>0&&(n.save(),n.font=S.buildFontString$1(H,q,Y,nn),T+=n.measureText(N).width,n.restore()),D+=I.text.length});let P=0;l==="center"?P=-T/2:l==="right"&&(P=-T);const M=x+c.ascent+v*d;D=0,w.forEach(I=>{const H=I.style.fontSize!==void 0?I.style.fontSize:a,q=I.style.fontFamily!==void 0?I.style.fontFamily:r;I.style.color!==void 0?I.style.color:e.color;const Y=I.style.bold!==void 0?I.style.bold:s,nn=I.style.italic!==void 0?I.style.italic:o;let N=I.text;const R=D,F=D+I.text.length;if(!C&&k>0&&R<k){const L=Math.min(k-R,I.text.length);N=N.substring(L)}if(!_&&A>0){const L=E.length-A;if(F>L){const O=!C&&R<k?Math.min(k-R,I.text.length):0,z=Math.max(0,L-R-O);N=N.substring(0,z)}}D+=I.text.length,N.length>0&&(g.font=S.buildFontString$1(H,q,Y,nn),g.textAlign="left",g.globalCompositeOperation="source-over",g.strokeStyle=n.strokeStyle,g.globalAlpha=Math.min(n.globalAlpha*1.6,.8),g.lineWidth=(h+f)*2,g.strokeText(N,P,M),g.globalCompositeOperation="destination-out",g.globalAlpha=1,g.lineWidth=h*2,g.strokeText(N,P,M),g.fillText(N,P,M),P+=g.measureText(N).width)})})}else{n.font=S.buildFontString$1(a,r,s,o),g.font=n.font,g.textAlign=l;let p,y;if(e.transformType==="custom"&&e.transformData){const x=e.transformData.width-S.HORIZONTAL_PADDING*2,{lines:w}=S.calculateVisualBoundsWithSpaceCollapsing(e.text,x,a,r,s,o,void 0,!0);p=w}else{p=e.text.split(`
1
+ "use strict";const S=require("./HybridHistoryManager-BXD93pp8.cjs"),rn={canvas:{get selectionColor(){return S.getThemeAccentColor()},snapThreshold:8,snapGuideDash:[5,5],snapGuideWidth:1,selectionPadding:1,spacingIndicatorWidth:1.5,spacingLabelFontSize:11,spacingLabelFontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"}},rt=2,Fn=6,st=16,it=5,ot=5,ze=.5;function oe(i){return rt/i}function lt(i){return Fn/i}function ct(i){return st/i}function dt(i){return[it/i,ot/i]}function ft(i,n,e,t){i.save();const a=ze/t;i.translate(n,e),i.scale(a,a),i.strokeStyle="#000",i.lineWidth=1.5,i.lineCap="round",i.lineJoin="round",i.translate(-12,-12),i.beginPath(),i.moveTo(21,12),i.arc(12,12,9,0,-Math.PI/2,!0),i.bezierCurveTo(3.5,4.5,4,6,3,8),i.stroke(),i.beginPath(),i.moveTo(3,3),i.lineTo(3,8),i.lineTo(8,8),i.stroke(),i.beginPath(),i.moveTo(3,12),i.arc(12,12,9,Math.PI,Math.PI/2,!0),i.bezierCurveTo(20.5,19.5,20,18,21,16),i.stroke(),i.beginPath(),i.moveTo(16,16),i.lineTo(21,16),i.lineTo(21,21),i.stroke(),i.restore()}function ut(i,n,e,t=1,a="#3b82f6",r=!1){const s=ct(t);i.save(),i.fillStyle="#fff",i.strokeStyle=a,i.lineWidth=r?oe(t)*1.25:oe(t),i.beginPath(),i.arc(n,e,s,0,Math.PI*2),i.fill(),i.stroke(),ft(i,n,e,t),i.restore()}const ke=Fn*2;class ht{constructor(){this.resizeHandles=[],this.rotationHandle=null,this.elementRotation=0,this.rotationAnchor={x:0,y:0}}update(n,e=1){const a="isCropping"in n&&n.isCropping?n.getBoundingBox():n.getVisualBoundingBox(),r=n.getRotationAnchor(),s=n.getEnabledAnchors();this.elementRotation=n.rotation,this.rotationAnchor=r;const o=rn.canvas.selectionPadding,l={x:a.x-o,y:a.y-o,width:a.width+o*2,height:a.height+o*2},c=S.calculateResizeHandles(l,n.rotation,r),d=Math.abs(n.rotation%360)>.1;this.resizeHandles=c.filter(f=>!(!s.includes(f.anchor)||d&&f.anchor.includes("middle"))),this.rotationHandle=S.calculateRotationHandlePosition(l,n.rotation,r,e)}render(n,e=!0,t=0,a=!1,r=!1,s=null,o=!1,l=null,c=1,d=!0){this.resizeHandles.forEach(f=>{if(o&&l&&f.anchor!==l.anchor)return;const h=!!(s&&s.anchor===f.anchor),u=!!(o&&l&&l.anchor===f.anchor);this.renderResizeHandle(n,f,h,u,c)}),d&&e&&this.rotationHandle&&!a&&!o&&this.renderRotationHandle(n,this.rotationHandle,r,c),d&&e&&this.rotationHandle&&a&&this.renderRotationTooltip(n,this.rotationHandle,t,c)}renderResizeHandle(n,e,t=!1,a=!1,r=1){n.save();const s=e.x*r,o=e.y*r;if(e.anchor.includes("middle")){const c=e.anchor==="middle-top"||e.anchor==="middle-bottom";n.translate(s,o),n.rotate(-this.elementRotation*Math.PI/180),c&&n.rotate(Math.PI/2),n.translate(-s,-o);const d=ke*.6,f=ke*1.4,h=d/2,u=s-d/2,g=o-f/2;n.fillStyle="#fff",n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=t||a?2.5:2,n.beginPath(),n.roundRect(u,g,d,f,h),n.fill(),n.stroke()}else n.fillStyle="#fff",n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=t||a?2.5:2,n.beginPath(),n.arc(s,o,Fn,0,Math.PI*2),n.fill(),n.stroke();n.restore()}renderRotationHandle(n,e,t=!1,a=1){n.save();const r=e.x*a,s=e.y*a,o=Fn*2.67;n.fillStyle="#fff",n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=t?2.5:2,n.beginPath(),n.arc(r,s,o,0,Math.PI*2),n.fill(),n.stroke();const l=ze;n.translate(r,s),n.scale(l,l),n.strokeStyle="#000",n.lineWidth=1.5,n.lineCap="round",n.lineJoin="round",n.translate(-12,-12),n.beginPath(),n.moveTo(21,12),n.arc(12,12,9,0,-Math.PI/2,!0),n.bezierCurveTo(3.5,4.5,4,6,3,8),n.stroke(),n.beginPath(),n.moveTo(3,3),n.lineTo(3,8),n.lineTo(8,8),n.stroke(),n.beginPath(),n.moveTo(3,12),n.arc(12,12,9,Math.PI,Math.PI/2,!0),n.bezierCurveTo(20.5,19.5,20,18,21,16),n.stroke(),n.beginPath(),n.moveTo(16,16),n.lineTo(21,16),n.lineTo(21,21),n.stroke(),n.restore()}renderRotationTooltip(n,e,t,a=1){n.save();const r=`${Math.round(t)}°`,s=r.length*8+12,o=22,l=e.x*a,c=e.y*a-35;n.shadowColor="rgba(0,0,0,0.3)",n.shadowBlur=3,n.shadowOffsetY=1,n.fillStyle="#333",n.beginPath(),n.roundRect(l-s/2,c,s,o,3),n.fill(),n.shadowColor="transparent",n.shadowBlur=0,n.shadowOffsetY=0,n.fillStyle="#fff",n.font="12px Arial",n.textAlign="center",n.textBaseline="middle",n.fillText(r,l,c+o/2),n.restore()}hitTestResize(n,e,t=1){const a=S.CORNER_HANDLE_HIT_RADIUS/t;for(const r of this.resizeHandles)if(S.hitTestCircle(n,e,r.x,r.y,a))return r;return null}hitTestRotation(n,e,t=1){if(!this.rotationHandle)return!1;const a=(Fn*2.67+2)/t;return S.hitTestCircle(n,e,this.rotationHandle.x,this.rotationHandle.y,a)}getRotationHandlePosition(){return this.rotationHandle}getCursor(n,e){const t=n.anchor.includes("middle")?"edge":"corner";return S.getCursorForWorldPosition(n.x,n.y,this.rotationAnchor.x,this.rotationAnchor.y,t,e,n.anchor)}}class pt{static calculateResize({element:n,handle:e,dx:t,dy:a,startData:r,snapSystem:s}){var D,P,M,W,B;const l=new S.Transform(n).worldDeltaToLocal(t,a),c=l.dx,d=l.dy,f=r.visualWidth??r.width??0,h=r.visualHeight??r.height??0,u=r.width??0,g=r.height??0;let m=f,p=h;e.anchor.includes("right")?m=f+c:e.anchor.includes("left")&&(m=f-c),e.anchor!=="middle-left"&&e.anchor!=="middle-right"&&(e.anchor.includes("bottom")?p=h+d:e.anchor.includes("top")&&(p=h-d));let y,b;if(e.anchor==="middle-left"||e.anchor==="middle-right"){const I=m-f;y=u+I,b=g}else if(e.anchor==="middle-top"||e.anchor==="middle-bottom"){const I=p-h;y=u,b=g+I}else{const I=m/f,H=p/h;y=u*I,b=g*H}const $=m,x=p;let w=!1;if(s&&n.transformType==="image"){const I=e.anchor??"",H=I==="top-left"||I==="top-right"||I==="bottom-left"||I==="bottom-right",q=I.startsWith("crop-");if(H&&!q){const Y=(D=s.activeSnaps)==null?void 0:D.x,nn=(P=s.activeSnaps)==null?void 0:P.y;if(!!Y||!!nn){const R=[Y,nn].find(F=>typeof F=="object"&&F!==null&&"frozenWidth"in F);if(R){const F=n,L=r.transformData,O=R.frozenWidth??((M=F.transformData)==null?void 0:M.width)??u,z=F.imageAspectRatio||(L!=null&&L.width&&(L!=null&&L.height)?L.width/L.height:null);let j=R.frozenHeight;j==null&&(z&&z!==0?j=O/z:(W=F.transformData)!=null&&W.height?j=F.transformData.height:j=g);const cn=u!==0?O/u:1,yn=g!==0?j/g:1;m=f*cn,p=h*yn,y=O,b=j,w=!0}}}}y=Math.max(50,y),b=Math.max(40,b);const v=n.clone(),C=v.resize(e.anchor,y,b,r);if(!e.anchor.includes("middle")&&((B=v.stroke)!=null&&B.enabled)&&r.strokeWidth!==void 0&&r.strokeWidth>0){const I=r.width??1,H=r.height??1,q=Math.sqrt(y/I*(b/H)),Y=Math.max(1,Math.round(r.strokeWidth*q*10)/10);v.stroke={...v.stroke,width:Y}}const T=w||C===!1,E=e.anchor.includes("top")||e.anchor.includes("bottom"),k="isCropping"in v&&v.isCropping,A="isGroup"in v&&v.isGroup;if(E&&!k&&!A){const I=n.getRotationAnchor(),H=this._calculateFixedCornerOffset({element:n,updatedElement:v,handle:e,rotationAnchor:I});v.x+=H.x,v.y+=H.y}return{element:v,isFrozen:T,unfrozenDimensions:w?{width:$,height:x}:void 0}}static _calculateFixedCornerOffset({element:n,updatedElement:e,handle:t,rotationAnchor:a}){const r=new S.Transform(n),{cos:s,sin:o}=r.getRenderingCosSin(),l=n.getVisualBoundingBox(),c=e.getVisualBoundingBox(),d=a,f=e.getRotationAnchor(),h=this._getFixedLocalCoords(t.anchor,l.width,l.height),u=h.x,g=h.y,m=l.x-d.x,p=l.y-d.y,y=m+u,b=p+g,$=y*s-b*o,x=y*o+b*s,w=d.x+$,v=d.y+x,C=this._getFixedLocalCoords(t.anchor,c.width,c.height),_=C.x,T=C.y,E=c.x-f.x,k=c.y-f.y,A=E+_,D=k+T,P=A*s-D*o,M=A*o+D*s,W=f.x+P,B=f.y+M;return{x:w-W,y:v-B}}static _getFixedLocalCoords(n,e,t){const a={x:0,y:0};switch(n){case"top-left":a.x=e,a.y=t;break;case"top-right":a.x=0,a.y=t;break;case"bottom-left":a.x=e,a.y=0;break;case"bottom-right":a.x=0,a.y=0;break;case"middle-left":a.x=e,a.y=t/2;break;case"middle-right":a.x=0,a.y=t/2;break;case"middle-top":a.x=e/2,a.y=t;break;case"middle-bottom":a.x=e/2,a.y=0;break}return a}}class We{constructor(){this.hooks={beforeResize:[],afterResize:[],beforePositionUpdate:[],afterPositionUpdate:[]}}addHook(n,e){if(!this.hooks[n])throw new Error(`Invalid hook stage: ${n}`);this.hooks[n].push(e)}removeHook(n,e){if(!this.hooks[n])return;const t=this.hooks[n].indexOf(e);t!==-1&&this.hooks[n].splice(t,1)}clearHooks(n){this.hooks[n]&&(this.hooks[n]=[])}clearAllHooks(){Object.keys(this.hooks).forEach(n=>{this.hooks[n]=[]})}runHooks(n,e){return this.hooks[n]?this.hooks[n].reduce((t,a)=>{const r=a(t);return r!==void 0?r:t},e):e}executeResize(n){const e=this.runHooks("beforeResize",n);let t=pt.calculateResize({...e,snapSystem:n.snapSystem});return t.handle=n.handle,t.startData=n.startData,t=this.runHooks("afterResize",t),t}executePositionUpdate(n,e){const t=this.runHooks("beforePositionUpdate",{position:n,element:e});return this.runHooks("afterPositionUpdate",t).position}}const gt=new We;class bt{constructor(n=null){this.state="IDLE",this.context={mode:null,startX:0,startY:0,startData:null,activeHandle:null,element:null},this.snapHandler=null,this.resizePipeline=n}setSnapHandler(n){this.snapHandler=n}setResizePipeline(n){this.resizePipeline=n}getState(){return this.state}getContext(){return this.context}isInteracting(){return this.state!=="IDLE"}startDrag(n,e,t,a=null){this.state="DRAGGING";const r=n.getTransformStartData();let s=r;if(a==="crop-image-drag"&&n.transformData){const o=n.transformData;s={...r,cropX:o.cropX,cropY:o.cropY,cropWidth:o.cropWidth,cropHeight:o.cropHeight}}this.context={mode:"drag",dragMode:a,startX:e,startY:t,startData:s,activeHandle:null,element:n}}getDragMode(){return this.context.dragMode}resetDragStart(n,e){this.state==="DRAGGING"&&(this.context.startX=n,this.context.startY=e)}updateDrag(n,e,t=null){if(this.state!=="DRAGGING")throw new Error("Cannot update drag: not in DRAGGING state");const a=n-this.context.startX,r=e-this.context.startY,s=this.context.startData;let o=s.x+a,l=s.y+r;if(this.snapHandler&&this.snapHandler.snapPosition&&this.context.element){const c=this.snapHandler.snapPosition({x:o,y:l},this.context.element,t);o=c.x,l=c.y}return{x:o,y:l}}startResize(n,e,t,a,r,s){this.state="RESIZING";const o=n.getTransformStartData(),l=n.clone();(e.anchor==="top-left"||e.anchor==="top-right"||e.anchor==="bottom-left"||e.anchor==="bottom-right")&&o.lineCount!==void 0&&l.transformType==="custom"&&(l._lockedLineCount=o.lineCount),this.context={mode:"resize",startX:t,startY:a,startData:{...o,visualX:s.x,visualY:s.y,visualWidth:s.width,visualHeight:s.height,bboxX:r.x,bboxY:r.y},activeHandle:e,element:l}}updateResize(n,e){if(this.state!=="RESIZING")throw new Error("Cannot update resize: not in RESIZING state");const t=n-this.context.startX,a=e-this.context.startY;return{dx:t,dy:a}}adjustResizeStart(n,e){this.state==="RESIZING"&&(this.context.startX+=n,this.context.startY+=e)}getResizeContext(){if(this.state!=="RESIZING")throw new Error("Cannot get resize context: not in RESIZING state");return{element:this.context.element,handle:this.context.activeHandle,startData:this.context.startData}}updateResizeElement(n){this.state==="RESIZING"&&(this.context.element=n)}resetResizeStartData(n,e,t){if(this.state!=="RESIZING")return;const a=n.getBoundingBox(),r=n.getVisualBoundingBox(),s=n.getTransformStartData();this.context.startX=e,this.context.startY=t,this.context.startData={...s,visualX:r.x,visualY:r.y,visualWidth:r.width,visualHeight:r.height,bboxX:a.x,bboxY:a.y}}startRotate(n,e,t,a,r){this.state="ROTATING",this.context={mode:"rotate",startX:e,startY:t,startData:{startAngle:a,currentRotation:r,elementData:n.getTransformStartData()},activeHandle:null,element:n}}updateRotate(n,e,t,a){if(this.state!=="ROTATING")throw new Error("Cannot update rotate: not in ROTATING state");const r=this.context.startData,o=(S.calculateAngle(t,a,n,e)-r.startAngle)*180/Math.PI;let l=r.currentRotation-o;return l=(l%360+360)%360,l>180&&(l-=360),this.snapHandler&&this.snapHandler.snapRotation&&this.context.element?this.snapHandler.snapRotation(l,this.context.element):l}getRotationContext(){if(this.state!=="ROTATING")throw new Error("Cannot get rotation context: not in ROTATING state");const n=this.context.startData;return{startAngle:n.startAngle,currentRotation:n.currentRotation}}startPinch(n,e,t){this.state="PINCHING";const a={x:(e.x+t.x)/2,y:(e.y+t.y)/2},r=t.x-e.x,s=t.y-e.y,o=Math.hypot(r,s),l=Math.atan2(s,r),c={elementData:n.getTransformStartData(),startCentroid:a,startDistance:o,startAngle:l};this.context={mode:"pinch",startX:a.x,startY:a.y,startData:c,activeHandle:null,element:n.clone()}}updatePinch(n,e){if(this.state!=="PINCHING")throw new Error("Cannot update pinch: not in PINCHING state");const t=this.context.startData,a={x:(n.x+e.x)/2,y:(n.y+e.y)/2},r=e.x-n.x,s=e.y-n.y,o=Math.hypot(r,s),l=Math.atan2(s,r),c=Math.max(t.startDistance,1e-4),d=o/c,f=Math.max(d,.05),h=l-t.startAngle;return{scale:f,rotationDelta:h,startCentroid:t.startCentroid,currentCentroid:a}}getPinchContext(){if(this.state!=="PINCHING")throw new Error("Cannot get pinch context: not in PINCHING state");const n=this.context.startData;return{element:this.context.element,startData:n.elementData}}end(){this.state="IDLE",this.context={mode:null,startX:0,startY:0,startData:null,activeHandle:null,element:null}}cancel(){this.end()}getActiveHandle(){return this.context.activeHandle}getMode(){return this.context.mode}}class wn{static resolve(n){return n.getRotationAnchor()}static getSnapAnchors(n){const e=n.getVisualBoundingBox(),t={topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomLeft:{x:e.x,y:e.y+e.height},bottomRight:{x:e.x+e.width,y:e.y+e.height},topCenter:{x:e.x+e.width/2,y:e.y},rightCenter:{x:e.x+e.width,y:e.y+e.height/2},bottomCenter:{x:e.x+e.width/2,y:e.y+e.height},leftCenter:{x:e.x,y:e.y+e.height/2},center:{x:e.x+e.width/2,y:e.y+e.height/2},rotation:this.resolve(n)};if(n.rotation!==0){const a=t.rotation,r=S.RotationUtils.toRadiansInverse(n.rotation);Object.keys(t).forEach(s=>{if(s==="rotation")return;const o=t[s],l=o.x-a.x,c=o.y-a.y,d=l*Math.cos(r)-c*Math.sin(r),f=l*Math.sin(r)+c*Math.cos(r);t[s]={x:a.x+d,y:a.y+f}})}return t}static getEdgeLines(n){const e=this.getSnapAnchors(n);return{top:{start:e.topLeft,end:e.topRight},right:{start:e.topRight,end:e.bottomRight},bottom:{start:e.bottomRight,end:e.bottomLeft},left:{start:e.bottomLeft,end:e.topLeft}}}static getAnchorTypes(){return["topLeft","topCenter","topRight","rightCenter","bottomRight","bottomCenter","bottomLeft","leftCenter","center","rotation"]}static hasCustomRotationAnchor(n){const e=n.getVisualBoundingBox(),t={x:e.x+e.width/2,y:e.y+e.height/2},a=this.resolve(n),r=.001;return Math.abs(a.x-t.x)>r||Math.abs(a.y-t.y)>r}}class Te{constructor(n){this.cellSize=n,this.cells=new Map,this.idIndex=new Map}clear(){this.cells.clear(),this.idIndex.clear()}insert(n){const e=this.getCellKey(n.x,n.y);let t=this.cells.get(e);t||(t=new Set,this.cells.set(e,t)),t.add(n);let a=this.idIndex.get(n.id);a||(a=new Set,this.idIndex.set(n.id,a)),a.add(e)}removeById(n){const e=this.idIndex.get(n);if(e){for(const t of e){const a=this.cells.get(t);if(a){for(const r of a)r.id===n&&a.delete(r);a.size===0&&this.cells.delete(t)}}this.idIndex.delete(n)}}queryNear(n,e,t,a){const r=[],s=Math.floor((n-t)/this.cellSize),o=Math.floor((n+t)/this.cellSize),l=Math.floor((e-t)/this.cellSize),c=Math.floor((e+t)/this.cellSize);for(let d=s;d<=o;d++)for(let f=l;f<=c;f++){const h=`${d},${f}`,u=this.cells.get(h);if(u)for(const g of u){if(a!==void 0&&g.id===a)continue;const m=g.x-n,p=g.y-e;m*m+p*p<=t*t&&r.push(g)}}return r}queryNearAxis(n,e,t,a){const r=[];if(n==="x"){const s=Math.floor((e-t)/this.cellSize),o=Math.floor((e+t)/this.cellSize);for(const[l,c]of this.cells){const d=l.indexOf(","),f=parseInt(l.substring(0,d),10);if(!(f<s||f>o))for(const h of c)a!==void 0&&h.id===a||Math.abs(h.x-e)<=t&&r.push(h)}}else{const s=Math.floor((e-t)/this.cellSize),o=Math.floor((e+t)/this.cellSize);for(const[l,c]of this.cells){const d=l.indexOf(","),f=parseInt(l.substring(d+1),10);if(!(f<s||f>o))for(const h of c)a!==void 0&&h.id===a||Math.abs(h.y-e)<=t&&r.push(h)}}return r}rebuild(n){this.clear();for(const e of n)this.insert(e)}getCellKey(n,e){return`${Math.floor(n/this.cellSize)},${Math.floor(e/this.cellSize)}`}}function fn(i){const n=i.transformData;if(n&&"width"in n&&typeof n.width=="number")return n.width}function Sn(i){const n=i.transformData;if(n&&"height"in n&&typeof n.height=="number")return n.height}function In(i,n){const e=i.transformData;return e&&"width"in e?(e.width=n,!0):!1}function Wn(i,n){const e=i.transformData;return e&&"height"in e?(e.height=n,!0):!1}class mt{constructor(n={}){this._extraSnapRects=[],this.snapThreshold=n.snapThreshold||rn.canvas.snapThreshold,this.enabled=n.enabled!==!1,this.showGuides=n.showGuides!==!1,this.guides=[],this.activeSnaps={x:null,y:null},this.stickyThreshold=n.stickyThreshold||15,this._spatialGrid=new Te(Math.max(this.snapThreshold*2,16)),this._anchorMetadata=new Map}setEnabled(n){this.enabled=n}setSnapThreshold(n){this.snapThreshold=n,this._spatialGrid=new Te(Math.max(n*2,16))}getGuides(){return this.guides}clearGuides(){this.guides=[]}clearSnapState(){this.activeSnaps.x=null,this.activeSnaps.y=null}setExtraSnapRects(n){this._extraSnapRects=n}_populateSpatialGrid(n){this._spatialGrid.clear(),this._anchorMetadata.clear();for(const e of n){const t=wn.getSnapAnchors(e);for(const[a,r]of Object.entries(t)){const s=`${e.id}:${a}`,o={x:r.x,y:r.y,id:s};this._spatialGrid.insert(o),this._anchorMetadata.set(s,{elementId:e.id,anchorKey:a,point:r})}}for(const e of this._extraSnapRects){const t=e.x+e.width/2,a=e.y+e.height/2,r=e.x+e.width,s=e.y+e.height,o={topLeft:{x:e.x,y:e.y},topRight:{x:r,y:e.y},bottomLeft:{x:e.x,y:s},bottomRight:{x:r,y:s},topCenter:{x:t,y:e.y},rightCenter:{x:r,y:a},bottomCenter:{x:t,y:s},leftCenter:{x:e.x,y:a},center:{x:t,y:a}},l=`__snap-rect:${e.id}`;for(const[c,d]of Object.entries(o)){const f=`${l}:${c}`;this._spatialGrid.insert({x:d.x,y:d.y,id:f}),this._anchorMetadata.set(f,{elementId:l,anchorKey:c,point:d})}}}snapPosition(n,e,t){if(!this.enabled||!t)return this.clearGuides(),n;const a=e.clone();a.x=n.x,a.y=n.y;const r=wn.getSnapAnchors(a),s=t.filter(b=>b.id!==e.id);this._populateSpatialGrid(s);let o=null,l=null,c=1/0,d=1/0;const f=[],h=[],u=[];for(const[b,$]of Object.entries(r)){const x=this._spatialGrid.queryNearAxis("x",$.x,this.snapThreshold);for(const v of x){const C=this._anchorMetadata.get(v.id);if(!C)continue;const _=C.point,T=C.anchorKey,E=Math.abs($.x-_.x);if(E<this.snapThreshold){const k={snapTo:_.x,offset:$.x-n.x,distance:E,guide:{type:"vertical",x:_.x,y1:Math.min($.y,_.y)-50,y2:Math.max($.y,_.y)+50,movingKey:b,otherKey:T}};f.push(k),E<c&&(c=E,o=k)}}const w=this._spatialGrid.queryNearAxis("y",$.y,this.snapThreshold);for(const v of w){const C=this._anchorMetadata.get(v.id);if(!C)continue;const _=C.point,T=C.anchorKey,E=Math.abs($.y-_.y);if(E<this.snapThreshold){const k={snapTo:_.y,offset:$.y-n.y,distance:E,guide:{type:"horizontal",y:_.y,x1:Math.min($.x,_.x)-50,x2:Math.max($.x,_.x)+50,movingKey:b,otherKey:T}};h.push(k),E<d&&(d=E,l=k)}}}let g=n.x,m=n.y;o&&(g=o.snapTo-o.offset),l&&(m=l.snapTo-l.offset);const p=new Map,y=new Map;for(const b of f){const $=p.get(b.snapTo);(!$||b.distance<$.distance)&&p.set(b.snapTo,b)}for(const b of h){const $=y.get(b.snapTo);(!$||b.distance<$.distance)&&y.set(b.snapTo,b)}for(const b of p.values())u.push(b.guide);for(const b of y.values())u.push(b.guide);return this.guides=u,{x:g,y:m}}_calculateFrozenFontSizeAtSnap(n,e,t,a,r){if(!r)return n.fontSize??0;const s=a!=null&&a.anchor?String(a.anchor):"";if(!(a&&(s.includes("top")||s.includes("bottom"))))return r.fontSize??0;const l=fn(n)??n.width??r.width;let c=l;s.includes("right")&&e!==0?c=l+e:s.includes("left")&&e!==0&&(c=l-e);const d=c/r.width;return(r.fontSize??0)*d}_isPositionBasedSnap(n,e){return e==="x"?!1:e==="y"?!(Sn(n)!==void 0||n.height!==void 0&&typeof n.height=="number"):!1}_getSnapKeysForHandle(n){return!n||!n.anchor?["topLeft","topRight","bottomLeft","bottomRight"]:n.anchor==="top-left"||n.anchor==="topLeft"?["topLeft"]:n.anchor==="top-right"||n.anchor==="topRight"?["topRight"]:n.anchor==="bottom-left"||n.anchor==="bottomLeft"?["bottomLeft"]:n.anchor==="bottom-right"||n.anchor==="bottomRight"?["bottomRight"]:n.anchor.includes("left")?["topLeft","bottomLeft"]:n.anchor.includes("right")?["topRight","bottomRight"]:n.anchor.includes("top")?["topLeft","topRight"]:n.anchor.includes("bottom")?["bottomLeft","bottomRight"]:[]}_getTargetSnapKeys(){return["topLeft","topRight","bottomLeft","bottomRight"]}_findXSnaps(n,e,t,a){const r=[],s=new Set(a);for(const o of t){const l=n[o];if(!l)continue;const c=this._spatialGrid.queryNearAxis("x",l.x,this.snapThreshold);for(const d of c){const f=this._anchorMetadata.get(d.id);if(!f||!s.has(f.anchorKey))continue;const h=f.point,u=f.anchorKey,g=Math.abs(l.x-h.x);g<this.snapThreshold&&r.push({distance:g,snapTo:h.x,currentValue:l.x,guide:{type:"vertical",x:h.x,y1:Math.min(l.y,h.y)-50,y2:Math.max(l.y,h.y)+50,movingKey:o,otherKey:u}})}}return r}_findYSnaps(n,e,t,a){const r=[],s=new Set(a);for(const o of t){const l=n[o];if(!l)continue;const c=this._spatialGrid.queryNearAxis("y",l.y,this.snapThreshold);for(const d of c){const f=this._anchorMetadata.get(d.id);if(!f||!s.has(f.anchorKey))continue;const h=f.point,u=f.anchorKey,g=Math.abs(l.y-h.y);g<this.snapThreshold&&r.push({distance:g,snapTo:h.y,currentValue:l.y,guide:{type:"horizontal",y:h.y,x1:Math.min(l.x,h.x)-50,x2:Math.max(l.x,h.x)+50,movingKey:o,otherKey:u}})}}return r}_prioritizeSnaps(n,e,t){if(!e||!e.anchor){n.sort((a,r)=>a.distance-r.distance);return}t==="x"?e.anchor.includes("left")?n.sort((a,r)=>{const s=a.guide.movingKey.includes("left")?-1e3:0,o=r.guide.movingKey.includes("left")?-1e3:0;return a.distance+s-(r.distance+o)}):e.anchor.includes("right")?n.sort((a,r)=>{const s=a.guide.movingKey.includes("right")?-1e3:0,o=r.guide.movingKey.includes("right")?-1e3:0;return a.distance+s-(r.distance+o)}):n.sort((a,r)=>a.distance-r.distance):t==="y"&&(e.anchor.includes("top")?n.sort((a,r)=>{const s=a.guide.movingKey.includes("top")?-1e3:0,o=r.guide.movingKey.includes("top")?-1e3:0;return a.distance+s-(r.distance+o)}):e.anchor.includes("bottom")?n.sort((a,r)=>{const s=a.guide.movingKey.includes("bottom")?-1e3:0,o=r.guide.movingKey.includes("bottom")?-1e3:0;return a.distance+s-(r.distance+o)}):n.sort((a,r)=>a.distance-r.distance))}_createGuideForSnap(n,e,t,a,r){const s=t[e];if(!s)return null;if(r==="x"){let o=1/0,l=-1/0;for(const c of Object.values(t))Math.abs(c.x-n.snapTo)<5&&(o=Math.min(o,c.y),l=Math.max(l,c.y));for(const c of a){const d=wn.getSnapAnchors(c);for(const f of Object.values(d))Math.abs(f.x-n.snapTo)<5&&(o=Math.min(o,f.y),l=Math.max(l,f.y))}return(!isFinite(o)||!isFinite(l))&&(o=s.y,l=s.y),{snapTo:n.snapTo,currentValue:s.x,distance:0,guide:{type:"vertical",x:n.snapTo,y1:o-50,y2:l+50,movingKey:e,otherKey:"snap"}}}else if(r==="y"){let o=1/0,l=-1/0;for(const c of Object.values(t))Math.abs(c.y-n.snapTo)<5&&(o=Math.min(o,c.x),l=Math.max(l,c.x));for(const c of a){const d=wn.getSnapAnchors(c);for(const f of Object.values(d))Math.abs(f.y-n.snapTo)<5&&(o=Math.min(o,f.x),l=Math.max(l,f.x))}return(!isFinite(o)||!isFinite(l))&&(o=s.x,l=s.x),{snapTo:n.snapTo,currentValue:s.y,distance:0,guide:{type:"horizontal",y:n.snapTo,x1:o-50,x2:l+50,movingKey:e,otherKey:"snap"}}}return null}_getAdjustedStickyThreshold(n,e){const t=e.getVisualBoundingBox(),a=t.width/t.height;let r=this.stickyThreshold;return n==="x"?a>1&&(r=this.stickyThreshold/Math.sqrt(a)):n==="y"&&a<1&&(r=this.stickyThreshold*Math.sqrt(a)),r}_calculateFrozenDimensionsAtSnap(n,e,t,a,r){const s=fn(n)??n.width??0,o=Sn(n)??n.height??0;let l=s,c=o;const d=n.transformType==="image",f=d?n.imageAspectRatio||(s&&o?s/o:null):null,h=a.toLowerCase();return e==="x"?h.includes("right")?(l=s+t,d&&f&&(c=l/f)):h.includes("left")&&(l=s-t,d&&f&&(c=l/f)):e==="y"&&(h.includes("bottom")?(c=o+t,d&&f&&(l=c*f)):h.includes("top")&&(c=o-t,d&&f&&(l=c*f))),{frozenWidth:l,frozenHeight:c}}_processStickySnap(n,e,t,a,r,s,o){const l=this.activeSnaps[n];let c=0,d=null;if(l){const f=e[l.anchorKey];if(f){const h=n==="x"?f.x:f.y,u=Math.abs(h-l.snapTo),g=this._getAdjustedStickyThreshold(n,a);if(u<g){if(c=l.snapTo-h,!(n==="y"&&l.isPositionBasedSnap)){const p=this._calculateFrozenFontSizeAtSnap(a,n==="x"?c:0,n==="y"?c:0,r,s);p!==l.frozenFontSize&&(l.frozenFontSize=p)}d=this._createGuideForSnap(l,l.anchorKey,e,o,n)}else{const m=l;if(this.activeSnaps[n]=null,t.length>0&&t[0].distance<this.snapThreshold){d=t[0],c=d.snapTo-d.currentValue;const p=m&&m.anchorKey===d.guide.movingKey&&Math.abs(m.snapTo-d.snapTo)<1,y=p?m.frozenFontSize:this._calculateFrozenFontSizeAtSnap(a,n==="x"?c:0,n==="y"?c:0,r,s),b=this._isPositionBasedSnap(a,n);let $;p?$=m.frozenPosition:b?$={x:n==="x"?a.x+c:a.x,y:n==="y"?a.y+c:a.y}:$={x:a.x,y:a.y};const x=this._calculateFrozenDimensionsAtSnap(a,n,c,d.guide.movingKey,r);this.activeSnaps[n]={snapTo:d.snapTo,anchorKey:d.guide.movingKey,frozenFontSize:y,frozenWidth:x.frozenWidth,frozenHeight:x.frozenHeight,frozenPosition:$,isPositionBasedSnap:b}}}}else this.activeSnaps[n]=null}else if(t.length>0&&t[0].distance<this.snapThreshold){d=t[0],c=d.snapTo-d.currentValue;const f=this.activeSnaps[n],h=f&&f.anchorKey===d.guide.movingKey&&Math.abs(f.snapTo-d.snapTo)<1,u=h?f.frozenFontSize:this._calculateFrozenFontSizeAtSnap(a,n==="x"?c:0,n==="y"?c:0,r,s),g=this._isPositionBasedSnap(a,n);let m;h?m=f.frozenPosition:g?m={x:n==="x"?a.x+c:a.x,y:n==="y"?a.y+c:a.y}:m={x:a.x,y:a.y};const p=this._calculateFrozenDimensionsAtSnap(a,n,c,d.guide.movingKey,r);this.activeSnaps[n]={snapTo:d.snapTo,anchorKey:d.guide.movingKey,frozenFontSize:u,frozenWidth:p.frozenWidth,frozenHeight:p.frozenHeight,frozenPosition:m,isPositionBasedSnap:g}}return{snapDelta:c,bestSnap:d}}_adjustElementForRightResize(n,e,t){const a=n.getVisualBoundingBox(),r=n.transformType==="image";if(!r){const s=fn(n);s!==void 0?In(n,s+e):n.width!==void 0&&(n.width+=e)}if(t.anchor==="middle-right"){const s=S.RotationUtils.toRadiansInverse(n.rotation),o=Math.cos(s),l=Math.sin(s);n.x+=e/2*o,n.y+=e/2*l}else if(!r){const o=n.getVisualBoundingBox().x-a.x;o!==0&&(n.x-=o)}}_adjustElementForLeftResize(n,e,t){const a=n.getVisualBoundingBox(),r=n.transformType==="image";if(!r){const s=fn(n);s!==void 0?In(n,s-e):n.width!==void 0&&(n.width-=e)}if(t.anchor==="middle-left"){const s=S.RotationUtils.toRadiansInverse(n.rotation),o=Math.cos(s),l=Math.sin(s);n.x+=e/2*o,n.y+=e/2*l}else if(n.x+=e,!r){const s=n.getVisualBoundingBox(),o=s.x+s.width-(a.x+a.width);o!==0&&(n.x-=o)}}_adjustElementForBottomResize(n,e,t){const a=n.getVisualBoundingBox(),r=n.transformType==="image";if(!r){const l=Sn(n);l!==void 0?Wn(n,l+e):n.height!==void 0&&(n.height+=e)}const s=n.getVisualBoundingBox(),o=Math.abs(s.height-a.height)>.01;if(t.anchor==="middle-bottom"){const l=S.RotationUtils.toRadiansInverse(n.rotation),c=Math.cos(l),d=Math.sin(l);n.x-=e/2*d,n.y+=e/2*c}else if(!r&&o){const l=s.y-a.y;l!==0&&(n.y-=l)}else r||(n.y+=e)}_adjustElementForTopResize(n,e,t){const a=n.getVisualBoundingBox(),r=n.transformType==="image";if(!r){const l=Sn(n);l!==void 0?Wn(n,l-e):n.height!==void 0&&(n.height-=e)}const s=n.getVisualBoundingBox(),o=Math.abs(s.height-a.height)>.01;if(t.anchor==="middle-top"){const l=S.RotationUtils.toRadiansInverse(n.rotation),c=Math.cos(l),d=Math.sin(l);n.x-=e/2*d,n.y+=e/2*c}else{const l=!r&&o;if(n.y+=e,l){const c=n.getVisualBoundingBox(),d=c.y+c.height-(a.y+a.height);d!==0&&(n.y-=d)}}}snapDimensions(n,e,t=null){var v,C,_,T,E;if(!this.enabled||!e)return this.clearGuides(),n;const{element:a}=n,r=n.handle;let s;const o=a.transformType==="image",l=this.activeSnaps.x!==null||this.activeSnaps.y!==null;if(o&&l&&n.isFrozen&&n.unfrozenDimensions){const k=a.clone();if(k.transformData){const A=a.getVisualBoundingBox(),D=A.width,P=A.height,M=(t==null?void 0:t.width)??a.width??0,W=(t==null?void 0:t.height)??a.height??0,B=(t==null?void 0:t.visualWidth)??D,I=(t==null?void 0:t.visualHeight)??P,H=n.unfrozenDimensions.width/B,q=n.unfrozenDimensions.height/I;In(k,M*H),Wn(k,W*q)}s=wn.getSnapAnchors(k)}else s=wn.getSnapAnchors(a);const c=e.filter(k=>k.id!==a.id);if(c.length===0)return this.clearGuides(),n;this._populateSpatialGrid(c);const d=this._getSnapKeysForHandle(r),f=this._getTargetSnapKeys(),h=this._findXSnaps(s,c,d,f),u=this._findYSnaps(s,c,d,f);this._prioritizeSnaps(h,r,"x"),this._prioritizeSnaps(u,r,"y");const g=this._processStickySnap("x",s,h,a,r,t,c),m=this._processStickySnap("y",s,u,a,r,t,c),p=g.snapDelta,y=m.snapDelta,b=g.bestSnap,$=m.bestSnap,x=[];b&&x.push(b.guide),$&&x.push($.guide),this.guides=x,x.length>0;const w=r&&(r.anchor==="top-left"||r.anchor==="top-right"||r.anchor==="bottom-left"||r.anchor==="bottom-right");if(o&&w&&(p!==0||y!==0))return n;if(p!==0||y!==0){const k=a.clone(),A=this.activeSnaps.x||this.activeSnaps.y,D=(A==null?void 0:A.frozenFontSize)??a.fontSize??0,P=(A==null?void 0:A.frozenWidth)??fn(a)??a.width??0,M=(A==null?void 0:A.frozenHeight)??Sn(a)??a.height??0,W=(A==null?void 0:A.frozenPosition)??{x:a.x,y:a.y},B=k.isCropping&&!String(r.anchor).startsWith("crop-");if(!B)if(r&&r.anchor){if(p!==0){const R=(v=this.activeSnaps.x)==null?void 0:v.anchorKey,F=R==null?void 0:R.toLowerCase();F&&F.includes("right")?this._adjustElementForRightResize(k,p,r):F&&F.includes("left")?this._adjustElementForLeftResize(k,p,r):k.x+=p}if(y!==0){const R=(C=this.activeSnaps.y)==null?void 0:C.anchorKey,F=R==null?void 0:R.toLowerCase();F&&F.includes("bottom")?this._adjustElementForBottomResize(k,y,r):F&&F.includes("top")?this._adjustElementForTopResize(k,y,r):k.y+=y}}else k.x+=p,k.y+=y;k.fontSize!==void 0&&(k.fontSize=D);const I=k.transformType==="image",H=this.activeSnaps.x!==null||this.activeSnaps.y!==null;if(I&&H){if(fn(k)!==void 0){const R=this.activeSnaps.x||this.activeSnaps.y;let F=P,L=M;R&&(F=R.frozenWidth??F,L=R.frozenHeight??L);const O=fn(a),z=Sn(a),j=k.imageAspectRatio||(O&&z?O/z:null);j&&j!==0&&(L=F/j),In(k,F),Wn(k,L),R&&(R.frozenWidth=F,R.frozenHeight=L)}}else(((_=this.activeSnaps.y)==null?void 0:_.isPositionBasedSnap)||!1)&&(fn(k)!==void 0?In(k,P):k.width!==void 0&&(k.width=P));const q=r&&(r.anchor==="middle-left"||r.anchor==="middle-right"),Y=r&&(r.anchor==="middle-top"||r.anchor==="middle-bottom"),nn=((T=this.activeSnaps.x)==null?void 0:T.isPositionBasedSnap)||!1,N=((E=this.activeSnaps.y)==null?void 0:E.isPositionBasedSnap)||!1;return(p===0||nn)&&!q&&!Y&&!B&&(k.x=W.x),(y===0||N)&&!Y&&!q&&!B&&(k.y=W.y),{...n,element:k,snapAdjustment:{dx:p,dy:y},isInStickySnap:!0}}return n}snapRotation(n,e,t){if(!this.enabled)return n;const a=[0,45,90,135,180,225,270,315,360],r=5;for(const s of a)if(S.isNear(n,s,r))return s;return n}}class yt{constructor(n={}){this.lastSnapTarget=null,this.detectionThreshold=n.detectionThreshold||100,this.minDistance=n.minDistance||10,this.enabled=n.enabled!==!1,this.showLabels=n.showLabels!==!1,this.indicators=[]}setEnabled(n){this.enabled=n}setDetectionThreshold(n){this.detectionThreshold=n}getIndicators(){return this.indicators}clearIndicators(){this.indicators=[],this.lastSnapTarget=null}snapToSpacing(n,e,t){if(!this.enabled||!t)return n;const a=S.SPACING_SNAP_THRESHOLD,r=t.filter(p=>p.id!==e.id);if(r.length===0)return n;const s=e.clone();s.x=n.x,s.y=n.y;const o=s.getVisualBoundingBox(),l=o.x-n.x,c=o.y-n.y;let d=n.x,f=n.y,h=!1,u=!1;const g=r.filter(p=>{const y=p.getVisualBoundingBox();return!(o.x+o.width<y.x||o.x>y.x+y.width)});if(g.sort((p,y)=>{const b=p.getVisualBoundingBox(),$=y.getVisualBoundingBox();return b.y-$.y}),g.length>=1){let p=null,y=null;for(const x of g){const w=x.getVisualBoundingBox();w.y+w.height<=o.y?(!p||w.y>p.getVisualBoundingBox().y)&&(p=x):w.y>=o.y+o.height&&(!y||w.y<y.getVisualBoundingBox().y)&&(y=x)}const b=[];for(let x=0;x<g.length-1;x++){const w=g[x].getVisualBoundingBox(),C=g[x+1].getVisualBoundingBox().y-(w.y+w.height);b.push(C)}let $=null;if(p){const x=p.getVisualBoundingBox(),w=o.y-(x.y+x.height);for(const v of b)if(Math.abs(w-v)<=a){$=v;break}}if(!$&&y){const w=y.getVisualBoundingBox().y-(o.y+o.height);for(const v of b)if(Math.abs(w-v)<=a){$=v;break}}if($!==null&&$>0){if(p){const x=p.getVisualBoundingBox(),w=o.y-(x.y+x.height);Math.abs(w-$)<=a&&(f=x.y+x.height+$-c,u=!0)}if(!u&&y){const x=y.getVisualBoundingBox(),w=x.y-(o.y+o.height);Math.abs(w-$)<=a&&(f=x.y-o.height-$-c,u=!0)}}}const m=r.filter(p=>{const y=p.getVisualBoundingBox();return!(o.y+o.height<y.y||o.y>y.y+y.height)});if(m.sort((p,y)=>{const b=p.getVisualBoundingBox(),$=y.getVisualBoundingBox();return b.x-$.x}),m.length>=1){let p=null,y=null;for(const x of m){const w=x.getVisualBoundingBox();w.x+w.width<=o.x?(!p||w.x>p.getVisualBoundingBox().x)&&(p=x):w.x>=o.x+o.width&&(!y||w.x<y.getVisualBoundingBox().x)&&(y=x)}const b=[];for(let x=0;x<m.length-1;x++){const w=m[x].getVisualBoundingBox(),C=m[x+1].getVisualBoundingBox().x-(w.x+w.width);b.push(C)}let $=null;if(p){const x=p.getVisualBoundingBox(),w=o.x-(x.x+x.width);for(const v of b)if(Math.abs(w-v)<=a){$=v;break}}if(!$&&y){const w=y.getVisualBoundingBox().x-(o.x+o.width);for(const v of b)if(Math.abs(w-v)<=a){$=v;break}}if($!==null&&$>0){if(p){const x=p.getVisualBoundingBox(),w=o.x-(x.x+x.width);Math.abs(w-$)<=a&&(d=x.x+x.width+$-l,h=!0)}if(!h&&y){const x=y.getVisualBoundingBox(),w=x.x-(o.x+o.width);Math.abs(w-$)<=a&&(d=x.x-o.width-$-l,h=!0)}}}return this.lastSnapTarget=h||u?{x:d,y:f}:null,{x:d,y:f}}detectSpacing(n,e,t=!1){if(!this.enabled||!e)return this.clearIndicators(),[];const a=e.filter(f=>f.id!==n.id);if(a.length===0)return this.clearIndicators(),[];const r=n.getVisualBoundingBox(),s=[],o=[],l=[],c=[];for(const f of a){const h=f.getVisualBoundingBox(),u=r.x-(h.x+h.width),g=h.x-(r.x+r.width),m=r.y-(h.y+h.height),p=h.y-(r.y+r.height),y=!(r.y+r.height<h.y||r.y>h.y+h.height),b=!(r.x+r.width<h.x||r.x>h.x+h.width);u>=this.minDistance&&u<this.detectionThreshold&&y&&s.push({element:f,distance:u}),g>=this.minDistance&&g<this.detectionThreshold&&y&&o.push({element:f,distance:g}),m>=this.minDistance&&m<this.detectionThreshold&&b&&l.push({element:f,distance:m}),p>=this.minDistance&&p<this.detectionThreshold&&b&&c.push({element:f,distance:p})}s.sort((f,h)=>f.distance-h.distance),o.sort((f,h)=>f.distance-h.distance),l.sort((f,h)=>f.distance-h.distance),c.sort((f,h)=>f.distance-h.distance);const d=[];if(t){const f=this.detectAllMeasurements(n,e);d.push(...f)}else{if(s.length>0){const f=this.detectConsistentSpacing(n,r,s,"left",a);d.push(...f)}if(o.length>0){const f=this.detectConsistentSpacing(n,r,o,"right",a);d.push(...f)}if(l.length>0){const f=this.detectConsistentSpacing(n,r,l,"top",a);d.push(...f)}if(c.length>0){const f=this.detectConsistentSpacing(n,r,c,"bottom",a);d.push(...f)}}return this.indicators=d,d}detectAllMeasurements(n,e){const t=[],a=n.getVisualBoundingBox(),r=e.filter(c=>c.id!==n.id),s=this.detectionThreshold*3;let o=0,l=0;for(const c of r){const d=c.getVisualBoundingBox();if(Math.min(Math.abs(a.x-(d.x+d.width)),Math.abs(d.x-(a.x+a.width)),Math.abs(a.y-(d.y+d.height)),Math.abs(d.y-(a.y+a.height)))>s)continue;let h=0,u=!1,g=0,m=0,p=0;const b=-30*(o%2===0?1:-1);d.x>=a.x+a.width?(h=d.x-(a.x+a.width),h>=this.minDistance&&(u=!0,g=a.x+a.width,m=d.x,p=(a.y+a.height/2+d.y+d.height/2)/2+b)):a.x>=d.x+d.width&&(h=a.x-(d.x+d.width),h>=this.minDistance&&(u=!0,g=d.x+d.width,m=a.x,p=(a.y+a.height/2+d.y+d.height/2)/2+b)),u&&(t.push({type:"horizontal",distance:Math.round(h),x1:g,x2:m,y:p,labelX:(g+m)/2,labelY:p,isAltHover:!0}),o++);let $=0,x=!1,w=0,v=0,C=0;const T=30*(l%2===0?1:-1);d.y>=a.y+a.height?($=d.y-(a.y+a.height),$>=this.minDistance&&(x=!0,w=(a.x+a.width/2+d.x+d.width/2)/2+T,v=a.y+a.height,C=d.y)):a.y>=d.y+d.height&&($=a.y-(d.y+d.height),$>=this.minDistance&&(x=!0,w=(a.x+a.width/2+d.x+d.width/2)/2+T,v=d.y+d.height,C=a.y)),x&&(t.push({type:"vertical",distance:Math.round($),x:w,y1:v,y2:C,labelX:w,labelY:(v+C)/2,isAltHover:!0}),l++)}return t}detectConsistentSpacing(n,e,t,a,r){const s=[],l=t[0],c=l.distance,d=l.element.getVisualBoundingBox(),f=this.checkIfWouldSnap(e,c,a,r);if(this.addIndicatorForDirection(s,e,d,c,a,f),a==="left"||a==="right"){const h=r.filter(u=>{if(u.id===n.id)return!1;const g=u.getVisualBoundingBox();return!(e.y+e.height<g.y||e.y>g.y+g.height)});if(h.sort((u,g)=>{const m=u.getVisualBoundingBox(),p=g.getVisualBoundingBox();return m.x-p.x}),a==="left")for(let u=0;u<h.length-1;u++){const g=h[u],m=h[u+1],p=g.getVisualBoundingBox(),y=m.getVisualBoundingBox(),b=y.x-(p.x+p.width);if(Math.abs(b-c)<=16&&b>=this.minDistance){const $=Math.max(p.y,y.y),x=Math.min(p.y+p.height,y.y+y.height),w=($+x)/2;s.push({type:"horizontal",distance:Math.round(b),x1:p.x+p.width,x2:y.x,y:w,labelX:(p.x+p.width+y.x)/2,labelY:w})}}else for(let u=0;u<h.length-1;u++){const g=h[u],m=h[u+1],p=g.getVisualBoundingBox(),y=m.getVisualBoundingBox(),b=y.x-(p.x+p.width);if(Math.abs(b-c)<=16&&b>=this.minDistance){const $=Math.max(p.y,y.y),x=Math.min(p.y+p.height,y.y+y.height),w=($+x)/2;s.push({type:"horizontal",distance:Math.round(b),x1:p.x+p.width,x2:y.x,y:w,labelX:(p.x+p.width+y.x)/2,labelY:w})}}}else{const h=r.filter(u=>{if(u.id===n.id)return!1;const g=u.getVisualBoundingBox();return!(e.x+e.width<g.x||e.x>g.x+g.width)});if(h.sort((u,g)=>{const m=u.getVisualBoundingBox(),p=g.getVisualBoundingBox();return m.y-p.y}),a==="top")for(let u=0;u<h.length-1;u++){const g=h[u],m=h[u+1],p=g.getVisualBoundingBox(),y=m.getVisualBoundingBox(),b=y.y-(p.y+p.height);if(Math.abs(b-c)<=16&&b>=this.minDistance){const $=Math.max(p.x,y.x),x=Math.min(p.x+p.width,y.x+y.width),w=($+x)/2;s.push({type:"vertical",distance:Math.round(b),x:w,y1:p.y+p.height,y2:y.y,labelX:w,labelY:(p.y+p.height+y.y)/2})}}else for(let u=0;u<h.length-1;u++){const g=h[u],m=h[u+1],p=g.getVisualBoundingBox(),y=m.getVisualBoundingBox(),b=y.y-(p.y+p.height);if(Math.abs(b-c)<=16&&b>=this.minDistance){const $=Math.max(p.x,y.x),x=Math.min(p.x+p.width,y.x+y.width),w=($+x)/2;s.push({type:"vertical",distance:Math.round(b),x:w,y1:p.y+p.height,y2:y.y,labelX:w,labelY:(p.y+p.height+y.y)/2})}}}return s}checkIfWouldSnap(n,e,t,a){const r=S.SPACING_SNAP_THRESHOLD;if(t==="top"||t==="bottom"){const s=a.filter(o=>{const l=o.getVisualBoundingBox();return!(n.x+n.width<l.x||n.x>l.x+l.width)});if(s.length>=1){s.sort((l,c)=>{const d=l.getVisualBoundingBox(),f=c.getVisualBoundingBox();return d.y-f.y});const o=[];for(let l=0;l<s.length-1;l++){const c=s[l].getVisualBoundingBox(),f=s[l+1].getVisualBoundingBox().y-(c.y+c.height);o.push(f)}if(o.length>0){const l=o.reduce((f,h)=>f+h,0)/o.length;return Math.abs(e-l)<=r}}return!1}else{const s=a.filter(o=>{const l=o.getVisualBoundingBox();return!(n.y+n.height<l.y||n.y>l.y+l.height)});if(s.length>=1){s.sort((l,c)=>{const d=l.getVisualBoundingBox(),f=c.getVisualBoundingBox();return d.x-f.x});const o=[];for(let l=0;l<s.length-1;l++){const c=s[l].getVisualBoundingBox(),f=s[l+1].getVisualBoundingBox().x-(c.x+c.width);o.push(f)}if(o.length>0){const l=o.reduce((f,h)=>f+h,0)/o.length;return Math.abs(e-l)<=r}}return!1}}addIndicatorForDirection(n,e,t,a,r,s=!1){if(r==="left"){const o=Math.max(e.y,t.y),l=Math.min(e.y+e.height,t.y+t.height),c=(o+l)/2;n.push({type:"horizontal",distance:Math.round(a),x1:t.x+t.width,x2:e.x,y:c,labelX:(t.x+t.width+e.x)/2,labelY:c,isSnapTarget:s})}else if(r==="right"){const o=Math.max(e.y,t.y),l=Math.min(e.y+e.height,t.y+t.height),c=(o+l)/2;n.push({type:"horizontal",distance:Math.round(a),x1:e.x+e.width,x2:t.x,y:c,labelX:(e.x+e.width+t.x)/2,labelY:c,isSnapTarget:s})}else if(r==="top"){const o=Math.max(e.x,t.x),l=Math.min(e.x+e.width,t.x+t.width),c=(o+l)/2;n.push({type:"vertical",distance:Math.round(a),x:c,y1:t.y+t.height,y2:e.y,labelX:c,labelY:(t.y+t.height+e.y)/2,isSnapTarget:s})}else if(r==="bottom"){const o=Math.max(e.x,t.x),l=Math.min(e.x+e.width,t.x+t.width),c=(o+l)/2;n.push({type:"vertical",distance:Math.round(a),x:c,y1:e.y+e.height,y2:t.y,labelX:c,labelY:(e.y+e.height+t.y)/2,isSnapTarget:s})}}}const xt=S.createLogger("TextureManager"),On=class On{static async loadTexture(n){if(this.cache.has(n))return this.cache.get(n);if(this.loading.has(n))return this.loading.get(n);const e=this.resolveTextureUrl(n),t=new Promise((a,r)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.cache.set(n,s),this.cache.set(e,s),this.loading.delete(n),this.loading.delete(e),a(s)},s.onerror=()=>{xt.error("Failed to load texture:",e),this.loading.delete(n),this.loading.delete(e),r(new Error(`Failed to load texture: ${e}`))},s.src=e});return this.loading.set(n,t),e!==n&&this.loading.set(e,t),t}static getTexture(n){const e=this.resolveTextureUrl(n);return this.cache.get(n)||this.cache.get(e)||null}static async preloadTextures(n){await Promise.all(n.map(e=>this.loadTexture(e)))}static async preloadAllTextures(){await this.preloadTextures(this.TEXTURES.map(n=>n.id))}static clearCache(){this.cache.clear(),this.loading.clear()}static resolveTextureUrl(n){if(n.startsWith("http://")||n.startsWith("https://")||n.startsWith("/")||n.startsWith("data:"))return n;const e=this.TEXTURES.find(t=>t.id===n);return e?e.url:`/textures/${n}`}static getTextureInfo(n){return this.TEXTURES.find(e=>e.id===n)}static getAllTextures(){return[...this.TEXTURES]}static getTexturesByCategory(n){return this.TEXTURES.filter(e=>e.category===n)}static getTexturePresetColor(n){const e=this.TEXTURES.find(t=>t.id===n);return(e==null?void 0:e.presetColor)||"#ffffff"}};On.cache=new Map,On.loading=new Map,On.TEXTURES=[{id:"glass-frame",name:"Glass Frame",url:"/textures/glass-frame.svg",category:"glass",presetColor:"#ccc"}];let sn=On;const ae=S.createLogger("ArtboardRenderer"),$t={showLabel:!0,showBorder:!0,borderColor:"",borderWidth:1,labelFontSize:14,labelColor:"",labelPadding:8,selectedBorderColor:"",selectedBorderWidth:2,showPreviewBackground:!0,borderRadius:0};class xe{constructor(n={}){this.options={...$t,...n}}render(n,e,t=!1){n.save(),this.renderBackground(n,e),this.options.showBorder&&this.renderBorder(n,e,t),this.options.showLabel&&this.renderLabel(n,e,t),n.restore()}renderBackground(n,e){n.save(),this.applyClipPath(n,e),this.options.showPreviewBackground&&e.previewBackgroundColor&&e.previewBackgroundColor!=="transparent"&&(n.fillStyle=e.previewBackgroundColor,n.fillRect(e.x,e.y,e.width,e.height)),e.backgroundType==="texture"&&e.backgroundTexture?this.renderTextureBackground(n,e):e.backgroundType==="transparent"||e.backgroundColor==="transparent"?this.renderCheckerboard(n,e.x,e.y,e.width,e.height):(n.fillStyle=e.backgroundColor,n.fillRect(e.x,e.y,e.width,e.height)),n.restore()}renderTextureBackground(n,e){const t=sn.getTexture(e.backgroundTexture),a=sn.getTexturePresetColor(e.backgroundTexture);if(n.fillStyle=a,n.fillRect(e.x,e.y,e.width,e.height),!t||!t.complete){sn.loadTexture(e.backgroundTexture).catch(r=>{ae.error("Failed to load texture:",r)});return}n.save(),n.beginPath(),n.rect(e.x,e.y,e.width,e.height),n.clip(),n.drawImage(t,e.x,e.y,e.width,e.height),n.restore()}renderCheckerboard(n,e,t,a,r){const o="#ffffff",l="#d0d0d0";n.save(),n.beginPath(),n.rect(e,t,a,r),n.clip(),n.fillStyle=o,n.fillRect(e,t,a,r),n.fillStyle=l;for(let c=0;c<Math.ceil(r/16);c++)for(let d=0;d<Math.ceil(a/16);d++)(c+d)%2===1&&n.fillRect(e+d*16,t+c*16,16,16);n.restore()}renderBorder(n,e,t){const{x:a,y:r,width:s,height:o,clipShape:l}=e,c=this.options.borderColor||S.getThemeArtboardBorderColor(),d=this.options.selectedBorderColor||S.getThemeAccentColor();if(n.strokeStyle=t?d:c,n.lineWidth=t?this.options.selectedBorderWidth:this.options.borderWidth,n.beginPath(),!l||l==="rectangle")if(this.options.borderRadius>0){const f=Math.min(this.options.borderRadius,Math.min(s,o)/2);this.roundedRect(n,a,r,s,o,f)}else n.rect(a,r,s,o);else if(l==="circle"){const f=a+s/2,h=r+o/2,u=Math.min(s,o)/2;n.arc(f,h,u,0,Math.PI*2)}else if(typeof l=="object"&&l.type==="rounded"){const f=Math.min(l.radius,Math.min(s,o)/2);this.roundedRect(n,a,r,s,o,f)}else if(typeof l=="object"&&l.type==="path")try{const f=new Path2D(l.d);n.save(),n.translate(a,r),n.stroke(f),n.restore();return}catch(f){ae.warn("Invalid SVG path for border, falling back to rectangle:",f),n.rect(a,r,s,o)}n.stroke()}renderLabel(n,e,t){const a=this.options.labelFontSize,r=this.options.labelPadding,s=`${e.name} (${Math.round(e.width)} × ${Math.round(e.height)})`,o=e.x,l=e.y-r;n.font=`${a}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;const c=this.options.selectedBorderColor||S.getThemeAccentColor(),d=this.options.labelColor||S.getThemeArtboardLabelColor();n.fillStyle=t?c:d,n.textAlign="left",n.textBaseline="bottom",n.fillText(s,o,l)}renderMultiple(n,e,t){e.forEach(a=>{const r=a.id===t;this.render(n,a,r)})}clipToArtboard(n,e){n.save(),this.applyClipPath(n,e)}applyClipPath(n,e){const{x:t,y:a,width:r,height:s,clipShape:o}=e;if(this.options.borderRadius>0,n.beginPath(),!o||o==="rectangle")if(this.options.borderRadius>0){const l=Math.min(this.options.borderRadius,Math.min(r,s)/2);this.roundedRect(n,t,a,r,s,l)}else n.rect(t,a,r,s);else if(o==="circle"){const l=t+r/2,c=a+s/2,d=Math.min(r,s)/2;n.arc(l,c,d,0,Math.PI*2)}else if(typeof o=="object"&&o.type==="rounded"){const l=Math.min(o.radius,Math.min(r,s)/2);this.roundedRect(n,t,a,r,s,l)}else if(typeof o=="object"&&o.type==="path")try{const l=new Path2D(o.d);n.translate(t,a),n.clip(l),n.translate(-t,-a);return}catch(l){ae.warn("Invalid SVG path, falling back to rectangle:",l),n.rect(t,a,r,s)}n.clip()}roundedRect(n,e,t,a,r,s){typeof n.roundRect=="function"?n.roundRect(e,t,a,r,s):(n.moveTo(e+s,t),n.lineTo(e+a-s,t),n.arcTo(e+a,t,e+a,t+s,s),n.lineTo(e+a,t+r-s),n.arcTo(e+a,t+r,e+a-s,t+r,s),n.lineTo(e+s,t+r),n.arcTo(e,t+r,e,t+r-s,s),n.lineTo(e,t+s),n.arcTo(e,t,e+s,t,s))}restoreClip(n){n.restore()}renderOutline(n,e,t,a,r,s=!1){n.save(),n.setLineDash([5,5]),n.strokeStyle=s?"#0066cc":"#999",n.lineWidth=1,n.strokeRect(e,t,a,r),n.restore()}renderResizeHandles(n,e){const{x:a,y:r,width:s,height:o}=e,l=[{x:a,y:r},{x:a+s,y:r},{x:a,y:r+o},{x:a+s,y:r+o}];n.save(),l.forEach(c=>{n.fillStyle="#fff",n.strokeStyle="#0066cc",n.lineWidth=2,n.fillRect(c.x-8/2,c.y-8/2,8,8),n.strokeRect(c.x-8/2,c.y-8/2,8,8)}),n.restore()}setOptions(n){this.options={...this.options,...n}}getOptions(){return{...this.options}}static createForExport(n={}){return new xe({...n,showPreviewBackground:!1})}willRenderPreviewBackground(n){return!!(this.options.showPreviewBackground&&n.previewBackgroundColor&&n.previewBackgroundColor!=="transparent")}}function vt(i){return i instanceof S.TextElement}function He(i){return i instanceof S.ImageElement}function Gn(i){return i instanceof S.GroupElement}function wt(i){return i instanceof S.ShapeElement}function St(i){return i instanceof S.PathElement}function $e(i,n,e={}){const t=e.mode||"both";switch(i.save(),i.translate(n.x||0,n.y||0),i.rotate(-(n.rotation||0)*Math.PI/180),n.transformType){case"image":kt(i,n,t,e);break;case"shape":Tt(i,n,t,e);break;case"group":break;default:Ct(i,n,t,e);break}i.restore()}function Ct(i,n,e,t){var s;const a=n,r=a.text||"";r&&((e==="stroke"||e==="both")&&((s=n.stroke)!=null&&s.enabled)&&(i.save(),S.renderTextStroke(i,n,{...t.renderingContext,positionApplied:!0}),i.restore()),(e==="fill"||e==="both")&&(i.save(),S.renderTextFillOnly(i,{text:r,fontSize:a.fontSize||24,fontFamily:a.fontFamily||"Arial",bold:a.bold||!1,italic:a.italic||!1,textAlign:a.textAlign||"center",color:a.color||"#000000"}),i.restore()))}function kt(i,n,e,t){var r;if(!n.transformData)return;const a=n.transformData;if(e==="fill"||e==="both")if(It(i,n),t.loadedImage){i.save(),i.clip();const s=a.flipHorizontal?-1:1,o=a.flipVertical?-1:1;i.scale(s,o);const l=a.width??100,c=a.height??100;i.drawImage(t.loadedImage,-l/2,-c/2,l,c),i.restore()}else i.fillStyle="#cccccc",i.fill();(e==="stroke"||e==="both")&&((r=n.stroke)!=null&&r.enabled)&&(i.save(),S.renderImageStroke(i,n,t.renderingContext),i.restore())}function Tt(i,n,e,t){var s,o;if(!n.transformData)return;const a=n.transformData,r=((s=t.renderingContext)==null?void 0:s.isKnockout)===!0;i.beginPath(),Ge(i,a),(e==="fill"||e==="both")&&(i.fillStyle=r?"#000000":a.fillColor||"#3b82f6",i.globalAlpha=r?1:a.fillOpacity??1,i.fill()),(e==="stroke"||e==="both")&&((o=n.stroke)!=null&&o.enabled)&&(i.save(),Pt(i,n,t.renderingContext),i.restore())}function Ge(i,n){const{shapeType:e}=n,t=n.width??100,a=n.height??100;switch(e){case"rectangle":_e(i,n,t,a);break;case"circle":_t(i,Math.min(t,a)/2);break;case"ellipse":Et(i,t/2,a/2);break;case"star":At(i,n,Math.min(t,a)/2);break;default:_e(i,n,t,a)}}function _e(i,n,e,t){const a=n.borderRadius||0,r=-e/2,s=-t/2;if(a>0){const o=Math.min(a/100*Math.min(e,t),e/2,t/2);i.roundRect(r,s,e,t,o)}else i.rect(r,s,e,t)}function _t(i,n){i.arc(0,0,n,0,Math.PI*2)}function Et(i,n,e){i.ellipse(0,0,n,e,0,0,Math.PI*2)}function At(i,n,e){const t=Math.max(3,Math.min(20,n.points||5)),a=Math.max(.1,Math.min(.9,n.innerRadius||.4)),r=e*a,s=Math.PI/t,o=-Math.PI/2;for(let l=0;l<t*2;l++){const c=o+s*l,d=l%2===0?e:r,f=Math.cos(c)*d,h=Math.sin(c)*d;l===0?i.moveTo(f,h):i.lineTo(f,h)}i.closePath()}function Pt(i,n,e){var a;if(!((a=n.stroke)!=null&&a.enabled)||!n.transformData)return;const t=(e==null?void 0:e.isKnockout)===!0;i.save(),t?(i.strokeStyle="#000000",i.lineWidth=n.stroke.width,i.lineCap=n.stroke.lineCap||"butt",i.lineJoin=n.stroke.lineJoin||"miter",i.globalAlpha=1):(i.strokeStyle=n.stroke.color,i.lineWidth=n.stroke.width,i.lineCap=n.stroke.lineCap||"butt",i.lineJoin=n.stroke.lineJoin||"miter",n.stroke.opacity!==void 0&&(i.globalAlpha=n.stroke.opacity)),n.stroke.miterLimit!==void 0&&(i.miterLimit=n.stroke.miterLimit),n.stroke.dashArray&&n.stroke.dashArray.length>0&&i.setLineDash(n.stroke.dashArray),!t&&n.stroke.feather&&n.stroke.feather>0&&"filter"in i&&(i.filter=`blur(${n.stroke.feather}px)`),i.beginPath(),Ge(i,n.transformData),i.stroke(),i.restore()}function It(i,n){if(!n.transformData)return;const{borderRadius:e}=n.transformData,t=n.transformData.width??100,a=n.transformData.height??100,r=-t/2,s=-a/2;if(i.beginPath(),e&&e>0){const o=Math.min(e/100*Math.min(t,a),t/2,a/2);i.roundRect(r,s,t,a,o)}else i.rect(r,s,t,a)}function Vn(i,n,e,t,a,r,s="destination-out"){var $;if(!n.knockoutParts)return;if(!(n.knockoutParts.fill||n.knockoutParts.stroke)){t(i,n);return}const l=i.getTransform();i.save();const c=n.knockoutParts.scope||"group",d=Rt(n,c,e);if(d.length===0&&c==="artboard"){Ft(i,n,t),i.restore();return}if(d.length===0){t(i,n),i.restore();return}const f=i.canvas,u=i.getTransform().a,g=Ot(f.width,f.height),m=g.getContext("2d");if(!m)return;m.scale(u,u),a&&r&&(m.fillStyle=a,m.fillRect(r.x,r.y,r.width,r.height));for(const x of d)t(m,x);n.knockoutParts.fill&&!n.knockoutParts.stroke&&(($=n.stroke)!=null&&$.enabled)&&(m.save(),ce(m,n),m.restore()),m.save(),m.globalCompositeOperation=s,n.knockoutParts.fill&&le(m,n),n.knockoutParts.stroke&&ce(m,n),m.restore(),n.knockoutParts.fill||(m.save(),le(m,n),m.restore());const p=f.width/u,y=f.height/u;i.drawImage(g,0,0,p,y),i.restore();const b=i.getTransform();(Math.abs(b.a-l.a)>.001||Math.abs(b.d-l.d)>.001||Math.abs(b.e-l.e)>.001||Math.abs(b.f-l.f)>.001)&&i.setTransform(l.a,l.b,l.c,l.d,l.e,l.f)}function Dt(i,n,e,t,a,r){Vn(i,n,e,t,a,r,"destination-out")}function Rt(i,n,e){return n==="artboard"?Ve(i,e):Mt(i,e)}function Ve(i,n){const e=n.findIndex(t=>t.id===i.id);return e===-1?[]:n.slice(0,e)}function Mt(i,n){const e=je(i,n);if(!e)return Ve(i,n);if(e.transformType!=="group"||!e.children)return[];const t=e.children.findIndex(a=>a.id===i.id);return t===-1?[]:e.children.slice(0,t)}function je(i,n){for(const e of n)if(e.transformType==="group"&&e.children){if(e.children.some(a=>a.id===i.id))return e;const t=je(i,e.children);if(t)return t}return null}function le(i,n,e){$e(i,n,{mode:"fill",renderingContext:{isKnockout:!0}})}function ce(i,n){var e;(e=n.stroke)!=null&&e.enabled&&$e(i,n,{mode:"stroke",renderingContext:{isKnockout:!0}})}function Ft(i,n,e){var a;const t=n.knockoutParts;if(!t){e(i,n);return}t.fill||(i.save(),le(i,n),i.restore()),!t.stroke&&((a=n.stroke)!=null&&a.enabled)&&(i.save(),ce(i,n),i.restore())}function Ot(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);if(typeof document<"u"){const e=document.createElement("canvas");return e.width=i,e.height=n,e}throw new Error("No canvas context available")}function Ee(i,n,e,t,a=0){if(e<=0||t<=0||i<=0||n<=0)return{width:i+a,height:n+a};const r=e/t,s=i/n;let o,l;return s>r?(l=n,o=n*r):(o=i,l=i/r),{width:o+a,height:l+a}}const Dn=64,re=512;function Bt(i,n){i.beginPath(),i.arc(n/2,n/2,n*.45,0,Math.PI*2),i.fill()}function Lt(i,n){const e=n/2,t=n/2,a=n*.45,r=a*.4,s=5;i.beginPath();for(let o=0;o<s*2;o++){const l=-Math.PI/2+Math.PI/s*o,c=o%2===0?a:r,d=e+Math.cos(l)*c,f=t+Math.sin(l)*c;o===0?i.moveTo(d,f):i.lineTo(d,f)}i.closePath(),i.fill()}function Nt(i,n){const e=n/2,t=n*.42;i.beginPath(),i.moveTo(e,n*.82),i.bezierCurveTo(e-t*1.1,n*.6,e-t*1.3,n*.2,e,n*.35),i.bezierCurveTo(e+t*1.3,n*.2,e+t*1.1,n*.6,e,n*.82),i.closePath(),i.fill()}function Ut(i,n){const e=n/2,t=n/2,a=n*.4,r=n*.48;i.beginPath(),i.moveTo(e,t-r),i.lineTo(e+a,t),i.lineTo(e,t+r),i.lineTo(e-a,t),i.closePath(),i.fill()}function zt(i,n){const e=n/2,t=n/2,a=n*.44;i.beginPath();for(let r=0;r<6;r++){const s=-Math.PI/2+Math.PI/3*r,o=e+Math.cos(s)*a,l=t+Math.sin(s)*a;r===0?i.moveTo(o,l):i.lineTo(o,l)}i.closePath(),i.fill()}function Wt(i,n){const e=n/2,t=n*.4,a=n*.12;i.beginPath(),i.moveTo(e,a),i.lineTo(e+t,n*.25),i.lineTo(e+t,n*.55),i.quadraticCurveTo(e+t*.3,n*.8,e,n*.9),i.quadraticCurveTo(e-t*.3,n*.8,e-t,n*.55),i.lineTo(e-t,n*.25),i.closePath(),i.fill()}function Ht(i,n){const e=n/2,t=n/2;let a=42;const r=()=>(a=(a*16807+0)%2147483647,a/2147483647);i.beginPath(),i.arc(e,t,n*.28,0,Math.PI*2),i.fill();for(let s=0;s<30;s++){const o=r()*Math.PI*2,l=n*.15+r()*n*.3,c=n*.02+r()*n*.06;i.beginPath(),i.arc(e+Math.cos(o)*l,t+Math.sin(o)*l,c,0,Math.PI*2),i.fill()}}function Gt(i,n){let e=123;const t=()=>(e=(e*16807+0)%2147483647,e/2147483647),a=n*.08,r=40;i.beginPath(),i.moveTo(a,a);for(let s=1;s<=r;s++){const o=a+(n-2*a)*(s/r),l=a+(t()-.5)*n*.08;i.lineTo(o,l)}for(let s=1;s<=r;s++){const o=n-a+(t()-.5)*n*.08,l=a+(n-2*a)*(s/r);i.lineTo(o,l)}for(let s=r;s>=0;s--){const o=a+(n-2*a)*(s/r),l=n-a+(t()-.5)*n*.08;i.lineTo(o,l)}for(let s=r;s>=0;s--){const o=a+(t()-.5)*n*.08,l=a+(n-2*a)*(s/r);i.lineTo(o,l)}i.closePath(),i.fill()}function Vt(i,n){let e=77;const t=()=>(e=(e*16807+0)%2147483647,e/2147483647),a=n*.25,r=n*.75,s=n*.1;i.beginPath(),i.moveTo(s,a+t()*n*.05);for(let o=1;o<=10;o++){const l=s+(n-2*s)*(o/10),c=a+(t()-.5)*n*.1;i.lineTo(l,c)}for(let o=10;o>=0;o--){const l=s+(n-2*s)*(o/10),c=r+(t()-.5)*n*.1;i.lineTo(l,c)}i.closePath(),i.fill()}function jt(i,n){const e=n/2,t=n*.55;i.beginPath(),i.arc(e,t,n*.2,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(e-n*.18,t+n*.02,n*.15,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(e+n*.18,t+n*.02,n*.16,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(e-n*.06,t-n*.14,n*.14,0,Math.PI*2),i.fill(),i.beginPath(),i.arc(e+n*.1,t-n*.12,n*.12,0,Math.PI*2),i.fill()}const Xe=[{id:"circle",name:"Circle",description:"Perfect circle",imageUrl:"builtin-mask:circle",thumbnailUrl:"",category:"geometric",draw:Bt},{id:"star",name:"Star",description:"5-pointed star",imageUrl:"builtin-mask:star",thumbnailUrl:"",category:"geometric",draw:Lt},{id:"heart",name:"Heart",description:"Heart shape",imageUrl:"builtin-mask:heart",thumbnailUrl:"",category:"geometric",draw:Nt},{id:"diamond",name:"Diamond",description:"Diamond/rhombus",imageUrl:"builtin-mask:diamond",thumbnailUrl:"",category:"geometric",draw:Ut},{id:"hexagon",name:"Hexagon",description:"Regular hexagon",imageUrl:"builtin-mask:hexagon",thumbnailUrl:"",category:"geometric",draw:zt},{id:"shield",name:"Shield",description:"Shield/crest shape",imageUrl:"builtin-mask:shield",thumbnailUrl:"",category:"geometric",draw:Wt},{id:"splatter",name:"Splatter",description:"Ink splatter",imageUrl:"builtin-mask:splatter",thumbnailUrl:"",category:"organic",draw:Ht},{id:"torn-edge",name:"Torn Edge",description:"Rough torn paper edge",imageUrl:"builtin-mask:torn-edge",thumbnailUrl:"",category:"organic",draw:Gt},{id:"paint-stroke",name:"Paint Stroke",description:"Horizontal brush stroke",imageUrl:"builtin-mask:paint-stroke",thumbnailUrl:"",category:"organic",draw:Vt},{id:"cloud",name:"Cloud",description:"Soft cloud shape",imageUrl:"builtin-mask:cloud",thumbnailUrl:"",category:"organic",draw:jt}];let Ae=!1;function Pe(i,n){if(typeof document>"u")return null;const e=document.createElement("canvas");return e.width=i,e.height=n,e}function qe(){if(typeof document>"u"||Ae)return;Ae=!0;const i=S.ImageCache.getInstance();for(const n of Xe){const e=Pe(re,re);if(!e)continue;const t=e.getContext("2d");if(!t)continue;t.fillStyle="white",n.draw(t,re);const a=e.toDataURL("image/png"),r=i.acquire(n.imageUrl);r.crossOrigin="anonymous",r.src=a;const s=Pe(Dn,Dn);if(s){const o=s.getContext("2d");o&&(o.fillStyle="#1a1a2e",o.fillRect(0,0,Dn,Dn),o.fillStyle="white",n.draw(o,Dn),n.thumbnailUrl=s.toDataURL("image/png"))}}}const Xt=S.createLogger("MaskRenderer"),de=new Map,qt=new Map;function Yt(i){const n=[];de.forEach((e,t)=>{t.startsWith(i)&&n.push(t)}),n.forEach(e=>de.delete(e))}function Kt(){de.clear()}function mn(i,n,e){if(!n.masks||n.masks.length===0){e(i);return}const t=i.canvas,a=jn(t.width,t.height),r=a.getContext("2d");if(!r){Xt.error("[renderWithMasks] Failed to get offscreen context");return}const s=i.getTransform();r.setTransform(s),e(r);for(const o of n.masks)Jt(r,o,n);i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(a,0,0),i.restore()}function Jt(i,n,e){switch(n.type){case"clip":Zt(i,n,e);break;case"alpha":Qt(i,n,e);break;case"luma":na(i,n,e);break;case"distress":ea(i,n,e);break}}function Zt(i,n,e){i.save(),i.globalCompositeOperation=n.inverted?"destination-out":"destination-in",n.opacity!==void 0&&(i.globalAlpha=n.opacity),Zn(i,n.maskElement,e),i.restore()}function Qt(i,n,e){i.save(),i.globalCompositeOperation=n.inverted?"destination-out":"destination-in",n.opacity!==void 0&&(i.globalAlpha=n.opacity),Zn(i,n.maskElement,e),n.feather&&n.feather>0&&Ye(i,n.feather),i.restore()}function na(i,n,e){const t=jn(i.canvas.width,i.canvas.height),a=t.getContext("2d");if(!a)return;Zn(a,n.maskElement,e);const r=a.getImageData(0,0,t.width,t.height),s=r.data;for(let o=0;o<s.length;o+=4){const l=s[o],c=s[o+1],d=s[o+2],f=.299*l+.587*c+.114*d;s[o+3]=n.inverted?255-f:f}a.putImageData(r,0,0),i.save(),i.globalCompositeOperation="destination-in",n.opacity!==void 0&&(i.globalAlpha=n.opacity),i.drawImage(t,0,0),i.restore()}function ea(i,n,e){i.save(),i.globalCompositeOperation=n.inverted?"destination-in":"destination-out",n.opacity!==void 0&&(i.globalAlpha=n.opacity),Zn(i,n.maskElement,e),n.feather&&n.feather>0&&Ye(i,n.feather),i.restore()}function Zn(i,n,e){const t=e.x||0,a=e.y||0,r=n.x||0,s=n.y||0,o={...n,x:t+r,y:a+s,rotation:(n.rotation||0)+(e.rotation||0)},l=4,c=e.transformData,d=e,f=(c==null?void 0:c.width)||d.width||0,h=(c==null?void 0:c.height)||d.height||0,u=n.transformData;f&&h&&u&&(o.transformData={...u,width:f+l,height:h+l});let g,m;if(n.transformType==="image"){const x=n;if(x.imageUrl)if(typeof document<"u"){x.imageUrl.startsWith("builtin-mask:")&&qe();const w=S.ImageCache.getInstance(),v=w.acquire(x.imageUrl);v.complete&&v.naturalWidth>0&&(g=v),w.release(x.imageUrl)}else m=qt.get(x.imageUrl)}const p=o.transformData,y=(u==null?void 0:u.width)||0,b=(u==null?void 0:u.height)||0,$=y>0&&b>0&&f>0&&h>0&&Math.abs(y/b-f/h)>.001;if(m){i.save();const x=(p==null?void 0:p.width)||m.width,w=(p==null?void 0:p.height)||m.height;if(i.translate(o.x||0,o.y||0),i.rotate(-(o.rotation||0)*Math.PI/180),$){const v=Ee(x,w,y,b,0);i.drawImage(m,-v.width/2,-v.height/2,v.width,v.height)}else i.drawImage(m,-x/2,-w/2,x,w);i.restore()}else if($&&g){const x=(p==null?void 0:p.width)||f,w=(p==null?void 0:p.height)||h,v=Ee(x,w,y,b,0);i.save(),i.translate(o.x||0,o.y||0),i.rotate(-(o.rotation||0)*Math.PI/180),i.drawImage(g,-v.width/2,-v.height/2,v.width,v.height),i.restore()}else $e(i,o,{mode:"both",loadedImage:g})}function Ye(i,n){"filter"in i&&(i.filter=`blur(${n}px)`)}function jn(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);if(typeof document<"u"){const e=document.createElement("canvas");return e.width=i,e.height=n,e}throw new Error("No canvas context available")}function Ke(i,n,e,t){if(!n.enabled||!n.imageUrl||n.opacity<=0)return;const a=S.ImageCache.getInstance(),r=a.acquire(n.imageUrl);if(!r.complete||r.naturalWidth===0){a.release(n.imageUrl);return}const{x:s,y:o,width:l,height:c}=e,d=i.getTransform(),f=d.a*s+d.e,h=d.d*o+d.f,u=d.a*l,g=d.d*c,m=Math.ceil(u),p=Math.ceil(g);if(m<=0||p<=0){a.release(n.imageUrl);return}const y=jn(m,p),b=y.getContext("2d");if(!b){a.release(n.imageUrl);return}b.drawImage(i.canvas,f,h,u,g,0,0,m,p);let $;if(n.maskType==="luma"?$="destination-in":$=n.inverted?"destination-out":"destination-in",n.maskType==="luma"){const x=jn(m,p),w=x.getContext("2d");if(w){w.drawImage(r,0,0,m,p);const v=w.getImageData(0,0,m,p),C=v.data;for(let _=0;_<C.length;_+=4){const T=.299*C[_]+.587*C[_+1]+.114*C[_+2];C[_+3]=n.inverted?255-T:T}w.putImageData(v,0,0),b.globalCompositeOperation="destination-in",b.globalAlpha=n.opacity/100,b.drawImage(x,0,0)}}else b.globalCompositeOperation=$,b.globalAlpha=n.opacity/100,b.drawImage(r,0,0,m,p);b.globalCompositeOperation="source-over",b.globalAlpha=1,i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(f,h,u,g),t&&(i.fillStyle=t,i.fillRect(f,h,u,g)),i.drawImage(y,f,h),i.restore(),a.release(n.imageUrl)}class ta{constructor(n=Math.random()){this.perm=[];for(let t=0;t<256;t++)this.perm[t]=t;const e=this.seededRandom(n);for(let t=255;t>0;t--){const a=Math.floor(e()*(t+1));[this.perm[t],this.perm[a]]=[this.perm[a],this.perm[t]]}for(let t=0;t<256;t++)this.perm[256+t]=this.perm[t]}seededRandom(n){let e=Math.sin(n++)*1e4;return()=>(e=Math.sin(n++)*1e4,e-Math.floor(e))}fade(n){return n*n*n*(n*(n*6-15)+10)}lerp(n,e,t){return e+n*(t-e)}grad(n,e,t){const a=n&15,r=a<8?e:t,s=a<4?t:a===12||a===14?e:0;return((a&1)===0?r:-r)+((a&2)===0?s:-s)}noise(n,e){const t=Math.floor(n)&255,a=Math.floor(e)&255;n-=Math.floor(n),e-=Math.floor(e);const r=this.fade(n),s=this.fade(e),o=this.perm[t]+a,l=this.perm[t+1]+a;return this.lerp(s,this.lerp(r,this.grad(this.perm[o],n,e),this.grad(this.perm[l],n-1,e)),this.lerp(r,this.grad(this.perm[o+1],n,e-1),this.grad(this.perm[l+1],n-1,e-1)))}}function se(i,n,e,t=Date.now()){const s=Qn(i,n).getContext("2d").createImageData(i,n),o=s.data,l=new ta(t),c=.02,d=1-e/100;for(let f=0;f<n;f++)for(let h=0;h<i;h++){const u=(f*i+h)*4;let g=0;g+=l.noise(h*c,f*c)*.5,g+=l.noise(h*c*2,f*c*2)*.25,g+=l.noise(h*c*4,f*c*4)*.125,g=(g+1)/2;const m=Math.min(h/i,(i-h)/i)*2,p=Math.min(f/n,(n-f)/n)*2,y=Math.min(m,p);g*=.7+y*.3;const b=g>d?255:0;o[u]=255,o[u+1]=255,o[u+2]=255,o[u+3]=b}return s}function aa(i,n,e,t=Date.now()){const r=Qn(i,n).getContext("2d");r.clearRect(0,0,i,n),r.strokeStyle="#000000",r.lineWidth=1+e/50,r.lineCap="round";const s=ve(t),o=Math.floor(e/100*30+5);for(let l=0;l<o;l++){const c=s()*i,d=s()*n;fe(r,c,d,s()*Math.PI*2,50+s()*100,s,0)}return r.getImageData(0,0,i,n)}function fe(i,n,e,t,a,r,s){if(s>3||a<10)return;const o=n+Math.cos(t)*a,l=e+Math.sin(t)*a;if(i.beginPath(),i.moveTo(n,e),i.lineTo(o,l),i.stroke(),r()>.5){const c=t+(r()-.5)*Math.PI/2;fe(i,o,l,c,a*.6,r,s+1)}if(r()>.7){const c=t-(r()-.5)*Math.PI/2;fe(i,o,l,c,a*.6,r,s+1)}}function Hn(i,n,e,t=Date.now()){const s=Qn(i,n).getContext("2d").createImageData(i,n),o=s.data,l=ve(t),c=e/100*.5;for(let d=0;d<n;d++)for(let f=0;f<i;f++){const h=(d*i+f)*4,g=l()<c?255:0;o[h]=0,o[h+1]=0,o[h+2]=0,o[h+3]=g}return s}function ra(i,n,e,t=Date.now()){const r=Qn(i,n).getContext("2d");r.fillStyle="#000000";const s=ve(t),o=4+e/100*6,l=o*2;for(let c=0;c<n;c+=l)for(let d=0;d<i;d+=l)if(s()<e/100){const f=o*(.5+s()*.5);r.beginPath(),r.arc(d,c,f/2,0,Math.PI*2),r.fill()}return r.getImageData(0,0,i,n)}function Qn(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);if(typeof document<"u"){const e=document.createElement("canvas");return e.width=i,e.height=n,e}throw new Error("No canvas context available")}function ve(i){let n=Math.sin(i++)*1e4;return()=>(n=Math.sin(i++)*1e4,n-Math.floor(n))}const ln=42,Cn=512,kn=64;function ue(i){const n=i.data;for(let e=0;e<n.length;e+=4)n[e]=255,n[e+1]=255,n[e+2]=255;return i}function sa(i,n){const e=i.data,t=n.data;for(let a=0;a<e.length;a+=4)e[a]=255,e[a+1]=255,e[a+2]=255,e[a+3]=Math.min(255,e[a+3]+t[a+3]);return i}const Je=[{id:"grunge-heavy",name:"Heavy Grunge",textureUrl:"builtin:grunge-heavy",thumbnailUrl:"",description:"Dense random splatters",generate:(i,n)=>Hn(i,n,80,ln)},{id:"grunge-fine",name:"Fine Grunge",textureUrl:"builtin:grunge-fine",thumbnailUrl:"",description:"Sparse fine grain",generate:(i,n)=>Hn(i,n,25,ln+1)},{id:"concrete",name:"Concrete",textureUrl:"builtin:concrete",thumbnailUrl:"",description:"Rough surface via Perlin noise",generate:(i,n)=>se(i,n,55,ln+2)},{id:"paper",name:"Old Paper",textureUrl:"builtin:paper",thumbnailUrl:"",description:"Subtle aging",generate:(i,n)=>se(i,n,20,ln+3)},{id:"rust",name:"Rust",textureUrl:"builtin:rust",thumbnailUrl:"",description:"Noise + splatter combined",generate:(i,n)=>{const e=se(i,n,45,ln+4),t=Hn(i,n,35,ln+5);return sa(ue(e),ue(t))}},{id:"scratches",name:"Scratches",textureUrl:"builtin:scratches",thumbnailUrl:"",description:"Branching crack lines",generate:(i,n)=>aa(i,n,55,ln+6)},{id:"halftone",name:"Halftone",textureUrl:"builtin:halftone",thumbnailUrl:"",description:"Dot grid pattern",generate:(i,n)=>ra(i,n,55,ln+7)},{id:"spray",name:"Spray Paint",textureUrl:"builtin:spray",thumbnailUrl:"",description:"Medium random splatter",generate:(i,n)=>Hn(i,n,55,ln+8)}];let Ie=!1;function ia(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);const e=document.createElement("canvas");return e.width=i,e.height=n,e}function De(i,n){if(typeof document>"u")return null;const e=document.createElement("canvas");return e.width=i,e.height=n,e}function oa(i){const n=De(i.width,i.height);if(!n)return"";const e=n.getContext("2d");if(!e)return"";e.putImageData(i,0,0);const t=De(kn,kn);if(!t)return"";const a=t.getContext("2d");if(!a)return"";a.drawImage(n,0,0,i.width,i.height,0,0,kn,kn);const r=a.getImageData(0,0,kn,kn),s=r.data;for(let o=0;o<s.length;o+=4){const l=s[o+3],c=255-Math.round(l/255*195);s[o]=c,s[o+1]=c,s[o+2]=c,s[o+3]=255}return a.putImageData(r,0,0),t.toDataURL("image/png")}function Ze(){if(!Ie){Ie=!0;for(const i of Je){const n=i.generate(Cn,Cn);ue(n);const e=ia(Cn,Cn),t=e.getContext("2d");t&&(t.putImageData(n,0,0),ca(i.textureUrl,e,Cn,Cn)),typeof document<"u"&&(i.thumbnailUrl=oa(n))}}}const hn=new Set,pn=new Map,Xn=new Map;function Re(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);const e=document.createElement("canvas");return e.width=i,e.height=n,e}function Me(i){return i.getContext("2d")}function Fe(i){const{width:n,height:e}=i,t=Re(n,e),a=Me(t);if(!a)throw new Error("Failed to get 2d context for temp canvas");a.drawImage(i,0,0);const r=a.getImageData(0,0,n,e),s=r.data;for(let c=0;c<s.length;c+=4){const d=s[c],f=s[c+1],h=s[c+2],g=255-(.299*d+.587*f+.114*h);s[c]=255,s[c+1]=255,s[c+2]=255,s[c+3]=g}const o=Re(n,e),l=Me(o);if(!l)throw new Error("Failed to get 2d context for mask canvas");return l.putImageData(r,0,0),{alphaMask:o,width:n,height:e}}function Qe(i){const n=pn.get(i);if(n)return n;if(i.startsWith("builtin:")){Ze();const e=pn.get(i);return e||null}return hn.has(i)||(hn.add(i),nt(i)),null}function la(i){return pn.has(i)?Promise.resolve():new Promise(n=>{if(pn.has(i)){n();return}const e=Xn.get(i)||[];e.push(n),Xn.set(i,e),hn.has(i)||(hn.add(i),nt(i))})}function ca(i,n,e,t){pn.has(i)||(pn.set(i,{alphaMask:n,width:e,height:t}),Mn(i))}function Mn(i){const n=Xn.get(i);n&&(n.forEach(e=>e()),Xn.delete(i))}function nt(i){if(typeof document<"u"){const n=new Image;n.crossOrigin="anonymous",n.onload=()=>{const e=Fe(n);pn.set(i,e),hn.delete(i),Mn(i)},n.onerror=()=>{hn.delete(i),Mn(i)},n.src=i}else fetch(i).then(n=>n.blob()).then(n=>createImageBitmap(n)).then(n=>{const e=Fe(n);pn.set(i,e),hn.delete(i),Mn(i)}).catch(()=>{hn.delete(i),Mn(i)})}function et(i,n){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(i,n);const e=document.createElement("canvas");return e.width=i,e.height=n,e}function tt(i,n,e,t){if(!n.enabled||!n.textureUrl||n.intensity<=0)return;const a=Qe(n.textureUrl);if(!a)return;const{x:r,y:s,width:o,height:l}=e,c=i.getTransform(),d=c.a*r+c.e,f=c.d*s+c.f,h=c.a*o,u=c.d*l,g=Math.ceil(h),m=Math.ceil(u);if(g<=0||m<=0)return;const p=et(g,m),y=p.getContext("2d");if(!y)return;y.drawImage(i.canvas,d,f,h,u,0,0,g,m);const b=a.alphaMask.getContext("2d");if(b){const $=n.intensity/100,x=b.getImageData(0,0,a.width,a.height).data,w=a.width,v=a.height,C=y.getImageData(0,0,g,m),_=C.data;for(let T=0;T<m;T++){const E=Math.floor(T/m*v);for(let k=0;k<g;k++){const A=Math.floor(k/g*w),D=x[(E*w+A)*4+3]/255,P=(T*g+k)*4;_[P+3]=Math.round(_[P+3]*(1-D*$))}}y.putImageData(C,0,0)}else y.globalCompositeOperation="destination-out",y.globalAlpha=n.intensity/100,y.drawImage(a.alphaMask,0,0,g,m),y.globalCompositeOperation="source-over";y.globalAlpha=1,i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(d,f,h,u),t&&(i.fillStyle=t,i.fillRect(d,f,h,u)),i.drawImage(p,d,f),i.restore()}function qn(i,n,e,t){if(!n.enabled||n.style!=="custom"||!n.textureUrl)return;const a=Qe(n.textureUrl);if(!a){t(i);return}const r=n.textureOpacity??n.intensity/100,s=i.getTransform(),o=Math.sqrt(e.width**2+e.height**2),l=(o-e.width)/2,c=(o-e.height)/2,d=20,f=l+d,h=c+d,u={x:e.x-f,y:e.y-h,width:e.width+f*2,height:e.height+h*2},g=s.a*u.x+s.e,m=s.d*u.y+s.f,p=s.a*u.width,y=s.d*u.height,b=Math.ceil(p),$=Math.ceil(y);if(b<=0||$<=0){t(i);return}const x=et(b,$),w=x.getContext("2d");if(!w){t(i);return}w.setTransform(s.a,s.b,s.c,s.d,s.e-g,s.f-m),t(w),w.setTransform(1,0,0,1,0,0);const v=a.alphaMask.getContext("2d");if(v){const C=v.getImageData(0,0,a.width,a.height).data,_=a.width,T=a.height,E=w.getImageData(0,0,b,$),k=E.data;for(let A=0;A<$;A++){const D=Math.floor(A/$*T);for(let P=0;P<b;P++){const M=Math.floor(P/b*_),W=C[(D*_+M)*4+3]/255,B=(A*b+P)*4;k[B+3]=Math.round(k[B+3]*(1-W*r))}}w.putImageData(E,0,0)}else w.globalCompositeOperation="destination-out",w.globalAlpha=r,w.drawImage(a.alphaMask,0,0,b,$),w.globalCompositeOperation="source-over",w.globalAlpha=1;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(x,g,m),i.restore()}class Tn{static renderSelectionLayer(n,e,t,a=1){if(!e||e.visible===!1||t&&t.getMode()==="drag"||"isGroup"in e&&e.isGroup)return;const s=e.getVisualBoundingBox(),o=e.getRotationAnchor();n.save(),n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=2,n.translate(o.x*a,o.y*a),n.rotate(S.RotationUtils.toRadians(e.rotation)),n.translate(-o.x*a,-o.y*a);const l=rn.canvas.selectionPadding;n.strokeRect((s.x-l)*a,(s.y-l)*a,(s.width+l*2)*a,(s.height+l*2)*a),n.restore()}static renderPositionSizeInfo(n,e,t,a,r=1){if(!e||!(t!=null&&t.rotationHandle)||(a==null?void 0:a.getMode())!=="resize")return;const s=e.getVisualBoundingBox(),o=Math.round(s.width),l=Math.round(s.height),c=`${o} × ${l}`,d=t.rotationHandle,f=d.x*r,h=d.y*r-20;n.save(),n.font="10px system-ui, -apple-system, sans-serif";const g=n.measureText(c).width+12,m=18;n.shadowColor=S.getThemeTooltipShadowColor(n.canvas),n.shadowBlur=4,n.shadowOffsetY=1,n.fillStyle=S.getThemeTooltipBackground(n.canvas),n.beginPath(),n.roundRect(f-g/2,h-m/2,g,m,3),n.fill(),n.shadowColor="transparent",n.shadowBlur=0,n.shadowOffsetY=0,n.fillStyle=S.getThemeTooltipForeground(n.canvas),n.textAlign="center",n.textBaseline="middle",n.fillText(c,f,h+.5),n.restore()}static renderHandlesLayer(n,e,t,a,r,s,o,l=1,c=!0){if(!e||e.visible===!1||o.getMode()==="drag")return;const f=s.type==="rotation-handle",h=s.type==="resize-handle"?s.data:null,u=o.getMode()==="resize",g=u?o.getActiveHandle():null;t.render(n,c,a,r,f,h,u,g,l,!0)}}class he{static renderHoverLayer(n,e,t,a=!1,r=1,s){if(e.type!=="element"||!e.data||e.data.id===t)return;const o=e.data;n.save();const l=150,c=.5;let d=c;if(e.startTime){const f=performance.now()-e.startTime;d=Math.min(f/l,1)*c}n.strokeStyle=S.getThemeAccentHoverColor(n.canvas),n.globalAlpha=d,n.lineWidth=3,this.renderElementOutline(n,o,r,s),n.restore()}static renderElementOutline(n,e,t=1,a){const r=e.getRotationAnchor();n.translate(r.x*t,r.y*t),n.rotate(S.RotationUtils.toRadians(e.rotation)),n.translate(-r.x*t,-r.y*t),e.transformType==="shape"?this.renderShapeOutline(n,e,t):e.transformType==="image"?this.renderImageOutline(n,e,t):e.transformType==="group"?this.renderGroupOutline(n,e,t):this.renderTextOutline(n,e,t,a)}static renderShapeOutline(n,e,t){const a=e.transformData,r=a.width*t,s=a.height*t,o=2,c=o+o/2;switch(n.save(),n.translate(e.x*t,e.y*t),n.beginPath(),a.shapeType){case"rectangle":{const d=a.borderRadius||0,f=-(r+c*2)/2,h=-(s+c*2)/2,u=r+c*2,g=s+c*2;if(d>0){const m=Math.min(d/100*Math.min(u,g),u/2,g/2);n.roundRect(f,h,u,g,m)}else n.rect(f,h,u,g);break}case"circle":{const d=Math.min(r,s)/2+c;n.arc(0,0,d,0,Math.PI*2);break}case"ellipse":{const d=(a.radiusX??r/2)+c,f=(a.radiusY??s/2)+c;n.ellipse(0,0,d,f,0,0,Math.PI*2);break}case"triangle":{const d=r/2,f=s/2,h=[{x:0,y:-f},{x:d,y:f},{x:-d,y:f}],u=h.map((m,p)=>{const y=h[(p+1)%3],b=y.x-m.x,$=y.y-m.y,x=Math.sqrt(b*b+$*$);return{x:$/x,y:-b/x}}),g=h.map((m,p)=>{const y=u[(p+2)%3],b=u[p],$=y.x+b.x,x=y.y+b.y,w=Math.sqrt($*$+x*x),v=($*y.x+x*y.y)/w,C=c/v;return{x:m.x+$/w*C,y:m.y+x/w*C}});n.moveTo(g[0].x,g[0].y),n.lineTo(g[1].x,g[1].y),n.lineTo(g[2].x,g[2].y),n.closePath();break}case"star":{const d=a.points??5,f=a.innerRadius??.4,h=Math.min(r,s)/2+c,u=h*f;for(let g=0;g<d*2;g++){const m=g*Math.PI/d-Math.PI/2,p=g%2===0?h:u,y=p*Math.cos(m),b=p*Math.sin(m);g===0?n.moveTo(y,b):n.lineTo(y,b)}n.closePath();break}case"polygon":{const d=a.sides??5,f=Math.min(r,s)/2+c;for(let h=0;h<d;h++){const u=h*2*Math.PI/d-Math.PI/2,g=f*Math.cos(u),m=f*Math.sin(u);h===0?n.moveTo(g,m):n.lineTo(g,m)}n.closePath();break}case"line":{const d=r/2+c;n.moveTo(-d,0),n.lineTo(d,0);break}}n.stroke(),n.restore()}static renderImageOutline(n,e,t){var m;const a=e.getVisualBoundingBox(),r=a.width*t,s=a.height*t,o=((m=e.transformData)==null?void 0:m.borderRadius)||0,l=2,d=l+l/2;n.save(),n.translate(e.x*t,e.y*t);const f=-(r+d*2)/2,h=-(s+d*2)/2,u=r+d*2,g=s+d*2;if(n.beginPath(),o>0){const p=Math.min(o/100*Math.min(u,g),u/2,g/2);n.roundRect(f,h,u,g,p)}else n.rect(f,h,u,g);n.stroke(),n.restore()}static renderGroupOutline(n,e,t){const a=e.getVisualBoundingBox(),r=2,o=r+r/2,l=a.x*t-o,c=a.y*t-o,d=a.width*t+o*2,f=a.height*t+o*2;n.save(),n.setLineDash([5,5]),n.beginPath(),n.roundRect(l,c,d,f,8),n.stroke(),n.restore()}static renderTextOutline(n,e,t,a){const r=e.transformType;r==="circle"||r==="wave"||r==="arch"||r==="lean"||r==="ascend"||r==="flag"?this.renderTransformHoverRingEffect(n,e,t):this.renderHoverRingEffect(n,e,t)}static renderHoverRingEffect(n,e,t){n.save(),n.translate(e.x*t,e.y*t),t!==1&&n.scale(t,t);const a=e.fontSize,r=e.fontFamily,s=e.bold||!1,o=e.italic||!1,l=e.textAlign||"center",c=S.getFontMetrics$1(a,r,s,o),d=a*1.2,f=4/t,h=4/t,u=document.createElement("canvas");u.width=n.canvas.width,u.height=n.canvas.height;const g=u.getContext("2d");if(!g){n.restore();return}g.setTransform(n.getTransform()),g.textBaseline="alphabetic",g.lineJoin="round";const m=e.getRichText?e.getRichText():null;if(m){const p=S.splitRichTextIntoLines(m),y=[],b=[];p.forEach(w=>{if(e.transformType==="custom"&&e.transformData){const v=e.transformData.width-S.HORIZONTAL_PADDING*2,C=S.wrapRichTextSpans(w,v,{fontSize:a,fontFamily:r,bold:s,italic:o});C.forEach((_,T)=>{y.push(_),b.push({isParagraphStart:T===0,isParagraphEnd:T===C.length-1})})}else y.push(w),b.push({isParagraphStart:!0,isParagraphEnd:!0})});let $;y.length===0?$=0:y.length===1?$=c.height:$=(y.length-1)*d+c.height;const x=-$/2;y.forEach((w,v)=>{var W,B;const C=b[v].isParagraphStart,_=b[v].isParagraphEnd;let T=0;const E=w.map(I=>I.text).join(""),k=((W=E.match(/^ +/))==null?void 0:W[0].length)||0,A=((B=E.match(/ +$/))==null?void 0:B[0].length)||0;let D=0;w.forEach(I=>{const H=I.style.fontSize!==void 0?I.style.fontSize:a,q=I.style.fontFamily!==void 0?I.style.fontFamily:r,Y=I.style.bold!==void 0?I.style.bold:s,nn=I.style.italic!==void 0?I.style.italic:o;let N=I.text;const R=D,F=D+I.text.length;if(!C&&k>0&&R<k){const L=Math.min(k-R,I.text.length);N=N.substring(L)}if(!_&&A>0){const L=E.length-A;if(F>L){const O=!C&&R<k?Math.min(k-R,I.text.length):0,z=Math.max(0,L-R-O);N=N.substring(0,z)}}N.length>0&&(n.save(),n.font=S.buildFontString$1(H,q,Y,nn),T+=n.measureText(N).width,n.restore()),D+=I.text.length});let P=0;l==="center"?P=-T/2:l==="right"&&(P=-T);const M=x+c.ascent+v*d;D=0,w.forEach(I=>{const H=I.style.fontSize!==void 0?I.style.fontSize:a,q=I.style.fontFamily!==void 0?I.style.fontFamily:r;I.style.color!==void 0?I.style.color:e.color;const Y=I.style.bold!==void 0?I.style.bold:s,nn=I.style.italic!==void 0?I.style.italic:o;let N=I.text;const R=D,F=D+I.text.length;if(!C&&k>0&&R<k){const L=Math.min(k-R,I.text.length);N=N.substring(L)}if(!_&&A>0){const L=E.length-A;if(F>L){const O=!C&&R<k?Math.min(k-R,I.text.length):0,z=Math.max(0,L-R-O);N=N.substring(0,z)}}D+=I.text.length,N.length>0&&(g.font=S.buildFontString$1(H,q,Y,nn),g.textAlign="left",g.globalCompositeOperation="source-over",g.strokeStyle=n.strokeStyle,g.globalAlpha=Math.min(n.globalAlpha*1.6,.8),g.lineWidth=(h+f)*2,g.strokeText(N,P,M),g.globalCompositeOperation="destination-out",g.globalAlpha=1,g.lineWidth=h*2,g.strokeText(N,P,M),g.fillText(N,P,M),P+=g.measureText(N).width)})})}else{n.font=S.buildFontString$1(a,r,s,o),g.font=n.font,g.textAlign=l;let p,y;if(e.transformType==="custom"&&e.transformData){const x=e.transformData.width-S.HORIZONTAL_PADDING*2,{lines:w}=S.calculateVisualBoundsWithSpaceCollapsing(e.text,x,a,r,s,o,void 0,!0);p=w}else{p=e.text.split(`
2
2
  `);const x=e.text.includes(`
3
3
  `);p=S.applySpaceLayoutRules(p,x)}p.length===0?y=0:p.length===1?y=c.height:y=(p.length-1)*d+c.height;const b=-y/2,$=e.text.includes(`
4
- `);p.forEach((x,w)=>{const v=b+c.ascent+w*d,C=$||w===0,_=$||w===p.length-1;let T=x;C||(T=T.replace(/^ +/,"")),_||(T=T.replace(/ +$/,"")),g.globalCompositeOperation="source-over",g.strokeStyle=n.strokeStyle,g.globalAlpha=Math.min(n.globalAlpha*1.6,.8),g.lineWidth=(h+f)*2,g.lineJoin="round",g.strokeText(T,0,v),g.globalCompositeOperation="destination-out",g.globalAlpha=1,g.lineWidth=h*2,g.strokeText(T,0,v),g.fillText(T,0,v)})}n.setTransform(1,0,0,1,0,0),n.drawImage(u,0,0),n.restore()}static renderTransformHoverRingEffect(n,e,t){n.save(),n.translate(e.x*t,e.y*t),t!==1&&n.scale(t,t),n.rotate(-e.rotation*Math.PI/180);const a=4/t,r=4/t,s=document.createElement("canvas");s.width=n.canvas.width,s.height=n.canvas.height;const o=s.getContext("2d");if(!o){n.restore();return}o.setTransform(n.getTransform()),this.renderTransformWithHoverEffect(o,e,a,r,n.strokeStyle),n.setTransform(1,0,0,1,0,0),n.drawImage(s,0,0),n.restore()}static renderTransformWithHoverEffect(n,e,t,a,r){const s=e,o=s.fontSize,l=s.fontFamily,c=s.bold||!1,d=s.italic||!1,f=c?"bold":"normal",h=d?"italic":"normal";if(n.font=`${h} ${f} ${o}px ${l}`,n.textAlign="center",n.textBaseline="middle",s.transformType==="lean"){const b=-s.transformData.leanAmount*Math.PI/4;n.transform(1,0,Math.tan(b),1,0,0),n.globalCompositeOperation="source-over",n.strokeStyle=r,n.globalAlpha=.8,n.lineWidth=(a+t)*2,n.lineJoin="round",n.strokeText(s.text,0,0),n.globalCompositeOperation="destination-out",n.globalAlpha=1,n.lineWidth=a*2,n.strokeText(s.text,0,0),n.fillText(s.text,0,0);return}const u=s.text.split(""),g=u.map(y=>n.measureText(y).width),m=this.calculateCharPositions(e,u,g),p=y=>{n.translate(y.x,y.y),y.angle&&n.rotate(y.angle),y.skewY&&n.transform(1,y.skewY,0,1,0,0)};n.globalCompositeOperation="source-over",n.strokeStyle=r,n.globalAlpha=.8,n.lineWidth=(a+t)*2,n.lineJoin="round",m.forEach((y,b)=>{n.save(),p(y),n.strokeText(u[b],0,0),n.restore()}),n.globalCompositeOperation="destination-out",n.globalAlpha=1,n.lineWidth=a*2,m.forEach((y,b)=>{n.save(),p(y),n.strokeText(u[b],0,0),n.fillText(u[b],0,0),n.restore()})}static calculateCharPositions(n,e,t){const a=n.transformType,r=n.transformData;return a==="circle"?this.calculateCirclePositions(r,e,t):a==="wave"?this.calculateWavePositions(n,e,t,r):a==="arch"?this.calculateArchPositions(n,e,t,r):a==="lean"?this.calculateLeanPositions(e,t):a==="ascend"?this.calculateAscendPositions(n,e,t,r):a==="flag"?this.calculateFlagPositions(n,e,t,r):e.map(()=>({x:0,y:0,angle:0}))}static calculateCirclePositions(n,e,t){const a=[],r=t.reduce((o,l)=>o+l,0),s=n.radius*n.scale;if(n.reverse){let o=Math.PI/2+r/(2*s);e.forEach((l,c)=>{const f=t[c]/s,h=Math.cos(o-f/2)*s,u=Math.sin(o-f/2)*s,g=o-f/2-Math.PI/2;a.push({x:h,y:u,angle:g}),o-=f})}else{let o=-Math.PI/2-r/(2*s);e.forEach((l,c)=>{const f=t[c]/s,h=Math.cos(o+f/2)*s,u=Math.sin(o+f/2)*s,g=o+f/2+Math.PI/2;a.push({x:h,y:u,angle:g}),o+=f})}return a}static calculateWavePositions(n,e,t,a){const r=[];let o=-t.reduce((l,c)=>l+c,0)/2;return e.forEach((l,c)=>{const d=t[c],f=o+d/2,h=f/(a.width/2),u=a.amplitude*n.fontSize*Math.sin(a.frequency*Math.PI*h),g=a.amplitude*a.frequency*Math.PI*Math.cos(a.frequency*Math.PI*h);r.push({x:f,y:u,angle:0,skewY:g*S.WAVE_SKEW_FACTOR}),o+=d}),r}static calculateArchPositions(n,e,t,a){const r=[],s=t.reduce((c,d)=>c+d,0),o=a.width/2;let l=-s/2;return e.forEach((c,d)=>{const f=t[d],h=l+f/2,u=h/o,g=(Math.pow(u,2)-1)*a.archHeight*n.fontSize,m=2*u*a.archHeight;r.push({x:h,y:g,angle:0,skewY:m*.3}),l+=f}),r}static calculateLeanPositions(n,e){const t=[];let r=-e.reduce((s,o)=>s+o,0)/2;return n.forEach((s,o)=>{const l=e[o],c=r+l/2;t.push({x:c,y:0,angle:0}),r+=l}),t}static calculateAscendPositions(n,e,t,a){const r=[],s=t.reduce((d,f)=>d+f,0),o=a.ascendAngle*Math.PI/180,l=Math.tan(o);let c=-s/2;return e.forEach((d,f)=>{const h=t[f],u=c+h/2,g=u*l;r.push({x:u,y:g,angle:0,skewY:l*1}),c+=h}),r}static calculateFlagPositions(n,e,t,a){const r=[];let o=-t.reduce((l,c)=>l+c,0)/2;return e.forEach((l,c)=>{const d=t[c],f=o+d/2,h=f/(a.width/2),u=Math.abs(h),g=a.amplitude*u,m=g*n.fontSize*Math.sin(a.frequency*Math.PI*h),p=g*a.frequency*Math.PI*Math.cos(a.frequency*Math.PI*h),y=a.amplitude*Math.sign(h)*Math.sin(a.frequency*Math.PI*h),b=p+y;r.push({x:f,y:m,angle:0,skewY:b*.3}),o+=d}),r}}class Rn{static renderSnapGuidesLayer(n,e=[]){e.length!==0&&(n.save(),n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=rn.canvas.snapGuideWidth,n.setLineDash(rn.canvas.snapGuideDash),e.forEach(t=>{n.beginPath(),t.type==="vertical"?(n.moveTo(t.x??0,t.y1??0),n.lineTo(t.x??0,t.y2??0)):t.type==="horizontal"?(n.moveTo(t.x1??0,t.y??0),n.lineTo(t.x2??0,t.y??0)):(n.moveTo(t.x1??0,t.y1??0),n.lineTo(t.x2??0,t.y2??0)),n.stroke()}),n.restore())}static renderSpacingIndicatorsLayer(n,e=[]){e.length!==0&&(n.save(),n.setLineDash([]),e.forEach(t=>{const a=S.getThemeSpacingColor(n.canvas);if(n.strokeStyle=a,n.fillStyle=a,n.lineWidth=rn.canvas.spacingIndicatorWidth,n.beginPath(),t.type==="horizontal"){const r=t.x1??0,s=t.x2??0,o=t.y??0;n.moveTo(r,o),n.lineTo(s,o),n.stroke();const l=6;n.beginPath(),n.moveTo(r,o-l),n.lineTo(r,o+l),n.stroke(),n.beginPath(),n.moveTo(s,o-l),n.lineTo(s,o+l),n.stroke();const c=t.labelX,d=t.labelY;this.renderDistanceLabel(n,c,d,t.distance)}else if(t.type==="vertical"){const r=t.x??0,s=t.y1??0,o=t.y2??0;n.moveTo(r,s),n.lineTo(r,o),n.stroke();const l=6;n.beginPath(),n.moveTo(r-l,s),n.lineTo(r+l,s),n.stroke(),n.beginPath(),n.moveTo(r-l,o),n.lineTo(r+l,o),n.stroke();const c=t.labelX,d=t.labelY;this.renderDistanceLabel(n,c,d,t.distance)}}),n.restore())}static renderDistanceLabel(n,e,t,a){const r=`${a}`;n.font=`600 ${rn.canvas.spacingLabelFontSize}px ${rn.canvas.spacingLabelFontFamily}`;const o=n.measureText(r).width,l=rn.canvas.spacingLabelFontSize,c=4,d=o+c*2,f=l+c*2;n.fillStyle=S.getThemeSpacingColor(n.canvas),n.beginPath(),n.roundRect(e-d/2,t-f/2,d,f,S.SPACING_LABEL_BORDER_RADIUS),n.fill(),n.fillStyle=S.SPACING_LABEL_TEXT_COLOR,n.textAlign="center",n.textBaseline="middle",n.fillText(r,e,t)}}class se{static renderEditModeLayer(n,e,t,a){if(!e||e.transformType==="image"||e.transformType==="group")return;const r=e,{cursorPosition:s,selectionStart:o,selectionEnd:l,editText:c,editRichText:d,cursorOpacity:f,isTouchDevice:h,selectionHandlePositionsRef:u}=t,g=a||1,m=r.transformType;if(m==="circle"||m==="wave"||m==="arch"||m==="lean"||m==="ascend"||m==="flag"){this.renderTransformEditModeLayer(n,r,t,g);return}const p=r.fontSize||24,y=r.fontFamily||"Arial",b=r.bold||!1,$=r.italic||!1,x=r.underline||!1,w=r.strikethrough||!1,v=r.textAlign||"center";n.save(),n.translate(r.x,r.y),n.rotate(-r.rotation*Math.PI/180);const C=S.getFontMetrics$1(p,y,b,$),_=C.height,T=p*1.2;let E,k,A;if(d&&r.transformType==="custom"&&r.transformData.width){const N=r.transformData.width-S.HORIZONTAL_PADDING*2;A=N;const R=S.splitRichTextIntoLines(d);E=[],k=[],R.forEach(F=>{const L=S.wrapRichTextSpans(F,N,{fontSize:r.fontSize,fontFamily:r.fontFamily,bold:r.bold,italic:r.italic});L.forEach((O,z)=>{E.push(O),k.push({isParagraphStart:z===0,isParagraphEnd:z===L.length-1})})})}else E=c.split(`
5
- `).map(R=>[{text:R,style:{fontSize:p,fontFamily:y,bold:b,italic:$}}]),k=E.map(()=>({isParagraphStart:!0,isParagraphEnd:!0}));const D=E.length>1?C.height+(E.length-1)*T:C.height;let P=-D/2,M=0,W=P,B=_;const I=[];let H=0;E.forEach((N,R)=>{var z,j;const F=k[R].isParagraphStart,L=k[R].isParagraphEnd,O=[];N.forEach(cn=>{Array.from(cn.text).forEach(gn=>{let G=p,on=y,en=b,J=$;if(d&&H<c.length){const Q=d.getStyleAt(H);G=Q.fontSize||p,on=Q.fontFamily||y,en=Q.bold!==void 0?Q.bold:b,J=Q.italic!==void 0?Q.italic:$}n.save();const tn=en?"bold":"normal",U=J?"italic":"normal";n.font=`${U} ${tn} ${G}px "${on}", Arial, sans-serif`;const K=n.measureText(gn).width;n.restore(),O.push({char:gn,width:K,fontSize:G,index:H}),H++})});{const cn=R===0,yn=R===E.length-1,gn=O.map(U=>U.char).join(""),G=((z=gn.match(/^ +/))==null?void 0:z[0].length)||0,on=((j=gn.match(/ +$/))==null?void 0:j[0].length)||0;let en=0;for(let U=0;U<O.length;U++)!cn&&U<G||!yn&&U>=O.length-on||(en+=O[U].width);let J;v==="center"?J=-en/2:v==="right"?J=A!==void 0?A/2-en:-en:J=A!==void 0?-A/2:0;let tn=J;for(let U=0;U<O.length;U++){const K=O[U];I[K.index]={x:tn,y:P,width:K.width,height:K.fontSize},tn+=K.width}if(O.length>0){const U=O[0].index,K=O[O.length-1].index,bn=R<E.length-1&&K+1===H?K:K+1;if(s>=U&&s<=bn)if(s===U)M=J,W=P,B=_;else{let $n=0;for(let an=0;an<O.length&&O[an].index<s;an++){const dn=O[an],Nn=dn.char===" ";let vn=!0;if(Nn){const Un=an<G,V=an>=O.length-on,An=!F&&G>0,Pn=!L&&on>0;vn=!(Un&&An||V&&Pn)}vn&&($n+=dn.width)}M=J+$n,W=P,B=_}}R<E.length-1&&(P+=T)}});const q=o!==l;let Y=null,nn=null;if(q){const N=Math.min(o,l),R=Math.max(o,l);n.save(),n.fillStyle=S.getThemeTextSelectionColor(n.canvas);let F=0,L=-D/2;if(E.forEach((O,z)=>{var on,en;const j=k[z].isParagraphStart,cn=k[z].isParagraphEnd,yn=z===0,gn=z===E.length-1,G=[];if(O.forEach(J=>{Array.from(J.text).forEach(tn=>{const U=J.style||{},K=U.fontSize!==void 0?U.fontSize:p,Q=U.fontFamily!==void 0?U.fontFamily:y,xn=U.bold!==void 0?U.bold:b,bn=U.italic!==void 0?U.italic:$;n.save();const $n=xn?"bold":"normal",an=bn?"italic":"normal";n.font=`${an} ${$n} ${K}px "${Q}", Arial, sans-serif`;const dn=n.measureText(tn).width;n.restore(),G.push({char:tn,index:F,width:dn,style:U}),F++})}),G.length>0){const J=G[0].index,tn=G[G.length-1].index;if(R>J&&N<=tn){n.save();const U=G.map(V=>V.char).join(""),K=((on=U.match(/^ +/))==null?void 0:on[0].length)||0,Q=((en=U.match(/ +$/))==null?void 0:en[0].length)||0;let xn=0;for(let V=0;V<G.length;V++)!yn&&V<K||!gn&&V>=G.length-Q||(xn+=G[V].width);let bn=0;v==="center"?bn=-xn/2:v==="right"&&(bn=-xn);const $n=Math.max(N,J),an=Math.min(R,tn+1);let dn=0;for(let V=0;V<G.length&&G[V].index<$n;V++){const An=G[V],Pn=V<K,Qn=V>=G.length-Q,ne=!j&&K>0,ee=!cn&&Q>0;!(Pn&&ne||Qn&&ee)&&(dn+=An.width)}let Nn=0;for(let V=0;V<G.length&&G[V].index<an;V++){const An=G[V],Pn=V<K,Qn=V>=G.length-Q,ne=!j&&K>0,ee=!cn&&Q>0;!(Pn&&ne||Qn&&ee)&&(Nn+=An.width)}const vn=bn+dn,Un=Nn-dn;n.fillRect(vn,L,Un,_),Y===null&&(Y={x:vn,y:L}),nn={x:vn+Un,y:L+_},n.restore()}}z<E.length-1&&(L+=T)}),n.restore(),d){n.save();const O=r.transformType==="custom"?r.transformData:null,z=O!=null&&O.width?O.width-S.HORIZONTAL_PADDING*2:void 0;S.renderRichTextFillOnly(n,d,{fontSize:p,fontFamily:y,color:r.color||"#000000",bold:b,italic:$,underline:x,strikethrough:w,textAlign:v},z),n.restore()}}if(q&&h&&Y&&nn){const N=Y,R=nn,F=6/g,L=2/g;n.save();const O=S.getThemeAccentColor();n.fillStyle=O,n.strokeStyle=O,n.lineWidth=L,n.lineCap="round";const z={x:N.x,y:N.y-F},j={x:R.x,y:R.y+F};n.beginPath(),n.moveTo(N.x,N.y),n.lineTo(N.x,N.y+_),n.stroke(),n.beginPath(),n.arc(z.x,z.y,F,0,Math.PI*2),n.fill(),n.strokeStyle="white",n.lineWidth=2/g,n.stroke(),n.strokeStyle=O,n.lineWidth=L,n.beginPath(),n.moveTo(R.x,R.y-_),n.lineTo(R.x,R.y),n.stroke(),n.beginPath(),n.arc(j.x,j.y,F,0,Math.PI*2),n.fill(),n.strokeStyle="white",n.lineWidth=2/g,n.stroke(),n.restore(),u&&(u.current={start:{center:z,textEdge:N},end:{center:j,textEdge:R}})}else u&&(u.current={start:null,end:null});!q&&f>0&&(n.save(),n.globalAlpha=f,n.strokeStyle=S.getThemeAccentColor(),n.lineWidth=3/g,n.lineCap="round",n.beginPath(),n.moveTo(M,W),n.lineTo(M,W+B),n.stroke(),n.restore()),n.restore()}static renderTransformEditModeLayer(n,e,t,a=1){const{cursorPosition:r,cursorOpacity:s}=t,o=e.fontSize||24,l=e.fontFamily||"Arial",c=e.bold||!1,d=e.italic||!1;n.save(),n.translate(e.x,e.y),n.rotate(-e.rotation*Math.PI/180);const f=c?"bold":"normal",h=d?"italic":"normal";n.font=`${h} ${f} ${o}px ${l}`;const u=Array.from(e.text),g=u.map(p=>n.measureText(p).width),m=ue.calculateCharPositions(e,u,g);if(r>=0&&r<=u.length&&s>0){let p;if(r===0)if(m.length>0){const b=m[0],$=g[0];p={x:b.x-Math.cos(b.angle)*($/2),y:b.y-Math.sin(b.angle)*($/2),angle:b.angle}}else p={x:0,y:0,angle:0};else if(r>=m.length){const b=m[m.length-1],$=g[g.length-1];p={x:b.x+Math.cos(b.angle)*($/2),y:b.y+Math.sin(b.angle)*($/2),angle:b.angle}}else{const b=m[r],$=g[r];p={x:b.x-Math.cos(b.angle)*($/2),y:b.y-Math.sin(b.angle)*($/2),angle:b.angle}}n.save(),n.translate(p.x,p.y),n.rotate(p.angle),n.globalAlpha=s,n.strokeStyle=S.getThemeAccentColor(),n.lineWidth=2/a;const y=o*1.2;n.beginPath(),n.moveTo(0,-y/2),n.lineTo(0,y/2),n.stroke(),n.restore()}n.restore()}static renderCropBoxLayer(n,e,t,a=1){if(!(e instanceof S.ImageElement)||!e.isCropping)return;const r=e,s=r.getCropBoxBounds();if(!s)return;const o=4/a,l=2/a,c=S.CORNER_HANDLE_VISUAL_RADIUS/a,d=S.EDGE_HANDLE_VISUAL_LENGTH/a,f=1/a;n.save(),n.translate(e.x*a,e.y*a),n.rotate(S.RotationUtils.toRadians(e.rotation));const h=r.transformData.flipHorizontal?-1:1,u=r.transformData.flipVertical?-1:1;n.scale(h*a,u*a);const g=r.transformData.width*r.transformData.cropWidth,m=r.transformData.height*r.transformData.cropHeight,p=r.transformData.width/2-(r.transformData.cropX*r.transformData.width+g/2),y=r.transformData.height/2-(r.transformData.cropY*r.transformData.height+m/2),b=r.transformData.width/2,$=r.transformData.height/2,x={x:p-b,y:y-$,width:r.transformData.width,height:r.transformData.height};n.fillStyle="rgba(0, 0, 0, 0.5)",s.y>x.y&&n.fillRect(x.x,x.y,x.width,s.y-x.y);const w=s.y+s.height,v=x.y+x.height;w<v&&n.fillRect(x.x,w,x.width,v-w),s.x>x.x&&n.fillRect(x.x,s.y,s.x-x.x,s.height);const C=s.x+s.width,_=x.x+x.width;C<_&&n.fillRect(C,s.y,_-C,s.height),n.strokeStyle=rn.canvas.selectionColor,n.lineWidth=l,n.strokeRect(s.x,s.y,s.width,s.height),n.strokeStyle="rgba(255, 255, 255, 0.5)",n.lineWidth=f;const T=s.width/3;n.beginPath(),n.moveTo(s.x+T,s.y),n.lineTo(s.x+T,s.y+s.height),n.moveTo(s.x+2*T,s.y),n.lineTo(s.x+2*T,s.y+s.height),n.stroke();const E=s.height/3;if(n.beginPath(),n.moveTo(s.x,s.y+E),n.lineTo(s.x+s.width,s.y+E),n.moveTo(s.x,s.y+2*E),n.lineTo(s.x+s.width,s.y+2*E),n.stroke(),[{x:s.x,y:s.y},{x:s.x+s.width,y:s.y},{x:s.x+s.width,y:s.y+s.height},{x:s.x,y:s.y+s.height}].forEach(D=>{n.beginPath(),n.arc(D.x,D.y,c+1/a,0,Math.PI*2),n.fillStyle="#bbb",n.fill(),n.beginPath(),n.arc(D.x,D.y,c,0,Math.PI*2),n.fillStyle="#fff",n.fill()}),[{x:s.x+s.width/2,y:s.y,orientation:"horizontal"},{x:s.x+s.width/2,y:s.y+s.height,orientation:"horizontal"},{x:s.x,y:s.y+s.height/2,orientation:"vertical"},{x:s.x+s.width,y:s.y+s.height/2,orientation:"vertical"}].forEach(D=>{let P,M;D.orientation==="horizontal"?(P=d,M=o):(P=o,M=d);const W=D.x-P/2,B=D.y-M/2;n.fillStyle="#fff",n.fillRect(W,B,P,M),n.strokeStyle="#bbb",n.lineWidth=f,n.strokeRect(W,B,P,M)}),n.restore(),t&&t.resizeHandles){const D=t.resizeHandles.filter(B=>B.anchor==="top-left"||B.anchor==="top-right"||B.anchor==="bottom-left"||B.anchor==="bottom-right"),P=r.getCropBoxWorldCorners(),M=6,W=20;D.forEach(B=>{let I=!1;if(P)for(const H of P){const q=B.x-H.x,Y=B.y-H.y;if(Math.sqrt(q*q+Y*Y)<W){I=!0;break}}I||(n.save(),n.globalAlpha=1,n.beginPath(),n.arc(B.x*a,B.y*a,M,0,2*Math.PI),n.fillStyle="#fff",n.fill(),n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=2,n.stroke(),n.restore())})}}}const oa=S.createLogger("CanvasRenderer"),X=class X{static _getContentCanvas(n,e){return(!this._contentCanvas||this._contentCanvasSize.width!==n||this._contentCanvasSize.height!==e)&&(this._contentCanvas=document.createElement("canvas"),this._contentCanvas.width=n,this._contentCanvas.height=e,this._contentCanvasSize={width:n,height:e}),this._contentCanvas}static _getMaskCanvas(n,e){return(!this._maskCanvas||this._maskCanvasSize.width!==n||this._maskCanvasSize.height!==e)&&(this._maskCanvas=document.createElement("canvas"),this._maskCanvas.width=n,this._maskCanvas.height=e,this._maskCanvasSize={width:n,height:e}),this._maskCanvas}static safeRender(n,e,t,a){try{e.render(n,t,a)}catch(r){const s=r instanceof Error?r:new Error(String(r));oa.error(`Failed to render element ${e.id}:`,s),X.onRenderError&&X.onRenderError({category:"render",message:`Failed to render element: ${s.message}`,originalError:s,elementId:e.id,recoverable:!0})}}static renderElement(n,e,t=!0){t&&(n.save(),n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),e.render(n,!1,!1),t&&n.restore()}static applyArtboardClipPath(n,e){const{x:t,y:a,width:r,height:s,clipShape:o}=e,l=e.borderRadius||0;if(n.beginPath(),!o||o==="rectangle")l>0?n.roundRect(t,a,r,s,l):n.rect(t,a,r,s);else if(o==="circle"){const c=t+r/2,d=a+s/2,f=Math.min(r,s)/2;n.arc(c,d,f,0,Math.PI*2)}else if(typeof o=="object"&&o.type==="rounded"){const c=Math.min(o.radius,Math.min(r,s)/2);n.roundRect(t,a,r,s,c)}else if(typeof o=="object"&&o.type==="path")try{const c=new Path2D(o.d);n.translate(t,a),n.clip(c),n.translate(-t,-a);return}catch{n.rect(t,a,r,s)}else if(typeof o=="object"&&o.type==="composite-path")try{const c=new Path2D;for(const d of o.pieces){const f=new Path2D(d.d),h=d.rotation??0,u=new DOMMatrix;if(u.translateSelf(d.x,d.y),h!==0){const g=(d.baseWidth??0)/2,m=(d.baseHeight??0)/2,p=h===90||h===270,y=p?d.baseHeight??0:d.baseWidth??0,b=p?d.baseWidth??0:d.baseHeight??0;u.translateSelf(y/2,b/2),u.rotateSelf(h),u.translateSelf(-g,-m)}c.addPath(f,u)}n.translate(t,a),n.clip(c),n.translate(-t,-a);return}catch{n.rect(t,a,r,s)}n.clip()}static renderElementWithOverflowDimming(n,e,t,a,r,s){const o=n.getTransform(),l=t.borderRadius||0;n.save(),n.globalAlpha=.3*(s?S.PREVIEW_ELEMENT_OPACITY:1),n.filter="blur(4px)",n.beginPath();const d=n.getTransform().inverse(),f=n.canvas.width,h=n.canvas.height,u=new DOMPoint(0,0).matrixTransform(d),g=new DOMPoint(f,h).matrixTransform(d),m=Math.max(g.x-u.x,g.y-u.y),p=u.x-m,y=u.y-m,b=g.x+m,$=g.y+m,x=typeof t.clipShape=="object"&&t.clipShape!==null&&t.clipShape.type==="composite-path"?t.clipShape:null;if(x){const w=new Path2D;w.rect(p,y,b-p,$-y);for(const v of x.pieces){const C=new Path2D(v.d),_=v.rotation??0,T=new DOMMatrix;if(T.translateSelf(t.x+v.x,t.y+v.y),_!==0){const E=(v.baseWidth??0)/2,k=(v.baseHeight??0)/2,A=_===90||_===270,D=A?v.baseHeight??0:v.baseWidth??0,P=A?v.baseWidth??0:v.baseHeight??0;T.translateSelf(D/2,P/2),T.rotateSelf(_),T.translateSelf(-E,-k)}w.addPath(C,T)}n.clip(w,"evenodd")}else n.rect(p,y,b-p,$-y),l>0?n.roundRect(t.x,t.y,t.width,t.height,l):n.rect(t.x,t.y,t.width,t.height),n.clip("evenodd");e.render(n,!1,!1),n.restore(),n.save(),this.applyArtboardClipPath(n,t),s&&(n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),e.render(n,a,r),n.restore(),n.setTransform(o)}static renderElementsLayer(n,e,t,a,r,s,o,l=!0,c=!1,d=!1){const f=r!=null&&r.getMode()==="drag",h=r==null?void 0:r._activeChildContext;e!==X._cachedElementsRef&&(X._cachedElementConfigs=e.map(y=>y.toJSON()),X._cachedElementMap=new Map(e.map(y=>[y.id,y])),X._cachedElementsRef=e);const u=X._cachedElementConfigs,g=X._cachedElementMap,m=X._knockoutRenderedIds;m.clear(),e.forEach((y,b)=>{var $,x,w;if(y.blendMode==="knockout"||y.blendMode==="clip"){const v=u[b],C=y.blendMode==="knockout"?"destination-out":"destination-in",_=(($=v.knockoutParts)==null?void 0:$.scope)||"group",T=u.findIndex(D=>D.id===v.id),E=((x=v.knockoutParts)==null?void 0:x.fill)||((w=v.knockoutParts)==null?void 0:w.stroke),k=_==="artboard"&&T!==-1?u.slice(0,T):[];E&&(_==="artboard"||k.length>0)&&(k.forEach(D=>D.id&&m.add(D.id)),Gn(n,v,u,(D,P)=>{const M=P.id&&g.get(P.id);M&&this.renderElement(D,M,l)},s,o,C),m.add(y.id))}}),e.some(y=>!m.has(y.id)&&y.isClipping)?this._renderWithClipping(n,e,m,t,a,f,h,u,l):e.forEach(y=>{var _,T;if(m.has(y.id)||y.visible===!1)return;const b=y.id===t,$=(a==null?void 0:a.type)==="element"&&((_=a==null?void 0:a.data)==null?void 0:_.id)===y.id,x=f&&h&&Hn(y)&&y.id===t,w=b&&!x,v=u[e.indexOf(y)],C=((T=v==null?void 0:v.distressEffect)==null?void 0:T.enabled)&&v.distressEffect.style==="custom"&&v.distressEffect.textureUrl;if(v&&v.masks&&v.masks.length>0)mn(n,v,E=>{const k=A=>{l&&(A.save(),A.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),this.safeRender(A,y,w,$),l&&A.restore()};if(C){const A=y.getVisualBoundingBox();Xn(E,v.distressEffect,A,k)}else k(E)});else if(C){const E=y.getVisualBoundingBox();Xn(n,v.distressEffect,E,k=>{l&&(k.save(),k.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),this.safeRender(k,y,w,$),l&&k.restore()})}else c&&!d&&o&&w?this.renderElementWithOverflowDimming(n,y,o,w,$,l):c&&o?(n.save(),this.applyArtboardClipPath(n,o),l&&(n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),this.safeRender(n,y,w,$),n.restore()):(l&&(n.save(),n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),this.safeRender(n,y,w,$),l&&n.restore())})}static _renderWithClipping(n,e,t,a,r,s,o,l,c=!0){var y;const d=n.canvas,f=d.width,h=d.height,u=n.getTransform(),g=[];let m=[],p=[];for(let b=0;b<e.length;b++){const $=e[b],x=l[b];t.has($.id)||$.visible!==!1&&($.isClipping?m.length>0?(g.push({content:m,mask:$,contentConfigs:p,maskConfig:x}),m=[],p=[]):g.push({content:[$],contentConfigs:[x]}):(m.push($),p.push(x)))}m.length>0&&g.push({content:m,contentConfigs:p});for(const b of g)if(!b.mask)b.content.forEach(($,x)=>{var E;const w=$.id===a,v=(r==null?void 0:r.type)==="element"&&((E=r==null?void 0:r.data)==null?void 0:E.id)===$.id,C=s&&o&&Hn($)&&$.id===a,_=w&&!C,T=b.contentConfigs[x];T&&T.masks&&T.masks.length>0?mn(n,T,k=>{c&&(k.save(),k.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),$.render(k,_,v),c&&k.restore()}):(c&&(n.save(),n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),$.render(n,_,v),c&&n.restore())});else{const $=this._getContentCanvas(f,h),x=$.getContext("2d");if(!x)continue;x.setTransform(1,0,0,1,0,0),x.clearRect(0,0,f,h),x.globalCompositeOperation="source-over",x.setTransform(u),b.content.forEach((T,E)=>{var W;const k=T.id===a,A=(r==null?void 0:r.type)==="element"&&((W=r==null?void 0:r.data)==null?void 0:W.id)===T.id,D=s&&o&&Hn(T)&&T.id===a,P=k&&!D,M=b.contentConfigs[E];M&&M.masks&&M.masks.length>0?mn(x,M,B=>{c&&(B.save(),B.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),T.render(B,P,A),c&&B.restore()}):(c&&(x.save(),x.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),T.render(x,P,A),c&&x.restore())});const w=this._getMaskCanvas(f,h),v=w.getContext("2d");if(!v)continue;v.setTransform(1,0,0,1,0,0),v.clearRect(0,0,f,h),v.globalCompositeOperation="source-over",v.setTransform(u);const C=b.mask.id===a,_=(r==null?void 0:r.type)==="element"&&((y=r==null?void 0:r.data)==null?void 0:y.id)===b.mask.id;b.maskConfig&&b.maskConfig.masks&&b.maskConfig.masks.length>0?mn(v,b.maskConfig,T=>{c&&(T.save(),T.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),b.mask.render(T,C,_),c&&T.restore()}):(c&&(v.save(),v.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),b.mask.render(v,C,_),c&&v.restore()),x.globalCompositeOperation="destination-in",x.setTransform(1,0,0,1,0,0),x.drawImage(w,0,0),n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage($,0,0),n.restore()}}static renderSnapGuidesLayer(n,e=[]){Rn.renderSnapGuidesLayer(n,e)}static renderSpacingIndicatorsLayer(n,e=[]){Rn.renderSpacingIndicatorsLayer(n,e)}static renderDistanceLabel(n,e,t,a){Rn.renderDistanceLabel(n,e,t,a)}static renderSelectionLayer(n,e,t,a=1){Tn.renderSelectionLayer(n,e,t,a)}static renderPositionSizeInfo(n,e,t,a,r=1){Tn.renderPositionSizeInfo(n,e,t,a,r)}static renderHandlesLayer(n,e,t,a,r,s,o,l=1,c=!0){Tn.renderHandlesLayer(n,e,t,a,r,s,o,l,c)}static renderHoverLayer(n,e,t,a=!1,r=1,s){ue.renderHoverLayer(n,e,t,a,r,s)}static renderCropBoxLayer(n,e,t,a=1){se.renderCropBoxLayer(n,e,t,a)}static render({ctx:n,elements:e,selectedId:t,selectedElement:a,hoverState:r,isEditing:s,stateMachine:o,snapGuides:l=[],spacingIndicators:c=[],artboardBackgroundColor:d,artboard:f,isPreview:h=!0,zoom:u=1,paddingOffset:g={x:0,y:0},showOverflowDimmed:m=!1,suppressOverflowDim:p=!1,distressTexture:y,imageMask:b,editModeData:$}){if(this.renderElementsLayer(n,e,t,r,o??void 0,d,f,h,m,p),y!=null&&y.enabled&&f&&Qe(n,y,f,d),b!=null&&b.enabled&&f&&Xe(n,b,f,d),s&&$&&a&&se.renderEditModeLayer(n,a,$,u),u!==1){n.save();const C=n.getTransform().a/u,_=g.x*u*C,T=g.y*u*C;n.setTransform(C,0,0,C,_,T)}const x=l.map(v=>({...v,x:v.x!==void 0?v.x*u:void 0,y:v.y!==void 0?v.y*u:void 0,x1:v.x1!==void 0?v.x1*u:void 0,y1:v.y1!==void 0?v.y1*u:void 0,x2:v.x2!==void 0?v.x2*u:void 0,y2:v.y2!==void 0?v.y2*u:void 0})),w=c.map(v=>({...v,x:v.x!==void 0?v.x*u:void 0,y:v.y!==void 0?v.y*u:void 0,x1:v.x1!==void 0?v.x1*u:void 0,y1:v.y1!==void 0?v.y1*u:void 0,x2:v.x2!==void 0?v.x2*u:void 0,y2:v.y2!==void 0?v.y2*u:void 0,labelX:v.labelX*u,labelY:v.labelY*u}));Rn.renderSnapGuidesLayer(n,x),Rn.renderSpacingIndicatorsLayer(n,w),u!==1&&n.restore()}static renderInteractionChromeLayer({ctx:n,selectedElement:e,transformHandles:t,stateMachine:a,currentRotation:r,isRotating:s,hoverState:o,selectedId:l,hideHandles:c=!1,isEditing:d,isAltKeyPressed:f=!1,artboardBackgroundColor:h,hoverClipArtboard:u,showRotationHandle:g=!0,zoom:m=1,paddingOffset:p={x:0,y:0}}){if(m!==1){n.save();const $=n.getTransform().a/m,x=p.x*m*$,w=p.y*m*$;n.setTransform($,0,0,$,x,w)}if(e&&Ue(e)&&e.isCropping)t&&se.renderCropBoxLayer(n,e,t,m);else if(!c&&a&&Tn.renderSelectionLayer(n,e,a,m),t&&a&&Tn.renderPositionSizeInfo(n,e,t,a,m),!c&&t&&a&&Tn.renderHandlesLayer(n,e,t,r,s,o,a,m,g),!d){if(u){n.save();const b=u,$=b.x*m,x=b.y*m,w=b.width*m,v=b.height*m,C=(b.borderRadius??0)*m;n.beginPath(),C>0?n.roundRect($,x,w,v,C):n.rect($,x,w,v),n.clip()}ue.renderHoverLayer(n,o,l,f,m,h),u&&n.restore()}m!==1&&n.restore()}};X._contentCanvas=null,X._contentCanvasSize={width:0,height:0},X._maskCanvas=null,X._maskCanvasSize={width:0,height:0},X._cachedElementsRef=null,X._cachedElementConfigs=null,X._cachedElementMap=null,X._knockoutRenderedIds=new Set,X.onRenderError=null;let he=X;const Me=S.createLogger("element-serializer"),$e=4e3,Ln=new Set;function la(i,n){const e=n?ca(n):"no-src";return`${i}:${e}`}function ca(i){let n=0;for(let e=0;e<i.length;e++){const t=i.charCodeAt(e);n=(n<<5)-n+t,n=n&n}return n.toString(36)}function qn(){Ln.clear()}function ve(i){for(const n of Ln)n.startsWith(`${i}:`)&&Ln.delete(n)}function da(i){Ln.add(i)}function fa(i){return Ln.has(i)}async function ua(i,n=$e){const{naturalWidth:e,naturalHeight:t}=i;if(e<=n&&t<=n)return createImageBitmap(i);const a=n/Math.max(e,t),r=Math.round(e*a),s=Math.round(t*a);return createImageBitmap(i,{resizeWidth:r,resizeHeight:s,resizeQuality:"high"})}let Yn=null,Kn=null;function ha(i,n){Yn=i,Kn=n}function pa(){Yn=null,Kn=null}function ga(){qn(),Yn&&Yn()}function ba(i){ve(i),Kn&&Kn(i)}function pe(i,n){const e=i;if(typeof e.fontFamily=="string"&&n.add(e.fontFamily),e.richText&&typeof e.richText=="object"){const t=e.richText;if(t.spans&&Array.isArray(t.spans))for(const a of t.spans){const r=a;if(r.style&&typeof r.style=="object"){const s=r.style;typeof s.fontFamily=="string"&&n.add(s.fontFamily)}}}if(e.children&&Array.isArray(e.children))for(const t of e.children)pe(t,n);if(i.masks&&Array.isArray(i.masks))for(const t of i.masks)t.maskElement&&pe(t.maskElement,n)}function Fe(i){if(typeof document>"u")return i;const n=S.ImageCache.getInstance();return i.map(e=>{if(!(e!=null&&e.maskElement)||e.maskElement.transformType!=="image")return e;const t=e.maskElement.imageUrl;if(!t||!t.startsWith("builtin-mask:"))return e;const a=n.get(t);return a!=null&&a.src&&a.src.startsWith("data:")?{...e,maskElement:{...e.maskElement,imageUrl:a.src}}:e})}async function Oe(i,n,e=$e){const t=n.filter(l=>i.hasElementId(l.id)),a=[],r=[],s=new Set;for(const l of t){const c=l.toJSON();if(pe(c,s),l instanceof S.ImageElement&&!l.imageElement){Me.warn(`[element-serializer] Skipping image ${l.id}: image not loaded (state: ${l.imageLoadState})`);continue}if(l instanceof S.ImageElement&&l.imageElement)try{const d=la(l.id,l.imageUrl);if(!fa(d)){const $=await ua(l.imageElement,e);r.push({cacheKey:d,bitmap:$}),da(d)}const h=l.transformData||{},u=c.masks&&c.masks.length>0,g=u?h.width:h.width*(h.cropWidth??1),m=u?h.height:h.height*(h.cropHeight??1),p={id:l.id,type:"image",x:l.x,y:l.y,width:g,height:m,rotation:l.rotation||0,bitmapCacheKey:d};if(!u&&(h.cropX!==0||h.cropY!==0||h.cropWidth!==1||h.cropHeight!==1)){const $=l.imageElement.naturalWidth,x=l.imageElement.naturalHeight;let w=1;($>e||x>e)&&(w=e/Math.max($,x)),p.cropX=h.cropX*$*w,p.cropY=h.cropY*x*w,p.cropWidth=h.cropWidth*$*w,p.cropHeight=h.cropHeight*x*w}h.flipHorizontal&&(p.flipHorizontal=h.flipHorizontal),h.flipVertical&&(p.flipVertical=h.flipVertical),h.borderRadius&&(p.borderRadius=h.borderRadius),l.opacity!==void 0&&(p.opacity=l.opacity);const b=p;l.distressEffect&&(b.distressEffect={...l.distressEffect}),c.masks&&c.masks.length>0&&(b.masks=Fe(c.masks)),c.blendMode&&(b.blendMode=c.blendMode),c.knockoutParts&&(b.knockoutParts=c.knockoutParts),"getVisualBoundingBox"in l&&typeof l.getVisualBoundingBox=="function"?b._boundingBox=l.getVisualBoundingBox():"getBoundingBox"in l&&typeof l.getBoundingBox=="function"&&(b._boundingBox=l.getBoundingBox()),a.push(b)}catch(d){Me.error(`[element-serializer] Failed to create ImageBitmap for ${c.id}:`,d)}else{const d={...c,type:c.transformType};d.masks&&Array.isArray(d.masks)&&d.masks.length>0&&(d.masks=Fe(d.masks)),"getVisualBoundingBox"in l&&typeof l.getVisualBoundingBox=="function"?d._boundingBox=l.getVisualBoundingBox():"getBoundingBox"in l&&typeof l.getBoundingBox=="function"&&(d._boundingBox=l.getBoundingBox()),a.push(d)}}const o=Array.from(s);return{data:{version:"1.0.0",artboard:{id:i.id,name:i.name,width:i.width,height:i.height,backgroundColor:i.backgroundColor,exportBackground:i.exportBackground,x:i.x,y:i.y,...i.distressTexture&&{distressTexture:{...i.distressTexture}},...i.imageMask&&{imageMask:{...i.imageMask}}},elements:a,fonts:o},newBitmaps:r}}const ma=`"use strict";
4
+ `);p.forEach((x,w)=>{const v=b+c.ascent+w*d,C=$||w===0,_=$||w===p.length-1;let T=x;C||(T=T.replace(/^ +/,"")),_||(T=T.replace(/ +$/,"")),g.globalCompositeOperation="source-over",g.strokeStyle=n.strokeStyle,g.globalAlpha=Math.min(n.globalAlpha*1.6,.8),g.lineWidth=(h+f)*2,g.lineJoin="round",g.strokeText(T,0,v),g.globalCompositeOperation="destination-out",g.globalAlpha=1,g.lineWidth=h*2,g.strokeText(T,0,v),g.fillText(T,0,v)})}n.setTransform(1,0,0,1,0,0),n.drawImage(u,0,0),n.restore()}static renderTransformHoverRingEffect(n,e,t){n.save(),n.translate(e.x*t,e.y*t),t!==1&&n.scale(t,t),n.rotate(-e.rotation*Math.PI/180);const a=4/t,r=4/t,s=document.createElement("canvas");s.width=n.canvas.width,s.height=n.canvas.height;const o=s.getContext("2d");if(!o){n.restore();return}o.setTransform(n.getTransform()),this.renderTransformWithHoverEffect(o,e,a,r,n.strokeStyle),n.setTransform(1,0,0,1,0,0),n.drawImage(s,0,0),n.restore()}static renderTransformWithHoverEffect(n,e,t,a,r){const s=e,o=s.fontSize,l=s.fontFamily,c=s.bold||!1,d=s.italic||!1,f=c?"bold":"normal",h=d?"italic":"normal";if(n.font=`${h} ${f} ${o}px ${l}`,n.textAlign="center",n.textBaseline="middle",s.transformType==="lean"){const b=-s.transformData.leanAmount*Math.PI/4;n.transform(1,0,Math.tan(b),1,0,0),n.globalCompositeOperation="source-over",n.strokeStyle=r,n.globalAlpha=.8,n.lineWidth=(a+t)*2,n.lineJoin="round",n.strokeText(s.text,0,0),n.globalCompositeOperation="destination-out",n.globalAlpha=1,n.lineWidth=a*2,n.strokeText(s.text,0,0),n.fillText(s.text,0,0);return}const u=s.text.split(""),g=u.map(y=>n.measureText(y).width),m=this.calculateCharPositions(e,u,g),p=y=>{n.translate(y.x,y.y),y.angle&&n.rotate(y.angle),y.skewY&&n.transform(1,y.skewY,0,1,0,0)};n.globalCompositeOperation="source-over",n.strokeStyle=r,n.globalAlpha=.8,n.lineWidth=(a+t)*2,n.lineJoin="round",m.forEach((y,b)=>{n.save(),p(y),n.strokeText(u[b],0,0),n.restore()}),n.globalCompositeOperation="destination-out",n.globalAlpha=1,n.lineWidth=a*2,m.forEach((y,b)=>{n.save(),p(y),n.strokeText(u[b],0,0),n.fillText(u[b],0,0),n.restore()})}static calculateCharPositions(n,e,t){const a=n.transformType,r=n.transformData;return a==="circle"?this.calculateCirclePositions(r,e,t):a==="wave"?this.calculateWavePositions(n,e,t,r):a==="arch"?this.calculateArchPositions(n,e,t,r):a==="lean"?this.calculateLeanPositions(e,t):a==="ascend"?this.calculateAscendPositions(n,e,t,r):a==="flag"?this.calculateFlagPositions(n,e,t,r):e.map(()=>({x:0,y:0,angle:0}))}static calculateCirclePositions(n,e,t){const a=[],r=t.reduce((o,l)=>o+l,0),s=n.radius*n.scale;if(n.reverse){let o=Math.PI/2+r/(2*s);e.forEach((l,c)=>{const f=t[c]/s,h=Math.cos(o-f/2)*s,u=Math.sin(o-f/2)*s,g=o-f/2-Math.PI/2;a.push({x:h,y:u,angle:g}),o-=f})}else{let o=-Math.PI/2-r/(2*s);e.forEach((l,c)=>{const f=t[c]/s,h=Math.cos(o+f/2)*s,u=Math.sin(o+f/2)*s,g=o+f/2+Math.PI/2;a.push({x:h,y:u,angle:g}),o+=f})}return a}static calculateWavePositions(n,e,t,a){const r=[];let o=-t.reduce((l,c)=>l+c,0)/2;return e.forEach((l,c)=>{const d=t[c],f=o+d/2,h=f/(a.width/2),u=a.amplitude*n.fontSize*Math.sin(a.frequency*Math.PI*h),g=a.amplitude*a.frequency*Math.PI*Math.cos(a.frequency*Math.PI*h);r.push({x:f,y:u,angle:0,skewY:g*S.WAVE_SKEW_FACTOR}),o+=d}),r}static calculateArchPositions(n,e,t,a){const r=[],s=t.reduce((c,d)=>c+d,0),o=a.width/2;let l=-s/2;return e.forEach((c,d)=>{const f=t[d],h=l+f/2,u=h/o,g=(Math.pow(u,2)-1)*a.archHeight*n.fontSize,m=2*u*a.archHeight;r.push({x:h,y:g,angle:0,skewY:m*.3}),l+=f}),r}static calculateLeanPositions(n,e){const t=[];let r=-e.reduce((s,o)=>s+o,0)/2;return n.forEach((s,o)=>{const l=e[o],c=r+l/2;t.push({x:c,y:0,angle:0}),r+=l}),t}static calculateAscendPositions(n,e,t,a){const r=[],s=t.reduce((d,f)=>d+f,0),o=a.ascendAngle*Math.PI/180,l=Math.tan(o);let c=-s/2;return e.forEach((d,f)=>{const h=t[f],u=c+h/2,g=u*l;r.push({x:u,y:g,angle:0,skewY:l*1}),c+=h}),r}static calculateFlagPositions(n,e,t,a){const r=[];let o=-t.reduce((l,c)=>l+c,0)/2;return e.forEach((l,c)=>{const d=t[c],f=o+d/2,h=f/(a.width/2),u=Math.abs(h),g=a.amplitude*u,m=g*n.fontSize*Math.sin(a.frequency*Math.PI*h),p=g*a.frequency*Math.PI*Math.cos(a.frequency*Math.PI*h),y=a.amplitude*Math.sign(h)*Math.sin(a.frequency*Math.PI*h),b=p+y;r.push({x:f,y:m,angle:0,skewY:b*.3}),o+=d}),r}}class Rn{static renderSnapGuidesLayer(n,e=[]){e.length!==0&&(n.save(),n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=rn.canvas.snapGuideWidth,n.setLineDash(rn.canvas.snapGuideDash),e.forEach(t=>{n.beginPath(),t.type==="vertical"?(n.moveTo(t.x??0,t.y1??0),n.lineTo(t.x??0,t.y2??0)):t.type==="horizontal"?(n.moveTo(t.x1??0,t.y??0),n.lineTo(t.x2??0,t.y??0)):(n.moveTo(t.x1??0,t.y1??0),n.lineTo(t.x2??0,t.y2??0)),n.stroke()}),n.restore())}static renderSpacingIndicatorsLayer(n,e=[]){e.length!==0&&(n.save(),n.setLineDash([]),e.forEach(t=>{const a=S.getThemeSpacingColor(n.canvas);if(n.strokeStyle=a,n.fillStyle=a,n.lineWidth=rn.canvas.spacingIndicatorWidth,n.beginPath(),t.type==="horizontal"){const r=t.x1??0,s=t.x2??0,o=t.y??0;n.moveTo(r,o),n.lineTo(s,o),n.stroke();const l=6;n.beginPath(),n.moveTo(r,o-l),n.lineTo(r,o+l),n.stroke(),n.beginPath(),n.moveTo(s,o-l),n.lineTo(s,o+l),n.stroke();const c=t.labelX,d=t.labelY;this.renderDistanceLabel(n,c,d,t.distance)}else if(t.type==="vertical"){const r=t.x??0,s=t.y1??0,o=t.y2??0;n.moveTo(r,s),n.lineTo(r,o),n.stroke();const l=6;n.beginPath(),n.moveTo(r-l,s),n.lineTo(r+l,s),n.stroke(),n.beginPath(),n.moveTo(r-l,o),n.lineTo(r+l,o),n.stroke();const c=t.labelX,d=t.labelY;this.renderDistanceLabel(n,c,d,t.distance)}}),n.restore())}static renderDistanceLabel(n,e,t,a){const r=`${a}`;n.font=`600 ${rn.canvas.spacingLabelFontSize}px ${rn.canvas.spacingLabelFontFamily}`;const o=n.measureText(r).width,l=rn.canvas.spacingLabelFontSize,c=4,d=o+c*2,f=l+c*2;n.fillStyle=S.getThemeSpacingColor(n.canvas),n.beginPath(),n.roundRect(e-d/2,t-f/2,d,f,S.SPACING_LABEL_BORDER_RADIUS),n.fill(),n.fillStyle=S.SPACING_LABEL_TEXT_COLOR,n.textAlign="center",n.textBaseline="middle",n.fillText(r,e,t)}}class ie{static renderEditModeLayer(n,e,t,a){if(!e||e.transformType==="image"||e.transformType==="group")return;const r=e,{cursorPosition:s,selectionStart:o,selectionEnd:l,editText:c,editRichText:d,cursorOpacity:f,isTouchDevice:h,selectionHandlePositionsRef:u}=t,g=a||1,m=r.transformType;if(m==="circle"||m==="wave"||m==="arch"||m==="lean"||m==="ascend"||m==="flag"){this.renderTransformEditModeLayer(n,r,t,g);return}const p=r.fontSize||24,y=r.fontFamily||"Arial",b=r.bold||!1,$=r.italic||!1,x=r.underline||!1,w=r.strikethrough||!1,v=r.textAlign||"center";n.save(),n.translate(r.x,r.y),n.rotate(-r.rotation*Math.PI/180);const C=S.getFontMetrics$1(p,y,b,$),_=C.height,T=p*1.2;let E,k,A;if(d&&r.transformType==="custom"&&r.transformData.width){const N=r.transformData.width-S.HORIZONTAL_PADDING*2;A=N;const R=S.splitRichTextIntoLines(d);E=[],k=[],R.forEach(F=>{const L=S.wrapRichTextSpans(F,N,{fontSize:r.fontSize,fontFamily:r.fontFamily,bold:r.bold,italic:r.italic});L.forEach((O,z)=>{E.push(O),k.push({isParagraphStart:z===0,isParagraphEnd:z===L.length-1})})})}else E=c.split(`
5
+ `).map(R=>[{text:R,style:{fontSize:p,fontFamily:y,bold:b,italic:$}}]),k=E.map(()=>({isParagraphStart:!0,isParagraphEnd:!0}));const D=E.length>1?C.height+(E.length-1)*T:C.height;let P=-D/2,M=0,W=P,B=_;const I=[];let H=0;E.forEach((N,R)=>{var z,j;const F=k[R].isParagraphStart,L=k[R].isParagraphEnd,O=[];N.forEach(cn=>{Array.from(cn.text).forEach(gn=>{let G=p,on=y,en=b,Z=$;if(d&&H<c.length){const Q=d.getStyleAt(H);G=Q.fontSize||p,on=Q.fontFamily||y,en=Q.bold!==void 0?Q.bold:b,Z=Q.italic!==void 0?Q.italic:$}n.save();const tn=en?"bold":"normal",U=Z?"italic":"normal";n.font=`${U} ${tn} ${G}px "${on}", Arial, sans-serif`;const K=n.measureText(gn).width;n.restore(),O.push({char:gn,width:K,fontSize:G,index:H}),H++})});{const cn=R===0,yn=R===E.length-1,gn=O.map(U=>U.char).join(""),G=((z=gn.match(/^ +/))==null?void 0:z[0].length)||0,on=((j=gn.match(/ +$/))==null?void 0:j[0].length)||0;let en=0;for(let U=0;U<O.length;U++)!cn&&U<G||!yn&&U>=O.length-on||(en+=O[U].width);let Z;v==="center"?Z=-en/2:v==="right"?Z=A!==void 0?A/2-en:-en:Z=A!==void 0?-A/2:0;let tn=Z;for(let U=0;U<O.length;U++){const K=O[U];I[K.index]={x:tn,y:P,width:K.width,height:K.fontSize},tn+=K.width}if(O.length>0){const U=O[0].index,K=O[O.length-1].index,bn=R<E.length-1&&K+1===H?K:K+1;if(s>=U&&s<=bn)if(s===U)M=Z,W=P,B=_;else{let $n=0;for(let an=0;an<O.length&&O[an].index<s;an++){const dn=O[an],Un=dn.char===" ";let vn=!0;if(Un){const zn=an<G,V=an>=O.length-on,An=!F&&G>0,Pn=!L&&on>0;vn=!(zn&&An||V&&Pn)}vn&&($n+=dn.width)}M=Z+$n,W=P,B=_}}R<E.length-1&&(P+=T)}});const q=o!==l;let Y=null,nn=null;if(q){const N=Math.min(o,l),R=Math.max(o,l);n.save(),n.fillStyle=S.getThemeTextSelectionColor(n.canvas);let F=0,L=-D/2;if(E.forEach((O,z)=>{var on,en;const j=k[z].isParagraphStart,cn=k[z].isParagraphEnd,yn=z===0,gn=z===E.length-1,G=[];if(O.forEach(Z=>{Array.from(Z.text).forEach(tn=>{const U=Z.style||{},K=U.fontSize!==void 0?U.fontSize:p,Q=U.fontFamily!==void 0?U.fontFamily:y,xn=U.bold!==void 0?U.bold:b,bn=U.italic!==void 0?U.italic:$;n.save();const $n=xn?"bold":"normal",an=bn?"italic":"normal";n.font=`${an} ${$n} ${K}px "${Q}", Arial, sans-serif`;const dn=n.measureText(tn).width;n.restore(),G.push({char:tn,index:F,width:dn,style:U}),F++})}),G.length>0){const Z=G[0].index,tn=G[G.length-1].index;if(R>Z&&N<=tn){n.save();const U=G.map(V=>V.char).join(""),K=((on=U.match(/^ +/))==null?void 0:on[0].length)||0,Q=((en=U.match(/ +$/))==null?void 0:en[0].length)||0;let xn=0;for(let V=0;V<G.length;V++)!yn&&V<K||!gn&&V>=G.length-Q||(xn+=G[V].width);let bn=0;v==="center"?bn=-xn/2:v==="right"&&(bn=-xn);const $n=Math.max(N,Z),an=Math.min(R,tn+1);let dn=0;for(let V=0;V<G.length&&G[V].index<$n;V++){const An=G[V],Pn=V<K,ne=V>=G.length-Q,ee=!j&&K>0,te=!cn&&Q>0;!(Pn&&ee||ne&&te)&&(dn+=An.width)}let Un=0;for(let V=0;V<G.length&&G[V].index<an;V++){const An=G[V],Pn=V<K,ne=V>=G.length-Q,ee=!j&&K>0,te=!cn&&Q>0;!(Pn&&ee||ne&&te)&&(Un+=An.width)}const vn=bn+dn,zn=Un-dn;n.fillRect(vn,L,zn,_),Y===null&&(Y={x:vn,y:L}),nn={x:vn+zn,y:L+_},n.restore()}}z<E.length-1&&(L+=T)}),n.restore(),d){n.save();const O=r.transformType==="custom"?r.transformData:null,z=O!=null&&O.width?O.width-S.HORIZONTAL_PADDING*2:void 0;S.renderRichTextFillOnly(n,d,{fontSize:p,fontFamily:y,color:r.color||"#000000",bold:b,italic:$,underline:x,strikethrough:w,textAlign:v},z),n.restore()}}if(q&&h&&Y&&nn){const N=Y,R=nn,F=6/g,L=2/g;n.save();const O=S.getThemeAccentColor();n.fillStyle=O,n.strokeStyle=O,n.lineWidth=L,n.lineCap="round";const z={x:N.x,y:N.y-F},j={x:R.x,y:R.y+F};n.beginPath(),n.moveTo(N.x,N.y),n.lineTo(N.x,N.y+_),n.stroke(),n.beginPath(),n.arc(z.x,z.y,F,0,Math.PI*2),n.fill(),n.strokeStyle="white",n.lineWidth=2/g,n.stroke(),n.strokeStyle=O,n.lineWidth=L,n.beginPath(),n.moveTo(R.x,R.y-_),n.lineTo(R.x,R.y),n.stroke(),n.beginPath(),n.arc(j.x,j.y,F,0,Math.PI*2),n.fill(),n.strokeStyle="white",n.lineWidth=2/g,n.stroke(),n.restore(),u&&(u.current={start:{center:z,textEdge:N},end:{center:j,textEdge:R}})}else u&&(u.current={start:null,end:null});!q&&f>0&&(n.save(),n.globalAlpha=f,n.strokeStyle=S.getThemeAccentColor(),n.lineWidth=3/g,n.lineCap="round",n.beginPath(),n.moveTo(M,W),n.lineTo(M,W+B),n.stroke(),n.restore()),n.restore()}static renderTransformEditModeLayer(n,e,t,a=1){const{cursorPosition:r,cursorOpacity:s}=t,o=e.fontSize||24,l=e.fontFamily||"Arial",c=e.bold||!1,d=e.italic||!1;n.save(),n.translate(e.x,e.y),n.rotate(-e.rotation*Math.PI/180);const f=c?"bold":"normal",h=d?"italic":"normal";n.font=`${h} ${f} ${o}px ${l}`;const u=Array.from(e.text),g=u.map(p=>n.measureText(p).width),m=he.calculateCharPositions(e,u,g);if(r>=0&&r<=u.length&&s>0){let p;if(r===0)if(m.length>0){const b=m[0],$=g[0];p={x:b.x-Math.cos(b.angle)*($/2),y:b.y-Math.sin(b.angle)*($/2),angle:b.angle}}else p={x:0,y:0,angle:0};else if(r>=m.length){const b=m[m.length-1],$=g[g.length-1];p={x:b.x+Math.cos(b.angle)*($/2),y:b.y+Math.sin(b.angle)*($/2),angle:b.angle}}else{const b=m[r],$=g[r];p={x:b.x-Math.cos(b.angle)*($/2),y:b.y-Math.sin(b.angle)*($/2),angle:b.angle}}n.save(),n.translate(p.x,p.y),n.rotate(p.angle),n.globalAlpha=s,n.strokeStyle=S.getThemeAccentColor(),n.lineWidth=2/a;const y=o*1.2;n.beginPath(),n.moveTo(0,-y/2),n.lineTo(0,y/2),n.stroke(),n.restore()}n.restore()}static renderCropBoxLayer(n,e,t,a=1){if(!(e instanceof S.ImageElement)||!e.isCropping)return;const r=e,s=r.getCropBoxBounds();if(!s)return;const o=4/a,l=2/a,c=S.CORNER_HANDLE_VISUAL_RADIUS/a,d=S.EDGE_HANDLE_VISUAL_LENGTH/a,f=1/a;n.save(),n.translate(e.x*a,e.y*a),n.rotate(S.RotationUtils.toRadians(e.rotation));const h=r.transformData.flipHorizontal?-1:1,u=r.transformData.flipVertical?-1:1;n.scale(h*a,u*a);const g=r.transformData.width*r.transformData.cropWidth,m=r.transformData.height*r.transformData.cropHeight,p=r.transformData.width/2-(r.transformData.cropX*r.transformData.width+g/2),y=r.transformData.height/2-(r.transformData.cropY*r.transformData.height+m/2),b=r.transformData.width/2,$=r.transformData.height/2,x={x:p-b,y:y-$,width:r.transformData.width,height:r.transformData.height};n.fillStyle="rgba(0, 0, 0, 0.5)",s.y>x.y&&n.fillRect(x.x,x.y,x.width,s.y-x.y);const w=s.y+s.height,v=x.y+x.height;w<v&&n.fillRect(x.x,w,x.width,v-w),s.x>x.x&&n.fillRect(x.x,s.y,s.x-x.x,s.height);const C=s.x+s.width,_=x.x+x.width;C<_&&n.fillRect(C,s.y,_-C,s.height),n.strokeStyle=rn.canvas.selectionColor,n.lineWidth=l,n.strokeRect(s.x,s.y,s.width,s.height),n.strokeStyle="rgba(255, 255, 255, 0.5)",n.lineWidth=f;const T=s.width/3;n.beginPath(),n.moveTo(s.x+T,s.y),n.lineTo(s.x+T,s.y+s.height),n.moveTo(s.x+2*T,s.y),n.lineTo(s.x+2*T,s.y+s.height),n.stroke();const E=s.height/3;if(n.beginPath(),n.moveTo(s.x,s.y+E),n.lineTo(s.x+s.width,s.y+E),n.moveTo(s.x,s.y+2*E),n.lineTo(s.x+s.width,s.y+2*E),n.stroke(),[{x:s.x,y:s.y},{x:s.x+s.width,y:s.y},{x:s.x+s.width,y:s.y+s.height},{x:s.x,y:s.y+s.height}].forEach(D=>{n.beginPath(),n.arc(D.x,D.y,c+1/a,0,Math.PI*2),n.fillStyle="#bbb",n.fill(),n.beginPath(),n.arc(D.x,D.y,c,0,Math.PI*2),n.fillStyle="#fff",n.fill()}),[{x:s.x+s.width/2,y:s.y,orientation:"horizontal"},{x:s.x+s.width/2,y:s.y+s.height,orientation:"horizontal"},{x:s.x,y:s.y+s.height/2,orientation:"vertical"},{x:s.x+s.width,y:s.y+s.height/2,orientation:"vertical"}].forEach(D=>{let P,M;D.orientation==="horizontal"?(P=d,M=o):(P=o,M=d);const W=D.x-P/2,B=D.y-M/2;n.fillStyle="#fff",n.fillRect(W,B,P,M),n.strokeStyle="#bbb",n.lineWidth=f,n.strokeRect(W,B,P,M)}),n.restore(),t&&t.resizeHandles){const D=t.resizeHandles.filter(B=>B.anchor==="top-left"||B.anchor==="top-right"||B.anchor==="bottom-left"||B.anchor==="bottom-right"),P=r.getCropBoxWorldCorners(),M=6,W=20;D.forEach(B=>{let I=!1;if(P)for(const H of P){const q=B.x-H.x,Y=B.y-H.y;if(Math.sqrt(q*q+Y*Y)<W){I=!0;break}}I||(n.save(),n.globalAlpha=1,n.beginPath(),n.arc(B.x*a,B.y*a,M,0,2*Math.PI),n.fillStyle="#fff",n.fill(),n.strokeStyle=S.getThemeAccentColor(n.canvas),n.lineWidth=2,n.stroke(),n.restore())})}}}const da=S.createLogger("CanvasRenderer"),X=class X{static _getContentCanvas(n,e){return(!this._contentCanvas||this._contentCanvasSize.width!==n||this._contentCanvasSize.height!==e)&&(this._contentCanvas=document.createElement("canvas"),this._contentCanvas.width=n,this._contentCanvas.height=e,this._contentCanvasSize={width:n,height:e}),this._contentCanvas}static _getMaskCanvas(n,e){return(!this._maskCanvas||this._maskCanvasSize.width!==n||this._maskCanvasSize.height!==e)&&(this._maskCanvas=document.createElement("canvas"),this._maskCanvas.width=n,this._maskCanvas.height=e,this._maskCanvasSize={width:n,height:e}),this._maskCanvas}static safeRender(n,e,t,a){try{e.render(n,t,a)}catch(r){const s=r instanceof Error?r:new Error(String(r));da.error(`Failed to render element ${e.id}:`,s),X.onRenderError&&X.onRenderError({category:"render",message:`Failed to render element: ${s.message}`,originalError:s,elementId:e.id,recoverable:!0})}}static renderElement(n,e,t=!0){t&&(n.save(),n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),e.render(n,!1,!1),t&&n.restore()}static applyArtboardClipPath(n,e){const{x:t,y:a,width:r,height:s,clipShape:o}=e,l=e.borderRadius||0;if(n.beginPath(),!o||o==="rectangle")l>0?n.roundRect(t,a,r,s,l):n.rect(t,a,r,s);else if(o==="circle"){const c=t+r/2,d=a+s/2,f=Math.min(r,s)/2;n.arc(c,d,f,0,Math.PI*2)}else if(typeof o=="object"&&o.type==="rounded"){const c=Math.min(o.radius,Math.min(r,s)/2);n.roundRect(t,a,r,s,c)}else if(typeof o=="object"&&o.type==="path")try{const c=new Path2D(o.d);n.translate(t,a),n.clip(c),n.translate(-t,-a);return}catch{n.rect(t,a,r,s)}else if(typeof o=="object"&&o.type==="composite-path")try{const c=new Path2D;for(const d of o.pieces){const f=new Path2D(d.d),h=d.rotation??0,u=new DOMMatrix;if(u.translateSelf(d.x,d.y),h!==0){const g=(d.baseWidth??0)/2,m=(d.baseHeight??0)/2,p=h===90||h===270,y=p?d.baseHeight??0:d.baseWidth??0,b=p?d.baseWidth??0:d.baseHeight??0;u.translateSelf(y/2,b/2),u.rotateSelf(h),u.translateSelf(-g,-m)}c.addPath(f,u)}n.translate(t,a),n.clip(c),n.translate(-t,-a);return}catch{n.rect(t,a,r,s)}n.clip()}static renderElementWithOverflowDimming(n,e,t,a,r,s){const o=n.getTransform(),l=t.borderRadius||0;n.save(),n.globalAlpha=.3*(s?S.PREVIEW_ELEMENT_OPACITY:1),n.filter="blur(4px)",n.beginPath();const d=n.getTransform().inverse(),f=n.canvas.width,h=n.canvas.height,u=new DOMPoint(0,0).matrixTransform(d),g=new DOMPoint(f,h).matrixTransform(d),m=Math.max(g.x-u.x,g.y-u.y),p=u.x-m,y=u.y-m,b=g.x+m,$=g.y+m,x=typeof t.clipShape=="object"&&t.clipShape!==null&&t.clipShape.type==="composite-path"?t.clipShape:null;if(x){const w=new Path2D;w.rect(p,y,b-p,$-y);for(const v of x.pieces){const C=new Path2D(v.d),_=v.rotation??0,T=new DOMMatrix;if(T.translateSelf(t.x+v.x,t.y+v.y),_!==0){const E=(v.baseWidth??0)/2,k=(v.baseHeight??0)/2,A=_===90||_===270,D=A?v.baseHeight??0:v.baseWidth??0,P=A?v.baseWidth??0:v.baseHeight??0;T.translateSelf(D/2,P/2),T.rotateSelf(_),T.translateSelf(-E,-k)}w.addPath(C,T)}n.clip(w,"evenodd")}else n.rect(p,y,b-p,$-y),l>0?n.roundRect(t.x,t.y,t.width,t.height,l):n.rect(t.x,t.y,t.width,t.height),n.clip("evenodd");e.render(n,!1,!1),n.restore(),n.save(),this.applyArtboardClipPath(n,t),s&&(n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),e.render(n,a,r),n.restore(),n.setTransform(o)}static renderElementsLayer(n,e,t,a,r,s,o,l=!0,c=!1,d=!1){const f=r!=null&&r.getMode()==="drag",h=r==null?void 0:r._activeChildContext;e!==X._cachedElementsRef&&(X._cachedElementConfigs=e.map(y=>y.toJSON()),X._cachedElementMap=new Map(e.map(y=>[y.id,y])),X._cachedElementsRef=e);const u=X._cachedElementConfigs,g=X._cachedElementMap,m=X._knockoutRenderedIds;m.clear(),e.forEach((y,b)=>{var $,x,w;if(y.blendMode==="knockout"||y.blendMode==="clip"){const v=u[b],C=y.blendMode==="knockout"?"destination-out":"destination-in",_=(($=v.knockoutParts)==null?void 0:$.scope)||"group",T=u.findIndex(D=>D.id===v.id),E=((x=v.knockoutParts)==null?void 0:x.fill)||((w=v.knockoutParts)==null?void 0:w.stroke),k=_==="artboard"&&T!==-1?u.slice(0,T):[];E&&(_==="artboard"||k.length>0)&&(k.forEach(D=>D.id&&m.add(D.id)),Vn(n,v,u,(D,P)=>{const M=P.id&&g.get(P.id);M&&this.renderElement(D,M,l)},s,o,C),m.add(y.id))}}),e.some(y=>!m.has(y.id)&&y.isClipping)?this._renderWithClipping(n,e,m,t,a,f,h,u,l):e.forEach(y=>{var _,T;if(m.has(y.id)||y.visible===!1)return;const b=y.id===t,$=(a==null?void 0:a.type)==="element"&&((_=a==null?void 0:a.data)==null?void 0:_.id)===y.id,x=f&&h&&Gn(y)&&y.id===t,w=b&&!x,v=u[e.indexOf(y)],C=((T=v==null?void 0:v.distressEffect)==null?void 0:T.enabled)&&v.distressEffect.style==="custom"&&v.distressEffect.textureUrl;if(v&&v.masks&&v.masks.length>0)mn(n,v,E=>{const k=A=>{l&&(A.save(),A.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),this.safeRender(A,y,w,$),l&&A.restore()};if(C){const A=y.getVisualBoundingBox();qn(E,v.distressEffect,A,k)}else k(E)});else if(C){const E=y.getVisualBoundingBox();qn(n,v.distressEffect,E,k=>{l&&(k.save(),k.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),this.safeRender(k,y,w,$),l&&k.restore()})}else c&&!d&&o&&w?this.renderElementWithOverflowDimming(n,y,o,w,$,l):c&&o?(n.save(),this.applyArtboardClipPath(n,o),l&&(n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),this.safeRender(n,y,w,$),n.restore()):(l&&(n.save(),n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),this.safeRender(n,y,w,$),l&&n.restore())})}static _renderWithClipping(n,e,t,a,r,s,o,l,c=!0){var y;const d=n.canvas,f=d.width,h=d.height,u=n.getTransform(),g=[];let m=[],p=[];for(let b=0;b<e.length;b++){const $=e[b],x=l[b];t.has($.id)||$.visible!==!1&&($.isClipping?m.length>0?(g.push({content:m,mask:$,contentConfigs:p,maskConfig:x}),m=[],p=[]):g.push({content:[$],contentConfigs:[x]}):(m.push($),p.push(x)))}m.length>0&&g.push({content:m,contentConfigs:p});for(const b of g)if(!b.mask)b.content.forEach(($,x)=>{var E;const w=$.id===a,v=(r==null?void 0:r.type)==="element"&&((E=r==null?void 0:r.data)==null?void 0:E.id)===$.id,C=s&&o&&Gn($)&&$.id===a,_=w&&!C,T=b.contentConfigs[x];T&&T.masks&&T.masks.length>0?mn(n,T,k=>{c&&(k.save(),k.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),$.render(k,_,v),c&&k.restore()}):(c&&(n.save(),n.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),$.render(n,_,v),c&&n.restore())});else{const $=this._getContentCanvas(f,h),x=$.getContext("2d");if(!x)continue;x.setTransform(1,0,0,1,0,0),x.clearRect(0,0,f,h),x.globalCompositeOperation="source-over",x.setTransform(u),b.content.forEach((T,E)=>{var W;const k=T.id===a,A=(r==null?void 0:r.type)==="element"&&((W=r==null?void 0:r.data)==null?void 0:W.id)===T.id,D=s&&o&&Gn(T)&&T.id===a,P=k&&!D,M=b.contentConfigs[E];M&&M.masks&&M.masks.length>0?mn(x,M,B=>{c&&(B.save(),B.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),T.render(B,P,A),c&&B.restore()}):(c&&(x.save(),x.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),T.render(x,P,A),c&&x.restore())});const w=this._getMaskCanvas(f,h),v=w.getContext("2d");if(!v)continue;v.setTransform(1,0,0,1,0,0),v.clearRect(0,0,f,h),v.globalCompositeOperation="source-over",v.setTransform(u);const C=b.mask.id===a,_=(r==null?void 0:r.type)==="element"&&((y=r==null?void 0:r.data)==null?void 0:y.id)===b.mask.id;b.maskConfig&&b.maskConfig.masks&&b.maskConfig.masks.length>0?mn(v,b.maskConfig,T=>{c&&(T.save(),T.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),b.mask.render(T,C,_),c&&T.restore()}):(c&&(v.save(),v.globalAlpha=S.PREVIEW_ELEMENT_OPACITY),b.mask.render(v,C,_),c&&v.restore()),x.globalCompositeOperation="destination-in",x.setTransform(1,0,0,1,0,0),x.drawImage(w,0,0),n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage($,0,0),n.restore()}}static renderSnapGuidesLayer(n,e=[]){Rn.renderSnapGuidesLayer(n,e)}static renderSpacingIndicatorsLayer(n,e=[]){Rn.renderSpacingIndicatorsLayer(n,e)}static renderDistanceLabel(n,e,t,a){Rn.renderDistanceLabel(n,e,t,a)}static renderSelectionLayer(n,e,t,a=1){Tn.renderSelectionLayer(n,e,t,a)}static renderPositionSizeInfo(n,e,t,a,r=1){Tn.renderPositionSizeInfo(n,e,t,a,r)}static renderHandlesLayer(n,e,t,a,r,s,o,l=1,c=!0){Tn.renderHandlesLayer(n,e,t,a,r,s,o,l,c)}static renderHoverLayer(n,e,t,a=!1,r=1,s){he.renderHoverLayer(n,e,t,a,r,s)}static renderCropBoxLayer(n,e,t,a=1){ie.renderCropBoxLayer(n,e,t,a)}static render({ctx:n,elements:e,selectedId:t,selectedElement:a,hoverState:r,isEditing:s,stateMachine:o,snapGuides:l=[],spacingIndicators:c=[],artboardBackgroundColor:d,artboard:f,isPreview:h=!0,zoom:u=1,paddingOffset:g={x:0,y:0},showOverflowDimmed:m=!1,suppressOverflowDim:p=!1,distressTexture:y,imageMask:b,editModeData:$}){if(this.renderElementsLayer(n,e,t,r,o??void 0,d,f,h,m,p),y!=null&&y.enabled&&f&&tt(n,y,f,d),b!=null&&b.enabled&&f&&Ke(n,b,f,d),s&&$&&a&&ie.renderEditModeLayer(n,a,$,u),u!==1){n.save();const C=n.getTransform().a/u,_=g.x*u*C,T=g.y*u*C;n.setTransform(C,0,0,C,_,T)}const x=l.map(v=>({...v,x:v.x!==void 0?v.x*u:void 0,y:v.y!==void 0?v.y*u:void 0,x1:v.x1!==void 0?v.x1*u:void 0,y1:v.y1!==void 0?v.y1*u:void 0,x2:v.x2!==void 0?v.x2*u:void 0,y2:v.y2!==void 0?v.y2*u:void 0})),w=c.map(v=>({...v,x:v.x!==void 0?v.x*u:void 0,y:v.y!==void 0?v.y*u:void 0,x1:v.x1!==void 0?v.x1*u:void 0,y1:v.y1!==void 0?v.y1*u:void 0,x2:v.x2!==void 0?v.x2*u:void 0,y2:v.y2!==void 0?v.y2*u:void 0,labelX:v.labelX*u,labelY:v.labelY*u}));Rn.renderSnapGuidesLayer(n,x),Rn.renderSpacingIndicatorsLayer(n,w),u!==1&&n.restore()}static renderInteractionChromeLayer({ctx:n,selectedElement:e,transformHandles:t,stateMachine:a,currentRotation:r,isRotating:s,hoverState:o,selectedId:l,hideHandles:c=!1,isEditing:d,isAltKeyPressed:f=!1,artboardBackgroundColor:h,hoverClipArtboard:u,showRotationHandle:g=!0,zoom:m=1,paddingOffset:p={x:0,y:0}}){if(m!==1){n.save();const $=n.getTransform().a/m,x=p.x*m*$,w=p.y*m*$;n.setTransform($,0,0,$,x,w)}if(e&&He(e)&&e.isCropping)t&&ie.renderCropBoxLayer(n,e,t,m);else if(!c&&a&&Tn.renderSelectionLayer(n,e,a,m),t&&a&&Tn.renderPositionSizeInfo(n,e,t,a,m),!c&&t&&a&&Tn.renderHandlesLayer(n,e,t,r,s,o,a,m,g),!d){if(u){n.save();const b=u,$=b.x*m,x=b.y*m,w=b.width*m,v=b.height*m,C=(b.borderRadius??0)*m;n.beginPath(),C>0?n.roundRect($,x,w,v,C):n.rect($,x,w,v),n.clip()}he.renderHoverLayer(n,o,l,f,m,h),u&&n.restore()}m!==1&&n.restore()}};X._contentCanvas=null,X._contentCanvasSize={width:0,height:0},X._maskCanvas=null,X._maskCanvasSize={width:0,height:0},X._cachedElementsRef=null,X._cachedElementConfigs=null,X._cachedElementMap=null,X._knockoutRenderedIds=new Set,X.onRenderError=null;let pe=X;const Oe=S.createLogger("element-serializer"),we=4e3,Ln=new Set;function fa(i,n){const e=n?ua(n):"no-src";return`${i}:${e}`}function ua(i){let n=0;for(let e=0;e<i.length;e++){const t=i.charCodeAt(e);n=(n<<5)-n+t,n=n&n}return n.toString(36)}function Yn(){Ln.clear()}function Se(i){for(const n of Ln)n.startsWith(`${i}:`)&&Ln.delete(n)}function ha(i){Ln.add(i)}function pa(i){return Ln.has(i)}async function ga(i,n=we){const{naturalWidth:e,naturalHeight:t}=i;if(e<=n&&t<=n)return createImageBitmap(i);const a=n/Math.max(e,t),r=Math.round(e*a),s=Math.round(t*a);return createImageBitmap(i,{resizeWidth:r,resizeHeight:s,resizeQuality:"high"})}let Kn=null,Jn=null;function ba(i,n){Kn=i,Jn=n}function ma(){Kn=null,Jn=null}function ya(){Yn(),Kn&&Kn()}function xa(i){Se(i),Jn&&Jn(i)}function ge(i,n){const e=i;if(typeof e.fontFamily=="string"&&n.add(e.fontFamily),e.richText&&typeof e.richText=="object"){const t=e.richText;if(t.spans&&Array.isArray(t.spans))for(const a of t.spans){const r=a;if(r.style&&typeof r.style=="object"){const s=r.style;typeof s.fontFamily=="string"&&n.add(s.fontFamily)}}}if(e.children&&Array.isArray(e.children))for(const t of e.children)ge(t,n);if(i.masks&&Array.isArray(i.masks))for(const t of i.masks)t.maskElement&&ge(t.maskElement,n)}function Be(i){if(typeof document>"u")return i;const n=S.ImageCache.getInstance();return i.map(e=>{if(!(e!=null&&e.maskElement)||e.maskElement.transformType!=="image")return e;const t=e.maskElement.imageUrl;if(!t||!t.startsWith("builtin-mask:"))return e;const a=n.get(t);return a!=null&&a.src&&a.src.startsWith("data:")?{...e,maskElement:{...e.maskElement,imageUrl:a.src}}:e})}async function Le(i,n,e=we){const t=n.filter(l=>i.hasElementId(l.id)),a=[],r=[],s=new Set;for(const l of t){const c=l.toJSON();if(ge(c,s),l instanceof S.ImageElement&&!l.imageElement){Oe.warn(`[element-serializer] Skipping image ${l.id}: image not loaded (state: ${l.imageLoadState})`);continue}if(l instanceof S.ImageElement&&l.imageElement)try{const d=fa(l.id,l.imageUrl);if(!pa(d)){const $=await ga(l.imageElement,e);r.push({cacheKey:d,bitmap:$}),ha(d)}const h=l.transformData||{},u=c.masks&&c.masks.length>0,g=u?h.width:h.width*(h.cropWidth??1),m=u?h.height:h.height*(h.cropHeight??1),p={id:l.id,type:"image",x:l.x,y:l.y,width:g,height:m,rotation:l.rotation||0,bitmapCacheKey:d};if(!u&&(h.cropX!==0||h.cropY!==0||h.cropWidth!==1||h.cropHeight!==1)){const $=l.imageElement.naturalWidth,x=l.imageElement.naturalHeight;let w=1;($>e||x>e)&&(w=e/Math.max($,x)),p.cropX=h.cropX*$*w,p.cropY=h.cropY*x*w,p.cropWidth=h.cropWidth*$*w,p.cropHeight=h.cropHeight*x*w}h.flipHorizontal&&(p.flipHorizontal=h.flipHorizontal),h.flipVertical&&(p.flipVertical=h.flipVertical),h.borderRadius&&(p.borderRadius=h.borderRadius),l.opacity!==void 0&&(p.opacity=l.opacity);const b=p;l.distressEffect&&(b.distressEffect={...l.distressEffect}),c.masks&&c.masks.length>0&&(b.masks=Be(c.masks)),c.blendMode&&(b.blendMode=c.blendMode),c.knockoutParts&&(b.knockoutParts=c.knockoutParts),"getVisualBoundingBox"in l&&typeof l.getVisualBoundingBox=="function"?b._boundingBox=l.getVisualBoundingBox():"getBoundingBox"in l&&typeof l.getBoundingBox=="function"&&(b._boundingBox=l.getBoundingBox()),a.push(b)}catch(d){Oe.error(`[element-serializer] Failed to create ImageBitmap for ${c.id}:`,d)}else{const d={...c,type:c.transformType};d.masks&&Array.isArray(d.masks)&&d.masks.length>0&&(d.masks=Be(d.masks)),"getVisualBoundingBox"in l&&typeof l.getVisualBoundingBox=="function"?d._boundingBox=l.getVisualBoundingBox():"getBoundingBox"in l&&typeof l.getBoundingBox=="function"&&(d._boundingBox=l.getBoundingBox()),a.push(d)}}const o=Array.from(s);return{data:{version:"1.0.0",artboard:{id:i.id,name:i.name,width:i.width,height:i.height,backgroundColor:i.backgroundColor,exportBackground:i.exportBackground,x:i.x,y:i.y,...i.distressTexture&&{distressTexture:{...i.distressTexture}},...i.imageMask&&{imageMask:{...i.imageMask}}},elements:a,fonts:o},newBitmaps:r}}const $a=`"use strict";
6
6
  (() => {
7
7
  var __create = Object.create;
8
8
  var __defProp = Object.defineProperty;
@@ -23861,5 +23861,5 @@
23861
23861
  console.error("[Export Worker] Unhandled promise rejection:", event.reason);
23862
23862
  };
23863
23863
  })();
23864
- `,Z=S.createLogger("WorkerExport");class En{constructor(){this.worker=null,this.workerBlobUrl=null,this.pendingRequests=new Map,this.requestQueue=[],this.blobRequestQueue=[],this.isProcessingQueue=!1,this.isReady=!1,this.readyPromise=null,this.requestIdCounter=0,this.workerCrashCount=0,this.MAX_CRASHES_BEFORE_FALLBACK=3,this.lastCrashTime=0,this.CRASH_RESET_TIMEOUT=6e4,this.progressListeners=new Set,this.idleTimeout=null,this.IDLE_TIMEOUT_MS=3e4}onProgress(n){return this.progressListeners.add(n),()=>{this.progressListeners.delete(n)}}offProgress(n){this.progressListeners.delete(n)}emitProgress(n){for(const e of this.progressListeners)try{e(n)}catch(t){Z.error("Error in progress listener:",t)}}resetIdleTimer(){this.idleTimeout&&clearTimeout(this.idleTimeout),this.idleTimeout=window.setTimeout(()=>{this.terminate()},this.IDLE_TIMEOUT_MS)}registerBitmapsWithWorker(n){if(!(!this.worker||n.length===0))for(const{cacheKey:e,bitmap:t}of n){const a={type:"register-bitmap",cacheKey:e,bitmap:t};this.worker.postMessage(a,[t])}}clearWorkerBitmapCache(){if(qn(),this.worker&&this.isReady){const n={type:"clear-all-bitmaps"};this.worker.postMessage(n)}}clearWorkerBitmap(n){if(ve(n),this.worker&&this.isReady){const e={type:"clear-bitmap",elementId:n};this.worker.postMessage(e)}}static supportsWorkerExport(){try{return typeof OffscreenCanvas>"u"?(Z.warn("OffscreenCanvas not supported"),!1):typeof Worker>"u"?(Z.warn("Web Workers not supported"),!1):new OffscreenCanvas(1,1).getContext("2d")?!0:(Z.warn("OffscreenCanvas 2D context not supported"),!1)}catch(n){return Z.warn("Feature detection failed:",n),!1}}async initialize(){if(this.worker)return this.readyPromise||Promise.resolve();if(!En.supportsWorkerExport())throw new Error("Browser does not support OffscreenCanvas or Web Workers");return this.readyPromise=new Promise((n,e)=>{try{let t;try{const s=new Blob([ma],{type:"application/javascript"});t=URL.createObjectURL(s),this.workerBlobUrl=t}catch(s){Z.error("Failed to create worker blob:",s),e(new Error(`Worker creation failed: ${s instanceof Error?s.message:String(s)}`));return}this.worker=new Worker(t,{type:"classic"}),this.worker.onmessage=s=>{this.handleWorkerMessage(s.data)},this.worker.onerror=s=>{Z.error("Worker error:",s),this.handleWorkerError(s)};const a=setTimeout(()=>{e(new Error("Worker initialization timeout"))},15e3),r=s=>{s.data.type==="ready"&&(clearTimeout(a),this.isReady=!0,ha(()=>this.clearWorkerBitmapCache(),o=>this.clearWorkerBitmap(o)),n())};this.worker.addEventListener("message",r,{once:!0})}catch(t){Z.error("Failed to create worker:",t),e(t)}}),this.readyPromise}async restartWorker(){const n=Date.now();if(n-this.lastCrashTime>this.CRASH_RESET_TIMEOUT&&(this.workerCrashCount=0),this.workerCrashCount++,this.lastCrashTime=n,Z.warn(`Worker crashed (${this.workerCrashCount}/${this.MAX_CRASHES_BEFORE_FALLBACK})`),this.workerCrashCount>=this.MAX_CRASHES_BEFORE_FALLBACK)throw Z.error("Worker crashed too many times, giving up"),new Error("Worker has crashed too many times. Please refresh the page or use main thread export.");this.worker&&(this.worker.terminate(),this.worker=null,this.isReady=!1,this.readyPromise=null,this.workerBlobUrl&&(URL.revokeObjectURL(this.workerBlobUrl),this.workerBlobUrl=null));const e=Math.min(1e3*Math.pow(2,this.workerCrashCount-1),5e3);await new Promise(t=>setTimeout(t,e)),await this.initialize()}async exportArtboardToDataURL(n,e,t={}){return this.resetIdleTimer(),new Promise((a,r)=>{this.requestQueue.push({artboard:n,elements:e,config:{...t,returnFormat:"dataUrl"},resolve:a,reject:r}),this.processQueue()})}async exportArtboardToBlob(n,e,t={}){return this.resetIdleTimer(),new Promise((a,r)=>{this.blobRequestQueue.push({artboard:n,elements:e,config:{...t,returnFormat:"blob"},resolve:a,reject:r}),this.processBlobQueue()})}async processQueue(){if(!(this.isProcessingQueue||this.requestQueue.length===0)){for(this.isProcessingQueue=!0;this.requestQueue.length>0;){const n=this.requestQueue.shift();try{const e=await this.executeExportRequest(n);n.resolve(e)}catch(e){n.reject(e instanceof Error?e:new Error(String(e)))}}this.isProcessingQueue=!1}}async executeExportRequest(n){const{artboard:e,elements:t,config:a}=n;if((!this.worker||!this.isReady)&&await this.initialize(),!this.worker)throw new Error("Worker is not initialized");const r=`export-${++this.requestIdCounter}-${Date.now()}`,s=performance.now(),{data:o,newBitmaps:l}=await Oe(e,t);l.length>0&&this.registerBitmapsWithWorker(l);const c={type:"export",requestId:r,artboardData:o.artboard,elements:o.elements,fonts:o.fonts,scale:a.scale||1,format:a.format||"png",quality:a.quality||.95},d=new Promise((g,m)=>{this.pendingRequests.set(r,{requestId:r,resolve:g,reject:m,startTime:s,returnFormat:"dataUrl"}),setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),m(new Error("Export request timeout")))},3e4)});this.worker.postMessage(c);const f=await d,u=performance.now()-s;return{dataUrl:f.dataUrl,artboardId:f.artboardId,artboardName:f.artboardName,renderTime:f.renderTime,totalTime:f.totalTime,mainThreadBlockTime:u}}async processBlobQueue(){if(!(this.isProcessingQueue||this.blobRequestQueue.length===0)){for(this.isProcessingQueue=!0;this.blobRequestQueue.length>0;){const n=this.blobRequestQueue.shift();try{const e=await this.executeBlobExportRequest(n);n.resolve(e)}catch(e){n.reject(e instanceof Error?e:new Error(String(e)))}}this.isProcessingQueue=!1}}async executeBlobExportRequest(n){const{artboard:e,elements:t,config:a}=n;if((!this.worker||!this.isReady)&&await this.initialize(),!this.worker)throw new Error("Worker is not initialized");const r=`export-blob-${++this.requestIdCounter}-${Date.now()}`,s=performance.now(),{data:o,newBitmaps:l}=await Oe(e,t);l.length>0&&this.registerBitmapsWithWorker(l);const c={type:"export",requestId:r,artboardData:o.artboard,elements:o.elements,fonts:o.fonts,scale:a.scale||1,format:a.format||"png",quality:a.quality||.95,returnFormat:"blob"},d=new Promise((m,p)=>{this.pendingRequests.set(r,{requestId:r,resolve:m,reject:p,startTime:s,returnFormat:"blob"}),setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),p(new Error("Export request timeout")))},3e4)});this.worker.postMessage(c);const f=await d,u=performance.now()-s;return{blob:new Blob([f.blobData],{type:f.mimeType}),artboardId:f.artboardId,artboardName:f.artboardName,renderTime:f.renderTime,totalTime:f.totalTime,mainThreadBlockTime:u}}handleWorkerMessage(n){switch(n.type){case"exportComplete":this.handleExportComplete(n);break;case"exportBlobComplete":this.handleBlobExportComplete(n);break;case"exportError":this.handleExportError(n);break;case"exportProgress":this.emitProgress({requestId:n.requestId,progress:n.progress,message:n.message});break;case"ready":break;default:Z.warn("Unknown message type:",n)}}handleExportComplete(n){const e=this.pendingRequests.get(n.requestId);e&&e.returnFormat==="dataUrl"?(e.resolve(n),this.pendingRequests.delete(n.requestId)):e?(Z.warn("Received dataUrl response for blob request:",n.requestId),e.reject(new Error("Received dataUrl response when expecting blob")),this.pendingRequests.delete(n.requestId)):Z.warn("Received response for unknown request:",n.requestId)}handleBlobExportComplete(n){const e=this.pendingRequests.get(n.requestId);e&&e.returnFormat==="blob"?(e.resolve(n),this.pendingRequests.delete(n.requestId)):e?(Z.warn("Received blob response for dataUrl request:",n.requestId),e.reject(new Error("Received blob response when expecting dataUrl")),this.pendingRequests.delete(n.requestId)):Z.warn("Received blob response for unknown request:",n.requestId)}handleExportError(n){const e=this.pendingRequests.get(n.requestId);if(e){const t=new Error(n.error);n.stack&&(t.stack=n.stack),e.reject(t),this.pendingRequests.delete(n.requestId)}else Z.warn("Received error for unknown request:",n.requestId)}async handleWorkerError(n){Z.error("Worker error:",n);const e=Array.from(this.pendingRequests.values());for(const[t,a]of this.pendingRequests.entries())this.pendingRequests.delete(t);this.isReady=!1;try{await this.restartWorker()}catch(t){Z.error("Failed to restart worker:",t);for(const a of e)a.reject(new Error(`Worker crashed and could not be restarted: ${n.message}`));for(;this.requestQueue.length>0;)this.requestQueue.shift().reject(new Error("Worker crashed and could not be restarted"))}}terminate(){if(this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.worker){for(const[n,e]of this.pendingRequests.entries())e.reject(new Error("Worker terminated")),this.pendingRequests.delete(n);for(;this.requestQueue.length>0;)this.requestQueue.shift().reject(new Error("Worker terminated"));this.worker.terminate(),this.worker=null,this.isReady=!1,this.readyPromise=null,qn(),pa(),this.workerBlobUrl&&(URL.revokeObjectURL(this.workerBlobUrl),this.workerBlobUrl=null)}}getStatus(){return{isReady:this.isReady,pendingRequests:this.pendingRequests.size,queuedRequests:this.requestQueue.length,crashCount:this.workerCrashCount}}}let _n=null;function ya(){return _n||(_n=new En),_n}function xa(){_n&&(_n.terminate(),_n=null)}const un=S.createLogger("Export");function ge(i,n){var e;if(!(!i||typeof i!="object")){if(typeof i.fontFamily=="string"&&i.fontFamily.trim()&&n.add(i.fontFamily),i.richText&&Array.isArray(i.richText.spans))for(const t of i.richText.spans)(e=t==null?void 0:t.style)!=null&&e.fontFamily&&typeof t.style.fontFamily=="string"&&n.add(t.style.fontFamily);if(Array.isArray(i.children))for(const t of i.children)ge(t,n);if(Array.isArray(i.masks))for(const t of i.masks)t!=null&&t.maskElement&&ge(t.maskElement,n)}}async function Be(i){if(typeof document>"u"||!document.fonts)return;const n=new Set;for(const t of i)ge(t,n);if(n.size===0)return;const e=[];for(const t of n)e.push(document.fonts.load(`16px "${t}"`).catch(()=>{}));await Promise.all(e),document.fonts.ready&&await document.fonts.ready}const Bn=class Bn{static supportsWorkerExport(){return En.supportsWorkerExport()}static async getWorkerManager(){return this.supportsWorkerExport()?this.workerManager?this.workerManager:this.workerInitPromise?(await this.workerInitPromise,this.workerManager):(this.workerInitPromise=(async()=>{try{this.workerManager=new En,await this.workerManager.initialize()}catch(n){un.error("Failed to initialize worker:",n),this.workerManager=null}})(),await this.workerInitPromise,this.workerInitPromise=null,this.workerManager):null}static terminateWorker(){this.workerManager&&(this.workerManager.terminate(),this.workerManager=null)}static exportToJSON(n,e,t,a){const r={metadata:{version:this.CURRENT_VERSION,timestamp:new Date().toISOString(),appVersion:"1.0.0"},artboards:n.map(d=>{const f=new Set(d.getElementIds()),h=e.filter(u=>f.has(u.id));return{id:d.id,name:d.name,x:d.x,y:d.y,width:d.width,height:d.height,backgroundColor:d.backgroundColor,elements:h.map(u=>u.toJSON())}}),activeArtboardId:t.getActiveArtboardId()},s=JSON.stringify(r,null,2),o=new Blob([s],{type:"application/json"}),l=new Date().toISOString().replace(/[:.]/g,"-").split("T")[0],c=a||`canvas-${l}.json`;this.downloadBlob(o,c)}static async exportArtboardToImage(n,e,t,a={}){const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor,filename:d,forceMainThread:f=!1}=a,h=await this.exportArtboardToDataURL(n,e,t,{format:r,quality:s,scale:o,transparentBackground:l,backgroundColor:c,forceMainThread:f}),u=await this.dataUrlToBlob(h),g=new Date().toISOString().replace(/[:.]/g,"-").split("T")[0],m=d||`${n.name}-${g}.${r}`;this.downloadBlob(u,m)}static async exportArtboardToDataURL(n,e,t,a={}){const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor,forceMainThread:d=!1}=a;if(!d&&this.supportsWorkerExport())try{const f=await this.getWorkerManager();if(f){const h=new Set(n.getElementIds()),u=e.filter(m=>h.has(m.id));return(await f.exportArtboardToDataURL(n,u,{scale:o,format:r==="jpg"?"jpeg":r,quality:s})).dataUrl}}catch(f){un.warn("Worker export failed, falling back to main thread:",f)}return this.mainThreadExportToDataURL(n,e,t,{format:r,quality:s,scale:o,transparentBackground:l,backgroundColor:c})}static async exportArtboardToBlob(n,e,t,a={}){const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor,forceMainThread:d=!1}=a;if(!d&&this.supportsWorkerExport())try{const f=await this.getWorkerManager();if(f){const h=new Set(n.getElementIds()),u=e.filter(m=>h.has(m.id));return(await f.exportArtboardToBlob(n,u,{scale:o,format:r==="jpg"?"jpeg":r,quality:s})).blob}}catch(f){un.warn("Worker blob export failed, falling back to main thread:",f)}return this.mainThreadExportToBlob(n,e,t,{format:r,quality:s,scale:o,transparentBackground:l,backgroundColor:c})}static async mainThreadExportToBlob(n,e,t,a={}){const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor}=a;await Be(e);const d=document.createElement("canvas"),f=n.width*o,h=n.height*o;d.width=f,d.height=h;const u=d.getContext("2d");if(u.scale(o,o),!l&&n.exportBackground){if(u.save(),this.applyExportBackgroundClipPath(u,n),n.backgroundType==="texture"&&n.backgroundTexture){const x=sn.getTexturePresetColor(n.backgroundTexture);u.fillStyle=x,u.fillRect(0,0,n.width,n.height);const w=sn.getTexture(n.backgroundTexture);w&&w.complete&&u.drawImage(w,0,0,n.width,n.height)}else u.fillStyle=c||n.backgroundColor,u.fillRect(0,0,n.width,n.height);u.restore()}u.save(),u.translate(-n.x,-n.y),this.applyExportClipPath(u,n);const g=new Set(n.getElementIds()),m=e.filter(x=>g.has(x.id)),p=new Map;m.forEach(x=>p.set(x.id,x));const y=(x,w)=>{if(!w.id)return;const v=p.get(w.id);v&&v.render(x,!1)},b=m.map(x=>x.toJSON()),$=new Set;return m.forEach((x,w)=>{var v;if(x.blendMode==="knockout"||x.blendMode==="clip"){const C=b[w],_=x.blendMode==="knockout"?"destination-out":"destination-in",T=((v=C.knockoutParts)==null?void 0:v.scope)||"group",E=b.findIndex(k=>k.id===C.id);if(E!==-1&&T==="artboard")for(let k=0;k<E;k++){const A=b[k].id;A&&$.add(A)}Gn(u,C,b,y,l||!n.exportBackground?void 0:c,n,_),$.add(x.id)}}),m.forEach(x=>{$.has(x.id)||x.render(u,!1)}),u.restore(),new Promise((x,w)=>{d.toBlob(v=>{v?x(v):w(new Error("Failed to create blob from canvas"))},r==="jpg"||r==="jpeg"?"image/jpeg":r==="webp"?"image/webp":"image/png",s)})}static async mainThreadExportToDataURL(n,e,t,a={}){var w,v;const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor}=a;await Be(e);const d=document.createElement("canvas"),f=n.width*o,h=n.height*o;d.width=f,d.height=h;const u=d.getContext("2d");if(u.scale(o,o),!l&&n.exportBackground){if(u.save(),this.applyExportBackgroundClipPath(u,n),n.backgroundType==="texture"&&n.backgroundTexture){const C=sn.getTexturePresetColor(n.backgroundTexture);u.fillStyle=C,u.fillRect(0,0,n.width,n.height);const _=sn.getTexture(n.backgroundTexture);_&&_.complete?u.drawImage(_,0,0,n.width,n.height):un.warn("Texture not loaded for export:",n.backgroundTexture)}else u.fillStyle=c,u.fillRect(0,0,n.width,n.height);u.restore()}u.save(),u.translate(-n.x,-n.y),this.applyExportClipPath(u,n);const g=new Set(n.getElementIds()),m=e.filter(C=>g.has(C.id)),p=new Map;m.forEach(C=>p.set(C.id,C));const y=(C,_)=>{if(!_.id)return;const T=p.get(_.id);T?T.render(C,!1):un.warn("Element not found in map:",_.id)},b=m.map(C=>C.toJSON()),$=new Set;m.forEach((C,_)=>{var T;if(C.blendMode==="knockout"||C.blendMode==="clip"){const E=b[_],k=C.blendMode==="knockout"?"destination-out":"destination-in",A=((T=E.knockoutParts)==null?void 0:T.scope)||"group",D=b.findIndex(P=>P.id===E.id);if(D!==-1&&A==="artboard")for(let P=0;P<D;P++){const M=b[P].id;M&&$.add(M)}Gn(u,E,b,y,l||!n.exportBackground?void 0:c,n,k),$.add(C.id)}}),m.forEach((C,_)=>{var T;if(!$.has(C.id)){const E=b[_],k=((T=E==null?void 0:E.distressEffect)==null?void 0:T.enabled)&&E.distressEffect.style==="custom"&&E.distressEffect.textureUrl,A=(E==null?void 0:E.masks)&&E.masks.length>0,D=P=>{C.render(P,!1)};if(A&&k)mn(u,E,P=>{const M=C.getVisualBoundingBox();Xn(P,E.distressEffect,M,D)});else if(A)mn(u,E,D);else if(k){const P=C.getVisualBoundingBox();Xn(u,E.distressEffect,P,D)}else C.render(u,!1)}}),(w=n.distressTexture)!=null&&w.enabled&&Qe(u,n.distressTexture,{x:n.x,y:n.y,width:n.width,height:n.height}),(v=n.imageMask)!=null&&v.enabled&&Xe(u,n.imageMask,{x:n.x,y:n.y,width:n.width,height:n.height}),u.restore();const x=r==="png"?"image/png":r==="webp"?"image/webp":"image/jpeg";return d.toDataURL(x,s)}static applyExportBackgroundClipPath(n,e){const{width:t,height:a,clipShape:r}=e,s=0,o=0;if(n.beginPath(),!r||r==="rectangle")n.rect(s,o,t,a);else if(r==="circle"){const l=s+t/2,c=o+a/2,d=Math.min(t,a)/2;n.arc(l,c,d,0,Math.PI*2)}else if(typeof r=="object"&&r.type==="rounded"){const l=Math.min(r.radius,Math.min(t,a)/2);typeof n.roundRect=="function"?n.roundRect(s,o,t,a,l):(n.moveTo(s+l,o),n.lineTo(s+t-l,o),n.arcTo(s+t,o,s+t,o+l,l),n.lineTo(s+t,o+a-l),n.arcTo(s+t,o+a,s+t-l,o+a,l),n.lineTo(s+l,o+a),n.arcTo(s,o+a,s,o+a-l,l),n.lineTo(s,o+l),n.arcTo(s,o,s+l,o,l))}else if(typeof r=="object"&&r.type==="path")try{const l=new Path2D(r.d);n.clip(l);return}catch(l){un.warn("Invalid SVG path, falling back to rectangle:",l),n.rect(s,o,t,a)}n.clip()}static applyExportClipPath(n,e){const{x:t,y:a,width:r,height:s,clipShape:o}=e;if(n.beginPath(),!o||o==="rectangle")n.rect(t,a,r,s);else if(o==="circle"){const l=t+r/2,c=a+s/2,d=Math.min(r,s)/2;n.arc(l,c,d,0,Math.PI*2)}else if(typeof o=="object"&&o.type==="rounded"){const l=Math.min(o.radius,Math.min(r,s)/2);typeof n.roundRect=="function"?n.roundRect(t,a,r,s,l):(n.moveTo(t+l,a),n.lineTo(t+r-l,a),n.arcTo(t+r,a,t+r,a+l,l),n.lineTo(t+r,a+s-l),n.arcTo(t+r,a+s,t+r-l,a+s,l),n.lineTo(t+l,a+s),n.arcTo(t,a+s,t,a+s-l,l),n.lineTo(t,a+l),n.arcTo(t,a,t+l,a,l))}else if(typeof o=="object"&&o.type==="path")try{const l=new Path2D(o.d);n.translate(t,a),n.clip(l),n.translate(-t,-a);return}catch(l){un.warn("Invalid SVG path, falling back to rectangle:",l),n.rect(t,a,r,s)}n.clip()}static async exportAllArtboardsToImages(n,e,t,a={}){const r=n.map(s=>this.exportArtboardToImage(s,e,t,{...a,filename:a.filename?`${a.filename}-${s.name}.${a.format||"png"}`:void 0}));await Promise.all(r)}static downloadBlob(n,e){const t=URL.createObjectURL(n),a=document.createElement("a");a.href=t,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(t)}static async dataUrlToBlob(n){return(await fetch(n)).blob()}static getExportSummary(n,e){const t=n.length,a=e.length,o=t*200+a*500,l=Math.ceil(o/1024);return{artboardCount:t,totalElementCount:a,estimatedFileSize:l<1024?`${l} KB`:`${(l/1024).toFixed(1)} MB`}}static async benchmarkExport(n,e,t,a={}){const r=performance.now(),s=await this.exportArtboardToDataURL(n,e,t,{...a,forceMainThread:!0}),o=performance.now()-r,l={workerSupported:this.supportsWorkerExport(),mainThread:{time:o,dataUrl:s},recommendation:""};if(this.supportsWorkerExport())try{const c=performance.now(),d=await this.getWorkerManager();if(d){const f=new Set(n.getElementIds()),h=e.filter(p=>f.has(p.id)),u=await d.exportArtboardToDataURL(n,h,{scale:a.scale||1,format:(a.format==="jpg"?"jpeg":a.format)||"png",quality:a.quality||.95}),g=performance.now()-c,m=o/g;return{...l,worker:{time:g,dataUrl:u.dataUrl,mainThreadBlockTime:u.mainThreadBlockTime},speedup:m,recommendation:m>1.2?`Worker export is ${m.toFixed(2)}x faster - recommended for continuous export`:m<.8?`Main thread export is ${(1/m).toFixed(2)}x faster - worker overhead not worth it for single exports`:"Performance is similar, but worker keeps UI responsive during export"}}}catch(c){un.error("Worker benchmark failed:",c),l.recommendation="Worker export not available - using main thread export"}else l.recommendation="Worker export not supported in this browser - using main thread export";return l}static async benchmarkContinuousExport(n,e,t,a={}){const{duration:r=5e3,interval:s=500,useWorker:o=this.supportsWorkerExport()}=a,l=[];let c=0,d=!0;for(setTimeout(()=>{d=!1},r);d;){const b=performance.now();await this.exportArtboardToDataURL(n,e,t,{forceMainThread:!o});const $=performance.now()-b;l.push($),o||(c+=$),await new Promise(x=>setTimeout(x,Math.max(0,s-$)))}const f=l.length,h=l.reduce((b,$)=>b+$,0)/f,u=Math.min(...l),g=Math.max(...l),m=f/r*1e3,p=c/r*100,y=p>20?`Main thread blocked ${p.toFixed(1)}% of the time - STRONGLY recommend worker export`:p>10?`Main thread blocked ${p.toFixed(1)}% of the time - consider worker export`:`Main thread blocked ${p.toFixed(1)}% of the time - performance is acceptable`;return{totalExports:f,duration:r,averageTime:h,minTime:u,maxTime:g,totalMainThreadBlockTime:c,exportsPerSecond:m,recommendation:y}}static getWorkerStats(){var n;return{workerSupported:this.supportsWorkerExport(),workerInitialized:this.workerManager!==null,workerStatus:(n=this.workerManager)==null?void 0:n.getStatus()}}static getTShirtExportOptions(n={}){return{format:"png",scale:2,quality:1,...n,transparentBackground:!0}}static getPatternExportOptions(n={}){return{format:"png",scale:2,transparentBackground:!1,quality:1,...n}}static validateExportOptions(n,e){const t=[];return e&&!n.transparentBackground&&t.push("WARNING: Document has knockout effects but transparentBackground is false. Knockout effects work best with transparent backgrounds for t-shirt designs."),n.transparentBackground&&(n.format==="jpg"||n.format==="jpeg")&&t.push("WARNING: JPEG format does not support transparency. Use PNG format for transparent backgrounds."),n.quality&&n.quality<.9&&t.push("NOTE: Using quality < 0.9 may reduce the appearance of distress and other effects."),n.scale&&n.scale<2&&t.push("NOTE: For print-ready designs, recommend scale of 2x or higher."),t}static hasKnockoutEffects(n){const e=t=>(t.blendMode==="knockout"||t.blendMode==="clip")&&t.knockoutParts?!0:"children"in t&&Array.isArray(t.children)?t.children.some(a=>e(a)):!1;return n.some(t=>e(t))}static makeArtboardExportSafe(n){const e=Object.assign(Object.create(Object.getPrototypeOf(n)),n);return"previewBackgroundColor"in e&&delete e.previewBackgroundColor,e}};Bn.CURRENT_VERSION="2.0.0",Bn.workerManager=null,Bn.workerInitPromise=null;let be=Bn;class we{static createFromJSON(n){const{transformType:e}=n;switch(e){case"custom":return new S.CustomTransform(n);case"distort":throw new Error("DistortTransform is not yet implemented");case"circle":return new S.CircleTransform(n);case"lean":return new S.LeanTransform(n);case"arch":return new S.ArchTransform(n);case"ascend":return new S.AscendTransform(n);case"wave":return new S.WaveTransform(n);case"flag":return new S.FlagTransform(n);case"image":return new S.ImageElement(n);case"group":const t=(n.children||[]).map(s=>we.createFromJSON(s)),a=new S.GroupElement({id:n.id,x:n.x,y:n.y,rotation:n.rotation});return t.forEach(s=>a.addChild(s)),a;case"shape":return new S.ShapeElement(n);case"path":return new S.PathElement(n);default:const r=e;throw new Error(`Unknown transform type: ${r}`)}}static createManyFromJSON(n){return n.map(e=>this.createFromJSON(e))}static isTextElement(n){const e=n;return!!n&&typeof n=="object"&&typeof e.id=="string"&&typeof e.transformType=="string"&&typeof e.getBoundingBox=="function"&&typeof e.getVisualBoundingBox=="function"&&typeof e.hitTest=="function"&&typeof e.render=="function"&&typeof e.toJSON=="function"&&typeof e.clone=="function"}static isValidConfig(n){const e=n;return!!n&&typeof n=="object"&&typeof e.transformType=="string"&&(e.id===void 0||typeof e.id=="string")}static createDefaultConfig(n){const e={id:`${n}-${Date.now()}`,x:window.innerWidth/2,y:window.innerHeight/2,rotation:0};switch(n){case"custom":return{...e,transformType:"custom",text:"Custom Text",transformData:{type:"custom",controlPoints:[]}};case"distort":return{...e,transformType:"distort",text:"Distorted Text",transformData:{type:"distort"}};case"circle":return{...e,transformType:"circle",text:"Circular Text",transformData:{type:"circle",radius:100,scale:1,reverse:!1}};case"lean":return{...e,transformType:"lean",text:"Leaning Text",transformData:{type:"lean",leanAmount:0}};case"arch":return{...e,transformType:"arch",text:"Arched Text",transformData:{type:"arch",archHeight:.5}};case"ascend":return{...e,transformType:"ascend",text:"Ascending Text",transformData:{type:"ascend",ascendAngle:-15}};case"wave":return{...e,transformType:"wave",text:"Wavy Text",transformData:{type:"wave",amplitude:.5,frequency:2}};case"flag":return{...e,transformType:"flag",text:"Flag Text",transformData:{type:"flag",amplitude:.5,frequency:2}};case"image":return{...e,transformType:"image",imageUrl:"",transformData:{type:"image",width:200,height:200,cropX:0,cropY:0,cropWidth:1,cropHeight:1,flipHorizontal:!1,flipVertical:!1,borderRadius:0}};case"group":return{...e,transformType:"group",children:[],transformData:{type:"group"}};case"shape":return{...e,transformType:"shape",transformData:{type:"shape",shapeType:"rectangle",width:200,height:200,borderRadius:0,fillColor:"#3b82f6",fillOpacity:1}};case"path":return{...e,transformType:"path",transformData:{type:"path",points:[],closed:!1,width:200,height:200,fillEnabled:!1,fillColor:"#3b82f6",fillOpacity:1,strokeEnabled:!0,strokeColor:"#000000",strokeWidth:2}};case"artboard":throw new Error("Artboards cannot be created via ElementFactory");default:const t=n;throw new Error(`Unknown transform type: ${t}`)}}static clone(n){const e=n.toJSON();return this.createFromJSON(e)}}exports.AlignmentSnapSystem=pt;exports.ArtboardRenderer=me;exports.CanvasRenderer=he;exports.DEFAULT_MAX_BITMAP_DIMENSION=$e;exports.DISTRESS_TEXTURE_PRESETS=qe;exports.ElementFactory=we;exports.ExportManager=be;exports.InteractionStateMachine=ht;exports.MASK_IMAGE_PRESETS=Ge;exports.ResizePipeline=Ne;exports.SpacingSystem=gt;exports.TextureManager=sn;exports.TransformHandles=dt;exports.WorkerExportManager=En;exports.clearImageBitmapCache=ga;exports.clearMaskCache=Xt;exports.clearRegisteredBitmapKeys=qn;exports.ensureBuiltinTexturesReady=Ye;exports.ensureMaskPresetsReady=Ve;exports.getDashPattern=ot;exports.getHandleRadius=st;exports.getLineWidth=ie;exports.getSharedWorkerExportManager=ya;exports.globalResizePipeline=ut;exports.invalidateMaskCache=jt;exports.isGroupElement=Hn;exports.isImageElement=Ue;exports.isPathElement=$t;exports.isShapeElement=xt;exports.isTextElement=yt;exports.preloadTexture=sa;exports.removeFromImageBitmapCache=ba;exports.renderRotationHandle=ct;exports.renderWithKnockout=At;exports.renderWithMasks=mn;exports.terminateSharedWorkerExportManager=xa;exports.unregisterElementBitmaps=ve;
23865
- //# sourceMappingURL=ElementFactory-DEjwp-Wg.cjs.map
23864
+ `,J=S.createLogger("WorkerExport");class En{constructor(){this.worker=null,this.workerBlobUrl=null,this.pendingRequests=new Map,this.requestQueue=[],this.blobRequestQueue=[],this.isProcessingQueue=!1,this.isReady=!1,this.readyPromise=null,this.requestIdCounter=0,this.workerCrashCount=0,this.MAX_CRASHES_BEFORE_FALLBACK=3,this.lastCrashTime=0,this.CRASH_RESET_TIMEOUT=6e4,this.progressListeners=new Set,this.idleTimeout=null,this.IDLE_TIMEOUT_MS=3e4}onProgress(n){return this.progressListeners.add(n),()=>{this.progressListeners.delete(n)}}offProgress(n){this.progressListeners.delete(n)}emitProgress(n){for(const e of this.progressListeners)try{e(n)}catch(t){J.error("Error in progress listener:",t)}}resetIdleTimer(){this.idleTimeout&&clearTimeout(this.idleTimeout),this.idleTimeout=window.setTimeout(()=>{this.terminate()},this.IDLE_TIMEOUT_MS)}registerBitmapsWithWorker(n){if(!(!this.worker||n.length===0))for(const{cacheKey:e,bitmap:t}of n){const a={type:"register-bitmap",cacheKey:e,bitmap:t};this.worker.postMessage(a,[t])}}clearWorkerBitmapCache(){if(Yn(),this.worker&&this.isReady){const n={type:"clear-all-bitmaps"};this.worker.postMessage(n)}}clearWorkerBitmap(n){if(Se(n),this.worker&&this.isReady){const e={type:"clear-bitmap",elementId:n};this.worker.postMessage(e)}}static supportsWorkerExport(){try{return typeof OffscreenCanvas>"u"?(J.warn("OffscreenCanvas not supported"),!1):typeof Worker>"u"?(J.warn("Web Workers not supported"),!1):new OffscreenCanvas(1,1).getContext("2d")?!0:(J.warn("OffscreenCanvas 2D context not supported"),!1)}catch(n){return J.warn("Feature detection failed:",n),!1}}async initialize(){if(this.worker)return this.readyPromise||Promise.resolve();if(!En.supportsWorkerExport())throw new Error("Browser does not support OffscreenCanvas or Web Workers");return this.readyPromise=new Promise((n,e)=>{try{let t;try{const s=new Blob([$a],{type:"application/javascript"});t=URL.createObjectURL(s),this.workerBlobUrl=t}catch(s){J.error("Failed to create worker blob:",s),e(new Error(`Worker creation failed: ${s instanceof Error?s.message:String(s)}`));return}this.worker=new Worker(t,{type:"classic"}),this.worker.onmessage=s=>{this.handleWorkerMessage(s.data)},this.worker.onerror=s=>{J.error("Worker error:",s),this.handleWorkerError(s)};const a=setTimeout(()=>{e(new Error("Worker initialization timeout"))},15e3),r=s=>{s.data.type==="ready"&&(clearTimeout(a),this.isReady=!0,ba(()=>this.clearWorkerBitmapCache(),o=>this.clearWorkerBitmap(o)),n())};this.worker.addEventListener("message",r,{once:!0})}catch(t){J.error("Failed to create worker:",t),e(t)}}),this.readyPromise}async restartWorker(){const n=Date.now();if(n-this.lastCrashTime>this.CRASH_RESET_TIMEOUT&&(this.workerCrashCount=0),this.workerCrashCount++,this.lastCrashTime=n,J.warn(`Worker crashed (${this.workerCrashCount}/${this.MAX_CRASHES_BEFORE_FALLBACK})`),this.workerCrashCount>=this.MAX_CRASHES_BEFORE_FALLBACK)throw J.error("Worker crashed too many times, giving up"),new Error("Worker has crashed too many times. Please refresh the page or use main thread export.");this.worker&&(this.worker.terminate(),this.worker=null,this.isReady=!1,this.readyPromise=null,this.workerBlobUrl&&(URL.revokeObjectURL(this.workerBlobUrl),this.workerBlobUrl=null));const e=Math.min(1e3*Math.pow(2,this.workerCrashCount-1),5e3);await new Promise(t=>setTimeout(t,e)),await this.initialize()}async exportArtboardToDataURL(n,e,t={}){return this.resetIdleTimer(),new Promise((a,r)=>{this.requestQueue.push({artboard:n,elements:e,config:{...t,returnFormat:"dataUrl"},resolve:a,reject:r}),this.processQueue()})}async exportArtboardToBlob(n,e,t={}){return this.resetIdleTimer(),new Promise((a,r)=>{this.blobRequestQueue.push({artboard:n,elements:e,config:{...t,returnFormat:"blob"},resolve:a,reject:r}),this.processBlobQueue()})}async processQueue(){if(!(this.isProcessingQueue||this.requestQueue.length===0)){for(this.isProcessingQueue=!0;this.requestQueue.length>0;){const n=this.requestQueue.shift();try{const e=await this.executeExportRequest(n);n.resolve(e)}catch(e){n.reject(e instanceof Error?e:new Error(String(e)))}}this.isProcessingQueue=!1}}async executeExportRequest(n){const{artboard:e,elements:t,config:a}=n;if((!this.worker||!this.isReady)&&await this.initialize(),!this.worker)throw new Error("Worker is not initialized");const r=`export-${++this.requestIdCounter}-${Date.now()}`,s=performance.now(),{data:o,newBitmaps:l}=await Le(e,t);l.length>0&&this.registerBitmapsWithWorker(l);const c={type:"export",requestId:r,artboardData:o.artboard,elements:o.elements,fonts:o.fonts,scale:a.scale||1,format:a.format||"png",quality:a.quality||.95},d=new Promise((g,m)=>{this.pendingRequests.set(r,{requestId:r,resolve:g,reject:m,startTime:s,returnFormat:"dataUrl"}),setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),m(new Error("Export request timeout")))},3e4)});this.worker.postMessage(c);const f=await d,u=performance.now()-s;return{dataUrl:f.dataUrl,artboardId:f.artboardId,artboardName:f.artboardName,renderTime:f.renderTime,totalTime:f.totalTime,mainThreadBlockTime:u}}async processBlobQueue(){if(!(this.isProcessingQueue||this.blobRequestQueue.length===0)){for(this.isProcessingQueue=!0;this.blobRequestQueue.length>0;){const n=this.blobRequestQueue.shift();try{const e=await this.executeBlobExportRequest(n);n.resolve(e)}catch(e){n.reject(e instanceof Error?e:new Error(String(e)))}}this.isProcessingQueue=!1}}async executeBlobExportRequest(n){const{artboard:e,elements:t,config:a}=n;if((!this.worker||!this.isReady)&&await this.initialize(),!this.worker)throw new Error("Worker is not initialized");const r=`export-blob-${++this.requestIdCounter}-${Date.now()}`,s=performance.now(),{data:o,newBitmaps:l}=await Le(e,t);l.length>0&&this.registerBitmapsWithWorker(l);const c={type:"export",requestId:r,artboardData:o.artboard,elements:o.elements,fonts:o.fonts,scale:a.scale||1,format:a.format||"png",quality:a.quality||.95,returnFormat:"blob"},d=new Promise((m,p)=>{this.pendingRequests.set(r,{requestId:r,resolve:m,reject:p,startTime:s,returnFormat:"blob"}),setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),p(new Error("Export request timeout")))},3e4)});this.worker.postMessage(c);const f=await d,u=performance.now()-s;return{blob:new Blob([f.blobData],{type:f.mimeType}),artboardId:f.artboardId,artboardName:f.artboardName,renderTime:f.renderTime,totalTime:f.totalTime,mainThreadBlockTime:u}}handleWorkerMessage(n){switch(n.type){case"exportComplete":this.handleExportComplete(n);break;case"exportBlobComplete":this.handleBlobExportComplete(n);break;case"exportError":this.handleExportError(n);break;case"exportProgress":this.emitProgress({requestId:n.requestId,progress:n.progress,message:n.message});break;case"ready":break;default:J.warn("Unknown message type:",n)}}handleExportComplete(n){const e=this.pendingRequests.get(n.requestId);e&&e.returnFormat==="dataUrl"?(e.resolve(n),this.pendingRequests.delete(n.requestId)):e?(J.warn("Received dataUrl response for blob request:",n.requestId),e.reject(new Error("Received dataUrl response when expecting blob")),this.pendingRequests.delete(n.requestId)):J.warn("Received response for unknown request:",n.requestId)}handleBlobExportComplete(n){const e=this.pendingRequests.get(n.requestId);e&&e.returnFormat==="blob"?(e.resolve(n),this.pendingRequests.delete(n.requestId)):e?(J.warn("Received blob response for dataUrl request:",n.requestId),e.reject(new Error("Received blob response when expecting dataUrl")),this.pendingRequests.delete(n.requestId)):J.warn("Received blob response for unknown request:",n.requestId)}handleExportError(n){const e=this.pendingRequests.get(n.requestId);if(e){const t=new Error(n.error);n.stack&&(t.stack=n.stack),e.reject(t),this.pendingRequests.delete(n.requestId)}else J.warn("Received error for unknown request:",n.requestId)}async handleWorkerError(n){J.error("Worker error:",n);const e=Array.from(this.pendingRequests.values());for(const[t,a]of this.pendingRequests.entries())this.pendingRequests.delete(t);this.isReady=!1;try{await this.restartWorker()}catch(t){J.error("Failed to restart worker:",t);for(const a of e)a.reject(new Error(`Worker crashed and could not be restarted: ${n.message}`));for(;this.requestQueue.length>0;)this.requestQueue.shift().reject(new Error("Worker crashed and could not be restarted"))}}terminate(){if(this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.worker){for(const[n,e]of this.pendingRequests.entries())e.reject(new Error("Worker terminated")),this.pendingRequests.delete(n);for(;this.requestQueue.length>0;)this.requestQueue.shift().reject(new Error("Worker terminated"));this.worker.terminate(),this.worker=null,this.isReady=!1,this.readyPromise=null,Yn(),ma(),this.workerBlobUrl&&(URL.revokeObjectURL(this.workerBlobUrl),this.workerBlobUrl=null)}}getStatus(){return{isReady:this.isReady,pendingRequests:this.pendingRequests.size,queuedRequests:this.requestQueue.length,crashCount:this.workerCrashCount}}}let _n=null;function va(){return _n||(_n=new En),_n}function wa(){_n&&(_n.terminate(),_n=null)}const un=S.createLogger("Export");function be(i,n){var e;if(!(!i||typeof i!="object")){if(typeof i.fontFamily=="string"&&i.fontFamily.trim()&&n.add(i.fontFamily),i.richText&&Array.isArray(i.richText.spans))for(const t of i.richText.spans)(e=t==null?void 0:t.style)!=null&&e.fontFamily&&typeof t.style.fontFamily=="string"&&n.add(t.style.fontFamily);if(Array.isArray(i.children))for(const t of i.children)be(t,n);if(Array.isArray(i.masks))for(const t of i.masks)t!=null&&t.maskElement&&be(t.maskElement,n)}}async function Ne(i){if(typeof document>"u"||!document.fonts)return;const n=new Set;for(const t of i)be(t,n);if(n.size===0)return;const e=[];for(const t of n)e.push(document.fonts.load(`16px "${t}"`).catch(()=>{}));await Promise.all(e),document.fonts.ready&&await document.fonts.ready}const Bn=class Bn{static supportsWorkerExport(){return En.supportsWorkerExport()}static async getWorkerManager(){return this.supportsWorkerExport()?this.workerManager?this.workerManager:this.workerInitPromise?(await this.workerInitPromise,this.workerManager):(this.workerInitPromise=(async()=>{try{this.workerManager=new En,await this.workerManager.initialize()}catch(n){un.error("Failed to initialize worker:",n),this.workerManager=null}})(),await this.workerInitPromise,this.workerInitPromise=null,this.workerManager):null}static terminateWorker(){this.workerManager&&(this.workerManager.terminate(),this.workerManager=null)}static exportToJSON(n,e,t,a){const r={metadata:{version:this.CURRENT_VERSION,timestamp:new Date().toISOString(),appVersion:"1.0.0"},artboards:n.map(d=>{const f=new Set(d.getElementIds()),h=e.filter(u=>f.has(u.id));return{id:d.id,name:d.name,x:d.x,y:d.y,width:d.width,height:d.height,backgroundColor:d.backgroundColor,elements:h.map(u=>u.toJSON())}}),activeArtboardId:t.getActiveArtboardId()},s=JSON.stringify(r,null,2),o=new Blob([s],{type:"application/json"}),l=new Date().toISOString().replace(/[:.]/g,"-").split("T")[0],c=a||`canvas-${l}.json`;this.downloadBlob(o,c)}static async exportArtboardToImage(n,e,t,a={}){const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor,filename:d,forceMainThread:f=!1}=a,h=await this.exportArtboardToDataURL(n,e,t,{format:r,quality:s,scale:o,transparentBackground:l,backgroundColor:c,forceMainThread:f}),u=await this.dataUrlToBlob(h),g=new Date().toISOString().replace(/[:.]/g,"-").split("T")[0],m=d||`${n.name}-${g}.${r}`;this.downloadBlob(u,m)}static async exportArtboardToDataURL(n,e,t,a={}){const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor,forceMainThread:d=!1}=a;if(!d&&this.supportsWorkerExport())try{const f=await this.getWorkerManager();if(f){const h=new Set(n.getElementIds()),u=e.filter(m=>h.has(m.id));return(await f.exportArtboardToDataURL(n,u,{scale:o,format:r==="jpg"?"jpeg":r,quality:s})).dataUrl}}catch(f){un.warn("Worker export failed, falling back to main thread:",f)}return this.mainThreadExportToDataURL(n,e,t,{format:r,quality:s,scale:o,transparentBackground:l,backgroundColor:c})}static async exportArtboardToBlob(n,e,t,a={}){const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor,forceMainThread:d=!1}=a;if(!d&&this.supportsWorkerExport())try{const f=await this.getWorkerManager();if(f){const h=new Set(n.getElementIds()),u=e.filter(m=>h.has(m.id));return(await f.exportArtboardToBlob(n,u,{scale:o,format:r==="jpg"?"jpeg":r,quality:s})).blob}}catch(f){un.warn("Worker blob export failed, falling back to main thread:",f)}return this.mainThreadExportToBlob(n,e,t,{format:r,quality:s,scale:o,transparentBackground:l,backgroundColor:c})}static async mainThreadExportToBlob(n,e,t,a={}){const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor}=a;await Ne(e);const d=document.createElement("canvas"),f=n.width*o,h=n.height*o;d.width=f,d.height=h;const u=d.getContext("2d");if(u.scale(o,o),!l&&n.exportBackground){if(u.save(),this.applyExportBackgroundClipPath(u,n),n.backgroundType==="texture"&&n.backgroundTexture){const x=sn.getTexturePresetColor(n.backgroundTexture);u.fillStyle=x,u.fillRect(0,0,n.width,n.height);const w=sn.getTexture(n.backgroundTexture);w&&w.complete&&u.drawImage(w,0,0,n.width,n.height)}else u.fillStyle=c||n.backgroundColor,u.fillRect(0,0,n.width,n.height);u.restore()}u.save(),u.translate(-n.x,-n.y),this.applyExportClipPath(u,n);const g=new Set(n.getElementIds()),m=e.filter(x=>g.has(x.id)),p=new Map;m.forEach(x=>p.set(x.id,x));const y=(x,w)=>{if(!w.id)return;const v=p.get(w.id);v&&v.render(x,!1)},b=m.map(x=>x.toJSON()),$=new Set;return m.forEach((x,w)=>{var v;if(x.blendMode==="knockout"||x.blendMode==="clip"){const C=b[w],_=x.blendMode==="knockout"?"destination-out":"destination-in",T=((v=C.knockoutParts)==null?void 0:v.scope)||"group",E=b.findIndex(k=>k.id===C.id);if(E!==-1&&T==="artboard")for(let k=0;k<E;k++){const A=b[k].id;A&&$.add(A)}Vn(u,C,b,y,l||!n.exportBackground?void 0:c,n,_),$.add(x.id)}}),m.forEach(x=>{$.has(x.id)||x.render(u,!1)}),u.restore(),new Promise((x,w)=>{d.toBlob(v=>{v?x(v):w(new Error("Failed to create blob from canvas"))},r==="jpg"||r==="jpeg"?"image/jpeg":r==="webp"?"image/webp":"image/png",s)})}static async mainThreadExportToDataURL(n,e,t,a={}){var w,v;const{format:r="png",quality:s=.95,scale:o=1,transparentBackground:l=!1,backgroundColor:c=n.backgroundColor}=a;await Ne(e);const d=document.createElement("canvas"),f=n.width*o,h=n.height*o;d.width=f,d.height=h;const u=d.getContext("2d");if(u.scale(o,o),!l&&n.exportBackground){if(u.save(),this.applyExportBackgroundClipPath(u,n),n.backgroundType==="texture"&&n.backgroundTexture){const C=sn.getTexturePresetColor(n.backgroundTexture);u.fillStyle=C,u.fillRect(0,0,n.width,n.height);const _=sn.getTexture(n.backgroundTexture);_&&_.complete?u.drawImage(_,0,0,n.width,n.height):un.warn("Texture not loaded for export:",n.backgroundTexture)}else u.fillStyle=c,u.fillRect(0,0,n.width,n.height);u.restore()}u.save(),u.translate(-n.x,-n.y),this.applyExportClipPath(u,n);const g=new Set(n.getElementIds()),m=e.filter(C=>g.has(C.id)),p=new Map;m.forEach(C=>p.set(C.id,C));const y=(C,_)=>{if(!_.id)return;const T=p.get(_.id);T?T.render(C,!1):un.warn("Element not found in map:",_.id)},b=m.map(C=>C.toJSON()),$=new Set;m.forEach((C,_)=>{var T;if(C.blendMode==="knockout"||C.blendMode==="clip"){const E=b[_],k=C.blendMode==="knockout"?"destination-out":"destination-in",A=((T=E.knockoutParts)==null?void 0:T.scope)||"group",D=b.findIndex(P=>P.id===E.id);if(D!==-1&&A==="artboard")for(let P=0;P<D;P++){const M=b[P].id;M&&$.add(M)}Vn(u,E,b,y,l||!n.exportBackground?void 0:c,n,k),$.add(C.id)}}),m.forEach((C,_)=>{var T;if(!$.has(C.id)){const E=b[_],k=((T=E==null?void 0:E.distressEffect)==null?void 0:T.enabled)&&E.distressEffect.style==="custom"&&E.distressEffect.textureUrl,A=(E==null?void 0:E.masks)&&E.masks.length>0,D=P=>{C.render(P,!1)};if(A&&k)mn(u,E,P=>{const M=C.getVisualBoundingBox();qn(P,E.distressEffect,M,D)});else if(A)mn(u,E,D);else if(k){const P=C.getVisualBoundingBox();qn(u,E.distressEffect,P,D)}else C.render(u,!1)}}),(w=n.distressTexture)!=null&&w.enabled&&tt(u,n.distressTexture,{x:n.x,y:n.y,width:n.width,height:n.height}),(v=n.imageMask)!=null&&v.enabled&&Ke(u,n.imageMask,{x:n.x,y:n.y,width:n.width,height:n.height}),u.restore();const x=r==="png"?"image/png":r==="webp"?"image/webp":"image/jpeg";return d.toDataURL(x,s)}static applyExportBackgroundClipPath(n,e){const{width:t,height:a,clipShape:r}=e,s=0,o=0;if(n.beginPath(),!r||r==="rectangle")n.rect(s,o,t,a);else if(r==="circle"){const l=s+t/2,c=o+a/2,d=Math.min(t,a)/2;n.arc(l,c,d,0,Math.PI*2)}else if(typeof r=="object"&&r.type==="rounded"){const l=Math.min(r.radius,Math.min(t,a)/2);typeof n.roundRect=="function"?n.roundRect(s,o,t,a,l):(n.moveTo(s+l,o),n.lineTo(s+t-l,o),n.arcTo(s+t,o,s+t,o+l,l),n.lineTo(s+t,o+a-l),n.arcTo(s+t,o+a,s+t-l,o+a,l),n.lineTo(s+l,o+a),n.arcTo(s,o+a,s,o+a-l,l),n.lineTo(s,o+l),n.arcTo(s,o,s+l,o,l))}else if(typeof r=="object"&&r.type==="path")try{const l=new Path2D(r.d);n.clip(l);return}catch(l){un.warn("Invalid SVG path, falling back to rectangle:",l),n.rect(s,o,t,a)}n.clip()}static applyExportClipPath(n,e){const{x:t,y:a,width:r,height:s,clipShape:o}=e;if(n.beginPath(),!o||o==="rectangle")n.rect(t,a,r,s);else if(o==="circle"){const l=t+r/2,c=a+s/2,d=Math.min(r,s)/2;n.arc(l,c,d,0,Math.PI*2)}else if(typeof o=="object"&&o.type==="rounded"){const l=Math.min(o.radius,Math.min(r,s)/2);typeof n.roundRect=="function"?n.roundRect(t,a,r,s,l):(n.moveTo(t+l,a),n.lineTo(t+r-l,a),n.arcTo(t+r,a,t+r,a+l,l),n.lineTo(t+r,a+s-l),n.arcTo(t+r,a+s,t+r-l,a+s,l),n.lineTo(t+l,a+s),n.arcTo(t,a+s,t,a+s-l,l),n.lineTo(t,a+l),n.arcTo(t,a,t+l,a,l))}else if(typeof o=="object"&&o.type==="path")try{const l=new Path2D(o.d);n.translate(t,a),n.clip(l),n.translate(-t,-a);return}catch(l){un.warn("Invalid SVG path, falling back to rectangle:",l),n.rect(t,a,r,s)}n.clip()}static async exportAllArtboardsToImages(n,e,t,a={}){const r=n.map(s=>this.exportArtboardToImage(s,e,t,{...a,filename:a.filename?`${a.filename}-${s.name}.${a.format||"png"}`:void 0}));await Promise.all(r)}static downloadBlob(n,e){const t=URL.createObjectURL(n),a=document.createElement("a");a.href=t,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(t)}static async dataUrlToBlob(n){return(await fetch(n)).blob()}static getExportSummary(n,e){const t=n.length,a=e.length,o=t*200+a*500,l=Math.ceil(o/1024);return{artboardCount:t,totalElementCount:a,estimatedFileSize:l<1024?`${l} KB`:`${(l/1024).toFixed(1)} MB`}}static async benchmarkExport(n,e,t,a={}){const r=performance.now(),s=await this.exportArtboardToDataURL(n,e,t,{...a,forceMainThread:!0}),o=performance.now()-r,l={workerSupported:this.supportsWorkerExport(),mainThread:{time:o,dataUrl:s},recommendation:""};if(this.supportsWorkerExport())try{const c=performance.now(),d=await this.getWorkerManager();if(d){const f=new Set(n.getElementIds()),h=e.filter(p=>f.has(p.id)),u=await d.exportArtboardToDataURL(n,h,{scale:a.scale||1,format:(a.format==="jpg"?"jpeg":a.format)||"png",quality:a.quality||.95}),g=performance.now()-c,m=o/g;return{...l,worker:{time:g,dataUrl:u.dataUrl,mainThreadBlockTime:u.mainThreadBlockTime},speedup:m,recommendation:m>1.2?`Worker export is ${m.toFixed(2)}x faster - recommended for continuous export`:m<.8?`Main thread export is ${(1/m).toFixed(2)}x faster - worker overhead not worth it for single exports`:"Performance is similar, but worker keeps UI responsive during export"}}}catch(c){un.error("Worker benchmark failed:",c),l.recommendation="Worker export not available - using main thread export"}else l.recommendation="Worker export not supported in this browser - using main thread export";return l}static async benchmarkContinuousExport(n,e,t,a={}){const{duration:r=5e3,interval:s=500,useWorker:o=this.supportsWorkerExport()}=a,l=[];let c=0,d=!0;for(setTimeout(()=>{d=!1},r);d;){const b=performance.now();await this.exportArtboardToDataURL(n,e,t,{forceMainThread:!o});const $=performance.now()-b;l.push($),o||(c+=$),await new Promise(x=>setTimeout(x,Math.max(0,s-$)))}const f=l.length,h=l.reduce((b,$)=>b+$,0)/f,u=Math.min(...l),g=Math.max(...l),m=f/r*1e3,p=c/r*100,y=p>20?`Main thread blocked ${p.toFixed(1)}% of the time - STRONGLY recommend worker export`:p>10?`Main thread blocked ${p.toFixed(1)}% of the time - consider worker export`:`Main thread blocked ${p.toFixed(1)}% of the time - performance is acceptable`;return{totalExports:f,duration:r,averageTime:h,minTime:u,maxTime:g,totalMainThreadBlockTime:c,exportsPerSecond:m,recommendation:y}}static getWorkerStats(){var n;return{workerSupported:this.supportsWorkerExport(),workerInitialized:this.workerManager!==null,workerStatus:(n=this.workerManager)==null?void 0:n.getStatus()}}static getTShirtExportOptions(n={}){return{format:"png",scale:2,quality:1,...n,transparentBackground:!0}}static getPatternExportOptions(n={}){return{format:"png",scale:2,transparentBackground:!1,quality:1,...n}}static validateExportOptions(n,e){const t=[];return e&&!n.transparentBackground&&t.push("WARNING: Document has knockout effects but transparentBackground is false. Knockout effects work best with transparent backgrounds for t-shirt designs."),n.transparentBackground&&(n.format==="jpg"||n.format==="jpeg")&&t.push("WARNING: JPEG format does not support transparency. Use PNG format for transparent backgrounds."),n.quality&&n.quality<.9&&t.push("NOTE: Using quality < 0.9 may reduce the appearance of distress and other effects."),n.scale&&n.scale<2&&t.push("NOTE: For print-ready designs, recommend scale of 2x or higher."),t}static hasKnockoutEffects(n){const e=t=>(t.blendMode==="knockout"||t.blendMode==="clip")&&t.knockoutParts?!0:"children"in t&&Array.isArray(t.children)?t.children.some(a=>e(a)):!1;return n.some(t=>e(t))}static makeArtboardExportSafe(n){const e=Object.assign(Object.create(Object.getPrototypeOf(n)),n);return"previewBackgroundColor"in e&&delete e.previewBackgroundColor,e}};Bn.CURRENT_VERSION="2.0.0",Bn.workerManager=null,Bn.workerInitPromise=null;let me=Bn;class Nn{static createFromJSON(n){const{transformType:e}=n;switch(e){case"custom":return new S.CustomTransform(n);case"distort":throw new Error("DistortTransform is not yet implemented");case"circle":return new S.CircleTransform(n);case"lean":return new S.LeanTransform(n);case"arch":return new S.ArchTransform(n);case"ascend":return new S.AscendTransform(n);case"wave":return new S.WaveTransform(n);case"flag":return new S.FlagTransform(n);case"image":return new S.ImageElement(n);case"group":const t=(n.children||[]).map(s=>Nn.createFromJSON(s)),a=new S.GroupElement({id:n.id,x:n.x,y:n.y,rotation:n.rotation});return t.forEach(s=>a.addChild(s)),a;case"shape":return new S.ShapeElement(n);case"path":return new S.PathElement(n);default:const r=e;throw new Error(`Unknown transform type: ${r}`)}}static createManyFromJSON(n){return n.map(e=>this.createFromJSON(e))}static isTextElement(n){const e=n;return!!n&&typeof n=="object"&&typeof e.id=="string"&&typeof e.transformType=="string"&&typeof e.getBoundingBox=="function"&&typeof e.getVisualBoundingBox=="function"&&typeof e.hitTest=="function"&&typeof e.render=="function"&&typeof e.toJSON=="function"&&typeof e.clone=="function"}static isValidConfig(n){const e=n;return!!n&&typeof n=="object"&&typeof e.transformType=="string"&&(e.id===void 0||typeof e.id=="string")}static createDefaultConfig(n){const e={id:`${n}-${Date.now()}`,x:window.innerWidth/2,y:window.innerHeight/2,rotation:0};switch(n){case"custom":return{...e,transformType:"custom",text:"Custom Text",transformData:{type:"custom",controlPoints:[]}};case"distort":return{...e,transformType:"distort",text:"Distorted Text",transformData:{type:"distort"}};case"circle":return{...e,transformType:"circle",text:"Circular Text",transformData:{type:"circle",radius:100,scale:1,reverse:!1}};case"lean":return{...e,transformType:"lean",text:"Leaning Text",transformData:{type:"lean",leanAmount:0}};case"arch":return{...e,transformType:"arch",text:"Arched Text",transformData:{type:"arch",archHeight:.5}};case"ascend":return{...e,transformType:"ascend",text:"Ascending Text",transformData:{type:"ascend",ascendAngle:-15}};case"wave":return{...e,transformType:"wave",text:"Wavy Text",transformData:{type:"wave",amplitude:.5,frequency:2}};case"flag":return{...e,transformType:"flag",text:"Flag Text",transformData:{type:"flag",amplitude:.5,frequency:2}};case"image":return{...e,transformType:"image",imageUrl:"",transformData:{type:"image",width:200,height:200,cropX:0,cropY:0,cropWidth:1,cropHeight:1,flipHorizontal:!1,flipVertical:!1,borderRadius:0}};case"group":return{...e,transformType:"group",children:[],transformData:{type:"group"}};case"shape":return{...e,transformType:"shape",transformData:{type:"shape",shapeType:"rectangle",width:200,height:200,borderRadius:0,fillColor:"#3b82f6",fillOpacity:1}};case"path":return{...e,transformType:"path",transformData:{type:"path",points:[],closed:!1,width:200,height:200,fillEnabled:!1,fillColor:"#3b82f6",fillOpacity:1,strokeEnabled:!0,strokeColor:"#000000",strokeWidth:2}};case"artboard":throw new Error("Artboards cannot be created via ElementFactory");default:const t=n;throw new Error(`Unknown transform type: ${t}`)}}static clone(n){const e=n.toJSON();return this.createFromJSON(e)}}const Ue=S.createLogger("ImportManager"),Ce=class Ce{static async importFromJSON(n){try{const e=await this.readFileAsText(n),t=JSON.parse(e);if(this.validateDocument(t),!this.SUPPORTED_VERSIONS.includes(t.metadata.version))throw new Error(`Unsupported version: ${t.metadata.version}. Supported versions: ${this.SUPPORTED_VERSIONS.join(", ")}`);if(t.metadata.version==="1.0.0")return this.migrateV1Document(t);const a=[],r=[];return t.artboards.forEach(s=>{const o=S.ArtboardElement.fromJSON({id:s.id,name:s.name,x:s.x,y:s.y,width:s.width,height:s.height,backgroundColor:s.backgroundColor,elementIds:s.elements.map(c=>c.id||"")}),l=s.elements.map(c=>{try{return Nn.createFromJSON(c)}catch(d){return Ue.error("Failed to create element:",c,d),null}}).filter(c=>c!==null);a.push(o),r.push(...l)}),await this.preloadAllImages(r),{success:!0,artboards:a,elements:r,activeArtboardId:t.activeArtboardId}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}static async migrateV1Document(n){var e,t,a;try{const r=n.elements||[],s=new S.ArtboardElement({id:"artboard-migrated",name:"Artboard 1",x:0,y:0,width:((e=n.canvas)==null?void 0:e.width)||1920,height:((t=n.canvas)==null?void 0:t.height)||1080,backgroundColor:((a=n.canvas)==null?void 0:a.backgroundColor)||"#ffffff"}),o=r.map(l=>{try{return Nn.createFromJSON(l)}catch(c){return Ue.error("Failed to create element:",l,c),null}}).filter(l=>l!==null);return o.forEach(l=>{s.addElementId(l.id)}),await this.preloadAllImages(o),{success:!0,artboards:[s],elements:o,activeArtboardId:s.id}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Migration failed"}}}static async importImage(n){try{if(!n.type.startsWith("image/"))throw new Error("File is not an image");const e=10*1024*1024;if(n.size>e)throw new Error("Image file is too large (max 10MB)");const t=await this.readFileAsDataURL(n),{width:a,height:r}=await this.getImageDimensions(t);return{success:!0,dataUrl:t,filename:n.name,width:a,height:r}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}static validateDocument(n){if(!n||typeof n!="object")throw new Error("Invalid document");const e=n;if(!e.metadata)throw new Error("Missing metadata");if(!e.metadata.version)throw new Error("Missing version in metadata");if(!e.artboards&&!e.elements)throw new Error("Missing artboards or elements array");if(e.artboards&&!Array.isArray(e.artboards))throw new Error("Invalid artboards array")}static readFileAsText(n){return new Promise((e,t)=>{const a=new FileReader;a.onload=r=>{var s;return e((s=r.target)==null?void 0:s.result)},a.onerror=()=>t(new Error("Failed to read file")),a.readAsText(n)})}static readFileAsDataURL(n){return new Promise((e,t)=>{const a=new FileReader;a.onload=r=>{var s;return e((s=r.target)==null?void 0:s.result)},a.onerror=()=>t(new Error("Failed to read file")),a.readAsDataURL(n)})}static getImageDimensions(n){return new Promise((e,t)=>{const a=new Image;a.onload=()=>{e({width:a.width,height:a.height})},a.onerror=()=>t(new Error("Failed to load image")),a.src=n})}static validateImportedData(n,e){const t=[],a=new Set;n.forEach(s=>{a.has(s.id)&&t.push(`Duplicate artboard ID: ${s.id}`),a.add(s.id)});const r=new Set;return e.forEach(s=>{r.has(s.id)&&t.push(`Duplicate element ID: ${s.id}`),r.add(s.id)}),n.forEach(s=>{s.getElementIds().forEach(o=>{r.has(o)||t.push(`Artboard "${s.name}" references missing element: ${o}`)})}),{valid:t.length===0,errors:t}}static getImportSummary(n,e){const t=this.validateImportedData(n,e);return{artboardCount:n.length,elementCount:e.length,artboardNames:n.map(a=>a.name),warnings:t.errors}}static async preloadAllImages(n){const e=[],t=r=>{r.transformType==="image"?e.push(r):r.transformType==="group"&&"children"in r&&r.children.forEach(s=>t(s))};n.forEach(t);const a=e.map(r=>new Promise(s=>{if(r.imageLoaded)s();else if(r.imageElement){const o=r.imageElement,l=()=>{o.removeEventListener("load",l),o.removeEventListener("error",c),s()},c=()=>{o.removeEventListener("load",l),o.removeEventListener("error",c),s()};o.addEventListener("load",l),o.addEventListener("error",c)}else s()}));await Promise.all(a)}};Ce.SUPPORTED_VERSIONS=["1.0.0","2.0.0"];let ye=Ce;exports.AlignmentSnapSystem=mt;exports.ArtboardRenderer=xe;exports.CanvasRenderer=pe;exports.DEFAULT_MAX_BITMAP_DIMENSION=we;exports.DISTRESS_TEXTURE_PRESETS=Je;exports.ElementFactory=Nn;exports.ExportManager=me;exports.ImportManager=ye;exports.InteractionStateMachine=bt;exports.MASK_IMAGE_PRESETS=Xe;exports.ResizePipeline=We;exports.SpacingSystem=yt;exports.TextureManager=sn;exports.TransformHandles=ht;exports.WorkerExportManager=En;exports.clearImageBitmapCache=ya;exports.clearMaskCache=Kt;exports.clearRegisteredBitmapKeys=Yn;exports.ensureBuiltinTexturesReady=Ze;exports.ensureMaskPresetsReady=qe;exports.getDashPattern=dt;exports.getHandleRadius=lt;exports.getLineWidth=oe;exports.getSharedWorkerExportManager=va;exports.globalResizePipeline=gt;exports.invalidateMaskCache=Yt;exports.isGroupElement=Gn;exports.isImageElement=He;exports.isPathElement=St;exports.isShapeElement=wt;exports.isTextElement=vt;exports.preloadTexture=la;exports.removeFromImageBitmapCache=xa;exports.renderRotationHandle=ut;exports.renderWithKnockout=Dt;exports.renderWithMasks=mn;exports.terminateSharedWorkerExportManager=wa;exports.unregisterElementBitmaps=Se;
23865
+ //# sourceMappingURL=ImportManager-W1eWhfyM.cjs.map