@yft-design/engine 0.0.58 → 0.0.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- var _e={enabled:!1,metrics:new Map,counters:new Map,sampleRate:1,reportIntervalMs:5e3,reportTimer:null},yu=()=>performance.now(),yb=()=>typeof window>"u"?!1:window.location.search.includes("canvasPerf=1"),Sb=n=>{let e=_e.metrics.get(n);return e||(e={count:0,total:0,max:0,last:0},_e.metrics.set(n,e)),e},vb=(n,e)=>e>0?n/e:0,za=()=>[..._e.metrics.entries()].map(([n,e])=>({name:n,count:e.count,totalMs:Number(e.total.toFixed(2)),avgMs:Number(vb(e.total,e.count).toFixed(3)),maxMs:Number(e.max.toFixed(3)),lastMs:Number(e.last.toFixed(3))})).sort((n,e)=>e.totalMs-n.totalMs),Ya=()=>[..._e.counters.entries()].map(([n,e])=>({name:n,count:e})).sort((n,e)=>e.count-n.count),wb=()=>({type:"canvas-perf",timestamp:new Date().toISOString(),enabled:_e.enabled,metrics:za(),counters:Ya()}),Su=()=>JSON.stringify(wb()),Tb=()=>{let n=za(),e=Ya(),t=["[canvas-perf] report"];if(n.length){t.push("metrics:");for(let r of n)t.push(`- ${r.name}: count=${r.count}, totalMs=${r.totalMs}, avgMs=${r.avgMs}, maxMs=${r.maxMs}, lastMs=${r.lastMs}`)}else t.push("metrics: none");if(e.length){t.push("counters:");for(let r of e)t.push(`- ${r.name}: count=${r.count}`)}else t.push("counters: none");return t.join(`
2
- `)},vu=()=>{let n=Su();if(!_e.enabled)return n;let e=za(),t=Ya();return console.info(n),console.groupCollapsed("[canvas-perf] report details"),e.length?console.table(e):console.log("no timing metrics"),t.length&&console.table(t),console.groupEnd(),n},Eb=()=>{typeof window>"u"||!_e.enabled||_e.reportTimer!=null||(_e.reportTimer=window.setInterval(vu,_e.reportIntervalMs))},Cb=()=>{_e.reportTimer!=null&&(window.clearInterval(_e.reportTimer),_e.reportTimer=null)},Xa=n=>{_e.enabled=n,n?(Eb(),console.info("[canvas-perf] enabled")):(Cb(),console.info("[canvas-perf] disabled"))},wu=()=>_e.enabled,Mb=()=>{_e.metrics.clear(),_e.counters.clear()},Tu=(n,e=1)=>{_e.enabled&&_e.counters.set(n,(_e.counters.get(n)||0)+e)},li=(n,e)=>{if(!_e.enabled)return;let t=Sb(n);t.count+=1,t.total+=e,t.max=Math.max(t.max,e),t.last=e},Ua=(n,e)=>{if(!_e.enabled)return e();let t=yu();try{return e()}finally{li(n,yu()-t)}};var Eu=()=>{typeof window>"u"||window.__YFT_CANVAS_PERF__||(window.__YFT_CANVAS_PERF__={enable:()=>Xa(!0),disable:()=>Xa(!1),report:vu,reportJson:Su,reportText:Tb,reset:Mb,mark:Tu,time:Ua,isEnabled:wu},yb()&&Xa(!0))};var Hn=class{_handlers=new Map;on(e,t){let r=this._handlers.get(e);r||(r=new Set,this._handlers.set(e,r));let o=t;return r.add(o),()=>this.off(e,o)}once(e,t){let r=t,o=(...i)=>{this.off(e,o),r(...i)};return this.on(e,o)}off(e,t){if(!t){this._handlers.delete(e);return}this._handlers.get(e)?.delete(t)}fire(e,...t){let r=this._handlers.get(e);if(!(!r||r.size===0))for(let o of[...r])o(...t)}clear(){this._handlers.clear()}};var mr=n=>n*Math.PI/180,j=(n,e,t=!1)=>[n[0]*e[0]+n[2]*e[1],n[1]*e[0]+n[3]*e[1],n[0]*e[2]+n[2]*e[3],n[1]*e[2]+n[3]*e[3],t?0:n[0]*e[4]+n[2]*e[5]+n[4],t?0:n[1]*e[4]+n[3]*e[5]+n[5]],ve=n=>{let e=1/(n[0]*n[3]-n[1]*n[2]),t=[e*n[3],-e*n[1],-e*n[2],e*n[0],0,0],r=t[0]*n[4]+t[2]*n[5],o=t[1]*n[4]+t[3]*n[5];return t[4]=-r,t[5]=-o,t},Q=(n,e,t,r=!1)=>({x:n[0]*e+n[2]*t+(r?0:n[4]),y:n[1]*e+n[3]*t+(r?0:n[5])}),Rb=n=>n[0]===1&&n[1]===0&&n[2]===0&&n[3]===1&&n[4]===0&&n[5]===0,ci=n=>{if(typeof n=="number")return n-.5;switch(n){case"left":case"top":return-.5;case"right":case"bottom":return .5;default:return 0}},Pb=n=>{let e=mr(n),t=Math.cos(e),r=Math.sin(e);return[t,r,-r,t,0,0]},Cu=n=>{let{scaleX:e=1,scaleY:t=1,flipX:r=!1,flipY:o=!1,skewX:i=0,skewY:s=0}=n,a=[r?-e:e,0,0,o?-t:t,0,0];return i&&(a=j(a,[1,0,Math.tan(mr(i)),1,0,0],!0)),s&&(a=j(a,[1,Math.tan(mr(s)),0,1,0,0],!0)),a},At=n=>{let{translateX:e=0,translateY:t=0,angle:r=0}=n,o=[1,0,0,1,e,t];r&&(o=j(o,Pb(r)));let i=Cu(n);return Rb(i)||(o=j(o,i)),o},kb=(n,e,t)=>{let r=n/2,o=e/2,i=[],s=[];for(let[a,l]of[[-r,-o],[r,-o],[-r,o],[r,o]]){let u=Q(t,a,l,!0);i.push(u.x),s.push(u.y)}return{x:Math.max(...i)-Math.min(...i),y:Math.max(...s)-Math.min(...s)}},ui=n=>{let{width:e=0,height:t=0,scaleX:r=1,scaleY:o=1,skewX:i=0,skewY:s=0,strokeWidth:a=0,strokeUniform:l}=n,u=l?0:a,c=l?a:0,h=e+u,d=t+u,f;return i===0&&s===0?f={x:h*r,y:d*o}:f=kb(h,d,Cu(n)),{x:f.x+c,y:f.y+c}},Gn=n=>{let e=Ut(n);return At({...n,translateX:e.x,translateY:e.y})},Ut=n=>{let e=ui(n),t=-ci(n.originX??"left")*e.x,r=-ci(n.originY??"top")*e.y,o=n.angle??0;if(o){let i=mr(o),s=Math.cos(i),a=Math.sin(i),l=t*s-r*a,u=t*a+r*s;t=l,r=u}return{x:(n.left??0)+t,y:(n.top??0)+r}},ge=(n,e)=>{let t=ui(n),r=-ci(n.originX??"left")*t.x,o=-ci(n.originY??"top")*t.y,i=n.angle??0;if(i){let s=mr(i),a=Math.cos(s),l=Math.sin(s),u=r*a-o*l,c=r*l+o*a;r=u,o=c}return{x:e.x-r,y:e.y-o}},Ab=n=>{let e=a=>a*180/Math.PI,t=e(Math.atan2(n[1],n[0])),r=n[0]*n[0]+n[1]*n[1],o=Math.sqrt(r),i=r===0?0:(n[0]*n[3]-n[2]*n[1])/o,s=r===0?0:e(Math.atan2(n[0]*n[2]+n[1]*n[3],r));return{angle:t,scaleX:o,scaleY:i,skewX:s,skewY:0,center:{x:n[4],y:n[5]}}},$a=n=>{let e=Ut(n),t=mr(n.angle??0),r=Math.cos(t),o=Math.sin(t),i=ui(n),s=i.x/2,a=i.y/2,l=(u,c)=>({x:e.x+r*u-o*c,y:e.y+o*u+r*c});return{tl:l(-s,-a),tr:l(s,-a),br:l(s,a),bl:l(-s,a)}},Xn=n=>{let e=[n.tl.x,n.tr.x,n.br.x,n.bl.x],t=[n.tl.y,n.tr.y,n.br.y,n.bl.y],r=Math.min(...e),o=Math.min(...t);return{left:r,top:o,right:Math.max(...e),bottom:Math.max(...t),width:Math.max(...e)-r,height:Math.max(...t)-o}},Zr=(n,e,t,r)=>{let o=Math.max(1,e*r),i=Math.max(1,t*r),s=[2/o,0,0,-2/i,-1,1];return j(s,j([r,0,0,r,0,0],n))};var ht=(n,e=!1)=>{if(typeof window>"u")return e;let t=new URLSearchParams(window.location.search).get(n);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;let r=window.localStorage.getItem(`engine.${n}`);return r==="1"?!0:r==="0"?!1:e},Mu=()=>ht("gpuShadow",!0),ja=()=>ht("gpuPsdShadow",!0),Va=()=>ht("gpuPsdFill",!0),Ru=()=>ht("stencilClip",!0),qa=()=>{if(typeof window>"u")return!0;let n=new URLSearchParams(window.location.search).get("snapGuide");return!(n==="0"||n==="false")},Pu=()=>ht("arcGlyph",!0),Nb=()=>ht("export",!0),Ka=()=>ht("retained",!0),zn=()=>ht("retainedDebug",!1),hi=()=>ht("sdfDash",!0),ku=()=>ht("sdfPolygon",!0),Au=()=>ht("sdfLineDeco",!0),Lb=()=>ht("svgexport",!0);var Ib={transparent:"#0000",aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},Nu=n=>{if(n.length===3||n.length===4){let e=parseInt(n[0]+n[0],16)/255,t=parseInt(n[1]+n[1],16)/255,r=parseInt(n[2]+n[2],16)/255,o=n.length===4?parseInt(n[3]+n[3],16)/255:1;return[e,t,r,o]}if(n.length===6||n.length===8){let e=parseInt(n.slice(0,2),16)/255,t=parseInt(n.slice(2,4),16)/255,r=parseInt(n.slice(4,6),16)/255,o=n.length===8?parseInt(n.slice(6,8),16)/255:1;return[e,t,r,o]}return[0,0,0,0]},_b=Object.fromEntries(Object.entries(Ib).map(([n,e])=>[n,Nu(e.slice(1))])),Jr=n=>Math.min(1,Math.max(0,n)),Db=65536,di=new Map,ee=n=>{if(!n)return[0,0,0,0];if(Array.isArray(n))return n;if(typeof n!="string")return[0,0,0,0];let e=di.get(n);if(e)return e;let t=Fb(n);return di.size>=Db&&di.clear(),di.set(n,t),t},Fb=n=>{let e=n.trim().toLowerCase(),t=_b[e];if(t)return t;if(e.startsWith("#"))return Nu(e.slice(1));let r=e.match(/^(rgba?|hsla?)\(([^)]+)\)$/);if(r){let o=r[2].split(/[\s,/]+/).filter(Boolean);if(r[1].startsWith("rgb")&&o.length>=3){let i=s=>s.endsWith("%")?parseFloat(s)/100*255:parseFloat(s);return[Jr(i(o[0])/255),Jr(i(o[1])/255),Jr(i(o[2])/255),o[3]!==void 0?Jr(parseFloat(o[3])):1]}if(r[1].startsWith("hsl")&&o.length>=3){let i=parseFloat(o[0])/360,s=parseFloat(o[1])/100,a=parseFloat(o[2])/100,l=(d,f,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<1/6?d+(f-d)*6*m:m<1/2?f:m<2/3?d+(f-d)*(2/3-m)*6:d),u=a<.5?a*(1+s):a+s-a*s,c=2*a-u,h=o[3]!==void 0?Jr(parseFloat(o[3])):1;return[l(c,u,i+1/3),l(c,u,i),l(c,u,i-1/3),h]}}return[0,0,0,0]};var Yn=n=>{if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n,t=e.type;if(typeof t!="string"||t==="pattern")return null;let r=t==="linear"?"linear":"radial",o=e.coords??{},i=Array.isArray(e.colorStops)?e.colorStops:[],s=[];for(let a of i){if(!a||typeof a!="object")continue;let l=a,u=ee(l.color),c=typeof l.opacity=="number"?l.opacity:1;s.push({offset:Number(l.offset)||0,color:[u[0],u[1],u[2],u[3]*c]})}return s.length===0?null:(s.sort((a,l)=>a.offset-l.offset),{kind:r,x1:Number(o.x1)||0,y1:Number(o.y1)||0,x2:Number(o.x2)||0,y2:Number(o.y2)||0,r1:Math.max(0,Number(o.r1)||0),r2:Math.max(0,Number(o.r2)||0),stops:s,offsetX:Number(e.offsetX)||0,offsetY:Number(e.offsetY)||0,gradientUnits:e.gradientUnits==="percentage"?"percentage":"pixels",gradientTransform:Array.isArray(e.gradientTransform)&&e.gradientTransform.length===6?[...e.gradientTransform]:null})},fi=(n,e,t)=>{let r=[1,0,0,1,-e/2+n.offsetX,-t/2+n.offsetY];return n.gradientUnits==="percentage"&&(r=j(r,[e,0,0,t,0,0])),n.gradientTransform&&(r=j(r,n.gradientTransform)),r};var Lu=(n,e)=>{let t=n.x2-n.x1,r=n.y2-n.y1,o=t*t+r*r;return o<=0?0:((e.x-n.x1)*t+(e.y-n.y1)*r)/o},Iu=(n,e)=>{let t=n.x2-n.x1,r=n.y2-n.y1,o=n.r2-n.r1,i=e.x-n.x1,s=e.y-n.y1,a=t*t+r*r-o*o,l=2*(-(t*i+r*s)-n.r1*o),u=i*i+s*s-n.r1*n.r1;if(Math.abs(a)<1e-9)return Math.abs(l)>1e-9?-u/l:0;let c=Math.max(0,l*l-4*a*u);return(-l-Math.sqrt(c))/(2*a)},mi=(n,e=512)=>{let t=new Uint8Array(e*4),r=n.stops,o=i=>Math.round(Math.min(255,Math.max(0,i*255)));for(let i=0;i<e;i++){let s=i/(e-1),a;if(s<=r[0].offset)a=r[0].color;else if(s>=r[r.length-1].offset)a=r[r.length-1].color;else{let l=r[0],u=r[1];for(let h=0;h<r.length-1;h++)if(s>=r[h].offset&&s<=r[h+1].offset){l=r[h],u=r[h+1];break}let c=u.offset===l.offset?0:(s-l.offset)/(u.offset-l.offset);a=[l.color[0]+(u.color[0]-l.color[0])*c,l.color[1]+(u.color[1]-l.color[1])*c,l.color[2]+(u.color[2]-l.color[2])*c,l.color[3]+(u.color[3]-l.color[3])*c]}t[i*4]=o(a[0]),t[i*4+1]=o(a[1]),t[i*4+2]=o(a[2]),t[i*4+3]=o(a[3])}return t},pi=n=>{let e=r=>String(Math.round(r*1e4)/1e4),t=n.stops.map(r=>`${e(r.offset)}:${r.color.map(o=>e(o)).join(",")}`).join(";");return[n.kind,e(n.x1),e(n.y1),e(n.x2),e(n.y2),e(n.r1),e(n.r2),t,e(n.offsetX),e(n.offsetY),n.gradientUnits,n.gradientTransform?n.gradientTransform.map(e).join(","):""].join("|")};var Ob=["repeat","repeat-x","repeat-y","no-repeat"],pr=n=>{if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;if(e.type!=="pattern"||typeof e.source!="string"||!e.source)return null;let t=Ob.includes(e.repeat)?e.repeat:"repeat";return{kind:"pattern",src:e.source,repeat:t,offsetX:Number(e.offsetX)||0,offsetY:Number(e.offsetY)||0,patternTransform:Array.isArray(e.patternTransform)&&e.patternTransform.length===6?[...e.patternTransform]:null,crossOrigin:typeof e.crossOrigin=="string"?e.crossOrigin:null}},bi=(n,e,t)=>{let r=[1,0,0,1,-e/2+n.offsetX,-t/2+n.offsetY];return n.patternTransform&&(r=j(r,n.patternTransform)),r},_u=n=>[n==="repeat"||n==="repeat-x",n==="repeat"||n==="repeat-y"];var L={TEXTBOX:"textbox",TEXT:"text",ITEXT:"i-text",INPUTTEXT:"itext",ARCHTEXT:"archtext",WAISTTEXT:"waisttext",FLAGTEXT:"flagtext",ARCTEXT:"arctext",CIRCLETEXT:"circletext",SCROLLTEXT:"scrolltext",TEXTIMAGE:"textimage",IMAGE:"image",SVGIMAGE:"svgimage",CROPIMAGE:"cropimage",ECHART:"echart",FABRIC_ECHART:"fabricechart",QRCODE:"qrcode",BARCODE:"barcode",MASK:"mask",PATH:"path",RECT:"rect",FABRICRECT:"fabricrect",LINE:"line",ARROW:"arrow",POLYLINE:"polyline",POLYGON:"polygon",ELLIPSE:"ellipse",CIRCLE:"circle",TRIANGLE:"triangle",TABLE:"table",GROUP:"group",ACTIVE_SELECTION:"activeselection",PUZZLE:"puzzle",GIF:"gif",VIDEO:"video",DIMENSION:"dimension",REFERENCELINE:"referenceline"},se=n=>{let e=n?.type;return typeof e=="string"?e.toLowerCase():""},an=new Set([L.TEXTBOX,L.INPUTTEXT,L.ITEXT,L.TEXT,L.ARCHTEXT,L.WAISTTEXT,L.FLAGTEXT,L.ARCTEXT,L.CIRCLETEXT,L.SCROLLTEXT,L.TEXTIMAGE]),dt=new Set([L.IMAGE,L.SVGIMAGE,L.CROPIMAGE,L.QRCODE,L.BARCODE,L.ECHART,L.FABRIC_ECHART]),Un=new Set([L.ELLIPSE,L.CIRCLE,L.POLYGON,L.POLYLINE,L.PATH,L.TRIANGLE]),ft=new Set([L.LINE,L.ARROW,L.DIMENSION,L.REFERENCELINE]),$n=new Set([L.RECT,L.FABRICRECT]),ot=new Set([L.MASK]),gi=new Set([L.PUZZLE]),xi=new Set([L.GIF]),yi=new Set([L.VIDEO]);var ln=1-.5522847498,Qa=new Set([L.FABRICRECT]),cn=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,Za=(n,e,t)=>{let r=cn(n,0);return r>0?{rx:r/(cn(e,1)||1),ry:r/(cn(t,1)||1)}:null},Du=n=>{if(!Qa.has(se(n)))return;let e=Za(n.radius,n.scaleX,n.scaleY);e&&(n.rx=e.rx,n.ry=e.ry)},Fu=(n,e)=>{if(!Qa.has(se(n)))return!1;let t="radius"in e,r="scaleX"in e||"scaleY"in e,o=cn(n.radius,0)>0&&("rx"in e||"ry"in e);if(!t&&!r&&!o)return!1;let i=t?e.radius:n.radius,s="scaleX"in e?e.scaleX:n.scaleX,a="scaleY"in e?e.scaleY:n.scaleY,l=Za(i,s,a);return e.rx=l?l.rx:0,e.ry=l?l.ry:0,!0},it=(n,e,t)=>{if(!(e>0)||!(t>0))return null;let r=Qa.has(se(n))?Za(n.radius,n.scaleX,n.scaleY):null,o=r?r.rx:cn(n.rx,0),i=r?r.ry:cn(n.ry,0);o>0&&!(i>0)&&(i=o);let s=Math.min(o,e/2),a=Math.min(i,t/2);return s>0||a>0?{rx:s,ry:a}:null},br=(n,e,t)=>{if(!(e>0)||!(t>0))return null;let r=Math.min(Math.max(cn(n.rx,0),cn(n.ry,0)),e/2,t/2);return r>0?r:null},jn=(n,e,t,r,o)=>{let i=Math.max(0,e),s=Math.max(0,t),a=Math.min(Math.max(0,r),i/2),l=Math.min(Math.max(0,o),s/2),u=-i/2,c=-s/2,h=a!==0||l!==0;n.beginPath(),n.moveTo(u+a,c),n.lineTo(u+i-a,c),h&&n.bezierCurveTo(u+i-ln*a,c,u+i,c+ln*l,u+i,c+l),n.lineTo(u+i,c+s-l),h&&n.bezierCurveTo(u+i,c+s-ln*l,u+i-ln*a,c+s,u+i-a,c+s),n.lineTo(u+a,c+s),h&&n.bezierCurveTo(u+ln*a,c+s,u,c+s-ln*l,u,c+s-l),n.lineTo(u,c+l),h&&n.bezierCurveTo(u,c+ln*l,u+ln*a,c,u+a,c),n.closePath()},Ou=(n,e,t,r)=>{let o=Math.max(0,n),i=Math.max(0,e);if(!(o>0)||!(i>0))return null;let s=Math.min(Math.max(0,t),o/2),a=Math.min(Math.max(0,r),i/2);if(!(s>0)&&!(a>0))return null;let l=Math.max(2,Math.min(16,Math.ceil((s+a)*.6))),u=[[o/2-s,-i/2+a,s,a,-Math.PI/2],[o/2-s,i/2-a,s,a,0],[-o/2+s,i/2-a,s,a,Math.PI/2],[-o/2+s,-i/2+a,s,a,Math.PI]],c=[0,0];for(let[f,m,p,b,g]of u)for(let x=0;x<l;x++){let S=g+x/l*(Math.PI/2);c.push(f+p*Math.cos(S),m+b*Math.sin(S))}let h=c.length/2-1,d=new Uint32Array(h*3);for(let f=0;f<h;f++)d[f*3]=0,d[f*3+1]=1+f,d[f*3+2]=1+(f+1)%h;return{verts:new Float32Array(c),triangles:d}};import Bb from"rbush";var Ne=1e-12,Wb=96,Si=(n,e,t,r,o,i)=>(t-n)*(i-e)-(r-e)*(o-n),Ja=(n,e,t,r)=>{if(Math.abs(r)>Ne)return!1;let o=e.x-n.x,i=e.y-n.y,s=o*o+i*i;if(s<Ne)return!0;let a=(t.x-n.x)*o+(t.y-n.y)*i;return a>=-Ne&&a<=s+Ne},gr=n=>{let e=0;for(let t=0;t<n.length;t++){let r=n[t],o=n[(t+1)%n.length];e+=r.x*o.y-o.x*r.y}return e/2},Bu=(n,e,t,r,o)=>{let i=n[e];if(Math.abs(i.x-t.x)<Ne&&Math.abs(i.y-t.y)<Ne||Math.abs(i.x-r.x)<Ne&&Math.abs(i.y-r.y)<Ne||Math.abs(i.x-o.x)<Ne&&Math.abs(i.y-o.y)<Ne)return!1;let s=Si(t.x,t.y,r.x,r.y,i.x,i.y),a=Si(r.x,r.y,o.x,o.y,i.x,i.y),l=Si(o.x,o.y,t.x,t.y,i.x,i.y);return s>Ne&&a>Ne&&l>Ne||s<-Ne&&a<-Ne&&l<-Ne?!0:Ja(t,r,i,s)||Ja(r,o,i,a)||Ja(o,t,i,l)},el=n=>{let e=n.length;if(e<3)return[];let t=gr(n);if(Math.abs(t)<Ne)return[];let r=new Array(e);for(let d=0;d<e;d++)r[d]=t>0?d:e-1-d;let o=[],i=r.length,s=i*i+16,a=0,l=null,u=null,c=null;if(e>=Wb){l=new Bb,u=new Array(e);for(let d=0;d<e;d++){let f=n[d];u[d]={minX:f.x,minY:f.y,maxX:f.x,maxY:f.y,v:d}}l.load(u),c=new Uint8Array(e).fill(1)}let h=0;for(;i>3&&s-- >0&&(a>=i&&(a=0),!(++h>i));){let d=r[a],f=r[(a+1)%i],m=r[(a+2)%i],p=n[d],b=n[f],g=n[m],x=Si(p.x,p.y,b.x,b.y,g.x,g.y);if(x>Ne){let S=!1;if(l&&u){let w=Math.min(p.x,b.x,g.x)-Ne,y=Math.max(p.x,b.x,g.x)+Ne,v=Math.min(p.y,b.y,g.y)-Ne,R=Math.max(p.y,b.y,g.y)+Ne,P=l.search({minX:w,minY:v,maxX:y,maxY:R});for(let T=0;T<P.length;T++){let C=P[T].v;if(c[C]&&!(C===d||C===f||C===m)&&Bu(n,C,p,b,g)){S=!0;break}}}else for(let w=3;w<i;w++){let y=r[(a+w)%i];if(Bu(n,y,p,b,g)){S=!0;break}}if(!S){o.push(d,f,m);let w=r.splice((a+1)%i,1)[0];i--,c&&(c[w]=0),h=0;continue}}else if(x>=-Ne){let S=r.splice((a+1)%i,1)[0];i--,c&&(c[S]=0),h=0;continue}a++}if(i>3)for(let d=1;d<i-1;d++)o.push(r[0],r[d],r[d+1]);else i===3&&o.push(r[0],r[1],r[2]);return o};var vi=Math.PI,Hb=Math.PI/180,$u=Math.PI/2,rl=n=>{if(n===0)return 1;switch(Math.abs(n)/$u){case 1:case 3:return 0;case 2:return-1}return Math.cos(n)},ol=n=>{if(n===0)return 0;let e=n/$u,t=Math.sign(n);switch(e){case 1:return t;case 2:return 0;case 3:return-t}return Math.sin(n)},Gb=/[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/gi,Xb=/[mzlhvcsqta][^mzlhvcsqta]*/gi,Vn=/\s*,?\s*/,eo="([-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)",tl=new RegExp(`${Vn.source}${eo}${Vn.source}${eo}${Vn.source}${eo}${Vn.source}([01])${Vn.source}([01])${Vn.source}${eo}${Vn.source}${eo}`,"g"),ju={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},zb={m:"l",M:"L"},Yb=n=>{let e=[],t=n.match(Xb)??[];for(let r of t){let o=r[0];if(o==="z"||o==="Z"){e.push([o]);continue}let i=ju[o.toLowerCase()],s=[];if(o==="a"||o==="A"){tl.lastIndex=0;for(let a=tl.exec(r);a;a=tl.exec(r))s=s.concat(a.slice(1))}else s=r.match(Gb)??[];for(let a=0;a<s.length;a+=i){let l=new Array(i),u=zb[o];l[0]=a>0&&u?u:o;for(let c=0;c<i;c++)l[c+1]=parseFloat(s[a+c]);e.push(l)}}return e},Wu=(n,e,t,r)=>{let o=Math.atan2(e,n),i=Math.atan2(r,t);return i>=o?i-o:2*vi-(o-i)},Ub=(n,e,t,r,o,i,s,a,l,u,c)=>{let h=rl(n),d=ol(n),f=rl(e),m=ol(e),p=t*o*f-r*i*m+s,b=r*o*f+t*i*m+a,g=u+l*(-t*o*d-r*i*h),x=c+l*(-r*o*d+t*i*h),S=p+l*(t*o*m+r*i*f),w=b+l*(r*o*m-t*i*f);return["C",g,x,S,w,p,b]},$b=(n,e,t,r,o,i,s)=>{if(t===0||r===0)return[];let a=0,l=0,u=0,c=s*Hb,h=ol(c),d=rl(c),f=.5*(-d*n-h*e),m=.5*(-d*e+h*n),p=t**2,b=r**2,g=m**2,x=f**2,S=p*b-p*g-b*x,w=Math.abs(t),y=Math.abs(r);if(S<0){let W=Math.sqrt(1-S/(p*b));w*=W,y*=W}else u=(o===i?-1:1)*Math.sqrt(S/(p*g+b*x));let v=u*w*m/y,R=-u*y*f/w,P=d*v-h*R+n*.5,T=h*v+d*R+e*.5,C=Wu(1,0,(f-v)/w,(m-R)/y),E=Wu((f-v)/w,(m-R)/y,(-f-v)/w,(-m-R)/y);i===0&&E>0?E-=2*vi:i===1&&E<0&&(E+=2*vi);let M=Math.ceil(Math.abs(E/vi*2)),k=[],A=E/M,O=8/3*Math.sin(A/4)*Math.sin(A/4)/Math.sin(A/2),F=C+A;for(let W=0;W<M;W++)k[W]=Ub(C,F,d,h,w,y,P,T,O,a,l),a=k[W][5],l=k[W][6],C=F,F+=A;return k},jb=(n,e,t,r,o,i,s,a,l)=>$b(a-n,l-e,t,r,i,s,o).map(u=>(u[1]=u[1]+n,u[2]=u[2]+e,u[3]=u[3]+n,u[4]=u[4]+e,u[5]=u[5]+n,u[6]=u[6]+e,u)),Hu=n=>{let e=0,t=0,r=0,o=0,i=[],s,a=0,l=0;for(let u of n){let c=[...u],h;switch(c[0]){case"l":c[1]+=e,c[2]+=t;case"L":e=c[1],t=c[2],h=["L",e,t];break;case"h":c[1]+=e;case"H":e=c[1],h=["L",e,t];break;case"v":c[1]+=t;case"V":t=c[1],h=["L",e,t];break;case"m":c[1]+=e,c[2]+=t;case"M":e=c[1],t=c[2],r=c[1],o=c[2],h=["M",e,t];break;case"c":c[1]+=e,c[2]+=t,c[3]+=e,c[4]+=t,c[5]+=e,c[6]+=t;case"C":a=c[3],l=c[4],e=c[5],t=c[6],h=["C",c[1],c[2],a,l,e,t];break;case"s":c[1]+=e,c[2]+=t,c[3]+=e,c[4]+=t;case"S":s==="C"?(a=2*e-a,l=2*t-l):(a=e,l=t),e=c[3],t=c[4],h=["C",a,l,c[1],c[2],e,t],a=h[3],l=h[4];break;case"q":c[1]+=e,c[2]+=t,c[3]+=e,c[4]+=t;case"Q":a=c[1],l=c[2],e=c[3],t=c[4],h=["Q",a,l,e,t];break;case"t":c[1]+=e,c[2]+=t;case"T":s==="Q"?(a=2*e-a,l=2*t-l):(a=e,l=t),e=c[1],t=c[2],h=["Q",a,l,e,t];break;case"a":c[6]+=e,c[7]+=t;case"A":for(let d of jb(e,t,c[1],c[2],c[3],c[4],c[5],c[6],c[7]))i.push(d);e=c[6],t=c[7];break;case"z":case"Z":e=r,t=o,h=["Z"];break}h&&(i.push(h),s=h[0])}return i},Ce=n=>{if(typeof n=="string"){if(!n)return null;let e=Yb(n);return e.length>0?Hu(e):null}if(Array.isArray(n)){if(n.length===0)return null;let e=[];for(let t of n){if(!Array.isArray(t)||typeof t[0]!="string")continue;let r=t[0].toLowerCase();(r==="z"||ju[r]!==void 0)&&e.push(t)}return e.length===0?null:Hu(e)}return null},Gu=(n,e,t,r,o,i,s,a)=>{let l=[],u=[],c=[],h=6*n-12*t+6*o,d=-3*n+9*t-9*o+3*s,f=3*t-3*n;for(let p=0;p<2;++p){if(p>0&&(h=6*e-12*r+6*i,d=-3*e+9*r-9*i+3*a,f=3*r-3*e),Math.abs(d)<1e-12){if(Math.abs(h)<1e-12)continue;let w=-f/h;0<w&&w<1&&l.push(w);continue}let b=h*h-4*f*d;if(b<0)continue;let g=Math.sqrt(b),x=(-h+g)/(2*d);0<x&&x<1&&l.push(x);let S=(-h-g)/(2*d);0<S&&S<1&&l.push(S)}let m=l.length;for(let p=0;p<m;p++){let b=l[p],g=b**3,x=3*b**2*(1-b),S=3*b*(1-b)**2,w=(1-b)**3;u.push(s*g+o*x+t*S+n*w),c.push(a*g+i*x+r*S+e*w)}return u.push(n,s),c.push(e,a),[{x:Math.min(...u),y:Math.min(...c)},{x:Math.max(...u),y:Math.max(...c)}]},Fe=n=>{let e=[],t=0,r=0,o=0,i=0;for(let c of n)switch(c[0]){case"L":o=c[1],i=c[2],e.push({x:t,y:r},{x:o,y:i});break;case"M":o=c[1],i=c[2],t=o,r=i;break;case"C":for(let h of Gu(o,i,c[1],c[2],c[3],c[4],c[5],c[6]))e.push(h);o=c[5],i=c[6];break;case"Q":for(let h of Gu(o,i,c[1],c[2],c[1],c[2],c[3],c[4]))e.push(h);o=c[3],i=c[4];break;case"Z":o=t,i=r;break}if(e.length===0)return null;let s=1/0,a=1/0,l=-1/0,u=-1/0;for(let c of e){if(!Number.isFinite(c.x)||!Number.isFinite(c.y))return null;s>c.x&&(s=c.x),a>c.y&&(a=c.y),l<c.x&&(l=c.x),u<c.y&&(u=c.y)}return{left:s,top:a,right:l,bottom:u}},Vb=(n,e,t,r,o,i,s,a)=>{let l=s-n,u=a-e,c=l*l+u*u;if(c<1e-12)return Math.hypot(t-n,r-e)+Math.hypot(o-s,i-a);let h=Math.abs(l*(r-e)-u*(t-n)),d=Math.abs(l*(i-e)-u*(o-n));return(h+d)/Math.sqrt(c)},Ti=(n,e,t,r,o,i,s,a,l,u,c)=>{if(c>24){n.push({x:a,y:l});return}if(Vb(e,t,r,o,i,s,a,l)<=u){n.push({x:a,y:l});return}let h=(e+r)/2,d=(t+o)/2,f=(r+i)/2,m=(o+s)/2,p=(i+a)/2,b=(s+l)/2,g=(h+f)/2,x=(d+m)/2,S=(f+p)/2,w=(m+b)/2,y=(g+S)/2,v=(x+w)/2;Ti(n,e,t,h,d,g,x,y,v,u,c+1),Ti(n,y,v,S,w,p,b,a,l,u,c+1)},Vu=(n,e=.1)=>{let t=[],r=null,o=0,i=0,s=0,a=0;for(let l of n)switch(l[0]){case"M":{r&&r.length>=2&&t.push({points:r,closed:!1}),r=[{x:l[1],y:l[2]}],o=l[1],i=l[2],s=o,a=i;break}case"L":{o=l[1],i=l[2],(r??=[]).push({x:o,y:i});break}case"C":{Ti(r??=[],o,i,l[1],l[2],l[3],l[4],l[5],l[6],e,0),o=l[5],i=l[6];break}case"Q":{Ti(r??=[],o,i,o+2/3*(l[1]-o),i+2/3*(l[2]-i),l[3]+2/3*(l[1]-l[3]),l[4]+2/3*(l[2]-l[4]),l[3],l[4],e,0),o=l[3],i=l[4];break}case"Z":{if(r&&r.length>=2){let u=r[0],c=r[r.length-1];(Math.abs(u.x-c.x)>1e-9||Math.abs(u.y-c.y)>1e-9)&&r.push({x:u.x,y:u.y}),t.push({points:r,closed:!0})}r=null,o=s,i=a;break}}return r&&r.length>=2&&t.push({points:r,closed:!1}),t},Xu=(n,e)=>{let t=!1;for(let r=0,o=e.length-1;r<e.length;o=r++){let i=e[o],s=e[r];s.y>n.y!=i.y>n.y&&n.x<(i.x-s.x)*(n.y-s.y)/(i.y-s.y)+s.x&&(t=!t)}return t},qb=n=>{if(n.length<3)return[];let e=[];for(let i of n){let s=e[e.length-1];s&&Math.abs(i.x-s.x)<1e-9&&Math.abs(i.y-s.y)<1e-9||e.push(i)}if(e.length<3)return[];let t=e[0],r=e[e.length-1];if(Math.abs(t.x-r.x)<1e-9&&Math.abs(t.y-r.y)<1e-9&&e.pop(),e.length<3)return[];let o=new Map;for(let i=0;i<e.length;i++){let s=e[i],a=`${s.x},${s.y}`,l=o.get(a);if(l&&i-l.index>1){let u=e[i-1],c=s.x-u.x,h=s.y-u.y,d=Math.hypot(c,h)||1,f=(l.occurrence+1)*1e-6;e[i]={x:s.x+c/d*f,y:s.y+h/d*f}}else o.set(a,{index:i,occurrence:l?l.occurrence+1:0})}return e},Kb=(n,e,t,r)=>{let o=(e.x-n.x)*(r.y-n.y)-(e.y-n.y)*(r.x-n.x),i=(t.x-e.x)*(r.y-e.y)-(t.y-e.y)*(r.x-e.x),s=(n.x-t.x)*(r.y-t.y)-(n.y-t.y)*(r.x-t.x),a=o<-1e-12||i<-1e-12||s<-1e-12,l=o>1e-12||i>1e-12||s>1e-12;return!(a&&l)},qu=(n,e,t,r)=>{let o=(e.x-n.x)*(r.y-t.y)-(e.y-n.y)*(r.x-t.x);if(Math.abs(o)<1e-12)return!1;let i=((t.x-n.x)*(r.y-t.y)-(t.y-n.y)*(r.x-t.x))/o,s=((t.x-n.x)*(e.y-n.y)-(t.y-n.y)*(e.x-n.x))/o;return i>1e-9&&i<1-1e-9&&s>1e-9&&s<1-1e-9},zu=(n,e,t)=>{for(let r=0,o=e.length-1;r<e.length;o=r++){let i=e[o],s=e[r],a=s.x-i.x,l=s.y-i.y,u=a*a+l*l;if(u===0){if(Math.hypot(n.x-i.x,n.y-i.y)<=t)return!0;continue}let c=Math.min(1,Math.max(0,((n.x-i.x)*a+(n.y-i.y)*l)/u));if(Math.hypot(n.x-i.x-c*a,n.y-i.y-c*l)<=t)return!0}return!1},il=n=>{let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)i.x<e&&(e=i.x),i.x>r&&(r=i.x),i.y<t&&(t=i.y),i.y>o&&(o=i.y);return{minX:e,minY:t,maxX:r,maxY:o}},nl=(n,e,t)=>e.x>=n.minX-t&&e.x<=n.maxX+t&&e.y>=n.minY-t&&e.y<=n.maxY+t,Qb=n=>{let e=n.length,t=il(n),r=Math.max(8,Math.min(64,Math.ceil(Math.sqrt(e)))),o=Math.max(t.maxX-t.minX,1e-9)/r,i=Math.max(t.maxY-t.minY,1e-9)/r,s=new Array(r*r),a=l=>{let u=Math.max(0,Math.min(r-1,Math.floor((Math.min(l.pa.x,l.pb.x)-t.minX)/o))),c=Math.max(0,Math.min(r-1,Math.floor((Math.max(l.pa.x,l.pb.x)-t.minX)/o))),h=Math.max(0,Math.min(r-1,Math.floor((Math.min(l.pa.y,l.pb.y)-t.minY)/i))),d=Math.max(0,Math.min(r-1,Math.floor((Math.max(l.pa.y,l.pb.y)-t.minY)/i)));for(let f=h;f<=d;f++)for(let m=u;m<=c;m++)(s[f*r+m]??=[]).push(l)};for(let l=0;l<e;l++)a({pa:n[l],pb:n[(l+1)%e]});return{addEdge:(l,u)=>a({pa:l,pb:u}),blockedExcept(l,u){let c=Math.max(0,Math.min(r-1,Math.floor((Math.min(l.x,u.x)-t.minX)/o))),h=Math.max(0,Math.min(r-1,Math.floor((Math.max(l.x,u.x)-t.minX)/o))),d=Math.max(0,Math.min(r-1,Math.floor((Math.min(l.y,u.y)-t.minY)/i))),f=Math.max(0,Math.min(r-1,Math.floor((Math.max(l.y,u.y)-t.minY)/i)));for(let m=d;m<=f;m++)for(let p=c;p<=h;p++){let b=s[m*r+p];if(b){for(let g of b)if(!(g.pa===u||g.pb===u)&&qu(l,u,g.pa,g.pb))return!0}}return!1}}},wi=(n,e,t)=>{let r=`${e.x},${e.y}`;n.set(r,(n.get(r)??0)+t)},Zb=(n,e,t,r,o)=>{let i=n.length,s=0;for(let y=1;y<e.length;y++)(e[y].x>e[s].x||e[y].x===e[s].x&&e[y].y>e[s].y)&&(s=y);let a=e[s],l=-1,u=1/0;for(let y=0;y<i;y++){let v=n[y],R=Math.hypot(v.x-a.x,v.y-a.y);if(R>=u||R<1e-7||(r.get(`${v.x},${v.y}`)??0)>1)continue;let P=t.blockedExcept(a,v);if(!P&&o.length>0){let T=v.x-a.x,C=v.y-a.y,E=T*T+C*C;for(let M of o){let k=M.x-a.x,A=M.y-a.y,O=(k*T+A*C)/E;if(O>1e-9&&O<1-1e-9&&Math.abs(k*C-A*T)<=1e-7*Math.sqrt(E)){P=!0;break}}}if(!P){for(let T=0;T<e.length;T++)if(!(T===s||(T+1)%e.length===s)&&qu(a,v,e[T],e[(T+1)%e.length])){P=!0;break}}P||(u=R,l=y)}if(l>=0){let y=[];for(let v=l;v<i;v++)y.push(n[v]);for(let v=0;v<l;v++)y.push(n[v]);y.push(n[l]),y.push(a);for(let v=1;v<e.length;v++)y.push(e[(s+v)%e.length]);y.push(a),Yu(t,n[l],a,e),wi(r,n[l],1),wi(r,a,2);for(let v=0;v<e.length;v++)v!==s&&wi(r,e[v],1);return(r.get(`${n[l].x},${n[l].y}`)??0)>=2&&o.push(n[l]),o.push(a),y}let c=1/0,h=-1;for(let y=0;y<i;y++){let v=n[y],R=n[(y+1)%i];if(v.y!==R.y&&a.y>=Math.min(v.y,R.y)&&a.y<Math.max(v.y,R.y)){let P=(a.y-v.y)/(R.y-v.y),T=v.x+P*(R.x-v.x);T>=a.x&&T<c&&(c=T,h=y)}}if(h<0)return n;let d=n[h];l=n[(h+1)%i].x>d.x?(h+1)%i:h;let m=n[l],p={x:c,y:a.y},b=m.x-a.x,g=m.y-a.y,x=Math.hypot(b,g)||1,S=-1/0;for(let y=0;y<i;y++){if(y===l)continue;let v=n[y];if(!Kb(a,p,m,v))continue;let R=v.x-a.x,P=v.y-a.y,T=Math.hypot(R,P)||1,C=(R*b+P*g)/(T*x);(C>S+1e-12||Math.abs(C-S)<=1e-12&&T<u)&&(S=C,u=T,m=v,l=y)}let w=[];for(let y=l;y<i;y++)w.push(n[y]);for(let y=0;y<l;y++)w.push(n[y]);w.push(n[l]),w.push(a);for(let y=1;y<e.length;y++)w.push(e[(s+y)%e.length]);return w.push(a),Yu(t,n[l],a,e),w},Yu=(n,e,t,r)=>{n.addEdge(e,t);for(let o=0;o<r.length;o++)n.addEdge(r[o],r[(o+1)%r.length])},Ku=(n,e="evenodd")=>{let t=n.map(h=>qb(h.points)).filter(h=>h.length>=3);if(t.length===0)return[];let r=t.map(h=>il(h)),o=h=>{let d=t[h],f=Math.max(1,Math.floor(d.length/8));for(let m=0;m<d.length;m+=f){let p=d[m],b=!1;for(let g=0;g<t.length;g++)if(g!==h&&nl(r[g],p,1e-6)&&zu(p,t[g],1e-6)){b=!0;break}if(!b)return p}},i=t.map((h,d)=>o(d)),s=new Array(t.length).fill(0),a=t.map(()=>new Array(t.length).fill(!1));for(let h=0;h<t.length;h++){let d=i[h];if(d)for(let f=0;f<t.length;f++)h!==f&&nl(r[f],d,1e-6)&&(zu(d,t[f],1e-6)||Xu(d,t[f])&&(s[h]++,a[f][h]=!0))}let l=new Array(t.length);if(e==="evenodd")for(let h=0;h<t.length;h++)l[h]=s[h]%2===0;else for(let h=0;h<t.length;h++){let d=gr(t[h])>0?1:-1;for(let f=0;f<t.length;f++)f!==h&&a[f][h]&&(d+=gr(t[f])>0?1:-1);l[h]=d!==0}let u=[],c=[];for(let h=0;h<t.length;h++)l[h]?u.push({ring:t[h],index:h,bbox:r[h]}):c.push({ring:t[h],index:h,depth:s[h]});if(u.length===0)return[];c.sort((h,d)=>Uu(d.ring)-Uu(h.ring));for(let h of c){let d=i[h.index]??h.ring[0],f=u.find(p=>s[p.index]===h.depth-1&&nl(p.bbox,d,0)&&Xu(d,p.ring));if(!f)continue;gr(f.ring)*gr(h.ring)>0&&(h.ring=h.ring.slice().reverse()),f.grid??=Qb(f.ring),f.coordCounts??=(()=>{let p=new Map;for(let b of f.ring)wi(p,b,1);return p})(),f.multiPts??=[],f.ring=Zb(f.ring,h.ring,f.grid,f.coordCounts,f.multiPts);let m=il(h.ring);f.bbox.minX=Math.min(f.bbox.minX,m.minX),f.bbox.minY=Math.min(f.bbox.minY,m.minY),f.bbox.maxX=Math.max(f.bbox.maxX,m.maxX),f.bbox.maxY=Math.max(f.bbox.maxY,m.maxY)}return u.map(h=>h.ring)},Uu=n=>{let e=-1/0;for(let t of n)t.x>e&&(e=t.x);return e};var Jb=new Set(["miter","round","bevel"]),eg=new Set(["butt","round","square"]),Ei=n=>{if(typeof n.stroke!="string"||!n.stroke)return null;let e=Number(n.strokeWidth)||0;if(e<=0)return null;let t=Array.isArray(n.strokeDashArray)?n.strokeDashArray.map(i=>Number(i)||0).filter(i=>i>=0):null,r=typeof n.strokeLineJoin=="string"&&Jb.has(n.strokeLineJoin)?n.strokeLineJoin:"miter",o=typeof n.strokeLineCap=="string"&&eg.has(n.strokeLineCap)?n.strokeLineCap:"butt";return{color:n.stroke,rgba:ee(n.stroke),width:e,dashArray:t&&t.length>0?t:null,dashOffset:Number(n.strokeDashOffset)||0,lineJoin:r,lineCap:o,miterLimit:Number(n.strokeMiterLimit)||4,paintFirst:n.paintFirst==="stroke"?"stroke":"fill",alignment:n.strokeAlignment==="inside"||n.strokeAlignment==="outside"?n.strokeAlignment:"center",uniform:n.strokeUniform===!0||se(n)===L.PATH}},Qu=n=>{let e=r=>String(Math.round(r*1e4)/1e4),t=n.dashArray?n.dashArray.map(e).join(","):"-";return`s|${n.rgba.map(e).join(",")}|${e(n.width)}|${n.uniform?1:0}|${t}|${e(n.dashOffset)}|${n.lineJoin}|${n.lineCap}|${e(n.miterLimit)}|${n.paintFirst}|${n.alignment}`};var tg=(n,e)=>{let t=e.matrix,r=Math.max(Math.hypot(t[0],t[1]),Math.hypot(t[2],t[3]));return Math.ceil(n.width*Math.max(1,n.miterLimit)*(n.uniform?1:r)/2+4)},ng=625e4,Zu=(n,e,t)=>Math.min(n,8192/e,8192/t,Math.sqrt(ng/(e*t))),Ci=(n,e,t,r,o,i)=>{let s=e*t,a=r[4]*t,l=r[5]*t;return{lx:(Math.round((n[4]-o/2)*s+a)-a)/s,ly:(Math.round((n[5]-i/2)*s+l)-l)/s}},xr=(n,e)=>{let t=e.raw,r=se(t);if(n.beginPath(),r===L.PATH){let o=Ce(t.path);if(!o)return!1;let i=Fe(o);if(!i)return!1;let s=(i.left+i.right)/2,a=(i.top+i.bottom)/2;for(let l of o)switch(l[0]){case"M":n.moveTo(l[1]-s,l[2]-a);break;case"L":n.lineTo(l[1]-s,l[2]-a);break;case"C":n.bezierCurveTo(l[1]-s,l[2]-a,l[3]-s,l[4]-a,l[5]-s,l[6]-a);break;case"Q":n.quadraticCurveTo(l[1]-s,l[2]-a,l[3]-s,l[4]-a);break;case"Z":n.closePath();break}return!0}if(r===L.POLYGON||r===L.POLYLINE){let o=Array.isArray(t.points)?t.points:[];if(o.length<2)return!1;let i=1/0,s=1/0,a=-1/0,l=-1/0;for(let h of o)i>h.x&&(i=h.x),s>h.y&&(s=h.y),a<h.x&&(a=h.x),l<h.y&&(l=h.y);let u=(i+a)/2,c=(s+l)/2;n.moveTo(o[0].x-u,o[0].y-c);for(let h=0;h<o.length;h++)n.lineTo(o[h].x-u,o[h].y-c);return r===L.POLYGON&&n.closePath(),!0}if(r===L.TRIANGLE){let o=e.dims.x,i=e.dims.y;return!(o>0)||!(i>0)?!1:(n.moveTo(0,-i/2),n.lineTo(o/2,i/2),n.lineTo(-o/2,i/2),n.closePath(),!0)}if(r===L.ELLIPSE||r===L.CIRCLE){let o=(r===L.CIRCLE?Number(t.radius):Number(t.rx))||0,i=(r===L.CIRCLE?Number(t.radius):Number(t.ry))||0;return!(o>0)||!(i>0)?!1:(n.ellipse(0,0,o,i,0,0,Math.PI*2),!0)}if(r===L.LINE||r===L.REFERENCELINE){let o=Number(t.x1),i=Number(t.y1),s=Number(t.x2),a=Number(t.y2);return!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)?!1:(n.moveTo(o,i),n.lineTo(s,a),!0)}if(r===L.RECT||r===L.FABRICRECT){let o=e.dims.x,i=e.dims.y;if(!(o>0)||!(i>0))return!1;let s=it(t,o,i);return s?jn(n,o,i,s.rx,s.ry):n.rect(-o/2,-i/2,o,i),!0}return!1},Ju=(n,e)=>{let t=Ei(n.raw);if(!t)return null;let r=se(n.raw);if(r===L.ARROW||r===L.DIMENSION)return ig(n,t,e);let o=Math.abs(n.matrix[0])*n.dims.x+Math.abs(n.matrix[2])*n.dims.y,i=Math.abs(n.matrix[1])*n.dims.x+Math.abs(n.matrix[3])*n.dims.y,s=tg(t,n),a=o+s*2,l=i+s*2;if(!(a>0)||!(l>0)||a>8192||l>8192)return null;let u=e?e.zoom*e.dpr:1,c=Zu(u,a,l),h=Math.ceil(a*c),d=Math.ceil(l*c);if(!(h>0)||!(d>0))return null;let f=document.createElement("canvas");f.width=h,f.height=d;let m=f.getContext("2d");if(!m)return null;let p=n.matrix,b=e&&c===u?Ci(p,e.zoom,e.dpr,e.vpt,a,l):null,g=b?b.lx:p[4]-a/2,x=b?b.ly:p[5]-l/2,S=h/c,w=d/c,y=[p[0]*c,p[1]*c,p[2]*c,p[3]*c,(p[4]-g)*c,(p[5]-x)*c];if(m.setTransform(y[0],y[1],y[2],y[3],y[4],y[5]),!xr(m,n))return null;let v=y;if(t.uniform){let R=Math.hypot(p[0],p[1])||1,P=Math.hypot(p[2],p[3])||1;v=j(y,[1/R,0,0,1/P,0,0])}if(m.setTransform(v[0],v[1],v[2],v[3],v[4],v[5]),m.lineWidth=t.width,m.lineCap=t.lineCap,m.lineDashOffset=t.dashOffset,m.lineJoin=t.lineJoin,m.miterLimit=t.miterLimit,t.dashArray&&m.setLineDash(t.dashArray),m.strokeStyle=t.color,t.alignment==="outside"||t.alignment==="inside"){if(m.lineWidth=t.width*2,t.alignment==="inside")m.clip(),m.stroke();else{m.stroke(),m.globalCompositeOperation="destination-out";let R=to(n,m);typeof n.raw.fill=="string"&&n.raw.fill!==""&&n.raw.fill!=="transparent"||m.clip(),m.fillStyle=R,m.fill(),m.globalCompositeOperation="source-over"}return{canvas:f,w:S,h:w,lx:g,ly:x,sceneW:a,sceneH:l,snapped:!!b}}return m.stroke(),{canvas:f,w:S,h:w,lx:g,ly:x,sceneW:a,sceneH:l,snapped:!!b}},to=(n,e)=>{let t=n.raw.fill;if(typeof t=="string"&&t)return t;if(t&&typeof t=="object"&&t.type==="linear"){let r=t,o=r.coords??{},i=n.dims.x,s=n.dims.y,a=r.gradientUnits==="percentage"?i:1,l=r.gradientUnits==="percentage"?s:1,u=e.createLinearGradient((o.x1??0)*a+(r.offsetX??0),(o.y1??0)*l+(r.offsetY??0),(o.x2??0)*a+(r.offsetX??0),(o.y2??0)*l+(r.offsetY??0));for(let c of r.colorStops??[])typeof c?.offset=="number"&&typeof c?.color=="string"&&u.addColorStop(Math.min(1,Math.max(0,c.offset)),c.color);return u}return rg(n)},rg=n=>{let e=n.raw.stroke;return typeof e=="string"&&e?e:"#000"},og=n=>{let e=Number(n.raw.x1),t=Number(n.raw.y1),r=Number(n.raw.x2),o=Number(n.raw.y2);return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o)?null:{x1:e,y1:t,x2:r,y2:o}},ig=(n,e,t)=>{let r=og(n);if(!r)return null;let o=n.raw,s=se(o)===L.ARROW,a=Number(o.strokeWidth)||1,l=typeof o.stroke=="string"?o.stroke:"#000000",u=Array.isArray(o.strokeDashArray)?o.strokeDashArray:null,c=Math.ceil(a*2+8),h=null,d=Number(o.arrowWidth)||15,f=Number(o.arrowHeight)||22.5,m=o.arrowType==="start"||o.arrowType==="both"?o.arrowType:(o.arrowType==="end","end"),p=Math.sqrt(a),b=d*p,g=f*p;if(s)c=Math.ceil(c+g+b);else{let Y=Number(o.textFontSize)||50,X=typeof o.text=="string"&&o.text.trim()?o.text:"50cm",Z=Number(o.textPadding)||4,B=`${Y}px Arial, sans-serif`,q=no(B,X)+Z*2,U=Math.atan2(r.y2-r.y1,r.x2-r.x1),oe=-Math.sin(U),ne=Math.cos(U),de=Y+a/2+5;h={text:X,fontPx:Y,w:q,h:Y+Z*2,cx:(r.x1+r.x2)/2+oe*de,cy:(r.y1+r.y2)/2+ne*de,angle:o.textFollowLine===!1?0:U,color:typeof o.textColor=="string"?o.textColor:"#333333",bg:typeof o.textBackgroundColor=="string"?o.textBackgroundColor:"#ffffff",pad:Z,follow:o.textFollowLine!==!1},c=Math.ceil(c+de+Math.max(q,Y*2)*.75)}let x=Math.abs(n.matrix[0])*n.dims.x+Math.abs(n.matrix[2])*n.dims.y,S=Math.abs(n.matrix[1])*n.dims.x+Math.abs(n.matrix[3])*n.dims.y,w=x+c*2,y=S+c*2;if(!(w>0)||!(y>0)||w>8192||y>8192)return null;let v=t?t.zoom*t.dpr:1,R=Zu(v,w,y),P=Math.ceil(w*R),T=Math.ceil(y*R);if(!(P>0)||!(T>0))return null;let C=document.createElement("canvas");C.width=P,C.height=T;let E=C.getContext("2d");if(!E)return null;let M=n.matrix,k=t&&R===v?Ci(M,t.zoom,t.dpr,t.vpt,w,y):null,A=k?k.lx:M[4]-w/2,O=k?k.ly:M[5]-y/2,F=[M[0]*R,M[1]*R,M[2]*R,M[3]*R,(M[4]-A)*R,(M[5]-O)*R];E.setTransform(F[0],F[1],F[2],F[3],F[4],F[5]);let W=r.x2-r.x1,z=r.y2-r.y1,_=Math.atan2(z,W),D=Math.cos(_),I=Math.sin(_);if(s){let Y=m==="start"||m==="both",X=m==="end"||m==="both",Z=r.x1+D*(Y?g:0),B=r.y1+I*(Y?g:0),q=r.x2-D*(X?g:0),U=r.y2-I*(X?g:0);E.lineWidth=a,E.strokeStyle=l,u&&u.length>0?E.setLineDash(u):E.setLineDash([]),E.beginPath(),E.moveTo(Z,B),E.lineTo(q,U),E.stroke(),E.setLineDash([]);let oe=(ne,de,Pe)=>{E.save(),E.translate(ne,de),E.rotate(Pe),E.beginPath(),E.moveTo(0,0),E.lineTo(-g,-b/2),E.lineTo(-g,b/2),E.closePath(),E.fillStyle=l,E.fill(),E.restore()};return X&&oe(r.x2,r.y2,_),Y&&oe(r.x1,r.y1,_+Math.PI),{canvas:C,w:P/R,h:T/R,lx:A,ly:O,sceneW:w,sceneH:y,snapped:!!k}}E.beginPath(),E.moveTo(r.x1,r.y1),E.lineTo(r.x2,r.y2);let G=F;if(e.uniform){let Y=Math.hypot(M[0],M[1])||1,X=Math.hypot(M[2],M[3])||1;G=j(F,[1/Y,0,0,1/X,0,0])}E.setTransform(G[0],G[1],G[2],G[3],G[4],G[5]),E.lineWidth=e.width,E.lineCap=e.lineCap,E.lineDashOffset=e.dashOffset,E.lineJoin=e.lineJoin,E.miterLimit=e.miterLimit,e.dashArray&&E.setLineDash(e.dashArray),E.strokeStyle=l,E.stroke(),E.setTransform(F[0],F[1],F[2],F[3],F[4],F[5]);let $=-I,V=D,H=(Number(o.textFontSize)||50)/2;E.lineWidth=a,E.lineCap="round",e.dashArray&&E.setLineDash([]),E.strokeStyle=l;for(let[Y,X]of[[r.x1,r.y1],[r.x2,r.y2]])E.beginPath(),E.moveTo(Y-$*H,X-V*H),E.lineTo(Y+$*H,X+V*H),E.stroke();return h&&(E.save(),E.translate(h.cx,h.cy),h.follow&&E.rotate(h.angle),E.font=`${h.fontPx}px Arial, sans-serif`,E.textAlign="center",E.textBaseline="middle",h.bg&&(E.fillStyle=h.bg,E.fillRect(-h.w/2,-h.h/2,h.w,h.h)),E.fillStyle=h.color,E.fillText(h.text,0,0),E.restore()),{canvas:C,w:P/R,h:T/R,lx:A,ly:O,sceneW:w,sceneH:y,snapped:!!k}},no=(n,e)=>{let t=document.createElement("canvas").getContext("2d");return t?(t.font=n,t.measureText(e).width):e.length*50};var fe={LEFT:"left",CENTER:"center",RIGHT:"right",JUSTIFY:"justify",JUSTIFY_LEFT:"justify-left",JUSTIFY_CENTER:"justify-center",JUSTIFY_RIGHT:"justify-right",DISPERSE:"disperse"},sg=Object.values(fe),$t=n=>n===fe.JUSTIFY||n===fe.JUSTIFY_LEFT||n===fe.JUSTIFY_CENTER||n===fe.JUSTIFY_RIGHT,sl=n=>n===fe.JUSTIFY_LEFT||n===fe.JUSTIFY_CENTER||n===fe.JUSTIFY_RIGHT,ro=n=>n===fe.JUSTIFY||n===fe.DISPERSE;var eh=400,Mi=1.13,Ri=.222,ag=2,lg={underline:.1,linethrough:-.28167,overline:-.81333},cg=66.667,ug=/[a-zA-Z.\s]+/,hg=/[0-9]/,dg=/[()[\]{}></:;:,.?!]/,so=n=>ug.test(n)||hg.test(n)||dg.test(n),fg=new Set(["ー","「","」","『","』","(",")","〔","〕","[","]","{","}","⦅","⦆","〈","〉","《","》","【","】","〖","〗","〘","〙","〚","〛","゛","゜","。","、","・","゠","=","〜","…","•","‥","◦","﹅","﹆"]),mg=new Set(["「","」","『","』","〔","〕","[","]","{","}","⦅","⦆","〈","〉","《","》","【","】","〖","〗","〘","〙","〚","〛","(",")"]),qn=n=>so(n)?"latin":mg.has(n)?"bracket":fg.has(n)?"symbol":"cjk",Kn=(n,e,t)=>so(n)?e.width:e.height+t,un=n=>n/1.1,yr=(n,e,t)=>n==="symbol"?-t/3.14:e.height/2-t/3.14,wt=(n,e,t)=>n===0||t%2===0?0:n/300*e*.5,ih=(n,e,t)=>{if(n===0)return 0;let r=e.fontSize;for(let o of t)for(let i of o.charStyles){let s=i?.fontSize;typeof s=="number"&&s>r&&(r=s)}return Math.abs(n)/300*r*.5},oo=null,sh=(n,e,t)=>{let r={left:0,right:0,ascent:t*.88,descent:t*.24};if(typeof document>"u")return r;if(!oo){let i=document.createElement("canvas");i.width=8,i.height=8,oo=i.getContext("2d")}if(!oo)return r;oo.font=n;let o=oo.measureText(e);return o.actualBoundingBoxAscent===void 0||o.actualBoundingBoxDescent===void 0?r:{left:-(o.actualBoundingBoxLeft??0),right:o.actualBoundingBoxRight??0,ascent:o.actualBoundingBoxAscent,descent:o.actualBoundingBoxDescent}},th=new WeakMap,cl=new Set,nh=(n,e,t)=>{let r=th.get(n);r||(r=new Map,th.set(n,r),cl.add(r));let o=`${Me(e,e.fontSize)}|${t}`,i=r.get(o);return i||(i=n(Me(e,e.fontSize),t,e.fontSize),r.set(o,i)),i},ah=(n,e,t=sh)=>{let r=e.charSpacing?e.fontSize*e.charSpacing/1e3:0,o=0,i=0,s=0;for(let a=0;a<n.graphemes.length;a++){let l=n.graphemes[a],u=n.boxes[a],c=ch(e,n.charStyles[a]),h=qn(l),d,f;if(h==="latin"||h==="bracket"){let m=h==="latin"?u.kernedWidth-u.width:0,p=nh(t,c,l);d=p.left+m,f=p.right+m}else{let m=nh(t,c,l);d=un(c.fontSize)-m.ascent,f=un(c.fontSize)+m.descent}a===0&&(i=d),s=o+f,o+=Kn(l,u,r)}return{start:i,end:s}},ul=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong","inherit","initial","unset"]),Pi=(n,e,t={})=>{let r=1/0,o=-1/0,i=1/0;for(let a of n.lines){if(a.width<=0||a.graphemes.length===0)continue;let l,u;if(t.vertical){let c=ah(a,e,t.inkMeasure);l=a.leftOffset+c.start,u=a.leftOffset+c.end}else{let c=a.boxes[a.boxes.length-1];l=a.leftOffset,u=a.leftOffset+Math.max(a.width,c.left+c.width)}u>l&&(r=Math.min(r,l),o=Math.max(o,u),i=Math.min(i,a.top))}if(!(o>r)||!Number.isFinite(i))return null;let s=t.align===void 0?{lo:r,hi:o}:pg(r,o,n.width,t.align);return{lo:s.lo,hi:s.hi,firstTop:i}},pg=(n,e,t,r)=>!(t>0)||!Number.isFinite(t)?{lo:n,hi:e}:r===fe.CENTER||r===fe.JUSTIFY_CENTER?{lo:Math.min(0,n),hi:Math.max(t,e)}:r===fe.RIGHT||r===fe.JUSTIFY_RIGHT?{lo:n,hi:Math.max(t,e)}:{lo:Math.min(0,n),hi:e},Me=(n,e)=>{let t=n.fontFamily,r=t.includes("'")||t.includes('"')||t.includes(",")||ul.has(t.toLowerCase())?t:`"${t}"`;return`${n.fontStyle??"normal"} ${n.fontWeight??"normal"} ${e}px ${r}`},bg=(n,e)=>{if(n)return n.id===0?`${e+1}`:n.content||void 0},Oe=(n,e)=>{let t=e?.stroke??n?.color,r=e?.strokeWidth??n?.width;return!t||!r?null:{color:t,width:r,lineJoin:n?.lineJoin,miterLimit:n?.miterLimit,lineCap:n?.lineCap}},ao=/[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/,hn=n=>{let e=n.boxes[n.boxes.length-1];return e?e.left+e.width:0},Tt=(n,e,t,r,o={})=>{let i=e.prefix;if(!i)return 0;let s=n.font;return n.font=Me(i.style,i.style.fontSize),o.fill&&(o.fill!=="keep"&&(n.fillStyle=o.fill),n.fillText(i.text,t,r)),o.stroke&&o.stroke.width>0&&(n.lineWidth=o.stroke.width,n.strokeStyle=o.stroke.color,n.strokeText(i.text,t,r)),n.font=s,i.width},hl=(n,e,t)=>{let r=[],o=!!t[e],i=S=>!!(n.charStyles[S]?.[e]??o);if(!n.graphemes.some((S,w)=>i(w)))return r;let s=S=>n.charStyles[S]?.fill??t.fill??"",a=S=>n.charStyles[S]?.textDecorationThickness??t.textDecorationThickness??cg,l=S=>n.charStyles[S]?.fontSize??t.fontSize,u=lg[e],c=e==="linethrough"?.5:e==="overline"?1:0,h=t.charSpacing?t.fontSize*t.charSpacing/1e3:0,d=(S,w,y,v,R,P)=>{if(!S||!w||!y||P<=0)return;let T=t.fontSize*y/1e3;r.push({x:R,width:P,y:u*v-c*T,thickness:T,color:w})},f=0,m=0,p=i(0),b=s(0),g=a(0),x=l(0);for(let S=0;S<n.graphemes.length;S++){let w=i(S),y=s(S),v=a(S),R=l(S),P=n.boxes[S],T=t.vertical?so(n.graphemes[S])?P.kernedWidth:P.height:P.kernedWidth;(w!==p||y!==b||v!==g||R!==x)&&m>0?(d(p,b,g,x,f,m),f=P.left,m=t.vertical?T:P.width,p=w,b=y,g=v,x=R):m+=t.vertical?T:P.kernedWidth}return d(p,b,g,x,f,m-h),r},io=null,gg=(n,e)=>{if(typeof document>"u")return 0;if(!io){let t=document.createElement("canvas");if(t.width=8,t.height=8,io=t.getContext("2d"),!io)return 0}return io.font=n,io.measureText(e).width},Nt=n=>Array.from(n),xg=n=>n.split(/[ \t\r]/),al=class{constructor(e,t){this.decl=e;this.measure=t}decl;measure;charWidths=new Map;coupleWidths=new Map;charWidth(e){let t=this.charWidths.get(e);return t===void 0&&(t=this.measure(this.decl,e),this.charWidths.set(e,t)),t}coupleWidth(e,t){let r=e+"\0"+t,o=this.coupleWidths.get(r);return o===void 0&&(o=this.measure(this.decl,e+t),this.coupleWidths.set(r,o)),o}},rh=new WeakMap,yg=(n,e)=>{let t=rh.get(e);t||(t=new Map,rh.set(e,t),cl.add(t));let r=t.get(n);return r||(r=new al(n,e),t.set(n,r)),r},lh=()=>{for(let n of cl)n.clear()},ch=(n,e)=>!e||e.fontSize===void 0&&e.fontFamily===void 0&&e.fontWeight===void 0&&e.fontStyle===void 0?n:{...n,fontSize:e.fontSize??n.fontSize,fontFamily:e.fontFamily??n.fontFamily,fontWeight:e.fontWeight??n.fontWeight,fontStyle:e.fontStyle??n.fontStyle},ll=(n,e,t,r,o)=>{let i=yg(Me(e,eh),n),s=e.fontSize/eh,a=i.charWidth(t),l=a;return r&&o&&Me(o,o.fontSize)===Me(e,e.fontSize)&&(l=i.coupleWidth(r,t)-i.charWidth(r)),{width:a*s,kernedWidth:l*s}},uh=n=>n.charSpacing?n.fontSize*n.charSpacing/1e3:0,oh=(n,e,t,r,o,i,s,a=!1)=>{let l=uh(o),u=[],c=" ",h=0,d=[],f=0,m=!0,p=0,b=Math.max(e,r,ag),g=t[n];for(let x=0;x<g.length;x++){let S=g[x].graphemes,w=g[x].width;p+=S.length,h+=(a?0:f)+w-l,h>b&&!m?(u.push(d),d=[],h=w,m=!0):h+=l,!m&&!a&&d.push(c),d=d.concat(S),f=a?0:ll(s,i(n,p),c).kernedWidth+l,p++,m=!1}return g.length&&u.push(d),u},jt=(n,e,t={})=>{let r=t.measure??gg,o=t.inkMeasure??sh,i=t.styles,s=(E,M)=>ch(e,i?.[E]?.[M]),a=uh(e),l=e.lineHeight??1.16,u=(E,M,k)=>{let A=0,O;for(let F=0;F<E.length;F++){let W=ll(r,s(M,k+F),E[F],O,F>0?s(M,k+F-1):void 0);A+=W.kernedWidth+a,O=E[F]}return A},c=(n??"").split(`
3
- `),h,d=0;if(t.boxWidth==null)h=c.map(E=>Nt(E));else if(t.splitByGrapheme){let E=[];for(let M=0;M<c.length;M++){let k=Nt(c[M]);if(k.length===0){E.push([{graphemes:[],width:0,charOffset:0}]);continue}let A=k.map((O,F)=>{let W=u([O],M,F);return d=Math.max(W,d),{graphemes:[O],width:W,charOffset:F}});E.push(A)}h=[];for(let M=0;M<E.length;M++)h.push(...oh(M,t.boxWidth,E,d,e,s,r,!0))}else{let E=[];for(let M=0;M<c.length;M++){let k=[],A=0;for(let O of xg(c[M])){let F=Nt(O),W=u(F,M,A);d=Math.max(W,d),k.push({graphemes:F,width:W,charOffset:A}),A+=F.length+1}E.push(k)}h=[];for(let M=0;M<E.length;M++)h.push(...oh(M,t.boxWidth,E,d,e,s,r))}let f=Nt(n??""),m=[];{let E=0,M=0,k=0;for(let A=0;A<h.length;A++){let O=f[k];O===`
4
- `&&A>0?(M=0,k++,E++):A>0&&!t.splitByGrapheme&&/[ \t\r]/.test(O??"")&&(M++,k++),m[A]={line:E,offset:M,flatStart:k},k+=h[A].length,M+=h[A].length}}let p=h.map((E,M)=>{let k=m[M],A=[],O=0;for(let _=0;_<E.length;_++){let D=ll(r,s(k.line,k.offset+_),E[_],_>0?E[_-1]:void 0,_>0?s(k.line,k.offset+_-1):void 0),I={left:0,width:D.width+a,kernedWidth:D.kernedWidth+a,height:s(k.line,k.offset+_).fontSize};_>0&&(I.left=A[_-1].left+A[_-1].width+D.kernedWidth-D.width),A.push(I),t.vertical&&!so(E[_])?O+=I.height:O+=I.kernedWidth}a!==0&&(O-=a),O<0&&(O=0);let F=E.map((_,D)=>i?.[k.line]?.[k.offset+D]),W=0;if(E.length>0)for(let _=0;_<E.length;_++)W=Math.max(W,i?.[k.line]?.[k.offset+_]?.fontSize??e.fontSize);else W=i?.[k.line]?.[k.offset]?.fontSize??e.fontSize;let z;if(t.paragraph){let _=bg(t.paragraph,M);if(_){let D=s(k.line,k.offset),I=Me(D,D.fontSize),G=r(I,_);if(G>0){z={text:_,width:G,advances:Nt(_).map($=>r(I,$)),style:D};for(let $ of A)$.left+=z.width;O+=z.width}}}return{graphemes:E,boxes:A,width:O,leftOffset:0,baseline:0,top:0,implHeight:W*Mi,styleMap:k,charStyles:F,prefix:z}}),b=0,g=0;for(let E=0;E<p.length;E++){let M=p[E].implHeight,k=E===p.length-1;p[E].top=g,p[E].baseline=g+M*(1-Ri),g+=M*l,b+=k?M:M*l}let x=t.boxWidth!=null?Math.max(t.boxWidth,d-a):0,S=()=>{let E=0;for(let M of p){let k=0;for(let A=0;A<M.graphemes.length;A++)k+=so(M.graphemes[A])?M.boxes[A].width+a:M.boxes[A].height+a;E=Math.max(E,k)}return E+2},w=t.vertical?S():void 0,y=t.boxWidth!=null?x:t.vertical?w:Math.max(0,...p.map(E=>E.width)),v=e.textAlign??fe.LEFT,R=E=>{if(t.boxWidth==null)return E===p.length-1;let M=p[E+1]?.styleMap;return!M||M.line!==p[E].styleMap.line};for(let E=0;E<p.length;E++){let M=v===fe.CENTER||v===fe.JUSTIFY_CENTER&&R(E),k=v===fe.RIGHT||v===fe.JUSTIFY_RIGHT&&R(E);if(t.vertical&&(M||k)&&p[E].graphemes.length>0){let O=ah(p[E],e,o);p[E].leftOffset=M?(y-O.start-O.end)/2:y-O.end;continue}let A=y-p[E].width;M?p[E].leftOffset=A/2:k&&(p[E].leftOffset=A)}let P=v===fe.DISPERSE;if(($t(v)||P)&&!t.vertical)for(let E=0;E<p.length;E++){let M=p[E],k=sl(v);if(k&&(E===p.length-1||R(E))||!k&&!P&&E===p.length-1||M.width>=y)continue;let A=!k&&M.graphemes.some(z=>ao.test(z)),O=A?M.graphemes.length-1:M.graphemes.reduce((z,_)=>/[ \t\r]/.test(_)?z+1:z,0);if(O<=0)continue;let F=(y-M.width)/O,W=0;for(let z=0;z<M.graphemes.length;z++){let _=M.boxes[z],D=A?z<M.graphemes.length-1:/[ \t\r]/.test(M.graphemes[z]);_.left+=W,D&&(_.width+=F,_.kernedWidth+=F,W+=F)}}let T=[],C=0;for(let E of f)T.push(C),C+=E.length;return T.push(C),{lines:p,width:y,height:b,graphemeCodeUnitOffsets:T,verticalWidth:w}};var Sg={arc:"arc",circle:"circle",waist:"waist",flag:"flag",arch:"arch",scroll:"scroll"},vg={[L.ARCTEXT]:"arc",[L.CIRCLETEXT]:"circle",[L.WAISTTEXT]:"waist",[L.FLAGTEXT]:"flag",[L.ARCHTEXT]:"arch",[L.SCROLLTEXT]:"scroll"},Ge=n=>{let e=n.textTransform;if(typeof e=="string"){let t=Sg[e];if(t)return t}return vg[se(n)]??null},wg=new Set(["arc","circle","waist","flag","arch"]),hh=n=>{let e=Ge(n);return e!=null&&wg.has(e)},Sr=n=>{if(!(Number(n.warpStrength)||0))return null;let t=Ge(n);return t==="arch"||t==="waist"||t==="flag"?t:null},dh=(n,e,t,r,o)=>{if(!(r.hi>r.lo))return null;let i=Math.max(-1,Math.min(1,Number(t.warpStrength)||0)),s=Number(t.fontSize)||40,a=typeof t.height=="number"?t.height:0,l=Math.max(a,s),u=-e.width/2+r.lo,c=-e.width/2+r.hi,h=o+r.firstTop,d=o+e.height,f=d-h;if(n==="arch"){if(i<=0)return{left:u,right:c,top:h,bottom:d};let b=l*i/2;return{left:u,right:c,top:d+b-f*(1+i),bottom:d+b}}if(n==="flag"){let b=Math.abs(i)*(a||s)*.3,g=Math.abs(i)*b;return{left:u,right:c,top:h-g,bottom:d+g}}let m=(h+d)/2,p=f/2*(1+.5*Math.abs(i));return{left:u,right:c,top:m-p,bottom:m+p}};var Tg=1e4,lo=2,fh=(n,e)=>{let t=e-n;for(;t>=2*Math.PI;)t-=2*Math.PI;for(;t<=0;)t+=2*Math.PI;return t},ki=(n,e,t)=>fh(n,e)+fh(e,t)<2*Math.PI,Ai=(n,e,t,r)=>{let o=n.x,i=n.y,s=o,a=i;e.x<o&&(o=e.x),e.x>s&&(s=e.x),e.y<i&&(i=e.y),e.y>a&&(a=e.y);let l=Math.atan2(n.y-t.y,n.x-t.x),u=Math.atan2(e.y-t.y,e.x-t.x);if(ki(l,0,u)){let c=t.x+r;c>s&&(s=c)}if(ki(l,Math.PI/2,u)){let c=t.y+r;c>a&&(a=c)}if(ki(l,Math.PI,u)){let c=t.x-r;c<o&&(o=c)}if(ki(l,Math.PI*3/2,u)){let c=t.y-r;c<i&&(i=c)}return{x:o,y:i,width:s-o,height:a-i}},Xe=n=>{let e=Ge(n);return e==="arc"||e==="circle"?e:null},mh=n=>n.lines.map(e=>{let t=e.boxes.map(o=>({left:o.left,width:o.width})),r=t[t.length-1];return t.push(r?{left:r.left+r.width,width:0}:{left:0,width:0}),t}),Eg=(n,e,t)=>{let r=mh(n),o=n.width,i=P=>n.lines[P].implHeight*e,s=0;for(let P=0;P<n.lines.length;P++)s+=i(P);let a=Math.abs(t),l=a*Math.PI/180,u=0;for(let P=0;P<n.lines.length;P++)u+=n.lines[P].width;let c=l>0?u/l:0,h=Math.max(Tg/Math.max(a,.1),c),d=0,f=t>0?s/2+h:-s/2+h,m=t>0?s:0,p=1/0,b=-1/0,g=1/0,x=-1/0,S=[];for(let P=0;P<r.length;P++){let T=-o/2+n.lines[P].leftOffset,C=i(P),E=C-C/e+C*Ri/e;m+=t>0?-C:C;let M=Math.abs(h)+m,k=t>0?M+C-C/e:M-C+C/e,A=[];for(let D=0;D<r[P].length;D++){let I=r[P][D],G,$,V,H,Y,X,Z;t>0?(G=M,$=M+C,V=M+E,H=(G*3+$*2)/5,Y=-(T+I.left)/H,X=-(T+I.left+I.width)/H,Z=-(T+I.left+I.width/2)/H):(G=M,$=M-C,V=M-E,H=(G*2+$*3)/5,Y=Math.PI+(T+I.left)/H,X=Math.PI+(T+I.left+I.width)/H,Z=Math.PI+(T+I.left+I.width/2)/H);let B=Math.sin(X),q=Math.cos(X),U=Math.sin(Y),oe=Math.cos(Y),ne=Math.sin(Z),de=Math.cos(Z);A.push({tl:{x:d-$*U,y:f-$*oe},tr:{x:d-$*B,y:f-$*q},nl:{x:d-k*U,y:f-k*oe},nr:{x:d-k*B,y:f-k*q}});let Pe=n.lines[P].graphemes[D];Pe!==void 0&&S.push({char:Pe,line:P,index:D,x:d-V*ne,y:f-V*de,rotation:t>0?-Z:-Z-Math.PI})}let O=A[0],F=A[A.length-1];if(!O||!F)continue;let W={x:d,y:f},z=t>0?Ai(O.tl,F.tr,W,M+C):Ai(F.tr,O.tl,W,M-C),_=t>0?Ai(O.nl,F.nr,W,M):Ai(F.nr,O.nl,W,M);p=Math.min(p,z.x,_.x),b=Math.max(b,z.x+z.width,_.x+_.width),g=Math.min(g,z.y,_.y),x=Math.max(x,z.y+z.height,_.y+_.height)}Number.isFinite(p)||(p=b=g=x=0);let w=-p-o/2,y=b-o/2,v=-g-s/2,R=x-s/2;return{width:Math.max(o+w+y,lo),height:s+v+R,contentOffsetX:y/2-w/2,contentOffsetY:R/2-v/2,chars:S}},Cg=(n,e,t)=>{let r=mh(n),o=C=>n.lines[C].implHeight*e,i=0;for(let C=0;C<n.lines.length;C++)i+=o(C);let s=n.width,a=Math.max(t.size,1),l=Math.min(Math.max(t.eccentricity,0),.95),u=a*(1-l),c=Math.max(t.sweep,1)*(Math.PI/180),h=t.startAngle*(Math.PI/180),d=t.horizontal,f=0;for(let C=0;C<n.lines.length;C++)f+=n.lines[C].width;let m=0,p=0;if(f<=0||r.length===0)return{width:lo,height:Math.max(i,lo),contentOffsetX:0,contentOffsetY:0,chars:[]};let b=1/0,g=-1/0,x=1/0,S=-1/0,w=[],y=0;for(let C=0;C<r.length;C++){let E=o(C),M=E-E/e+E*Ri/e,k=E-M;for(let A=0;A<r[C].length;A++){let O=r[C][A],W=(y+O.left+O.width/2)/f,z=h-W*c,_=Math.sin(z),D=Math.cos(z),I=m-a*_,G=p-u*D,$,V,H,Y,X;if(d)$=0,V=1,H=0,Y=0,X=-1;else{let U=a*D,oe=-u*_,ne=Math.hypot(U,oe)||1;V=U/ne,H=oe/ne;let de=-u*_,Pe=-a*D,De=Math.hypot(de,Pe)||1;Y=de/De,X=Pe/De,$=Math.atan2(oe,U)}let Z=-$,B=O.width/2;b=Math.min(b,I-Y*M-V*B,I-Y*M+V*B,I+Y*k-V*B,I+Y*k+V*B),g=Math.max(g,I-Y*M-V*B,I-Y*M+V*B,I+Y*k-V*B,I+Y*k+V*B),x=Math.min(x,G-X*M-H*B,G-X*M+H*B,G+X*k-H*B,G+X*k+H*B),S=Math.max(S,G-X*M-H*B,G-X*M+H*B,G+X*k-H*B,G+X*k+H*B);let q=n.lines[C].graphemes[A];q!==void 0&&w.push({char:q,line:C,index:A,x:I,y:G,rotation:-Z})}y+=n.lines[C].width}Number.isFinite(b)||(b=g=x=S=0);let v=-b-s/2,R=g-s/2,P=-x-i/2,T=S-i/2;return{width:Math.max(g-b,lo),height:Math.max(S-x,lo),contentOffsetX:R/2-v/2,contentOffsetY:T/2-P/2,chars:w}},Et=(n,e,t)=>Ge(e)==="circle"?Cg(n,t,{size:typeof e.circleSize=="number"?e.circleSize:40,startAngle:typeof e.circleStartAngle=="number"?e.circleStartAngle:0,sweep:typeof e.circleSweep=="number"?e.circleSweep:360,eccentricity:typeof e.circleEccentricity=="number"?e.circleEccentricity:0,horizontal:e.circleDirection==="horizontal"}):Eg(n,t,typeof e.curvature=="number"?e.curvature:300);var ph=(n,e)=>{let t=1-e;return n===2?[t,e,0,0]:n===3?[t*t,2*t*e,e*e,0]:[t*t*t,3*t*t*e,3*t*e*e,e*e*e]},dn=(n,e,t,r,o,i)=>{let s={uOrder:Math.min(4,Math.max(2,o)),vOrder:Math.min(4,Math.max(2,i)),xs:[],ys:[]};for(let a=0;a<s.vOrder;a++){let l=s.vOrder===1?0:a/(s.vOrder-1);for(let u=0;u<s.uOrder;u++){let c=s.uOrder===1?0:u/(s.uOrder-1);s.xs.push(n+(t-n)*c),s.ys.push(e+(r-e)*l)}}return s},Ni=(n,e,t)=>{let r=ph(n.uOrder,e),o=ph(n.vOrder,t),i=0,s=0;for(let a=0;a<n.vOrder;a++)for(let l=0;l<n.uOrder;l++){let u=r[l]*o[a];i+=u*n.xs[a*n.uOrder+l],s+=u*n.ys[a*n.uOrder+l]}return{x:i,y:s}},Qn=(n,e,t,r,o,i)=>{let s=Math.sin(o),a=Math.cos(o),l=(t-e)/(2*s),u=4/3*Math.tan(o/2)*l,c=i?-u*s:u*s;n.xs.push(e,e+u*a,t-u*a,t),n.ys.push(r,r+c,r+c,r)},mt=(n,e,t)=>{n.xs.push(0,e/3,2*e/3,e),n.ys.push(t,t,t,t)},dl=(n,e)=>{let t={uOrder:n.uOrder,vOrder:n.vOrder,xs:[],ys:[]};for(let r=0;r<n.vOrder;r++){let o=n.vOrder-1-r;for(let i=0;i<n.uOrder;i++){let s=r*n.uOrder+i,a=o*n.uOrder+i;t.xs[s]=n.xs[a],t.ys[s]=e-n.ys[a]}}return t},Mg=n=>{let e={uOrder:n.vOrder,vOrder:n.uOrder,xs:[],ys:[]};for(let t=0;t<n.vOrder;t++)for(let r=0;r<n.uOrder;r++){let o=t*n.uOrder+r,i=r*n.vOrder+t;e.xs[i]=n.ys[o],e.ys[i]=n.xs[o]}return e},bh=(n,e,t,r)=>{let o=Math.min(100,Math.max(-100,e)),i=Math.abs(o)*Math.PI/200,s=2*r*o/100,a={uOrder:4,vOrder:n==="wave"?3:2,xs:[],ys:[]};if(n==="arcLower"||n==="arcUpper")return Math.abs(o)<1e-9?dn(0,0,t,r,4,2):(mt(a,t,0),Qn(a,0,t,r,i,o<0),n==="arcUpper"?dl(a,r):a);if(n==="fish")return mt(a,t,0),mt(a,t,r),a.ys[1]-=s,a.ys[2]+=s,a.ys[5]+=s,a.ys[6]-=s,a;if(n==="fisheye"){a=dn(0,0,t,r,4,4);let l=o/50;for(let u=1;u<=2;u++)for(let c=1;c<=2;c++){let h=u*4+c,d=c===1?0:t,f=u===1?0:r;a.xs[h]+=l*(d-a.xs[h]),a.ys[h]+=l*(f-a.ys[h])}return a}if(n==="inflate"||n==="squeeze"){a=dn(0,0,t,r,3,3);let l=t*o/200,u=r*o/200;return a.ys[1]-=u,a.ys[7]+=u,n==="inflate"?(a.xs[3]-=l,a.xs[5]+=l):(a.xs[3]+=l,a.xs[5]-=l),a}if(n==="twist"){a=dn(0,0,t,r,4,4);let l=t*Math.abs(o)/100,u=r*Math.abs(o)/100;return o>0?(a.xs[5]+=l,a.ys[6]+=u,a.xs[10]-=l,a.ys[9]-=u):o<0&&(a.ys[5]+=u,a.xs[6]-=l,a.ys[10]-=u,a.xs[9]+=l),a}if(n==="shellLower"||n==="shellUpper"){if(Math.abs(o)<1e-9)return dn(0,0,t,r,4,4);let l=Math.sin(i),u=Math.cos(i);if(a={uOrder:4,vOrder:4,xs:[],ys:[]},mt(a,t,0),mt(a,t,r/3),o>0){let c=2*r/3;a.xs.push(-c*l,t/3,2*t/3,t+c*l),a.ys.push(c*u,2*r/3,2*r/3,c*u),Qn(a,-r*l,t+r*l,r*u,i,!1)}else{let c=r/3;a.xs.push(-c*l,t/3,2*t/3,t+c*l),a.ys.push(r-c*u,2*r/3,2*r/3,r-c*u),Qn(a,0,t,r,i,!0)}return n==="shellUpper"?dl(a,r):a}if(n==="arc"){if(Math.abs(o)<1e-9)return dn(0,0,t,r,4,2);let l=Math.sin(i);return Qn(a,-r*l,t+r*l,r*(1-Math.cos(i)),i,!0),Qn(a,0,t,r,i,!0),o<0?dl(a,r):a}if(n==="arch"||n==="bulge"){if(Math.abs(o)<1e-9)return dn(0,0,t,r,4,2);let l=o>0;return Qn(a,0,t,0,i,l),Qn(a,0,t,r,i,n==="bulge"?!l:l),a}if(n==="flag")return mt(a,t,0),mt(a,t,r),a.ys[1]-=s,a.ys[2]+=s,a.ys[5]-=s,a.ys[6]+=s,a;if(n==="wave")return mt(a,t,0),mt(a,t,r/2),mt(a,t,r),a.ys[5]+=s,a.ys[6]-=s,a;if(n==="rise")return mt(a,t,0),mt(a,t,r),a.ys[0]+=s,a.ys[1]+=s,a.ys[4]+=s,a.ys[5]+=s,a},fl=n=>n==="arc"||n==="arch"||n==="bulge"||n==="flag"||n==="wave"||n==="rise"||n==="arcLower"||n==="arcUpper"||n==="shellLower"||n==="shellUpper"||n==="fish"||n==="fisheye"||n==="inflate"||n==="squeeze"||n==="twist",gh=(n,e,t,r,o)=>{if(!fl(n)||r<=0||o<=0)return;if(!t||n==="twist")return bh(n,e,r,o);let i=bh(n,e,o,r);return i?Mg(i):void 0},xh=(n,e,t)=>{let r=Math.min(100,Math.max(-100,t)),o=Math.min(100,Math.max(-100,e));if(r!==0&&n.vOrder>1)for(let i=0;i<n.vOrder;i++){let s=i*n.uOrder,a=s+n.uOrder-1,l=(n.xs[s]+n.xs[a])/2,u=(n.ys[s]+n.ys[a])/2,h=1+(2*(i/(n.vOrder-1))-1)*r/100;for(let d=0;d<n.uOrder;d++){let f=s+d;n.xs[f]=l+(n.xs[f]-l)*h,n.ys[f]=u+(n.ys[f]-u)*h}}if(o!==0&&n.uOrder>1)for(let i=0;i<n.uOrder;i++){let s=i,a=(n.vOrder-1)*n.uOrder+i,l=(n.xs[s]+n.xs[a])/2,u=(n.ys[s]+n.ys[a])/2,h=1+(2*(i/(n.uOrder-1))-1)*o/100;for(let d=0;d<n.vOrder;d++){let f=d*n.uOrder+i;n.xs[f]=l+(n.xs[f]-l)*h,n.ys[f]=u+(n.ys[f]-u)*h}}},ml=(n,e,t)=>{let r=gh(n.style,n.bend,n.rotate==="vertical",e,t);if(r)return xh(r,n.horizontal,n.vertical),r},Zn=n=>{if(n===null||typeof n!="object")return null;let t=n.psdWarp;if(t===null||typeof t!="object")return null;let r=t,o=typeof r.style=="string"?r.style:"";if(!fl(o))return null;let i=Number(r.bend)||0,s=Number(r.horizontal)||0,a=Number(r.vertical)||0;return i===0&&s===0&&a===0?null:{style:o,bend:i,horizontal:s,vertical:a,rotate:r.rotate==="vertical"?"vertical":"horizontal"}},pl=(n,e,t,r,o,i,s,a,l,u,c,h,d,f)=>{let m=r-e,p=o-t,b=a-i,g=l-s;if(m<=0||p<=0||b<=0||g<=0||u<=0||c<=0||d<=0||n.xs.length===0)return;let x=(i-e)/m,S=(a-e)/m,w=(s-t)/p,y=(l-t)/p,v=(W,z)=>{let _=Ni(n,W,z);return{x:h[0]*_.x+h[2]*_.y+h[4],y:h[1]*_.x+h[3]*_.y+h[5]}},R=0,P=0,T=0,C=0,E=!0,M=8;for(let W=0;W<=M;W++){let z=w+(y-w)*W/M;for(let _=0;_<=M;_++){let D=x+(S-x)*_/M,I=v(D,z);E?(R=P=I.x,T=C=I.y,E=!1):(R=Math.min(R,I.x),P=Math.max(P,I.x),T=Math.min(T,I.y),C=Math.max(C,I.y))}}let k=Math.max(8,f),A=Math.min(k,Math.max(8,Math.ceil((P-R)/d))),O=Math.min(k,Math.max(8,Math.ceil((C-T)/d))),F={columns:A+1,rows:O+1,docXs:[],docYs:[],sourceXs:[],sourceYs:[]};for(let W=0;W<F.rows;W++){let z=W/O;for(let _=0;_<F.columns;_++){let D=_/A,I=v(x+(S-x)*D,w+(y-w)*z);F.docXs.push(I.x),F.docYs.push(I.y),F.sourceXs.push(D*u),F.sourceYs.push(z*c)}}return F},bl=(n,e,t,r,o,i,s,a,l,u)=>{let c=o-t,h=i-r,d=l-t,f=u-r,m=t-o-l+s,p=r-i-u+a,b=n-t,g=e-r,x=c*p-h*m,S=c*f-h*d-(b*p-g*m),w=-(b*f-g*d),y;if(Math.abs(x)<1e-9){if(Math.abs(S)<1e-9)return;y=-w/S}else{let T=S*S-4*x*w;if(T<0)return;let C=Math.sqrt(T),E=(-S+C)/(2*x),M=(-S-C)/(2*x),k=E>=-1e-9&&E<=1+1e-9,A=M>=-1e-9&&M<=1+1e-9;if(k&&A)y=Math.min(Math.max(E,0),1);else if(k)y=E;else if(A)y=M;else return}let v=d+m*y,R=f+p*y,P;if(Math.abs(v)>=Math.abs(R)){if(Math.abs(v)<1e-9)return;P=(b-c*y)/v}else{if(Math.abs(R)<1e-9)return;P=(g-h*y)/R}if(!(y<-1e-9||y>1.000000001||P<-1e-9||P>1.000000001))return{s:Math.min(Math.max(y,0),1),t:Math.min(Math.max(P,0),1)}};var Rg=(n,e)=>{let t=n.boxes;if(t.length===0)return{left:0,width:0,kernedWidth:0,height:e};let r=t[t.length-1];return{left:r.left+r.width,width:0,kernedWidth:0,height:e}},Li=(n,e,t)=>e<0?null:e<n.boxes.length?n.boxes[e]:e===n.boxes.length?Rg(n,t):null,Pg=(n,e,t)=>{if(!Array.isArray(t)||t.length===0)return[];let r=0;for(let h of t){if(!h||typeof h.text!="string")return[];r+=h.text.length}if(r!==n.length)return[];let o=[],i=[];for(let h=0;h<e.lines.length;h++){let d=e.lines[h].graphemes.length;for(let f=0;f<d;f++)i.push(f),o.push(h)}let s=[],a=0;for(let h=0;h<n.length;h++)n[h]===`
1
+ var _e={enabled:!1,metrics:new Map,counters:new Map,sampleRate:1,reportIntervalMs:5e3,reportTimer:null},Su=()=>performance.now(),Sb=()=>typeof window>"u"?!1:window.location.search.includes("canvasPerf=1"),vb=n=>{let e=_e.metrics.get(n);return e||(e={count:0,total:0,max:0,last:0},_e.metrics.set(n,e)),e},wb=(n,e)=>e>0?n/e:0,za=()=>[..._e.metrics.entries()].map(([n,e])=>({name:n,count:e.count,totalMs:Number(e.total.toFixed(2)),avgMs:Number(wb(e.total,e.count).toFixed(3)),maxMs:Number(e.max.toFixed(3)),lastMs:Number(e.last.toFixed(3))})).sort((n,e)=>e.totalMs-n.totalMs),Ya=()=>[..._e.counters.entries()].map(([n,e])=>({name:n,count:e})).sort((n,e)=>e.count-n.count),Tb=()=>({type:"canvas-perf",timestamp:new Date().toISOString(),enabled:_e.enabled,metrics:za(),counters:Ya()}),vu=()=>JSON.stringify(Tb()),Eb=()=>{let n=za(),e=Ya(),t=["[canvas-perf] report"];if(n.length){t.push("metrics:");for(let r of n)t.push(`- ${r.name}: count=${r.count}, totalMs=${r.totalMs}, avgMs=${r.avgMs}, maxMs=${r.maxMs}, lastMs=${r.lastMs}`)}else t.push("metrics: none");if(e.length){t.push("counters:");for(let r of e)t.push(`- ${r.name}: count=${r.count}`)}else t.push("counters: none");return t.join(`
2
+ `)},wu=()=>{let n=vu();if(!_e.enabled)return n;let e=za(),t=Ya();return console.info(n),console.groupCollapsed("[canvas-perf] report details"),e.length?console.table(e):console.log("no timing metrics"),t.length&&console.table(t),console.groupEnd(),n},Cb=()=>{typeof window>"u"||!_e.enabled||_e.reportTimer!=null||(_e.reportTimer=window.setInterval(wu,_e.reportIntervalMs))},Mb=()=>{_e.reportTimer!=null&&(window.clearInterval(_e.reportTimer),_e.reportTimer=null)},Xa=n=>{_e.enabled=n,n?(Cb(),console.info("[canvas-perf] enabled")):(Mb(),console.info("[canvas-perf] disabled"))},Tu=()=>_e.enabled,Rb=()=>{_e.metrics.clear(),_e.counters.clear()},Eu=(n,e=1)=>{_e.enabled&&_e.counters.set(n,(_e.counters.get(n)||0)+e)},li=(n,e)=>{if(!_e.enabled)return;let t=vb(n);t.count+=1,t.total+=e,t.max=Math.max(t.max,e),t.last=e},Ua=(n,e)=>{if(!_e.enabled)return e();let t=Su();try{return e()}finally{li(n,Su()-t)}};var Cu=()=>{typeof window>"u"||window.__YFT_CANVAS_PERF__||(window.__YFT_CANVAS_PERF__={enable:()=>Xa(!0),disable:()=>Xa(!1),report:wu,reportJson:vu,reportText:Eb,reset:Rb,mark:Eu,time:Ua,isEnabled:Tu},Sb()&&Xa(!0))};var Hn=class{_handlers=new Map;on(e,t){let r=this._handlers.get(e);r||(r=new Set,this._handlers.set(e,r));let o=t;return r.add(o),()=>this.off(e,o)}once(e,t){let r=t,o=(...i)=>{this.off(e,o),r(...i)};return this.on(e,o)}off(e,t){if(!t){this._handlers.delete(e);return}this._handlers.get(e)?.delete(t)}fire(e,...t){let r=this._handlers.get(e);if(!(!r||r.size===0))for(let o of[...r])o(...t)}clear(){this._handlers.clear()}};var mr=n=>n*Math.PI/180,j=(n,e,t=!1)=>[n[0]*e[0]+n[2]*e[1],n[1]*e[0]+n[3]*e[1],n[0]*e[2]+n[2]*e[3],n[1]*e[2]+n[3]*e[3],t?0:n[0]*e[4]+n[2]*e[5]+n[4],t?0:n[1]*e[4]+n[3]*e[5]+n[5]],ve=n=>{let e=1/(n[0]*n[3]-n[1]*n[2]),t=[e*n[3],-e*n[1],-e*n[2],e*n[0],0,0],r=t[0]*n[4]+t[2]*n[5],o=t[1]*n[4]+t[3]*n[5];return t[4]=-r,t[5]=-o,t},Q=(n,e,t,r=!1)=>({x:n[0]*e+n[2]*t+(r?0:n[4]),y:n[1]*e+n[3]*t+(r?0:n[5])}),Pb=n=>n[0]===1&&n[1]===0&&n[2]===0&&n[3]===1&&n[4]===0&&n[5]===0,ci=n=>{if(typeof n=="number")return n-.5;switch(n){case"left":case"top":return-.5;case"right":case"bottom":return .5;default:return 0}},kb=n=>{let e=mr(n),t=Math.cos(e),r=Math.sin(e);return[t,r,-r,t,0,0]},Mu=n=>{let{scaleX:e=1,scaleY:t=1,flipX:r=!1,flipY:o=!1,skewX:i=0,skewY:s=0}=n,a=[r?-e:e,0,0,o?-t:t,0,0];return i&&(a=j(a,[1,0,Math.tan(mr(i)),1,0,0],!0)),s&&(a=j(a,[1,Math.tan(mr(s)),0,1,0,0],!0)),a},At=n=>{let{translateX:e=0,translateY:t=0,angle:r=0}=n,o=[1,0,0,1,e,t];r&&(o=j(o,kb(r)));let i=Mu(n);return Pb(i)||(o=j(o,i)),o},Ab=(n,e,t)=>{let r=n/2,o=e/2,i=[],s=[];for(let[a,l]of[[-r,-o],[r,-o],[-r,o],[r,o]]){let u=Q(t,a,l,!0);i.push(u.x),s.push(u.y)}return{x:Math.max(...i)-Math.min(...i),y:Math.max(...s)-Math.min(...s)}},ui=n=>{let{width:e=0,height:t=0,scaleX:r=1,scaleY:o=1,skewX:i=0,skewY:s=0,strokeWidth:a=0,strokeUniform:l}=n,u=l?0:a,c=l?a:0,h=e+u,d=t+u,f;return i===0&&s===0?f={x:h*r,y:d*o}:f=Ab(h,d,Mu(n)),{x:f.x+c,y:f.y+c}},Gn=n=>{let e=Ut(n);return At({...n,translateX:e.x,translateY:e.y})},Ut=n=>{let e=ui(n),t=-ci(n.originX??"left")*e.x,r=-ci(n.originY??"top")*e.y,o=n.angle??0;if(o){let i=mr(o),s=Math.cos(i),a=Math.sin(i),l=t*s-r*a,u=t*a+r*s;t=l,r=u}return{x:(n.left??0)+t,y:(n.top??0)+r}},ge=(n,e)=>{let t=ui(n),r=-ci(n.originX??"left")*t.x,o=-ci(n.originY??"top")*t.y,i=n.angle??0;if(i){let s=mr(i),a=Math.cos(s),l=Math.sin(s),u=r*a-o*l,c=r*l+o*a;r=u,o=c}return{x:e.x-r,y:e.y-o}},Nb=n=>{let e=a=>a*180/Math.PI,t=e(Math.atan2(n[1],n[0])),r=n[0]*n[0]+n[1]*n[1],o=Math.sqrt(r),i=r===0?0:(n[0]*n[3]-n[2]*n[1])/o,s=r===0?0:e(Math.atan2(n[0]*n[2]+n[1]*n[3],r));return{angle:t,scaleX:o,scaleY:i,skewX:s,skewY:0,center:{x:n[4],y:n[5]}}},$a=n=>{let e=Ut(n),t=mr(n.angle??0),r=Math.cos(t),o=Math.sin(t),i=ui(n),s=i.x/2,a=i.y/2,l=(u,c)=>({x:e.x+r*u-o*c,y:e.y+o*u+r*c});return{tl:l(-s,-a),tr:l(s,-a),br:l(s,a),bl:l(-s,a)}},Xn=n=>{let e=[n.tl.x,n.tr.x,n.br.x,n.bl.x],t=[n.tl.y,n.tr.y,n.br.y,n.bl.y],r=Math.min(...e),o=Math.min(...t);return{left:r,top:o,right:Math.max(...e),bottom:Math.max(...t),width:Math.max(...e)-r,height:Math.max(...t)-o}},Zr=(n,e,t,r)=>{let o=Math.max(1,e*r),i=Math.max(1,t*r),s=[2/o,0,0,-2/i,-1,1];return j(s,j([r,0,0,r,0,0],n))};var ht=(n,e=!1)=>{if(typeof window>"u")return e;let t=new URLSearchParams(window.location.search).get(n);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;let r=window.localStorage.getItem(`engine.${n}`);return r==="1"?!0:r==="0"?!1:e},Ru=()=>ht("gpuShadow",!0),ja=()=>ht("gpuPsdShadow",!0),Va=()=>ht("gpuPsdFill",!0),Pu=()=>ht("stencilClip",!0),qa=()=>{if(typeof window>"u")return!0;let n=new URLSearchParams(window.location.search).get("snapGuide");return!(n==="0"||n==="false")},ku=()=>ht("arcGlyph",!0),Lb=()=>ht("export",!0),Ka=()=>ht("retained",!0),zn=()=>ht("retainedDebug",!1),hi=()=>ht("sdfDash",!0),Au=()=>ht("sdfPolygon",!0),Nu=()=>ht("sdfLineDeco",!0),Ib=()=>ht("svgexport",!0);var _b={transparent:"#0000",aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},Lu=n=>{if(n.length===3||n.length===4){let e=parseInt(n[0]+n[0],16)/255,t=parseInt(n[1]+n[1],16)/255,r=parseInt(n[2]+n[2],16)/255,o=n.length===4?parseInt(n[3]+n[3],16)/255:1;return[e,t,r,o]}if(n.length===6||n.length===8){let e=parseInt(n.slice(0,2),16)/255,t=parseInt(n.slice(2,4),16)/255,r=parseInt(n.slice(4,6),16)/255,o=n.length===8?parseInt(n.slice(6,8),16)/255:1;return[e,t,r,o]}return[0,0,0,0]},Db=Object.fromEntries(Object.entries(_b).map(([n,e])=>[n,Lu(e.slice(1))])),Jr=n=>Math.min(1,Math.max(0,n)),Fb=65536,di=new Map,ee=n=>{if(!n)return[0,0,0,0];if(Array.isArray(n))return n;if(typeof n!="string")return[0,0,0,0];let e=di.get(n);if(e)return e;let t=Ob(n);return di.size>=Fb&&di.clear(),di.set(n,t),t},Ob=n=>{let e=n.trim().toLowerCase(),t=Db[e];if(t)return t;if(e.startsWith("#"))return Lu(e.slice(1));let r=e.match(/^(rgba?|hsla?)\(([^)]+)\)$/);if(r){let o=r[2].split(/[\s,/]+/).filter(Boolean);if(r[1].startsWith("rgb")&&o.length>=3){let i=s=>s.endsWith("%")?parseFloat(s)/100*255:parseFloat(s);return[Jr(i(o[0])/255),Jr(i(o[1])/255),Jr(i(o[2])/255),o[3]!==void 0?Jr(parseFloat(o[3])):1]}if(r[1].startsWith("hsl")&&o.length>=3){let i=parseFloat(o[0])/360,s=parseFloat(o[1])/100,a=parseFloat(o[2])/100,l=(d,f,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<1/6?d+(f-d)*6*m:m<1/2?f:m<2/3?d+(f-d)*(2/3-m)*6:d),u=a<.5?a*(1+s):a+s-a*s,c=2*a-u,h=o[3]!==void 0?Jr(parseFloat(o[3])):1;return[l(c,u,i+1/3),l(c,u,i),l(c,u,i-1/3),h]}}return[0,0,0,0]};var Yn=n=>{if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n,t=e.type;if(typeof t!="string"||t==="pattern")return null;let r=t==="linear"?"linear":"radial",o=e.coords??{},i=Array.isArray(e.colorStops)?e.colorStops:[],s=[];for(let a of i){if(!a||typeof a!="object")continue;let l=a,u=ee(l.color),c=typeof l.opacity=="number"?l.opacity:1;s.push({offset:Number(l.offset)||0,color:[u[0],u[1],u[2],u[3]*c]})}return s.length===0?null:(s.sort((a,l)=>a.offset-l.offset),{kind:r,x1:Number(o.x1)||0,y1:Number(o.y1)||0,x2:Number(o.x2)||0,y2:Number(o.y2)||0,r1:Math.max(0,Number(o.r1)||0),r2:Math.max(0,Number(o.r2)||0),stops:s,offsetX:Number(e.offsetX)||0,offsetY:Number(e.offsetY)||0,gradientUnits:e.gradientUnits==="percentage"?"percentage":"pixels",gradientTransform:Array.isArray(e.gradientTransform)&&e.gradientTransform.length===6?[...e.gradientTransform]:null})},fi=(n,e,t)=>{let r=[1,0,0,1,-e/2+n.offsetX,-t/2+n.offsetY];return n.gradientUnits==="percentage"&&(r=j(r,[e,0,0,t,0,0])),n.gradientTransform&&(r=j(r,n.gradientTransform)),r};var Iu=(n,e)=>{let t=n.x2-n.x1,r=n.y2-n.y1,o=t*t+r*r;return o<=0?0:((e.x-n.x1)*t+(e.y-n.y1)*r)/o},_u=(n,e)=>{let t=n.x2-n.x1,r=n.y2-n.y1,o=n.r2-n.r1,i=e.x-n.x1,s=e.y-n.y1,a=t*t+r*r-o*o,l=2*(-(t*i+r*s)-n.r1*o),u=i*i+s*s-n.r1*n.r1;if(Math.abs(a)<1e-9)return Math.abs(l)>1e-9?-u/l:0;let c=Math.max(0,l*l-4*a*u);return(-l-Math.sqrt(c))/(2*a)},mi=(n,e=512)=>{let t=new Uint8Array(e*4),r=n.stops,o=i=>Math.round(Math.min(255,Math.max(0,i*255)));for(let i=0;i<e;i++){let s=i/(e-1),a;if(s<=r[0].offset)a=r[0].color;else if(s>=r[r.length-1].offset)a=r[r.length-1].color;else{let l=r[0],u=r[1];for(let h=0;h<r.length-1;h++)if(s>=r[h].offset&&s<=r[h+1].offset){l=r[h],u=r[h+1];break}let c=u.offset===l.offset?0:(s-l.offset)/(u.offset-l.offset);a=[l.color[0]+(u.color[0]-l.color[0])*c,l.color[1]+(u.color[1]-l.color[1])*c,l.color[2]+(u.color[2]-l.color[2])*c,l.color[3]+(u.color[3]-l.color[3])*c]}t[i*4]=o(a[0]),t[i*4+1]=o(a[1]),t[i*4+2]=o(a[2]),t[i*4+3]=o(a[3])}return t},pi=n=>{let e=r=>String(Math.round(r*1e4)/1e4),t=n.stops.map(r=>`${e(r.offset)}:${r.color.map(o=>e(o)).join(",")}`).join(";");return[n.kind,e(n.x1),e(n.y1),e(n.x2),e(n.y2),e(n.r1),e(n.r2),t,e(n.offsetX),e(n.offsetY),n.gradientUnits,n.gradientTransform?n.gradientTransform.map(e).join(","):""].join("|")};var Bb=["repeat","repeat-x","repeat-y","no-repeat"],pr=n=>{if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;if(e.type!=="pattern"||typeof e.source!="string"||!e.source)return null;let t=Bb.includes(e.repeat)?e.repeat:"repeat";return{kind:"pattern",src:e.source,repeat:t,offsetX:Number(e.offsetX)||0,offsetY:Number(e.offsetY)||0,patternTransform:Array.isArray(e.patternTransform)&&e.patternTransform.length===6?[...e.patternTransform]:null,crossOrigin:typeof e.crossOrigin=="string"?e.crossOrigin:null}},bi=(n,e,t)=>{let r=[1,0,0,1,-e/2+n.offsetX,-t/2+n.offsetY];return n.patternTransform&&(r=j(r,n.patternTransform)),r},Du=n=>[n==="repeat"||n==="repeat-x",n==="repeat"||n==="repeat-y"];var L={TEXTBOX:"textbox",TEXT:"text",ITEXT:"i-text",INPUTTEXT:"itext",ARCHTEXT:"archtext",WAISTTEXT:"waisttext",FLAGTEXT:"flagtext",ARCTEXT:"arctext",CIRCLETEXT:"circletext",SCROLLTEXT:"scrolltext",TEXTIMAGE:"textimage",IMAGE:"image",SVGIMAGE:"svgimage",CROPIMAGE:"cropimage",ECHART:"echart",FABRIC_ECHART:"fabricechart",QRCODE:"qrcode",BARCODE:"barcode",MASK:"mask",PATH:"path",RECT:"rect",FABRICRECT:"fabricrect",LINE:"line",ARROW:"arrow",POLYLINE:"polyline",POLYGON:"polygon",ELLIPSE:"ellipse",CIRCLE:"circle",TRIANGLE:"triangle",TABLE:"table",GROUP:"group",ACTIVE_SELECTION:"activeselection",PUZZLE:"puzzle",GIF:"gif",VIDEO:"video",DIMENSION:"dimension",REFERENCELINE:"referenceline"},se=n=>{let e=n?.type;return typeof e=="string"?e.toLowerCase():""},an=new Set([L.TEXTBOX,L.INPUTTEXT,L.ITEXT,L.TEXT,L.ARCHTEXT,L.WAISTTEXT,L.FLAGTEXT,L.ARCTEXT,L.CIRCLETEXT,L.SCROLLTEXT,L.TEXTIMAGE]),dt=new Set([L.IMAGE,L.SVGIMAGE,L.CROPIMAGE,L.QRCODE,L.BARCODE,L.ECHART,L.FABRIC_ECHART]),Un=new Set([L.ELLIPSE,L.CIRCLE,L.POLYGON,L.POLYLINE,L.PATH,L.TRIANGLE]),ft=new Set([L.LINE,L.ARROW,L.DIMENSION,L.REFERENCELINE]),$n=new Set([L.RECT,L.FABRICRECT]),ot=new Set([L.MASK]),gi=new Set([L.PUZZLE]),xi=new Set([L.GIF]),yi=new Set([L.VIDEO]);var ln=1-.5522847498,Qa=new Set([L.FABRICRECT]),cn=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,Za=(n,e,t)=>{let r=cn(n,0);return r>0?{rx:r/(cn(e,1)||1),ry:r/(cn(t,1)||1)}:null},Fu=n=>{if(!Qa.has(se(n)))return;let e=Za(n.radius,n.scaleX,n.scaleY);e&&(n.rx=e.rx,n.ry=e.ry)},Ou=(n,e)=>{if(!Qa.has(se(n)))return!1;let t="radius"in e,r="scaleX"in e||"scaleY"in e,o=cn(n.radius,0)>0&&("rx"in e||"ry"in e);if(!t&&!r&&!o)return!1;let i=t?e.radius:n.radius,s="scaleX"in e?e.scaleX:n.scaleX,a="scaleY"in e?e.scaleY:n.scaleY,l=Za(i,s,a);return e.rx=l?l.rx:0,e.ry=l?l.ry:0,!0},it=(n,e,t)=>{if(!(e>0)||!(t>0))return null;let r=Qa.has(se(n))?Za(n.radius,n.scaleX,n.scaleY):null,o=r?r.rx:cn(n.rx,0),i=r?r.ry:cn(n.ry,0);o>0&&!(i>0)&&(i=o);let s=Math.min(o,e/2),a=Math.min(i,t/2);return s>0||a>0?{rx:s,ry:a}:null},br=(n,e,t)=>{if(!(e>0)||!(t>0))return null;let r=Math.min(Math.max(cn(n.rx,0),cn(n.ry,0)),e/2,t/2);return r>0?r:null},jn=(n,e,t,r,o)=>{let i=Math.max(0,e),s=Math.max(0,t),a=Math.min(Math.max(0,r),i/2),l=Math.min(Math.max(0,o),s/2),u=-i/2,c=-s/2,h=a!==0||l!==0;n.beginPath(),n.moveTo(u+a,c),n.lineTo(u+i-a,c),h&&n.bezierCurveTo(u+i-ln*a,c,u+i,c+ln*l,u+i,c+l),n.lineTo(u+i,c+s-l),h&&n.bezierCurveTo(u+i,c+s-ln*l,u+i-ln*a,c+s,u+i-a,c+s),n.lineTo(u+a,c+s),h&&n.bezierCurveTo(u+ln*a,c+s,u,c+s-ln*l,u,c+s-l),n.lineTo(u,c+l),h&&n.bezierCurveTo(u,c+ln*l,u+ln*a,c,u+a,c),n.closePath()},Bu=(n,e,t,r)=>{let o=Math.max(0,n),i=Math.max(0,e);if(!(o>0)||!(i>0))return null;let s=Math.min(Math.max(0,t),o/2),a=Math.min(Math.max(0,r),i/2);if(!(s>0)&&!(a>0))return null;let l=Math.max(2,Math.min(16,Math.ceil((s+a)*.6))),u=[[o/2-s,-i/2+a,s,a,-Math.PI/2],[o/2-s,i/2-a,s,a,0],[-o/2+s,i/2-a,s,a,Math.PI/2],[-o/2+s,-i/2+a,s,a,Math.PI]],c=[0,0];for(let[f,m,p,b,g]of u)for(let x=0;x<l;x++){let S=g+x/l*(Math.PI/2);c.push(f+p*Math.cos(S),m+b*Math.sin(S))}let h=c.length/2-1,d=new Uint32Array(h*3);for(let f=0;f<h;f++)d[f*3]=0,d[f*3+1]=1+f,d[f*3+2]=1+(f+1)%h;return{verts:new Float32Array(c),triangles:d}};import Wb from"rbush";var Ne=1e-12,Hb=96,Si=(n,e,t,r,o,i)=>(t-n)*(i-e)-(r-e)*(o-n),Ja=(n,e,t,r)=>{if(Math.abs(r)>Ne)return!1;let o=e.x-n.x,i=e.y-n.y,s=o*o+i*i;if(s<Ne)return!0;let a=(t.x-n.x)*o+(t.y-n.y)*i;return a>=-Ne&&a<=s+Ne},gr=n=>{let e=0;for(let t=0;t<n.length;t++){let r=n[t],o=n[(t+1)%n.length];e+=r.x*o.y-o.x*r.y}return e/2},Wu=(n,e,t,r,o)=>{let i=n[e];if(Math.abs(i.x-t.x)<Ne&&Math.abs(i.y-t.y)<Ne||Math.abs(i.x-r.x)<Ne&&Math.abs(i.y-r.y)<Ne||Math.abs(i.x-o.x)<Ne&&Math.abs(i.y-o.y)<Ne)return!1;let s=Si(t.x,t.y,r.x,r.y,i.x,i.y),a=Si(r.x,r.y,o.x,o.y,i.x,i.y),l=Si(o.x,o.y,t.x,t.y,i.x,i.y);return s>Ne&&a>Ne&&l>Ne||s<-Ne&&a<-Ne&&l<-Ne?!0:Ja(t,r,i,s)||Ja(r,o,i,a)||Ja(o,t,i,l)},el=n=>{let e=n.length;if(e<3)return[];let t=gr(n);if(Math.abs(t)<Ne)return[];let r=new Array(e);for(let d=0;d<e;d++)r[d]=t>0?d:e-1-d;let o=[],i=r.length,s=i*i+16,a=0,l=null,u=null,c=null;if(e>=Hb){l=new Wb,u=new Array(e);for(let d=0;d<e;d++){let f=n[d];u[d]={minX:f.x,minY:f.y,maxX:f.x,maxY:f.y,v:d}}l.load(u),c=new Uint8Array(e).fill(1)}let h=0;for(;i>3&&s-- >0&&(a>=i&&(a=0),!(++h>i));){let d=r[a],f=r[(a+1)%i],m=r[(a+2)%i],p=n[d],b=n[f],g=n[m],x=Si(p.x,p.y,b.x,b.y,g.x,g.y);if(x>Ne){let S=!1;if(l&&u){let w=Math.min(p.x,b.x,g.x)-Ne,y=Math.max(p.x,b.x,g.x)+Ne,v=Math.min(p.y,b.y,g.y)-Ne,R=Math.max(p.y,b.y,g.y)+Ne,P=l.search({minX:w,minY:v,maxX:y,maxY:R});for(let T=0;T<P.length;T++){let C=P[T].v;if(c[C]&&!(C===d||C===f||C===m)&&Wu(n,C,p,b,g)){S=!0;break}}}else for(let w=3;w<i;w++){let y=r[(a+w)%i];if(Wu(n,y,p,b,g)){S=!0;break}}if(!S){o.push(d,f,m);let w=r.splice((a+1)%i,1)[0];i--,c&&(c[w]=0),h=0;continue}}else if(x>=-Ne){let S=r.splice((a+1)%i,1)[0];i--,c&&(c[S]=0),h=0;continue}a++}if(i>3)for(let d=1;d<i-1;d++)o.push(r[0],r[d],r[d+1]);else i===3&&o.push(r[0],r[1],r[2]);return o};var vi=Math.PI,Gb=Math.PI/180,ju=Math.PI/2,rl=n=>{if(n===0)return 1;switch(Math.abs(n)/ju){case 1:case 3:return 0;case 2:return-1}return Math.cos(n)},ol=n=>{if(n===0)return 0;let e=n/ju,t=Math.sign(n);switch(e){case 1:return t;case 2:return 0;case 3:return-t}return Math.sin(n)},Xb=/[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/gi,zb=/[mzlhvcsqta][^mzlhvcsqta]*/gi,Vn=/\s*,?\s*/,eo="([-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)",tl=new RegExp(`${Vn.source}${eo}${Vn.source}${eo}${Vn.source}${eo}${Vn.source}([01])${Vn.source}([01])${Vn.source}${eo}${Vn.source}${eo}`,"g"),Vu={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Yb={m:"l",M:"L"},Ub=n=>{let e=[],t=n.match(zb)??[];for(let r of t){let o=r[0];if(o==="z"||o==="Z"){e.push([o]);continue}let i=Vu[o.toLowerCase()],s=[];if(o==="a"||o==="A"){tl.lastIndex=0;for(let a=tl.exec(r);a;a=tl.exec(r))s=s.concat(a.slice(1))}else s=r.match(Xb)??[];for(let a=0;a<s.length;a+=i){let l=new Array(i),u=Yb[o];l[0]=a>0&&u?u:o;for(let c=0;c<i;c++)l[c+1]=parseFloat(s[a+c]);e.push(l)}}return e},Hu=(n,e,t,r)=>{let o=Math.atan2(e,n),i=Math.atan2(r,t);return i>=o?i-o:2*vi-(o-i)},$b=(n,e,t,r,o,i,s,a,l,u,c)=>{let h=rl(n),d=ol(n),f=rl(e),m=ol(e),p=t*o*f-r*i*m+s,b=r*o*f+t*i*m+a,g=u+l*(-t*o*d-r*i*h),x=c+l*(-r*o*d+t*i*h),S=p+l*(t*o*m+r*i*f),w=b+l*(r*o*m-t*i*f);return["C",g,x,S,w,p,b]},jb=(n,e,t,r,o,i,s)=>{if(t===0||r===0)return[];let a=0,l=0,u=0,c=s*Gb,h=ol(c),d=rl(c),f=.5*(-d*n-h*e),m=.5*(-d*e+h*n),p=t**2,b=r**2,g=m**2,x=f**2,S=p*b-p*g-b*x,w=Math.abs(t),y=Math.abs(r);if(S<0){let W=Math.sqrt(1-S/(p*b));w*=W,y*=W}else u=(o===i?-1:1)*Math.sqrt(S/(p*g+b*x));let v=u*w*m/y,R=-u*y*f/w,P=d*v-h*R+n*.5,T=h*v+d*R+e*.5,C=Hu(1,0,(f-v)/w,(m-R)/y),E=Hu((f-v)/w,(m-R)/y,(-f-v)/w,(-m-R)/y);i===0&&E>0?E-=2*vi:i===1&&E<0&&(E+=2*vi);let M=Math.ceil(Math.abs(E/vi*2)),k=[],A=E/M,O=8/3*Math.sin(A/4)*Math.sin(A/4)/Math.sin(A/2),F=C+A;for(let W=0;W<M;W++)k[W]=$b(C,F,d,h,w,y,P,T,O,a,l),a=k[W][5],l=k[W][6],C=F,F+=A;return k},Vb=(n,e,t,r,o,i,s,a,l)=>jb(a-n,l-e,t,r,i,s,o).map(u=>(u[1]=u[1]+n,u[2]=u[2]+e,u[3]=u[3]+n,u[4]=u[4]+e,u[5]=u[5]+n,u[6]=u[6]+e,u)),Gu=n=>{let e=0,t=0,r=0,o=0,i=[],s,a=0,l=0;for(let u of n){let c=[...u],h;switch(c[0]){case"l":c[1]+=e,c[2]+=t;case"L":e=c[1],t=c[2],h=["L",e,t];break;case"h":c[1]+=e;case"H":e=c[1],h=["L",e,t];break;case"v":c[1]+=t;case"V":t=c[1],h=["L",e,t];break;case"m":c[1]+=e,c[2]+=t;case"M":e=c[1],t=c[2],r=c[1],o=c[2],h=["M",e,t];break;case"c":c[1]+=e,c[2]+=t,c[3]+=e,c[4]+=t,c[5]+=e,c[6]+=t;case"C":a=c[3],l=c[4],e=c[5],t=c[6],h=["C",c[1],c[2],a,l,e,t];break;case"s":c[1]+=e,c[2]+=t,c[3]+=e,c[4]+=t;case"S":s==="C"?(a=2*e-a,l=2*t-l):(a=e,l=t),e=c[3],t=c[4],h=["C",a,l,c[1],c[2],e,t],a=h[3],l=h[4];break;case"q":c[1]+=e,c[2]+=t,c[3]+=e,c[4]+=t;case"Q":a=c[1],l=c[2],e=c[3],t=c[4],h=["Q",a,l,e,t];break;case"t":c[1]+=e,c[2]+=t;case"T":s==="Q"?(a=2*e-a,l=2*t-l):(a=e,l=t),e=c[1],t=c[2],h=["Q",a,l,e,t];break;case"a":c[6]+=e,c[7]+=t;case"A":for(let d of Vb(e,t,c[1],c[2],c[3],c[4],c[5],c[6],c[7]))i.push(d);e=c[6],t=c[7];break;case"z":case"Z":e=r,t=o,h=["Z"];break}h&&(i.push(h),s=h[0])}return i},Ce=n=>{if(typeof n=="string"){if(!n)return null;let e=Ub(n);return e.length>0?Gu(e):null}if(Array.isArray(n)){if(n.length===0)return null;let e=[];for(let t of n){if(!Array.isArray(t)||typeof t[0]!="string")continue;let r=t[0].toLowerCase();(r==="z"||Vu[r]!==void 0)&&e.push(t)}return e.length===0?null:Gu(e)}return null},Xu=(n,e,t,r,o,i,s,a)=>{let l=[],u=[],c=[],h=6*n-12*t+6*o,d=-3*n+9*t-9*o+3*s,f=3*t-3*n;for(let p=0;p<2;++p){if(p>0&&(h=6*e-12*r+6*i,d=-3*e+9*r-9*i+3*a,f=3*r-3*e),Math.abs(d)<1e-12){if(Math.abs(h)<1e-12)continue;let w=-f/h;0<w&&w<1&&l.push(w);continue}let b=h*h-4*f*d;if(b<0)continue;let g=Math.sqrt(b),x=(-h+g)/(2*d);0<x&&x<1&&l.push(x);let S=(-h-g)/(2*d);0<S&&S<1&&l.push(S)}let m=l.length;for(let p=0;p<m;p++){let b=l[p],g=b**3,x=3*b**2*(1-b),S=3*b*(1-b)**2,w=(1-b)**3;u.push(s*g+o*x+t*S+n*w),c.push(a*g+i*x+r*S+e*w)}return u.push(n,s),c.push(e,a),[{x:Math.min(...u),y:Math.min(...c)},{x:Math.max(...u),y:Math.max(...c)}]},Fe=n=>{let e=[],t=0,r=0,o=0,i=0;for(let c of n)switch(c[0]){case"L":o=c[1],i=c[2],e.push({x:t,y:r},{x:o,y:i});break;case"M":o=c[1],i=c[2],t=o,r=i;break;case"C":for(let h of Xu(o,i,c[1],c[2],c[3],c[4],c[5],c[6]))e.push(h);o=c[5],i=c[6];break;case"Q":for(let h of Xu(o,i,c[1],c[2],c[1],c[2],c[3],c[4]))e.push(h);o=c[3],i=c[4];break;case"Z":o=t,i=r;break}if(e.length===0)return null;let s=1/0,a=1/0,l=-1/0,u=-1/0;for(let c of e){if(!Number.isFinite(c.x)||!Number.isFinite(c.y))return null;s>c.x&&(s=c.x),a>c.y&&(a=c.y),l<c.x&&(l=c.x),u<c.y&&(u=c.y)}return{left:s,top:a,right:l,bottom:u}},qb=(n,e,t,r,o,i,s,a)=>{let l=s-n,u=a-e,c=l*l+u*u;if(c<1e-12)return Math.hypot(t-n,r-e)+Math.hypot(o-s,i-a);let h=Math.abs(l*(r-e)-u*(t-n)),d=Math.abs(l*(i-e)-u*(o-n));return(h+d)/Math.sqrt(c)},Ti=(n,e,t,r,o,i,s,a,l,u,c)=>{if(c>24){n.push({x:a,y:l});return}if(qb(e,t,r,o,i,s,a,l)<=u){n.push({x:a,y:l});return}let h=(e+r)/2,d=(t+o)/2,f=(r+i)/2,m=(o+s)/2,p=(i+a)/2,b=(s+l)/2,g=(h+f)/2,x=(d+m)/2,S=(f+p)/2,w=(m+b)/2,y=(g+S)/2,v=(x+w)/2;Ti(n,e,t,h,d,g,x,y,v,u,c+1),Ti(n,y,v,S,w,p,b,a,l,u,c+1)},qu=(n,e=.1)=>{let t=[],r=null,o=0,i=0,s=0,a=0;for(let l of n)switch(l[0]){case"M":{r&&r.length>=2&&t.push({points:r,closed:!1}),r=[{x:l[1],y:l[2]}],o=l[1],i=l[2],s=o,a=i;break}case"L":{o=l[1],i=l[2],(r??=[]).push({x:o,y:i});break}case"C":{Ti(r??=[],o,i,l[1],l[2],l[3],l[4],l[5],l[6],e,0),o=l[5],i=l[6];break}case"Q":{Ti(r??=[],o,i,o+2/3*(l[1]-o),i+2/3*(l[2]-i),l[3]+2/3*(l[1]-l[3]),l[4]+2/3*(l[2]-l[4]),l[3],l[4],e,0),o=l[3],i=l[4];break}case"Z":{if(r&&r.length>=2){let u=r[0],c=r[r.length-1];(Math.abs(u.x-c.x)>1e-9||Math.abs(u.y-c.y)>1e-9)&&r.push({x:u.x,y:u.y}),t.push({points:r,closed:!0})}r=null,o=s,i=a;break}}return r&&r.length>=2&&t.push({points:r,closed:!1}),t},zu=(n,e)=>{let t=!1;for(let r=0,o=e.length-1;r<e.length;o=r++){let i=e[o],s=e[r];s.y>n.y!=i.y>n.y&&n.x<(i.x-s.x)*(n.y-s.y)/(i.y-s.y)+s.x&&(t=!t)}return t},Kb=n=>{if(n.length<3)return[];let e=[];for(let i of n){let s=e[e.length-1];s&&Math.abs(i.x-s.x)<1e-9&&Math.abs(i.y-s.y)<1e-9||e.push(i)}if(e.length<3)return[];let t=e[0],r=e[e.length-1];if(Math.abs(t.x-r.x)<1e-9&&Math.abs(t.y-r.y)<1e-9&&e.pop(),e.length<3)return[];let o=new Map;for(let i=0;i<e.length;i++){let s=e[i],a=`${s.x},${s.y}`,l=o.get(a);if(l&&i-l.index>1){let u=e[i-1],c=s.x-u.x,h=s.y-u.y,d=Math.hypot(c,h)||1,f=(l.occurrence+1)*1e-6;e[i]={x:s.x+c/d*f,y:s.y+h/d*f}}else o.set(a,{index:i,occurrence:l?l.occurrence+1:0})}return e},Qb=(n,e,t,r)=>{let o=(e.x-n.x)*(r.y-n.y)-(e.y-n.y)*(r.x-n.x),i=(t.x-e.x)*(r.y-e.y)-(t.y-e.y)*(r.x-e.x),s=(n.x-t.x)*(r.y-t.y)-(n.y-t.y)*(r.x-t.x),a=o<-1e-12||i<-1e-12||s<-1e-12,l=o>1e-12||i>1e-12||s>1e-12;return!(a&&l)},Ku=(n,e,t,r)=>{let o=(e.x-n.x)*(r.y-t.y)-(e.y-n.y)*(r.x-t.x);if(Math.abs(o)<1e-12)return!1;let i=((t.x-n.x)*(r.y-t.y)-(t.y-n.y)*(r.x-t.x))/o,s=((t.x-n.x)*(e.y-n.y)-(t.y-n.y)*(e.x-n.x))/o;return i>1e-9&&i<1-1e-9&&s>1e-9&&s<1-1e-9},Yu=(n,e,t)=>{for(let r=0,o=e.length-1;r<e.length;o=r++){let i=e[o],s=e[r],a=s.x-i.x,l=s.y-i.y,u=a*a+l*l;if(u===0){if(Math.hypot(n.x-i.x,n.y-i.y)<=t)return!0;continue}let c=Math.min(1,Math.max(0,((n.x-i.x)*a+(n.y-i.y)*l)/u));if(Math.hypot(n.x-i.x-c*a,n.y-i.y-c*l)<=t)return!0}return!1},il=n=>{let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)i.x<e&&(e=i.x),i.x>r&&(r=i.x),i.y<t&&(t=i.y),i.y>o&&(o=i.y);return{minX:e,minY:t,maxX:r,maxY:o}},nl=(n,e,t)=>e.x>=n.minX-t&&e.x<=n.maxX+t&&e.y>=n.minY-t&&e.y<=n.maxY+t,Zb=n=>{let e=n.length,t=il(n),r=Math.max(8,Math.min(64,Math.ceil(Math.sqrt(e)))),o=Math.max(t.maxX-t.minX,1e-9)/r,i=Math.max(t.maxY-t.minY,1e-9)/r,s=new Array(r*r),a=l=>{let u=Math.max(0,Math.min(r-1,Math.floor((Math.min(l.pa.x,l.pb.x)-t.minX)/o))),c=Math.max(0,Math.min(r-1,Math.floor((Math.max(l.pa.x,l.pb.x)-t.minX)/o))),h=Math.max(0,Math.min(r-1,Math.floor((Math.min(l.pa.y,l.pb.y)-t.minY)/i))),d=Math.max(0,Math.min(r-1,Math.floor((Math.max(l.pa.y,l.pb.y)-t.minY)/i)));for(let f=h;f<=d;f++)for(let m=u;m<=c;m++)(s[f*r+m]??=[]).push(l)};for(let l=0;l<e;l++)a({pa:n[l],pb:n[(l+1)%e]});return{addEdge:(l,u)=>a({pa:l,pb:u}),blockedExcept(l,u){let c=Math.max(0,Math.min(r-1,Math.floor((Math.min(l.x,u.x)-t.minX)/o))),h=Math.max(0,Math.min(r-1,Math.floor((Math.max(l.x,u.x)-t.minX)/o))),d=Math.max(0,Math.min(r-1,Math.floor((Math.min(l.y,u.y)-t.minY)/i))),f=Math.max(0,Math.min(r-1,Math.floor((Math.max(l.y,u.y)-t.minY)/i)));for(let m=d;m<=f;m++)for(let p=c;p<=h;p++){let b=s[m*r+p];if(b){for(let g of b)if(!(g.pa===u||g.pb===u)&&Ku(l,u,g.pa,g.pb))return!0}}return!1}}},wi=(n,e,t)=>{let r=`${e.x},${e.y}`;n.set(r,(n.get(r)??0)+t)},Jb=(n,e,t,r,o)=>{let i=n.length,s=0;for(let y=1;y<e.length;y++)(e[y].x>e[s].x||e[y].x===e[s].x&&e[y].y>e[s].y)&&(s=y);let a=e[s],l=-1,u=1/0;for(let y=0;y<i;y++){let v=n[y],R=Math.hypot(v.x-a.x,v.y-a.y);if(R>=u||R<1e-7||(r.get(`${v.x},${v.y}`)??0)>1)continue;let P=t.blockedExcept(a,v);if(!P&&o.length>0){let T=v.x-a.x,C=v.y-a.y,E=T*T+C*C;for(let M of o){let k=M.x-a.x,A=M.y-a.y,O=(k*T+A*C)/E;if(O>1e-9&&O<1-1e-9&&Math.abs(k*C-A*T)<=1e-7*Math.sqrt(E)){P=!0;break}}}if(!P){for(let T=0;T<e.length;T++)if(!(T===s||(T+1)%e.length===s)&&Ku(a,v,e[T],e[(T+1)%e.length])){P=!0;break}}P||(u=R,l=y)}if(l>=0){let y=[];for(let v=l;v<i;v++)y.push(n[v]);for(let v=0;v<l;v++)y.push(n[v]);y.push(n[l]),y.push(a);for(let v=1;v<e.length;v++)y.push(e[(s+v)%e.length]);y.push(a),Uu(t,n[l],a,e),wi(r,n[l],1),wi(r,a,2);for(let v=0;v<e.length;v++)v!==s&&wi(r,e[v],1);return(r.get(`${n[l].x},${n[l].y}`)??0)>=2&&o.push(n[l]),o.push(a),y}let c=1/0,h=-1;for(let y=0;y<i;y++){let v=n[y],R=n[(y+1)%i];if(v.y!==R.y&&a.y>=Math.min(v.y,R.y)&&a.y<Math.max(v.y,R.y)){let P=(a.y-v.y)/(R.y-v.y),T=v.x+P*(R.x-v.x);T>=a.x&&T<c&&(c=T,h=y)}}if(h<0)return n;let d=n[h];l=n[(h+1)%i].x>d.x?(h+1)%i:h;let m=n[l],p={x:c,y:a.y},b=m.x-a.x,g=m.y-a.y,x=Math.hypot(b,g)||1,S=-1/0;for(let y=0;y<i;y++){if(y===l)continue;let v=n[y];if(!Qb(a,p,m,v))continue;let R=v.x-a.x,P=v.y-a.y,T=Math.hypot(R,P)||1,C=(R*b+P*g)/(T*x);(C>S+1e-12||Math.abs(C-S)<=1e-12&&T<u)&&(S=C,u=T,m=v,l=y)}let w=[];for(let y=l;y<i;y++)w.push(n[y]);for(let y=0;y<l;y++)w.push(n[y]);w.push(n[l]),w.push(a);for(let y=1;y<e.length;y++)w.push(e[(s+y)%e.length]);return w.push(a),Uu(t,n[l],a,e),w},Uu=(n,e,t,r)=>{n.addEdge(e,t);for(let o=0;o<r.length;o++)n.addEdge(r[o],r[(o+1)%r.length])},Qu=(n,e="evenodd")=>{let t=n.map(h=>Kb(h.points)).filter(h=>h.length>=3);if(t.length===0)return[];let r=t.map(h=>il(h)),o=h=>{let d=t[h],f=Math.max(1,Math.floor(d.length/8));for(let m=0;m<d.length;m+=f){let p=d[m],b=!1;for(let g=0;g<t.length;g++)if(g!==h&&nl(r[g],p,1e-6)&&Yu(p,t[g],1e-6)){b=!0;break}if(!b)return p}},i=t.map((h,d)=>o(d)),s=new Array(t.length).fill(0),a=t.map(()=>new Array(t.length).fill(!1));for(let h=0;h<t.length;h++){let d=i[h];if(d)for(let f=0;f<t.length;f++)h!==f&&nl(r[f],d,1e-6)&&(Yu(d,t[f],1e-6)||zu(d,t[f])&&(s[h]++,a[f][h]=!0))}let l=new Array(t.length);if(e==="evenodd")for(let h=0;h<t.length;h++)l[h]=s[h]%2===0;else for(let h=0;h<t.length;h++){let d=gr(t[h])>0?1:-1;for(let f=0;f<t.length;f++)f!==h&&a[f][h]&&(d+=gr(t[f])>0?1:-1);l[h]=d!==0}let u=[],c=[];for(let h=0;h<t.length;h++)l[h]?u.push({ring:t[h],index:h,bbox:r[h]}):c.push({ring:t[h],index:h,depth:s[h]});if(u.length===0)return[];c.sort((h,d)=>$u(d.ring)-$u(h.ring));for(let h of c){let d=i[h.index]??h.ring[0],f=u.find(p=>s[p.index]===h.depth-1&&nl(p.bbox,d,0)&&zu(d,p.ring));if(!f)continue;gr(f.ring)*gr(h.ring)>0&&(h.ring=h.ring.slice().reverse()),f.grid??=Zb(f.ring),f.coordCounts??=(()=>{let p=new Map;for(let b of f.ring)wi(p,b,1);return p})(),f.multiPts??=[],f.ring=Jb(f.ring,h.ring,f.grid,f.coordCounts,f.multiPts);let m=il(h.ring);f.bbox.minX=Math.min(f.bbox.minX,m.minX),f.bbox.minY=Math.min(f.bbox.minY,m.minY),f.bbox.maxX=Math.max(f.bbox.maxX,m.maxX),f.bbox.maxY=Math.max(f.bbox.maxY,m.maxY)}return u.map(h=>h.ring)},$u=n=>{let e=-1/0;for(let t of n)t.x>e&&(e=t.x);return e};var eg=new Set(["miter","round","bevel"]),tg=new Set(["butt","round","square"]),Ei=n=>{if(typeof n.stroke!="string"||!n.stroke)return null;let e=Number(n.strokeWidth)||0;if(e<=0)return null;let t=Array.isArray(n.strokeDashArray)?n.strokeDashArray.map(i=>Number(i)||0).filter(i=>i>=0):null,r=typeof n.strokeLineJoin=="string"&&eg.has(n.strokeLineJoin)?n.strokeLineJoin:"miter",o=typeof n.strokeLineCap=="string"&&tg.has(n.strokeLineCap)?n.strokeLineCap:"butt";return{color:n.stroke,rgba:ee(n.stroke),width:e,dashArray:t&&t.length>0?t:null,dashOffset:Number(n.strokeDashOffset)||0,lineJoin:r,lineCap:o,miterLimit:Number(n.strokeMiterLimit)||4,paintFirst:n.paintFirst==="stroke"?"stroke":"fill",alignment:n.strokeAlignment==="inside"||n.strokeAlignment==="outside"?n.strokeAlignment:"center",uniform:n.strokeUniform===!0||se(n)===L.PATH}},Zu=n=>{let e=r=>String(Math.round(r*1e4)/1e4),t=n.dashArray?n.dashArray.map(e).join(","):"-";return`s|${n.rgba.map(e).join(",")}|${e(n.width)}|${n.uniform?1:0}|${t}|${e(n.dashOffset)}|${n.lineJoin}|${n.lineCap}|${e(n.miterLimit)}|${n.paintFirst}|${n.alignment}`};var ng=(n,e)=>{let t=e.matrix,r=Math.max(Math.hypot(t[0],t[1]),Math.hypot(t[2],t[3]));return Math.ceil(n.width*Math.max(1,n.miterLimit)*(n.uniform?1:r)/2+4)},rg=625e4,Ju=(n,e,t)=>Math.min(n,8192/e,8192/t,Math.sqrt(rg/(e*t))),Ci=(n,e,t,r,o,i)=>{let s=e*t,a=r[4]*t,l=r[5]*t;return{lx:(Math.round((n[4]-o/2)*s+a)-a)/s,ly:(Math.round((n[5]-i/2)*s+l)-l)/s}},xr=(n,e)=>{let t=e.raw,r=se(t);if(n.beginPath(),r===L.PATH){let o=Ce(t.path);if(!o)return!1;let i=Fe(o);if(!i)return!1;let s=(i.left+i.right)/2,a=(i.top+i.bottom)/2;for(let l of o)switch(l[0]){case"M":n.moveTo(l[1]-s,l[2]-a);break;case"L":n.lineTo(l[1]-s,l[2]-a);break;case"C":n.bezierCurveTo(l[1]-s,l[2]-a,l[3]-s,l[4]-a,l[5]-s,l[6]-a);break;case"Q":n.quadraticCurveTo(l[1]-s,l[2]-a,l[3]-s,l[4]-a);break;case"Z":n.closePath();break}return!0}if(r===L.POLYGON||r===L.POLYLINE){let o=Array.isArray(t.points)?t.points:[];if(o.length<2)return!1;let i=1/0,s=1/0,a=-1/0,l=-1/0;for(let h of o)i>h.x&&(i=h.x),s>h.y&&(s=h.y),a<h.x&&(a=h.x),l<h.y&&(l=h.y);let u=(i+a)/2,c=(s+l)/2;n.moveTo(o[0].x-u,o[0].y-c);for(let h=0;h<o.length;h++)n.lineTo(o[h].x-u,o[h].y-c);return r===L.POLYGON&&n.closePath(),!0}if(r===L.TRIANGLE){let o=e.dims.x,i=e.dims.y;return!(o>0)||!(i>0)?!1:(n.moveTo(0,-i/2),n.lineTo(o/2,i/2),n.lineTo(-o/2,i/2),n.closePath(),!0)}if(r===L.ELLIPSE||r===L.CIRCLE){let o=(r===L.CIRCLE?Number(t.radius):Number(t.rx))||0,i=(r===L.CIRCLE?Number(t.radius):Number(t.ry))||0;return!(o>0)||!(i>0)?!1:(n.ellipse(0,0,o,i,0,0,Math.PI*2),!0)}if(r===L.LINE||r===L.REFERENCELINE){let o=Number(t.x1),i=Number(t.y1),s=Number(t.x2),a=Number(t.y2);return!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)?!1:(n.moveTo(o,i),n.lineTo(s,a),!0)}if(r===L.RECT||r===L.FABRICRECT){let o=e.dims.x,i=e.dims.y;if(!(o>0)||!(i>0))return!1;let s=it(t,o,i);return s?jn(n,o,i,s.rx,s.ry):n.rect(-o/2,-i/2,o,i),!0}return!1},eh=(n,e)=>{let t=Ei(n.raw);if(!t)return null;let r=se(n.raw);if(r===L.ARROW||r===L.DIMENSION)return sg(n,t,e);let o=Math.abs(n.matrix[0])*n.dims.x+Math.abs(n.matrix[2])*n.dims.y,i=Math.abs(n.matrix[1])*n.dims.x+Math.abs(n.matrix[3])*n.dims.y,s=ng(t,n),a=o+s*2,l=i+s*2;if(!(a>0)||!(l>0)||a>8192||l>8192)return null;let u=e?e.zoom*e.dpr:1,c=Ju(u,a,l),h=Math.ceil(a*c),d=Math.ceil(l*c);if(!(h>0)||!(d>0))return null;let f=document.createElement("canvas");f.width=h,f.height=d;let m=f.getContext("2d");if(!m)return null;let p=n.matrix,b=e&&c===u?Ci(p,e.zoom,e.dpr,e.vpt,a,l):null,g=b?b.lx:p[4]-a/2,x=b?b.ly:p[5]-l/2,S=h/c,w=d/c,y=[p[0]*c,p[1]*c,p[2]*c,p[3]*c,(p[4]-g)*c,(p[5]-x)*c];if(m.setTransform(y[0],y[1],y[2],y[3],y[4],y[5]),!xr(m,n))return null;let v=y;if(t.uniform){let R=Math.hypot(p[0],p[1])||1,P=Math.hypot(p[2],p[3])||1;v=j(y,[1/R,0,0,1/P,0,0])}if(m.setTransform(v[0],v[1],v[2],v[3],v[4],v[5]),m.lineWidth=t.width,m.lineCap=t.lineCap,m.lineDashOffset=t.dashOffset,m.lineJoin=t.lineJoin,m.miterLimit=t.miterLimit,t.dashArray&&m.setLineDash(t.dashArray),m.strokeStyle=t.color,t.alignment==="outside"||t.alignment==="inside"){if(m.lineWidth=t.width*2,t.alignment==="inside")m.clip(),m.stroke();else{m.stroke(),m.globalCompositeOperation="destination-out";let R=to(n,m);typeof n.raw.fill=="string"&&n.raw.fill!==""&&n.raw.fill!=="transparent"||m.clip(),m.fillStyle=R,m.fill(),m.globalCompositeOperation="source-over"}return{canvas:f,w:S,h:w,lx:g,ly:x,sceneW:a,sceneH:l,snapped:!!b}}return m.stroke(),{canvas:f,w:S,h:w,lx:g,ly:x,sceneW:a,sceneH:l,snapped:!!b}},to=(n,e)=>{let t=n.raw.fill;if(typeof t=="string"&&t)return t;if(t&&typeof t=="object"&&t.type==="linear"){let r=t,o=r.coords??{},i=n.dims.x,s=n.dims.y,a=r.gradientUnits==="percentage"?i:1,l=r.gradientUnits==="percentage"?s:1,u=e.createLinearGradient((o.x1??0)*a+(r.offsetX??0),(o.y1??0)*l+(r.offsetY??0),(o.x2??0)*a+(r.offsetX??0),(o.y2??0)*l+(r.offsetY??0));for(let c of r.colorStops??[])typeof c?.offset=="number"&&typeof c?.color=="string"&&u.addColorStop(Math.min(1,Math.max(0,c.offset)),c.color);return u}return og(n)},og=n=>{let e=n.raw.stroke;return typeof e=="string"&&e?e:"#000"},ig=n=>{let e=Number(n.raw.x1),t=Number(n.raw.y1),r=Number(n.raw.x2),o=Number(n.raw.y2);return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o)?null:{x1:e,y1:t,x2:r,y2:o}},sg=(n,e,t)=>{let r=ig(n);if(!r)return null;let o=n.raw,s=se(o)===L.ARROW,a=Number(o.strokeWidth)||1,l=typeof o.stroke=="string"?o.stroke:"#000000",u=Array.isArray(o.strokeDashArray)?o.strokeDashArray:null,c=Math.ceil(a*2+8),h=null,d=Number(o.arrowWidth)||15,f=Number(o.arrowHeight)||22.5,m=o.arrowType==="start"||o.arrowType==="both"?o.arrowType:(o.arrowType==="end","end"),p=Math.sqrt(a),b=d*p,g=f*p;if(s)c=Math.ceil(c+g+b);else{let Y=Number(o.textFontSize)||50,X=typeof o.text=="string"&&o.text.trim()?o.text:"50cm",Z=Number(o.textPadding)||4,B=`${Y}px Arial, sans-serif`,q=no(B,X)+Z*2,U=Math.atan2(r.y2-r.y1,r.x2-r.x1),oe=-Math.sin(U),ne=Math.cos(U),de=Y+a/2+5;h={text:X,fontPx:Y,w:q,h:Y+Z*2,cx:(r.x1+r.x2)/2+oe*de,cy:(r.y1+r.y2)/2+ne*de,angle:o.textFollowLine===!1?0:U,color:typeof o.textColor=="string"?o.textColor:"#333333",bg:typeof o.textBackgroundColor=="string"?o.textBackgroundColor:"#ffffff",pad:Z,follow:o.textFollowLine!==!1},c=Math.ceil(c+de+Math.max(q,Y*2)*.75)}let x=Math.abs(n.matrix[0])*n.dims.x+Math.abs(n.matrix[2])*n.dims.y,S=Math.abs(n.matrix[1])*n.dims.x+Math.abs(n.matrix[3])*n.dims.y,w=x+c*2,y=S+c*2;if(!(w>0)||!(y>0)||w>8192||y>8192)return null;let v=t?t.zoom*t.dpr:1,R=Ju(v,w,y),P=Math.ceil(w*R),T=Math.ceil(y*R);if(!(P>0)||!(T>0))return null;let C=document.createElement("canvas");C.width=P,C.height=T;let E=C.getContext("2d");if(!E)return null;let M=n.matrix,k=t&&R===v?Ci(M,t.zoom,t.dpr,t.vpt,w,y):null,A=k?k.lx:M[4]-w/2,O=k?k.ly:M[5]-y/2,F=[M[0]*R,M[1]*R,M[2]*R,M[3]*R,(M[4]-A)*R,(M[5]-O)*R];E.setTransform(F[0],F[1],F[2],F[3],F[4],F[5]);let W=r.x2-r.x1,z=r.y2-r.y1,_=Math.atan2(z,W),D=Math.cos(_),I=Math.sin(_);if(s){let Y=m==="start"||m==="both",X=m==="end"||m==="both",Z=r.x1+D*(Y?g:0),B=r.y1+I*(Y?g:0),q=r.x2-D*(X?g:0),U=r.y2-I*(X?g:0);E.lineWidth=a,E.strokeStyle=l,u&&u.length>0?E.setLineDash(u):E.setLineDash([]),E.beginPath(),E.moveTo(Z,B),E.lineTo(q,U),E.stroke(),E.setLineDash([]);let oe=(ne,de,Pe)=>{E.save(),E.translate(ne,de),E.rotate(Pe),E.beginPath(),E.moveTo(0,0),E.lineTo(-g,-b/2),E.lineTo(-g,b/2),E.closePath(),E.fillStyle=l,E.fill(),E.restore()};return X&&oe(r.x2,r.y2,_),Y&&oe(r.x1,r.y1,_+Math.PI),{canvas:C,w:P/R,h:T/R,lx:A,ly:O,sceneW:w,sceneH:y,snapped:!!k}}E.beginPath(),E.moveTo(r.x1,r.y1),E.lineTo(r.x2,r.y2);let G=F;if(e.uniform){let Y=Math.hypot(M[0],M[1])||1,X=Math.hypot(M[2],M[3])||1;G=j(F,[1/Y,0,0,1/X,0,0])}E.setTransform(G[0],G[1],G[2],G[3],G[4],G[5]),E.lineWidth=e.width,E.lineCap=e.lineCap,E.lineDashOffset=e.dashOffset,E.lineJoin=e.lineJoin,E.miterLimit=e.miterLimit,e.dashArray&&E.setLineDash(e.dashArray),E.strokeStyle=l,E.stroke(),E.setTransform(F[0],F[1],F[2],F[3],F[4],F[5]);let $=-I,V=D,H=(Number(o.textFontSize)||50)/2;E.lineWidth=a,E.lineCap="round",e.dashArray&&E.setLineDash([]),E.strokeStyle=l;for(let[Y,X]of[[r.x1,r.y1],[r.x2,r.y2]])E.beginPath(),E.moveTo(Y-$*H,X-V*H),E.lineTo(Y+$*H,X+V*H),E.stroke();return h&&(E.save(),E.translate(h.cx,h.cy),h.follow&&E.rotate(h.angle),E.font=`${h.fontPx}px Arial, sans-serif`,E.textAlign="center",E.textBaseline="middle",h.bg&&(E.fillStyle=h.bg,E.fillRect(-h.w/2,-h.h/2,h.w,h.h)),E.fillStyle=h.color,E.fillText(h.text,0,0),E.restore()),{canvas:C,w:P/R,h:T/R,lx:A,ly:O,sceneW:w,sceneH:y,snapped:!!k}},no=(n,e)=>{let t=document.createElement("canvas").getContext("2d");return t?(t.font=n,t.measureText(e).width):e.length*50};var fe={LEFT:"left",CENTER:"center",RIGHT:"right",JUSTIFY:"justify",JUSTIFY_LEFT:"justify-left",JUSTIFY_CENTER:"justify-center",JUSTIFY_RIGHT:"justify-right",DISPERSE:"disperse"},ag=Object.values(fe),$t=n=>n===fe.JUSTIFY||n===fe.JUSTIFY_LEFT||n===fe.JUSTIFY_CENTER||n===fe.JUSTIFY_RIGHT,sl=n=>n===fe.JUSTIFY_LEFT||n===fe.JUSTIFY_CENTER||n===fe.JUSTIFY_RIGHT,ro=n=>n===fe.JUSTIFY||n===fe.DISPERSE;var th=400,Mi=1.13,Ri=.222,lg=2,cg={underline:.1,linethrough:-.28167,overline:-.81333},ug=66.667,hg=/[a-zA-Z.\s]+/,dg=/[0-9]/,fg=/[()[\]{}></:;:,.?!]/,so=n=>hg.test(n)||dg.test(n)||fg.test(n),mg=new Set(["ー","「","」","『","』","(",")","〔","〕","[","]","{","}","⦅","⦆","〈","〉","《","》","【","】","〖","〗","〘","〙","〚","〛","゛","゜","。","、","・","゠","=","〜","…","•","‥","◦","﹅","﹆"]),pg=new Set(["「","」","『","』","〔","〕","[","]","{","}","⦅","⦆","〈","〉","《","》","【","】","〖","〗","〘","〙","〚","〛","(",")"]),qn=n=>so(n)?"latin":pg.has(n)?"bracket":mg.has(n)?"symbol":"cjk",Kn=(n,e,t)=>so(n)?e.width:e.height+t,un=n=>n/1.1,yr=(n,e,t)=>n==="symbol"?-t/3.14:e.height/2-t/3.14,wt=(n,e,t)=>n===0||t%2===0?0:n/300*e*.5,sh=(n,e,t)=>{if(n===0)return 0;let r=e.fontSize;for(let o of t)for(let i of o.charStyles){let s=i?.fontSize;typeof s=="number"&&s>r&&(r=s)}return Math.abs(n)/300*r*.5},oo=null,ah=(n,e,t)=>{let r={left:0,right:0,ascent:t*.88,descent:t*.24};if(typeof document>"u")return r;if(!oo){let i=document.createElement("canvas");i.width=8,i.height=8,oo=i.getContext("2d")}if(!oo)return r;oo.font=n;let o=oo.measureText(e);return o.actualBoundingBoxAscent===void 0||o.actualBoundingBoxDescent===void 0?r:{left:-(o.actualBoundingBoxLeft??0),right:o.actualBoundingBoxRight??0,ascent:o.actualBoundingBoxAscent,descent:o.actualBoundingBoxDescent}},nh=new WeakMap,cl=new Set,rh=(n,e,t)=>{let r=nh.get(n);r||(r=new Map,nh.set(n,r),cl.add(r));let o=`${Me(e,e.fontSize)}|${t}`,i=r.get(o);return i||(i=n(Me(e,e.fontSize),t,e.fontSize),r.set(o,i)),i},lh=(n,e,t=ah)=>{let r=e.charSpacing?e.fontSize*e.charSpacing/1e3:0,o=0,i=0,s=0;for(let a=0;a<n.graphemes.length;a++){let l=n.graphemes[a],u=n.boxes[a],c=uh(e,n.charStyles[a]),h=qn(l),d,f;if(h==="latin"||h==="bracket"){let m=h==="latin"?u.kernedWidth-u.width:0,p=rh(t,c,l);d=p.left+m,f=p.right+m}else{let m=rh(t,c,l);d=un(c.fontSize)-m.ascent,f=un(c.fontSize)+m.descent}a===0&&(i=d),s=o+f,o+=Kn(l,u,r)}return{start:i,end:s}},ul=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong","inherit","initial","unset"]),Pi=(n,e,t={})=>{let r=1/0,o=-1/0,i=1/0;for(let a of n.lines){if(a.width<=0||a.graphemes.length===0)continue;let l,u;if(t.vertical){let c=lh(a,e,t.inkMeasure);l=a.leftOffset+c.start,u=a.leftOffset+c.end}else{let c=a.boxes[a.boxes.length-1];l=a.leftOffset,u=a.leftOffset+Math.max(a.width,c.left+c.width)}u>l&&(r=Math.min(r,l),o=Math.max(o,u),i=Math.min(i,a.top))}if(!(o>r)||!Number.isFinite(i))return null;let s=t.align===void 0?{lo:r,hi:o}:bg(r,o,n.width,t.align);return{lo:s.lo,hi:s.hi,firstTop:i}},bg=(n,e,t,r)=>!(t>0)||!Number.isFinite(t)?{lo:n,hi:e}:r===fe.CENTER||r===fe.JUSTIFY_CENTER?{lo:Math.min(0,n),hi:Math.max(t,e)}:r===fe.RIGHT||r===fe.JUSTIFY_RIGHT?{lo:n,hi:Math.max(t,e)}:{lo:Math.min(0,n),hi:e},Me=(n,e)=>{let t=n.fontFamily,r=t.includes("'")||t.includes('"')||t.includes(",")||ul.has(t.toLowerCase())?t:`"${t}"`;return`${n.fontStyle??"normal"} ${n.fontWeight??"normal"} ${e}px ${r}`},gg=(n,e)=>{if(n)return n.id===0?`${e+1}`:n.content||void 0},Oe=(n,e)=>{let t=e?.stroke??n?.color,r=e?.strokeWidth??n?.width;return!t||!r?null:{color:t,width:r,lineJoin:n?.lineJoin,miterLimit:n?.miterLimit,lineCap:n?.lineCap}},ao=/[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/,hn=n=>{let e=n.boxes[n.boxes.length-1];return e?e.left+e.width:0},Tt=(n,e,t,r,o={})=>{let i=e.prefix;if(!i)return 0;let s=n.font;return n.font=Me(i.style,i.style.fontSize),o.fill&&(o.fill!=="keep"&&(n.fillStyle=o.fill),n.fillText(i.text,t,r)),o.stroke&&o.stroke.width>0&&(n.lineWidth=o.stroke.width,n.strokeStyle=o.stroke.color,n.strokeText(i.text,t,r)),n.font=s,i.width},hl=(n,e,t)=>{let r=[],o=!!t[e],i=S=>!!(n.charStyles[S]?.[e]??o);if(!n.graphemes.some((S,w)=>i(w)))return r;let s=S=>n.charStyles[S]?.fill??t.fill??"",a=S=>n.charStyles[S]?.textDecorationThickness??t.textDecorationThickness??ug,l=S=>n.charStyles[S]?.fontSize??t.fontSize,u=cg[e],c=e==="linethrough"?.5:e==="overline"?1:0,h=t.charSpacing?t.fontSize*t.charSpacing/1e3:0,d=(S,w,y,v,R,P)=>{if(!S||!w||!y||P<=0)return;let T=t.fontSize*y/1e3;r.push({x:R,width:P,y:u*v-c*T,thickness:T,color:w})},f=0,m=0,p=i(0),b=s(0),g=a(0),x=l(0);for(let S=0;S<n.graphemes.length;S++){let w=i(S),y=s(S),v=a(S),R=l(S),P=n.boxes[S],T=t.vertical?so(n.graphemes[S])?P.kernedWidth:P.height:P.kernedWidth;(w!==p||y!==b||v!==g||R!==x)&&m>0?(d(p,b,g,x,f,m),f=P.left,m=t.vertical?T:P.width,p=w,b=y,g=v,x=R):m+=t.vertical?T:P.kernedWidth}return d(p,b,g,x,f,m-h),r},io=null,xg=(n,e)=>{if(typeof document>"u")return 0;if(!io){let t=document.createElement("canvas");if(t.width=8,t.height=8,io=t.getContext("2d"),!io)return 0}return io.font=n,io.measureText(e).width},Nt=n=>Array.from(n),yg=n=>n.split(/[ \t\r]/),al=class{constructor(e,t){this.decl=e;this.measure=t}decl;measure;charWidths=new Map;coupleWidths=new Map;charWidth(e){let t=this.charWidths.get(e);return t===void 0&&(t=this.measure(this.decl,e),this.charWidths.set(e,t)),t}coupleWidth(e,t){let r=e+"\0"+t,o=this.coupleWidths.get(r);return o===void 0&&(o=this.measure(this.decl,e+t),this.coupleWidths.set(r,o)),o}},oh=new WeakMap,Sg=(n,e)=>{let t=oh.get(e);t||(t=new Map,oh.set(e,t),cl.add(t));let r=t.get(n);return r||(r=new al(n,e),t.set(n,r)),r},ch=()=>{for(let n of cl)n.clear()},uh=(n,e)=>!e||e.fontSize===void 0&&e.fontFamily===void 0&&e.fontWeight===void 0&&e.fontStyle===void 0?n:{...n,fontSize:e.fontSize??n.fontSize,fontFamily:e.fontFamily??n.fontFamily,fontWeight:e.fontWeight??n.fontWeight,fontStyle:e.fontStyle??n.fontStyle},ll=(n,e,t,r,o)=>{let i=Sg(Me(e,th),n),s=e.fontSize/th,a=i.charWidth(t),l=a;return r&&o&&Me(o,o.fontSize)===Me(e,e.fontSize)&&(l=i.coupleWidth(r,t)-i.charWidth(r)),{width:a*s,kernedWidth:l*s}},hh=n=>n.charSpacing?n.fontSize*n.charSpacing/1e3:0,ih=(n,e,t,r,o,i,s,a=!1)=>{let l=hh(o),u=[],c=" ",h=0,d=[],f=0,m=!0,p=0,b=Math.max(e,r,lg),g=t[n];for(let x=0;x<g.length;x++){let S=g[x].graphemes,w=g[x].width;p+=S.length,h+=(a?0:f)+w-l,h>b&&!m?(u.push(d),d=[],h=w,m=!0):h+=l,!m&&!a&&d.push(c),d=d.concat(S),f=a?0:ll(s,i(n,p),c).kernedWidth+l,p++,m=!1}return g.length&&u.push(d),u},jt=(n,e,t={})=>{let r=t.measure??xg,o=t.inkMeasure??ah,i=t.styles,s=(E,M)=>uh(e,i?.[E]?.[M]),a=hh(e),l=e.lineHeight??1.16,u=(E,M,k)=>{let A=0,O;for(let F=0;F<E.length;F++){let W=ll(r,s(M,k+F),E[F],O,F>0?s(M,k+F-1):void 0);A+=W.kernedWidth+a,O=E[F]}return A},c=(n??"").split(`
3
+ `),h,d=0;if(t.boxWidth==null)h=c.map(E=>Nt(E));else if(t.splitByGrapheme){let E=[];for(let M=0;M<c.length;M++){let k=Nt(c[M]);if(k.length===0){E.push([{graphemes:[],width:0,charOffset:0}]);continue}let A=k.map((O,F)=>{let W=u([O],M,F);return d=Math.max(W,d),{graphemes:[O],width:W,charOffset:F}});E.push(A)}h=[];for(let M=0;M<E.length;M++)h.push(...ih(M,t.boxWidth,E,d,e,s,r,!0))}else{let E=[];for(let M=0;M<c.length;M++){let k=[],A=0;for(let O of yg(c[M])){let F=Nt(O),W=u(F,M,A);d=Math.max(W,d),k.push({graphemes:F,width:W,charOffset:A}),A+=F.length+1}E.push(k)}h=[];for(let M=0;M<E.length;M++)h.push(...ih(M,t.boxWidth,E,d,e,s,r))}let f=Nt(n??""),m=[];{let E=0,M=0,k=0;for(let A=0;A<h.length;A++){let O=f[k];O===`
4
+ `&&A>0?(M=0,k++,E++):A>0&&!t.splitByGrapheme&&/[ \t\r]/.test(O??"")&&(M++,k++),m[A]={line:E,offset:M,flatStart:k},k+=h[A].length,M+=h[A].length}}let p=h.map((E,M)=>{let k=m[M],A=[],O=0;for(let _=0;_<E.length;_++){let D=ll(r,s(k.line,k.offset+_),E[_],_>0?E[_-1]:void 0,_>0?s(k.line,k.offset+_-1):void 0),I={left:0,width:D.width+a,kernedWidth:D.kernedWidth+a,height:s(k.line,k.offset+_).fontSize};_>0&&(I.left=A[_-1].left+A[_-1].width+D.kernedWidth-D.width),A.push(I),t.vertical&&!so(E[_])?O+=I.height:O+=I.kernedWidth}a!==0&&(O-=a),O<0&&(O=0);let F=E.map((_,D)=>i?.[k.line]?.[k.offset+D]),W=0;if(E.length>0)for(let _=0;_<E.length;_++)W=Math.max(W,i?.[k.line]?.[k.offset+_]?.fontSize??e.fontSize);else W=i?.[k.line]?.[k.offset]?.fontSize??e.fontSize;let z;if(t.paragraph){let _=gg(t.paragraph,M);if(_){let D=s(k.line,k.offset),I=Me(D,D.fontSize),G=r(I,_);if(G>0){z={text:_,width:G,advances:Nt(_).map($=>r(I,$)),style:D};for(let $ of A)$.left+=z.width;O+=z.width}}}return{graphemes:E,boxes:A,width:O,leftOffset:0,baseline:0,top:0,implHeight:W*Mi,styleMap:k,charStyles:F,prefix:z}}),b=0,g=0;for(let E=0;E<p.length;E++){let M=p[E].implHeight,k=E===p.length-1;p[E].top=g,p[E].baseline=g+M*(1-Ri),g+=M*l,b+=k?M:M*l}let x=t.boxWidth!=null?Math.max(t.boxWidth,d-a):0,S=()=>{let E=0;for(let M of p){let k=0;for(let A=0;A<M.graphemes.length;A++)k+=so(M.graphemes[A])?M.boxes[A].width+a:M.boxes[A].height+a;E=Math.max(E,k)}return E+2},w=t.vertical?S():void 0,y=t.boxWidth!=null?x:t.vertical?w:Math.max(0,...p.map(E=>E.width)),v=e.textAlign??fe.LEFT,R=E=>{if(t.boxWidth==null)return E===p.length-1;let M=p[E+1]?.styleMap;return!M||M.line!==p[E].styleMap.line};for(let E=0;E<p.length;E++){let M=v===fe.CENTER||v===fe.JUSTIFY_CENTER&&R(E),k=v===fe.RIGHT||v===fe.JUSTIFY_RIGHT&&R(E);if(t.vertical&&(M||k)&&p[E].graphemes.length>0){let O=lh(p[E],e,o);p[E].leftOffset=M?(y-O.start-O.end)/2:y-O.end;continue}let A=y-p[E].width;M?p[E].leftOffset=A/2:k&&(p[E].leftOffset=A)}let P=v===fe.DISPERSE;if(($t(v)||P)&&!t.vertical)for(let E=0;E<p.length;E++){let M=p[E],k=sl(v);if(k&&(E===p.length-1||R(E))||!k&&!P&&E===p.length-1||M.width>=y)continue;let A=!k&&M.graphemes.some(z=>ao.test(z)),O=A?M.graphemes.length-1:M.graphemes.reduce((z,_)=>/[ \t\r]/.test(_)?z+1:z,0);if(O<=0)continue;let F=(y-M.width)/O,W=0;for(let z=0;z<M.graphemes.length;z++){let _=M.boxes[z],D=A?z<M.graphemes.length-1:/[ \t\r]/.test(M.graphemes[z]);_.left+=W,D&&(_.width+=F,_.kernedWidth+=F,W+=F)}}let T=[],C=0;for(let E of f)T.push(C),C+=E.length;return T.push(C),{lines:p,width:y,height:b,graphemeCodeUnitOffsets:T,verticalWidth:w}};var vg={arc:"arc",circle:"circle",waist:"waist",flag:"flag",arch:"arch",scroll:"scroll"},wg={[L.ARCTEXT]:"arc",[L.CIRCLETEXT]:"circle",[L.WAISTTEXT]:"waist",[L.FLAGTEXT]:"flag",[L.ARCHTEXT]:"arch",[L.SCROLLTEXT]:"scroll"},Ge=n=>{let e=n.textTransform;if(typeof e=="string"){let t=vg[e];if(t)return t}return wg[se(n)]??null},Tg=new Set(["arc","circle","waist","flag","arch"]),dh=n=>{let e=Ge(n);return e!=null&&Tg.has(e)},Sr=n=>{if(!(Number(n.warpStrength)||0))return null;let t=Ge(n);return t==="arch"||t==="waist"||t==="flag"?t:null},fh=(n,e,t,r,o)=>{if(!(r.hi>r.lo))return null;let i=Math.max(-1,Math.min(1,Number(t.warpStrength)||0)),s=Number(t.fontSize)||40,a=typeof t.height=="number"?t.height:0,l=Math.max(a,s),u=-e.width/2+r.lo,c=-e.width/2+r.hi,h=o+r.firstTop,d=o+e.height,f=d-h;if(n==="arch"){if(i<=0)return{left:u,right:c,top:h,bottom:d};let b=l*i/2;return{left:u,right:c,top:d+b-f*(1+i),bottom:d+b}}if(n==="flag"){let b=Math.abs(i)*(a||s)*.3,g=Math.abs(i)*b;return{left:u,right:c,top:h-g,bottom:d+g}}let m=(h+d)/2,p=f/2*(1+.5*Math.abs(i));return{left:u,right:c,top:m-p,bottom:m+p}};var Eg=1e4,lo=2,mh=(n,e)=>{let t=e-n;for(;t>=2*Math.PI;)t-=2*Math.PI;for(;t<=0;)t+=2*Math.PI;return t},ki=(n,e,t)=>mh(n,e)+mh(e,t)<2*Math.PI,Ai=(n,e,t,r)=>{let o=n.x,i=n.y,s=o,a=i;e.x<o&&(o=e.x),e.x>s&&(s=e.x),e.y<i&&(i=e.y),e.y>a&&(a=e.y);let l=Math.atan2(n.y-t.y,n.x-t.x),u=Math.atan2(e.y-t.y,e.x-t.x);if(ki(l,0,u)){let c=t.x+r;c>s&&(s=c)}if(ki(l,Math.PI/2,u)){let c=t.y+r;c>a&&(a=c)}if(ki(l,Math.PI,u)){let c=t.x-r;c<o&&(o=c)}if(ki(l,Math.PI*3/2,u)){let c=t.y-r;c<i&&(i=c)}return{x:o,y:i,width:s-o,height:a-i}},Xe=n=>{let e=Ge(n);return e==="arc"||e==="circle"?e:null},ph=n=>n.lines.map(e=>{let t=e.boxes.map(o=>({left:o.left,width:o.width})),r=t[t.length-1];return t.push(r?{left:r.left+r.width,width:0}:{left:0,width:0}),t}),Cg=(n,e,t)=>{let r=ph(n),o=n.width,i=P=>n.lines[P].implHeight*e,s=0;for(let P=0;P<n.lines.length;P++)s+=i(P);let a=Math.abs(t),l=a*Math.PI/180,u=0;for(let P=0;P<n.lines.length;P++)u+=n.lines[P].width;let c=l>0?u/l:0,h=Math.max(Eg/Math.max(a,.1),c),d=0,f=t>0?s/2+h:-s/2+h,m=t>0?s:0,p=1/0,b=-1/0,g=1/0,x=-1/0,S=[];for(let P=0;P<r.length;P++){let T=-o/2+n.lines[P].leftOffset,C=i(P),E=C-C/e+C*Ri/e;m+=t>0?-C:C;let M=Math.abs(h)+m,k=t>0?M+C-C/e:M-C+C/e,A=[];for(let D=0;D<r[P].length;D++){let I=r[P][D],G,$,V,H,Y,X,Z;t>0?(G=M,$=M+C,V=M+E,H=(G*3+$*2)/5,Y=-(T+I.left)/H,X=-(T+I.left+I.width)/H,Z=-(T+I.left+I.width/2)/H):(G=M,$=M-C,V=M-E,H=(G*2+$*3)/5,Y=Math.PI+(T+I.left)/H,X=Math.PI+(T+I.left+I.width)/H,Z=Math.PI+(T+I.left+I.width/2)/H);let B=Math.sin(X),q=Math.cos(X),U=Math.sin(Y),oe=Math.cos(Y),ne=Math.sin(Z),de=Math.cos(Z);A.push({tl:{x:d-$*U,y:f-$*oe},tr:{x:d-$*B,y:f-$*q},nl:{x:d-k*U,y:f-k*oe},nr:{x:d-k*B,y:f-k*q}});let Pe=n.lines[P].graphemes[D];Pe!==void 0&&S.push({char:Pe,line:P,index:D,x:d-V*ne,y:f-V*de,rotation:t>0?-Z:-Z-Math.PI})}let O=A[0],F=A[A.length-1];if(!O||!F)continue;let W={x:d,y:f},z=t>0?Ai(O.tl,F.tr,W,M+C):Ai(F.tr,O.tl,W,M-C),_=t>0?Ai(O.nl,F.nr,W,M):Ai(F.nr,O.nl,W,M);p=Math.min(p,z.x,_.x),b=Math.max(b,z.x+z.width,_.x+_.width),g=Math.min(g,z.y,_.y),x=Math.max(x,z.y+z.height,_.y+_.height)}Number.isFinite(p)||(p=b=g=x=0);let w=-p-o/2,y=b-o/2,v=-g-s/2,R=x-s/2;return{width:Math.max(o+w+y,lo),height:s+v+R,contentOffsetX:y/2-w/2,contentOffsetY:R/2-v/2,chars:S}},Mg=(n,e,t)=>{let r=ph(n),o=C=>n.lines[C].implHeight*e,i=0;for(let C=0;C<n.lines.length;C++)i+=o(C);let s=n.width,a=Math.max(t.size,1),l=Math.min(Math.max(t.eccentricity,0),.95),u=a*(1-l),c=Math.max(t.sweep,1)*(Math.PI/180),h=t.startAngle*(Math.PI/180),d=t.horizontal,f=0;for(let C=0;C<n.lines.length;C++)f+=n.lines[C].width;let m=0,p=0;if(f<=0||r.length===0)return{width:lo,height:Math.max(i,lo),contentOffsetX:0,contentOffsetY:0,chars:[]};let b=1/0,g=-1/0,x=1/0,S=-1/0,w=[],y=0;for(let C=0;C<r.length;C++){let E=o(C),M=E-E/e+E*Ri/e,k=E-M;for(let A=0;A<r[C].length;A++){let O=r[C][A],W=(y+O.left+O.width/2)/f,z=h-W*c,_=Math.sin(z),D=Math.cos(z),I=m-a*_,G=p-u*D,$,V,H,Y,X;if(d)$=0,V=1,H=0,Y=0,X=-1;else{let U=a*D,oe=-u*_,ne=Math.hypot(U,oe)||1;V=U/ne,H=oe/ne;let de=-u*_,Pe=-a*D,De=Math.hypot(de,Pe)||1;Y=de/De,X=Pe/De,$=Math.atan2(oe,U)}let Z=-$,B=O.width/2;b=Math.min(b,I-Y*M-V*B,I-Y*M+V*B,I+Y*k-V*B,I+Y*k+V*B),g=Math.max(g,I-Y*M-V*B,I-Y*M+V*B,I+Y*k-V*B,I+Y*k+V*B),x=Math.min(x,G-X*M-H*B,G-X*M+H*B,G+X*k-H*B,G+X*k+H*B),S=Math.max(S,G-X*M-H*B,G-X*M+H*B,G+X*k-H*B,G+X*k+H*B);let q=n.lines[C].graphemes[A];q!==void 0&&w.push({char:q,line:C,index:A,x:I,y:G,rotation:-Z})}y+=n.lines[C].width}Number.isFinite(b)||(b=g=x=S=0);let v=-b-s/2,R=g-s/2,P=-x-i/2,T=S-i/2;return{width:Math.max(g-b,lo),height:Math.max(S-x,lo),contentOffsetX:R/2-v/2,contentOffsetY:T/2-P/2,chars:w}},Et=(n,e,t)=>Ge(e)==="circle"?Mg(n,t,{size:typeof e.circleSize=="number"?e.circleSize:40,startAngle:typeof e.circleStartAngle=="number"?e.circleStartAngle:0,sweep:typeof e.circleSweep=="number"?e.circleSweep:360,eccentricity:typeof e.circleEccentricity=="number"?e.circleEccentricity:0,horizontal:e.circleDirection==="horizontal"}):Cg(n,t,typeof e.curvature=="number"?e.curvature:300);var bh=(n,e)=>{let t=1-e;return n===2?[t,e,0,0]:n===3?[t*t,2*t*e,e*e,0]:[t*t*t,3*t*t*e,3*t*e*e,e*e*e]},dn=(n,e,t,r,o,i)=>{let s={uOrder:Math.min(4,Math.max(2,o)),vOrder:Math.min(4,Math.max(2,i)),xs:[],ys:[]};for(let a=0;a<s.vOrder;a++){let l=s.vOrder===1?0:a/(s.vOrder-1);for(let u=0;u<s.uOrder;u++){let c=s.uOrder===1?0:u/(s.uOrder-1);s.xs.push(n+(t-n)*c),s.ys.push(e+(r-e)*l)}}return s},Ni=(n,e,t)=>{let r=bh(n.uOrder,e),o=bh(n.vOrder,t),i=0,s=0;for(let a=0;a<n.vOrder;a++)for(let l=0;l<n.uOrder;l++){let u=r[l]*o[a];i+=u*n.xs[a*n.uOrder+l],s+=u*n.ys[a*n.uOrder+l]}return{x:i,y:s}},Qn=(n,e,t,r,o,i)=>{let s=Math.sin(o),a=Math.cos(o),l=(t-e)/(2*s),u=4/3*Math.tan(o/2)*l,c=i?-u*s:u*s;n.xs.push(e,e+u*a,t-u*a,t),n.ys.push(r,r+c,r+c,r)},mt=(n,e,t)=>{n.xs.push(0,e/3,2*e/3,e),n.ys.push(t,t,t,t)},dl=(n,e)=>{let t={uOrder:n.uOrder,vOrder:n.vOrder,xs:[],ys:[]};for(let r=0;r<n.vOrder;r++){let o=n.vOrder-1-r;for(let i=0;i<n.uOrder;i++){let s=r*n.uOrder+i,a=o*n.uOrder+i;t.xs[s]=n.xs[a],t.ys[s]=e-n.ys[a]}}return t},Rg=n=>{let e={uOrder:n.vOrder,vOrder:n.uOrder,xs:[],ys:[]};for(let t=0;t<n.vOrder;t++)for(let r=0;r<n.uOrder;r++){let o=t*n.uOrder+r,i=r*n.vOrder+t;e.xs[i]=n.ys[o],e.ys[i]=n.xs[o]}return e},gh=(n,e,t,r)=>{let o=Math.min(100,Math.max(-100,e)),i=Math.abs(o)*Math.PI/200,s=2*r*o/100,a={uOrder:4,vOrder:n==="wave"?3:2,xs:[],ys:[]};if(n==="arcLower"||n==="arcUpper")return Math.abs(o)<1e-9?dn(0,0,t,r,4,2):(mt(a,t,0),Qn(a,0,t,r,i,o<0),n==="arcUpper"?dl(a,r):a);if(n==="fish")return mt(a,t,0),mt(a,t,r),a.ys[1]-=s,a.ys[2]+=s,a.ys[5]+=s,a.ys[6]-=s,a;if(n==="fisheye"){a=dn(0,0,t,r,4,4);let l=o/50;for(let u=1;u<=2;u++)for(let c=1;c<=2;c++){let h=u*4+c,d=c===1?0:t,f=u===1?0:r;a.xs[h]+=l*(d-a.xs[h]),a.ys[h]+=l*(f-a.ys[h])}return a}if(n==="inflate"||n==="squeeze"){a=dn(0,0,t,r,3,3);let l=t*o/200,u=r*o/200;return a.ys[1]-=u,a.ys[7]+=u,n==="inflate"?(a.xs[3]-=l,a.xs[5]+=l):(a.xs[3]+=l,a.xs[5]-=l),a}if(n==="twist"){a=dn(0,0,t,r,4,4);let l=t*Math.abs(o)/100,u=r*Math.abs(o)/100;return o>0?(a.xs[5]+=l,a.ys[6]+=u,a.xs[10]-=l,a.ys[9]-=u):o<0&&(a.ys[5]+=u,a.xs[6]-=l,a.ys[10]-=u,a.xs[9]+=l),a}if(n==="shellLower"||n==="shellUpper"){if(Math.abs(o)<1e-9)return dn(0,0,t,r,4,4);let l=Math.sin(i),u=Math.cos(i);if(a={uOrder:4,vOrder:4,xs:[],ys:[]},mt(a,t,0),mt(a,t,r/3),o>0){let c=2*r/3;a.xs.push(-c*l,t/3,2*t/3,t+c*l),a.ys.push(c*u,2*r/3,2*r/3,c*u),Qn(a,-r*l,t+r*l,r*u,i,!1)}else{let c=r/3;a.xs.push(-c*l,t/3,2*t/3,t+c*l),a.ys.push(r-c*u,2*r/3,2*r/3,r-c*u),Qn(a,0,t,r,i,!0)}return n==="shellUpper"?dl(a,r):a}if(n==="arc"){if(Math.abs(o)<1e-9)return dn(0,0,t,r,4,2);let l=Math.sin(i);return Qn(a,-r*l,t+r*l,r*(1-Math.cos(i)),i,!0),Qn(a,0,t,r,i,!0),o<0?dl(a,r):a}if(n==="arch"||n==="bulge"){if(Math.abs(o)<1e-9)return dn(0,0,t,r,4,2);let l=o>0;return Qn(a,0,t,0,i,l),Qn(a,0,t,r,i,n==="bulge"?!l:l),a}if(n==="flag")return mt(a,t,0),mt(a,t,r),a.ys[1]-=s,a.ys[2]+=s,a.ys[5]-=s,a.ys[6]+=s,a;if(n==="wave")return mt(a,t,0),mt(a,t,r/2),mt(a,t,r),a.ys[5]+=s,a.ys[6]-=s,a;if(n==="rise")return mt(a,t,0),mt(a,t,r),a.ys[0]+=s,a.ys[1]+=s,a.ys[4]+=s,a.ys[5]+=s,a},fl=n=>n==="arc"||n==="arch"||n==="bulge"||n==="flag"||n==="wave"||n==="rise"||n==="arcLower"||n==="arcUpper"||n==="shellLower"||n==="shellUpper"||n==="fish"||n==="fisheye"||n==="inflate"||n==="squeeze"||n==="twist",xh=(n,e,t,r,o)=>{if(!fl(n)||r<=0||o<=0)return;if(!t||n==="twist")return gh(n,e,r,o);let i=gh(n,e,o,r);return i?Rg(i):void 0},yh=(n,e,t)=>{let r=Math.min(100,Math.max(-100,t)),o=Math.min(100,Math.max(-100,e));if(r!==0&&n.vOrder>1)for(let i=0;i<n.vOrder;i++){let s=i*n.uOrder,a=s+n.uOrder-1,l=(n.xs[s]+n.xs[a])/2,u=(n.ys[s]+n.ys[a])/2,h=1+(2*(i/(n.vOrder-1))-1)*r/100;for(let d=0;d<n.uOrder;d++){let f=s+d;n.xs[f]=l+(n.xs[f]-l)*h,n.ys[f]=u+(n.ys[f]-u)*h}}if(o!==0&&n.uOrder>1)for(let i=0;i<n.uOrder;i++){let s=i,a=(n.vOrder-1)*n.uOrder+i,l=(n.xs[s]+n.xs[a])/2,u=(n.ys[s]+n.ys[a])/2,h=1+(2*(i/(n.uOrder-1))-1)*o/100;for(let d=0;d<n.vOrder;d++){let f=d*n.uOrder+i;n.xs[f]=l+(n.xs[f]-l)*h,n.ys[f]=u+(n.ys[f]-u)*h}}},ml=(n,e,t)=>{let r=xh(n.style,n.bend,n.rotate==="vertical",e,t);if(r)return yh(r,n.horizontal,n.vertical),r},Zn=n=>{if(n===null||typeof n!="object")return null;let t=n.psdWarp;if(t===null||typeof t!="object")return null;let r=t,o=typeof r.style=="string"?r.style:"";if(!fl(o))return null;let i=Number(r.bend)||0,s=Number(r.horizontal)||0,a=Number(r.vertical)||0;return i===0&&s===0&&a===0?null:{style:o,bend:i,horizontal:s,vertical:a,rotate:r.rotate==="vertical"?"vertical":"horizontal"}},pl=(n,e,t,r,o,i,s,a,l,u,c,h,d,f)=>{let m=r-e,p=o-t,b=a-i,g=l-s;if(m<=0||p<=0||b<=0||g<=0||u<=0||c<=0||d<=0||n.xs.length===0)return;let x=(i-e)/m,S=(a-e)/m,w=(s-t)/p,y=(l-t)/p,v=(W,z)=>{let _=Ni(n,W,z);return{x:h[0]*_.x+h[2]*_.y+h[4],y:h[1]*_.x+h[3]*_.y+h[5]}},R=0,P=0,T=0,C=0,E=!0,M=8;for(let W=0;W<=M;W++){let z=w+(y-w)*W/M;for(let _=0;_<=M;_++){let D=x+(S-x)*_/M,I=v(D,z);E?(R=P=I.x,T=C=I.y,E=!1):(R=Math.min(R,I.x),P=Math.max(P,I.x),T=Math.min(T,I.y),C=Math.max(C,I.y))}}let k=Math.max(8,f),A=Math.min(k,Math.max(8,Math.ceil((P-R)/d))),O=Math.min(k,Math.max(8,Math.ceil((C-T)/d))),F={columns:A+1,rows:O+1,docXs:[],docYs:[],sourceXs:[],sourceYs:[]};for(let W=0;W<F.rows;W++){let z=W/O;for(let _=0;_<F.columns;_++){let D=_/A,I=v(x+(S-x)*D,w+(y-w)*z);F.docXs.push(I.x),F.docYs.push(I.y),F.sourceXs.push(D*u),F.sourceYs.push(z*c)}}return F},bl=(n,e,t,r,o,i,s,a,l,u)=>{let c=o-t,h=i-r,d=l-t,f=u-r,m=t-o-l+s,p=r-i-u+a,b=n-t,g=e-r,x=c*p-h*m,S=c*f-h*d-(b*p-g*m),w=-(b*f-g*d),y;if(Math.abs(x)<1e-9){if(Math.abs(S)<1e-9)return;y=-w/S}else{let T=S*S-4*x*w;if(T<0)return;let C=Math.sqrt(T),E=(-S+C)/(2*x),M=(-S-C)/(2*x),k=E>=-1e-9&&E<=1+1e-9,A=M>=-1e-9&&M<=1+1e-9;if(k&&A)y=Math.min(Math.max(E,0),1);else if(k)y=E;else if(A)y=M;else return}let v=d+m*y,R=f+p*y,P;if(Math.abs(v)>=Math.abs(R)){if(Math.abs(v)<1e-9)return;P=(b-c*y)/v}else{if(Math.abs(R)<1e-9)return;P=(g-h*y)/R}if(!(y<-1e-9||y>1.000000001||P<-1e-9||P>1.000000001))return{s:Math.min(Math.max(y,0),1),t:Math.min(Math.max(P,0),1)}};var Pg=(n,e)=>{let t=n.boxes;if(t.length===0)return{left:0,width:0,kernedWidth:0,height:e};let r=t[t.length-1];return{left:r.left+r.width,width:0,kernedWidth:0,height:e}},Li=(n,e,t)=>e<0?null:e<n.boxes.length?n.boxes[e]:e===n.boxes.length?Pg(n,t):null,kg=(n,e,t)=>{if(!Array.isArray(t)||t.length===0)return[];let r=0;for(let h of t){if(!h||typeof h.text!="string")return[];r+=h.text.length}if(r!==n.length)return[];let o=[],i=[];for(let h=0;h<e.lines.length;h++){let d=e.lines[h].graphemes.length;for(let f=0;f<d;f++)i.push(f),o.push(h)}let s=[],a=0;for(let h=0;h<n.length;h++)n[h]===`
5
5
  `?s.push(-1):a<o.length?(s.push(a),a++):s.push(-1);let l=[],u=h=>{let d=s[h];return d===void 0||d===-1||d>=o.length?-1:d},c=0;for(let h of t){if(h.text.length===0)continue;if(h.text===`
6
- `){c+=1;continue}if(!h.highlight||h.highlight.type!=="svg"||!h.highlight.svgInfo){c+=h.text.length;continue}let d=h.highlight.svgInfo,f=u(c);if(f===-1){c+=h.text.length;continue}let m=o[f],p=0,b=m,g=0,x=S=>{if(p>=S)return;let w=u(c+p),y=u(c+g);w===-1||y===-1||l.push({lineIndex:b,start:i[w],end:i[y]+1,info:d})};for(let S=0;S<h.text.length;S++){let w=u(c+S);if(w===-1){x(S),p=S+1;continue}let y=o[w];y!==m&&(x(S),p=S,m=y),b=y,g=S}x(h.text.length),c+=h.text.length}return l},gl=(n,e,t,r,o,i)=>{let s=r||e;return i==="bottom"?n+e-(t+s)*o:i==="top"?n-t*o:n+(e-s*o)/2-t*o},yh=n=>{let e=Ce(n);if(!e)return null;let t=Fe(e);return t?{left:t.left,top:t.top,width:t.right-t.left,height:t.bottom-t.top}:null},kg=n=>{let e=n.split(/[Zz]/).map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)return null;let t=e[0];return t.endsWith("Z")||t.endsWith("z")?t:`${t} Z`},Jn=(n,e,t,r,o)=>{let i=Pg(n,e,t);if(i.length===0)return null;let s=[],a={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},l=(f,m)=>{let p=f.isFill?0:(f.strokeWidth||0)*Math.abs(f.scaleX)/2,b=f.isFill?0:(f.strokeWidth||0)*Math.abs(f.scaleY)/2,g=f.translateX+m.left*f.scaleX-p,x=f.translateY+m.top*f.scaleY-b,S=f.translateX+(m.left+m.width)*f.scaleX+p,w=f.translateY+(m.top+m.height)*f.scaleY+b;g<a.minX&&(a.minX=g),x<a.minY&&(a.minY=x),S>a.maxX&&(a.maxX=S),w>a.maxY&&(a.maxY=w)};for(let f of i){let m=e.lines[f.lineIndex];if(!m)continue;let p=f.info,b=typeof p.path=="string"?p.path:"";if(!b)continue;let g=p.alignVertical||"center",x=p.isFill===!0,S=p.strokeWidth||0,w=-e.width/2+m.leftOffset,y=r+m.top,v=Li(m,f.start,o);if(!v)continue;if(p.isSingle===!0){let z=kg(b);if(!z)continue;let _=yh(z);if(!_||!Number.isFinite(_.width)||!Number.isFinite(_.height))continue;let D=z;for(let I=f.start;I<f.end;I++){let G=m.graphemes[I];if(!G||/^\s$/.test(G))continue;let $=Li(m,I,o),V=Li(m,I+1,o);if(!$)continue;let H=w+$.left,Y=y,X=$.kernedWidth||$.width||(V?V.left:$.left)-$.left,Z=$.height,B=_.height;B||(B=Z);let q=_.width?X/_.width:1,U=B?Z/B:1,oe=p.scale||1,ne=Math.min(q,U)*oe,de=(_.width||0)*ne,Pe=H+(X-de)/2-_.left*ne,De=g==="bottom"?Y+Z-_.top*ne:gl(Y,Z,_.top,B,ne,g),nt={d:D,translateX:Pe,translateY:De,scaleX:ne,scaleY:ne,isFill:x,fill:p.fill||"#9FFFFC",stroke:p.stroke||"#9FFFFC",strokeWidth:S};s.push(nt),l(nt,_)}continue}let R=Li(m,f.end,o);if(!R)continue;let P=w+v.left,T=R.left-v.left,C=v.height,E=yh(b);if(!E||!Number.isFinite(E.width)||!Number.isFinite(E.height)||E.width===0)continue;let M=E.height;M||(M=C);let k=T/E.width,A=C/M,O=P-E.left*k,F=gl(y,C,E.top,M,A,g);if(g==="bottom"||g==="top"){let z=E.top+M,_=z>0?z:M||1;A=C/_,F=gl(y,C,E.top,M,A,g)}E.height||(F+=C/2);let W={d:b,translateX:O,translateY:F,scaleX:k,scaleY:A,isFill:x,fill:p.fill||"#9FFFFC",stroke:p.stroke||"#9FFFFC",strokeWidth:S};s.push(W),l(W,E)}if(s.length===0)return null;let u=e.width/2,c=Number.isFinite(a.minX)&&Number.isFinite(a.minY),h=c?Math.max(2,-u-a.minX,a.maxX-u):2,d=c?Math.max(2,r-a.minY,a.maxY-(r+e.height)):2;return{ops:s,padX:h,padY:d,inkBounds:{left:a.minX,top:a.minY,right:a.maxX,bottom:a.maxY}}},Sh=(n,e,t,r)=>{let o=Math.ceil(e.width+n.padX*2),i=Math.ceil(e.height+n.padY*2);if(!(o>0)||!(i>0)||o>8192||i>8192)return null;let s=document.createElement("canvas");s.width=Math.ceil(o*r),s.height=Math.ceil(i*r);let a=s.getContext("2d");if(!a)return null;a.setTransform(r,0,0,r,0,0),a.translate(e.width/2+n.padX,n.padY-t);for(let l of n.ops){let u=new Path2D(l.d);a.save(),a.translate(l.translateX,l.translateY),a.scale(l.scaleX,l.scaleY),l.isFill?(a.fillStyle=l.fill,a.fill(u)):(a.lineWidth=l.strokeWidth,a.strokeStyle=l.stroke,a.stroke(u)),a.restore()}return{canvas:s,logicalW:o,logicalH:i}};var co=n=>{let e=n.pathBackground;if(!e||!e.backgroundChecked||typeof e.path!="string"||!e.path.trim())return null;let t=Number(e.width)||0,r=Number(e.height)||0;if(!t||!r)return null;let o=typeof e.fill=="string"&&e.fill?e.fill:void 0;return{path:e.path,fill:o,width:t,height:r}};var Ii=n=>{let e=n.raw,t=co(e);if(!t||!t.fill)return null;let r=n.dims;if(!r.x||!r.y)return null;let o=Ce(t.path);if(!o)return null;let i=Fe(o);if(!i)return null;let s=i.right-i.left,a=i.bottom-i.top;if(!(s>0)||!(a>0))return null;let l=r.x/t.width,u=r.y/t.height,c=s*l,h=a*u;return!(c>0)||!(h>0)||c>8192||h>8192?null:{path:t.path,fill:t.fill,bounds:i,scaleX:l,scaleY:u,logicalW:c,logicalH:h,sigBase:[t.path,t.fill,t.width,t.height,r.x.toFixed(3),r.y.toFixed(3)].join(";")}},vh=(n,e)=>{let t=document.createElement("canvas");t.width=Math.ceil(n.logicalW*e),t.height=Math.ceil(n.logicalH*e);let r=t.getContext("2d");if(!r)return null;let o=(n.bounds.left+n.bounds.right)/2,i=(n.bounds.top+n.bounds.bottom)/2;r.setTransform(e*n.scaleX,0,0,e*n.scaleY,t.width/2-o*n.scaleX*e,t.height/2-i*n.scaleY*e);let s=ee(n.fill);return r.fillStyle=`rgba(${Math.round(s[0]*255)}, ${Math.round(s[1]*255)}, ${Math.round(s[2]*255)}, ${s[3]})`,r.fill(new Path2D(n.path),"nonzero"),{canvas:t,logicalW:n.logicalW,logicalH:n.logicalH}};var wh=n=>{if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n,t=Number(e.blur)||0,r=Number(e.offsetX)||0,o=Number(e.offsetY)||0;if(!t&&!r&&!o)return null;let i=typeof e.color=="string"&&e.color?e.color:"rgb(0,0,0)";return{color:i,rgba:ee(i),blur:t,offsetX:r,offsetY:o,nonScaling:!!e.nonScaling}},Lt=(n,e,t)=>{if(n.nonScaling)return{blur:n.blur,offX:n.offsetX,offY:n.offsetY};let r=Math.abs(e),o=Math.abs(t);return{blur:n.blur*(r+o)/2,offX:n.offsetX*r,offY:n.offsetY*o}},_i=n=>Math.ceil(n.blur*2+Math.max(Math.abs(n.offX),Math.abs(n.offY))+4),Th=n=>{let e=t=>String(Math.round(t*1e4)/1e4);return[n.color,e(n.blur),e(n.offsetX),e(n.offsetY),n.nonScaling?1:0].join("|")};var Vt=(n,e,t,r,o)=>{let i=[],s=o?r.fontSize*o/1e3:0,a=0;for(let l=0;l<n.graphemes.length;l++){let u=n.graphemes[l],c=n.boxes[l],h=n.charStyles[l]?.fontSize??r.fontSize,d=qn(u);d==="latin"||d==="bracket"?i.push({ch:u,rotated:!1,x:e+a+(d==="latin"?c.kernedWidth-c.width:0),y:t}):i.push({ch:u,rotated:!0,x:e+a+un(h),y:t+yr(d,c,h)}),a+=Kn(u,c,s)}return i},qt=(n,e,t)=>{if(!e.rotated){n[t](e.ch,e.x,e.y);return}n.save(),n.translate(e.x,e.y),n.rotate(-Math.PI/2),n[t](e.ch,0,0),n.restore()},fn=(n,e)=>!e||e.fontSize===void 0&&e.fontFamily===void 0&&e.fontWeight===void 0&&e.fontStyle===void 0?n:{...n,fontSize:e.fontSize??n.fontSize,fontFamily:e.fontFamily??n.fontFamily,fontWeight:e.fontWeight??n.fontWeight,fontStyle:e.fontStyle??n.fontStyle};var xl=n=>{let e=n.matrix,t=n.dims.x,r=n.dims.y;return{x:Math.abs(e[0])*t+Math.abs(e[2])*r,y:Math.abs(e[1])*t+Math.abs(e[3])*r}},Fi=n=>{let e=n.raw;return JSON.stringify([e.path,e.points,e.rx,e.ry,e.radius])},yl=(n,e,t)=>{let r=e.textLayout,o=e.textStyle;n.fillStyle=t,n.textBaseline="alphabetic";let i=e.raw.vertical===!0,s=Number(e.raw.textOffsetY)||0,a=0;for(let l of r.lines){let u=-r.width/2+l.leftOffset,c=e.contentTopY+l.baseline;if(l.prefix&&Tt(n,l,u,c,{fill:"keep"}),i){let h=Vt(l,u,c,o,o.charSpacing??0);for(let d=0;d<h.length;d++){let f=fn(o,l.charStyles[d]);n.font=Me(f,f.fontSize),qt(n,{...h[d],y:h[d].y+wt(s,f.fontSize,a+d)},"fillText")}a+=l.graphemes.length;continue}for(let h=0;h<l.graphemes.length;h++){let d=l.charStyles[h],f=fn(o,d);n.font=Me(f,f.fontSize),n.fillText(l.graphemes[h],u+l.boxes[h].left,c+wt(s,f.fontSize,a+h))}a+=l.graphemes.length}},Di=(n,e,t)=>{let r=e.dims.x,o=e.dims.y;if(e.isSolidType){n.fillStyle=t;let i=it(e.raw,r,o);if(i){jn(n,r,o,i.rx,i.ry),n.fill();return}n.fillRect(-r/2,-o/2,r,o);return}if(e.isShapeType){let i=e.raw;if(se(i)===L.ELLIPSE||se(i)===L.CIRCLE){n.fillStyle=t,n.beginPath(),n.ellipse(0,0,r/2,o/2,0,0,Math.PI*2),n.fill();return}let s=e.shapeMesh;if(!s)return;n.fillStyle=t,n.beginPath();let a=s.verts.length/2;for(let l=0;l<a;l++){let u=s.verts[l*2],c=s.verts[l*2+1];l===0?n.moveTo(u,c):n.lineTo(u,c)}n.closePath(),n.fill();return}if(e instanceof ie){let i=e.paintSource;i&&n.drawImage(i,-r/2,-o/2,r,o);return}if((e.isImageType||e.isMaskType)&&e.imageEl){let i=e.cropRect,s=e.isImageType&&!(e instanceof ie)?br(e.raw,r,o):null;s&&(n.save(),jn(n,r,o,s,s),n.clip()),i?n.drawImage(e.imageEl,i.sx,i.sy,i.sw,i.sh,-r/2,-o/2,r,o):n.drawImage(e.imageEl,-r/2,-o/2,r,o),s&&n.restore();return}if(e.isTextType&&e instanceof ye){if(Kt(e)){if(!e.imageEl)return;let i=e.bitmapRect;n.save(),n.translate(i.x,i.y),i.angle&&n.rotate(-i.angle*Math.PI/180),n.drawImage(e.imageEl,-i.w/2,-i.h/2,i.w,i.h),n.restore();return}yl(n,e,t)}},Eh=(n,e)=>{let t=Lt(e,n.raw.scaleX??1,n.raw.scaleY??1),r=_i(t)+(n.isTextType?Math.ceil((n.raw.fontSize??40)*.5):0),o=xl(n),i=Math.ceil(o.x+r*2),s=Math.ceil(o.y+r*2);if(!(i>0)||!(s>0)||i>8192||s>8192)return null;let a=document.createElement("canvas");a.width=i,a.height=s;let l=a.getContext("2d");if(!l)return null;let u=n.matrix;l.setTransform(u[0],u[1],u[2],u[3],i/2,s/2);let c=`rgba(${Math.round(e.rgba[0]*255)},${Math.round(e.rgba[1]*255)},${Math.round(e.rgba[2]*255)},1)`;return l.shadowColor=e.color,l.shadowBlur=t.blur,l.shadowOffsetX=t.offX,l.shadowOffsetY=t.offY,Di(l,n,c),l.shadowColor="rgba(0,0,0,0)",l.shadowBlur=0,l.shadowOffsetX=0,l.shadowOffsetY=0,l.globalCompositeOperation="destination-out",Di(l,n,c),{canvas:a,w:i,h:s}};var uo=(n,e,t)=>{let r=e+t,o=n,i=new Int32Array(e*t);for(let f=0;f<e;f++){o[f+0*e]?i[f+0*e]=0:i[f+0*e]=r;for(let m=1;m<t;m++)o[f+m*e]?i[f+m*e]=0:i[f+m*e]=1+i[f+(m-1)*e];for(let m=t-2;m>=0;m--)i[f+(m+1)*e]<i[f+m*e]&&(i[f+m*e]=1+i[f+(m+1)*e])}let s=(f,m,p)=>(f-m)*(f-m)+p*p,a=(f,m,p,b)=>Math.floor((m*m-f*f+b*b-p*p)/(2*(m-f))),l=new Int32Array(e*t),u=new Int32Array(e),c=new Int32Array(e),h,d;for(let f=0;f<t;f++){h=0,u[0]=0,c[0]=0;for(let m=1;m<e;m++){for(;h>=0&&s(c[h],u[h],i[u[h]+f*e])>s(c[h],m,i[m+f*e]);)h--;h<0?(h=0,u[0]=m):(d=1+a(u[h],m,i[u[h]+f*e],i[m+f*e]),d<e&&(h++,u[h]=m,c[h]=d))}for(let m=e-1;m>=0;m--){let p=s(m,u[h],i[u[h]+f*e]);p=Math.floor(Math.sqrt(p)),l[m+f*e]=p,m===c[h]&&h--}}return l},Sl=(n,e=10)=>{let t=new Uint8Array(n.length/4);for(let r=0;r<t.length;r++)t[r]=n[r*4+3]>e?1:0;return t};var Ch=(n,e)=>e==="smooth"?6*n*(1-n):1,Mh=(n,e,t,r,o,i)=>{let s=r*o,a=new Float32Array(s),l=new Float32Array(s),u=Math.max(i.sizePx,.5),c=i.angleDeg*Math.PI/180,h=Math.sin(c),d=-Math.cos(c),f=Math.max(0,i.strength)*((90-Math.min(90,Math.max(0,i.altitudeDeg)))/90),m=i.style==="pillow"!==i.directionDown,p=i.style==="inner"||i.style==="emboss"||i.style==="pillow",b=i.style==="outer"||i.style==="emboss"||i.style==="pillow",g=(w,y,v)=>{let R=Math.min(1,Math.max(0,y)*v*f);R<=0||(m?l[w]=Math.min(1,l[w]+R):a[w]=Math.min(1,a[w]+R))},x=(w,y,v)=>{let R=Math.min(1,Math.max(0,-y)*v*f);R<=0||(m?a[w]=Math.min(1,a[w]+R):l[w]=Math.min(1,l[w]+R))},S=(w,y,v)=>{let R=w[Math.min(y+1,r-1)+v*r]-w[Math.max(y-1,0)+v*r],P=w[y+Math.min(v+1,o-1)*r]-w[y+Math.max(v-1,0)*r];return[R,P]};for(let w=0;w<o;w++)for(let y=0;y<r;y++){let v=y+w*r;if(t[v]){if(!p)continue;let R=n[v]-.5;if(R>=u)continue;let P=Math.max(0,R/u),[T,C]=S(n,y,w),E=Math.hypot(T,C);if(E<1e-6)continue;let M=-(T/E*h+C/E*d),k=Ch(P,i.technique);g(v,M,k),x(v,M,k)}else{if(!b)continue;let R=e[v]-.5;if(R>=u)continue;let P=Math.max(0,1-R/u),[T,C]=S(e,y,w),E=Math.hypot(T,C);if(E<1e-6)continue;let M=T/E*h+C/E*d,k=Ch(P,i.technique);g(v,M,k),x(v,M,k)}}return{highlight:a,shadow:l}};var Rh={Brownie:[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0],Vintage:[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0],Kodachrome:[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0],Technicolor:[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0],Polaroid:[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],Sepia:[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0],BlackWhite:[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]},me=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,mn=(n,e)=>typeof n=="string"&&n?n:e,vl=(n,e)=>typeof n=="boolean"?n:e;function Ag(n){let e=i=>Math.max(0,Math.min(255,Math.round(i))),t=n.map(i=>({input:e(i.input),output:e(i.output)}));t.sort((i,s)=>i.input-s.input);let r=[];for(let i of t)r.length&&r[r.length-1].input===i.input?r[r.length-1]=i:r.push(i);if(r.length<2)return[];if(r.length<=16)return r;let o=[];for(let i=0;i<16;i++){let s=e(i/15*255);o.push({input:s,output:e(Ng(r,s))})}return o}function Ng(n,e){if(n.length===0)return e;let t=n[0],r=n[n.length-1];if(e<=t.input)return t.output;if(e>=r.input)return r.output;for(let o=0;o<n.length-1;o++){let i=n[o],s=n[o+1];if(e>=i.input&&e<=s.input){let a=(e-i.input)/Math.max(1e-5,s.input-i.input);return i.output+(s.output-i.output)*a}}return e}function Lg(n){if(!Array.isArray(n))return[];let e=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=o.input,s=o.output;typeof i!="number"||!Number.isFinite(i)||typeof s!="number"||!Number.isFinite(s)||e.push({input:i,output:s})}let t=[];for(let r of Ag(e))t.push(r.input,r.output);return t}function ho(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,o=r.psd===1;switch(r.type){case"Brightness":e.push({kind:"Brightness",brightness:o?me(r.brightness,0)/100:me(r.brightness,0)});break;case"Contrast":e.push({kind:"Contrast",contrast:o?me(r.contrast,0)/100:me(r.contrast,0)});break;case"Saturation":e.push({kind:"Saturation",saturation:o?me(r.saturation,0)/100:me(r.saturation,0)});break;case"Vibrance":e.push({kind:"Vibrance",vibrance:o?me(r.vibrance,0)/100:me(r.vibrance,0)});break;case"HueRotation":e.push({kind:"HueRotation",rotation:o?me(r.hue,0)/100:me(r.rotation,0)});break;case"Grayscale":{let i=mn(r.mode,"average");e.push({kind:"Grayscale",mode:i==="lightness"||i==="luminosity"?i:"average"});break}case"Invert":e.push({kind:"Invert",invert:vl(r.invert,!0),alphaOnly:vl(r.alphaOnly,!1)});break;case"Sepia":case"Brownie":case"Kodachrome":case"Technicolor":case"Polaroid":case"BlackWhite":case"Vintage":e.push({kind:"ColorMatrix",matrixId:r.type});break;case"ColorMatrix":{let i=Array.isArray(r.matrix)?r.matrix.filter(s=>typeof s=="number"&&Number.isFinite(s)):[];i.length===20&&e.push({kind:"ColorMatrixOp",matrix:i});break}case"Blur":e.push({kind:"Blur",blur:me(o?r.radius:r.blur,0)});break;case"Noise":e.push({kind:"Noise",noise:me(r.noise,0)});break;case"Pixelate":e.push({kind:"Pixelate",blocksize:me(r.blocksize,1)});break;case"Convolute":{let i=Array.isArray(r.matrix)?r.matrix.filter(a=>typeof a=="number"):[],s=Math.sqrt(i.length);Number.isInteger(s)&&s>=3&&s<=9&&e.push({kind:"Convolute",matrix:i,opaque:vl(r.opaque,!1)});break}case"BlendColor":{let i=mn(r.mode,"multiply"),s=["multiply","screen","add","difference","subtract","darken","lighten","overlay","exclusion","tint"];e.push({kind:"BlendColor",color:mn(r.color,"#000000"),mode:s.includes(i)?i:"multiply",alpha:me(r.alpha,1)});break}case"Vignette":e.push({kind:"Vignette",intensity:me(r.intensity,0)});break;case"Temperature":{if(o){let i=pn(mn(r.color,"#ffb86b")),s=i[0]>=i[2];e.push({kind:"Temperature",temperature:me(r.density,0)/100*(s?1:-1)})}else e.push({kind:"Temperature",temperature:me(r.temperature,0)});break}case"Posterize":e.push({kind:"Posterize",levels:me(r.levels,20)});break;case"FilmGrain":e.push({kind:"FilmGrain",intensity:me(r.intensity,0),seed:me(r.seed,0)});break;case"Duotone":e.push({kind:"Duotone",color1:mn(r.color1,"#000000"),color2:mn(r.color2,"#ffffff")});break;case"Sketch":e.push({kind:"Sketch"});break;case"ChromaticAberration":e.push({kind:"ChromaticAberration",offset:me(r.offset,4)});break;case"SoftFocus":e.push({kind:"SoftFocus",blend:me(r.blend,.5)});break;case"Threshold":e.push({kind:"Threshold",threshold:me(r.threshold,128)});break;case"UnsharpMask":e.push({kind:"UnsharpMask",amount:o?me(r.amount,100)/100:me(r.amount,1)});break;case"MotionBlur":e.push({kind:"MotionBlur",distance:me(r.distance,0),angle:me(r.angle,0)});break;case"LensFlare":e.push({kind:"LensFlare",intensity:me(r.intensity,.8)});break;case"GradientMap":e.push({kind:"GradientMap",color0:mn(r.color0,"#000000"),color1:mn(r.color1,"#888888"),color2:typeof r.color2=="string"&&r.color2?r.color2:""});break;case"Levels":e.push({kind:"Levels",blackPoint:me(r.blackPoint,0),whitePoint:me(r.whitePoint,255),gamma:me(r.gamma,1)});break;case"Curves":e.push({kind:"Curves",points:Lg(r.points)});break;case"SurfaceBlur":e.push({kind:"SurfaceBlur",radius:me(r.radius,3),threshold:o?me(r.threshold,51)/255:me(r.threshold,.2)});break;case"Exposure":e.push({kind:"Exposure",exposure:me(r.exposure,0),offset:me(r.offset,0),gamma:me(r.gamma,1)});break;default:break}}return e}function Oi(n){return JSON.stringify(n)}var eT=Math.PI/2;function pn(n){let e=n.replace("#","");return/^[0-9a-fA-F]{6}$/.test(e)?[parseInt(e.substring(0,2),16),parseInt(e.substring(2,4),16),parseInt(e.substring(4,6),16)]:[0,0,0]}var wl=new Map,Ph=(n,e)=>{wl.set(n,new WeakRef(e))},Ig=n=>{let e=wl.get(n);if(!e)return null;let t=e.deref();return t||(wl.delete(n),null)},kh=n=>Ig(n);var Qt=(n,e,t,r,o,i,s)=>{t?n.drawImage(e,t.sx,t.sy,t.sw,t.sh,r,o,i,s):n.drawImage(e,r,o,i,s)},_g=6e5,Bi=n=>Math.max(1,Math.floor(Math.sqrt(_g/Math.max(1,n.dims.x*n.dims.y)))),Wi=n=>{if(!n.isImageType||n instanceof ie)return"";let e=ho(n.raw.filters);return e.length?`|f${Oi(e)}`:""},It=n=>!n.isImageType||n instanceof ie?null:br(n.raw,n.dims.x,n.dims.y),Nh=n=>{let e=It(n);return e?`|rr${e}`:""},Tl=(n,e,t,r,o,i,s)=>{n.save(),n.translate(t,r),e&&(jn(n,o,i,e,e),n.clip()),s(),n.restore()},fo=(n,e,t,r,o)=>{if(!t)return n;let i=document.createElement("canvas");i.width=r,i.height=o;let s=i.getContext("2d",{willReadFrequently:!0});return s?(Tl(s,t,r/2,o/2,r,o,()=>Qt(s,n,e,-r/2,-o/2,r,o)),i):n},Dg=n=>{let e=n.matrix,t=n.dims.x,r=n.dims.y;return{x:Math.abs(e[0])*t+Math.abs(e[2])*r,y:Math.abs(e[1])*t+Math.abs(e[3])*r}},Ah=n=>({color:n.color,rgba:n.rgba,blur:n.blur,offsetX:n.offsetX,offsetY:n.offsetY,nonScaling:!1}),mo=(n,e=1)=>{let t=Math.max(1,Math.ceil(n.dims.x*e)),r=Math.max(1,Math.ceil(n.dims.y*e));if(t>8192||r>8192)return null;let o=document.createElement("canvas");o.width=t,o.height=r;let i=o.getContext("2d");return i?(i.translate(t/2,r/2),i.scale(e,e),yl(i,n,"#ffffff"),o):null},Hi=(n,e,t,r=1,o=null)=>{if(!t||e.length===0)return null;let i=n.raw.scaleX??1,s=n.raw.scaleY??1,a=4;for(let y of e){let v=Lt(Ah(y),i,s);a=Math.max(a,Math.ceil(v.blur*2+Math.max(Math.abs(v.offX),Math.abs(v.offY))+4))}let l=Dg(n),u=Math.ceil(l.x+a*2),c=Math.ceil(l.y+a*2),h=Math.ceil(u*r),d=Math.ceil(c*r);if(!(u>0)||!(c>0)||h>8192||d>8192)return null;let f=It(n),m=f?fo(t,o,f*r,Math.max(1,Math.ceil(n.dims.x*r)),Math.max(1,Math.ceil(n.dims.y*r))):t,p=f?null:o,b=document.createElement("canvas");b.width=h,b.height=d;let g=b.getContext("2d");if(!g)return null;let x=n.matrix;g.setTransform(x[0]*r,x[1]*r,x[2]*r,x[3]*r,h/2,d/2);let S=n.dims.x,w=n.dims.y;for(let y of e){let v=Lt(Ah(y),i,s);g.filter=`drop-shadow(${v.offX*r}px ${v.offY*r}px ${v.blur*r}px ${y.color})`,Qt(g,m,p,-S/2,-w/2,S,w)}return g.filter="none",g.globalCompositeOperation="destination-out",Qt(g,m,p,-S/2,-w/2,S,w),{canvas:b,w:h,h:d,quadW:u,quadH:c}},Lh=(n,e,t)=>{let r=[1,0,0,1,n.offsetX,n.offsetY];return n.gradientUnits==="percentage"&&(r=j(r,[e,0,0,t,0,0])),n.gradientTransform&&(r=j(r,n.gradientTransform)),r},Fg=(n,e,t,r)=>{let o=j([1,0,0,1,r,r],Lh(n,e,t)),i=ve(o),s=mi(n,512),a=511,l=n.kind==="linear";return(u,c)=>{let h=u+.5,d=c+.5,f=i[0]*h+i[2]*d+i[4],m=i[1]*h+i[3]*d+i[5],p=l?Lu(n,{x:f,y:m}):Iu(n,{x:f,y:m}),b=Math.min(a,Math.max(0,Math.round((isFinite(p)?p:0)*a)));return[s[b*4],s[b*4+1],s[b*4+2],s[b*4+3]]}},Ih=(n,e,t,r)=>{let o=ve(e),i=[Q(o,0,0),Q(o,t,0),Q(o,0,r),Q(o,t,r)];if(i.every(s=>isFinite(s.x)&&isFinite(s.y))){let s=Math.min(...i.map(c=>c.x))-2,a=Math.max(...i.map(c=>c.x))+2,l=Math.min(...i.map(c=>c.y))-2,u=Math.max(...i.map(c=>c.y))+2;n.fillRect(s,l,a-s,u-l)}else n.fillRect(-t-r,-t-r,(t+r)*3,(t+r)*3)},Og=(n,e,t,r,o,i)=>{let s=i(e.src);if(!s)return!1;let a;try{a=n.createPattern(s,e.repeat)}catch{return!1}if(!a)return!1;let l=[o,0,0,o,0,0];return l=j(l,[1,0,0,1,e.offsetX,e.offsetY]),e.patternTransform&&(l=j(l,e.patternTransform)),n.setTransform(l[0],l[1],l[2],l[3],l[4],l[5]),n.fillStyle=a,Ih(n,l,t,r),n.setTransform(1,0,0,1,0,0),!0},vr=(n,e,t,r=1,o=null,i=kh)=>{if(!t)return null;let s=Math.max(1,Math.ceil(n.dims.x)),a=Math.max(1,Math.ceil(n.dims.y)),l=Math.ceil(s*r),u=Math.ceil(a*r);if(l>8192||u>8192)return null;let c=document.createElement("canvas");c.width=l,c.height=u;let h=c.getContext("2d");if(!h)return null;if(e.kind==="gradient"){let f=e.decl,m=Lh(f,l,u);h.setTransform(m[0],m[1],m[2],m[3],m[4],m[5]);let p=f.kind==="linear"?h.createLinearGradient(f.x1,f.y1,f.x2,f.y2):h.createRadialGradient(f.x1,f.y1,f.r1,f.x2,f.y2,f.r2);for(let b of f.stops){let g=Math.min(1,Math.max(0,b.offset));p.addColorStop(g,`rgba(${Math.round(b.color[0]*255)}, ${Math.round(b.color[1]*255)}, ${Math.round(b.color[2]*255)}, ${b.color[3]})`)}h.fillStyle=p,f.gradientUnits==="percentage"?h.fillRect(-2,-2,5,5):Ih(h,m,l,u),h.setTransform(1,0,0,1,0,0)}else if(e.kind==="pattern"){if(!Og(h,e.decl,l,u,r,i))return null}else h.fillStyle=e.color,h.fillRect(0,0,l,u);h.globalCompositeOperation="destination-in";let d=It(n);return d?Qt(h,fo(t,o,d*r,l,u),null,0,0,l,u):Qt(h,t,o,0,0,l,u),c},_h=(n,e)=>{if(e.length===0)return null;let t=n.raw.fill;if(t==null||t===""||t==="transparent")return null;let r=Math.abs(n.matrix[0])*n.dims.x+Math.abs(n.matrix[2])*n.dims.y,o=Math.abs(n.matrix[1])*n.dims.x+Math.abs(n.matrix[3])*n.dims.y,i=4;for(let h of e)i=Math.max(i,Math.ceil(h.blur*2+Math.max(Math.abs(h.offsetX),Math.abs(h.offsetY))+4));let s=Math.ceil(r+i*2),a=Math.ceil(o+i*2);if(!(s>0)||!(a>0)||s>8192||a>8192)return null;let l=document.createElement("canvas");l.width=s,l.height=a;let u=l.getContext("2d");if(!u)return null;let c=n.matrix;u.setTransform(c[0],c[1],c[2],c[3],s/2,a/2);for(let h of e){if(u.filter=`drop-shadow(${h.offsetX}px ${h.offsetY}px ${h.blur}px ${h.color})`,u.fillStyle=to(n,u),!xr(u,n))return null;u.fill()}return u.filter="none",{canvas:l,w:s,h:a,quadW:s,quadH:a}},Dh=(n,e=1)=>{let t=Math.max(1,Math.ceil(n.dims.x*e)),r=Math.max(1,Math.ceil(n.dims.y*e));if(t>8192||r>8192)return null;let o=document.createElement("canvas");o.width=t,o.height=r;let i=o.getContext("2d");return!i||(i.setTransform(e,0,0,e,t/2,r/2),i.fillStyle="#fff",!xr(i,n))?null:(i.fill(n.raw.fillRule==="evenodd"?"evenodd":"nonzero"),o)},wr=(n,e,t,r=1,o=null)=>{if(!t)return null;let i=Math.max(1,Math.ceil(n.dims.x)),s=Math.max(1,Math.ceil(n.dims.y)),a=Math.ceil(i*r),l=Math.ceil(s*r);if(a>8192||l>8192)return null;let u=It(n),c=u?fo(t,o,u*r,a,l):t,h=document.createElement("canvas");h.width=a,h.height=l;let d=h.getContext("2d");if(!d)return null;Qt(d,c,u?null:o,0,0,a,l),d.globalCompositeOperation="source-in",d.fillStyle=e.color,d.fillRect(0,0,a,l);let f=document.createElement("canvas");f.width=a,f.height=l;let m=f.getContext("2d");return m?(m.drawImage(h,0,0),m.globalCompositeOperation="destination-out",e.blur>0&&(m.filter=`blur(${e.blur}px)`),Qt(m,c,u?null:o,e.offsetX,e.offsetY,a,l),m.filter="none",m.globalCompositeOperation="source-over",f):null},bn=(n,e,t,r=!0,o=1,i=null,s=!1)=>{if(!t||e.length===0)return[];let a=o,l=Math.max(1,Math.ceil(n.dims.x*a)),u=Math.max(1,Math.ceil(n.dims.y*a));if((l>8192||u>8192)&&(a=1,l=Math.max(1,Math.ceil(n.dims.x)),u=Math.max(1,Math.ceil(n.dims.y))),l>8192||u>8192)return[];let c=document.createElement("canvas");c.width=l,c.height=u;let h=c.getContext("2d",{willReadFrequently:!0});if(!h)return[];let d=It(n),f=n.dims.x*a,m=n.dims.y*a;Tl(h,d?d*a:null,l/2,u/2,f,m,()=>Qt(h,t,i,-f/2,-m/2,f,m));let p=[];for(let b=e.length-1;b>=0;b--){let g=e[b],x=g.width,S=g.alignment,w=S==="outside"?x:S==="center"?Math.ceil(x/2):0,y=w*a,v=Math.floor(l+y*2),R=Math.floor(u+y*2);if(v<=0||R<=0)continue;let P=document.createElement("canvas");P.width=v,P.height=R;let T=P.getContext("2d",{willReadFrequently:!0});if(!T)continue;T.drawImage(c,y,y);let C=Sl(T.getImageData(0,0,v,R).data),E=uo(C,v,R),M=new Uint8Array(C.length);for(let U=0;U<C.length;U++)M[U]=C[U]?0:1;for(let U=0;U<v;U++)M[U]=1,M[U+(R-1)*v]=1;for(let U=0;U<R;U++)M[U*v]=1,M[v-1+U*v]=1;let k=uo(M,v,R),A=v*R,O=new Int32Array(A);for(let U=0;U<A;U++)O[U]=C[U]?-k[U]:E[U];let F=s?.5*a:0,W,z;S==="inside"?(W=-x*a-F,z=F):S==="center"?(W=-x/2*a-F,z=x/2*a+F):(W=-F,z=x*a+F);let _=Math.round(g.rgba[0]*255),D=Math.round(g.rgba[1]*255),I=Math.round(g.rgba[2]*255),G=Math.round(g.rgba[3]*255),$=g.kind==="gradient"&&g.decl?Fg(g.decl,l,u,y):null,V=document.createElement("canvas");V.width=v,V.height=R;let H=V.getContext("2d");if(!H)continue;let Y=H.createImageData(v,R),X=Y.data;for(let U=0;U<A;U++){let oe=O[U];if(oe>=W&&oe<z){let ne=U*4;if($){let de=$(U%v,U/v|0);X[ne]=de[0],X[ne+1]=de[1],X[ne+2]=de[2],X[ne+3]=de[3]}else X[ne]=_,X[ne+1]=D,X[ne+2]=I,X[ne+3]=G}}H.putImageData(Y,0,0);let Z=document.createElement("canvas");Z.width=v,Z.height=R;let B=Z.getContext("2d");if(!B)continue;r&&B.drawImage(c,y,y),B.drawImage(V,0,0);let q=S==="outside"?x:S==="center"?x/2:0;p.push({canvas:Z,w:v,h:R,quadW:v/a,quadH:R/a,dx:w-q+g.offset.x,dy:w-q+g.offset.y})}return p},Fh=(n,e,t,r=1,o=null)=>{if(!t)return null;let i=r,s=Math.max(1,Math.ceil(n.dims.x*i)),a=Math.max(1,Math.ceil(n.dims.y*i));if((s>8192||a>8192)&&(i=1,s=Math.max(1,Math.ceil(n.dims.x)),a=Math.max(1,Math.ceil(n.dims.y))),s>8192||a>8192)return null;let l=document.createElement("canvas");l.width=s,l.height=a;let u=l.getContext("2d",{willReadFrequently:!0});if(!u)return null;let c=It(n),h=n.dims.x*i,d=n.dims.y*i;Tl(u,c?c*i:null,s/2,a/2,h,d,()=>Qt(u,t,o,-h/2,-d/2,h,d));let f=e.sizePx*i,m=e.style==="outer"||e.style==="emboss"||e.style==="pillow"?Math.ceil(f):0,p=s+m*2,b=a+m*2,g=document.createElement("canvas");g.width=p,g.height=b;let x=g.getContext("2d",{willReadFrequently:!0});if(!x)return null;x.drawImage(l,m,m);let S=Sl(x.getImageData(0,0,p,b).data),w=uo(S,p,b),y=new Uint8Array(S.length);for(let T=0;T<S.length;T++)y[T]=S[T]?0:1;for(let T=0;T<p;T++)y[T]=1,y[T+(b-1)*p]=1;for(let T=0;T<b;T++)y[T*p]=1,y[p-1+T*p]=1;let v=uo(y,p,b),R=Mh(v,w,S,p,b,{sizePx:f,angleDeg:e.angleDeg,altitudeDeg:e.altitudeDeg,strength:e.strength,directionDown:e.directionDown,technique:e.technique,style:e.style}),P=(T,C,E)=>{let M=document.createElement("canvas");M.width=p,M.height=b;let k=M.getContext("2d");if(!k)return M;let A=ee(C),O=Math.round(A[0]*255),F=Math.round(A[1]*255),W=Math.round(A[2]*255),z=k.createImageData(p,b),_=z.data;for(let D=0;D<T.length;D++){let I=T[D];if(I<=0)continue;let G=D*4;_[G]=O,_[G+1]=F,_[G+2]=W,_[G+3]=Math.round(Math.min(1,I*E)*255)}return k.putImageData(z,0,0),M};return{highlight:P(R.highlight,e.highlight.color,e.highlight.opacity),shadow:P(R.shadow,e.shadow.color,e.shadow.opacity),w:p,h:b,quadW:p/i,quadH:b/i,dx:0,dy:0}};var Oh=n=>Sr(n),Qe=2,po=(n,e)=>{let t=e.textLayout,r=e.textStyle,o=e.textStroke;n.textBaseline="alphabetic";for(let i of t.lines){let s=-t.width/2+i.leftOffset,a=e.contentTopY+i.baseline,l=i.charStyles[0],u=typeof l?.fill=="string"&&l.fill?l.fill:typeof e.raw.fill=="string"?e.raw.fill:null,c="",h=i.prefix?Tt(n,i,s,a,{fill:u,stroke:Oe(o,l)}):0,d="",f="",m=null,p=b=>{if(!c)return;n.font=d;let g=s+h;typeof f=="string"&&f?(n.fillStyle=f,n.fillText(c,g,a)):typeof e.raw.fill=="string"&&e.raw.fill&&(n.fillStyle=e.raw.fill,n.fillText(c,g,a)),m&&m.width>0&&(n.lineWidth=m.width,n.strokeStyle=m.color,n.strokeText(c,g,a)),c="",b<i.boxes.length&&(h=i.boxes[b].left)};for(let b=0;b<i.graphemes.length;b++){let g=i.charStyles[b],S=g!==void 0&&(g.fontSize!==void 0||g.fontFamily!==void 0||g.fontWeight!==void 0||g.fontStyle!==void 0)&&g?{...r,fontSize:g.fontSize??r.fontSize,fontFamily:g.fontFamily??r.fontFamily,fontWeight:g.fontWeight??r.fontWeight,fontStyle:g.fontStyle??r.fontStyle}:r,w=Me(S,S.fontSize),y=Oe(o,g),v=typeof g?.fill=="string"?g.fill:"",R=m;c&&(w!==d||y?.color!==R?.color||y?.width!==R?.width||v!==f)&&p(b),c||(d=w,m=y,f=v),c+=i.graphemes[b]}p(i.graphemes.length)}},Tr=n=>{let e=0;for(let t of n.strokes)e=Math.max(e,t.alignment==="outside"?t.width:t.alignment==="center"?Math.ceil(t.width/2):0);for(let t of n.dropShadows)e=Math.max(e,Math.ceil(t.blur*2+Math.max(Math.abs(t.offsetX),Math.abs(t.offsetY))));for(let t of n.solidFills)e=Math.max(e,Math.ceil(Math.max(Math.abs(t.offset.x),Math.abs(t.offset.y))));return e},El=(n,e,t)=>{let r=4;for(let m of n)r=Math.max(r,Math.ceil(m.blur*2+Math.max(Math.abs(m.offsetX),Math.abs(m.offsetY))+4));let o=e.width/t,i=e.height/t,s=Math.ceil(o+r*2),a=Math.ceil(i+r*2),l=Math.ceil(s*t),u=Math.ceil(a*t);if(!(l>0)||!(u>0)||l>8192||u>8192)return null;let c=document.createElement("canvas");c.width=l,c.height=u;let h=c.getContext("2d");if(!h)return null;let d=(l-e.width)/2,f=(u-e.height)/2;for(let m of n)h.filter=`drop-shadow(${m.offsetX*t}px ${m.offsetY*t}px ${m.blur*t}px ${m.color})`,h.drawImage(e,d,f);return h.filter="none",h.globalCompositeOperation="destination-out",h.drawImage(e,d,f),{canvas:c,w:s,h:a}},bo=(n,e,t)=>{if(!t||t.dropShadows.length===0&&t.innerShadows.length===0&&t.solidFills.length===0&&t.strokes.length===0)return;let r=mo(e,Qe);if(!r)return;let o=e.dims.x,i=e.dims.y;if(t.dropShadows.length){let l=El(t.dropShadows,r,Qe);l&&(n.save(),n.globalCompositeOperation="destination-over",n.drawImage(l.canvas,-l.w/2,-l.h/2,l.w,l.h),n.restore())}let s=(l,u)=>{if(!l){u();return}n.save(),n.globalCompositeOperation=l,u(),n.restore()};for(let l of t.innerShadows){let u=wr(e,l,r,Qe);u&&s(l.blendMode,()=>n.drawImage(u,-o/2,-i/2,o,i))}for(let l of t.solidFills){let u=vr(e,l,r,Qe);u&&s(l.blendMode,()=>n.drawImage(u,-o/2+l.offset.x,-i/2+l.offset.y,o,i))}bn(e,t.strokes,r,!1,Math.min(2,Qe),null,!0).forEach((l,u)=>{let c=t.strokes[t.strokes.length-1-u];s(c?.blendMode,()=>n.drawImage(l.canvas,-l.quadW/2+l.dx,-l.quadH/2+l.dy,l.quadW,l.quadH))})},Cl=(n,e,t=null)=>{let r=n.textLayout,o=Number(n.raw.fontSize)||40,i=Math.max(-1,Math.min(1,Number(n.raw.warpStrength)||0)),s=typeof n.raw.width=="number"?n.raw.width:r.width,a=typeof n.raw.height=="number"?n.raw.height:r.height,l=o*(e==="arch"?.6:.5),u=Math.max(r.width,s,o),c=Math.max(a,o),h=e==="arch"?c*Math.max(0,i):0,d=e==="flag"?Math.abs(i)*(a||o)*.3:0,f=1+Math.abs(i),m=t?Tr(t):0,p=Math.ceil(u+l*2+m*2),b=Math.ceil(e==="arch"?c+l*2+m*2+h:e==="flag"?(a||o)+d*2+l*2+m*2:(a||o)*f+l*2+m*2),g=p*Qe,x=b*Qe;if(!(g>0)||!(x>0)||g>8192||x>8192)return null;let S=document.createElement("canvas");S.width=g,S.height=x;let w=S.getContext("2d",{willReadFrequently:!0});if(!w)return null;let y=e==="arch"?h/2*Qe:0;w.setTransform(Qe,0,0,Qe,g/2,x/2+y),po(w,n),bo(w,n,t);let v=w.getImageData(0,0,g,x),R=new Uint32Array(v.data.buffer),P=g,T=0,C=x,E=0,M=!1;for(let _=0;_<x;_++)for(let D=0;D<g;D++)(R[_*g+D]>>>24&255)>10&&(M=!0,D<P&&(P=D),D>T&&(T=D),_<C&&(C=_),_>E&&(E=_));let k=M?(P+T)/2:g/2,A=M?E:x-1,O=M?Math.max(1,T-P)/2:g/2,F=w.createImageData(g,x),W=new Uint32Array(F.data.buffer),z=(_,D)=>{let I=Math.floor(D),G=I+1;if(I<0||G>=x)return 0;let $=D-I,V=R[I*g+_],H=R[G*g+_],Y=V>>>24&255,X=H>>>24&255;if(Y<=10&&X<=10)return 0;let Z=Math.round((V&255)*(1-$)+(H&255)*$),B=Math.round((V>>>8&255)*(1-$)+(H>>>8&255)*$),q=Math.round((V>>>16&255)*(1-$)+(H>>>16&255)*$);return Math.round(Y*(1-$)+X*$)<<24|q<<16|B<<8|Z};if(e==="flag")for(let _=0;_<g;_++){let D=O>0?(_-k)/O:0,I=Math.sin(D*Math.PI)*d*Qe*i;for(let G=0;G<x;G++)W[G*g+_]=z(_,G+I)}else if(e==="arch")for(let _=0;_<g;_++){let D=Math.max(-1,Math.min(1,(_-k)/O)),I=Math.sqrt(Math.max(0,1-D*D)),G=I*I*(3-2*I),$=i>0?Math.pow(G,2.5):G,V=Math.min(1+Math.max(0,i),Math.max(.05,1+i*$));for(let H=0;H<=A;H++){let Y=A-H;W[H*g+_]=z(_,A-Y/V)}}else{let _=M?(C+E)/2:x/2;for(let D=0;D<g;D++){let I=O>0?(D-k)/O:0,G=1+i*(I*I-.5);G=Math.min(1+Math.abs(i),Math.max(.4,G));for(let $=0;$<x;$++)W[$*g+D]=z(D,_+($-_)/G)}}return w.setTransform(1,0,0,1,0,0),w.clearRect(0,0,g,x),w.putImageData(F,0,0),{canvas:S,logicalW:p,logicalH:b}},Gi=(n,e)=>{let t=e.textLayout,r=e.textStyle,o=e.textStroke,i=typeof e.raw.fill=="string"?e.raw.fill:"",s=Number(e.raw.textOffsetY)||0;n.textBaseline="alphabetic";let a=0;for(let l of t.lines){let u=-t.width/2+l.leftOffset,c=e.contentTopY+l.baseline,h=l.charStyles[0],d=typeof h?.fill=="string"&&h.fill?h.fill:i||null;l.prefix&&Tt(n,l,u,c,{fill:d,stroke:Oe(o,h)});let f=Vt(l,u,c,r,r.charSpacing??0);for(let m=0;m<f.length;m++){let p=l.charStyles[m],b=fn(r,p);n.font=Me(b,b.fontSize);let g=typeof p?.fill=="string"&&p.fill?p.fill:i,x=Oe(o,p),S={...f[m],y:f[m].y+wt(s,b.fontSize,a+m)};g&&(n.fillStyle=g,qt(n,S,"fillText")),x&&x.width>0&&(n.lineWidth=x.width,n.strokeStyle=x.color,qt(n,S,"strokeText"))}a+=l.graphemes.length}},Bg=(n,e)=>{let t=e?Tr(e):0,r=Math.ceil(n.dims.x+t*2),o=Math.ceil(n.dims.y+t*2),i=r*Qe,s=o*Qe;if(!(i>0)||!(s>0)||i>8192||s>8192)return null;let a=document.createElement("canvas");a.width=i,a.height=s;let l=a.getContext("2d");return l?(l.setTransform(Qe,0,0,Qe,i/2,s/2),n.raw.vertical===!0?Gi(l,n):po(l,n),bo(l,n,e),{canvas:a,logicalW:r,logicalH:o}):null};var Wh=2,gn=(n,e)=>e!==void 0&&(e.fontSize!==void 0||e.fontFamily!==void 0||e.fontWeight!==void 0||e.fontStyle!==void 0)&&e?{...n,fontSize:e.fontSize??n.fontSize,fontFamily:e.fontFamily??n.fontFamily,fontWeight:e.fontWeight??n.fontWeight,fontStyle:e.fontStyle??n.fontStyle}:n,Hh=(n,e,t,r)=>{let o=e.textStyle,i=e.textStroke,s=e.raw.strokeVisible===!0,a=e.paintFirst==="stroke",l=typeof e.raw.fill=="string"?e.raw.fill:"";for(let u of t.chars){let c=e.textLayout.lines[u.line]?.charStyles[u.index],h=gn(o,c),d=r==="silhouette"?"#ffffff":typeof c?.fill=="string"&&c.fill?c.fill:l,f=r==="silhouette"?null:s?Oe(i,c):null,m=Me(h,h.fontSize);n.save(),n.translate(u.x,u.y),n.rotate(u.rotation),n.font=m;let p=()=>{d&&(n.fillStyle=d,n.fillText(u.char,0,0))},b=()=>{f&&f.width>0&&(n.lineWidth=f.width,n.strokeStyle=f.color,n.strokeText(u.char,0,0))};a?(b(),p()):(p(),b()),n.restore()}},Bh=(n,e,t=Wh)=>{let r=Math.max(1,Math.ceil(n.dims.x*t)),o=Math.max(1,Math.ceil(n.dims.y*t));if(r>8192||o>8192)return null;let i=document.createElement("canvas");i.width=r,i.height=o;let s=i.getContext("2d");return s?(s.setTransform(t,0,0,t,r/2-e.contentOffsetX*t,o/2-e.contentOffsetY*t),s.textBaseline="alphabetic",s.textAlign="center",Hh(s,n,e,"silhouette"),i):null},Wg=(n,e,t,r,o)=>{if(r.dropShadows.length===0&&r.innerShadows.length===0&&r.solidFills.length===0&&r.strokes.length===0)return;let i=e.dims.x,s=e.dims.y,a=t.contentOffsetX,l=t.contentOffsetY,u=(c,h)=>{if(!c){h();return}n.save(),n.globalCompositeOperation=c,h(),n.restore()};if(r.dropShadows.length||r.solidFills.length||r.innerShadows.length){let c=Bh(e,t,o);if(c){if(r.dropShadows.length){let h=El(r.dropShadows,c,o);h&&(n.save(),n.globalCompositeOperation="destination-over",n.drawImage(h.canvas,a-h.w/2,l-h.h/2,h.w,h.h),n.restore())}for(let h of r.innerShadows){let d=wr(e,h,c,o);d&&u(h.blendMode,()=>n.drawImage(d,a-i/2,l-s/2,i,s))}for(let h of r.solidFills){let d=vr(e,h,c,o);d&&u(h.blendMode,()=>n.drawImage(d,a-i/2+h.offset.x,l-s/2+h.offset.y,i,s))}}}if(r.strokes.length){let c=Math.min(Math.max(2,o),Bi(e)),h=Bh(e,t,c);h&&bn(e,r.strokes,h,!1,c,null,!0).forEach((f,m)=>{let p=r.strokes[r.strokes.length-1-m];u(p?.blendMode,()=>n.drawImage(f.canvas,a-f.quadW/2+f.dx,l-f.quadH/2+f.dy,f.quadW,f.quadH))})}},Ml=(n,e,t=null,r=Wh)=>{let o=Et(n.textLayout,n.raw,n.textStyle.lineHeight??1.16),i=t?Tr(t):0,s=o.width+i*2,a=o.height+i*2,l=Math.ceil(s*r),u=Math.ceil(a*r);if(!(l>0)||!(u>0)||l>8192||u>8192)return null;let c=document.createElement("canvas");c.width=l,c.height=u;let h=c.getContext("2d");return h?(h.setTransform(r,0,0,r,l/2-o.contentOffsetX*r,u/2-o.contentOffsetY*r),h.textBaseline="alphabetic",h.textAlign="center",Hh(h,n,o,"render"),t&&Wg(h,n,o,t,r),{canvas:c,logicalW:s,logicalH:a}):null};var Er=n=>{if(Ge(n)!=="scroll")return null;let e=typeof n.scrollSpeed=="number"&&Number.isFinite(n.scrollSpeed)?n.scrollSpeed:50;return{direction:n.scrollDirection==="right-to-left"?"right-to-left":"left-to-right",speed:e,enabled:n.scrollEnabled===void 0?!0:n.scrollEnabled===!0}},Hg=(n,e,t,r)=>{let o=t+e,i=n.direction==="left-to-right"?-e/2-t+r:e/2-r,s=n.direction==="left-to-right"?o:-o;return{copy1:i,copy2:i+s}},Gh=n=>{let e=Er(n.raw);return e?{target:n,viewWidth:n.dims.x,textTotalWidth:n.textTotalWidth,scrollSpeed:e.speed,scrollDirection:e.direction,scrollEnabled:e.enabled}:null},Gg=n=>`rgba(${Math.round(n.color[0]*255)},${Math.round(n.color[1]*255)},${Math.round(n.color[2]*255)},${n.color[3]})`,Xh=(n,e,t)=>{let r=Er(n.raw);if(!r||!r.enabled)return null;let o=n.dims.x,i=n.dims.y;if(!(o>0)||!(i>0))return null;let s=Math.max(1,e);if((o*s>8192||i*s>8192)&&(s=Math.max(1,Math.floor(Math.min(8192/o,8192/i))),o*s>8192||i*s>8192))return null;let a=Math.ceil(o*s),l=Math.ceil(i*s);if(!(a>0)||!(l>0))return null;let u=document.createElement("canvas");u.width=a,u.height=l;let c=u.getContext("2d");if(!c)return null;c.setTransform(s,0,0,s,a/2,l/2),c.textBaseline="alphabetic",c.textAlign="left",c.beginPath(),c.rect(-o/2,-i/2,o,i),c.clip();let h=n.textTotalWidth,{copy1:d,copy2:f}=Hg(r,o,h,t);for(let m of[d,f])c.save(),c.translate(m,0),Xg(c,n),c.restore();return{canvas:u,logicalW:o,logicalH:i}},Xg=(n,e)=>{let t=e.paintFirst==="stroke"?["stroke","fill"]:["fill","stroke"];for(let r of t)zg(n,e,r)},zg=(n,e,t)=>{let r=e.textLayout,o=e.textStyle,i=e.textStroke,s=e.raw,a=e.fillPaint,l=typeof s.fill=="string"?s.fill:a?.kind==="gradient"&&a.decl.stops.length?Gg(a.decl.stops[0]):"",u=s.vertical===!0,c=Number(s.charSpacing)||0,h=t==="stroke"&&Array.isArray(s.strokeDashArray)?s.strokeDashArray.filter(f=>typeof f=="number"&&Number.isFinite(f)):null;if(t==="fill"&&!l&&!r.lines.some(f=>f.charStyles.some(m=>typeof m?.fill=="string"))||t==="stroke"&&!i)return;h&&h.length&&(n.setLineDash(h),n.lineDashOffset=Number(s.strokeDashOffset)||0);let d=f=>{n.lineWidth=f.width,n.strokeStyle=f.color,n.lineJoin=typeof s.strokeLineJoin=="string"?s.strokeLineJoin:"miter",n.lineCap=typeof s.strokeLineCap=="string"?s.strokeLineCap:"butt",n.miterLimit=Number(s.strokeMiterLimit)||4};for(let f of r.lines){let m=-r.width/2+f.leftOffset,p=e.contentTopY+f.baseline,b=f.prefix?.width??0;if(f.prefix){let g=f.charStyles[0];if(t==="fill"){let x=typeof g?.fill=="string"&&g.fill?g.fill:l;x&&Tt(n,f,m,p,{fill:x})}else Tt(n,f,m,p,{stroke:Oe(i,g)})}if(u){let g=Vt(f,m,p,o,c);for(let x=0;x<g.length;x++){let S=f.charStyles[x];if(t==="fill"){let y=typeof S?.fill=="string"&&S.fill?S.fill:l;if(!y)continue;n.fillStyle=y}else{let y=Oe(i,S);if(!y||y.width<=0)continue;d(y)}let w=gn(o,S);n.font=Me(w,w.fontSize),qt(n,g[x],t==="fill"?"fillText":"strokeText")}continue}if(h&&h.length){let g="",x=b,S="",w=null,y,v=C=>{if(!g)return;let E=w;E&&E.width>0&&(n.font=S,d(E),n.strokeText(g,m+x,p)),g="",C<f.boxes.length&&(x=f.boxes[C].left)},R=$t(s.textAlign),P=s.textAlign===fe.DISPERSE,T=ro(s.textAlign)&&f.graphemes.some(C=>ao.test(C));for(let C=0;C<f.graphemes.length;C++){let E=f.charStyles[C],M=gn(o,E),k=Me(M,M.fontSize),A=Oe(i,E),O=E?.fill??"",F=w;g&&(k!==S||A?.color!==F?.color||A?.width!==F?.width||O!==y)&&v(C),g||(S=k,w=A,y=O),g+=f.graphemes[C],(c||(R||P)&&/[ \t\r]/.test(f.graphemes[C])||T)&&v(C+1)}v(f.graphemes.length);continue}for(let g=0;g<f.graphemes.length;g++){let x=f.charStyles[g];if(t==="fill"){let y=typeof x?.fill=="string"&&x.fill?x.fill:l;if(!y)continue;n.fillStyle=y}else{let y=Oe(i,x);if(!y||y.width<=0)continue;d(y)}let S=gn(o,x);n.font=Me(S,S.fontSize);let w=m+f.boxes[g].left;t==="fill"?n.fillText(f.graphemes[g],w,p):n.strokeText(f.graphemes[g],w,p)}}};var zh=(n,e)=>{let t=[],r=Ii(n);r&&t.push({left:-r.logicalW/2,top:-r.logicalH/2,right:r.logicalW/2,bottom:r.logicalH/2});let o=n.raw;if(Array.isArray(o.texts)&&typeof o.renderSrc!="string"&&!Sr(o)&&!Zn(o)&&!Xe(o)&&!Er(o)?.enabled){let h=n.textLayout,d=Jn(String(o.text??""),h,o.texts,n.contentTopY,n.textStyle.fontSize);if(d&&Math.ceil(h.width+d.padX*2)<=8192&&Math.ceil(h.height+d.padY*2)<=8192){let f=d.inkBounds;t.push({left:f.left-2,top:f.top-2,right:f.right+2,bottom:f.bottom+2})}}if(!t.length)return e;let i=Xn(e),{left:s,top:a,right:l,bottom:u}=i,c=n.matrix;for(let h of t)for(let[d,f]of[[h.left,h.top],[h.right,h.top],[h.right,h.bottom],[h.left,h.bottom]]){let m=Q(c,d,f);s=Math.min(s,m.x),a=Math.min(a,m.y),l=Math.max(l,m.x),u=Math.max(u,m.y)}return{tl:{x:s,y:a},tr:{x:l,y:a},br:{x:l,y:u},bl:{x:s,y:u}}};var er=n=>{if(!n||typeof n!="object")return null;let e=n;if(typeof e.rows!="number"||typeof e.cols!="number"||!Array.isArray(e.pieces)||e.pieces.length===0)return null;let t=[];for(let r of e.pieces){if(!r||typeof r!="object")continue;let o=r;typeof o.row!="number"||typeof o.col!="number"||t.push({id:r.id,row:o.row,col:o.col,rowSpan:r.rowSpan,colSpan:r.colSpan})}return t.length>0?{rows:e.rows,cols:e.cols,pieces:t}:null},Rl=(n,e)=>{let{rows:t,cols:r,pieces:o}=n,i=Math.max(0,e.width-e.groupPadding*2),s=Math.max(0,e.height-e.groupPadding*2),a=e.hGap*Math.max(0,r-1),l=e.vGap*Math.max(0,t-1),u=r>0?(i-a)/r:0,c=t>0?(s-l)/t:0,h=u+e.hGap,d=c+e.vGap,f=(r-1)/2,m=(t-1)/2;return o.map(p=>{let b=p.colSpan??1,g=p.rowSpan??1,x=Math.max(u*b+e.hGap*(b-1),0),S=Math.max(c*g+e.vGap*(g-1),0),w=p.col+(b-1)/2,y=p.row+(g-1)/2;return{w:x,h:S,cx:(w-f)*h,cy:(y-m)*d}})},Yg=(n,e)=>e&&e.naturalWidth&&e.naturalHeight?{w:e.naturalWidth,h:e.naturalHeight}:{w:n?.width??0,h:n?.height??0},Yh=(n,e,t)=>{let r=typeof e.widthRatio=="number"&&isFinite(e.widthRatio)&&e.widthRatio>0?e.widthRatio:1,o=typeof e.heightRatio=="number"&&isFinite(e.heightRatio)&&e.heightRatio>0?e.heightRatio:1,i=r!==1,s=o!==1;if(!i&&!s||n.masks.length===0)return!1;let a=n.width||0,l=n.height||0;return i&&a&&(n.width=a*r,n.hGap*=r,n.groupPadding*=r),s&&l&&(n.height=l*o,n.vGap*=o,n.groupPadding*=o),n.masks.forEach((u,c)=>{let h=u.width||0,d=u.height||0,f=i?Math.max(h*r,1):h,m=s?Math.max(d*o,1):d,p=i?(u.left||0)*r:u.left,b=s?(u.top||0)*o:u.top;if(u.left=p,u.top=b,u.width=f,u.height=m,u.clip){let g=i&&h?f/h:1,x=s&&d?m/d:1,S=t?.[c]??Yg(u.clip,null);if(S.w&&S.h){let w=Math.max(h/S.w,d/S.h),y=Math.max(f/S.w,m/S.h),v=u.clip.scaleX||u.clip.scaleY||1,R=w?v/w:1,P=y*(R||1);u.clip.scaleX=P,u.clip.scaleY=P}u.clip.clipX=(u.clip.clipX||0)*g,u.clip.clipY=(u.clip.clipY||0)*x}}),!0},Xi=n=>{let e=n.clipImage;if(!e||typeof e!="object"||typeof e.src!="string")return null;let t=e;return{scaleX:t.scaleX??1,scaleY:t.scaleY??1,clipX:t.clipX??0,clipY:t.clipY??0,width:t.width??0,height:t.height??0}};var Ug=(n,e)=>{if(typeof n.colStart!="number"||typeof n.colEnd!="number"||e<=0)return 0;let t=0;return n.colStart>0&&(t+=1),n.colEnd<e-1&&(t+=1),t},$g=(n,e)=>{if(typeof n.rowStart!="number"||typeof n.rowEnd!="number"||e<=0)return 0;let t=0;return n.rowStart>0&&(t+=1),n.rowEnd<e-1&&(t+=1),t},_t=n=>({left:n.left-n.width/2,right:n.left+n.width/2,top:n.top-n.height/2,bottom:n.top+n.height/2}),Cr=(n,e,t,r)=>{if(!n.clip)return;let o=n.width,i=n.height,s=e?o/e:1,a=t?i/t:1,l=r??{w:n.clip.width,h:n.clip.height};if(l.w&&l.h){let u=Math.max(e/l.w,t/l.h),c=Math.max(o/l.w,i/l.h),h=n.clip.scaleX||n.clip.scaleY||1,d=u?h/u:1,f=c*(d||1);n.clip.scaleX=f,n.clip.scaleY=f}n.clip.clipX=(n.clip.clipX||0)*s,n.clip.clipY=(n.clip.clipY||0)*a},Uh=(n,e,t,r="right",o)=>{let i=n.masks[e];if(!i)return!1;let s=Math.max(n.innerRadius+1,12);if(t<=s||!n.layoutWidth)return!1;let a=n.groupPadding||0,l=Math.max(0,n.layoutWidth-a*2),u=1,c=i.width||0,h=i.height||0;if(!l||!c)return!1;let d=n.innerRadius+1,f=Ug(i,n.cols)*d;if(t<f)return!1;let m=l-f,p=Math.min(t,Math.max(u,m)),b=_t(i),g=n.hGap||0,x=[],S=null,w=5,y=.3;n.masks.forEach((B,q)=>{if(q===e)return;let U=_t(B),oe=Math.min(b.bottom,U.bottom)-Math.max(b.top,U.top);if(!(oe<=0||oe<Math.min(i.height,B.height)*y))if(r==="right"){if(U.left<=i.left)return;let ne=U.left;S===null||ne<S-w?(S=ne,x.length=0,x.push(q)):Math.abs(ne-S)<=w&&x.push(q)}else{if(U.right>=i.left)return;let ne=U.right;S===null||ne>S+w?(S=ne,x.length=0,x.push(q)):Math.abs(ne-S)<=w&&x.push(q)}});let v=B=>o?.[B]??null;if(!x.length){let B=l/2,q=r==="right"?B-b.left:b.right+B,U=Math.max(s,Math.min(p,Math.max(s,q)));return U===c?!1:(i.left=r==="right"?b.left+U/2:b.right-U/2,i.width=U,Cr(i,c,h,v(e)),!0)}let R=1/0,P=-1/0;for(let B of x){let q=_t(n.masks[B]);q.left<R&&(R=q.left),q.right>P&&(P=q.right)}let T=r==="right"?b.left:b.right,C=B=>{let q=_t(n.masks[B]);return r==="right"?q.right:q.left},E=1/0;for(let B of x){let q=(r==="right"?C(B)-T:T-C(B))-g-s;q<E&&(E=q)}let M=Math.max(s,Math.min(p,Math.max(s,E))),k=r==="right"?T+M:T-M;for(let B of x)if((r==="right"?C(B)-k:k-C(B))-g<s-1e-6)return!1;if(M<=0)return!1;i.left=r==="right"?T+M/2:T-M/2,i.width=M;let A=new Map;A.set(e,{width:c,height:h});for(let B of x){let q=n.masks[B];A.set(B,{width:q.width,height:q.height});let U=C(B);r==="right"?(q.width=U-k-g,q.left=(k+g+U)/2):(q.width=k-g-U,q.left=(k-g+U)/2)}for(let B of[e,...x]){let q=A.get(B);Cr(n.masks[B],q.width,q.height,v(B))}let O=_t(i),F=O.left,W=O.right,z=_t(n.masks[x[0]]),_=z.left,D=z.right,I=r==="right"?b.right:b.left,G=r==="right"?W:F,$=new Set(x),V=typeof i.colStart=="number"&&typeof i.colEnd=="number"?{colStart:i.colStart,colEnd:i.colEnd}:null,H=n.masks[x[0]],Y=H&&typeof H.colStart=="number"&&typeof H.colEnd=="number"?{colStart:H.colStart,colEnd:H.colEnd}:null,X=n.cols>0&&!!V&&!!Y,Z=(B,q,U)=>{let oe=n.masks[B],ne=oe.width,de=oe.height,Pe=Math.max(u,U-q);oe.left=(q+U)/2,oe.width=Pe,Cr(oe,ne,de,v(B))};return n.masks.forEach((B,q)=>{if(q===e||$.has(q))return;let U=_t(B),oe=U.left,ne=U.right;if(X&&V&&Y&&typeof B.colStart=="number"&&typeof B.colEnd=="number"){if(B.colStart===V.colStart&&B.colEnd===V.colEnd){Z(q,F,W);return}if(B.colStart===Y.colStart&&B.colEnd===Y.colEnd){Z(q,_,D);return}let Ee=r==="right"?V.colEnd+1:V.colStart,ue=B.colStart===Ee,xe=B.colEnd+1===Ee;if(!ue&&!xe)return;let pe=ue?G+(r==="right"?g:0):oe,Te=xe?G-(r==="left"?g:0):ne;if(Te-pe<=0)return;Z(q,pe,Te);return}let de=.5;if(Math.abs(oe-b.left)<de&&Math.abs(ne-b.right)<de){Z(q,F,W);return}if(Math.abs(oe-R)<de&&Math.abs(ne-P)<de){Z(q,_,D);return}let Pe=Math.abs(oe-I)<de,De=Math.abs(ne-I)<de;if(!Pe&&!De)return;let nt=Pe?G:oe,ke=De?G:ne;ke-nt<=0||Z(q,nt,ke)}),i.width!==c},$h=(n,e,t,r="bottom",o)=>{let i=n.masks[e];if(!i)return!1;let s=Math.max(n.innerRadius+1,12);if(t<=s||!n.layoutHeight)return!1;let a=n.groupPadding||0,l=Math.max(0,n.layoutHeight-a*2),u=1,c=i.height||0,h=i.width||0;if(!l||!c)return!1;let d=n.innerRadius+1,f=$g(i,n.rows)*d;if(t<f)return!1;let m=l-f,p=Math.min(t,Math.max(u,m)),b=_t(i),g=n.vGap||0,x=-1,S=0,w=0,y=.3;n.masks.forEach((ue,xe)=>{if(xe===e)return;let pe=_t(ue),Te=Math.min(b.right,pe.right)-Math.max(b.left,pe.left);if(!(Te<=0||Te<Math.min(i.width,ue.width)*y))if(r==="bottom"){if(pe.top<=i.top)return;(x===-1||pe.top<S)&&(x=xe,S=pe.top,w=pe.bottom)}else{if(pe.bottom>=i.top)return;(x===-1||pe.bottom>w)&&(x=xe,S=pe.top,w=pe.bottom)}});let v=ue=>o?.[ue]??null;if(x===-1){let ue=l/2,xe=r==="bottom"?ue-b.top:b.bottom+ue,pe=Math.max(s,Math.min(p,Math.max(s,xe)));return pe===c?!1:(i.top=r==="bottom"?b.top+pe/2:b.bottom-pe/2,i.height=pe,Cr(i,h,c,v(e)),!0)}let R=r==="bottom"?b.top:S,P=r==="bottom"?w:b.bottom,T=P-R,C=Math.max(s,T-g-s),E=Math.max(s,Math.min(p,C)),M=T-g-E;if(M<s){let ue=T-g-s;if(ue<s||(E=Math.max(s,Math.min(p,ue)),M=T-g-E,M<s))return!1}if(E<=0||M<=0)return!1;let k,A;r==="bottom"?(k=R+E/2,A=P-M/2):(A=R+M/2,k=P-E/2);let O=new Map;O.set(e,{width:h,height:c}),O.set(x,{width:n.masks[x].width,height:n.masks[x].height}),i.top=k,i.height=E;let F=n.masks[x];F.top=A,F.height=M;for(let ue of[e,x]){let xe=O.get(ue);Cr(n.masks[ue],xe.width,xe.height,v(ue))}let W=k-E/2,z=k+E/2,_=A-M/2,D=A+M/2,I=r==="bottom",G=I?W:_,$=I?z:D,V=I?_:W,H=I?D:z,Y=I?b.top:S,X=I?b.bottom:w,Z=I?S:b.top,B=I?w:b.bottom,q=r==="bottom"?b.bottom:b.top,U=r==="bottom"?z:W,oe=typeof i.rowStart=="number"&&typeof i.rowEnd=="number"?{rowStart:i.rowStart,rowEnd:i.rowEnd}:null,ne=n.masks[x],de=ne&&typeof ne.rowStart=="number"&&typeof ne.rowEnd=="number"?{rowStart:ne.rowStart,rowEnd:ne.rowEnd}:null,Pe=n.rows>0&&!!oe&&!!de,De=Pe&&oe&&de?oe.rowStart<=de.rowStart?oe:de:null,nt=Pe&&oe&&de?De===oe?de:oe:null,ke=De?De.rowEnd+1:void 0,Ee=(ue,xe,pe)=>{let Te=n.masks[ue],rt=Te.width,Ke=Te.height,Ue=Math.max(u,pe-xe);Te.top=(xe+pe)/2,Te.height=Ue,Cr(Te,rt,Ke,v(ue))};return n.masks.forEach((ue,xe)=>{if(xe===e||xe===x)return;let pe=_t(ue),Te=pe.top,rt=pe.bottom;if(Pe&&De&&nt&&ke!==void 0&&typeof ue.rowStart=="number"&&typeof ue.rowEnd=="number"){if(ue.rowStart===De.rowStart&&ue.rowEnd===De.rowEnd){Ee(xe,G,$);return}if(ue.rowStart===nt.rowStart&&ue.rowEnd===nt.rowEnd){Ee(xe,V,H);return}let yt=ue.rowStart===ke,St=ue.rowEnd+1===ke;if(!yt&&!St)return;let Bn=yt?U+(r==="bottom"?g:0):Te,Wn=St?U-(r==="top"?g:0):rt;if(Wn-Bn<=0)return;Ee(xe,Bn,Wn);return}let Ke=.5;if(Math.abs(Te-Y)<Ke&&Math.abs(rt-X)<Ke){Ee(xe,G,$);return}if(Math.abs(Te-Z)<Ke&&Math.abs(rt-B)<Ke){Ee(xe,V,H);return}let Ue=Math.abs(Te-q)<Ke,bt=Math.abs(rt-q)<Ke;if(!Ue&&!bt)return;let gt=Ue?U:Te,xt=bt?U:rt;xt-gt<=0||Ee(xe,gt,xt)}),i.height!==c};var jh=(n,e,t=[])=>{let r=n.layoutConfig,o=r&&typeof r=="object"&&Array.isArray(r.pieces)?r.pieces:[],i=e.map(u=>({left:u.left??0,top:u.top??0,width:u.width??0,height:u.height??0,clip:Xi(u)})),s=e.map((u,c)=>{let h=u.clipImage;if(!h||typeof h.src!="string")return null;let d=t[c];return d&&d.naturalWidth&&d.naturalHeight?{w:d.naturalWidth,h:d.naturalHeight}:{w:h.width??0,h:h.height??0}});o.forEach((u,c)=>{let h=i[c];!h||typeof u.col!="number"||typeof u.row!="number"||(h.colStart=u.col,h.colEnd=u.col+(u.colSpan??1)-1,h.rowStart=u.row,h.rowEnd=u.row+(u.rowSpan??1)-1)});let a={layoutWidth:n.layoutWidth??600,layoutHeight:n.layoutHeight??600,hGap:n.hGap??12,vGap:n.vGap??12,groupPadding:n.groupPadding??0,innerRadius:n.innerRadius??12,cols:(r&&typeof r.cols=="number"?r.cols:0)||1,rows:(r&&typeof r.rows=="number"?r.rows:0)||1,masks:i},l=o.filter(u=>typeof u.row=="number"&&typeof u.col=="number").map(u=>({row:u.row,col:u.col,rowSpan:u.rowSpan,colSpan:u.colSpan}));return{state:a,pieces:l,clipSizes:s}},Vh=(n,e,t)=>{if(e<=1)return null;let r=[];n.forEach((o,i)=>{let s=o.col,a=o.col+(o.colSpan??1)-1;s===t&&(o.colSpan??1)===1?r.push(i):t>=s&&t<=a&&(o.colSpan=(o.colSpan??1)-1)}),r.forEach(o=>{let i=n[o],s=t>0?t-1:t+1,a=n.find((l,u)=>!r.includes(u)&&l.row===i.row&&l.col<=s&&l.col+(l.colSpan??1)-1>=s);a&&(a.colSpan=(a.colSpan??1)+1,a.col>t&&(a.col=t))}),n.forEach(o=>{o.col>t&&(o.col-=1)});for(let o of[...r].sort((i,s)=>s-i))n.splice(o,1);return{removed:r}},qh=(n,e,t)=>{if(e<=1)return null;let r=[];n.forEach((o,i)=>{let s=o.row,a=o.row+(o.rowSpan??1)-1;s===t&&(o.rowSpan??1)===1?r.push(i):t>=s&&t<=a&&(o.rowSpan=(o.rowSpan??1)-1)}),r.forEach(o=>{let i=n[o],s=t>0?t-1:t+1,a=n.find((l,u)=>!r.includes(u)&&l.col===i.col&&l.row<=s&&l.row+(l.rowSpan??1)-1>=s);a&&(a.rowSpan=(a.rowSpan??1)+1,a.row>t&&(a.row=t))}),n.forEach(o=>{o.row>t&&(o.row-=1)});for(let o of[...r].sort((i,s)=>s-i))n.splice(o,1);return{removed:r}},Kh=(n,e)=>{let t=n.findIndex(h=>h.row===e.row&&h.col===e.col);if(t===-1||n.length<=1)return null;let r=n[t],o=r.row,i=r.col,s=r.rowSpan??1,a=r.colSpan??1,l=[],u="v",c=n.filter(h=>h!==r&&h.row+(h.rowSpan??1)===o&&h.col>=i&&h.col+(h.colSpan??1)<=i+a);if(c.reduce((h,d)=>h+(d.colSpan??1),0)===a)l=c,u="v";else{let h=n.filter(d=>d!==r&&d.row===o+s&&d.col>=i&&d.col+(d.colSpan??1)<=i+a);if(h.reduce((d,f)=>d+(f.colSpan??1),0)===a)l=h,u="v",l.forEach(d=>d.row=o);else{let d=n.filter(f=>f!==r&&f.col+(f.colSpan??1)===i&&f.row>=o&&f.row+(f.rowSpan??1)<=o+s);if(d.reduce((f,m)=>f+(m.rowSpan??1),0)===s)l=d,u="h";else{let f=n.filter(m=>m!==r&&m.col===i+a&&m.row>=o&&m.row+(m.rowSpan??1)<=o+s);f.reduce((m,p)=>m+(p.rowSpan??1),0)===s&&(l=f,u="h",l.forEach(m=>m.col=i))}}}return l.length>0&&l.forEach(h=>{u==="v"?h.rowSpan=(h.rowSpan??1)+s:h.colSpan=(h.colSpan??1)+a}),n.splice(t,1),{removed:[t]}};var Dt=n=>{let e=new Map;for(let t of n)e.set(`${t.row},${t.col}`,t);for(let t of n){if(t.isMerged)continue;let r=t.colspan??1,o=t.rowspan??1;if(!(r<=1&&o<=1))for(let i=t.row;i<t.row+o;i++)for(let s=t.col;s<t.col+r;s++){if(i===t.row&&s===t.col)continue;let a=`${i},${s}`;e.has(a)||e.set(a,{row:i,col:s,isMerged:!0,mergeParent:{row:t.row,col:t.col}})}}return e},we=(n,e,t)=>n.get(`${e},${t}`),lt=(n,e,t)=>{let r=we(n,e,t);return r?.isMerged&&r.mergeParent?{row:r.mergeParent.row,col:r.mergeParent.col}:{row:e,col:t}},Pr=n=>{let e=Array.isArray(n.cellData)?n.cellData:null;if(e)return e;let t=[];return n.cellData=t,t},kr=n=>n.rows??3,Yi=n=>n.cols??3,kl=n=>n.minCellHeight??40,Pl=n=>n.minCellWidth??40,Al=n=>{let e=Yi(n),t=Array.isArray(n.columnWidths)?n.columnWidths:[],r=typeof t[0]=="number"?t[0]:n.cellWidth??100,o=t.slice(0,e).map(i=>typeof i=="number"&&i>0?i:r);for(;o.length<e;)o.push(r);return o},go=(n,e)=>{let t=Array.isArray(n.columnWidths)?n.columnWidths:null;t?(t.length=0,t.push(...e)):n.columnWidths=e},Jh=(n,e,t,r)=>{let o=kr(n),i=kl(n),s=Array.isArray(n.rowHeights)?n.rowHeights:Array.from({length:o},()=>i);for(;s.length<o;)s.push(i);r!==void 0?s.splice(e,t,r):s.splice(e,t),n.rowHeights=s},ed=(n,e,t,r)=>{let o=kr(n),i=Array.isArray(n.manualRowHeights)?n.manualRowHeights:[],s=[];for(let a=0;a<Math.max(o,i.length);a++)s.push(typeof i[a]=="number"?i[a]:null);r!==void 0?s.splice(e,t,r):s.splice(e,t),n.manualRowHeights=s},xo=(n,e,t)=>{let r=Al(n);e<0||e>=r.length||(r[e]=Math.max(Pl(n),t),go(n,r))},yo=(n,e,t)=>{let r=kr(n);if(e<0||e>=r)return;let o=Array.isArray(n.manualRowHeights)?n.manualRowHeights:[],i=[];for(let s=0;s<r;s++)i.push(typeof o[s]=="number"?o[s]:null);i[e]=Math.max(kl(n),t),n.manualRowHeights=i},Nl=(n,e,t,r,o)=>{let i=!0;for(;i;){i=!1;for(let s=e;s<=t;s++)for(let a=r;a<=o;a++){let l=we(n,s,a);if(l){if(l.isMerged&&l.mergeParent){let u=we(n,l.mergeParent.row,l.mergeParent.col);if(u){l.mergeParent.row<e&&(e=l.mergeParent.row,i=!0),l.mergeParent.col<r&&(r=l.mergeParent.col,i=!0);let c=l.mergeParent.row+(u.rowspan??1)-1,h=l.mergeParent.col+(u.colspan??1)-1;c>t&&(t=c,i=!0),h>o&&(o=h,i=!0)}}(l.colspan??1)>1&&a+(l.colspan??1)-1>o&&(o=a+(l.colspan??1)-1,i=!0),(l.rowspan??1)>1&&s+(l.rowspan??1)-1>t&&(t=s+(l.rowspan??1)-1,i=!0)}}}return{r1:e,r2:t,c1:r,c2:o}},jg=(n,e,t)=>{for(let r=t.r1;r<=t.r2;r++)for(let o=t.c1;o<=t.c2;o++){let i=we(e,r,o);i||(i={row:r,col:o},n.push(i),e.set(`${r},${o}`,i)),i.colspan=1,i.rowspan=1,i.isMerged=!1,i.mergeParent=null}},Vg=(n,e)=>{let t=[];for(let r=e.r1;r<=e.r2;r++)for(let o=e.c1;o<=e.c2;o++){let i=we(n,r,o)?.text;i&&i.trim()&&t.push(i.trim())}return t.join(`
7
- `)},Ll=(n,e,t,r,o,i)=>{for(let s=t;s<t+o;s++)for(let a=r;a<r+i;a++){if(s===t&&a===r)continue;let l=we(e,s,a);l||(l={row:s,col:a},n.push(l),e.set(`${s},${a}`,l)),l.isMerged=!0,l.mergeParent={row:t,col:r},l.text=""}},So=(n,e,t,r,o)=>{let i=Pr(n),s=Dt(i),a=Nl(s,Math.min(e,r),Math.max(e,r),Math.min(t,o),Math.max(t,o));jg(i,s,a);let l=we(s,a.r1,a.c1);return l&&(l.text=Vg(s,a),l.colspan=a.c2-a.c1+1,l.rowspan=a.r2-a.r1+1,Ll(i,s,a.r1,a.c1,l.rowspan,l.colspan)),a},vo=(n,e,t)=>{let r=Dt(Pr(n)),o=we(r,e,t);if(!o||(o.colspan??1)===1&&(o.rowspan??1)===1)return!1;let i=o.colspan??1,s=o.rowspan??1;o.colspan=1,o.rowspan=1;for(let a=e;a<e+s;a++)for(let l=t;l<t+i;l++){if(a===e&&l===t)continue;let u=we(r,a,l);u&&(u.isMerged=!1,u.mergeParent=null)}return!0},td=n=>({cellFill:n.cellFill,textFill:n.textFill,fontSize:n.fontSize,fontWeight:n.fontWeight,fontFamily:n.fontFamily,fontStyle:n.fontStyle,textAlign:n.textAlign}),nd=(n,e,t,r)=>({row:t,col:r,fill:n?.fill??e.cellFill,stroke:n?.stroke,text:"",textFill:n?.textFill??e.textFill,fontSize:n?.fontSize??e.fontSize,fontWeight:n?.fontWeight??e.fontWeight,fontFamily:n?.fontFamily??e.fontFamily,fontStyle:n?.fontStyle??e.fontStyle,textAlign:n?.textAlign??e.textAlign}),Ui=(n,e,t,r)=>{for(let o of n)o[e]>=t&&(o[e]+=r),o.isMerged&&o.mergeParent&&o.mergeParent[e]>=t&&(o.mergeParent[e]+=r)},rd=(n,e,t)=>{let r=e==="row"?"rowspan":"colspan",o=[];for(let i of n){let s=i[r]??1;if(s>1){let a=i[e];t>a&&t<=a+s-1&&o.push(i)}}return o},wo=(n,e)=>{let t=kr(n),r=Yi(n),o=Pr(n),i=Dt(o),s=Math.max(0,Math.min(e,t)),a=rd(o,"row",s),l=s>0?s-1:s<t?s:null;Ui(o,"row",s,1);for(let c=0;c<r;c++){let h=l!==null?we(i,l,c):void 0;o.push(nd(h,td(n),s,c))}Jh(n,s,0,kl(n)),ed(n,s,0,null),n.rows=t+1;let u=Dt(o);for(let c of a)c.rowspan=(c.rowspan??1)+1,Ll(o,u,c.row,c.col,c.rowspan??1,c.colspan??1)},Il=(n,e)=>{let t=kr(n);if(t<=1)return!1;let r=Math.max(0,Math.min(e,t-1)),o=Pr(n),i=0;for(let s of o)s.row!==r&&(o[i++]=s);return o.length=i,Ui(o,"row",r+1,-1),Jh(n,r,1),ed(n,r,1),n.rows=t-1,!0},To=(n,e)=>{let t=kr(n),r=Yi(n),o=Pr(n),i=Dt(o),s=Al(n),a=Math.max(0,Math.min(e,r)),l=rd(o,"col",a),u=a>0?a-1:a<r?a:null;Ui(o,"col",a,1);for(let d=0;d<t;d++){let f=u!==null?we(i,d,u):void 0;o.push(nd(f,td(n),d,a))}n.cols=r+1;let c=Math.max(Pl(n),u!==null?s[u]:Pl(n));s.splice(a,0,c),go(n,s);let h=Dt(o);for(let d of l)d.colspan=(d.colspan??1)+1,Ll(o,h,d.row,d.col,d.rowspan??1,d.colspan??1)},_l=(n,e)=>{let t=Yi(n);if(t<=1)return!1;let r=Math.max(0,Math.min(e,t-1)),o=Pr(n),i=Al(n),s=0;for(let a of o)a.col!==r&&(o[s++]=a);return o.length=s,Ui(o,"col",r+1,-1),n.cols=t-1,i.splice(r,1),go(n,i),!0},tr=n=>n.columnWidths.reduce((e,t)=>e+t,0)+(n.cols-1)*n.cellSpacing,nr=n=>n.rowHeights.reduce((e,t)=>e+t,0)+(n.rows-1)*n.cellSpacing,Mr=(n,e,t)=>{let r=0;for(let o=0;o<n.length;o++){if(t>=r&&t<r+n[o])return o;r+=n[o]+e}return-1},Rr=(n,e,t)=>{let r=e==="col"?n.columnWidths:n.rowHeights,o=e==="col"?tr(n):nr(n),i=0;for(let s=0;s<t&&s<r.length;s++)i+=r[s]+n.cellSpacing;return i-n.cellSpacing/2-o/2},Qh=(n,e,t,r,o,i)=>{let s=e/2,a=0;for(let l=0;l<=n.length;l++){let u=l>0&&l<n.length,c=a-s;if(u&&Math.abs(t-c)<r&&o>=0&&o<=i)return l;l<n.length&&(a+=n[l]+e)}return-1},Zh=(n,e,t,r)=>{if(e==="col"){let i=we(n,r,t-1);if(!i)return!1;if(i.isMerged&&i.mergeParent){let s=we(n,i.mergeParent.row,i.mergeParent.col);if(s&&s.col+(s.colspan??1)>t)return!0}else if((i.colspan??1)>1)return!0;return!1}let o=we(n,t-1,r);if(!o)return!1;if(o.isMerged&&o.mergeParent){let i=we(n,o.mergeParent.row,o.mergeParent.col);if(i&&i.row+(i.rowspan??1)>t)return!0}else if((o.rowspan??1)>1)return!0;return!1},Dl=(n,e,t,r,o,i)=>{let s=t+tr(n)/2,a=r+nr(n)/2,l=o,u=i,c=Mr(n.rowHeights,n.cellSpacing,a),h=Mr(n.columnWidths,n.cellSpacing,s),d=Qh(n.columnWidths,n.cellSpacing,s,l,a,nr(n));if(d>0&&c>=0&&!Zh(e,"col",d,c))return{type:"col",index:d,position:Rr(n,"col",d)};let f=Qh(n.rowHeights,n.cellSpacing,a,u,s,tr(n));return f>0&&h>=0&&!Zh(e,"row",f,h)?{type:"row",index:f,position:Rr(n,"row",f)}:null},od=(n,e,t,r)=>{let o=t+tr(n)/2,i=r+nr(n)/2,s=Mr(n.columnWidths,n.cellSpacing,o);if(s<0)return null;let a=Mr(n.rowHeights,n.cellSpacing,i);return a<0?null:lt(e,a,s)},id=(n,e,t,r,o)=>{let i=o.indicatorOffset??15,s=o.indicatorRadius??8,a=nr(n)/2,l=tr(n)/2;for(let c=1;c<=n.cols;c++){let h=Rr(n,"col",c),d=s/(Math.abs(o.scaleX)*o.zoom);if(Math.hypot(t-h,r-(-a-i))<=d)return{border:{type:"col",index:c,position:h},inCircle:!0}}for(let c=1;c<=n.rows;c++){let h=Rr(n,"row",c),d=s/(Math.abs(o.scaleY)*o.zoom);if(Math.hypot(t-(-l-i),r-h)<=d)return{border:{type:"row",index:c,position:h},inCircle:!0}}let u=Dl(n,e,t,r,o.thresholdX,o.thresholdY);return u?{border:u,inCircle:!1}:null},Eo=(n,e)=>{let t=0;for(let l=0;l<e.c1;l++)t+=n.columnWidths[l]+n.cellSpacing;let r=0;for(let l=e.c1;l<=e.c2;l++)r+=n.columnWidths[l]+(l<e.c2?n.cellSpacing:0);let o=0;for(let l=0;l<e.r1;l++)o+=n.rowHeights[l]+n.cellSpacing;let i=0;for(let l=e.r1;l<=e.r2;l++)i+=n.rowHeights[l]+(l<e.r2?n.cellSpacing:0);let s=tr(n)/2,a=nr(n)/2;return{left:t-s,top:o-a,width:r,height:i}},Co=n=>{let e=new Set,t=[];for(let r of n){let o=`${r.row},${r.col}`;e.has(o)||(e.add(o),t.push(r))}return t},xn=(n,e,t)=>Co((()=>{let r=[];for(let o=Math.min(e.row,t.row);o<=Math.max(e.row,t.row);o++)for(let i=Math.min(e.col,t.col);i<=Math.max(e.col,t.col);i++)r.push(lt(n,o,i));return r})()),$i=(n,e,t)=>{let r=[];for(let o=0;o<e;o++){let i=lt(n,o,t);i.col===t&&r.push(i)}return Co(r)},ji=(n,e,t)=>{let r=[];for(let o=0;o<e;o++){let i=lt(n,t,o);i.row===t&&r.push(i)}return Co(r)},Mo=(n,e,t)=>{let r=[];for(let o=0;o<e;o++)for(let i=0;i<t;i++)r.push(lt(n,o,i));return Co(r)},ze=n=>{if(!n.length)return null;let e=1/0,t=-1/0,r=1/0,o=-1/0;for(let i of n)e>i.row&&(e=i.row),t<i.row&&(t=i.row),r>i.col&&(r=i.col),o<i.col&&(o=i.col);return{r1:e,r2:t,c1:r,c2:o}},Vi=(n,e,t,r)=>{let o=[];for(let u of n){let c=r==="row"?u.row:u.col;if(c===t)continue;let h=c>t?c-1:c;o.push(r==="row"?{row:h,col:u.col}:{row:u.row,col:h})}let i=Co(o);if(!i.length)return null;if(!e)return{cells:i,range:null};let s=r==="row"?e.r1:e.c1,a=r==="row"?e.r2:e.c2,l;if(s===t&&a===t)l=ze(i)??e;else{let u=s>t?s-1:s,c=a>t?a-1:a===t?t-1:a;l=r==="row"?{r1:u,r2:c,c1:e.c1,c2:e.c2}:{r1:e.r1,r2:e.r2,c1:u,c2:c}}return{cells:i,range:l}},sd=(n,e,t,r)=>Math.abs(e-n)>=.5||Math.abs(t)<=1?0:Math.sign(t)*Math.min(1.5,Math.abs(t)*.1)/r,qg=["ew","nwse","ns","nesw"],ad=(n,e)=>{let t=e==="col"?0:2,r=(n%180+180)%180,o=Math.round(r/45)%4;return`${qg[(t+o)%4]}-resize`};var zi=(n,e)=>{let t=Math.abs(n)*Math.max(e,1e-6);return t>1e-6?20/t:20},ld=(n,e,t,r,o,i={x:1,y:1},s=1)=>{if(o<-t/2&&o>=-t/2-zi(i.y,s)){let a=Mr(n.columnWidths,n.cellSpacing,r+tr(n)/2);if(a>=0)return{kind:"col-strip",col:a}}if(r<-e/2&&r>=-e/2-zi(i.x,s)){let a=Mr(n.rowHeights,n.cellSpacing,o+nr(n)/2);if(a>=0)return{kind:"row-strip",row:a}}return null},cd=(n,e,t,r,o={x:1,y:1},i=1)=>{let s=zi(o.x,i),a=zi(o.y,i);return t>=-n/2-s&&t<-n/2&&r>=-e/2-a&&r<-e/2};var ud=(n,e,t,r={x:1,y:1},o=1)=>{let i=l=>Math.max(Math.abs(l)*Math.max(o,1e-6),1e-6),s=12/i(r.x),a=12/i(r.y);return Math.abs(e-(n.left+n.width))<=s&&Math.abs(t-(n.top+n.height))<=a},Ar=(n,e)=>{let t=new Set,r=new Set;for(let o of e){let i=lt(n,o.row,o.col),s=we(n,i.row,i.col),a=s?.rowspan??1,l=s?.colspan??1;for(let u=i.row;u<i.row+a;u++)t.add(u);for(let u=i.col;u<i.col+l;u++)r.add(u)}return{rows:t,cols:r}};var qi=14,hd=(n,e,t)=>{let r=[0];for(let o=0;o<n-1;o++)r.push(r[o]+e[o]+t);return r},Fl=(n,e,t,r)=>{let o=0;for(let i=0;i<e;i++)o+=t[n+i]??0,i>0&&(o+=r);return o},Ro=(n,e,t)=>{let r=n.rows??3,o=n.cols??3,i=Array.isArray(n.columnWidths)?n.columnWidths:[],s=i[0]??100,a=Array.from({length:o},(_,D)=>i[D]??s),l=n.minCellHeight??40,u=n.cellPadding??8,c=n.cellSpacing??0,h=n.cellStrokeWidth??1,d=n.cellFill,f=n.cellStroke,m=n.textFill,p=n.fontFamily||"仓耳小丸子",b=Array.isArray(n.manualRowHeights)?n.manualRowHeights:[],g=Array.from({length:r},(_,D)=>typeof b[D]=="number"?b[D]:null),x=Array.isArray(n.cellData)?n.cellData:[],S=Dt(x),w=new Map;for(let _ of x){if(_.isMerged)continue;let D=Math.max(0,Fl(_.col,_.colspan??1,a,c)-u*2);w.set(`${_.row},${_.col}`,{layout:jt(_.text??"",{fontFamily:_.fontFamily||p,fontSize:_.fontSize??qi,fontWeight:_.fontWeight,fontStyle:_.fontStyle,lineHeight:1.16,charSpacing:0,textAlign:_.textAlign??fe.CENTER},{boxWidth:D,splitByGrapheme:!0,measure:e}),data:_})}let y=qi*Mi,v=[],R=[];for(let _=0;_<r;_++){let D=0;for(let V=0;V<o;V++){if(S.get(`${_},${V}`)?.isMerged)continue;let H=w.get(`${_},${V}`);D=Math.max(D,H?H.layout.height:y)}let I=g[_],G=D+u*2,$=I!==null?I:l;R.push(G),v.push(Math.max($,G))}let P=a.reduce((_,D)=>_+D,0)+(o-1)*c,T=v.reduce((_,D)=>_+D,0)+(r-1)*c,C=hd(o,a,c),E=hd(r,v,c),M=typeof n.id=="string"&&n.id?n.id:"table",k=[];for(let _=0;_<r;_++)for(let D=0;D<o;D++){let I=S.get(`${_},${D}`);if(I?.isMerged)continue;let G=I?.colspan??1,$=I?.rowspan??1,V=Fl(D,G,a,c),H=Fl(_,$,v,c),Y=C[D]-P/2+V/2,X=E[_]-T/2+H/2;k.push({type:"rect",id:`${M}-r${_}c${D}-rect`,left:Y,top:X,width:V,height:H,originX:"center",originY:"center",fill:I?I.fill:d,stroke:I?I.stroke:f,strokeWidth:h,scaleX:1,scaleY:1,angle:0,opacity:1,visible:!0});let Z=I?w.get(`${_},${D}`):void 0,B=t?.hideTextCell!==void 0&&t.hideTextCell.row===_&&t.hideTextCell.col===D;if(Z&&!B&&(I?.text??"")!==""){let q=Z.layout.height,U=I?.verticalAlign??"middle",oe=X;U==="top"?oe=X-H/2+q/2+u:U==="bottom"&&(oe=X+H/2-q/2-u),k.push({type:"textbox",id:`${M}-r${_}c${D}-text`,left:Y,top:oe,width:Math.max(0,V-u*2),text:I?.text??"",fill:I?.textFill??m,fontFamily:I?.fontFamily||p,fontSize:I?.fontSize??qi,fontWeight:I?.fontWeight,fontStyle:I?.fontStyle,textAlign:I?.textAlign??fe.CENTER,lineHeight:1.16,splitByGrapheme:!0,originX:"center",originY:"center",scaleX:1,scaleY:1,angle:0,opacity:1,visible:!0})}}let A=Math.max(l,qi*Mi+u*2),O=o*s+(o-1)*c+h,F=r*A+(r-1)*c+h,W=P+h,z=T+h;return{rowHeights:v,rowTextFloors:R,columnWidths:a,contentWidth:P,contentHeight:T,width:W,height:z,children:k,constructorDims:{width:O,height:F}}};var Sn="WorkSpaceDrawType",Ir=new Set(["WorkSpaceDrawType","WorkSpaceClipType","WorkSpaceSafeType","WorkSpaceMaskType","WorkSpaceLineType","WorkSpaceShadowType"]),Kg=new Set(["WorkSpaceClipType","WorkSpaceSafeType"]),rr=n=>{let e=n.raw?.id;return typeof e=="string"&&Kg.has(e)},Kt=n=>n.isTextType&&typeof n.raw.renderSrc=="string",Po=n=>{let e=n.fill;return typeof e!="string"||!e?1:Math.max(0,Math.min(1,ee(e)[3]))},bd=n=>{let e=n.fillOpacity;if(typeof e!="number"||!isFinite(e))return 1;let t=e>1?e/255:e;return Math.max(0,Math.min(1,t))},Qg=new Set(["left","top","angle","scaleX","scaleY","skewX","skewY","flipX","flipY","originX","originY"]),Zg=new Set(["text","styles","paragraph","texts","textPath","path","pathStartOffset","pathSide","pathAlign","fontFamily","fontSize","fontWeight","fontStyle","lineHeight","charSpacing","textAlign","splitByGrapheme","vertical","direction","underline","overline","linethrough","textBackgroundColor","textDecorationThickness","textScaleX","textScaleY","width","height","minWidth","fill","stroke","strokeWidth","strokeUniform","paintFirst"]),Wl=n=>{for(let e in n)if(!Qg.has(e))return!1;return!0},Qi=999999,Ze=n=>n.isReferenceLine,gd=(n,e)=>({type:"ReferenceLine",id:`referenceline-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,name:"ReferenceLine",axis:n,x1:n==="horizontal"?-Qi:0,y1:n==="horizontal"?0:-Qi,x2:n==="horizontal"?Qi:0,y2:n==="horizontal"?0:Qi,left:n==="horizontal"?0:e,top:n==="horizontal"?e:0,originX:"center",originY:"center",scaleX:1,scaleY:1,angle:0,opacity:1,visible:!1,selectable:!1,evented:!0,hasControls:!1,hasBorders:!1,stroke:"pink",fill:"pink",strokeWidth:1,padding:8,globalCompositeOperation:"difference",lockMovementX:n==="horizontal",lockMovementY:n==="vertical",hoverCursor:n==="horizontal"?"ns-resize":"ew-resize"}),Jg=["type","left","top","width","height","angle","scaleX","scaleY","skewX","skewY","flipX","flipY","originX","originY","strokeWidth","strokeUniform","fill","opacity","visible","src","crossOrigin","id","name"],ct=class{raw;syntheticOwner;_parentMatrix=null;_parentOpacity=1;_inIsolatedFBO=!1;_imageEl=null;_matrix=null;_aCoords=null;_bounds=null;_fillPaint;_animationOverride=null;constructor(e){this.raw={...e},Du(this.raw),this._typeKey=se(this.raw),this._isReferenceLine=this._typeKey===L.REFERENCELINE}_typeKey;get typeKey(){return this._typeKey}_isReferenceLine;get isReferenceLine(){return this._isReferenceLine}_strokeDecl;get strokeDecl(){return this._strokeDecl===void 0&&(this._strokeDecl=Ei(this.raw)),this._strokeDecl}get imageEl(){return this._imageEl}set imageEl(e){this._imageEl=e,this.invalidateGeometryCache(),this._renderNotify?.()}invalidateGeometryCache(){this._matrix=null,this._aCoords=null,this._bounds=null}_renderNotify=null;markRenderDirty(){this._renderNotify?.()}set(e){Fu(this.raw,e),Object.assign(this.raw,e),this.invalidateGeometryCache(),Wl(e)||(this._fillPaint=void 0,this._strokeDecl=void 0),"type"in e&&(this._typeKey=se(e),this._isReferenceLine=this._typeKey===L.REFERENCELINE),this._renderNotify?.()}setAnimationOverride(e){this._animationOverride=e,this.invalidateGeometryCache(),this._renderNotify?.()}get id(){return typeof this.raw.id=="string"?this.raw.id:""}get isImageType(){return dt.has(this.typeKey)}get isMaskType(){return ot.has(this.typeKey)}get isSolidType(){return $n.has(this.typeKey)}get isTextType(){return an.has(this.typeKey)}get isLineType(){return ft.has(this.typeKey)}get isShapeType(){return Un.has(this.typeKey)}get visible(){return this.raw.visible!==!1}get fillPaint(){if(this._fillPaint===void 0){let e=Yn(this.raw.fill),t=e?null:pr(this.raw.fill);e?this._fillPaint={kind:"gradient",decl:e}:t?this._fillPaint={kind:"pattern",decl:t}:this.raw.fill?this._fillPaint={kind:"solid",color:ee(this.raw.fill)}:this._fillPaint=null}return this._fillPaint}get drawColor(){let e=this.renderOpacity;if(this.isImageType)return[1,1,1,e];let t=ee(this.raw.fill);return[t[0],t[1],t[2],t[3]*e]}get transformProps(){let e={...this.raw,width:this.dims.x,height:this.dims.y},t=this._animationOverride;if(!t)return e;let{opacity:r,...o}=t;return{...e,...o}}get center(){return Ut(this.transformProps)}get matrix(){return this._matrix||(this._matrix=Gn(this.transformProps)),this._parentMatrix?j(this._parentMatrix,this._matrix):this._matrix}get ownMatrix(){return this._matrix||(this._matrix=Gn(this.transformProps)),this._matrix}get worldAngle(){let e=this.matrix;return Math.atan2(e[1],e[0])*180/Math.PI}get worldScale(){let e=this.matrix;return{x:Math.hypot(e[0],e[1]),y:Math.hypot(e[2],e[3])}}get aCoords(){if(this._aCoords||(this._aCoords=$a(this.transformProps)),!this._parentMatrix)return this._aCoords;let e=this._parentMatrix;return{tl:Q(e,this._aCoords.tl.x,this._aCoords.tl.y),tr:Q(e,this._aCoords.tr.x,this._aCoords.tr.y),br:Q(e,this._aCoords.br.x,this._aCoords.br.y),bl:Q(e,this._aCoords.bl.x,this._aCoords.bl.y)}}contentBoxCorners(){let e=typeof this.raw.strokeWidth=="number"?this.raw.strokeWidth:0,t=this.raw.strokeUniform===!0,r=(t?this.dims.x:this.dims.x+e)/2,o=(t?this.dims.y:this.dims.y+e)/2,i=t?e/2:0,s=this.ownMatrix,a=1/0,l=1/0,u=-1/0,c=-1/0;for(let h of[-r,r])for(let d of[-o,o]){let f=Q(s,h,d);f.x<a&&(a=f.x),f.y<l&&(l=f.y),f.x>u&&(u=f.x),f.y>c&&(c=f.y)}return{tl:{x:a-i,y:l-i},tr:{x:u+i,y:l-i},br:{x:u+i,y:c+i},bl:{x:a-i,y:c+i}}}get inkACoords(){return this.aCoords}get parentMatrix(){return this._parentMatrix}setParentMatrix(e,t=1){this._parentMatrix=e,this._parentOpacity=t,this.invalidateWorldGeometry(),this._renderNotify?.()}get renderOpacity(){return(this._animationOverride?.opacity??this.raw.opacity??1)*(this._inIsolatedFBO?1:this._parentOpacity)}setIsolation(e){if(this._inIsolatedFBO=e,this instanceof J)for(let t of this.children)t.setIsolation(e)}invalidateWorldGeometry(){this._matrix=null,this._aCoords=null,this._bounds=null}get bounds(){return this._bounds||(this._bounds=Xn(this.aCoords)),this._bounds}containsPoint(e,t,r=0){if(this.isSolidType&&!es(this))return Hl(this)&&this.outlineStrokeHitAt(e,t,r);let o=this.aCoords,i=[o.tl,o.tr,o.br,o.bl],s=!1;for(let a=0,l=3;a<4;l=a++){let u=i[a].x,c=i[a].y,h=i[l].x,d=i[l].y;c>t!=d>t&&e<(h-u)*(t-c)/(d-c)+u&&(s=!s)}return s}outlineStrokeHitAt(e,t,r=0){if(!this.isSolidType)return!1;let o=this.dims.x/2,i=this.dims.y/2;if(!(o>0)||!(i>0))return!1;let s=this.localPoint(e,t),a=Math.abs(s.x)-o,l=Math.abs(s.y)-i;return(a>0||l>0?Math.hypot(Math.max(a,0),Math.max(l,0)):Math.min(-a,-l))<=Gl(this,r)}localPoint(e,t){return Q(ve(this.matrix),e,t)}rotateAroundCenter(e,t=this.center){let r=ge({...this.transformProps,angle:e},t);return{angle:e,left:r.x,top:r.y}}get dims(){let e=this.cropRect;if(e)return{x:e.sw,y:e.sh};let t=this.raw.width??(this.imageEl?this.imageEl.naturalWidth:0),r=this.raw.height??(this.imageEl?this.imageEl.naturalHeight:0);return{x:t,y:r}}get cropRect(){return ts(this.raw)}toObject(){let e={};for(let t of Jg)this.raw[t]!==void 0&&(e[t]=this.raw[t]);for(let[t,r]of Object.entries(this.raw))e[t]===void 0&&!t.startsWith("_")&&(e[t]=r);return e}},ex=n=>{if(n.angle===0||n.w<=0||n.h<=0)return null;let e=(n.angle%180+180)%180,t=Math.min(e,180-e);if(t<2)return null;let r=t*Math.PI/180,o=Math.abs(Math.cos(r)),i=Math.abs(Math.sin(r)),s=o*o-i*i;if(Math.abs(s)<.5)return null;let a=(n.w*o-n.h*i)/s,l=(n.h*o-n.w*i)/s;return!Number.isFinite(a)||!Number.isFinite(l)||a<=0||l<=0?null:{w:a,h:l}},tx=n=>{let{fw:e,fh:t}=n;if(e===void 0||t===void 0)return null;let r=n.w+n.h;return!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0||e>r||t>r?null:{w:e,h:t}},ye=class extends ct{_layout=null;_arcDims=null;_scrollOffset=0;constructor(e){super(e)}set(e){super.set(e),Wl(e)||(this.invalidateTextLayout(),typeof this.raw.renderSrc=="string"&&Object.keys(e).some(t=>Zg.has(t))&&(delete this.raw.renderSrc,delete this.raw.renderRect))}invalidateTextLayout(){this._layout=null,this._arcDims=null,this.invalidateGeometryCache(),this._renderNotify?.()}get textStyle(){let e=this.raw;return{fontFamily:e.fontFamily??"Times New Roman",fontSize:e.fontSize??40,fontWeight:e.fontWeight,fontStyle:e.fontStyle,lineHeight:e.lineHeight??1.16,charSpacing:e.charSpacing??0,textAlign:e.textAlign??fe.LEFT}}get paintFirst(){return this.raw.paintFirst==="stroke"?"stroke":"fill"}get textStroke(){let e=this.raw,t=typeof e.stroke=="string"?e.stroke:"",r=e.strokeWidth??1;return!t||r===0?null:{color:t,width:r,lineJoin:e.strokeLineJoin,miterLimit:e.strokeMiterLimit,lineCap:e.strokeLineCap}}get decorationDefaults(){let e=this.raw;return{underline:!!e.underline,overline:!!e.overline,linethrough:!!e.linethrough,textDecorationThickness:e.textDecorationThickness,fontSize:this.textStyle.fontSize,fill:typeof e.fill=="string"?e.fill:void 0,charSpacing:this.textStyle.charSpacing,vertical:e.vertical===!0}}get textLayout(){if(!this._layout){let e=this.raw,t=Ge(e),r=(se(e)===L.TEXTBOX||se(e)===L.TEXTIMAGE)&&t===null;this._layout=jt(e.text??"",this.textStyle,{boxWidth:r?e.width??0:null,styles:e.styles,splitByGrapheme:e.splitByGrapheme===!0,vertical:e.vertical===!0,paragraph:t==="arc"||t==="circle"?void 0:e.paragraph})}return this._layout}get scrollOffset(){return this._scrollOffset}setScrollOffset(e){this._scrollOffset=Number.isFinite(e)?e:0,this._renderNotify?.()}get textTotalWidth(){let e=this.textLayout;if(this.raw.vertical===!0&&e.verticalWidth!==void 0)return e.verticalWidth;let t=0;for(let r of e.lines)r.width>t&&(t=r.width);return t}get dims(){if(typeof this.raw.renderSrc=="string"){let t=this.bitmapRect;return{x:t.w,y:t.h}}if(Xe(this.raw)){if(!this._arcDims){let t=Et(this.textLayout,this.raw,this.textStyle.lineHeight??1.16);this._arcDims={x:t.width,y:t.height}}return this._arcDims}let e=typeof this.raw.height=="number"?this.raw.height:0;return{x:this.textLayout.width,y:Math.max(this.textLayout.height,e)}}get bitmapRect(){let e=this.raw.renderRect,t=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,r=(e&&t(e.w))??(typeof this.raw.width=="number"?this.raw.width:0),o=(e&&t(e.h))??(typeof this.raw.height=="number"?this.raw.height:0),i=e&&typeof e.x=="number"&&Number.isFinite(e.x)?e.x:0,s=e&&typeof e.y=="number"&&Number.isFinite(e.y)?e.y:0,a=e&&typeof e.angle=="number"&&Number.isFinite(e.angle)?e.angle:0,l={x:i,y:s,w:r,h:o,angle:a};if(e){let u=m=>typeof m=="number"&&Number.isFinite(m)?m:void 0,c=u(e.fw),h=u(e.fh);c!==void 0&&h!==void 0&&(l.fw=c,l.fh=h);let d=u(e.fx),f=u(e.fy);d!==void 0&&f!==void 0&&(l.fx=d,l.fy=f)}return l}get aCoords(){let e=this.bitmapFrameCorners();if(e){let t=this.parentMatrix;if(!t)return e;let r=o=>Q(t,o.x,o.y);return{tl:r(e.tl),tr:r(e.tr),br:r(e.br),bl:r(e.bl)}}return super.aCoords}contentBoxCorners(){return this.bitmapFrameCorners()??super.contentBoxCorners()}bitmapFrameCorners(){if(typeof this.raw.renderSrc!="string")return null;let e=this.bitmapRect,t=tx(e)??ex(e);if(!t&&e.angle===0&&e.x===0&&e.y===0)return null;let r=this.ownMatrix;(e.x!==0||e.y!==0)&&(r=j(r,[1,0,0,1,e.x,e.y])),t&&e.fx!==void 0&&e.fy!==void 0&&(e.fx!==0||e.fy!==0)&&(r=j(r,[1,0,0,1,e.fx,e.fy])),!t&&e.angle!==0&&(r=j(r,At({angle:-e.angle})));let o=(t?t.w:e.w)/2,i=(t?t.h:e.h)/2;return{tl:Q(r,-o,-i),tr:Q(r,o,-i),br:Q(r,o,i),bl:Q(r,-o,i)}}get inkACoords(){return zh(this,this.textInkACoords)}get textInkACoords(){if(typeof this.raw.renderSrc=="string")return super.inkACoords;let e=Ge(this.raw);if(e==="arc"||e==="circle"||e==="scroll")return super.inkACoords;let t=this.textLayout,r,o,i,s;if(e!==null){let c=Sr(this.raw),h=c?Pi(t,this.textStyle,{align:this.textStyle.textAlign}):null,d=c&&h?dh(c,t,this.raw,h,this.contentTopY):null;if(d)r=d.left,o=d.right,i=d.top,s=d.bottom;else{if(c)return super.inkACoords;let f=Pi(t,this.textStyle,{vertical:this.raw.vertical===!0,align:this.textStyle.textAlign});if(!f)return super.inkACoords;let m=t.width/2;r=-m+f.lo,o=-m+f.hi,i=this.contentTopY+f.firstTop,s=this.contentTopY+t.height}}else{let c=Pi(t,this.textStyle,{vertical:this.raw.vertical===!0,align:this.textStyle.textAlign});if(!c)return super.inkACoords;let h=t.width/2;r=-h+c.lo,o=-h+c.hi,i=this.contentTopY+c.firstTop,s=this.contentTopY+t.height}let a=this.ownMatrix,l=this.parentMatrix,u=(c,h)=>{let d=Q(a,c,h);return l?Q(l,d.x,d.y):d};return{tl:u(r,i),tr:u(o,i),br:u(o,s),bl:u(r,s)}}get contentTopY(){return typeof this.raw.renderSrc=="string"?-this.textLayout.height/2:-this.dims.y/2}cursorCoord(e){let t=this.textLayout;if(t.lines.length===0)return null;let r=0,o=0;for(let c=0;c<t.lines.length;c++){let h=t.lines[c],d=h.styleMap.flatStart,f=d+h.graphemes.length;if(e<=f){r=c,o=Math.max(0,e-d);break}c===t.lines.length-1&&(r=c,o=h.graphemes.length)}let i=t.lines[r],s=-t.width/2+i.leftOffset+(o<i.boxes.length?i.boxes[o].left:hn(i)),l=i.charStyles[Math.max(0,o-1)]?.fontSize??this.textStyle.fontSize,u=this.contentTopY+i.baseline-l*.93;return{x:s,y:u,height:l*1.28}}cursorIndexAt(e,t){let r=this.textLayout;if(r.lines.length===0)return 0;let o=t-this.contentTopY,i=0;for(let l=0;l<r.lines.length;l++){let u=r.lines[l];if(o<=u.baseline+this.textStyle.fontSize*.3){i=l;break}i=l}let s=r.lines[i],a=-r.width/2+s.leftOffset;for(let l=0;l<s.boxes.length;l++){let u=s.boxes[l];if(e<a+u.left+u.width/2)return s.styleMap.flatStart+l}return s.styleMap.flatStart+s.graphemes.length}wordBoundsAt(e){let t=Array.from(this.raw.text??""),r=a=>a===" "||a===" "||a==="\r"||a===`
8
- `,o=Math.max(0,Math.min(e,t.length));if(r(t[o]))return[o,o];let i=o,s=o;for(;i>0&&!r(t[i-1]);)i--;for(;s<t.length&&!r(t[s]);)s++;return[i,s]}},nx=(n,e)=>Math.max(24,Math.min(128,Math.ceil((n+e)*.6))),dd=(n,e)=>{if(!(n>0)||!(e>0))return null;let t=nx(n,e),r=new Float32Array((t+1)*2);for(let i=0;i<t;i++){let s=i/t*Math.PI*2;r[(i+1)*2]=n*Math.cos(s),r[(i+1)*2+1]=e*Math.sin(s)}let o=new Uint32Array(t*3);for(let i=0;i<t;i++)o[i*3]=0,o[i*3+1]=1+i,o[i*3+2]=1+(i+1)%t;return{verts:r,triangles:o}},fd=n=>{if(!Array.isArray(n)||n.length<3)return null;let e=n,t=1/0,r=1/0,o=-1/0,i=-1/0;for(let h of e)t>h.x&&(t=h.x),r>h.y&&(r=h.y),o<h.x&&(o=h.x),i<h.y&&(i=h.y);let s=(t+o)/2,a=(r+i)/2,l=new Float32Array(e.length*2),u=new Array(e.length);for(let h=0;h<e.length;h++)l[h*2]=e[h].x-s,l[h*2+1]=e[h].y-a,u[h]={x:l[h*2],y:l[h*2+1]};let c=el(u);return c.length>0?{verts:l,triangles:new Uint32Array(c)}:null},rx=n=>{let e=0;for(let i of n)e+=i.length;if(e<3)return null;let t=new Float32Array(e*2),r=[],o=0;for(let i of n){for(let s=0;s<i.length;s++)t[(o+s)*2]=i[s].x,t[(o+s)*2+1]=i[s].y;for(let s of el(i))r.push(s+o);o+=i.length}return r.length>0?{verts:t,triangles:new Uint32Array(r)}:null},ox=n=>{let e=Ce(n);if(!e)return{contours:[],dims:{x:0,y:0}};let t=Fe(e),r=Vu(e);if(!t)return{contours:r,dims:{x:0,y:0}};let o=(t.left+t.right)/2,i=(t.top+t.bottom)/2;return{contours:r.map(a=>({closed:a.closed,points:a.points.map(l=>({x:l.x-o,y:l.y-i}))})),dims:{x:t.right-t.left,y:t.bottom-t.top}}},yn=class extends ct{_mesh;set(e){super.set(e),Wl(e)||(this._mesh=void 0)}get shapeKind(){return this.typeKey}get shapeMesh(){if(this._mesh===void 0){let e=this.raw,t=this.shapeKind;if(t===L.ELLIPSE)this._mesh=dd(e.rx??0,e.ry??0);else if(t===L.CIRCLE){let r=e.radius??0;this._mesh=dd(r,r)}else t===L.TRIANGLE?this._mesh=fd(md(e)):this._mesh=fd(e.points)}return this._mesh}get dims(){let e=this.raw,t=this.shapeKind;return t===L.ELLIPSE?{x:2*(e.rx??0),y:2*(e.ry??0)}:t===L.CIRCLE?{x:2*(e.radius??0),y:2*(e.radius??0)}:t===L.TRIANGLE?{x:e.width??0,y:e.height??0}:ix(e.points)}containsPoint(e,t,r=0){if(!es(this))return Hl(this)&&this.outlineStrokeHitAt(e,t,r);let o=this.localPoint(e,t),i=this.shapeKind;if(i===L.ELLIPSE||i===L.CIRCLE){let a=this.dims.x/2,l=this.dims.y/2;if(!(a>0)||!(l>0))return!1;let u=o.x/a,c=o.y/l;return u*u+c*c<=1}let s=this.shapeMesh;return i===L.POLYLINE||i===L.POLYGON?s?pd(s.verts,o.x,o.y):Ol(this.raw.points,o,i===L.POLYGON,Math.max((Number(this.raw.strokeWidth)||1)/2,3,r)):s?pd(s.verts,o.x,o.y):!1}outlineStrokeHitAt(e,t,r=0){let o=this.localPoint(e,t),i=this.shapeKind,s=Gl(this,r);if(i===L.ELLIPSE||i===L.CIRCLE){let a=this.dims.x/2,l=this.dims.y/2;if(!(a>0)||!(l>0))return!1;let u=2*o.x/(a*a),c=2*o.y/(l*l),h=Math.hypot(u,c);if(h<1e-9)return Math.min(a,l)<=s;let d=o.x*o.x/(a*a)+o.y*o.y/(l*l)-1;return Math.abs(d)/h<=s}return i===L.TRIANGLE?Ol(md(this.raw),o,!0,s):Ol(this.raw.points,o,i===L.POLYGON,s)}},md=n=>{let e=n.width??0,t=n.height??0;return[{x:e/2,y:0},{x:e,y:t},{x:0,y:t}]},ix=n=>{if(!Array.isArray(n)||n.length===0)return{x:0,y:0};let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)e>i.x&&(e=i.x),t>i.y&&(t=i.y),r<i.x&&(r=i.x),o<i.y&&(o=i.y);return{x:r-e,y:o-t}},Ji=10,Bl=n=>Math.min(1,Math.max(0,n)),sx=n=>{let e=n.fillPaint;if(!e)return 0;if(e.kind==="solid")return Bl(e.color[3])*n.renderOpacity;if(e.kind==="gradient"){let t=0;for(let r of e.decl.stops)t=Math.max(t,Bl(r.color[3]));return t*n.renderOpacity}return null},es=n=>{let e=sx(n);return e===null||e*255>Ji},Hl=n=>{let e=n.raw.stroke;return typeof e=="object"&&e!==null?!0:typeof e!="string"||!e||Number(n.raw.strokeWidth)===0?!1:Bl(ee(e)[3])*n.renderOpacity*255>Ji},Gl=(n,e)=>Math.max((Number(n.raw.strokeWidth)||1)/2,3,e),Xl=8,xd=n=>{let e=n.typeKey;return e===L.LINE||e===L.ARROW||e===L.DIMENSION||e===L.POLYLINE?!0:(n.isShapeType||n.isSolidType)&&!es(n)},Zi=(n,e,t,r,o,i)=>{let s=o-t,a=i-r,l=s*s+a*a,u=l>0?Math.max(0,Math.min(1,((n-t)*s+(e-r)*a)/l)):0,c=t+u*s-n,h=r+u*a-e;return c*c+h*h},Ol=(n,e,t,r)=>{if(!Array.isArray(n)||n.length<2)return!1;let o=n,i=1/0,s=1/0,a=-1/0,l=-1/0;for(let d of o)i>d.x&&(i=d.x),s>d.y&&(s=d.y),a<d.x&&(a=d.x),l<d.y&&(l=d.y);let u=(i+a)/2,c=(s+l)/2,h=r*r;for(let d=0;d+1<o.length;d++)if(Zi(e.x,e.y,o[d].x-u,o[d].y-c,o[d+1].x-u,o[d+1].y-c)<=h)return!0;if(t&&o.length>2){let d=o[o.length-1];if(Zi(e.x,e.y,d.x-u,d.y-c,o[0].x-u,o[0].y-c)<=h)return!0}return!1},Nr=class extends yn{_pathGeo;_fillPolys;_pathMesh;set(e){super.set(e),("path"in e||"fillRule"in e)&&(this._pathGeo=void 0,this._fillPolys=void 0,this._pathMesh=void 0)}get pathGeometry(){return this._pathGeo===void 0&&(this._pathGeo=ox(this.raw.path)),this._pathGeo}get fillPolygons(){if(this._fillPolys===void 0){let e=this.raw.fillRule==="evenodd"?"evenodd":"nonzero";this._fillPolys=Ku(this.pathGeometry.contours,e)}return this._fillPolys}get shapeMesh(){return this._pathMesh===void 0&&(this._pathMesh=rx(this.fillPolygons)),this._pathMesh}get dims(){return this.pathGeometry.dims}containsPoint(e,t,r=0){return es(this)?ct.prototype.containsPoint.call(this,e,t):Hl(this)&&this.outlineStrokeHitAt(e,t,r)}outlineStrokeHitAt(e,t,r=0){let o=this.localPoint(e,t),i=this.pathGeometry.contours;if(i.length===0)return!1;let s=Gl(this,r)**2;for(let a of i){let l=a.points;for(let u=0;u+1<l.length;u++)if(Zi(o.x,o.y,l[u].x,l[u].y,l[u+1].x,l[u+1].y)<=s)return!0}return!1}},ax=(n,e,t)=>{let r=Number(n.strokeWidth)||1,o=Number(n.arrowWidth)||15,i=Number(n.arrowHeight)||22.5,s=n.arrowType==="start"||n.arrowType==="both"?n.arrowType:"end",a=Math.sqrt(r),l=o*a,u=i*a;if(!(u>0)||!(l>0))return!1;let c=Math.atan2(t.y2-t.y1,t.x2-t.x1),h=(d,f,m)=>{let p=Math.cos(m),b=Math.sin(m),g=e.x-d,x=e.y-f,S=g*p+x*b,w=-g*b+x*p;return S<-u||S>0?!1:Math.abs(w)<=l/2*(1+S/u)};return!!((s==="end"||s==="both")&&h(t.x2,t.y2,c)||(s==="start"||s==="both")&&h(t.x1,t.y1,c+Math.PI))},lx=(n,e,t,r)=>{let o=Number(n.textFontSize)||50,i=Number(n.textPadding)||4,s=typeof n.text=="string"&&n.text.trim()?n.text:"50cm",a=no(`${o}px Arial, sans-serif`,s)+i*2,l=Math.atan2(t.y2-t.y1,t.x2-t.x1),u=-Math.sin(l),c=Math.cos(l),h=o/2,d=r*r;for(let[R,P]of[[t.x1,t.y1],[t.x2,t.y2]])if(Zi(e.x,e.y,R-u*h,P-c*h,R+u*h,P+c*h)<=d)return!0;let f=o+(Number(n.strokeWidth)||1)/2+5,m=(t.x1+t.x2)/2+u*f,p=(t.y1+t.y2)/2+c*f,b=n.textFollowLine===!1?0:l,g=Math.cos(b),x=Math.sin(b),S=e.x-m,w=e.y-p,y=S*g+w*x,v=-S*x+w*g;return Math.abs(y)<=a/2&&Math.abs(v)<=(o+i*2)/2},Lr=class extends ct{get dims(){let e=this.linePoints;return e?{x:Math.abs(e.x2-e.x1),y:Math.abs(e.y2-e.y1)}:{x:0,y:0}}get linePoints(){let e=Number(this.raw.x1),t=Number(this.raw.y1),r=Number(this.raw.x2),o=Number(this.raw.y2);return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o)?null:{x1:e,y1:t,x2:r,y2:o}}containsPoint(e,t,r=0){let o=this.linePoints;if(!o)return!1;let i=this.localPoint(e,t);if(!i)return!1;let s=o.x2-o.x1,a=o.y2-o.y1,l=s*s+a*a,u=0;l>0&&(u=Math.max(0,Math.min(1,((i.x-o.x1)*s+(i.y-o.y1)*a)/l)));let c=o.x1+u*s,h=o.y1+u*a,d=Math.max((Number(this.raw.strokeWidth)||1)/2,3,r);if(Math.hypot(i.x-c,i.y-h)<=d)return!0;let f=this.typeKey;return f===L.ARROW?ax(this.raw,i,o):f===L.DIMENSION?lx(this.raw,i,o,d):!1}},ie=class extends ct{animatedKind;_sprite=null;_frameCanvas=null;_frameIndex=0;_anchorTime=0;_playing=!1;_videoEl=null;_frameDirty=!1;_rvfcActive=!1;_contentVersion=0;_onNewFrame=null;constructor(e,t){super(e),this.animatedKind=t}get isImageType(){return!0}get animating(){if(this.animatedKind==="video"){let e=this._videoEl;return!!e&&!e.paused&&!e.ended}return this._playing&&!!this._sprite&&this._sprite.framesLength>1}get paintSource(){return this.animatedKind==="video"?this._videoEl:this._frameCanvas}attachSprite(e,t){this._sprite=e,this._onNewFrame=t??null;let r=document.createElement("canvas");r.width=e.frameWidth,r.height=e.canvas.height,this._frameCanvas=r,this._frameIndex=0,this._anchorTime=performance.now(),this._playing=e.framesLength>1,this.blitFrame(),this.invalidateGeometryCache(),this._renderNotify?.()}attachVideo(e,t){this._videoEl=e,this._onNewFrame=t??null;let r=()=>{this._frameDirty=!0,this._onNewFrame?.()};e.addEventListener("play",()=>this.startFrameWatch()),e.addEventListener("pause",r),e.addEventListener("seeked",r),e.addEventListener("ended",()=>{try{e.currentTime=0,e.pause()}catch{}}),this.invalidateGeometryCache(),this._renderNotify?.(),e.play().catch(()=>{})}tick(e){if(this.animatedKind==="video"){let s=this._videoEl;if(!s)return!1;if(this._frameDirty)return this._frameDirty=!1,this._contentVersion++,!0;let a=this._rvfcActive?!1:!s.paused&&!s.ended;return a&&this._contentVersion++,a}let t=this._sprite;if(!this._playing||!t||t.framesLength<=1)return!1;let r=!1,o=0,i=t.framesLength;for(;o<i;){let s=t.frameDelays[this._frameIndex]||t.delay||100;if(e-this._anchorTime<s)break;this._anchorTime+=s,this._frameIndex=(this._frameIndex+1)%i,r=!0,o++}return r&&(this._contentVersion++,this.blitFrame()),r}play(){if(this.animatedKind==="video"){this._videoEl?.play().catch(()=>{});return}!this._sprite||this._sprite.framesLength<=1||(this._playing=!0,this._anchorTime=performance.now())}pause(){if(this.animatedKind==="video"){this._videoEl?.pause();return}this._playing=!1}stop(){if(this.animatedKind==="video"){let e=this._videoEl;if(!e)return;try{e.currentTime=0,e.pause()}catch{}return}this._playing=!1,this._frameIndex=0,this._contentVersion++,this.blitFrame()}syncVideoToTime(e,t){if(this.animatedKind!=="video")return;let r=this._videoEl;if(!r)return;r.pause();let o=r.duration,i=Number.isFinite(o)&&o>0?Math.min(Math.max(e,0),o):Math.max(e,0);try{r.currentTime=i}catch{}t&&r.play().catch(()=>{})}get frameIndex(){return this._frameIndex}get contentVersion(){return this._contentVersion}get mediaDuration(){if(this.animatedKind==="video"){let t=this._videoEl?.duration;if(t&&Number.isFinite(t))return t;let r=Number(this.raw.duration);return Number.isFinite(r)&&r>0?r:0}let e=this._sprite;return e?e.frameDelays.reduce((t,r)=>t+(r||e.delay||100),0)/1e3:0}startFrameWatch(){let e=this._videoEl;if(!e||this._rvfcActive||typeof e.requestVideoFrameCallback!="function")return;this._rvfcActive=!0;let t=()=>{if(!(!this._rvfcActive||!this._videoEl)){if(this._videoEl.paused||this._videoEl.ended){this._rvfcActive=!1;return}this._frameDirty=!0,this._onNewFrame?.(),e.requestVideoFrameCallback(t)}};e.requestVideoFrameCallback(t)}blitFrame(){let e=this._sprite,t=this._frameCanvas;if(!e||!t)return;let r=t.getContext("2d");r&&(r.clearRect(0,0,t.width,t.height),r.drawImage(e.canvas,this._frameIndex*e.frameWidth,0,e.frameWidth,e.canvas.height,0,0,t.width,t.height))}detach(){this._playing=!1,this._rvfcActive=!1,this._frameDirty=!1;let e=this._videoEl;if(e)try{e.pause(),e.removeAttribute("src"),e.load()}catch{}this._videoEl=null,this._sprite=null,this._frameCanvas=null,this._onNewFrame=null}get dims(){return this.animatedKind==="gif"?{x:this.raw.width??this._sprite?.frameWidth??0,y:this.raw.height??this._sprite?.canvas.height??0}:{x:this.raw.width??this._videoEl?.videoWidth??0,y:this.raw.height??this._videoEl?.videoHeight??0}}},pd=(n,e,t)=>{let r=n.length/2,o=!1;for(let i=0,s=r-1;i<r;s=i++){let a=n[i*2],l=n[i*2+1],u=n[s*2],c=n[s*2+1];l>t!=c>t&&e<(u-a)*(t-l)/(c-l)+a&&(o=!o)}return o},J=class n extends ct{children=[];constructor(e,t){super(e);let r=Array.isArray(e.objects)?e.objects:[];for(let o of r){if(!o||typeof o.type!="string")continue;let i=t(o);i&&this.children.push(i)}this.syncChildMatrices()}set(e){super.set(e),this.syncChildMatrices()}setParentMatrix(e,t=1){super.setParentMatrix(e,t),this.syncChildMatrices()}setAnimationOverride(e){super.setAnimationOverride(e),this.syncChildMatrices()}syncChildMatrices(){let e=this.matrix,t=this.renderOpacity;for(let r of this.children)r.setParentMatrix(e,t)}get dims(){let e=Number(this.raw.width),t=Number(this.raw.height);return{x:Number.isFinite(e)&&e>0?e:0,y:Number.isFinite(t)&&t>0?t:0}}containsPoint(e,t,r=0){return this.visible?this.children.some(o=>o.visible&&o.containsPoint(e,t,r)):!1}get inkACoords(){let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of this.children)if(i.visible)for(let s of[i.inkACoords.tl,i.inkACoords.tr,i.inkACoords.br,i.inkACoords.bl])e=Math.min(e,s.x),t=Math.min(t,s.y),r=Math.max(r,s.x),o=Math.max(o,s.y);return Number.isFinite(e)?{tl:{x:e,y:t},tr:{x:r,y:t},br:{x:r,y:o},bl:{x:e,y:o}}:this.aCoords}childAtPoint(e,t,r=0){for(let o=this.children.length-1;o>=0;o--){let i=this.children[o];if(!(!i.visible||!i.containsPoint(e,t,r)))return i instanceof n&&!(i instanceof te)&&!(i instanceof le)?i.childAtPoint(e,t)??i:i}return null}containsDeep(e){return this.children.some(t=>t===e||t instanceof n&&t.containsDeep(e))}adoptChild(e,t=this.children.length){this.children.splice(t,0,e),this.syncChildMatrices()}removeChildRaw(e){let t=this.children.indexOf(e);t<0||(this.children.splice(t,1),e.setParentMatrix(null),this.syncChildMatrices())}moveChildRaw(e,t){let r=this.children.indexOf(e);if(r<0)return;this.children.splice(r,1);let o=Math.max(0,Math.min(t,this.children.length));this.children.splice(o,0,e),this.syncChildMatrices()}toObject(){let e=super.toObject();return e.objects=this.children.map(t=>t.toObject()),e}},te=class n extends J{_layout;_childFactory;_placedShift;get inkACoords(){return this.aCoords}selectedCells=[];cellAnchor=null;cellRange=null;hoveredBorder=null;hoveredIndicator=null;indicatorVisible=!1;borderDragging=!1;hoveredStrip=null;hoveredDragHandle=!1;hoveredRangeHandle=!1;editingCell=null;constructor(e,t){let r=Ro(e),o=Ut({...e,width:r.constructorDims.width,height:r.constructorDims.height}),i=ge({...e,width:r.width,height:r.height},o);super({...e,left:i.x,top:i.y,width:r.width,height:r.height,objects:r.children},t),this._layout=r,this._childFactory=t,this._placedShift={x:i.x-(e.left??0),y:i.y-(e.top??0)}}_rebuilding=!1;set(e){let t=["rows","cols","columnWidths","rowHeights","manualRowHeights","minCellWidth","minCellHeight","cellPadding","cellSpacing","cellData"],r=!this._rebuilding&&Object.keys(e).some(o=>t.includes(o));if(super.set(e),r){this._rebuilding=!0;try{this.rebuildTable()}finally{this._rebuilding=!1}}}toObject(){let e=super.toObject();return typeof e.left=="number"&&(e.left=e.left-this._placedShift.x),typeof e.top=="number"&&(e.top=e.top-this._placedShift.y),e}get layout(){return this._layout}get tableView(){let e=this.raw.rows??3,t=this.raw.cols??3,r=this.raw.cellSpacing??0;return{rows:e,cols:t,columnWidths:this._layout.columnWidths,rowHeights:this._layout.rowHeights,cellSpacing:r}}get cellMap(){let e=Array.isArray(this.raw.cellData)?this.raw.cellData:[];return Dt(e)}get tableAngle(){return this.raw.angle??0}get objectScale(){return{x:Math.abs(this.raw.scaleX??1),y:Math.abs(this.raw.scaleY??1)}}cellHit(e,t){let r=this.localPoint(e,t);return od(this.tableView,this.cellMap,r.x,r.y)}borderHit(e,t){let r=this.localPoint(e,t),o=this.objectScale;return Dl(this.tableView,this.cellMap,r.x,r.y,5/o.x,5/o.y)}borderOrIndicatorHit(e,t,r){let o=this.localPoint(e,t),i=this.objectScale;return id(this.tableView,this.cellMap,o.x,o.y,{thresholdX:5/i.x,thresholdY:5/i.y,scaleX:this.raw.scaleX??1,scaleY:this.raw.scaleY??1,zoom:r})}stripHit(e,t,r=1){let o=this.localPoint(e,t);return ld(this.tableView,this.dims.x,this.dims.y,o.x,o.y,this.objectScale,r)}dragHandleHit(e,t,r=1){let o=this.localPoint(e,t);return cd(this.dims.x,this.dims.y,o.x,o.y,this.objectScale,r)}get expandedCellRange(){if(!this.selectedCells.length)return null;let e=this.cellRange??ze(this.selectedCells);return e?Nl(this.cellMap,e.r1,e.r2,e.c1,e.c2):null}get selectionBoundsRect(){let e=this.expandedCellRange;return e?Eo(this.tableView,e):null}get isFullCellSelection(){let e=this.expandedCellRange;if(!e)return!1;let t=this.tableView;return e.r1===0&&e.c1===0&&e.r2===t.rows-1&&e.c2===t.cols-1}rangeHandleHit(e,t,r=1){if(this.editingCell||!this.selectedCells.length||this.isFullCellSelection)return!1;let o=this.selectionBoundsRect;if(!o)return!1;let i=this.localPoint(e,t);return ud(o,i.x,i.y,this.objectScale,r)}static cellSelectionSink=null;setCellSelection(e,t,r){let o=this.selectedCells,i=o.length!==e.length||o.some((s,a)=>s.row!==e[a].row||s.col!==e[a].col)||this.cellAnchor?.row!==t?.row||this.cellAnchor?.col!==t?.col||this.cellRange?.r1!==r?.r1||this.cellRange?.r2!==r?.r2||this.cellRange?.c1!==r?.c1||this.cellRange?.c2!==r?.c2;this.selectedCells=e,this.cellAnchor=t,this.cellRange=r,i&&n.cellSelectionSink?.(this)}setRowSelection(e){let t=ji(this.cellMap,this.tableView.cols,e);this.setCellSelection(t,t[0]??null,ze(t))}setColumnSelection(e){let t=$i(this.cellMap,this.tableView.rows,e);this.setCellSelection(t,t[0]??null,ze(t))}clearCellSelection(){let e=this.selectedCells.length>0;this.selectedCells=[],this.cellAnchor=null,this.cellRange=null,e&&n.cellSelectionSink?.(this)}get hasCellSelection(){return this.selectedCells.length>0}clearCellInteractionState(){this.clearCellSelection(),this.clearHoverState()}clearHoverState(){this.hoveredBorder=null,this.hoveredIndicator=null,this.indicatorVisible=!1,this.hoveredStrip=null,this.hoveredDragHandle=!1,this.hoveredRangeHandle=!1}getRowMinHeight(e){let t=this.raw.minCellHeight??40;return Math.max(t,this._layout.rowTextFloors[e]??0)}cellBounds(e,t){let r=we(this.cellMap,e,t);if(r?.isMerged)return null;let o=this.tableView;if(e<0||t<0||e>=o.rows||t>=o.cols)return null;let i=r?.colspan??1,s=r?.rowspan??1;return Eo(o,{r1:e,r2:e+s-1,c1:t,c2:t+i-1})}cellSceneCenter(e,t){let r=this.cellBounds(e,t);return r?Q(this.matrix,r.left+r.width/2,r.top+r.height/2):null}rebuildTable(){let e=this.raw.reflowOriginX??"left",t=this.raw.reflowOriginY??"top",r=(b,g)=>({x:e==="left"?-b/2:e==="right"?b/2:0,y:t==="top"?-g/2:t==="bottom"?g/2:0}),o=this.dims.x,i=this.dims.y,s=Gn({...this.raw,width:o,height:i}),a=Q(s,r(o,i).x,r(o,i).y),l=Ro(this.raw,void 0,this.editingCell?{hideTextCell:this.editingCell}:void 0);this._layout=l;let u=[];for(let b of l.children){let g=this._childFactory(b);g&&u.push(g)}this.children.length=0,this.children.push(...u),this.set({width:l.width,height:l.height,objects:l.children,rowHeights:l.rowHeights});let c=r(l.width,l.height),h=a.x-(s[0]*c.x+s[2]*c.y),d=a.y-(s[1]*c.x+s[3]*c.y),f=ge({...this.raw,width:l.width,height:l.height},{x:h,y:d});this.set({left:f.x,top:f.y});let m=Ut({...this.raw,width:l.constructorDims.width,height:l.constructorDims.height}),p=ge({...this.raw,width:l.width,height:l.height},m);this._placedShift={x:p.x-(this.raw.left??0),y:p.y-(this.raw.top??0)}}},ae=class extends ct{_clipImageEl=null;constructor(e){super(e)}get clipImageEl(){return this._clipImageEl}set clipImageEl(e){this._clipImageEl=e,this._renderNotify?.()}get clipImageRaw(){let e=this.raw.clipImage;return!e||typeof e!="object"||typeof e.src!="string"?null:e}_clipVideoEl=null;_clipSprite=null;_clipFrameCanvas=null;_clipFrameIndex=0;_clipAnchorTime=0;_clipPlaying=!1;_clipOnNewFrame=null;clipDynamicVersion=0;get clipDynamicKind(){let e=se(this.clipImageRaw);return e===L.VIDEO?"video":e===L.GIF?"gif":null}get hasDynamicClip(){return!!this._clipVideoEl||!!this._clipFrameCanvas}get clipAnimating(){return this._clipVideoEl?!this._clipVideoEl.paused&&!this._clipVideoEl.ended:this._clipPlaying&&!!this._clipSprite&&this._clipSprite.framesLength>1}attachClipSprite(e,t){this._clipSprite=e,this._clipOnNewFrame=t??null;let r=document.createElement("canvas");r.width=e.frameWidth,r.height=e.canvas.height,this._clipFrameCanvas=r,this._clipFrameIndex=0,this._clipAnchorTime=performance.now(),this._clipPlaying=e.framesLength>1,this.clipDynamicVersion++,this.blitClipFrame(),this._renderNotify?.()}attachClipVideo(e,t){this._clipVideoEl=e,this._clipOnNewFrame=t??null;let r=()=>{this.clipDynamicVersion++,this._renderNotify?.(),this._clipOnNewFrame?.()};e.addEventListener("seeked",r),e.addEventListener("pause",r),e.addEventListener("play",r),this.clipDynamicVersion++,this._renderNotify?.(),e.play().catch(()=>{})}dynamicClipSource(){return this._clipVideoEl?this._clipVideoEl:this._clipFrameCanvas}tickDynamicClip(e){if(this._clipVideoEl){let i=this._clipVideoEl;return!i.paused&&!i.ended?(this.clipDynamicVersion++,!0):!1}if(!this._clipPlaying||!this._clipSprite||this._clipSprite.framesLength<=1)return!1;let t=!1,r=0,o=this._clipSprite.framesLength;for(;r<o;){let i=this._clipSprite.frameDelays[this._clipFrameIndex]||this._clipSprite.delay||100;if(e-this._clipAnchorTime<i)break;this._clipAnchorTime+=i,this._clipFrameIndex=(this._clipFrameIndex+1)%o,t=!0,r++}return t&&(this.clipDynamicVersion=this._clipFrameIndex,this.blitClipFrame()),t}blitClipFrame(){let e=this._clipSprite,t=this._clipFrameCanvas;if(!e||!t)return;let r=t.getContext("2d");r&&(r.clearRect(0,0,t.width,t.height),r.drawImage(e.canvas,this._clipFrameIndex*e.frameWidth,0,e.frameWidth,e.canvas.height,0,0,t.width,t.height))}detachDynamicClip(){this._clipPlaying=!1;try{this._clipVideoEl?.pause()}catch{}this._clipVideoEl=null,this._clipSprite=null,this._clipFrameCanvas=null,this._renderNotify?.()}get clipMediaDuration(){if(this.clipDynamicKind!=="video")return 0;let e=this._clipVideoEl?.duration;if(e&&Number.isFinite(e))return e;let t=Number(this.clipImageRaw?.duration);return Number.isFinite(t)&&t>0?t:0}playClipMedia(){this.clipDynamicKind==="video"&&this._clipVideoEl?.play().catch(()=>{})}pauseClipMedia(){this.clipDynamicKind==="video"&&this._clipVideoEl?.pause()}syncClipMediaToTime(e,t){if(this.clipDynamicKind!=="video")return;let r=this._clipVideoEl;if(!r)return;r.pause();let o=r.duration,i=Number.isFinite(o)&&o>0?Math.min(Math.max(e,0),o):Math.max(e,0);try{r.currentTime=i}catch{}t&&r.play().catch(()=>{})}},le=class extends J{constructor(e,t){super(e,t);let r=this.layoutParams,o=er(e.layoutConfig),i=!!o&&o.pieces.length===this.maskChildren.length;o&&!i&&this.reconcileIncompleteLayout(o),this.set({width:r.width,height:r.height}),this.reconcileOverlappingChildren()}get inkACoords(){return this.aCoords}reconcileIncompleteLayout(e){let t=this.maskChildren;if(t.length>0&&e.pieces.length>t.length){let r=e.pieces.slice(0,t.length),o=1,i=1;for(let s of r)o=Math.max(o,s.col+(s.colSpan??1)),i=Math.max(i,s.row+(s.rowSpan??1));e.cols=o,e.rows=i,e.pieces=r,this.set({layoutConfig:{rows:i,cols:o,pieces:r}})}this.relayoutFromConfig(e,this.layoutParams)}reconcileOverlappingChildren(){let{hGap:e,vGap:t}=this.layoutParams,r=this.layoutParams.width/2,o=this.layoutParams.height/2,i=.5,s=this.maskChildren,a=new Map,l=c=>{let h=c.raw,d=h.width??0,f=h.height??0;return{x0:h.left-d/2,x1:h.left+d/2,y0:h.top-f/2,y1:h.top+f/2}};for(let c=0;c<s.length;c++)for(let h=c+1;h<s.length;h++){let d=l(s[c]),f=l(s[h]),m=Math.min(d.x1,f.x1)-Math.max(d.x0,f.x0),p=Math.min(d.y1,f.y1)-Math.max(d.y0,f.y0);if(!(m>i&&p>i))continue;let b=d.x0<=f.x0?s[c]:s[h],g=b===s[c]?s[h]:s[c],x=l(b),S=l(g);if(x.x1>S.x0+i){if(Math.abs(x.x1-r)<i&&S.x0<r-i){let P=a.get(b)??{};P.right=S.x0-e,a.set(b,P)}else if(Math.abs(S.x0+r)<i&&x.x1>-r+i){let P=a.get(g)??{};P.left=x.x1+e,a.set(g,P)}}let w=d.y0<=f.y0?s[c]:s[h],y=w===s[c]?s[h]:s[c],v=l(w),R=l(y);if(v.y1>R.y0+i){if(Math.abs(v.y1-o)<i&&R.y0<o-i){let P=a.get(w)??{};P.bottom=R.y0-t,a.set(w,P)}else if(Math.abs(R.y0+o)<i&&v.y1>-o+i){let P=a.get(y)??{};P.top=v.y1+t,a.set(y,P)}}}if(!a.size)return;let u=[];for(let[c,h]of a){let d=l(c),f=h.left??d.x0,m=h.right??d.x1,p=h.top??d.y0,b=h.bottom??d.y1;if(!(m-f>i)||!(b-p>i))continue;let g={left:(f+m)/2,width:m-f,top:(p+b)/2,height:b-p};c.set(g),u.push(`${String(c.raw.id)}→${Math.round(g.left)},${Math.round(g.top)},${Math.round(g.width)}×${Math.round(g.height)}`)}u.length&&console.info("[PuzzleNode] 装载期叠压自愈(外缘钉签名,批次 307 存量损伤):",u.join("; "))}get layoutParams(){return{width:this.raw.layoutWidth??600,height:this.raw.layoutHeight??600,hGap:this.raw.hGap??12,vGap:this.raw.vGap??12,groupPadding:this.raw.groupPadding??0}}get maskChildren(){return this.children.filter(e=>e instanceof ae)}containsPoint(e,t,r=0){return super.containsPoint(e,t,r)?!0:this.visible?ct.prototype.containsPoint.call(this,e,t,r):!1}applyMaskParams(e){let t={};for(let[r,o]of Object.entries(e))if(o!==void 0){t[r]=o;for(let i of this.maskChildren)i.set({[r]:o})}Object.keys(t).length&&this.set(t)}updateGapParams(e){let t={};if(typeof e.hGap=="number"&&(t.hGap=e.hGap),typeof e.vGap=="number"&&(t.vGap=e.vGap),typeof e.groupPadding=="number"&&(t.groupPadding=e.groupPadding),!Object.keys(t).length)return;this.set(t);let r=er(this.raw.layoutConfig);r&&this.relayoutFromConfig(r,this.layoutParams)}updateLayout(e){let t=er(this.raw.layoutConfig);if(!t||!t.pieces.length){console.warn("[PuzzleNode] layoutConfig is invalid, skipping layout update");return}let r={...this.layoutParams};typeof e.width=="number"&&e.width>0&&(r.width=e.width),typeof e.height=="number"&&e.height>0&&(r.height=e.height),typeof e.hGap=="number"&&(r.hGap=e.hGap),typeof e.vGap=="number"&&(r.vGap=e.vGap),typeof e.groupPadding=="number"&&(r.groupPadding=e.groupPadding),this.set({hGap:r.hGap,vGap:r.vGap,groupPadding:r.groupPadding}),this.relayoutFromConfig(t,r),this.set({width:r.width,height:r.height})}editingMask=null;get editingMaskIndex(){return this.editingMask?this.maskChildren.indexOf(this.editingMask):-1}maskEdgeOnOuterBorder(e,t){let r=this.layoutParams,o=Math.max(0,r.width-r.groupPadding*2),i=Math.max(0,r.height-r.groupPadding*2),s=o/2,a=i/2,l=e.raw.left??0,u=e.raw.top??0,c=e.raw.width??0,h=e.raw.height??0,d=.5;return t==="left"?l-c/2<=-s+d:t==="right"?l+c/2>=s-d:t==="top"?u-h/2<=-a+d:u+h/2>=a-d}exitMaskEditing(){this.editingMask=null}removeCol(e){let t=er(this.raw.layoutConfig);if(!t||t.pieces.length!==this.maskChildren.length)return!1;let r=Vh(t.pieces,t.cols,e);return r?(t.cols-=1,this.applyPuzzleRemoval(t,r.removed)):!1}removeRow(e){let t=er(this.raw.layoutConfig);if(!t||t.pieces.length!==this.maskChildren.length)return!1;let r=qh(t.pieces,t.rows,e);return r?(t.rows-=1,this.applyPuzzleRemoval(t,r.removed)):!1}removePiece(e){let t=er(this.raw.layoutConfig);if(!t||t.pieces.length!==this.maskChildren.length)return!1;let r=Kh(t.pieces,e);return r?this.applyPuzzleRemoval(t,r.removed):!1}applyPuzzleRemoval(e,t){if(!e)return!1;let r=new Set(t),o=this.children.filter(s=>!(s instanceof ae&&r.has(this.maskChildren.indexOf(s)))),i=o.filter(s=>s instanceof ae).map(s=>s.toObject());return this.children.length=0,this.children.push(...o),this.set({layoutConfig:{rows:e.rows,cols:e.cols,pieces:e.pieces},objects:i}),this.relayoutFromConfig(e,this.layoutParams),!0}toObject(){let e=super.toObject();return e.objects=this.children.map(t=>t.toObject()),e}relayoutFromConfig(e,t){let r=Rl(e,t);this.maskChildren.forEach((o,i)=>{let s=r[i];if(!s)return;let a=o.raw.width||s.w,l=o.raw.height||s.h;o.set({left:s.cx,top:s.cy,width:s.w,height:s.h});let u=o.clipImageRaw;if(u){let c=u.width||0,h=u.height||0;if(c&&h){let d=Math.max(a/c,l/h),f=Math.max(s.w/c,s.h/h),m=u.scaleX??1,p=d?m/d:1,b=f*(p||1);o.set({clipImage:{...u,scaleX:b,scaleY:b}})}typeof u.clipX=="number"&&o.set({clipImage:{...o.raw.clipImage,clipX:(u.clipX||0)*(a?s.w/a:1)}}),typeof u.clipY=="number"&&o.set({clipImage:{...o.raw.clipImage,clipY:(u.clipY||0)*(l?s.h/l:1)}})}}),this.set({layoutWidth:t.width,layoutHeight:t.height})}},ts=n=>{if(!dt.has(se(n)))return null;let e=Number(n.cropX)||0,t=Number(n.cropY)||0;if(!(typeof n.cropX=="number"||typeof n.cropY=="number"||n.cropSizeMode==="visible"||e>0||t>0)||typeof n.width!="number"||typeof n.height!="number")return null;let o=n.cropSizeMode==="visible";return{sx:e,sy:t,sw:Math.max(0,o?n.width:n.width-e),sh:Math.max(0,o?n.height:n.height-t)}},Ct=n=>{if(!n||typeof n.type!="string")return null;let e=se(n);return e===L.TABLE?new te(n,Ct):gi.has(e)?new le(n,Ct):ot.has(e)&&typeof n.src=="string"?new ae(n):e===L.GROUP?new J(n,Ct):xi.has(e)&&typeof n.src=="string"?new ie(n,"gif"):yi.has(e)&&typeof n.src=="string"?new ie(n,"video"):dt.has(e)&&typeof n.src=="string"?new ct(n):$n.has(e)?new ct(n):an.has(e)&&typeof n.text=="string"?new ye(n):e===L.PATH?new Nr(n):ft.has(e)?new Lr(n):Un.has(e)?new yn(n):null},zl=n=>{let e=[],t={};for(let r of n){let o=Ct(r);o?e.push(o):r&&typeof r.type=="string"&&(t[r.type]=(t[r.type]||0)+1)}return{nodes:e,skippedTypes:t}},Je=(n,e)=>new Promise((t,r)=>{let o=new Image;e!==null&&(o.crossOrigin=e||"anonymous"),o.onload=()=>t(o),o.onerror=()=>r(new Error(`[engine] image load failed: ${n.slice(0,80)}`)),o.src=n}),ko=n=>{if(n instanceof J||n instanceof ae||n instanceof ie||n.isImageType)return null;let e=n.raw.mask;return!e||e.disabled===!0||typeof e.src!="string"||!e.src?null:e.src};var cx=n=>typeof n!="string"||!n||/^cmyk\(/i.test(n)?null:n,Ft=n=>{if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.r!="number"||typeof e.g!="number"||typeof e.b!="number")return null;let t=r=>Math.max(0,Math.min(255,Math.round(r)));return`rgba(${t(e.r)}, ${t(e.g)}, ${t(e.b)}, 1)`}return cx(n)},ns=n=>n?.offsetEnable?{x:Number(n.offsetX)||0,y:Number(n.offsetY)||0}:{x:0,y:0},vn=n=>{if(typeof n!="string")return;let e=n.trim().toLowerCase().replace(/\s*\([^)]*\)\s*$/,"").replace(/\s+/g,"-");if(!(!e||e==="normal"||e==="source-over")){if(e==="linear-dodge")return"lighter";if(/^[a-z-]+$/.test(e))return e}},Mt=(n,e={})=>{if(!n||typeof n!="object"||Array.isArray(n))return null;let t=n,r=c=>{if(!c||typeof c!="object")return!1;let h=c;return h.enabled!==!1&&h.showInDialog!==!1},o=[];if(Array.isArray(t.dropShadow))for(let c of t.dropShadow){if(!r(c))continue;let h=Ft(c?.fill)??Ft(c?.color)??"rgba(0,0,0,0.5)",d=Number(c?.blur)||0,f=Number(c?.offsetX)||0,m=Number(c?.offsetY)||0;!d&&!f&&!m||o.push({color:h,rgba:ee(h),blur:d,offsetX:f,offsetY:m,blendMode:vn(c?.blendMode)})}let i=[];if(Array.isArray(t.innerShadow))for(let c of t.innerShadow){if(!r(c))continue;let h=Ft(c?.fill)??Ft(c?.color)??"rgba(0,0,0,0.5)",d=Number(c?.blur)||0,f=Number(c?.offsetX)||0,m=Number(c?.offsetY)||0;!d&&!f&&!m||i.push({color:h,rgba:ee(h),blur:d,offsetX:f,offsetY:m,blendMode:vn(c?.blendMode)})}let s=[];if(Array.isArray(t.solidFill))for(let c of t.solidFill){if(!r(c))continue;let h=Number(c?.fillType)||0;if(h===1){if(!c?.fill||typeof c.fill!="object")continue;let f=Yn(c.fill);if(!f)continue;s.push({kind:"gradient",decl:f,offset:ns(c),blendMode:vn(c?.blendMode)});continue}if(h===2){let f=pr(c?.fill);if(!f)continue;s.push({kind:"pattern",decl:f,offset:ns(c),blendMode:vn(c?.blendMode)});continue}if(h!==0)continue;let d=Ft(c?.fill)??Ft(c?.color);d&&s.push({kind:"solid",color:d,rgba:ee(d),offset:ns(c),blendMode:vn(c?.blendMode)})}let a=[];if(Array.isArray(t.stroke))for(let c of t.stroke){if(!r(c))continue;let h=c?.size&&typeof c.size=="object"?Number(c.size.value):0,d=e.text?h:Number(c?.strokeWidth)||h||0;if(!d)continue;let f=c?.fill&&typeof c.fill=="object"&&!Array.isArray(c.fill)?Yn(c.fill):null,m=Ft(c?.fill)??Ft(c?.color)??"#666666",p=c?.position||c?.strokeAlignment||(e.text?"center":"outside");a.push({kind:f?"gradient":"solid",color:m,rgba:ee(m),width:d,alignment:p,offset:ns(c),blendMode:vn(c?.blendMode),...f?{decl:f}:{}})}let l,u=n.bevel;if(u&&typeof u=="object"&&!Array.isArray(u)){let c=u;if(r(c)){let h=Number(n.scale)||1,d=c.size&&typeof c.size=="object"?Number(c.size.value):Number(c.size),f=(Number.isFinite(d)?d:0)/(h>0?h:1);if(f>0){let m=typeof c.style=="string"?c.style.toLowerCase():"",p=m.includes("outer")?"outer":m.includes("pillow")?"pillow":m.includes("emboss")?"emboss":"inner",b=typeof c.technique=="string"&&c.technique.toLowerCase().includes("chisel")&&!c.technique.toLowerCase().includes("soft")?"hard":"smooth",g=Ft(c.highlightColor)??"rgba(255, 255, 255, 1)",x=Ft(c.shadowColor)??"rgba(0, 0, 0, 1)";l={style:p,technique:b,sizePx:f,strength:Math.min(4,Math.max(0,Number(c.strength??c.depth)||1)),angleDeg:Number.isFinite(Number(c.angle))?Number(c.angle):120,altitudeDeg:Math.min(90,Math.max(0,Number.isFinite(Number(c.altitude))?Number(c.altitude):30)),directionDown:typeof c.direction=="string"&&c.direction.toLowerCase()==="down",highlight:{color:g,rgba:ee(g),opacity:Math.min(1,Math.max(0,Number(c.highlightOpacity)||.5)),blendMode:vn(c.highlightBlendMode)},shadow:{color:x,rgba:ee(x),opacity:Math.min(1,Math.max(0,Number(c.shadowOpacity)||.5)),blendMode:vn(c.shadowBlendMode)}}}}}return o.length===0&&i.length===0&&s.length===0&&a.length===0&&!l?null:{dropShadows:o,innerShadows:i,solidFills:s,strokes:a,...l?{bevel:l}:{}}},ux=n=>{let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return`${n.length}:${(e>>>0).toString(36)}`},_r=n=>{if(!n)return[];let e=[];for(let t of n.solidFills)t.kind==="pattern"&&!e.includes(t.decl.src)&&e.push(t.decl.src);return e},wn=n=>{let e=c=>String(Math.round(c*1e4)/1e4),t=c=>c.map(e).join(","),r=c=>c?`~${c}`:"",o=n.dropShadows.map(c=>`${t(c.rgba)}:${e(c.blur)}:${e(c.offsetX)}:${e(c.offsetY)}${r(c.blendMode)}`).join(";"),i=n.innerShadows.map(c=>`${t(c.rgba)}:${e(c.blur)}:${e(c.offsetX)}:${e(c.offsetY)}${r(c.blendMode)}`).join(";"),s=c=>{let h=`@${e(c.offset.x)},${e(c.offset.y)}${r(c.blendMode)}`;if(c.kind==="solid")return t(c.rgba)+h;if(c.kind==="pattern"){let p=c.decl,b=p.patternTransform?p.patternTransform.map(e).join(","):"-";return`p:${ux(p.src)}:${p.repeat}@${e(p.offsetX)},${e(p.offsetY)}:${b}${h}`}let d=c.decl,f=d.stops.map(p=>`${e(p.offset)}@${p.color.map(e).join(",")}`).join(","),m=d.gradientTransform?d.gradientTransform.map(e).join(","):"-";return`g${d.kind[0]}:${e(d.x1)},${e(d.y1)},${e(d.x2)},${e(d.y2)},${e(d.r1)},${e(d.r2)},${d.gradientUnits},${m};${f}${h}`},a=n.solidFills.map(s).join(";"),l=n.strokes.map(c=>`${t(c.rgba)}:${e(c.width)}:${c.alignment}@${e(c.offset.x)},${e(c.offset.y)}${r(c.blendMode)}${c.decl?`~g${pi(c.decl)}`:""}`).join(";"),u=n.bevel?`${n.bevel.style}/${n.bevel.technique}:${e(n.bevel.sizePx)}:${e(n.bevel.strength)}:${e(n.bevel.angleDeg)}:${e(n.bevel.altitudeDeg)}:${n.bevel.directionDown?"d":"u"}:${t(n.bevel.highlight.rgba)}@${e(n.bevel.highlight.opacity)}${r(n.bevel.highlight.blendMode)}:${t(n.bevel.shadow.rgba)}@${e(n.bevel.shadow.opacity)}${r(n.bevel.shadow.blendMode)}`:"";return`psd|${o}|${i}|${a}|${l}|${u}`};var hx=512,dx=new Set([L.QRCODE,L.BARCODE,L.ECHART,L.FABRIC_ECHART]),Sd=n=>{let e=Mt(n.raw.effects);if(!e)return null;let t=e.dropShadows,r=e.strokes;return!t.length&&!r.length?null:{shadows:t,strokes:r,key:wn(e)}},fx=n=>n?`${n.sx},${n.sy},${n.sw},${n.sh}`:"none",Yl=new WeakMap,yd=n=>Math.max(1,Math.min(hx,Math.floor(n))),mx=(n,e,t,r,o)=>{let i=Sd(n);if(!i)return;let s=n.imageEl;if(!s)return;let a=n.dims,l=null;if(i.shadows.length){let h=Hi(n,i.shadows,s,1,n.cropRect);if(!h)throw new Error("fx mask: shadow bake unavailable");let d=h.canvas.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("fx mask: shadow ctx unavailable");l={data:d.getImageData(0,0,h.w,h.h).data,w:h.w,h:h.h}}let u=[];if(i.strokes.length){for(let h of bn(n,i.strokes,s,!0,1,n.cropRect)){let d=h.canvas.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("fx mask: stroke ctx unavailable");u.push({data:d.getImageData(0,0,h.w,h.h).data,w:h.w,h:h.h,dx:h.dx,dy:h.dy})}if(!u.length)throw new Error("fx mask: stroke bake unavailable")}let c=n.matrix;for(let h=0;h<r;h++)for(let d=0;d<t;d++){if(e[h*t+d])continue;let f=((d+.5)/t-.5)*a.x,m=((h+.5)/r-.5)*a.y;if(l){let p=Math.round(c[0]*f+c[2]*m+l.w/2),b=Math.round(c[1]*f+c[3]*m+l.h/2);if(p>=0&&b>=0&&p<l.w&&b<l.h&&l.data[(b*l.w+p)*4+3]>o){e[h*t+d]=1;continue}}for(let p of u){let b=Math.round(f-p.dx+p.w/2),g=Math.round(m-p.dy+p.h/2);if(b>=0&&g>=0&&b<p.w&&g<p.h&&p.data[(g*p.w+b)*4+3]>o){e[h*t+d]=1;break}}}},px=n=>{let e=n.imageEl,t=n.dims,r=n.cropRect,o=r?r.sw:e?.naturalWidth||0,i=r?r.sh:e?.naturalHeight||0;if(!e||!(t.x>0)||!(t.y>0)||!(o>0)||!(i>0))return{mask:new Uint8Array(0),maskW:0,maskH:0};let s=yd(t.x),a=yd(t.y),l=document.createElement("canvas");l.width=s,l.height=a;let u=new Uint8Array(0);try{let c=l.getContext("2d",{willReadFrequently:!0});if(c){c.drawImage(e,r?r.sx:0,r?r.sy:0,o,i,0,0,s,a);let h=Math.min(255,Ji/Math.max(n.renderOpacity,1/255)),{data:d}=c.getImageData(0,0,s,a);u=new Uint8Array(s*a);for(let f=0;f<u.length;f++)d[f*4+3]>h&&(u[f]=1);mx(n,u,s,a,h)}}catch{u=new Uint8Array(0)}finally{l.width=0,l.height=0}return{mask:u,maskW:u.length>0?s:0,maskH:u.length>0?a:0}},bx=n=>{let e=`${n.dims.x},${n.dims.y}|${fx(n.cropRect)}|${n.renderOpacity}`,t=Sd(n);if(!t)return e;let r=n.matrix,o=i=>Math.round(i*1e3)/1e3;return`${e}|${t.key}|${o(r[0])},${o(r[1])},${o(r[2])},${o(r[3])}`},gx=n=>{let e=bx(n),t=Yl.get(n);if(t&&t.stamp===e&&t.element===n.imageEl)return t.rec;let r=px(n);return Yl.set(n,{element:n.imageEl,stamp:e,rec:r}),r},xx=(n,e,t)=>{let r=gx(n);if(r.maskW===0||r.maskH===0)return!1;let o=n.dims,i=n.localPoint(e,t),s=i.x+o.x/2,a=i.y+o.y/2;if(s<0||a<0||s>=o.x||a>=o.y)return!0;let l=Math.min(r.maskW-1,Math.floor(s/o.x*r.maskW)),u=Math.min(r.maskH-1,Math.floor(a/o.y*r.maskH));return r.mask[u*r.maskW+l]===0},yx=(n,e,t,r)=>{for(let o of n.children)if(!(!o.visible||!o.containsPoint(e,t,r.strokeBandOf?.(o)??0))&&!rs(o,e,t,r))return!0;return!1},rs=(n,e,t,r)=>{if(n instanceof te)return!1;let o=typeof n.raw.globalCompositeOperation=="string"?n.raw.globalCompositeOperation:"";return o==="multiply"&&!r.selection.includes(n)||o&&o!=="source-over"&&n.typeKey!==L.REFERENCELINE&&r.hasSelectableBelow()?!0:n instanceof le||n instanceof ae||n instanceof ie||n.isTextType||n.isLineType?!1:n instanceof J?!yx(n,e,t,r):!n.isImageType||dx.has(n.typeKey)||typeof n.raw.name=="string"&&n.raw.name.toLowerCase()==="qrcode"||!dt.has(n.typeKey)?!1:xx(n,e,t)},Sx=n=>{Yl.delete(n)},Dr=(n,e,t,r)=>{for(let o=n.children.length-1;o>=0;o--){let i=n.children[o];if(!(!i.visible||i.raw.evented===!1||!i.containsPoint(e,t)||rs(i,e,t,{selection:r,hasSelectableBelow:()=>{for(let a=o-1;a>=0;a--){let l=n.children[a];if(l.visible&&l.raw.evented!==!1&&l.containsPoint(e,t))return!0}return!1}})))return i instanceof J&&!(i instanceof te)&&!(i instanceof le)?Dr(i,e,t,r)??i:i}return null};import vx from"rbush";var Ul=0,wx=()=>(Ul=(Ul+1)%4294967295,`tx-${Date.now().toString(36)}-${Ul.toString(36)}`),Ao=class{events=new Hn;_nodes=[];_index=new vx;_indexDirty=!1;_selection=[];_editingNode=null;_editingTextSnapshot="";_editingBeforeObject=null;_editingBitmapSnapshot=null;_editingTransient=!1;editSelection={start:0,end:0};skippedTypes={};get nodes(){return this._nodes}get selection(){return this._selection}get editingNode(){return this._editingNode}_selectionFrame=null;get selectionFrame(){return this._selectionFrame}setSelectionFrame(e){this._selectionFrame=e}get activeObject(){return this._selection[0]??null}_activeGroupChild=null;get activeGroupChild(){return this._activeGroupChild}setActiveGroupChild(e){let t=this._selection.length===1?this._selection[0]:null,r=e&&t instanceof J&&t.containsDeep(e)?e:null;if(this._activeGroupChild===r)return;let o=this._activeGroupChild;this._activeGroupChild=r,o&&this.events.fire("group:child-deactivated"),r&&this.events.fire("group:child-activated",r,t)}_groupEditingGroup=null;get groupEditing(){return this._groupEditingGroup!==null}get groupEditingGroup(){return this._groupEditingGroup}setGroupEditing(e,t){if(!e){this._groupEditingGroup=null;return}let r=t??(this._selection.length===1&&this._selection[0]instanceof J?this._selection[0]:null);this._groupEditingGroup=r&&!(r instanceof te)&&!(r instanceof le)?r:null}_hovered=null;get hovered(){return this._hovered}setHovered(e){let r=e!==null&&this._nodes.some(o=>o===e||o instanceof J&&o.containsDeep(e))?e:null;this._hovered!==r&&(this._hovered=r)}_seamHover=null;get seamHover(){return this._seamHover}setSeamHover(e){let t=this._seamHover,r=e&&this._nodes.includes(e.puzzle)&&e.puzzle.maskChildren.includes(e.mask)?e:null;t?.puzzle===r?.puzzle&&t?.mask===r?.mask&&t?.handle===r?.handle||(this._seamHover=r)}loadObjects(e){let{nodes:t,skippedTypes:r}=zl(e);this._nodes=t,this.skippedTypes=r;for(let o of t)this.attachRenderTracking(o);this.clearSelection(),this.rebuildIndex(),this.bumpStructure()}add(e){this._nodes.push(e),this.attachRenderTracking(e),this.markIndexDirty(),this.events.fire("object:added",e),this.bumpStructure()}remove(e){let t=this._nodes.indexOf(e);t>=0&&this._nodes.splice(t,1),this._selection=this._selection.filter(r=>r!==e),this._selectionFrame=null,this._activeGroupChild&&this.setActiveGroupChild(this._activeGroupChild),this._hovered&&this.setHovered(this._hovered),this.markIndexDirty(),this.events.fire("object:removed",e),this.bumpStructure()}insertAt(e,...t){let r=Math.max(0,Math.min(e,this._nodes.length));this._nodes.splice(r,0,...t);for(let o of t)this.attachRenderTracking(o);this.markIndexDirty();for(let o of t)this.events.fire("object:added",o);return this.bumpStructure(),this._nodes.length}moveNodeTo(e,t){let r=this._nodes.indexOf(e);if(r<0)return;this._nodes.splice(r,1);let o=Math.max(0,Math.min(t,this._nodes.length));this._nodes.splice(o,0,e),this.bumpStructure()}_structureVersion=1;_renderDirty=new Set;get structureVersion(){return this._structureVersion}get renderDirty(){return this._renderDirty}drainRenderDirty(){this._renderDirty.clear()}bumpStructure(){this._structureVersion++,this._renderDirty.clear()}attachRenderTracking(e){if(e._renderNotify=()=>{this._renderDirty.add(e)},e instanceof J)for(let t of e.children)this.attachRenderTracking(t)}findNodeDeep(e){let t=(r,o)=>{for(let i=0;i<r.length;i++){let s=r[i];if(s.id===e)return{node:s,parent:o,index:i};if(s instanceof J&&!(s instanceof te)){let a=t(s.children,s);if(a)return a}}return null};return t(this._nodes,null)}setProps(e,t,r={}){let o="visible"in t;if(o&&t.visible===e.raw.visible&&Object.keys(t).length===1)return;let i=e.visible;e.set(t);let s=o&&e.visible!==i;s&&this.bumpStructure(),o&&!s&&Object.keys(t).length===1||this.markIndexDirty()}rebuildIndex(){let e=[];for(let t of this._nodes){if(!t.visible)continue;let r=t.bounds,o=this.strokeHitBand(t);e.push({minX:r.left-o,minY:r.top-o,maxX:r.right+o,maxY:r.bottom+o,node:t})}this._index.clear(),this._index.load(e),this._indexDirty=!1}commitGeometry(){this._indexDirty&&this.rebuildIndex()}refreshHitIndex(){this.rebuildIndex()}markIndexDirty(){this._indexDirty=!0}_hitZoom=1;setViewportZoom(e){!(e>0)||e===this._hitZoom||(this._hitZoom=e,this.rebuildIndex())}hitBandScene(){return Xl/this._hitZoom}strokeHitBand(e){return xd(e)?Math.max(Number(e.raw.padding)||0,Xl)/this._hitZoom:0}findTarget(e,t){this._indexDirty&&this.rebuildIndex();let r=this._index.search({minX:e,minY:t,maxX:e,maxY:t}),o=new Map;this._nodes.forEach((i,s)=>o.set(i,s)),r.sort((i,s)=>(o.get(s.node)??-1)-(o.get(i.node)??-1));for(let i=0;i<r.length;i++){let s=r[i].node,a=this.hitBandScene();if(!(!s.visible||s.raw.evented===!1||!s.containsPoint(e,t,a))&&!rs(s,e,t,this.alphaHitContext(r,i,e,t)))return s}return null}alphaHitContext(e,t,r,o){let i=null,s=this.hitBandScene();return{selection:this._selection,strokeBandOf:()=>s,hasSelectableBelow:()=>(i===null&&(i=e.slice(t+1).some(a=>a.node.visible&&a.node.raw.evented!==!1&&a.node.containsPoint(r,o,s))),i)}}objectsIntersectingRect(e,t,r,o){this._indexDirty&&this.rebuildIndex();let i={minX:Math.min(e,r),minY:Math.min(t,o),maxX:Math.max(e,r),maxY:Math.max(t,o)},s=new Set(this._index.search(i).map(a=>a.node));return this._nodes.filter(a=>a.visible&&s.has(a)&&a.bounds.left<=i.maxX&&i.minX<=a.bounds.right&&a.bounds.top<=i.maxY&&i.minY<=a.bounds.bottom&&!a.syntheticOwner&&!Ir.has(String(a.raw.id??""))&&!Ze(a))}setSelection(e,t="create"){this._selection=e.filter(r=>this._nodes.includes(r)),this._selectionFrame=null,this._groupEditingGroup&&!(this._selection.length===1&&this._selection[0]===this._groupEditingGroup)&&(this._groupEditingGroup=null),this._hovered=null,this._selection.length===0?this.events.fire("selection:cleared"):t==="create"?this.events.fire("selection:created",[...this._selection]):this.events.fire("selection:updated",[...this._selection]),this._activeGroupChild&&this.setActiveGroupChild(this._activeGroupChild)}clearSelection(){this._activeGroupChild&&this.setActiveGroupChild(null),this._groupEditingGroup=null,this._hovered=null,this._selection.length!==0&&(this._selection=[],this._selectionFrame=null,this.events.fire("selection:cleared"))}_transformGestureAt=-1/0;get transformGestureAt(){return this._transformGestureAt}applyTransform(e,t,r,o){if(e.length){(r==="moving"||r==="scaling"||r==="rotating")&&(this._transformGestureAt=performance.now());for(let i of e)this.setProps(i,t(i),{deferIndexRebuild:!0});if(this.markIndexDirty(),r==="modified"){this.commitGeometry();let i=o?.before,s=i||o?.action||o?.transactionId?{action:o?.action,before:i?e.map(a=>i.get(a)).filter(a=>!!a):void 0,transactionId:o?.transactionId}:void 0;this.fireObjectModified([...e],s)}else this.events.fire(`object:${r}`,e[0])}}fireObjectModified(e,t){let r=t?.transactionId??wx();this.events.fire("object:modified",e,{...t,transactionId:r})}enterEditing(e,t={}){let r=this._nodes.find(i=>i===e||i instanceof J&&i.containsDeep(e));if(!r||this._editingNode===e)return;this._editingNode&&this.exitEditing(),this._editingNode=e,this._editingTransient=t.transient===!0,this._editingTextSnapshot=e.raw.text??"",this._editingBitmapSnapshot=typeof e.raw.renderSrc=="string"?{renderSrc:e.raw.renderSrc,renderRect:e.raw.renderRect}:null,this._editingBeforeObject=e.toObject();let o=this._editingTextSnapshot.length;this.editSelection.start=this.editSelection.end=o,t.transient||this.setSelection([r],"update"),this.events.fire("text:editing:entered",e)}exitEditing(){let e=this._editingNode;if(!e)return;let t=this._editingTransient;if(this._editingNode=null,this._editingTransient=!1,this.rebuildIndex(),this.events.fire("text:editing:exited",e),t){this._editingTextSnapshot="",this._editingBeforeObject=null,this._editingBitmapSnapshot=null;return}let r=e.raw.text??"";r!==this._editingTextSnapshot?(this.events.fire("text:editing:committed",e,this._editingTextSnapshot,r),this.fireObjectModified([e],{before:this._editingBeforeObject?[this._editingBeforeObject]:void 0})):this._editingBitmapSnapshot&&(e.raw.renderSrc=this._editingBitmapSnapshot.renderSrc,e.raw.renderRect=this._editingBitmapSnapshot.renderRect,e.markRenderDirty()),this._editingTextSnapshot="",this._editingBeforeObject=null,this._editingBitmapSnapshot=null}updateEditingText(e,t,r){let o=this._editingNode;o&&(o.set({text:e}),this.syncEditSelection(t,r),this.markIndexDirty(),this.events.fire("text:changed",o))}updateEditingSelection(e,t){this._editingNode&&this.syncEditSelection(e,t)}syncEditSelection(e,t){let r=this._editingNode.textLayout.graphemeCodeUnitOffsets;this.editSelection.start=vd(r,e),this.editSelection.end=vd(r,t)}toObjects(){return this._nodes.filter(e=>!e.syntheticOwner).map(e=>e.toObject())}},vd=(n,e)=>{let t=0,r=n.length-1;for(;t<r;){let o=t+r+1>>1;n[o]<=e?t=o:r=o-1}return t};var os=n=>typeof n!="string"||n.length===0?!1:/^data:image\/svg\+xml/i.test(n)?!0:/\.svg(?:[?#]|$)/i.test(n),wd=(n,e,t,r=4096)=>{let o=Math.max(n.w,n.h);if(!(o>0)||!(t>=1))return{factor:1,needsRaster:!1};let i=Math.max(e.w/n.w,e.h/n.h);if(!(i>0)||!Number.isFinite(i))return{factor:1,needsRaster:!1};let s=1;for(;s*2*o<=r;)s*=2;let a=1;for(;a<i-1e-9&&a<s;)a*=2;return a===t?{factor:t,needsRaster:!1}:{factor:a,needsRaster:!0}},Td=(n,e)=>{let t=n.naturalWidth||n.width,r=n.naturalHeight||n.height,o=document.createElement("canvas");o.width=Math.max(1,Math.round(t*e)),o.height=Math.max(1,Math.round(r*e));let i=o.getContext("2d");return i&&(i.imageSmoothingEnabled=!0,i.imageSmoothingQuality="high",i.drawImage(n,0,0,o.width,o.height)),o};var is=(n,e)=>{if(n.children.includes(e))return[n];for(let t of n.children)if(t instanceof J&&!(t instanceof te)&&!(t instanceof le)){let r=is(t,e);if(r.length)return[...r,n]}return[]},Ed=n=>{let e=n.matrix,t=n.ownMatrix,r=ve(e),o=(i,s,a)=>Q(i,s,a,!0);return(i,s)=>{let a=o(r,i,s);return o(t,a.x,a.y)}},Cd=n=>{let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n.children){if(!i.visible)continue;let s=i.contentBoxCorners();for(let a of[s.tl,s.tr,s.br,s.bl])a.x<e&&(e=a.x),a.y<t&&(t=a.y),a.x>r&&(r=a.x),a.y>o&&(o=a.y)}return Number.isFinite(e)?{minX:e,minY:t,maxX:r,maxY:o}:null},Md=n=>{let e=Cd(n);if(!e)return null;let t=n.matrix;return{tl:Q(t,e.minX,e.minY),tr:Q(t,e.maxX,e.minY),br:Q(t,e.maxX,e.maxY),bl:Q(t,e.minX,e.maxY)}},ss=n=>{let e=[];for(let t=0;t<n.length;t++){let r=n[t],o=Cd(r);if(!o)continue;let i=o.maxX-o.minX,s=o.maxY-o.minY,a={x:(o.minX+o.maxX)/2,y:(o.minY+o.maxY)/2},l=new Map;for(let m of r.children){let p=m.aCoords;l.set(m,{x:(p.tl.x+p.br.x)/2,y:(p.tl.y+p.br.y)/2})}let u=Q(r.matrix,a.x,a.y),c=n[t+1]??null,h=c?Q(ve(c.matrix),u.x,u.y):u,d=ge({...r.raw,width:i,height:s},h);r.set({width:i,height:s,left:d.x,top:d.y});let f=ve(r.matrix);for(let m of r.children){let p=l.get(m);if(!p)continue;let b=Q(f,p.x,p.y),g=ge({...m.raw,width:m.dims.x,height:m.dims.y},b);m.set({left:g.x,top:g.y})}e.push(r,...r.children)}return e};var $l=["tl","tr","bl","br"],Tn=new Set($l),as=["tlS","trS","blS","brS"],Tx=new Set(as),No={tlS:"tl",trS:"tr",blS:"bl",brS:"br"},Ex=new Set(["ml","mr","mt","mb"]),or={ml:"x",mr:"x",mt:"y",mb:"y"},ls={ml:"left",mr:"right",mt:"top",mb:"bottom"},En=n=>Ex.has(n),cs=n=>Tn.has(n),Fr=n=>Tx.has(n);var kn=8,ir=12,Rt=1.5,Rd=24,Cx=["lockMovementX","lockMovementY","lockScalingX","lockScalingY","lockSkewingX","lockSkewingY","lockRotation"],at=n=>{let e=n.raw;return Cx.some(t=>!!e[t])},ms=28,jl=null,Mx=()=>{if(jl)return jl;let n=document.createElement("canvas");n.width=ms*2,n.height=ms*2;let e=n.getContext("2d");if(e){e.scale(2,2);let t=ms/2;e.beginPath(),e.arc(t,t,12,0,Math.PI*2),e.fillStyle="#ffffff",e.fill(),e.strokeStyle="#e0e0e0",e.lineWidth=4/3,e.stroke(),typeof Path2D<"u"&&(e.translate(t,t),e.scale(2/3,2/3),e.translate(-12,-12),e.beginPath(),e.strokeStyle="#2c2c2c",e.lineWidth=2,e.lineCap="round",e.lineJoin="round",e.stroke(new Path2D("M5 13a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v6a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-6z M11 16a1 1 0 1 0 2 0a1 1 0 0 0 -2 0 M8 11v-4a4 4 0 1 1 8 0v4")))}return jl=n,n},ps=28,Rx="M706.144 847.264A384.32 384.32 0 0 0 896 515.84c0-118.016-53.504-227.136-143.776-299.616a32 32 0 0 1 40.064-49.92A447.136 447.136 0 0 1 960 515.84c0 166.528-91.424 313.6-228.672 390.784l34.624 81.6-270.464-29.28 168.768-210.368 41.888 98.688zM320.736 182.72A384.288 384.288 0 0 0 128 515.84a383.36 383.36 0 0 0 157.76 310.304 32 32 0 0 1-37.728 51.712A447.36 447.36 0 0 1 64 515.84 448.32 448.32 0 0 1 294.56 123.968L261.664 50.112l268.928 20.032-163.04 217.76-46.816-105.184z",Vl=null,Px=()=>{if(Vl)return Vl;let n=document.createElement("canvas");n.width=ps*2,n.height=ps*2;let e=n.getContext("2d");if(e){e.scale(2,2);let t=ps/2;e.fillStyle="#ffffff",e.beginPath(),e.arc(t,t,10,0,Math.PI*2),e.shadowColor="#333",e.shadowBlur=2,e.fill(),e.shadowColor="",e.shadowBlur=0,typeof Path2D<"u"&&(e.translate(t-8-1.392,t-8-.89),e.scale(.0178,.0178),e.fillStyle="black",e.fill(new Path2D(Rx)))}return Vl=n,n};var kx=24,bs=20,kd=16,Ax="M607.573333 295.908693h-184.32l92.16-92.16zM515.413333 813.42464l-92.16-92.16h184.32l-92.16 92.16M210.57536 508.586667l92.16-92.16v184.32l-92.16-92.16M820.251307 508.586667l-92.16 92.16v-184.32l92.16 92.16M446.88384 507.405653c0 37.195093 30.153387 67.345067 67.345067 67.345067 37.198507 0 67.351893-30.149973 67.351893-67.345067s-30.153387-67.345067-67.34848-67.345066c-37.195093 0-67.345067 30.149973-67.345067 67.345066z",ql=null,Nx=()=>{if(ql)return ql;let n=document.createElement("canvas");n.width=bs*2,n.height=bs*2;let e=n.getContext("2d");if(e){e.scale(2,2);let t=bs/2;e.beginPath(),e.arc(t,t,8,0,Math.PI*2),e.strokeStyle="#2c2c2c",e.lineWidth=2,e.stroke(),e.fillStyle="#ffffff",e.fill(),typeof Path2D<"u"&&(e.translate(t-8,t-8),e.scale(16/1024,16/1024),e.fillStyle="#2c2c2c",e.fill(new Path2D(Ax)))}return ql=n,n},Jl=n=>{if(n.selection.length!==1)return null;let e=n.selection[0];if(e instanceof te||e instanceof le)return null;let t=e.typeKey;return ft.has(t)||ot.has(t)||at(e)?null:e},ec=(n,e,t)=>vs(n,e,t,{x:.5,y:0,offsetX:kx,offsetY:0}),Mn=3,Kl=new Map,Lx=n=>{let e=Kl.get(n);if(e)return e;let t=document.createElement("canvas"),r=t.getContext("2d"),o=`bold ${14*Mn}px Helvetica, Arial, sans-serif`;if(!r)return t.width=Math.max(1,Math.round((n.length*14*.6+16)*Mn)),t.height=Math.round(30*Mn),Kl.set(n,t),t;r.font=o;let i=r.measureText(n).width,s=8*Mn;t.width=Math.max(1,Math.ceil(i)+s*2),t.height=Math.ceil(30*Mn),r.font=o;let a=6*Mn;return r.beginPath(),r.moveTo(a,0),r.lineTo(t.width-a,0),r.arcTo(t.width,0,t.width,a,a),r.lineTo(t.width,t.height-a),r.arcTo(t.width,t.height,t.width-a,t.height,a),r.lineTo(a,t.height),r.arcTo(0,t.height,0,t.height-a,a),r.lineTo(0,a),r.arcTo(0,0,a,0,a),r.closePath(),r.fillStyle="rgba(44, 44, 44, 0.9)",r.fill(),r.fillStyle="#ffffff",r.textAlign="center",r.textBaseline="middle",r.fillText(n,t.width/2,t.height/2),Kl.set(n,t),t},Ix=(n,e,t)=>{let r=Lx(`${Math.round(e)}°`);return{matrix:[1,0,0,1,n.x,n.y],dims:{x:r.width/Mn/t,y:r.height/Mn/t},color:[1,1,1,1],texture:r}},st=ee("#2f6fed"),Lo=ee("#ffffff"),us=ee("#2f6fed"),tc=st,hs=(n,e)=>({x:(n.x+e.x)/2,y:(n.y+e.y)/2}),Re=(n,e,t,r)=>{let o=(n.x+e.x)/2,i=(n.y+e.y)/2,s=Math.hypot(e.x-n.x,e.y-n.y),a=Math.atan2(e.y-n.y,e.x-n.x),l=Math.cos(a),u=Math.sin(a);return{matrix:[l,u,-u,l,o,i],dims:{x:s,y:t},color:r}},Rn=(n,e,t,r)=>{let o=r*Math.PI/180,i=Math.cos(o),s=Math.sin(o);return{matrix:[i,s,-s,i,n.x,n.y],dims:{x:e,y:e},color:t}},_x=n=>{let e=n.angle*Math.PI/180,t=Math.cos(e),r=Math.sin(e),o=n.width/2,i=n.height/2,s=(a,l)=>({x:n.center.x+t*a-r*l,y:n.center.y+r*a+t*l});return{tl:s(-o,-i),tr:s(o,-i),br:s(o,i),bl:s(-o,i)}},et=n=>{let e=n.selection;if(e.length===0)return null;if(e.length===1){let a=e[0];return{quad:a.aCoords,angle:a.raw.angle??0}}let t=n.selectionFrame;if(t)return{quad:_x(t),angle:t.angle};let r=1/0,o=1/0,i=-1/0,s=-1/0;for(let a of e){let l=a.bounds;r=Math.min(r,l.left),o=Math.min(o,l.top),i=Math.max(i,l.right),s=Math.max(s,l.bottom)}return{quad:{tl:{x:r,y:o},tr:{x:i,y:o},br:{x:i,y:s},bl:{x:r,y:s}},angle:0}},Br=(n,e,t=1,r)=>{let o=hs(n.tl,n.tr),i=hs(n.tr,n.br),s=hs(n.bl,n.br),a=hs(n.tl,n.bl),l=qx(n,e,t),u=[{id:"tl",x:n.tl.x,y:n.tl.y},{id:"tr",x:n.tr.x,y:n.tr.y},{id:"br",x:n.br.x,y:n.br.y},{id:"bl",x:n.bl.x,y:n.bl.y},{id:"mt",x:o.x,y:o.y},{id:"mr",x:i.x,y:i.y},{id:"mb",x:s.x,y:s.y},{id:"ml",x:a.x,y:a.y},{id:"mtr",x:l.x,y:l.y}],c=r?Wx(r,t):[];return c.length?[...c,...u]:u},Dx=32,Fx=.25,xs=14,Ad=n=>n<=0?0:Math.min(Dx,n*Fx),Nd=(n,e)=>{if(e<=0)return 0;let t=Math.max(0,Math.min(e,n)),r=Ad(e);return r<=0||e<=r?t:r+t/e*(e-r)},nc=(n,e)=>{if(e<=0)return 0;let t=Math.max(0,Math.min(e,n)),r=Ad(e);return r<=0||e<=r?t:t<=r?0:(t-r)/(e-r)*e},ys=n=>!!n&&n.typeKey===L.FABRICRECT,Ox=new Set([L.QRCODE,L.BARCODE,L.ECHART,L.FABRIC_ECHART]),Io=n=>{if(!n)return!1;let e=se(n.raw);return!Ox.has(e)&&(e===L.IMAGE||e===L.SVGIMAGE||e===L.CROPIMAGE)},Ld=n=>{let e=Math.max(Math.abs(n.raw.scaleX??1)||1,1e-4),t=Math.max(Math.abs(n.raw.scaleY??1)||1,1e-4);return Math.min(n.dims.x*e,n.dims.y*t)/2},Bx=(n,e)=>{let t=n.aCoords,r=Math.hypot(t.tr.x-t.tl.x,t.tr.y-t.tl.y)*e,o=Math.hypot(t.bl.x-t.tl.x,t.bl.y-t.tl.y)*e;return r>Or&&o>Or},Wx=(n,e)=>Bx(n,e)?ys(n)?Hx(n,e):Io(n)?Gx(n,e):[]:[],Hx=(n,e)=>{let t=n.raw,r=Math.max(Math.abs(t.scaleX??1)||1,1e-4),o=Math.max(Math.abs(t.scaleY??1)||1,1e-4),i=n.dims.x/2,s=n.dims.y/2,a=i*r,l=s*o,u=Math.min(a,l),c=Math.max(0,Math.min(u,t.radius??0)),h=Nd(c,u),d=Math.max(0,(xs-h*e)/e),f=Math.max(0,(xs-h*e)/e),m=h+Math.min(d,Math.max(0,a-h)),p=h+Math.min(f,Math.max(0,l-h)),b=n.matrix;return as.map(g=>{let x=No[g],S=x==="tl"||x==="bl",w=x==="tl"||x==="tr",y=(S?-a+m:a-m)/r,v=(w?-l+p:l-p)/o;return{id:g,x:b[0]*y+b[2]*v+b[4],y:b[1]*y+b[3]*v+b[5]}})},Gx=(n,e)=>{let t=n.raw,r=n.dims.x/2,o=n.dims.y/2,i=Math.min(r,o),s=Math.max(0,Math.min(i,Math.max(t.rx??0,t.ry??0))),a=Nd(s,i),l=Math.max(Math.abs(t.scaleX??1)||1,1e-4),u=Math.max(Math.abs(t.scaleY??1)||1,1e-4),c=l*e,h=u*e,d=Math.min(Math.max(0,(xs-a*c)/c),Math.max(0,r-a)),f=Math.min(Math.max(0,(xs-a*h)/h),Math.max(0,o-a)),m=n.matrix;return as.map(p=>{let b=No[p],g=b==="tl"||b==="bl",x=b==="tl"||b==="tr",S=g?-r+a+d:r-a-d,w=x?-o+a+f:o-a-f;return{id:p,x:m[0]*S+m[2]*w+m[4],y:m[1]*S+m[3]*w+m[5]}})},gs=12,ds=null,Xx=()=>{if(ds)return ds;let n=document.createElement("canvas");n.width=gs*2,n.height=gs*2;let e=n.getContext("2d");if(e){e.scale(2,2);let t=gs/2,r=kn/2;e.beginPath(),e.arc(t,t,r+Rt,0,Math.PI*2),e.fillStyle=`rgb(${st[0]*255},${st[1]*255},${st[2]*255})`,e.fill(),e.beginPath(),e.arc(t,t,r,0,Math.PI*2),e.fillStyle=`rgb(${Lo[0]*255},${Lo[1]*255},${Lo[2]*255})`,e.fill()}return ds=n,ds},Id=16,Cn=4,Pd={tlr:{x:-.5,y:-.5,offsetX:-Cn,offsetY:-Cn},trr:{x:.5,y:-.5,offsetX:Cn,offsetY:-Cn},brr:{x:.5,y:.5,offsetX:Cn,offsetY:Cn},blr:{x:-.5,y:.5,offsetX:-Cn,offsetY:Cn}},rc={tlr:0,trr:90,brr:180,blr:270},Or=50,oc=(n,e)=>({width:Math.hypot(n.tr.x-n.tl.x,n.tr.y-n.tl.y)*e,height:Math.hypot(n.bl.x-n.tl.x,n.bl.y-n.tl.y)*e}),zx=(n,e)=>{let{width:t,height:r}=oc(n,e);return t>Or&&r>Or},Yx=new Set(["mr","br","mtr"]),Ux=new Set(["mr","br"]),$x=new Set(["mr","br","mtr"]),jx=new Set(["ml","mr","tl","tr","bl","br","tlS","trS","blS","brS"]),Vx=new Set(["mt","mb","tl","tr","bl","br","mtr","tlS","trS","blS","brS"]),_d=(n,e,t)=>{let r=e<=Or,o=t<=Or;return!r&&!o?!0:r&&o?Yx.has(n):!(r&&jx.has(n)&&!Ux.has(n)||o&&Vx.has(n)&&!$x.has(n))},Dd=n=>n instanceof le||n instanceof te||ot.has(n.typeKey),Fd=(n,e)=>e&&hh(e.raw)?n.filter(t=>!En(t.id)):n,_o=(n,e,t,r,o)=>{let i=Br(e,t,r,o),s=n.selection.length===1?n.selection[0]:null;if(!s||Dd(s))return i;let a=ft.has(s.typeKey),l=oc(e,r);return Fd(i.filter(u=>a&&(u.id==="ml"||u.id==="mr")||_d(u.id,l.width,l.height)),s)},ic=(n,e)=>{let t=n.aCoords,r=n.worldAngle,o=Br(t,r,e);if(Dd(n))return o;let i=ft.has(n.typeKey),s=oc(t,e);return Fd(o.filter(a=>i&&(a.id==="ml"||a.id==="mr")||_d(a.id,s.width,s.height)),n)},Od=(n,e,t)=>zx(n,t)?Object.keys(Pd).map(r=>{let o=vs(n,e,t,Pd[r]);return{id:r,x:o.x,y:o.y}}):[],Ss=n=>{let e=n*Math.PI/180,t=Math.sin(e),r=Math.cos(e);if(Math.abs(t)>=Math.abs(r)){let i=Math.sign(t);return{x:i/2,y:0,offsetX:i*Rd,offsetY:0}}let o=Math.sign(r);return{x:0,y:o/2,offsetX:0,offsetY:o*Rd}},vs=(n,e,t,r)=>{let o=(n.tl.x+n.br.x)/2,i=(n.tl.y+n.br.y)/2,s=Math.hypot(n.tr.x-n.tl.x,n.tr.y-n.tl.y),a=Math.hypot(n.bl.x-n.tl.x,n.bl.y-n.tl.y),l=r.x*s+r.offsetX/t,u=r.y*a+r.offsetY/t,c=e*Math.PI/180,h=Math.cos(c),d=Math.sin(c);return{x:o+l*h-u*d,y:i+l*d+u*h}},qx=(n,e,t)=>vs(n,e,t,Ss(e)),Pn=(n,e)=>{let t=Rt/e;return[Re(n.tl,n.tr,t,st),Re(n.tr,n.br,t,st),Re(n.br,n.bl,t,st),Re(n.bl,n.tl,t,st)]},Kx=3,fs=(n,e,t,r,o)=>{let i=e.x-n.x,s=e.y-n.y,a=Math.hypot(i,s);if(a<=0)return[];let l=i/a,u=s/a,c=Kx/o,h=[];for(let d=0;d<a;d+=c*2){let f=Math.min(d+c,a);h.push(Re({x:n.x+l*d,y:n.y+u*d},{x:n.x+l*f,y:n.y+u*f},t,r))}return h},ws=(n,e)=>{let t=Rt/e;return[...fs(n.tl,n.tr,t,st,e),...fs(n.tr,n.br,t,st,e),...fs(n.br,n.bl,t,st,e),...fs(n.bl,n.tl,t,st,e)]},Qx=(n,e,t,r)=>{let o=Rt/r,i=kn/r;for(let s of e)s.id==="mtr"?n.push({...Rn(s,ps/r,[1,1,1,1],t),texture:Px()}):Fr(s.id)?n.push({...Rn(s,gs/r,[1,1,1,1],t),texture:Xx()}):(n.push(Rn(s,i,st,t)),n.push(Rn(s,i-2*o,Lo,t)))},Ql=(n,e,t,r,o,i)=>{if(i?.spec){let s=e.find(l=>l.id==="mtr"),a=vs(t,r,o,i.spec);s.x=a.x,s.y=a.y}Qx(n,e,r,o),i&&n.push(Ix(i.center,r,o))},Bd=(n,e,t=null,r=!1)=>{if(n.selection.length===1&&Ze(n.selection[0]))return[];let o=et(n);if(!o)return[];let{quad:i,angle:s}=o,a=[],l=n.activeGroupChild,u=l&&n.groupEditing&&n.selection[0]instanceof J&&!(n.selection[0]instanceof te)&&!(n.selection[0]instanceof le)?n.selection[0]:null,h=(u?Md(u):null)??i;if(l)a.push(...Pn(l.aCoords,e)),a.push(...ws(h,e));else{if(n.selection.length>=2)for(let d of n.selection)a.push(...Pn(d.aCoords,e));a.push(...Pn(i,e))}if(n.selection.length===1&&at(n.selection[0]))return a.push({...Rn(i.br,ms/e,[1,1,1,1],s),texture:Mx()}),a;if(Ql(a,_o(n,h,s,e,Do(n)),h,s,e,t?.onChild?null:t),l&&n.groupEditing&&Ql(a,ic(l,e),l.aCoords,l.worldAngle,e,t?.onChild?t:null),r&&Jl(n)){let d=ec(h,s,e);a.push({...Rn(d,bs/e,[1,1,1,1],0),texture:Nx()})}return a},Do=n=>{if(n.selection.length!==1)return null;let e=n.selection[0];return ys(e)||Io(e)?e:null},Wd=(n,e)=>{let t=Rt/e,r={x:n.left,y:n.top},o={x:n.right,y:n.top},i={x:n.right,y:n.bottom},s={x:n.left,y:n.bottom};return[Re(r,o,t,us),Re(o,i,t,us),Re(i,s,t,us),Re(s,r,t,us)]},Fo=n=>{let e=n.editingMask;if(!e)return[];let t=e.aCoords;return Br(t,e.worldAngle).filter(o=>En(o.id)?!n.maskEdgeOnOuterBorder(e,ls[o.id]):!1)},Hd=(n,e,t=null)=>{let r=n.editingMask;if(!r)return[];let o=r.worldAngle,i=Pn(r.aCoords,e),s=Rt/e,a=kn/e;for(let u of Fo(n))i.push(Rn(u,a,st,o)),i.push(Rn(u,a-2*s,Lo,o));let l=n.raw.angle??0;return i.push(...ws(n.aCoords,e)),Ql(i,Br(n.aCoords,l),n.aCoords,l,e,t),i},Zx=2.5,Zl=(n,e,t)=>{let r=e.aCoords,o=t==="mr"?{p1:r.tr,p2:r.br}:{p1:r.bl,p2:r.br},i=n.layoutParams,s=t==="mr"?i.hGap:i.vGap;if(s>0){let a=(o.p1.x+o.p2.x)/2,l=(o.p1.y+o.p2.y)/2,u=(r.tl.x+r.br.x)/2,c=(r.tl.y+r.br.y)/2,h=a-u,d=l-c,f=Math.hypot(h,d)||1,m=s/2*(t==="mr"?n.worldScale.x:n.worldScale.y);return{mask:e,handle:t,p1:{x:o.p1.x+h/f*m,y:o.p1.y+d/f*m},p2:{x:o.p2.x+h/f*m,y:o.p2.y+d/f*m}}}return{mask:e,handle:t,p1:o.p1,p2:o.p2}},sc=n=>{let e=[];for(let i of n.maskChildren)i.visible&&(n.maskEdgeOnOuterBorder(i,"right")||e.push(Zl(n,i,"mr")),n.maskEdgeOnOuterBorder(i,"bottom")||e.push(Zl(n,i,"mb")));let t=n.layoutParams,r=Math.max(t.hGap,t.vGap)+1,o=[];for(let i of e){let s=o.find(a=>{let l=a.p2.x-a.p1.x,u=a.p2.y-a.p1.y,c=Math.hypot(l,u)||1,h=l/c,d=u/c;if(Math.abs((i.p2.x-i.p1.x)*d-(i.p2.y-i.p1.y)*h)/Math.max(1e-9,Math.hypot(i.p2.x-i.p1.x,i.p2.y-i.p1.y))>1e-6||Math.abs((i.p1.x-a.p1.x)*d-(i.p1.y-a.p1.y)*h)>.5)return!1;let m=(i.p1.x-a.p1.x)*h+(i.p1.y-a.p1.y)*d,p=(i.p2.x-a.p1.x)*h+(i.p2.y-a.p1.y)*d,b=Math.min(m,p),g=Math.max(m,p);return b<=c+r&&g>=-r});if(s){let a=s.p2.x-s.p1.x,l=s.p2.y-s.p1.y,u=Math.hypot(a,l)||1,c=a/u,h=l/u,d=[0,u,(i.p1.x-s.p1.x)*c+(i.p1.y-s.p1.y)*h,(i.p2.x-s.p1.x)*c+(i.p2.y-s.p1.y)*h],f=Math.min(...d),m=Math.max(...d);s.p1={x:s.p1.x+c*f,y:s.p1.y+h*f},s.p2={x:s.p1.x+c*(m-f),y:s.p1.y+h*(m-f)}}else o.push({...i})}return o},Gd=(n,e,t)=>sc(n).find(o=>o.mask===e&&o.handle===t)??Zl(n,e,t),Xd=(n,e)=>[Re(n.p1,n.p2,Zx/e,tc)],Jx=ee("#3c7eff"),ey=2,ty=(n,e,t)=>{let r=e.x-n.x,o=e.y-n.y,i=Math.hypot(r,o)||1,s=-o/i,a=r/i,l={x:(n.x+e.x)/2,y:(n.y+e.y)/2};return(l.x+s-t.x)*s+(l.y+a-t.y)*a>=0?{x:s,y:a}:{x:-s,y:-a}},zd=(n,e)=>{let t=n.aCoords,r=[t.tl,t.tr,t.br,t.bl],o={x:(t.tl.x+t.br.x)/2,y:(t.tl.y+t.br.y)/2},i=r.map((u,c)=>ty(u,r[(c+1)%4],o)),s=n.bounds,a=Math.min(ey,(s.right-s.left)*e,(s.bottom-s.top)*e)/e;if(a<=0)return[];let l=[];for(let u=0;u<4;u++){let c=r[u],h=r[(u+1)%4],d=i[u];l.push(Re({x:c.x-d.x*a/2,y:c.y-d.y*a/2},{x:h.x-d.x*a/2,y:h.y-d.y*a/2},a,Jx))}return l};function Yd(n,e,t,r){let o=n.selection.map(l=>l.id),i=et(n);if(!i||n.editingNode||e)return{ids:o,handles:[]};let s=n.selection.length===1&&n.selection[0]instanceof le?n.selection[0]:null,a=s?.editingMask?[...Fo(s).map(l=>{let u=r(l.x,l.y);return{id:l.id,x:u.x,y:u.y}}),...Br(i.quad,i.angle,t).map(l=>{let u=r(l.x,l.y);return{id:l.id,x:u.x,y:u.y}})]:_o(n,i.quad,i.angle,t,Do(n)).map(l=>{let u=r(l.x,l.y);return{id:l.id,x:u.x,y:u.y}});return{ids:o,handles:a}}function Ud(n){let e=n.activeGroupChild;if(!e)return null;let t=n.selection[0];return!(t instanceof J)||!t.containsDeep(e)?null:{rootId:t.id,childId:e.id}}function $d(n,e){let t=[],r=o=>{for(let i of o){if(i instanceof J&&r(i.children),!i.imageEl||!os(i.raw.src))continue;let s=i.imageEl.naturalWidth||i.imageEl.width,a=i.imageEl.naturalHeight||i.imageEl.height,l=e(i);t.push({id:i.id,type:i.raw.type,factor:l,rasterWidth:Math.round(s*(l??1)),rasterHeight:Math.round(a*(l??1))})}};return r(n.nodes),t}function jd(n){return n.nodes.map(e=>({id:e.id,type:e.raw.type,left:e.raw.left??0,top:e.raw.top??0,width:e.raw.width??0,height:e.raw.height??0,scaleX:e.raw.scaleX??1,scaleY:e.raw.scaleY??1,angle:e.raw.angle??0,visible:e.visible,bounds:e.bounds,aCoords:e.aCoords}))}function Vd(n,e){e();let t=performance.now();for(let o=0;o<n;o++)e();let r=(performance.now()-t)/n;return li("engine.render.avgMeasured",r),r}function qd(n){let e=n.width,t=n.height,r=document.createElement("canvas");r.width=e,r.height=t;let o=r.getContext("2d");o.drawImage(n,0,0);let i=o.getImageData(0,0,e,t);return{width:e,height:t,data:i.data}}var ny=2,Le={drag:"drag",scale:"scale",rotate:"rotate",cornerRadius:"cornerRadius",crop:"crop",tableCellEdit:"table-cell-edit",warpImage:"warpvas-image"},ry=(n,e)=>{let{bus:t,wrap:r,syncSelection:o,settleSnap:i}=e,s=n.events,a=(c,h)=>{let d=h.map(r);o(),t.fire(c,{selected:d,deselected:[],target:d[0]})},l=(c,h)=>{h.syntheticOwner||t.fire(c,{target:r(h)})},u=[s.on("selection:created",c=>a("selection:created",c)),s.on("selection:updated",c=>a("selection:updated",c)),s.on("selection:cleared",()=>{o(),t.fire("selection:cleared",{selected:[],deselected:[]})}),s.on("object:added",c=>l("object:added",c)),s.on("object:removed",c=>l("object:removed",c)),s.on("object:moving",c=>{i?.(),l("object:moving",c)}),s.on("object:scaling",c=>l("object:scaling",c)),s.on("object:rotating",c=>l("object:rotating",c)),s.on("object:cornerRadius",c=>l("object:cornerRadius",c)),s.on("object:modified",(c,h)=>{let d=c.map((g,x)=>g.syntheticOwner?-1:x).filter(g=>g>=0);if(!d.length)return;let f=d.map(g=>r(c[g])),m=h?.before,p=m?.length?d.map(g=>m[g]).filter(g=>!!g):void 0,b=p&&(p.length>1||d.length>1)?{original:{objects:p}}:p?{original:p[0]}:void 0;t.fire("object:modified",{target:f[0],targets:f,transform:b,action:h?.action,transactionId:h?.transactionId,protocolVersion:2})}),s.on("text:editing:entered",c=>l("text:editing:entered",c)),s.on("text:editing:exited",c=>l("text:editing:exited",c)),s.on("text:changed",c=>l("text:changed",c)),s.on("text:editing:committed",(c,h,d)=>{t.fire("text:editing:committed",{target:r(c),before:h,after:d})}),s.on("smartobject:open-requested",c=>l("smartobject:open-requested",c)),s.on("image:replace-requested",c=>l("image:replace-requested",c)),s.on("lock:unlock-requested",c=>l("lock:unlock-requested",c)),s.on("path:active-anchor-change",(c,h)=>{t.fire("path:active-anchor-change",{target:r(c),key:h})}),s.on("group:child-activated",c=>{o(),t.fire("group:child-activated",{target:r(c)})}),s.on("group:child-deactivated",()=>{o(),t.fire("group:child-deactivated")}),s.on("table:cellselection",c=>{t.fire("table:cellselection",{target:r(c)})})];return()=>u.forEach(c=>c())};function Kd(n,e){let t=n.nodes.filter(r=>r.visible&&!Ir.has(String(r.raw.id??""))&&!Ze(r));return n.setSelection(t),e(),t.length}function Qd(n,e){let t=[...n.selection];for(let r of t)n.remove(r);return t.length&&e(),t.length}function Zd(n,e,t,r){let o=[...n.selection];if(!o.length)return 0;let i=o.map(s=>s.toObject());for(let s of o)n.setProps(s,{left:(s.raw.left??0)+e,top:(s.raw.top??0)+t},{deferIndexRebuild:!0});return n.commitGeometry(),n.fireObjectModified(o,{action:Le.drag,before:i}),r(),o.length}var Cs=20,ef={ruleSize:Cs,backgroundColor:ee("#ffffff"),tickColor:ee("#A1A7AF"),textColor:"#444444",highlightColor:ee("#165dff3b"),fontSize:8,unitName:"px"},oy=.6,Ye=3,tf="'Arial Narrow', 'Segoe UI', sans-serif",Jd=[.02,.03,.05,.1,.2,.5,1,2,5],iy=[5e3,2500,1e3,500,200,100,50,20,10],sy=n=>{let e=0;for(;e<Jd.length&&Jd[e]<n;)e++;return iy[e-1]??1e4},ay=(n,e,t,r)=>{let o=sy(r),i=Math.floor(n/o)*o,s=n+e,a=[],l=[],u=c=>c>=n-1e-6&&c<=s+1e-6&&(!t||c>=t[0]-1e-6&&c<=t[1]+1e-6);for(let c=i;c<=s+o;c+=o){u(c)&&a.push(c);for(let h=1;h<10;h++){let d=c+o*h/10;if(d>s+o)break;u(d)&&l.push(d)}}return{majors:a,minors:l}},ly=(n,e)=>{if(!n.length)return[];let t=e?"left":"top",r=e?"width":"height",o=[...n].sort((a,l)=>a[t]-l[t]),i=[],s={start:o[0][t],length:o[0][r]};for(let a=1;a<o.length;a++){let l=o[a];s.start+s.length>=l[t]?s.length=Math.max(s.start+s.length,l[t]+l[r])-s.start:(i.push(s),s={start:l[t],length:l[r]})}return i.push(s),i},ac=new Map,cy=(n,e=ef)=>{let t=ac.get(n);if(t)return t;let r=document.createElement("canvas"),o=r.getContext("2d");if(!o)return r.width=Math.max(1,Math.round(n.length*e.fontSize*.6*Ye)),r.height=Math.max(1,Math.round(e.fontSize*1.4*Ye)),ac.set(n,r),r;let i=`${e.fontSize*Ye}px ${tf}`;o.font=i;let s=o.measureText(n);return r.width=Math.max(1,Math.ceil(s.width)+2),r.height=Math.ceil(e.fontSize*Ye*1.25),o.font=i,o.textBaseline="top",o.fillStyle=e.textColor,o.fillText(n,1,Math.round(e.fontSize*Ye*.15)),ac.set(n,r),r},lc=new Map,Ts=10,Es=4,uy=n=>{let e=lc.get(n);if(e)return e;let t=Ts*Ye,r=Es*Ye,o=document.createElement("canvas"),i=o.getContext("2d");if(!i)return o.width=Math.max(1,Math.round((n.length*Ts*.6+Es*2)*Ye)),o.height=Math.max(1,Math.round((Ts+Es*2)*Ye)),lc.set(n,o),o;let s=`${t}px ${tf}`;i.font=s;let a=i.measureText(n).width,l=3*Ye;return o.width=Math.max(1,Math.ceil(a)+r*2),o.height=Math.ceil((Ts+Es*2)*Ye),i.font=s,i.beginPath(),i.moveTo(l,0),i.lineTo(o.width-l,0),i.quadraticCurveTo(o.width,0,o.width,l),i.lineTo(o.width,o.height-l),i.quadraticCurveTo(o.width,o.height,o.width-l,o.height),i.lineTo(l,o.height),i.quadraticCurveTo(0,o.height,0,o.height-l),i.lineTo(0,l),i.quadraticCurveTo(0,0,l,0),i.closePath(),i.fillStyle="rgba(22, 93, 255, 0.9)",i.fill(),i.strokeStyle="#fff",i.lineWidth=.5*Ye,i.stroke(),i.fillStyle="#fff",i.textBaseline="top",i.fillText(n,r,r),lc.set(n,o),o},nf=n=>{let e={...ef,...n.style},{vpt:t,cssWidth:r,cssHeight:o}=n,i=t[0],s=n.digitCanvas??(b=>cy(b,e)),a=[],l=b=>(b-t[4])/i,u=b=>(b-t[5])/i,c=1/i,h=(b,g,x,S,w)=>({matrix:[c,0,0,c,l(b+x/2),u(g+S/2)],dims:{x,y:S},color:w}),d=(b,g,x,S=!1)=>{let w=s(b),y=w.width/Ye,v=w.height/Ye;return{matrix:S?[0,c,-c,0,l(g+v/2),u(x-y/2)]:[c,0,0,c,l(g+y/2),u(x+v/2)],dims:{x:y,y:v},color:[1,1,1,1],texture:w}},f=e.ruleSize,m=b=>{let g=b?r:o;a.push(b?h(0,0,r,f,e.backgroundColor):h(0,0,f,o,e.backgroundColor));let x=n.workspaceRect,S=x?b?[x.left,x.left+x.width]:[x.top,x.top+x.height]:null,w=b?-t[4]/i:-t[5]/i,y=ay(w,g/i,S,i),v=[e.tickColor[0],e.tickColor[1],e.tickColor[2],e.tickColor[3]*oy],R=P=>(P-w)*i;for(let P of y.majors){let T=Math.round(R(P));a.push(b?h(T,0,1,f,v):h(0,T,f,1,v))}for(let P of y.minors){let T=Math.round(R(P));a.push(b?h(T,f-8,1,8,v):h(f-8,T,8,1,v))}for(let P of y.majors){let T=R(P),C=String(Math.round(P));b?a.push(d(C,T+6,2.5)):a.push(d(C,2.5,T-6,!0))}for(let P of ly(n.selectionRects,b)){let T=(P.start-w)*i,C=P.length*i;a.push(b?h(T,0,C,f,e.highlightColor):h(0,T,f,C,e.highlightColor))}};m(!0),m(!1),a.push(h(0,0,f,f,e.backgroundColor));let p=s(e.unitName);if(a.push(d(e.unitName,f/2-p.width/Ye/2,f/2-p.height/Ye/2)),n.referenceLine){let b=uy(String(Math.round(n.referenceLine.position))),g=b.width/Ye,x=b.height/Ye,S,w;if(n.referenceLine.axis==="horizontal"){let y=n.referenceLine.position*i+t[5];S=f+5,w=y+x/2,w<0&&(w=2),w+x>o&&(w=o-x-2)}else S=n.referenceLine.position*i+t[4]+g/2,w=f+5,S<0&&(S=2),S+g>r&&(S=r-g-2);a.push({matrix:[c,0,0,c,l(S+g/2),u(w+x/2)],dims:{x:g,y:x},color:[1,1,1,1],texture:b})}return a};var Ms=n=>n*180/Math.PI,Se=n=>n*Math.PI/180,Rs=n=>({x:(n.tl.x+n.br.x)/2,y:(n.tl.y+n.br.y)/2}),Ps=n=>({width:Math.hypot(n.tr.x-n.tl.x,n.tr.y-n.tl.y),height:Math.hypot(n.bl.x-n.tl.x,n.bl.y-n.tl.y)}),cc={mr:0,br:45,mb:90,bl:135,ml:180,tl:225,mt:270,tr:315},uc=["ew-resize","nwse-resize","ns-resize","nesw-resize"],ks=5,rf=4,Zt=(n,e,t)=>{let r=e/2,o=t/2;switch(n){case"tl":return{u:{x:-r,y:-o},a:{x:r,y:o},axis:"both"};case"tr":return{u:{x:r,y:-o},a:{x:-r,y:o},axis:"both"};case"br":return{u:{x:r,y:o},a:{x:-r,y:-o},axis:"both"};case"bl":return{u:{x:-r,y:o},a:{x:r,y:-o},axis:"both"};case"ml":return{u:{x:-r,y:0},a:{x:r,y:0},axis:"x"};case"mr":return{u:{x:r,y:0},a:{x:-r,y:0},axis:"x"};case"mt":return{u:{x:0,y:-o},a:{x:0,y:o},axis:"y"};case"mb":return{u:{x:0,y:o},a:{x:0,y:-o},axis:"y"};default:return{u:{x:r,y:o},a:{x:-r,y:-o},axis:"both"}}},hc=(n,e,t)=>Q([Math.cos(Se(n)),-Math.sin(Se(n)),Math.sin(Se(n)),Math.cos(Se(n)),0,0],e.x-t.x,e.y-t.y,!0),dc=(n,e)=>{let r=(s,a)=>{let l=s/a;return Math.sign(l||a)*Math.max(.01,Math.abs(l))},o=n.scaleX,i=n.scaleY;if(n.axis==="both"||n.axis==="x"){let s=n.handleLocal.x-n.anchorLocal.x;Math.abs(s)>1e-6&&(o=r(e.x,s))}if(n.axis==="both"||n.axis==="y"){let s=n.handleLocal.y-n.anchorLocal.y;Math.abs(s)>1e-6&&(i=r(e.y,s))}return{scaleX:o,scaleY:i}};var hy=n=>n instanceof ye&&(n.typeKey===L.TEXTBOX||n.typeKey===L.TEXTIMAGE&&!Kt(n));function fc(n,e){let t=n.dims.x,r=n.dims.y,o=n.raw,i={x:-e*t/2,y:0},s=n.matrix,a=n.children.map(h=>({node:h,centerX:h.center.x,centerY:h.center.y,scaleX:h.raw.scaleX??1,width:h.dims.x,fixedBox:hy(h)})),l=Q(s,i.x,i.y),u=n.parentMatrix,c=u?Q(ve(u),l.x,l.y):l;return{node:n,sign:e,width:t,height:r,angle:o.angle??0,scaleX:o.scaleX??1,scaleY:o.scaleY??1,anchorScene:l,anchorWrite:c,children:a}}function of(n,e,t){let r=t/Math.max(e.width,1e-6);n.setProps(e.node,{width:t},{deferIndexRebuild:!0});let o={x:-e.sign*t/2,y:0},i=e.angle*Math.PI/180,s=Math.cos(i),a=Math.sin(i),l=s*(e.scaleX*o.x)-a*(e.scaleY*o.y),u=a*(e.scaleX*o.x)+s*(e.scaleY*o.y),c={x:e.anchorWrite.x-l,y:e.anchorWrite.y-u},h=ge({...e.node.raw,width:t,height:e.height,scaleX:e.scaleX,scaleY:e.scaleY},c);n.setProps(e.node,{left:h.x,top:h.y},{deferIndexRebuild:!0});for(let d of e.children){let f=d.centerX*r;if(d.fixedBox){let m=Math.max(d.width*r,1);n.setProps(d.node,{width:m},{deferIndexRebuild:!0});let p=d.node.dims,b=ge({...d.node.raw,width:p.x,height:p.y},{x:f,y:d.centerY});n.setProps(d.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}else{let m=d.scaleX*r;n.setProps(d.node,{scaleX:m},{deferIndexRebuild:!0});let p=d.node.dims,b=ge({...d.node.raw,width:p.x,height:p.y,scaleX:m},{x:f,y:d.centerY});n.setProps(d.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}}}function sf(n,e,t){if(t.x*e.sign<=0)return;let o=(typeof e.node.raw.strokeWidth=="number"?e.node.raw.strokeWidth:0)/(e.node.raw.strokeUniform?e.scaleX:1),i=Math.max(e.sign*t.x/e.scaleX-o,1);of(n,e,i)}function dy(n,e,t){if(!(t>0))return;let r=fc(e,1);of(n,r,t)}function Wr(n){return n instanceof J&&!(n instanceof te)&&!(n instanceof le)}function pc(n,e,t){let r=n.raw,o=n.dims.x,i=n.dims.y,{u:s,a,axis:l}=Zt(e,o,i),u=Kt(n),c=(n.typeKey===L.TEXTBOX||n.typeKey===L.TEXTIMAGE&&!u)&&(e==="ml"||e==="mr");c&&(a.x=-s.x,a.y=-i/2);let h=n.matrix,d=Q(h,a.x,a.y),f=n.parentMatrix,m=f?Q(ve(f),d.x,d.y):d,p={node:n,left:r.left??0,top:r.top??0,angle:r.angle??0,scaleX:r.scaleX??1,scaleY:r.scaleY??1,width:o,height:i,anchorLocal:a,handleLocal:s,anchorScene:d,anchorWrite:m,axis:l,bakeWidth:c||void 0,bakeHeight:n.isTextType&&!u&&(e==="mt"||e==="mb")&&n instanceof ye||void 0};if(Wr(n)&&(e==="ml"||e==="mr")&&(p.bakeGroup=fc(n,e==="mr"?1:-1)),n.isMaskType&&(!t||t.nodes.includes(n))&&(e==="ml"||e==="mr"?p.bakeMaskWidth=!0:(e==="mt"||e==="mb")&&(p.bakeMaskHeight=!0)),n.isTextType&&!u&&Tn.has(e)&&n instanceof ye){let b=Xe(r)==="circle"?typeof r.circleSize=="number"?r.circleSize:40:void 0;p.bakeFont={fontSize0:n.textStyle.fontSize,styles0:r.styles??null,singleLine0:n.textLayout.lines.length===1,...b!==void 0?{circleSize0:b}:{}}}return p}function uf(n,e,t,r=!1){let o=hc(e.angle,t,e.anchorScene);if(e.bakeFont){my(n,e,o);return}if(e.bakeWidth){py(n,e,o);return}if(e.bakeHeight){by(n,e,o);return}if(e.bakeGroup){sf(n,e.bakeGroup,o);return}if(e.bakeMaskWidth){af(n,e,o,"width");return}if(e.bakeMaskHeight){af(n,e,o,"height");return}let i,s;if(e.axis==="both"&&!r){let f=(Math.abs(o.x)+Math.abs(o.y))/Math.max(Math.abs(e.width*e.scaleX)+Math.abs(e.height*e.scaleY),1e-6),m=Math.max(f,.01);i=e.scaleX*m,s=e.scaleY*m}else({scaleX:i,scaleY:s}=dc(e,o));let a=Math.cos(Se(e.angle)),l=Math.sin(Se(e.angle)),u=a*(i*e.anchorLocal.x)-l*(s*e.anchorLocal.y),c=l*(i*e.anchorLocal.x)+a*(s*e.anchorLocal.y),h={x:e.anchorWrite.x-u,y:e.anchorWrite.y-c},d=ge({...e.node.raw,width:e.width,height:e.height,scaleX:i,scaleY:s},h);n.setProps(e.node,{scaleX:i,scaleY:s,left:d.x,top:d.y},{deferIndexRebuild:!0})}function hf(n,e,t){let{quad:r,angle:o}=t,i=Rs(r),{width:s,height:a}=Ps(r),{u:l,a:u,axis:c}=Zt(e,s,a),h=Math.cos(Se(o)),d=Math.sin(Se(o));return{members:n.map(f=>({node:f,center:{...f.center},scaleX:f.raw.scaleX??1,scaleY:f.raw.scaleY??1,dims:{...f.dims}})),center:i,angle:o,width:s,height:a,anchorLocal:u,handleLocal:l,anchorScene:{x:i.x+h*u.x-d*u.y,y:i.y+d*u.x+h*u.y},axis:c,handle:e}}function df(n,e,t,r=!1){let o=hc(e.angle,t,e.anchorScene),i,s;if(e.axis==="both"&&!r){let h=(Math.abs(o.x)+Math.abs(o.y))/Math.max(Math.abs(e.width)+Math.abs(e.height),1e-6);i=s=Math.max(h,.01)}else({scaleX:i,scaleY:s}=dc({...e,scaleX:1,scaleY:1},o));let a=Math.cos(Se(e.angle)),l=Math.sin(Se(e.angle)),u={x:e.anchorScene.x-(a*(i*e.anchorLocal.x)-l*(s*e.anchorLocal.y)),y:e.anchorScene.y-(l*(i*e.anchorLocal.x)+a*(s*e.anchorLocal.y))},c=e.members;n.applyTransform(c.map(h=>h.node),h=>{let d=c.find(g=>g.node===h),f=fy(e,u,i,s,d,a,l),m=d.scaleX*i,p=d.scaleY*s,b=ge({...h.raw,width:d.dims.x,height:d.dims.y,scaleX:m,scaleY:p},f);return{scaleX:m,scaleY:p,left:b.x,top:b.y}},"scaling"),n.setSelectionFrame({center:u,width:e.width*i,height:e.height*s,angle:e.angle})}function fy(n,e,t,r,o,i,s){let a=i*(o.center.x-n.center.x)+s*(o.center.y-n.center.y),l=-s*(o.center.x-n.center.x)+i*(o.center.y-n.center.y);return{x:e.x+i*(t*a)-s*(r*l),y:e.y+s*(t*a)+i*(r*l)}}function ff(n,e,t){let r=Math.atan2(t.y-e.center.y,t.x-e.center.x),o=Ms(r-e.startAngle),i=Math.cos(Se(o)),s=Math.sin(Se(o)),a=e.snapshot.members;n.applyTransform(a.map(u=>u.node),u=>{let c=a.find(p=>p.node===u),h=((c.angle0+o)%360+360)%360,d=c.center0.x-e.center.x,f=c.center0.y-e.center.y,m={x:e.center.x+i*d-s*f,y:e.center.y+s*d+i*f};return u.rotateAroundCenter(h,m)},"rotating");let l=((e.frameAngle0+o)%360+360)%360;n.setSelectionFrame({center:{...e.center},width:e.frame.width,height:e.frame.height,angle:l})}var mc=n=>{if(n===null||typeof n!="object")return typeof n=="function"?void 0:n;if(Array.isArray(n))return n.map(mc);let e={};for(let t of Object.keys(n)){let r=mc(n[t]);r!==void 0&&(e[t]=r)}return e};function my(n,e,t){let r=e.bakeFont,o=e.handleLocal.x-e.anchorLocal.x,i=e.handleLocal.y-e.anchorLocal.y,s=Math.abs(o)+Math.abs(i),a=s>1e-6?(Math.abs(t.x)+Math.abs(t.y))/s:1,l=Math.max(r.fontSize0*a,1);a=l/r.fontSize0;let u={fontSize:l,scaleX:e.scaleX,scaleY:e.scaleY},c=r.styles0;if(c){let w=mc(c);for(let y of Object.values(w))if(y)for(let[v,R]of Object.entries(y)){let P=R;P&&typeof P.fontSize=="number"&&(y[v]={...P,fontSize:P.fontSize*a})}u.styles=w}let h=r.circleSize0,d=h!==void 0;if(d&&(u.circleSize=Math.max(h*a,1)),e.node.typeKey===L.TEXTBOX&&!d){let w=Math.max(e.width*a,1);if(r.singleLine0&&e.node instanceof ye&&Ge(e.node.raw)===null&&e.node.raw.vertical!==!0){let y=jt(e.node.raw.text??"",{...e.node.textStyle,fontSize:l},{boxWidth:null,styles:u.styles??e.node.raw.styles,splitByGrapheme:e.node.raw.splitByGrapheme===!0}).width;w=Math.max(w,y)}u.width=w}d||(u.height=Math.max(e.height*a,1));let f=Math.cos(Se(e.angle)),m=Math.sin(Se(e.angle)),p=f*(e.scaleX*e.anchorLocal.x*a)-m*(e.scaleY*e.anchorLocal.y*a),b=m*(e.scaleX*e.anchorLocal.x*a)+f*(e.scaleY*e.anchorLocal.y*a),g={x:e.anchorWrite.x-p,y:e.anchorWrite.y-b},x=typeof u.width=="number"?u.width:e.width*a,S=ge({...e.node.raw,width:x,height:e.height*a,scaleX:e.scaleX,scaleY:e.scaleY},g);u.left=S.x,u.top=S.y,n.setProps(e.node,u,{deferIndexRebuild:!0})}function py(n,e,t){let o=Math.sign(e.handleLocal.x);if(t.x*o<=0)return;let s=(typeof e.node.raw.strokeWidth=="number"?e.node.raw.strokeWidth:0)/(e.node.raw.strokeUniform?e.scaleX:1),a=Math.max(o*t.x/e.scaleX-s,1);n.setProps(e.node,{width:a},{deferIndexRebuild:!0});let l=e.node.dims.x,u=e.node.dims.y,c={x:-o*l/2,y:-u/2},h=Math.cos(Se(e.angle)),d=Math.sin(Se(e.angle)),f=h*(e.scaleX*c.x)-d*(e.scaleY*c.y),m=d*(e.scaleX*c.x)+h*(e.scaleY*c.y),p={x:e.anchorWrite.x-f,y:e.anchorWrite.y-m},b=ge({...e.node.raw,width:l,height:u,scaleX:e.scaleX,scaleY:e.scaleY},p);n.setProps(e.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}function by(n,e,t){let r=e.node;if(!(r instanceof ye))return;let o=Math.sign(e.handleLocal.y);if(t.y*o<=0)return;let s=(typeof r.raw.strokeWidth=="number"?r.raw.strokeWidth:0)/(r.raw.strokeUniform?e.scaleY:1),a=Math.max(Math.ceil(Math.abs(t.y)/e.scaleY-s),r.textLayout.height,0);n.setProps(r,{height:a},{deferIndexRebuild:!0});let l={x:0,y:-o*a/2},u=Math.cos(Se(e.angle)),c=Math.sin(Se(e.angle)),h=u*(e.scaleX*l.x)-c*(e.scaleY*l.y),d=c*(e.scaleX*l.x)+u*(e.scaleY*l.y),f={x:e.anchorWrite.x-h,y:e.anchorWrite.y-d},m=ge({...r.raw,width:e.width,height:a,scaleX:e.scaleX,scaleY:e.scaleY},f);n.setProps(r,{left:m.x,top:m.y},{deferIndexRebuild:!0})}function af(n,e,t,r){let i=e.node,s=i.raw,a=typeof s.strokeWidth=="number"?s.strokeWidth:0;if(r==="width"){let l=Math.sign(e.handleLocal.x);if(t.x*l<=0)return;let u=a/(s.strokeUniform?e.scaleX:1),c=Math.max(l*t.x/e.scaleX-u,1),h=Number(s.width)||e.width,d=Number(s.height)||e.height,f=cf(i,h,d,c,d);n.setProps(e.node,{width:c,...f??{}},{deferIndexRebuild:!0});let m={x:-l*c/2,y:0},p=lf(e,m),b=ge({...s,width:c,height:d,scaleX:e.scaleX,scaleY:e.scaleY},p);n.setProps(e.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}else{let l=Math.sign(e.handleLocal.y);if(t.y*l<=0)return;let u=a/(s.strokeUniform?e.scaleY:1),c=Math.max(l*t.y/e.scaleY-u,1),h=Number(s.width)||e.width,d=Number(s.height)||e.height,f=cf(i,h,d,h,c);n.setProps(e.node,{height:c,...f??{}},{deferIndexRebuild:!0});let m={x:0,y:-l*c/2},p=lf(e,m),b=ge({...s,width:h,height:c,scaleX:e.scaleX,scaleY:e.scaleY},p);n.setProps(e.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}}function lf(n,e){let t=Math.cos(Se(n.angle)),r=Math.sin(Se(n.angle)),o=t*(n.scaleX*e.x)-r*(n.scaleY*e.y),i=r*(n.scaleX*e.x)+t*(n.scaleY*e.y);return{x:n.anchorWrite.x-o,y:n.anchorWrite.y-i}}function cf(n,e,t,r,o){let s=n.raw.clipImage;if(!s||typeof s.src!="string")return null;let a=n.clipImageEl,l=a?.naturalWidth||Number(s.width)||0,u=a?.naturalHeight||Number(s.height)||0;if(!l||!u||!e||!t||!r||!o)return null;let c=(m,p)=>Math.max(m/l,p/u),h=Number(s.scaleX)||1,d=c(e,t)?h/c(e,t):1,f=c(r,o)*(d||1);return{clipImage:{...s,scaleX:f,scaleY:f}}}var mf=(n,e)=>e.length>=2&&(e.includes(n-1)||e.includes(n));function bf(n,e,t){let r=n.raw,o={type:"table-border-drag",node:n,border:e,startMatrix:[...n.matrix],startLocal:n.localPoint(t.x,t.y),startBorderPos:e.position,startWidths:Array.isArray(r.columnWidths)?[...r.columnWidths]:[...n.layout.columnWidths],startHeights:[...n.layout.rowHeights],selectedCols:[...new Set(n.selectedCells.map(i=>i.col))],selectedRows:[...new Set(n.selectedCells.map(i=>i.row))],savedCells:n.selectedCells,savedAnchor:n.cellAnchor,savedRange:n.cellRange};return n.setCellSelection([],null,null),n.borderDragging=!0,o}function gf(n,e){let t=n.node.raw,r=Q(ve(n.startMatrix),e.x,e.y),o={x:r.x-n.startLocal.x,y:r.y-n.startLocal.y};if(n.border.type==="col"){let u=t.minCellWidth??40,c=(Array.isArray(t.columnWidths)?[...t.columnWidths]:[...n.startWidths]).slice(0,n.node.tableView.cols);for(;c.length<n.node.tableView.cols;)c.push(u);if(mf(n.border.index,n.selectedCols))for(let h of n.selectedCols)c[h]=Math.max(u,n.startWidths[h]+o.x);else c[n.border.index-1]=Math.max(u,n.startWidths[n.border.index-1]+o.x);go(t,c)}else{let u=n.node.tableView.rows,c=Array.isArray(t.manualRowHeights)?t.manualRowHeights:[],h=[];for(let d=0;d<u;d++)h.push(typeof c[d]=="number"?c[d]:null);if(mf(n.border.index,n.selectedRows))for(let d of n.selectedRows)h[d]=Math.max(n.node.getRowMinHeight(d),n.startHeights[d]+o.y);else{let d=n.border.index-1;h[d]=Math.max(n.node.getRowMinHeight(d),n.startHeights[d]+o.y)}t.manualRowHeights=h}n.node.rebuildTable();let i=Rr(n.node.tableView,n.border.type,n.border.index),s=n.border.type==="col"?o.x:o.y,a=n.border.type==="col"?n.node.objectScale.x:n.node.objectScale.y,l=sd(n.startBorderPos,i,s,a);n.node.hoveredBorder={type:n.border.type,index:n.border.index,position:i+l}}function xf(n,e){let t=Zt(e,n.dims.x,n.dims.y).a;return{type:"table-edge-resize",node:n,handle:e,anchorScene:Q(n.matrix,t.x,t.y)}}function yf(n,e){let t=Zt(e,n.dims.x,n.dims.y).a;return{type:"puzzle-edge-resize",node:n,handle:e,anchorScene:Q(n.matrix,t.x,t.y)}}function As(n,e,t,r){for(let o of Fo(e)){let i=n(o.x,o.y);if(En(o.id)&&Math.hypot(i.x-t,i.y-r)<=ir)return o.id}return null}function xy(n,e,t,r){let o=r.x-t.x,i=r.y-t.y,s=o*o+i*i,a=s>0?Math.max(0,Math.min(1,((n-t.x)*o+(e-t.y)*i)/s)):0;return Math.hypot(n-(t.x+a*o),e-(t.y+a*i))}function Oo(n,e,t,r){for(let o of sc(e)){let i=n(o.p1.x,o.p1.y),s=n(o.p2.x,o.p2.y);if(xy(t,r,i,s)<=ir)return{mask:o.mask,handle:o.handle}}return null}function bc(n,e,t){let r=n.maskChildren.indexOf(e);if(r<0)return null;let o=jh(n.raw,n.maskChildren.map(s=>s.raw),n.maskChildren.map(s=>s.clipImageEl)),i=Zt(t,e.dims.x,e.dims.y).a;return{type:"puzzle-mask-edge-resize",node:n,maskIdx:r,handle:t,anchorScene:Q(e.matrix,i.x,i.y),state:o.state,pieces:o.pieces,clipSizes:o.clipSizes}}function yy(n,e){n.maskChildren.forEach((t,r)=>{let o=e.masks[r];if(!o)return;let i=t.clipImageRaw,s=o.clip&&i?{...i,scaleX:o.clip.scaleX,scaleY:o.clip.scaleY,clipX:o.clip.clipX,clipY:o.clip.clipY}:null;t.set({left:o.left,top:o.top,width:o.width,height:o.height,...s?{clipImage:s}:{}})})}function Sf(n,e){let t=n.node.maskChildren[n.maskIdx];if(!t)return;let r=t.raw,o=t.worldAngle,i=t.worldScale,s=e.x-n.anchorScene.x,a=e.y-n.anchorScene.y;if(o){let u=Math.cos(Se(-o)),c=Math.sin(Se(-o)),h=s;s=u*h-c*a,a=c*h+u*a}let l=ls[n.handle];if(l==="left"||l==="right"){let u=(r.strokeWidth??0)/(r.strokeUniform===!0?i.x:1);Uh(n.state,n.maskIdx,Math.abs(s)/i.x-u,l,n.clipSizes)}else{let u=(r.strokeWidth??0)/(r.strokeUniform===!0?i.y:1);$h(n.state,n.maskIdx,Math.abs(a)/i.y-u,l,n.clipSizes)}yy(n.node,n.state)}function pf(n,e){let t=n.layoutParams,r=n.maskChildren,o={...t,masks:r.map(s=>({left:s.raw.left??0,top:s.raw.top??0,width:s.raw.width??0,height:s.raw.height??0,clip:Xi(s.raw)}))},i=r.map(s=>s.clipImageEl?{w:s.clipImageEl.naturalWidth,h:s.clipImageEl.naturalHeight}:null);Yh(o,e,i)&&(n.set({layoutWidth:o.width,layoutHeight:o.height,hGap:o.hGap,vGap:o.vGap,groupPadding:o.groupPadding,width:o.width,height:o.height}),r.forEach((s,a)=>{let l=o.masks[a],u=s.clipImageRaw,c=l.clip&&u?{...u,scaleX:l.clip.scaleX,scaleY:l.clip.scaleY,clipX:l.clip.clipX,clipY:l.clip.clipY}:null;s.set({left:l.left,top:l.top,width:l.width,height:l.height,...c?{clipImage:c}:{}})}))}function vf(n,e,t){let r=e.node.raw,o={x:Math.abs(r.scaleX??1),y:Math.abs(r.scaleY??1)},i=r.angle??0,s=t.x-e.anchorScene.x,a=t.y-e.anchorScene.y;if(i){let m=Math.cos(Se(-i)),p=Math.sin(Se(-i)),b=s;s=m*b-p*a,a=p*b+m*a}let l=e.node.layoutParams;if(or[e.handle]==="x"){let m=(r.strokeWidth??0)/(r.strokeUniform===!0?o.x:1),p=Math.max(Math.abs(s)/o.x-m,1);pf(e.node,{widthRatio:p/(l.width||1)})}else{let m=(r.strokeWidth??0)/(r.strokeUniform===!0?o.y:1),p=Math.max(Math.abs(a)/o.y-m,1);pf(e.node,{heightRatio:p/(l.height||1)})}let u=Zt(e.handle,e.node.dims.x,e.node.dims.y).a,c=Math.cos(Se(i)),h=Math.sin(Se(i)),d={x:e.anchorScene.x-(c*(o.x*u.x)-h*(o.y*u.y)),y:e.anchorScene.y-(h*(o.x*u.x)+c*(o.y*u.y))},f=ge({...r,width:e.node.dims.x,height:e.node.dims.y},d);n.setProps(e.node,{left:f.x,top:f.y},{deferIndexRebuild:!0})}function wf(n,e,t){let r=e.node.raw,o=e.node.tableView,i=e.node.objectScale,s=e.node.tableAngle,a=t.x-e.anchorScene.x,l=t.y-e.anchorScene.y;if(s){let p=Math.cos(Se(-s)),b=Math.sin(Se(-s)),g=a;a=p*g-b*l,l=b*g+p*l}let u=r.cellStrokeWidth??1;if(or[e.handle]==="x"){let p=Math.abs(a)/i.x-o.cellSpacing*(o.cols-1)-u,b=e.handle==="ml"?0:o.cols-1,g=o.columnWidths.reduce((x,S,w)=>w===b?x:x+S,0);xo(r,b,p-g)}else{let p=Math.abs(l)/i.y-o.cellSpacing*(o.rows-1)-u,b=e.handle==="mt"?0:o.rows-1,g=o.rowHeights.reduce((x,S,w)=>w===b?x:x+S,0);yo(r,b,p-g)}e.node.rebuildTable();let c=Zt(e.handle,e.node.dims.x,e.node.dims.y).a,h=Math.cos(Se(s)),d=Math.sin(Se(s)),f={x:e.anchorScene.x-(h*(i.x*c.x)-d*(i.y*c.y)),y:e.anchorScene.y-(d*(i.x*c.x)+h*(i.y*c.y))},m=ge({...r,width:e.node.dims.x,height:e.node.dims.y},f);n.setProps(e.node,{left:m.x,top:m.y},{deferIndexRebuild:!0})}function Tf(n,e,t){let r=Math.max(0,t.index);if(t.type==="col"){To(e.raw,r),e.rebuildTable();let o=e.tableView,i=$i(e.cellMap,o.rows,Math.min(r,o.cols-1));e.setCellSelection(i,i[0]??null,ze(i))}else{wo(e.raw,r),e.rebuildTable();let o=e.tableView,i=ji(e.cellMap,o.cols,Math.min(r,o.rows-1));e.setCellSelection(i,i[0]??null,ze(i))}n.applyTransform([e],()=>({}),"modified")}var Sy=n=>n.kind==="col-strip"?{kind:"col",index:n.col}:{kind:"row",index:n.row},vy=(n,e,t)=>{let r=n.raw,{x:o,y:i}=n.dims;if(!o||!i)return null;let s=Math.max(Math.abs(r.scaleX??1)||1,1e-4),a=Math.max(Math.abs(r.scaleY??1)||1,1e-4),l=n.localPoint(t.x,t.y),u=o/2,c=i/2,h,d;e==="tl"?(h=(l.x+u)*s,d=(l.y+c)*a):e==="tr"?(h=(u-l.x)*s,d=(l.y+c)*a):e==="bl"?(h=(l.x+u)*s,d=(c-l.y)*a):(h=(u-l.x)*s,d=(c-l.y)*a);let f=Ld(n),m=Math.max(0,Math.min(f,nc(Math.min(h,d),f))),p=r.radius??0;return Math.abs(m-p)<.001?null:m},wy=(n,e,t)=>{let r=n.raw,{x:o,y:i}=n.dims;if(!o||!i)return null;let s=n.localPoint(t.x,t.y),a=o/2,l=i/2,u,c;e==="tl"?(u=s.x+a,c=s.y+l):e==="tr"?(u=a-s.x,c=s.y+l):e==="bl"?(u=s.x+a,c=l-s.y):(u=a-s.x,c=l-s.y);let h=Math.min(a,l),d=Math.max(0,Math.min(h,nc(Math.min(u,c),h))),f=Math.max(r.rx??0,r.ry??0);if(Math.abs(d-f)<.001)return null;let m={rx:d,ry:d};return d>0&&r.perPixelTargetFind===!1&&(m.perPixelTargetFind=!0),m},gc=(n,e)=>n<Cs?"vertical":e<Cs?"horizontal":null,Bo=n=>`url("data:image/svg+xml,<svg height='20' width='20' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'><g fill='none' transform='rotate(${n} 16 16)'><path fill='white' d='M18.24 5.37C11.41 6.04 5.98 11.46 5.32 18.26L0 18.26L7.8 26L15.61 18.27L10.6 18.27C11.21 14.35 14.31 11.25 18.24 10.64L18.24 15.55L26 7.78L18.24 0L18.24 5.37Z'></path><path fill='black' d='M19.5463 6.61441C12.4063 6.68441 6.61632 12.4444 6.56632 19.5644L3.17632 19.5644L7.80632 24.1444L12.4363 19.5644L9.18632 19.5644C9.24632 13.8844 13.8563 9.28441 19.5463 9.22441L19.5463 12.3844L24.1463 7.78441L19.5463 3.16441L19.5463 6.61441Z'></path></g></svg>") 12 12,auto`,We=n=>{let e=new Map;for(let t of n)e.set(t,t.toObject());return e},Ns=class{host;el;gesture={type:"none"};performed=!1;hoveredTable=null;deferredClickSwitch=null;detach=null;interactive;constructor(e,t,r=!0){this.el=e,this.host=t,this.interactive=r,this.attach()}get active(){return this.gesture.type!=="none"}hitHandle(e,t){let r=et(this.host.document);if(!r||this.host.document.selection.length===1&&at(this.host.document.selection[0]))return null;for(let o of _o(this.host.document,r.quad,r.angle,this.host.zoom,Do(this.host.document))){let i=this.host.toScreen(o.x,o.y);if(Math.hypot(i.x-e,i.y-t)<=ir)return o.id}return null}hitActiveChildHandle(e,t){let r=this.host.document,o=r.activeGroupChild;if(!o||!r.groupEditing)return null;for(let i of ic(o,this.host.zoom)){let s=this.host.toScreen(i.x,i.y);if(Math.hypot(s.x-e,s.y-t)<=ir)return i.id}return null}hitLockControl(e,t){let r=this.host.document;if(r.selection.length!==1||!at(r.selection[0]))return null;let o=et(r);if(!o)return null;let i=this.host.toScreen(o.quad.br.x,o.quad.br.y);return Math.hypot(i.x-e,i.y-t)<=ir?r.selection[0]:null}hitMoveControl(e,t){if(this.host.mobileControls!==!0||!Jl(this.host.document))return!1;let r=et(this.host.document);if(!r)return!1;let o=ec(r.quad,r.angle,this.host.zoom),i=this.host.toScreen(o.x,o.y);return Math.hypot(i.x-e,i.y-t)<=kd}hitCornerRotateZone(e,t){let r=this.host.document;if(r.selection.length!==1)return null;let o=r.selection[0];if(o instanceof te||at(o))return null;let i=et(r);if(!i)return null;let s=i.angle*Math.PI/180,a=Math.cos(s),l=Math.sin(s),u=Id/2;for(let c of Od(i.quad,i.angle,this.host.zoom)){let h=this.host.toScreen(c.x,c.y),d=e-h.x,f=t-h.y,m=d*a+f*l,p=-d*l+f*a;if(Math.abs(m)<=u&&Math.abs(p)<=u)return c.id}return null}freezeRotateHandle(e,t,r=!1){this.host.rotateDrag!==void 0&&(this.host.rotateDrag=r?{spec:Ss(e),center:{x:t.x,y:t.y},onChild:!0}:{spec:Ss(e),center:{x:t.x,y:t.y}})}hoverCursor(e,t,r){let o=this.host.document;if(this.host.rulerVisible){let p=gc(e,t);if(p)return p==="horizontal"?"ns-resize":"ew-resize"}let i=this.host.cropSession;if(i)return i.hoverCursor(e,t,r);let s=this.host.expandSession;if(s)return s.hoverCursor(e,t,r.x,r.y);let a=this.host.pathSession;if(a)return a.hoverCursor(e,t,r);let l=this.host.warpSession;if(l)return l.hoverCursor(e,t);let u=o.selection.length===1&&o.selection[0]instanceof le?o.selection[0]:null;if(u?.editingMask){let p=As((g,x)=>this.host.toScreen(g,x),u,e,t);if(p)return or[p]==="x"?"ew-resize":"ns-resize";let b=Oo((g,x)=>this.host.toScreen(g,x),u,e,t);if(b)return or[b.handle]==="x"?"ew-resize":"ns-resize"}else if(u){let p=Oo((b,g)=>this.host.toScreen(b,g),u,e,t);if(p)return or[p.handle]==="x"?"ew-resize":"ns-resize"}let c=o.selection.length===1&&o.selection[0]instanceof te?o.selection[0]:null;if(c&&!o.findTarget(r.x,r.y)){let p=c.borderOrIndicatorHit(r.x,r.y,this.host.zoom);if(p?.inCircle)return this.updateTableHover(c,p,!1),"pointer";let b=c.stripHit(r.x,r.y,this.host.zoom);if(b)return this.updateTableHover(c,null,!1,{strip:Sy(b)}),"pointer";if(c.dragHandleHit(r.x,r.y,this.host.zoom))return this.updateTableHover(c,null,!1,{dragHandle:!0}),"move"}if(c&&o.findTarget(r.x,r.y)===c&&c.rangeHandleHit(r.x,r.y,this.host.zoom))return this.updateTableHover(c,null,!0,{rangeHandle:!0}),"crosshair";if(this.hitLockControl(e,t))return"pointer";let h=this.hitActiveChildHandle(e,t);if(h==="mtr"){let p=o.activeGroupChild;return Bo(p.worldAngle+225)}if(h){let p=o.activeGroupChild,b=cc[h];if(typeof b=="number"){let g=b+p.worldAngle;return uc[(Math.round(g/45)%4+4)%4]}}if(this.hitMoveControl(e,t))return"move";let d=this.hitHandle(e,t);if(d==="mtr")return Bo((et(o)?.angle??0)+225);if(d&&Fr(d))return d==="tlS"||d==="brS"?"nwse-resize":"nesw-resize";if(d){let p=cc[d]+(et(o)?.angle??0);return uc[(Math.round(p/45)%4+4)%4]}let f=this.hitCornerRotateZone(e,t);if(f)return Bo((et(o)?.angle??0)+rc[f]);let m=o.findTarget(r.x,r.y);if(m&&m===o.editingNode)return"text";if(m instanceof te){let p=m.borderOrIndicatorHit(r.x,r.y,this.host.zoom),b="move";return p?.inCircle?b="pointer":p?.border&&o.selection.includes(m)&&(b=ad(m.tableAngle,p.border.type)),this.updateTableHover(m,p,!0),b}if(this.updateTableHover(null,null,!1),!this.host.cropSession&&!this.host.expandSession&&!this.host.pathSession&&!this.host.warpSession){let p=o.nodes.find(b=>Ze(b)&&b.visible&&b.raw.visible!==!1&&b.containsPoint(r.x,r.y));if(p)return p.dims.y===0?"ns-resize":"ew-resize"}return m?"move":""}updateTableHover(e,t,r,o={}){if(this.hoveredTable&&this.hoveredTable!==e&&(this.hoveredTable.clearHoverState(),this.hoveredTable=null,this.host.requestRenderAll()),!e)return;let i=e.hoveredBorder,s=e.hoveredIndicator,a=e.indicatorVisible,l=e.hoveredStrip,u=e.hoveredDragHandle,c=e.hoveredRangeHandle;e.hoveredBorder=t&&!t.inCircle?t.border:null,e.hoveredIndicator=t?.inCircle?t.border:null,e.indicatorVisible=r||!!t,e.hoveredStrip=o.strip??null,e.hoveredDragHandle=o.dragHandle??!1,e.hoveredRangeHandle=o.rangeHandle??!1,this.hoveredTable=e;let h=l?.kind!==e.hoveredStrip?.kind||l?.index!==e.hoveredStrip?.index;(i!==e.hoveredBorder||s!==e.hoveredIndicator||a!==e.indicatorVisible||h||u!==e.hoveredDragHandle||c!==e.hoveredRangeHandle)&&this.host.requestRenderAll()}updateHover(e,t,r){let o=this.host.document,i=null,s=null,a=o.nodes.find(d=>d instanceof le&&d.editingMask)??null,l=!!this.host.cropSession||!!this.host.expandSession||!!this.host.pathSession||!!this.host.warpSession||!!a,u=!this.hitHandle(e,t)&&!this.hitMoveControl(e,t);if(!l&&u){let d=o.findTarget(r.x,r.y);if(d instanceof J&&!(d instanceof te)&&!(d instanceof le)){let f=o.activeGroupChild;if(!(f!==null&&o.selection.length===1&&o.selection[0]===d))o.selection.includes(d)||(i=d);else{let p=Dr(d,r.x,r.y,o.selection);i=p&&p!==f?p:null}}else d&&!o.selection.includes(d)&&(i=d)}if(i&&i===o.editingNode&&(i=null),u&&!(a&&As((d,f)=>this.host.toScreen(d,f),a,e,t))){let d=o.selection.length===1&&o.selection[0]instanceof le?o.selection[0]:null;if(d){let f=Oo((m,p)=>this.host.toScreen(m,p),d,e,t);f&&(s={puzzle:d,mask:f.mask,handle:f.handle})}}let c=o.hovered;o.setHovered(i);let h=o.seamHover;o.setSeamHover(s),(o.hovered!==c||o.seamHover!==h)&&this.host.requestRenderAll()}attach(){if(!this.interactive)return;let e=this.el,t=s=>{if(s.button!==0||this.host.interactionSuspended)return;this.host.document.editingNode&&s.preventDefault();let a=e.getBoundingClientRect(),l=s.clientX-a.left,u=s.clientY-a.top;this.onPointerDown(l,u,s.shiftKey)},r=s=>{if(this.host.interactionSuspended&&this.gesture.type==="none"||this.host.panning)return;let a=e.getBoundingClientRect();this.onPointerMove(s.clientX-a.left,s.clientY-a.top)},o=s=>{if(this.host.interactionSuspended&&this.gesture.type==="none")return;let a=e.getBoundingClientRect();this.onPointerUp(s.clientX-a.left,s.clientY-a.top)},i=()=>{let s=this.host.document,a=s.hovered;s.setHovered(null),this.el.style.cursor="",s.hovered!==a&&this.host.requestRenderAll()};e.addEventListener("pointerdown",t),window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),e.addEventListener("pointerleave",i),this.detach=()=>{e.removeEventListener("pointerdown",t),window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),e.removeEventListener("pointerleave",i)}}onPointerDown(e,t,r){let o=this.host.document,i=this.host.toScene(e,t);this.performed=!1,this.deferredClickSwitch=null,o.setHovered(null);let s=this.host.cropSession;if(s){let y=s.hitHandle(e,t);y?this.gesture={type:"crop-handle",handle:y}:s.hitRect(i.x,i.y)?this.gesture={type:"crop-move",last:i}:s.exitByOutsideClick(),this.host.requestRenderAll();return}let a=this.host.expandSession;if(a){let y=a.hitHandle(e,t);y?this.gesture={type:"expand-handle",handle:y}:a.hitRect(i.x,i.y)?this.gesture={type:"expand-image-drag",last:i}:a.exitByOutsideClick(),this.host.requestRenderAll();return}let l=this.host.pathSession;if(l){let y=l.hitAnchor(e,t);if(y&&l.startAnchorDrag(y)){this.gesture={type:"path-anchor-drag",key:y},this.host.requestRenderAll();return}let v=l.findInsertCandidate(i.x,i.y);if(v){let R=l.insertAnchor(v);if(R){this.gesture={type:"path-anchor-drag",key:R},this.host.requestRenderAll();return}}if(l.hitBody(i.x,i.y)){this.gesture={type:"path-body-drag",last:i},this.host.requestRenderAll();return}l.exitByOutsideClick()}let u=this.host.warpSession;if(u){let y=u.hitAnchor(e,t);y&&(this.gesture={type:"warp-anchor-drag",anchor:y},u.applyAnchorDrag(y,i)),this.host.requestRenderAll();return}if(this.host.rulerVisible){let y=gc(e,t);if(y){let v=gd(y,y==="horizontal"?i.y:i.x),R=Ct(v);R&&(o.add(R),o.clearSelection(),this.gesture={type:"reference-line",node:R,axis:y,creating:!0,historyBefore:We([R])}),this.host.requestRenderAll();return}}let c=o.editingNode,h=!1;if(c){if(c.containsPoint(i.x,i.y)){let y=c.localPoint(i.x,i.y),v=c.cursorIndexAt(y.x,y.y);this.host.setEditingSelection(v,v),this.gesture={type:"text-select",anchorIdx:v};return}o.exitEditing(),h=!0}if(!h&&o.selection.length===1&&o.selection[0]instanceof te){let y=o.selection[0],v=o.findTarget(i.x,i.y)?null:y.borderOrIndicatorHit(i.x,i.y,this.host.zoom);if(v?.inCircle){this.gesture={type:"table-indicator-click",node:y,border:v.border};return}let R=o.findTarget(i.x,i.y)?null:y.stripHit(i.x,i.y,this.host.zoom);if(R){this.gesture=R.kind==="col-strip"?{type:"table-strip-click",node:y,kind:"col",index:R.col}:{type:"table-strip-click",node:y,kind:"row",index:R.row};return}}if(!h&&o.selection.length===1&&o.selection[0]instanceof te){let y=o.selection[0];if(o.findTarget(i.x,i.y)===y&&y.rangeHandleHit(i.x,i.y,this.host.zoom)){let v=y.expandedCellRange;if(v){this.gesture={type:"table-range-drag",node:y,anchor:{row:v.r1,col:v.c1}};return}}}let d=h?null:o.nodes.find(y=>y instanceof le&&y.editingMask)??null,f=!!d;if(f&&d){let y=As((v,R)=>this.host.toScreen(v,R),d,e,t);if(y&&d.editingMask){let v=bc(d,d.editingMask,y);v&&(this.gesture=v);return}}{let y=o.selection.length===1&&o.selection[0]instanceof le?o.selection[0]:null;if(y){let v=Oo((R,P)=>this.host.toScreen(R,P),y,e,t);if(v){let R=bc(y,v.mask,v.handle);R&&(this.gesture=R);return}}}let m=h?null:this.hitLockControl(e,t);if(m){this.host.document.events.fire("lock:unlock-requested",m);return}let p=!f||d!=null&&o.selection.length===1&&o.selection[0]===d;if(p&&!h){let y=this.hitActiveChildHandle(e,t),v=o.activeGroupChild,R=o.selection.length===1?o.selection[0]:null;if(y&&v&&R instanceof J&&!(R instanceof te)&&!(R instanceof le)){let P=is(R,v);if(P.length){let T=[v,...P,...P.flatMap(C=>C.children)];if(y==="mtr"){let C=v.aCoords,E={x:(C.tl.x+C.br.x)/2,y:(C.tl.y+C.br.y)/2};this.freezeRotateHandle(v.raw.angle??0,E,!0),this.gesture={type:"rotate",center:E,startAngle:Math.atan2(i.y-E.y,i.x-E.x),snapshot:{node:v,angle0:v.raw.angle??0},cursorOffset:225,childTransform:{child:v,shells:P,pivotLocal:{...v.center}},historyBefore:We(T)}}else if(!Fr(y))this.gesture={type:"scale",handle:y,snapshot:pc(v,y,o),freeScale:r&&Tn.has(y),childTransform:{child:v,shells:P},historyBefore:We(T)};else return;this.host.requestRenderAll();return}}}if(!h&&p&&this.hitMoveControl(e,t)){let y=o.selection[0],v=new Map;v.set(y,{left:y.raw.left??0,top:y.raw.top??0}),this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:v,historyBefore:We([y])},this.host.requestRenderAll();return}let b=h||!p?null:this.hitHandle(e,t);if(b){if(o.selection.length===1){let y=o.selection[0];if(b==="mtr"){let v=y.center;this.freezeRotateHandle(y.raw.angle??0,v),this.gesture={type:"rotate",center:v,startAngle:Math.atan2(i.y-v.y,i.x-v.x),snapshot:{node:y,angle0:y.raw.angle??0},cursorOffset:225,historyBefore:We([y])}}else if(Fr(b)&&(ys(y)||Io(y)))this.gesture={type:"cornerRadius",node:y,corner:No[b],model:Io(y)?"image":"rect",historyBefore:We([y])};else if(y instanceof te&&En(b)){let v=xf(y,b);v.historyBefore=We([y]),this.gesture=v}else if(y instanceof le&&En(b)){let v=yf(y,b);v.historyBefore=We([y]),this.gesture=v}else this.gesture={type:"scale",handle:b,snapshot:pc(y,b,o),freeScale:r&&Tn.has(b),historyBefore:We([y])}}else{let y=et(o),v=o.selection.filter(R=>!at(R));if(b==="mtr"){let R=Rs(y.quad);v.length&&this.freezeRotateHandle(y.angle,R),this.gesture={type:"multi-rotate",center:R,startAngle:Math.atan2(i.y-R.y,i.x-R.x),frameAngle0:y.angle,frame:Ps(y.quad),snapshot:{members:v.map(P=>({node:P,angle0:P.raw.angle??0,center0:{...P.center}}))},historyBefore:We(o.selection)}}else this.gesture={type:"multi-scale",snapshot:hf(v,b,y),freeScale:r&&Tn.has(b),historyBefore:We(o.selection)}}return}let g=h||!p?null:this.hitCornerRotateZone(e,t);if(g){let y=o.selection[0],v=y.center;this.host.rotateDrag!==void 0&&(this.host.rotateDrag={spec:null,center:{x:v.x,y:v.y}}),this.gesture={type:"rotate",center:v,startAngle:Math.atan2(i.y-v.y,i.x-v.x),snapshot:{node:y,angle0:y.raw.angle??0},cursorOffset:rc[g],historyBefore:We([y])};return}if(!h&&o.selection.length===1&&o.selection[0]instanceof te){let y=o.selection[0];if(!o.findTarget(i.x,i.y)&&y.dragHandleHit(i.x,i.y,this.host.zoom)){let v=new Map;for(let R of o.selection)v.set(R,{left:R.raw.left??0,top:R.raw.top??0});this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:v,historyBefore:We(o.selection)},this.host.requestRenderAll();return}}if(!r){let y=o.nodes.find(v=>Ze(v)&&v.visible&&v.raw.visible!==!1&&v.containsPoint(i.x,i.y));if(y){o.setSelection([y],"create"),this.gesture={type:"reference-line",node:y,axis:y.dims.y===0?"horizontal":"vertical",creating:!1,historyBefore:We([y])},this.host.requestRenderAll();return}}let x=o.findTarget(i.x,i.y),S=x instanceof te?x:null;if(S){let y=S.borderOrIndicatorHit(i.x,i.y,this.host.zoom);if(y?.inCircle){this.gesture={type:"table-indicator-click",node:S,border:y.border};return}let v=S.borderHit(i.x,i.y);if(v&&o.selection.includes(S)){let P=bf(S,v,i);P.historyBefore=We([S]),this.gesture=P;return}let R=S.cellHit(i.x,i.y);if(R){o.selection.includes(S)?!r&&o.selection.length>1&&(this.deferredClickSwitch=S):o.setSelection([S],"create");let P=new Map;for(let T of o.selection)at(T)||P.set(T,{left:T.raw.left??0,top:T.raw.top??0});this.gesture={type:"table-cell-click",node:S,start:i,anchorCell:R,shift:r,moveSnapshot:P,frame0:o.selection.length>1&&o.selectionFrame?{...o.selectionFrame}:void 0,historyBefore:We(o.selection)},this.host.requestRenderAll();return}}if(f&&d){if(x===d){let y=d.maskChildren.find(v=>v.visible&&v.containsPoint(i.x,i.y));if(y){y!==d.editingMask&&(d.editingMask=y),o.setActiveGroupChild(y);let v=new Map;for(let R of o.selection)at(R)||v.set(R,{left:R.raw.left??0,top:R.raw.top??0});this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:v,frame0:void 0,historyBefore:We(o.selection)}}else d.exitMaskEditing(),o.setActiveGroupChild(null);this.host.requestRenderAll();return}d.exitMaskEditing(),this.host.requestRenderAll()}let w=x instanceof te?null:x;if(w){let y=o.selection.includes(w),v=o.groupEditing;if(r){let R=(o.selection.includes(w)?o.selection.filter(P=>P!==w):[...o.selection,w]).filter(P=>!at(P));o.setSelection(R,"update")}else o.selection.includes(w)?o.selection.length>1&&(this.deferredClickSwitch=w):o.setSelection([w],"create");if(w instanceof J&&!(w instanceof te)&&!(w instanceof le))o.setActiveGroupChild(Dr(w,i.x,i.y,o.selection));else if(w instanceof le&&y&&o.selection.length===1){let R=w.maskChildren.find(P=>P.visible&&P.containsPoint(i.x,i.y))??null;o.setActiveGroupChild(R),R?w.editingMask=R:w.exitMaskEditing()}else o.activeGroupChild&&o.setActiveGroupChild(null);if(o.selection.includes(w))if(at(w)&&y&&o.selection.length===1&&o.selection[0]===w)this.gesture={type:"marquee",anchor:i,additive:r,hold:!0};else{let R=o.activeGroupChild,P=v&&R&&w instanceof J&&!(w instanceof te)&&!(w instanceof le)&&o.selection.length===1&&o.selection[0]===w?is(w,R):[],T=P.length&&R?{child:R,toLocal:Ed(R),shells:P}:null;if(T){let C=new Map;C.set(T.child,{left:T.child.raw.left??0,top:T.child.raw.top??0});let E=[T.child,...T.shells,...T.shells.flatMap(M=>M.children)];this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:C,childMove:T,historyBefore:We(E)}}else{let C=new Map;for(let E of o.selection)at(E)||C.set(E,{left:E.raw.left??0,top:E.raw.top??0});this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:C,frame0:o.selection.length>1&&o.selectionFrame?{...o.selectionFrame}:void 0,historyBefore:We(o.selection)}}}this.host.requestRenderAll();return}this.gesture={type:"marquee",anchor:i,additive:r},r||o.clearSelection(),this.host.requestRenderAll()}onPointerMove(e,t){let r=this.host.document,o=this.host.toScene(e,t),i=this.gesture;if(i.type==="none"){this.el.style.cursor=this.hoverCursor(e,t,o),this.updateHover(e,t,o);return}if(i.type==="move"){if(i.snapshot.size){if(!this.performed&&Math.hypot(e-i.startCss.x,t-i.startCss.y)<=rf)return;this.performed=!0;let s=o.x-i.start.x,a=o.y-i.start.y;if(i.childMove){let l=i.childMove.toLocal(s,a);r.applyTransform([...i.snapshot.keys()],u=>{let c=i.snapshot.get(u);return{left:c.left+l.x,top:c.top+l.y}},"moving")}else r.applyTransform([...i.snapshot.keys()],l=>{let u=i.snapshot.get(l);return{left:u.left+s,top:u.top+a}},"moving"),i.frame0&&r.setSelectionFrame({...i.frame0,center:{x:i.frame0.center.x+s,y:i.frame0.center.y+a}})}}else if(i.type==="reference-line"){this.performed=!0;let s=i.axis==="horizontal";r.applyTransform([i.node],()=>({visible:!0,...s?{top:o.y}:{left:o.x}}),"moving"),this.host.referenceLineDrag!==void 0&&(this.host.referenceLineDrag={axis:i.axis,position:s?o.y:o.x})}else if(i.type==="scale")this.performed=!0,uf(r,i.snapshot,o,i.freeScale),r.applyTransform([i.snapshot.node],()=>({}),"scaling"),!i.snapshot.bakeFont&&!i.snapshot.bakeWidth&&!i.snapshot.bakeHeight&&!i.snapshot.bakeGroup&&this.host.registerScalingSnap?.(i.snapshot.node,i.handle);else if(i.type==="cornerRadius")if(i.model==="image"){let s=wy(i.node,i.corner,o);s&&(this.performed=!0,r.applyTransform([i.node],()=>s,"cornerRadius"))}else{let s=vy(i.node,i.corner,o);s!==null&&(this.performed=!0,r.applyTransform([i.node],()=>({radius:s}),"cornerRadius"))}else if(i.type==="multi-scale")i.snapshot.members.length&&(this.performed=!0,df(r,i.snapshot,o,i.freeScale),this.host.registerScalingSnap?.(r.selection[0],i.snapshot.handle));else if(i.type==="rotate"){this.performed=!0;let s=Math.atan2(o.y-i.center.y,o.x-i.center.x),a=i.snapshot.angle0+Ms(s-i.startAngle);a=(a%360+360)%360;let l=i.childTransform?.pivotLocal??i.center;r.applyTransform([i.snapshot.node],u=>u.rotateAroundCenter(a,l),"rotating"),this.el.style.cursor=Bo((i.snapshot.node.raw.angle??0)+(i.cursorOffset??225))}else if(i.type==="multi-rotate")i.snapshot.members.length&&(this.performed=!0,ff(r,i,o),this.el.style.cursor=Bo((r.selectionFrame?.angle??0)+225));else if(i.type==="marquee"){if(i.hold&&Math.hypot(o.x-i.anchor.x,o.y-i.anchor.y)<=ks)return;this.host.marquee={left:i.anchor.x,top:i.anchor.y,right:o.x,bottom:o.y};let s=r.objectsIntersectingRect(i.anchor.x,i.anchor.y,o.x,o.y).filter(l=>!at(l)),a=(i.additive?[...new Set([...r.selection,...s])]:s).filter(l=>!at(l));r.setSelection(a,"update")}else if(i.type==="text-select"){let s=r.editingNode;if(s){let a=s.localPoint(o.x,o.y),l=s.cursorIndexAt(a.x,a.y);this.host.setEditingSelection(Math.min(i.anchorIdx,l),Math.max(i.anchorIdx,l))}}else if(i.type==="table-border-drag")this.performed=!0,gf(i,o);else if(i.type==="table-edge-resize")this.performed=!0,wf(r,i,o);else if(i.type==="puzzle-edge-resize")this.performed=!0,vf(r,i,o);else if(i.type==="puzzle-mask-edge-resize")this.performed=!0,Sf(i,o);else if(i.type==="crop-handle")this.performed=!0,this.host.cropSession?.applyHandle(i.handle,o);else if(i.type==="expand-handle")this.performed=!0,this.host.expandSession?.applyHandle(i.handle,o);else if(i.type==="expand-image-drag")this.performed=!0,this.host.expandSession?.moveImageBy({x:o.x-i.last.x,y:o.y-i.last.y}),i.last=o;else if(i.type==="crop-move")this.performed=!0,this.host.cropSession?.moveImageBy({x:o.x-i.last.x,y:o.y-i.last.y}),i.last=o;else if(i.type==="path-anchor-drag")this.performed=!0,this.host.pathSession?.applyAnchorDrag(i.key,o);else if(i.type==="path-body-drag")this.performed=!0,this.host.pathSession?.moveBodyBy({x:o.x-i.last.x,y:o.y-i.last.y}),i.last=o;else if(i.type==="warp-anchor-drag")this.performed=!0,this.host.warpSession?.applyAnchorDrag(i.anchor,o);else if(i.type==="table-range-drag"){let s=i.node.cellHit(o.x,o.y);if(s){let a=xn(i.node.cellMap,i.anchor,s);i.node.setCellSelection(a,i.anchor,ze(a))}}else if(i.type==="table-cell-click"){if(i.shift){let s=i.node.cellHit(o.x,o.y),a=i.node.cellAnchor??i.anchorCell;if(s&&a){let l=xn(i.node.cellMap,a,s);i.node.setCellSelection(l,a,ze(l))}}else if(Math.hypot(o.x-i.start.x,o.y-i.start.y)>ks)return this.deferredClickSwitch=null,this.gesture={type:"move",start:i.start,startCss:{x:e,y:t},snapshot:i.moveSnapshot,frame0:i.frame0,historyBefore:i.historyBefore},this.onPointerMove(e,t)}this.host.requestRenderAll()}onPointerUp(e,t){let r=this.host.document,o=this.gesture;if(this.gesture={type:"none"},this.host.marquee=null,this.host.rotateDrag!==void 0&&(this.host.rotateDrag=null),o.type!=="none"){if(this.host.settleMoveSnap?.(),this.host.finishSnapGesture?.(),o.type==="move"){if(this.performed)if(o.childMove){let i=ss(o.childMove.shells),s=[...new Set([o.childMove.child,...i])];r.applyTransform(s,()=>({}),"modified",{action:Le.drag,before:o.historyBefore})}else r.applyTransform([...o.snapshot.keys()],()=>({}),"modified",{action:Le.drag,before:o.historyBefore});else if(this.deferredClickSwitch){let i=this.deferredClickSwitch;r.selection.length>1&&r.selection.includes(i)&&r.setSelection([i],"create")}}else if(o.type==="reference-line")this.host.referenceLineDrag!==void 0&&(this.host.referenceLineDrag=null),(this.host.rulerVisible?gc(e,t):null)===o.axis||o.creating&&!this.performed?(r.remove(o.node),r.fireObjectModified([o.node],{action:Le.drag,before:o.historyBefore?[o.historyBefore.get(o.node)].filter(s=>!!s):void 0})):this.performed&&r.applyTransform([o.node],()=>({selectable:!1}),"modified",{action:Le.drag,before:o.historyBefore});else if(o.type==="scale"||o.type==="rotate"){if(this.performed)if(o.childTransform){let i=ss(o.childTransform.shells),s=[...new Set([o.childTransform.child,...i])];r.applyTransform(s,()=>({}),"modified",{action:o.type,before:o.historyBefore})}else r.applyTransform([o.snapshot.node],()=>({}),"modified",{action:o.type,before:o.historyBefore})}else if(o.type==="cornerRadius")this.performed&&r.applyTransform([o.node],()=>({}),"modified",{action:Le.cornerRadius,before:o.historyBefore});else if(o.type==="multi-scale"||o.type==="multi-rotate")this.performed&&r.applyTransform(o.snapshot.members.map(i=>i.node),()=>({}),"modified",{action:o.type==="multi-scale"?Le.scale:Le.rotate,before:o.historyBefore});else if(o.type==="marquee")r.commitGeometry();else if(o.type==="path-anchor-drag"||o.type==="path-body-drag")this.performed&&this.host.pathSession?.commit();else if(o.type==="warp-anchor-drag")this.performed&&this.host.warpSession?.endDrag();else if(o.type==="table-border-drag")o.node.setCellSelection(o.savedCells,o.savedAnchor,o.savedRange),o.node.hoveredBorder=null,o.node.borderDragging=!1,this.performed&&(o.node.rebuildTable(),r.applyTransform([o.node],()=>({}),"modified",{action:Le.scale,before:o.historyBefore}));else if(o.type==="table-edge-resize")this.performed&&r.applyTransform([o.node],()=>({}),"modified",{action:Le.scale,before:o.historyBefore});else if(o.type==="puzzle-edge-resize")this.performed&&r.applyTransform([o.node],()=>({}),"modified",{action:Le.scale,before:o.historyBefore});else if(o.type==="puzzle-mask-edge-resize")this.performed&&r.applyTransform([o.node],()=>({}),"modified",{action:Le.scale,before:o.historyBefore});else if(o.type==="table-indicator-click"){let i=this.host.toScene(e,t),s=o.node.borderOrIndicatorHit(i.x,i.y,this.host.zoom);s?.inCircle&&Tf(r,o.node,s.border)}else if(o.type==="table-strip-click"){let i=this.host.toScene(e,t),s=o.node.stripHit(i.x,i.y,this.host.zoom);s?.kind==="col-strip"?o.node.setColumnSelection(s.col):s?.kind==="row-strip"&&o.node.setRowSelection(s.row)}else if(o.type==="table-cell-click"){let i=this.host.toScene(e,t);if(Math.hypot(i.x-o.start.x,i.y-o.start.y)<=ks)if(this.deferredClickSwitch===o.node)r.selection.length>1&&r.selection.includes(o.node)&&r.setSelection([o.node],"create");else{let s=o.node.cellHit(i.x,i.y);if(s)if(o.shift){let a=o.node.cellAnchor??o.anchorCell??s,l=xn(o.node.cellMap,a,s);o.node.setCellSelection(l,a,ze(l))}else o.node.setCellSelection([s],s,{r1:s.row,r2:s.row,c1:s.col,c2:s.col})}}this.deferredClickSwitch=null,this.host.requestRenderAll()}}dispose(){this.detach?.(),this.detach=null}};var Ty=new Set(["qrcode","barcode"]),Ey=n=>{let e=n.raw.type;return typeof e=="string"&&Ty.has(e.toLowerCase())},Ls=class{host;onDblClick;disposed=!1;interactive;constructor(e,t=!0){this.host=e,this.interactive=t,this.onDblClick=r=>{if(e.interactionSuspended)return;let o=e.canvasEl.getBoundingClientRect(),i=e.toScene(r.clientX-o.left,r.clientY-o.top),s=e.document.findTarget(i.x,i.y);if(s instanceof J&&!(s instanceof te)&&!(s instanceof le)){let a=Dr(s,i.x,i.y,e.document.selection);a&&!(a instanceof te)&&!(a instanceof le)&&(s=a)}this.dispatch(s,i.x,i.y)},this.interactive&&e.canvasEl.addEventListener("dblclick",this.onDblClick)}dispatch(e,t,r){if(e instanceof te){let o=e.cellHit(t,r);o&&this.host.startCellEditing(e,o.row,o.col);return}if(e instanceof le){let o=e.maskChildren.find(i=>i.visible&&i.containsPoint(t,r));o&&(this.host.document.selection.includes(e)||this.host.document.setSelection([e],"create"),e.editingMask=o,this.host.document.setActiveGroupChild(o),this.host.requestRenderAll());return}if(e instanceof ye){this.host.enterTextEditingAtClick(e,t,r);return}if(e?.isImageType&&!Ey(e)){let o=this.host.document.events;e.raw.smartObject?o.fire("smartobject:open-requested",e):o.fire("image:replace-requested",e)}}dispose(){this.disposed||(this.disposed=!0,this.host.canvasEl.removeEventListener("dblclick",this.onDblClick))}};var Is=class n{host;onKeydown;offDocEvents;disposed=!1;constructor(e){this.host=e,this.onKeydown=i=>this.handleKey(i),window.addEventListener("keydown",this.onKeydown);let t=e.document.events,r=()=>this.pruneCellState(),o=[t.on("selection:created",r),t.on("selection:updated",r),t.on("selection:cleared",r)];this.offDocEvents=()=>o.forEach(i=>i())}dispose(){this.disposed||(this.disposed=!0,window.removeEventListener("keydown",this.onKeydown),this.offDocEvents())}pruneCellState(){let e=this.host.document;for(let t of e.nodes)t instanceof te&&!e.selection.includes(t)&&t.clearCellInteractionState()}get activeTable(){let e=this.host.document;if(e.editingNode||e.selection.length!==1)return null;let t=e.selection[0];return t instanceof te?t:null}static isTypingTarget(e){let t=e.target;return t instanceof HTMLElement?t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable:!1}handleKey(e){let t=this.activeTable;if(!t||n.isTypingTarget(e))return;let r=e.ctrlKey||e.metaKey,o=e.key;if(o==="Escape"){t.hasCellSelection&&(t.clearCellSelection(),this.host.requestRenderAll(),e.preventDefault());return}if(r&&!e.shiftKey&&o.toLowerCase()==="a"){let i=t.tableView,s=Mo(t.cellMap,i.rows,i.cols);t.setCellSelection(s,s[0]??null,ze(s)),this.host.requestRenderAll(),e.preventDefault();return}if(r&&o.toLowerCase()==="m"){e.shiftKey?this.unmergeFirst(t):this.mergeSelection(t);return}if(t.hasCellSelection&&!r&&!e.altKey&&o.length===1&&!/^(Enter|Escape|Tab|Delete|Backspace)$/.test(o)){let i=t.selectedCells[0];i&&(e.preventDefault(),this.host.startCellEditing(t,i.row,i.col,{initialText:o}));return}if(o==="Enter"&&t.hasCellSelection){let i=t.selectedCells[0];i&&(e.preventDefault(),this.host.startCellEditing(t,i.row,i.col));return}if(o==="Delete"||o==="Backspace"){this.deleteSelectionText(t);return}if(t.hasCellSelection&&(o==="ArrowUp"||o==="ArrowDown"||o==="ArrowLeft"||o==="ArrowRight")){let s={ArrowUp:{row:-1,col:0},ArrowDown:{row:1,col:0},ArrowLeft:{row:0,col:-1},ArrowRight:{row:0,col:1}}[o];this.navigate(t,s.row,s.col),e.preventDefault();return}o==="Tab"&&(this.navigate(t,0,e.shiftKey?-1:1,!0),e.preventDefault())}navigate(e,t,r,o=!1){let i=e.tableView,s=e.cellAnchor??e.selectedCells[0]??{row:0,col:0},a=s.row+t,l=s.col+r;o?(l>=i.cols?(l=0,a++):l<0&&(l=i.cols-1,a--),a>=i.rows?a=0:a<0&&(a=i.rows-1)):(a=Math.max(0,Math.min(i.rows-1,a)),l=Math.max(0,Math.min(i.cols-1,l)));let u=lt(e.cellMap,a,l);e.setCellSelection([u],u,{r1:u.row,r2:u.row,c1:u.col,c2:u.col}),this.host.requestRenderAll()}commit(e){e.rebuildTable(),this.host.document.applyTransform([e],()=>({}),"modified"),this.host.requestRenderAll()}mergeSelection(e){if(e.selectedCells.length<2)return;let t=ze(e.selectedCells);if(!t)return;let r=So(e.raw,t.r1,t.c1,t.r2,t.c2),o={row:r.r1,col:r.c1};e.setCellSelection([o],o,r),this.commit(e)}unmergeFirst(e){for(let t of e.selectedCells)if(vo(e.raw,t.row,t.col)){let r={row:t.row,col:t.col};e.setCellSelection([r],r,{r1:t.row,r2:t.row,c1:t.col,c2:t.col}),this.commit(e);return}}deleteSelectionText(e){let t=e.cellMap,r=!1;for(let o of e.selectedCells){let i=we(t,o.row,o.col);i&&!i.isMerged&&i.text&&(i.text="",r=!0)}r&&this.commit(e)}};var xc=(n,e,t)=>Math.max(e,Math.min(t,n)),_s={min:.05,max:5},Hr=60,Cy=n=>{let e=n.workspaceRect();if(e.width<=0||e.height<=0)return null;let t=n.viewportTransform,r=e.left*t[0]+t[4],o=e.top*t[0]+t[5],i=r+e.width*t[0],s=o+e.height*t[0],{width:a,height:l}=n.viewSize;return r<-1||o<-1||i>a+1||s>l+1?null:{x:(r+i)/2,y:(o+s)/2}},Ef=(n,e)=>{n.preventDefault();let{deltaX:t,deltaY:r,deltaMode:o,ctrlKey:i,metaKey:s,altKey:a,shiftKey:l}=n,u=o===1?16:o===2&&e.viewSize.height||1,c=o===0?t:t*u,h=o===0?r:r*u;if(i||s||a){let A=Math.abs(h)<10?h*2:h/3,O=e.viewportTransform[0],F=xc(O*(1-A/200),_s.min,_s.max),W=Cy(e)??e.cursorPoint(n);e.zoomAt(W.x,W.y,F/O);return}let d=o===0&&Math.abs(t)<=10&&Math.abs(r)<=10,f=xc(e.viewportTransform[0],.1,_s.max),m=Math.max(1,f)*1.25,p=20*m,b=A=>xc(A,-60,60),g=0,x=0;if(l||Math.abs(c)>Math.abs(h)){let A=c!==0?c:h;A!==0&&(g=d?-b(A)*m:A>0?-p:p)}else h!==0&&(x=d?-b(h)*m:h>0?-p:p);if(g===0&&x===0)return;let w=e.viewportTransform,{width:y,height:v}=e.viewSize,R=e.workspaceRect(),P=R.width*f,T=R.height*f,C=w[4],E=w[5],M=Hr-P;C+g<M&&(g=M-C),C+g>y-Hr&&(g=y-Hr-C);let k=Hr-T;E+x<k&&(x=k-E),E+x>v-Hr&&(x=v-Hr-E),!(g===0&&x===0)&&e.pan(g,x)};var Ds=class{constructor(e,t,r,o=!0){this.host=e;this.snapGuide=t;this.sources=r;this.interactive=o;let i=e.canvasEl;this.pointer=new Ns(i,e,this.interactive),this.tableInteraction=new Is(e);let s=p=>{if(p.key!=="Escape")return;let b=e.document.selection;b.length===1&&b[0]instanceof le&&b[0].editingMask&&(b[0].exitMaskEditing(),e.document.setActiveGroupChild(null),e.requestRenderAll())};this.interactive&&window.addEventListener("keydown",s);let a=e.document.events,l=()=>e.requestRenderAll(),u=[a.on("selection:created",l),a.on("selection:updated",l),a.on("selection:cleared",l),a.on("object:modified",l),a.on("object:moving",p=>this.snapGuide.registerMove(p)),a.on("object:removed",p=>{p instanceof ie&&this.sources.releaseAnimatedNode(p)})];this.offDocEvents=()=>u.forEach(p=>p()),this.dblClick=new Ls(e,this.interactive);let c=p=>{Ef(p,e)},h=p=>{if(p.button===1){p.preventDefault(),e.panning=!0,this.lastPanPointer={x:p.clientX,y:p.clientY},i.style.cursor="grab";try{i.setPointerCapture(p.pointerId)}catch{}}},d=p=>{if(!e.panning||!this.lastPanPointer)return;let b=p.clientX-this.lastPanPointer.x,g=p.clientY-this.lastPanPointer.y;this.lastPanPointer={x:p.clientX,y:p.clientY},e.pan(b,g),i.style.cursor="grab"},f=p=>{e.panning&&(e.panning=!1,this.lastPanPointer=null,i.hasPointerCapture(p.pointerId)&&i.releasePointerCapture(p.pointerId),i.style.cursor="default")},m=p=>e.handleFontsLoaded(p.fontfaces??[]);document.fonts?.addEventListener?.("loadingdone",m),this.interactive&&(i.addEventListener("wheel",c,{passive:!1}),i.addEventListener("pointerdown",h),window.addEventListener("pointermove",d),window.addEventListener("pointerup",f)),this.detachListeners=()=>{document.fonts?.removeEventListener?.("loadingdone",m),i.removeEventListener("wheel",c),i.removeEventListener("pointerdown",h),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",f),window.removeEventListener("keydown",s)}}host;snapGuide;sources;interactive;pointer;tableInteraction;dblClick;detachListeners=null;offDocEvents=null;lastPanPointer=null;get pointerActive(){return this.pointer.active}dispose(){this.detachListeners?.(),this.offDocEvents?.(),this.pointer.dispose(),this.dblClick.dispose(),this.tableInteraction.dispose()}};var My={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Ot=n=>typeof n=="string"?My[n]??0:n-.5,yc=(n,e,t)=>{let r=Math.cos(e),o=Math.sin(e),i=n.x-t.x,s=n.y-t.y;return{x:t.x+r*i-o*s,y:t.y+o*i+r*s}},Sc=n=>({x:n.width*n.scaleX,y:n.height*n.scaleY}),Fs=Sc,Wo=n=>n*Math.PI/180,vc=(n,e,t,r,o,i=!1,s=!1)=>{let a=i?-1:1,l=s?-1:1,u={x:n.x+e*r.x*a,y:n.y+t*r.y*l};return o&&(u=yc(u,Wo(o),n)),u},wc=(n,e,t,r,o,i=!1,s=!1)=>{let a=i?-1:1,l=s?-1:1,u={x:n.x-e*r.x*a,y:n.y-t*r.y*l};return o&&(u=yc(u,Wo(o),n)),u},Bs=(n,e,t,r,o)=>vc(n,Ot(e),Ot(t),r,o),Ho=(n,e,t,r,o,i)=>wc({x:n,y:e},Ot(t),Ot(r),o,i),Gr=(n,e,t=0,r=0)=>{let o=Ho(n.left,n.top,n.originX,n.originY,Fs(n),n.angle),i=e;n.angle&&(i=yc(i,-Wo(n.angle),o));let s=Fs(n),a=n.flipX?-1:1,l=n.flipY?-1:1;return{x:(i.x-o.x)*a-t*s.x,y:(i.y-o.y)*l-r*s.y}},Xr=(n,e,t,r)=>{let o=Fs(n),i=Ho(n.left,n.top,n.originX,n.originY,o,n.angle),s=vc(i,e,t,o,n.angle,n.flipX,n.flipY),a=r.scaleX??n.scaleX,l=r.scaleY??n.scaleY,u={x:r.width*a,y:r.height*l},c=wc(s,e,t,u,n.angle,n.flipX,n.flipY),h=Bs(c,n.originX,n.originY,u,n.angle);return{...n,...r,scaleX:a,scaleY:l,left:h.x,top:h.y}},Ry=(n,e)=>{let{width:t,cropX:r}=n,i=Gr(n,e).x/n.scaleX- -(t/2),s=t-i;if(r+i<0&&(i=-r,s=t+r),s<8){let a=Math.min(8,r+t);i=t-a,s=a}return Xr(n,.5,0,{width:s,height:n.height,cropX:r+i,cropY:n.cropY})};var Py=(n,e)=>{let{width:t,cropX:r}=n,o=Gr(n,e),i=t-(t/2-o.x/n.scaleX);return i+r>n.naturalWidth&&(i=n.naturalWidth-r),i<8&&(i=Math.min(8,n.naturalWidth-r)),Xr(n,-.5,0,{width:i,height:n.height,cropX:r,cropY:n.cropY})};var ky=(n,e)=>{let{height:t,cropY:r}=n,i=Gr(n,e).y/n.scaleY- -(t/2),s=t-i;if(r+i<0&&(i=-r,s=t+r),s<8){let a=Math.min(8,r+t);i=t-a,s=a}return Xr(n,0,.5,{width:n.width,height:s,cropX:n.cropX,cropY:r+i})};var Ay=(n,e)=>{let{height:t,cropY:r}=n,o=Gr(n,e),i=t-(t/2-o.y/n.scaleY);return i+r>n.naturalHeight&&(i=n.naturalHeight-r),i<8&&(i=Math.min(8,n.naturalHeight-r)),Xr(n,0,-.5,{width:n.width,height:i,cropX:n.cropX,cropY:r})};var Os=(n,e,t)=>e==="left"||e==="right"?e==="left"?Ry(n,t):Py(n,t):e==="top"?ky(n,t):Ay(n,t),Cf=(n,e,t)=>{let r=e==="tl"||e==="bl"?"left":"right",o=e==="tl"||e==="tr"?"top":"bottom",i=Os(n,r,t);return Os(i,o,t)};var Mf=(n,e,t,r)=>{if(!(r>0)||!Number.isFinite(r))return null;let o=Gr(n,t),i=e==="tl"||e==="bl",s=e==="tl"||e==="tr",a=i?n.cropX+n.width:n.naturalWidth-n.cropX,l=s?n.cropY+n.height:n.naturalHeight-n.cropY,u=Math.min(a,l/r);if(!(u>0))return null;let c=Math.min(u,Math.max(8,8/r)),h=n.width/2+(i?-1:1)*o.x/n.scaleX,d=n.height/2+(s?-1:1)*o.y/n.scaleY,f=Math.max(c,Math.min(u,h,d/r)),m=f*r;return Xr(n,i?.5:-.5,s?.5:-.5,{width:f,height:m,cropX:i?n.cropX+n.width-f:n.cropX,cropY:s?n.cropY+n.height-m:n.cropY})},Rf=(n,e,t=!1)=>{if(!(e>0)||!Number.isFinite(e))return null;let r=t?n.scaleY*e/n.scaleX:e,o=n.width*n.scaleX/e,i=n.height*n.scaleY/r,s=n.cropX+(n.width-o)/2,a=n.cropY+(n.height-i)/2;return o<Math.min(8,n.naturalWidth)||i<Math.min(8,n.naturalHeight)||s<0||a<0||s+o>n.naturalWidth||a+i>n.naturalHeight?null:Xr(n,0,0,{width:o,height:i,cropX:s,cropY:a,scaleX:e,scaleY:r})},Ny=(n,e,t,r,o)=>{let i=Math.abs(n.x/t),s=Math.abs(n.y/e);return Math.min(i,s)},Pf=(n,e,t)=>{if(n.width<=0||n.height<=0)return null;let{naturalWidth:r,naturalHeight:o}=n,i=r-n.width-n.cropX,s=o-n.height-n.cropY,a,l;e==="br"?(a=-n.cropX/n.width,l=-n.cropY/n.height):e==="tl"?(a=1+i/n.width,l=1+s/n.height):e==="tr"?(a=-n.cropX/n.width,l=1+s/n.height):(a=1+i/n.width,l=-n.cropY/n.height);let u=Gr(n,t,Ot(a),Ot(l)),c=Math.min(n.width*n.scaleX/Math.min(8,r),n.height*n.scaleY/Math.min(8,o)),h=Math.min(Ny(u,o,r,n.flipX,n.flipY),c);if(!(h>0)||!Number.isFinite(h))return null;let d=h/n.scaleX,f=h/n.scaleY,m=n.width/d,p=n.height/f,b=i/d,g=s/f,x,S;if(e==="br"){if(x=n.cropX/d,S=n.cropY/f,x+m>r||S+p>o)return null}else if(e==="tl"){if(x=r-m-b,S=o-p-g,m+b>r||p+g>o)return null}else if(e==="tr"){if(x=n.cropX/d,S=o-p-g,x+m>r||g+p>o)return null}else if(x=r-m-b,S=n.cropY/f,m+b>r||p+S>o)return null;let w,y;e==="br"?(w=-x/m,y=-S/p):e==="tl"?(w=1+b/m,y=1+g/p):e==="tr"?(w=-x/m,y=1+g/p):(w=1+b/m,y=-S/p);let v=Fs(n),R=Ho(n.left,n.top,n.originX,n.originY,v,n.angle),P=vc(R,Ot(a),Ot(l),v,n.angle,n.flipX,n.flipY),T={x:m*h,y:p*h},C=wc(P,Ot(w),Ot(y),T,n.angle,n.flipX,n.flipY),E=Bs(C,n.originX,n.originY,T,n.angle);return{...n,width:m,height:p,cropX:x,cropY:S,scaleX:h,scaleY:h,left:E.x,top:E.y}},kf=(n,e)=>{let t=Math.cos(Wo(n.angle)),r=Math.sin(Wo(n.angle)),o=n.flipX?-1:1,i=n.flipY?-1:1,s=t*e.x+r*e.y,a=-r*e.x+t*e.y,l=-s/(o*n.scaleX),u=-a/(i*n.scaleY),c=n.cropX+l,h=n.cropY+u;return c<0?c=0:c+n.width>n.naturalWidth&&(c=n.naturalWidth-n.width),h<0?h=0:h+n.height>n.naturalHeight&&(h=n.naturalHeight-n.height),{cropX:c,cropY:h}},Af=(n,e)=>{let t=n.naturalHeight/n.naturalWidth,r,o;t>e?(r=n.naturalWidth,o=n.naturalWidth*e):(o=n.naturalHeight,r=n.naturalHeight/e);let i=(n.naturalWidth-r)/2,s=(n.naturalHeight-o)/2;return{...n,width:r,height:o,cropX:i,cropY:s}},Nf=(n,e,t)=>{let r=n.cropSizeMode==="visible",o=n.cropX??0,i=n.cropY??0,s=n.width??e,a=n.height??t,l=r?s:s-o,u=r?a:a-i;return e>0&&t>0&&(l=Math.min(Math.max(l,0),e),u=Math.min(Math.max(u,0),t),o=Math.min(Math.max(o,0),e-l),i=Math.min(Math.max(i,0),t-u)),{left:n.left??0,top:n.top??0,angle:n.angle??0,originX:n.originX??"left",originY:n.originY??"top",flipX:n.flipX===!0,flipY:n.flipY===!0,width:l,height:u,cropX:o,cropY:i,scaleX:n.scaleX??1,scaleY:n.scaleY??1,naturalWidth:e,naturalHeight:t,cropSizeMode:n.cropSizeMode??"legacy"}},Lf=n=>{let e=n.cropSizeMode==="visible";return{left:n.left,top:n.top,width:e?n.width:n.width+n.cropX,height:e?n.height:n.height+n.cropY,cropX:n.cropX,cropY:n.cropY,scaleX:n.scaleX,scaleY:n.scaleY}},Jt={tl:{x:-.5,y:-.5},tr:{x:.5,y:-.5},bl:{x:-.5,y:.5},br:{x:.5,y:.5},left:{x:-.5,y:0},right:{x:.5,y:0},top:{x:0,y:-.5},bottom:{x:0,y:.5}},Go=(n,e)=>{let t=-n.width/2-n.cropX,r=-n.height/2-n.cropY,o=n.naturalWidth-n.width/2-n.cropX,i=n.naturalHeight-n.height/2-n.cropY;return e==="tl"?{x:t,y:r}:e==="tr"?{x:o,y:r}:e==="bl"?{x:t,y:i}:{x:o,y:i}};var If=(n,e,t)=>({type:"Path",path:n.pathOf(e,t),originX:"center",originY:"center",left:0,top:0}),Tc=n=>{if(!(n.width>0)||!(n.height>0))return n;let e=n.naturalWidth>0?n.naturalWidth:n.width,t=n.naturalHeight>0?n.naturalHeight:n.height,r=Math.min(n.width,n.height,e,t);if(!(r>0))return n;let o=n.cropX+n.width/2,i=n.cropY+n.height/2,s=o-r/2,a=i-r/2;s<0?s=0:s+r>n.naturalWidth&&n.naturalWidth>0&&(s=Math.max(0,n.naturalWidth-r)),a<0?a=0:a+r>n.naturalHeight&&n.naturalHeight>0&&(a=Math.max(0,n.naturalHeight-r));let l=Ho(n.left,n.top,n.originX,n.originY,Sc(n),n.angle),u=Bs(l,n.originX,n.originY,{x:r*n.scaleX,y:r*n.scaleY},n.angle);return{...n,width:r,height:r,cropX:s,cropY:a,left:u.x,top:u.y}};var Ly=(n,e)=>({w:e.naturalWidth||e.width||(n.width??0),h:e.naturalHeight||e.height||(n.height??0)}),Iy=(n,e,t)=>({w:e*Math.abs((n.scaleX??1)||1),h:t*Math.abs((n.scaleY??1)||1)}),_y=(n,e,t,r,o,i)=>({cropX:Math.max(0,t/2-o/2-n),cropY:Math.max(0,r/2-i/2-e)}),Dy=(n,e,t,r,o,i)=>({clipX:t/2-o/2-n,clipY:r/2-i/2-e}),_f=(n,e,t)=>{let r=Ly(e,t),o=Iy(e,r.w,r.h),i=n.width??0,s=n.height??0,{cropX:a,cropY:l}=_y(n.clipX??0,n.clipY??0,o.w,o.h,i,s);return{left:n.left??0,top:n.top??0,angle:n.angle??0,originX:n.originX??"center",originY:n.originY??"center",flipX:n.flipX===!0,flipY:n.flipY===!0,width:i,height:s,cropX:a,cropY:l,scaleX:n.scaleX??1,scaleY:n.scaleY??1,naturalWidth:o.w,naturalHeight:o.h,cropSizeMode:"visible"}},Df=n=>{let{clipX:e,clipY:t}=Dy(n.cropX,n.cropY,n.naturalWidth,n.naturalHeight,n.width,n.height);return{left:n.left,top:n.top,width:n.width,height:n.height,cropX:n.cropX,cropY:n.cropY,clipX:e,clipY:t,scaleX:n.scaleX,scaleY:n.scaleY}};var Ff=12,Of=14,Bf=7,Fy=1,Oy=1,Wf=ee("#f6f7fa"),Hf=ee("#2f6fed"),Rc=["e","se","s","sw","w","nw","n","ne","e"],By=["tl","tr","bl","br"],Wy=["tl","tr","bl","br"],Hy=["left","right","top","bottom"],Ec=(n,e,t,r,o)=>{let i=null,s=1/0;for(let a of n){let l=e(a),u=Math.hypot(l.x-t,l.y-r);u<=o&&u<s&&(i=a,s=u)}return i},Cc=null,Pc=()=>{if(Cc)return Cc;let n=Math.ceil((Bf+2)*2),e=document.createElement("canvas");e.width=n,e.height=n;let t=e.getContext("2d");return t.beginPath(),t.arc(n/2,n/2,Bf,0,Math.PI*2),t.fillStyle="#ffffff",t.fill(),t.lineWidth=1.5,t.strokeStyle="#2f6fed",t.stroke(),Cc=e,e},sr=30,ar=7,Xo={x:28,y:16},zo={x:14,y:4},Mc=2,Xf=(n,e)=>{let t=document.createElement("canvas");t.width=n*Mc,t.height=e*Mc;let r=t.getContext("2d");return r?{canvas:t,ctx:r}:null},tt=n=>n*Mc,Ws=null,kc=()=>{if(Ws)return Ws;let n=Xf(sr,sr);if(!n)return Ws=document.createElement("canvas");let{canvas:e,ctx:t}=n;return t.translate(tt(ar),tt(ar)),t.shadowColor="rgba(12, 18, 28, 0.38)",t.shadowBlur=tt(4),t.shadowOffsetX=tt(2),t.shadowOffsetY=tt(2),t.beginPath(),t.lineWidth=tt(6),t.lineCap="round",t.strokeStyle="#dfe2e8",t.moveTo(0,tt(10)),t.lineTo(0,0),t.lineTo(tt(10),0),t.stroke(),Ws=e,e},Hs=null,Ac=()=>{if(Hs)return Hs;let n=Xf(Xo.x,Xo.y);if(!n)return Hs=document.createElement("canvas");let{canvas:e,ctx:t}=n;return t.translate(tt(zo.x),tt(zo.y)),t.shadowColor="rgba(12, 18, 28, 0.38)",t.shadowBlur=tt(4),t.shadowOffsetX=0,t.shadowOffsetY=tt(2),t.beginPath(),t.lineWidth=tt(4),t.lineCap="round",t.strokeStyle="#dfe2e8",t.moveTo(tt(-6),0),t.lineTo(tt(6),0),t.stroke(),Hs=e,e},zf=n=>{let e=Math.hypot(n[0],n[1])||1,t=Math.hypot(n[2],n[3])||1;return[n[0]/e,n[1]/e,n[2]/t,n[3]/t]},Yo=(n,e,t,r,o,i,s,a)=>{let l=r*Math.PI/180,u=Math.cos(l),c=Math.sin(l),[h,d,f,m]=zf(n),p=n[0]*e+n[2]*t+n[4],b=n[1]*e+n[3]*t+n[5],g=j([h,d,f,m,0,0],[u,c,-c,u,0,0],!0),x=(i.x-o.x/2)/s,S=(i.y-o.y/2)/s;return{matrix:[g[0],g[1],g[2],g[3],p-(g[0]*x+g[2]*S),b-(g[1]*x+g[3]*S)],dims:{x:o.x/s,y:o.y/s},color:[1,1,1,1],texture:a}},Gf=(n,e)=>{let t=!1;for(let r=0,o=e.length-1;r<e.length;o=r++){let i=e[r].x,s=e[r].y,a=e[o].x,l=e[o].y;s>n.y!=l>n.y&&n.x<(a-i)*(n.y-s)/(l-s)+i&&(t=!t)}return t},Gs=class{constructor(e){this.host=e}host;node=null;circlesVisible=!0;ratio=null;shape=null;detachKey=null;get active(){return this.node!==null}get target(){return this.node}get info(){let e=this.node;if(!e||!(e instanceof ae?e.clipImageEl:e.imageEl))return null;let t=this.liveState();return{nodeId:e.id,handle:"",ratio:this.ratio,circlesVisible:this.circlesVisible,cropX:t.cropX,cropY:t.cropY,width:t.width,height:t.height,isMask:e instanceof ae,shapeActive:!(e instanceof ae)&&this.shape!==null}}enter(e,t){if(this.node&&this.exit(),e instanceof ae){if(!this.host.document.nodes.includes(e)||e.clipDynamicKind||!e.clipImageRaw||!e.clipImageEl)return!1}else if(e instanceof ie||!e.isImageType||!e.imageEl)return!1;this.node=e,this.ratio=null,this.shape=e instanceof ae||!t?.shape?null:t.shape,this.ratio=this.shape?.aspectRatio??null;let r=Math.abs(e.raw.scaleX??1),o=Math.abs(e.raw.scaleY??1);if(this.circlesVisible=r===o,this.host.document.exitEditing(),this.host.document.setSelection([e],"update"),!(e instanceof ae)){let i=s=>{s.key==="Escape"&&this.node&&this.exit()};window.addEventListener("keydown",i),this.detachKey=()=>window.removeEventListener("keydown",i)}return this.shape&&this.writeBack(Tc(this.liveState())),this.host.requestRenderAll(),!0}exit(){if(!this.node)return;let e=this.node;this.node=null,this.ratio=null,this.shape=null,this.detachKey?.(),this.detachKey=null,this.host.document.applyTransform([e],()=>({}),"modified",{action:Le.crop}),this.host.requestRenderAll()}exitByOutsideClick(){this.exit()}setCropShape(e){let t=this.node;if(!t||t instanceof ae)return;this.ratio=e?.aspectRatio??null;let r=this.shape!==null;this.shape=e,e?this.writeBack(Tc(this.liveState())):r&&this.writeBack(this.liveState(),!0),this.host.requestRenderAll()}setAspectRatio(e){if(this.node){if(this.ratio=e,e&&e>0){let t=this.shape!==null;this.shape=null;let r=Af(this.liveState(),e);this.writeBack(r,t)}this.host.requestRenderAll()}}hitHandle(e,t){let r=this.node;if(!r)return null;let o=r.matrix,i=this.liveState(),s=(l,u)=>{let c=Q(o,l,u);return this.host.toScreen(c.x,c.y)},a=Ec(["br","bl","tr","tl"],l=>{let u=Jt[l];return s(u.x*i.width,u.y*i.height)},e,t,Ff);if(a)return a;if(!this.ratio){let l=Ec(["bottom","right","top","left"],u=>{let c=Jt[u];return s(c.x*i.width,c.y*i.height)},e,t,Ff);if(l)return l}if(this.circlesVisible){let l=Ec(["br","bl","tr","tl"],u=>{let c=Go(i,u);return s(c.x,c.y)},e,t,Of);if(l){let u=Jt[l],c=s(u.x*i.width,u.y*i.height);return Math.hypot(c.x-e,c.y-t)<=Of?l:`${l}S`}}return null}hitRect(e,t){let r=this.node;if(!r)return!1;let o=this.liveState(),i=r.matrix;if(!(r instanceof ae)){let c=["tl","tr","br","bl"].map(h=>{let d=(h==="tr"||h==="br"?.5:-.5)*o.width,f=(h==="bl"||h==="br"?.5:-.5)*o.height;return Q(i,d,f)});return Gf({x:e,y:t},c)}let s=["tl","tr","br","bl"].map(c=>{let h=(c==="tr"||c==="br"?.5:-.5)*o.width,d=(c==="bl"||c==="br"?.5:-.5)*o.height,f=Q(i,h,d);return this.host.toScreen(f.x,f.y)}),a=Math.abs(s[1].x-s[0].x)/2,l=Math.abs(s[3].y-s[0].y)/2,u=[{x:s[0].x-a,y:s[0].y-l},{x:s[1].x+a,y:s[1].y-l},{x:s[2].x+a,y:s[2].y+l},{x:s[3].x-a,y:s[3].y+l}];return Gf(this.host.toScreen(e,t),u)}applyHandle(e,t){if(!this.node)return;let o=this.liveState(),i=null;e.endsWith("S")?i=this.circlesVisible?Pf(o,e.slice(0,2),t):null:cs(e)?i=this.ratio?Mf(o,e,t,this.ratio):Cf(o,e,t):this.ratio||(i=Os(o,e,t)),i&&this.writeBack(i),this.host.requestRenderAll()}setScale(e){if(!this.node)return!1;let t=Rf(this.liveState(),e,this.shape!==null);return t?(this.writeBack(t),this.host.document.setProps(this.node,{cropScale:t.scaleX},{deferIndexRebuild:!0}),this.host.requestRenderAll(),!0):!1}moveImageBy(e){if(!this.node)return;let r=this.liveState(),{cropX:o,cropY:i}=kf(r,e);this.writeBack({...r,cropX:o,cropY:i}),this.host.requestRenderAll()}hoverCursor(e,t,r){let o=this.hitHandle(e,t);if(o){if(o.endsWith("S")&&this.node){let i=Jt[o.slice(0,2)],a=((this.node.raw.angle??0)+Math.atan2(i.y,i.x)*180/Math.PI+360)%360;return`${Rc[Math.round(a/45)]}-resize`}return"pointer"}return this.hitRect(r.x,r.y)?"move":""}buildOverlay(e){let t=this.node;if(!t||!t.imageEl)return[];let r=this.liveState(),o=t.matrix,i=[],s=(b,g)=>Q(o,b,g),a=r.width,l=r.height,u=Fy/e;for(let b of[1,2]){let g=-a/2+b*a/3,x=s(g,-l/2),S=s(g,l/2);i.push(Re(x,S,u,Wf))}for(let b of[1,2]){let g=-l/2+b*l/3,x=s(-a/2,g),S=s(a/2,g);i.push(Re(x,S,u,Wf))}let c=Oy/e,h=["tl","tr","br","bl"].map(b=>s(Go(r,b).x,Go(r,b).y));for(let b=0;b<4;b++)i.push(Re(h[b],h[(b+1)%4],c,Hf));let d=1.5/e,f=["tl","tr","br","bl"].map(b=>s(Jt[b].x*a,Jt[b].y*l));for(let b=0;b<4;b++)i.push(Re(f[b],f[(b+1)%4],d,Hf));if(this.circlesVisible){let b=Pc(),[g,x,S,w]=zf(o),y=b.width/e;for(let v of Wy){let R=Go(r,v);i.push({matrix:[g,x,S,w,o[0]*R.x+o[2]*R.y+o[4],o[1]*R.x+o[3]*R.y+o[5]],dims:{x:y,y},color:[1,1,1,1],texture:b})}}if(!this.ratio){let b={top:0,right:90,bottom:180,left:270},g=Ac();for(let x of Hy){let S=Jt[x];i.push(Yo(o,S.x*a,S.y*l,b[x],Xo,zo,e,g))}}let m={tl:0,tr:90,br:180,bl:270},p=kc();for(let b of By){let g=Jt[b];i.push(Yo(o,g.x*a,g.y*l,m[b],{x:sr,y:sr},{x:ar,y:ar},e,p))}return i}dispose(){this.detachKey?.(),this.detachKey=null,this.node=null,this.shape=null}liveState(){let e=this.node;if(e instanceof ae)return _f(e.raw,e.clipImageRaw,e.clipImageEl);let t=e.imageEl;return Nf(e.raw,t.naturalWidth,t.naturalHeight)}writeBack(e,t=!1){let r=this.node,o={...r instanceof ae?Df(e):Lf(e)};r instanceof ae||(this.shape?o.clipPath=If(this.shape,e.width,e.height):t&&(o.clipPath=void 0)),this.host.document.setProps(r,o,{deferIndexRebuild:!0})}};var Yf={ml:{left:!0},mr:{right:!0},mt:{top:!0},mb:{bottom:!0},tl:{left:!0,top:!0},tr:{right:!0,top:!0},bl:{left:!0,bottom:!0},br:{right:!0,bottom:!0}},Uf=(n,e,t)=>{let r=n.expandScale??1.5;return{width:n.expandWidth??t.width*r,height:n.expandHeight??t.height*r,centerX:n.expandRectCenterX??e.x,centerY:n.expandRectCenterY??e.y}},$f=(n,e,t,r,o)=>{let i=t*Math.PI/180,s=Math.cos(i),a=Math.sin(i),{centerX:l,centerY:u}=n,c=n.width/2,h=n.height/2,d=r.x-l,f=r.y-u,m=d*s+f*a,p=-d*a+f*s,b=-c,g=c,x=-h,S=h;o.left&&(b=Math.min(m,g-1)),o.right&&(g=Math.max(m,b+1)),o.top&&(x=Math.min(p,S-1)),o.bottom&&(S=Math.max(p,x+1));let w=o.right,y=o.left,v=o.bottom,R=o.top,P=e.centerX-l,T=e.centerY-u,C=P*s+T*a,E=-P*a+T*s,M=C-e.scaledWidth/2,k=C+e.scaledWidth/2,A=E-e.scaledHeight/2,O=E+e.scaledHeight/2;!w&&M<b&&(b=M),!y&&k>g&&(g=k),!v&&A<x&&(x=A),!R&&O>S&&(S=O);let F=(b+g)/2,W=(x+S)/2;return{width:g-b,height:S-x,centerX:l+F*s-W*a,centerY:u+F*a+W*s}},Nc=(n,e,t,r)=>{let o=t*Math.PI/180,i=Math.cos(o),s=Math.sin(o),a=r.width/e.scaledWidth,l=r.height/e.scaledHeight,u=e.centerX-n.centerX,c=e.centerY-n.centerY,h=u*i+c*s,d=-u*s+c*i,f=e.scaledWidth/2,m=e.scaledHeight/2,p=n.width/2,b=n.height/2,g=Math.max(0,h-f+p),x=Math.max(0,p-h-f),S=Math.max(0,d-m+b),w=Math.max(0,b-d-m);return{left:Math.floor(g*a),right:Math.floor(x*a),top:Math.floor(S*l),bottom:Math.floor(w*l)}},jf=(n,e,t,r)=>{let o=t*Math.PI/180,i=Math.cos(o),s=Math.sin(o),a=r.x-n.centerX,l=r.y-n.centerY,u=a*i+l*s,c=-a*s+l*i,h=Math.max(0,n.width/2-e.scaledWidth/2),d=Math.max(0,n.height/2-e.scaledHeight/2);return u=Math.max(-h,Math.min(h,u)),c=Math.max(-d,Math.min(d,c)),{x:n.centerX+u*i-c*s,y:n.centerY+u*s+c*i}},An={tl:{x:-.5,y:-.5},tr:{x:.5,y:-.5},bl:{x:-.5,y:.5},br:{x:.5,y:.5},ml:{x:-.5,y:0},mr:{x:.5,y:0},mt:{x:0,y:-.5},mb:{x:0,y:.5}},Gy={tl:{x:-1,y:-1},tr:{x:1,y:-1},bl:{x:-1,y:1},br:{x:1,y:1}},Vf=(n,e,t,r)=>{let o=Gy[t],i=n.centerX-o.x*(n.scaledWidth/2),s=n.centerY-o.y*(n.scaledHeight/2),a=r.x-i,l=r.y-s,u=Math.hypot(n.scaledWidth,n.scaledHeight),c=u>0?Math.hypot(a,l)/u:1,h=Math.max(Math.abs(n.scaleX),Math.abs(n.scaleY));c=Math.max(.1/h,Math.min(5/h,c));let d=n.scaledWidth*c,f=n.scaledHeight*c,m=i+o.x*(d/2),p=s+o.y*(f/2),b=Math.min(i,i+o.x*d),g=Math.min(s,s+o.y*f),x=b+d,S=g+f;return b<e.centerX-e.width/2||g<e.centerY-e.height/2||x>e.centerX+e.width/2||S>e.centerY+e.height/2?null:{scaleX:n.scaleX*c,scaleY:n.scaleY*c,centerX:m,centerY:p}};var Uo=n=>n*Math.PI/180,Xy=12,zy=14,Yy=1,Uy=(()=>{let n=ee("#3788ff");return[n[0],n[1],n[2],.5]})(),$y=ee("#3788ff"),Lc=["tl","tr","bl","br"],jy={tl:0,tr:90,br:180,bl:270},Vy={mt:0,mr:90,mb:180,ml:270},qy=(n,e)=>{let t=!1;for(let r=0,o=e.length-1;r<e.length;o=r++){let i=e[r].x,s=e[r].y,a=e[o].x,l=e[o].y;s>n.y!=l>n.y&&n.x<(a-i)*(n.y-s)/(l-s)+i&&(t=!t)}return t},Xs=class{constructor(e){this.host=e}host;node=null;detachKey=null;get active(){return this.node!==null}get target(){return this.node}get info(){let e=this.node;if(!e)return null;let t=this.view();return{nodeId:e.id,width:t.rect.width,height:t.rect.height,centerX:t.rect.centerX,centerY:t.rect.centerY,angle:t.angle,offsets:t.offsets}}enter(e){if(this.node&&this.exit(),!(e instanceof ie?!1:(e.isImageType||e instanceof ae)&&!!e.imageEl&&!(e instanceof ae&&e.clipDynamicKind)))return!1;this.node=e,this.host.document.exitEditing(),this.host.document.setSelection([e],"update");let r=e.raw,o=Math.abs(r.scaleX??1),i=Math.abs(r.scaleY??1),s=r.expandScale??1.5,a=e.center,l={};r.expandRectCenterX===void 0&&(l.expandRectCenterX=a.x),r.expandRectCenterY===void 0&&(l.expandRectCenterY=a.y),r.expandWidth===void 0&&(l.expandWidth=e.dims.x*o*s),r.expandHeight===void 0&&(l.expandHeight=e.dims.y*i*s),Object.keys(l).length>0&&this.host.document.setProps(e,l);let u=c=>{c.key==="Escape"&&this.node&&this.exit()};return window.addEventListener("keydown",u),this.detachKey=()=>window.removeEventListener("keydown",u),this.host.requestRenderAll(),!0}exit(){let e=this.node;if(!e)return;this.node=null,this.detachKey?.(),this.detachKey=null;let t=e.imageEl;if(t){let r=this.expandViewOf(e,t),o=Nc(r.rect,r.img,r.angle,{width:t.naturalWidth,height:t.naturalHeight});this.host.document.setProps(e,{expandLeftOffset:o.left,expandRightOffset:o.right,expandTopOffset:o.top,expandBottomOffset:o.bottom})}this.host.document.applyTransform([e],()=>({}),"modified",{action:Le.crop}),this.host.requestRenderAll()}exitByOutsideClick(){let e=this.node;this.exit(),e&&this.host.document.selection.includes(e)&&this.host.document.clearSelection()}async applyResult(e,t,r){this.host.document.setProps(e,{src:t});let o=await this.host.reloadImageElement(e);if(!o||!o.naturalWidth||!o.naturalHeight)return!1;let i=r.width/o.naturalWidth,s=r.height/o.naturalHeight,a=ge({...e.raw,width:o.naturalWidth,height:o.naturalHeight,scaleX:i,scaleY:s},{x:r.centerX,y:r.centerY});return this.host.document.setProps(e,{width:o.naturalWidth,height:o.naturalHeight,scaleX:i,scaleY:s,left:a.x,top:a.y}),this.host.document.applyTransform([e],()=>({}),"modified"),this.host.requestRenderAll(),!0}hitHandle(e,t){let r=this.view(),o=Uo(r.angle),i=Math.cos(o),s=Math.sin(o);for(let a of Object.keys(An)){let l=An[a],u=l.x*r.rect.width,c=l.y*r.rect.height,h=r.rect.centerX+u*i-c*s,d=r.rect.centerY+u*s+c*i,f=this.host.toScreen(h,d);if(Math.hypot(f.x-e,f.y-t)<=Xy)return a}for(let a of Lc){let l=this.imageCornerOf(a),u=this.host.toScreen(l.x,l.y);if(Math.hypot(u.x-e,u.y-t)<=zy)return`${a}S`}return null}hitRect(e,t){let r=this.view(),o=Uo(r.angle),i=Math.cos(o),s=Math.sin(o),a=["tl","tr","br","bl"].map(l=>{let u=An[l],c=u.x*r.rect.width,h=u.y*r.rect.height;return{x:r.rect.centerX+c*i-h*s,y:r.rect.centerY+c*s+h*i}});return qy({x:e,y:t},a)}applyHandle(e,t){let r=this.node;if(!r)return;if(e.endsWith("S")){let s=this.view(),a=r.raw,l=Vf({...s.img,scaleX:a.scaleX??1,scaleY:a.scaleY??1},s.rect,e.slice(0,2),t);if(l){let u=ge({...r.raw,width:r.dims.x,height:r.dims.y,scaleX:l.scaleX,scaleY:l.scaleY},{x:l.centerX,y:l.centerY});this.host.document.setProps(r,{scaleX:l.scaleX,scaleY:l.scaleY,left:u.x,top:u.y},{deferIndexRebuild:!0})}this.host.requestRenderAll();return}let o=this.view(),i=$f(o.rect,o.img,o.angle,t,Yf[e]);this.host.document.setProps(r,{expandWidth:i.width,expandHeight:i.height,expandRectCenterX:i.centerX,expandRectCenterY:i.centerY},{deferIndexRebuild:!0}),this.host.requestRenderAll()}moveImageBy(e){let t=this.node;if(!t)return;let r=this.view(),o=jf(r.rect,r.img,r.angle,{x:r.img.centerX+e.x,y:r.img.centerY+e.y}),i=ge({...t.raw,width:t.dims.x,height:t.dims.y},o);this.host.document.setProps(t,{left:i.x,top:i.y},{deferIndexRebuild:!0}),this.host.requestRenderAll()}hoverCursor(e,t,r,o){let i=this.hitHandle(e,t);if(i){if(i.endsWith("S")&&this.node){let s=An[i.slice(0,2)],l=((this.node.raw.angle??0)+Math.atan2(s.y,s.x)*180/Math.PI+360)%360;return`${Rc[Math.round(l/45)]}-resize`}return"pointer"}return this.hitRect(r,o)?"move":""}buildUnderlay(){let e=this.view(),t=Uo(e.angle);return[{matrix:[Math.cos(t),Math.sin(t),-Math.sin(t),Math.cos(t),e.rect.centerX,e.rect.centerY],dims:{x:e.rect.width,y:e.rect.height},color:Uy}]}buildOverlay(e){let t=this.view(),r=[],o=Uo(t.angle),i=[Math.cos(o),Math.sin(o),-Math.sin(o),Math.cos(o),t.rect.centerX,t.rect.centerY],s=p=>{let b=An[p];return Q(i,b.x*t.rect.width,b.y*t.rect.height)},a=Yy/e,l=["tl","tr","br","bl"].map(s);for(let p=0;p<4;p++)r.push(Re(l[p],l[(p+1)%4],a,$y));let u=Pc(),c=u.width/e,h=Math.cos(o),d=Math.sin(o);for(let p of Lc){let b=this.imageCornerOf(p);r.push({matrix:[h,d,-d,h,b.x,b.y],dims:{x:c,y:c},color:[1,1,1,1],texture:u})}let f=Ac();for(let p of["ml","mr","mt","mb"]){let b=An[p];r.push(Yo(i,b.x*t.rect.width,b.y*t.rect.height,Vy[p],Xo,zo,e,f))}let m=kc();for(let p of Lc){let b=An[p];r.push(Yo(i,b.x*t.rect.width,b.y*t.rect.height,jy[p],{x:sr,y:sr},{x:ar,y:ar},e,m))}return r}dispose(){this.detachKey?.(),this.detachKey=null,this.node=null}view(){let e=this.node;return this.expandViewOf(e,e.imageEl)}imageCornerOf(e){let t=this.view(),r=Uo(t.angle),o=Math.cos(r),i=Math.sin(r),s=(e==="tr"||e==="br"?.5:-.5)*t.img.scaledWidth,a=(e==="bl"||e==="br"?.5:-.5)*t.img.scaledHeight;return{x:t.img.centerX+s*o-a*i,y:t.img.centerY+s*i+a*o}}expandViewOf(e,t){let r=e.raw,o=Math.abs(r.scaleX??1),i=Math.abs(r.scaleY??1),s=e.center,a=e.dims.x*o,l=e.dims.y*i,u={centerX:s.x,centerY:s.y,scaledWidth:a,scaledHeight:l},c=Uf(r,s,{width:a,height:l}),h=r.angle??0,d=t?Nc(c,u,h,{width:t.naturalWidth,height:t.naturalHeight}):null;return{rect:c,img:u,angle:h,offsets:d}}};var Ky=8,Qy=6;var cr=n=>{if(!n)return null;let e=Fe(n);return e?{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}:null},qf=(n,e)=>{let t=n[e],r=String(t[0]).toUpperCase();if(r==="M"||r==="L")return{x:t[1],y:t[2]};if(r==="C")return{x:t[5],y:t[6]};if(r==="Q")return{x:t[3],y:t[4]};for(let o=e;o>=0;o--)if(String(n[o][0]).toUpperCase()==="M")return{x:n[o][1],y:n[o][2]};return{x:0,y:0}},lr=(n,e)=>{for(let t=e-1;t>=0;t--){let r=String(n[t][0]).toUpperCase();if(r==="M"||r==="L")return{x:n[t][1],y:n[t][2]};if(r==="C")return{x:n[t][5],y:n[t][6]};if(r==="Q")return{x:n[t][3],y:n[t][4]};if(r==="Z"){for(let o=t;o>=0;o--)if(String(n[o][0]).toUpperCase()==="M")return{x:n[o][1],y:n[o][2]}}}return{x:0,y:0}},Zy=n=>n==="C"?5:n==="Q"?3:1,ut=(n,e,t)=>({x:n[e]-t.x,y:n[e+1]-t.y}),Ic=(n,e)=>{let t=[],r=[];return n.forEach((o,i)=>{let s=String(o[0]);if(s!=="Z"&&t.push({key:`c_${i}_${s}`,kind:"anchor",commandIndex:i,pointIndex:o.length-2,local:ut(o,o.length-2,e)}),s==="C"){let a=ut(o,1,e),l=ut(o,3,e);t.push({key:`c_${i}_C_CP_1`,kind:"handle",commandIndex:i,pointIndex:1,local:a}),t.push({key:`c_${i}_C_CP_2`,kind:"handle",commandIndex:i,pointIndex:3,local:l});let u=i>0?String(n[i-1][0]).toUpperCase():"M",c=i>0?ut(n[i-1],Zy(u),e):a;r.push({from:a,to:c},{from:l,to:ut(o,5,e)})}else if(s==="Q"){let a=ut(o,1,e);t.push({key:`c_${i}_Q_CP_1`,kind:"handle",commandIndex:i,pointIndex:1,local:a}),r.push({from:a,to:ut(o,3,e)})}}),{handles:t,connections:r}},Zf=(n,e)=>n.map((t,r)=>({key:`p_${r}`,kind:"point",commandIndex:r,pointIndex:r,local:{x:t.x-e.x,y:t.y-e.y}})),zs=n=>{if(!n.length)return null;let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)e>i.x&&(e=i.x),t>i.y&&(t=i.y),r<i.x&&(r=i.x),o<i.y&&(o=i.y);return{x:(e+r)/2,y:(t+o)/2}},Jy=(n,e,t)=>{let r=t.x-e.x,o=t.y-e.y,i=r*r+o*o;if(!i)return{distance:Math.hypot(n.x-e.x,n.y-e.y),t:0,point:{...e},length:0};let s=Math.max(0,Math.min(1,((n.x-e.x)*r+(n.y-e.y)*o)/i)),a={x:e.x+r*s,y:e.y+o*s};return{distance:Math.hypot(n.x-a.x,n.y-a.y),t:s,point:a,length:Math.sqrt(i)}},e0=(n,e,t=100)=>{let r=1/t,o=0,i=Number.POSITIVE_INFINITY,s=0,a=null;for(let h=0;h<=t;h++){let d=h*r,f=e(d);a&&(s+=Math.hypot(f.x-a.x,f.y-a.y)),a=f;let m=(f.x-n.x)**2+(f.y-n.y)**2;m<i&&(i=m,o=d)}let l=Math.max(0,o-r),u=Math.min(1,o+r),c=(u-l)/20;for(let h=l;h<=u;h+=c){let d=e(h),f=(d.x-n.x)**2+(d.y-n.y)**2;f<i&&(i=f,o=h)}return{distance:Math.sqrt(i),t:o,point:e(o),length:s}},Kf=(n,e,t,r,o)=>{let i=1-o,s=i*i*i,a=3*i*i*o,l=3*i*o*o,u=o*o*o;return{x:s*n.x+a*e.x+l*t.x+u*r.x,y:s*n.y+a*e.y+l*t.y+u*r.y}},Qf=(n,e,t,r)=>{let o=1-r,i=o*o,s=2*o*r,a=r*r;return{x:i*n.x+s*e.x+a*t.x,y:i*n.y+s*e.y+a*t.y}},t0=(n,e,t)=>({x:n.x+(e.x-n.x)*t,y:n.y+(e.y-n.y)*t}),Jf=(n,e,t,r,o)=>{let i=Ky/o,s=Qy/o,a=h=>Q(r,h.x,h.y),l=(h,d)=>a(ut(h,d,e)),u,c=Number.POSITIVE_INFINITY;return n.forEach((h,d)=>{let f=String(h[0]).toUpperCase();if(f==="C"||f==="Q"){let v={x:lr(n,d).x-e.x,y:lr(n,d).y-e.y},R=a(v),P=l(h,1),T=f==="C"?ut(h,5,e):ut(h,3,e),C=a(T),M=e0(t,f==="C"?F=>Kf(R,P,l(h,3),C,F):F=>Qf(R,P,C,F));if(M.distance>i||M.length<=s*2||M.distance>=c)return;let k=s/M.length;if(M.t<=k||M.t>=1-k)return;let A=lr(n,d),O=f==="C"?(()=>{let F={x:A.x-e.x,y:A.y-e.y},W=ut(h,1,e),z=ut(h,3,e),_={x:h[5]-e.x,y:h[6]-e.y};return Kf(F,W,z,_,M.t)})():(()=>{let F={x:A.x-e.x,y:A.y-e.y},W=ut(h,1,e),z={x:h[3]-e.x,y:h[4]-e.y};return Qf(F,W,z,M.t)})();c=M.distance,u={commandIndex:d,commandType:f,t:M.t,local:O,scene:M.point};return}if(f!=="L"&&f!=="Z")return;let m=f==="L"?lr(n,d):qf(n,Math.max(0,d-1)),p=qf(n,d),b=a({x:m.x-e.x,y:m.y-e.y}),g=a({x:p.x-e.x,y:p.y-e.y}),x=Jy(t,b,g);if(x.distance>i||x.length<=s*2||x.distance>=c)return;let S=s/x.length;if(x.t<=S||x.t>=1-S)return;c=x.distance;let w={x:m.x-e.x,y:m.y-e.y},y={x:p.x-e.x,y:p.y-e.y};u={commandIndex:d,commandType:f,t:x.t,local:t0(w,y,x.t),scene:x.point}}),u},em=(n,e,t,r,o)=>n.map((i,s)=>{if(s!==e)return i;let a=[...i];return a[t]=r.x+o.x,a[t+1]=r.y+o.y,a}),tm=(n,e,t,r)=>n.map((o,i)=>i===e?{x:t.x+r.x,y:t.y+r.y}:o),nm=(n,e,t)=>{let r=n.map(a=>[...a]),o=t.local.x+e.x,i=t.local.y+e.y,s=t.commandIndex;if(t.commandType==="L"){let a=r[s],l=a[1],u=a[2];return r[s]=["L",o,i],r.splice(s+1,0,["L",l,u]),r}if(t.commandType==="C"){let a=r[s],l=lr(n,s),u=t.t,c=a[1],h=a[2],d=a[3],f=a[4],m=a[5],p=a[6],b=l.x+(c-l.x)*u,g=l.y+(h-l.y)*u,x=c+(d-c)*u,S=h+(f-h)*u,w=d+(m-d)*u,y=f+(p-f)*u,v=b+(x-b)*u,R=g+(S-g)*u,P=x+(w-x)*u,T=S+(y-S)*u;return r[s]=["C",b,g,v,R,o,i],r.splice(s+1,0,["C",P,T,w,y,m,p]),r}if(t.commandType==="Q"){let a=r[s],l=lr(n,s),u=t.t,c=a[1],h=a[2],d=a[3],f=a[4],m=l.x+(c-l.x)*u,p=l.y+(h-l.y)*u,b=c+(d-c)*u,g=h+(f-h)*u;return r[s]=["Q",m,p,o,i],r.splice(s+1,0,["Q",b,g,d,f]),r}return t.commandType==="Z"?(r.splice(s,1,["L",o,i],["Z"]),r):null},rm=(n,e,t)=>{if(e<0||e>=n.length)return null;let r=n[e],o=String(r[0]).toUpperCase();if(o==="M"||o==="Z")return null;let i=o==="C"||o==="Q",s=t.toUpperCase()==="C";if(i===s)return{commands:n,changed:!1};let a,l;o==="L"?(a=r[1],l=r[2]):o==="C"?(a=r[5],l=r[6]):(a=r[3],l=r[4]);let u=lr(n,e),c=n.map(h=>[...h]);return c[e]=s?["C",u.x+(a-u.x)/3,u.y+(l-u.y)/3,a-(a-u.x)/3,l-(l-u.y)/3,a,l]:["L",a,l],{commands:c,changed:!0}},_c=(n,e)=>{let t=n?.[e]?.[0];return t&&["C","Q","S","T","A"].includes(String(t).toUpperCase())?"smooth":"line"},om=(n,e,t,r)=>{if(!t)return n;let o=t.x-e.x,i=t.y-e.y;return{x:n.x+r[0]*o+r[2]*i,y:n.y+r[1]*o+r[3]*i}};var n0=12,$o=ee("#2254f4"),im=ee("#ffffff"),sm=7,am=5,r0=1,Dc=null,o0=()=>{if(Dc)return Dc;let n=Math.ceil((am+2)*2),e=document.createElement("canvas");e.width=n,e.height=n;let t=e.getContext("2d");return t.beginPath(),t.arc(n/2,n/2,am,0,Math.PI*2),t.fillStyle="#ffffff",t.fill(),t.lineWidth=1.5,t.strokeStyle="#2254f4",t.stroke(),Dc=e,e},Bt=n=>{let e=n.typeKey;return e===L.PATH?"path":e===L.POLYGON||e===L.POLYLINE?"poly":e===L.LINE?"line":null},Ys=class{constructor(e){this.host=e}host;node=null;kind=null;activeAnchorKey;insertCandidate;detachKey=null;get active(){return this.node!==null}get target(){return this.node}get info(){let e=this.node,t=this.kind;if(!e||!t)return null;let r=e.matrix,o=this.currentHandles().map(i=>{let s=Q(r,i.local.x,i.local.y);return{key:i.key,kind:i.kind,x:s.x,y:s.y}});return{nodeId:e.id,kind:t,anchors:o,activeAnchorKey:this.activeAnchorKey,activeAnchorIndex:this.activeAnchorIndex(),insertCandidate:this.insertCandidate?{commandIndex:this.insertCandidate.commandIndex,commandType:this.insertCandidate.commandType,x:this.insertCandidate.scene.x,y:this.insertCandidate.scene.y}:void 0}}enter(e){this.node&&this.exit();let t=Bt(e);if(!t||t==="path"&&!Ce(e.raw.path)||t==="poly"&&!Array.isArray(e.raw.points)||t==="line"&&!(e instanceof Lr))return!1;this.node=e,this.kind=t,this.activeAnchorKey=void 0,this.insertCandidate=void 0,this.host.document.exitEditing(),this.host.document.setSelection([e],"update");let r=o=>{o.key==="Escape"&&this.node&&this.exit()};return window.addEventListener("keydown",r),this.detachKey=()=>window.removeEventListener("keydown",r),this.host.requestRenderAll(),!0}exit(){this.node&&(this.node=null,this.kind=null,this.activeAnchorKey=void 0,this.insertCandidate=void 0,this.detachKey?.(),this.detachKey=null,this.host.requestRenderAll())}exitByOutsideClick(){this.exit()}hitAnchor(e,t){let r=this.node;if(!r)return null;let o=r.matrix,i=null,s=n0;for(let a of this.currentHandles()){let l=Q(o,a.local.x,a.local.y),u=this.host.toScreen(l.x,l.y),c=Math.hypot(u.x-e,u.y-t);c<=s&&(s=c,i=a.key)}return i}hitBody(e,t){let r=this.node;return r?r.containsPoint(e,t):!1}findInsertCandidate(e,t){let r=this.node;if(!r||this.kind!=="path")return null;let o=Ce(r.raw.path),i=cr(o);return!o||!i?null:Jf(o,i,{x:e,y:t},r.matrix,this.host.zoom)??null}startAnchorDrag(e){return!this.node||!this.currentHandles().some(r=>r.key===e)?!1:(this.captureDragBefore(),this.setActiveAnchor(e),!0)}applyAnchorDrag(e,t){let r=this.node,o=this.kind;if(!r||!o)return;let i=this.currentHandles().find(l=>l.key===e);if(!i)return;let s=r.matrix,a=Q(ve(s),t.x,t.y);if(o==="path"){let l=Ce(r.raw.path),u=cr(l);if(!l||!u)return;let c=em(l,i.commandIndex,i.pointIndex,a,u);this.writeBackWithCompensation(r,c,u,cr(c),Fe(c))}else if(o==="poly"){let l=r.raw.points,u=zs(l);if(!u)return;let c=tm(l,i.commandIndex,a,u),h=1/0,d=1/0,f=-1/0,m=-1/0;for(let p of c)h>p.x&&(h=p.x),d>p.y&&(d=p.y),f<p.x&&(f=p.x),m<p.y&&(m=p.y);this.writeBackWithCompensation(r,c,u,zs(c),{left:h,top:d,right:f,bottom:m})}else{let l=i.commandIndex===0?{x1:a.x,y1:a.y}:{x2:a.x,y2:a.y},u=Number(l.x1??r.raw.x1),c=Number(l.y1??r.raw.y1),h=Number(l.x2??r.raw.x2),d=Number(l.y2??r.raw.y2),f=ge({...r.raw,width:Math.abs(h-u),height:Math.abs(d-c)},r.center);this.host.document.setProps(r,{...l,left:f.x,top:f.y},{deferIndexRebuild:!0})}this.host.requestRenderAll()}moveBodyBy(e){let t=this.node;t&&(this.captureDragBefore(),this.host.document.setProps(t,{left:(t.raw.left??0)+e.x,top:(t.raw.top??0)+e.y},{deferIndexRebuild:!0}),this.host.requestRenderAll())}captureDragBefore(){this._dragBefore??=this.node?this.node.toObject():null}_dragBefore=null;commit(){let e=this.node;if(!e)return;let t=this._dragBefore;this._dragBefore=null,this.host.document.applyTransform([e],()=>({}),"modified",t?{before:new Map([[e,t]])}:void 0)}insertAnchor(e){let t=this.node;if(!t||this.kind!=="path")return null;let r=Ce(t.raw.path),o=cr(r);if(!r||!o)return null;let i=nm(r,o,e);if(!i)return null;let s=t.toObject();this.host.document.setProps(t,{path:i},{deferIndexRebuild:!0}),this.host.document.applyTransform([t],()=>({}),"modified",{before:new Map([[t,s]])});let a=e.commandType==="Z"?"L":e.commandType,l=`c_${e.commandIndex}_${a}`;return this.insertCandidate=void 0,this.setActiveAnchor(l),this.host.requestRenderAll(),l}setAnchorType(e,t){let r=this.node;if(!r||this.kind!=="path")return!1;let o=Ce(r.raw.path);if(!o)return!1;let i=rm(o,e,t);if(!i)return!1;if(i.changed){let s=r.toObject();this.host.document.setProps(r,{path:i.commands},{deferIndexRebuild:!0}),this.host.document.applyTransform([r],()=>({}),"modified",{before:new Map([[r,s]])})}return this.setActiveAnchor(`c_${e}_${String(i.commands[e][0])}`),this.host.requestRenderAll(),i.changed}setActiveAnchor(e){if(this.activeAnchorKey===e)return;this.activeAnchorKey=e;let t=this.node;t&&this.host.document.events.fire("path:active-anchor-change",t,e),this.host.requestRenderAll()}resetAnchorStyles(){this.activeAnchorKey!==void 0&&(this.activeAnchorKey=void 0,this.host.requestRenderAll())}activeAnchorIndex(){let e=this.activeAnchorKey;if(e){if(e.startsWith("c_")){let t=e.match(/^c_(\d+)_/),r=t?Number(t[1]):NaN;return Number.isFinite(r)?r:void 0}if(e.startsWith("p_"))return Number(e.slice(2));if(e==="e0"||e==="e1")return Number(e[1])}}hoverCursor(e,t,r){let o=this.hitAnchor(e,t);if(o)return o.includes("_CP_")?"crosshair":"default";let i=this.findInsertCandidate(r.x,r.y);return i?(this.updateInsertCandidate(i),"copy"):(this.updateInsertCandidate(void 0),this.hitBody(r.x,r.y)?"move":"")}updateInsertCandidate(e){let t=this.insertCandidate;t&&e&&t.commandIndex===e.commandIndex&&t.commandType===e.commandType&&Math.abs(t.scene.x-e.scene.x)<.1&&Math.abs(t.scene.y-e.scene.y)<.1||!t&&!e||(this.insertCandidate=e,this.host.requestRenderAll())}buildOverlay(e){let t=this.node,r=this.kind;if(!t||!r)return[];let o=t.matrix,i=[...Pn(t.aCoords,e)],s=a=>Q(o,a.x,a.y);if(r==="path"){let a=Ce(t.raw.path),l=cr(a);if(!a||!l)return i;let{handles:u,connections:c}=Ic(a,l),h=r0/e;for(let p of c)i.push(Re(s(p.from),s(p.to),h,$o));let d=sm/e,f=o0(),m=f.width/2*2*(1/e);for(let p of u){let b=s(p.local);if(p.kind==="handle")i.push({matrix:[1,0,0,1,b.x,b.y],dims:{x:m,y:m},color:[1,1,1,1],texture:f});else{let g=p.key===this.activeAnchorKey;i.push({matrix:[1,0,0,1,b.x,b.y],dims:{x:d,y:d},color:$o}),i.push({matrix:[1,0,0,1,b.x,b.y],dims:{x:d-2/e,y:d-2/e},color:g?$o:im})}}this.insertCandidate&&i.push({matrix:[1,0,0,1,this.insertCandidate.scene.x,this.insertCandidate.scene.y],dims:{x:m,y:m},color:[1,1,1,1],texture:f})}else{let a=sm/e;for(let l of this.currentHandles()){let u=s(l.local),c=l.key===this.activeAnchorKey;i.push({matrix:[1,0,0,1,u.x,u.y],dims:{x:a,y:a},color:$o}),i.push({matrix:[1,0,0,1,u.x,u.y],dims:{x:a-2/e,y:a-2/e},color:c?$o:im})}}return i}dispose(){this.detachKey?.(),this.detachKey=null,this.node=null,this.kind=null}currentHandles(){let e=this.node,t=this.kind;if(!e||!t)return[];if(t==="path"){let a=Ce(e.raw.path),l=cr(a);return!a||!l?[]:Ic(a,l).handles}if(t==="poly"){let a=e.raw.points,l=zs(a);return!Array.isArray(a)||!l?[]:Zf(a,l)}let r=Number(e.raw.x1),o=Number(e.raw.y1),i=Number(e.raw.x2),s=Number(e.raw.y2);return[r,o,i,s].every(Number.isFinite)?[{key:"e0",kind:"endpoint",commandIndex:0,pointIndex:0,local:{x:r,y:o}},{key:"e1",kind:"endpoint",commandIndex:1,pointIndex:1,local:{x:i,y:s}}]:[]}writeBackWithCompensation(e,t,r,o,i){if(!i)return;let s=e.ownMatrix,a=om(e.center,r,o,[s[0],s[1],s[2],s[3]]),l=ge({...e.raw,width:i.right-i.left,height:i.bottom-i.top},a),u=this.kind==="path"?{path:t}:{points:t};this.host.document.setProps(e,{...u,left:l.x,top:l.y},{deferIndexRebuild:!0})}};import{Warpvas as i0}from"warpvas";var lm=12,s0=5,a0=4,l0=1,cm=3,um=2e3,hm=10,c0=[.2,.2,.2,.6],u0=[.11,.35,.96,1],h0=[1,1,1,.9],Us=class{host;warp=null;node=null;beforeRaw=null;originalSrc=null;undoStack=[];redoStack=[];previewCanvas=null;previewVersion=0;renderedVersion=-1;coreSize={w:0,h:0};displayScale={x:1,y:1};coreAnchor={x:0,y:0};renderCanvas=null;constructor(e){this.host=e}get document(){return this.host.document}get zoom(){return this.host.zoom}get textures(){return this.host.textures}toScreen(e,t){return this.host.toScreen(e,t)}requestRenderAll(){this.host.requestRenderAll()}reloadNodeImage(e){return this.host.reloadNodeImage(e)}get active(){return!!this.warp}get target(){return this.node}get debugAnchors(){if(!this.warp||!this.node)return[];let e=[],t=this.currentBounds();for(let r=0;r<t.length;r++)for(let o=0;o<t[r].length;o++){let i=t[r][o];for(let s of Fc){let a=i[s];a&&a.forEach((l,u)=>{let c=this.toScene(l);e.push({row:r,col:o,dir:s,i:u,srcX:Math.round(l.x),srcY:Math.round(l.y),sceneX:Math.round(c.x),sceneY:Math.round(c.y)})})}}return e}get debugPreviewInfo(){if(!this.previewCanvas)return null;let e=this.previewCanvas;e.__probeId===void 0&&(e.__probeId=Math.random());let t=this.warp?this.warp.getBoundingBoxInfo():null;return{canvasId:e.__probeId,width:e.width,height:e.height,version:this.previewVersion,box:t,dataURL:e.width*e.height<=4e5?e.toDataURL("image/png"):void 0}}get debugBoundsSample(){return!this.warp||!this.coreSize.w?null:{region:this.currentBounds()[0]?.[0]??null,natural:{w:this.coreSize.w,h:this.coreSize.h}}}async enter(e,t){if(this.warp&&this.cancel(),!e.imageEl||e.cropRect||e instanceof ie||!e.imageEl.naturalWidth||!e.imageEl.naturalHeight)return!1;let r=e.raw;this.originalSrc=r.warpOriginalSrc??r.src??null;let o=e.imageEl,i=r.warpOriginalSrc,s=o,a=!1;if(i)try{let f=await this.host.loadImage(i,r.crossOrigin??void 0);f?.naturalWidth&&(s=f,a=!0)}catch{}let l=new i0(s,t?.gridRows??cm,t?.gridCols??cm);l.setInputLimitSize({width:um,height:um}),this.renderCanvas=document.createElement("canvas"),l.setRenderingCanvas(this.renderCanvas);let u=s===o?o:s;this.coreSize={w:u.naturalWidth*l.scale.x,h:u.naturalHeight*l.scale.y};let c=r.warpDisplayScale,h=r.warpCoreAnchor;a&&c&&typeof c.x=="number"&&h&&typeof h.x=="number"?(this.displayScale={x:c.x,y:c.y??c.x},this.coreAnchor={x:h.x,y:h.y??h.x}):(this.displayScale={x:e.dims.x/this.coreSize.w,y:e.dims.y/this.coreSize.h},this.coreAnchor={x:this.coreSize.w/2,y:this.coreSize.h/2});let d=a?r.warpvasState:void 0;if(d&&Array.isArray(d.splitPoints))try{l.setWarpState(d.splitPoints,d.regionBounds??null)}catch{}return this.node=e,this.warp=l,this.beforeRaw=e.toObject(),this.undoStack=[this.snapshot()],this.redoStack=[],this.fireHistory(),this.refreshPreview(),this.requestRenderAll(),!0}hitAnchor(e,t){let r=this.hitAnchorsOfKind(e,t,"vertex");return r||this.hitAnchorsOfKind(e,t,"curve")}hitAnchorsOfKind(e,t,r){let o=this.currentBounds(),i=null;for(let s=0;s<o.length;s++)for(let a=0;a<o[s].length;a++){let l=o[s][a];if(r==="vertex")for(let u of dm){let c=fm(l,u);if(!c)continue;let h=this.screenDist(c,e,t);h<=lm&&(!i||h<i.dist)&&(i={anchor:{kind:"vertex",row:s,col:a,pos:u},dist:h})}else for(let u of Fc){let c=l[u];if(!(!c||c.length<4))for(let h of[0,1]){let d=this.screenDist(c[h+1],e,t);d<=lm&&(!i||d<i.dist)&&(i={anchor:{kind:"curve",row:s,col:a,dir:u,index:h},dist:d})}}}return i?.anchor??null}applyAnchorDrag(e,t){let r=this.warp;if(!r)return;let o=this.toSource(t);if(e.kind==="vertex")r.updateVertexCoord(e.row,e.col,e.pos,o);else{let i=this.currentBounds()[e.row]?.[e.col]?.[e.dir];if(!i||i.length<4)return;let s=i.map(a=>({...a}));s[e.index+1]=o,r.updateRegionBoundCoords(e.row,e.col,e.dir,[s[0],s[1],s[2],s[3]])}this.refreshPreview(),this.requestRenderAll()}endDrag(){this.warp&&(this.undoStack.push(this.snapshot()),this.redoStack=[],this.fireHistory())}undo(){return!this.warp||this.undoStack.length<=1?!1:(this.redoStack.push(this.undoStack.pop()),this.restore(this.undoStack[this.undoStack.length-1]),this.afterHistoryStep(),!0)}redo(){if(!this.warp)return!1;let e=this.redoStack.pop();return e?(this.undoStack.push(e),this.restore(e),this.afterHistoryStep(),!0):!1}afterHistoryStep(){this.fireHistory(),this.refreshPreview(),this.requestRenderAll()}get undoable(){return this.undoStack.length>1}get redoable(){return this.redoStack.length>0}getWarpState(){return this.warp?this.snapshot():null}buildOverlay(){if(!this.warp||!this.node)return[];let e=this.zoom,t=[];if(this.previewCanvas){this.renderedVersion!==this.previewVersion&&(this.textures.update(this.previewCanvas),this.renderedVersion=this.previewVersion);let s=this.localFromSourceBox(this.warp.getBoundingBoxInfo());t.push({matrix:this.quadMatrix(s.cx,s.cy),dims:{x:s.w,y:s.h},color:[1,1,1,1],texture:this.previewCanvas})}let r=this.currentBounds(),o=new Set,i=new Set;for(let s of r)for(let a of s){for(let l of Fc){let u=a[l];if(!u||u.length<4)continue;let c=this.toScene(u[0]);for(let h=1;h<=hm;h++){let d=this.toScene(d0(u[0],u[1],u[2],u[3],h/hm));t.push(Re(c,d,l0/e,c0)),c=d}for(let h of[0,1]){let d=u[h+1],f=`${Math.round(d.x)},${Math.round(d.y)}`;i.has(f)||(i.add(f),t.push(mm(this.toScene(d),a0,h0,e)))}}for(let l of dm){let u=fm(a,l);if(!u)continue;let c=`${Math.round(u.x)},${Math.round(u.y)}`;o.has(c)||(o.add(c),t.push(mm(this.toScene(u),s0,u0,e)))}}return t}hoverCursor(e,t){return this.hitAnchor(e,t)?"pointer":"default"}async exit(e){let t=this.warp,r=this.node;if(!t||!r)return null;let o=this.beforeRaw,i=null;if(e&&!t.isUnwarped()){let a=t.render().toDataURL("image/png"),l=t.getBoundingBoxInfo(),u=t.getWarpState(),c=this.localFromSourceBox(l),h=this.sourceToDisplayScale(),d=Math.max(1,Math.round(l.width*h.x)),f=Math.max(1,Math.round(l.height*h.y)),m=r.matrix,p={x:r.center.x+m[0]*c.cx+m[2]*c.cy,y:r.center.y+m[1]*c.cx+m[3]*c.cy},b=ge({...r.raw,width:d,height:f},p),g={x:l.width/2-l.offsetX,y:l.height/2-l.offsetY};i={dataURL:a,state:u,nextWidth:d,nextHeight:f,left:b.x,top:b.y,originalSrc:this.originalSrc,displayScale:{x:this.displayScale.x,y:this.displayScale.y},coreAnchor:g}}this.teardown(t);let s=!1;return i&&(r.set({src:i.dataURL,width:i.nextWidth,height:i.nextHeight,left:i.left,top:i.top,warpvasState:i.state,warpOriginalSrc:i.originalSrc??void 0,warpDisplayScale:i.displayScale,warpCoreAnchor:i.coreAnchor}),await this.reloadNodeImage(r.id),this.host.document.applyTransform([r],()=>({}),"modified",{action:Le.warpImage,before:new Map([[r,o]])}),s=!0),this.requestRenderAll(),{committed:s,node:r,before:o,after:r.toObject()}}async cancel(){await this.exit(!1)}teardown(e=this.warp){this.previewCanvas&&this.textures.remove(this.previewCanvas),e?.dispose?.(),this.warp=null,this.node=null,this.beforeRaw=null,this.originalSrc=null,this.undoStack=[],this.redoStack=[],this.previewCanvas=null,this.previewVersion=0,this.renderedVersion=-1,this.coreSize={w:0,h:0},this.displayScale={x:1,y:1},this.coreAnchor={x:0,y:0},this.renderCanvas=null}snapshot(){return this.warp.getWarpState()}restore(e){this.warp.setWarpState(e.splitPoints,e.regionBounds)}currentBounds(){return this.warp?this.warp.getWarpState().regionBounds??[]:[]}sourceToDisplayScale(){return{x:this.displayScale.x,y:this.displayScale.y}}quadMatrix(e,t){return f0(this.node.matrix,e,t)}toScene(e){let t=this.node;return Q(t.matrix,(e.x-this.coreAnchor.x)*this.displayScale.x,(e.y-this.coreAnchor.y)*this.displayScale.y)}toSource(e){let r=this.node.localPoint(e.x,e.y);return{x:r.x/this.displayScale.x+this.coreAnchor.x,y:r.y/this.displayScale.y+this.coreAnchor.y}}screenDist(e,t,r){let o=this.toScene(e),i=this.toScreen(o.x,o.y);return Math.hypot(i.x-t,i.y-r)}localFromSourceBox(e){return{cx:(e.width/2-e.offsetX-this.coreAnchor.x)*this.displayScale.x,cy:(e.height/2-e.offsetY-this.coreAnchor.y)*this.displayScale.y,w:e.width*this.displayScale.x,h:e.height*this.displayScale.y}}refreshPreview(){if(!this.warp)return;let e=this.previewCanvas;this.previewCanvas=this.warp.render(),e&&e!==this.previewCanvas&&this.textures.remove(e),this.previewVersion++}fireHistory(){this.host.onWarpHistoryChange?.(this.undoable,this.redoable)}},dm=["tl","tr","bl","br"],Fc=["top","right","bottom","left"],fm=(n,e)=>{let t=n[e==="tl"||e==="tr"?"top":"bottom"],r=n[e==="tl"||e==="bl"?"left":"right"];if(!t||t.length<4||!r||r.length<4)return null;let o=null;for(let i of[t[0],t[3]])for(let s of[r[0],r[3]]){let a=Math.hypot(i.x-s.x,i.y-s.y);(!o||a<o.dist)&&(o={pt:{x:(i.x+s.x)/2,y:(i.y+s.y)/2},dist:a})}return o?.pt??null},d0=(n,e,t,r,o)=>{let i=1-o;return{x:i*i*i*n.x+3*i*i*o*e.x+3*i*o*o*t.x+o*o*o*r.x,y:i*i*i*n.y+3*i*i*o*e.y+3*i*o*o*t.y+o*o*o*r.y}},mm=(n,e,t,r)=>({matrix:[1,0,0,1,n.x,n.y],dims:{x:e*2/r,y:e*2/r},color:t}),f0=(n,e,t)=>[n[0],n[1],n[2],n[3],n[0]*e+n[2]*t+n[4],n[1]*e+n[3]*t+n[5]];var he=n=>Math.round(n*1e6)/1e6;var zr=([n,e],[t,r])=>n<=t?e>=t:n>=t?r>=n:!1,$s=([n,e],[t,r])=>{let o=Math.max(n,t),i=Math.min(e,r);return o<=i?[o,i]:null},en=(n,e,t,r,o)=>{let i=Math.abs(e);i<=t[r]&&(i<t[r]&&(n.length=0),n.push(o),t[r]=i)},gm=n=>{let e=n.map((r,o)=>({p:r,i:o}));e.sort((r,o)=>r.p.x-o.p.x);let t=n.map((r,o)=>({p:r,i:o}));return t.sort((r,o)=>r.p.y-o.p.y),{byX:e,byY:t}},m0=(n,e,t)=>{let r=0,o=n.length;for(;r<o;){let i=r+o>>1;n[i].p[e]<t?r=i+1:o=i}return r},pm=(n,e,t,r,o,i,s)=>{let a=[],l=(u,c,h,d,f,m)=>{let p=c;for(let b of d){let g=m0(u,c,b[c]-h),x=b[c]+h,S=m[p];a.length=0;for(let w=g;w<u.length;w++){let y=u[w];if(y.p[c]>x)break;let v=y.p[c]-b[c],R=Math.abs(v);R<=S&&(R<S&&(S=R,a.length=0),a.push({p:y.p,i:y.i,offset:v}))}a.sort((w,y)=>w.i-y.i);for(let w of a)en(f,w.offset,m,p,{type:"point",points:[b,w.p],offset:w.offset})}};l(e.byX,"x",t,n,i,o),l(e.byY,"y",r,n,s,o)},Bc=n=>({x:he(n.x),y:he(n.y)}),Oc=n=>({left:he(n.left),top:he(n.top),right:he(n.right),bottom:he(n.bottom)}),Vs=n=>[n.tl,n.tr,n.br,n.bl,n.c].map(Bc),xm=n=>n.flatMap(Vs);var ym=n=>{let e=n.map(Oc).map((o,i)=>({bounds:o,idx:i})),t=o=>[...e].sort((i,s)=>i.bounds[o]-s.bounds[o]),r=(o,i)=>[...e].sort((s,a)=>s.bounds[o]+s.bounds[i]-a.bounds[o]-a.bounds[i]);return{byLeft:t("left"),byRight:t("right"),byTop:t("top"),byBottom:t("bottom"),byLeftPlusRight:r("left","right"),byTopPlusBottom:r("top","bottom")}};var p0=(n,e,t,r,o)=>{let{left:i,top:s,right:a,bottom:l}=n,u=(i+a)/2,c=(s+l)/2,h=t.x,d=t.y,f=a-i,m=l-s,p=(T,C,E,M)=>({startBounds:T,endBounds:C,startSide:[{x:T.right,y:T.top},{x:T.right,y:T.bottom}],endSide:[{x:C.left,y:C.top},{x:C.left,y:C.bottom}],length:M,overlap:E}),b=(T,C,E,M)=>({startBounds:T,endBounds:C,startSide:[{x:T.left,y:T.bottom},{x:T.right,y:T.bottom}],endSide:[{x:C.left,y:C.top},{x:C.right,y:C.top}],length:M,overlap:E}),g=(T,C)=>{if(!(T.right<C.left&&zr([T.top,T.bottom],[C.top,C.bottom])))return;let E=$s([T.top,T.bottom],[C.top,C.bottom]);if(!zr([s,l],E))return;let M=C.left-T.right,k=he(T.right+M/2-u);if(M>f&&Math.abs(k)<=t.x){en(r,k,t,"x",{type:"gap",direction:"center_horizontal",gap:p(T,C,E,M),offset:k});return}let A=he(M-(i-C.right));if(Math.abs(A)<=t.x){en(r,A,t,"x",{type:"gap",direction:"side_right",gap:p(T,C,E,M),offset:A});return}let O=he(T.left-a-M);Math.abs(O)<=t.x&&en(r,O,t,"x",{type:"gap",direction:"side_left",gap:p(T,C,E,M),offset:O})},x=(T,C)=>{if(!(T.bottom<C.top&&zr([T.left,T.right],[C.left,C.right])))return;let E=$s([T.left,T.right],[C.left,C.right]);if(!zr([i,a],E))return;let M=C.top-T.bottom,k=he(T.bottom+M/2-c);if(M>m&&Math.abs(k)<=t.y){en(o,k,t,"y",{type:"gap",direction:"center_vertical",gap:b(T,C,E,M),offset:k});return}let A=he(T.top-l-M);if(Math.abs(A)<=t.y){en(o,A,t,"y",{type:"gap",direction:"side_top",gap:b(T,C,E,M),offset:A});return}let O=he(s-C.bottom),F=M-O;Math.abs(F)<=t.y&&en(o,F,t,"y",{type:"gap",direction:"side_bottom",gap:b(T,C,E,M),offset:F})},S=e.byLeft,w=e.byRight,y=e.byTop,v=e.byBottom,R=h+1e-6,P=d+1e-6;{let T=S.length;for(let C of w){if(C.bounds.right>=u+h+.001)break;let E=2*u-C.bounds.right,M=E+2*R,k=E-2*R;for(;T>0&&S[T-1].bounds.left>M;)T--;for(let A=T-1;A>=0&&S[A].bounds.left>=k;A--)g(C.bounds,S[A].bounds)}}{let T=0;for(let C of e.byLeftPlusRight){if(C.bounds.right>=i+h+.001)continue;let E=C.bounds.left+C.bounds.right-i,M=E-R,k=E+R;for(;T<w.length&&w[T].bounds.right<M;)T++;for(let A=T;A<w.length&&w[A].bounds.right<=k;A++)g(w[A].bounds,C.bounds)}}{let T=0;for(let C of e.byLeftPlusRight){if(C.bounds.left<=a-h-.001)continue;let E=C.bounds.left+C.bounds.right-a,M=E-R,k=E+R;for(;T<S.length&&S[T].bounds.left<M;)T++;for(let A=T;A<S.length&&S[A].bounds.left<=k;A++)g(C.bounds,S[A].bounds)}}{let T=y.length;for(let C of v){if(C.bounds.bottom>=c+d+.001)break;let E=2*c-C.bounds.bottom,M=E+2*P,k=E-2*P;for(;T>0&&y[T-1].bounds.top>M;)T--;for(let A=T-1;A>=0&&y[A].bounds.top>=k;A--)x(C.bounds,y[A].bounds)}}{let T=0;for(let C of e.byTopPlusBottom){if(C.bounds.top<=l-d-.001)continue;let E=C.bounds.top+C.bounds.bottom-l,M=E-P,k=E+P;for(;T<y.length&&y[T].bounds.top<M;)T++;for(let A=T;A<y.length&&y[A].bounds.top<=k;A++)x(C.bounds,y[A].bounds)}}{let C=0;for(let E of e.byTopPlusBottom){if(E.bounds.bottom>=s+d+.001)continue;let M=E.bounds.top-he(s-E.bounds.bottom),k=M-P,A=M+P;for(;C<v.length&&v[C].bounds.bottom<k-1e-5;)C++;for(let O=C;O<v.length&&v[O].bounds.bottom<=A;O++)x(v[O].bounds,E.bounds)}}},js=(n,e,t,r,o)=>{for(let i of n)for(let s of e){let a=s.x-i.x,l=s.y-i.y;Math.abs(a)<=t.x&&en(r,a,t,"x",{type:"point",points:[i,s],offset:a}),Math.abs(l)<=t.y&&en(o,l,t,"y",{type:"point",points:[i,s],offset:l})}},b0=(n,e,t,r,o)=>{let{left:i,top:s,right:a,bottom:l}=n,u=(i+a)/2,c=(s+l)/2;for(let h of e.horizontalGaps){if(!zr([s,l],h.overlap))continue;let d=h.startSide[0].x+h.length/2,f=he(d-u);if(h.length>a-i&&Math.abs(f)<=t.x){Math.abs(f)<t.x&&(r.length=0),t.x=Math.abs(f),r.push({type:"gap",direction:"center_horizontal",gap:h,offset:f});continue}let p=i-h.endBounds.right,b=he(h.length-p);if(Math.abs(b)<=t.x){Math.abs(b)<t.x&&(r.length=0),t.x=Math.abs(b),r.push({type:"gap",direction:"side_right",gap:h,offset:b});continue}let g=h.startBounds.left-a,x=he(g-h.length);if(Math.abs(x)<=t.x){Math.abs(x)<t.x&&(r.length=0),t.x=Math.abs(x),r.push({type:"gap",direction:"side_left",gap:h,offset:x});continue}}for(let h of e.verticalGaps){if(!zr([i,a],h.overlap))continue;let d=h.startSide[0].y+h.length/2,f=he(d-c);if(h.length>l-s&&Math.abs(f)<=t.y){Math.abs(f)<t.y&&(o.length=0),t.y=Math.abs(f),o.push({type:"gap",direction:"center_vertical",gap:h,offset:f});continue}let p=h.startBounds.top-l,b=he(p-h.length);if(Math.abs(b)<=t.y){Math.abs(b)<t.y&&(o.length=0),t.y=Math.abs(b),o.push({type:"gap",direction:"side_top",gap:h,offset:b});continue}let g=he(s-h.endBounds.bottom),x=h.length-g;if(Math.abs(x)<=t.y){Math.abs(x)<t.y&&(o.length=0),t.y=Math.abs(x),o.push({type:"gap",direction:"side_bottom",gap:h,offset:x});continue}}},bm=n=>{let e=new Map;for(let t of n){let r=`${he(t.x)},${he(t.y)}`;e.has(r)||e.set(r,t)}return Array.from(e.values())},Sm=(n,e)=>{let t={},r={};for(let s of n){if(s.type!=="point")continue;let a=String(he(s.points[0].x));t[a]||(t[a]=[]),t[a].push(...s.points.map(l=>({x:he(l.x),y:he(l.y)})))}for(let s of e){if(s.type!=="point")continue;let a=String(he(s.points[0].y));r[a]||(r[a]=[]),r[a].push(...s.points.map(l=>({x:he(l.x),y:he(l.y)})))}let o=Object.entries(t).map(([s,a])=>({type:"points",points:bm(a.map(l=>({x:Number(s),y:l.y})).sort((l,u)=>l.y-u.y))})),i=Object.entries(r).map(([s,a])=>({type:"points",points:bm(a.map(l=>({x:l.x,y:Number(s)})).sort((l,u)=>l.x-u.x))}));return[...o,...i]},g0=n=>{let e=new Map;for(let t of n){let r=[t.points[0],t.points[1]].flatMap(o=>[he(o.x),he(o.y)]).join(",");e.has(r)||e.set(r,t)}return Array.from(e.values())},x0=(n,e)=>{let{left:t,top:r,right:o,bottom:i}=n,s=[];for(let a of e){let l=a.gap.startBounds,u=a.gap.endBounds,c=$s([r,i],a.gap.overlap),h=$s([t,o],a.gap.overlap);switch(a.direction){case"center_horizontal":{if(c){let d=(c[0]+c[1])/2;s.push({type:"gap",direction:"horizontal",points:[{x:a.gap.startSide[0].x,y:d},{x:t,y:d}]},{type:"gap",direction:"horizontal",points:[{x:o,y:d},{x:a.gap.endSide[0].x,y:d}]})}break}case"center_vertical":{if(h){let d=(h[0]+h[1])/2;s.push({type:"gap",direction:"vertical",points:[{x:d,y:a.gap.startSide[0].y},{x:d,y:r}]},{type:"gap",direction:"vertical",points:[{x:d,y:i},{x:d,y:a.gap.endSide[0].y}]})}break}case"side_right":{if(c){let d=(c[0]+c[1])/2;s.push({type:"gap",direction:"horizontal",points:[{x:l.right,y:d},{x:u.left,y:d}]},{type:"gap",direction:"horizontal",points:[{x:u.right,y:d},{x:t,y:d}]})}break}case"side_left":{if(c){let d=(c[0]+c[1])/2;s.push({type:"gap",direction:"horizontal",points:[{x:o,y:d},{x:l.left,y:d}]},{type:"gap",direction:"horizontal",points:[{x:l.right,y:d},{x:u.left,y:d}]})}break}case"side_top":{if(h){let d=(h[0]+h[1])/2;s.push({type:"gap",direction:"vertical",points:[{x:d,y:i},{x:d,y:l.top}]},{type:"gap",direction:"vertical",points:[{x:d,y:l.bottom},{x:d,y:u.top}]})}break}case"side_bottom":{if(h){let d=(h[0]+h[1])/2;s.push({type:"gap",direction:"vertical",points:[{x:d,y:l.bottom},{x:d,y:u.top}]},{type:"gap",direction:"vertical",points:[{x:d,y:u.bottom},{x:d,y:r}]})}break}}}return g0(s.map(a=>({...a,points:[{x:he(a.points[0].x),y:he(a.points[0].y)},{x:he(a.points[1].x),y:he(a.points[1].y)}]})))},vm=(n,e,t,r,o,i)=>{let s=(g,x,S)=>{"byLeft"in r?p0(g,r,l,x,S):b0(g,r,l,x,S)},a=Oc(e),l={x:o,y:o},u=[],c=[];i?pm(n,i,o,o,l,u,c):js(n,t,l,u,c),s(a,u,c);let h={x:he(u[0]?.offset??0),y:he(c[0]?.offset??0)},d=n.map(g=>Bc({x:g.x+h.x,y:g.y+h.y})),f=Oc({left:a.left+h.x,top:a.top+h.y,right:a.right+h.x,bottom:a.bottom+h.y});l.x=0,l.y=0,u.length=0,c.length=0,i?pm(d,i,0,0,l,u,c):js(d,t,l,u,c),s(f,u,c);let m=Sm(u,c),p=[...u,...c].filter(g=>g.type==="gap"),b=x0(f,p);return{snapOffset:h,pointSnapLines:m,gapSnapLines:b}},wm=(n,e,t)=>{let r={x:t,y:t},o=[],i=[];js(n,e,r,o,i);let s={x:he(o[0]?.offset??0),y:he(i[0]?.offset??0)};r.x=0,r.y=0,o.length=0,i.length=0;let a=n.map(u=>Bc({x:u.x+s.x,y:u.y+s.y}));js(a,e,r,o,i);let l=Sm(o,i);return{snapOffset:s,pointSnapLines:l}};var y0=200,Tm=8,S0=1,v0=3,w0=8,T0=ee("#F68066"),Em=new Set(["WorkSpaceClipType","WorkSpaceSafeType","WorkSpaceMaskType","WorkSpaceLineType","WorkSpaceShadowType"]),E0="WorkSpaceDrawType",Yr=n=>({left:Math.min(n.tl.x,n.tr.x,n.br.x,n.bl.x),top:Math.min(n.tl.y,n.tr.y,n.br.y,n.bl.y),right:Math.max(n.tl.x,n.tr.x,n.br.x,n.bl.x),bottom:Math.max(n.tl.y,n.tr.y,n.br.y,n.bl.y)}),Cm=(n,e)=>!(Yr(n).right<e.minX||Yr(n).left>e.maxX||Yr(n).bottom<e.minY||Yr(n).top>e.maxY),C0=n=>({x:(n.tl.x+n.br.x)/2,y:(n.tl.y+n.br.y)/2}),qs=class{constructor(e,t=()=>!1){this.host=e;this.enabled=t}host;enabled;pointSnapLines=[];gapSnapLines=[];lastSnapOffset={x:0,y:0};activeType="";pendingMove=!1;gestureKey="";viewportSignature="";referenceCoords=[];referencePoints=[];axisIndex=null;gapIndex=null;scalingKey="";scalingPoints=[];workspaceResolved=!1;workspacePointKeys=new Set;workspaceBounds;get info(){return{pending:this.pendingMove,offset:{...this.lastSnapOffset},pointLines:this.pointSnapLines.length,gapLines:this.gapSnapLines.length,candidates:this.referenceCoords.length,activeType:this.activeType}}registerMove(e){this.enabled()&&(this.clearLines(),this.activeType=e.raw.type,this.ensureMoveCaches(),this.pendingMove=!0)}settleMoveSnap(){if(!this.pendingMove||(this.pendingMove=!1,!this.enabled()))return;let e=this.host.document;if(e.groupEditing&&e.activeGroupChild){this.clearLines();return}let t=e.selection;if(!t.length||!this.referenceCoords.length||!this.referencePoints.length||!this.gapIndex){this.clearLines();return}let r=et(e);if(!r){this.clearLines();return}let o={tl:r.quad.tl,tr:r.quad.tr,br:r.quad.br,bl:r.quad.bl,c:C0(r.quad)},i=Tm/this.host.zoom,{snapOffset:s,pointSnapLines:a,gapSnapLines:l}=vm(Vs(o),Yr(o),this.referencePoints,this.gapIndex,i,this.axisIndex??void 0);if(s.x!==0||s.y!==0){for(let c of t)e.setProps(c,{left:(c.raw.left??0)+s.x,top:(c.raw.top??0)+s.y},{deferIndexRebuild:!0});let u=e.selectionFrame;u&&e.setSelectionFrame({...u,center:{x:u.center.x+s.x,y:u.center.y+s.y}})}this.lastSnapOffset={...s},this.pointSnapLines=a,this.gapSnapLines=l}registerScaling(e,t){if(!this.enabled()||e.typeKey===L.CIRCLE)return;this.clearLines(),this.activeType=e.raw.type;let r=this.host.document;this.ensureScalingCaches();let o=et(r);if(!o||!this.scalingPoints.length)return;let s=(cs(t)?[t]:[...$l]).map(u=>({x:o.quad[u].x,y:o.quad[u].y})),a=Tm/this.host.zoom,{pointSnapLines:l}=wm(s,this.scalingPoints,a);this.pointSnapLines=l,this.gapSnapLines=[]}finishGesture(){this.settleMoveSnap(),this.clearLines(),this.activeType="",this.gestureKey="",this.viewportSignature="",this.referenceCoords=[],this.referencePoints=[],this.axisIndex=null,this.gapIndex=null,this.scalingKey="",this.scalingPoints=[],this.workspaceResolved=!1,this.workspacePointKeys.clear(),this.workspaceBounds=void 0}buildOverlay(e){if(this.activeType==="ReferenceLine")return[];if(!this.pointSnapLines.length&&!this.gapSnapLines.length)return[];let t=[],r=S0/e,o=(i,s)=>t.push(Re(i,s,r,T0));this.ensureWorkspaceInfo();for(let i of this.pointSnapLines){let s=i.points;if(!s.length)continue;if(!!this.workspaceBounds&&s.some(u=>this.workspacePointKeys.has(`${he(u.x)},${he(u.y)}`))&&this.workspaceBounds){let u=this.workspaceBounds,c=s.every(d=>d.x===s[0].x),h=s.every(d=>d.y===s[0].y);c&&o({x:s[0].x,y:Math.min(s[0].y,u.top)},{x:s[0].x,y:Math.max(s[s.length-1].y,u.bottom)}),h&&o({x:Math.min(s[0].x,u.left),y:s[0].y},{x:Math.max(s[s.length-1].x,u.right),y:s[0].y})}else s.length>=2&&o(s[0],s[s.length-1]);let l=v0/e;for(let u of s)o({x:u.x-l,y:u.y-l},{x:u.x+l,y:u.y+l}),o({x:u.x+l,y:u.y-l},{x:u.x-l,y:u.y+l})}for(let i of this.gapSnapLines){let[s,a]=i.points,l=w0/e,u=l/2,c=l/4;if(i.direction==="horizontal"){let h=s.y,d=(s.x+a.x)/2;o({x:s.x,y:h-l},{x:s.x,y:h+l}),o({x:d-c,y:h-u},{x:d-c,y:h+u}),o({x:d+c,y:h-u},{x:d+c,y:h+u}),o({x:a.x,y:h-l},{x:a.x,y:h+l}),o(s,a)}else{let h=s.x,d=(s.y+a.y)/2;o({x:h-l,y:s.y},{x:h+l,y:s.y}),o({x:h-u,y:d-c},{x:h+u,y:d-c}),o({x:h-u,y:d+c},{x:h+u,y:d+c}),o({x:h-l,y:a.y},{x:h+l,y:a.y}),o(s,a)}}return t}clearLines(){this.pointSnapLines=[],this.gapSnapLines=[]}keyCacheSelection=null;keyCacheValue="";ensureMoveCaches(){let e=this.host.document,t=e.selection;this.keyCacheSelection!==t&&(this.keyCacheSelection=t,this.keyCacheValue=t.map(l=>l.id).join("|"));let r=this.keyCacheValue,o=this.getViewportRect(),i=o?.signature??"";if(this.gestureKey===r&&this.referenceCoords.length&&this.viewportSignature===i)return;this.gestureKey=r,this.viewportSignature=i;let s=new Set(t),a=o?.rect;this.referenceCoords=[];for(let l of e.nodes){if(!l.visible||s.has(l)||Em.has(l.id))continue;let u=this.nodeCoords(l);a&&!Cm(u,a)||this.referenceCoords.push(u)}this.referencePoints=xm(this.referenceCoords),this.axisIndex=gm(this.referencePoints),this.gapIndex=ym(this.referenceCoords.map(Yr))}ensureScalingCaches(){let e=this.host.document,t=e.selection.map(s=>s.id).join("|");if(this.scalingKey===t&&this.scalingPoints.length)return;this.scalingKey=t;let r=new Set(e.selection),o=this.getViewportRect()?.rect,i=[];for(let s of e.nodes){if(!s.visible||r.has(s)||Em.has(s.id))continue;let a=this.nodeCoords(s);o&&!Cm(a,o)||i.push(...Vs(a))}this.scalingPoints=i}ensureWorkspaceInfo(){if(this.workspaceResolved)return;this.workspaceResolved=!0;let e=this.host.document.nodes.find(o=>o.id===E0);if(!e)return;let t=e.aCoords,r=e.center;for(let o of[t.tl,t.tr,t.br,t.bl,r])this.workspacePointKeys.add(`${he(o.x)},${he(o.y)}`);this.workspaceBounds=e.bounds}nodeCoords(e){let t=e.aCoords,r=e.center;return{tl:{x:t.tl.x,y:t.tl.y},tr:{x:t.tr.x,y:t.tr.y},br:{x:t.br.x,y:t.br.y},bl:{x:t.bl.x,y:t.bl.y},c:{x:r.x,y:r.y}}}getViewportRect(){let e=this.host.viewportTransform,t=e[0];if(!t||!Number.isFinite(t))return;let{width:r,height:o}=this.host.viewSize,i={x:(0-e[4])/e[0],y:(0-e[5])/e[3]},s={x:(r-e[4])/e[0],y:(o-e[5])/e[3]},a=y0/t;return{rect:{minX:Math.min(i.x,s.x)-a,minY:Math.min(i.y,s.y)-a,maxX:Math.max(i.x,s.x)+a,maxY:Math.max(i.y,s.y)+a},signature:`${e[0]},${e[1]},${e[2]},${e[3]},${e[4]},${e[5]}`}}};var Mm=n=>{let e=n?.animates;return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.key=="string"):[]},M0={width:0,height:0},be=(n,e={})=>({originX:"center",originY:"center",left:n.center.x,top:n.center.y,...e}),Wt=(n,e,t=M0,r={})=>e==="left"?be(n,{left:-n.width/2,...r}):e==="right"?be(n,{left:t.width+n.width/2,...r}):e==="top"?be(n,{top:-n.height/2,...r}):be(n,{top:t.height+n.height/2,...r}),R0=[{key:"left-swipe-entry",name:"左滑入场",category:"entrance",getStartState:n=>Wt(n,"left"),getEndState:n=>be(n)},{key:"right-swipe-entry",name:"右滑入场",category:"entrance",getStartState:(n,e)=>Wt(n,"right",e),getEndState:n=>be(n)},{key:"top-swipe-entry",name:"上滑入场",category:"entrance",getStartState:(n,e)=>Wt(n,"bottom",e),getEndState:n=>be(n)},{key:"bottom-swipe-entry",name:"下滑入场",category:"entrance",getStartState:n=>Wt(n,"top"),getEndState:n=>be(n)},{key:"smash-off",name:"砸落",category:"entrance",getStartState:n=>be(n,{scaleX:n.scaleX*2.5,scaleY:n.scaleY*2.5}),getEndState:n=>be(n,{scaleX:n.scaleX,scaleY:n.scaleY})},{key:"gradually-display",name:"渐显",category:"entrance",getStartState:n=>be(n,{scaleX:n.scaleX*.01,scaleY:n.scaleY*.01,opacity:.01}),getEndState:n=>be(n,{scaleX:n.scaleX,scaleY:n.scaleY,opacity:1})},{key:"pop-up",name:"弹出",category:"entrance",getStartState:n=>be(n,{scaleX:n.scaleX*.01,scaleY:n.scaleY*.01}),getEndState:n=>be(n,{scaleX:n.scaleX*1.3,scaleY:n.scaleY*1.3})},{key:"flip-horizontal-entry",name:"水平翻转",category:"entrance",getStartState:n=>be(n,{scaleX:n.scaleX*.01}),getEndState:n=>be(n,{scaleX:n.scaleX})},{key:"flip-vertical-entry",name:"垂直翻转",category:"entrance",getStartState:n=>be(n,{scaleY:n.scaleY*.01}),getEndState:n=>be(n,{scaleY:n.scaleY})},{key:"rotate-entry",name:"旋入",category:"entrance",getStartState:n=>be(n,{angle:n.angle-720,scaleX:n.scaleX*.01,scaleY:n.scaleY*.01}),getEndState:n=>be(n,{angle:n.angle,scaleX:n.scaleX,scaleY:n.scaleY})}],P0=[{key:"left-swipe-exit",name:"左滑退场",category:"exit",getStartState:n=>be(n),getEndState:n=>Wt(n,"left")},{key:"right-swipe-exit",name:"右滑退场",category:"exit",getStartState:n=>be(n),getEndState:(n,e)=>Wt(n,"right",e)},{key:"top-swipe-exit",name:"上滑退场",category:"exit",getStartState:n=>be(n),getEndState:n=>Wt(n,"top")},{key:"bottom-swipe-exit",name:"下滑退场",category:"exit",getStartState:n=>be(n),getEndState:(n,e)=>Wt(n,"bottom",e)},{key:"fade-out",name:"渐隐",category:"exit",getStartState:n=>be(n,{scaleX:n.scaleX,scaleY:n.scaleY,opacity:1}),getEndState:n=>be(n,{scaleX:n.scaleX*.01,scaleY:n.scaleY*.01,opacity:.01})},{key:"flip-horizontal-exit",name:"水平翻转",category:"exit",getStartState:n=>be(n,{scaleX:n.scaleX}),getEndState:n=>be(n,{scaleX:n.scaleX*.01})},{key:"flip-vertical-exit",name:"垂直翻转",category:"exit",getStartState:n=>be(n,{scaleY:n.scaleY}),getEndState:n=>be(n,{scaleY:n.scaleY*.01})},{key:"rotate-exit",name:"旋出",category:"exit",getStartState:n=>be(n,{angle:n.angle-720,scaleX:n.scaleX,scaleY:n.scaleY}),getEndState:n=>be(n,{angle:n.angle+720,scaleX:n.scaleX*.01,scaleY:n.scaleY*.01})}],k0=[{key:"subtitle-scroll",name:"字幕滚动",category:"emphasis",getStartState:(n,e)=>Wt(n,"right",e),getEndState:n=>Wt(n,"left")},{key:"flip-horizontal",name:"水平翻转",category:"emphasis",getStartState:n=>be(n,{scaleX:n.scaleX}),getEndState:n=>be(n,{scaleX:-n.scaleX})},{key:"flip-vertical",name:"垂直翻转",category:"emphasis",getStartState:n=>be(n,{scaleY:n.scaleY}),getEndState:n=>be(n,{scaleY:-n.scaleY})}],A0=[...R0,...P0,...k0],Wc=new Map(A0.map(n=>[n.key,n])),N0=n=>Wc.get(n),Ks=n=>{let e=Wc.get(n);return e?e.category==="entrance"?0:e.category==="emphasis"?1:2:Number.MAX_SAFE_INTEGER},Rm=n=>Ks(n)===1,L0=n=>{let e=n.duration??0;return!Rm(n.key)||!n.single?e:Math.floor(e/n.single)*n.single},I0=n=>{let e=[...n].sort((r,o)=>{let i=Ks(r.key)-Ks(o.key);return i!==0?i:Ks(r.key)===Number.MAX_SAFE_INTEGER?(r.startTime??0)-(o.startTime??0):0}),t=0;return e.map(r=>{let o={...r,startTime:Number(t.toFixed(3))};return t+=r.duration??0,o})},Pm=.2,km=(n,e)=>{let t=[];for(let s of n)for(let a of I0(s.animates??[]))t.push({target:s.target,view:s.view,animate:a});t.sort((s,a)=>(s.animate.startTime??0)-(a.animate.startTime??0));let r=[],o=0,i=0;for(let s of t){let a=s.animate.startTime??0,l=Math.max(0,a-i),u=o+l,c=L0(s.animate),h=u+Pm,d=h+c;r.push({target:s.target,animate:s.animate,definition:Wc.get(s.animate.key)??null,view:s.view,waitTime:l,invokeTime:u,motionStart:h,motionEnd:d,playbackDuration:c}),o=d,i=a+(s.animate.duration??0)}return{timeline:r,duration:r[r.length-1]?.motionEnd??0,ws:e}},Hc=(n,e)=>{let t=new Map;for(let o of e.timeline){let i=t.get(o.target);i?i.push(o):t.set(o.target,[o])}let r=[];return t.forEach((o,i)=>{let s=o.find(f=>n>=f.invokeTime&&n<f.motionEnd);if(!s||!s.definition){r.push({target:i,override:null});return}if(n<s.motionStart){r.push({target:i,override:s.definition.getStartState(s.view,e.ws)});return}let a=n-s.motionStart,l=s.animate,u=s.playbackDuration>0?s.playbackDuration:1,c;Rm(l.key)&&l.single&&l.single>0?c=a%l.single/l.single:c=a/u,c=Math.min(Math.max(c,0),1);let h=s.definition.getStartState(s.view,e.ws),d=s.definition.getEndState(s.view,e.ws);r.push({target:i,override:Am(l.key,h,d,c)})}),r},Am=(n,e,t,r)=>{let o={};for(let i of Object.keys(t)){let s=e[i],a=t[i];if(typeof s=="number"&&typeof a=="number"){let l;n==="smash-off"&&(i==="scaleX"||i==="scaleY")?l=s-(s-a)*r:l=s+(a-s)*r,o[i]=Number(l.toFixed(3))}else o[i]=r<.5?s:a}for(let i of Object.keys(e))i in o||(o[i]=e[i]);return o},_0=n=>1-Math.cos(Math.min(Math.max(n,0),1)*Math.PI/2),Nm=(n,e,t)=>{let r=N0(t.key);if(!r)return null;let o=t.duration??0,i=t.single&&t.single>0?t.single:void 0,s=r.category==="emphasis",a=s&&i?Math.floor(o/i):1,l=s&&i?i:o;return{key:t.key,definition:r,view:n,ws:e,delay:Pm,loopDuration:l,loopCount:a}},Gc=(n,e)=>{if(n<0)return{override:e.definition.getStartState(e.view,e.ws),done:!1};if(n<e.delay)return{override:e.definition.getStartState(e.view,e.ws),done:!1};let t=n-e.delay,r=e.loopCount*e.loopDuration;if(t>=r)return{override:null,done:!0};let o=e.loopDuration>0?Math.floor(t/e.loopDuration):0,i=e.loopDuration>0?t-o*e.loopDuration:0,s=e.loopDuration>0?i/e.loopDuration:1,a=e.definition.getStartState(e.view,e.ws),l=e.definition.getEndState(e.view,e.ws);return{override:Am(e.key,a,l,_0(s)),done:!1}},Vo=n=>n.scrollSpeed?(n.textTotalWidth+n.viewWidth)/n.scrollSpeed:0,D0=(n,e,t)=>{if(e<=0)return 0;let r=Math.max(n,0);return t==="loop"?r%e:Math.min(r,e)},Lm=(n,e,t="loop")=>{if(!n.scrollEnabled)return 0;let r=Vo(n);if(r<=0)return 0;let o=D0(e,r,t)/r,i=n.textTotalWidth+n.viewWidth;return n.scrollDirection==="left-to-right"?o*i:-o*i},jo=class{_state="idle";_time=0;anchorNow=0;anchorTime=0;_trackDuration;constructor(e){this._trackDuration=e}get trackDuration(){return this._trackDuration}retargetDuration(e){this._trackDuration=e,this._time>e&&(this._time=e)}get state(){return this._state}get time(){return this._time}play(e){this._state==="idle"||this._state==="ended"?(this._time=0,this.anchorTime=0):this.anchorTime=this._time,this.anchorNow=e,this._state="playing"}pause(e){this._state==="playing"&&(this.syncTime(e),this._state=this._time>=this.trackDuration?"ended":"paused")}seek(e,t){this._time=Math.min(Math.max(t,0),this.trackDuration),this.anchorNow=e,this.anchorTime=this._time,this._state=this._time>=this.trackDuration?"ended":"paused"}stop(){this._state="idle",this._time=0,this.anchorNow=0,this.anchorTime=0}tick(e){return this._state==="idle"?null:(this._state==="playing"&&this.syncTime(e),{time:this._time,playing:this._state==="playing"})}syncTime(e){let t=(e-this.anchorNow)/1e3;this._time=Math.min(Math.max(this.anchorTime+t,0),this.trackDuration),this._time>=this.trackDuration&&(this._state="ended")}},Xc=(n,e)=>Math.max(n,...e,0);var Qs=class{constructor(e){this.host=e;this.editorScrollEnabled=e.editorScroll!==!1,this.anchorScrollClock(performance.now(),0)}host;playback=null;player=null;totalDuration=0;overridesActive=!1;previews=new Map;previewOverridesActive=!1;scrollRunning=!1;scrollAnchorNow=0;scrollAnchorTime=0;editorHadTracks=!1;editorScrollEnabled;reset(){this.playback=null,this.player=null,this.totalDuration=0,this.overridesActive=!1,this.previews.clear(),this.previewOverridesActive=!1,this.scrollRunning=!1,this.editorHadTracks=!1,this.anchorScrollClock(performance.now(),0)}play(){this.cancelPreviews(),this.rebuild();let e=[...this.collectMediaDurations(),...this.collectScrollTextDurations()];this.totalDuration=Xc(this.playback?.duration??0,e),this.player?this.player.retargetDuration(this.totalDuration):this.player=new jo(this.totalDuration);let t=performance.now();this.player.play(t),this.scrollRunning=!0,this.anchorScrollClock(t,this.player.time);for(let r of this.host.document.nodes)r instanceof ie?r.play():r instanceof ae&&r.playClipMedia();this.syncVideosToTime(this.player.time,!0),this.applyScrollTextOffsets(this.player.time),this.host.requestRenderAll()}pause(){let e=performance.now();this.anchorScrollClock(e,this.scrollClockTime(e)),this.scrollRunning=!1,this.player?.pause(e);for(let t of this.host.document.nodes)t instanceof ie?t.pause():t instanceof ae&&t.pauseClipMedia();this.host.requestRenderAll()}stop(){this.cancelPreviews(),this.player?.stop(),this.scrollRunning=!1,this.editorHadTracks=!1,this.anchorScrollClock(performance.now(),0),this.clearOverrides();for(let{node:e}of this.scrollTextTracks())e.setScrollOffset(0);for(let e of this.host.document.nodes)e instanceof ie?e.stop():e instanceof ae&&e.syncClipMediaToTime(0,!1);this.host.requestRenderAll()}seek(e){if(this.cancelPreviews(),!this.player){this.rebuild();let r=[...this.collectMediaDurations(),...this.collectScrollTextDurations()];this.totalDuration=Xc(this.playback?.duration??0,r),this.player=new jo(this.totalDuration)}let t=performance.now();this.player.seek(t,e),this.scrollRunning=!1,this.anchorScrollClock(t,this.player.time),this.applyAnimationTime(this.player.time),this.applyScrollTextOffsets(this.player.time),this.syncVideosToTime(this.player.time,!1),this.host.requestRenderAll()}get info(){return!this.player&&!this.playback?null:{state:this.player?.state??"idle",time:this.player?.time??0,duration:this.totalDuration,animatedCount:this.playback?.timeline.length??0}}playSingleAnimation(e,t,r){let o=Nm(this.targetView(e),this.workspaceView(),t);if(!o)return!1;this.stopSingleAnimation(e);let i={target:e,plan:o,startAt:performance.now(),onComplete:r};this.previews.set(e,i);let s=Gc(0,o);return e.setAnimationOverride(s.override),(s.override||this.previewOverridesActive)&&this.host.document.refreshHitIndex(),this.previewOverridesActive=!!s.override,this.host.requestRenderAll(),!0}stopSingleAnimation(e){let t=e?this.previews.has(e)?[e]:[]:[...this.previews.keys()];if(t.length){for(let r of t)this.previews.delete(r),r.setAnimationOverride(null);this.previewOverridesActive&&this.host.document.refreshHitIndex(),this.previewOverridesActive=!1,this.host.requestRenderAll()}}get singlePreviewInfo(){let e=performance.now();return[...this.previews.values()].map(t=>{let r=(e-t.startAt)/1e3,o=t.plan.loopCount*t.plan.loopDuration;return{nodeId:t.target.id,key:t.plan.key,elapsed:r,duration:t.plan.delay+o,state:r<t.plan.delay?"delay":r<t.plan.delay+o?"playing":"done"}})}tick(e){let t=this.player,r=t?t.tick(e):null;r?(this.applyAnimationTime(r.time),this.applyScrollTextOffsets(this.scrollClockTime(e))):this.tickEditorScroll(e);let o=this.tickPreviews(e);return!!r?.playing||o||this.scrollClockAdvancing()}tickPreviews(e){if(!this.previews.size)return!1;let t=!1,r=!1;for(let o of[...this.previews.values()]){let i=(e-o.startAt)/1e3,s=Gc(i,o.plan);o.target.setAnimationOverride(s.override),s.override&&(r=!0),s.done?(this.previews.delete(o.target),o.onComplete?.()):t=!0}return(r||this.previewOverridesActive)&&this.host.document.refreshHitIndex(),this.previewOverridesActive=r,t}cancelPreviews(){this.previews.size&&this.stopSingleAnimation()}anchorScrollClock(e,t){this.scrollAnchorNow=e,this.scrollAnchorTime=t}scrollClockTime(e){return this.scrollClockAdvancing()?this.scrollAnchorTime+Math.max(0,(e-this.scrollAnchorNow)/1e3):this.scrollAnchorTime}hasLiveScrollTracks(){return this.scrollTextTracks().some(({input:e})=>e.scrollEnabled&&Vo(e)>0)}scrollClockAdvancing(){return this.hasLiveScrollTracks()?this.scrollRunning||this.editorScrollActive():!1}editorScrollActive(){return!this.editorScrollEnabled||this.player&&this.player.state!=="idle"?!1:this.hasLiveScrollTracks()}tickEditorScroll(e){if(!this.editorScrollActive()){this.editorHadTracks=!1;return}this.editorHadTracks||(this.anchorScrollClock(e,0),this.editorHadTracks=!0),this.applyScrollTextOffsets(this.scrollClockTime(e))}get scrollTextInfo(){return this.scrollTextTracks().map(({node:e,input:t})=>({id:e.id,offset:e.scrollOffset,duration:Vo(t),viewWidth:t.viewWidth,textTotalWidth:t.textTotalWidth,speed:t.scrollSpeed,direction:t.scrollDirection,enabled:t.scrollEnabled}))}applyAnimationTime(e){if(!this.playback)return;let t=!1;for(let{target:r,override:o}of Hc(e,this.playback))r.setAnimationOverride(o),o&&(t=!0);(t||this.overridesActive)&&this.host.document.refreshHitIndex(),this.overridesActive=t}clearOverrides(){if(this.playback){for(let{target:e}of Hc(0,this.playback))e.setAnimationOverride(null);this.host.document.refreshHitIndex(),this.overridesActive=!1}}rebuild(){let e=[];for(let t of this.host.document.nodes){let r=Mm(t.raw);r.length&&e.push({target:t,view:this.targetView(t),animates:r})}this.playback=km(e,this.workspaceView())}targetView(e){let t=e.raw.scaleX??1,r=e.raw.scaleY??1,o=e.dims;return{left:e.raw.left??0,top:e.raw.top??0,scaleX:t,scaleY:r,angle:e.raw.angle??0,opacity:e.raw.opacity??1,width:o.x*t,height:o.y*r,center:Ut({...e.raw,width:o.x,height:o.y})}}workspaceView(){for(let e of this.host.document.nodes)if(e.raw.id===Sn)return{width:e.dims.x*(e.raw.scaleX??1),height:e.dims.y*(e.raw.scaleY??1)};return{width:0,height:0}}scrollTextTracks(){let e=[];for(let t of this.host.document.nodes){if(!(t instanceof ye))continue;let r=Gh(t);r&&e.push({node:t,input:r})}return e}collectScrollTextDurations(){return this.scrollTextTracks().map(({input:e})=>e.scrollEnabled?Vo(e):0)}applyScrollTextOffsets(e){for(let{node:t,input:r}of this.scrollTextTracks())t.setScrollOffset(Lm(r,e,"loop"))}collectMediaDurations(){let e=[],t=r=>{for(let o of r)o instanceof ie?e.push(o.mediaDuration):o instanceof ae?o.clipMediaDuration>0&&e.push(o.clipMediaDuration):o instanceof J&&t(o.children)};return t(this.host.document.nodes),e}syncVideosToTime(e,t){let r=o=>{for(let i of o)i instanceof ie?i.syncVideoToTime(e,t):i instanceof ae?i.syncClipMediaToTime(e,t):i instanceof J&&r(i.children)};r(this.host.document.nodes)}};var Im=14,_m=n=>n.fontFamily||"仓耳小丸子",Zs=class{host;session=null;offDocEvents;disposed=!1;constructor(e){this.host=e;let t=e.document.events,r=[t.on("text:changed",o=>this.onTextChanged(o)),t.on("text:editing:exited",()=>this.finish()),t.on("object:removed",o=>this.onOverlayRemoved(o))];this.offDocEvents=()=>r.forEach(o=>o())}dispose(){this.disposed||(this.disposed=!0,this.offDocEvents())}get active(){return this.session!==null}isOverlay(e){return this.session?.overlay===e}get info(){let e=this.session;return e?{tableId:e.table.id,row:e.row,col:e.col,text:e.overlay.raw.text??""}:null}startEditing(e,t,r,o={}){let i=this.host.document;if(!i.nodes.includes(e))return!1;let s=lt(e.cellMap,t,r),a=e.cellBounds(s.row,s.col);if(!a)return!1;i.editingNode&&i.exitEditing(),e.rebuildTable();let l=JSON.stringify(e.toObject()),u=e.raw,c=u.cellPadding??8,h=we(e.cellMap,s.row,s.col),d=e.cellSceneCenter(s.row,s.col),f={type:"textbox",id:`${e.id}-cell-edit`,text:o.initialText??h?.text??"",left:d.x,top:d.y,width:Math.max(0,a.width-c*2),originX:"center",originY:"center",scaleX:u.scaleX??1,scaleY:u.scaleY??1,angle:e.tableAngle,fill:h?.textFill??u.textFill,fontSize:h?.fontSize??Im,fontWeight:h?.fontWeight,fontStyle:h?.fontStyle,fontFamily:h?.fontFamily||_m(u),textAlign:h?.textAlign??fe.CENTER,lineHeight:1.16,splitByGrapheme:!0,opacity:1,visible:!0},m=new ye(f);if(e.editingCell=s,e.clearCellInteractionState(),this.session={overlay:m,table:e,row:s.row,col:s.col,snapshot:l,data:h??null},i.add(m),e.rebuildTable(),(i.selection.length!==1||i.selection[0]!==e)&&i.setSelection([e],"update"),i.enterEditing(m,{transient:!0}),o.initialText===void 0){let p=m.textLayout.graphemeCodeUnitOffsets.length-1;this.host.setEditingSelection(0,p)}return this.host.requestRenderAll(),!0}onTextChanged(e){let t=this.session;if(!t||e!==t.overlay)return;if(!t.data){let o=Array.isArray(t.table.raw.cellData)?t.table.raw.cellData:t.table.raw.cellData=[];t.data={row:t.row,col:t.col,fill:t.table.raw.cellFill,stroke:t.table.raw.cellStroke,text:"",textFill:t.table.raw.textFill,fontSize:Im,fontWeight:"normal",fontStyle:"normal",fontFamily:_m(t.table.raw),textAlign:"center"},o.push(t.data)}t.data.text=e.raw.text??"",t.table.rebuildTable();let r=t.table.cellSceneCenter(t.row,t.col);r&&e.set({left:r.x,top:r.y}),this.host.requestRenderAll()}finish(){let e=this.session;if(!e)return;this.session=null;let t=this.host.document;if(e.table.editingCell=null,t.remove(e.overlay),e.table.rebuildTable(),t.setSelection([e.table],"create"),e.table.setCellSelection([{row:e.row,col:e.col}],{row:e.row,col:e.col},{r1:e.row,r2:e.row,c1:e.col,c2:e.col}),JSON.stringify(e.table.toObject())!==e.snapshot){let r=new Map;r.set(e.table,JSON.parse(e.snapshot)),t.applyTransform([e.table],()=>({}),"modified",{action:Le.tableCellEdit,before:r})}this.host.requestRenderAll()}onOverlayRemoved(e){let t=this.session;!t||e!==t.overlay||(this.session=null,t.table.editingCell=null,t.table.rebuildTable(),this.host.requestRenderAll())}};var F0=530,Dm=[.1,.1,.1,1],O0=[.18,.44,.96,.3],Js=class{host;textarea=null;blinkTimer=null;caretVisible=!0;onSelectionChange=null;offDocEvents;inComposition=!1;compositionRange=null;constructor(e){this.host=e;let t=e.document.events,r=[t.on("text:changed",()=>{this.positionAtCaret(),this.host.requestRenderAll()}),t.on("text:editing:entered",()=>this.startUi()),t.on("text:editing:exited",()=>this.stopUi())];this.offDocEvents=()=>r.forEach(o=>o())}get composing(){return this.inComposition}enterEditingAtClick(e,t,r){let o=this.host.document.editingNode===e;if(this.host.document.enterEditing(e),!o){let u=e.textLayout.graphemeCodeUnitOffsets.length-1;this.setSelection(0,u);return}let i=e.localPoint(t,r),s=e.cursorIndexAt(i.x,i.y),[a,l]=e.wordBoundsAt(s);this.setSelection(a,l)}setSelection(e,t){let r=this.host.document.editingNode;if(!r)return;this.host.document.editSelection.start=e,this.host.document.editSelection.end=t;let o=this.textarea;if(o){let i=r.textLayout.graphemeCodeUnitOffsets,s=i[Math.min(e,i.length-1)]??0,a=i[Math.min(t,i.length-1)]??0;o.setSelectionRange(Math.min(s,a),Math.max(s,a))}this.caretVisible=!0,this.positionAtCaret(),this.focusTextarea(),this.host.requestRenderAll()}buildOverlay(){let e=this.host.document.editingNode;if(!e)return[];let t=e.textLayout,r=this.host.document.editSelection,o=Math.min(r.start,r.end),i=Math.max(r.start,r.end),s=e.matrix,a=Math.hypot(s[0],s[1])||1,l=[];for(let u of t.lines){let c=u.styleMap.flatStart,h=c+u.graphemes.length,d=Math.max(o,c),f=Math.min(i,h);if(f>d){let m=-t.width/2+u.leftOffset,p=m+(d<h?u.boxes[d-c].left:hn(u)),b=m+(f<h?u.boxes[f-c].left:hn(u));if(b>p){let g=e.contentTopY+u.top;l.push({matrix:j(s,[1,0,0,1,(p+b)/2,g+u.implHeight/2]),dims:{x:b-p,y:u.implHeight},color:O0})}}}if(o===i&&this.caretVisible&&!this.inComposition){let u=e.cursorCoord(o);if(u){let c=2/this.host.zoom/a;l.push({matrix:j(s,[1,0,0,1,u.x+c/2,u.y+u.height/2]),dims:{x:c,y:u.height},color:Dm})}}if(this.inComposition&&this.compositionRange){let u=this.compositionRange.start,c=this.compositionRange.end,h=t.lines.find(d=>{let f=d.styleMap.flatStart;return u>=f&&u<=f+d.graphemes.length});if(h){let d=h.styleMap.flatStart,f=-t.width/2+h.leftOffset,m=f+(u-d<h.boxes.length?h.boxes[u-d].left:hn(h)),p=f+(c-d<h.boxes.length?h.boxes[c-d].left:hn(h)),g=e.contentTopY+h.baseline+e.textStyle.fontSize*.14;l.push({matrix:j(s,[1,0,0,1,(m+p)/2,g]),dims:{x:Math.max(0,p-m),y:1.5/this.host.zoom/a},color:Dm})}}return l}startUi(){let e=this.host.document.editingNode;if(!e)return;let t=this.ensureTextarea();t.value=e.raw.text??"",this.positionAtCaret();let r=t.value.length;t.setSelectionRange(r,r),this.focusTextarea(),this.caretVisible=!0,this.inComposition=!1,this.compositionRange=null,this.blinkTimer!==null&&window.clearInterval(this.blinkTimer),this.blinkTimer=window.setInterval(()=>{this.caretVisible=!this.caretVisible,this.host.requestRenderAll()},F0),this.host.requestRenderAll()}stopUi(){this.blinkTimer!==null&&(window.clearInterval(this.blinkTimer),this.blinkTimer=null),this.textarea?.blur(),this.textarea?.remove(),this.textarea=null,this.host.requestRenderAll()}ensureTextarea(){if(this.textarea)return this.textarea;let e=document.createElement("textarea");return e.setAttribute("data-engine-editing",""),e.autocomplete="off",e.spellcheck=!1,Object.assign(e.style,{position:"absolute",opacity:"0",width:"4px",height:"20px",padding:"0",border:"none",overflow:"hidden",resize:"none",background:"transparent",pointerEvents:"none",zIndex:"0"}),this.host.canvasEl.parentElement?.appendChild(e),e.addEventListener("input",()=>{this.host.document.updateEditingText(e.value,e.selectionStart??0,e.selectionEnd??0)}),e.addEventListener("compositionstart",()=>{this.inComposition=!0,this.caretVisible=!0,this.blinkTimer!==null&&(window.clearInterval(this.blinkTimer),this.blinkTimer=null)}),e.addEventListener("compositionupdate",t=>{let r=t.data??"",i=t.target.selectionStart??0;this.compositionRange={start:i-r.length,end:i},this.positionAtCaret(),this.host.requestRenderAll()}),e.addEventListener("compositionend",()=>{this.inComposition=!1,this.compositionRange=null,this.host.requestRenderAll()}),e.addEventListener("keydown",t=>{if(t.stopPropagation(),t.key==="Escape"){if(this.inComposition)return;t.preventDefault(),this.host.document.exitEditing();return}if(this.inComposition)return;let r=this.navigateKey(t);r&&(t.preventDefault(),e.setSelectionRange(r[0],r[1],r[2]),this.host.document.updateEditingSelection(r[0],r[1]),this.caretVisible=!0,this.positionAtCaret(),this.host.requestRenderAll())}),this.onSelectionChange&&document.removeEventListener("selectionchange",this.onSelectionChange),this.onSelectionChange=()=>{let t=this.textarea;t&&this.host.document.editingNode&&document.activeElement===t&&(this.host.document.updateEditingSelection(t.selectionStart??0,t.selectionEnd??0),this.positionAtCaret(),this.host.requestRenderAll())},document.addEventListener("selectionchange",this.onSelectionChange),this.textarea=e,e}focusTextarea(){this.textarea?.focus({preventScroll:!0})}positionAtCaret(){let e=this.host.document.editingNode,t=this.textarea;if(!e||!t)return;let r=this.host.document.editSelection,o=e.cursorCoord(Math.min(r.start,r.end));if(!o)return;let i=e.matrix,s=i[0]*o.x+i[2]*o.y+i[4],a=i[1]*o.x+i[3]*o.y+i[5],l=this.host.toScreen(s,a),u=this.host.canvasEl.getBoundingClientRect(),c=this.host.canvasEl.parentElement?.getBoundingClientRect()??u;t.style.left=`${u.left-c.left+l.x}px`,t.style.top=`${u.top-c.top+l.y}px`}navigateKey(e){let t=this.host.document.editingNode;if(!t||e.ctrlKey||e.metaKey||e.altKey)return null;let r=t.textLayout,o=r.graphemeCodeUnitOffsets,i=o.length-1,s=this.host.document.editSelection,a=e.shiftKey?Math.max(s.start,s.end):s.end,l=e.shiftKey?Math.min(s.start,s.end):a,u=p=>o[Math.max(0,Math.min(p,i))]??0,c=p=>{for(let b=0;b<r.lines.length;b++){let g=r.lines[b].styleMap.flatStart;if(p<=g+r.lines[b].graphemes.length)return b}return r.lines.length-1},h=(p,b)=>{let g=r.lines[p],x=b-g.styleMap.flatStart;return-r.width/2+g.leftOffset+(x<g.boxes.length?g.boxes[x].left:hn(g))},d=(p,b)=>{let g=r.lines[p],x=-r.width/2+g.leftOffset;for(let S=0;S<g.boxes.length;S++)if(b<x+g.boxes[S].left+g.boxes[S].width/2)return g.styleMap.flatStart+S;return g.styleMap.flatStart+g.graphemes.length},f,m;switch(e.key){case"ArrowLeft":f=Math.max(0,a-1),m="backward";break;case"ArrowRight":f=Math.min(i,a+1),m="forward";break;case"Home":case"End":{let p=r.lines[c(a)];f=e.key==="Home"?p.styleMap.flatStart:p.styleMap.flatStart+p.graphemes.length,m=e.key==="Home"?"backward":"forward";break}case"ArrowUp":case"ArrowDown":{let p=c(a),b=e.key==="ArrowUp"?p-1:p+1;if(b<0||b>=r.lines.length)return null;f=d(b,h(p,a)),m=e.key==="ArrowUp"?"backward":"forward";break}default:return null}return e.shiftKey?[u(Math.min(l,f)),u(Math.max(l,f)),m]:[u(f),u(f),"none"]}dispose(){this.offDocEvents(),this.onSelectionChange&&document.removeEventListener("selectionchange",this.onSelectionChange),this.blinkTimer!==null&&window.clearInterval(this.blinkTimer),this.textarea?.remove(),this.textarea=null}};var Fm=(n,e={})=>{let t=n.getContext("webgl2",{alpha:!0,premultipliedAlpha:!0,antialias:!0,stencil:!0,preserveDrawingBuffer:!0,powerPreference:"high-performance"});if(!t)return null;let r=a=>{a.preventDefault(),e.onLost?.()},o=()=>e.onRestored?.();n.addEventListener("webglcontextlost",r),n.addEventListener("webglcontextrestored",o);let i=t.getExtension("WEBGL_debug_renderer_info"),s=i?String(t.getParameter(i.UNMASKED_RENDERER_WEBGL)):"unknown";return{gl:t,capabilities:{maxTextureSize:t.getParameter(t.MAX_TEXTURE_SIZE),maxTextureUnits:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),renderer:s},dispose:()=>{n.removeEventListener("webglcontextlost",r),n.removeEventListener("webglcontextrestored",o)}}};var ea=n=>n.trim().replace(/^['"]|['"]$/g,"").toLowerCase(),Om=n=>{let e=new Set;for(let t of n){let r=ea(t?.family??"");r&&e.add(r)}return e},B0=n=>{let e=new Set,t=o=>{if(!(typeof o!="string"||!o))for(let i of o.split(",")){let s=ea(i);s&&e.add(s)}};t(n.raw.fontFamily);let r=n.raw.styles;if(r&&typeof r=="object"){for(let o of Object.values(r))if(!(!o||typeof o!="object"))for(let i of Object.values(o))i&&typeof i=="object"&&t(i.fontFamily)}return e},Bm=(n,e)=>{let t=[],r=o=>{for(let i of o)if(i instanceof ye){for(let s of B0(i))if(e.has(s)){t.push(i);break}}else i instanceof J&&r(i.children)};return r(n),t};var ta=class{constructor(e,t,r,o){this.host=e;this.textRenderer=t;this.glyphAtlas=r;this.renderer=o}host;textRenderer;glyphAtlas;renderer;pendingSettle=new Set;invalidateNodeTextBakes(e){this.host.engineDisposed||(this.textRenderer.invalidateNodeBakes(e),e.markRenderDirty(),this.host.requestRenderAll())}handleFontsLoaded(e){if(this.host.engineDisposed||this.host.engineContextLost)return;let t=Om(e);t.size===0||!this.invalidateTextCachesFor(t)||(this.glyphAtlas.reset(),this.host.requestRenderAll(),this.host.render())}invalidateTextCachesFor(e){let t=Bm(this.host.document.nodes,e);if(t.length===0)return!1;for(let r of t)r.invalidateTextLayout(),this.textRenderer.invalidateNodeBakes(r);return lh(),this.renderer.invalidateTextDerivedBakes(),!0}queueSettle(e){if(!(this.host.engineDisposed||e.length===0))for(let t of e)this.pendingSettle.add(t)}consumePendingSettle(){if(this.pendingSettle.size===0)return;let e=new Set(this.pendingSettle);this.pendingSettle.clear(),this.invalidateTextCachesFor(e)}};var Nn=class{_value=0;_lastReason="";get value(){return this._value}get lastReason(){return this._lastReason}bump(e){this._value++,this._lastReason=e}};var pt=1024,W0=2,H0=256,Ht=n=>{let e=[.5,1,2,4];for(let t of e)if(n<=t+1e-6)return t;return e[e.length-1]},G0=256,ra=(n,e)=>{let t=Math.max(6,Math.ceil(n*e)),r=Math.max(G0,Math.ceil(n));return t<=r?{rs:t,scale:e}:{rs:r,scale:r/Math.max(1,n)}},na=class{gl;pages=new Map;currentPage=null;nextPageIndex=0;frameStamp=0;cells=new Map;tmpCanvas;disposed=!1;pageCap=12;pendingTrim=!1;_generation=0;provisionalFaces=new Map;faceLoads=new Map;onCellsInvalidated;onProvisionalSettled;detachFontsListener=null;epoch;constructor(e,t,r,o=new Nn){this.gl=e,this.onCellsInvalidated=t,this.onProvisionalSettled=r,this.epoch=o,this.tmpCanvas=document.createElement("canvas"),this.tmpCanvas.width=8,this.tmpCanvas.height=8;let i=this.fontSet();if(i&&typeof i.addEventListener=="function"){let s=()=>this.dropProvisionalCells();i.addEventListener("loadingdone",s),this.detachFontsListener=()=>i.removeEventListener("loadingdone",s)}}fontSet(){return typeof document>"u"?null:document.fonts??null}isFacePending(e,t){let r=this.fontSet();if(!r||typeof r.check!="function")return!1;try{if(!r.check(e))return!0;let o=t.fontFamily?.trim().replace(/^['"]|['"]$/g,"")??"";if(!o||o.includes(",")||ul.has(o.toLowerCase())||typeof r.forEach!="function")return!1;let i=!1;return r.forEach(s=>{i||typeof s?.family!="string"||(s.family===o||s.family.toLowerCase()===o.toLowerCase())&&(i=!0)}),!i}catch{return!1}}kickFaceLoad(e){if(this.faceLoads.has(e))return;let t=this.fontSet();if(!t||typeof t.load!="function")return;let r={};this.faceLoads.set(e,r);let o=()=>{this.faceLoads.get(e)===r&&this.faceLoads.delete(e)};try{t.load(e).then(o,o)}catch{o()}}dropProvisionalCells(){if(!(this.disposed||this.provisionalFaces.size===0)){for(let e of this.provisionalFaces.values())for(let t of e.keys)this.cells.delete(t);this.provisionalFaces.clear(),this.onCellsInvalidated?.()}}markFrame(){this.pendingTrim&&this.trimUnusedPages(),this.frameStamp++,this.settleProvisionalCells()}keepPagesForRetainedFrame(){for(let e of this.pages.values())e.lastFrame=this.frameStamp}trimUnusedPages(){let e=[...this.pages.values()].filter(r=>r.lastFrame<this.frameStamp).sort((r,o)=>r.lastFrame-o.lastFrame),t=!1;for(let r of e){if(this.pages.size<=this.pageCap)break;this.gl.deleteTexture(r.texture),this.pages.delete(r.index),this.currentPage===r&&(this.currentPage=null),t=!0}if(this.pendingTrim=this.pages.size>this.pageCap,!!t){for(let[r,o]of this.cells)this.pages.has(o.pageIndex)||this.cells.delete(r);for(let[r,o]of this.provisionalFaces){for(let i of o.keys)this.cells.has(i)||o.keys.delete(i);o.keys.size===0&&this.provisionalFaces.delete(r)}this._generation++,this.epoch.bump("atlas-trim")}}settleProvisionalCells(){if(this.disposed||this.provisionalFaces.size===0)return;let e=!1,t=new Set;for(let[r,o]of this.provisionalFaces)if(!this.isFacePending(r,o.style)){for(let s of o.keys)this.cells.delete(s);this.provisionalFaces.delete(r),e=!0;let i=ea(o.style.fontFamily??"");i&&t.add(i)}e&&(this.onCellsInvalidated?.(),t.size>0&&this.onProvisionalSettled?.([...t]))}reset(){let e=this.pages.size>0;if(!this.disposed&&e)for(let t of this.pages.values())this.gl.deleteTexture(t.texture);this.pages.clear(),this.currentPage=null,this.pendingTrim=!1,this.cells.clear(),this.provisionalFaces.clear(),e&&(this._generation++,this.epoch.bump("atlas-reset"),zn()&&console.warn("[retained] GlyphAtlas.reset → generation",this._generation,new Error("reset 调用栈取证").stack))}get generation(){return this._generation}stats(){return{pages:this.pages.size,cells:this.cells.size,pageCap:this.pageCap,pendingReset:!1,pendingTrim:this.pendingTrim,generation:this._generation}}get(e,t,r,o=null){if(this.disposed||r===" "||r===""||r===`
9
- `||r===" ")return null;let i=`${e.fontFamily}|${e.fontWeight??""}|${e.fontStyle??""}|${t}|${r}`;o&&(i+=`|S${o.width}|${o.lineJoin??""}|${o.lineCap??""}|${o.miterLimit??""}`);let s=this.cells.get(i);if(s)return this.pages.get(s.pageIndex).lastFrame=this.frameStamp,s;let a=Me(e,t),l=this.isFacePending(a,e);l&&this.kickFaceLoad(a);let u=this.rasterize(e,t,r,o);if(u&&(this.cells.set(i,u),l)){let c=this.provisionalFaces.get(a);c||(c={style:{fontFamily:e.fontFamily,fontSize:e.fontSize,fontWeight:e.fontWeight,fontStyle:e.fontStyle},keys:new Set},this.provisionalFaces.set(a,c)),c.keys.add(i)}return u}rasterize(e,t,r,o){let i=this.currentPage;i||(i=this.newPage());let s=i.ctx;s.font=Me(e,t),s.textBaseline="alphabetic",s.textAlign="left",s.fillStyle="#ffffff";let a=s.measureText(r);if(!isFinite(a.width)||a.width<=0&&r.trim()==="")return null;let l=a.actualBoundingBoxLeft??0,u=a.actualBoundingBoxRight??a.width,c=a.actualBoundingBoxAscent??t*.88,h=a.actualBoundingBoxDescent??t*.24,d=t/Math.max(1,e.fontSize),f=o?Math.max(.5,o.width*d):0,m=o?Math.min(f*Math.max(1,o.miterLimit??4)/2,H0):0,p=W0+(o?Math.ceil(m)+1:0),b=Math.max(1,Math.ceil(l+u)+p*2),g=Math.max(1,Math.ceil(c+h)+p*2);if(b>pt||g>pt)return null;i.cursorX+b>pt&&(i.cursorX=0,i.cursorY+=i.rowHeight,i.rowHeight=0),i.cursorY+g>pt&&(i=this.newPage());let x=i.ctx;x.font=Me(e,t),x.textBaseline="alphabetic",x.textAlign="left",x.fillStyle="#ffffff";let S=i.cursorX,w=i.cursorY,y=S+p+l,v=w+p+c;x.save(),o?(x.lineWidth=f,x.lineJoin=o.lineJoin??"miter",x.lineCap=o.lineCap??"butt",x.miterLimit=Math.max(1,o.miterLimit??4),x.strokeStyle="#ffffff",x.strokeText(r,y,v)):x.fillText(r,y,v),x.restore(),(this.tmpCanvas.width<b||this.tmpCanvas.height<g)&&(this.tmpCanvas.width=Math.max(this.tmpCanvas.width,b),this.tmpCanvas.height=Math.max(this.tmpCanvas.height,g));let R=this.tmpCanvas.getContext("2d");return R.clearRect(0,0,this.tmpCanvas.width,this.tmpCanvas.height),R.drawImage(i.canvas,S,w,b,g,0,0,b,g),this.gl.bindTexture(this.gl.TEXTURE_2D,i.texture),this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,S,w,b,g,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.tmpCanvas),i.cursorX+=b,i.rowHeight=Math.max(i.rowHeight,g),{pageIndex:i.index,u0:S/pt,v0:w/pt,u1:(S+b)/pt,v1:(w+g)/pt,wPx:b,hPx:g,inkLeftPx:-l,ascentPx:c,padPx:p,advancePx:a.width}}textureOf(e){let t=this.pages.get(e.pageIndex);return t?(t.lastFrame=this.frameStamp,t.texture):null}newPage(){this.pages.size>=this.pageCap&&(this.pendingTrim=!0);let e=document.createElement("canvas");e.width=pt,e.height=pt;let t=e.getContext("2d"),r=this.gl.createTexture();this.gl.bindTexture(this.gl.TEXTURE_2D,r),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,pt,pt,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE);let o={index:this.nextPageIndex++,lastFrame:this.frameStamp,canvas:e,ctx:t,texture:r,cursorX:0,cursorY:0,rowHeight:0};return this.pages.set(o.index,o),this.currentPage=o,o}dispose(){if(!this.disposed){this.disposed=!0,this.detachFontsListener?.(),this.detachFontsListener=null;for(let e of this.pages.values())this.gl.deleteTexture(e.texture);this.pages.clear(),this.currentPage=null,this.pendingTrim=!1,this.cells.clear(),this.provisionalFaces.clear(),this.faceLoads.clear()}}};var Ur=(n,e,t,r)=>{if(!t){n.uniform1i(e.paintMode,0);return}n.uniform1i(e.paintMode,t.kind==="gradient"?t.decl.kind==="linear"?1:2:3),n.uniformMatrix3fv(e.paintInv,!1,[t.inv[0],t.inv[1],0,t.inv[2],t.inv[3],0,t.inv[4],t.inv[5],1]),t.kind==="gradient"?t.decl.kind==="linear"?n.uniform4f(e.paintA,t.decl.x1,t.decl.y1,t.decl.x2,t.decl.y2):(n.uniform4f(e.paintA,t.decl.x1,t.decl.y1,t.decl.r1,0),n.uniform4f(e.paintB,t.decl.x2,t.decl.y2,t.decl.r2,0)):n.uniform4f(e.patInfo,t.size[0],t.size[1],t.repeat[0]?1:0,t.repeat[1]?1:0),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,t.tex),n.uniform1i(e.fillTex,r)},oa=class{gl;cache=new Map;disposed=!1;constructor(e){this.gl=e}get(e){if(this.disposed)return null;let t=pi(e),r=this.cache.get(t);if(r)return r;let o=this.gl,i=o.createTexture();if(!i)return null;let s=mi(e);return o.bindTexture(o.TEXTURE_2D,i),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,s.length/4,1,0,o.RGBA,o.UNSIGNED_BYTE,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),this.cache.set(t,i),i}invalidateAll(){for(let e of this.cache.values())this.gl.deleteTexture(e);this.cache.clear()}dispose(){this.disposed||(this.disposed=!0,this.invalidateAll())}};var X0=512*1024*1024,z0=2048,Y0=30,U0=32*1024*1024,ia=class{gl;cache=new Map;budgetBytes;maxEntries;evictGraceFrames;gestureActive=!1;frameStamp=0;frameTouches=0;evictions=0;trackedBytes=0;disposed=!1;epoch;constructor(e,t={}){this.gl=e,this.budgetBytes=t.budgetBytes??X0,this.maxEntries=t.maxEntries??z0,this.evictGraceFrames=t.evictGraceFrames??Y0,this.epoch=t.epoch??new Nn}markFrame(e=!1){this.frameStamp+=1,this.frameTouches=0,this.gestureActive=e}get evictionCount(){return this.evictions}setBudget(e){e>0&&(this.budgetBytes=e,this.evictIfNeeded(0,!1))}get(e){if(this.disposed)return null;let t=this.cache.get(e);if(t)return t.lastFrame=this.frameStamp,this.frameTouches+=1,this.cache.delete(e),this.cache.set(e,t),t.tex;let r=this.gl.createTexture();if(!r)return null;let o=!(e instanceof HTMLVideoElement);this.gl.bindTexture(this.gl.TEXTURE_2D,r),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),o?(this.gl.generateMipmap(this.gl.TEXTURE_2D),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR_MIPMAP_LINEAR)):this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE);let i=$0(e,o),s={tex:r,mipmap:o,bytes:i,lastFrame:this.frameStamp};return this.evictIfNeeded(i,!0),this.trackedBytes+=i,this.frameTouches+=1,this.cache.set(e,s),r}evictIfNeeded(e,t){if(!this.disposed&&!(t&&this.gestureActive)){for(;this.trackedBytes+e>this.budgetBytes||this.cache.size>=this.maxEntries;)if(!(this.evictOldestEligible(t,!1)||this.evictOldestEligible(t,!0)))return}}evictOldestEligible(e,t){for(let[r,o]of this.cache)if(!(e&&this.frameStamp-o.lastFrame<this.evictGraceFrames)&&!(!t&&o.bytes>=U0))return this.gl.deleteTexture(o.tex),this.cache.delete(r),this.trackedBytes-=o.bytes,this.evictions+=1,this.epoch.bump("texture-evict"),!0;return!1}update(e){if(this.disposed)return;let t=this.cache.get(e);t&&(this.gl.bindTexture(this.gl.TEXTURE_2D,t.tex),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),t.mipmap&&this.gl.generateMipmap(this.gl.TEXTURE_2D))}remove(e){let t=this.cache.get(e);t&&(this.gl.deleteTexture(t.tex),this.cache.delete(e),this.trackedBytes-=t.bytes)}invalidateAll(){for(let e of this.cache.values())this.gl.deleteTexture(e.tex);this.cache.clear(),this.trackedBytes=0}stats(){return{entries:this.cache.size,bytes:this.trackedBytes,budgetBytes:this.budgetBytes,maxEntries:this.maxEntries,evictions:this.evictions,frameTouches:this.frameTouches}}dispose(){this.disposed||(this.disposed=!0,this.invalidateAll())}},$0=(n,e)=>{let t=n instanceof HTMLVideoElement?n.videoWidth:n instanceof HTMLImageElement&&n.naturalWidth||n.width,r=n instanceof HTMLVideoElement?n.videoHeight:n instanceof HTMLImageElement&&n.naturalHeight||n.height,o=Math.max(1,t)*Math.max(1,r)*4;return Math.round(e?o*(4/3):o)};var Wm=`#version 300 es
6
+ `){c+=1;continue}if(!h.highlight||h.highlight.type!=="svg"||!h.highlight.svgInfo){c+=h.text.length;continue}let d=h.highlight.svgInfo,f=u(c);if(f===-1){c+=h.text.length;continue}let m=o[f],p=0,b=m,g=0,x=S=>{if(p>=S)return;let w=u(c+p),y=u(c+g);w===-1||y===-1||l.push({lineIndex:b,start:i[w],end:i[y]+1,info:d})};for(let S=0;S<h.text.length;S++){let w=u(c+S);if(w===-1){x(S),p=S+1;continue}let y=o[w];y!==m&&(x(S),p=S,m=y),b=y,g=S}x(h.text.length),c+=h.text.length}return l},gl=(n,e,t,r,o,i)=>{let s=r||e;return i==="bottom"?n+e-(t+s)*o:i==="top"?n-t*o:n+(e-s*o)/2-t*o},Sh=n=>{let e=Ce(n);if(!e)return null;let t=Fe(e);return t?{left:t.left,top:t.top,width:t.right-t.left,height:t.bottom-t.top}:null},Ag=n=>{let e=n.split(/[Zz]/).map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)return null;let t=e[0];return t.endsWith("Z")||t.endsWith("z")?t:`${t} Z`},Jn=(n,e,t,r,o)=>{let i=kg(n,e,t);if(i.length===0)return null;let s=[],a={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},l=(f,m)=>{let p=f.isFill?0:(f.strokeWidth||0)*Math.abs(f.scaleX)/2,b=f.isFill?0:(f.strokeWidth||0)*Math.abs(f.scaleY)/2,g=f.translateX+m.left*f.scaleX-p,x=f.translateY+m.top*f.scaleY-b,S=f.translateX+(m.left+m.width)*f.scaleX+p,w=f.translateY+(m.top+m.height)*f.scaleY+b;g<a.minX&&(a.minX=g),x<a.minY&&(a.minY=x),S>a.maxX&&(a.maxX=S),w>a.maxY&&(a.maxY=w)};for(let f of i){let m=e.lines[f.lineIndex];if(!m)continue;let p=f.info,b=typeof p.path=="string"?p.path:"";if(!b)continue;let g=p.alignVertical||"center",x=p.isFill===!0,S=p.strokeWidth||0,w=-e.width/2+m.leftOffset,y=r+m.top,v=Li(m,f.start,o);if(!v)continue;if(p.isSingle===!0){let z=Ag(b);if(!z)continue;let _=Sh(z);if(!_||!Number.isFinite(_.width)||!Number.isFinite(_.height))continue;let D=z;for(let I=f.start;I<f.end;I++){let G=m.graphemes[I];if(!G||/^\s$/.test(G))continue;let $=Li(m,I,o),V=Li(m,I+1,o);if(!$)continue;let H=w+$.left,Y=y,X=$.kernedWidth||$.width||(V?V.left:$.left)-$.left,Z=$.height,B=_.height;B||(B=Z);let q=_.width?X/_.width:1,U=B?Z/B:1,oe=p.scale||1,ne=Math.min(q,U)*oe,de=(_.width||0)*ne,Pe=H+(X-de)/2-_.left*ne,De=g==="bottom"?Y+Z-_.top*ne:gl(Y,Z,_.top,B,ne,g),nt={d:D,translateX:Pe,translateY:De,scaleX:ne,scaleY:ne,isFill:x,fill:p.fill||"#9FFFFC",stroke:p.stroke||"#9FFFFC",strokeWidth:S};s.push(nt),l(nt,_)}continue}let R=Li(m,f.end,o);if(!R)continue;let P=w+v.left,T=R.left-v.left,C=v.height,E=Sh(b);if(!E||!Number.isFinite(E.width)||!Number.isFinite(E.height)||E.width===0)continue;let M=E.height;M||(M=C);let k=T/E.width,A=C/M,O=P-E.left*k,F=gl(y,C,E.top,M,A,g);if(g==="bottom"||g==="top"){let z=E.top+M,_=z>0?z:M||1;A=C/_,F=gl(y,C,E.top,M,A,g)}E.height||(F+=C/2);let W={d:b,translateX:O,translateY:F,scaleX:k,scaleY:A,isFill:x,fill:p.fill||"#9FFFFC",stroke:p.stroke||"#9FFFFC",strokeWidth:S};s.push(W),l(W,E)}if(s.length===0)return null;let u=e.width/2,c=Number.isFinite(a.minX)&&Number.isFinite(a.minY),h=c?Math.max(2,-u-a.minX,a.maxX-u):2,d=c?Math.max(2,r-a.minY,a.maxY-(r+e.height)):2;return{ops:s,padX:h,padY:d,inkBounds:{left:a.minX,top:a.minY,right:a.maxX,bottom:a.maxY}}},vh=(n,e,t,r)=>{let o=Math.ceil(e.width+n.padX*2),i=Math.ceil(e.height+n.padY*2);if(!(o>0)||!(i>0)||o>8192||i>8192)return null;let s=document.createElement("canvas");s.width=Math.ceil(o*r),s.height=Math.ceil(i*r);let a=s.getContext("2d");if(!a)return null;a.setTransform(r,0,0,r,0,0),a.translate(e.width/2+n.padX,n.padY-t);for(let l of n.ops){let u=new Path2D(l.d);a.save(),a.translate(l.translateX,l.translateY),a.scale(l.scaleX,l.scaleY),l.isFill?(a.fillStyle=l.fill,a.fill(u)):(a.lineWidth=l.strokeWidth,a.strokeStyle=l.stroke,a.stroke(u)),a.restore()}return{canvas:s,logicalW:o,logicalH:i}};var co=n=>{let e=n.pathBackground;if(!e||!e.backgroundChecked||typeof e.path!="string"||!e.path.trim())return null;let t=Number(e.width)||0,r=Number(e.height)||0;if(!t||!r)return null;let o=typeof e.fill=="string"&&e.fill?e.fill:void 0;return{path:e.path,fill:o,width:t,height:r}};var Ii=n=>{let e=n.raw,t=co(e);if(!t||!t.fill)return null;let r=n.dims;if(!r.x||!r.y)return null;let o=Ce(t.path);if(!o)return null;let i=Fe(o);if(!i)return null;let s=i.right-i.left,a=i.bottom-i.top;if(!(s>0)||!(a>0))return null;let l=r.x/t.width,u=r.y/t.height,c=s*l,h=a*u;return!(c>0)||!(h>0)||c>8192||h>8192?null:{path:t.path,fill:t.fill,bounds:i,scaleX:l,scaleY:u,logicalW:c,logicalH:h,sigBase:[t.path,t.fill,t.width,t.height,r.x.toFixed(3),r.y.toFixed(3)].join(";")}},wh=(n,e)=>{let t=document.createElement("canvas");t.width=Math.ceil(n.logicalW*e),t.height=Math.ceil(n.logicalH*e);let r=t.getContext("2d");if(!r)return null;let o=(n.bounds.left+n.bounds.right)/2,i=(n.bounds.top+n.bounds.bottom)/2;r.setTransform(e*n.scaleX,0,0,e*n.scaleY,t.width/2-o*n.scaleX*e,t.height/2-i*n.scaleY*e);let s=ee(n.fill);return r.fillStyle=`rgba(${Math.round(s[0]*255)}, ${Math.round(s[1]*255)}, ${Math.round(s[2]*255)}, ${s[3]})`,r.fill(new Path2D(n.path),"nonzero"),{canvas:t,logicalW:n.logicalW,logicalH:n.logicalH}};var Th=n=>{if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n,t=Number(e.blur)||0,r=Number(e.offsetX)||0,o=Number(e.offsetY)||0;if(!t&&!r&&!o)return null;let i=typeof e.color=="string"&&e.color?e.color:"rgb(0,0,0)";return{color:i,rgba:ee(i),blur:t,offsetX:r,offsetY:o,nonScaling:!!e.nonScaling}},Lt=(n,e,t)=>{if(n.nonScaling)return{blur:n.blur,offX:n.offsetX,offY:n.offsetY};let r=Math.abs(e),o=Math.abs(t);return{blur:n.blur*(r+o)/2,offX:n.offsetX*r,offY:n.offsetY*o}},_i=n=>Math.ceil(n.blur*2+Math.max(Math.abs(n.offX),Math.abs(n.offY))+4),Eh=n=>{let e=t=>String(Math.round(t*1e4)/1e4);return[n.color,e(n.blur),e(n.offsetX),e(n.offsetY),n.nonScaling?1:0].join("|")};var Vt=(n,e,t,r,o)=>{let i=[],s=o?r.fontSize*o/1e3:0,a=0;for(let l=0;l<n.graphemes.length;l++){let u=n.graphemes[l],c=n.boxes[l],h=n.charStyles[l]?.fontSize??r.fontSize,d=qn(u);d==="latin"||d==="bracket"?i.push({ch:u,rotated:!1,x:e+a+(d==="latin"?c.kernedWidth-c.width:0),y:t}):i.push({ch:u,rotated:!0,x:e+a+un(h),y:t+yr(d,c,h)}),a+=Kn(u,c,s)}return i},qt=(n,e,t)=>{if(!e.rotated){n[t](e.ch,e.x,e.y);return}n.save(),n.translate(e.x,e.y),n.rotate(-Math.PI/2),n[t](e.ch,0,0),n.restore()},fn=(n,e)=>!e||e.fontSize===void 0&&e.fontFamily===void 0&&e.fontWeight===void 0&&e.fontStyle===void 0?n:{...n,fontSize:e.fontSize??n.fontSize,fontFamily:e.fontFamily??n.fontFamily,fontWeight:e.fontWeight??n.fontWeight,fontStyle:e.fontStyle??n.fontStyle};var xl=n=>{let e=n.matrix,t=n.dims.x,r=n.dims.y;return{x:Math.abs(e[0])*t+Math.abs(e[2])*r,y:Math.abs(e[1])*t+Math.abs(e[3])*r}},Fi=n=>{let e=n.raw;return JSON.stringify([e.path,e.points,e.rx,e.ry,e.radius])},yl=(n,e,t)=>{let r=e.textLayout,o=e.textStyle;n.fillStyle=t,n.textBaseline="alphabetic";let i=e.raw.vertical===!0,s=Number(e.raw.textOffsetY)||0,a=0;for(let l of r.lines){let u=-r.width/2+l.leftOffset,c=e.contentTopY+l.baseline;if(l.prefix&&Tt(n,l,u,c,{fill:"keep"}),i){let h=Vt(l,u,c,o,o.charSpacing??0);for(let d=0;d<h.length;d++){let f=fn(o,l.charStyles[d]);n.font=Me(f,f.fontSize),qt(n,{...h[d],y:h[d].y+wt(s,f.fontSize,a+d)},"fillText")}a+=l.graphemes.length;continue}for(let h=0;h<l.graphemes.length;h++){let d=l.charStyles[h],f=fn(o,d);n.font=Me(f,f.fontSize),n.fillText(l.graphemes[h],u+l.boxes[h].left,c+wt(s,f.fontSize,a+h))}a+=l.graphemes.length}},Di=(n,e,t)=>{let r=e.dims.x,o=e.dims.y;if(e.isSolidType){n.fillStyle=t;let i=it(e.raw,r,o);if(i){jn(n,r,o,i.rx,i.ry),n.fill();return}n.fillRect(-r/2,-o/2,r,o);return}if(e.isShapeType){let i=e.raw;if(se(i)===L.ELLIPSE||se(i)===L.CIRCLE){n.fillStyle=t,n.beginPath(),n.ellipse(0,0,r/2,o/2,0,0,Math.PI*2),n.fill();return}let s=e.shapeMesh;if(!s)return;n.fillStyle=t,n.beginPath();let a=s.verts.length/2;for(let l=0;l<a;l++){let u=s.verts[l*2],c=s.verts[l*2+1];l===0?n.moveTo(u,c):n.lineTo(u,c)}n.closePath(),n.fill();return}if(e instanceof ie){let i=e.paintSource;i&&n.drawImage(i,-r/2,-o/2,r,o);return}if((e.isImageType||e.isMaskType)&&e.imageEl){let i=e.cropRect,s=e.isImageType&&!(e instanceof ie)?br(e.raw,r,o):null;s&&(n.save(),jn(n,r,o,s,s),n.clip()),i?n.drawImage(e.imageEl,i.sx,i.sy,i.sw,i.sh,-r/2,-o/2,r,o):n.drawImage(e.imageEl,-r/2,-o/2,r,o),s&&n.restore();return}if(e.isTextType&&e instanceof ye){if(Kt(e)){if(!e.imageEl)return;let i=e.bitmapRect;n.save(),n.translate(i.x,i.y),i.angle&&n.rotate(-i.angle*Math.PI/180),n.drawImage(e.imageEl,-i.w/2,-i.h/2,i.w,i.h),n.restore();return}yl(n,e,t)}},Ch=(n,e)=>{let t=Lt(e,n.raw.scaleX??1,n.raw.scaleY??1),r=_i(t)+(n.isTextType?Math.ceil((n.raw.fontSize??40)*.5):0),o=xl(n),i=Math.ceil(o.x+r*2),s=Math.ceil(o.y+r*2);if(!(i>0)||!(s>0)||i>8192||s>8192)return null;let a=document.createElement("canvas");a.width=i,a.height=s;let l=a.getContext("2d");if(!l)return null;let u=n.matrix;l.setTransform(u[0],u[1],u[2],u[3],i/2,s/2);let c=`rgba(${Math.round(e.rgba[0]*255)},${Math.round(e.rgba[1]*255)},${Math.round(e.rgba[2]*255)},1)`;return l.shadowColor=e.color,l.shadowBlur=t.blur,l.shadowOffsetX=t.offX,l.shadowOffsetY=t.offY,Di(l,n,c),l.shadowColor="rgba(0,0,0,0)",l.shadowBlur=0,l.shadowOffsetX=0,l.shadowOffsetY=0,l.globalCompositeOperation="destination-out",Di(l,n,c),{canvas:a,w:i,h:s}};var uo=(n,e,t)=>{let r=e+t,o=n,i=new Int32Array(e*t);for(let f=0;f<e;f++){o[f+0*e]?i[f+0*e]=0:i[f+0*e]=r;for(let m=1;m<t;m++)o[f+m*e]?i[f+m*e]=0:i[f+m*e]=1+i[f+(m-1)*e];for(let m=t-2;m>=0;m--)i[f+(m+1)*e]<i[f+m*e]&&(i[f+m*e]=1+i[f+(m+1)*e])}let s=(f,m,p)=>(f-m)*(f-m)+p*p,a=(f,m,p,b)=>Math.floor((m*m-f*f+b*b-p*p)/(2*(m-f))),l=new Int32Array(e*t),u=new Int32Array(e),c=new Int32Array(e),h,d;for(let f=0;f<t;f++){h=0,u[0]=0,c[0]=0;for(let m=1;m<e;m++){for(;h>=0&&s(c[h],u[h],i[u[h]+f*e])>s(c[h],m,i[m+f*e]);)h--;h<0?(h=0,u[0]=m):(d=1+a(u[h],m,i[u[h]+f*e],i[m+f*e]),d<e&&(h++,u[h]=m,c[h]=d))}for(let m=e-1;m>=0;m--){let p=s(m,u[h],i[u[h]+f*e]);p=Math.floor(Math.sqrt(p)),l[m+f*e]=p,m===c[h]&&h--}}return l},Sl=(n,e=10)=>{let t=new Uint8Array(n.length/4);for(let r=0;r<t.length;r++)t[r]=n[r*4+3]>e?1:0;return t};var Mh=(n,e)=>e==="smooth"?6*n*(1-n):1,Rh=(n,e,t,r,o,i)=>{let s=r*o,a=new Float32Array(s),l=new Float32Array(s),u=Math.max(i.sizePx,.5),c=i.angleDeg*Math.PI/180,h=Math.sin(c),d=-Math.cos(c),f=Math.max(0,i.strength)*((90-Math.min(90,Math.max(0,i.altitudeDeg)))/90),m=i.style==="pillow"!==i.directionDown,p=i.style==="inner"||i.style==="emboss"||i.style==="pillow",b=i.style==="outer"||i.style==="emboss"||i.style==="pillow",g=(w,y,v)=>{let R=Math.min(1,Math.max(0,y)*v*f);R<=0||(m?l[w]=Math.min(1,l[w]+R):a[w]=Math.min(1,a[w]+R))},x=(w,y,v)=>{let R=Math.min(1,Math.max(0,-y)*v*f);R<=0||(m?a[w]=Math.min(1,a[w]+R):l[w]=Math.min(1,l[w]+R))},S=(w,y,v)=>{let R=w[Math.min(y+1,r-1)+v*r]-w[Math.max(y-1,0)+v*r],P=w[y+Math.min(v+1,o-1)*r]-w[y+Math.max(v-1,0)*r];return[R,P]};for(let w=0;w<o;w++)for(let y=0;y<r;y++){let v=y+w*r;if(t[v]){if(!p)continue;let R=n[v]-.5;if(R>=u)continue;let P=Math.max(0,R/u),[T,C]=S(n,y,w),E=Math.hypot(T,C);if(E<1e-6)continue;let M=-(T/E*h+C/E*d),k=Mh(P,i.technique);g(v,M,k),x(v,M,k)}else{if(!b)continue;let R=e[v]-.5;if(R>=u)continue;let P=Math.max(0,1-R/u),[T,C]=S(e,y,w),E=Math.hypot(T,C);if(E<1e-6)continue;let M=T/E*h+C/E*d,k=Mh(P,i.technique);g(v,M,k),x(v,M,k)}}return{highlight:a,shadow:l}};var Ph={Brownie:[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0],Vintage:[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0],Kodachrome:[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0],Technicolor:[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0],Polaroid:[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],Sepia:[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0],BlackWhite:[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]},me=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,mn=(n,e)=>typeof n=="string"&&n?n:e,vl=(n,e)=>typeof n=="boolean"?n:e;function Ng(n){let e=i=>Math.max(0,Math.min(255,Math.round(i))),t=n.map(i=>({input:e(i.input),output:e(i.output)}));t.sort((i,s)=>i.input-s.input);let r=[];for(let i of t)r.length&&r[r.length-1].input===i.input?r[r.length-1]=i:r.push(i);if(r.length<2)return[];if(r.length<=16)return r;let o=[];for(let i=0;i<16;i++){let s=e(i/15*255);o.push({input:s,output:e(Lg(r,s))})}return o}function Lg(n,e){if(n.length===0)return e;let t=n[0],r=n[n.length-1];if(e<=t.input)return t.output;if(e>=r.input)return r.output;for(let o=0;o<n.length-1;o++){let i=n[o],s=n[o+1];if(e>=i.input&&e<=s.input){let a=(e-i.input)/Math.max(1e-5,s.input-i.input);return i.output+(s.output-i.output)*a}}return e}function Ig(n){if(!Array.isArray(n))return[];let e=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r,i=o.input,s=o.output;typeof i!="number"||!Number.isFinite(i)||typeof s!="number"||!Number.isFinite(s)||e.push({input:i,output:s})}let t=[];for(let r of Ng(e))t.push(r.input,r.output);return t}function ho(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,o=r.psd===1;switch(r.type){case"Brightness":e.push({kind:"Brightness",brightness:o?me(r.brightness,0)/100:me(r.brightness,0)});break;case"Contrast":e.push({kind:"Contrast",contrast:o?me(r.contrast,0)/100:me(r.contrast,0)});break;case"Saturation":e.push({kind:"Saturation",saturation:o?me(r.saturation,0)/100:me(r.saturation,0)});break;case"Vibrance":e.push({kind:"Vibrance",vibrance:o?me(r.vibrance,0)/100:me(r.vibrance,0)});break;case"HueRotation":e.push({kind:"HueRotation",rotation:o?me(r.hue,0)/100:me(r.rotation,0)});break;case"Grayscale":{let i=mn(r.mode,"average");e.push({kind:"Grayscale",mode:i==="lightness"||i==="luminosity"?i:"average"});break}case"Invert":e.push({kind:"Invert",invert:vl(r.invert,!0),alphaOnly:vl(r.alphaOnly,!1)});break;case"Sepia":case"Brownie":case"Kodachrome":case"Technicolor":case"Polaroid":case"BlackWhite":case"Vintage":e.push({kind:"ColorMatrix",matrixId:r.type});break;case"ColorMatrix":{let i=Array.isArray(r.matrix)?r.matrix.filter(s=>typeof s=="number"&&Number.isFinite(s)):[];i.length===20&&e.push({kind:"ColorMatrixOp",matrix:i});break}case"Blur":e.push({kind:"Blur",blur:me(o?r.radius:r.blur,0)});break;case"Noise":e.push({kind:"Noise",noise:me(r.noise,0)});break;case"Pixelate":e.push({kind:"Pixelate",blocksize:me(r.blocksize,1)});break;case"Convolute":{let i=Array.isArray(r.matrix)?r.matrix.filter(a=>typeof a=="number"):[],s=Math.sqrt(i.length);Number.isInteger(s)&&s>=3&&s<=9&&e.push({kind:"Convolute",matrix:i,opaque:vl(r.opaque,!1)});break}case"BlendColor":{let i=mn(r.mode,"multiply"),s=["multiply","screen","add","difference","subtract","darken","lighten","overlay","exclusion","tint"];e.push({kind:"BlendColor",color:mn(r.color,"#000000"),mode:s.includes(i)?i:"multiply",alpha:me(r.alpha,1)});break}case"Vignette":e.push({kind:"Vignette",intensity:me(r.intensity,0)});break;case"Temperature":{if(o){let i=pn(mn(r.color,"#ffb86b")),s=i[0]>=i[2];e.push({kind:"Temperature",temperature:me(r.density,0)/100*(s?1:-1)})}else e.push({kind:"Temperature",temperature:me(r.temperature,0)});break}case"Posterize":e.push({kind:"Posterize",levels:me(r.levels,20)});break;case"FilmGrain":e.push({kind:"FilmGrain",intensity:me(r.intensity,0),seed:me(r.seed,0)});break;case"Duotone":e.push({kind:"Duotone",color1:mn(r.color1,"#000000"),color2:mn(r.color2,"#ffffff")});break;case"Sketch":e.push({kind:"Sketch"});break;case"ChromaticAberration":e.push({kind:"ChromaticAberration",offset:me(r.offset,4)});break;case"SoftFocus":e.push({kind:"SoftFocus",blend:me(r.blend,.5)});break;case"Threshold":e.push({kind:"Threshold",threshold:me(r.threshold,128)});break;case"UnsharpMask":e.push({kind:"UnsharpMask",amount:o?me(r.amount,100)/100:me(r.amount,1)});break;case"MotionBlur":e.push({kind:"MotionBlur",distance:me(r.distance,0),angle:me(r.angle,0)});break;case"LensFlare":e.push({kind:"LensFlare",intensity:me(r.intensity,.8)});break;case"GradientMap":e.push({kind:"GradientMap",color0:mn(r.color0,"#000000"),color1:mn(r.color1,"#888888"),color2:typeof r.color2=="string"&&r.color2?r.color2:""});break;case"Levels":e.push({kind:"Levels",blackPoint:me(r.blackPoint,0),whitePoint:me(r.whitePoint,255),gamma:me(r.gamma,1)});break;case"Curves":e.push({kind:"Curves",points:Ig(r.points)});break;case"SurfaceBlur":e.push({kind:"SurfaceBlur",radius:me(r.radius,3),threshold:o?me(r.threshold,51)/255:me(r.threshold,.2)});break;case"Exposure":e.push({kind:"Exposure",exposure:me(r.exposure,0),offset:me(r.offset,0),gamma:me(r.gamma,1)});break;default:break}}return e}function Oi(n){return JSON.stringify(n)}var tT=Math.PI/2;function pn(n){let e=n.replace("#","");return/^[0-9a-fA-F]{6}$/.test(e)?[parseInt(e.substring(0,2),16),parseInt(e.substring(2,4),16),parseInt(e.substring(4,6),16)]:[0,0,0]}var wl=new Map,kh=(n,e)=>{wl.set(n,new WeakRef(e))},_g=n=>{let e=wl.get(n);if(!e)return null;let t=e.deref();return t||(wl.delete(n),null)},Ah=n=>_g(n);var Qt=(n,e,t,r,o,i,s)=>{t?n.drawImage(e,t.sx,t.sy,t.sw,t.sh,r,o,i,s):n.drawImage(e,r,o,i,s)},Dg=6e5,Bi=n=>Math.max(1,Math.floor(Math.sqrt(Dg/Math.max(1,n.dims.x*n.dims.y)))),Wi=n=>{if(!n.isImageType||n instanceof ie)return"";let e=ho(n.raw.filters);return e.length?`|f${Oi(e)}`:""},It=n=>!n.isImageType||n instanceof ie?null:br(n.raw,n.dims.x,n.dims.y),Lh=n=>{let e=It(n);return e?`|rr${e}`:""},Tl=(n,e,t,r,o,i,s)=>{n.save(),n.translate(t,r),e&&(jn(n,o,i,e,e),n.clip()),s(),n.restore()},fo=(n,e,t,r,o)=>{if(!t)return n;let i=document.createElement("canvas");i.width=r,i.height=o;let s=i.getContext("2d",{willReadFrequently:!0});return s?(Tl(s,t,r/2,o/2,r,o,()=>Qt(s,n,e,-r/2,-o/2,r,o)),i):n},Fg=n=>{let e=n.matrix,t=n.dims.x,r=n.dims.y;return{x:Math.abs(e[0])*t+Math.abs(e[2])*r,y:Math.abs(e[1])*t+Math.abs(e[3])*r}},Nh=n=>({color:n.color,rgba:n.rgba,blur:n.blur,offsetX:n.offsetX,offsetY:n.offsetY,nonScaling:!1}),mo=(n,e=1)=>{let t=Math.max(1,Math.ceil(n.dims.x*e)),r=Math.max(1,Math.ceil(n.dims.y*e));if(t>8192||r>8192)return null;let o=document.createElement("canvas");o.width=t,o.height=r;let i=o.getContext("2d");return i?(i.translate(t/2,r/2),i.scale(e,e),yl(i,n,"#ffffff"),o):null},Hi=(n,e,t,r=1,o=null)=>{if(!t||e.length===0)return null;let i=n.raw.scaleX??1,s=n.raw.scaleY??1,a=4;for(let y of e){let v=Lt(Nh(y),i,s);a=Math.max(a,Math.ceil(v.blur*2+Math.max(Math.abs(v.offX),Math.abs(v.offY))+4))}let l=Fg(n),u=Math.ceil(l.x+a*2),c=Math.ceil(l.y+a*2),h=Math.ceil(u*r),d=Math.ceil(c*r);if(!(u>0)||!(c>0)||h>8192||d>8192)return null;let f=It(n),m=f?fo(t,o,f*r,Math.max(1,Math.ceil(n.dims.x*r)),Math.max(1,Math.ceil(n.dims.y*r))):t,p=f?null:o,b=document.createElement("canvas");b.width=h,b.height=d;let g=b.getContext("2d");if(!g)return null;let x=n.matrix;g.setTransform(x[0]*r,x[1]*r,x[2]*r,x[3]*r,h/2,d/2);let S=n.dims.x,w=n.dims.y;for(let y of e){let v=Lt(Nh(y),i,s);g.filter=`drop-shadow(${v.offX*r}px ${v.offY*r}px ${v.blur*r}px ${y.color})`,Qt(g,m,p,-S/2,-w/2,S,w)}return g.filter="none",g.globalCompositeOperation="destination-out",Qt(g,m,p,-S/2,-w/2,S,w),{canvas:b,w:h,h:d,quadW:u,quadH:c}},Ih=(n,e,t)=>{let r=[1,0,0,1,n.offsetX,n.offsetY];return n.gradientUnits==="percentage"&&(r=j(r,[e,0,0,t,0,0])),n.gradientTransform&&(r=j(r,n.gradientTransform)),r},Og=(n,e,t,r)=>{let o=j([1,0,0,1,r,r],Ih(n,e,t)),i=ve(o),s=mi(n,512),a=511,l=n.kind==="linear";return(u,c)=>{let h=u+.5,d=c+.5,f=i[0]*h+i[2]*d+i[4],m=i[1]*h+i[3]*d+i[5],p=l?Iu(n,{x:f,y:m}):_u(n,{x:f,y:m}),b=Math.min(a,Math.max(0,Math.round((isFinite(p)?p:0)*a)));return[s[b*4],s[b*4+1],s[b*4+2],s[b*4+3]]}},_h=(n,e,t,r)=>{let o=ve(e),i=[Q(o,0,0),Q(o,t,0),Q(o,0,r),Q(o,t,r)];if(i.every(s=>isFinite(s.x)&&isFinite(s.y))){let s=Math.min(...i.map(c=>c.x))-2,a=Math.max(...i.map(c=>c.x))+2,l=Math.min(...i.map(c=>c.y))-2,u=Math.max(...i.map(c=>c.y))+2;n.fillRect(s,l,a-s,u-l)}else n.fillRect(-t-r,-t-r,(t+r)*3,(t+r)*3)},Bg=(n,e,t,r,o,i)=>{let s=i(e.src);if(!s)return!1;let a;try{a=n.createPattern(s,e.repeat)}catch{return!1}if(!a)return!1;let l=[o,0,0,o,0,0];return l=j(l,[1,0,0,1,e.offsetX,e.offsetY]),e.patternTransform&&(l=j(l,e.patternTransform)),n.setTransform(l[0],l[1],l[2],l[3],l[4],l[5]),n.fillStyle=a,_h(n,l,t,r),n.setTransform(1,0,0,1,0,0),!0},vr=(n,e,t,r=1,o=null,i=Ah)=>{if(!t)return null;let s=Math.max(1,Math.ceil(n.dims.x)),a=Math.max(1,Math.ceil(n.dims.y)),l=Math.ceil(s*r),u=Math.ceil(a*r);if(l>8192||u>8192)return null;let c=document.createElement("canvas");c.width=l,c.height=u;let h=c.getContext("2d");if(!h)return null;if(e.kind==="gradient"){let f=e.decl,m=Ih(f,l,u);h.setTransform(m[0],m[1],m[2],m[3],m[4],m[5]);let p=f.kind==="linear"?h.createLinearGradient(f.x1,f.y1,f.x2,f.y2):h.createRadialGradient(f.x1,f.y1,f.r1,f.x2,f.y2,f.r2);for(let b of f.stops){let g=Math.min(1,Math.max(0,b.offset));p.addColorStop(g,`rgba(${Math.round(b.color[0]*255)}, ${Math.round(b.color[1]*255)}, ${Math.round(b.color[2]*255)}, ${b.color[3]})`)}h.fillStyle=p,f.gradientUnits==="percentage"?h.fillRect(-2,-2,5,5):_h(h,m,l,u),h.setTransform(1,0,0,1,0,0)}else if(e.kind==="pattern"){if(!Bg(h,e.decl,l,u,r,i))return null}else h.fillStyle=e.color,h.fillRect(0,0,l,u);h.globalCompositeOperation="destination-in";let d=It(n);return d?Qt(h,fo(t,o,d*r,l,u),null,0,0,l,u):Qt(h,t,o,0,0,l,u),c},Dh=(n,e)=>{if(e.length===0)return null;let t=n.raw.fill;if(t==null||t===""||t==="transparent")return null;let r=Math.abs(n.matrix[0])*n.dims.x+Math.abs(n.matrix[2])*n.dims.y,o=Math.abs(n.matrix[1])*n.dims.x+Math.abs(n.matrix[3])*n.dims.y,i=4;for(let h of e)i=Math.max(i,Math.ceil(h.blur*2+Math.max(Math.abs(h.offsetX),Math.abs(h.offsetY))+4));let s=Math.ceil(r+i*2),a=Math.ceil(o+i*2);if(!(s>0)||!(a>0)||s>8192||a>8192)return null;let l=document.createElement("canvas");l.width=s,l.height=a;let u=l.getContext("2d");if(!u)return null;let c=n.matrix;u.setTransform(c[0],c[1],c[2],c[3],s/2,a/2);for(let h of e){if(u.filter=`drop-shadow(${h.offsetX}px ${h.offsetY}px ${h.blur}px ${h.color})`,u.fillStyle=to(n,u),!xr(u,n))return null;u.fill()}return u.filter="none",{canvas:l,w:s,h:a,quadW:s,quadH:a}},Fh=(n,e=1)=>{let t=Math.max(1,Math.ceil(n.dims.x*e)),r=Math.max(1,Math.ceil(n.dims.y*e));if(t>8192||r>8192)return null;let o=document.createElement("canvas");o.width=t,o.height=r;let i=o.getContext("2d");return!i||(i.setTransform(e,0,0,e,t/2,r/2),i.fillStyle="#fff",!xr(i,n))?null:(i.fill(n.raw.fillRule==="evenodd"?"evenodd":"nonzero"),o)},wr=(n,e,t,r=1,o=null)=>{if(!t)return null;let i=Math.max(1,Math.ceil(n.dims.x)),s=Math.max(1,Math.ceil(n.dims.y)),a=Math.ceil(i*r),l=Math.ceil(s*r);if(a>8192||l>8192)return null;let u=It(n),c=u?fo(t,o,u*r,a,l):t,h=document.createElement("canvas");h.width=a,h.height=l;let d=h.getContext("2d");if(!d)return null;Qt(d,c,u?null:o,0,0,a,l),d.globalCompositeOperation="source-in",d.fillStyle=e.color,d.fillRect(0,0,a,l);let f=document.createElement("canvas");f.width=a,f.height=l;let m=f.getContext("2d");return m?(m.drawImage(h,0,0),m.globalCompositeOperation="destination-out",e.blur>0&&(m.filter=`blur(${e.blur}px)`),Qt(m,c,u?null:o,e.offsetX,e.offsetY,a,l),m.filter="none",m.globalCompositeOperation="source-over",f):null},bn=(n,e,t,r=!0,o=1,i=null,s=!1)=>{if(!t||e.length===0)return[];let a=o,l=Math.max(1,Math.ceil(n.dims.x*a)),u=Math.max(1,Math.ceil(n.dims.y*a));if((l>8192||u>8192)&&(a=1,l=Math.max(1,Math.ceil(n.dims.x)),u=Math.max(1,Math.ceil(n.dims.y))),l>8192||u>8192)return[];let c=document.createElement("canvas");c.width=l,c.height=u;let h=c.getContext("2d",{willReadFrequently:!0});if(!h)return[];let d=It(n),f=n.dims.x*a,m=n.dims.y*a;Tl(h,d?d*a:null,l/2,u/2,f,m,()=>Qt(h,t,i,-f/2,-m/2,f,m));let p=[];for(let b=e.length-1;b>=0;b--){let g=e[b],x=g.width,S=g.alignment,w=S==="outside"?x:S==="center"?Math.ceil(x/2):0,y=w*a,v=Math.floor(l+y*2),R=Math.floor(u+y*2);if(v<=0||R<=0)continue;let P=document.createElement("canvas");P.width=v,P.height=R;let T=P.getContext("2d",{willReadFrequently:!0});if(!T)continue;T.drawImage(c,y,y);let C=Sl(T.getImageData(0,0,v,R).data),E=uo(C,v,R),M=new Uint8Array(C.length);for(let U=0;U<C.length;U++)M[U]=C[U]?0:1;for(let U=0;U<v;U++)M[U]=1,M[U+(R-1)*v]=1;for(let U=0;U<R;U++)M[U*v]=1,M[v-1+U*v]=1;let k=uo(M,v,R),A=v*R,O=new Int32Array(A);for(let U=0;U<A;U++)O[U]=C[U]?-k[U]:E[U];let F=s?.5*a:0,W,z;S==="inside"?(W=-x*a-F,z=F):S==="center"?(W=-x/2*a-F,z=x/2*a+F):(W=-F,z=x*a+F);let _=Math.round(g.rgba[0]*255),D=Math.round(g.rgba[1]*255),I=Math.round(g.rgba[2]*255),G=Math.round(g.rgba[3]*255),$=g.kind==="gradient"&&g.decl?Og(g.decl,l,u,y):null,V=document.createElement("canvas");V.width=v,V.height=R;let H=V.getContext("2d");if(!H)continue;let Y=H.createImageData(v,R),X=Y.data;for(let U=0;U<A;U++){let oe=O[U];if(oe>=W&&oe<z){let ne=U*4;if($){let de=$(U%v,U/v|0);X[ne]=de[0],X[ne+1]=de[1],X[ne+2]=de[2],X[ne+3]=de[3]}else X[ne]=_,X[ne+1]=D,X[ne+2]=I,X[ne+3]=G}}H.putImageData(Y,0,0);let Z=document.createElement("canvas");Z.width=v,Z.height=R;let B=Z.getContext("2d");if(!B)continue;r&&B.drawImage(c,y,y),B.drawImage(V,0,0);let q=S==="outside"?x:S==="center"?x/2:0;p.push({canvas:Z,w:v,h:R,quadW:v/a,quadH:R/a,dx:w-q+g.offset.x,dy:w-q+g.offset.y})}return p},Oh=(n,e,t,r=1,o=null)=>{if(!t)return null;let i=r,s=Math.max(1,Math.ceil(n.dims.x*i)),a=Math.max(1,Math.ceil(n.dims.y*i));if((s>8192||a>8192)&&(i=1,s=Math.max(1,Math.ceil(n.dims.x)),a=Math.max(1,Math.ceil(n.dims.y))),s>8192||a>8192)return null;let l=document.createElement("canvas");l.width=s,l.height=a;let u=l.getContext("2d",{willReadFrequently:!0});if(!u)return null;let c=It(n),h=n.dims.x*i,d=n.dims.y*i;Tl(u,c?c*i:null,s/2,a/2,h,d,()=>Qt(u,t,o,-h/2,-d/2,h,d));let f=e.sizePx*i,m=e.style==="outer"||e.style==="emboss"||e.style==="pillow"?Math.ceil(f):0,p=s+m*2,b=a+m*2,g=document.createElement("canvas");g.width=p,g.height=b;let x=g.getContext("2d",{willReadFrequently:!0});if(!x)return null;x.drawImage(l,m,m);let S=Sl(x.getImageData(0,0,p,b).data),w=uo(S,p,b),y=new Uint8Array(S.length);for(let T=0;T<S.length;T++)y[T]=S[T]?0:1;for(let T=0;T<p;T++)y[T]=1,y[T+(b-1)*p]=1;for(let T=0;T<b;T++)y[T*p]=1,y[p-1+T*p]=1;let v=uo(y,p,b),R=Rh(v,w,S,p,b,{sizePx:f,angleDeg:e.angleDeg,altitudeDeg:e.altitudeDeg,strength:e.strength,directionDown:e.directionDown,technique:e.technique,style:e.style}),P=(T,C,E)=>{let M=document.createElement("canvas");M.width=p,M.height=b;let k=M.getContext("2d");if(!k)return M;let A=ee(C),O=Math.round(A[0]*255),F=Math.round(A[1]*255),W=Math.round(A[2]*255),z=k.createImageData(p,b),_=z.data;for(let D=0;D<T.length;D++){let I=T[D];if(I<=0)continue;let G=D*4;_[G]=O,_[G+1]=F,_[G+2]=W,_[G+3]=Math.round(Math.min(1,I*E)*255)}return k.putImageData(z,0,0),M};return{highlight:P(R.highlight,e.highlight.color,e.highlight.opacity),shadow:P(R.shadow,e.shadow.color,e.shadow.opacity),w:p,h:b,quadW:p/i,quadH:b/i,dx:0,dy:0}};var Bh=n=>Sr(n),Qe=2,po=(n,e)=>{let t=e.textLayout,r=e.textStyle,o=e.textStroke;n.textBaseline="alphabetic";for(let i of t.lines){let s=-t.width/2+i.leftOffset,a=e.contentTopY+i.baseline,l=i.charStyles[0],u=typeof l?.fill=="string"&&l.fill?l.fill:typeof e.raw.fill=="string"?e.raw.fill:null,c="",h=i.prefix?Tt(n,i,s,a,{fill:u,stroke:Oe(o,l)}):0,d="",f="",m=null,p=b=>{if(!c)return;n.font=d;let g=s+h;typeof f=="string"&&f?(n.fillStyle=f,n.fillText(c,g,a)):typeof e.raw.fill=="string"&&e.raw.fill&&(n.fillStyle=e.raw.fill,n.fillText(c,g,a)),m&&m.width>0&&(n.lineWidth=m.width,n.strokeStyle=m.color,n.strokeText(c,g,a)),c="",b<i.boxes.length&&(h=i.boxes[b].left)};for(let b=0;b<i.graphemes.length;b++){let g=i.charStyles[b],S=g!==void 0&&(g.fontSize!==void 0||g.fontFamily!==void 0||g.fontWeight!==void 0||g.fontStyle!==void 0)&&g?{...r,fontSize:g.fontSize??r.fontSize,fontFamily:g.fontFamily??r.fontFamily,fontWeight:g.fontWeight??r.fontWeight,fontStyle:g.fontStyle??r.fontStyle}:r,w=Me(S,S.fontSize),y=Oe(o,g),v=typeof g?.fill=="string"?g.fill:"",R=m;c&&(w!==d||y?.color!==R?.color||y?.width!==R?.width||v!==f)&&p(b),c||(d=w,m=y,f=v),c+=i.graphemes[b]}p(i.graphemes.length)}},Tr=n=>{let e=0;for(let t of n.strokes)e=Math.max(e,t.alignment==="outside"?t.width:t.alignment==="center"?Math.ceil(t.width/2):0);for(let t of n.dropShadows)e=Math.max(e,Math.ceil(t.blur*2+Math.max(Math.abs(t.offsetX),Math.abs(t.offsetY))));for(let t of n.solidFills)e=Math.max(e,Math.ceil(Math.max(Math.abs(t.offset.x),Math.abs(t.offset.y))));return e},El=(n,e,t)=>{let r=4;for(let m of n)r=Math.max(r,Math.ceil(m.blur*2+Math.max(Math.abs(m.offsetX),Math.abs(m.offsetY))+4));let o=e.width/t,i=e.height/t,s=Math.ceil(o+r*2),a=Math.ceil(i+r*2),l=Math.ceil(s*t),u=Math.ceil(a*t);if(!(l>0)||!(u>0)||l>8192||u>8192)return null;let c=document.createElement("canvas");c.width=l,c.height=u;let h=c.getContext("2d");if(!h)return null;let d=(l-e.width)/2,f=(u-e.height)/2;for(let m of n)h.filter=`drop-shadow(${m.offsetX*t}px ${m.offsetY*t}px ${m.blur*t}px ${m.color})`,h.drawImage(e,d,f);return h.filter="none",h.globalCompositeOperation="destination-out",h.drawImage(e,d,f),{canvas:c,w:s,h:a}},bo=(n,e,t)=>{if(!t||t.dropShadows.length===0&&t.innerShadows.length===0&&t.solidFills.length===0&&t.strokes.length===0)return;let r=mo(e,Qe);if(!r)return;let o=e.dims.x,i=e.dims.y;if(t.dropShadows.length){let l=El(t.dropShadows,r,Qe);l&&(n.save(),n.globalCompositeOperation="destination-over",n.drawImage(l.canvas,-l.w/2,-l.h/2,l.w,l.h),n.restore())}let s=(l,u)=>{if(!l){u();return}n.save(),n.globalCompositeOperation=l,u(),n.restore()};for(let l of t.innerShadows){let u=wr(e,l,r,Qe);u&&s(l.blendMode,()=>n.drawImage(u,-o/2,-i/2,o,i))}for(let l of t.solidFills){let u=vr(e,l,r,Qe);u&&s(l.blendMode,()=>n.drawImage(u,-o/2+l.offset.x,-i/2+l.offset.y,o,i))}bn(e,t.strokes,r,!1,Math.min(2,Qe),null,!0).forEach((l,u)=>{let c=t.strokes[t.strokes.length-1-u];s(c?.blendMode,()=>n.drawImage(l.canvas,-l.quadW/2+l.dx,-l.quadH/2+l.dy,l.quadW,l.quadH))})},Cl=(n,e,t=null)=>{let r=n.textLayout,o=Number(n.raw.fontSize)||40,i=Math.max(-1,Math.min(1,Number(n.raw.warpStrength)||0)),s=typeof n.raw.width=="number"?n.raw.width:r.width,a=typeof n.raw.height=="number"?n.raw.height:r.height,l=o*(e==="arch"?.6:.5),u=Math.max(r.width,s,o),c=Math.max(a,o),h=e==="arch"?c*Math.max(0,i):0,d=e==="flag"?Math.abs(i)*(a||o)*.3:0,f=1+Math.abs(i),m=t?Tr(t):0,p=Math.ceil(u+l*2+m*2),b=Math.ceil(e==="arch"?c+l*2+m*2+h:e==="flag"?(a||o)+d*2+l*2+m*2:(a||o)*f+l*2+m*2),g=p*Qe,x=b*Qe;if(!(g>0)||!(x>0)||g>8192||x>8192)return null;let S=document.createElement("canvas");S.width=g,S.height=x;let w=S.getContext("2d",{willReadFrequently:!0});if(!w)return null;let y=e==="arch"?h/2*Qe:0;w.setTransform(Qe,0,0,Qe,g/2,x/2+y),po(w,n),bo(w,n,t);let v=w.getImageData(0,0,g,x),R=new Uint32Array(v.data.buffer),P=g,T=0,C=x,E=0,M=!1;for(let _=0;_<x;_++)for(let D=0;D<g;D++)(R[_*g+D]>>>24&255)>10&&(M=!0,D<P&&(P=D),D>T&&(T=D),_<C&&(C=_),_>E&&(E=_));let k=M?(P+T)/2:g/2,A=M?E:x-1,O=M?Math.max(1,T-P)/2:g/2,F=w.createImageData(g,x),W=new Uint32Array(F.data.buffer),z=(_,D)=>{let I=Math.floor(D),G=I+1;if(I<0||G>=x)return 0;let $=D-I,V=R[I*g+_],H=R[G*g+_],Y=V>>>24&255,X=H>>>24&255;if(Y<=10&&X<=10)return 0;let Z=Math.round((V&255)*(1-$)+(H&255)*$),B=Math.round((V>>>8&255)*(1-$)+(H>>>8&255)*$),q=Math.round((V>>>16&255)*(1-$)+(H>>>16&255)*$);return Math.round(Y*(1-$)+X*$)<<24|q<<16|B<<8|Z};if(e==="flag")for(let _=0;_<g;_++){let D=O>0?(_-k)/O:0,I=Math.sin(D*Math.PI)*d*Qe*i;for(let G=0;G<x;G++)W[G*g+_]=z(_,G+I)}else if(e==="arch")for(let _=0;_<g;_++){let D=Math.max(-1,Math.min(1,(_-k)/O)),I=Math.sqrt(Math.max(0,1-D*D)),G=I*I*(3-2*I),$=i>0?Math.pow(G,2.5):G,V=Math.min(1+Math.max(0,i),Math.max(.05,1+i*$));for(let H=0;H<=A;H++){let Y=A-H;W[H*g+_]=z(_,A-Y/V)}}else{let _=M?(C+E)/2:x/2;for(let D=0;D<g;D++){let I=O>0?(D-k)/O:0,G=1+i*(I*I-.5);G=Math.min(1+Math.abs(i),Math.max(.4,G));for(let $=0;$<x;$++)W[$*g+D]=z(D,_+($-_)/G)}}return w.setTransform(1,0,0,1,0,0),w.clearRect(0,0,g,x),w.putImageData(F,0,0),{canvas:S,logicalW:p,logicalH:b}},Gi=(n,e)=>{let t=e.textLayout,r=e.textStyle,o=e.textStroke,i=typeof e.raw.fill=="string"?e.raw.fill:"",s=Number(e.raw.textOffsetY)||0;n.textBaseline="alphabetic";let a=0;for(let l of t.lines){let u=-t.width/2+l.leftOffset,c=e.contentTopY+l.baseline,h=l.charStyles[0],d=typeof h?.fill=="string"&&h.fill?h.fill:i||null;l.prefix&&Tt(n,l,u,c,{fill:d,stroke:Oe(o,h)});let f=Vt(l,u,c,r,r.charSpacing??0);for(let m=0;m<f.length;m++){let p=l.charStyles[m],b=fn(r,p);n.font=Me(b,b.fontSize);let g=typeof p?.fill=="string"&&p.fill?p.fill:i,x=Oe(o,p),S={...f[m],y:f[m].y+wt(s,b.fontSize,a+m)};g&&(n.fillStyle=g,qt(n,S,"fillText")),x&&x.width>0&&(n.lineWidth=x.width,n.strokeStyle=x.color,qt(n,S,"strokeText"))}a+=l.graphemes.length}},Wg=(n,e)=>{let t=e?Tr(e):0,r=Math.ceil(n.dims.x+t*2),o=Math.ceil(n.dims.y+t*2),i=r*Qe,s=o*Qe;if(!(i>0)||!(s>0)||i>8192||s>8192)return null;let a=document.createElement("canvas");a.width=i,a.height=s;let l=a.getContext("2d");return l?(l.setTransform(Qe,0,0,Qe,i/2,s/2),n.raw.vertical===!0?Gi(l,n):po(l,n),bo(l,n,e),{canvas:a,logicalW:r,logicalH:o}):null};var Hh=2,gn=(n,e)=>e!==void 0&&(e.fontSize!==void 0||e.fontFamily!==void 0||e.fontWeight!==void 0||e.fontStyle!==void 0)&&e?{...n,fontSize:e.fontSize??n.fontSize,fontFamily:e.fontFamily??n.fontFamily,fontWeight:e.fontWeight??n.fontWeight,fontStyle:e.fontStyle??n.fontStyle}:n,Gh=(n,e,t,r)=>{let o=e.textStyle,i=e.textStroke,s=e.raw.strokeVisible===!0,a=e.paintFirst==="stroke",l=typeof e.raw.fill=="string"?e.raw.fill:"";for(let u of t.chars){let c=e.textLayout.lines[u.line]?.charStyles[u.index],h=gn(o,c),d=r==="silhouette"?"#ffffff":typeof c?.fill=="string"&&c.fill?c.fill:l,f=r==="silhouette"?null:s?Oe(i,c):null,m=Me(h,h.fontSize);n.save(),n.translate(u.x,u.y),n.rotate(u.rotation),n.font=m;let p=()=>{d&&(n.fillStyle=d,n.fillText(u.char,0,0))},b=()=>{f&&f.width>0&&(n.lineWidth=f.width,n.strokeStyle=f.color,n.strokeText(u.char,0,0))};a?(b(),p()):(p(),b()),n.restore()}},Wh=(n,e,t=Hh)=>{let r=Math.max(1,Math.ceil(n.dims.x*t)),o=Math.max(1,Math.ceil(n.dims.y*t));if(r>8192||o>8192)return null;let i=document.createElement("canvas");i.width=r,i.height=o;let s=i.getContext("2d");return s?(s.setTransform(t,0,0,t,r/2-e.contentOffsetX*t,o/2-e.contentOffsetY*t),s.textBaseline="alphabetic",s.textAlign="center",Gh(s,n,e,"silhouette"),i):null},Hg=(n,e,t,r,o)=>{if(r.dropShadows.length===0&&r.innerShadows.length===0&&r.solidFills.length===0&&r.strokes.length===0)return;let i=e.dims.x,s=e.dims.y,a=t.contentOffsetX,l=t.contentOffsetY,u=(c,h)=>{if(!c){h();return}n.save(),n.globalCompositeOperation=c,h(),n.restore()};if(r.dropShadows.length||r.solidFills.length||r.innerShadows.length){let c=Wh(e,t,o);if(c){if(r.dropShadows.length){let h=El(r.dropShadows,c,o);h&&(n.save(),n.globalCompositeOperation="destination-over",n.drawImage(h.canvas,a-h.w/2,l-h.h/2,h.w,h.h),n.restore())}for(let h of r.innerShadows){let d=wr(e,h,c,o);d&&u(h.blendMode,()=>n.drawImage(d,a-i/2,l-s/2,i,s))}for(let h of r.solidFills){let d=vr(e,h,c,o);d&&u(h.blendMode,()=>n.drawImage(d,a-i/2+h.offset.x,l-s/2+h.offset.y,i,s))}}}if(r.strokes.length){let c=Math.min(Math.max(2,o),Bi(e)),h=Wh(e,t,c);h&&bn(e,r.strokes,h,!1,c,null,!0).forEach((f,m)=>{let p=r.strokes[r.strokes.length-1-m];u(p?.blendMode,()=>n.drawImage(f.canvas,a-f.quadW/2+f.dx,l-f.quadH/2+f.dy,f.quadW,f.quadH))})}},Ml=(n,e,t=null,r=Hh)=>{let o=Et(n.textLayout,n.raw,n.textStyle.lineHeight??1.16),i=t?Tr(t):0,s=o.width+i*2,a=o.height+i*2,l=Math.ceil(s*r),u=Math.ceil(a*r);if(!(l>0)||!(u>0)||l>8192||u>8192)return null;let c=document.createElement("canvas");c.width=l,c.height=u;let h=c.getContext("2d");return h?(h.setTransform(r,0,0,r,l/2-o.contentOffsetX*r,u/2-o.contentOffsetY*r),h.textBaseline="alphabetic",h.textAlign="center",Gh(h,n,o,"render"),t&&Hg(h,n,o,t,r),{canvas:c,logicalW:s,logicalH:a}):null};var Er=n=>{if(Ge(n)!=="scroll")return null;let e=typeof n.scrollSpeed=="number"&&Number.isFinite(n.scrollSpeed)?n.scrollSpeed:50;return{direction:n.scrollDirection==="right-to-left"?"right-to-left":"left-to-right",speed:e,enabled:n.scrollEnabled===void 0?!0:n.scrollEnabled===!0}},Gg=(n,e,t,r)=>{let o=t+e,i=n.direction==="left-to-right"?-e/2-t+r:e/2-r,s=n.direction==="left-to-right"?o:-o;return{copy1:i,copy2:i+s}},Xh=n=>{let e=Er(n.raw);return e?{target:n,viewWidth:n.dims.x,textTotalWidth:n.textTotalWidth,scrollSpeed:e.speed,scrollDirection:e.direction,scrollEnabled:e.enabled}:null},Xg=n=>`rgba(${Math.round(n.color[0]*255)},${Math.round(n.color[1]*255)},${Math.round(n.color[2]*255)},${n.color[3]})`,zh=(n,e,t)=>{let r=Er(n.raw);if(!r||!r.enabled)return null;let o=n.dims.x,i=n.dims.y;if(!(o>0)||!(i>0))return null;let s=Math.max(1,e);if((o*s>8192||i*s>8192)&&(s=Math.max(1,Math.floor(Math.min(8192/o,8192/i))),o*s>8192||i*s>8192))return null;let a=Math.ceil(o*s),l=Math.ceil(i*s);if(!(a>0)||!(l>0))return null;let u=document.createElement("canvas");u.width=a,u.height=l;let c=u.getContext("2d");if(!c)return null;c.setTransform(s,0,0,s,a/2,l/2),c.textBaseline="alphabetic",c.textAlign="left",c.beginPath(),c.rect(-o/2,-i/2,o,i),c.clip();let h=n.textTotalWidth,{copy1:d,copy2:f}=Gg(r,o,h,t);for(let m of[d,f])c.save(),c.translate(m,0),zg(c,n),c.restore();return{canvas:u,logicalW:o,logicalH:i}},zg=(n,e)=>{let t=e.paintFirst==="stroke"?["stroke","fill"]:["fill","stroke"];for(let r of t)Yg(n,e,r)},Yg=(n,e,t)=>{let r=e.textLayout,o=e.textStyle,i=e.textStroke,s=e.raw,a=e.fillPaint,l=typeof s.fill=="string"?s.fill:a?.kind==="gradient"&&a.decl.stops.length?Xg(a.decl.stops[0]):"",u=s.vertical===!0,c=Number(s.charSpacing)||0,h=t==="stroke"&&Array.isArray(s.strokeDashArray)?s.strokeDashArray.filter(f=>typeof f=="number"&&Number.isFinite(f)):null;if(t==="fill"&&!l&&!r.lines.some(f=>f.charStyles.some(m=>typeof m?.fill=="string"))||t==="stroke"&&!i)return;h&&h.length&&(n.setLineDash(h),n.lineDashOffset=Number(s.strokeDashOffset)||0);let d=f=>{n.lineWidth=f.width,n.strokeStyle=f.color,n.lineJoin=typeof s.strokeLineJoin=="string"?s.strokeLineJoin:"miter",n.lineCap=typeof s.strokeLineCap=="string"?s.strokeLineCap:"butt",n.miterLimit=Number(s.strokeMiterLimit)||4};for(let f of r.lines){let m=-r.width/2+f.leftOffset,p=e.contentTopY+f.baseline,b=f.prefix?.width??0;if(f.prefix){let g=f.charStyles[0];if(t==="fill"){let x=typeof g?.fill=="string"&&g.fill?g.fill:l;x&&Tt(n,f,m,p,{fill:x})}else Tt(n,f,m,p,{stroke:Oe(i,g)})}if(u){let g=Vt(f,m,p,o,c);for(let x=0;x<g.length;x++){let S=f.charStyles[x];if(t==="fill"){let y=typeof S?.fill=="string"&&S.fill?S.fill:l;if(!y)continue;n.fillStyle=y}else{let y=Oe(i,S);if(!y||y.width<=0)continue;d(y)}let w=gn(o,S);n.font=Me(w,w.fontSize),qt(n,g[x],t==="fill"?"fillText":"strokeText")}continue}if(h&&h.length){let g="",x=b,S="",w=null,y,v=C=>{if(!g)return;let E=w;E&&E.width>0&&(n.font=S,d(E),n.strokeText(g,m+x,p)),g="",C<f.boxes.length&&(x=f.boxes[C].left)},R=$t(s.textAlign),P=s.textAlign===fe.DISPERSE,T=ro(s.textAlign)&&f.graphemes.some(C=>ao.test(C));for(let C=0;C<f.graphemes.length;C++){let E=f.charStyles[C],M=gn(o,E),k=Me(M,M.fontSize),A=Oe(i,E),O=E?.fill??"",F=w;g&&(k!==S||A?.color!==F?.color||A?.width!==F?.width||O!==y)&&v(C),g||(S=k,w=A,y=O),g+=f.graphemes[C],(c||(R||P)&&/[ \t\r]/.test(f.graphemes[C])||T)&&v(C+1)}v(f.graphemes.length);continue}for(let g=0;g<f.graphemes.length;g++){let x=f.charStyles[g];if(t==="fill"){let y=typeof x?.fill=="string"&&x.fill?x.fill:l;if(!y)continue;n.fillStyle=y}else{let y=Oe(i,x);if(!y||y.width<=0)continue;d(y)}let S=gn(o,x);n.font=Me(S,S.fontSize);let w=m+f.boxes[g].left;t==="fill"?n.fillText(f.graphemes[g],w,p):n.strokeText(f.graphemes[g],w,p)}}};var Yh=(n,e)=>{let t=[],r=Ii(n);r&&t.push({left:-r.logicalW/2,top:-r.logicalH/2,right:r.logicalW/2,bottom:r.logicalH/2});let o=n.raw;if(Array.isArray(o.texts)&&typeof o.renderSrc!="string"&&!Sr(o)&&!Zn(o)&&!Xe(o)&&!Er(o)?.enabled){let h=n.textLayout,d=Jn(String(o.text??""),h,o.texts,n.contentTopY,n.textStyle.fontSize);if(d&&Math.ceil(h.width+d.padX*2)<=8192&&Math.ceil(h.height+d.padY*2)<=8192){let f=d.inkBounds;t.push({left:f.left-2,top:f.top-2,right:f.right+2,bottom:f.bottom+2})}}if(!t.length)return e;let i=Xn(e),{left:s,top:a,right:l,bottom:u}=i,c=n.matrix;for(let h of t)for(let[d,f]of[[h.left,h.top],[h.right,h.top],[h.right,h.bottom],[h.left,h.bottom]]){let m=Q(c,d,f);s=Math.min(s,m.x),a=Math.min(a,m.y),l=Math.max(l,m.x),u=Math.max(u,m.y)}return{tl:{x:s,y:a},tr:{x:l,y:a},br:{x:l,y:u},bl:{x:s,y:u}}};var er=n=>{if(!n||typeof n!="object")return null;let e=n;if(typeof e.rows!="number"||typeof e.cols!="number"||!Array.isArray(e.pieces)||e.pieces.length===0)return null;let t=[];for(let r of e.pieces){if(!r||typeof r!="object")continue;let o=r;typeof o.row!="number"||typeof o.col!="number"||t.push({id:r.id,row:o.row,col:o.col,rowSpan:r.rowSpan,colSpan:r.colSpan})}return t.length>0?{rows:e.rows,cols:e.cols,pieces:t}:null},Rl=(n,e)=>{let{rows:t,cols:r,pieces:o}=n,i=Math.max(0,e.width-e.groupPadding*2),s=Math.max(0,e.height-e.groupPadding*2),a=e.hGap*Math.max(0,r-1),l=e.vGap*Math.max(0,t-1),u=r>0?(i-a)/r:0,c=t>0?(s-l)/t:0,h=u+e.hGap,d=c+e.vGap,f=(r-1)/2,m=(t-1)/2;return o.map(p=>{let b=p.colSpan??1,g=p.rowSpan??1,x=Math.max(u*b+e.hGap*(b-1),0),S=Math.max(c*g+e.vGap*(g-1),0),w=p.col+(b-1)/2,y=p.row+(g-1)/2;return{w:x,h:S,cx:(w-f)*h,cy:(y-m)*d}})},Ug=(n,e)=>e&&e.naturalWidth&&e.naturalHeight?{w:e.naturalWidth,h:e.naturalHeight}:{w:n?.width??0,h:n?.height??0},Uh=(n,e,t)=>{let r=typeof e.widthRatio=="number"&&isFinite(e.widthRatio)&&e.widthRatio>0?e.widthRatio:1,o=typeof e.heightRatio=="number"&&isFinite(e.heightRatio)&&e.heightRatio>0?e.heightRatio:1,i=r!==1,s=o!==1;if(!i&&!s||n.masks.length===0)return!1;let a=n.width||0,l=n.height||0;return i&&a&&(n.width=a*r,n.hGap*=r,n.groupPadding*=r),s&&l&&(n.height=l*o,n.vGap*=o,n.groupPadding*=o),n.masks.forEach((u,c)=>{let h=u.width||0,d=u.height||0,f=i?Math.max(h*r,1):h,m=s?Math.max(d*o,1):d,p=i?(u.left||0)*r:u.left,b=s?(u.top||0)*o:u.top;if(u.left=p,u.top=b,u.width=f,u.height=m,u.clip){let g=i&&h?f/h:1,x=s&&d?m/d:1,S=t?.[c]??Ug(u.clip,null);if(S.w&&S.h){let w=Math.max(h/S.w,d/S.h),y=Math.max(f/S.w,m/S.h),v=u.clip.scaleX||u.clip.scaleY||1,R=w?v/w:1,P=y*(R||1);u.clip.scaleX=P,u.clip.scaleY=P}u.clip.clipX=(u.clip.clipX||0)*g,u.clip.clipY=(u.clip.clipY||0)*x}}),!0},Xi=n=>{let e=n.clipImage;if(!e||typeof e!="object"||typeof e.src!="string")return null;let t=e;return{scaleX:t.scaleX??1,scaleY:t.scaleY??1,clipX:t.clipX??0,clipY:t.clipY??0,width:t.width??0,height:t.height??0}};var $g=(n,e)=>{if(typeof n.colStart!="number"||typeof n.colEnd!="number"||e<=0)return 0;let t=0;return n.colStart>0&&(t+=1),n.colEnd<e-1&&(t+=1),t},jg=(n,e)=>{if(typeof n.rowStart!="number"||typeof n.rowEnd!="number"||e<=0)return 0;let t=0;return n.rowStart>0&&(t+=1),n.rowEnd<e-1&&(t+=1),t},_t=n=>({left:n.left-n.width/2,right:n.left+n.width/2,top:n.top-n.height/2,bottom:n.top+n.height/2}),Cr=(n,e,t,r)=>{if(!n.clip)return;let o=n.width,i=n.height,s=e?o/e:1,a=t?i/t:1,l=r??{w:n.clip.width,h:n.clip.height};if(l.w&&l.h){let u=Math.max(e/l.w,t/l.h),c=Math.max(o/l.w,i/l.h),h=n.clip.scaleX||n.clip.scaleY||1,d=u?h/u:1,f=c*(d||1);n.clip.scaleX=f,n.clip.scaleY=f}n.clip.clipX=(n.clip.clipX||0)*s,n.clip.clipY=(n.clip.clipY||0)*a},$h=(n,e,t,r="right",o)=>{let i=n.masks[e];if(!i)return!1;let s=Math.max(n.innerRadius+1,12);if(t<=s||!n.layoutWidth)return!1;let a=n.groupPadding||0,l=Math.max(0,n.layoutWidth-a*2),u=1,c=i.width||0,h=i.height||0;if(!l||!c)return!1;let d=n.innerRadius+1,f=$g(i,n.cols)*d;if(t<f)return!1;let m=l-f,p=Math.min(t,Math.max(u,m)),b=_t(i),g=n.hGap||0,x=[],S=null,w=5,y=.3;n.masks.forEach((B,q)=>{if(q===e)return;let U=_t(B),oe=Math.min(b.bottom,U.bottom)-Math.max(b.top,U.top);if(!(oe<=0||oe<Math.min(i.height,B.height)*y))if(r==="right"){if(U.left<=i.left)return;let ne=U.left;S===null||ne<S-w?(S=ne,x.length=0,x.push(q)):Math.abs(ne-S)<=w&&x.push(q)}else{if(U.right>=i.left)return;let ne=U.right;S===null||ne>S+w?(S=ne,x.length=0,x.push(q)):Math.abs(ne-S)<=w&&x.push(q)}});let v=B=>o?.[B]??null;if(!x.length){let B=l/2,q=r==="right"?B-b.left:b.right+B,U=Math.max(s,Math.min(p,Math.max(s,q)));return U===c?!1:(i.left=r==="right"?b.left+U/2:b.right-U/2,i.width=U,Cr(i,c,h,v(e)),!0)}let R=1/0,P=-1/0;for(let B of x){let q=_t(n.masks[B]);q.left<R&&(R=q.left),q.right>P&&(P=q.right)}let T=r==="right"?b.left:b.right,C=B=>{let q=_t(n.masks[B]);return r==="right"?q.right:q.left},E=1/0;for(let B of x){let q=(r==="right"?C(B)-T:T-C(B))-g-s;q<E&&(E=q)}let M=Math.max(s,Math.min(p,Math.max(s,E))),k=r==="right"?T+M:T-M;for(let B of x)if((r==="right"?C(B)-k:k-C(B))-g<s-1e-6)return!1;if(M<=0)return!1;i.left=r==="right"?T+M/2:T-M/2,i.width=M;let A=new Map;A.set(e,{width:c,height:h});for(let B of x){let q=n.masks[B];A.set(B,{width:q.width,height:q.height});let U=C(B);r==="right"?(q.width=U-k-g,q.left=(k+g+U)/2):(q.width=k-g-U,q.left=(k-g+U)/2)}for(let B of[e,...x]){let q=A.get(B);Cr(n.masks[B],q.width,q.height,v(B))}let O=_t(i),F=O.left,W=O.right,z=_t(n.masks[x[0]]),_=z.left,D=z.right,I=r==="right"?b.right:b.left,G=r==="right"?W:F,$=new Set(x),V=typeof i.colStart=="number"&&typeof i.colEnd=="number"?{colStart:i.colStart,colEnd:i.colEnd}:null,H=n.masks[x[0]],Y=H&&typeof H.colStart=="number"&&typeof H.colEnd=="number"?{colStart:H.colStart,colEnd:H.colEnd}:null,X=n.cols>0&&!!V&&!!Y,Z=(B,q,U)=>{let oe=n.masks[B],ne=oe.width,de=oe.height,Pe=Math.max(u,U-q);oe.left=(q+U)/2,oe.width=Pe,Cr(oe,ne,de,v(B))};return n.masks.forEach((B,q)=>{if(q===e||$.has(q))return;let U=_t(B),oe=U.left,ne=U.right;if(X&&V&&Y&&typeof B.colStart=="number"&&typeof B.colEnd=="number"){if(B.colStart===V.colStart&&B.colEnd===V.colEnd){Z(q,F,W);return}if(B.colStart===Y.colStart&&B.colEnd===Y.colEnd){Z(q,_,D);return}let Ee=r==="right"?V.colEnd+1:V.colStart,ue=B.colStart===Ee,xe=B.colEnd+1===Ee;if(!ue&&!xe)return;let pe=ue?G+(r==="right"?g:0):oe,Te=xe?G-(r==="left"?g:0):ne;if(Te-pe<=0)return;Z(q,pe,Te);return}let de=.5;if(Math.abs(oe-b.left)<de&&Math.abs(ne-b.right)<de){Z(q,F,W);return}if(Math.abs(oe-R)<de&&Math.abs(ne-P)<de){Z(q,_,D);return}let Pe=Math.abs(oe-I)<de,De=Math.abs(ne-I)<de;if(!Pe&&!De)return;let nt=Pe?G:oe,ke=De?G:ne;ke-nt<=0||Z(q,nt,ke)}),i.width!==c},jh=(n,e,t,r="bottom",o)=>{let i=n.masks[e];if(!i)return!1;let s=Math.max(n.innerRadius+1,12);if(t<=s||!n.layoutHeight)return!1;let a=n.groupPadding||0,l=Math.max(0,n.layoutHeight-a*2),u=1,c=i.height||0,h=i.width||0;if(!l||!c)return!1;let d=n.innerRadius+1,f=jg(i,n.rows)*d;if(t<f)return!1;let m=l-f,p=Math.min(t,Math.max(u,m)),b=_t(i),g=n.vGap||0,x=-1,S=0,w=0,y=.3;n.masks.forEach((ue,xe)=>{if(xe===e)return;let pe=_t(ue),Te=Math.min(b.right,pe.right)-Math.max(b.left,pe.left);if(!(Te<=0||Te<Math.min(i.width,ue.width)*y))if(r==="bottom"){if(pe.top<=i.top)return;(x===-1||pe.top<S)&&(x=xe,S=pe.top,w=pe.bottom)}else{if(pe.bottom>=i.top)return;(x===-1||pe.bottom>w)&&(x=xe,S=pe.top,w=pe.bottom)}});let v=ue=>o?.[ue]??null;if(x===-1){let ue=l/2,xe=r==="bottom"?ue-b.top:b.bottom+ue,pe=Math.max(s,Math.min(p,Math.max(s,xe)));return pe===c?!1:(i.top=r==="bottom"?b.top+pe/2:b.bottom-pe/2,i.height=pe,Cr(i,h,c,v(e)),!0)}let R=r==="bottom"?b.top:S,P=r==="bottom"?w:b.bottom,T=P-R,C=Math.max(s,T-g-s),E=Math.max(s,Math.min(p,C)),M=T-g-E;if(M<s){let ue=T-g-s;if(ue<s||(E=Math.max(s,Math.min(p,ue)),M=T-g-E,M<s))return!1}if(E<=0||M<=0)return!1;let k,A;r==="bottom"?(k=R+E/2,A=P-M/2):(A=R+M/2,k=P-E/2);let O=new Map;O.set(e,{width:h,height:c}),O.set(x,{width:n.masks[x].width,height:n.masks[x].height}),i.top=k,i.height=E;let F=n.masks[x];F.top=A,F.height=M;for(let ue of[e,x]){let xe=O.get(ue);Cr(n.masks[ue],xe.width,xe.height,v(ue))}let W=k-E/2,z=k+E/2,_=A-M/2,D=A+M/2,I=r==="bottom",G=I?W:_,$=I?z:D,V=I?_:W,H=I?D:z,Y=I?b.top:S,X=I?b.bottom:w,Z=I?S:b.top,B=I?w:b.bottom,q=r==="bottom"?b.bottom:b.top,U=r==="bottom"?z:W,oe=typeof i.rowStart=="number"&&typeof i.rowEnd=="number"?{rowStart:i.rowStart,rowEnd:i.rowEnd}:null,ne=n.masks[x],de=ne&&typeof ne.rowStart=="number"&&typeof ne.rowEnd=="number"?{rowStart:ne.rowStart,rowEnd:ne.rowEnd}:null,Pe=n.rows>0&&!!oe&&!!de,De=Pe&&oe&&de?oe.rowStart<=de.rowStart?oe:de:null,nt=Pe&&oe&&de?De===oe?de:oe:null,ke=De?De.rowEnd+1:void 0,Ee=(ue,xe,pe)=>{let Te=n.masks[ue],rt=Te.width,Ke=Te.height,Ue=Math.max(u,pe-xe);Te.top=(xe+pe)/2,Te.height=Ue,Cr(Te,rt,Ke,v(ue))};return n.masks.forEach((ue,xe)=>{if(xe===e||xe===x)return;let pe=_t(ue),Te=pe.top,rt=pe.bottom;if(Pe&&De&&nt&&ke!==void 0&&typeof ue.rowStart=="number"&&typeof ue.rowEnd=="number"){if(ue.rowStart===De.rowStart&&ue.rowEnd===De.rowEnd){Ee(xe,G,$);return}if(ue.rowStart===nt.rowStart&&ue.rowEnd===nt.rowEnd){Ee(xe,V,H);return}let yt=ue.rowStart===ke,St=ue.rowEnd+1===ke;if(!yt&&!St)return;let Bn=yt?U+(r==="bottom"?g:0):Te,Wn=St?U-(r==="top"?g:0):rt;if(Wn-Bn<=0)return;Ee(xe,Bn,Wn);return}let Ke=.5;if(Math.abs(Te-Y)<Ke&&Math.abs(rt-X)<Ke){Ee(xe,G,$);return}if(Math.abs(Te-Z)<Ke&&Math.abs(rt-B)<Ke){Ee(xe,V,H);return}let Ue=Math.abs(Te-q)<Ke,bt=Math.abs(rt-q)<Ke;if(!Ue&&!bt)return;let gt=Ue?U:Te,xt=bt?U:rt;xt-gt<=0||Ee(xe,gt,xt)}),i.height!==c};var Vh=(n,e,t=[])=>{let r=n.layoutConfig,o=r&&typeof r=="object"&&Array.isArray(r.pieces)?r.pieces:[],i=e.map(u=>({left:u.left??0,top:u.top??0,width:u.width??0,height:u.height??0,clip:Xi(u)})),s=e.map((u,c)=>{let h=u.clipImage;if(!h||typeof h.src!="string")return null;let d=t[c];return d&&d.naturalWidth&&d.naturalHeight?{w:d.naturalWidth,h:d.naturalHeight}:{w:h.width??0,h:h.height??0}});o.forEach((u,c)=>{let h=i[c];!h||typeof u.col!="number"||typeof u.row!="number"||(h.colStart=u.col,h.colEnd=u.col+(u.colSpan??1)-1,h.rowStart=u.row,h.rowEnd=u.row+(u.rowSpan??1)-1)});let a={layoutWidth:n.layoutWidth??600,layoutHeight:n.layoutHeight??600,hGap:n.hGap??12,vGap:n.vGap??12,groupPadding:n.groupPadding??0,innerRadius:n.innerRadius??12,cols:(r&&typeof r.cols=="number"?r.cols:0)||1,rows:(r&&typeof r.rows=="number"?r.rows:0)||1,masks:i},l=o.filter(u=>typeof u.row=="number"&&typeof u.col=="number").map(u=>({row:u.row,col:u.col,rowSpan:u.rowSpan,colSpan:u.colSpan}));return{state:a,pieces:l,clipSizes:s}},qh=(n,e,t)=>{if(e<=1)return null;let r=[];n.forEach((o,i)=>{let s=o.col,a=o.col+(o.colSpan??1)-1;s===t&&(o.colSpan??1)===1?r.push(i):t>=s&&t<=a&&(o.colSpan=(o.colSpan??1)-1)}),r.forEach(o=>{let i=n[o],s=t>0?t-1:t+1,a=n.find((l,u)=>!r.includes(u)&&l.row===i.row&&l.col<=s&&l.col+(l.colSpan??1)-1>=s);a&&(a.colSpan=(a.colSpan??1)+1,a.col>t&&(a.col=t))}),n.forEach(o=>{o.col>t&&(o.col-=1)});for(let o of[...r].sort((i,s)=>s-i))n.splice(o,1);return{removed:r}},Kh=(n,e,t)=>{if(e<=1)return null;let r=[];n.forEach((o,i)=>{let s=o.row,a=o.row+(o.rowSpan??1)-1;s===t&&(o.rowSpan??1)===1?r.push(i):t>=s&&t<=a&&(o.rowSpan=(o.rowSpan??1)-1)}),r.forEach(o=>{let i=n[o],s=t>0?t-1:t+1,a=n.find((l,u)=>!r.includes(u)&&l.col===i.col&&l.row<=s&&l.row+(l.rowSpan??1)-1>=s);a&&(a.rowSpan=(a.rowSpan??1)+1,a.row>t&&(a.row=t))}),n.forEach(o=>{o.row>t&&(o.row-=1)});for(let o of[...r].sort((i,s)=>s-i))n.splice(o,1);return{removed:r}},Qh=(n,e)=>{let t=n.findIndex(h=>h.row===e.row&&h.col===e.col);if(t===-1||n.length<=1)return null;let r=n[t],o=r.row,i=r.col,s=r.rowSpan??1,a=r.colSpan??1,l=[],u="v",c=n.filter(h=>h!==r&&h.row+(h.rowSpan??1)===o&&h.col>=i&&h.col+(h.colSpan??1)<=i+a);if(c.reduce((h,d)=>h+(d.colSpan??1),0)===a)l=c,u="v";else{let h=n.filter(d=>d!==r&&d.row===o+s&&d.col>=i&&d.col+(d.colSpan??1)<=i+a);if(h.reduce((d,f)=>d+(f.colSpan??1),0)===a)l=h,u="v",l.forEach(d=>d.row=o);else{let d=n.filter(f=>f!==r&&f.col+(f.colSpan??1)===i&&f.row>=o&&f.row+(f.rowSpan??1)<=o+s);if(d.reduce((f,m)=>f+(m.rowSpan??1),0)===s)l=d,u="h";else{let f=n.filter(m=>m!==r&&m.col===i+a&&m.row>=o&&m.row+(m.rowSpan??1)<=o+s);f.reduce((m,p)=>m+(p.rowSpan??1),0)===s&&(l=f,u="h",l.forEach(m=>m.col=i))}}}return l.length>0&&l.forEach(h=>{u==="v"?h.rowSpan=(h.rowSpan??1)+s:h.colSpan=(h.colSpan??1)+a}),n.splice(t,1),{removed:[t]}};var Dt=n=>{let e=new Map;for(let t of n)e.set(`${t.row},${t.col}`,t);for(let t of n){if(t.isMerged)continue;let r=t.colspan??1,o=t.rowspan??1;if(!(r<=1&&o<=1))for(let i=t.row;i<t.row+o;i++)for(let s=t.col;s<t.col+r;s++){if(i===t.row&&s===t.col)continue;let a=`${i},${s}`;e.has(a)||e.set(a,{row:i,col:s,isMerged:!0,mergeParent:{row:t.row,col:t.col}})}}return e},we=(n,e,t)=>n.get(`${e},${t}`),lt=(n,e,t)=>{let r=we(n,e,t);return r?.isMerged&&r.mergeParent?{row:r.mergeParent.row,col:r.mergeParent.col}:{row:e,col:t}},Pr=n=>{let e=Array.isArray(n.cellData)?n.cellData:null;if(e)return e;let t=[];return n.cellData=t,t},kr=n=>n.rows??3,Yi=n=>n.cols??3,kl=n=>n.minCellHeight??40,Pl=n=>n.minCellWidth??40,Al=n=>{let e=Yi(n),t=Array.isArray(n.columnWidths)?n.columnWidths:[],r=typeof t[0]=="number"?t[0]:n.cellWidth??100,o=t.slice(0,e).map(i=>typeof i=="number"&&i>0?i:r);for(;o.length<e;)o.push(r);return o},go=(n,e)=>{let t=Array.isArray(n.columnWidths)?n.columnWidths:null;t?(t.length=0,t.push(...e)):n.columnWidths=e},ed=(n,e,t,r)=>{let o=kr(n),i=kl(n),s=Array.isArray(n.rowHeights)?n.rowHeights:Array.from({length:o},()=>i);for(;s.length<o;)s.push(i);r!==void 0?s.splice(e,t,r):s.splice(e,t),n.rowHeights=s},td=(n,e,t,r)=>{let o=kr(n),i=Array.isArray(n.manualRowHeights)?n.manualRowHeights:[],s=[];for(let a=0;a<Math.max(o,i.length);a++)s.push(typeof i[a]=="number"?i[a]:null);r!==void 0?s.splice(e,t,r):s.splice(e,t),n.manualRowHeights=s},xo=(n,e,t)=>{let r=Al(n);e<0||e>=r.length||(r[e]=Math.max(Pl(n),t),go(n,r))},yo=(n,e,t)=>{let r=kr(n);if(e<0||e>=r)return;let o=Array.isArray(n.manualRowHeights)?n.manualRowHeights:[],i=[];for(let s=0;s<r;s++)i.push(typeof o[s]=="number"?o[s]:null);i[e]=Math.max(kl(n),t),n.manualRowHeights=i},Nl=(n,e,t,r,o)=>{let i=!0;for(;i;){i=!1;for(let s=e;s<=t;s++)for(let a=r;a<=o;a++){let l=we(n,s,a);if(l){if(l.isMerged&&l.mergeParent){let u=we(n,l.mergeParent.row,l.mergeParent.col);if(u){l.mergeParent.row<e&&(e=l.mergeParent.row,i=!0),l.mergeParent.col<r&&(r=l.mergeParent.col,i=!0);let c=l.mergeParent.row+(u.rowspan??1)-1,h=l.mergeParent.col+(u.colspan??1)-1;c>t&&(t=c,i=!0),h>o&&(o=h,i=!0)}}(l.colspan??1)>1&&a+(l.colspan??1)-1>o&&(o=a+(l.colspan??1)-1,i=!0),(l.rowspan??1)>1&&s+(l.rowspan??1)-1>t&&(t=s+(l.rowspan??1)-1,i=!0)}}}return{r1:e,r2:t,c1:r,c2:o}},Vg=(n,e,t)=>{for(let r=t.r1;r<=t.r2;r++)for(let o=t.c1;o<=t.c2;o++){let i=we(e,r,o);i||(i={row:r,col:o},n.push(i),e.set(`${r},${o}`,i)),i.colspan=1,i.rowspan=1,i.isMerged=!1,i.mergeParent=null}},qg=(n,e)=>{let t=[];for(let r=e.r1;r<=e.r2;r++)for(let o=e.c1;o<=e.c2;o++){let i=we(n,r,o)?.text;i&&i.trim()&&t.push(i.trim())}return t.join(`
7
+ `)},Ll=(n,e,t,r,o,i)=>{for(let s=t;s<t+o;s++)for(let a=r;a<r+i;a++){if(s===t&&a===r)continue;let l=we(e,s,a);l||(l={row:s,col:a},n.push(l),e.set(`${s},${a}`,l)),l.isMerged=!0,l.mergeParent={row:t,col:r},l.text=""}},So=(n,e,t,r,o)=>{let i=Pr(n),s=Dt(i),a=Nl(s,Math.min(e,r),Math.max(e,r),Math.min(t,o),Math.max(t,o));Vg(i,s,a);let l=we(s,a.r1,a.c1);return l&&(l.text=qg(s,a),l.colspan=a.c2-a.c1+1,l.rowspan=a.r2-a.r1+1,Ll(i,s,a.r1,a.c1,l.rowspan,l.colspan)),a},vo=(n,e,t)=>{let r=Dt(Pr(n)),o=we(r,e,t);if(!o||(o.colspan??1)===1&&(o.rowspan??1)===1)return!1;let i=o.colspan??1,s=o.rowspan??1;o.colspan=1,o.rowspan=1;for(let a=e;a<e+s;a++)for(let l=t;l<t+i;l++){if(a===e&&l===t)continue;let u=we(r,a,l);u&&(u.isMerged=!1,u.mergeParent=null)}return!0},nd=n=>({cellFill:n.cellFill,textFill:n.textFill,fontSize:n.fontSize,fontWeight:n.fontWeight,fontFamily:n.fontFamily,fontStyle:n.fontStyle,textAlign:n.textAlign}),rd=(n,e,t,r)=>({row:t,col:r,fill:n?.fill??e.cellFill,stroke:n?.stroke,text:"",textFill:n?.textFill??e.textFill,fontSize:n?.fontSize??e.fontSize,fontWeight:n?.fontWeight??e.fontWeight,fontFamily:n?.fontFamily??e.fontFamily,fontStyle:n?.fontStyle??e.fontStyle,textAlign:n?.textAlign??e.textAlign}),Ui=(n,e,t,r)=>{for(let o of n)o[e]>=t&&(o[e]+=r),o.isMerged&&o.mergeParent&&o.mergeParent[e]>=t&&(o.mergeParent[e]+=r)},od=(n,e,t)=>{let r=e==="row"?"rowspan":"colspan",o=[];for(let i of n){let s=i[r]??1;if(s>1){let a=i[e];t>a&&t<=a+s-1&&o.push(i)}}return o},wo=(n,e)=>{let t=kr(n),r=Yi(n),o=Pr(n),i=Dt(o),s=Math.max(0,Math.min(e,t)),a=od(o,"row",s),l=s>0?s-1:s<t?s:null;Ui(o,"row",s,1);for(let c=0;c<r;c++){let h=l!==null?we(i,l,c):void 0;o.push(rd(h,nd(n),s,c))}ed(n,s,0,kl(n)),td(n,s,0,null),n.rows=t+1;let u=Dt(o);for(let c of a)c.rowspan=(c.rowspan??1)+1,Ll(o,u,c.row,c.col,c.rowspan??1,c.colspan??1)},Il=(n,e)=>{let t=kr(n);if(t<=1)return!1;let r=Math.max(0,Math.min(e,t-1)),o=Pr(n),i=0;for(let s of o)s.row!==r&&(o[i++]=s);return o.length=i,Ui(o,"row",r+1,-1),ed(n,r,1),td(n,r,1),n.rows=t-1,!0},To=(n,e)=>{let t=kr(n),r=Yi(n),o=Pr(n),i=Dt(o),s=Al(n),a=Math.max(0,Math.min(e,r)),l=od(o,"col",a),u=a>0?a-1:a<r?a:null;Ui(o,"col",a,1);for(let d=0;d<t;d++){let f=u!==null?we(i,d,u):void 0;o.push(rd(f,nd(n),d,a))}n.cols=r+1;let c=Math.max(Pl(n),u!==null?s[u]:Pl(n));s.splice(a,0,c),go(n,s);let h=Dt(o);for(let d of l)d.colspan=(d.colspan??1)+1,Ll(o,h,d.row,d.col,d.rowspan??1,d.colspan??1)},_l=(n,e)=>{let t=Yi(n);if(t<=1)return!1;let r=Math.max(0,Math.min(e,t-1)),o=Pr(n),i=Al(n),s=0;for(let a of o)a.col!==r&&(o[s++]=a);return o.length=s,Ui(o,"col",r+1,-1),n.cols=t-1,i.splice(r,1),go(n,i),!0},tr=n=>n.columnWidths.reduce((e,t)=>e+t,0)+(n.cols-1)*n.cellSpacing,nr=n=>n.rowHeights.reduce((e,t)=>e+t,0)+(n.rows-1)*n.cellSpacing,Mr=(n,e,t)=>{let r=0;for(let o=0;o<n.length;o++){if(t>=r&&t<r+n[o])return o;r+=n[o]+e}return-1},Rr=(n,e,t)=>{let r=e==="col"?n.columnWidths:n.rowHeights,o=e==="col"?tr(n):nr(n),i=0;for(let s=0;s<t&&s<r.length;s++)i+=r[s]+n.cellSpacing;return i-n.cellSpacing/2-o/2},Zh=(n,e,t,r,o,i)=>{let s=e/2,a=0;for(let l=0;l<=n.length;l++){let u=l>0&&l<n.length,c=a-s;if(u&&Math.abs(t-c)<r&&o>=0&&o<=i)return l;l<n.length&&(a+=n[l]+e)}return-1},Jh=(n,e,t,r)=>{if(e==="col"){let i=we(n,r,t-1);if(!i)return!1;if(i.isMerged&&i.mergeParent){let s=we(n,i.mergeParent.row,i.mergeParent.col);if(s&&s.col+(s.colspan??1)>t)return!0}else if((i.colspan??1)>1)return!0;return!1}let o=we(n,t-1,r);if(!o)return!1;if(o.isMerged&&o.mergeParent){let i=we(n,o.mergeParent.row,o.mergeParent.col);if(i&&i.row+(i.rowspan??1)>t)return!0}else if((o.rowspan??1)>1)return!0;return!1},Dl=(n,e,t,r,o,i)=>{let s=t+tr(n)/2,a=r+nr(n)/2,l=o,u=i,c=Mr(n.rowHeights,n.cellSpacing,a),h=Mr(n.columnWidths,n.cellSpacing,s),d=Zh(n.columnWidths,n.cellSpacing,s,l,a,nr(n));if(d>0&&c>=0&&!Jh(e,"col",d,c))return{type:"col",index:d,position:Rr(n,"col",d)};let f=Zh(n.rowHeights,n.cellSpacing,a,u,s,tr(n));return f>0&&h>=0&&!Jh(e,"row",f,h)?{type:"row",index:f,position:Rr(n,"row",f)}:null},id=(n,e,t,r)=>{let o=t+tr(n)/2,i=r+nr(n)/2,s=Mr(n.columnWidths,n.cellSpacing,o);if(s<0)return null;let a=Mr(n.rowHeights,n.cellSpacing,i);return a<0?null:lt(e,a,s)},sd=(n,e,t,r,o)=>{let i=o.indicatorOffset??15,s=o.indicatorRadius??8,a=nr(n)/2,l=tr(n)/2;for(let c=1;c<=n.cols;c++){let h=Rr(n,"col",c),d=s/(Math.abs(o.scaleX)*o.zoom);if(Math.hypot(t-h,r-(-a-i))<=d)return{border:{type:"col",index:c,position:h},inCircle:!0}}for(let c=1;c<=n.rows;c++){let h=Rr(n,"row",c),d=s/(Math.abs(o.scaleY)*o.zoom);if(Math.hypot(t-(-l-i),r-h)<=d)return{border:{type:"row",index:c,position:h},inCircle:!0}}let u=Dl(n,e,t,r,o.thresholdX,o.thresholdY);return u?{border:u,inCircle:!1}:null},Eo=(n,e)=>{let t=0;for(let l=0;l<e.c1;l++)t+=n.columnWidths[l]+n.cellSpacing;let r=0;for(let l=e.c1;l<=e.c2;l++)r+=n.columnWidths[l]+(l<e.c2?n.cellSpacing:0);let o=0;for(let l=0;l<e.r1;l++)o+=n.rowHeights[l]+n.cellSpacing;let i=0;for(let l=e.r1;l<=e.r2;l++)i+=n.rowHeights[l]+(l<e.r2?n.cellSpacing:0);let s=tr(n)/2,a=nr(n)/2;return{left:t-s,top:o-a,width:r,height:i}},Co=n=>{let e=new Set,t=[];for(let r of n){let o=`${r.row},${r.col}`;e.has(o)||(e.add(o),t.push(r))}return t},xn=(n,e,t)=>Co((()=>{let r=[];for(let o=Math.min(e.row,t.row);o<=Math.max(e.row,t.row);o++)for(let i=Math.min(e.col,t.col);i<=Math.max(e.col,t.col);i++)r.push(lt(n,o,i));return r})()),$i=(n,e,t)=>{let r=[];for(let o=0;o<e;o++){let i=lt(n,o,t);i.col===t&&r.push(i)}return Co(r)},ji=(n,e,t)=>{let r=[];for(let o=0;o<e;o++){let i=lt(n,t,o);i.row===t&&r.push(i)}return Co(r)},Mo=(n,e,t)=>{let r=[];for(let o=0;o<e;o++)for(let i=0;i<t;i++)r.push(lt(n,o,i));return Co(r)},ze=n=>{if(!n.length)return null;let e=1/0,t=-1/0,r=1/0,o=-1/0;for(let i of n)e>i.row&&(e=i.row),t<i.row&&(t=i.row),r>i.col&&(r=i.col),o<i.col&&(o=i.col);return{r1:e,r2:t,c1:r,c2:o}},Vi=(n,e,t,r)=>{let o=[];for(let u of n){let c=r==="row"?u.row:u.col;if(c===t)continue;let h=c>t?c-1:c;o.push(r==="row"?{row:h,col:u.col}:{row:u.row,col:h})}let i=Co(o);if(!i.length)return null;if(!e)return{cells:i,range:null};let s=r==="row"?e.r1:e.c1,a=r==="row"?e.r2:e.c2,l;if(s===t&&a===t)l=ze(i)??e;else{let u=s>t?s-1:s,c=a>t?a-1:a===t?t-1:a;l=r==="row"?{r1:u,r2:c,c1:e.c1,c2:e.c2}:{r1:e.r1,r2:e.r2,c1:u,c2:c}}return{cells:i,range:l}},ad=(n,e,t,r)=>Math.abs(e-n)>=.5||Math.abs(t)<=1?0:Math.sign(t)*Math.min(1.5,Math.abs(t)*.1)/r,Kg=["ew","nwse","ns","nesw"],ld=(n,e)=>{let t=e==="col"?0:2,r=(n%180+180)%180,o=Math.round(r/45)%4;return`${Kg[(t+o)%4]}-resize`};var zi=(n,e)=>{let t=Math.abs(n)*Math.max(e,1e-6);return t>1e-6?20/t:20},cd=(n,e,t,r,o,i={x:1,y:1},s=1)=>{if(o<-t/2&&o>=-t/2-zi(i.y,s)){let a=Mr(n.columnWidths,n.cellSpacing,r+tr(n)/2);if(a>=0)return{kind:"col-strip",col:a}}if(r<-e/2&&r>=-e/2-zi(i.x,s)){let a=Mr(n.rowHeights,n.cellSpacing,o+nr(n)/2);if(a>=0)return{kind:"row-strip",row:a}}return null},ud=(n,e,t,r,o={x:1,y:1},i=1)=>{let s=zi(o.x,i),a=zi(o.y,i);return t>=-n/2-s&&t<-n/2&&r>=-e/2-a&&r<-e/2};var hd=(n,e,t,r={x:1,y:1},o=1)=>{let i=l=>Math.max(Math.abs(l)*Math.max(o,1e-6),1e-6),s=12/i(r.x),a=12/i(r.y);return Math.abs(e-(n.left+n.width))<=s&&Math.abs(t-(n.top+n.height))<=a},Ar=(n,e)=>{let t=new Set,r=new Set;for(let o of e){let i=lt(n,o.row,o.col),s=we(n,i.row,i.col),a=s?.rowspan??1,l=s?.colspan??1;for(let u=i.row;u<i.row+a;u++)t.add(u);for(let u=i.col;u<i.col+l;u++)r.add(u)}return{rows:t,cols:r}};var qi=14,dd=(n,e,t)=>{let r=[0];for(let o=0;o<n-1;o++)r.push(r[o]+e[o]+t);return r},Fl=(n,e,t,r)=>{let o=0;for(let i=0;i<e;i++)o+=t[n+i]??0,i>0&&(o+=r);return o},Ro=(n,e,t)=>{let r=n.rows??3,o=n.cols??3,i=Array.isArray(n.columnWidths)?n.columnWidths:[],s=i[0]??100,a=Array.from({length:o},(_,D)=>i[D]??s),l=n.minCellHeight??40,u=n.cellPadding??8,c=n.cellSpacing??0,h=n.cellStrokeWidth??1,d=n.cellFill,f=n.cellStroke,m=n.textFill,p=n.fontFamily||"仓耳小丸子",b=Array.isArray(n.manualRowHeights)?n.manualRowHeights:[],g=Array.from({length:r},(_,D)=>typeof b[D]=="number"?b[D]:null),x=Array.isArray(n.cellData)?n.cellData:[],S=Dt(x),w=new Map;for(let _ of x){if(_.isMerged)continue;let D=Math.max(0,Fl(_.col,_.colspan??1,a,c)-u*2);w.set(`${_.row},${_.col}`,{layout:jt(_.text??"",{fontFamily:_.fontFamily||p,fontSize:_.fontSize??qi,fontWeight:_.fontWeight,fontStyle:_.fontStyle,lineHeight:1.16,charSpacing:0,textAlign:_.textAlign??fe.CENTER},{boxWidth:D,splitByGrapheme:!0,measure:e}),data:_})}let y=qi*Mi,v=[],R=[];for(let _=0;_<r;_++){let D=0;for(let V=0;V<o;V++){if(S.get(`${_},${V}`)?.isMerged)continue;let H=w.get(`${_},${V}`);D=Math.max(D,H?H.layout.height:y)}let I=g[_],G=D+u*2,$=I!==null?I:l;R.push(G),v.push(Math.max($,G))}let P=a.reduce((_,D)=>_+D,0)+(o-1)*c,T=v.reduce((_,D)=>_+D,0)+(r-1)*c,C=dd(o,a,c),E=dd(r,v,c),M=typeof n.id=="string"&&n.id?n.id:"table",k=[];for(let _=0;_<r;_++)for(let D=0;D<o;D++){let I=S.get(`${_},${D}`);if(I?.isMerged)continue;let G=I?.colspan??1,$=I?.rowspan??1,V=Fl(D,G,a,c),H=Fl(_,$,v,c),Y=C[D]-P/2+V/2,X=E[_]-T/2+H/2;k.push({type:"rect",id:`${M}-r${_}c${D}-rect`,left:Y,top:X,width:V,height:H,originX:"center",originY:"center",fill:I?I.fill:d,stroke:I?I.stroke:f,strokeWidth:h,scaleX:1,scaleY:1,angle:0,opacity:1,visible:!0});let Z=I?w.get(`${_},${D}`):void 0,B=t?.hideTextCell!==void 0&&t.hideTextCell.row===_&&t.hideTextCell.col===D;if(Z&&!B&&(I?.text??"")!==""){let q=Z.layout.height,U=I?.verticalAlign??"middle",oe=X;U==="top"?oe=X-H/2+q/2+u:U==="bottom"&&(oe=X+H/2-q/2-u),k.push({type:"textbox",id:`${M}-r${_}c${D}-text`,left:Y,top:oe,width:Math.max(0,V-u*2),text:I?.text??"",fill:I?.textFill??m,fontFamily:I?.fontFamily||p,fontSize:I?.fontSize??qi,fontWeight:I?.fontWeight,fontStyle:I?.fontStyle,textAlign:I?.textAlign??fe.CENTER,lineHeight:1.16,splitByGrapheme:!0,originX:"center",originY:"center",scaleX:1,scaleY:1,angle:0,opacity:1,visible:!0})}}let A=Math.max(l,qi*Mi+u*2),O=o*s+(o-1)*c+h,F=r*A+(r-1)*c+h,W=P+h,z=T+h;return{rowHeights:v,rowTextFloors:R,columnWidths:a,contentWidth:P,contentHeight:T,width:W,height:z,children:k,constructorDims:{width:O,height:F}}};var Sn="WorkSpaceDrawType",Ir=new Set(["WorkSpaceDrawType","WorkSpaceClipType","WorkSpaceSafeType","WorkSpaceMaskType","WorkSpaceLineType","WorkSpaceShadowType"]),Qg=new Set(["WorkSpaceClipType","WorkSpaceSafeType"]),rr=n=>{let e=n.raw?.id;return typeof e=="string"&&Qg.has(e)},Kt=n=>n.isTextType&&typeof n.raw.renderSrc=="string",Po=n=>{let e=n.fill;return typeof e!="string"||!e?1:Math.max(0,Math.min(1,ee(e)[3]))},gd=n=>{let e=n.fillOpacity;if(typeof e!="number"||!isFinite(e))return 1;let t=e>1?e/255:e;return Math.max(0,Math.min(1,t))},Zg=new Set(["left","top","angle","scaleX","scaleY","skewX","skewY","flipX","flipY","originX","originY"]),Jg=new Set(["text","styles","paragraph","texts","textPath","path","pathStartOffset","pathSide","pathAlign","fontFamily","fontSize","fontWeight","fontStyle","lineHeight","charSpacing","textAlign","splitByGrapheme","vertical","direction","underline","overline","linethrough","textBackgroundColor","textDecorationThickness","textScaleX","textScaleY","width","height","minWidth","fill","stroke","strokeWidth","strokeUniform","paintFirst"]),Wl=n=>{for(let e in n)if(!Zg.has(e))return!1;return!0},Qi=999999,Ze=n=>n.isReferenceLine,Hl=n=>{let e=n.raw;return e.lockMovementX===!0&&e.lockMovementY===!0},xd=(n,e)=>({type:"ReferenceLine",id:`referenceline-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,name:"ReferenceLine",axis:n,x1:n==="horizontal"?-Qi:0,y1:n==="horizontal"?0:-Qi,x2:n==="horizontal"?Qi:0,y2:n==="horizontal"?0:Qi,left:n==="horizontal"?0:e,top:n==="horizontal"?e:0,originX:"center",originY:"center",scaleX:1,scaleY:1,angle:0,opacity:1,visible:!1,selectable:!1,evented:!0,hasControls:!1,hasBorders:!1,stroke:"pink",fill:"pink",strokeWidth:1,padding:8,globalCompositeOperation:"difference",lockMovementX:n==="horizontal",lockMovementY:n==="vertical",hoverCursor:n==="horizontal"?"ns-resize":"ew-resize"}),ex=["type","left","top","width","height","angle","scaleX","scaleY","skewX","skewY","flipX","flipY","originX","originY","strokeWidth","strokeUniform","fill","opacity","visible","src","crossOrigin","id","name"],ct=class{raw;syntheticOwner;_parentMatrix=null;_parentOpacity=1;_inIsolatedFBO=!1;_imageEl=null;_matrix=null;_aCoords=null;_bounds=null;_fillPaint;_animationOverride=null;constructor(e){this.raw={...e},Fu(this.raw),this._typeKey=se(this.raw),this._isReferenceLine=this._typeKey===L.REFERENCELINE}_typeKey;get typeKey(){return this._typeKey}_isReferenceLine;get isReferenceLine(){return this._isReferenceLine}_strokeDecl;get strokeDecl(){return this._strokeDecl===void 0&&(this._strokeDecl=Ei(this.raw)),this._strokeDecl}get imageEl(){return this._imageEl}set imageEl(e){this._imageEl=e,this.invalidateGeometryCache(),this._renderNotify?.()}invalidateGeometryCache(){this._matrix=null,this._aCoords=null,this._bounds=null}_renderNotify=null;markRenderDirty(){this._renderNotify?.()}set(e){Ou(this.raw,e),Object.assign(this.raw,e),this.invalidateGeometryCache(),Wl(e)||(this._fillPaint=void 0,this._strokeDecl=void 0),"type"in e&&(this._typeKey=se(e),this._isReferenceLine=this._typeKey===L.REFERENCELINE),this._renderNotify?.()}setAnimationOverride(e){this._animationOverride=e,this.invalidateGeometryCache(),this._renderNotify?.()}get id(){return typeof this.raw.id=="string"?this.raw.id:""}get isImageType(){return dt.has(this.typeKey)}get isMaskType(){return ot.has(this.typeKey)}get isSolidType(){return $n.has(this.typeKey)}get isTextType(){return an.has(this.typeKey)}get isLineType(){return ft.has(this.typeKey)}get isShapeType(){return Un.has(this.typeKey)}get visible(){return this.raw.visible!==!1}get fillPaint(){if(this._fillPaint===void 0){let e=Yn(this.raw.fill),t=e?null:pr(this.raw.fill);e?this._fillPaint={kind:"gradient",decl:e}:t?this._fillPaint={kind:"pattern",decl:t}:this.raw.fill?this._fillPaint={kind:"solid",color:ee(this.raw.fill)}:this._fillPaint=null}return this._fillPaint}get drawColor(){let e=this.renderOpacity;if(this.isImageType)return[1,1,1,e];let t=ee(this.raw.fill);return[t[0],t[1],t[2],t[3]*e]}get transformProps(){let e={...this.raw,width:this.dims.x,height:this.dims.y},t=this._animationOverride;if(!t)return e;let{opacity:r,...o}=t;return{...e,...o}}get center(){return Ut(this.transformProps)}get matrix(){return this._matrix||(this._matrix=Gn(this.transformProps)),this._parentMatrix?j(this._parentMatrix,this._matrix):this._matrix}get ownMatrix(){return this._matrix||(this._matrix=Gn(this.transformProps)),this._matrix}get worldAngle(){let e=this.matrix;return Math.atan2(e[1],e[0])*180/Math.PI}get worldScale(){let e=this.matrix;return{x:Math.hypot(e[0],e[1]),y:Math.hypot(e[2],e[3])}}get aCoords(){if(this._aCoords||(this._aCoords=$a(this.transformProps)),!this._parentMatrix)return this._aCoords;let e=this._parentMatrix;return{tl:Q(e,this._aCoords.tl.x,this._aCoords.tl.y),tr:Q(e,this._aCoords.tr.x,this._aCoords.tr.y),br:Q(e,this._aCoords.br.x,this._aCoords.br.y),bl:Q(e,this._aCoords.bl.x,this._aCoords.bl.y)}}contentBoxCorners(){let e=typeof this.raw.strokeWidth=="number"?this.raw.strokeWidth:0,t=this.raw.strokeUniform===!0,r=(t?this.dims.x:this.dims.x+e)/2,o=(t?this.dims.y:this.dims.y+e)/2,i=t?e/2:0,s=this.ownMatrix,a=1/0,l=1/0,u=-1/0,c=-1/0;for(let h of[-r,r])for(let d of[-o,o]){let f=Q(s,h,d);f.x<a&&(a=f.x),f.y<l&&(l=f.y),f.x>u&&(u=f.x),f.y>c&&(c=f.y)}return{tl:{x:a-i,y:l-i},tr:{x:u+i,y:l-i},br:{x:u+i,y:c+i},bl:{x:a-i,y:c+i}}}get inkACoords(){return this.aCoords}get parentMatrix(){return this._parentMatrix}setParentMatrix(e,t=1){this._parentMatrix=e,this._parentOpacity=t,this.invalidateWorldGeometry(),this._renderNotify?.()}get renderOpacity(){return(this._animationOverride?.opacity??this.raw.opacity??1)*(this._inIsolatedFBO?1:this._parentOpacity)}setIsolation(e){if(this._inIsolatedFBO=e,this instanceof J)for(let t of this.children)t.setIsolation(e)}invalidateWorldGeometry(){this._matrix=null,this._aCoords=null,this._bounds=null}get bounds(){return this._bounds||(this._bounds=Xn(this.aCoords)),this._bounds}containsPoint(e,t,r=0){if(this.isSolidType&&!es(this))return Gl(this)&&this.outlineStrokeHitAt(e,t,r);let o=this.aCoords,i=[o.tl,o.tr,o.br,o.bl],s=!1;for(let a=0,l=3;a<4;l=a++){let u=i[a].x,c=i[a].y,h=i[l].x,d=i[l].y;c>t!=d>t&&e<(h-u)*(t-c)/(d-c)+u&&(s=!s)}return s}outlineStrokeHitAt(e,t,r=0){if(!this.isSolidType)return!1;let o=this.dims.x/2,i=this.dims.y/2;if(!(o>0)||!(i>0))return!1;let s=this.localPoint(e,t),a=Math.abs(s.x)-o,l=Math.abs(s.y)-i;return(a>0||l>0?Math.hypot(Math.max(a,0),Math.max(l,0)):Math.min(-a,-l))<=Xl(this,r)}localPoint(e,t){return Q(ve(this.matrix),e,t)}rotateAroundCenter(e,t=this.center){let r=ge({...this.transformProps,angle:e},t);return{angle:e,left:r.x,top:r.y}}get dims(){let e=this.cropRect;if(e)return{x:e.sw,y:e.sh};let t=this.raw.width??(this.imageEl?this.imageEl.naturalWidth:0),r=this.raw.height??(this.imageEl?this.imageEl.naturalHeight:0);return{x:t,y:r}}get cropRect(){return ts(this.raw)}toObject(){let e={};for(let t of ex)this.raw[t]!==void 0&&(e[t]=this.raw[t]);for(let[t,r]of Object.entries(this.raw))e[t]===void 0&&!t.startsWith("_")&&(e[t]=r);return e}},tx=n=>{if(n.angle===0||n.w<=0||n.h<=0)return null;let e=(n.angle%180+180)%180,t=Math.min(e,180-e);if(t<2)return null;let r=t*Math.PI/180,o=Math.abs(Math.cos(r)),i=Math.abs(Math.sin(r)),s=o*o-i*i;if(Math.abs(s)<.5)return null;let a=(n.w*o-n.h*i)/s,l=(n.h*o-n.w*i)/s;return!Number.isFinite(a)||!Number.isFinite(l)||a<=0||l<=0?null:{w:a,h:l}},nx=n=>{let{fw:e,fh:t}=n;if(e===void 0||t===void 0)return null;let r=n.w+n.h;return!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0||e>r||t>r?null:{w:e,h:t}},ye=class extends ct{_layout=null;_arcDims=null;_scrollOffset=0;constructor(e){super(e)}set(e){super.set(e),Wl(e)||(this.invalidateTextLayout(),typeof this.raw.renderSrc=="string"&&Object.keys(e).some(t=>Jg.has(t))&&(delete this.raw.renderSrc,delete this.raw.renderRect))}invalidateTextLayout(){this._layout=null,this._arcDims=null,this.invalidateGeometryCache(),this._renderNotify?.()}get textStyle(){let e=this.raw;return{fontFamily:e.fontFamily??"Times New Roman",fontSize:e.fontSize??40,fontWeight:e.fontWeight,fontStyle:e.fontStyle,lineHeight:e.lineHeight??1.16,charSpacing:e.charSpacing??0,textAlign:e.textAlign??fe.LEFT}}get paintFirst(){return this.raw.paintFirst==="stroke"?"stroke":"fill"}get textStroke(){let e=this.raw,t=typeof e.stroke=="string"?e.stroke:"",r=e.strokeWidth??1;return!t||r===0?null:{color:t,width:r,lineJoin:e.strokeLineJoin,miterLimit:e.strokeMiterLimit,lineCap:e.strokeLineCap}}get decorationDefaults(){let e=this.raw;return{underline:!!e.underline,overline:!!e.overline,linethrough:!!e.linethrough,textDecorationThickness:e.textDecorationThickness,fontSize:this.textStyle.fontSize,fill:typeof e.fill=="string"?e.fill:void 0,charSpacing:this.textStyle.charSpacing,vertical:e.vertical===!0}}get textLayout(){if(!this._layout){let e=this.raw,t=Ge(e),r=(se(e)===L.TEXTBOX||se(e)===L.TEXTIMAGE)&&t===null;this._layout=jt(e.text??"",this.textStyle,{boxWidth:r?e.width??0:null,styles:e.styles,splitByGrapheme:e.splitByGrapheme===!0,vertical:e.vertical===!0,paragraph:t==="arc"||t==="circle"?void 0:e.paragraph})}return this._layout}get scrollOffset(){return this._scrollOffset}setScrollOffset(e){this._scrollOffset=Number.isFinite(e)?e:0,this._renderNotify?.()}get textTotalWidth(){let e=this.textLayout;if(this.raw.vertical===!0&&e.verticalWidth!==void 0)return e.verticalWidth;let t=0;for(let r of e.lines)r.width>t&&(t=r.width);return t}get dims(){if(typeof this.raw.renderSrc=="string"){let t=this.bitmapRect;return{x:t.w,y:t.h}}if(Xe(this.raw)){if(!this._arcDims){let t=Et(this.textLayout,this.raw,this.textStyle.lineHeight??1.16);this._arcDims={x:t.width,y:t.height}}return this._arcDims}let e=typeof this.raw.height=="number"?this.raw.height:0;return{x:this.textLayout.width,y:Math.max(this.textLayout.height,e)}}get bitmapRect(){let e=this.raw.renderRect,t=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0?u:null,r=(e&&t(e.w))??(typeof this.raw.width=="number"?this.raw.width:0),o=(e&&t(e.h))??(typeof this.raw.height=="number"?this.raw.height:0),i=e&&typeof e.x=="number"&&Number.isFinite(e.x)?e.x:0,s=e&&typeof e.y=="number"&&Number.isFinite(e.y)?e.y:0,a=e&&typeof e.angle=="number"&&Number.isFinite(e.angle)?e.angle:0,l={x:i,y:s,w:r,h:o,angle:a};if(e){let u=m=>typeof m=="number"&&Number.isFinite(m)?m:void 0,c=u(e.fw),h=u(e.fh);c!==void 0&&h!==void 0&&(l.fw=c,l.fh=h);let d=u(e.fx),f=u(e.fy);d!==void 0&&f!==void 0&&(l.fx=d,l.fy=f)}return l}get aCoords(){let e=this.bitmapFrameCorners();if(e){let t=this.parentMatrix;if(!t)return e;let r=o=>Q(t,o.x,o.y);return{tl:r(e.tl),tr:r(e.tr),br:r(e.br),bl:r(e.bl)}}return super.aCoords}contentBoxCorners(){return this.bitmapFrameCorners()??super.contentBoxCorners()}bitmapFrameCorners(){if(typeof this.raw.renderSrc!="string")return null;let e=this.bitmapRect,t=nx(e)??tx(e);if(!t&&e.angle===0&&e.x===0&&e.y===0)return null;let r=this.ownMatrix;(e.x!==0||e.y!==0)&&(r=j(r,[1,0,0,1,e.x,e.y])),t&&e.fx!==void 0&&e.fy!==void 0&&(e.fx!==0||e.fy!==0)&&(r=j(r,[1,0,0,1,e.fx,e.fy])),!t&&e.angle!==0&&(r=j(r,At({angle:-e.angle})));let o=(t?t.w:e.w)/2,i=(t?t.h:e.h)/2;return{tl:Q(r,-o,-i),tr:Q(r,o,-i),br:Q(r,o,i),bl:Q(r,-o,i)}}get inkACoords(){return Yh(this,this.textInkACoords)}get textInkACoords(){if(typeof this.raw.renderSrc=="string")return super.inkACoords;let e=Ge(this.raw);if(e==="arc"||e==="circle"||e==="scroll")return super.inkACoords;let t=this.textLayout,r,o,i,s;if(e!==null){let c=Sr(this.raw),h=c?Pi(t,this.textStyle,{align:this.textStyle.textAlign}):null,d=c&&h?fh(c,t,this.raw,h,this.contentTopY):null;if(d)r=d.left,o=d.right,i=d.top,s=d.bottom;else{if(c)return super.inkACoords;let f=Pi(t,this.textStyle,{vertical:this.raw.vertical===!0,align:this.textStyle.textAlign});if(!f)return super.inkACoords;let m=t.width/2;r=-m+f.lo,o=-m+f.hi,i=this.contentTopY+f.firstTop,s=this.contentTopY+t.height}}else{let c=Pi(t,this.textStyle,{vertical:this.raw.vertical===!0,align:this.textStyle.textAlign});if(!c)return super.inkACoords;let h=t.width/2;r=-h+c.lo,o=-h+c.hi,i=this.contentTopY+c.firstTop,s=this.contentTopY+t.height}let a=this.ownMatrix,l=this.parentMatrix,u=(c,h)=>{let d=Q(a,c,h);return l?Q(l,d.x,d.y):d};return{tl:u(r,i),tr:u(o,i),br:u(o,s),bl:u(r,s)}}get contentTopY(){return typeof this.raw.renderSrc=="string"?-this.textLayout.height/2:-this.dims.y/2}cursorCoord(e){let t=this.textLayout;if(t.lines.length===0)return null;let r=0,o=0;for(let c=0;c<t.lines.length;c++){let h=t.lines[c],d=h.styleMap.flatStart,f=d+h.graphemes.length;if(e<=f){r=c,o=Math.max(0,e-d);break}c===t.lines.length-1&&(r=c,o=h.graphemes.length)}let i=t.lines[r],s=-t.width/2+i.leftOffset+(o<i.boxes.length?i.boxes[o].left:hn(i)),l=i.charStyles[Math.max(0,o-1)]?.fontSize??this.textStyle.fontSize,u=this.contentTopY+i.baseline-l*.93;return{x:s,y:u,height:l*1.28}}cursorIndexAt(e,t){let r=this.textLayout;if(r.lines.length===0)return 0;let o=t-this.contentTopY,i=0;for(let l=0;l<r.lines.length;l++){let u=r.lines[l];if(o<=u.baseline+this.textStyle.fontSize*.3){i=l;break}i=l}let s=r.lines[i],a=-r.width/2+s.leftOffset;for(let l=0;l<s.boxes.length;l++){let u=s.boxes[l];if(e<a+u.left+u.width/2)return s.styleMap.flatStart+l}return s.styleMap.flatStart+s.graphemes.length}wordBoundsAt(e){let t=Array.from(this.raw.text??""),r=a=>a===" "||a===" "||a==="\r"||a===`
8
+ `,o=Math.max(0,Math.min(e,t.length));if(r(t[o]))return[o,o];let i=o,s=o;for(;i>0&&!r(t[i-1]);)i--;for(;s<t.length&&!r(t[s]);)s++;return[i,s]}},rx=(n,e)=>Math.max(24,Math.min(128,Math.ceil((n+e)*.6))),fd=(n,e)=>{if(!(n>0)||!(e>0))return null;let t=rx(n,e),r=new Float32Array((t+1)*2);for(let i=0;i<t;i++){let s=i/t*Math.PI*2;r[(i+1)*2]=n*Math.cos(s),r[(i+1)*2+1]=e*Math.sin(s)}let o=new Uint32Array(t*3);for(let i=0;i<t;i++)o[i*3]=0,o[i*3+1]=1+i,o[i*3+2]=1+(i+1)%t;return{verts:r,triangles:o}},md=n=>{if(!Array.isArray(n)||n.length<3)return null;let e=n,t=1/0,r=1/0,o=-1/0,i=-1/0;for(let h of e)t>h.x&&(t=h.x),r>h.y&&(r=h.y),o<h.x&&(o=h.x),i<h.y&&(i=h.y);let s=(t+o)/2,a=(r+i)/2,l=new Float32Array(e.length*2),u=new Array(e.length);for(let h=0;h<e.length;h++)l[h*2]=e[h].x-s,l[h*2+1]=e[h].y-a,u[h]={x:l[h*2],y:l[h*2+1]};let c=el(u);return c.length>0?{verts:l,triangles:new Uint32Array(c)}:null},ox=n=>{let e=0;for(let i of n)e+=i.length;if(e<3)return null;let t=new Float32Array(e*2),r=[],o=0;for(let i of n){for(let s=0;s<i.length;s++)t[(o+s)*2]=i[s].x,t[(o+s)*2+1]=i[s].y;for(let s of el(i))r.push(s+o);o+=i.length}return r.length>0?{verts:t,triangles:new Uint32Array(r)}:null},ix=n=>{let e=Ce(n);if(!e)return{contours:[],dims:{x:0,y:0}};let t=Fe(e),r=qu(e);if(!t)return{contours:r,dims:{x:0,y:0}};let o=(t.left+t.right)/2,i=(t.top+t.bottom)/2;return{contours:r.map(a=>({closed:a.closed,points:a.points.map(l=>({x:l.x-o,y:l.y-i}))})),dims:{x:t.right-t.left,y:t.bottom-t.top}}},yn=class extends ct{_mesh;set(e){super.set(e),Wl(e)||(this._mesh=void 0)}get shapeKind(){return this.typeKey}get shapeMesh(){if(this._mesh===void 0){let e=this.raw,t=this.shapeKind;if(t===L.ELLIPSE)this._mesh=fd(e.rx??0,e.ry??0);else if(t===L.CIRCLE){let r=e.radius??0;this._mesh=fd(r,r)}else t===L.TRIANGLE?this._mesh=md(pd(e)):this._mesh=md(e.points)}return this._mesh}get dims(){let e=this.raw,t=this.shapeKind;return t===L.ELLIPSE?{x:2*(e.rx??0),y:2*(e.ry??0)}:t===L.CIRCLE?{x:2*(e.radius??0),y:2*(e.radius??0)}:t===L.TRIANGLE?{x:e.width??0,y:e.height??0}:sx(e.points)}containsPoint(e,t,r=0){if(!es(this))return Gl(this)&&this.outlineStrokeHitAt(e,t,r);let o=this.localPoint(e,t),i=this.shapeKind;if(i===L.ELLIPSE||i===L.CIRCLE){let a=this.dims.x/2,l=this.dims.y/2;if(!(a>0)||!(l>0))return!1;let u=o.x/a,c=o.y/l;return u*u+c*c<=1}let s=this.shapeMesh;return i===L.POLYLINE||i===L.POLYGON?s?bd(s.verts,o.x,o.y):Ol(this.raw.points,o,i===L.POLYGON,Math.max((Number(this.raw.strokeWidth)||1)/2,3,r)):s?bd(s.verts,o.x,o.y):!1}outlineStrokeHitAt(e,t,r=0){let o=this.localPoint(e,t),i=this.shapeKind,s=Xl(this,r);if(i===L.ELLIPSE||i===L.CIRCLE){let a=this.dims.x/2,l=this.dims.y/2;if(!(a>0)||!(l>0))return!1;let u=2*o.x/(a*a),c=2*o.y/(l*l),h=Math.hypot(u,c);if(h<1e-9)return Math.min(a,l)<=s;let d=o.x*o.x/(a*a)+o.y*o.y/(l*l)-1;return Math.abs(d)/h<=s}return i===L.TRIANGLE?Ol(pd(this.raw),o,!0,s):Ol(this.raw.points,o,i===L.POLYGON,s)}},pd=n=>{let e=n.width??0,t=n.height??0;return[{x:e/2,y:0},{x:e,y:t},{x:0,y:t}]},sx=n=>{if(!Array.isArray(n)||n.length===0)return{x:0,y:0};let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)e>i.x&&(e=i.x),t>i.y&&(t=i.y),r<i.x&&(r=i.x),o<i.y&&(o=i.y);return{x:r-e,y:o-t}},Ji=10,Bl=n=>Math.min(1,Math.max(0,n)),ax=n=>{let e=n.fillPaint;if(!e)return 0;if(e.kind==="solid")return Bl(e.color[3])*n.renderOpacity;if(e.kind==="gradient"){let t=0;for(let r of e.decl.stops)t=Math.max(t,Bl(r.color[3]));return t*n.renderOpacity}return null},es=n=>{let e=ax(n);return e===null||e*255>Ji},Gl=n=>{let e=n.raw.stroke;return typeof e=="object"&&e!==null?!0:typeof e!="string"||!e||Number(n.raw.strokeWidth)===0?!1:Bl(ee(e)[3])*n.renderOpacity*255>Ji},Xl=(n,e)=>Math.max((Number(n.raw.strokeWidth)||1)/2,3,e),zl=8,yd=n=>{let e=n.typeKey;return e===L.LINE||e===L.ARROW||e===L.DIMENSION||e===L.POLYLINE?!0:(n.isShapeType||n.isSolidType)&&!es(n)},Zi=(n,e,t,r,o,i)=>{let s=o-t,a=i-r,l=s*s+a*a,u=l>0?Math.max(0,Math.min(1,((n-t)*s+(e-r)*a)/l)):0,c=t+u*s-n,h=r+u*a-e;return c*c+h*h},Ol=(n,e,t,r)=>{if(!Array.isArray(n)||n.length<2)return!1;let o=n,i=1/0,s=1/0,a=-1/0,l=-1/0;for(let d of o)i>d.x&&(i=d.x),s>d.y&&(s=d.y),a<d.x&&(a=d.x),l<d.y&&(l=d.y);let u=(i+a)/2,c=(s+l)/2,h=r*r;for(let d=0;d+1<o.length;d++)if(Zi(e.x,e.y,o[d].x-u,o[d].y-c,o[d+1].x-u,o[d+1].y-c)<=h)return!0;if(t&&o.length>2){let d=o[o.length-1];if(Zi(e.x,e.y,d.x-u,d.y-c,o[0].x-u,o[0].y-c)<=h)return!0}return!1},Nr=class extends yn{_pathGeo;_fillPolys;_pathMesh;set(e){super.set(e),("path"in e||"fillRule"in e)&&(this._pathGeo=void 0,this._fillPolys=void 0,this._pathMesh=void 0)}get pathGeometry(){return this._pathGeo===void 0&&(this._pathGeo=ix(this.raw.path)),this._pathGeo}get fillPolygons(){if(this._fillPolys===void 0){let e=this.raw.fillRule==="evenodd"?"evenodd":"nonzero";this._fillPolys=Qu(this.pathGeometry.contours,e)}return this._fillPolys}get shapeMesh(){return this._pathMesh===void 0&&(this._pathMesh=ox(this.fillPolygons)),this._pathMesh}get dims(){return this.pathGeometry.dims}containsPoint(e,t,r=0){return es(this)?ct.prototype.containsPoint.call(this,e,t):Gl(this)&&this.outlineStrokeHitAt(e,t,r)}outlineStrokeHitAt(e,t,r=0){let o=this.localPoint(e,t),i=this.pathGeometry.contours;if(i.length===0)return!1;let s=Xl(this,r)**2;for(let a of i){let l=a.points;for(let u=0;u+1<l.length;u++)if(Zi(o.x,o.y,l[u].x,l[u].y,l[u+1].x,l[u+1].y)<=s)return!0}return!1}},lx=(n,e,t)=>{let r=Number(n.strokeWidth)||1,o=Number(n.arrowWidth)||15,i=Number(n.arrowHeight)||22.5,s=n.arrowType==="start"||n.arrowType==="both"?n.arrowType:"end",a=Math.sqrt(r),l=o*a,u=i*a;if(!(u>0)||!(l>0))return!1;let c=Math.atan2(t.y2-t.y1,t.x2-t.x1),h=(d,f,m)=>{let p=Math.cos(m),b=Math.sin(m),g=e.x-d,x=e.y-f,S=g*p+x*b,w=-g*b+x*p;return S<-u||S>0?!1:Math.abs(w)<=l/2*(1+S/u)};return!!((s==="end"||s==="both")&&h(t.x2,t.y2,c)||(s==="start"||s==="both")&&h(t.x1,t.y1,c+Math.PI))},cx=(n,e,t,r)=>{let o=Number(n.textFontSize)||50,i=Number(n.textPadding)||4,s=typeof n.text=="string"&&n.text.trim()?n.text:"50cm",a=no(`${o}px Arial, sans-serif`,s)+i*2,l=Math.atan2(t.y2-t.y1,t.x2-t.x1),u=-Math.sin(l),c=Math.cos(l),h=o/2,d=r*r;for(let[R,P]of[[t.x1,t.y1],[t.x2,t.y2]])if(Zi(e.x,e.y,R-u*h,P-c*h,R+u*h,P+c*h)<=d)return!0;let f=o+(Number(n.strokeWidth)||1)/2+5,m=(t.x1+t.x2)/2+u*f,p=(t.y1+t.y2)/2+c*f,b=n.textFollowLine===!1?0:l,g=Math.cos(b),x=Math.sin(b),S=e.x-m,w=e.y-p,y=S*g+w*x,v=-S*x+w*g;return Math.abs(y)<=a/2&&Math.abs(v)<=(o+i*2)/2},Lr=class extends ct{get dims(){let e=this.linePoints;return e?{x:Math.abs(e.x2-e.x1),y:Math.abs(e.y2-e.y1)}:{x:0,y:0}}get linePoints(){let e=Number(this.raw.x1),t=Number(this.raw.y1),r=Number(this.raw.x2),o=Number(this.raw.y2);return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o)?null:{x1:e,y1:t,x2:r,y2:o}}containsPoint(e,t,r=0){let o=this.linePoints;if(!o)return!1;let i=this.localPoint(e,t);if(!i)return!1;let s=o.x2-o.x1,a=o.y2-o.y1,l=s*s+a*a,u=0;l>0&&(u=Math.max(0,Math.min(1,((i.x-o.x1)*s+(i.y-o.y1)*a)/l)));let c=o.x1+u*s,h=o.y1+u*a,d=Math.max((Number(this.raw.strokeWidth)||1)/2,3,r,Number(this.raw.padding)||0);if(Math.hypot(i.x-c,i.y-h)<=d)return!0;let f=this.typeKey;return f===L.ARROW?lx(this.raw,i,o):f===L.DIMENSION?cx(this.raw,i,o,d):!1}},ie=class extends ct{animatedKind;_sprite=null;_frameCanvas=null;_frameIndex=0;_anchorTime=0;_playing=!1;_videoEl=null;_frameDirty=!1;_rvfcActive=!1;_contentVersion=0;_onNewFrame=null;constructor(e,t){super(e),this.animatedKind=t}get isImageType(){return!0}get animating(){if(this.animatedKind==="video"){let e=this._videoEl;return!!e&&!e.paused&&!e.ended}return this._playing&&!!this._sprite&&this._sprite.framesLength>1}get paintSource(){return this.animatedKind==="video"?this._videoEl:this._frameCanvas}attachSprite(e,t){this._sprite=e,this._onNewFrame=t??null;let r=document.createElement("canvas");r.width=e.frameWidth,r.height=e.canvas.height,this._frameCanvas=r,this._frameIndex=0,this._anchorTime=performance.now(),this._playing=e.framesLength>1,this.blitFrame(),this.invalidateGeometryCache(),this._renderNotify?.()}attachVideo(e,t){this._videoEl=e,this._onNewFrame=t??null;let r=()=>{this._frameDirty=!0,this._onNewFrame?.()};e.addEventListener("play",()=>this.startFrameWatch()),e.addEventListener("pause",r),e.addEventListener("seeked",r),e.addEventListener("ended",()=>{try{e.currentTime=0,e.pause()}catch{}}),this.invalidateGeometryCache(),this._renderNotify?.(),e.play().catch(()=>{})}tick(e){if(this.animatedKind==="video"){let s=this._videoEl;if(!s)return!1;if(this._frameDirty)return this._frameDirty=!1,this._contentVersion++,!0;let a=this._rvfcActive?!1:!s.paused&&!s.ended;return a&&this._contentVersion++,a}let t=this._sprite;if(!this._playing||!t||t.framesLength<=1)return!1;let r=!1,o=0,i=t.framesLength;for(;o<i;){let s=t.frameDelays[this._frameIndex]||t.delay||100;if(e-this._anchorTime<s)break;this._anchorTime+=s,this._frameIndex=(this._frameIndex+1)%i,r=!0,o++}return r&&(this._contentVersion++,this.blitFrame()),r}play(){if(this.animatedKind==="video"){this._videoEl?.play().catch(()=>{});return}!this._sprite||this._sprite.framesLength<=1||(this._playing=!0,this._anchorTime=performance.now())}pause(){if(this.animatedKind==="video"){this._videoEl?.pause();return}this._playing=!1}stop(){if(this.animatedKind==="video"){let e=this._videoEl;if(!e)return;try{e.currentTime=0,e.pause()}catch{}return}this._playing=!1,this._frameIndex=0,this._contentVersion++,this.blitFrame()}syncVideoToTime(e,t){if(this.animatedKind!=="video")return;let r=this._videoEl;if(!r)return;r.pause();let o=r.duration,i=Number.isFinite(o)&&o>0?Math.min(Math.max(e,0),o):Math.max(e,0);try{r.currentTime=i}catch{}t&&r.play().catch(()=>{})}get frameIndex(){return this._frameIndex}get contentVersion(){return this._contentVersion}get mediaDuration(){if(this.animatedKind==="video"){let t=this._videoEl?.duration;if(t&&Number.isFinite(t))return t;let r=Number(this.raw.duration);return Number.isFinite(r)&&r>0?r:0}let e=this._sprite;return e?e.frameDelays.reduce((t,r)=>t+(r||e.delay||100),0)/1e3:0}startFrameWatch(){let e=this._videoEl;if(!e||this._rvfcActive||typeof e.requestVideoFrameCallback!="function")return;this._rvfcActive=!0;let t=()=>{if(!(!this._rvfcActive||!this._videoEl)){if(this._videoEl.paused||this._videoEl.ended){this._rvfcActive=!1;return}this._frameDirty=!0,this._onNewFrame?.(),e.requestVideoFrameCallback(t)}};e.requestVideoFrameCallback(t)}blitFrame(){let e=this._sprite,t=this._frameCanvas;if(!e||!t)return;let r=t.getContext("2d");r&&(r.clearRect(0,0,t.width,t.height),r.drawImage(e.canvas,this._frameIndex*e.frameWidth,0,e.frameWidth,e.canvas.height,0,0,t.width,t.height))}detach(){this._playing=!1,this._rvfcActive=!1,this._frameDirty=!1;let e=this._videoEl;if(e)try{e.pause(),e.removeAttribute("src"),e.load()}catch{}this._videoEl=null,this._sprite=null,this._frameCanvas=null,this._onNewFrame=null}get dims(){return this.animatedKind==="gif"?{x:this.raw.width??this._sprite?.frameWidth??0,y:this.raw.height??this._sprite?.canvas.height??0}:{x:this.raw.width??this._videoEl?.videoWidth??0,y:this.raw.height??this._videoEl?.videoHeight??0}}},bd=(n,e,t)=>{let r=n.length/2,o=!1;for(let i=0,s=r-1;i<r;s=i++){let a=n[i*2],l=n[i*2+1],u=n[s*2],c=n[s*2+1];l>t!=c>t&&e<(u-a)*(t-l)/(c-l)+a&&(o=!o)}return o},J=class n extends ct{children=[];constructor(e,t){super(e);let r=Array.isArray(e.objects)?e.objects:[];for(let o of r){if(!o||typeof o.type!="string")continue;let i=t(o);i&&this.children.push(i)}this.syncChildMatrices()}set(e){super.set(e),this.syncChildMatrices()}setParentMatrix(e,t=1){super.setParentMatrix(e,t),this.syncChildMatrices()}setAnimationOverride(e){super.setAnimationOverride(e),this.syncChildMatrices()}syncChildMatrices(){let e=this.matrix,t=this.renderOpacity;for(let r of this.children)r.setParentMatrix(e,t)}get dims(){let e=Number(this.raw.width),t=Number(this.raw.height);return{x:Number.isFinite(e)&&e>0?e:0,y:Number.isFinite(t)&&t>0?t:0}}containsPoint(e,t,r=0){return this.visible?this.children.some(o=>o.visible&&o.containsPoint(e,t,r)):!1}get inkACoords(){let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of this.children)if(i.visible)for(let s of[i.inkACoords.tl,i.inkACoords.tr,i.inkACoords.br,i.inkACoords.bl])e=Math.min(e,s.x),t=Math.min(t,s.y),r=Math.max(r,s.x),o=Math.max(o,s.y);return Number.isFinite(e)?{tl:{x:e,y:t},tr:{x:r,y:t},br:{x:r,y:o},bl:{x:e,y:o}}:this.aCoords}childAtPoint(e,t,r=0){for(let o=this.children.length-1;o>=0;o--){let i=this.children[o];if(!(!i.visible||!i.containsPoint(e,t,r)))return i instanceof n&&!(i instanceof te)&&!(i instanceof le)?i.childAtPoint(e,t)??i:i}return null}containsDeep(e){return this.children.some(t=>t===e||t instanceof n&&t.containsDeep(e))}adoptChild(e,t=this.children.length){this.children.splice(t,0,e),this.syncChildMatrices()}removeChildRaw(e){let t=this.children.indexOf(e);t<0||(this.children.splice(t,1),e.setParentMatrix(null),this.syncChildMatrices())}moveChildRaw(e,t){let r=this.children.indexOf(e);if(r<0)return;this.children.splice(r,1);let o=Math.max(0,Math.min(t,this.children.length));this.children.splice(o,0,e),this.syncChildMatrices()}toObject(){let e=super.toObject();return e.objects=this.children.map(t=>t.toObject()),e}},te=class n extends J{_layout;_childFactory;_placedShift;get inkACoords(){return this.aCoords}selectedCells=[];cellAnchor=null;cellRange=null;hoveredBorder=null;hoveredIndicator=null;indicatorVisible=!1;borderDragging=!1;hoveredStrip=null;hoveredDragHandle=!1;hoveredRangeHandle=!1;editingCell=null;constructor(e,t){let r=Ro(e),o=Ut({...e,width:r.constructorDims.width,height:r.constructorDims.height}),i=ge({...e,width:r.width,height:r.height},o);super({...e,left:i.x,top:i.y,width:r.width,height:r.height,objects:r.children},t),this._layout=r,this._childFactory=t,this._placedShift={x:i.x-(e.left??0),y:i.y-(e.top??0)}}_rebuilding=!1;set(e){let t=["rows","cols","columnWidths","rowHeights","manualRowHeights","minCellWidth","minCellHeight","cellPadding","cellSpacing","cellData"],r=!this._rebuilding&&Object.keys(e).some(o=>t.includes(o));if(super.set(e),r){this._rebuilding=!0;try{this.rebuildTable()}finally{this._rebuilding=!1}}}toObject(){let e=super.toObject();return typeof e.left=="number"&&(e.left=e.left-this._placedShift.x),typeof e.top=="number"&&(e.top=e.top-this._placedShift.y),e}get layout(){return this._layout}get tableView(){let e=this.raw.rows??3,t=this.raw.cols??3,r=this.raw.cellSpacing??0;return{rows:e,cols:t,columnWidths:this._layout.columnWidths,rowHeights:this._layout.rowHeights,cellSpacing:r}}get cellMap(){let e=Array.isArray(this.raw.cellData)?this.raw.cellData:[];return Dt(e)}get tableAngle(){return this.raw.angle??0}get objectScale(){return{x:Math.abs(this.raw.scaleX??1),y:Math.abs(this.raw.scaleY??1)}}cellHit(e,t){let r=this.localPoint(e,t);return id(this.tableView,this.cellMap,r.x,r.y)}borderHit(e,t){let r=this.localPoint(e,t),o=this.objectScale;return Dl(this.tableView,this.cellMap,r.x,r.y,5/o.x,5/o.y)}borderOrIndicatorHit(e,t,r){let o=this.localPoint(e,t),i=this.objectScale;return sd(this.tableView,this.cellMap,o.x,o.y,{thresholdX:5/i.x,thresholdY:5/i.y,scaleX:this.raw.scaleX??1,scaleY:this.raw.scaleY??1,zoom:r})}stripHit(e,t,r=1){let o=this.localPoint(e,t);return cd(this.tableView,this.dims.x,this.dims.y,o.x,o.y,this.objectScale,r)}dragHandleHit(e,t,r=1){let o=this.localPoint(e,t);return ud(this.dims.x,this.dims.y,o.x,o.y,this.objectScale,r)}get expandedCellRange(){if(!this.selectedCells.length)return null;let e=this.cellRange??ze(this.selectedCells);return e?Nl(this.cellMap,e.r1,e.r2,e.c1,e.c2):null}get selectionBoundsRect(){let e=this.expandedCellRange;return e?Eo(this.tableView,e):null}get isFullCellSelection(){let e=this.expandedCellRange;if(!e)return!1;let t=this.tableView;return e.r1===0&&e.c1===0&&e.r2===t.rows-1&&e.c2===t.cols-1}rangeHandleHit(e,t,r=1){if(this.editingCell||!this.selectedCells.length||this.isFullCellSelection)return!1;let o=this.selectionBoundsRect;if(!o)return!1;let i=this.localPoint(e,t);return hd(o,i.x,i.y,this.objectScale,r)}static cellSelectionSink=null;setCellSelection(e,t,r){let o=this.selectedCells,i=o.length!==e.length||o.some((s,a)=>s.row!==e[a].row||s.col!==e[a].col)||this.cellAnchor?.row!==t?.row||this.cellAnchor?.col!==t?.col||this.cellRange?.r1!==r?.r1||this.cellRange?.r2!==r?.r2||this.cellRange?.c1!==r?.c1||this.cellRange?.c2!==r?.c2;this.selectedCells=e,this.cellAnchor=t,this.cellRange=r,i&&n.cellSelectionSink?.(this)}setRowSelection(e){let t=ji(this.cellMap,this.tableView.cols,e);this.setCellSelection(t,t[0]??null,ze(t))}setColumnSelection(e){let t=$i(this.cellMap,this.tableView.rows,e);this.setCellSelection(t,t[0]??null,ze(t))}clearCellSelection(){let e=this.selectedCells.length>0;this.selectedCells=[],this.cellAnchor=null,this.cellRange=null,e&&n.cellSelectionSink?.(this)}get hasCellSelection(){return this.selectedCells.length>0}clearCellInteractionState(){this.clearCellSelection(),this.clearHoverState()}clearHoverState(){this.hoveredBorder=null,this.hoveredIndicator=null,this.indicatorVisible=!1,this.hoveredStrip=null,this.hoveredDragHandle=!1,this.hoveredRangeHandle=!1}getRowMinHeight(e){let t=this.raw.minCellHeight??40;return Math.max(t,this._layout.rowTextFloors[e]??0)}cellBounds(e,t){let r=we(this.cellMap,e,t);if(r?.isMerged)return null;let o=this.tableView;if(e<0||t<0||e>=o.rows||t>=o.cols)return null;let i=r?.colspan??1,s=r?.rowspan??1;return Eo(o,{r1:e,r2:e+s-1,c1:t,c2:t+i-1})}cellSceneCenter(e,t){let r=this.cellBounds(e,t);return r?Q(this.matrix,r.left+r.width/2,r.top+r.height/2):null}rebuildTable(){let e=this.raw.reflowOriginX??"left",t=this.raw.reflowOriginY??"top",r=(b,g)=>({x:e==="left"?-b/2:e==="right"?b/2:0,y:t==="top"?-g/2:t==="bottom"?g/2:0}),o=this.dims.x,i=this.dims.y,s=Gn({...this.raw,width:o,height:i}),a=Q(s,r(o,i).x,r(o,i).y),l=Ro(this.raw,void 0,this.editingCell?{hideTextCell:this.editingCell}:void 0);this._layout=l;let u=[];for(let b of l.children){let g=this._childFactory(b);g&&u.push(g)}this.children.length=0,this.children.push(...u),this.set({width:l.width,height:l.height,objects:l.children,rowHeights:l.rowHeights});let c=r(l.width,l.height),h=a.x-(s[0]*c.x+s[2]*c.y),d=a.y-(s[1]*c.x+s[3]*c.y),f=ge({...this.raw,width:l.width,height:l.height},{x:h,y:d});this.set({left:f.x,top:f.y});let m=Ut({...this.raw,width:l.constructorDims.width,height:l.constructorDims.height}),p=ge({...this.raw,width:l.width,height:l.height},m);this._placedShift={x:p.x-(this.raw.left??0),y:p.y-(this.raw.top??0)}}},ae=class extends ct{_clipImageEl=null;constructor(e){super(e)}get clipImageEl(){return this._clipImageEl}set clipImageEl(e){this._clipImageEl=e,this._renderNotify?.()}get clipImageRaw(){let e=this.raw.clipImage;return!e||typeof e!="object"||typeof e.src!="string"?null:e}_clipVideoEl=null;_clipSprite=null;_clipFrameCanvas=null;_clipFrameIndex=0;_clipAnchorTime=0;_clipPlaying=!1;_clipOnNewFrame=null;clipDynamicVersion=0;get clipDynamicKind(){let e=se(this.clipImageRaw);return e===L.VIDEO?"video":e===L.GIF?"gif":null}get hasDynamicClip(){return!!this._clipVideoEl||!!this._clipFrameCanvas}get clipAnimating(){return this._clipVideoEl?!this._clipVideoEl.paused&&!this._clipVideoEl.ended:this._clipPlaying&&!!this._clipSprite&&this._clipSprite.framesLength>1}attachClipSprite(e,t){this._clipSprite=e,this._clipOnNewFrame=t??null;let r=document.createElement("canvas");r.width=e.frameWidth,r.height=e.canvas.height,this._clipFrameCanvas=r,this._clipFrameIndex=0,this._clipAnchorTime=performance.now(),this._clipPlaying=e.framesLength>1,this.clipDynamicVersion++,this.blitClipFrame(),this._renderNotify?.()}attachClipVideo(e,t){this._clipVideoEl=e,this._clipOnNewFrame=t??null;let r=()=>{this.clipDynamicVersion++,this._renderNotify?.(),this._clipOnNewFrame?.()};e.addEventListener("seeked",r),e.addEventListener("pause",r),e.addEventListener("play",r),this.clipDynamicVersion++,this._renderNotify?.(),e.play().catch(()=>{})}dynamicClipSource(){return this._clipVideoEl?this._clipVideoEl:this._clipFrameCanvas}tickDynamicClip(e){if(this._clipVideoEl){let i=this._clipVideoEl;return!i.paused&&!i.ended?(this.clipDynamicVersion++,!0):!1}if(!this._clipPlaying||!this._clipSprite||this._clipSprite.framesLength<=1)return!1;let t=!1,r=0,o=this._clipSprite.framesLength;for(;r<o;){let i=this._clipSprite.frameDelays[this._clipFrameIndex]||this._clipSprite.delay||100;if(e-this._clipAnchorTime<i)break;this._clipAnchorTime+=i,this._clipFrameIndex=(this._clipFrameIndex+1)%o,t=!0,r++}return t&&(this.clipDynamicVersion=this._clipFrameIndex,this.blitClipFrame()),t}blitClipFrame(){let e=this._clipSprite,t=this._clipFrameCanvas;if(!e||!t)return;let r=t.getContext("2d");r&&(r.clearRect(0,0,t.width,t.height),r.drawImage(e.canvas,this._clipFrameIndex*e.frameWidth,0,e.frameWidth,e.canvas.height,0,0,t.width,t.height))}detachDynamicClip(){this._clipPlaying=!1;try{this._clipVideoEl?.pause()}catch{}this._clipVideoEl=null,this._clipSprite=null,this._clipFrameCanvas=null,this._renderNotify?.()}get clipMediaDuration(){if(this.clipDynamicKind!=="video")return 0;let e=this._clipVideoEl?.duration;if(e&&Number.isFinite(e))return e;let t=Number(this.clipImageRaw?.duration);return Number.isFinite(t)&&t>0?t:0}playClipMedia(){this.clipDynamicKind==="video"&&this._clipVideoEl?.play().catch(()=>{})}pauseClipMedia(){this.clipDynamicKind==="video"&&this._clipVideoEl?.pause()}syncClipMediaToTime(e,t){if(this.clipDynamicKind!=="video")return;let r=this._clipVideoEl;if(!r)return;r.pause();let o=r.duration,i=Number.isFinite(o)&&o>0?Math.min(Math.max(e,0),o):Math.max(e,0);try{r.currentTime=i}catch{}t&&r.play().catch(()=>{})}},le=class extends J{constructor(e,t){super(e,t);let r=this.layoutParams,o=er(e.layoutConfig),i=!!o&&o.pieces.length===this.maskChildren.length;o&&!i&&this.reconcileIncompleteLayout(o),this.set({width:r.width,height:r.height}),this.reconcileOverlappingChildren()}get inkACoords(){return this.aCoords}reconcileIncompleteLayout(e){let t=this.maskChildren;if(t.length>0&&e.pieces.length>t.length){let r=e.pieces.slice(0,t.length),o=1,i=1;for(let s of r)o=Math.max(o,s.col+(s.colSpan??1)),i=Math.max(i,s.row+(s.rowSpan??1));e.cols=o,e.rows=i,e.pieces=r,this.set({layoutConfig:{rows:i,cols:o,pieces:r}})}this.relayoutFromConfig(e,this.layoutParams)}reconcileOverlappingChildren(){let{hGap:e,vGap:t}=this.layoutParams,r=this.layoutParams.width/2,o=this.layoutParams.height/2,i=.5,s=this.maskChildren,a=new Map,l=c=>{let h=c.raw,d=h.width??0,f=h.height??0;return{x0:h.left-d/2,x1:h.left+d/2,y0:h.top-f/2,y1:h.top+f/2}};for(let c=0;c<s.length;c++)for(let h=c+1;h<s.length;h++){let d=l(s[c]),f=l(s[h]),m=Math.min(d.x1,f.x1)-Math.max(d.x0,f.x0),p=Math.min(d.y1,f.y1)-Math.max(d.y0,f.y0);if(!(m>i&&p>i))continue;let b=d.x0<=f.x0?s[c]:s[h],g=b===s[c]?s[h]:s[c],x=l(b),S=l(g);if(x.x1>S.x0+i){if(Math.abs(x.x1-r)<i&&S.x0<r-i){let P=a.get(b)??{};P.right=S.x0-e,a.set(b,P)}else if(Math.abs(S.x0+r)<i&&x.x1>-r+i){let P=a.get(g)??{};P.left=x.x1+e,a.set(g,P)}}let w=d.y0<=f.y0?s[c]:s[h],y=w===s[c]?s[h]:s[c],v=l(w),R=l(y);if(v.y1>R.y0+i){if(Math.abs(v.y1-o)<i&&R.y0<o-i){let P=a.get(w)??{};P.bottom=R.y0-t,a.set(w,P)}else if(Math.abs(R.y0+o)<i&&v.y1>-o+i){let P=a.get(y)??{};P.top=v.y1+t,a.set(y,P)}}}if(!a.size)return;let u=[];for(let[c,h]of a){let d=l(c),f=h.left??d.x0,m=h.right??d.x1,p=h.top??d.y0,b=h.bottom??d.y1;if(!(m-f>i)||!(b-p>i))continue;let g={left:(f+m)/2,width:m-f,top:(p+b)/2,height:b-p};c.set(g),u.push(`${String(c.raw.id)}→${Math.round(g.left)},${Math.round(g.top)},${Math.round(g.width)}×${Math.round(g.height)}`)}u.length&&console.info("[PuzzleNode] 装载期叠压自愈(外缘钉签名,批次 307 存量损伤):",u.join("; "))}get layoutParams(){return{width:this.raw.layoutWidth??600,height:this.raw.layoutHeight??600,hGap:this.raw.hGap??12,vGap:this.raw.vGap??12,groupPadding:this.raw.groupPadding??0}}get maskChildren(){return this.children.filter(e=>e instanceof ae)}containsPoint(e,t,r=0){return super.containsPoint(e,t,r)?!0:this.visible?ct.prototype.containsPoint.call(this,e,t,r):!1}applyMaskParams(e){let t={};for(let[r,o]of Object.entries(e))if(o!==void 0){t[r]=o;for(let i of this.maskChildren)i.set({[r]:o})}Object.keys(t).length&&this.set(t)}updateGapParams(e){let t={};if(typeof e.hGap=="number"&&(t.hGap=e.hGap),typeof e.vGap=="number"&&(t.vGap=e.vGap),typeof e.groupPadding=="number"&&(t.groupPadding=e.groupPadding),!Object.keys(t).length)return;this.set(t);let r=er(this.raw.layoutConfig);r&&this.relayoutFromConfig(r,this.layoutParams)}updateLayout(e){let t=er(this.raw.layoutConfig);if(!t||!t.pieces.length){console.warn("[PuzzleNode] layoutConfig is invalid, skipping layout update");return}let r={...this.layoutParams};typeof e.width=="number"&&e.width>0&&(r.width=e.width),typeof e.height=="number"&&e.height>0&&(r.height=e.height),typeof e.hGap=="number"&&(r.hGap=e.hGap),typeof e.vGap=="number"&&(r.vGap=e.vGap),typeof e.groupPadding=="number"&&(r.groupPadding=e.groupPadding),this.set({hGap:r.hGap,vGap:r.vGap,groupPadding:r.groupPadding}),this.relayoutFromConfig(t,r),this.set({width:r.width,height:r.height})}editingMask=null;get editingMaskIndex(){return this.editingMask?this.maskChildren.indexOf(this.editingMask):-1}maskEdgeOnOuterBorder(e,t){let r=this.layoutParams,o=Math.max(0,r.width-r.groupPadding*2),i=Math.max(0,r.height-r.groupPadding*2),s=o/2,a=i/2,l=e.raw.left??0,u=e.raw.top??0,c=e.raw.width??0,h=e.raw.height??0,d=.5;return t==="left"?l-c/2<=-s+d:t==="right"?l+c/2>=s-d:t==="top"?u-h/2<=-a+d:u+h/2>=a-d}exitMaskEditing(){this.editingMask=null}removeCol(e){let t=er(this.raw.layoutConfig);if(!t||t.pieces.length!==this.maskChildren.length)return!1;let r=qh(t.pieces,t.cols,e);return r?(t.cols-=1,this.applyPuzzleRemoval(t,r.removed)):!1}removeRow(e){let t=er(this.raw.layoutConfig);if(!t||t.pieces.length!==this.maskChildren.length)return!1;let r=Kh(t.pieces,t.rows,e);return r?(t.rows-=1,this.applyPuzzleRemoval(t,r.removed)):!1}removePiece(e){let t=er(this.raw.layoutConfig);if(!t||t.pieces.length!==this.maskChildren.length)return!1;let r=Qh(t.pieces,e);return r?this.applyPuzzleRemoval(t,r.removed):!1}applyPuzzleRemoval(e,t){if(!e)return!1;let r=new Set(t),o=this.children.filter(s=>!(s instanceof ae&&r.has(this.maskChildren.indexOf(s)))),i=o.filter(s=>s instanceof ae).map(s=>s.toObject());return this.children.length=0,this.children.push(...o),this.set({layoutConfig:{rows:e.rows,cols:e.cols,pieces:e.pieces},objects:i}),this.relayoutFromConfig(e,this.layoutParams),!0}toObject(){let e=super.toObject();return e.objects=this.children.map(t=>t.toObject()),e}relayoutFromConfig(e,t){let r=Rl(e,t);this.maskChildren.forEach((o,i)=>{let s=r[i];if(!s)return;let a=o.raw.width||s.w,l=o.raw.height||s.h;o.set({left:s.cx,top:s.cy,width:s.w,height:s.h});let u=o.clipImageRaw;if(u){let c=u.width||0,h=u.height||0;if(c&&h){let d=Math.max(a/c,l/h),f=Math.max(s.w/c,s.h/h),m=u.scaleX??1,p=d?m/d:1,b=f*(p||1);o.set({clipImage:{...u,scaleX:b,scaleY:b}})}typeof u.clipX=="number"&&o.set({clipImage:{...o.raw.clipImage,clipX:(u.clipX||0)*(a?s.w/a:1)}}),typeof u.clipY=="number"&&o.set({clipImage:{...o.raw.clipImage,clipY:(u.clipY||0)*(l?s.h/l:1)}})}}),this.set({layoutWidth:t.width,layoutHeight:t.height})}},ts=n=>{if(!dt.has(se(n)))return null;let e=Number(n.cropX)||0,t=Number(n.cropY)||0;if(!(typeof n.cropX=="number"||typeof n.cropY=="number"||n.cropSizeMode==="visible"||e>0||t>0)||typeof n.width!="number"||typeof n.height!="number")return null;let o=n.cropSizeMode==="visible";return{sx:e,sy:t,sw:Math.max(0,o?n.width:n.width-e),sh:Math.max(0,o?n.height:n.height-t)}},Ct=n=>{if(!n||typeof n.type!="string")return null;let e=se(n);return e===L.TABLE?new te(n,Ct):gi.has(e)?new le(n,Ct):ot.has(e)&&typeof n.src=="string"?new ae(n):e===L.GROUP?new J(n,Ct):xi.has(e)&&typeof n.src=="string"?new ie(n,"gif"):yi.has(e)&&typeof n.src=="string"?new ie(n,"video"):dt.has(e)&&typeof n.src=="string"?new ct(n):$n.has(e)?new ct(n):an.has(e)&&typeof n.text=="string"?new ye(n):e===L.PATH?new Nr(n):ft.has(e)?new Lr(n):Un.has(e)?new yn(n):null},Yl=n=>{let e=[],t={};for(let r of n){let o=Ct(r);o?e.push(o):r&&typeof r.type=="string"&&(t[r.type]=(t[r.type]||0)+1)}return{nodes:e,skippedTypes:t}},Je=(n,e)=>new Promise((t,r)=>{let o=new Image;e!==null&&(o.crossOrigin=e||"anonymous"),o.onload=()=>t(o),o.onerror=()=>r(new Error(`[engine] image load failed: ${n.slice(0,80)}`)),o.src=n}),ko=n=>{if(n instanceof J||n instanceof ae||n instanceof ie||n.isImageType)return null;let e=n.raw.mask;return!e||e.disabled===!0||typeof e.src!="string"||!e.src?null:e.src};var ux=n=>typeof n!="string"||!n||/^cmyk\(/i.test(n)?null:n,Ft=n=>{if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.r!="number"||typeof e.g!="number"||typeof e.b!="number")return null;let t=r=>Math.max(0,Math.min(255,Math.round(r)));return`rgba(${t(e.r)}, ${t(e.g)}, ${t(e.b)}, 1)`}return ux(n)},ns=n=>n?.offsetEnable?{x:Number(n.offsetX)||0,y:Number(n.offsetY)||0}:{x:0,y:0},vn=n=>{if(typeof n!="string")return;let e=n.trim().toLowerCase().replace(/\s*\([^)]*\)\s*$/,"").replace(/\s+/g,"-");if(!(!e||e==="normal"||e==="source-over")){if(e==="linear-dodge")return"lighter";if(/^[a-z-]+$/.test(e))return e}},Mt=(n,e={})=>{if(!n||typeof n!="object"||Array.isArray(n))return null;let t=n,r=c=>{if(!c||typeof c!="object")return!1;let h=c;return h.enabled!==!1&&h.showInDialog!==!1},o=[];if(Array.isArray(t.dropShadow))for(let c of t.dropShadow){if(!r(c))continue;let h=Ft(c?.fill)??Ft(c?.color)??"rgba(0,0,0,0.5)",d=Number(c?.blur)||0,f=Number(c?.offsetX)||0,m=Number(c?.offsetY)||0;!d&&!f&&!m||o.push({color:h,rgba:ee(h),blur:d,offsetX:f,offsetY:m,blendMode:vn(c?.blendMode)})}let i=[];if(Array.isArray(t.innerShadow))for(let c of t.innerShadow){if(!r(c))continue;let h=Ft(c?.fill)??Ft(c?.color)??"rgba(0,0,0,0.5)",d=Number(c?.blur)||0,f=Number(c?.offsetX)||0,m=Number(c?.offsetY)||0;!d&&!f&&!m||i.push({color:h,rgba:ee(h),blur:d,offsetX:f,offsetY:m,blendMode:vn(c?.blendMode)})}let s=[];if(Array.isArray(t.solidFill))for(let c of t.solidFill){if(!r(c))continue;let h=Number(c?.fillType)||0;if(h===1){if(!c?.fill||typeof c.fill!="object")continue;let f=Yn(c.fill);if(!f)continue;s.push({kind:"gradient",decl:f,offset:ns(c),blendMode:vn(c?.blendMode)});continue}if(h===2){let f=pr(c?.fill);if(!f)continue;s.push({kind:"pattern",decl:f,offset:ns(c),blendMode:vn(c?.blendMode)});continue}if(h!==0)continue;let d=Ft(c?.fill)??Ft(c?.color);d&&s.push({kind:"solid",color:d,rgba:ee(d),offset:ns(c),blendMode:vn(c?.blendMode)})}let a=[];if(Array.isArray(t.stroke))for(let c of t.stroke){if(!r(c))continue;let h=c?.size&&typeof c.size=="object"?Number(c.size.value):0,d=e.text?h:Number(c?.strokeWidth)||h||0;if(!d)continue;let f=c?.fill&&typeof c.fill=="object"&&!Array.isArray(c.fill)?Yn(c.fill):null,m=Ft(c?.fill)??Ft(c?.color)??"#666666",p=c?.position||c?.strokeAlignment||(e.text?"center":"outside");a.push({kind:f?"gradient":"solid",color:m,rgba:ee(m),width:d,alignment:p,offset:ns(c),blendMode:vn(c?.blendMode),...f?{decl:f}:{}})}let l,u=n.bevel;if(u&&typeof u=="object"&&!Array.isArray(u)){let c=u;if(r(c)){let h=Number(n.scale)||1,d=c.size&&typeof c.size=="object"?Number(c.size.value):Number(c.size),f=(Number.isFinite(d)?d:0)/(h>0?h:1);if(f>0){let m=typeof c.style=="string"?c.style.toLowerCase():"",p=m.includes("outer")?"outer":m.includes("pillow")?"pillow":m.includes("emboss")?"emboss":"inner",b=typeof c.technique=="string"&&c.technique.toLowerCase().includes("chisel")&&!c.technique.toLowerCase().includes("soft")?"hard":"smooth",g=Ft(c.highlightColor)??"rgba(255, 255, 255, 1)",x=Ft(c.shadowColor)??"rgba(0, 0, 0, 1)";l={style:p,technique:b,sizePx:f,strength:Math.min(4,Math.max(0,Number(c.strength??c.depth)||1)),angleDeg:Number.isFinite(Number(c.angle))?Number(c.angle):120,altitudeDeg:Math.min(90,Math.max(0,Number.isFinite(Number(c.altitude))?Number(c.altitude):30)),directionDown:typeof c.direction=="string"&&c.direction.toLowerCase()==="down",highlight:{color:g,rgba:ee(g),opacity:Math.min(1,Math.max(0,Number(c.highlightOpacity)||.5)),blendMode:vn(c.highlightBlendMode)},shadow:{color:x,rgba:ee(x),opacity:Math.min(1,Math.max(0,Number(c.shadowOpacity)||.5)),blendMode:vn(c.shadowBlendMode)}}}}}return o.length===0&&i.length===0&&s.length===0&&a.length===0&&!l?null:{dropShadows:o,innerShadows:i,solidFills:s,strokes:a,...l?{bevel:l}:{}}},hx=n=>{let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return`${n.length}:${(e>>>0).toString(36)}`},_r=n=>{if(!n)return[];let e=[];for(let t of n.solidFills)t.kind==="pattern"&&!e.includes(t.decl.src)&&e.push(t.decl.src);return e},wn=n=>{let e=c=>String(Math.round(c*1e4)/1e4),t=c=>c.map(e).join(","),r=c=>c?`~${c}`:"",o=n.dropShadows.map(c=>`${t(c.rgba)}:${e(c.blur)}:${e(c.offsetX)}:${e(c.offsetY)}${r(c.blendMode)}`).join(";"),i=n.innerShadows.map(c=>`${t(c.rgba)}:${e(c.blur)}:${e(c.offsetX)}:${e(c.offsetY)}${r(c.blendMode)}`).join(";"),s=c=>{let h=`@${e(c.offset.x)},${e(c.offset.y)}${r(c.blendMode)}`;if(c.kind==="solid")return t(c.rgba)+h;if(c.kind==="pattern"){let p=c.decl,b=p.patternTransform?p.patternTransform.map(e).join(","):"-";return`p:${hx(p.src)}:${p.repeat}@${e(p.offsetX)},${e(p.offsetY)}:${b}${h}`}let d=c.decl,f=d.stops.map(p=>`${e(p.offset)}@${p.color.map(e).join(",")}`).join(","),m=d.gradientTransform?d.gradientTransform.map(e).join(","):"-";return`g${d.kind[0]}:${e(d.x1)},${e(d.y1)},${e(d.x2)},${e(d.y2)},${e(d.r1)},${e(d.r2)},${d.gradientUnits},${m};${f}${h}`},a=n.solidFills.map(s).join(";"),l=n.strokes.map(c=>`${t(c.rgba)}:${e(c.width)}:${c.alignment}@${e(c.offset.x)},${e(c.offset.y)}${r(c.blendMode)}${c.decl?`~g${pi(c.decl)}`:""}`).join(";"),u=n.bevel?`${n.bevel.style}/${n.bevel.technique}:${e(n.bevel.sizePx)}:${e(n.bevel.strength)}:${e(n.bevel.angleDeg)}:${e(n.bevel.altitudeDeg)}:${n.bevel.directionDown?"d":"u"}:${t(n.bevel.highlight.rgba)}@${e(n.bevel.highlight.opacity)}${r(n.bevel.highlight.blendMode)}:${t(n.bevel.shadow.rgba)}@${e(n.bevel.shadow.opacity)}${r(n.bevel.shadow.blendMode)}`:"";return`psd|${o}|${i}|${a}|${l}|${u}`};var dx=512,fx=new Set([L.QRCODE,L.BARCODE,L.ECHART,L.FABRIC_ECHART]),vd=n=>{let e=Mt(n.raw.effects);if(!e)return null;let t=e.dropShadows,r=e.strokes;return!t.length&&!r.length?null:{shadows:t,strokes:r,key:wn(e)}},mx=n=>n?`${n.sx},${n.sy},${n.sw},${n.sh}`:"none",Ul=new WeakMap,Sd=n=>Math.max(1,Math.min(dx,Math.floor(n))),px=(n,e,t,r,o)=>{let i=vd(n);if(!i)return;let s=n.imageEl;if(!s)return;let a=n.dims,l=null;if(i.shadows.length){let h=Hi(n,i.shadows,s,1,n.cropRect);if(!h)throw new Error("fx mask: shadow bake unavailable");let d=h.canvas.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("fx mask: shadow ctx unavailable");l={data:d.getImageData(0,0,h.w,h.h).data,w:h.w,h:h.h}}let u=[];if(i.strokes.length){for(let h of bn(n,i.strokes,s,!0,1,n.cropRect)){let d=h.canvas.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("fx mask: stroke ctx unavailable");u.push({data:d.getImageData(0,0,h.w,h.h).data,w:h.w,h:h.h,dx:h.dx,dy:h.dy})}if(!u.length)throw new Error("fx mask: stroke bake unavailable")}let c=n.matrix;for(let h=0;h<r;h++)for(let d=0;d<t;d++){if(e[h*t+d])continue;let f=((d+.5)/t-.5)*a.x,m=((h+.5)/r-.5)*a.y;if(l){let p=Math.round(c[0]*f+c[2]*m+l.w/2),b=Math.round(c[1]*f+c[3]*m+l.h/2);if(p>=0&&b>=0&&p<l.w&&b<l.h&&l.data[(b*l.w+p)*4+3]>o){e[h*t+d]=1;continue}}for(let p of u){let b=Math.round(f-p.dx+p.w/2),g=Math.round(m-p.dy+p.h/2);if(b>=0&&g>=0&&b<p.w&&g<p.h&&p.data[(g*p.w+b)*4+3]>o){e[h*t+d]=1;break}}}},bx=n=>{let e=n.imageEl,t=n.dims,r=n.cropRect,o=r?r.sw:e?.naturalWidth||0,i=r?r.sh:e?.naturalHeight||0;if(!e||!(t.x>0)||!(t.y>0)||!(o>0)||!(i>0))return{mask:new Uint8Array(0),maskW:0,maskH:0};let s=Sd(t.x),a=Sd(t.y),l=document.createElement("canvas");l.width=s,l.height=a;let u=new Uint8Array(0);try{let c=l.getContext("2d",{willReadFrequently:!0});if(c){c.drawImage(e,r?r.sx:0,r?r.sy:0,o,i,0,0,s,a);let h=Math.min(255,Ji/Math.max(n.renderOpacity,1/255)),{data:d}=c.getImageData(0,0,s,a);u=new Uint8Array(s*a);for(let f=0;f<u.length;f++)d[f*4+3]>h&&(u[f]=1);px(n,u,s,a,h)}}catch{u=new Uint8Array(0)}finally{l.width=0,l.height=0}return{mask:u,maskW:u.length>0?s:0,maskH:u.length>0?a:0}},gx=n=>{let e=`${n.dims.x},${n.dims.y}|${mx(n.cropRect)}|${n.renderOpacity}`,t=vd(n);if(!t)return e;let r=n.matrix,o=i=>Math.round(i*1e3)/1e3;return`${e}|${t.key}|${o(r[0])},${o(r[1])},${o(r[2])},${o(r[3])}`},xx=n=>{let e=gx(n),t=Ul.get(n);if(t&&t.stamp===e&&t.element===n.imageEl)return t.rec;let r=bx(n);return Ul.set(n,{element:n.imageEl,stamp:e,rec:r}),r},yx=(n,e,t)=>{let r=xx(n);if(r.maskW===0||r.maskH===0)return!1;let o=n.dims,i=n.localPoint(e,t),s=i.x+o.x/2,a=i.y+o.y/2;if(s<0||a<0||s>=o.x||a>=o.y)return!0;let l=Math.min(r.maskW-1,Math.floor(s/o.x*r.maskW)),u=Math.min(r.maskH-1,Math.floor(a/o.y*r.maskH));return r.mask[u*r.maskW+l]===0},Sx=(n,e,t,r)=>{for(let o of n.children)if(!(!o.visible||!o.containsPoint(e,t,r.strokeBandOf?.(o)??0))&&!rs(o,e,t,r))return!0;return!1},rs=(n,e,t,r)=>{if(n instanceof te)return!1;let o=typeof n.raw.globalCompositeOperation=="string"?n.raw.globalCompositeOperation:"";return o==="multiply"&&!r.selection.includes(n)||o&&o!=="source-over"&&n.typeKey!==L.REFERENCELINE&&r.hasSelectableBelow()?!0:n instanceof le||n instanceof ae||n instanceof ie||n.isTextType||n.isLineType?!1:n instanceof J?!Sx(n,e,t,r):!n.isImageType||fx.has(n.typeKey)||typeof n.raw.name=="string"&&n.raw.name.toLowerCase()==="qrcode"||!dt.has(n.typeKey)?!1:yx(n,e,t)},vx=n=>{Ul.delete(n)},Dr=(n,e,t,r)=>{for(let o=n.children.length-1;o>=0;o--){let i=n.children[o];if(!(!i.visible||i.raw.evented===!1||!i.containsPoint(e,t)||rs(i,e,t,{selection:r,hasSelectableBelow:()=>{for(let a=o-1;a>=0;a--){let l=n.children[a];if(l.visible&&l.raw.evented!==!1&&l.containsPoint(e,t))return!0}return!1}})))return i instanceof J&&!(i instanceof te)&&!(i instanceof le)?Dr(i,e,t,r)??i:i}return null};import wx from"rbush";var $l=0,Tx=()=>($l=($l+1)%4294967295,`tx-${Date.now().toString(36)}-${$l.toString(36)}`),Ao=class{events=new Hn;_nodes=[];_index=new wx;_indexDirty=!1;_selection=[];_editingNode=null;_editingTextSnapshot="";_editingBeforeObject=null;_editingBitmapSnapshot=null;_editingTransient=!1;editSelection={start:0,end:0};skippedTypes={};get nodes(){return this._nodes}get selection(){return this._selection}get editingNode(){return this._editingNode}_selectionFrame=null;get selectionFrame(){return this._selectionFrame}setSelectionFrame(e){this._selectionFrame=e}get activeObject(){return this._selection[0]??null}_activeGroupChild=null;get activeGroupChild(){return this._activeGroupChild}setActiveGroupChild(e){let t=this._selection.length===1?this._selection[0]:null,r=e&&t instanceof J&&t.containsDeep(e)?e:null;if(this._activeGroupChild===r)return;let o=this._activeGroupChild;this._activeGroupChild=r,o&&this.events.fire("group:child-deactivated"),r&&this.events.fire("group:child-activated",r,t)}_groupEditingGroup=null;get groupEditing(){return this._groupEditingGroup!==null}get groupEditingGroup(){return this._groupEditingGroup}setGroupEditing(e,t){if(!e){this._groupEditingGroup=null;return}let r=t??(this._selection.length===1&&this._selection[0]instanceof J?this._selection[0]:null);this._groupEditingGroup=r&&!(r instanceof te)&&!(r instanceof le)?r:null}_hovered=null;get hovered(){return this._hovered}setHovered(e){let r=e!==null&&this._nodes.some(o=>o===e||o instanceof J&&o.containsDeep(e))?e:null;this._hovered!==r&&(this._hovered=r)}_seamHover=null;get seamHover(){return this._seamHover}setSeamHover(e){let t=this._seamHover,r=e&&this._nodes.includes(e.puzzle)&&e.puzzle.maskChildren.includes(e.mask)?e:null;t?.puzzle===r?.puzzle&&t?.mask===r?.mask&&t?.handle===r?.handle||(this._seamHover=r)}loadObjects(e){let{nodes:t,skippedTypes:r}=Yl(e);this._nodes=t,this.skippedTypes=r;for(let o of t)this.attachRenderTracking(o);this.clearSelection(),this.rebuildIndex(),this.bumpStructure()}add(e){this._nodes.push(e),this.attachRenderTracking(e),this.markIndexDirty(),this.events.fire("object:added",e),this.bumpStructure()}remove(e){let t=this._nodes.indexOf(e);t>=0&&this._nodes.splice(t,1),this._selection=this._selection.filter(r=>r!==e),this._selectionFrame=null,this._activeGroupChild&&this.setActiveGroupChild(this._activeGroupChild),this._hovered&&this.setHovered(this._hovered),this.markIndexDirty(),this.events.fire("object:removed",e),this.bumpStructure()}insertAt(e,...t){let r=Math.max(0,Math.min(e,this._nodes.length));this._nodes.splice(r,0,...t);for(let o of t)this.attachRenderTracking(o);this.markIndexDirty();for(let o of t)this.events.fire("object:added",o);return this.bumpStructure(),this._nodes.length}moveNodeTo(e,t){let r=this._nodes.indexOf(e);if(r<0)return;this._nodes.splice(r,1);let o=Math.max(0,Math.min(t,this._nodes.length));this._nodes.splice(o,0,e),this.bumpStructure()}_structureVersion=1;_renderDirty=new Set;get structureVersion(){return this._structureVersion}get renderDirty(){return this._renderDirty}drainRenderDirty(){this._renderDirty.clear()}bumpStructure(){this._structureVersion++,this._renderDirty.clear()}attachRenderTracking(e){if(e._renderNotify=()=>{this._renderDirty.add(e)},e instanceof J)for(let t of e.children)this.attachRenderTracking(t)}findNodeDeep(e){let t=(r,o)=>{for(let i=0;i<r.length;i++){let s=r[i];if(s.id===e)return{node:s,parent:o,index:i};if(s instanceof J&&!(s instanceof te)){let a=t(s.children,s);if(a)return a}}return null};return t(this._nodes,null)}setProps(e,t,r={}){let o="visible"in t;if(o&&t.visible===e.raw.visible&&Object.keys(t).length===1)return;let i=e.visible;e.set(t);let s=o&&e.visible!==i;s&&this.bumpStructure(),o&&!s&&Object.keys(t).length===1||this.markIndexDirty()}rebuildIndex(){let e=[];for(let t of this._nodes){if(!t.visible)continue;let r=t.bounds,o=this.strokeHitBand(t);e.push({minX:r.left-o,minY:r.top-o,maxX:r.right+o,maxY:r.bottom+o,node:t})}this._index.clear(),this._index.load(e),this._indexDirty=!1}commitGeometry(){this._indexDirty&&this.rebuildIndex()}refreshHitIndex(){this.rebuildIndex()}markIndexDirty(){this._indexDirty=!0}_hitZoom=1;setViewportZoom(e){!(e>0)||e===this._hitZoom||(this._hitZoom=e,this.rebuildIndex())}hitBandScene(){return zl/this._hitZoom}strokeHitBand(e){return yd(e)?Math.max(Number(e.raw.padding)||0,zl)/this._hitZoom:0}findTarget(e,t){this._indexDirty&&this.rebuildIndex();let r=this._index.search({minX:e,minY:t,maxX:e,maxY:t}),o=new Map;this._nodes.forEach((i,s)=>o.set(i,s)),r.sort((i,s)=>(o.get(s.node)??-1)-(o.get(i.node)??-1));for(let i=0;i<r.length;i++){let s=r[i].node,a=this.hitBandScene();if(!(!s.visible||s.raw.evented===!1||!s.containsPoint(e,t,a))&&!rs(s,e,t,this.alphaHitContext(r,i,e,t)))return s}return null}alphaHitContext(e,t,r,o){let i=null,s=this.hitBandScene();return{selection:this._selection,strokeBandOf:()=>s,hasSelectableBelow:()=>(i===null&&(i=e.slice(t+1).some(a=>a.node.visible&&a.node.raw.evented!==!1&&a.node.containsPoint(r,o,s))),i)}}objectsIntersectingRect(e,t,r,o){this._indexDirty&&this.rebuildIndex();let i={minX:Math.min(e,r),minY:Math.min(t,o),maxX:Math.max(e,r),maxY:Math.max(t,o)},s=new Set(this._index.search(i).map(a=>a.node));return this._nodes.filter(a=>a.visible&&s.has(a)&&a.bounds.left<=i.maxX&&i.minX<=a.bounds.right&&a.bounds.top<=i.maxY&&i.minY<=a.bounds.bottom&&!a.syntheticOwner&&!Ir.has(String(a.raw.id??""))&&!Ze(a))}setSelection(e,t="create"){this._selection=e.filter(r=>this._nodes.includes(r)),this._selectionFrame=null,this._groupEditingGroup&&!(this._selection.length===1&&this._selection[0]===this._groupEditingGroup)&&(this._groupEditingGroup=null),this._hovered=null,this._selection.length===0?this.events.fire("selection:cleared"):t==="create"?this.events.fire("selection:created",[...this._selection]):this.events.fire("selection:updated",[...this._selection]),this._activeGroupChild&&this.setActiveGroupChild(this._activeGroupChild)}clearSelection(){this._activeGroupChild&&this.setActiveGroupChild(null),this._groupEditingGroup=null,this._hovered=null,this._selection.length!==0&&(this._selection=[],this._selectionFrame=null,this.events.fire("selection:cleared"))}_transformGestureAt=-1/0;get transformGestureAt(){return this._transformGestureAt}applyTransform(e,t,r,o){if(e.length){(r==="moving"||r==="scaling"||r==="rotating")&&(this._transformGestureAt=performance.now());for(let i of e)this.setProps(i,t(i),{deferIndexRebuild:!0});if(this.markIndexDirty(),r==="modified"){this.commitGeometry();let i=o?.before,s=i||o?.action||o?.transactionId?{action:o?.action,before:i?e.map(a=>i.get(a)).filter(a=>!!a):void 0,transactionId:o?.transactionId}:void 0;this.fireObjectModified([...e],s)}else this.events.fire(`object:${r}`,e[0])}}fireObjectModified(e,t){let r=t?.transactionId??Tx();this.events.fire("object:modified",e,{...t,transactionId:r})}enterEditing(e,t={}){let r=this._nodes.find(i=>i===e||i instanceof J&&i.containsDeep(e));if(!r||this._editingNode===e)return;this._editingNode&&this.exitEditing(),this._editingNode=e,this._editingTransient=t.transient===!0,this._editingTextSnapshot=e.raw.text??"",this._editingBitmapSnapshot=typeof e.raw.renderSrc=="string"?{renderSrc:e.raw.renderSrc,renderRect:e.raw.renderRect}:null,this._editingBeforeObject=e.toObject();let o=this._editingTextSnapshot.length;this.editSelection.start=this.editSelection.end=o,t.transient||this.setSelection([r],"update"),this.events.fire("text:editing:entered",e)}exitEditing(){let e=this._editingNode;if(!e)return;let t=this._editingTransient;if(this._editingNode=null,this._editingTransient=!1,this.rebuildIndex(),this.events.fire("text:editing:exited",e),t){this._editingTextSnapshot="",this._editingBeforeObject=null,this._editingBitmapSnapshot=null;return}let r=e.raw.text??"";r!==this._editingTextSnapshot?(this.events.fire("text:editing:committed",e,this._editingTextSnapshot,r),this.fireObjectModified([e],{before:this._editingBeforeObject?[this._editingBeforeObject]:void 0})):this._editingBitmapSnapshot&&(e.raw.renderSrc=this._editingBitmapSnapshot.renderSrc,e.raw.renderRect=this._editingBitmapSnapshot.renderRect,e.markRenderDirty()),this._editingTextSnapshot="",this._editingBeforeObject=null,this._editingBitmapSnapshot=null}updateEditingText(e,t,r){let o=this._editingNode;o&&(o.set({text:e}),this.syncEditSelection(t,r),this.markIndexDirty(),this.events.fire("text:changed",o))}updateEditingSelection(e,t){this._editingNode&&this.syncEditSelection(e,t)}syncEditSelection(e,t){let r=this._editingNode.textLayout.graphemeCodeUnitOffsets;this.editSelection.start=wd(r,e),this.editSelection.end=wd(r,t)}toObjects(){return this._nodes.filter(e=>!e.syntheticOwner).map(e=>e.toObject())}},wd=(n,e)=>{let t=0,r=n.length-1;for(;t<r;){let o=t+r+1>>1;n[o]<=e?t=o:r=o-1}return t};var os=n=>typeof n!="string"||n.length===0?!1:/^data:image\/svg\+xml/i.test(n)?!0:/\.svg(?:[?#]|$)/i.test(n),Td=(n,e,t,r=4096)=>{let o=Math.max(n.w,n.h);if(!(o>0)||!(t>=1))return{factor:1,needsRaster:!1};let i=Math.max(e.w/n.w,e.h/n.h);if(!(i>0)||!Number.isFinite(i))return{factor:1,needsRaster:!1};let s=1;for(;s*2*o<=r;)s*=2;let a=1;for(;a<i-1e-9&&a<s;)a*=2;return a===t?{factor:t,needsRaster:!1}:{factor:a,needsRaster:!0}},Ed=(n,e)=>{let t=n.naturalWidth||n.width,r=n.naturalHeight||n.height,o=document.createElement("canvas");o.width=Math.max(1,Math.round(t*e)),o.height=Math.max(1,Math.round(r*e));let i=o.getContext("2d");return i&&(i.imageSmoothingEnabled=!0,i.imageSmoothingQuality="high",i.drawImage(n,0,0,o.width,o.height)),o};var is=(n,e)=>{if(n.children.includes(e))return[n];for(let t of n.children)if(t instanceof J&&!(t instanceof te)&&!(t instanceof le)){let r=is(t,e);if(r.length)return[...r,n]}return[]},Cd=n=>{let e=n.matrix,t=n.ownMatrix,r=ve(e),o=(i,s,a)=>Q(i,s,a,!0);return(i,s)=>{let a=o(r,i,s);return o(t,a.x,a.y)}},Md=n=>{let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n.children){if(!i.visible)continue;let s=i.contentBoxCorners();for(let a of[s.tl,s.tr,s.br,s.bl])a.x<e&&(e=a.x),a.y<t&&(t=a.y),a.x>r&&(r=a.x),a.y>o&&(o=a.y)}return Number.isFinite(e)?{minX:e,minY:t,maxX:r,maxY:o}:null},Rd=n=>{let e=Md(n);if(!e)return null;let t=n.matrix;return{tl:Q(t,e.minX,e.minY),tr:Q(t,e.maxX,e.minY),br:Q(t,e.maxX,e.maxY),bl:Q(t,e.minX,e.maxY)}},ss=n=>{let e=[];for(let t=0;t<n.length;t++){let r=n[t],o=Md(r);if(!o)continue;let i=o.maxX-o.minX,s=o.maxY-o.minY,a={x:(o.minX+o.maxX)/2,y:(o.minY+o.maxY)/2},l=new Map;for(let m of r.children){let p=m.aCoords;l.set(m,{x:(p.tl.x+p.br.x)/2,y:(p.tl.y+p.br.y)/2})}let u=Q(r.matrix,a.x,a.y),c=n[t+1]??null,h=c?Q(ve(c.matrix),u.x,u.y):u,d=ge({...r.raw,width:i,height:s},h);r.set({width:i,height:s,left:d.x,top:d.y});let f=ve(r.matrix);for(let m of r.children){let p=l.get(m);if(!p)continue;let b=Q(f,p.x,p.y),g=ge({...m.raw,width:m.dims.x,height:m.dims.y},b);m.set({left:g.x,top:g.y})}e.push(r,...r.children)}return e};var jl=["tl","tr","bl","br"],Tn=new Set(jl),as=["tlS","trS","blS","brS"],Ex=new Set(as),No={tlS:"tl",trS:"tr",blS:"bl",brS:"br"},Cx=new Set(["ml","mr","mt","mb"]),or={ml:"x",mr:"x",mt:"y",mb:"y"},ls={ml:"left",mr:"right",mt:"top",mb:"bottom"},En=n=>Cx.has(n),cs=n=>Tn.has(n),Fr=n=>Ex.has(n);var kn=8,ir=12,Rt=1.5,Pd=24,Mx=["lockMovementX","lockMovementY","lockScalingX","lockScalingY","lockSkewingX","lockSkewingY","lockRotation"],at=n=>{let e=n.raw;return Mx.some(t=>!!e[t])},ms=28,Vl=null,Rx=()=>{if(Vl)return Vl;let n=document.createElement("canvas");n.width=ms*2,n.height=ms*2;let e=n.getContext("2d");if(e){e.scale(2,2);let t=ms/2;e.beginPath(),e.arc(t,t,12,0,Math.PI*2),e.fillStyle="#ffffff",e.fill(),e.strokeStyle="#e0e0e0",e.lineWidth=4/3,e.stroke(),typeof Path2D<"u"&&(e.translate(t,t),e.scale(2/3,2/3),e.translate(-12,-12),e.beginPath(),e.strokeStyle="#2c2c2c",e.lineWidth=2,e.lineCap="round",e.lineJoin="round",e.stroke(new Path2D("M5 13a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v6a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-6z M11 16a1 1 0 1 0 2 0a1 1 0 0 0 -2 0 M8 11v-4a4 4 0 1 1 8 0v4")))}return Vl=n,n},ps=28,Px="M706.144 847.264A384.32 384.32 0 0 0 896 515.84c0-118.016-53.504-227.136-143.776-299.616a32 32 0 0 1 40.064-49.92A447.136 447.136 0 0 1 960 515.84c0 166.528-91.424 313.6-228.672 390.784l34.624 81.6-270.464-29.28 168.768-210.368 41.888 98.688zM320.736 182.72A384.288 384.288 0 0 0 128 515.84a383.36 383.36 0 0 0 157.76 310.304 32 32 0 0 1-37.728 51.712A447.36 447.36 0 0 1 64 515.84 448.32 448.32 0 0 1 294.56 123.968L261.664 50.112l268.928 20.032-163.04 217.76-46.816-105.184z",ql=null,kx=()=>{if(ql)return ql;let n=document.createElement("canvas");n.width=ps*2,n.height=ps*2;let e=n.getContext("2d");if(e){e.scale(2,2);let t=ps/2;e.fillStyle="#ffffff",e.beginPath(),e.arc(t,t,10,0,Math.PI*2),e.shadowColor="#333",e.shadowBlur=2,e.fill(),e.shadowColor="",e.shadowBlur=0,typeof Path2D<"u"&&(e.translate(t-8-1.392,t-8-.89),e.scale(.0178,.0178),e.fillStyle="black",e.fill(new Path2D(Px)))}return ql=n,n};var Ax=24,bs=20,Ad=16,Nx="M607.573333 295.908693h-184.32l92.16-92.16zM515.413333 813.42464l-92.16-92.16h184.32l-92.16 92.16M210.57536 508.586667l92.16-92.16v184.32l-92.16-92.16M820.251307 508.586667l-92.16 92.16v-184.32l92.16 92.16M446.88384 507.405653c0 37.195093 30.153387 67.345067 67.345067 67.345067 37.198507 0 67.351893-30.149973 67.351893-67.345067s-30.153387-67.345067-67.34848-67.345066c-37.195093 0-67.345067 30.149973-67.345067 67.345066z",Kl=null,Lx=()=>{if(Kl)return Kl;let n=document.createElement("canvas");n.width=bs*2,n.height=bs*2;let e=n.getContext("2d");if(e){e.scale(2,2);let t=bs/2;e.beginPath(),e.arc(t,t,8,0,Math.PI*2),e.strokeStyle="#2c2c2c",e.lineWidth=2,e.stroke(),e.fillStyle="#ffffff",e.fill(),typeof Path2D<"u"&&(e.translate(t-8,t-8),e.scale(16/1024,16/1024),e.fillStyle="#2c2c2c",e.fill(new Path2D(Nx)))}return Kl=n,n},ec=n=>{if(n.selection.length!==1)return null;let e=n.selection[0];if(e instanceof te||e instanceof le)return null;let t=e.typeKey;return ft.has(t)||ot.has(t)||at(e)?null:e},tc=(n,e,t)=>vs(n,e,t,{x:.5,y:0,offsetX:Ax,offsetY:0}),Mn=3,Ql=new Map,Ix=n=>{let e=Ql.get(n);if(e)return e;let t=document.createElement("canvas"),r=t.getContext("2d"),o=`bold ${14*Mn}px Helvetica, Arial, sans-serif`;if(!r)return t.width=Math.max(1,Math.round((n.length*14*.6+16)*Mn)),t.height=Math.round(30*Mn),Ql.set(n,t),t;r.font=o;let i=r.measureText(n).width,s=8*Mn;t.width=Math.max(1,Math.ceil(i)+s*2),t.height=Math.ceil(30*Mn),r.font=o;let a=6*Mn;return r.beginPath(),r.moveTo(a,0),r.lineTo(t.width-a,0),r.arcTo(t.width,0,t.width,a,a),r.lineTo(t.width,t.height-a),r.arcTo(t.width,t.height,t.width-a,t.height,a),r.lineTo(a,t.height),r.arcTo(0,t.height,0,t.height-a,a),r.lineTo(0,a),r.arcTo(0,0,a,0,a),r.closePath(),r.fillStyle="rgba(44, 44, 44, 0.9)",r.fill(),r.fillStyle="#ffffff",r.textAlign="center",r.textBaseline="middle",r.fillText(n,t.width/2,t.height/2),Ql.set(n,t),t},_x=(n,e,t)=>{let r=Ix(`${Math.round(e)}°`);return{matrix:[1,0,0,1,n.x,n.y],dims:{x:r.width/Mn/t,y:r.height/Mn/t},color:[1,1,1,1],texture:r}},st=ee("#2f6fed"),Lo=ee("#ffffff"),us=ee("#2f6fed"),nc=st,hs=(n,e)=>({x:(n.x+e.x)/2,y:(n.y+e.y)/2}),Re=(n,e,t,r)=>{let o=(n.x+e.x)/2,i=(n.y+e.y)/2,s=Math.hypot(e.x-n.x,e.y-n.y),a=Math.atan2(e.y-n.y,e.x-n.x),l=Math.cos(a),u=Math.sin(a);return{matrix:[l,u,-u,l,o,i],dims:{x:s,y:t},color:r}},Rn=(n,e,t,r)=>{let o=r*Math.PI/180,i=Math.cos(o),s=Math.sin(o);return{matrix:[i,s,-s,i,n.x,n.y],dims:{x:e,y:e},color:t}},Dx=n=>{let e=n.angle*Math.PI/180,t=Math.cos(e),r=Math.sin(e),o=n.width/2,i=n.height/2,s=(a,l)=>({x:n.center.x+t*a-r*l,y:n.center.y+r*a+t*l});return{tl:s(-o,-i),tr:s(o,-i),br:s(o,i),bl:s(-o,i)}},et=n=>{let e=n.selection;if(e.length===0)return null;if(e.length===1){let a=e[0];return{quad:a.aCoords,angle:a.raw.angle??0}}let t=n.selectionFrame;if(t)return{quad:Dx(t),angle:t.angle};let r=1/0,o=1/0,i=-1/0,s=-1/0;for(let a of e){let l=a.bounds;r=Math.min(r,l.left),o=Math.min(o,l.top),i=Math.max(i,l.right),s=Math.max(s,l.bottom)}return{quad:{tl:{x:r,y:o},tr:{x:i,y:o},br:{x:i,y:s},bl:{x:r,y:s}},angle:0}},Br=(n,e,t=1,r)=>{let o=hs(n.tl,n.tr),i=hs(n.tr,n.br),s=hs(n.bl,n.br),a=hs(n.tl,n.bl),l=Kx(n,e,t),u=[{id:"tl",x:n.tl.x,y:n.tl.y},{id:"tr",x:n.tr.x,y:n.tr.y},{id:"br",x:n.br.x,y:n.br.y},{id:"bl",x:n.bl.x,y:n.bl.y},{id:"mt",x:o.x,y:o.y},{id:"mr",x:i.x,y:i.y},{id:"mb",x:s.x,y:s.y},{id:"ml",x:a.x,y:a.y},{id:"mtr",x:l.x,y:l.y}],c=r?Hx(r,t):[];return c.length?[...c,...u]:u},Fx=32,Ox=.25,xs=14,Nd=n=>n<=0?0:Math.min(Fx,n*Ox),Ld=(n,e)=>{if(e<=0)return 0;let t=Math.max(0,Math.min(e,n)),r=Nd(e);return r<=0||e<=r?t:r+t/e*(e-r)},rc=(n,e)=>{if(e<=0)return 0;let t=Math.max(0,Math.min(e,n)),r=Nd(e);return r<=0||e<=r?t:t<=r?0:(t-r)/(e-r)*e},ys=n=>!!n&&n.typeKey===L.FABRICRECT,Bx=new Set([L.QRCODE,L.BARCODE,L.ECHART,L.FABRIC_ECHART]),Io=n=>{if(!n)return!1;let e=se(n.raw);return!Bx.has(e)&&(e===L.IMAGE||e===L.SVGIMAGE||e===L.CROPIMAGE)},Id=n=>{let e=Math.max(Math.abs(n.raw.scaleX??1)||1,1e-4),t=Math.max(Math.abs(n.raw.scaleY??1)||1,1e-4);return Math.min(n.dims.x*e,n.dims.y*t)/2},Wx=(n,e)=>{let t=n.aCoords,r=Math.hypot(t.tr.x-t.tl.x,t.tr.y-t.tl.y)*e,o=Math.hypot(t.bl.x-t.tl.x,t.bl.y-t.tl.y)*e;return r>Or&&o>Or},Hx=(n,e)=>Wx(n,e)?ys(n)?Gx(n,e):Io(n)?Xx(n,e):[]:[],Gx=(n,e)=>{let t=n.raw,r=Math.max(Math.abs(t.scaleX??1)||1,1e-4),o=Math.max(Math.abs(t.scaleY??1)||1,1e-4),i=n.dims.x/2,s=n.dims.y/2,a=i*r,l=s*o,u=Math.min(a,l),c=Math.max(0,Math.min(u,t.radius??0)),h=Ld(c,u),d=Math.max(0,(xs-h*e)/e),f=Math.max(0,(xs-h*e)/e),m=h+Math.min(d,Math.max(0,a-h)),p=h+Math.min(f,Math.max(0,l-h)),b=n.matrix;return as.map(g=>{let x=No[g],S=x==="tl"||x==="bl",w=x==="tl"||x==="tr",y=(S?-a+m:a-m)/r,v=(w?-l+p:l-p)/o;return{id:g,x:b[0]*y+b[2]*v+b[4],y:b[1]*y+b[3]*v+b[5]}})},Xx=(n,e)=>{let t=n.raw,r=n.dims.x/2,o=n.dims.y/2,i=Math.min(r,o),s=Math.max(0,Math.min(i,Math.max(t.rx??0,t.ry??0))),a=Ld(s,i),l=Math.max(Math.abs(t.scaleX??1)||1,1e-4),u=Math.max(Math.abs(t.scaleY??1)||1,1e-4),c=l*e,h=u*e,d=Math.min(Math.max(0,(xs-a*c)/c),Math.max(0,r-a)),f=Math.min(Math.max(0,(xs-a*h)/h),Math.max(0,o-a)),m=n.matrix;return as.map(p=>{let b=No[p],g=b==="tl"||b==="bl",x=b==="tl"||b==="tr",S=g?-r+a+d:r-a-d,w=x?-o+a+f:o-a-f;return{id:p,x:m[0]*S+m[2]*w+m[4],y:m[1]*S+m[3]*w+m[5]}})},gs=12,ds=null,zx=()=>{if(ds)return ds;let n=document.createElement("canvas");n.width=gs*2,n.height=gs*2;let e=n.getContext("2d");if(e){e.scale(2,2);let t=gs/2,r=kn/2;e.beginPath(),e.arc(t,t,r+Rt,0,Math.PI*2),e.fillStyle=`rgb(${st[0]*255},${st[1]*255},${st[2]*255})`,e.fill(),e.beginPath(),e.arc(t,t,r,0,Math.PI*2),e.fillStyle=`rgb(${Lo[0]*255},${Lo[1]*255},${Lo[2]*255})`,e.fill()}return ds=n,ds},_d=16,Cn=4,kd={tlr:{x:-.5,y:-.5,offsetX:-Cn,offsetY:-Cn},trr:{x:.5,y:-.5,offsetX:Cn,offsetY:-Cn},brr:{x:.5,y:.5,offsetX:Cn,offsetY:Cn},blr:{x:-.5,y:.5,offsetX:-Cn,offsetY:Cn}},oc={tlr:0,trr:90,brr:180,blr:270},Or=50,ic=(n,e)=>({width:Math.hypot(n.tr.x-n.tl.x,n.tr.y-n.tl.y)*e,height:Math.hypot(n.bl.x-n.tl.x,n.bl.y-n.tl.y)*e}),Yx=(n,e)=>{let{width:t,height:r}=ic(n,e);return t>Or&&r>Or},Ux=new Set(["mr","br","mtr"]),$x=new Set(["mr","br"]),jx=new Set(["mr","br","mtr"]),Vx=new Set(["ml","mr","tl","tr","bl","br","tlS","trS","blS","brS"]),qx=new Set(["mt","mb","tl","tr","bl","br","mtr","tlS","trS","blS","brS"]),Dd=(n,e,t)=>{let r=e<=Or,o=t<=Or;return!r&&!o?!0:r&&o?Ux.has(n):!(r&&Vx.has(n)&&!$x.has(n)||o&&qx.has(n)&&!jx.has(n))},Fd=n=>n instanceof le||n instanceof te||ot.has(n.typeKey),Od=(n,e)=>e&&dh(e.raw)?n.filter(t=>!En(t.id)):n,_o=(n,e,t,r,o)=>{let i=Br(e,t,r,o),s=n.selection.length===1?n.selection[0]:null;if(!s||Fd(s))return i;let a=ft.has(s.typeKey),l=ic(e,r);return Od(i.filter(u=>a&&(u.id==="ml"||u.id==="mr")||Dd(u.id,l.width,l.height)),s)},sc=(n,e)=>{let t=n.aCoords,r=n.worldAngle,o=Br(t,r,e);if(Fd(n))return o;let i=ft.has(n.typeKey),s=ic(t,e);return Od(o.filter(a=>i&&(a.id==="ml"||a.id==="mr")||Dd(a.id,s.width,s.height)),n)},Bd=(n,e,t)=>Yx(n,t)?Object.keys(kd).map(r=>{let o=vs(n,e,t,kd[r]);return{id:r,x:o.x,y:o.y}}):[],Ss=n=>{let e=n*Math.PI/180,t=Math.sin(e),r=Math.cos(e);if(Math.abs(t)>=Math.abs(r)){let i=Math.sign(t);return{x:i/2,y:0,offsetX:i*Pd,offsetY:0}}let o=Math.sign(r);return{x:0,y:o/2,offsetX:0,offsetY:o*Pd}},vs=(n,e,t,r)=>{let o=(n.tl.x+n.br.x)/2,i=(n.tl.y+n.br.y)/2,s=Math.hypot(n.tr.x-n.tl.x,n.tr.y-n.tl.y),a=Math.hypot(n.bl.x-n.tl.x,n.bl.y-n.tl.y),l=r.x*s+r.offsetX/t,u=r.y*a+r.offsetY/t,c=e*Math.PI/180,h=Math.cos(c),d=Math.sin(c);return{x:o+l*h-u*d,y:i+l*d+u*h}},Kx=(n,e,t)=>vs(n,e,t,Ss(e)),Pn=(n,e)=>{let t=Rt/e;return[Re(n.tl,n.tr,t,st),Re(n.tr,n.br,t,st),Re(n.br,n.bl,t,st),Re(n.bl,n.tl,t,st)]},Qx=3,fs=(n,e,t,r,o)=>{let i=e.x-n.x,s=e.y-n.y,a=Math.hypot(i,s);if(a<=0)return[];let l=i/a,u=s/a,c=Qx/o,h=[];for(let d=0;d<a;d+=c*2){let f=Math.min(d+c,a);h.push(Re({x:n.x+l*d,y:n.y+u*d},{x:n.x+l*f,y:n.y+u*f},t,r))}return h},ws=(n,e)=>{let t=Rt/e;return[...fs(n.tl,n.tr,t,st,e),...fs(n.tr,n.br,t,st,e),...fs(n.br,n.bl,t,st,e),...fs(n.bl,n.tl,t,st,e)]},Zx=(n,e,t,r)=>{let o=Rt/r,i=kn/r;for(let s of e)s.id==="mtr"?n.push({...Rn(s,ps/r,[1,1,1,1],t),texture:kx()}):Fr(s.id)?n.push({...Rn(s,gs/r,[1,1,1,1],t),texture:zx()}):(n.push(Rn(s,i,st,t)),n.push(Rn(s,i-2*o,Lo,t)))},Zl=(n,e,t,r,o,i)=>{if(i?.spec){let s=e.find(l=>l.id==="mtr"),a=vs(t,r,o,i.spec);s.x=a.x,s.y=a.y}Zx(n,e,r,o),i&&n.push(_x(i.center,r,o))},Wd=(n,e,t=null,r=!1)=>{if(n.selection.length===1&&Ze(n.selection[0]))return[];let o=et(n);if(!o)return[];let{quad:i,angle:s}=o,a=[],l=n.activeGroupChild,u=l&&n.groupEditing&&n.selection[0]instanceof J&&!(n.selection[0]instanceof te)&&!(n.selection[0]instanceof le)?n.selection[0]:null,h=(u?Rd(u):null)??i;if(l)a.push(...Pn(l.aCoords,e)),a.push(...ws(h,e));else{if(n.selection.length>=2)for(let d of n.selection)a.push(...Pn(d.aCoords,e));a.push(...Pn(i,e))}if(n.selection.length===1&&at(n.selection[0]))return a.push({...Rn(i.br,ms/e,[1,1,1,1],s),texture:Rx()}),a;if(Zl(a,_o(n,h,s,e,Do(n)),h,s,e,t?.onChild?null:t),l&&n.groupEditing&&Zl(a,sc(l,e),l.aCoords,l.worldAngle,e,t?.onChild?t:null),r&&ec(n)){let d=tc(h,s,e);a.push({...Rn(d,bs/e,[1,1,1,1],0),texture:Lx()})}return a},Do=n=>{if(n.selection.length!==1)return null;let e=n.selection[0];return ys(e)||Io(e)?e:null},Hd=(n,e)=>{let t=Rt/e,r={x:n.left,y:n.top},o={x:n.right,y:n.top},i={x:n.right,y:n.bottom},s={x:n.left,y:n.bottom};return[Re(r,o,t,us),Re(o,i,t,us),Re(i,s,t,us),Re(s,r,t,us)]},Fo=n=>{let e=n.editingMask;if(!e)return[];let t=e.aCoords;return Br(t,e.worldAngle).filter(o=>En(o.id)?!n.maskEdgeOnOuterBorder(e,ls[o.id]):!1)},Gd=(n,e,t=null)=>{let r=n.editingMask;if(!r)return[];let o=r.worldAngle,i=Pn(r.aCoords,e),s=Rt/e,a=kn/e;for(let u of Fo(n))i.push(Rn(u,a,st,o)),i.push(Rn(u,a-2*s,Lo,o));let l=n.raw.angle??0;return i.push(...ws(n.aCoords,e)),Zl(i,Br(n.aCoords,l),n.aCoords,l,e,t),i},Jx=2.5,Jl=(n,e,t)=>{let r=e.aCoords,o=t==="mr"?{p1:r.tr,p2:r.br}:{p1:r.bl,p2:r.br},i=n.layoutParams,s=t==="mr"?i.hGap:i.vGap;if(s>0){let a=(o.p1.x+o.p2.x)/2,l=(o.p1.y+o.p2.y)/2,u=(r.tl.x+r.br.x)/2,c=(r.tl.y+r.br.y)/2,h=a-u,d=l-c,f=Math.hypot(h,d)||1,m=s/2*(t==="mr"?n.worldScale.x:n.worldScale.y);return{mask:e,handle:t,p1:{x:o.p1.x+h/f*m,y:o.p1.y+d/f*m},p2:{x:o.p2.x+h/f*m,y:o.p2.y+d/f*m}}}return{mask:e,handle:t,p1:o.p1,p2:o.p2}},ac=n=>{let e=[];for(let i of n.maskChildren)i.visible&&(n.maskEdgeOnOuterBorder(i,"right")||e.push(Jl(n,i,"mr")),n.maskEdgeOnOuterBorder(i,"bottom")||e.push(Jl(n,i,"mb")));let t=n.layoutParams,r=Math.max(t.hGap,t.vGap)+1,o=[];for(let i of e){let s=o.find(a=>{let l=a.p2.x-a.p1.x,u=a.p2.y-a.p1.y,c=Math.hypot(l,u)||1,h=l/c,d=u/c;if(Math.abs((i.p2.x-i.p1.x)*d-(i.p2.y-i.p1.y)*h)/Math.max(1e-9,Math.hypot(i.p2.x-i.p1.x,i.p2.y-i.p1.y))>1e-6||Math.abs((i.p1.x-a.p1.x)*d-(i.p1.y-a.p1.y)*h)>.5)return!1;let m=(i.p1.x-a.p1.x)*h+(i.p1.y-a.p1.y)*d,p=(i.p2.x-a.p1.x)*h+(i.p2.y-a.p1.y)*d,b=Math.min(m,p),g=Math.max(m,p);return b<=c+r&&g>=-r});if(s){let a=s.p2.x-s.p1.x,l=s.p2.y-s.p1.y,u=Math.hypot(a,l)||1,c=a/u,h=l/u,d=[0,u,(i.p1.x-s.p1.x)*c+(i.p1.y-s.p1.y)*h,(i.p2.x-s.p1.x)*c+(i.p2.y-s.p1.y)*h],f=Math.min(...d),m=Math.max(...d);s.p1={x:s.p1.x+c*f,y:s.p1.y+h*f},s.p2={x:s.p1.x+c*(m-f),y:s.p1.y+h*(m-f)}}else o.push({...i})}return o},Xd=(n,e,t)=>ac(n).find(o=>o.mask===e&&o.handle===t)??Jl(n,e,t),zd=(n,e)=>[Re(n.p1,n.p2,Jx/e,nc)],ey=ee("#3c7eff"),ty=2,ny=(n,e,t)=>{let r=e.x-n.x,o=e.y-n.y,i=Math.hypot(r,o)||1,s=-o/i,a=r/i,l={x:(n.x+e.x)/2,y:(n.y+e.y)/2};return(l.x+s-t.x)*s+(l.y+a-t.y)*a>=0?{x:s,y:a}:{x:-s,y:-a}},Yd=(n,e)=>{let t=n.aCoords,r=[t.tl,t.tr,t.br,t.bl],o={x:(t.tl.x+t.br.x)/2,y:(t.tl.y+t.br.y)/2},i=r.map((u,c)=>ny(u,r[(c+1)%4],o)),s=n.bounds,a=Math.min(ty,(s.right-s.left)*e,(s.bottom-s.top)*e)/e;if(a<=0)return[];let l=[];for(let u=0;u<4;u++){let c=r[u],h=r[(u+1)%4],d=i[u];l.push(Re({x:c.x-d.x*a/2,y:c.y-d.y*a/2},{x:h.x-d.x*a/2,y:h.y-d.y*a/2},a,ey))}return l};function Ud(n,e,t,r){let o=n.selection.map(l=>l.id),i=et(n);if(!i||n.editingNode||e)return{ids:o,handles:[]};let s=n.selection.length===1&&n.selection[0]instanceof le?n.selection[0]:null,a=s?.editingMask?[...Fo(s).map(l=>{let u=r(l.x,l.y);return{id:l.id,x:u.x,y:u.y}}),...Br(i.quad,i.angle,t).map(l=>{let u=r(l.x,l.y);return{id:l.id,x:u.x,y:u.y}})]:_o(n,i.quad,i.angle,t,Do(n)).map(l=>{let u=r(l.x,l.y);return{id:l.id,x:u.x,y:u.y}});return{ids:o,handles:a}}function $d(n){let e=n.activeGroupChild;if(!e)return null;let t=n.selection[0];return!(t instanceof J)||!t.containsDeep(e)?null:{rootId:t.id,childId:e.id}}function jd(n,e){let t=[],r=o=>{for(let i of o){if(i instanceof J&&r(i.children),!i.imageEl||!os(i.raw.src))continue;let s=i.imageEl.naturalWidth||i.imageEl.width,a=i.imageEl.naturalHeight||i.imageEl.height,l=e(i);t.push({id:i.id,type:i.raw.type,factor:l,rasterWidth:Math.round(s*(l??1)),rasterHeight:Math.round(a*(l??1))})}};return r(n.nodes),t}function Vd(n){return n.nodes.map(e=>({id:e.id,type:e.raw.type,left:e.raw.left??0,top:e.raw.top??0,width:e.raw.width??0,height:e.raw.height??0,scaleX:e.raw.scaleX??1,scaleY:e.raw.scaleY??1,angle:e.raw.angle??0,visible:e.visible,bounds:e.bounds,aCoords:e.aCoords}))}function qd(n,e){e();let t=performance.now();for(let o=0;o<n;o++)e();let r=(performance.now()-t)/n;return li("engine.render.avgMeasured",r),r}function Kd(n){let e=n.width,t=n.height,r=document.createElement("canvas");r.width=e,r.height=t;let o=r.getContext("2d");o.drawImage(n,0,0);let i=o.getImageData(0,0,e,t);return{width:e,height:t,data:i.data}}var ry=2,Le={drag:"drag",scale:"scale",rotate:"rotate",cornerRadius:"cornerRadius",crop:"crop",tableCellEdit:"table-cell-edit",warpImage:"warpvas-image"},oy=(n,e)=>{let{bus:t,wrap:r,syncSelection:o,settleSnap:i}=e,s=n.events,a=(c,h)=>{let d=h.map(r);o(),t.fire(c,{selected:d,deselected:[],target:d[0]})},l=(c,h)=>{h.syntheticOwner||t.fire(c,{target:r(h)})},u=[s.on("selection:created",c=>a("selection:created",c)),s.on("selection:updated",c=>a("selection:updated",c)),s.on("selection:cleared",()=>{o(),t.fire("selection:cleared",{selected:[],deselected:[]})}),s.on("object:added",c=>l("object:added",c)),s.on("object:removed",c=>l("object:removed",c)),s.on("object:moving",c=>{i?.(),l("object:moving",c)}),s.on("object:scaling",c=>l("object:scaling",c)),s.on("object:rotating",c=>l("object:rotating",c)),s.on("object:cornerRadius",c=>l("object:cornerRadius",c)),s.on("object:modified",(c,h)=>{let d=c.map((g,x)=>g.syntheticOwner?-1:x).filter(g=>g>=0);if(!d.length)return;let f=d.map(g=>r(c[g])),m=h?.before,p=m?.length?d.map(g=>m[g]).filter(g=>!!g):void 0,b=p&&(p.length>1||d.length>1)?{original:{objects:p}}:p?{original:p[0]}:void 0;t.fire("object:modified",{target:f[0],targets:f,transform:b,action:h?.action,transactionId:h?.transactionId,protocolVersion:2})}),s.on("text:editing:entered",c=>l("text:editing:entered",c)),s.on("text:editing:exited",c=>l("text:editing:exited",c)),s.on("text:changed",c=>l("text:changed",c)),s.on("text:editing:committed",(c,h,d)=>{t.fire("text:editing:committed",{target:r(c),before:h,after:d})}),s.on("smartobject:open-requested",c=>l("smartobject:open-requested",c)),s.on("image:replace-requested",c=>l("image:replace-requested",c)),s.on("lock:unlock-requested",c=>l("lock:unlock-requested",c)),s.on("path:active-anchor-change",(c,h)=>{t.fire("path:active-anchor-change",{target:r(c),key:h})}),s.on("group:child-activated",c=>{o(),t.fire("group:child-activated",{target:r(c)})}),s.on("group:child-deactivated",()=>{o(),t.fire("group:child-deactivated")}),s.on("table:cellselection",c=>{t.fire("table:cellselection",{target:r(c)})})];return()=>u.forEach(c=>c())};function Qd(n,e){let t=n.nodes.filter(r=>r.visible&&!Ir.has(String(r.raw.id??""))&&!Ze(r));return n.setSelection(t),e(),t.length}function Zd(n,e){let t=[...n.selection];for(let r of t)n.remove(r);return t.length&&e(),t.length}function Jd(n,e,t,r){let o=[...n.selection];if(!o.length)return 0;let i=o.map(s=>s.toObject());for(let s of o)n.setProps(s,{left:(s.raw.left??0)+e,top:(s.raw.top??0)+t},{deferIndexRebuild:!0});return n.commitGeometry(),n.fireObjectModified(o,{action:Le.drag,before:i}),r(),o.length}var Cs=20,tf={ruleSize:Cs,backgroundColor:ee("#ffffff"),tickColor:ee("#A1A7AF"),textColor:"#444444",highlightColor:ee("#165dff3b"),fontSize:8,unitName:"px"},iy=.6,Ye=3,nf="'Arial Narrow', 'Segoe UI', sans-serif",ef=[.02,.03,.05,.1,.2,.5,1,2,5],sy=[5e3,2500,1e3,500,200,100,50,20,10],ay=n=>{let e=0;for(;e<ef.length&&ef[e]<n;)e++;return sy[e-1]??1e4},ly=(n,e,t,r)=>{let o=ay(r),i=Math.floor(n/o)*o,s=n+e,a=[],l=[],u=c=>c>=n-1e-6&&c<=s+1e-6&&(!t||c>=t[0]-1e-6&&c<=t[1]+1e-6);for(let c=i;c<=s+o;c+=o){u(c)&&a.push(c);for(let h=1;h<10;h++){let d=c+o*h/10;if(d>s+o)break;u(d)&&l.push(d)}}return{majors:a,minors:l}},cy=(n,e)=>{if(!n.length)return[];let t=e?"left":"top",r=e?"width":"height",o=[...n].sort((a,l)=>a[t]-l[t]),i=[],s={start:o[0][t],length:o[0][r]};for(let a=1;a<o.length;a++){let l=o[a];s.start+s.length>=l[t]?s.length=Math.max(s.start+s.length,l[t]+l[r])-s.start:(i.push(s),s={start:l[t],length:l[r]})}return i.push(s),i},lc=new Map,uy=(n,e=tf)=>{let t=lc.get(n);if(t)return t;let r=document.createElement("canvas"),o=r.getContext("2d");if(!o)return r.width=Math.max(1,Math.round(n.length*e.fontSize*.6*Ye)),r.height=Math.max(1,Math.round(e.fontSize*1.4*Ye)),lc.set(n,r),r;let i=`${e.fontSize*Ye}px ${nf}`;o.font=i;let s=o.measureText(n);return r.width=Math.max(1,Math.ceil(s.width)+2),r.height=Math.ceil(e.fontSize*Ye*1.25),o.font=i,o.textBaseline="top",o.fillStyle=e.textColor,o.fillText(n,1,Math.round(e.fontSize*Ye*.15)),lc.set(n,r),r},cc=new Map,Ts=10,Es=4,hy=n=>{let e=cc.get(n);if(e)return e;let t=Ts*Ye,r=Es*Ye,o=document.createElement("canvas"),i=o.getContext("2d");if(!i)return o.width=Math.max(1,Math.round((n.length*Ts*.6+Es*2)*Ye)),o.height=Math.max(1,Math.round((Ts+Es*2)*Ye)),cc.set(n,o),o;let s=`${t}px ${nf}`;i.font=s;let a=i.measureText(n).width,l=3*Ye;return o.width=Math.max(1,Math.ceil(a)+r*2),o.height=Math.ceil((Ts+Es*2)*Ye),i.font=s,i.beginPath(),i.moveTo(l,0),i.lineTo(o.width-l,0),i.quadraticCurveTo(o.width,0,o.width,l),i.lineTo(o.width,o.height-l),i.quadraticCurveTo(o.width,o.height,o.width-l,o.height),i.lineTo(l,o.height),i.quadraticCurveTo(0,o.height,0,o.height-l),i.lineTo(0,l),i.quadraticCurveTo(0,0,l,0),i.closePath(),i.fillStyle="rgba(22, 93, 255, 0.9)",i.fill(),i.strokeStyle="#fff",i.lineWidth=.5*Ye,i.stroke(),i.fillStyle="#fff",i.textBaseline="top",i.fillText(n,r,r),cc.set(n,o),o},rf=n=>{let e={...tf,...n.style},{vpt:t,cssWidth:r,cssHeight:o}=n,i=t[0],s=n.digitCanvas??(b=>uy(b,e)),a=[],l=b=>(b-t[4])/i,u=b=>(b-t[5])/i,c=1/i,h=(b,g,x,S,w)=>({matrix:[c,0,0,c,l(b+x/2),u(g+S/2)],dims:{x,y:S},color:w}),d=(b,g,x,S=!1)=>{let w=s(b),y=w.width/Ye,v=w.height/Ye;return{matrix:S?[0,c,-c,0,l(g+v/2),u(x-y/2)]:[c,0,0,c,l(g+y/2),u(x+v/2)],dims:{x:y,y:v},color:[1,1,1,1],texture:w}},f=e.ruleSize,m=b=>{let g=b?r:o;a.push(b?h(0,0,r,f,e.backgroundColor):h(0,0,f,o,e.backgroundColor));let x=n.workspaceRect,S=x?b?[x.left,x.left+x.width]:[x.top,x.top+x.height]:null,w=b?-t[4]/i:-t[5]/i,y=ly(w,g/i,S,i),v=[e.tickColor[0],e.tickColor[1],e.tickColor[2],e.tickColor[3]*iy],R=P=>(P-w)*i;for(let P of y.majors){let T=Math.round(R(P));a.push(b?h(T,0,1,f,v):h(0,T,f,1,v))}for(let P of y.minors){let T=Math.round(R(P));a.push(b?h(T,f-8,1,8,v):h(f-8,T,8,1,v))}for(let P of y.majors){let T=R(P),C=String(Math.round(P));b?a.push(d(C,T+6,2.5)):a.push(d(C,2.5,T-6,!0))}for(let P of cy(n.selectionRects,b)){let T=(P.start-w)*i,C=P.length*i;a.push(b?h(T,0,C,f,e.highlightColor):h(0,T,f,C,e.highlightColor))}};m(!0),m(!1),a.push(h(0,0,f,f,e.backgroundColor));let p=s(e.unitName);if(a.push(d(e.unitName,f/2-p.width/Ye/2,f/2-p.height/Ye/2)),n.referenceLine){let b=hy(String(Math.round(n.referenceLine.position))),g=b.width/Ye,x=b.height/Ye,S,w;if(n.referenceLine.axis==="horizontal"){let y=n.referenceLine.position*i+t[5];S=f+5,w=y+x/2,w<0&&(w=2),w+x>o&&(w=o-x-2)}else S=n.referenceLine.position*i+t[4]+g/2,w=f+5,S<0&&(S=2),S+g>r&&(S=r-g-2);a.push({matrix:[c,0,0,c,l(S+g/2),u(w+x/2)],dims:{x:g,y:x},color:[1,1,1,1],texture:b})}return a};var Ms=n=>n*180/Math.PI,Se=n=>n*Math.PI/180,Rs=n=>({x:(n.tl.x+n.br.x)/2,y:(n.tl.y+n.br.y)/2}),Ps=n=>({width:Math.hypot(n.tr.x-n.tl.x,n.tr.y-n.tl.y),height:Math.hypot(n.bl.x-n.tl.x,n.bl.y-n.tl.y)}),uc={mr:0,br:45,mb:90,bl:135,ml:180,tl:225,mt:270,tr:315},hc=["ew-resize","nwse-resize","ns-resize","nesw-resize"],ks=5,of=4,Zt=(n,e,t)=>{let r=e/2,o=t/2;switch(n){case"tl":return{u:{x:-r,y:-o},a:{x:r,y:o},axis:"both"};case"tr":return{u:{x:r,y:-o},a:{x:-r,y:o},axis:"both"};case"br":return{u:{x:r,y:o},a:{x:-r,y:-o},axis:"both"};case"bl":return{u:{x:-r,y:o},a:{x:r,y:-o},axis:"both"};case"ml":return{u:{x:-r,y:0},a:{x:r,y:0},axis:"x"};case"mr":return{u:{x:r,y:0},a:{x:-r,y:0},axis:"x"};case"mt":return{u:{x:0,y:-o},a:{x:0,y:o},axis:"y"};case"mb":return{u:{x:0,y:o},a:{x:0,y:-o},axis:"y"};default:return{u:{x:r,y:o},a:{x:-r,y:-o},axis:"both"}}},dc=(n,e,t)=>Q([Math.cos(Se(n)),-Math.sin(Se(n)),Math.sin(Se(n)),Math.cos(Se(n)),0,0],e.x-t.x,e.y-t.y,!0),fc=(n,e)=>{let r=(s,a)=>{let l=s/a;return Math.sign(l||a)*Math.max(.01,Math.abs(l))},o=n.scaleX,i=n.scaleY;if(n.axis==="both"||n.axis==="x"){let s=n.handleLocal.x-n.anchorLocal.x;Math.abs(s)>1e-6&&(o=r(e.x,s))}if(n.axis==="both"||n.axis==="y"){let s=n.handleLocal.y-n.anchorLocal.y;Math.abs(s)>1e-6&&(i=r(e.y,s))}return{scaleX:o,scaleY:i}};var dy=n=>n instanceof ye&&(n.typeKey===L.TEXTBOX||n.typeKey===L.TEXTIMAGE&&!Kt(n));function mc(n,e){let t=n.dims.x,r=n.dims.y,o=n.raw,i={x:-e*t/2,y:0},s=n.matrix,a=n.children.map(h=>({node:h,centerX:h.center.x,centerY:h.center.y,scaleX:h.raw.scaleX??1,width:h.dims.x,fixedBox:dy(h)})),l=Q(s,i.x,i.y),u=n.parentMatrix,c=u?Q(ve(u),l.x,l.y):l;return{node:n,sign:e,width:t,height:r,angle:o.angle??0,scaleX:o.scaleX??1,scaleY:o.scaleY??1,anchorScene:l,anchorWrite:c,children:a}}function sf(n,e,t){let r=t/Math.max(e.width,1e-6);n.setProps(e.node,{width:t},{deferIndexRebuild:!0});let o={x:-e.sign*t/2,y:0},i=e.angle*Math.PI/180,s=Math.cos(i),a=Math.sin(i),l=s*(e.scaleX*o.x)-a*(e.scaleY*o.y),u=a*(e.scaleX*o.x)+s*(e.scaleY*o.y),c={x:e.anchorWrite.x-l,y:e.anchorWrite.y-u},h=ge({...e.node.raw,width:t,height:e.height,scaleX:e.scaleX,scaleY:e.scaleY},c);n.setProps(e.node,{left:h.x,top:h.y},{deferIndexRebuild:!0});for(let d of e.children){let f=d.centerX*r;if(d.fixedBox){let m=Math.max(d.width*r,1);n.setProps(d.node,{width:m},{deferIndexRebuild:!0});let p=d.node.dims,b=ge({...d.node.raw,width:p.x,height:p.y},{x:f,y:d.centerY});n.setProps(d.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}else{let m=d.scaleX*r;n.setProps(d.node,{scaleX:m},{deferIndexRebuild:!0});let p=d.node.dims,b=ge({...d.node.raw,width:p.x,height:p.y,scaleX:m},{x:f,y:d.centerY});n.setProps(d.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}}}function af(n,e,t){if(t.x*e.sign<=0)return;let o=(typeof e.node.raw.strokeWidth=="number"?e.node.raw.strokeWidth:0)/(e.node.raw.strokeUniform?e.scaleX:1),i=Math.max(e.sign*t.x/e.scaleX-o,1);sf(n,e,i)}function fy(n,e,t){if(!(t>0))return;let r=mc(e,1);sf(n,r,t)}function Wr(n){return n instanceof J&&!(n instanceof te)&&!(n instanceof le)}function bc(n,e,t){let r=n.raw,o=n.dims.x,i=n.dims.y,{u:s,a,axis:l}=Zt(e,o,i),u=Kt(n),c=(n.typeKey===L.TEXTBOX||n.typeKey===L.TEXTIMAGE&&!u)&&(e==="ml"||e==="mr");c&&(a.x=-s.x,a.y=-i/2);let h=n.matrix,d=Q(h,a.x,a.y),f=n.parentMatrix,m=f?Q(ve(f),d.x,d.y):d,p={node:n,left:r.left??0,top:r.top??0,angle:r.angle??0,scaleX:r.scaleX??1,scaleY:r.scaleY??1,width:o,height:i,anchorLocal:a,handleLocal:s,anchorScene:d,anchorWrite:m,axis:l,bakeWidth:c||void 0,bakeHeight:n.isTextType&&!u&&(e==="mt"||e==="mb")&&n instanceof ye||void 0};if(Wr(n)&&(e==="ml"||e==="mr")&&(p.bakeGroup=mc(n,e==="mr"?1:-1)),n.isMaskType&&(!t||t.nodes.includes(n))&&(e==="ml"||e==="mr"?p.bakeMaskWidth=!0:(e==="mt"||e==="mb")&&(p.bakeMaskHeight=!0)),n.isTextType&&!u&&Tn.has(e)&&n instanceof ye){let b=Xe(r)==="circle"?typeof r.circleSize=="number"?r.circleSize:40:void 0;p.bakeFont={fontSize0:n.textStyle.fontSize,styles0:r.styles??null,singleLine0:n.textLayout.lines.length===1,...b!==void 0?{circleSize0:b}:{}}}return p}function hf(n,e,t,r=!1){let o=dc(e.angle,t,e.anchorScene);if(e.bakeFont){py(n,e,o);return}if(e.bakeWidth){by(n,e,o);return}if(e.bakeHeight){gy(n,e,o);return}if(e.bakeGroup){af(n,e.bakeGroup,o);return}if(e.bakeMaskWidth){lf(n,e,o,"width");return}if(e.bakeMaskHeight){lf(n,e,o,"height");return}let i,s;if(e.axis==="both"&&!r){let f=(Math.abs(o.x)+Math.abs(o.y))/Math.max(Math.abs(e.width*e.scaleX)+Math.abs(e.height*e.scaleY),1e-6),m=Math.max(f,.01);i=e.scaleX*m,s=e.scaleY*m}else({scaleX:i,scaleY:s}=fc(e,o));let a=Math.cos(Se(e.angle)),l=Math.sin(Se(e.angle)),u=a*(i*e.anchorLocal.x)-l*(s*e.anchorLocal.y),c=l*(i*e.anchorLocal.x)+a*(s*e.anchorLocal.y),h={x:e.anchorWrite.x-u,y:e.anchorWrite.y-c},d=ge({...e.node.raw,width:e.width,height:e.height,scaleX:i,scaleY:s},h);n.setProps(e.node,{scaleX:i,scaleY:s,left:d.x,top:d.y},{deferIndexRebuild:!0})}function df(n,e,t){let{quad:r,angle:o}=t,i=Rs(r),{width:s,height:a}=Ps(r),{u:l,a:u,axis:c}=Zt(e,s,a),h=Math.cos(Se(o)),d=Math.sin(Se(o));return{members:n.map(f=>({node:f,center:{...f.center},scaleX:f.raw.scaleX??1,scaleY:f.raw.scaleY??1,dims:{...f.dims}})),center:i,angle:o,width:s,height:a,anchorLocal:u,handleLocal:l,anchorScene:{x:i.x+h*u.x-d*u.y,y:i.y+d*u.x+h*u.y},axis:c,handle:e}}function ff(n,e,t,r=!1){let o=dc(e.angle,t,e.anchorScene),i,s;if(e.axis==="both"&&!r){let h=(Math.abs(o.x)+Math.abs(o.y))/Math.max(Math.abs(e.width)+Math.abs(e.height),1e-6);i=s=Math.max(h,.01)}else({scaleX:i,scaleY:s}=fc({...e,scaleX:1,scaleY:1},o));let a=Math.cos(Se(e.angle)),l=Math.sin(Se(e.angle)),u={x:e.anchorScene.x-(a*(i*e.anchorLocal.x)-l*(s*e.anchorLocal.y)),y:e.anchorScene.y-(l*(i*e.anchorLocal.x)+a*(s*e.anchorLocal.y))},c=e.members;n.applyTransform(c.map(h=>h.node),h=>{let d=c.find(g=>g.node===h),f=my(e,u,i,s,d,a,l),m=d.scaleX*i,p=d.scaleY*s,b=ge({...h.raw,width:d.dims.x,height:d.dims.y,scaleX:m,scaleY:p},f);return{scaleX:m,scaleY:p,left:b.x,top:b.y}},"scaling"),n.setSelectionFrame({center:u,width:e.width*i,height:e.height*s,angle:e.angle})}function my(n,e,t,r,o,i,s){let a=i*(o.center.x-n.center.x)+s*(o.center.y-n.center.y),l=-s*(o.center.x-n.center.x)+i*(o.center.y-n.center.y);return{x:e.x+i*(t*a)-s*(r*l),y:e.y+s*(t*a)+i*(r*l)}}function mf(n,e,t){let r=Math.atan2(t.y-e.center.y,t.x-e.center.x),o=Ms(r-e.startAngle),i=Math.cos(Se(o)),s=Math.sin(Se(o)),a=e.snapshot.members;n.applyTransform(a.map(u=>u.node),u=>{let c=a.find(p=>p.node===u),h=((c.angle0+o)%360+360)%360,d=c.center0.x-e.center.x,f=c.center0.y-e.center.y,m={x:e.center.x+i*d-s*f,y:e.center.y+s*d+i*f};return u.rotateAroundCenter(h,m)},"rotating");let l=((e.frameAngle0+o)%360+360)%360;n.setSelectionFrame({center:{...e.center},width:e.frame.width,height:e.frame.height,angle:l})}var pc=n=>{if(n===null||typeof n!="object")return typeof n=="function"?void 0:n;if(Array.isArray(n))return n.map(pc);let e={};for(let t of Object.keys(n)){let r=pc(n[t]);r!==void 0&&(e[t]=r)}return e};function py(n,e,t){let r=e.bakeFont,o=e.handleLocal.x-e.anchorLocal.x,i=e.handleLocal.y-e.anchorLocal.y,s=Math.abs(o)+Math.abs(i),a=s>1e-6?(Math.abs(t.x)+Math.abs(t.y))/s:1,l=Math.max(r.fontSize0*a,1);a=l/r.fontSize0;let u={fontSize:l,scaleX:e.scaleX,scaleY:e.scaleY},c=r.styles0;if(c){let w=pc(c);for(let y of Object.values(w))if(y)for(let[v,R]of Object.entries(y)){let P=R;P&&typeof P.fontSize=="number"&&(y[v]={...P,fontSize:P.fontSize*a})}u.styles=w}let h=r.circleSize0,d=h!==void 0;if(d&&(u.circleSize=Math.max(h*a,1)),e.node.typeKey===L.TEXTBOX&&!d){let w=Math.max(e.width*a,1);if(r.singleLine0&&e.node instanceof ye&&Ge(e.node.raw)===null&&e.node.raw.vertical!==!0){let y=jt(e.node.raw.text??"",{...e.node.textStyle,fontSize:l},{boxWidth:null,styles:u.styles??e.node.raw.styles,splitByGrapheme:e.node.raw.splitByGrapheme===!0}).width;w=Math.max(w,y)}u.width=w}d||(u.height=Math.max(e.height*a,1));let f=Math.cos(Se(e.angle)),m=Math.sin(Se(e.angle)),p=f*(e.scaleX*e.anchorLocal.x*a)-m*(e.scaleY*e.anchorLocal.y*a),b=m*(e.scaleX*e.anchorLocal.x*a)+f*(e.scaleY*e.anchorLocal.y*a),g={x:e.anchorWrite.x-p,y:e.anchorWrite.y-b},x=typeof u.width=="number"?u.width:e.width*a,S=ge({...e.node.raw,width:x,height:e.height*a,scaleX:e.scaleX,scaleY:e.scaleY},g);u.left=S.x,u.top=S.y,n.setProps(e.node,u,{deferIndexRebuild:!0})}function by(n,e,t){let o=Math.sign(e.handleLocal.x);if(t.x*o<=0)return;let s=(typeof e.node.raw.strokeWidth=="number"?e.node.raw.strokeWidth:0)/(e.node.raw.strokeUniform?e.scaleX:1),a=Math.max(o*t.x/e.scaleX-s,1);n.setProps(e.node,{width:a},{deferIndexRebuild:!0});let l=e.node.dims.x,u=e.node.dims.y,c={x:-o*l/2,y:-u/2},h=Math.cos(Se(e.angle)),d=Math.sin(Se(e.angle)),f=h*(e.scaleX*c.x)-d*(e.scaleY*c.y),m=d*(e.scaleX*c.x)+h*(e.scaleY*c.y),p={x:e.anchorWrite.x-f,y:e.anchorWrite.y-m},b=ge({...e.node.raw,width:l,height:u,scaleX:e.scaleX,scaleY:e.scaleY},p);n.setProps(e.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}function gy(n,e,t){let r=e.node;if(!(r instanceof ye))return;let o=Math.sign(e.handleLocal.y);if(t.y*o<=0)return;let s=(typeof r.raw.strokeWidth=="number"?r.raw.strokeWidth:0)/(r.raw.strokeUniform?e.scaleY:1),a=Math.max(Math.ceil(Math.abs(t.y)/e.scaleY-s),r.textLayout.height,0);n.setProps(r,{height:a},{deferIndexRebuild:!0});let l={x:0,y:-o*a/2},u=Math.cos(Se(e.angle)),c=Math.sin(Se(e.angle)),h=u*(e.scaleX*l.x)-c*(e.scaleY*l.y),d=c*(e.scaleX*l.x)+u*(e.scaleY*l.y),f={x:e.anchorWrite.x-h,y:e.anchorWrite.y-d},m=ge({...r.raw,width:e.width,height:a,scaleX:e.scaleX,scaleY:e.scaleY},f);n.setProps(r,{left:m.x,top:m.y},{deferIndexRebuild:!0})}function lf(n,e,t,r){let i=e.node,s=i.raw,a=typeof s.strokeWidth=="number"?s.strokeWidth:0;if(r==="width"){let l=Math.sign(e.handleLocal.x);if(t.x*l<=0)return;let u=a/(s.strokeUniform?e.scaleX:1),c=Math.max(l*t.x/e.scaleX-u,1),h=Number(s.width)||e.width,d=Number(s.height)||e.height,f=uf(i,h,d,c,d);n.setProps(e.node,{width:c,...f??{}},{deferIndexRebuild:!0});let m={x:-l*c/2,y:0},p=cf(e,m),b=ge({...s,width:c,height:d,scaleX:e.scaleX,scaleY:e.scaleY},p);n.setProps(e.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}else{let l=Math.sign(e.handleLocal.y);if(t.y*l<=0)return;let u=a/(s.strokeUniform?e.scaleY:1),c=Math.max(l*t.y/e.scaleY-u,1),h=Number(s.width)||e.width,d=Number(s.height)||e.height,f=uf(i,h,d,h,c);n.setProps(e.node,{height:c,...f??{}},{deferIndexRebuild:!0});let m={x:0,y:-l*c/2},p=cf(e,m),b=ge({...s,width:h,height:c,scaleX:e.scaleX,scaleY:e.scaleY},p);n.setProps(e.node,{left:b.x,top:b.y},{deferIndexRebuild:!0})}}function cf(n,e){let t=Math.cos(Se(n.angle)),r=Math.sin(Se(n.angle)),o=t*(n.scaleX*e.x)-r*(n.scaleY*e.y),i=r*(n.scaleX*e.x)+t*(n.scaleY*e.y);return{x:n.anchorWrite.x-o,y:n.anchorWrite.y-i}}function uf(n,e,t,r,o){let s=n.raw.clipImage;if(!s||typeof s.src!="string")return null;let a=n.clipImageEl,l=a?.naturalWidth||Number(s.width)||0,u=a?.naturalHeight||Number(s.height)||0;if(!l||!u||!e||!t||!r||!o)return null;let c=(m,p)=>Math.max(m/l,p/u),h=Number(s.scaleX)||1,d=c(e,t)?h/c(e,t):1,f=c(r,o)*(d||1);return{clipImage:{...s,scaleX:f,scaleY:f}}}var pf=(n,e)=>e.length>=2&&(e.includes(n-1)||e.includes(n));function gf(n,e,t){let r=n.raw,o={type:"table-border-drag",node:n,border:e,startMatrix:[...n.matrix],startLocal:n.localPoint(t.x,t.y),startBorderPos:e.position,startWidths:Array.isArray(r.columnWidths)?[...r.columnWidths]:[...n.layout.columnWidths],startHeights:[...n.layout.rowHeights],selectedCols:[...new Set(n.selectedCells.map(i=>i.col))],selectedRows:[...new Set(n.selectedCells.map(i=>i.row))],savedCells:n.selectedCells,savedAnchor:n.cellAnchor,savedRange:n.cellRange};return n.setCellSelection([],null,null),n.borderDragging=!0,o}function xf(n,e){let t=n.node.raw,r=Q(ve(n.startMatrix),e.x,e.y),o={x:r.x-n.startLocal.x,y:r.y-n.startLocal.y};if(n.border.type==="col"){let u=t.minCellWidth??40,c=(Array.isArray(t.columnWidths)?[...t.columnWidths]:[...n.startWidths]).slice(0,n.node.tableView.cols);for(;c.length<n.node.tableView.cols;)c.push(u);if(pf(n.border.index,n.selectedCols))for(let h of n.selectedCols)c[h]=Math.max(u,n.startWidths[h]+o.x);else c[n.border.index-1]=Math.max(u,n.startWidths[n.border.index-1]+o.x);go(t,c)}else{let u=n.node.tableView.rows,c=Array.isArray(t.manualRowHeights)?t.manualRowHeights:[],h=[];for(let d=0;d<u;d++)h.push(typeof c[d]=="number"?c[d]:null);if(pf(n.border.index,n.selectedRows))for(let d of n.selectedRows)h[d]=Math.max(n.node.getRowMinHeight(d),n.startHeights[d]+o.y);else{let d=n.border.index-1;h[d]=Math.max(n.node.getRowMinHeight(d),n.startHeights[d]+o.y)}t.manualRowHeights=h}n.node.rebuildTable();let i=Rr(n.node.tableView,n.border.type,n.border.index),s=n.border.type==="col"?o.x:o.y,a=n.border.type==="col"?n.node.objectScale.x:n.node.objectScale.y,l=ad(n.startBorderPos,i,s,a);n.node.hoveredBorder={type:n.border.type,index:n.border.index,position:i+l}}function yf(n,e){let t=Zt(e,n.dims.x,n.dims.y).a;return{type:"table-edge-resize",node:n,handle:e,anchorScene:Q(n.matrix,t.x,t.y)}}function Sf(n,e){let t=Zt(e,n.dims.x,n.dims.y).a;return{type:"puzzle-edge-resize",node:n,handle:e,anchorScene:Q(n.matrix,t.x,t.y)}}function As(n,e,t,r){for(let o of Fo(e)){let i=n(o.x,o.y);if(En(o.id)&&Math.hypot(i.x-t,i.y-r)<=ir)return o.id}return null}function yy(n,e,t,r){let o=r.x-t.x,i=r.y-t.y,s=o*o+i*i,a=s>0?Math.max(0,Math.min(1,((n-t.x)*o+(e-t.y)*i)/s)):0;return Math.hypot(n-(t.x+a*o),e-(t.y+a*i))}function Oo(n,e,t,r){for(let o of ac(e)){let i=n(o.p1.x,o.p1.y),s=n(o.p2.x,o.p2.y);if(yy(t,r,i,s)<=ir)return{mask:o.mask,handle:o.handle}}return null}function gc(n,e,t){let r=n.maskChildren.indexOf(e);if(r<0)return null;let o=Vh(n.raw,n.maskChildren.map(s=>s.raw),n.maskChildren.map(s=>s.clipImageEl)),i=Zt(t,e.dims.x,e.dims.y).a;return{type:"puzzle-mask-edge-resize",node:n,maskIdx:r,handle:t,anchorScene:Q(e.matrix,i.x,i.y),state:o.state,pieces:o.pieces,clipSizes:o.clipSizes}}function Sy(n,e){n.maskChildren.forEach((t,r)=>{let o=e.masks[r];if(!o)return;let i=t.clipImageRaw,s=o.clip&&i?{...i,scaleX:o.clip.scaleX,scaleY:o.clip.scaleY,clipX:o.clip.clipX,clipY:o.clip.clipY}:null;t.set({left:o.left,top:o.top,width:o.width,height:o.height,...s?{clipImage:s}:{}})})}function vf(n,e){let t=n.node.maskChildren[n.maskIdx];if(!t)return;let r=t.raw,o=t.worldAngle,i=t.worldScale,s=e.x-n.anchorScene.x,a=e.y-n.anchorScene.y;if(o){let u=Math.cos(Se(-o)),c=Math.sin(Se(-o)),h=s;s=u*h-c*a,a=c*h+u*a}let l=ls[n.handle];if(l==="left"||l==="right"){let u=(r.strokeWidth??0)/(r.strokeUniform===!0?i.x:1);$h(n.state,n.maskIdx,Math.abs(s)/i.x-u,l,n.clipSizes)}else{let u=(r.strokeWidth??0)/(r.strokeUniform===!0?i.y:1);jh(n.state,n.maskIdx,Math.abs(a)/i.y-u,l,n.clipSizes)}Sy(n.node,n.state)}function bf(n,e){let t=n.layoutParams,r=n.maskChildren,o={...t,masks:r.map(s=>({left:s.raw.left??0,top:s.raw.top??0,width:s.raw.width??0,height:s.raw.height??0,clip:Xi(s.raw)}))},i=r.map(s=>s.clipImageEl?{w:s.clipImageEl.naturalWidth,h:s.clipImageEl.naturalHeight}:null);Uh(o,e,i)&&(n.set({layoutWidth:o.width,layoutHeight:o.height,hGap:o.hGap,vGap:o.vGap,groupPadding:o.groupPadding,width:o.width,height:o.height}),r.forEach((s,a)=>{let l=o.masks[a],u=s.clipImageRaw,c=l.clip&&u?{...u,scaleX:l.clip.scaleX,scaleY:l.clip.scaleY,clipX:l.clip.clipX,clipY:l.clip.clipY}:null;s.set({left:l.left,top:l.top,width:l.width,height:l.height,...c?{clipImage:c}:{}})}))}function wf(n,e,t){let r=e.node.raw,o={x:Math.abs(r.scaleX??1),y:Math.abs(r.scaleY??1)},i=r.angle??0,s=t.x-e.anchorScene.x,a=t.y-e.anchorScene.y;if(i){let m=Math.cos(Se(-i)),p=Math.sin(Se(-i)),b=s;s=m*b-p*a,a=p*b+m*a}let l=e.node.layoutParams;if(or[e.handle]==="x"){let m=(r.strokeWidth??0)/(r.strokeUniform===!0?o.x:1),p=Math.max(Math.abs(s)/o.x-m,1);bf(e.node,{widthRatio:p/(l.width||1)})}else{let m=(r.strokeWidth??0)/(r.strokeUniform===!0?o.y:1),p=Math.max(Math.abs(a)/o.y-m,1);bf(e.node,{heightRatio:p/(l.height||1)})}let u=Zt(e.handle,e.node.dims.x,e.node.dims.y).a,c=Math.cos(Se(i)),h=Math.sin(Se(i)),d={x:e.anchorScene.x-(c*(o.x*u.x)-h*(o.y*u.y)),y:e.anchorScene.y-(h*(o.x*u.x)+c*(o.y*u.y))},f=ge({...r,width:e.node.dims.x,height:e.node.dims.y},d);n.setProps(e.node,{left:f.x,top:f.y},{deferIndexRebuild:!0})}function Tf(n,e,t){let r=e.node.raw,o=e.node.tableView,i=e.node.objectScale,s=e.node.tableAngle,a=t.x-e.anchorScene.x,l=t.y-e.anchorScene.y;if(s){let p=Math.cos(Se(-s)),b=Math.sin(Se(-s)),g=a;a=p*g-b*l,l=b*g+p*l}let u=r.cellStrokeWidth??1;if(or[e.handle]==="x"){let p=Math.abs(a)/i.x-o.cellSpacing*(o.cols-1)-u,b=e.handle==="ml"?0:o.cols-1,g=o.columnWidths.reduce((x,S,w)=>w===b?x:x+S,0);xo(r,b,p-g)}else{let p=Math.abs(l)/i.y-o.cellSpacing*(o.rows-1)-u,b=e.handle==="mt"?0:o.rows-1,g=o.rowHeights.reduce((x,S,w)=>w===b?x:x+S,0);yo(r,b,p-g)}e.node.rebuildTable();let c=Zt(e.handle,e.node.dims.x,e.node.dims.y).a,h=Math.cos(Se(s)),d=Math.sin(Se(s)),f={x:e.anchorScene.x-(h*(i.x*c.x)-d*(i.y*c.y)),y:e.anchorScene.y-(d*(i.x*c.x)+h*(i.y*c.y))},m=ge({...r,width:e.node.dims.x,height:e.node.dims.y},f);n.setProps(e.node,{left:m.x,top:m.y},{deferIndexRebuild:!0})}function Ef(n,e,t){let r=Math.max(0,t.index);if(t.type==="col"){To(e.raw,r),e.rebuildTable();let o=e.tableView,i=$i(e.cellMap,o.rows,Math.min(r,o.cols-1));e.setCellSelection(i,i[0]??null,ze(i))}else{wo(e.raw,r),e.rebuildTable();let o=e.tableView,i=ji(e.cellMap,o.cols,Math.min(r,o.rows-1));e.setCellSelection(i,i[0]??null,ze(i))}n.applyTransform([e],()=>({}),"modified")}var vy=n=>n.kind==="col-strip"?{kind:"col",index:n.col}:{kind:"row",index:n.row},wy=(n,e,t)=>{let r=n.raw,{x:o,y:i}=n.dims;if(!o||!i)return null;let s=Math.max(Math.abs(r.scaleX??1)||1,1e-4),a=Math.max(Math.abs(r.scaleY??1)||1,1e-4),l=n.localPoint(t.x,t.y),u=o/2,c=i/2,h,d;e==="tl"?(h=(l.x+u)*s,d=(l.y+c)*a):e==="tr"?(h=(u-l.x)*s,d=(l.y+c)*a):e==="bl"?(h=(l.x+u)*s,d=(c-l.y)*a):(h=(u-l.x)*s,d=(c-l.y)*a);let f=Id(n),m=Math.max(0,Math.min(f,rc(Math.min(h,d),f))),p=r.radius??0;return Math.abs(m-p)<.001?null:m},Ty=(n,e,t)=>{let r=n.raw,{x:o,y:i}=n.dims;if(!o||!i)return null;let s=n.localPoint(t.x,t.y),a=o/2,l=i/2,u,c;e==="tl"?(u=s.x+a,c=s.y+l):e==="tr"?(u=a-s.x,c=s.y+l):e==="bl"?(u=s.x+a,c=l-s.y):(u=a-s.x,c=l-s.y);let h=Math.min(a,l),d=Math.max(0,Math.min(h,rc(Math.min(u,c),h))),f=Math.max(r.rx??0,r.ry??0);if(Math.abs(d-f)<.001)return null;let m={rx:d,ry:d};return d>0&&r.perPixelTargetFind===!1&&(m.perPixelTargetFind=!0),m},xc=(n,e)=>n<Cs?"vertical":e<Cs?"horizontal":null,Bo=n=>`url("data:image/svg+xml,<svg height='20' width='20' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'><g fill='none' transform='rotate(${n} 16 16)'><path fill='white' d='M18.24 5.37C11.41 6.04 5.98 11.46 5.32 18.26L0 18.26L7.8 26L15.61 18.27L10.6 18.27C11.21 14.35 14.31 11.25 18.24 10.64L18.24 15.55L26 7.78L18.24 0L18.24 5.37Z'></path><path fill='black' d='M19.5463 6.61441C12.4063 6.68441 6.61632 12.4444 6.56632 19.5644L3.17632 19.5644L7.80632 24.1444L12.4363 19.5644L9.18632 19.5644C9.24632 13.8844 13.8563 9.28441 19.5463 9.22441L19.5463 12.3844L24.1463 7.78441L19.5463 3.16441L19.5463 6.61441Z'></path></g></svg>") 12 12,auto`,We=n=>{let e=new Map;for(let t of n)e.set(t,t.toObject());return e},Ns=class{host;el;gesture={type:"none"};performed=!1;hoveredTable=null;deferredClickSwitch=null;detach=null;interactive;constructor(e,t,r=!0){this.el=e,this.host=t,this.interactive=r,this.attach()}get active(){return this.gesture.type!=="none"}hitHandle(e,t){let r=et(this.host.document);if(!r||this.host.document.selection.length===1&&at(this.host.document.selection[0]))return null;for(let o of _o(this.host.document,r.quad,r.angle,this.host.zoom,Do(this.host.document))){let i=this.host.toScreen(o.x,o.y);if(Math.hypot(i.x-e,i.y-t)<=ir)return o.id}return null}hitActiveChildHandle(e,t){let r=this.host.document,o=r.activeGroupChild;if(!o||!r.groupEditing)return null;for(let i of sc(o,this.host.zoom)){let s=this.host.toScreen(i.x,i.y);if(Math.hypot(s.x-e,s.y-t)<=ir)return i.id}return null}hitLockControl(e,t){let r=this.host.document;if(r.selection.length!==1||!at(r.selection[0]))return null;let o=et(r);if(!o)return null;let i=this.host.toScreen(o.quad.br.x,o.quad.br.y);return Math.hypot(i.x-e,i.y-t)<=ir?r.selection[0]:null}hitMoveControl(e,t){if(this.host.mobileControls!==!0||!ec(this.host.document))return!1;let r=et(this.host.document);if(!r)return!1;let o=tc(r.quad,r.angle,this.host.zoom),i=this.host.toScreen(o.x,o.y);return Math.hypot(i.x-e,i.y-t)<=Ad}hitCornerRotateZone(e,t){let r=this.host.document;if(r.selection.length!==1)return null;let o=r.selection[0];if(o instanceof te||at(o))return null;let i=et(r);if(!i)return null;let s=i.angle*Math.PI/180,a=Math.cos(s),l=Math.sin(s),u=_d/2;for(let c of Bd(i.quad,i.angle,this.host.zoom)){let h=this.host.toScreen(c.x,c.y),d=e-h.x,f=t-h.y,m=d*a+f*l,p=-d*l+f*a;if(Math.abs(m)<=u&&Math.abs(p)<=u)return c.id}return null}freezeRotateHandle(e,t,r=!1){this.host.rotateDrag!==void 0&&(this.host.rotateDrag=r?{spec:Ss(e),center:{x:t.x,y:t.y},onChild:!0}:{spec:Ss(e),center:{x:t.x,y:t.y}})}hoverCursor(e,t,r){let o=this.host.document;if(this.host.rulerVisible){let p=xc(e,t);if(p)return p==="horizontal"?"ns-resize":"ew-resize"}let i=this.host.cropSession;if(i)return i.hoverCursor(e,t,r);let s=this.host.expandSession;if(s)return s.hoverCursor(e,t,r.x,r.y);let a=this.host.pathSession;if(a)return a.hoverCursor(e,t,r);let l=this.host.warpSession;if(l)return l.hoverCursor(e,t);let u=o.selection.length===1&&o.selection[0]instanceof le?o.selection[0]:null;if(u?.editingMask){let p=As((g,x)=>this.host.toScreen(g,x),u,e,t);if(p)return or[p]==="x"?"ew-resize":"ns-resize";let b=Oo((g,x)=>this.host.toScreen(g,x),u,e,t);if(b)return or[b.handle]==="x"?"ew-resize":"ns-resize"}else if(u){let p=Oo((b,g)=>this.host.toScreen(b,g),u,e,t);if(p)return or[p.handle]==="x"?"ew-resize":"ns-resize"}let c=o.selection.length===1&&o.selection[0]instanceof te?o.selection[0]:null;if(c&&!o.findTarget(r.x,r.y)){let p=c.borderOrIndicatorHit(r.x,r.y,this.host.zoom);if(p?.inCircle)return this.updateTableHover(c,p,!1),"pointer";let b=c.stripHit(r.x,r.y,this.host.zoom);if(b)return this.updateTableHover(c,null,!1,{strip:vy(b)}),"pointer";if(c.dragHandleHit(r.x,r.y,this.host.zoom))return this.updateTableHover(c,null,!1,{dragHandle:!0}),"move"}if(c&&o.findTarget(r.x,r.y)===c&&c.rangeHandleHit(r.x,r.y,this.host.zoom))return this.updateTableHover(c,null,!0,{rangeHandle:!0}),"crosshair";if(this.hitLockControl(e,t))return"pointer";let h=this.hitActiveChildHandle(e,t);if(h==="mtr"){let p=o.activeGroupChild;return Bo(p.worldAngle+225)}if(h){let p=o.activeGroupChild,b=uc[h];if(typeof b=="number"){let g=b+p.worldAngle;return hc[(Math.round(g/45)%4+4)%4]}}if(this.hitMoveControl(e,t))return"move";let d=this.hitHandle(e,t);if(d==="mtr")return Bo((et(o)?.angle??0)+225);if(d&&Fr(d))return d==="tlS"||d==="brS"?"nwse-resize":"nesw-resize";if(d){let p=uc[d]+(et(o)?.angle??0);return hc[(Math.round(p/45)%4+4)%4]}let f=this.hitCornerRotateZone(e,t);if(f)return Bo((et(o)?.angle??0)+oc[f]);let m=o.findTarget(r.x,r.y);if(m&&m===o.editingNode)return"text";if(m instanceof te){let p=m.borderOrIndicatorHit(r.x,r.y,this.host.zoom),b="move";return p?.inCircle?b="pointer":p?.border&&o.selection.includes(m)&&(b=ld(m.tableAngle,p.border.type)),this.updateTableHover(m,p,!0),b}if(this.updateTableHover(null,null,!1),!this.host.cropSession&&!this.host.expandSession&&!this.host.pathSession&&!this.host.warpSession){let p=o.nodes.findLast(b=>Ze(b)&&b.visible&&b.raw.visible!==!1&&b.containsPoint(r.x,r.y));if(p)return Hl(p)?"not-allowed":p.dims.y===0?"ns-resize":"ew-resize"}return m?"move":""}updateTableHover(e,t,r,o={}){if(this.hoveredTable&&this.hoveredTable!==e&&(this.hoveredTable.clearHoverState(),this.hoveredTable=null,this.host.requestRenderAll()),!e)return;let i=e.hoveredBorder,s=e.hoveredIndicator,a=e.indicatorVisible,l=e.hoveredStrip,u=e.hoveredDragHandle,c=e.hoveredRangeHandle;e.hoveredBorder=t&&!t.inCircle?t.border:null,e.hoveredIndicator=t?.inCircle?t.border:null,e.indicatorVisible=r||!!t,e.hoveredStrip=o.strip??null,e.hoveredDragHandle=o.dragHandle??!1,e.hoveredRangeHandle=o.rangeHandle??!1,this.hoveredTable=e;let h=l?.kind!==e.hoveredStrip?.kind||l?.index!==e.hoveredStrip?.index;(i!==e.hoveredBorder||s!==e.hoveredIndicator||a!==e.indicatorVisible||h||u!==e.hoveredDragHandle||c!==e.hoveredRangeHandle)&&this.host.requestRenderAll()}updateHover(e,t,r){let o=this.host.document,i=null,s=null,a=o.nodes.find(d=>d instanceof le&&d.editingMask)??null,l=!!this.host.cropSession||!!this.host.expandSession||!!this.host.pathSession||!!this.host.warpSession||!!a,u=!this.hitHandle(e,t)&&!this.hitMoveControl(e,t);if(!l&&u){let d=o.findTarget(r.x,r.y);if(d instanceof J&&!(d instanceof te)&&!(d instanceof le)){let f=o.activeGroupChild;if(!(f!==null&&o.selection.length===1&&o.selection[0]===d))o.selection.includes(d)||(i=d);else{let p=Dr(d,r.x,r.y,o.selection);i=p&&p!==f?p:null}}else d&&!o.selection.includes(d)&&(i=d)}if(i&&i===o.editingNode&&(i=null),u&&!(a&&As((d,f)=>this.host.toScreen(d,f),a,e,t))){let d=o.selection.length===1&&o.selection[0]instanceof le?o.selection[0]:null;if(d){let f=Oo((m,p)=>this.host.toScreen(m,p),d,e,t);f&&(s={puzzle:d,mask:f.mask,handle:f.handle})}}let c=o.hovered;o.setHovered(i);let h=o.seamHover;o.setSeamHover(s),(o.hovered!==c||o.seamHover!==h)&&this.host.requestRenderAll()}isPointerOverCanvas(e){return!e||!(e instanceof Node)?!0:this.el.contains(e)}attach(){if(!this.interactive)return;let e=this.el,t=s=>{if(s.button!==0||this.host.interactionSuspended)return;this.host.document.editingNode&&s.preventDefault();let a=e.getBoundingClientRect(),l=s.clientX-a.left,u=s.clientY-a.top;this.onPointerDown(l,u,s.shiftKey)},r=s=>{if(this.host.interactionSuspended&&this.gesture.type==="none"||this.host.panning||this.gesture.type==="none"&&!this.isPointerOverCanvas(s.target))return;let a=e.getBoundingClientRect();this.onPointerMove(s.clientX-a.left,s.clientY-a.top)},o=s=>{if(this.host.interactionSuspended&&this.gesture.type==="none")return;let a=e.getBoundingClientRect();this.onPointerUp(s.clientX-a.left,s.clientY-a.top)},i=()=>{let s=this.host.document,a=s.hovered;s.setHovered(null),this.el.style.cursor="",s.hovered!==a&&this.host.requestRenderAll()};e.addEventListener("pointerdown",t),window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),e.addEventListener("pointerleave",i),this.detach=()=>{e.removeEventListener("pointerdown",t),window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),e.removeEventListener("pointerleave",i)}}onPointerDown(e,t,r){let o=this.host.document,i=this.host.toScene(e,t);this.performed=!1,this.deferredClickSwitch=null,o.setHovered(null);let s=this.host.cropSession;if(s){let y=s.hitHandle(e,t);y?this.gesture={type:"crop-handle",handle:y}:s.hitRect(i.x,i.y)?this.gesture={type:"crop-move",last:i}:s.exitByOutsideClick(),this.host.requestRenderAll();return}let a=this.host.expandSession;if(a){let y=a.hitHandle(e,t);y?this.gesture={type:"expand-handle",handle:y}:a.hitRect(i.x,i.y)?this.gesture={type:"expand-image-drag",last:i}:a.exitByOutsideClick(),this.host.requestRenderAll();return}let l=this.host.pathSession;if(l){let y=l.hitAnchor(e,t);if(y&&l.startAnchorDrag(y)){this.gesture={type:"path-anchor-drag",key:y},this.host.requestRenderAll();return}let v=l.findInsertCandidate(i.x,i.y);if(v){let R=l.insertAnchor(v);if(R){this.gesture={type:"path-anchor-drag",key:R},this.host.requestRenderAll();return}}if(l.hitBody(i.x,i.y)){this.gesture={type:"path-body-drag",last:i},this.host.requestRenderAll();return}l.exitByOutsideClick()}let u=this.host.warpSession;if(u){let y=u.hitAnchor(e,t);y&&(this.gesture={type:"warp-anchor-drag",anchor:y},u.applyAnchorDrag(y,i)),this.host.requestRenderAll();return}if(this.host.rulerVisible){let y=xc(e,t);if(y){let v=xd(y,y==="horizontal"?i.y:i.x),R=Ct(v);R&&(o.add(R),o.clearSelection(),this.gesture={type:"reference-line",node:R,axis:y,creating:!0,historyBefore:We([R])}),this.host.requestRenderAll();return}}let c=o.editingNode,h=!1;if(c){if(c.containsPoint(i.x,i.y)){let y=c.localPoint(i.x,i.y),v=c.cursorIndexAt(y.x,y.y);this.host.setEditingSelection(v,v),this.gesture={type:"text-select",anchorIdx:v};return}o.exitEditing(),h=!0}if(!h&&o.selection.length===1&&o.selection[0]instanceof te){let y=o.selection[0],v=o.findTarget(i.x,i.y)?null:y.borderOrIndicatorHit(i.x,i.y,this.host.zoom);if(v?.inCircle){this.gesture={type:"table-indicator-click",node:y,border:v.border};return}let R=o.findTarget(i.x,i.y)?null:y.stripHit(i.x,i.y,this.host.zoom);if(R){this.gesture=R.kind==="col-strip"?{type:"table-strip-click",node:y,kind:"col",index:R.col}:{type:"table-strip-click",node:y,kind:"row",index:R.row};return}}if(!h&&o.selection.length===1&&o.selection[0]instanceof te){let y=o.selection[0];if(o.findTarget(i.x,i.y)===y&&y.rangeHandleHit(i.x,i.y,this.host.zoom)){let v=y.expandedCellRange;if(v){this.gesture={type:"table-range-drag",node:y,anchor:{row:v.r1,col:v.c1}};return}}}let d=h?null:o.nodes.find(y=>y instanceof le&&y.editingMask)??null,f=!!d;if(f&&d){let y=As((v,R)=>this.host.toScreen(v,R),d,e,t);if(y&&d.editingMask){let v=gc(d,d.editingMask,y);v&&(this.gesture=v);return}}{let y=o.selection.length===1&&o.selection[0]instanceof le?o.selection[0]:null;if(y){let v=Oo((R,P)=>this.host.toScreen(R,P),y,e,t);if(v){let R=gc(y,v.mask,v.handle);R&&(this.gesture=R);return}}}let m=h?null:this.hitLockControl(e,t);if(m){this.host.document.events.fire("lock:unlock-requested",m);return}let p=!f||d!=null&&o.selection.length===1&&o.selection[0]===d;if(p&&!h){let y=this.hitActiveChildHandle(e,t),v=o.activeGroupChild,R=o.selection.length===1?o.selection[0]:null;if(y&&v&&R instanceof J&&!(R instanceof te)&&!(R instanceof le)){let P=is(R,v);if(P.length){let T=[v,...P,...P.flatMap(C=>C.children)];if(y==="mtr"){let C=v.aCoords,E={x:(C.tl.x+C.br.x)/2,y:(C.tl.y+C.br.y)/2};this.freezeRotateHandle(v.raw.angle??0,E,!0),this.gesture={type:"rotate",center:E,startAngle:Math.atan2(i.y-E.y,i.x-E.x),snapshot:{node:v,angle0:v.raw.angle??0},cursorOffset:225,childTransform:{child:v,shells:P,pivotLocal:{...v.center}},historyBefore:We(T)}}else if(!Fr(y))this.gesture={type:"scale",handle:y,snapshot:bc(v,y,o),freeScale:r&&Tn.has(y),childTransform:{child:v,shells:P},historyBefore:We(T)};else return;this.host.requestRenderAll();return}}}if(!h&&p&&this.hitMoveControl(e,t)){let y=o.selection[0],v=new Map;v.set(y,{left:y.raw.left??0,top:y.raw.top??0}),this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:v,historyBefore:We([y])},this.host.requestRenderAll();return}let b=h||!p?null:this.hitHandle(e,t);if(b){if(o.selection.length===1){let y=o.selection[0];if(b==="mtr"){let v=y.center;this.freezeRotateHandle(y.raw.angle??0,v),this.gesture={type:"rotate",center:v,startAngle:Math.atan2(i.y-v.y,i.x-v.x),snapshot:{node:y,angle0:y.raw.angle??0},cursorOffset:225,historyBefore:We([y])}}else if(Fr(b)&&(ys(y)||Io(y)))this.gesture={type:"cornerRadius",node:y,corner:No[b],model:Io(y)?"image":"rect",historyBefore:We([y])};else if(y instanceof te&&En(b)){let v=yf(y,b);v.historyBefore=We([y]),this.gesture=v}else if(y instanceof le&&En(b)){let v=Sf(y,b);v.historyBefore=We([y]),this.gesture=v}else this.gesture={type:"scale",handle:b,snapshot:bc(y,b,o),freeScale:r&&Tn.has(b),historyBefore:We([y])}}else{let y=et(o),v=o.selection.filter(R=>!at(R));if(b==="mtr"){let R=Rs(y.quad);v.length&&this.freezeRotateHandle(y.angle,R),this.gesture={type:"multi-rotate",center:R,startAngle:Math.atan2(i.y-R.y,i.x-R.x),frameAngle0:y.angle,frame:Ps(y.quad),snapshot:{members:v.map(P=>({node:P,angle0:P.raw.angle??0,center0:{...P.center}}))},historyBefore:We(o.selection)}}else this.gesture={type:"multi-scale",snapshot:df(v,b,y),freeScale:r&&Tn.has(b),historyBefore:We(o.selection)}}return}let g=h||!p?null:this.hitCornerRotateZone(e,t);if(g){let y=o.selection[0],v=y.center;this.host.rotateDrag!==void 0&&(this.host.rotateDrag={spec:null,center:{x:v.x,y:v.y}}),this.gesture={type:"rotate",center:v,startAngle:Math.atan2(i.y-v.y,i.x-v.x),snapshot:{node:y,angle0:y.raw.angle??0},cursorOffset:oc[g],historyBefore:We([y])};return}if(!h&&o.selection.length===1&&o.selection[0]instanceof te){let y=o.selection[0];if(!o.findTarget(i.x,i.y)&&y.dragHandleHit(i.x,i.y,this.host.zoom)){let v=new Map;for(let R of o.selection)v.set(R,{left:R.raw.left??0,top:R.raw.top??0});this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:v,historyBefore:We(o.selection)},this.host.requestRenderAll();return}}if(!r){let y=o.nodes.findLast(v=>Ze(v)&&v.visible&&v.raw.visible!==!1&&v.containsPoint(i.x,i.y));if(y){o.setSelection([y],"create"),Hl(y)||(this.gesture={type:"reference-line",node:y,axis:y.dims.y===0?"horizontal":"vertical",creating:!1,historyBefore:We([y])}),this.host.requestRenderAll();return}}let x=o.findTarget(i.x,i.y),S=x instanceof te?x:null;if(S){let y=S.borderOrIndicatorHit(i.x,i.y,this.host.zoom);if(y?.inCircle){this.gesture={type:"table-indicator-click",node:S,border:y.border};return}let v=S.borderHit(i.x,i.y);if(v&&o.selection.includes(S)){let P=gf(S,v,i);P.historyBefore=We([S]),this.gesture=P;return}let R=S.cellHit(i.x,i.y);if(R){o.selection.includes(S)?!r&&o.selection.length>1&&(this.deferredClickSwitch=S):o.setSelection([S],"create");let P=new Map;for(let T of o.selection)at(T)||P.set(T,{left:T.raw.left??0,top:T.raw.top??0});this.gesture={type:"table-cell-click",node:S,start:i,anchorCell:R,shift:r,moveSnapshot:P,frame0:o.selection.length>1&&o.selectionFrame?{...o.selectionFrame}:void 0,historyBefore:We(o.selection)},this.host.requestRenderAll();return}}if(f&&d){if(x===d){let y=d.maskChildren.find(v=>v.visible&&v.containsPoint(i.x,i.y));if(y){y!==d.editingMask&&(d.editingMask=y),o.setActiveGroupChild(y);let v=new Map;for(let R of o.selection)at(R)||v.set(R,{left:R.raw.left??0,top:R.raw.top??0});this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:v,frame0:void 0,historyBefore:We(o.selection)}}else d.exitMaskEditing(),o.setActiveGroupChild(null);this.host.requestRenderAll();return}d.exitMaskEditing(),this.host.requestRenderAll()}let w=x instanceof te?null:x;if(w){let y=o.selection.includes(w),v=o.groupEditing;if(r){let R=(o.selection.includes(w)?o.selection.filter(P=>P!==w):[...o.selection,w]).filter(P=>!at(P));o.setSelection(R,"update")}else o.selection.includes(w)?o.selection.length>1&&(this.deferredClickSwitch=w):o.setSelection([w],"create");if(w instanceof J&&!(w instanceof te)&&!(w instanceof le))o.setActiveGroupChild(Dr(w,i.x,i.y,o.selection));else if(w instanceof le&&y&&o.selection.length===1){let R=w.maskChildren.find(P=>P.visible&&P.containsPoint(i.x,i.y))??null;o.setActiveGroupChild(R),R?w.editingMask=R:w.exitMaskEditing()}else o.activeGroupChild&&o.setActiveGroupChild(null);if(o.selection.includes(w))if(at(w)&&y&&o.selection.length===1&&o.selection[0]===w)this.gesture={type:"marquee",anchor:i,additive:r,hold:!0};else{let R=o.activeGroupChild,P=v&&R&&w instanceof J&&!(w instanceof te)&&!(w instanceof le)&&o.selection.length===1&&o.selection[0]===w?is(w,R):[],T=P.length&&R?{child:R,toLocal:Cd(R),shells:P}:null;if(T){let C=new Map;C.set(T.child,{left:T.child.raw.left??0,top:T.child.raw.top??0});let E=[T.child,...T.shells,...T.shells.flatMap(M=>M.children)];this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:C,childMove:T,historyBefore:We(E)}}else{let C=new Map;for(let E of o.selection)at(E)||C.set(E,{left:E.raw.left??0,top:E.raw.top??0});this.gesture={type:"move",start:i,startCss:{x:e,y:t},snapshot:C,frame0:o.selection.length>1&&o.selectionFrame?{...o.selectionFrame}:void 0,historyBefore:We(o.selection)}}}this.host.requestRenderAll();return}this.gesture={type:"marquee",anchor:i,additive:r},r||o.clearSelection(),this.host.requestRenderAll()}onPointerMove(e,t){let r=this.host.document,o=this.host.toScene(e,t),i=this.gesture;if(i.type==="none"){this.el.style.cursor=this.hoverCursor(e,t,o),this.updateHover(e,t,o);return}if(i.type==="move"){if(i.snapshot.size){if(!this.performed&&Math.hypot(e-i.startCss.x,t-i.startCss.y)<=of)return;this.performed=!0;let s=o.x-i.start.x,a=o.y-i.start.y;if(i.childMove){let l=i.childMove.toLocal(s,a);r.applyTransform([...i.snapshot.keys()],u=>{let c=i.snapshot.get(u);return{left:c.left+l.x,top:c.top+l.y}},"moving")}else r.applyTransform([...i.snapshot.keys()],l=>{let u=i.snapshot.get(l);return{left:u.left+s,top:u.top+a}},"moving"),i.frame0&&r.setSelectionFrame({...i.frame0,center:{x:i.frame0.center.x+s,y:i.frame0.center.y+a}})}}else if(i.type==="reference-line"){this.performed=!0;let s=i.axis==="horizontal";r.applyTransform([i.node],()=>({visible:!0,...s?{top:o.y}:{left:o.x}}),"moving"),this.host.referenceLineDrag!==void 0&&(this.host.referenceLineDrag={axis:i.axis,position:s?o.y:o.x})}else if(i.type==="scale")this.performed=!0,hf(r,i.snapshot,o,i.freeScale),r.applyTransform([i.snapshot.node],()=>({}),"scaling"),!i.snapshot.bakeFont&&!i.snapshot.bakeWidth&&!i.snapshot.bakeHeight&&!i.snapshot.bakeGroup&&this.host.registerScalingSnap?.(i.snapshot.node,i.handle);else if(i.type==="cornerRadius")if(i.model==="image"){let s=Ty(i.node,i.corner,o);s&&(this.performed=!0,r.applyTransform([i.node],()=>s,"cornerRadius"))}else{let s=wy(i.node,i.corner,o);s!==null&&(this.performed=!0,r.applyTransform([i.node],()=>({radius:s}),"cornerRadius"))}else if(i.type==="multi-scale")i.snapshot.members.length&&(this.performed=!0,ff(r,i.snapshot,o,i.freeScale),this.host.registerScalingSnap?.(r.selection[0],i.snapshot.handle));else if(i.type==="rotate"){this.performed=!0;let s=Math.atan2(o.y-i.center.y,o.x-i.center.x),a=i.snapshot.angle0+Ms(s-i.startAngle);a=(a%360+360)%360;let l=i.childTransform?.pivotLocal??i.center;r.applyTransform([i.snapshot.node],u=>u.rotateAroundCenter(a,l),"rotating"),this.el.style.cursor=Bo((i.snapshot.node.raw.angle??0)+(i.cursorOffset??225))}else if(i.type==="multi-rotate")i.snapshot.members.length&&(this.performed=!0,mf(r,i,o),this.el.style.cursor=Bo((r.selectionFrame?.angle??0)+225));else if(i.type==="marquee"){if(i.hold&&Math.hypot(o.x-i.anchor.x,o.y-i.anchor.y)<=ks)return;this.host.marquee={left:i.anchor.x,top:i.anchor.y,right:o.x,bottom:o.y};let s=r.objectsIntersectingRect(i.anchor.x,i.anchor.y,o.x,o.y).filter(l=>!at(l)),a=(i.additive?[...new Set([...r.selection,...s])]:s).filter(l=>!at(l));r.setSelection(a,"update")}else if(i.type==="text-select"){let s=r.editingNode;if(s){let a=s.localPoint(o.x,o.y),l=s.cursorIndexAt(a.x,a.y);this.host.setEditingSelection(Math.min(i.anchorIdx,l),Math.max(i.anchorIdx,l))}}else if(i.type==="table-border-drag")this.performed=!0,xf(i,o);else if(i.type==="table-edge-resize")this.performed=!0,Tf(r,i,o);else if(i.type==="puzzle-edge-resize")this.performed=!0,wf(r,i,o);else if(i.type==="puzzle-mask-edge-resize")this.performed=!0,vf(i,o);else if(i.type==="crop-handle")this.performed=!0,this.host.cropSession?.applyHandle(i.handle,o);else if(i.type==="expand-handle")this.performed=!0,this.host.expandSession?.applyHandle(i.handle,o);else if(i.type==="expand-image-drag")this.performed=!0,this.host.expandSession?.moveImageBy({x:o.x-i.last.x,y:o.y-i.last.y}),i.last=o;else if(i.type==="crop-move")this.performed=!0,this.host.cropSession?.moveImageBy({x:o.x-i.last.x,y:o.y-i.last.y}),i.last=o;else if(i.type==="path-anchor-drag")this.performed=!0,this.host.pathSession?.applyAnchorDrag(i.key,o);else if(i.type==="path-body-drag")this.performed=!0,this.host.pathSession?.moveBodyBy({x:o.x-i.last.x,y:o.y-i.last.y}),i.last=o;else if(i.type==="warp-anchor-drag")this.performed=!0,this.host.warpSession?.applyAnchorDrag(i.anchor,o);else if(i.type==="table-range-drag"){let s=i.node.cellHit(o.x,o.y);if(s){let a=xn(i.node.cellMap,i.anchor,s);i.node.setCellSelection(a,i.anchor,ze(a))}}else if(i.type==="table-cell-click"){if(i.shift){let s=i.node.cellHit(o.x,o.y),a=i.node.cellAnchor??i.anchorCell;if(s&&a){let l=xn(i.node.cellMap,a,s);i.node.setCellSelection(l,a,ze(l))}}else if(Math.hypot(o.x-i.start.x,o.y-i.start.y)>ks)return this.deferredClickSwitch=null,this.gesture={type:"move",start:i.start,startCss:{x:e,y:t},snapshot:i.moveSnapshot,frame0:i.frame0,historyBefore:i.historyBefore},this.onPointerMove(e,t)}this.host.requestRenderAll()}onPointerUp(e,t){let r=this.host.document,o=this.gesture;if(this.gesture={type:"none"},this.host.marquee=null,this.host.rotateDrag!==void 0&&(this.host.rotateDrag=null),o.type!=="none"){if(this.host.settleMoveSnap?.(),this.host.finishSnapGesture?.(),o.type==="move"){if(this.performed)if(o.childMove){let i=ss(o.childMove.shells),s=[...new Set([o.childMove.child,...i])];r.applyTransform(s,()=>({}),"modified",{action:Le.drag,before:o.historyBefore})}else r.applyTransform([...o.snapshot.keys()],()=>({}),"modified",{action:Le.drag,before:o.historyBefore});else if(this.deferredClickSwitch){let i=this.deferredClickSwitch;r.selection.length>1&&r.selection.includes(i)&&r.setSelection([i],"create")}}else if(o.type==="reference-line")this.host.referenceLineDrag!==void 0&&(this.host.referenceLineDrag=null),(this.host.rulerVisible?xc(e,t):null)===o.axis||o.creating&&!this.performed?(r.remove(o.node),r.fireObjectModified([o.node],{action:Le.drag,before:o.historyBefore?[o.historyBefore.get(o.node)].filter(s=>!!s):void 0})):this.performed&&r.applyTransform([o.node],()=>({selectable:!1}),"modified",{action:Le.drag,before:o.historyBefore});else if(o.type==="scale"||o.type==="rotate"){if(this.performed)if(o.childTransform){let i=ss(o.childTransform.shells),s=[...new Set([o.childTransform.child,...i])];r.applyTransform(s,()=>({}),"modified",{action:o.type,before:o.historyBefore})}else r.applyTransform([o.snapshot.node],()=>({}),"modified",{action:o.type,before:o.historyBefore})}else if(o.type==="cornerRadius")this.performed&&r.applyTransform([o.node],()=>({}),"modified",{action:Le.cornerRadius,before:o.historyBefore});else if(o.type==="multi-scale"||o.type==="multi-rotate")this.performed&&r.applyTransform(o.snapshot.members.map(i=>i.node),()=>({}),"modified",{action:o.type==="multi-scale"?Le.scale:Le.rotate,before:o.historyBefore});else if(o.type==="marquee")r.commitGeometry();else if(o.type==="path-anchor-drag"||o.type==="path-body-drag")this.performed&&this.host.pathSession?.commit();else if(o.type==="warp-anchor-drag")this.performed&&this.host.warpSession?.endDrag();else if(o.type==="table-border-drag")o.node.setCellSelection(o.savedCells,o.savedAnchor,o.savedRange),o.node.hoveredBorder=null,o.node.borderDragging=!1,this.performed&&(o.node.rebuildTable(),r.applyTransform([o.node],()=>({}),"modified",{action:Le.scale,before:o.historyBefore}));else if(o.type==="table-edge-resize")this.performed&&r.applyTransform([o.node],()=>({}),"modified",{action:Le.scale,before:o.historyBefore});else if(o.type==="puzzle-edge-resize")this.performed&&r.applyTransform([o.node],()=>({}),"modified",{action:Le.scale,before:o.historyBefore});else if(o.type==="puzzle-mask-edge-resize")this.performed&&r.applyTransform([o.node],()=>({}),"modified",{action:Le.scale,before:o.historyBefore});else if(o.type==="table-indicator-click"){let i=this.host.toScene(e,t),s=o.node.borderOrIndicatorHit(i.x,i.y,this.host.zoom);s?.inCircle&&Ef(r,o.node,s.border)}else if(o.type==="table-strip-click"){let i=this.host.toScene(e,t),s=o.node.stripHit(i.x,i.y,this.host.zoom);s?.kind==="col-strip"?o.node.setColumnSelection(s.col):s?.kind==="row-strip"&&o.node.setRowSelection(s.row)}else if(o.type==="table-cell-click"){let i=this.host.toScene(e,t);if(Math.hypot(i.x-o.start.x,i.y-o.start.y)<=ks)if(this.deferredClickSwitch===o.node)r.selection.length>1&&r.selection.includes(o.node)&&r.setSelection([o.node],"create");else{let s=o.node.cellHit(i.x,i.y);if(s)if(o.shift){let a=o.node.cellAnchor??o.anchorCell??s,l=xn(o.node.cellMap,a,s);o.node.setCellSelection(l,a,ze(l))}else o.node.setCellSelection([s],s,{r1:s.row,r2:s.row,c1:s.col,c2:s.col})}}this.deferredClickSwitch=null,this.host.requestRenderAll()}}dispose(){this.detach?.(),this.detach=null}};var Ey=new Set(["qrcode","barcode"]),Cy=n=>{let e=n.raw.type;return typeof e=="string"&&Ey.has(e.toLowerCase())},Ls=class{host;onDblClick;disposed=!1;interactive;constructor(e,t=!0){this.host=e,this.interactive=t,this.onDblClick=r=>{if(e.interactionSuspended)return;let o=e.canvasEl.getBoundingClientRect(),i=e.toScene(r.clientX-o.left,r.clientY-o.top),s=e.document.findTarget(i.x,i.y);if(s instanceof J&&!(s instanceof te)&&!(s instanceof le)){let a=Dr(s,i.x,i.y,e.document.selection);a&&!(a instanceof te)&&!(a instanceof le)&&(s=a)}this.dispatch(s,i.x,i.y)},this.interactive&&e.canvasEl.addEventListener("dblclick",this.onDblClick)}dispatch(e,t,r){if(e instanceof te){let o=e.cellHit(t,r);o&&this.host.startCellEditing(e,o.row,o.col);return}if(e instanceof le){let o=e.maskChildren.find(i=>i.visible&&i.containsPoint(t,r));o&&(this.host.document.selection.includes(e)||this.host.document.setSelection([e],"create"),e.editingMask=o,this.host.document.setActiveGroupChild(o),this.host.requestRenderAll());return}if(e instanceof ye){this.host.enterTextEditingAtClick(e,t,r);return}if(e?.isImageType&&!Cy(e)){let o=this.host.document.events;e.raw.smartObject?o.fire("smartobject:open-requested",e):o.fire("image:replace-requested",e)}}dispose(){this.disposed||(this.disposed=!0,this.host.canvasEl.removeEventListener("dblclick",this.onDblClick))}};var Is=class n{host;onKeydown;offDocEvents;disposed=!1;constructor(e){this.host=e,this.onKeydown=i=>this.handleKey(i),window.addEventListener("keydown",this.onKeydown);let t=e.document.events,r=()=>this.pruneCellState(),o=[t.on("selection:created",r),t.on("selection:updated",r),t.on("selection:cleared",r)];this.offDocEvents=()=>o.forEach(i=>i())}dispose(){this.disposed||(this.disposed=!0,window.removeEventListener("keydown",this.onKeydown),this.offDocEvents())}pruneCellState(){let e=this.host.document;for(let t of e.nodes)t instanceof te&&!e.selection.includes(t)&&t.clearCellInteractionState()}get activeTable(){let e=this.host.document;if(e.editingNode||e.selection.length!==1)return null;let t=e.selection[0];return t instanceof te?t:null}static isTypingTarget(e){let t=e.target;return t instanceof HTMLElement?t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable:!1}handleKey(e){let t=this.activeTable;if(!t||n.isTypingTarget(e))return;let r=e.ctrlKey||e.metaKey,o=e.key;if(o==="Escape"){t.hasCellSelection&&(t.clearCellSelection(),this.host.requestRenderAll(),e.preventDefault());return}if(r&&!e.shiftKey&&o.toLowerCase()==="a"){let i=t.tableView,s=Mo(t.cellMap,i.rows,i.cols);t.setCellSelection(s,s[0]??null,ze(s)),this.host.requestRenderAll(),e.preventDefault();return}if(r&&o.toLowerCase()==="m"){e.shiftKey?this.unmergeFirst(t):this.mergeSelection(t);return}if(t.hasCellSelection&&!r&&!e.altKey&&o.length===1&&!/^(Enter|Escape|Tab|Delete|Backspace)$/.test(o)){let i=t.selectedCells[0];i&&(e.preventDefault(),this.host.startCellEditing(t,i.row,i.col,{initialText:o}));return}if(o==="Enter"&&t.hasCellSelection){let i=t.selectedCells[0];i&&(e.preventDefault(),this.host.startCellEditing(t,i.row,i.col));return}if(o==="Delete"||o==="Backspace"){this.deleteSelectionText(t);return}if(t.hasCellSelection&&(o==="ArrowUp"||o==="ArrowDown"||o==="ArrowLeft"||o==="ArrowRight")){let s={ArrowUp:{row:-1,col:0},ArrowDown:{row:1,col:0},ArrowLeft:{row:0,col:-1},ArrowRight:{row:0,col:1}}[o];this.navigate(t,s.row,s.col),e.preventDefault();return}o==="Tab"&&(this.navigate(t,0,e.shiftKey?-1:1,!0),e.preventDefault())}navigate(e,t,r,o=!1){let i=e.tableView,s=e.cellAnchor??e.selectedCells[0]??{row:0,col:0},a=s.row+t,l=s.col+r;o?(l>=i.cols?(l=0,a++):l<0&&(l=i.cols-1,a--),a>=i.rows?a=0:a<0&&(a=i.rows-1)):(a=Math.max(0,Math.min(i.rows-1,a)),l=Math.max(0,Math.min(i.cols-1,l)));let u=lt(e.cellMap,a,l);e.setCellSelection([u],u,{r1:u.row,r2:u.row,c1:u.col,c2:u.col}),this.host.requestRenderAll()}commit(e){e.rebuildTable(),this.host.document.applyTransform([e],()=>({}),"modified"),this.host.requestRenderAll()}mergeSelection(e){if(e.selectedCells.length<2)return;let t=ze(e.selectedCells);if(!t)return;let r=So(e.raw,t.r1,t.c1,t.r2,t.c2),o={row:r.r1,col:r.c1};e.setCellSelection([o],o,r),this.commit(e)}unmergeFirst(e){for(let t of e.selectedCells)if(vo(e.raw,t.row,t.col)){let r={row:t.row,col:t.col};e.setCellSelection([r],r,{r1:t.row,r2:t.row,c1:t.col,c2:t.col}),this.commit(e);return}}deleteSelectionText(e){let t=e.cellMap,r=!1;for(let o of e.selectedCells){let i=we(t,o.row,o.col);i&&!i.isMerged&&i.text&&(i.text="",r=!0)}r&&this.commit(e)}};var yc=(n,e,t)=>Math.max(e,Math.min(t,n)),_s={min:.05,max:5},Hr=60,My=n=>{let e=n.workspaceRect();if(e.width<=0||e.height<=0)return null;let t=n.viewportTransform,r=e.left*t[0]+t[4],o=e.top*t[0]+t[5],i=r+e.width*t[0],s=o+e.height*t[0],{width:a,height:l}=n.viewSize;return r<-1||o<-1||i>a+1||s>l+1?null:{x:(r+i)/2,y:(o+s)/2}},Cf=(n,e)=>{n.preventDefault();let{deltaX:t,deltaY:r,deltaMode:o,ctrlKey:i,metaKey:s,altKey:a,shiftKey:l}=n,u=o===1?16:o===2&&e.viewSize.height||1,c=o===0?t:t*u,h=o===0?r:r*u;if(i||s||a){let A=Math.abs(h)<10?h*2:h/3,O=e.viewportTransform[0],F=yc(O*(1-A/200),_s.min,_s.max),W=My(e)??e.cursorPoint(n);e.zoomAt(W.x,W.y,F/O);return}let d=o===0&&Math.abs(t)<=10&&Math.abs(r)<=10,f=yc(e.viewportTransform[0],.1,_s.max),m=Math.max(1,f)*1.25,p=20*m,b=A=>yc(A,-60,60),g=0,x=0;if(l||Math.abs(c)>Math.abs(h)){let A=c!==0?c:h;A!==0&&(g=d?-b(A)*m:A>0?-p:p)}else h!==0&&(x=d?-b(h)*m:h>0?-p:p);if(g===0&&x===0)return;let w=e.viewportTransform,{width:y,height:v}=e.viewSize,R=e.workspaceRect(),P=R.width*f,T=R.height*f,C=w[4],E=w[5],M=Hr-P;C+g<M&&(g=M-C),C+g>y-Hr&&(g=y-Hr-C);let k=Hr-T;E+x<k&&(x=k-E),E+x>v-Hr&&(x=v-Hr-E),!(g===0&&x===0)&&e.pan(g,x)};var Ds=class{constructor(e,t,r,o=!0){this.host=e;this.snapGuide=t;this.sources=r;this.interactive=o;let i=e.canvasEl;this.pointer=new Ns(i,e,this.interactive),this.tableInteraction=new Is(e);let s=p=>{if(p.key!=="Escape")return;let b=e.document.selection;b.length===1&&b[0]instanceof le&&b[0].editingMask&&(b[0].exitMaskEditing(),e.document.setActiveGroupChild(null),e.requestRenderAll())};this.interactive&&window.addEventListener("keydown",s);let a=e.document.events,l=()=>e.requestRenderAll(),u=[a.on("selection:created",l),a.on("selection:updated",l),a.on("selection:cleared",l),a.on("object:modified",l),a.on("object:moving",p=>this.snapGuide.registerMove(p)),a.on("object:removed",p=>{p instanceof ie&&this.sources.releaseAnimatedNode(p)})];this.offDocEvents=()=>u.forEach(p=>p()),this.dblClick=new Ls(e,this.interactive);let c=p=>{Cf(p,e)},h=p=>{if(p.button===1){p.preventDefault(),e.panning=!0,this.lastPanPointer={x:p.clientX,y:p.clientY},i.style.cursor="grab";try{i.setPointerCapture(p.pointerId)}catch{}}},d=p=>{if(!e.panning||!this.lastPanPointer)return;let b=p.clientX-this.lastPanPointer.x,g=p.clientY-this.lastPanPointer.y;this.lastPanPointer={x:p.clientX,y:p.clientY},e.pan(b,g),i.style.cursor="grab"},f=p=>{e.panning&&(e.panning=!1,this.lastPanPointer=null,i.hasPointerCapture(p.pointerId)&&i.releasePointerCapture(p.pointerId),i.style.cursor="default")},m=p=>e.handleFontsLoaded(p.fontfaces??[]);document.fonts?.addEventListener?.("loadingdone",m),this.interactive&&(i.addEventListener("wheel",c,{passive:!1}),i.addEventListener("pointerdown",h),window.addEventListener("pointermove",d),window.addEventListener("pointerup",f)),this.detachListeners=()=>{document.fonts?.removeEventListener?.("loadingdone",m),i.removeEventListener("wheel",c),i.removeEventListener("pointerdown",h),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",f),window.removeEventListener("keydown",s)}}host;snapGuide;sources;interactive;pointer;tableInteraction;dblClick;detachListeners=null;offDocEvents=null;lastPanPointer=null;get pointerActive(){return this.pointer.active}dispose(){this.detachListeners?.(),this.offDocEvents?.(),this.pointer.dispose(),this.dblClick.dispose(),this.tableInteraction.dispose()}};var Ry={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Ot=n=>typeof n=="string"?Ry[n]??0:n-.5,Sc=(n,e,t)=>{let r=Math.cos(e),o=Math.sin(e),i=n.x-t.x,s=n.y-t.y;return{x:t.x+r*i-o*s,y:t.y+o*i+r*s}},vc=n=>({x:n.width*n.scaleX,y:n.height*n.scaleY}),Fs=vc,Wo=n=>n*Math.PI/180,wc=(n,e,t,r,o,i=!1,s=!1)=>{let a=i?-1:1,l=s?-1:1,u={x:n.x+e*r.x*a,y:n.y+t*r.y*l};return o&&(u=Sc(u,Wo(o),n)),u},Tc=(n,e,t,r,o,i=!1,s=!1)=>{let a=i?-1:1,l=s?-1:1,u={x:n.x-e*r.x*a,y:n.y-t*r.y*l};return o&&(u=Sc(u,Wo(o),n)),u},Bs=(n,e,t,r,o)=>wc(n,Ot(e),Ot(t),r,o),Ho=(n,e,t,r,o,i)=>Tc({x:n,y:e},Ot(t),Ot(r),o,i),Gr=(n,e,t=0,r=0)=>{let o=Ho(n.left,n.top,n.originX,n.originY,Fs(n),n.angle),i=e;n.angle&&(i=Sc(i,-Wo(n.angle),o));let s=Fs(n),a=n.flipX?-1:1,l=n.flipY?-1:1;return{x:(i.x-o.x)*a-t*s.x,y:(i.y-o.y)*l-r*s.y}},Xr=(n,e,t,r)=>{let o=Fs(n),i=Ho(n.left,n.top,n.originX,n.originY,o,n.angle),s=wc(i,e,t,o,n.angle,n.flipX,n.flipY),a=r.scaleX??n.scaleX,l=r.scaleY??n.scaleY,u={x:r.width*a,y:r.height*l},c=Tc(s,e,t,u,n.angle,n.flipX,n.flipY),h=Bs(c,n.originX,n.originY,u,n.angle);return{...n,...r,scaleX:a,scaleY:l,left:h.x,top:h.y}},Py=(n,e)=>{let{width:t,cropX:r}=n,i=Gr(n,e).x/n.scaleX- -(t/2),s=t-i;if(r+i<0&&(i=-r,s=t+r),s<8){let a=Math.min(8,r+t);i=t-a,s=a}return Xr(n,.5,0,{width:s,height:n.height,cropX:r+i,cropY:n.cropY})};var ky=(n,e)=>{let{width:t,cropX:r}=n,o=Gr(n,e),i=t-(t/2-o.x/n.scaleX);return i+r>n.naturalWidth&&(i=n.naturalWidth-r),i<8&&(i=Math.min(8,n.naturalWidth-r)),Xr(n,-.5,0,{width:i,height:n.height,cropX:r,cropY:n.cropY})};var Ay=(n,e)=>{let{height:t,cropY:r}=n,i=Gr(n,e).y/n.scaleY- -(t/2),s=t-i;if(r+i<0&&(i=-r,s=t+r),s<8){let a=Math.min(8,r+t);i=t-a,s=a}return Xr(n,0,.5,{width:n.width,height:s,cropX:n.cropX,cropY:r+i})};var Ny=(n,e)=>{let{height:t,cropY:r}=n,o=Gr(n,e),i=t-(t/2-o.y/n.scaleY);return i+r>n.naturalHeight&&(i=n.naturalHeight-r),i<8&&(i=Math.min(8,n.naturalHeight-r)),Xr(n,0,-.5,{width:n.width,height:i,cropX:n.cropX,cropY:r})};var Os=(n,e,t)=>e==="left"||e==="right"?e==="left"?Py(n,t):ky(n,t):e==="top"?Ay(n,t):Ny(n,t),Mf=(n,e,t)=>{let r=e==="tl"||e==="bl"?"left":"right",o=e==="tl"||e==="tr"?"top":"bottom",i=Os(n,r,t);return Os(i,o,t)};var Rf=(n,e,t,r)=>{if(!(r>0)||!Number.isFinite(r))return null;let o=Gr(n,t),i=e==="tl"||e==="bl",s=e==="tl"||e==="tr",a=i?n.cropX+n.width:n.naturalWidth-n.cropX,l=s?n.cropY+n.height:n.naturalHeight-n.cropY,u=Math.min(a,l/r);if(!(u>0))return null;let c=Math.min(u,Math.max(8,8/r)),h=n.width/2+(i?-1:1)*o.x/n.scaleX,d=n.height/2+(s?-1:1)*o.y/n.scaleY,f=Math.max(c,Math.min(u,h,d/r)),m=f*r;return Xr(n,i?.5:-.5,s?.5:-.5,{width:f,height:m,cropX:i?n.cropX+n.width-f:n.cropX,cropY:s?n.cropY+n.height-m:n.cropY})},Pf=(n,e,t=!1)=>{if(!(e>0)||!Number.isFinite(e))return null;let r=t?n.scaleY*e/n.scaleX:e,o=n.width*n.scaleX/e,i=n.height*n.scaleY/r,s=n.cropX+(n.width-o)/2,a=n.cropY+(n.height-i)/2;return o<Math.min(8,n.naturalWidth)||i<Math.min(8,n.naturalHeight)||s<0||a<0||s+o>n.naturalWidth||a+i>n.naturalHeight?null:Xr(n,0,0,{width:o,height:i,cropX:s,cropY:a,scaleX:e,scaleY:r})},Ly=(n,e,t,r,o)=>{let i=Math.abs(n.x/t),s=Math.abs(n.y/e);return Math.min(i,s)},kf=(n,e,t)=>{if(n.width<=0||n.height<=0)return null;let{naturalWidth:r,naturalHeight:o}=n,i=r-n.width-n.cropX,s=o-n.height-n.cropY,a,l;e==="br"?(a=-n.cropX/n.width,l=-n.cropY/n.height):e==="tl"?(a=1+i/n.width,l=1+s/n.height):e==="tr"?(a=-n.cropX/n.width,l=1+s/n.height):(a=1+i/n.width,l=-n.cropY/n.height);let u=Gr(n,t,Ot(a),Ot(l)),c=Math.min(n.width*n.scaleX/Math.min(8,r),n.height*n.scaleY/Math.min(8,o)),h=Math.min(Ly(u,o,r,n.flipX,n.flipY),c);if(!(h>0)||!Number.isFinite(h))return null;let d=h/n.scaleX,f=h/n.scaleY,m=n.width/d,p=n.height/f,b=i/d,g=s/f,x,S;if(e==="br"){if(x=n.cropX/d,S=n.cropY/f,x+m>r||S+p>o)return null}else if(e==="tl"){if(x=r-m-b,S=o-p-g,m+b>r||p+g>o)return null}else if(e==="tr"){if(x=n.cropX/d,S=o-p-g,x+m>r||g+p>o)return null}else if(x=r-m-b,S=n.cropY/f,m+b>r||p+S>o)return null;let w,y;e==="br"?(w=-x/m,y=-S/p):e==="tl"?(w=1+b/m,y=1+g/p):e==="tr"?(w=-x/m,y=1+g/p):(w=1+b/m,y=-S/p);let v=Fs(n),R=Ho(n.left,n.top,n.originX,n.originY,v,n.angle),P=wc(R,Ot(a),Ot(l),v,n.angle,n.flipX,n.flipY),T={x:m*h,y:p*h},C=Tc(P,Ot(w),Ot(y),T,n.angle,n.flipX,n.flipY),E=Bs(C,n.originX,n.originY,T,n.angle);return{...n,width:m,height:p,cropX:x,cropY:S,scaleX:h,scaleY:h,left:E.x,top:E.y}},Af=(n,e)=>{let t=Math.cos(Wo(n.angle)),r=Math.sin(Wo(n.angle)),o=n.flipX?-1:1,i=n.flipY?-1:1,s=t*e.x+r*e.y,a=-r*e.x+t*e.y,l=-s/(o*n.scaleX),u=-a/(i*n.scaleY),c=n.cropX+l,h=n.cropY+u;return c<0?c=0:c+n.width>n.naturalWidth&&(c=n.naturalWidth-n.width),h<0?h=0:h+n.height>n.naturalHeight&&(h=n.naturalHeight-n.height),{cropX:c,cropY:h}},Nf=(n,e)=>{let t=n.naturalHeight/n.naturalWidth,r,o;t>e?(r=n.naturalWidth,o=n.naturalWidth*e):(o=n.naturalHeight,r=n.naturalHeight/e);let i=(n.naturalWidth-r)/2,s=(n.naturalHeight-o)/2;return{...n,width:r,height:o,cropX:i,cropY:s}},Lf=(n,e,t)=>{let r=n.cropSizeMode==="visible",o=n.cropX??0,i=n.cropY??0,s=n.width??e,a=n.height??t,l=r?s:s-o,u=r?a:a-i;return e>0&&t>0&&(l=Math.min(Math.max(l,0),e),u=Math.min(Math.max(u,0),t),o=Math.min(Math.max(o,0),e-l),i=Math.min(Math.max(i,0),t-u)),{left:n.left??0,top:n.top??0,angle:n.angle??0,originX:n.originX??"left",originY:n.originY??"top",flipX:n.flipX===!0,flipY:n.flipY===!0,width:l,height:u,cropX:o,cropY:i,scaleX:n.scaleX??1,scaleY:n.scaleY??1,naturalWidth:e,naturalHeight:t,cropSizeMode:n.cropSizeMode??"legacy"}},If=n=>{let e=n.cropSizeMode==="visible";return{left:n.left,top:n.top,width:e?n.width:n.width+n.cropX,height:e?n.height:n.height+n.cropY,cropX:n.cropX,cropY:n.cropY,scaleX:n.scaleX,scaleY:n.scaleY}},Jt={tl:{x:-.5,y:-.5},tr:{x:.5,y:-.5},bl:{x:-.5,y:.5},br:{x:.5,y:.5},left:{x:-.5,y:0},right:{x:.5,y:0},top:{x:0,y:-.5},bottom:{x:0,y:.5}},Go=(n,e)=>{let t=-n.width/2-n.cropX,r=-n.height/2-n.cropY,o=n.naturalWidth-n.width/2-n.cropX,i=n.naturalHeight-n.height/2-n.cropY;return e==="tl"?{x:t,y:r}:e==="tr"?{x:o,y:r}:e==="bl"?{x:t,y:i}:{x:o,y:i}};var _f=(n,e,t)=>({type:"Path",path:n.pathOf(e,t),originX:"center",originY:"center",left:0,top:0}),Ec=n=>{if(!(n.width>0)||!(n.height>0))return n;let e=n.naturalWidth>0?n.naturalWidth:n.width,t=n.naturalHeight>0?n.naturalHeight:n.height,r=Math.min(n.width,n.height,e,t);if(!(r>0))return n;let o=n.cropX+n.width/2,i=n.cropY+n.height/2,s=o-r/2,a=i-r/2;s<0?s=0:s+r>n.naturalWidth&&n.naturalWidth>0&&(s=Math.max(0,n.naturalWidth-r)),a<0?a=0:a+r>n.naturalHeight&&n.naturalHeight>0&&(a=Math.max(0,n.naturalHeight-r));let l=Ho(n.left,n.top,n.originX,n.originY,vc(n),n.angle),u=Bs(l,n.originX,n.originY,{x:r*n.scaleX,y:r*n.scaleY},n.angle);return{...n,width:r,height:r,cropX:s,cropY:a,left:u.x,top:u.y}};var Iy=(n,e)=>({w:e.naturalWidth||e.width||(n.width??0),h:e.naturalHeight||e.height||(n.height??0)}),_y=(n,e,t)=>({w:e*Math.abs((n.scaleX??1)||1),h:t*Math.abs((n.scaleY??1)||1)}),Dy=(n,e,t,r,o,i)=>({cropX:Math.max(0,t/2-o/2-n),cropY:Math.max(0,r/2-i/2-e)}),Fy=(n,e,t,r,o,i)=>({clipX:t/2-o/2-n,clipY:r/2-i/2-e}),Df=(n,e,t)=>{let r=Iy(e,t),o=_y(e,r.w,r.h),i=n.width??0,s=n.height??0,{cropX:a,cropY:l}=Dy(n.clipX??0,n.clipY??0,o.w,o.h,i,s);return{left:n.left??0,top:n.top??0,angle:n.angle??0,originX:n.originX??"center",originY:n.originY??"center",flipX:n.flipX===!0,flipY:n.flipY===!0,width:i,height:s,cropX:a,cropY:l,scaleX:n.scaleX??1,scaleY:n.scaleY??1,naturalWidth:o.w,naturalHeight:o.h,cropSizeMode:"visible"}},Ff=n=>{let{clipX:e,clipY:t}=Fy(n.cropX,n.cropY,n.naturalWidth,n.naturalHeight,n.width,n.height);return{left:n.left,top:n.top,width:n.width,height:n.height,cropX:n.cropX,cropY:n.cropY,clipX:e,clipY:t,scaleX:n.scaleX,scaleY:n.scaleY}};var Of=12,Bf=14,Wf=7,Oy=1,By=1,Hf=ee("#f6f7fa"),Gf=ee("#2f6fed"),Pc=["e","se","s","sw","w","nw","n","ne","e"],Wy=["tl","tr","bl","br"],Hy=["tl","tr","bl","br"],Gy=["left","right","top","bottom"],Cc=(n,e,t,r,o)=>{let i=null,s=1/0;for(let a of n){let l=e(a),u=Math.hypot(l.x-t,l.y-r);u<=o&&u<s&&(i=a,s=u)}return i},Mc=null,kc=()=>{if(Mc)return Mc;let n=Math.ceil((Wf+2)*2),e=document.createElement("canvas");e.width=n,e.height=n;let t=e.getContext("2d");return t.beginPath(),t.arc(n/2,n/2,Wf,0,Math.PI*2),t.fillStyle="#ffffff",t.fill(),t.lineWidth=1.5,t.strokeStyle="#2f6fed",t.stroke(),Mc=e,e},sr=30,ar=7,Xo={x:28,y:16},zo={x:14,y:4},Rc=2,zf=(n,e)=>{let t=document.createElement("canvas");t.width=n*Rc,t.height=e*Rc;let r=t.getContext("2d");return r?{canvas:t,ctx:r}:null},tt=n=>n*Rc,Ws=null,Ac=()=>{if(Ws)return Ws;let n=zf(sr,sr);if(!n)return Ws=document.createElement("canvas");let{canvas:e,ctx:t}=n;return t.translate(tt(ar),tt(ar)),t.shadowColor="rgba(12, 18, 28, 0.38)",t.shadowBlur=tt(4),t.shadowOffsetX=tt(2),t.shadowOffsetY=tt(2),t.beginPath(),t.lineWidth=tt(6),t.lineCap="round",t.strokeStyle="#dfe2e8",t.moveTo(0,tt(10)),t.lineTo(0,0),t.lineTo(tt(10),0),t.stroke(),Ws=e,e},Hs=null,Nc=()=>{if(Hs)return Hs;let n=zf(Xo.x,Xo.y);if(!n)return Hs=document.createElement("canvas");let{canvas:e,ctx:t}=n;return t.translate(tt(zo.x),tt(zo.y)),t.shadowColor="rgba(12, 18, 28, 0.38)",t.shadowBlur=tt(4),t.shadowOffsetX=0,t.shadowOffsetY=tt(2),t.beginPath(),t.lineWidth=tt(4),t.lineCap="round",t.strokeStyle="#dfe2e8",t.moveTo(tt(-6),0),t.lineTo(tt(6),0),t.stroke(),Hs=e,e},Yf=n=>{let e=Math.hypot(n[0],n[1])||1,t=Math.hypot(n[2],n[3])||1;return[n[0]/e,n[1]/e,n[2]/t,n[3]/t]},Yo=(n,e,t,r,o,i,s,a)=>{let l=r*Math.PI/180,u=Math.cos(l),c=Math.sin(l),[h,d,f,m]=Yf(n),p=n[0]*e+n[2]*t+n[4],b=n[1]*e+n[3]*t+n[5],g=j([h,d,f,m,0,0],[u,c,-c,u,0,0],!0),x=(i.x-o.x/2)/s,S=(i.y-o.y/2)/s;return{matrix:[g[0],g[1],g[2],g[3],p-(g[0]*x+g[2]*S),b-(g[1]*x+g[3]*S)],dims:{x:o.x/s,y:o.y/s},color:[1,1,1,1],texture:a}},Xf=(n,e)=>{let t=!1;for(let r=0,o=e.length-1;r<e.length;o=r++){let i=e[r].x,s=e[r].y,a=e[o].x,l=e[o].y;s>n.y!=l>n.y&&n.x<(a-i)*(n.y-s)/(l-s)+i&&(t=!t)}return t},Gs=class{constructor(e){this.host=e}host;node=null;circlesVisible=!0;ratio=null;shape=null;detachKey=null;get active(){return this.node!==null}get target(){return this.node}get info(){let e=this.node;if(!e||!(e instanceof ae?e.clipImageEl:e.imageEl))return null;let t=this.liveState();return{nodeId:e.id,handle:"",ratio:this.ratio,circlesVisible:this.circlesVisible,cropX:t.cropX,cropY:t.cropY,width:t.width,height:t.height,isMask:e instanceof ae,shapeActive:!(e instanceof ae)&&this.shape!==null}}enter(e,t){if(this.node&&this.exit(),e instanceof ae){if(!this.host.document.nodes.includes(e)||e.clipDynamicKind||!e.clipImageRaw||!e.clipImageEl)return!1}else if(e instanceof ie||!e.isImageType||!e.imageEl)return!1;this.node=e,this.ratio=null,this.shape=e instanceof ae||!t?.shape?null:t.shape,this.ratio=this.shape?.aspectRatio??null;let r=Math.abs(e.raw.scaleX??1),o=Math.abs(e.raw.scaleY??1);if(this.circlesVisible=r===o,this.host.document.exitEditing(),this.host.document.setSelection([e],"update"),!(e instanceof ae)){let i=s=>{s.key==="Escape"&&this.node&&this.exit()};window.addEventListener("keydown",i),this.detachKey=()=>window.removeEventListener("keydown",i)}return this.shape&&this.writeBack(Ec(this.liveState())),this.host.requestRenderAll(),!0}exit(){if(!this.node)return;let e=this.node;this.node=null,this.ratio=null,this.shape=null,this.detachKey?.(),this.detachKey=null,this.host.document.applyTransform([e],()=>({}),"modified",{action:Le.crop}),this.host.requestRenderAll()}exitByOutsideClick(){this.exit()}setCropShape(e){let t=this.node;if(!t||t instanceof ae)return;this.ratio=e?.aspectRatio??null;let r=this.shape!==null;this.shape=e,e?this.writeBack(Ec(this.liveState())):r&&this.writeBack(this.liveState(),!0),this.host.requestRenderAll()}setAspectRatio(e){if(this.node){if(this.ratio=e,e&&e>0){let t=this.shape!==null;this.shape=null;let r=Nf(this.liveState(),e);this.writeBack(r,t)}this.host.requestRenderAll()}}hitHandle(e,t){let r=this.node;if(!r)return null;let o=r.matrix,i=this.liveState(),s=(l,u)=>{let c=Q(o,l,u);return this.host.toScreen(c.x,c.y)},a=Cc(["br","bl","tr","tl"],l=>{let u=Jt[l];return s(u.x*i.width,u.y*i.height)},e,t,Of);if(a)return a;if(!this.ratio){let l=Cc(["bottom","right","top","left"],u=>{let c=Jt[u];return s(c.x*i.width,c.y*i.height)},e,t,Of);if(l)return l}if(this.circlesVisible){let l=Cc(["br","bl","tr","tl"],u=>{let c=Go(i,u);return s(c.x,c.y)},e,t,Bf);if(l){let u=Jt[l],c=s(u.x*i.width,u.y*i.height);return Math.hypot(c.x-e,c.y-t)<=Bf?l:`${l}S`}}return null}hitRect(e,t){let r=this.node;if(!r)return!1;let o=this.liveState(),i=r.matrix;if(!(r instanceof ae)){let c=["tl","tr","br","bl"].map(h=>{let d=(h==="tr"||h==="br"?.5:-.5)*o.width,f=(h==="bl"||h==="br"?.5:-.5)*o.height;return Q(i,d,f)});return Xf({x:e,y:t},c)}let s=["tl","tr","br","bl"].map(c=>{let h=(c==="tr"||c==="br"?.5:-.5)*o.width,d=(c==="bl"||c==="br"?.5:-.5)*o.height,f=Q(i,h,d);return this.host.toScreen(f.x,f.y)}),a=Math.abs(s[1].x-s[0].x)/2,l=Math.abs(s[3].y-s[0].y)/2,u=[{x:s[0].x-a,y:s[0].y-l},{x:s[1].x+a,y:s[1].y-l},{x:s[2].x+a,y:s[2].y+l},{x:s[3].x-a,y:s[3].y+l}];return Xf(this.host.toScreen(e,t),u)}applyHandle(e,t){if(!this.node)return;let o=this.liveState(),i=null;e.endsWith("S")?i=this.circlesVisible?kf(o,e.slice(0,2),t):null:cs(e)?i=this.ratio?Rf(o,e,t,this.ratio):Mf(o,e,t):this.ratio||(i=Os(o,e,t)),i&&this.writeBack(i),this.host.requestRenderAll()}setScale(e){if(!this.node)return!1;let t=Pf(this.liveState(),e,this.shape!==null);return t?(this.writeBack(t),this.host.document.setProps(this.node,{cropScale:t.scaleX},{deferIndexRebuild:!0}),this.host.requestRenderAll(),!0):!1}moveImageBy(e){if(!this.node)return;let r=this.liveState(),{cropX:o,cropY:i}=Af(r,e);this.writeBack({...r,cropX:o,cropY:i}),this.host.requestRenderAll()}hoverCursor(e,t,r){let o=this.hitHandle(e,t);if(o){if(o.endsWith("S")&&this.node){let i=Jt[o.slice(0,2)],a=((this.node.raw.angle??0)+Math.atan2(i.y,i.x)*180/Math.PI+360)%360;return`${Pc[Math.round(a/45)]}-resize`}return"pointer"}return this.hitRect(r.x,r.y)?"move":""}buildOverlay(e){let t=this.node;if(!t||!t.imageEl)return[];let r=this.liveState(),o=t.matrix,i=[],s=(b,g)=>Q(o,b,g),a=r.width,l=r.height,u=Oy/e;for(let b of[1,2]){let g=-a/2+b*a/3,x=s(g,-l/2),S=s(g,l/2);i.push(Re(x,S,u,Hf))}for(let b of[1,2]){let g=-l/2+b*l/3,x=s(-a/2,g),S=s(a/2,g);i.push(Re(x,S,u,Hf))}let c=By/e,h=["tl","tr","br","bl"].map(b=>s(Go(r,b).x,Go(r,b).y));for(let b=0;b<4;b++)i.push(Re(h[b],h[(b+1)%4],c,Gf));let d=1.5/e,f=["tl","tr","br","bl"].map(b=>s(Jt[b].x*a,Jt[b].y*l));for(let b=0;b<4;b++)i.push(Re(f[b],f[(b+1)%4],d,Gf));if(this.circlesVisible){let b=kc(),[g,x,S,w]=Yf(o),y=b.width/e;for(let v of Hy){let R=Go(r,v);i.push({matrix:[g,x,S,w,o[0]*R.x+o[2]*R.y+o[4],o[1]*R.x+o[3]*R.y+o[5]],dims:{x:y,y},color:[1,1,1,1],texture:b})}}if(!this.ratio){let b={top:0,right:90,bottom:180,left:270},g=Nc();for(let x of Gy){let S=Jt[x];i.push(Yo(o,S.x*a,S.y*l,b[x],Xo,zo,e,g))}}let m={tl:0,tr:90,br:180,bl:270},p=Ac();for(let b of Wy){let g=Jt[b];i.push(Yo(o,g.x*a,g.y*l,m[b],{x:sr,y:sr},{x:ar,y:ar},e,p))}return i}dispose(){this.detachKey?.(),this.detachKey=null,this.node=null,this.shape=null}liveState(){let e=this.node;if(e instanceof ae)return Df(e.raw,e.clipImageRaw,e.clipImageEl);let t=e.imageEl;return Lf(e.raw,t.naturalWidth,t.naturalHeight)}writeBack(e,t=!1){let r=this.node,o={...r instanceof ae?Ff(e):If(e)};r instanceof ae||(this.shape?o.clipPath=_f(this.shape,e.width,e.height):t&&(o.clipPath=void 0)),this.host.document.setProps(r,o,{deferIndexRebuild:!0})}};var Uf={ml:{left:!0},mr:{right:!0},mt:{top:!0},mb:{bottom:!0},tl:{left:!0,top:!0},tr:{right:!0,top:!0},bl:{left:!0,bottom:!0},br:{right:!0,bottom:!0}},$f=(n,e,t)=>{let r=n.expandScale??1.5;return{width:n.expandWidth??t.width*r,height:n.expandHeight??t.height*r,centerX:n.expandRectCenterX??e.x,centerY:n.expandRectCenterY??e.y}},jf=(n,e,t,r,o)=>{let i=t*Math.PI/180,s=Math.cos(i),a=Math.sin(i),{centerX:l,centerY:u}=n,c=n.width/2,h=n.height/2,d=r.x-l,f=r.y-u,m=d*s+f*a,p=-d*a+f*s,b=-c,g=c,x=-h,S=h;o.left&&(b=Math.min(m,g-1)),o.right&&(g=Math.max(m,b+1)),o.top&&(x=Math.min(p,S-1)),o.bottom&&(S=Math.max(p,x+1));let w=o.right,y=o.left,v=o.bottom,R=o.top,P=e.centerX-l,T=e.centerY-u,C=P*s+T*a,E=-P*a+T*s,M=C-e.scaledWidth/2,k=C+e.scaledWidth/2,A=E-e.scaledHeight/2,O=E+e.scaledHeight/2;!w&&M<b&&(b=M),!y&&k>g&&(g=k),!v&&A<x&&(x=A),!R&&O>S&&(S=O);let F=(b+g)/2,W=(x+S)/2;return{width:g-b,height:S-x,centerX:l+F*s-W*a,centerY:u+F*a+W*s}},Lc=(n,e,t,r)=>{let o=t*Math.PI/180,i=Math.cos(o),s=Math.sin(o),a=r.width/e.scaledWidth,l=r.height/e.scaledHeight,u=e.centerX-n.centerX,c=e.centerY-n.centerY,h=u*i+c*s,d=-u*s+c*i,f=e.scaledWidth/2,m=e.scaledHeight/2,p=n.width/2,b=n.height/2,g=Math.max(0,h-f+p),x=Math.max(0,p-h-f),S=Math.max(0,d-m+b),w=Math.max(0,b-d-m);return{left:Math.floor(g*a),right:Math.floor(x*a),top:Math.floor(S*l),bottom:Math.floor(w*l)}},Vf=(n,e,t,r)=>{let o=t*Math.PI/180,i=Math.cos(o),s=Math.sin(o),a=r.x-n.centerX,l=r.y-n.centerY,u=a*i+l*s,c=-a*s+l*i,h=Math.max(0,n.width/2-e.scaledWidth/2),d=Math.max(0,n.height/2-e.scaledHeight/2);return u=Math.max(-h,Math.min(h,u)),c=Math.max(-d,Math.min(d,c)),{x:n.centerX+u*i-c*s,y:n.centerY+u*s+c*i}},An={tl:{x:-.5,y:-.5},tr:{x:.5,y:-.5},bl:{x:-.5,y:.5},br:{x:.5,y:.5},ml:{x:-.5,y:0},mr:{x:.5,y:0},mt:{x:0,y:-.5},mb:{x:0,y:.5}},Xy={tl:{x:-1,y:-1},tr:{x:1,y:-1},bl:{x:-1,y:1},br:{x:1,y:1}},qf=(n,e,t,r)=>{let o=Xy[t],i=n.centerX-o.x*(n.scaledWidth/2),s=n.centerY-o.y*(n.scaledHeight/2),a=r.x-i,l=r.y-s,u=Math.hypot(n.scaledWidth,n.scaledHeight),c=u>0?Math.hypot(a,l)/u:1,h=Math.max(Math.abs(n.scaleX),Math.abs(n.scaleY));c=Math.max(.1/h,Math.min(5/h,c));let d=n.scaledWidth*c,f=n.scaledHeight*c,m=i+o.x*(d/2),p=s+o.y*(f/2),b=Math.min(i,i+o.x*d),g=Math.min(s,s+o.y*f),x=b+d,S=g+f;return b<e.centerX-e.width/2||g<e.centerY-e.height/2||x>e.centerX+e.width/2||S>e.centerY+e.height/2?null:{scaleX:n.scaleX*c,scaleY:n.scaleY*c,centerX:m,centerY:p}};var Uo=n=>n*Math.PI/180,zy=12,Yy=14,Uy=1,$y=(()=>{let n=ee("#3788ff");return[n[0],n[1],n[2],.5]})(),jy=ee("#3788ff"),Ic=["tl","tr","bl","br"],Vy={tl:0,tr:90,br:180,bl:270},qy={mt:0,mr:90,mb:180,ml:270},Ky=(n,e)=>{let t=!1;for(let r=0,o=e.length-1;r<e.length;o=r++){let i=e[r].x,s=e[r].y,a=e[o].x,l=e[o].y;s>n.y!=l>n.y&&n.x<(a-i)*(n.y-s)/(l-s)+i&&(t=!t)}return t},Xs=class{constructor(e){this.host=e}host;node=null;detachKey=null;get active(){return this.node!==null}get target(){return this.node}get info(){let e=this.node;if(!e)return null;let t=this.view();return{nodeId:e.id,width:t.rect.width,height:t.rect.height,centerX:t.rect.centerX,centerY:t.rect.centerY,angle:t.angle,offsets:t.offsets}}enter(e){if(this.node&&this.exit(),!(e instanceof ie?!1:(e.isImageType||e instanceof ae)&&!!e.imageEl&&!(e instanceof ae&&e.clipDynamicKind)))return!1;this.node=e,this.host.document.exitEditing(),this.host.document.setSelection([e],"update");let r=e.raw,o=Math.abs(r.scaleX??1),i=Math.abs(r.scaleY??1),s=r.expandScale??1.5,a=e.center,l={};r.expandRectCenterX===void 0&&(l.expandRectCenterX=a.x),r.expandRectCenterY===void 0&&(l.expandRectCenterY=a.y),r.expandWidth===void 0&&(l.expandWidth=e.dims.x*o*s),r.expandHeight===void 0&&(l.expandHeight=e.dims.y*i*s),Object.keys(l).length>0&&this.host.document.setProps(e,l);let u=c=>{c.key==="Escape"&&this.node&&this.exit()};return window.addEventListener("keydown",u),this.detachKey=()=>window.removeEventListener("keydown",u),this.host.requestRenderAll(),!0}exit(){let e=this.node;if(!e)return;this.node=null,this.detachKey?.(),this.detachKey=null;let t=e.imageEl;if(t){let r=this.expandViewOf(e,t),o=Lc(r.rect,r.img,r.angle,{width:t.naturalWidth,height:t.naturalHeight});this.host.document.setProps(e,{expandLeftOffset:o.left,expandRightOffset:o.right,expandTopOffset:o.top,expandBottomOffset:o.bottom})}this.host.document.applyTransform([e],()=>({}),"modified",{action:Le.crop}),this.host.requestRenderAll()}exitByOutsideClick(){let e=this.node;this.exit(),e&&this.host.document.selection.includes(e)&&this.host.document.clearSelection()}async applyResult(e,t,r){this.host.document.setProps(e,{src:t});let o=await this.host.reloadImageElement(e);if(!o||!o.naturalWidth||!o.naturalHeight)return!1;let i=r.width/o.naturalWidth,s=r.height/o.naturalHeight,a=ge({...e.raw,width:o.naturalWidth,height:o.naturalHeight,scaleX:i,scaleY:s},{x:r.centerX,y:r.centerY});return this.host.document.setProps(e,{width:o.naturalWidth,height:o.naturalHeight,scaleX:i,scaleY:s,left:a.x,top:a.y}),this.host.document.applyTransform([e],()=>({}),"modified"),this.host.requestRenderAll(),!0}hitHandle(e,t){let r=this.view(),o=Uo(r.angle),i=Math.cos(o),s=Math.sin(o);for(let a of Object.keys(An)){let l=An[a],u=l.x*r.rect.width,c=l.y*r.rect.height,h=r.rect.centerX+u*i-c*s,d=r.rect.centerY+u*s+c*i,f=this.host.toScreen(h,d);if(Math.hypot(f.x-e,f.y-t)<=zy)return a}for(let a of Ic){let l=this.imageCornerOf(a),u=this.host.toScreen(l.x,l.y);if(Math.hypot(u.x-e,u.y-t)<=Yy)return`${a}S`}return null}hitRect(e,t){let r=this.view(),o=Uo(r.angle),i=Math.cos(o),s=Math.sin(o),a=["tl","tr","br","bl"].map(l=>{let u=An[l],c=u.x*r.rect.width,h=u.y*r.rect.height;return{x:r.rect.centerX+c*i-h*s,y:r.rect.centerY+c*s+h*i}});return Ky({x:e,y:t},a)}applyHandle(e,t){let r=this.node;if(!r)return;if(e.endsWith("S")){let s=this.view(),a=r.raw,l=qf({...s.img,scaleX:a.scaleX??1,scaleY:a.scaleY??1},s.rect,e.slice(0,2),t);if(l){let u=ge({...r.raw,width:r.dims.x,height:r.dims.y,scaleX:l.scaleX,scaleY:l.scaleY},{x:l.centerX,y:l.centerY});this.host.document.setProps(r,{scaleX:l.scaleX,scaleY:l.scaleY,left:u.x,top:u.y},{deferIndexRebuild:!0})}this.host.requestRenderAll();return}let o=this.view(),i=jf(o.rect,o.img,o.angle,t,Uf[e]);this.host.document.setProps(r,{expandWidth:i.width,expandHeight:i.height,expandRectCenterX:i.centerX,expandRectCenterY:i.centerY},{deferIndexRebuild:!0}),this.host.requestRenderAll()}moveImageBy(e){let t=this.node;if(!t)return;let r=this.view(),o=Vf(r.rect,r.img,r.angle,{x:r.img.centerX+e.x,y:r.img.centerY+e.y}),i=ge({...t.raw,width:t.dims.x,height:t.dims.y},o);this.host.document.setProps(t,{left:i.x,top:i.y},{deferIndexRebuild:!0}),this.host.requestRenderAll()}hoverCursor(e,t,r,o){let i=this.hitHandle(e,t);if(i){if(i.endsWith("S")&&this.node){let s=An[i.slice(0,2)],l=((this.node.raw.angle??0)+Math.atan2(s.y,s.x)*180/Math.PI+360)%360;return`${Pc[Math.round(l/45)]}-resize`}return"pointer"}return this.hitRect(r,o)?"move":""}buildUnderlay(){let e=this.view(),t=Uo(e.angle);return[{matrix:[Math.cos(t),Math.sin(t),-Math.sin(t),Math.cos(t),e.rect.centerX,e.rect.centerY],dims:{x:e.rect.width,y:e.rect.height},color:$y}]}buildOverlay(e){let t=this.view(),r=[],o=Uo(t.angle),i=[Math.cos(o),Math.sin(o),-Math.sin(o),Math.cos(o),t.rect.centerX,t.rect.centerY],s=p=>{let b=An[p];return Q(i,b.x*t.rect.width,b.y*t.rect.height)},a=Uy/e,l=["tl","tr","br","bl"].map(s);for(let p=0;p<4;p++)r.push(Re(l[p],l[(p+1)%4],a,jy));let u=kc(),c=u.width/e,h=Math.cos(o),d=Math.sin(o);for(let p of Ic){let b=this.imageCornerOf(p);r.push({matrix:[h,d,-d,h,b.x,b.y],dims:{x:c,y:c},color:[1,1,1,1],texture:u})}let f=Nc();for(let p of["ml","mr","mt","mb"]){let b=An[p];r.push(Yo(i,b.x*t.rect.width,b.y*t.rect.height,qy[p],Xo,zo,e,f))}let m=Ac();for(let p of Ic){let b=An[p];r.push(Yo(i,b.x*t.rect.width,b.y*t.rect.height,Vy[p],{x:sr,y:sr},{x:ar,y:ar},e,m))}return r}dispose(){this.detachKey?.(),this.detachKey=null,this.node=null}view(){let e=this.node;return this.expandViewOf(e,e.imageEl)}imageCornerOf(e){let t=this.view(),r=Uo(t.angle),o=Math.cos(r),i=Math.sin(r),s=(e==="tr"||e==="br"?.5:-.5)*t.img.scaledWidth,a=(e==="bl"||e==="br"?.5:-.5)*t.img.scaledHeight;return{x:t.img.centerX+s*o-a*i,y:t.img.centerY+s*i+a*o}}expandViewOf(e,t){let r=e.raw,o=Math.abs(r.scaleX??1),i=Math.abs(r.scaleY??1),s=e.center,a=e.dims.x*o,l=e.dims.y*i,u={centerX:s.x,centerY:s.y,scaledWidth:a,scaledHeight:l},c=$f(r,s,{width:a,height:l}),h=r.angle??0,d=t?Lc(c,u,h,{width:t.naturalWidth,height:t.naturalHeight}):null;return{rect:c,img:u,angle:h,offsets:d}}};var Qy=8,Zy=6;var cr=n=>{if(!n)return null;let e=Fe(n);return e?{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}:null},Kf=(n,e)=>{let t=n[e],r=String(t[0]).toUpperCase();if(r==="M"||r==="L")return{x:t[1],y:t[2]};if(r==="C")return{x:t[5],y:t[6]};if(r==="Q")return{x:t[3],y:t[4]};for(let o=e;o>=0;o--)if(String(n[o][0]).toUpperCase()==="M")return{x:n[o][1],y:n[o][2]};return{x:0,y:0}},lr=(n,e)=>{for(let t=e-1;t>=0;t--){let r=String(n[t][0]).toUpperCase();if(r==="M"||r==="L")return{x:n[t][1],y:n[t][2]};if(r==="C")return{x:n[t][5],y:n[t][6]};if(r==="Q")return{x:n[t][3],y:n[t][4]};if(r==="Z"){for(let o=t;o>=0;o--)if(String(n[o][0]).toUpperCase()==="M")return{x:n[o][1],y:n[o][2]}}}return{x:0,y:0}},Jy=n=>n==="C"?5:n==="Q"?3:1,ut=(n,e,t)=>({x:n[e]-t.x,y:n[e+1]-t.y}),_c=(n,e)=>{let t=[],r=[];return n.forEach((o,i)=>{let s=String(o[0]);if(s!=="Z"&&t.push({key:`c_${i}_${s}`,kind:"anchor",commandIndex:i,pointIndex:o.length-2,local:ut(o,o.length-2,e)}),s==="C"){let a=ut(o,1,e),l=ut(o,3,e);t.push({key:`c_${i}_C_CP_1`,kind:"handle",commandIndex:i,pointIndex:1,local:a}),t.push({key:`c_${i}_C_CP_2`,kind:"handle",commandIndex:i,pointIndex:3,local:l});let u=i>0?String(n[i-1][0]).toUpperCase():"M",c=i>0?ut(n[i-1],Jy(u),e):a;r.push({from:a,to:c},{from:l,to:ut(o,5,e)})}else if(s==="Q"){let a=ut(o,1,e);t.push({key:`c_${i}_Q_CP_1`,kind:"handle",commandIndex:i,pointIndex:1,local:a}),r.push({from:a,to:ut(o,3,e)})}}),{handles:t,connections:r}},Jf=(n,e)=>n.map((t,r)=>({key:`p_${r}`,kind:"point",commandIndex:r,pointIndex:r,local:{x:t.x-e.x,y:t.y-e.y}})),zs=n=>{if(!n.length)return null;let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)e>i.x&&(e=i.x),t>i.y&&(t=i.y),r<i.x&&(r=i.x),o<i.y&&(o=i.y);return{x:(e+r)/2,y:(t+o)/2}},e0=(n,e,t)=>{let r=t.x-e.x,o=t.y-e.y,i=r*r+o*o;if(!i)return{distance:Math.hypot(n.x-e.x,n.y-e.y),t:0,point:{...e},length:0};let s=Math.max(0,Math.min(1,((n.x-e.x)*r+(n.y-e.y)*o)/i)),a={x:e.x+r*s,y:e.y+o*s};return{distance:Math.hypot(n.x-a.x,n.y-a.y),t:s,point:a,length:Math.sqrt(i)}},t0=(n,e,t=100)=>{let r=1/t,o=0,i=Number.POSITIVE_INFINITY,s=0,a=null;for(let h=0;h<=t;h++){let d=h*r,f=e(d);a&&(s+=Math.hypot(f.x-a.x,f.y-a.y)),a=f;let m=(f.x-n.x)**2+(f.y-n.y)**2;m<i&&(i=m,o=d)}let l=Math.max(0,o-r),u=Math.min(1,o+r),c=(u-l)/20;for(let h=l;h<=u;h+=c){let d=e(h),f=(d.x-n.x)**2+(d.y-n.y)**2;f<i&&(i=f,o=h)}return{distance:Math.sqrt(i),t:o,point:e(o),length:s}},Qf=(n,e,t,r,o)=>{let i=1-o,s=i*i*i,a=3*i*i*o,l=3*i*o*o,u=o*o*o;return{x:s*n.x+a*e.x+l*t.x+u*r.x,y:s*n.y+a*e.y+l*t.y+u*r.y}},Zf=(n,e,t,r)=>{let o=1-r,i=o*o,s=2*o*r,a=r*r;return{x:i*n.x+s*e.x+a*t.x,y:i*n.y+s*e.y+a*t.y}},n0=(n,e,t)=>({x:n.x+(e.x-n.x)*t,y:n.y+(e.y-n.y)*t}),em=(n,e,t,r,o)=>{let i=Qy/o,s=Zy/o,a=h=>Q(r,h.x,h.y),l=(h,d)=>a(ut(h,d,e)),u,c=Number.POSITIVE_INFINITY;return n.forEach((h,d)=>{let f=String(h[0]).toUpperCase();if(f==="C"||f==="Q"){let v={x:lr(n,d).x-e.x,y:lr(n,d).y-e.y},R=a(v),P=l(h,1),T=f==="C"?ut(h,5,e):ut(h,3,e),C=a(T),M=t0(t,f==="C"?F=>Qf(R,P,l(h,3),C,F):F=>Zf(R,P,C,F));if(M.distance>i||M.length<=s*2||M.distance>=c)return;let k=s/M.length;if(M.t<=k||M.t>=1-k)return;let A=lr(n,d),O=f==="C"?(()=>{let F={x:A.x-e.x,y:A.y-e.y},W=ut(h,1,e),z=ut(h,3,e),_={x:h[5]-e.x,y:h[6]-e.y};return Qf(F,W,z,_,M.t)})():(()=>{let F={x:A.x-e.x,y:A.y-e.y},W=ut(h,1,e),z={x:h[3]-e.x,y:h[4]-e.y};return Zf(F,W,z,M.t)})();c=M.distance,u={commandIndex:d,commandType:f,t:M.t,local:O,scene:M.point};return}if(f!=="L"&&f!=="Z")return;let m=f==="L"?lr(n,d):Kf(n,Math.max(0,d-1)),p=Kf(n,d),b=a({x:m.x-e.x,y:m.y-e.y}),g=a({x:p.x-e.x,y:p.y-e.y}),x=e0(t,b,g);if(x.distance>i||x.length<=s*2||x.distance>=c)return;let S=s/x.length;if(x.t<=S||x.t>=1-S)return;c=x.distance;let w={x:m.x-e.x,y:m.y-e.y},y={x:p.x-e.x,y:p.y-e.y};u={commandIndex:d,commandType:f,t:x.t,local:n0(w,y,x.t),scene:x.point}}),u},tm=(n,e,t,r,o)=>n.map((i,s)=>{if(s!==e)return i;let a=[...i];return a[t]=r.x+o.x,a[t+1]=r.y+o.y,a}),nm=(n,e,t,r)=>n.map((o,i)=>i===e?{x:t.x+r.x,y:t.y+r.y}:o),rm=(n,e,t)=>{let r=n.map(a=>[...a]),o=t.local.x+e.x,i=t.local.y+e.y,s=t.commandIndex;if(t.commandType==="L"){let a=r[s],l=a[1],u=a[2];return r[s]=["L",o,i],r.splice(s+1,0,["L",l,u]),r}if(t.commandType==="C"){let a=r[s],l=lr(n,s),u=t.t,c=a[1],h=a[2],d=a[3],f=a[4],m=a[5],p=a[6],b=l.x+(c-l.x)*u,g=l.y+(h-l.y)*u,x=c+(d-c)*u,S=h+(f-h)*u,w=d+(m-d)*u,y=f+(p-f)*u,v=b+(x-b)*u,R=g+(S-g)*u,P=x+(w-x)*u,T=S+(y-S)*u;return r[s]=["C",b,g,v,R,o,i],r.splice(s+1,0,["C",P,T,w,y,m,p]),r}if(t.commandType==="Q"){let a=r[s],l=lr(n,s),u=t.t,c=a[1],h=a[2],d=a[3],f=a[4],m=l.x+(c-l.x)*u,p=l.y+(h-l.y)*u,b=c+(d-c)*u,g=h+(f-h)*u;return r[s]=["Q",m,p,o,i],r.splice(s+1,0,["Q",b,g,d,f]),r}return t.commandType==="Z"?(r.splice(s,1,["L",o,i],["Z"]),r):null},om=(n,e,t)=>{if(e<0||e>=n.length)return null;let r=n[e],o=String(r[0]).toUpperCase();if(o==="M"||o==="Z")return null;let i=o==="C"||o==="Q",s=t.toUpperCase()==="C";if(i===s)return{commands:n,changed:!1};let a,l;o==="L"?(a=r[1],l=r[2]):o==="C"?(a=r[5],l=r[6]):(a=r[3],l=r[4]);let u=lr(n,e),c=n.map(h=>[...h]);return c[e]=s?["C",u.x+(a-u.x)/3,u.y+(l-u.y)/3,a-(a-u.x)/3,l-(l-u.y)/3,a,l]:["L",a,l],{commands:c,changed:!0}},Dc=(n,e)=>{let t=n?.[e]?.[0];return t&&["C","Q","S","T","A"].includes(String(t).toUpperCase())?"smooth":"line"},im=(n,e,t,r)=>{if(!t)return n;let o=t.x-e.x,i=t.y-e.y;return{x:n.x+r[0]*o+r[2]*i,y:n.y+r[1]*o+r[3]*i}};var r0=12,$o=ee("#2254f4"),sm=ee("#ffffff"),am=7,lm=5,o0=1,Fc=null,i0=()=>{if(Fc)return Fc;let n=Math.ceil((lm+2)*2),e=document.createElement("canvas");e.width=n,e.height=n;let t=e.getContext("2d");return t.beginPath(),t.arc(n/2,n/2,lm,0,Math.PI*2),t.fillStyle="#ffffff",t.fill(),t.lineWidth=1.5,t.strokeStyle="#2254f4",t.stroke(),Fc=e,e},Bt=n=>{let e=n.typeKey;return e===L.PATH?"path":e===L.POLYGON||e===L.POLYLINE?"poly":e===L.LINE?"line":null},Ys=class{constructor(e){this.host=e}host;node=null;kind=null;activeAnchorKey;insertCandidate;detachKey=null;get active(){return this.node!==null}get target(){return this.node}get info(){let e=this.node,t=this.kind;if(!e||!t)return null;let r=e.matrix,o=this.currentHandles().map(i=>{let s=Q(r,i.local.x,i.local.y);return{key:i.key,kind:i.kind,x:s.x,y:s.y}});return{nodeId:e.id,kind:t,anchors:o,activeAnchorKey:this.activeAnchorKey,activeAnchorIndex:this.activeAnchorIndex(),insertCandidate:this.insertCandidate?{commandIndex:this.insertCandidate.commandIndex,commandType:this.insertCandidate.commandType,x:this.insertCandidate.scene.x,y:this.insertCandidate.scene.y}:void 0}}enter(e){this.node&&this.exit();let t=Bt(e);if(!t||t==="path"&&!Ce(e.raw.path)||t==="poly"&&!Array.isArray(e.raw.points)||t==="line"&&!(e instanceof Lr))return!1;this.node=e,this.kind=t,this.activeAnchorKey=void 0,this.insertCandidate=void 0,this.host.document.exitEditing(),this.host.document.setSelection([e],"update");let r=o=>{o.key==="Escape"&&this.node&&this.exit()};return window.addEventListener("keydown",r),this.detachKey=()=>window.removeEventListener("keydown",r),this.host.requestRenderAll(),!0}exit(){this.node&&(this.node=null,this.kind=null,this.activeAnchorKey=void 0,this.insertCandidate=void 0,this.detachKey?.(),this.detachKey=null,this.host.requestRenderAll())}exitByOutsideClick(){this.exit()}hitAnchor(e,t){let r=this.node;if(!r)return null;let o=r.matrix,i=null,s=r0;for(let a of this.currentHandles()){let l=Q(o,a.local.x,a.local.y),u=this.host.toScreen(l.x,l.y),c=Math.hypot(u.x-e,u.y-t);c<=s&&(s=c,i=a.key)}return i}hitBody(e,t){let r=this.node;return r?r.containsPoint(e,t):!1}findInsertCandidate(e,t){let r=this.node;if(!r||this.kind!=="path")return null;let o=Ce(r.raw.path),i=cr(o);return!o||!i?null:em(o,i,{x:e,y:t},r.matrix,this.host.zoom)??null}startAnchorDrag(e){return!this.node||!this.currentHandles().some(r=>r.key===e)?!1:(this.captureDragBefore(),this.setActiveAnchor(e),!0)}applyAnchorDrag(e,t){let r=this.node,o=this.kind;if(!r||!o)return;let i=this.currentHandles().find(l=>l.key===e);if(!i)return;let s=r.matrix,a=Q(ve(s),t.x,t.y);if(o==="path"){let l=Ce(r.raw.path),u=cr(l);if(!l||!u)return;let c=tm(l,i.commandIndex,i.pointIndex,a,u);this.writeBackWithCompensation(r,c,u,cr(c),Fe(c))}else if(o==="poly"){let l=r.raw.points,u=zs(l);if(!u)return;let c=nm(l,i.commandIndex,a,u),h=1/0,d=1/0,f=-1/0,m=-1/0;for(let p of c)h>p.x&&(h=p.x),d>p.y&&(d=p.y),f<p.x&&(f=p.x),m<p.y&&(m=p.y);this.writeBackWithCompensation(r,c,u,zs(c),{left:h,top:d,right:f,bottom:m})}else{let l=i.commandIndex===0?{x1:a.x,y1:a.y}:{x2:a.x,y2:a.y},u=Number(l.x1??r.raw.x1),c=Number(l.y1??r.raw.y1),h=Number(l.x2??r.raw.x2),d=Number(l.y2??r.raw.y2),f=ge({...r.raw,width:Math.abs(h-u),height:Math.abs(d-c)},r.center);this.host.document.setProps(r,{...l,left:f.x,top:f.y},{deferIndexRebuild:!0})}this.host.requestRenderAll()}moveBodyBy(e){let t=this.node;t&&(this.captureDragBefore(),this.host.document.setProps(t,{left:(t.raw.left??0)+e.x,top:(t.raw.top??0)+e.y},{deferIndexRebuild:!0}),this.host.requestRenderAll())}captureDragBefore(){this._dragBefore??=this.node?this.node.toObject():null}_dragBefore=null;commit(){let e=this.node;if(!e)return;let t=this._dragBefore;this._dragBefore=null,this.host.document.applyTransform([e],()=>({}),"modified",t?{before:new Map([[e,t]])}:void 0)}insertAnchor(e){let t=this.node;if(!t||this.kind!=="path")return null;let r=Ce(t.raw.path),o=cr(r);if(!r||!o)return null;let i=rm(r,o,e);if(!i)return null;let s=t.toObject();this.host.document.setProps(t,{path:i},{deferIndexRebuild:!0}),this.host.document.applyTransform([t],()=>({}),"modified",{before:new Map([[t,s]])});let a=e.commandType==="Z"?"L":e.commandType,l=`c_${e.commandIndex}_${a}`;return this.insertCandidate=void 0,this.setActiveAnchor(l),this.host.requestRenderAll(),l}setAnchorType(e,t){let r=this.node;if(!r||this.kind!=="path")return!1;let o=Ce(r.raw.path);if(!o)return!1;let i=om(o,e,t);if(!i)return!1;if(i.changed){let s=r.toObject();this.host.document.setProps(r,{path:i.commands},{deferIndexRebuild:!0}),this.host.document.applyTransform([r],()=>({}),"modified",{before:new Map([[r,s]])})}return this.setActiveAnchor(`c_${e}_${String(i.commands[e][0])}`),this.host.requestRenderAll(),i.changed}setActiveAnchor(e){if(this.activeAnchorKey===e)return;this.activeAnchorKey=e;let t=this.node;t&&this.host.document.events.fire("path:active-anchor-change",t,e),this.host.requestRenderAll()}resetAnchorStyles(){this.activeAnchorKey!==void 0&&(this.activeAnchorKey=void 0,this.host.requestRenderAll())}activeAnchorIndex(){let e=this.activeAnchorKey;if(e){if(e.startsWith("c_")){let t=e.match(/^c_(\d+)_/),r=t?Number(t[1]):NaN;return Number.isFinite(r)?r:void 0}if(e.startsWith("p_"))return Number(e.slice(2));if(e==="e0"||e==="e1")return Number(e[1])}}hoverCursor(e,t,r){let o=this.hitAnchor(e,t);if(o)return o.includes("_CP_")?"crosshair":"default";let i=this.findInsertCandidate(r.x,r.y);return i?(this.updateInsertCandidate(i),"copy"):(this.updateInsertCandidate(void 0),this.hitBody(r.x,r.y)?"move":"")}updateInsertCandidate(e){let t=this.insertCandidate;t&&e&&t.commandIndex===e.commandIndex&&t.commandType===e.commandType&&Math.abs(t.scene.x-e.scene.x)<.1&&Math.abs(t.scene.y-e.scene.y)<.1||!t&&!e||(this.insertCandidate=e,this.host.requestRenderAll())}buildOverlay(e){let t=this.node,r=this.kind;if(!t||!r)return[];let o=t.matrix,i=[...Pn(t.aCoords,e)],s=a=>Q(o,a.x,a.y);if(r==="path"){let a=Ce(t.raw.path),l=cr(a);if(!a||!l)return i;let{handles:u,connections:c}=_c(a,l),h=o0/e;for(let p of c)i.push(Re(s(p.from),s(p.to),h,$o));let d=am/e,f=i0(),m=f.width/2*2*(1/e);for(let p of u){let b=s(p.local);if(p.kind==="handle")i.push({matrix:[1,0,0,1,b.x,b.y],dims:{x:m,y:m},color:[1,1,1,1],texture:f});else{let g=p.key===this.activeAnchorKey;i.push({matrix:[1,0,0,1,b.x,b.y],dims:{x:d,y:d},color:$o}),i.push({matrix:[1,0,0,1,b.x,b.y],dims:{x:d-2/e,y:d-2/e},color:g?$o:sm})}}this.insertCandidate&&i.push({matrix:[1,0,0,1,this.insertCandidate.scene.x,this.insertCandidate.scene.y],dims:{x:m,y:m},color:[1,1,1,1],texture:f})}else{let a=am/e;for(let l of this.currentHandles()){let u=s(l.local),c=l.key===this.activeAnchorKey;i.push({matrix:[1,0,0,1,u.x,u.y],dims:{x:a,y:a},color:$o}),i.push({matrix:[1,0,0,1,u.x,u.y],dims:{x:a-2/e,y:a-2/e},color:c?$o:sm})}}return i}dispose(){this.detachKey?.(),this.detachKey=null,this.node=null,this.kind=null}currentHandles(){let e=this.node,t=this.kind;if(!e||!t)return[];if(t==="path"){let a=Ce(e.raw.path),l=cr(a);return!a||!l?[]:_c(a,l).handles}if(t==="poly"){let a=e.raw.points,l=zs(a);return!Array.isArray(a)||!l?[]:Jf(a,l)}let r=Number(e.raw.x1),o=Number(e.raw.y1),i=Number(e.raw.x2),s=Number(e.raw.y2);return[r,o,i,s].every(Number.isFinite)?[{key:"e0",kind:"endpoint",commandIndex:0,pointIndex:0,local:{x:r,y:o}},{key:"e1",kind:"endpoint",commandIndex:1,pointIndex:1,local:{x:i,y:s}}]:[]}writeBackWithCompensation(e,t,r,o,i){if(!i)return;let s=e.ownMatrix,a=im(e.center,r,o,[s[0],s[1],s[2],s[3]]),l=ge({...e.raw,width:i.right-i.left,height:i.bottom-i.top},a),u=this.kind==="path"?{path:t}:{points:t};this.host.document.setProps(e,{...u,left:l.x,top:l.y},{deferIndexRebuild:!0})}};import{Warpvas as s0}from"warpvas";var cm=12,a0=5,l0=4,c0=1,um=3,hm=2e3,dm=10,u0=[.2,.2,.2,.6],h0=[.11,.35,.96,1],d0=[1,1,1,.9],Us=class{host;warp=null;node=null;beforeRaw=null;originalSrc=null;undoStack=[];redoStack=[];previewCanvas=null;previewVersion=0;renderedVersion=-1;coreSize={w:0,h:0};displayScale={x:1,y:1};coreAnchor={x:0,y:0};renderCanvas=null;constructor(e){this.host=e}get document(){return this.host.document}get zoom(){return this.host.zoom}get textures(){return this.host.textures}toScreen(e,t){return this.host.toScreen(e,t)}requestRenderAll(){this.host.requestRenderAll()}reloadNodeImage(e){return this.host.reloadNodeImage(e)}get active(){return!!this.warp}get target(){return this.node}get debugAnchors(){if(!this.warp||!this.node)return[];let e=[],t=this.currentBounds();for(let r=0;r<t.length;r++)for(let o=0;o<t[r].length;o++){let i=t[r][o];for(let s of Oc){let a=i[s];a&&a.forEach((l,u)=>{let c=this.toScene(l);e.push({row:r,col:o,dir:s,i:u,srcX:Math.round(l.x),srcY:Math.round(l.y),sceneX:Math.round(c.x),sceneY:Math.round(c.y)})})}}return e}get debugPreviewInfo(){if(!this.previewCanvas)return null;let e=this.previewCanvas;e.__probeId===void 0&&(e.__probeId=Math.random());let t=this.warp?this.warp.getBoundingBoxInfo():null;return{canvasId:e.__probeId,width:e.width,height:e.height,version:this.previewVersion,box:t,dataURL:e.width*e.height<=4e5?e.toDataURL("image/png"):void 0}}get debugBoundsSample(){return!this.warp||!this.coreSize.w?null:{region:this.currentBounds()[0]?.[0]??null,natural:{w:this.coreSize.w,h:this.coreSize.h}}}async enter(e,t){if(this.warp&&this.cancel(),!e.imageEl||e.cropRect||e instanceof ie||!e.imageEl.naturalWidth||!e.imageEl.naturalHeight)return!1;let r=e.raw;this.originalSrc=r.warpOriginalSrc??r.src??null;let o=e.imageEl,i=r.warpOriginalSrc,s=o,a=!1;if(i)try{let f=await this.host.loadImage(i,r.crossOrigin??void 0);f?.naturalWidth&&(s=f,a=!0)}catch{}let l=new s0(s,t?.gridRows??um,t?.gridCols??um);l.setInputLimitSize({width:hm,height:hm}),this.renderCanvas=document.createElement("canvas"),l.setRenderingCanvas(this.renderCanvas);let u=s===o?o:s;this.coreSize={w:u.naturalWidth*l.scale.x,h:u.naturalHeight*l.scale.y};let c=r.warpDisplayScale,h=r.warpCoreAnchor;a&&c&&typeof c.x=="number"&&h&&typeof h.x=="number"?(this.displayScale={x:c.x,y:c.y??c.x},this.coreAnchor={x:h.x,y:h.y??h.x}):(this.displayScale={x:e.dims.x/this.coreSize.w,y:e.dims.y/this.coreSize.h},this.coreAnchor={x:this.coreSize.w/2,y:this.coreSize.h/2});let d=a?r.warpvasState:void 0;if(d&&Array.isArray(d.splitPoints))try{l.setWarpState(d.splitPoints,d.regionBounds??null)}catch{}return this.node=e,this.warp=l,this.beforeRaw=e.toObject(),this.undoStack=[this.snapshot()],this.redoStack=[],this.fireHistory(),this.refreshPreview(),this.requestRenderAll(),!0}hitAnchor(e,t){let r=this.hitAnchorsOfKind(e,t,"vertex");return r||this.hitAnchorsOfKind(e,t,"curve")}hitAnchorsOfKind(e,t,r){let o=this.currentBounds(),i=null;for(let s=0;s<o.length;s++)for(let a=0;a<o[s].length;a++){let l=o[s][a];if(r==="vertex")for(let u of fm){let c=mm(l,u);if(!c)continue;let h=this.screenDist(c,e,t);h<=cm&&(!i||h<i.dist)&&(i={anchor:{kind:"vertex",row:s,col:a,pos:u},dist:h})}else for(let u of Oc){let c=l[u];if(!(!c||c.length<4))for(let h of[0,1]){let d=this.screenDist(c[h+1],e,t);d<=cm&&(!i||d<i.dist)&&(i={anchor:{kind:"curve",row:s,col:a,dir:u,index:h},dist:d})}}}return i?.anchor??null}applyAnchorDrag(e,t){let r=this.warp;if(!r)return;let o=this.toSource(t);if(e.kind==="vertex")r.updateVertexCoord(e.row,e.col,e.pos,o);else{let i=this.currentBounds()[e.row]?.[e.col]?.[e.dir];if(!i||i.length<4)return;let s=i.map(a=>({...a}));s[e.index+1]=o,r.updateRegionBoundCoords(e.row,e.col,e.dir,[s[0],s[1],s[2],s[3]])}this.refreshPreview(),this.requestRenderAll()}endDrag(){this.warp&&(this.undoStack.push(this.snapshot()),this.redoStack=[],this.fireHistory())}undo(){return!this.warp||this.undoStack.length<=1?!1:(this.redoStack.push(this.undoStack.pop()),this.restore(this.undoStack[this.undoStack.length-1]),this.afterHistoryStep(),!0)}redo(){if(!this.warp)return!1;let e=this.redoStack.pop();return e?(this.undoStack.push(e),this.restore(e),this.afterHistoryStep(),!0):!1}afterHistoryStep(){this.fireHistory(),this.refreshPreview(),this.requestRenderAll()}get undoable(){return this.undoStack.length>1}get redoable(){return this.redoStack.length>0}getWarpState(){return this.warp?this.snapshot():null}buildOverlay(){if(!this.warp||!this.node)return[];let e=this.zoom,t=[];if(this.previewCanvas){this.renderedVersion!==this.previewVersion&&(this.textures.update(this.previewCanvas),this.renderedVersion=this.previewVersion);let s=this.localFromSourceBox(this.warp.getBoundingBoxInfo());t.push({matrix:this.quadMatrix(s.cx,s.cy),dims:{x:s.w,y:s.h},color:[1,1,1,1],texture:this.previewCanvas})}let r=this.currentBounds(),o=new Set,i=new Set;for(let s of r)for(let a of s){for(let l of Oc){let u=a[l];if(!u||u.length<4)continue;let c=this.toScene(u[0]);for(let h=1;h<=dm;h++){let d=this.toScene(f0(u[0],u[1],u[2],u[3],h/dm));t.push(Re(c,d,c0/e,u0)),c=d}for(let h of[0,1]){let d=u[h+1],f=`${Math.round(d.x)},${Math.round(d.y)}`;i.has(f)||(i.add(f),t.push(pm(this.toScene(d),l0,d0,e)))}}for(let l of fm){let u=mm(a,l);if(!u)continue;let c=`${Math.round(u.x)},${Math.round(u.y)}`;o.has(c)||(o.add(c),t.push(pm(this.toScene(u),a0,h0,e)))}}return t}hoverCursor(e,t){return this.hitAnchor(e,t)?"pointer":"default"}async exit(e){let t=this.warp,r=this.node;if(!t||!r)return null;let o=this.beforeRaw,i=null;if(e&&!t.isUnwarped()){let a=t.render().toDataURL("image/png"),l=t.getBoundingBoxInfo(),u=t.getWarpState(),c=this.localFromSourceBox(l),h=this.sourceToDisplayScale(),d=Math.max(1,Math.round(l.width*h.x)),f=Math.max(1,Math.round(l.height*h.y)),m=r.matrix,p={x:r.center.x+m[0]*c.cx+m[2]*c.cy,y:r.center.y+m[1]*c.cx+m[3]*c.cy},b=ge({...r.raw,width:d,height:f},p),g={x:l.width/2-l.offsetX,y:l.height/2-l.offsetY};i={dataURL:a,state:u,nextWidth:d,nextHeight:f,left:b.x,top:b.y,originalSrc:this.originalSrc,displayScale:{x:this.displayScale.x,y:this.displayScale.y},coreAnchor:g}}this.teardown(t);let s=!1;return i&&(r.set({src:i.dataURL,width:i.nextWidth,height:i.nextHeight,left:i.left,top:i.top,warpvasState:i.state,warpOriginalSrc:i.originalSrc??void 0,warpDisplayScale:i.displayScale,warpCoreAnchor:i.coreAnchor}),await this.reloadNodeImage(r.id),this.host.document.applyTransform([r],()=>({}),"modified",{action:Le.warpImage,before:new Map([[r,o]])}),s=!0),this.requestRenderAll(),{committed:s,node:r,before:o,after:r.toObject()}}async cancel(){await this.exit(!1)}teardown(e=this.warp){this.previewCanvas&&this.textures.remove(this.previewCanvas),e?.dispose?.(),this.warp=null,this.node=null,this.beforeRaw=null,this.originalSrc=null,this.undoStack=[],this.redoStack=[],this.previewCanvas=null,this.previewVersion=0,this.renderedVersion=-1,this.coreSize={w:0,h:0},this.displayScale={x:1,y:1},this.coreAnchor={x:0,y:0},this.renderCanvas=null}snapshot(){return this.warp.getWarpState()}restore(e){this.warp.setWarpState(e.splitPoints,e.regionBounds)}currentBounds(){return this.warp?this.warp.getWarpState().regionBounds??[]:[]}sourceToDisplayScale(){return{x:this.displayScale.x,y:this.displayScale.y}}quadMatrix(e,t){return m0(this.node.matrix,e,t)}toScene(e){let t=this.node;return Q(t.matrix,(e.x-this.coreAnchor.x)*this.displayScale.x,(e.y-this.coreAnchor.y)*this.displayScale.y)}toSource(e){let r=this.node.localPoint(e.x,e.y);return{x:r.x/this.displayScale.x+this.coreAnchor.x,y:r.y/this.displayScale.y+this.coreAnchor.y}}screenDist(e,t,r){let o=this.toScene(e),i=this.toScreen(o.x,o.y);return Math.hypot(i.x-t,i.y-r)}localFromSourceBox(e){return{cx:(e.width/2-e.offsetX-this.coreAnchor.x)*this.displayScale.x,cy:(e.height/2-e.offsetY-this.coreAnchor.y)*this.displayScale.y,w:e.width*this.displayScale.x,h:e.height*this.displayScale.y}}refreshPreview(){if(!this.warp)return;let e=this.previewCanvas;this.previewCanvas=this.warp.render(),e&&e!==this.previewCanvas&&this.textures.remove(e),this.previewVersion++}fireHistory(){this.host.onWarpHistoryChange?.(this.undoable,this.redoable)}},fm=["tl","tr","bl","br"],Oc=["top","right","bottom","left"],mm=(n,e)=>{let t=n[e==="tl"||e==="tr"?"top":"bottom"],r=n[e==="tl"||e==="bl"?"left":"right"];if(!t||t.length<4||!r||r.length<4)return null;let o=null;for(let i of[t[0],t[3]])for(let s of[r[0],r[3]]){let a=Math.hypot(i.x-s.x,i.y-s.y);(!o||a<o.dist)&&(o={pt:{x:(i.x+s.x)/2,y:(i.y+s.y)/2},dist:a})}return o?.pt??null},f0=(n,e,t,r,o)=>{let i=1-o;return{x:i*i*i*n.x+3*i*i*o*e.x+3*i*o*o*t.x+o*o*o*r.x,y:i*i*i*n.y+3*i*i*o*e.y+3*i*o*o*t.y+o*o*o*r.y}},pm=(n,e,t,r)=>({matrix:[1,0,0,1,n.x,n.y],dims:{x:e*2/r,y:e*2/r},color:t}),m0=(n,e,t)=>[n[0],n[1],n[2],n[3],n[0]*e+n[2]*t+n[4],n[1]*e+n[3]*t+n[5]];var he=n=>Math.round(n*1e6)/1e6;var zr=([n,e],[t,r])=>n<=t?e>=t:n>=t?r>=n:!1,$s=([n,e],[t,r])=>{let o=Math.max(n,t),i=Math.min(e,r);return o<=i?[o,i]:null},en=(n,e,t,r,o)=>{let i=Math.abs(e);i<=t[r]&&(i<t[r]&&(n.length=0),n.push(o),t[r]=i)},xm=n=>{let e=n.map((r,o)=>({p:r,i:o}));e.sort((r,o)=>r.p.x-o.p.x);let t=n.map((r,o)=>({p:r,i:o}));return t.sort((r,o)=>r.p.y-o.p.y),{byX:e,byY:t}},p0=(n,e,t)=>{let r=0,o=n.length;for(;r<o;){let i=r+o>>1;n[i].p[e]<t?r=i+1:o=i}return r},bm=(n,e,t,r,o,i,s)=>{let a=[],l=(u,c,h,d,f,m)=>{let p=c;for(let b of d){let g=p0(u,c,b[c]-h),x=b[c]+h,S=m[p];a.length=0;for(let w=g;w<u.length;w++){let y=u[w];if(y.p[c]>x)break;let v=y.p[c]-b[c],R=Math.abs(v);R<=S&&(R<S&&(S=R,a.length=0),a.push({p:y.p,i:y.i,offset:v}))}a.sort((w,y)=>w.i-y.i);for(let w of a)en(f,w.offset,m,p,{type:"point",points:[b,w.p],offset:w.offset})}};l(e.byX,"x",t,n,i,o),l(e.byY,"y",r,n,s,o)},Wc=n=>({x:he(n.x),y:he(n.y)}),Bc=n=>({left:he(n.left),top:he(n.top),right:he(n.right),bottom:he(n.bottom)}),Vs=n=>[n.tl,n.tr,n.br,n.bl,n.c].map(Wc),ym=n=>n.flatMap(Vs);var Sm=n=>{let e=n.map(Bc).map((o,i)=>({bounds:o,idx:i})),t=o=>[...e].sort((i,s)=>i.bounds[o]-s.bounds[o]),r=(o,i)=>[...e].sort((s,a)=>s.bounds[o]+s.bounds[i]-a.bounds[o]-a.bounds[i]);return{byLeft:t("left"),byRight:t("right"),byTop:t("top"),byBottom:t("bottom"),byLeftPlusRight:r("left","right"),byTopPlusBottom:r("top","bottom")}};var b0=(n,e,t,r,o)=>{let{left:i,top:s,right:a,bottom:l}=n,u=(i+a)/2,c=(s+l)/2,h=t.x,d=t.y,f=a-i,m=l-s,p=(T,C,E,M)=>({startBounds:T,endBounds:C,startSide:[{x:T.right,y:T.top},{x:T.right,y:T.bottom}],endSide:[{x:C.left,y:C.top},{x:C.left,y:C.bottom}],length:M,overlap:E}),b=(T,C,E,M)=>({startBounds:T,endBounds:C,startSide:[{x:T.left,y:T.bottom},{x:T.right,y:T.bottom}],endSide:[{x:C.left,y:C.top},{x:C.right,y:C.top}],length:M,overlap:E}),g=(T,C)=>{if(!(T.right<C.left&&zr([T.top,T.bottom],[C.top,C.bottom])))return;let E=$s([T.top,T.bottom],[C.top,C.bottom]);if(!zr([s,l],E))return;let M=C.left-T.right,k=he(T.right+M/2-u);if(M>f&&Math.abs(k)<=t.x){en(r,k,t,"x",{type:"gap",direction:"center_horizontal",gap:p(T,C,E,M),offset:k});return}let A=he(M-(i-C.right));if(Math.abs(A)<=t.x){en(r,A,t,"x",{type:"gap",direction:"side_right",gap:p(T,C,E,M),offset:A});return}let O=he(T.left-a-M);Math.abs(O)<=t.x&&en(r,O,t,"x",{type:"gap",direction:"side_left",gap:p(T,C,E,M),offset:O})},x=(T,C)=>{if(!(T.bottom<C.top&&zr([T.left,T.right],[C.left,C.right])))return;let E=$s([T.left,T.right],[C.left,C.right]);if(!zr([i,a],E))return;let M=C.top-T.bottom,k=he(T.bottom+M/2-c);if(M>m&&Math.abs(k)<=t.y){en(o,k,t,"y",{type:"gap",direction:"center_vertical",gap:b(T,C,E,M),offset:k});return}let A=he(T.top-l-M);if(Math.abs(A)<=t.y){en(o,A,t,"y",{type:"gap",direction:"side_top",gap:b(T,C,E,M),offset:A});return}let O=he(s-C.bottom),F=M-O;Math.abs(F)<=t.y&&en(o,F,t,"y",{type:"gap",direction:"side_bottom",gap:b(T,C,E,M),offset:F})},S=e.byLeft,w=e.byRight,y=e.byTop,v=e.byBottom,R=h+1e-6,P=d+1e-6;{let T=S.length;for(let C of w){if(C.bounds.right>=u+h+.001)break;let E=2*u-C.bounds.right,M=E+2*R,k=E-2*R;for(;T>0&&S[T-1].bounds.left>M;)T--;for(let A=T-1;A>=0&&S[A].bounds.left>=k;A--)g(C.bounds,S[A].bounds)}}{let T=0;for(let C of e.byLeftPlusRight){if(C.bounds.right>=i+h+.001)continue;let E=C.bounds.left+C.bounds.right-i,M=E-R,k=E+R;for(;T<w.length&&w[T].bounds.right<M;)T++;for(let A=T;A<w.length&&w[A].bounds.right<=k;A++)g(w[A].bounds,C.bounds)}}{let T=0;for(let C of e.byLeftPlusRight){if(C.bounds.left<=a-h-.001)continue;let E=C.bounds.left+C.bounds.right-a,M=E-R,k=E+R;for(;T<S.length&&S[T].bounds.left<M;)T++;for(let A=T;A<S.length&&S[A].bounds.left<=k;A++)g(C.bounds,S[A].bounds)}}{let T=y.length;for(let C of v){if(C.bounds.bottom>=c+d+.001)break;let E=2*c-C.bounds.bottom,M=E+2*P,k=E-2*P;for(;T>0&&y[T-1].bounds.top>M;)T--;for(let A=T-1;A>=0&&y[A].bounds.top>=k;A--)x(C.bounds,y[A].bounds)}}{let T=0;for(let C of e.byTopPlusBottom){if(C.bounds.top<=l-d-.001)continue;let E=C.bounds.top+C.bounds.bottom-l,M=E-P,k=E+P;for(;T<y.length&&y[T].bounds.top<M;)T++;for(let A=T;A<y.length&&y[A].bounds.top<=k;A++)x(C.bounds,y[A].bounds)}}{let C=0;for(let E of e.byTopPlusBottom){if(E.bounds.bottom>=s+d+.001)continue;let M=E.bounds.top-he(s-E.bounds.bottom),k=M-P,A=M+P;for(;C<v.length&&v[C].bounds.bottom<k-1e-5;)C++;for(let O=C;O<v.length&&v[O].bounds.bottom<=A;O++)x(v[O].bounds,E.bounds)}}},js=(n,e,t,r,o)=>{for(let i of n)for(let s of e){let a=s.x-i.x,l=s.y-i.y;Math.abs(a)<=t.x&&en(r,a,t,"x",{type:"point",points:[i,s],offset:a}),Math.abs(l)<=t.y&&en(o,l,t,"y",{type:"point",points:[i,s],offset:l})}},g0=(n,e,t,r,o)=>{let{left:i,top:s,right:a,bottom:l}=n,u=(i+a)/2,c=(s+l)/2;for(let h of e.horizontalGaps){if(!zr([s,l],h.overlap))continue;let d=h.startSide[0].x+h.length/2,f=he(d-u);if(h.length>a-i&&Math.abs(f)<=t.x){Math.abs(f)<t.x&&(r.length=0),t.x=Math.abs(f),r.push({type:"gap",direction:"center_horizontal",gap:h,offset:f});continue}let p=i-h.endBounds.right,b=he(h.length-p);if(Math.abs(b)<=t.x){Math.abs(b)<t.x&&(r.length=0),t.x=Math.abs(b),r.push({type:"gap",direction:"side_right",gap:h,offset:b});continue}let g=h.startBounds.left-a,x=he(g-h.length);if(Math.abs(x)<=t.x){Math.abs(x)<t.x&&(r.length=0),t.x=Math.abs(x),r.push({type:"gap",direction:"side_left",gap:h,offset:x});continue}}for(let h of e.verticalGaps){if(!zr([i,a],h.overlap))continue;let d=h.startSide[0].y+h.length/2,f=he(d-c);if(h.length>l-s&&Math.abs(f)<=t.y){Math.abs(f)<t.y&&(o.length=0),t.y=Math.abs(f),o.push({type:"gap",direction:"center_vertical",gap:h,offset:f});continue}let p=h.startBounds.top-l,b=he(p-h.length);if(Math.abs(b)<=t.y){Math.abs(b)<t.y&&(o.length=0),t.y=Math.abs(b),o.push({type:"gap",direction:"side_top",gap:h,offset:b});continue}let g=he(s-h.endBounds.bottom),x=h.length-g;if(Math.abs(x)<=t.y){Math.abs(x)<t.y&&(o.length=0),t.y=Math.abs(x),o.push({type:"gap",direction:"side_bottom",gap:h,offset:x});continue}}},gm=n=>{let e=new Map;for(let t of n){let r=`${he(t.x)},${he(t.y)}`;e.has(r)||e.set(r,t)}return Array.from(e.values())},vm=(n,e)=>{let t={},r={};for(let s of n){if(s.type!=="point")continue;let a=String(he(s.points[0].x));t[a]||(t[a]=[]),t[a].push(...s.points.map(l=>({x:he(l.x),y:he(l.y)})))}for(let s of e){if(s.type!=="point")continue;let a=String(he(s.points[0].y));r[a]||(r[a]=[]),r[a].push(...s.points.map(l=>({x:he(l.x),y:he(l.y)})))}let o=Object.entries(t).map(([s,a])=>({type:"points",points:gm(a.map(l=>({x:Number(s),y:l.y})).sort((l,u)=>l.y-u.y))})),i=Object.entries(r).map(([s,a])=>({type:"points",points:gm(a.map(l=>({x:l.x,y:Number(s)})).sort((l,u)=>l.x-u.x))}));return[...o,...i]},x0=n=>{let e=new Map;for(let t of n){let r=[t.points[0],t.points[1]].flatMap(o=>[he(o.x),he(o.y)]).join(",");e.has(r)||e.set(r,t)}return Array.from(e.values())},y0=(n,e)=>{let{left:t,top:r,right:o,bottom:i}=n,s=[];for(let a of e){let l=a.gap.startBounds,u=a.gap.endBounds,c=$s([r,i],a.gap.overlap),h=$s([t,o],a.gap.overlap);switch(a.direction){case"center_horizontal":{if(c){let d=(c[0]+c[1])/2;s.push({type:"gap",direction:"horizontal",points:[{x:a.gap.startSide[0].x,y:d},{x:t,y:d}]},{type:"gap",direction:"horizontal",points:[{x:o,y:d},{x:a.gap.endSide[0].x,y:d}]})}break}case"center_vertical":{if(h){let d=(h[0]+h[1])/2;s.push({type:"gap",direction:"vertical",points:[{x:d,y:a.gap.startSide[0].y},{x:d,y:r}]},{type:"gap",direction:"vertical",points:[{x:d,y:i},{x:d,y:a.gap.endSide[0].y}]})}break}case"side_right":{if(c){let d=(c[0]+c[1])/2;s.push({type:"gap",direction:"horizontal",points:[{x:l.right,y:d},{x:u.left,y:d}]},{type:"gap",direction:"horizontal",points:[{x:u.right,y:d},{x:t,y:d}]})}break}case"side_left":{if(c){let d=(c[0]+c[1])/2;s.push({type:"gap",direction:"horizontal",points:[{x:o,y:d},{x:l.left,y:d}]},{type:"gap",direction:"horizontal",points:[{x:l.right,y:d},{x:u.left,y:d}]})}break}case"side_top":{if(h){let d=(h[0]+h[1])/2;s.push({type:"gap",direction:"vertical",points:[{x:d,y:i},{x:d,y:l.top}]},{type:"gap",direction:"vertical",points:[{x:d,y:l.bottom},{x:d,y:u.top}]})}break}case"side_bottom":{if(h){let d=(h[0]+h[1])/2;s.push({type:"gap",direction:"vertical",points:[{x:d,y:l.bottom},{x:d,y:u.top}]},{type:"gap",direction:"vertical",points:[{x:d,y:u.bottom},{x:d,y:r}]})}break}}}return x0(s.map(a=>({...a,points:[{x:he(a.points[0].x),y:he(a.points[0].y)},{x:he(a.points[1].x),y:he(a.points[1].y)}]})))},wm=(n,e,t,r,o,i)=>{let s=(g,x,S)=>{"byLeft"in r?b0(g,r,l,x,S):g0(g,r,l,x,S)},a=Bc(e),l={x:o,y:o},u=[],c=[];i?bm(n,i,o,o,l,u,c):js(n,t,l,u,c),s(a,u,c);let h={x:he(u[0]?.offset??0),y:he(c[0]?.offset??0)},d=n.map(g=>Wc({x:g.x+h.x,y:g.y+h.y})),f=Bc({left:a.left+h.x,top:a.top+h.y,right:a.right+h.x,bottom:a.bottom+h.y});l.x=0,l.y=0,u.length=0,c.length=0,i?bm(d,i,0,0,l,u,c):js(d,t,l,u,c),s(f,u,c);let m=vm(u,c),p=[...u,...c].filter(g=>g.type==="gap"),b=y0(f,p);return{snapOffset:h,pointSnapLines:m,gapSnapLines:b}},Tm=(n,e,t)=>{let r={x:t,y:t},o=[],i=[];js(n,e,r,o,i);let s={x:he(o[0]?.offset??0),y:he(i[0]?.offset??0)};r.x=0,r.y=0,o.length=0,i.length=0;let a=n.map(u=>Wc({x:u.x+s.x,y:u.y+s.y}));js(a,e,r,o,i);let l=vm(o,i);return{snapOffset:s,pointSnapLines:l}};var S0=200,Em=8,v0=1,w0=3,T0=8,E0=ee("#F68066"),Cm=new Set(["WorkSpaceClipType","WorkSpaceSafeType","WorkSpaceMaskType","WorkSpaceLineType","WorkSpaceShadowType"]),C0="WorkSpaceDrawType",Yr=n=>({left:Math.min(n.tl.x,n.tr.x,n.br.x,n.bl.x),top:Math.min(n.tl.y,n.tr.y,n.br.y,n.bl.y),right:Math.max(n.tl.x,n.tr.x,n.br.x,n.bl.x),bottom:Math.max(n.tl.y,n.tr.y,n.br.y,n.bl.y)}),Mm=(n,e)=>!(Yr(n).right<e.minX||Yr(n).left>e.maxX||Yr(n).bottom<e.minY||Yr(n).top>e.maxY),M0=n=>({x:(n.tl.x+n.br.x)/2,y:(n.tl.y+n.br.y)/2}),qs=class{constructor(e,t=()=>!1){this.host=e;this.enabled=t}host;enabled;pointSnapLines=[];gapSnapLines=[];lastSnapOffset={x:0,y:0};activeType="";pendingMove=!1;gestureKey="";viewportSignature="";referenceCoords=[];referencePoints=[];axisIndex=null;gapIndex=null;scalingKey="";scalingPoints=[];workspaceResolved=!1;workspacePointKeys=new Set;workspaceBounds;get info(){return{pending:this.pendingMove,offset:{...this.lastSnapOffset},pointLines:this.pointSnapLines.length,gapLines:this.gapSnapLines.length,candidates:this.referenceCoords.length,activeType:this.activeType}}registerMove(e){this.enabled()&&(this.clearLines(),this.activeType=e.raw.type,this.ensureMoveCaches(),this.pendingMove=!0)}settleMoveSnap(){if(!this.pendingMove||(this.pendingMove=!1,!this.enabled()))return;let e=this.host.document;if(e.groupEditing&&e.activeGroupChild){this.clearLines();return}let t=e.selection;if(!t.length||!this.referenceCoords.length||!this.referencePoints.length||!this.gapIndex){this.clearLines();return}let r=et(e);if(!r){this.clearLines();return}let o={tl:r.quad.tl,tr:r.quad.tr,br:r.quad.br,bl:r.quad.bl,c:M0(r.quad)},i=Em/this.host.zoom,{snapOffset:s,pointSnapLines:a,gapSnapLines:l}=wm(Vs(o),Yr(o),this.referencePoints,this.gapIndex,i,this.axisIndex??void 0);if(s.x!==0||s.y!==0){for(let c of t)e.setProps(c,{left:(c.raw.left??0)+s.x,top:(c.raw.top??0)+s.y},{deferIndexRebuild:!0});let u=e.selectionFrame;u&&e.setSelectionFrame({...u,center:{x:u.center.x+s.x,y:u.center.y+s.y}})}this.lastSnapOffset={...s},this.pointSnapLines=a,this.gapSnapLines=l}registerScaling(e,t){if(!this.enabled()||e.typeKey===L.CIRCLE)return;this.clearLines(),this.activeType=e.raw.type;let r=this.host.document;this.ensureScalingCaches();let o=et(r);if(!o||!this.scalingPoints.length)return;let s=(cs(t)?[t]:[...jl]).map(u=>({x:o.quad[u].x,y:o.quad[u].y})),a=Em/this.host.zoom,{pointSnapLines:l}=Tm(s,this.scalingPoints,a);this.pointSnapLines=l,this.gapSnapLines=[]}finishGesture(){this.settleMoveSnap(),this.clearLines(),this.activeType="",this.gestureKey="",this.viewportSignature="",this.referenceCoords=[],this.referencePoints=[],this.axisIndex=null,this.gapIndex=null,this.scalingKey="",this.scalingPoints=[],this.workspaceResolved=!1,this.workspacePointKeys.clear(),this.workspaceBounds=void 0}buildOverlay(e){if(this.activeType==="ReferenceLine")return[];if(!this.pointSnapLines.length&&!this.gapSnapLines.length)return[];let t=[],r=v0/e,o=(i,s)=>t.push(Re(i,s,r,E0));this.ensureWorkspaceInfo();for(let i of this.pointSnapLines){let s=i.points;if(!s.length)continue;if(!!this.workspaceBounds&&s.some(u=>this.workspacePointKeys.has(`${he(u.x)},${he(u.y)}`))&&this.workspaceBounds){let u=this.workspaceBounds,c=s.every(d=>d.x===s[0].x),h=s.every(d=>d.y===s[0].y);c&&o({x:s[0].x,y:Math.min(s[0].y,u.top)},{x:s[0].x,y:Math.max(s[s.length-1].y,u.bottom)}),h&&o({x:Math.min(s[0].x,u.left),y:s[0].y},{x:Math.max(s[s.length-1].x,u.right),y:s[0].y})}else s.length>=2&&o(s[0],s[s.length-1]);let l=w0/e;for(let u of s)o({x:u.x-l,y:u.y-l},{x:u.x+l,y:u.y+l}),o({x:u.x+l,y:u.y-l},{x:u.x-l,y:u.y+l})}for(let i of this.gapSnapLines){let[s,a]=i.points,l=T0/e,u=l/2,c=l/4;if(i.direction==="horizontal"){let h=s.y,d=(s.x+a.x)/2;o({x:s.x,y:h-l},{x:s.x,y:h+l}),o({x:d-c,y:h-u},{x:d-c,y:h+u}),o({x:d+c,y:h-u},{x:d+c,y:h+u}),o({x:a.x,y:h-l},{x:a.x,y:h+l}),o(s,a)}else{let h=s.x,d=(s.y+a.y)/2;o({x:h-l,y:s.y},{x:h+l,y:s.y}),o({x:h-u,y:d-c},{x:h+u,y:d-c}),o({x:h-u,y:d+c},{x:h+u,y:d+c}),o({x:h-l,y:a.y},{x:h+l,y:a.y}),o(s,a)}}return t}clearLines(){this.pointSnapLines=[],this.gapSnapLines=[]}keyCacheSelection=null;keyCacheValue="";ensureMoveCaches(){let e=this.host.document,t=e.selection;this.keyCacheSelection!==t&&(this.keyCacheSelection=t,this.keyCacheValue=t.map(l=>l.id).join("|"));let r=this.keyCacheValue,o=this.getViewportRect(),i=o?.signature??"";if(this.gestureKey===r&&this.referenceCoords.length&&this.viewportSignature===i)return;this.gestureKey=r,this.viewportSignature=i;let s=new Set(t),a=o?.rect;this.referenceCoords=[];for(let l of e.nodes){if(!l.visible||s.has(l)||Cm.has(l.id))continue;let u=this.nodeCoords(l);a&&!Mm(u,a)||this.referenceCoords.push(u)}this.referencePoints=ym(this.referenceCoords),this.axisIndex=xm(this.referencePoints),this.gapIndex=Sm(this.referenceCoords.map(Yr))}ensureScalingCaches(){let e=this.host.document,t=e.selection.map(s=>s.id).join("|");if(this.scalingKey===t&&this.scalingPoints.length)return;this.scalingKey=t;let r=new Set(e.selection),o=this.getViewportRect()?.rect,i=[];for(let s of e.nodes){if(!s.visible||r.has(s)||Cm.has(s.id))continue;let a=this.nodeCoords(s);o&&!Mm(a,o)||i.push(...Vs(a))}this.scalingPoints=i}ensureWorkspaceInfo(){if(this.workspaceResolved)return;this.workspaceResolved=!0;let e=this.host.document.nodes.find(o=>o.id===C0);if(!e)return;let t=e.aCoords,r=e.center;for(let o of[t.tl,t.tr,t.br,t.bl,r])this.workspacePointKeys.add(`${he(o.x)},${he(o.y)}`);this.workspaceBounds=e.bounds}nodeCoords(e){let t=e.aCoords,r=e.center;return{tl:{x:t.tl.x,y:t.tl.y},tr:{x:t.tr.x,y:t.tr.y},br:{x:t.br.x,y:t.br.y},bl:{x:t.bl.x,y:t.bl.y},c:{x:r.x,y:r.y}}}getViewportRect(){let e=this.host.viewportTransform,t=e[0];if(!t||!Number.isFinite(t))return;let{width:r,height:o}=this.host.viewSize,i={x:(0-e[4])/e[0],y:(0-e[5])/e[3]},s={x:(r-e[4])/e[0],y:(o-e[5])/e[3]},a=S0/t;return{rect:{minX:Math.min(i.x,s.x)-a,minY:Math.min(i.y,s.y)-a,maxX:Math.max(i.x,s.x)+a,maxY:Math.max(i.y,s.y)+a},signature:`${e[0]},${e[1]},${e[2]},${e[3]},${e[4]},${e[5]}`}}};var Rm=n=>{let e=n?.animates;return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.key=="string"):[]},R0={width:0,height:0},be=(n,e={})=>({originX:"center",originY:"center",left:n.center.x,top:n.center.y,...e}),Wt=(n,e,t=R0,r={})=>e==="left"?be(n,{left:-n.width/2,...r}):e==="right"?be(n,{left:t.width+n.width/2,...r}):e==="top"?be(n,{top:-n.height/2,...r}):be(n,{top:t.height+n.height/2,...r}),P0=[{key:"left-swipe-entry",name:"左滑入场",category:"entrance",getStartState:n=>Wt(n,"left"),getEndState:n=>be(n)},{key:"right-swipe-entry",name:"右滑入场",category:"entrance",getStartState:(n,e)=>Wt(n,"right",e),getEndState:n=>be(n)},{key:"top-swipe-entry",name:"上滑入场",category:"entrance",getStartState:(n,e)=>Wt(n,"bottom",e),getEndState:n=>be(n)},{key:"bottom-swipe-entry",name:"下滑入场",category:"entrance",getStartState:n=>Wt(n,"top"),getEndState:n=>be(n)},{key:"smash-off",name:"砸落",category:"entrance",getStartState:n=>be(n,{scaleX:n.scaleX*2.5,scaleY:n.scaleY*2.5}),getEndState:n=>be(n,{scaleX:n.scaleX,scaleY:n.scaleY})},{key:"gradually-display",name:"渐显",category:"entrance",getStartState:n=>be(n,{scaleX:n.scaleX*.01,scaleY:n.scaleY*.01,opacity:.01}),getEndState:n=>be(n,{scaleX:n.scaleX,scaleY:n.scaleY,opacity:1})},{key:"pop-up",name:"弹出",category:"entrance",getStartState:n=>be(n,{scaleX:n.scaleX*.01,scaleY:n.scaleY*.01}),getEndState:n=>be(n,{scaleX:n.scaleX*1.3,scaleY:n.scaleY*1.3})},{key:"flip-horizontal-entry",name:"水平翻转",category:"entrance",getStartState:n=>be(n,{scaleX:n.scaleX*.01}),getEndState:n=>be(n,{scaleX:n.scaleX})},{key:"flip-vertical-entry",name:"垂直翻转",category:"entrance",getStartState:n=>be(n,{scaleY:n.scaleY*.01}),getEndState:n=>be(n,{scaleY:n.scaleY})},{key:"rotate-entry",name:"旋入",category:"entrance",getStartState:n=>be(n,{angle:n.angle-720,scaleX:n.scaleX*.01,scaleY:n.scaleY*.01}),getEndState:n=>be(n,{angle:n.angle,scaleX:n.scaleX,scaleY:n.scaleY})}],k0=[{key:"left-swipe-exit",name:"左滑退场",category:"exit",getStartState:n=>be(n),getEndState:n=>Wt(n,"left")},{key:"right-swipe-exit",name:"右滑退场",category:"exit",getStartState:n=>be(n),getEndState:(n,e)=>Wt(n,"right",e)},{key:"top-swipe-exit",name:"上滑退场",category:"exit",getStartState:n=>be(n),getEndState:n=>Wt(n,"top")},{key:"bottom-swipe-exit",name:"下滑退场",category:"exit",getStartState:n=>be(n),getEndState:(n,e)=>Wt(n,"bottom",e)},{key:"fade-out",name:"渐隐",category:"exit",getStartState:n=>be(n,{scaleX:n.scaleX,scaleY:n.scaleY,opacity:1}),getEndState:n=>be(n,{scaleX:n.scaleX*.01,scaleY:n.scaleY*.01,opacity:.01})},{key:"flip-horizontal-exit",name:"水平翻转",category:"exit",getStartState:n=>be(n,{scaleX:n.scaleX}),getEndState:n=>be(n,{scaleX:n.scaleX*.01})},{key:"flip-vertical-exit",name:"垂直翻转",category:"exit",getStartState:n=>be(n,{scaleY:n.scaleY}),getEndState:n=>be(n,{scaleY:n.scaleY*.01})},{key:"rotate-exit",name:"旋出",category:"exit",getStartState:n=>be(n,{angle:n.angle-720,scaleX:n.scaleX,scaleY:n.scaleY}),getEndState:n=>be(n,{angle:n.angle+720,scaleX:n.scaleX*.01,scaleY:n.scaleY*.01})}],A0=[{key:"subtitle-scroll",name:"字幕滚动",category:"emphasis",getStartState:(n,e)=>Wt(n,"right",e),getEndState:n=>Wt(n,"left")},{key:"flip-horizontal",name:"水平翻转",category:"emphasis",getStartState:n=>be(n,{scaleX:n.scaleX}),getEndState:n=>be(n,{scaleX:-n.scaleX})},{key:"flip-vertical",name:"垂直翻转",category:"emphasis",getStartState:n=>be(n,{scaleY:n.scaleY}),getEndState:n=>be(n,{scaleY:-n.scaleY})}],N0=[...P0,...k0,...A0],Hc=new Map(N0.map(n=>[n.key,n])),L0=n=>Hc.get(n),Ks=n=>{let e=Hc.get(n);return e?e.category==="entrance"?0:e.category==="emphasis"?1:2:Number.MAX_SAFE_INTEGER},Pm=n=>Ks(n)===1,I0=n=>{let e=n.duration??0;return!Pm(n.key)||!n.single?e:Math.floor(e/n.single)*n.single},_0=n=>{let e=[...n].sort((r,o)=>{let i=Ks(r.key)-Ks(o.key);return i!==0?i:Ks(r.key)===Number.MAX_SAFE_INTEGER?(r.startTime??0)-(o.startTime??0):0}),t=0;return e.map(r=>{let o={...r,startTime:Number(t.toFixed(3))};return t+=r.duration??0,o})},km=.2,Am=(n,e)=>{let t=[];for(let s of n)for(let a of _0(s.animates??[]))t.push({target:s.target,view:s.view,animate:a});t.sort((s,a)=>(s.animate.startTime??0)-(a.animate.startTime??0));let r=[],o=0,i=0;for(let s of t){let a=s.animate.startTime??0,l=Math.max(0,a-i),u=o+l,c=I0(s.animate),h=u+km,d=h+c;r.push({target:s.target,animate:s.animate,definition:Hc.get(s.animate.key)??null,view:s.view,waitTime:l,invokeTime:u,motionStart:h,motionEnd:d,playbackDuration:c}),o=d,i=a+(s.animate.duration??0)}return{timeline:r,duration:r[r.length-1]?.motionEnd??0,ws:e}},Gc=(n,e)=>{let t=new Map;for(let o of e.timeline){let i=t.get(o.target);i?i.push(o):t.set(o.target,[o])}let r=[];return t.forEach((o,i)=>{let s=o.find(f=>n>=f.invokeTime&&n<f.motionEnd);if(!s||!s.definition){r.push({target:i,override:null});return}if(n<s.motionStart){r.push({target:i,override:s.definition.getStartState(s.view,e.ws)});return}let a=n-s.motionStart,l=s.animate,u=s.playbackDuration>0?s.playbackDuration:1,c;Pm(l.key)&&l.single&&l.single>0?c=a%l.single/l.single:c=a/u,c=Math.min(Math.max(c,0),1);let h=s.definition.getStartState(s.view,e.ws),d=s.definition.getEndState(s.view,e.ws);r.push({target:i,override:Nm(l.key,h,d,c)})}),r},Nm=(n,e,t,r)=>{let o={};for(let i of Object.keys(t)){let s=e[i],a=t[i];if(typeof s=="number"&&typeof a=="number"){let l;n==="smash-off"&&(i==="scaleX"||i==="scaleY")?l=s-(s-a)*r:l=s+(a-s)*r,o[i]=Number(l.toFixed(3))}else o[i]=r<.5?s:a}for(let i of Object.keys(e))i in o||(o[i]=e[i]);return o},D0=n=>1-Math.cos(Math.min(Math.max(n,0),1)*Math.PI/2),Lm=(n,e,t)=>{let r=L0(t.key);if(!r)return null;let o=t.duration??0,i=t.single&&t.single>0?t.single:void 0,s=r.category==="emphasis",a=s&&i?Math.floor(o/i):1,l=s&&i?i:o;return{key:t.key,definition:r,view:n,ws:e,delay:km,loopDuration:l,loopCount:a}},Xc=(n,e)=>{if(n<0)return{override:e.definition.getStartState(e.view,e.ws),done:!1};if(n<e.delay)return{override:e.definition.getStartState(e.view,e.ws),done:!1};let t=n-e.delay,r=e.loopCount*e.loopDuration;if(t>=r)return{override:null,done:!0};let o=e.loopDuration>0?Math.floor(t/e.loopDuration):0,i=e.loopDuration>0?t-o*e.loopDuration:0,s=e.loopDuration>0?i/e.loopDuration:1,a=e.definition.getStartState(e.view,e.ws),l=e.definition.getEndState(e.view,e.ws);return{override:Nm(e.key,a,l,D0(s)),done:!1}},Vo=n=>n.scrollSpeed?(n.textTotalWidth+n.viewWidth)/n.scrollSpeed:0,F0=(n,e,t)=>{if(e<=0)return 0;let r=Math.max(n,0);return t==="loop"?r%e:Math.min(r,e)},Im=(n,e,t="loop")=>{if(!n.scrollEnabled)return 0;let r=Vo(n);if(r<=0)return 0;let o=F0(e,r,t)/r,i=n.textTotalWidth+n.viewWidth;return n.scrollDirection==="left-to-right"?o*i:-o*i},jo=class{_state="idle";_time=0;anchorNow=0;anchorTime=0;_trackDuration;constructor(e){this._trackDuration=e}get trackDuration(){return this._trackDuration}retargetDuration(e){this._trackDuration=e,this._time>e&&(this._time=e)}get state(){return this._state}get time(){return this._time}play(e){this._state==="idle"||this._state==="ended"?(this._time=0,this.anchorTime=0):this.anchorTime=this._time,this.anchorNow=e,this._state="playing"}pause(e){this._state==="playing"&&(this.syncTime(e),this._state=this._time>=this.trackDuration?"ended":"paused")}seek(e,t){this._time=Math.min(Math.max(t,0),this.trackDuration),this.anchorNow=e,this.anchorTime=this._time,this._state=this._time>=this.trackDuration?"ended":"paused"}stop(){this._state="idle",this._time=0,this.anchorNow=0,this.anchorTime=0}tick(e){return this._state==="idle"?null:(this._state==="playing"&&this.syncTime(e),{time:this._time,playing:this._state==="playing"})}syncTime(e){let t=(e-this.anchorNow)/1e3;this._time=Math.min(Math.max(this.anchorTime+t,0),this.trackDuration),this._time>=this.trackDuration&&(this._state="ended")}},zc=(n,e)=>Math.max(n,...e,0);var Qs=class{constructor(e){this.host=e;this.editorScrollEnabled=e.editorScroll!==!1,this.anchorScrollClock(performance.now(),0)}host;playback=null;player=null;totalDuration=0;overridesActive=!1;previews=new Map;previewOverridesActive=!1;scrollRunning=!1;scrollAnchorNow=0;scrollAnchorTime=0;editorHadTracks=!1;editorScrollEnabled;reset(){this.playback=null,this.player=null,this.totalDuration=0,this.overridesActive=!1,this.previews.clear(),this.previewOverridesActive=!1,this.scrollRunning=!1,this.editorHadTracks=!1,this.anchorScrollClock(performance.now(),0)}play(){this.cancelPreviews(),this.rebuild();let e=[...this.collectMediaDurations(),...this.collectScrollTextDurations()];this.totalDuration=zc(this.playback?.duration??0,e),this.player?this.player.retargetDuration(this.totalDuration):this.player=new jo(this.totalDuration);let t=performance.now();this.player.play(t),this.scrollRunning=!0,this.anchorScrollClock(t,this.player.time);for(let r of this.host.document.nodes)r instanceof ie?r.play():r instanceof ae&&r.playClipMedia();this.syncVideosToTime(this.player.time,!0),this.applyScrollTextOffsets(this.player.time),this.host.requestRenderAll()}pause(){let e=performance.now();this.anchorScrollClock(e,this.scrollClockTime(e)),this.scrollRunning=!1,this.player?.pause(e);for(let t of this.host.document.nodes)t instanceof ie?t.pause():t instanceof ae&&t.pauseClipMedia();this.host.requestRenderAll()}stop(){this.cancelPreviews(),this.player?.stop(),this.scrollRunning=!1,this.editorHadTracks=!1,this.anchorScrollClock(performance.now(),0),this.clearOverrides();for(let{node:e}of this.scrollTextTracks())e.setScrollOffset(0);for(let e of this.host.document.nodes)e instanceof ie?e.stop():e instanceof ae&&e.syncClipMediaToTime(0,!1);this.host.requestRenderAll()}seek(e){if(this.cancelPreviews(),!this.player){this.rebuild();let r=[...this.collectMediaDurations(),...this.collectScrollTextDurations()];this.totalDuration=zc(this.playback?.duration??0,r),this.player=new jo(this.totalDuration)}let t=performance.now();this.player.seek(t,e),this.scrollRunning=!1,this.anchorScrollClock(t,this.player.time),this.applyAnimationTime(this.player.time),this.applyScrollTextOffsets(this.player.time),this.syncVideosToTime(this.player.time,!1),this.host.requestRenderAll()}get info(){return!this.player&&!this.playback?null:{state:this.player?.state??"idle",time:this.player?.time??0,duration:this.totalDuration,animatedCount:this.playback?.timeline.length??0}}playSingleAnimation(e,t,r){let o=Lm(this.targetView(e),this.workspaceView(),t);if(!o)return!1;this.stopSingleAnimation(e);let i={target:e,plan:o,startAt:performance.now(),onComplete:r};this.previews.set(e,i);let s=Xc(0,o);return e.setAnimationOverride(s.override),(s.override||this.previewOverridesActive)&&this.host.document.refreshHitIndex(),this.previewOverridesActive=!!s.override,this.host.requestRenderAll(),!0}stopSingleAnimation(e){let t=e?this.previews.has(e)?[e]:[]:[...this.previews.keys()];if(t.length){for(let r of t)this.previews.delete(r),r.setAnimationOverride(null);this.previewOverridesActive&&this.host.document.refreshHitIndex(),this.previewOverridesActive=!1,this.host.requestRenderAll()}}get singlePreviewInfo(){let e=performance.now();return[...this.previews.values()].map(t=>{let r=(e-t.startAt)/1e3,o=t.plan.loopCount*t.plan.loopDuration;return{nodeId:t.target.id,key:t.plan.key,elapsed:r,duration:t.plan.delay+o,state:r<t.plan.delay?"delay":r<t.plan.delay+o?"playing":"done"}})}tick(e){let t=this.player,r=t?t.tick(e):null;r?(this.applyAnimationTime(r.time),this.applyScrollTextOffsets(this.scrollClockTime(e))):this.tickEditorScroll(e);let o=this.tickPreviews(e);return!!r?.playing||o||this.scrollClockAdvancing()}tickPreviews(e){if(!this.previews.size)return!1;let t=!1,r=!1;for(let o of[...this.previews.values()]){let i=(e-o.startAt)/1e3,s=Xc(i,o.plan);o.target.setAnimationOverride(s.override),s.override&&(r=!0),s.done?(this.previews.delete(o.target),o.onComplete?.()):t=!0}return(r||this.previewOverridesActive)&&this.host.document.refreshHitIndex(),this.previewOverridesActive=r,t}cancelPreviews(){this.previews.size&&this.stopSingleAnimation()}anchorScrollClock(e,t){this.scrollAnchorNow=e,this.scrollAnchorTime=t}scrollClockTime(e){return this.scrollClockAdvancing()?this.scrollAnchorTime+Math.max(0,(e-this.scrollAnchorNow)/1e3):this.scrollAnchorTime}hasLiveScrollTracks(){return this.scrollTextTracks().some(({input:e})=>e.scrollEnabled&&Vo(e)>0)}scrollClockAdvancing(){return this.hasLiveScrollTracks()?this.scrollRunning||this.editorScrollActive():!1}editorScrollActive(){return!this.editorScrollEnabled||this.player&&this.player.state!=="idle"?!1:this.hasLiveScrollTracks()}tickEditorScroll(e){if(!this.editorScrollActive()){this.editorHadTracks=!1;return}this.editorHadTracks||(this.anchorScrollClock(e,0),this.editorHadTracks=!0),this.applyScrollTextOffsets(this.scrollClockTime(e))}get scrollTextInfo(){return this.scrollTextTracks().map(({node:e,input:t})=>({id:e.id,offset:e.scrollOffset,duration:Vo(t),viewWidth:t.viewWidth,textTotalWidth:t.textTotalWidth,speed:t.scrollSpeed,direction:t.scrollDirection,enabled:t.scrollEnabled}))}applyAnimationTime(e){if(!this.playback)return;let t=!1;for(let{target:r,override:o}of Gc(e,this.playback))r.setAnimationOverride(o),o&&(t=!0);(t||this.overridesActive)&&this.host.document.refreshHitIndex(),this.overridesActive=t}clearOverrides(){if(this.playback){for(let{target:e}of Gc(0,this.playback))e.setAnimationOverride(null);this.host.document.refreshHitIndex(),this.overridesActive=!1}}rebuild(){let e=[];for(let t of this.host.document.nodes){let r=Rm(t.raw);r.length&&e.push({target:t,view:this.targetView(t),animates:r})}this.playback=Am(e,this.workspaceView())}targetView(e){let t=e.raw.scaleX??1,r=e.raw.scaleY??1,o=e.dims;return{left:e.raw.left??0,top:e.raw.top??0,scaleX:t,scaleY:r,angle:e.raw.angle??0,opacity:e.raw.opacity??1,width:o.x*t,height:o.y*r,center:Ut({...e.raw,width:o.x,height:o.y})}}workspaceView(){for(let e of this.host.document.nodes)if(e.raw.id===Sn)return{width:e.dims.x*(e.raw.scaleX??1),height:e.dims.y*(e.raw.scaleY??1)};return{width:0,height:0}}scrollTextTracks(){let e=[];for(let t of this.host.document.nodes){if(!(t instanceof ye))continue;let r=Xh(t);r&&e.push({node:t,input:r})}return e}collectScrollTextDurations(){return this.scrollTextTracks().map(({input:e})=>e.scrollEnabled?Vo(e):0)}applyScrollTextOffsets(e){for(let{node:t,input:r}of this.scrollTextTracks())t.setScrollOffset(Im(r,e,"loop"))}collectMediaDurations(){let e=[],t=r=>{for(let o of r)o instanceof ie?e.push(o.mediaDuration):o instanceof ae?o.clipMediaDuration>0&&e.push(o.clipMediaDuration):o instanceof J&&t(o.children)};return t(this.host.document.nodes),e}syncVideosToTime(e,t){let r=o=>{for(let i of o)i instanceof ie?i.syncVideoToTime(e,t):i instanceof ae?i.syncClipMediaToTime(e,t):i instanceof J&&r(i.children)};r(this.host.document.nodes)}};var _m=14,Dm=n=>n.fontFamily||"仓耳小丸子",Zs=class{host;session=null;offDocEvents;disposed=!1;constructor(e){this.host=e;let t=e.document.events,r=[t.on("text:changed",o=>this.onTextChanged(o)),t.on("text:editing:exited",()=>this.finish()),t.on("object:removed",o=>this.onOverlayRemoved(o))];this.offDocEvents=()=>r.forEach(o=>o())}dispose(){this.disposed||(this.disposed=!0,this.offDocEvents())}get active(){return this.session!==null}isOverlay(e){return this.session?.overlay===e}get info(){let e=this.session;return e?{tableId:e.table.id,row:e.row,col:e.col,text:e.overlay.raw.text??""}:null}startEditing(e,t,r,o={}){let i=this.host.document;if(!i.nodes.includes(e))return!1;let s=lt(e.cellMap,t,r),a=e.cellBounds(s.row,s.col);if(!a)return!1;i.editingNode&&i.exitEditing(),e.rebuildTable();let l=JSON.stringify(e.toObject()),u=e.raw,c=u.cellPadding??8,h=we(e.cellMap,s.row,s.col),d=e.cellSceneCenter(s.row,s.col),f={type:"textbox",id:`${e.id}-cell-edit`,text:o.initialText??h?.text??"",left:d.x,top:d.y,width:Math.max(0,a.width-c*2),originX:"center",originY:"center",scaleX:u.scaleX??1,scaleY:u.scaleY??1,angle:e.tableAngle,fill:h?.textFill??u.textFill,fontSize:h?.fontSize??_m,fontWeight:h?.fontWeight,fontStyle:h?.fontStyle,fontFamily:h?.fontFamily||Dm(u),textAlign:h?.textAlign??fe.CENTER,lineHeight:1.16,splitByGrapheme:!0,opacity:1,visible:!0},m=new ye(f);if(e.editingCell=s,e.clearCellInteractionState(),this.session={overlay:m,table:e,row:s.row,col:s.col,snapshot:l,data:h??null},i.add(m),e.rebuildTable(),(i.selection.length!==1||i.selection[0]!==e)&&i.setSelection([e],"update"),i.enterEditing(m,{transient:!0}),o.initialText===void 0){let p=m.textLayout.graphemeCodeUnitOffsets.length-1;this.host.setEditingSelection(0,p)}return this.host.requestRenderAll(),!0}onTextChanged(e){let t=this.session;if(!t||e!==t.overlay)return;if(!t.data){let o=Array.isArray(t.table.raw.cellData)?t.table.raw.cellData:t.table.raw.cellData=[];t.data={row:t.row,col:t.col,fill:t.table.raw.cellFill,stroke:t.table.raw.cellStroke,text:"",textFill:t.table.raw.textFill,fontSize:_m,fontWeight:"normal",fontStyle:"normal",fontFamily:Dm(t.table.raw),textAlign:"center"},o.push(t.data)}t.data.text=e.raw.text??"",t.table.rebuildTable();let r=t.table.cellSceneCenter(t.row,t.col);r&&e.set({left:r.x,top:r.y}),this.host.requestRenderAll()}finish(){let e=this.session;if(!e)return;this.session=null;let t=this.host.document;if(e.table.editingCell=null,t.remove(e.overlay),e.table.rebuildTable(),t.setSelection([e.table],"create"),e.table.setCellSelection([{row:e.row,col:e.col}],{row:e.row,col:e.col},{r1:e.row,r2:e.row,c1:e.col,c2:e.col}),JSON.stringify(e.table.toObject())!==e.snapshot){let r=new Map;r.set(e.table,JSON.parse(e.snapshot)),t.applyTransform([e.table],()=>({}),"modified",{action:Le.tableCellEdit,before:r})}this.host.requestRenderAll()}onOverlayRemoved(e){let t=this.session;!t||e!==t.overlay||(this.session=null,t.table.editingCell=null,t.table.rebuildTable(),this.host.requestRenderAll())}};var O0=530,Fm=[.1,.1,.1,1],B0=[.18,.44,.96,.3],Js=class{host;textarea=null;blinkTimer=null;caretVisible=!0;onSelectionChange=null;offDocEvents;inComposition=!1;compositionRange=null;constructor(e){this.host=e;let t=e.document.events,r=[t.on("text:changed",()=>{this.positionAtCaret(),this.host.requestRenderAll()}),t.on("text:editing:entered",()=>this.startUi()),t.on("text:editing:exited",()=>this.stopUi())];this.offDocEvents=()=>r.forEach(o=>o())}get composing(){return this.inComposition}enterEditingAtClick(e,t,r){let o=this.host.document.editingNode===e;if(this.host.document.enterEditing(e),!o){let u=e.textLayout.graphemeCodeUnitOffsets.length-1;this.setSelection(0,u);return}let i=e.localPoint(t,r),s=e.cursorIndexAt(i.x,i.y),[a,l]=e.wordBoundsAt(s);this.setSelection(a,l)}setSelection(e,t){let r=this.host.document.editingNode;if(!r)return;this.host.document.editSelection.start=e,this.host.document.editSelection.end=t;let o=this.textarea;if(o){let i=r.textLayout.graphemeCodeUnitOffsets,s=i[Math.min(e,i.length-1)]??0,a=i[Math.min(t,i.length-1)]??0;o.setSelectionRange(Math.min(s,a),Math.max(s,a))}this.caretVisible=!0,this.positionAtCaret(),this.focusTextarea(),this.host.requestRenderAll()}buildOverlay(){let e=this.host.document.editingNode;if(!e)return[];let t=e.textLayout,r=this.host.document.editSelection,o=Math.min(r.start,r.end),i=Math.max(r.start,r.end),s=e.matrix,a=Math.hypot(s[0],s[1])||1,l=[];for(let u of t.lines){let c=u.styleMap.flatStart,h=c+u.graphemes.length,d=Math.max(o,c),f=Math.min(i,h);if(f>d){let m=-t.width/2+u.leftOffset,p=m+(d<h?u.boxes[d-c].left:hn(u)),b=m+(f<h?u.boxes[f-c].left:hn(u));if(b>p){let g=e.contentTopY+u.top;l.push({matrix:j(s,[1,0,0,1,(p+b)/2,g+u.implHeight/2]),dims:{x:b-p,y:u.implHeight},color:B0})}}}if(o===i&&this.caretVisible&&!this.inComposition){let u=e.cursorCoord(o);if(u){let c=2/this.host.zoom/a;l.push({matrix:j(s,[1,0,0,1,u.x+c/2,u.y+u.height/2]),dims:{x:c,y:u.height},color:Fm})}}if(this.inComposition&&this.compositionRange){let u=this.compositionRange.start,c=this.compositionRange.end,h=t.lines.find(d=>{let f=d.styleMap.flatStart;return u>=f&&u<=f+d.graphemes.length});if(h){let d=h.styleMap.flatStart,f=-t.width/2+h.leftOffset,m=f+(u-d<h.boxes.length?h.boxes[u-d].left:hn(h)),p=f+(c-d<h.boxes.length?h.boxes[c-d].left:hn(h)),g=e.contentTopY+h.baseline+e.textStyle.fontSize*.14;l.push({matrix:j(s,[1,0,0,1,(m+p)/2,g]),dims:{x:Math.max(0,p-m),y:1.5/this.host.zoom/a},color:Fm})}}return l}startUi(){let e=this.host.document.editingNode;if(!e)return;let t=this.ensureTextarea();t.value=e.raw.text??"",this.positionAtCaret();let r=t.value.length;t.setSelectionRange(r,r),this.focusTextarea(),this.caretVisible=!0,this.inComposition=!1,this.compositionRange=null,this.blinkTimer!==null&&window.clearInterval(this.blinkTimer),this.blinkTimer=window.setInterval(()=>{this.caretVisible=!this.caretVisible,this.host.requestRenderAll()},O0),this.host.requestRenderAll()}stopUi(){this.blinkTimer!==null&&(window.clearInterval(this.blinkTimer),this.blinkTimer=null),this.textarea?.blur(),this.textarea?.remove(),this.textarea=null,this.host.requestRenderAll()}ensureTextarea(){if(this.textarea)return this.textarea;let e=document.createElement("textarea");return e.setAttribute("data-engine-editing",""),e.autocomplete="off",e.spellcheck=!1,Object.assign(e.style,{position:"absolute",opacity:"0",width:"4px",height:"20px",padding:"0",border:"none",overflow:"hidden",resize:"none",background:"transparent",pointerEvents:"none",zIndex:"0"}),this.host.canvasEl.parentElement?.appendChild(e),e.addEventListener("input",()=>{this.host.document.updateEditingText(e.value,e.selectionStart??0,e.selectionEnd??0)}),e.addEventListener("compositionstart",()=>{this.inComposition=!0,this.caretVisible=!0,this.blinkTimer!==null&&(window.clearInterval(this.blinkTimer),this.blinkTimer=null)}),e.addEventListener("compositionupdate",t=>{let r=t.data??"",i=t.target.selectionStart??0;this.compositionRange={start:i-r.length,end:i},this.positionAtCaret(),this.host.requestRenderAll()}),e.addEventListener("compositionend",()=>{this.inComposition=!1,this.compositionRange=null,this.host.requestRenderAll()}),e.addEventListener("keydown",t=>{if(t.stopPropagation(),t.key==="Escape"){if(this.inComposition)return;t.preventDefault(),this.host.document.exitEditing();return}if(this.inComposition)return;let r=this.navigateKey(t);r&&(t.preventDefault(),e.setSelectionRange(r[0],r[1],r[2]),this.host.document.updateEditingSelection(r[0],r[1]),this.caretVisible=!0,this.positionAtCaret(),this.host.requestRenderAll())}),this.onSelectionChange&&document.removeEventListener("selectionchange",this.onSelectionChange),this.onSelectionChange=()=>{let t=this.textarea;t&&this.host.document.editingNode&&document.activeElement===t&&(this.host.document.updateEditingSelection(t.selectionStart??0,t.selectionEnd??0),this.positionAtCaret(),this.host.requestRenderAll())},document.addEventListener("selectionchange",this.onSelectionChange),this.textarea=e,e}focusTextarea(){this.textarea?.focus({preventScroll:!0})}positionAtCaret(){let e=this.host.document.editingNode,t=this.textarea;if(!e||!t)return;let r=this.host.document.editSelection,o=e.cursorCoord(Math.min(r.start,r.end));if(!o)return;let i=e.matrix,s=i[0]*o.x+i[2]*o.y+i[4],a=i[1]*o.x+i[3]*o.y+i[5],l=this.host.toScreen(s,a),u=this.host.canvasEl.getBoundingClientRect(),c=this.host.canvasEl.parentElement?.getBoundingClientRect()??u;t.style.left=`${u.left-c.left+l.x}px`,t.style.top=`${u.top-c.top+l.y}px`}navigateKey(e){let t=this.host.document.editingNode;if(!t||e.ctrlKey||e.metaKey||e.altKey)return null;let r=t.textLayout,o=r.graphemeCodeUnitOffsets,i=o.length-1,s=this.host.document.editSelection,a=e.shiftKey?Math.max(s.start,s.end):s.end,l=e.shiftKey?Math.min(s.start,s.end):a,u=p=>o[Math.max(0,Math.min(p,i))]??0,c=p=>{for(let b=0;b<r.lines.length;b++){let g=r.lines[b].styleMap.flatStart;if(p<=g+r.lines[b].graphemes.length)return b}return r.lines.length-1},h=(p,b)=>{let g=r.lines[p],x=b-g.styleMap.flatStart;return-r.width/2+g.leftOffset+(x<g.boxes.length?g.boxes[x].left:hn(g))},d=(p,b)=>{let g=r.lines[p],x=-r.width/2+g.leftOffset;for(let S=0;S<g.boxes.length;S++)if(b<x+g.boxes[S].left+g.boxes[S].width/2)return g.styleMap.flatStart+S;return g.styleMap.flatStart+g.graphemes.length},f,m;switch(e.key){case"ArrowLeft":f=Math.max(0,a-1),m="backward";break;case"ArrowRight":f=Math.min(i,a+1),m="forward";break;case"Home":case"End":{let p=r.lines[c(a)];f=e.key==="Home"?p.styleMap.flatStart:p.styleMap.flatStart+p.graphemes.length,m=e.key==="Home"?"backward":"forward";break}case"ArrowUp":case"ArrowDown":{let p=c(a),b=e.key==="ArrowUp"?p-1:p+1;if(b<0||b>=r.lines.length)return null;f=d(b,h(p,a)),m=e.key==="ArrowUp"?"backward":"forward";break}default:return null}return e.shiftKey?[u(Math.min(l,f)),u(Math.max(l,f)),m]:[u(f),u(f),"none"]}dispose(){this.offDocEvents(),this.onSelectionChange&&document.removeEventListener("selectionchange",this.onSelectionChange),this.blinkTimer!==null&&window.clearInterval(this.blinkTimer),this.textarea?.remove(),this.textarea=null}};var Om=(n,e={})=>{let t=n.getContext("webgl2",{alpha:!0,premultipliedAlpha:!0,antialias:!0,stencil:!0,preserveDrawingBuffer:!0,powerPreference:"high-performance"});if(!t)return null;let r=a=>{a.preventDefault(),e.onLost?.()},o=()=>e.onRestored?.();n.addEventListener("webglcontextlost",r),n.addEventListener("webglcontextrestored",o);let i=t.getExtension("WEBGL_debug_renderer_info"),s=i?String(t.getParameter(i.UNMASKED_RENDERER_WEBGL)):"unknown";return{gl:t,capabilities:{maxTextureSize:t.getParameter(t.MAX_TEXTURE_SIZE),maxTextureUnits:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),renderer:s},dispose:()=>{n.removeEventListener("webglcontextlost",r),n.removeEventListener("webglcontextrestored",o)}}};var ea=n=>n.trim().replace(/^['"]|['"]$/g,"").toLowerCase(),Bm=n=>{let e=new Set;for(let t of n){let r=ea(t?.family??"");r&&e.add(r)}return e},W0=n=>{let e=new Set,t=o=>{if(!(typeof o!="string"||!o))for(let i of o.split(",")){let s=ea(i);s&&e.add(s)}};t(n.raw.fontFamily);let r=n.raw.styles;if(r&&typeof r=="object"){for(let o of Object.values(r))if(!(!o||typeof o!="object"))for(let i of Object.values(o))i&&typeof i=="object"&&t(i.fontFamily)}return e},Wm=(n,e)=>{let t=[],r=o=>{for(let i of o)if(i instanceof ye){for(let s of W0(i))if(e.has(s)){t.push(i);break}}else i instanceof J&&r(i.children)};return r(n),t};var ta=class{constructor(e,t,r,o){this.host=e;this.textRenderer=t;this.glyphAtlas=r;this.renderer=o}host;textRenderer;glyphAtlas;renderer;pendingSettle=new Set;invalidateNodeTextBakes(e){this.host.engineDisposed||(this.textRenderer.invalidateNodeBakes(e),e.markRenderDirty(),this.host.requestRenderAll())}handleFontsLoaded(e){if(this.host.engineDisposed||this.host.engineContextLost)return;let t=Bm(e);t.size===0||!this.invalidateTextCachesFor(t)||(this.glyphAtlas.reset(),this.host.requestRenderAll(),this.host.render())}invalidateTextCachesFor(e){let t=Wm(this.host.document.nodes,e);if(t.length===0)return!1;for(let r of t)r.invalidateTextLayout(),this.textRenderer.invalidateNodeBakes(r);return ch(),this.renderer.invalidateTextDerivedBakes(),!0}queueSettle(e){if(!(this.host.engineDisposed||e.length===0))for(let t of e)this.pendingSettle.add(t)}consumePendingSettle(){if(this.pendingSettle.size===0)return;let e=new Set(this.pendingSettle);this.pendingSettle.clear(),this.invalidateTextCachesFor(e)}};var Nn=class{_value=0;_lastReason="";get value(){return this._value}get lastReason(){return this._lastReason}bump(e){this._value++,this._lastReason=e}};var pt=1024,H0=2,G0=256,Ht=n=>{let e=[.5,1,2,4];for(let t of e)if(n<=t+1e-6)return t;return e[e.length-1]},X0=256,ra=(n,e)=>{let t=Math.max(6,Math.ceil(n*e)),r=Math.max(X0,Math.ceil(n));return t<=r?{rs:t,scale:e}:{rs:r,scale:r/Math.max(1,n)}},na=class{gl;pages=new Map;currentPage=null;nextPageIndex=0;frameStamp=0;cells=new Map;tmpCanvas;disposed=!1;pageCap=12;pendingTrim=!1;_generation=0;provisionalFaces=new Map;faceLoads=new Map;onCellsInvalidated;onProvisionalSettled;detachFontsListener=null;epoch;constructor(e,t,r,o=new Nn){this.gl=e,this.onCellsInvalidated=t,this.onProvisionalSettled=r,this.epoch=o,this.tmpCanvas=document.createElement("canvas"),this.tmpCanvas.width=8,this.tmpCanvas.height=8;let i=this.fontSet();if(i&&typeof i.addEventListener=="function"){let s=()=>this.dropProvisionalCells();i.addEventListener("loadingdone",s),this.detachFontsListener=()=>i.removeEventListener("loadingdone",s)}}fontSet(){return typeof document>"u"?null:document.fonts??null}isFacePending(e,t){let r=this.fontSet();if(!r||typeof r.check!="function")return!1;try{if(!r.check(e))return!0;let o=t.fontFamily?.trim().replace(/^['"]|['"]$/g,"")??"";if(!o||o.includes(",")||ul.has(o.toLowerCase())||typeof r.forEach!="function")return!1;let i=!1;return r.forEach(s=>{i||typeof s?.family!="string"||(s.family===o||s.family.toLowerCase()===o.toLowerCase())&&(i=!0)}),!i}catch{return!1}}kickFaceLoad(e){if(this.faceLoads.has(e))return;let t=this.fontSet();if(!t||typeof t.load!="function")return;let r={};this.faceLoads.set(e,r);let o=()=>{this.faceLoads.get(e)===r&&this.faceLoads.delete(e)};try{t.load(e).then(o,o)}catch{o()}}dropProvisionalCells(){if(!(this.disposed||this.provisionalFaces.size===0)){for(let e of this.provisionalFaces.values())for(let t of e.keys)this.cells.delete(t);this.provisionalFaces.clear(),this.onCellsInvalidated?.()}}markFrame(){this.pendingTrim&&this.trimUnusedPages(),this.frameStamp++,this.settleProvisionalCells()}keepPagesForRetainedFrame(){for(let e of this.pages.values())e.lastFrame=this.frameStamp}trimUnusedPages(){let e=[...this.pages.values()].filter(r=>r.lastFrame<this.frameStamp).sort((r,o)=>r.lastFrame-o.lastFrame),t=!1;for(let r of e){if(this.pages.size<=this.pageCap)break;this.gl.deleteTexture(r.texture),this.pages.delete(r.index),this.currentPage===r&&(this.currentPage=null),t=!0}if(this.pendingTrim=this.pages.size>this.pageCap,!!t){for(let[r,o]of this.cells)this.pages.has(o.pageIndex)||this.cells.delete(r);for(let[r,o]of this.provisionalFaces){for(let i of o.keys)this.cells.has(i)||o.keys.delete(i);o.keys.size===0&&this.provisionalFaces.delete(r)}this._generation++,this.epoch.bump("atlas-trim")}}settleProvisionalCells(){if(this.disposed||this.provisionalFaces.size===0)return;let e=!1,t=new Set;for(let[r,o]of this.provisionalFaces)if(!this.isFacePending(r,o.style)){for(let s of o.keys)this.cells.delete(s);this.provisionalFaces.delete(r),e=!0;let i=ea(o.style.fontFamily??"");i&&t.add(i)}e&&(this.onCellsInvalidated?.(),t.size>0&&this.onProvisionalSettled?.([...t]))}reset(){let e=this.pages.size>0;if(!this.disposed&&e)for(let t of this.pages.values())this.gl.deleteTexture(t.texture);this.pages.clear(),this.currentPage=null,this.pendingTrim=!1,this.cells.clear(),this.provisionalFaces.clear(),e&&(this._generation++,this.epoch.bump("atlas-reset"),zn()&&console.warn("[retained] GlyphAtlas.reset → generation",this._generation,new Error("reset 调用栈取证").stack))}get generation(){return this._generation}stats(){return{pages:this.pages.size,cells:this.cells.size,pageCap:this.pageCap,pendingReset:!1,pendingTrim:this.pendingTrim,generation:this._generation}}get(e,t,r,o=null){if(this.disposed||r===" "||r===""||r===`
9
+ `||r===" ")return null;let i=`${e.fontFamily}|${e.fontWeight??""}|${e.fontStyle??""}|${t}|${r}`;o&&(i+=`|S${o.width}|${o.lineJoin??""}|${o.lineCap??""}|${o.miterLimit??""}`);let s=this.cells.get(i);if(s)return this.pages.get(s.pageIndex).lastFrame=this.frameStamp,s;let a=Me(e,t),l=this.isFacePending(a,e);l&&this.kickFaceLoad(a);let u=this.rasterize(e,t,r,o);if(u&&(this.cells.set(i,u),l)){let c=this.provisionalFaces.get(a);c||(c={style:{fontFamily:e.fontFamily,fontSize:e.fontSize,fontWeight:e.fontWeight,fontStyle:e.fontStyle},keys:new Set},this.provisionalFaces.set(a,c)),c.keys.add(i)}return u}rasterize(e,t,r,o){let i=this.currentPage;i||(i=this.newPage());let s=i.ctx;s.font=Me(e,t),s.textBaseline="alphabetic",s.textAlign="left",s.fillStyle="#ffffff";let a=s.measureText(r);if(!isFinite(a.width)||a.width<=0&&r.trim()==="")return null;let l=a.actualBoundingBoxLeft??0,u=a.actualBoundingBoxRight??a.width,c=a.actualBoundingBoxAscent??t*.88,h=a.actualBoundingBoxDescent??t*.24,d=t/Math.max(1,e.fontSize),f=o?Math.max(.5,o.width*d):0,m=o?Math.min(f*Math.max(1,o.miterLimit??4)/2,G0):0,p=H0+(o?Math.ceil(m)+1:0),b=Math.max(1,Math.ceil(l+u)+p*2),g=Math.max(1,Math.ceil(c+h)+p*2);if(b>pt||g>pt)return null;i.cursorX+b>pt&&(i.cursorX=0,i.cursorY+=i.rowHeight,i.rowHeight=0),i.cursorY+g>pt&&(i=this.newPage());let x=i.ctx;x.font=Me(e,t),x.textBaseline="alphabetic",x.textAlign="left",x.fillStyle="#ffffff";let S=i.cursorX,w=i.cursorY,y=S+p+l,v=w+p+c;x.save(),o?(x.lineWidth=f,x.lineJoin=o.lineJoin??"miter",x.lineCap=o.lineCap??"butt",x.miterLimit=Math.max(1,o.miterLimit??4),x.strokeStyle="#ffffff",x.strokeText(r,y,v)):x.fillText(r,y,v),x.restore(),(this.tmpCanvas.width<b||this.tmpCanvas.height<g)&&(this.tmpCanvas.width=Math.max(this.tmpCanvas.width,b),this.tmpCanvas.height=Math.max(this.tmpCanvas.height,g));let R=this.tmpCanvas.getContext("2d");return R.clearRect(0,0,this.tmpCanvas.width,this.tmpCanvas.height),R.drawImage(i.canvas,S,w,b,g,0,0,b,g),this.gl.bindTexture(this.gl.TEXTURE_2D,i.texture),this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,S,w,b,g,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.tmpCanvas),i.cursorX+=b,i.rowHeight=Math.max(i.rowHeight,g),{pageIndex:i.index,u0:S/pt,v0:w/pt,u1:(S+b)/pt,v1:(w+g)/pt,wPx:b,hPx:g,inkLeftPx:-l,ascentPx:c,padPx:p,advancePx:a.width}}textureOf(e){let t=this.pages.get(e.pageIndex);return t?(t.lastFrame=this.frameStamp,t.texture):null}newPage(){this.pages.size>=this.pageCap&&(this.pendingTrim=!0);let e=document.createElement("canvas");e.width=pt,e.height=pt;let t=e.getContext("2d"),r=this.gl.createTexture();this.gl.bindTexture(this.gl.TEXTURE_2D,r),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,pt,pt,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE);let o={index:this.nextPageIndex++,lastFrame:this.frameStamp,canvas:e,ctx:t,texture:r,cursorX:0,cursorY:0,rowHeight:0};return this.pages.set(o.index,o),this.currentPage=o,o}dispose(){if(!this.disposed){this.disposed=!0,this.detachFontsListener?.(),this.detachFontsListener=null;for(let e of this.pages.values())this.gl.deleteTexture(e.texture);this.pages.clear(),this.currentPage=null,this.pendingTrim=!1,this.cells.clear(),this.provisionalFaces.clear(),this.faceLoads.clear()}}};var Ur=(n,e,t,r)=>{if(!t){n.uniform1i(e.paintMode,0);return}n.uniform1i(e.paintMode,t.kind==="gradient"?t.decl.kind==="linear"?1:2:3),n.uniformMatrix3fv(e.paintInv,!1,[t.inv[0],t.inv[1],0,t.inv[2],t.inv[3],0,t.inv[4],t.inv[5],1]),t.kind==="gradient"?t.decl.kind==="linear"?n.uniform4f(e.paintA,t.decl.x1,t.decl.y1,t.decl.x2,t.decl.y2):(n.uniform4f(e.paintA,t.decl.x1,t.decl.y1,t.decl.r1,0),n.uniform4f(e.paintB,t.decl.x2,t.decl.y2,t.decl.r2,0)):n.uniform4f(e.patInfo,t.size[0],t.size[1],t.repeat[0]?1:0,t.repeat[1]?1:0),n.activeTexture(n.TEXTURE0+r),n.bindTexture(n.TEXTURE_2D,t.tex),n.uniform1i(e.fillTex,r)},oa=class{gl;cache=new Map;disposed=!1;constructor(e){this.gl=e}get(e){if(this.disposed)return null;let t=pi(e),r=this.cache.get(t);if(r)return r;let o=this.gl,i=o.createTexture();if(!i)return null;let s=mi(e);return o.bindTexture(o.TEXTURE_2D,i),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,s.length/4,1,0,o.RGBA,o.UNSIGNED_BYTE,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),this.cache.set(t,i),i}invalidateAll(){for(let e of this.cache.values())this.gl.deleteTexture(e);this.cache.clear()}dispose(){this.disposed||(this.disposed=!0,this.invalidateAll())}};var z0=512*1024*1024,Y0=2048,U0=30,$0=32*1024*1024,ia=class{gl;cache=new Map;budgetBytes;maxEntries;evictGraceFrames;gestureActive=!1;frameStamp=0;frameTouches=0;evictions=0;trackedBytes=0;disposed=!1;epoch;constructor(e,t={}){this.gl=e,this.budgetBytes=t.budgetBytes??z0,this.maxEntries=t.maxEntries??Y0,this.evictGraceFrames=t.evictGraceFrames??U0,this.epoch=t.epoch??new Nn}markFrame(e=!1){this.frameStamp+=1,this.frameTouches=0,this.gestureActive=e}get evictionCount(){return this.evictions}setBudget(e){e>0&&(this.budgetBytes=e,this.evictIfNeeded(0,!1))}get(e){if(this.disposed)return null;let t=this.cache.get(e);if(t)return t.lastFrame=this.frameStamp,this.frameTouches+=1,this.cache.delete(e),this.cache.set(e,t),t.tex;let r=this.gl.createTexture();if(!r)return null;let o=!(e instanceof HTMLVideoElement);this.gl.bindTexture(this.gl.TEXTURE_2D,r),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),o?(this.gl.generateMipmap(this.gl.TEXTURE_2D),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR_MIPMAP_LINEAR)):this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE);let i=j0(e,o),s={tex:r,mipmap:o,bytes:i,lastFrame:this.frameStamp};return this.evictIfNeeded(i,!0),this.trackedBytes+=i,this.frameTouches+=1,this.cache.set(e,s),r}evictIfNeeded(e,t){if(!this.disposed&&!(t&&this.gestureActive)){for(;this.trackedBytes+e>this.budgetBytes||this.cache.size>=this.maxEntries;)if(!(this.evictOldestEligible(t,!1)||this.evictOldestEligible(t,!0)))return}}evictOldestEligible(e,t){for(let[r,o]of this.cache)if(!(e&&this.frameStamp-o.lastFrame<this.evictGraceFrames)&&!(!t&&o.bytes>=$0))return this.gl.deleteTexture(o.tex),this.cache.delete(r),this.trackedBytes-=o.bytes,this.evictions+=1,this.epoch.bump("texture-evict"),!0;return!1}update(e){if(this.disposed)return;let t=this.cache.get(e);t&&(this.gl.bindTexture(this.gl.TEXTURE_2D,t.tex),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),t.mipmap&&this.gl.generateMipmap(this.gl.TEXTURE_2D))}remove(e){let t=this.cache.get(e);t&&(this.gl.deleteTexture(t.tex),this.cache.delete(e),this.trackedBytes-=t.bytes)}invalidateAll(){for(let e of this.cache.values())this.gl.deleteTexture(e.tex);this.cache.clear(),this.trackedBytes=0}stats(){return{entries:this.cache.size,bytes:this.trackedBytes,budgetBytes:this.budgetBytes,maxEntries:this.maxEntries,evictions:this.evictions,frameTouches:this.frameTouches}}dispose(){this.disposed||(this.disposed=!0,this.invalidateAll())}},j0=(n,e)=>{let t=n instanceof HTMLVideoElement?n.videoWidth:n instanceof HTMLImageElement&&n.naturalWidth||n.width,r=n instanceof HTMLVideoElement?n.videoHeight:n instanceof HTMLImageElement&&n.naturalHeight||n.height,o=Math.max(1,t)*Math.max(1,r)*4;return Math.round(e?o*(4/3):o)};var Hm=`#version 300 es
10
10
  layout(location = 0) in vec2 aCorner;
11
11
  layout(location = 1) in vec2 aRow0;
12
12
  layout(location = 2) in vec2 aRow1;
@@ -39,7 +39,7 @@ vHalf = aDim * 0.5;
39
39
  vShape = aUv;
40
40
  vDash = aDash;
41
41
  vSeg = aSeg;
42
- }`,Hm=`uniform int uPaintMode;
42
+ }`,Gm=`uniform int uPaintMode;
43
43
  uniform mat3 uPaintInv;
44
44
  uniform vec4 uPaintA;
45
45
  uniform vec4 uPaintB;
@@ -71,7 +71,7 @@ float disc = max(b * b - 4.0 * a * c, 0.0);
71
71
  t = abs(a) > 1e-9 ? (-b - sqrt(disc)) / (2.0 * a) : (abs(b) > 1e-9 ? -c / b : 0.0);
72
72
  }
73
73
  return texture(uFillTex, vec2(clamp(t, 0.0, 1.0), 0.5));
74
- }`,Gm=`#version 300 es
74
+ }`,Xm=`#version 300 es
75
75
  precision highp float;
76
76
  in vec2 vUv;
77
77
  in vec4 vColor;
@@ -85,7 +85,7 @@ uniform sampler2D uTex;
85
85
  uniform float uPenScale;
86
86
  uniform sampler2D uSegTex;
87
87
  const int MAX_QUAD_SEG = 64;
88
- ${Hm}
88
+ ${Gm}
89
89
  out vec4 fragColor;
90
90
  float sdRoundBoxDist(vec2 p, vec2 halfSize, vec2 r) {
91
91
  vec2 q = (abs(p) - (halfSize - r)) / max(r, vec2(1e-6));
@@ -233,7 +233,7 @@ return cov;
233
233
  void main() {
234
234
  fragColor = paintColor(vLocal, texture(uTex, vUv)) * vColor;
235
235
  fragColor.a *= -vRadius.y > 0.5 ? strokeCoverage(vLocal, vRadius, vShape, vDash, vSeg, uPenScale) : roundedCoverage(vLocal, vHalf, vRadius);
236
- }`,Xm=`#version 300 es
236
+ }`,zm=`#version 300 es
237
237
  layout(location = 0) in vec2 aPos;
238
238
  layout(location = 1) in vec4 aColor;
239
239
  layout(location = 2) in vec2 aLocal;
@@ -245,21 +245,21 @@ vec3 clip = uView * vec3(aPos, 1.0);
245
245
  gl_Position = vec4(clip.xy, 0.0, 1.0);
246
246
  vColor = aColor;
247
247
  vLocal = aLocal;
248
- }`,zm=`#version 300 es
248
+ }`,Ym=`#version 300 es
249
249
  precision mediump float;
250
250
  in vec4 vColor;
251
251
  in vec2 vLocal;
252
- ${Hm}
252
+ ${Gm}
253
253
  out vec4 fragColor;
254
254
  void main() {
255
255
  fragColor = paintColor(vLocal, vColor);
256
- }`,sa=(n,e,t)=>{let r=(a,l)=>{let u=n.createShader(a);return u?(n.shaderSource(u,l),n.compileShader(u),n.getShaderParameter(u,n.COMPILE_STATUS)?u:(console.error("[engine] shader compile failed:",n.getShaderInfoLog(u)),n.deleteShader(u),null)):null},o=r(n.VERTEX_SHADER,e),i=r(n.FRAGMENT_SHADER,t);if(!o||!i)return o&&n.deleteShader(o),i&&n.deleteShader(i),null;let s=n.createProgram();return s?(n.attachShader(s,o),n.attachShader(s,i),n.linkProgram(s),n.deleteShader(o),n.deleteShader(i),n.getProgramParameter(s,n.LINK_STATUS)?{program:s,uniforms:{view:n.getUniformLocation(s,"uView"),tex:n.getUniformLocation(s,"uTex"),penScale:n.getUniformLocation(s,"uPenScale"),segTex:n.getUniformLocation(s,"uSegTex"),paintMode:n.getUniformLocation(s,"uPaintMode"),paintInv:n.getUniformLocation(s,"uPaintInv"),paintA:n.getUniformLocation(s,"uPaintA"),paintB:n.getUniformLocation(s,"uPaintB"),fillTex:n.getUniformLocation(s,"uFillTex"),patInfo:n.getUniformLocation(s,"uPatInfo")}}:(console.error("[engine] program link failed:",n.getProgramInfoLog(s)),n.deleteProgram(s),null)):(n.deleteShader(o),n.deleteShader(i),null)};var $r=n=>{let e=2166136261;for(let t=0;t<n.length;t++)e=Math.imul(e^Math.round(n[t]*256),16777619);return e>>>1},aa=class{constructor(e){this.gl=e}gl;tex=null;data=new Float32Array(0);rowOwners=[];rowHashes=[];rows=0;healthy=!0;ensureRows(e){if(!this.healthy)return!1;if(e<=this.rows)return!0;let t=this.gl;try{let r=new Float32Array(e*64*4);r.set(this.data);let o=this.tex??t.createTexture();if(!o)return this.healthy=!1,!1;for(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,64,e,0,t.RGBA,t.FLOAT,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.activeTexture(t.TEXTURE0),this.tex=o,this.data=r;this.rowOwners.length<e;)this.rowOwners.push(null),this.rowHashes.push(0);return this.rows=e,!0}catch{return this.healthy=!1,!1}}writeRow(e,t,r){if(!this.healthy||e>=this.rows||t&&this.rowOwners[e]===t&&this.rowHashes[e]===r.hash)return;let o=e*64*4;this.data.fill(0,o,o+256),this.data.set(r.data.subarray(0,r.count*4),o),this.rowOwners[e]=t,this.rowHashes[e]=r.hash;let i=this.gl;i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this.tex),i.texSubImage2D(i.TEXTURE_2D,0,0,e,r.count,1,i.RGBA,i.FLOAT,this.data,o),i.activeTexture(i.TEXTURE0)}rowAt(e){return e>=this.rows?null:this.data.slice(e*64*4,(e+1)*64*4)}get texture(){return this.tex}get rowCount(){return this.rows}dispose(){this.tex&&this.gl.deleteTexture(this.tex),this.tex=null,this.data=new Float32Array(0),this.rowOwners=[],this.rowHashes=[],this.rows=0}};var qe=24,Ym=new Float32Array(9),j0=4096,V0=new Float32Array([0,0,1,0,1,1,0,1]),q0=new Uint16Array([0,1,2,0,2,3]),tn=class{gl;order=null;gpuRecords=new Map;ownerBlocks=new WeakMap;pendingSegments=[];pendingUploads=[];deferDraws=!1;frameSlots=null;drawnFrom=0;programInfo=null;vao=null;cornerBuffer=null;indexBuffer=null;instanceBuffer=null;instanceData=new Float32Array(j0*qe);whiteTexture=null;segmentTable=null;instanceCount=0;currentTexture=null;currentGradient=null;viewMat=[1,0,0,1,0,0];penScale=1;disposed=!1;constructor(e){this.gl=e,this.init()}init(){let e=this.gl;if(this.programInfo=sa(e,Wm,Gm),!this.programInfo){this.disposed=!0;return}this.whiteTexture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.whiteTexture),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255])),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.cornerBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.cornerBuffer),e.bufferData(e.ARRAY_BUFFER,V0,e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),this.indexBuffer=e.createBuffer(),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,q0,e.STATIC_DRAW),this.instanceBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.instanceBuffer),e.bufferData(e.ARRAY_BUFFER,this.instanceData.byteLength,e.DYNAMIC_DRAW);let t=qe*4,r=(o,i,s)=>{e.enableVertexAttribArray(o),e.vertexAttribPointer(o,i,e.FLOAT,!1,t,s*4),e.vertexAttribDivisor(o,1)};r(1,2,0),r(2,2,2),r(3,2,4),r(4,2,6),r(5,4,8),r(6,4,12),r(7,2,16),r(8,3,18),r(9,3,21),e.bindVertexArray(null),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)}get valid(){return!this.disposed&&!!this.programInfo}rebuild(){this.release(),this.disposed=!1,this.init()}release(){let e=this.gl;this.whiteTexture&&e.deleteTexture(this.whiteTexture),this.segmentTable?.dispose(),this.segmentTable=null,this.instanceBuffer&&e.deleteBuffer(this.instanceBuffer),this.indexBuffer&&e.deleteBuffer(this.indexBuffer),this.cornerBuffer&&e.deleteBuffer(this.cornerBuffer),this.vao&&e.deleteVertexArray(this.vao),this.programInfo&&e.deleteProgram(this.programInfo.program),this.whiteTexture=null,this.instanceBuffer=null,this.indexBuffer=null,this.cornerBuffer=null,this.vao=null,this.programInfo=null,this.instanceCount=0,this.drawnFrom=0,this.currentTexture=null,this.currentGradient=null,this.pendingSegments=[],this.pendingUploads=[],this.gpuRecords.clear()}pushedTextures=new Set;begin(e,t=1){this.valid&&(this.viewMat=e,this.penScale=t,this.frameSlots=null,this.instanceCount=0,this.drawnFrom=0,this.currentTexture=null,this.currentGradient=null,this.pushedTextures.clear(),this.dropPendingSegments(),this.pendingUploads=[])}pushQuad(e,t,r,o,i,s=[0,0,1,1],a=null,l,u,c){if(!this.valid)return;this.order?.beforeQuadPush(),i!==this.currentTexture&&(this.flush(),this.currentTexture=i),this.instanceCount*qe+qe>this.instanceData.length&&this.grow();let h=this.instanceCount*qe,d=this.instanceCount;this.pushedTextures.add(i);let f=this.instanceData,m=!0,p=l?this.ownerBlocks.get(l):void 0;p&&p.m0===e[0]&&p.m1===e[1]&&p.m2===e[2]&&p.m3===e[3]&&p.m4===e[4]&&p.m5===e[5]&&p.dx===t&&p.dy===r&&p.u0===s[0]&&p.u1===s[1]&&p.u2===s[2]&&p.u3===s[3]&&p.r0===(a?a[0]:0)&&p.r1===(a?a[1]:0)&&p.c0===o[0]&&p.c1===o[1]&&p.c2===o[2]&&p.c3===o[3]&&p.dashOn===(u?u[0]:0)&&p.dashCycle===(u?u[1]:0)&&p.dashPhase===(u?u[2]:0)&&p.segCount===(c?c.count:0)&&p.segHash===(c?c.hash:0)?(f.set(p.block,h),f[h+21]=d,f[h+22]=c?c.count:0,f[h+23]=c?c.hash:0,m=!1):(f[h]=e[0],f[h+1]=e[1],f[h+2]=e[2],f[h+3]=e[3],f[h+4]=e[4],f[h+5]=e[5],f[h+6]=t,f[h+7]=r,f[h+8]=s[0],f[h+9]=s[1],f[h+10]=s[2],f[h+11]=s[3],f[h+12]=o[0],f[h+13]=o[1],f[h+14]=o[2],f[h+15]=o[3],f[h+16]=a?a[0]:0,f[h+17]=a?a[1]:0,f[h+18]=u?u[0]:0,f[h+19]=u?u[1]:0,f[h+20]=u?u[2]:0,f[h+21]=d,f[h+22]=c?c.count:0,f[h+23]=c?c.hash:0,l&&this.ownerBlocks.set(l,{floatCount:qe,m0:e[0],m1:e[1],m2:e[2],m3:e[3],m4:e[4],m5:e[5],dx:t,dy:r,u0:s[0],u1:s[1],u2:s[2],u3:s[3],r0:a?a[0]:0,r1:a?a[1]:0,c0:o[0],c1:o[1],c2:o[2],c3:o[3],dashOn:u?u[0]:0,dashCycle:u?u[1]:0,dashPhase:u?u[2]:0,segCount:c?c.count:0,segHash:c?c.hash:0,block:this.instanceData.slice(h,h+qe)})),c&&this.segmentTable?.writeRow(d,l??null,c);let b=l?this.gpuRecords.get(l):void 0,g=m||!b||b.startFloat!==h||b.floatCount!==qe;if(this.pendingSegments.push({owner:l??null,startFloat:h,floatCount:qe,dirty:g}),g){let x=this.pendingUploads[this.pendingUploads.length-1];x&&x[1]===h?x[1]=h+qe:this.pendingUploads.push([h,h+qe])}if(this.instanceCount+=1,l){let x=this.frameSlots??=new Map,S=x.get(l);S&&S.start+S.count===this.instanceCount-1?S.count+=1:x.set(l,{start:this.instanceCount-1,count:1})}}pushPaintQuad(e,t,r,o,i,s=null){this.valid&&(this.order?.beforeQuadPush(),this.flush(),this.currentGradient=o,this.currentTexture=o.tex,this.pushQuad(e,t,r,[1,1,1,i],o.tex,[0,0,1,1],s),this.flush(),this.currentGradient=null)}flush(){if(!this.valid||this.instanceCount<=this.drawnFrom)return;if(this.deferDraws){let l={startInstance:this.drawnFrom,count:this.instanceCount-this.drawnFrom,texture:this.currentTexture,gradient:this.currentGradient};if(this.drawnFrom=this.instanceCount,this.order){this.order.recordDraw(this,l);return}this.uploadPending(),this.drawDeferred(l);return}let e=this.gl,{program:t,uniforms:r}=this.programInfo,o=this.instanceCount-this.drawnFrom;e.useProgram(t),e.bindVertexArray(this.vao);let i=new Float32Array([this.viewMat[0],this.viewMat[1],0,this.viewMat[2],this.viewMat[3],0,this.viewMat[4],this.viewMat[5],1]);e.uniformMatrix3fv(r.view,!1,i),e.uniform1f(r.penScale,this.penScale),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.currentTexture??this.whiteTexture),e.uniform1i(r.tex,0),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this.segmentTable?.texture??this.whiteTexture),e.uniform1i(r.segTex,2),e.activeTexture(e.TEXTURE0),Ur(e,r,this.currentGradient,1),e.bindBuffer(e.ARRAY_BUFFER,this.instanceBuffer);for(let[l,u]of this.pendingUploads)e.bufferSubData(e.ARRAY_BUFFER,l*4,this.instanceData,l,u-l),this.invalidateOverlappingRecords(l,u);this.pendingUploads=[];let s=qe*4,a=this.drawnFrom*s;e.vertexAttribPointer(1,2,e.FLOAT,!1,s,a),e.vertexAttribPointer(2,2,e.FLOAT,!1,s,a+8),e.vertexAttribPointer(3,2,e.FLOAT,!1,s,a+16),e.vertexAttribPointer(4,2,e.FLOAT,!1,s,a+24),e.vertexAttribPointer(5,4,e.FLOAT,!1,s,a+32),e.vertexAttribPointer(6,4,e.FLOAT,!1,s,a+48),e.vertexAttribPointer(7,2,e.FLOAT,!1,s,a+64),e.vertexAttribPointer(8,3,e.FLOAT,!1,s,a+72),e.vertexAttribPointer(9,3,e.FLOAT,!1,s,a+84),e.drawElementsInstanced(e.TRIANGLES,6,e.UNSIGNED_SHORT,0,o),this.drawnFrom=this.instanceCount;for(let l of this.pendingSegments)l.owner&&this.gpuRecords.set(l.owner,{startFloat:l.startFloat,floatCount:l.floatCount});this.pendingSegments=[]}currentFrameSlots(){return this.frameSlots??new Map}rewindToSlot(e){this.instanceCount=e,this.drawnFrom>e&&(this.drawnFrom=e)}restoreTotals(e){this.instanceCount=e,this.drawnFrom=e}uploadPending(){if(!this.valid)return;let e=this.gl;e.bindBuffer(e.ARRAY_BUFFER,this.instanceBuffer);let t=this.pendingUploads;for(let r=0;r<t.length;r++){let[o,i]=t[r],s=t[r+1];if(s&&s[0]<=i+4096){s[0]=o;continue}e.bufferSubData(e.ARRAY_BUFFER,o*4,this.instanceData,o,i-o),this.invalidateOverlappingRecords(o,i)}this.pendingUploads=[];for(let r of this.pendingSegments)r.owner&&this.gpuRecords.set(r.owner,{startFloat:r.startFloat,floatCount:r.floatCount});this.pendingSegments=[]}dropPendingSegments(){for(let e of this.pendingSegments)e.dirty&&e.owner&&this.gpuRecords.delete(e.owner);this.pendingSegments=[]}invalidateOverlappingRecords(e,t){if(this.gpuRecords.size===0)return;let r=new Set;for(let o of this.pendingSegments)o.owner&&o.startFloat<t&&e<o.startFloat+o.floatCount&&r.add(o.owner);for(let[o,i]of this.gpuRecords)!r.has(o)&&i.startFloat<t&&e<i.startFloat+i.floatCount&&this.gpuRecords.delete(o)}drawDeferred(e){if(!this.valid)return;let t=this.gl,{program:r,uniforms:o}=this.programInfo;t.useProgram(r),t.bindVertexArray(this.vao),Ym.set([this.viewMat[0],this.viewMat[1],0,this.viewMat[2],this.viewMat[3],0,this.viewMat[4],this.viewMat[5],1]),t.uniformMatrix3fv(o.view,!1,Ym),t.uniform1f(o.penScale,this.penScale),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e.texture??this.whiteTexture),t.uniform1i(o.tex,0),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.segmentTable?.texture??this.whiteTexture),t.uniform1i(o.segTex,2),t.activeTexture(t.TEXTURE0),Ur(t,o,e.gradient,1),t.bindBuffer(t.ARRAY_BUFFER,this.instanceBuffer);let i=qe*4,s=e.startInstance*i;t.vertexAttribPointer(1,2,t.FLOAT,!1,i,s),t.vertexAttribPointer(2,2,t.FLOAT,!1,i,s+8),t.vertexAttribPointer(3,2,t.FLOAT,!1,i,s+16),t.vertexAttribPointer(4,2,t.FLOAT,!1,i,s+24),t.vertexAttribPointer(5,4,t.FLOAT,!1,i,s+32),t.vertexAttribPointer(6,4,t.FLOAT,!1,i,s+48),t.vertexAttribPointer(7,2,t.FLOAT,!1,i,s+64),t.vertexAttribPointer(8,3,t.FLOAT,!1,i,s+72),t.vertexAttribPointer(9,3,t.FLOAT,!1,i,s+84),t.drawElementsInstanced(t.TRIANGLES,6,t.UNSIGNED_SHORT,0,e.count)}grow(){let e=this.gl,t=new Float32Array(this.instanceData.length*2);t.set(this.instanceData),this.instanceData=t,this.gpuRecords.clear(),this.pendingUploads=[[0,this.instanceCount*qe]],e.bindBuffer(e.ARRAY_BUFFER,this.instanceBuffer),e.bufferData(e.ARRAY_BUFFER,this.instanceData.byteLength,e.DYNAMIC_DRAW),this.segmentTable?.ensureRows(this.instanceData.length/qe)}canPushSegments(){return this.valid?(this.segmentTable||(this.segmentTable=new aa(this.gl)),this.segmentTable.ensureRows(this.instanceData.length/qe)):!1}get drawnInstances(){return this.instanceCount}get instanceTotal(){return this.instanceCount}dispose(){this.disposed||(this.disposed=!0,this.release())}};var la=class{constructor(e,t){this.quad=e;this.mesh=t}quad;mesh;seq=0;quadSeq=-1;meshSeq=-1;deferred=[];requestSnapshot=!1;retained=null;beforeQuadPush(){this.meshSeq>this.quadSeq&&(this.meshSeq=-1,this.mesh.flush()),this.quadSeq=++this.seq}beforeMeshPush(){this.quadSeq>this.meshSeq&&(this.quadSeq=-1,this.quad.flush()),this.meshSeq=++this.seq}recordDraw(e,t){this.deferred.push({batch:e,cmd:t})}recordState(e){this.quadSeq>=0&&(this.meshSeq<0||this.quadSeq>this.meshSeq)&&(this.quadSeq=-1,this.quad.flush()),this.meshSeq>=0&&(this.meshSeq=-1,this.mesh.flush()),this.quad.deferDraws&&this.mesh.deferDraws?this.deferred.push({fn:e}):e()}hasRecordedCommands(){return this.deferred.length>0}hasNovelPaintReferences(e){if(this.quad.pushedTextures.size){let t=new Set;for(let r of e.commands)"fn"in r||r.batch instanceof tn&&t.add(r.cmd.texture);for(let r of this.quad.pushedTextures)if(!t.has(r))return!0}if(this.mesh.pushedGradients.size){let t=new Set;for(let r of e.commands)"fn"in r||r.batch instanceof tn||t.add(r.cmd.gradient);for(let r of this.mesh.pushedGradients)if(!t.has(r))return!0}return!1}flushAll(){this.quadSeq>=0&&(this.meshSeq<0||this.quadSeq>this.meshSeq)&&(this.quadSeq=-1,this.quad.flush()),this.meshSeq>=0&&(this.meshSeq=-1,this.mesh.flush()),this.executeDeferred()}executeDeferred(){if(this.requestSnapshot&&(this.requestSnapshot=!1,this.retained={commands:this.deferred,quadSlots:this.quad.currentFrameSlots(),meshSlots:this.mesh.currentFrameSlots(),quadTotal:this.quad.instanceTotal,meshTotal:this.mesh.vertexTotal}),!!this.deferred.length){this.quad.uploadPending(),this.mesh.uploadPending();for(let e of this.deferred)"fn"in e?e.fn():(e.batch instanceof tn,e.batch.drawDeferred(e.cmd));this.deferred=[]}}reset(){this.seq=0,this.quadSeq=-1,this.meshSeq=-1,this.deferred=[]}discardRecorded(){this.deferred=[]}replaySnapshot(e){this.quad.uploadPending(),this.mesh.uploadPending();for(let t of e.commands)"fn"in t?t.fn():(t.batch instanceof tn,t.batch.drawDeferred(t.cmd))}};var Um=new Float32Array(9),Pt=8,K0=8192,ca=class{gl;order=null;ownerBlocks=new WeakMap;gpuRecords=new Map;pendingSegments=[];pendingUploads=[];deferDraws=!1;frameSlots=null;drawnFrom=0;programInfo=null;vao=null;vertexBuffer=null;whiteTex=null;vertexData=new Float32Array(K0*Pt);vertexCount=0;currentGradient=null;viewMat=[1,0,0,1,0,0];disposed=!1;constructor(e){this.gl=e,this.init()}init(){let e=this.gl;if(this.programInfo=sa(e,Xm,zm),!this.programInfo){this.disposed=!0;return}this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertexData.byteLength,e.DYNAMIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,Pt*4,0),e.enableVertexAttribArray(1),e.vertexAttribPointer(1,4,e.FLOAT,!1,Pt*4,8),e.enableVertexAttribArray(2),e.vertexAttribPointer(2,2,e.FLOAT,!1,Pt*4,24),e.bindVertexArray(null),this.whiteTex=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.whiteTex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255])),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)}get valid(){return!this.disposed&&!!this.programInfo}rebuild(){this.release(),this.disposed=!1,this.init()}release(){let e=this.gl;this.vertexBuffer&&e.deleteBuffer(this.vertexBuffer),this.vao&&e.deleteVertexArray(this.vao),this.programInfo&&e.deleteProgram(this.programInfo.program),this.whiteTex&&e.deleteTexture(this.whiteTex),this.vertexBuffer=null,this.vao=null,this.programInfo=null,this.whiteTex=null,this.vertexCount=0,this.drawnFrom=0,this.currentGradient=null,this.pendingSegments=[],this.pendingUploads=[],this.gpuRecords.clear()}pushedGradients=new Set;begin(e){this.valid&&(this.viewMat=e,this.frameSlots=null,this.vertexCount=0,this.drawnFrom=0,this.currentGradient=null,this.pushedGradients.clear(),this.dropPendingSegments(),this.pendingUploads=[])}pushMesh(e,t,r,o,i,s){if(!this.valid)return;this.order?.beforeMeshPush(),(!!i!=!!this.currentGradient||i&&this.currentGradient&&i!==this.currentGradient)&&(this.flush(),this.currentGradient=i??null);let a=o.length/3,l=a*3*Pt;this.vertexCount*Pt+l>this.vertexData.length&&this.grow(this.vertexCount*Pt+l);let u=this.vertexCount*Pt;this.pushedGradients.add(i??null);let c=!0,h=s?this.ownerBlocks.get(s):void 0;if(h&&h.floatCount===l&&h.verts===r&&h.triangles===o&&h.m0===e[0]&&h.m1===e[1]&&h.m2===e[2]&&h.m3===e[3]&&h.m4===e[4]&&h.m5===e[5]&&h.c0===t[0]&&h.c1===t[1]&&h.c2===t[2]&&h.c3===t[3])this.vertexData.set(h.block,u),c=!1;else{let p=e,b=this.vertexData,g=u;for(let x=0;x<o.length;x++){let S=o[x]*2,w=r[S],y=r[S+1];b[g]=p[0]*w+p[2]*y+p[4],b[g+1]=p[1]*w+p[3]*y+p[5],b[g+2]=t[0],b[g+3]=t[1],b[g+4]=t[2],b[g+5]=t[3],b[g+6]=w,b[g+7]=y,g+=Pt}s&&this.ownerBlocks.set(s,{floatCount:l,verts:r,triangles:o,m0:e[0],m1:e[1],m2:e[2],m3:e[3],m4:e[4],m5:e[5],c0:t[0],c1:t[1],c2:t[2],c3:t[3],block:this.vertexData.slice(u,u+l)})}let d=s?this.gpuRecords.get(s):void 0,f=d&&d.startFloat===u&&d.floatCount===l,m=c||!f;if(this.pendingSegments.push({owner:s??null,startFloat:u,floatCount:l,dirty:m}),m){let p=this.pendingUploads[this.pendingUploads.length-1];p&&p[1]===u?p[1]=u+l:this.pendingUploads.push([u,u+l])}if(this.vertexCount+=a*3,s){let p=this.frameSlots??=new Map,b=a*3,g=p.get(s);g&&g.start+g.count===this.vertexCount-b?g.count+=b:p.set(s,{start:this.vertexCount-b,count:b})}}flush(){if(!this.valid||this.vertexCount<=this.drawnFrom)return;if(this.deferDraws){let i={startVertex:this.drawnFrom,count:this.vertexCount-this.drawnFrom,gradient:this.currentGradient};if(this.drawnFrom=this.vertexCount,this.order){this.order.recordDraw(this,i);return}this.uploadPending(),this.drawDeferred(i);return}let e=this.gl,{program:t,uniforms:r}=this.programInfo;e.useProgram(t),e.bindVertexArray(this.vao);let o=new Float32Array([this.viewMat[0],this.viewMat[1],0,this.viewMat[2],this.viewMat[3],0,this.viewMat[4],this.viewMat[5],1]);e.uniformMatrix3fv(r.view,!1,o),Ur(e,r,this.currentGradient,0),!this.currentGradient&&this.whiteTex&&(e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.whiteTex),e.uniform1i(r.fillTex,0)),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);for(let[i,s]of this.pendingUploads)e.bufferSubData(e.ARRAY_BUFFER,i*4,this.vertexData,i,s-i),this.invalidateOverlappingRecords(i,s);this.pendingUploads=[],e.drawArrays(e.TRIANGLES,this.drawnFrom,this.vertexCount-this.drawnFrom),this.drawnFrom=this.vertexCount;for(let i of this.pendingSegments)i.owner&&this.gpuRecords.set(i.owner,{startFloat:i.startFloat,floatCount:i.floatCount});this.pendingSegments=[]}currentFrameSlots(){return this.frameSlots??new Map}rewindToSlot(e){this.vertexCount=e,this.drawnFrom>e&&(this.drawnFrom=e)}restoreTotals(e){this.vertexCount=e,this.drawnFrom=e}uploadPending(){if(!this.valid)return;let e=this.gl;e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);let t=this.pendingUploads;for(let r=0;r<t.length;r++){let[o,i]=t[r],s=t[r+1];if(s&&s[0]<=i+4096){s[0]=o;continue}e.bufferSubData(e.ARRAY_BUFFER,o*4,this.vertexData,o,i-o),this.invalidateOverlappingRecords(o,i)}this.pendingUploads=[];for(let r of this.pendingSegments)r.owner&&this.gpuRecords.set(r.owner,{startFloat:r.startFloat,floatCount:r.floatCount});this.pendingSegments=[]}dropPendingSegments(){for(let e of this.pendingSegments)e.dirty&&e.owner&&this.gpuRecords.delete(e.owner);this.pendingSegments=[]}invalidateOverlappingRecords(e,t){if(this.gpuRecords.size===0)return;let r=new Set;for(let o of this.pendingSegments)o.owner&&o.startFloat<t&&e<o.startFloat+o.floatCount&&r.add(o.owner);for(let[o,i]of this.gpuRecords)!r.has(o)&&i.startFloat<t&&e<i.startFloat+i.floatCount&&this.gpuRecords.delete(o)}drawDeferred(e){if(!this.valid)return;let t=this.gl,{program:r,uniforms:o}=this.programInfo;t.useProgram(r),t.bindVertexArray(this.vao),Um.set([this.viewMat[0],this.viewMat[1],0,this.viewMat[2],this.viewMat[3],0,this.viewMat[4],this.viewMat[5],1]),t.uniformMatrix3fv(o.view,!1,Um),Ur(t,o,e.gradient,0),!e.gradient&&this.whiteTex&&(t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.whiteTex),t.uniform1i(o.fillTex,0)),t.drawArrays(t.TRIANGLES,e.startVertex,e.count)}grow(e){let t=this.gl,r=this.vertexData.length;for(;r<e;)r*=2;let o=new Float32Array(r);o.set(this.vertexData.subarray(0,this.vertexCount*Pt)),this.vertexData=o,t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexData.byteLength,t.DYNAMIC_DRAW),this.gpuRecords.clear(),this.pendingUploads=[[0,this.vertexCount*Pt]]}get drawnVertices(){return this.vertexCount}get vertexTotal(){return this.vertexCount}dispose(){this.disposed||(this.disposed=!0,this.release())}};var Gt=tc,Z0=[Gt[0],Gt[1],Gt[2],.14],zc=[1,1,1,1],J0=2,Vm=[238/255,238/255,238/255,128/255],qm=[24/255,144/255,1,128/255],qo=20,Ln=20,ua=null,eS=()=>{if(ua)return ua;let n=e=>{let t=document.createElement("canvas");t.width=qo,t.height=qo;let r=t.getContext("2d");if(!r)return t;let o=qo/2;r.beginPath(),r.arc(o,o,8,0,Math.PI*2),r.fillStyle=e?"#2f6fed":"#ffffff",r.fill(),r.lineWidth=1.5,r.strokeStyle="#2f6fed",r.stroke();let i=4;return r.beginPath(),r.moveTo(o-i,o),r.lineTo(o+i,o),r.moveTo(o,o-i),r.lineTo(o,o+i),r.lineWidth=1.5,r.strokeStyle=e?"#ffffff":"#2f6fed",r.stroke(),t};return ua={normal:n(!1),hover:n(!0)},ua},tS=n=>n.columnWidths.reduce((e,t)=>e+t,0)+(n.cols-1)*n.cellSpacing,nS=n=>n.rowHeights.reduce((e,t)=>e+t,0)+(n.rows-1)*n.cellSpacing,Km=(n,e,t)=>{let r=0;for(let o=0;o<t;o++)r+=n[o]+e;return r},ha=null,rS=()=>{if(ha)return ha;let n=e=>{let t=document.createElement("canvas");t.width=Ln*2,t.height=Ln*2;let r=t.getContext("2d");if(!r)return t;r.scale(2,2),r.fillStyle=e?"#1890ff20":"#eeeeee99",r.fillRect(0,0,Ln-1,Ln-1);let o=Ln/2-.5,i=Ln/2-.5,s=Ln*.25,a=Ln*.18;r.strokeStyle=e?"#1890ff":"#888888",r.lineWidth=1.5,r.lineCap="round";for(let l=-1;l<=1;l++)r.beginPath(),r.moveTo(o-s,i+l*a),r.lineTo(o+s,i+l*a),r.stroke();return t};return ha={normal:n(!1),hover:n(!0)},ha},Qm=(n,e)=>{let t=[],r=n.tableView,o=n.cellMap,i=n.matrix,s=n.objectScale,a=tS(r)/2,l=nS(r)/2,u=Rt/e/Math.max(s.x,1e-6),c=Rt/e/Math.max(s.y,1e-6);for(let g of n.selectedCells){let x=o.get(`${g.row},${g.col}`);if(x?.isMerged)continue;let S=x?.rowspan??1,w=x?.colspan??1,y=Eo(r,{r1:g.row,r2:g.row+S-1,c1:g.col,c2:g.col+w-1}),v=y.left+y.width/2,R=y.top+y.height/2;t.push({matrix:j(i,[1,0,0,1,v,R]),dims:{x:y.width,y:y.height},color:Z0}),t.push({matrix:j(i,[1,0,0,1,v,y.top]),dims:{x:y.width+2*u,y:c},color:Gt}),t.push({matrix:j(i,[1,0,0,1,v,y.top+y.height]),dims:{x:y.width+2*u,y:c},color:Gt}),t.push({matrix:j(i,[1,0,0,1,y.left,R]),dims:{x:u,y:y.height+2*c},color:Gt}),t.push({matrix:j(i,[1,0,0,1,y.left+y.width,R]),dims:{x:u,y:y.height+2*c},color:Gt})}if(n.hoveredBorder){let{type:g,position:x}=n.hoveredBorder,S=g==="col"?Q(i,x,-l):Q(i,-a,x),w=g==="col"?Q(i,x,l):Q(i,a,x);t.push(Re(S,w,J0/e,Gt))}let h=-n.dims.x/2,d=-n.dims.y/2,f=20/(e*Math.max(s.x,1e-6)),m=20/(e*Math.max(s.y,1e-6)),p=Ar(o,n.selectedCells);for(let g=0;g<r.rows;g++){let x=Km(r.rowHeights,r.cellSpacing,g)-l,S=r.rowHeights[g],w=n.hoveredStrip?.kind==="row"&&n.hoveredStrip.index===g?!0:p.rows.has(g);t.push({matrix:j(i,[1,0,0,1,h-f/2,x+S/2]),dims:{x:f,y:S},color:w?qm:Vm})}for(let g=0;g<r.cols;g++){let x=Km(r.columnWidths,r.cellSpacing,g)-a,S=r.columnWidths[g],w=n.hoveredStrip?.kind==="col"&&n.hoveredStrip.index===g?!0:p.cols.has(g);t.push({matrix:j(i,[1,0,0,1,x+S/2,d-m/2]),dims:{x:S,y:m},color:w?qm:Vm})}{let g=rS();t.push({matrix:j(i,[1,0,0,1,h-f/2,d-m/2]),dims:{x:f,y:m},color:zc,texture:n.hoveredDragHandle?g.hover:g.normal})}let b=n.hoveredIndicator??(n.borderDragging?null:n.hoveredBorder);if(b){let g=eS(),x=b.type==="col";t.push({matrix:j(i,[1,0,0,1,x?b.position:-a-15,x?-l-15:b.position]),dims:{x:qo/(e*Math.max(s.x,1e-6)),y:qo/(e*Math.max(s.y,1e-6))},color:zc,texture:n.hoveredIndicator?g.hover:g.normal})}if(n.selectedCells.length&&!n.editingCell&&!n.isFullCellSelection){let g=n.selectionBoundsRect;if(g){let x=g.left+g.width,S=g.top+g.height,w=kn/e/Math.max(s.x,1e-6),y=kn/e/Math.max(s.y,1e-6),v=(kn-2*Rt)/e/Math.max(s.x,1e-6),R=(kn-2*Rt)/e/Math.max(s.y,1e-6);t.push({matrix:j(i,[1,0,0,1,x,S]),dims:{x:w,y},color:Gt}),t.push({matrix:j(i,[1,0,0,1,x,S]),dims:{x:v,y:R},color:n.hoveredRangeHandle?Gt:zc})}}return t};var oS=(n,e,t,r)=>{let o=n.nodes.filter(h=>Ze(h)&&h.visible&&h.raw.visible!==!1);if(!o.length)return[];let i=e[0],s=-e[4]/i,a=-e[5]/i,l=t/i,u=r/i,c=[];for(let h of o){let d=h.raw,f=ee(typeof d.stroke=="string"?d.stroke:"pink"),m=typeof d.opacity=="number"?d.opacity:1,p=[f[0],f[1],f[2],f[3]*m],b=Math.max(Number(d.strokeWidth)||1,1.2/i),g=h.bounds;if(h.dims.y===0){let x=(g.top+g.bottom)/2;c.push({matrix:[1,0,0,1,s+l/2,x],dims:{x:l,y:b},color:p})}else if(h.dims.x===0){let x=(g.left+g.right)/2;c.push({matrix:[1,0,0,1,x,a+u/2],dims:{x:b,y:u},color:p})}}return c},Zm=n=>{let{doc:e,zoom:t,marquee:r,textEdit:o,snapOverlay:i,ruler:s}=n,a=n.rotate??null,l=o.node,u=!l&&!r&&e.selection.length===1&&e.selection[0]instanceof le?e.selection[0]:null,c=l?[...n.cellEditOverlayOnly?[]:Pn(l.aCoords,t),...o.quads]:r?Wd(r,t):u?.editingMask?Hd(u,t,a):Bd(e,t,a,n.mobileControls===!0),h=l&&e.selection.length===1?e.selection[0]:null;l&&h instanceof J&&h.containsDeep(l)&&(c=[...c,...ws(h.aCoords,t)]),!l&&!r&&e.selection.length===1&&e.selection[0]instanceof te&&(c=[...c,...Qm(e.selection[0],t)]);let d=e.seamHover;if(u&&d&&d.puzzle===u&&(c=[...c,...Xd(Gd(d.puzzle,d.mask,d.handle),t)]),e.hovered&&!r&&!Ze(e.hovered)&&(c=[...c,...zd(e.hovered,t)]),c=[...c,...i],s&&(c=[...c,...oS(e,s.vpt,s.cssWidth,s.cssHeight)],s.visible!==!1)){let f=e.nodes.find(p=>p.raw.id===Sn),m=f&&typeof f.raw.width=="number"&&typeof f.raw.height=="number"?{left:f.raw.left??0,top:f.raw.top??0,width:f.raw.width,height:f.raw.height}:null;c=[...c,...nf({vpt:s.vpt,cssWidth:s.cssWidth,cssHeight:s.cssHeight,workspaceRect:m,referenceLine:s.referenceLine??null,selectionRects:e.selection.filter(p=>!Ze(p)).map(p=>({left:p.bounds.left,top:p.bounds.top,width:p.bounds.right-p.bounds.left,height:p.bounds.bottom-p.bounds.top}))})]}return c};function Jm(n,e,t,r,o){for(let i=0;i<o;i++){let s=t[i];if(!Ze(s)&&!rr(s)){if(r&&s===r.target)for(let a of r.underlay())n.pushQuad(a.matrix,a.dims.x,a.dims.y,a.color,null);e.renderSceneNode(s)}}}function ep(n,e){for(let t of e)rr(t)&&t.visible&&n.renderSceneNode(t)}function tp(n){let e=n.doc.editingNode;if(n.cropSessionController.active){Ko(n,n.cropSessionController.buildOverlay(n.zoom))&&n.requestRenderAll();return}if(n.expandSessionController.active){Ko(n,n.expandSessionController.buildOverlay(n.zoom))&&n.requestRenderAll();return}if(n.pathSessionController.active){Ko(n,n.pathSessionController.buildOverlay(n.zoom))&&n.requestRenderAll();return}if(n.warpSessionController.active){Ko(n,n.warpSessionController.buildOverlay())&&n.requestRenderAll();return}let t=Zm({doc:n.doc,zoom:n.zoom,marquee:n.marquee,textEdit:{node:e,quads:e?n.textEditing.buildOverlay():[]},cellEditOverlayOnly:e!==null&&n.tableCellEditing.isOverlay(e),snapOverlay:n.snapGuide.buildOverlay(n.zoom),rotate:n.rotateDrag,mobileControls:n.mobileControls,ruler:{vpt:n.vpt,cssWidth:n.cssWidth,cssHeight:n.cssHeight,referenceLine:n.referenceLineDrag,visible:n.rulerVisible}});Ko(n,t),n.renderer.frame.animationActive&&n.requestRenderAll()}function Ko(n,e){for(let t of e)n.batch.pushQuad(t.matrix,t.dims.x,t.dims.y,t.color,t.texture?n.textures.get(t.texture):null);return n.batch.flush(),n.batch.deferDraws=!1,n.meshBatch.deferDraws=!1,n.batchOrder.executeDeferred(),n.renderer.frame.animationActive}var da=class{constructor(e){this.host=e}host;limit=-1;rafId=null;deadline=0;rendered=!1;start(e=1e3,t=800){if(!this.host.alive())return;let r=this.host.nodeCount();r<e||(this.rafId!==null&&cancelAnimationFrame(this.rafId),this.limit=Math.min(e,r),this.rendered=!1,this.deadline=performance.now()+t,this.rafId=requestAnimationFrame(()=>this.step()))}step(){if(this.rafId=null,this.limit<0||!this.host.alive())return;let e=this.host.nodeCount();if(this.limit>=e){this.limit=-1,this.host.onProgressiveDone(e);return}let t=performance.now();this.host.render(),this.rendered=!0;let r=performance.now()-t,o=r>1?Math.min(4,Math.max(.5,20/r)):2;if(this.limit=Math.min(e,Math.max(this.limit+1,Math.round(this.limit*(1+o)))),this.limit>=e){this.host.render(),this.limit=-1,this.host.onProgressiveDone(e);return}this.rafId=requestAnimationFrame(()=>this.step())}absorbExternalRenderRequest(){this.rendered&&performance.now()>this.deadline&&this.limit>=0&&this.limit<this.host.nodeCount()&&(this.limit=this.host.nodeCount())}dispose(){this.rafId!==null&&cancelAnimationFrame(this.rafId),this.rafId=null,this.limit=-1,this.rendered=!1}};var fa=class{constructor(e){this.host=e}host;retained=null;lastFrameAnimated=!1;lastFrameBakeMore=!1;lastGateReason=null;tryRetainedFrame(){let{host:e}=this;if(e.renderer.flatFrame=!0,!Ka())return this.gateFail("flag-off");let t=this.retained;if(!t)return this.gateFail("no-snapshot");if(this.lastFrameAnimated)return this.gateFail("animating");if(this.lastFrameBakeMore)return this.gateFail("bake-continue");if(e.cropSessionController.active||e.expandSessionController.active||e.pathSessionController.active||e.warpSessionController.active)return this.gateFail("session");if(e.progressiveLoad.limit>=0&&e.progressiveLoad.limit<e.doc.nodes.length)return this.gateFail("progressive");if(e.doc.editingNode)return this.gateFail("editing");if(t.structureVersion!==e.doc.structureVersion)return this.gateFail("structure");if(t.vptKey!==e.vpt.join(","))return this.gateFail("vpt");if(t.dpr!==e.dpr||t.sizeKey!==`${e.canvasEl.width}x${e.canvasEl.height}`)return this.gateFail("surface");if(t.artifactEpoch!==e.renderEpoch.value)return this.gateFail(`artifact-epoch(${e.renderEpoch.lastReason})`);let r=t.snap,o=e.doc.renderDirty;for(let i of o){if(i.isReferenceLine||rr(i))continue;let s=r.quadSlots.get(i),a=r.meshSlots.get(i);if(!s&&!a)return this.gateFail("no-slot");let l=e.batch.instanceTotal,u=e.meshBatch.vertexTotal;if(s&&e.batch.rewindToSlot(s.start),a&&e.meshBatch.rewindToSlot(a.start),e.renderer.renderSceneNode(i),e.batch.instanceTotal!==(s?s.start+s.count:l))return this.gateFail("contract-quad");if(e.meshBatch.vertexTotal!==(a?a.start+a.count:u))return this.gateFail("contract-mesh");if(!e.renderer.flatFrame)return this.gateFail("isolated");if(e.batchOrder.hasNovelPaintReferences(r))return this.gateFail("repush-commands")}return t.artifactEpoch!==e.renderEpoch.value?this.gateFail(`artifact-epoch-late(${e.renderEpoch.lastReason})`):(e.batch.restoreTotals(r.quadTotal),e.meshBatch.restoreTotals(r.meshTotal),e.batchOrder.discardRecorded(),e.glyphAtlas.keepPagesForRetainedFrame(),e.batchOrder.replaySnapshot(r),this.gateOk(),!0)}captureSnapshot(){let{host:e}=this;if(!Ka()){this.retained=null;return}let t=e.renderer.flatFrame,r=e.cropSessionController.active||e.expandSessionController.active||e.pathSessionController.active||e.warpSessionController.active,o=e.progressiveLoad.limit>=0&&e.progressiveLoad.limit<e.doc.nodes.length;if(!t||r||o||e.doc.editingNode){this.retained=null,this.logDebug(`snapshot 跳过(flat=${t} sessions=${r} progressive=${o} editing=${e.doc.editingNode!==null})`);return}let i=e.batchOrder.retained;if(this.retained=i?{snap:i,structureVersion:e.doc.structureVersion,vptKey:e.vpt.join(","),dpr:e.dpr,sizeKey:`${e.canvasEl.width}x${e.canvasEl.height}`,artifactEpoch:e.renderEpoch.value}:null,i&&zn()){let s=e.glyphAtlas.stats();console.info("[retained] 快照收录",{commands:i.commands.length,quadSlots:i.quadSlots.size,meshSlots:i.meshSlots.size,structureVersion:e.doc.structureVersion,atlasPages:s.pages,artifactEpoch:e.renderEpoch.value,epochLastReason:e.renderEpoch.lastReason})}}noteFrameRendered(){this.lastFrameAnimated=this.host.renderer.frame.animationActive,this.lastFrameBakeMore=this.host.renderer.frame.bakeMore}invalidate(){this.retained=null}dispose(){this.retained=null}gateFail(e){return this.lastGateReason!==e&&(this.lastGateReason=e,zn()&&console.info("[retained] 门链回退:",e)),!1}gateOk(){this.lastGateReason!==null&&(this.lastGateReason=null,zn()&&console.info("[retained] 保留式帧恢复生效"))}logDebug(e){zn()&&console.info("[retained]",e)}};var iS=`#version 300 es
256
+ }`,sa=(n,e,t)=>{let r=(a,l)=>{let u=n.createShader(a);return u?(n.shaderSource(u,l),n.compileShader(u),n.getShaderParameter(u,n.COMPILE_STATUS)?u:(console.error("[engine] shader compile failed:",n.getShaderInfoLog(u)),n.deleteShader(u),null)):null},o=r(n.VERTEX_SHADER,e),i=r(n.FRAGMENT_SHADER,t);if(!o||!i)return o&&n.deleteShader(o),i&&n.deleteShader(i),null;let s=n.createProgram();return s?(n.attachShader(s,o),n.attachShader(s,i),n.linkProgram(s),n.deleteShader(o),n.deleteShader(i),n.getProgramParameter(s,n.LINK_STATUS)?{program:s,uniforms:{view:n.getUniformLocation(s,"uView"),tex:n.getUniformLocation(s,"uTex"),penScale:n.getUniformLocation(s,"uPenScale"),segTex:n.getUniformLocation(s,"uSegTex"),paintMode:n.getUniformLocation(s,"uPaintMode"),paintInv:n.getUniformLocation(s,"uPaintInv"),paintA:n.getUniformLocation(s,"uPaintA"),paintB:n.getUniformLocation(s,"uPaintB"),fillTex:n.getUniformLocation(s,"uFillTex"),patInfo:n.getUniformLocation(s,"uPatInfo")}}:(console.error("[engine] program link failed:",n.getProgramInfoLog(s)),n.deleteProgram(s),null)):(n.deleteShader(o),n.deleteShader(i),null)};var $r=n=>{let e=2166136261;for(let t=0;t<n.length;t++)e=Math.imul(e^Math.round(n[t]*256),16777619);return e>>>1},aa=class{constructor(e){this.gl=e}gl;tex=null;data=new Float32Array(0);rowOwners=[];rowHashes=[];rows=0;healthy=!0;ensureRows(e){if(!this.healthy)return!1;if(e<=this.rows)return!0;let t=this.gl;try{let r=new Float32Array(e*64*4);r.set(this.data);let o=this.tex??t.createTexture();if(!o)return this.healthy=!1,!1;for(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,o),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,64,e,0,t.RGBA,t.FLOAT,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.activeTexture(t.TEXTURE0),this.tex=o,this.data=r;this.rowOwners.length<e;)this.rowOwners.push(null),this.rowHashes.push(0);return this.rows=e,!0}catch{return this.healthy=!1,!1}}writeRow(e,t,r){if(!this.healthy||e>=this.rows||t&&this.rowOwners[e]===t&&this.rowHashes[e]===r.hash)return;let o=e*64*4;this.data.fill(0,o,o+256),this.data.set(r.data.subarray(0,r.count*4),o),this.rowOwners[e]=t,this.rowHashes[e]=r.hash;let i=this.gl;i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this.tex),i.texSubImage2D(i.TEXTURE_2D,0,0,e,r.count,1,i.RGBA,i.FLOAT,this.data,o),i.activeTexture(i.TEXTURE0)}rowAt(e){return e>=this.rows?null:this.data.slice(e*64*4,(e+1)*64*4)}get texture(){return this.tex}get rowCount(){return this.rows}dispose(){this.tex&&this.gl.deleteTexture(this.tex),this.tex=null,this.data=new Float32Array(0),this.rowOwners=[],this.rowHashes=[],this.rows=0}};var qe=24,Um=new Float32Array(9),V0=4096,q0=new Float32Array([0,0,1,0,1,1,0,1]),K0=new Uint16Array([0,1,2,0,2,3]),tn=class{gl;order=null;gpuRecords=new Map;ownerBlocks=new WeakMap;pendingSegments=[];pendingUploads=[];deferDraws=!1;frameSlots=null;drawnFrom=0;programInfo=null;vao=null;cornerBuffer=null;indexBuffer=null;instanceBuffer=null;instanceData=new Float32Array(V0*qe);whiteTexture=null;segmentTable=null;instanceCount=0;currentTexture=null;currentGradient=null;viewMat=[1,0,0,1,0,0];penScale=1;disposed=!1;constructor(e){this.gl=e,this.init()}init(){let e=this.gl;if(this.programInfo=sa(e,Hm,Xm),!this.programInfo){this.disposed=!0;return}this.whiteTexture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.whiteTexture),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255])),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.cornerBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.cornerBuffer),e.bufferData(e.ARRAY_BUFFER,q0,e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),this.indexBuffer=e.createBuffer(),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,K0,e.STATIC_DRAW),this.instanceBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.instanceBuffer),e.bufferData(e.ARRAY_BUFFER,this.instanceData.byteLength,e.DYNAMIC_DRAW);let t=qe*4,r=(o,i,s)=>{e.enableVertexAttribArray(o),e.vertexAttribPointer(o,i,e.FLOAT,!1,t,s*4),e.vertexAttribDivisor(o,1)};r(1,2,0),r(2,2,2),r(3,2,4),r(4,2,6),r(5,4,8),r(6,4,12),r(7,2,16),r(8,3,18),r(9,3,21),e.bindVertexArray(null),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)}get valid(){return!this.disposed&&!!this.programInfo}rebuild(){this.release(),this.disposed=!1,this.init()}release(){let e=this.gl;this.whiteTexture&&e.deleteTexture(this.whiteTexture),this.segmentTable?.dispose(),this.segmentTable=null,this.instanceBuffer&&e.deleteBuffer(this.instanceBuffer),this.indexBuffer&&e.deleteBuffer(this.indexBuffer),this.cornerBuffer&&e.deleteBuffer(this.cornerBuffer),this.vao&&e.deleteVertexArray(this.vao),this.programInfo&&e.deleteProgram(this.programInfo.program),this.whiteTexture=null,this.instanceBuffer=null,this.indexBuffer=null,this.cornerBuffer=null,this.vao=null,this.programInfo=null,this.instanceCount=0,this.drawnFrom=0,this.currentTexture=null,this.currentGradient=null,this.pendingSegments=[],this.pendingUploads=[],this.gpuRecords.clear()}pushedTextures=new Set;begin(e,t=1){this.valid&&(this.viewMat=e,this.penScale=t,this.frameSlots=null,this.instanceCount=0,this.drawnFrom=0,this.currentTexture=null,this.currentGradient=null,this.pushedTextures.clear(),this.dropPendingSegments(),this.pendingUploads=[])}pushQuad(e,t,r,o,i,s=[0,0,1,1],a=null,l,u,c){if(!this.valid)return;this.order?.beforeQuadPush(),i!==this.currentTexture&&(this.flush(),this.currentTexture=i),this.instanceCount*qe+qe>this.instanceData.length&&this.grow();let h=this.instanceCount*qe,d=this.instanceCount;this.pushedTextures.add(i);let f=this.instanceData,m=!0,p=l?this.ownerBlocks.get(l):void 0;p&&p.m0===e[0]&&p.m1===e[1]&&p.m2===e[2]&&p.m3===e[3]&&p.m4===e[4]&&p.m5===e[5]&&p.dx===t&&p.dy===r&&p.u0===s[0]&&p.u1===s[1]&&p.u2===s[2]&&p.u3===s[3]&&p.r0===(a?a[0]:0)&&p.r1===(a?a[1]:0)&&p.c0===o[0]&&p.c1===o[1]&&p.c2===o[2]&&p.c3===o[3]&&p.dashOn===(u?u[0]:0)&&p.dashCycle===(u?u[1]:0)&&p.dashPhase===(u?u[2]:0)&&p.segCount===(c?c.count:0)&&p.segHash===(c?c.hash:0)?(f.set(p.block,h),f[h+21]=d,f[h+22]=c?c.count:0,f[h+23]=c?c.hash:0,m=!1):(f[h]=e[0],f[h+1]=e[1],f[h+2]=e[2],f[h+3]=e[3],f[h+4]=e[4],f[h+5]=e[5],f[h+6]=t,f[h+7]=r,f[h+8]=s[0],f[h+9]=s[1],f[h+10]=s[2],f[h+11]=s[3],f[h+12]=o[0],f[h+13]=o[1],f[h+14]=o[2],f[h+15]=o[3],f[h+16]=a?a[0]:0,f[h+17]=a?a[1]:0,f[h+18]=u?u[0]:0,f[h+19]=u?u[1]:0,f[h+20]=u?u[2]:0,f[h+21]=d,f[h+22]=c?c.count:0,f[h+23]=c?c.hash:0,l&&this.ownerBlocks.set(l,{floatCount:qe,m0:e[0],m1:e[1],m2:e[2],m3:e[3],m4:e[4],m5:e[5],dx:t,dy:r,u0:s[0],u1:s[1],u2:s[2],u3:s[3],r0:a?a[0]:0,r1:a?a[1]:0,c0:o[0],c1:o[1],c2:o[2],c3:o[3],dashOn:u?u[0]:0,dashCycle:u?u[1]:0,dashPhase:u?u[2]:0,segCount:c?c.count:0,segHash:c?c.hash:0,block:this.instanceData.slice(h,h+qe)})),c&&this.segmentTable?.writeRow(d,l??null,c);let b=l?this.gpuRecords.get(l):void 0,g=m||!b||b.startFloat!==h||b.floatCount!==qe;if(this.pendingSegments.push({owner:l??null,startFloat:h,floatCount:qe,dirty:g}),g){let x=this.pendingUploads[this.pendingUploads.length-1];x&&x[1]===h?x[1]=h+qe:this.pendingUploads.push([h,h+qe])}if(this.instanceCount+=1,l){let x=this.frameSlots??=new Map,S=x.get(l);S&&S.start+S.count===this.instanceCount-1?S.count+=1:x.set(l,{start:this.instanceCount-1,count:1})}}pushPaintQuad(e,t,r,o,i,s=null){this.valid&&(this.order?.beforeQuadPush(),this.flush(),this.currentGradient=o,this.currentTexture=o.tex,this.pushQuad(e,t,r,[1,1,1,i],o.tex,[0,0,1,1],s),this.flush(),this.currentGradient=null)}flush(){if(!this.valid||this.instanceCount<=this.drawnFrom)return;if(this.deferDraws){let l={startInstance:this.drawnFrom,count:this.instanceCount-this.drawnFrom,texture:this.currentTexture,gradient:this.currentGradient};if(this.drawnFrom=this.instanceCount,this.order){this.order.recordDraw(this,l);return}this.uploadPending(),this.drawDeferred(l);return}let e=this.gl,{program:t,uniforms:r}=this.programInfo,o=this.instanceCount-this.drawnFrom;e.useProgram(t),e.bindVertexArray(this.vao);let i=new Float32Array([this.viewMat[0],this.viewMat[1],0,this.viewMat[2],this.viewMat[3],0,this.viewMat[4],this.viewMat[5],1]);e.uniformMatrix3fv(r.view,!1,i),e.uniform1f(r.penScale,this.penScale),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.currentTexture??this.whiteTexture),e.uniform1i(r.tex,0),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this.segmentTable?.texture??this.whiteTexture),e.uniform1i(r.segTex,2),e.activeTexture(e.TEXTURE0),Ur(e,r,this.currentGradient,1),e.bindBuffer(e.ARRAY_BUFFER,this.instanceBuffer);for(let[l,u]of this.pendingUploads)e.bufferSubData(e.ARRAY_BUFFER,l*4,this.instanceData,l,u-l),this.invalidateOverlappingRecords(l,u);this.pendingUploads=[];let s=qe*4,a=this.drawnFrom*s;e.vertexAttribPointer(1,2,e.FLOAT,!1,s,a),e.vertexAttribPointer(2,2,e.FLOAT,!1,s,a+8),e.vertexAttribPointer(3,2,e.FLOAT,!1,s,a+16),e.vertexAttribPointer(4,2,e.FLOAT,!1,s,a+24),e.vertexAttribPointer(5,4,e.FLOAT,!1,s,a+32),e.vertexAttribPointer(6,4,e.FLOAT,!1,s,a+48),e.vertexAttribPointer(7,2,e.FLOAT,!1,s,a+64),e.vertexAttribPointer(8,3,e.FLOAT,!1,s,a+72),e.vertexAttribPointer(9,3,e.FLOAT,!1,s,a+84),e.drawElementsInstanced(e.TRIANGLES,6,e.UNSIGNED_SHORT,0,o),this.drawnFrom=this.instanceCount;for(let l of this.pendingSegments)l.owner&&this.gpuRecords.set(l.owner,{startFloat:l.startFloat,floatCount:l.floatCount});this.pendingSegments=[]}currentFrameSlots(){return this.frameSlots??new Map}rewindToSlot(e){this.instanceCount=e,this.drawnFrom>e&&(this.drawnFrom=e)}restoreTotals(e){this.instanceCount=e,this.drawnFrom=e}uploadPending(){if(!this.valid)return;let e=this.gl;e.bindBuffer(e.ARRAY_BUFFER,this.instanceBuffer);let t=this.pendingUploads;for(let r=0;r<t.length;r++){let[o,i]=t[r],s=t[r+1];if(s&&s[0]<=i+4096){s[0]=o;continue}e.bufferSubData(e.ARRAY_BUFFER,o*4,this.instanceData,o,i-o),this.invalidateOverlappingRecords(o,i)}this.pendingUploads=[];for(let r of this.pendingSegments)r.owner&&this.gpuRecords.set(r.owner,{startFloat:r.startFloat,floatCount:r.floatCount});this.pendingSegments=[]}dropPendingSegments(){for(let e of this.pendingSegments)e.dirty&&e.owner&&this.gpuRecords.delete(e.owner);this.pendingSegments=[]}invalidateOverlappingRecords(e,t){if(this.gpuRecords.size===0)return;let r=new Set;for(let o of this.pendingSegments)o.owner&&o.startFloat<t&&e<o.startFloat+o.floatCount&&r.add(o.owner);for(let[o,i]of this.gpuRecords)!r.has(o)&&i.startFloat<t&&e<i.startFloat+i.floatCount&&this.gpuRecords.delete(o)}drawDeferred(e){if(!this.valid)return;let t=this.gl,{program:r,uniforms:o}=this.programInfo;t.useProgram(r),t.bindVertexArray(this.vao),Um.set([this.viewMat[0],this.viewMat[1],0,this.viewMat[2],this.viewMat[3],0,this.viewMat[4],this.viewMat[5],1]),t.uniformMatrix3fv(o.view,!1,Um),t.uniform1f(o.penScale,this.penScale),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e.texture??this.whiteTexture),t.uniform1i(o.tex,0),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.segmentTable?.texture??this.whiteTexture),t.uniform1i(o.segTex,2),t.activeTexture(t.TEXTURE0),Ur(t,o,e.gradient,1),t.bindBuffer(t.ARRAY_BUFFER,this.instanceBuffer);let i=qe*4,s=e.startInstance*i;t.vertexAttribPointer(1,2,t.FLOAT,!1,i,s),t.vertexAttribPointer(2,2,t.FLOAT,!1,i,s+8),t.vertexAttribPointer(3,2,t.FLOAT,!1,i,s+16),t.vertexAttribPointer(4,2,t.FLOAT,!1,i,s+24),t.vertexAttribPointer(5,4,t.FLOAT,!1,i,s+32),t.vertexAttribPointer(6,4,t.FLOAT,!1,i,s+48),t.vertexAttribPointer(7,2,t.FLOAT,!1,i,s+64),t.vertexAttribPointer(8,3,t.FLOAT,!1,i,s+72),t.vertexAttribPointer(9,3,t.FLOAT,!1,i,s+84),t.drawElementsInstanced(t.TRIANGLES,6,t.UNSIGNED_SHORT,0,e.count)}grow(){let e=this.gl,t=new Float32Array(this.instanceData.length*2);t.set(this.instanceData),this.instanceData=t,this.gpuRecords.clear(),this.pendingUploads=[[0,this.instanceCount*qe]],e.bindBuffer(e.ARRAY_BUFFER,this.instanceBuffer),e.bufferData(e.ARRAY_BUFFER,this.instanceData.byteLength,e.DYNAMIC_DRAW),this.segmentTable?.ensureRows(this.instanceData.length/qe)}canPushSegments(){return this.valid?(this.segmentTable||(this.segmentTable=new aa(this.gl)),this.segmentTable.ensureRows(this.instanceData.length/qe)):!1}get drawnInstances(){return this.instanceCount}get instanceTotal(){return this.instanceCount}dispose(){this.disposed||(this.disposed=!0,this.release())}};var la=class{constructor(e,t){this.quad=e;this.mesh=t}quad;mesh;seq=0;quadSeq=-1;meshSeq=-1;deferred=[];requestSnapshot=!1;retained=null;beforeQuadPush(){this.meshSeq>this.quadSeq&&(this.meshSeq=-1,this.mesh.flush()),this.quadSeq=++this.seq}beforeMeshPush(){this.quadSeq>this.meshSeq&&(this.quadSeq=-1,this.quad.flush()),this.meshSeq=++this.seq}recordDraw(e,t){this.deferred.push({batch:e,cmd:t})}recordState(e){this.quadSeq>=0&&(this.meshSeq<0||this.quadSeq>this.meshSeq)&&(this.quadSeq=-1,this.quad.flush()),this.meshSeq>=0&&(this.meshSeq=-1,this.mesh.flush()),this.quad.deferDraws&&this.mesh.deferDraws?this.deferred.push({fn:e}):e()}hasRecordedCommands(){return this.deferred.length>0}hasNovelPaintReferences(e){if(this.quad.pushedTextures.size){let t=new Set;for(let r of e.commands)"fn"in r||r.batch instanceof tn&&t.add(r.cmd.texture);for(let r of this.quad.pushedTextures)if(!t.has(r))return!0}if(this.mesh.pushedGradients.size){let t=new Set;for(let r of e.commands)"fn"in r||r.batch instanceof tn||t.add(r.cmd.gradient);for(let r of this.mesh.pushedGradients)if(!t.has(r))return!0}return!1}flushAll(){this.quadSeq>=0&&(this.meshSeq<0||this.quadSeq>this.meshSeq)&&(this.quadSeq=-1,this.quad.flush()),this.meshSeq>=0&&(this.meshSeq=-1,this.mesh.flush()),this.executeDeferred()}executeDeferred(){if(this.requestSnapshot&&(this.requestSnapshot=!1,this.retained={commands:this.deferred,quadSlots:this.quad.currentFrameSlots(),meshSlots:this.mesh.currentFrameSlots(),quadTotal:this.quad.instanceTotal,meshTotal:this.mesh.vertexTotal}),!!this.deferred.length){this.quad.uploadPending(),this.mesh.uploadPending();for(let e of this.deferred)"fn"in e?e.fn():(e.batch instanceof tn,e.batch.drawDeferred(e.cmd));this.deferred=[]}}reset(){this.seq=0,this.quadSeq=-1,this.meshSeq=-1,this.deferred=[]}discardRecorded(){this.deferred=[]}replaySnapshot(e){this.quad.uploadPending(),this.mesh.uploadPending();for(let t of e.commands)"fn"in t?t.fn():(t.batch instanceof tn,t.batch.drawDeferred(t.cmd))}};var $m=new Float32Array(9),Pt=8,Q0=8192,ca=class{gl;order=null;ownerBlocks=new WeakMap;gpuRecords=new Map;pendingSegments=[];pendingUploads=[];deferDraws=!1;frameSlots=null;drawnFrom=0;programInfo=null;vao=null;vertexBuffer=null;whiteTex=null;vertexData=new Float32Array(Q0*Pt);vertexCount=0;currentGradient=null;viewMat=[1,0,0,1,0,0];disposed=!1;constructor(e){this.gl=e,this.init()}init(){let e=this.gl;if(this.programInfo=sa(e,zm,Ym),!this.programInfo){this.disposed=!0;return}this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertexData.byteLength,e.DYNAMIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,Pt*4,0),e.enableVertexAttribArray(1),e.vertexAttribPointer(1,4,e.FLOAT,!1,Pt*4,8),e.enableVertexAttribArray(2),e.vertexAttribPointer(2,2,e.FLOAT,!1,Pt*4,24),e.bindVertexArray(null),this.whiteTex=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.whiteTex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255])),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)}get valid(){return!this.disposed&&!!this.programInfo}rebuild(){this.release(),this.disposed=!1,this.init()}release(){let e=this.gl;this.vertexBuffer&&e.deleteBuffer(this.vertexBuffer),this.vao&&e.deleteVertexArray(this.vao),this.programInfo&&e.deleteProgram(this.programInfo.program),this.whiteTex&&e.deleteTexture(this.whiteTex),this.vertexBuffer=null,this.vao=null,this.programInfo=null,this.whiteTex=null,this.vertexCount=0,this.drawnFrom=0,this.currentGradient=null,this.pendingSegments=[],this.pendingUploads=[],this.gpuRecords.clear()}pushedGradients=new Set;begin(e){this.valid&&(this.viewMat=e,this.frameSlots=null,this.vertexCount=0,this.drawnFrom=0,this.currentGradient=null,this.pushedGradients.clear(),this.dropPendingSegments(),this.pendingUploads=[])}pushMesh(e,t,r,o,i,s){if(!this.valid)return;this.order?.beforeMeshPush(),(!!i!=!!this.currentGradient||i&&this.currentGradient&&i!==this.currentGradient)&&(this.flush(),this.currentGradient=i??null);let a=o.length/3,l=a*3*Pt;this.vertexCount*Pt+l>this.vertexData.length&&this.grow(this.vertexCount*Pt+l);let u=this.vertexCount*Pt;this.pushedGradients.add(i??null);let c=!0,h=s?this.ownerBlocks.get(s):void 0;if(h&&h.floatCount===l&&h.verts===r&&h.triangles===o&&h.m0===e[0]&&h.m1===e[1]&&h.m2===e[2]&&h.m3===e[3]&&h.m4===e[4]&&h.m5===e[5]&&h.c0===t[0]&&h.c1===t[1]&&h.c2===t[2]&&h.c3===t[3])this.vertexData.set(h.block,u),c=!1;else{let p=e,b=this.vertexData,g=u;for(let x=0;x<o.length;x++){let S=o[x]*2,w=r[S],y=r[S+1];b[g]=p[0]*w+p[2]*y+p[4],b[g+1]=p[1]*w+p[3]*y+p[5],b[g+2]=t[0],b[g+3]=t[1],b[g+4]=t[2],b[g+5]=t[3],b[g+6]=w,b[g+7]=y,g+=Pt}s&&this.ownerBlocks.set(s,{floatCount:l,verts:r,triangles:o,m0:e[0],m1:e[1],m2:e[2],m3:e[3],m4:e[4],m5:e[5],c0:t[0],c1:t[1],c2:t[2],c3:t[3],block:this.vertexData.slice(u,u+l)})}let d=s?this.gpuRecords.get(s):void 0,f=d&&d.startFloat===u&&d.floatCount===l,m=c||!f;if(this.pendingSegments.push({owner:s??null,startFloat:u,floatCount:l,dirty:m}),m){let p=this.pendingUploads[this.pendingUploads.length-1];p&&p[1]===u?p[1]=u+l:this.pendingUploads.push([u,u+l])}if(this.vertexCount+=a*3,s){let p=this.frameSlots??=new Map,b=a*3,g=p.get(s);g&&g.start+g.count===this.vertexCount-b?g.count+=b:p.set(s,{start:this.vertexCount-b,count:b})}}flush(){if(!this.valid||this.vertexCount<=this.drawnFrom)return;if(this.deferDraws){let i={startVertex:this.drawnFrom,count:this.vertexCount-this.drawnFrom,gradient:this.currentGradient};if(this.drawnFrom=this.vertexCount,this.order){this.order.recordDraw(this,i);return}this.uploadPending(),this.drawDeferred(i);return}let e=this.gl,{program:t,uniforms:r}=this.programInfo;e.useProgram(t),e.bindVertexArray(this.vao);let o=new Float32Array([this.viewMat[0],this.viewMat[1],0,this.viewMat[2],this.viewMat[3],0,this.viewMat[4],this.viewMat[5],1]);e.uniformMatrix3fv(r.view,!1,o),Ur(e,r,this.currentGradient,0),!this.currentGradient&&this.whiteTex&&(e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.whiteTex),e.uniform1i(r.fillTex,0)),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);for(let[i,s]of this.pendingUploads)e.bufferSubData(e.ARRAY_BUFFER,i*4,this.vertexData,i,s-i),this.invalidateOverlappingRecords(i,s);this.pendingUploads=[],e.drawArrays(e.TRIANGLES,this.drawnFrom,this.vertexCount-this.drawnFrom),this.drawnFrom=this.vertexCount;for(let i of this.pendingSegments)i.owner&&this.gpuRecords.set(i.owner,{startFloat:i.startFloat,floatCount:i.floatCount});this.pendingSegments=[]}currentFrameSlots(){return this.frameSlots??new Map}rewindToSlot(e){this.vertexCount=e,this.drawnFrom>e&&(this.drawnFrom=e)}restoreTotals(e){this.vertexCount=e,this.drawnFrom=e}uploadPending(){if(!this.valid)return;let e=this.gl;e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer);let t=this.pendingUploads;for(let r=0;r<t.length;r++){let[o,i]=t[r],s=t[r+1];if(s&&s[0]<=i+4096){s[0]=o;continue}e.bufferSubData(e.ARRAY_BUFFER,o*4,this.vertexData,o,i-o),this.invalidateOverlappingRecords(o,i)}this.pendingUploads=[];for(let r of this.pendingSegments)r.owner&&this.gpuRecords.set(r.owner,{startFloat:r.startFloat,floatCount:r.floatCount});this.pendingSegments=[]}dropPendingSegments(){for(let e of this.pendingSegments)e.dirty&&e.owner&&this.gpuRecords.delete(e.owner);this.pendingSegments=[]}invalidateOverlappingRecords(e,t){if(this.gpuRecords.size===0)return;let r=new Set;for(let o of this.pendingSegments)o.owner&&o.startFloat<t&&e<o.startFloat+o.floatCount&&r.add(o.owner);for(let[o,i]of this.gpuRecords)!r.has(o)&&i.startFloat<t&&e<i.startFloat+i.floatCount&&this.gpuRecords.delete(o)}drawDeferred(e){if(!this.valid)return;let t=this.gl,{program:r,uniforms:o}=this.programInfo;t.useProgram(r),t.bindVertexArray(this.vao),$m.set([this.viewMat[0],this.viewMat[1],0,this.viewMat[2],this.viewMat[3],0,this.viewMat[4],this.viewMat[5],1]),t.uniformMatrix3fv(o.view,!1,$m),Ur(t,o,e.gradient,0),!e.gradient&&this.whiteTex&&(t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.whiteTex),t.uniform1i(o.fillTex,0)),t.drawArrays(t.TRIANGLES,e.startVertex,e.count)}grow(e){let t=this.gl,r=this.vertexData.length;for(;r<e;)r*=2;let o=new Float32Array(r);o.set(this.vertexData.subarray(0,this.vertexCount*Pt)),this.vertexData=o,t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexData.byteLength,t.DYNAMIC_DRAW),this.gpuRecords.clear(),this.pendingUploads=[[0,this.vertexCount*Pt]]}get drawnVertices(){return this.vertexCount}get vertexTotal(){return this.vertexCount}dispose(){this.disposed||(this.disposed=!0,this.release())}};var Gt=nc,J0=[Gt[0],Gt[1],Gt[2],.14],Yc=[1,1,1,1],eS=2,qm=[238/255,238/255,238/255,128/255],Km=[24/255,144/255,1,128/255],qo=20,Ln=20,ua=null,tS=()=>{if(ua)return ua;let n=e=>{let t=document.createElement("canvas");t.width=qo,t.height=qo;let r=t.getContext("2d");if(!r)return t;let o=qo/2;r.beginPath(),r.arc(o,o,8,0,Math.PI*2),r.fillStyle=e?"#2f6fed":"#ffffff",r.fill(),r.lineWidth=1.5,r.strokeStyle="#2f6fed",r.stroke();let i=4;return r.beginPath(),r.moveTo(o-i,o),r.lineTo(o+i,o),r.moveTo(o,o-i),r.lineTo(o,o+i),r.lineWidth=1.5,r.strokeStyle=e?"#ffffff":"#2f6fed",r.stroke(),t};return ua={normal:n(!1),hover:n(!0)},ua},nS=n=>n.columnWidths.reduce((e,t)=>e+t,0)+(n.cols-1)*n.cellSpacing,rS=n=>n.rowHeights.reduce((e,t)=>e+t,0)+(n.rows-1)*n.cellSpacing,Qm=(n,e,t)=>{let r=0;for(let o=0;o<t;o++)r+=n[o]+e;return r},ha=null,oS=()=>{if(ha)return ha;let n=e=>{let t=document.createElement("canvas");t.width=Ln*2,t.height=Ln*2;let r=t.getContext("2d");if(!r)return t;r.scale(2,2),r.fillStyle=e?"#1890ff20":"#eeeeee99",r.fillRect(0,0,Ln-1,Ln-1);let o=Ln/2-.5,i=Ln/2-.5,s=Ln*.25,a=Ln*.18;r.strokeStyle=e?"#1890ff":"#888888",r.lineWidth=1.5,r.lineCap="round";for(let l=-1;l<=1;l++)r.beginPath(),r.moveTo(o-s,i+l*a),r.lineTo(o+s,i+l*a),r.stroke();return t};return ha={normal:n(!1),hover:n(!0)},ha},Zm=(n,e)=>{let t=[],r=n.tableView,o=n.cellMap,i=n.matrix,s=n.objectScale,a=nS(r)/2,l=rS(r)/2,u=Rt/e/Math.max(s.x,1e-6),c=Rt/e/Math.max(s.y,1e-6);for(let g of n.selectedCells){let x=o.get(`${g.row},${g.col}`);if(x?.isMerged)continue;let S=x?.rowspan??1,w=x?.colspan??1,y=Eo(r,{r1:g.row,r2:g.row+S-1,c1:g.col,c2:g.col+w-1}),v=y.left+y.width/2,R=y.top+y.height/2;t.push({matrix:j(i,[1,0,0,1,v,R]),dims:{x:y.width,y:y.height},color:J0}),t.push({matrix:j(i,[1,0,0,1,v,y.top]),dims:{x:y.width+2*u,y:c},color:Gt}),t.push({matrix:j(i,[1,0,0,1,v,y.top+y.height]),dims:{x:y.width+2*u,y:c},color:Gt}),t.push({matrix:j(i,[1,0,0,1,y.left,R]),dims:{x:u,y:y.height+2*c},color:Gt}),t.push({matrix:j(i,[1,0,0,1,y.left+y.width,R]),dims:{x:u,y:y.height+2*c},color:Gt})}if(n.hoveredBorder){let{type:g,position:x}=n.hoveredBorder,S=g==="col"?Q(i,x,-l):Q(i,-a,x),w=g==="col"?Q(i,x,l):Q(i,a,x);t.push(Re(S,w,eS/e,Gt))}let h=-n.dims.x/2,d=-n.dims.y/2,f=20/(e*Math.max(s.x,1e-6)),m=20/(e*Math.max(s.y,1e-6)),p=Ar(o,n.selectedCells);for(let g=0;g<r.rows;g++){let x=Qm(r.rowHeights,r.cellSpacing,g)-l,S=r.rowHeights[g],w=n.hoveredStrip?.kind==="row"&&n.hoveredStrip.index===g?!0:p.rows.has(g);t.push({matrix:j(i,[1,0,0,1,h-f/2,x+S/2]),dims:{x:f,y:S},color:w?Km:qm})}for(let g=0;g<r.cols;g++){let x=Qm(r.columnWidths,r.cellSpacing,g)-a,S=r.columnWidths[g],w=n.hoveredStrip?.kind==="col"&&n.hoveredStrip.index===g?!0:p.cols.has(g);t.push({matrix:j(i,[1,0,0,1,x+S/2,d-m/2]),dims:{x:S,y:m},color:w?Km:qm})}{let g=oS();t.push({matrix:j(i,[1,0,0,1,h-f/2,d-m/2]),dims:{x:f,y:m},color:Yc,texture:n.hoveredDragHandle?g.hover:g.normal})}let b=n.hoveredIndicator??(n.borderDragging?null:n.hoveredBorder);if(b){let g=tS(),x=b.type==="col";t.push({matrix:j(i,[1,0,0,1,x?b.position:-a-15,x?-l-15:b.position]),dims:{x:qo/(e*Math.max(s.x,1e-6)),y:qo/(e*Math.max(s.y,1e-6))},color:Yc,texture:n.hoveredIndicator?g.hover:g.normal})}if(n.selectedCells.length&&!n.editingCell&&!n.isFullCellSelection){let g=n.selectionBoundsRect;if(g){let x=g.left+g.width,S=g.top+g.height,w=kn/e/Math.max(s.x,1e-6),y=kn/e/Math.max(s.y,1e-6),v=(kn-2*Rt)/e/Math.max(s.x,1e-6),R=(kn-2*Rt)/e/Math.max(s.y,1e-6);t.push({matrix:j(i,[1,0,0,1,x,S]),dims:{x:w,y},color:Gt}),t.push({matrix:j(i,[1,0,0,1,x,S]),dims:{x:v,y:R},color:n.hoveredRangeHandle?Gt:Yc})}}return t};var iS=(n,e,t,r)=>{let o=n.nodes.filter(h=>Ze(h)&&h.visible&&h.raw.visible!==!1);if(!o.length)return[];let i=e[0],s=-e[4]/i,a=-e[5]/i,l=t/i,u=r/i,c=[];for(let h of o){let d=h.raw,f=ee(typeof d.stroke=="string"?d.stroke:"pink"),m=typeof d.opacity=="number"?d.opacity:1,p=[f[0],f[1],f[2],f[3]*m],b=Math.max(Number(d.strokeWidth)||1,1.2/i),g=h.bounds;if(h.dims.y===0){let x=(g.top+g.bottom)/2;c.push({matrix:[1,0,0,1,s+l/2,x],dims:{x:l,y:b},color:p})}else if(h.dims.x===0){let x=(g.left+g.right)/2;c.push({matrix:[1,0,0,1,x,a+u/2],dims:{x:b,y:u},color:p})}}return c},Jm=n=>{let{doc:e,zoom:t,marquee:r,textEdit:o,snapOverlay:i,ruler:s}=n,a=n.rotate??null,l=o.node,u=!l&&!r&&e.selection.length===1&&e.selection[0]instanceof le?e.selection[0]:null,c=l?[...n.cellEditOverlayOnly?[]:Pn(l.aCoords,t),...o.quads]:r?Hd(r,t):u?.editingMask?Gd(u,t,a):Wd(e,t,a,n.mobileControls===!0),h=l&&e.selection.length===1?e.selection[0]:null;l&&h instanceof J&&h.containsDeep(l)&&(c=[...c,...ws(h.aCoords,t)]),!l&&!r&&e.selection.length===1&&e.selection[0]instanceof te&&(c=[...c,...Zm(e.selection[0],t)]);let d=e.seamHover;if(u&&d&&d.puzzle===u&&(c=[...c,...zd(Xd(d.puzzle,d.mask,d.handle),t)]),e.hovered&&!r&&!Ze(e.hovered)&&(c=[...c,...Yd(e.hovered,t)]),c=[...c,...i],s&&(c=[...c,...iS(e,s.vpt,s.cssWidth,s.cssHeight)],s.visible!==!1)){let f=e.nodes.find(p=>p.raw.id===Sn),m=f&&typeof f.raw.width=="number"&&typeof f.raw.height=="number"?{left:f.raw.left??0,top:f.raw.top??0,width:f.raw.width,height:f.raw.height}:null;c=[...c,...rf({vpt:s.vpt,cssWidth:s.cssWidth,cssHeight:s.cssHeight,workspaceRect:m,referenceLine:s.referenceLine??null,selectionRects:e.selection.filter(p=>!Ze(p)).map(p=>({left:p.bounds.left,top:p.bounds.top,width:p.bounds.right-p.bounds.left,height:p.bounds.bottom-p.bounds.top}))})]}return c};function ep(n,e,t,r,o){for(let i=0;i<o;i++){let s=t[i];if(!Ze(s)&&!rr(s)){if(r&&s===r.target)for(let a of r.underlay())n.pushQuad(a.matrix,a.dims.x,a.dims.y,a.color,null);e.renderSceneNode(s)}}}function tp(n,e){for(let t of e)rr(t)&&t.visible&&n.renderSceneNode(t)}function np(n){let e=n.doc.editingNode;if(n.cropSessionController.active){Ko(n,n.cropSessionController.buildOverlay(n.zoom))&&n.requestRenderAll();return}if(n.expandSessionController.active){Ko(n,n.expandSessionController.buildOverlay(n.zoom))&&n.requestRenderAll();return}if(n.pathSessionController.active){Ko(n,n.pathSessionController.buildOverlay(n.zoom))&&n.requestRenderAll();return}if(n.warpSessionController.active){Ko(n,n.warpSessionController.buildOverlay())&&n.requestRenderAll();return}let t=Jm({doc:n.doc,zoom:n.zoom,marquee:n.marquee,textEdit:{node:e,quads:e?n.textEditing.buildOverlay():[]},cellEditOverlayOnly:e!==null&&n.tableCellEditing.isOverlay(e),snapOverlay:n.snapGuide.buildOverlay(n.zoom),rotate:n.rotateDrag,mobileControls:n.mobileControls,ruler:{vpt:n.vpt,cssWidth:n.cssWidth,cssHeight:n.cssHeight,referenceLine:n.referenceLineDrag,visible:n.rulerVisible}});Ko(n,t),n.renderer.frame.animationActive&&n.requestRenderAll()}function Ko(n,e){for(let t of e)n.batch.pushQuad(t.matrix,t.dims.x,t.dims.y,t.color,t.texture?n.textures.get(t.texture):null);return n.batch.flush(),n.batch.deferDraws=!1,n.meshBatch.deferDraws=!1,n.batchOrder.executeDeferred(),n.renderer.frame.animationActive}var da=class{constructor(e){this.host=e}host;limit=-1;rafId=null;deadline=0;rendered=!1;start(e=1e3,t=800){if(!this.host.alive())return;let r=this.host.nodeCount();r<e||(this.rafId!==null&&cancelAnimationFrame(this.rafId),this.limit=Math.min(e,r),this.rendered=!1,this.deadline=performance.now()+t,this.rafId=requestAnimationFrame(()=>this.step()))}step(){if(this.rafId=null,this.limit<0||!this.host.alive())return;let e=this.host.nodeCount();if(this.limit>=e){this.limit=-1,this.host.onProgressiveDone(e);return}let t=performance.now();this.host.render(),this.rendered=!0;let r=performance.now()-t,o=r>1?Math.min(4,Math.max(.5,20/r)):2;if(this.limit=Math.min(e,Math.max(this.limit+1,Math.round(this.limit*(1+o)))),this.limit>=e){this.host.render(),this.limit=-1,this.host.onProgressiveDone(e);return}this.rafId=requestAnimationFrame(()=>this.step())}absorbExternalRenderRequest(){this.rendered&&performance.now()>this.deadline&&this.limit>=0&&this.limit<this.host.nodeCount()&&(this.limit=this.host.nodeCount())}dispose(){this.rafId!==null&&cancelAnimationFrame(this.rafId),this.rafId=null,this.limit=-1,this.rendered=!1}};var fa=class{constructor(e){this.host=e}host;retained=null;lastFrameAnimated=!1;lastFrameBakeMore=!1;lastGateReason=null;tryRetainedFrame(){let{host:e}=this;if(e.renderer.flatFrame=!0,!Ka())return this.gateFail("flag-off");let t=this.retained;if(!t)return this.gateFail("no-snapshot");if(this.lastFrameAnimated)return this.gateFail("animating");if(this.lastFrameBakeMore)return this.gateFail("bake-continue");if(e.cropSessionController.active||e.expandSessionController.active||e.pathSessionController.active||e.warpSessionController.active)return this.gateFail("session");if(e.progressiveLoad.limit>=0&&e.progressiveLoad.limit<e.doc.nodes.length)return this.gateFail("progressive");if(e.doc.editingNode)return this.gateFail("editing");if(t.structureVersion!==e.doc.structureVersion)return this.gateFail("structure");if(t.vptKey!==e.vpt.join(","))return this.gateFail("vpt");if(t.dpr!==e.dpr||t.sizeKey!==`${e.canvasEl.width}x${e.canvasEl.height}`)return this.gateFail("surface");if(t.artifactEpoch!==e.renderEpoch.value)return this.gateFail(`artifact-epoch(${e.renderEpoch.lastReason})`);let r=t.snap,o=e.doc.renderDirty;for(let i of o){if(i.isReferenceLine||rr(i))continue;let s=r.quadSlots.get(i),a=r.meshSlots.get(i);if(!s&&!a)return this.gateFail("no-slot");let l=e.batch.instanceTotal,u=e.meshBatch.vertexTotal;if(s&&e.batch.rewindToSlot(s.start),a&&e.meshBatch.rewindToSlot(a.start),e.renderer.renderSceneNode(i),e.batch.instanceTotal!==(s?s.start+s.count:l))return this.gateFail("contract-quad");if(e.meshBatch.vertexTotal!==(a?a.start+a.count:u))return this.gateFail("contract-mesh");if(!e.renderer.flatFrame)return this.gateFail("isolated");if(e.batchOrder.hasNovelPaintReferences(r))return this.gateFail("repush-commands")}return t.artifactEpoch!==e.renderEpoch.value?this.gateFail(`artifact-epoch-late(${e.renderEpoch.lastReason})`):(e.batch.restoreTotals(r.quadTotal),e.meshBatch.restoreTotals(r.meshTotal),e.batchOrder.discardRecorded(),e.glyphAtlas.keepPagesForRetainedFrame(),e.batchOrder.replaySnapshot(r),this.gateOk(),!0)}captureSnapshot(){let{host:e}=this;if(!Ka()){this.retained=null;return}let t=e.renderer.flatFrame,r=e.cropSessionController.active||e.expandSessionController.active||e.pathSessionController.active||e.warpSessionController.active,o=e.progressiveLoad.limit>=0&&e.progressiveLoad.limit<e.doc.nodes.length;if(!t||r||o||e.doc.editingNode){this.retained=null,this.logDebug(`snapshot 跳过(flat=${t} sessions=${r} progressive=${o} editing=${e.doc.editingNode!==null})`);return}let i=e.batchOrder.retained;if(this.retained=i?{snap:i,structureVersion:e.doc.structureVersion,vptKey:e.vpt.join(","),dpr:e.dpr,sizeKey:`${e.canvasEl.width}x${e.canvasEl.height}`,artifactEpoch:e.renderEpoch.value}:null,i&&zn()){let s=e.glyphAtlas.stats();console.info("[retained] 快照收录",{commands:i.commands.length,quadSlots:i.quadSlots.size,meshSlots:i.meshSlots.size,structureVersion:e.doc.structureVersion,atlasPages:s.pages,artifactEpoch:e.renderEpoch.value,epochLastReason:e.renderEpoch.lastReason})}}noteFrameRendered(){this.lastFrameAnimated=this.host.renderer.frame.animationActive,this.lastFrameBakeMore=this.host.renderer.frame.bakeMore}invalidate(){this.retained=null}dispose(){this.retained=null}gateFail(e){return this.lastGateReason!==e&&(this.lastGateReason=e,zn()&&console.info("[retained] 门链回退:",e)),!1}gateOk(){this.lastGateReason!==null&&(this.lastGateReason=null,zn()&&console.info("[retained] 保留式帧恢复生效"))}logDebug(e){zn()&&console.info("[retained]",e)}};var sS=`#version 300 es
257
257
  out vec2 vUv;
258
258
  void main() {
259
259
  vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
260
260
  vUv = p;
261
261
  gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
262
- }`,sS=`#version 300 es
262
+ }`,aS=`#version 300 es
263
263
  precision mediump float;
264
264
  in vec2 vUv;
265
265
  uniform sampler2D uSrc;
@@ -284,13 +284,13 @@ ma = uCovers;
284
284
  factor *= mix(ma, 1.0 - ma, uInvert);
285
285
  }
286
286
  outColor = vec4(src.rgb * factor, src.a * factor);
287
- }`,ma=class{fb=null;tex=null;prog=null;w=0;h=0;vao=null;boundFb=null;stencilRb=null;savedStencilEnabled=!1;savedStencilFunc=0;savedStencilRef=0;savedStencilMask=0;ensureProgram(e){if(this.prog)return;let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[GLIsolator] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,iS),o=t(e.FRAGMENT_SHADER,sS),i=e.createProgram();if(!(!r||!o||!i)){if(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),!e.getProgramParameter(i,e.LINK_STATUS)){console.warn("[GLIsolator] link:",e.getProgramInfoLog(i));return}this.prog=i,this.vao=e.createVertexArray()}}ensureSize(e,t,r){this.fb&&this.w===t&&this.h===r||(this.fb&&e.deleteFramebuffer(this.fb),this.tex&&e.deleteTexture(this.tex),this.stencilRb&&e.deleteRenderbuffer(this.stencilRb),this.tex=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.tex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.fb=e.createFramebuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this.fb),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.tex,0),this.stencilRb=e.createRenderbuffer(),this.stencilRb&&(e.bindRenderbuffer(e.RENDERBUFFER,this.stencilRb),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH24_STENCIL8,t,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,this.stencilRb),e.bindRenderbuffer(e.RENDERBUFFER,null)),e.bindFramebuffer(e.FRAMEBUFFER,null),this.w=t,this.h=r)}begin(e,t,r){return this.boundFb=e.getParameter(e.FRAMEBUFFER_BINDING),this.ensureProgram(e),!this.prog||(this.ensureSize(e,t,r),!this.fb)?!1:(this.savedStencilEnabled=e.isEnabled(e.STENCIL_TEST),this.savedStencilEnabled&&(this.savedStencilFunc=e.getParameter(e.STENCIL_FUNC),this.savedStencilRef=e.getParameter(e.STENCIL_REF),this.savedStencilMask=e.getParameter(e.STENCIL_VALUE_MASK)),e.bindFramebuffer(e.FRAMEBUFFER,this.fb),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),this.stencilRb&&(e.clearStencil(0),e.clear(e.STENCIL_BUFFER_BIT)),e.disable(e.STENCIL_TEST),!0)}end(e){e.bindFramebuffer(e.FRAMEBUFFER,this.boundFb),this.savedStencilEnabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.savedStencilEnabled&&e.stencilFunc(this.savedStencilFunc,this.savedStencilRef,this.savedStencilMask)}composite(e,t,r){!this.prog||!this.tex||(e.useProgram(this.prog),e.bindVertexArray(this.vao),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.tex),e.uniform1i(e.getUniformLocation(this.prog,"uSrc"),0),e.uniform1f(e.getUniformLocation(this.prog,"uOpacity"),t),r?(e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,r.tex),e.uniform1i(e.getUniformLocation(this.prog,"uMask"),1),e.uniformMatrix3fv(e.getUniformLocation(this.prog,"uMaskInv"),!1,r.maskInv),e.uniform1f(e.getUniformLocation(this.prog,"uHasMask"),1),e.uniform1f(e.getUniformLocation(this.prog,"uCovers"),r.coversHost?1:0),e.uniform1f(e.getUniformLocation(this.prog,"uInvert"),r.invert?1:0)):e.uniform1f(e.getUniformLocation(this.prog,"uHasMask"),0),e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLES,0,3),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.bindVertexArray(null),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null))}dispose(e){this.fb&&e.deleteFramebuffer(this.fb),this.tex&&e.deleteTexture(this.tex),this.prog&&e.deleteProgram(this.prog),this.vao&&e.deleteVertexArray(this.vao),this.fb=null,this.tex=null,this.prog=null,this.vao=null}};var Yc=["multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","lighter"],aS=new Map(Yc.map((n,e)=>[n,e])),pa=n=>typeof n!="string"?null:aS.get(n)??null;var lS=`#version 300 es
287
+ }`,ma=class{fb=null;tex=null;prog=null;w=0;h=0;vao=null;boundFb=null;stencilRb=null;savedStencilEnabled=!1;savedStencilFunc=0;savedStencilRef=0;savedStencilMask=0;ensureProgram(e){if(this.prog)return;let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[GLIsolator] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,sS),o=t(e.FRAGMENT_SHADER,aS),i=e.createProgram();if(!(!r||!o||!i)){if(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),!e.getProgramParameter(i,e.LINK_STATUS)){console.warn("[GLIsolator] link:",e.getProgramInfoLog(i));return}this.prog=i,this.vao=e.createVertexArray()}}ensureSize(e,t,r){this.fb&&this.w===t&&this.h===r||(this.fb&&e.deleteFramebuffer(this.fb),this.tex&&e.deleteTexture(this.tex),this.stencilRb&&e.deleteRenderbuffer(this.stencilRb),this.tex=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.tex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.fb=e.createFramebuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this.fb),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.tex,0),this.stencilRb=e.createRenderbuffer(),this.stencilRb&&(e.bindRenderbuffer(e.RENDERBUFFER,this.stencilRb),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH24_STENCIL8,t,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,this.stencilRb),e.bindRenderbuffer(e.RENDERBUFFER,null)),e.bindFramebuffer(e.FRAMEBUFFER,null),this.w=t,this.h=r)}begin(e,t,r){return this.boundFb=e.getParameter(e.FRAMEBUFFER_BINDING),this.ensureProgram(e),!this.prog||(this.ensureSize(e,t,r),!this.fb)?!1:(this.savedStencilEnabled=e.isEnabled(e.STENCIL_TEST),this.savedStencilEnabled&&(this.savedStencilFunc=e.getParameter(e.STENCIL_FUNC),this.savedStencilRef=e.getParameter(e.STENCIL_REF),this.savedStencilMask=e.getParameter(e.STENCIL_VALUE_MASK)),e.bindFramebuffer(e.FRAMEBUFFER,this.fb),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),this.stencilRb&&(e.clearStencil(0),e.clear(e.STENCIL_BUFFER_BIT)),e.disable(e.STENCIL_TEST),!0)}end(e){e.bindFramebuffer(e.FRAMEBUFFER,this.boundFb),this.savedStencilEnabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.savedStencilEnabled&&e.stencilFunc(this.savedStencilFunc,this.savedStencilRef,this.savedStencilMask)}composite(e,t,r){!this.prog||!this.tex||(e.useProgram(this.prog),e.bindVertexArray(this.vao),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.tex),e.uniform1i(e.getUniformLocation(this.prog,"uSrc"),0),e.uniform1f(e.getUniformLocation(this.prog,"uOpacity"),t),r?(e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,r.tex),e.uniform1i(e.getUniformLocation(this.prog,"uMask"),1),e.uniformMatrix3fv(e.getUniformLocation(this.prog,"uMaskInv"),!1,r.maskInv),e.uniform1f(e.getUniformLocation(this.prog,"uHasMask"),1),e.uniform1f(e.getUniformLocation(this.prog,"uCovers"),r.coversHost?1:0),e.uniform1f(e.getUniformLocation(this.prog,"uInvert"),r.invert?1:0)):e.uniform1f(e.getUniformLocation(this.prog,"uHasMask"),0),e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLES,0,3),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.bindVertexArray(null),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null))}dispose(e){this.fb&&e.deleteFramebuffer(this.fb),this.tex&&e.deleteTexture(this.tex),this.prog&&e.deleteProgram(this.prog),this.vao&&e.deleteVertexArray(this.vao),this.fb=null,this.tex=null,this.prog=null,this.vao=null}};var Uc=["multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","lighter"],lS=new Map(Uc.map((n,e)=>[n,e])),pa=n=>typeof n!="string"?null:lS.get(n)??null;var cS=`#version 300 es
288
288
  out vec2 vUv;
289
289
  void main() {
290
290
  vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
291
291
  vUv = p;
292
292
  gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
293
- }`,cS=`#version 300 es
293
+ }`,uS=`#version 300 es
294
294
  precision mediump float;
295
295
  in vec2 vUv;
296
296
  uniform sampler2D uSrc;
@@ -376,13 +376,13 @@ vec3 b = blendB(cb, cs, uMode);
376
376
  vec3 co = (1.0 - ab) * src.rgb + b * (as * ab) + (1.0 - as) * dst.rgb;
377
377
  float ao = as + ab * (1.0 - as);
378
378
  outColor = vec4(co, ao);
379
- }`,Qo=class{fb=null;tex=null;stencilRb=null;savedStencilEnabled=!1;savedStencilFunc=0;savedStencilRef=0;savedStencilMask=0;dstTex=null;prog=null;w=0;h=0;vao=null;boundFb=null;ensureProgram(e){if(this.prog)return;let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[GLBlender] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,lS),o=t(e.FRAGMENT_SHADER,cS),i=e.createProgram();if(!(!r||!o||!i)){if(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),!e.getProgramParameter(i,e.LINK_STATUS)){console.warn("[GLBlender] link:",e.getProgramInfoLog(i));return}this.prog=i,this.vao=e.createVertexArray()}}ensureSize(e,t,r){return this.fb&&this.w===t&&this.h===r?!0:(this.fb&&e.deleteFramebuffer(this.fb),this.tex&&e.deleteTexture(this.tex),this.tex=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.tex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.fb=e.createFramebuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this.fb),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.tex,0),this.stencilRb&&e.deleteRenderbuffer(this.stencilRb),this.stencilRb=e.createRenderbuffer(),this.stencilRb&&(e.bindRenderbuffer(e.RENDERBUFFER,this.stencilRb),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH24_STENCIL8,t,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,this.stencilRb),e.bindRenderbuffer(e.RENDERBUFFER,null)),this.dstTex&&e.deleteTexture(this.dstTex),this.dstTex=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.dstTex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),this.w=t,this.h=r,!!this.fb)}begin(e,t,r){return this.boundFb=e.getParameter(e.FRAMEBUFFER_BINDING),this.ensureProgram(e),!this.prog||!this.ensureSize(e,t,r)||!this.fb?!1:(this.savedStencilEnabled=e.isEnabled(e.STENCIL_TEST),this.savedStencilEnabled&&(this.savedStencilFunc=e.getParameter(e.STENCIL_FUNC),this.savedStencilRef=e.getParameter(e.STENCIL_REF),this.savedStencilMask=e.getParameter(e.STENCIL_VALUE_MASK)),e.bindFramebuffer(e.FRAMEBUFFER,this.fb),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),this.stencilRb&&(e.clearStencil(0),e.clear(e.STENCIL_BUFFER_BIT)),e.disable(e.STENCIL_TEST),!0)}end(e){e.bindFramebuffer(e.FRAMEBUFFER,this.boundFb),this.savedStencilEnabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.savedStencilEnabled&&e.stencilFunc(this.savedStencilFunc,this.savedStencilRef,this.savedStencilMask)}composite(e,t){!this.prog||!this.tex||!this.dstTex||t<0||t>=Yc.length||(e.bindTexture(e.TEXTURE_2D,this.dstTex),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,this.w,this.h),e.useProgram(this.prog),e.bindVertexArray(this.vao),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.tex),e.uniform1i(e.getUniformLocation(this.prog,"uSrc"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.dstTex),e.uniform1i(e.getUniformLocation(this.prog,"uDst"),1),e.uniform1i(e.getUniformLocation(this.prog,"uMode"),t),e.disable(e.BLEND),e.drawArrays(e.TRIANGLES,0,3),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.bindVertexArray(null),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null))}dispose(e){this.fb&&e.deleteFramebuffer(this.fb),this.tex&&e.deleteTexture(this.tex),this.dstTex&&e.deleteTexture(this.dstTex),this.prog&&e.deleteProgram(this.prog),this.vao&&e.deleteVertexArray(this.vao),this.fb=null,this.tex=null,this.dstTex=null,this.prog=null,this.vao=null,this.w=0,this.h=0}};var Ae=(n,e,t={})=>{let r=n.createTexture();if(!r)return null;n.bindTexture(n.TEXTURE_2D,r),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e),t.mipmap&&n.generateMipmap(n.TEXTURE_2D),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,t.mipmap?n.LINEAR_MIPMAP_LINEAR:n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR);let o=t.repeat?n.REPEAT:n.CLAMP_TO_EDGE;return n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,o),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,o),r};var np=`#version 300 es
379
+ }`,Qo=class{fb=null;tex=null;stencilRb=null;savedStencilEnabled=!1;savedStencilFunc=0;savedStencilRef=0;savedStencilMask=0;dstTex=null;prog=null;w=0;h=0;vao=null;boundFb=null;ensureProgram(e){if(this.prog)return;let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[GLBlender] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,cS),o=t(e.FRAGMENT_SHADER,uS),i=e.createProgram();if(!(!r||!o||!i)){if(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),!e.getProgramParameter(i,e.LINK_STATUS)){console.warn("[GLBlender] link:",e.getProgramInfoLog(i));return}this.prog=i,this.vao=e.createVertexArray()}}ensureSize(e,t,r){return this.fb&&this.w===t&&this.h===r?!0:(this.fb&&e.deleteFramebuffer(this.fb),this.tex&&e.deleteTexture(this.tex),this.tex=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.tex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.fb=e.createFramebuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this.fb),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.tex,0),this.stencilRb&&e.deleteRenderbuffer(this.stencilRb),this.stencilRb=e.createRenderbuffer(),this.stencilRb&&(e.bindRenderbuffer(e.RENDERBUFFER,this.stencilRb),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH24_STENCIL8,t,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,this.stencilRb),e.bindRenderbuffer(e.RENDERBUFFER,null)),this.dstTex&&e.deleteTexture(this.dstTex),this.dstTex=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.dstTex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),this.w=t,this.h=r,!!this.fb)}begin(e,t,r){return this.boundFb=e.getParameter(e.FRAMEBUFFER_BINDING),this.ensureProgram(e),!this.prog||!this.ensureSize(e,t,r)||!this.fb?!1:(this.savedStencilEnabled=e.isEnabled(e.STENCIL_TEST),this.savedStencilEnabled&&(this.savedStencilFunc=e.getParameter(e.STENCIL_FUNC),this.savedStencilRef=e.getParameter(e.STENCIL_REF),this.savedStencilMask=e.getParameter(e.STENCIL_VALUE_MASK)),e.bindFramebuffer(e.FRAMEBUFFER,this.fb),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),this.stencilRb&&(e.clearStencil(0),e.clear(e.STENCIL_BUFFER_BIT)),e.disable(e.STENCIL_TEST),!0)}end(e){e.bindFramebuffer(e.FRAMEBUFFER,this.boundFb),this.savedStencilEnabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.savedStencilEnabled&&e.stencilFunc(this.savedStencilFunc,this.savedStencilRef,this.savedStencilMask)}composite(e,t){!this.prog||!this.tex||!this.dstTex||t<0||t>=Uc.length||(e.bindTexture(e.TEXTURE_2D,this.dstTex),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,this.w,this.h),e.useProgram(this.prog),e.bindVertexArray(this.vao),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.tex),e.uniform1i(e.getUniformLocation(this.prog,"uSrc"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.dstTex),e.uniform1i(e.getUniformLocation(this.prog,"uDst"),1),e.uniform1i(e.getUniformLocation(this.prog,"uMode"),t),e.disable(e.BLEND),e.drawArrays(e.TRIANGLES,0,3),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.bindVertexArray(null),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null))}dispose(e){this.fb&&e.deleteFramebuffer(this.fb),this.tex&&e.deleteTexture(this.tex),this.dstTex&&e.deleteTexture(this.dstTex),this.prog&&e.deleteProgram(this.prog),this.vao&&e.deleteVertexArray(this.vao),this.fb=null,this.tex=null,this.dstTex=null,this.prog=null,this.vao=null,this.w=0,this.h=0}};var Ae=(n,e,t={})=>{let r=n.createTexture();if(!r)return null;n.bindTexture(n.TEXTURE_2D,r),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e),t.mipmap&&n.generateMipmap(n.TEXTURE_2D),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,t.mipmap?n.LINEAR_MIPMAP_LINEAR:n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR);let o=t.repeat?n.REPEAT:n.CLAMP_TO_EDGE;return n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,o),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,o),r};var rp=`#version 300 es
380
380
  out vec2 vUv;
381
381
  void main() {
382
382
  vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
383
383
  vUv = p;
384
384
  gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
385
- }`,uS=`#version 300 es
385
+ }`,hS=`#version 300 es
386
386
  precision mediump float;
387
387
  in vec2 vUv;
388
388
  uniform sampler2D uSrc;
@@ -396,7 +396,7 @@ if (k >= uBoxW) break;
396
396
  acc += texture(uSrc, vUv + uDir * (float(k) - float(uBoxW - 1) * 0.5)).a;
397
397
  }
398
398
  outColor = vec4(0.0, 0.0, 0.0, acc / float(uBoxW));
399
- }`,hS=`#version 300 es
399
+ }`,dS=`#version 300 es
400
400
  precision mediump float;
401
401
  in vec2 vUv;
402
402
  uniform sampler2D uBlur;
@@ -408,13 +408,13 @@ void main() {
408
408
  float bl = texture(uBlur, vUv + uOffUv).a;
409
409
  float sil = texture(uSil, vUv).a;
410
410
  outColor = vec4(uColor.rgb, bl * (1.0 - sil) * uColor.a);
411
- }`,dS=n=>{let e=n.cropRect?`${n.cropRect.sx},${n.cropRect.sy},${n.cropRect.sw},${n.cropRect.sh}`:"",t=n.isTextType?`${n.raw.renderSrc??""}|${n.raw.text??""}|${n.raw.fontSize??""}`:typeof n.raw.src=="string"?`${n.raw.src}|${e}`:e,r=n instanceof ie?`v${n.contentVersion}`:"";return`${n.raw.type};${t};${r};${Fi(n)}`},fS=(n,e,t,r)=>{let o=n.matrix;return[dS(n),n.dims.x,n.dims.y,mS(e),t,r,o[0].toFixed(4),o[1].toFixed(4),o[2].toFixed(4),o[3].toFixed(4)].join(";")},mS=n=>[n.rgba.join(","),n.blur,n.offsetX,n.offsetY,n.nonScaling?1:0].join("|"),ba=class{constructor(e){this.epoch=e}epoch;silhouettes=new WeakMap;targets=new WeakMap;blurProg=null;finalProg=null;b1=null;b2=null;liveRts=new Set;liveSilTexes=new Set;invalidate(e){for(let t of this.liveRts)e.isTexture(t.tex)&&e.deleteTexture(t.tex),e.isFramebuffer(t.fb)&&e.deleteFramebuffer(t.fb);this.liveRts.clear();for(let t of this.liveSilTexes)e.isTexture(t)&&e.deleteTexture(t);this.liveSilTexes.clear(),this.blurProg=null,this.finalProg=null,this.b1=null,this.b2=null,this.silhouettes=new WeakMap,this.targets=new WeakMap}compile(e,t,r){let o=(l,u)=>{let c=e.createShader(l);return c?(e.shaderSource(c,u),e.compileShader(c),e.getShaderParameter(c,e.COMPILE_STATUS)?c:(console.warn("[GpuShadowBaker] shader:",e.getShaderInfoLog(c)),e.deleteShader(c),null)):null},i=o(e.VERTEX_SHADER,t),s=o(e.FRAGMENT_SHADER,r),a=e.createProgram();return!i||!s||!a?null:(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),e.getProgramParameter(a,e.LINK_STATUS)?a:(console.warn("[GpuShadowBaker] link:",e.getProgramInfoLog(a)),null))}ensurePrograms(e){return this.blurProg&&this.finalProg?!0:(this.blurProg=this.blurProg??this.compile(e,np,uS),this.finalProg=this.finalProg??this.compile(e,np,hS),!!(this.blurProg&&this.finalProg))}ensureTarget(e,t,r,o){if(t&&t.w===r&&t.h===o)return t;t&&(e.deleteFramebuffer(t.fb),e.deleteTexture(t.tex),this.liveRts.delete(t));let i=e.createTexture();if(!i)return null;e.bindTexture(e.TEXTURE_2D,i),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r,o,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);let s=e.createFramebuffer();if(!s)return e.deleteTexture(i),null;e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.bindFramebuffer(e.FRAMEBUFFER,null);let a={fb:s,tex:i,w:r,h:o};return this.liveRts.add(a),a}silhouette(e,t,r,o,i){let s=this.silhouettes.get(t);if(s&&s.sig!==r&&(e.deleteTexture(s.tex),this.liveSilTexes.delete(s.tex),this.epoch?.bump("gpu-shadow-silhouette-rebake"),s=void 0),!s){let a=document.createElement("canvas");a.width=o,a.height=i;let l=a.getContext("2d");if(!l)return null;let u=t.matrix;l.setTransform(u[0],u[1],u[2],u[3],o/2,i/2),Di(l,t,"#ffffff");let c=Ae(e,a);if(!c)return null;this.liveSilTexes.add(c),s={sig:r,tex:c,w:o,h:i},this.silhouettes.set(t,s)}return s.tex}fullscreenPass(e,t,r,o){e.bindFramebuffer(e.FRAMEBUFFER,r.fb),e.viewport(0,0,r.w,r.h),e.useProgram(t),o(t),e.disable(e.BLEND),e.bindVertexArray(null),e.drawArrays(e.TRIANGLES,0,3)}render(e,t,r,o,i){if(!this.ensurePrograms(e))return null;let s=e.getParameter(e.FRAMEBUFFER_BINDING),a=Lt(r,t.raw.scaleX??1,t.raw.scaleY??1),l=_i(a)+(t.isTextType?Math.ceil((t.raw.fontSize??40)*.5):0),u=xl(t),c=Math.ceil(u.x+l*2),h=Math.ceil(u.y+l*2);if(!(c>0)||!(h>0)||c>8192||h>8192)return null;let d=fS(t,r,c,h);try{let f=this.targets.get(t);if(f&&f.sig!==d&&(e.deleteFramebuffer(f.rt.fb),e.deleteTexture(f.rt.tex),this.liveRts.delete(f.rt),this.epoch?.bump("gpu-shadow-rebake"),f=void 0),!f){let w=this.ensureTarget(e,null,c,h);if(!w)return null;f={sig:d,rt:w},this.targets.set(t,f)}let m=this.silhouette(e,t,d,c,h);if(!m)return null;this.b1=this.ensureTarget(e,this.b1,c,h),this.b2=this.ensureTarget(e,this.b2,c,h);let p=this.b1,b=this.b2;if(!p||!b)return null;let g=a.blur/2,x=g<.05?1:Math.max(1,Math.min(64,Math.round(Math.sqrt(4*g*g+1)))),S=(w,y,v,R)=>{this.fullscreenPass(e,this.blurProg,y,P=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,w),e.uniform1i(e.getUniformLocation(P,"uSrc"),0),e.uniform2f(e.getUniformLocation(P,"uDir"),v,R),e.uniform1i(e.getUniformLocation(P,"uBoxW"),x)})};return S(m,p,1/c,0),S(p.tex,b,1/c,0),S(b.tex,p,1/c,0),S(p.tex,b,0,1/h),S(b.tex,p,0,1/h),S(p.tex,b,0,1/h),this.fullscreenPass(e,this.finalProg,f.rt,w=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,b.tex),e.uniform1i(e.getUniformLocation(w,"uBlur"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,m),e.uniform1i(e.getUniformLocation(w,"uSil"),1),e.uniform2f(e.getUniformLocation(w,"uOffUv"),-a.offX/c,-a.offY/h),e.uniform4f(e.getUniformLocation(w,"uColor"),r.rgba[0],r.rgba[1],r.rgba[2],r.rgba[3])}),{tex:f.rt.tex,w:c,h}}finally{e.bindFramebuffer(e.FRAMEBUFFER,s),e.viewport(0,0,o,i),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)}}};var ga=class{host;shadowBakes=new WeakMap;liveTexes=new Set;gpuShadowBaker=null;constructor(e){this.host=e}render(e){let t=wh(e.raw.shadow);if(!t)return;let r=e.cropRect?`${e.cropRect.sx},${e.cropRect.sy},${e.cropRect.sw},${e.cropRect.sh}`:"",o=e.isTextType?`${e.raw.renderSrc??""}|${e.raw.text??""}|${e.raw.fontSize??""}`:typeof e.raw.src=="string"?`${e.raw.src}|${r}${Wi(e)}`:r,i=e instanceof ie?`v${e.contentVersion}`:"",s=[Th(t),e.raw.type,e.matrix.join(","),e.dims.x,e.dims.y,Fi(e),o,i].join(";");if(Mu()){this.gpuShadowBaker||(this.gpuShadowBaker=new ba(this.host.renderEpoch));let u=this.gpuShadowBaker.render(this.host.gl,e,t,this.host.canvasEl.width,this.host.canvasEl.height);u&&this.host.batch.pushQuad([1,0,0,1,e.matrix[4],e.matrix[5]],u.w,u.h,[1,1,1,e.renderOpacity],u.tex);return}let a=this.shadowBakes.get(e);if(a&&a.sig!==s&&(a.tex&&(this.host.gl.deleteTexture(a.tex),this.liveTexes.delete(a.tex)),a=void 0),!a){let u=Eh(e,t);if(!u)return;let c=Ae(this.host.gl,u.canvas,{mipmap:!0});if(!c)return;this.liveTexes.add(c),a={sig:s,tex:c,w:u.w,h:u.h},this.shadowBakes.set(e,a)}if(!a.tex)return;let l=e.matrix;this.host.batch.pushQuad([1,0,0,1,l[4],l[5]],a.w,a.h,[1,1,1,e.renderOpacity],a.tex)}invalidate(){for(let e of this.liveTexes)this.host.gl.deleteTexture(e);this.liveTexes.clear(),this.shadowBakes=new WeakMap,this.host.renderEpoch?.bump("shadow-bake-invalidate"),this.gpuShadowBaker?.invalidate(this.host.gl)}};var rp=(n,e,t,r)=>{let o=[];for(let T of n){if(!Number.isFinite(T.x)||!Number.isFinite(T.y))return null;let C=o[o.length-1];C&&C.x===T.x&&C.y===T.y||o.push({x:T.x,y:T.y})}if(e&&o.length>1){let T=o[0],C=o[o.length-1];T.x===C.x&&T.y===C.y&&o.pop()}let i=o.length;if(i<(e?3:2))return null;let s=e?i:i-1,a=[],l=[];for(let T=0;T<s;T++){let C=o[T],E=o[(T+1)%i],M=Math.hypot(E.x-C.x,E.y-C.y);if(!(M>1e-12))return null;a.push((E.x-C.x)/M),l.push((E.y-C.y)/M)}let u=[],c=[],h=[],d=[];for(let T=0;T<i;T++){let C=o[T],E=e||T>0,M=e||T<s;if(!E||!M){let D=E?T-1:0,I=-l[D],G=a[D];u.push(C.x+t*I),c.push(C.y+t*G),h.push(C.x-t*I),d.push(C.y-t*G);continue}let k=a[(T-1+s)%s],A=l[(T-1+s)%s],O=a[T%s],F=l[T%s],W=-(k*O+A*F),z=Math.sqrt(Math.max(0,(1-W)/2));if(1/Math.max(z,1e-300)>r*(1+1e-9))return null;let _=k*F-A*O;for(let D of[1,-1]){let I=o[(T-1+i)%i].x+t*D*-A,G=o[(T-1+i)%i].y+t*D*k,$=C.x+t*D*-F,V=C.y+t*D*O;if(Math.abs(_)<1e-12){let q=C.x+t*D*-F,U=C.y+t*D*O;if(!Number.isFinite(q)||!Number.isFinite(U))return null;D===1?(u.push(q),c.push(U)):(h.push(q),d.push(U));continue}let H=$-I,Y=V-G,X=(H*F-Y*O)/_,Z=I+X*k,B=G+X*A;if(!Number.isFinite(Z)||!Number.isFinite(B))return null;D===1?(u.push(Z),c.push(B)):(h.push(Z),d.push(B))}}for(let T=0;T<s;T++){let C=T+1;if((u[C]-u[T])*a[T]+(c[C]-c[T])*l[T]<=0||(h[C]-h[T])*a[T]+(d[C]-d[T])*l[T]<=0)return null}h.reverse(),d.reverse();let f=2*i;if(f>64||f<3)return null;let m=[],p=[],b=(T,C,E)=>{for(let M=0;M+1<T.length;M++)m.push(T[M],T[M+1]),p.push(C[M],C[M+1]);E&&T.length>2&&(m.push(T[T.length-1],T[0]),p.push(C[C.length-1],C[0]))};b(u,c,e),b(h,d,e),e||(m.push(u[u.length-1],h[0]),p.push(c[c.length-1],d[0]),m.push(h[h.length-1],u[0]),p.push(d[d.length-1],c[0]));let g=m.length/2;if(g!==f||g>64)return null;let x=(T,C,E,M,k,A)=>(E-T)*(A-C)-(M-C)*(k-T),S=(T,C)=>{let E=m[T*2],M=p[T*2],k=m[T*2+1],A=p[T*2+1],O=m[C*2],F=p[C*2],W=m[C*2+1],z=p[C*2+1];if(E===k&&M===A||O===W&&F===z)return!1;let _=x(E,M,k,A,O,F),D=x(E,M,k,A,W,z),I=x(O,F,W,z,E,M),G=x(O,F,W,z,k,A);return(_>0&&D<0||_<0&&D>0)&&(I>0&&G<0||I<0&&G>0)};for(let T=0;T<g;T++)for(let C=T+2;C<g;C++)if(S(T,C))return null;let w=new Float32Array(g*4),y=0,v=0,R=0,P=0;for(let T=0;T<g;T++)w[T*4]=m[T*2],w[T*4+1]=p[T*2],w[T*4+2]=m[T*2+1],w[T*4+3]=p[T*2+1],y=Math.max(y,Math.abs(m[T*2]),Math.abs(m[T*2+1])),v=Math.max(v,Math.abs(p[T*2]),Math.abs(p[T*2+1]));for(let T of o)R=Math.max(R,Math.abs(T.x)),P=Math.max(P,Math.abs(T.y));return!(R>0)||!(P>0)?null:{segments:{data:w,count:g,hash:$r(w)},marginX:y-R,marginY:v-P}};var pS=1,bS=2,gS=3,op=4,xS={butt:0,round:1,square:2},yS=1.5,SS=(n,e,t)=>{let r=e?n.length:n.length-1;if(r<1)return null;let o=[],i=[],s=[],a=[];for(let m=0;m<r;m++){let p=n[m],b=n[(m+1)%n.length],g=b.x-p.x,x=b.y-p.y;g*g+x*x<1e-18||(o.push(p.x),i.push(p.y),s.push(b.x),a.push(b.y))}let l=o.length;if(l<1||l>64)return null;let u=new Float32Array(l*4),c=0,h=0;for(let m=0;m<l;m++)u[m*4]=o[m],u[m*4+1]=i[m],u[m*4+2]=s[m],u[m*4+3]=a[m],c=Math.max(c,Math.abs(o[m]),Math.abs(s[m])),h=Math.max(h,Math.abs(i[m]),Math.abs(a[m]));let d=0,f=0;for(let m of n)d=Math.max(d,Math.abs(m.x)),f=Math.max(f,Math.abs(m.y));return!(d>0)||!(f>0)?null:{segments:{data:u,count:l,hash:$r(u)},marginX:c+t-d,marginY:h+t-f}},ip=(n,e,t,r)=>{let o=null;if(e.dashArray){if(!hi()||e.dashArray.length>2||e.lineCap!=="butt"&&e.lineCap!=="square"||e.uniform)return null;let E=e.dashArray[0],M=e.dashArray.length>1?e.dashArray[1]:E;E+M>0&&(o=[E,E+M,e.dashOffset])}if(e.alignment!=="center")return null;let i=n.raw,s=se(i),a=n.dims;if(s!==L.LINE&&(!(a.x>0)||!(a.y>0)))return null;let l=s===L.LINE?bS:s===L.ELLIPSE||s===L.CIRCLE?gS:s===L.POLYGON||s===L.POLYLINE||s===L.TRIANGLE?op:pS,u=e.width/2,c,h=null,d=u,f=u,m=0;if(s===L.RECT||s===L.FABRICRECT){let E=it(i,a.x,a.y),M=E?.rx??0,k=E?.ry??0;if(M<1e-4&&k<1e-4&&(e.lineJoin!=="miter"||e.miterLimit<yS)||o&&Math.abs(M-k)>=1e-4)return null;c=[M,k,a.x/2,a.y/2]}else if(s===L.LINE){let E=Number(i.x1),M=Number(i.y1),k=Number(i.x2),A=Number(i.y2);if(!Number.isFinite(E)||!Number.isFinite(M)||!Number.isFinite(k)||!Number.isFinite(A)||E===k&&M===A)return null;c=[E,M,k,A]}else if(s===L.ELLIPSE||s===L.CIRCLE){if(o)return null;c=[0,0,a.x/2,a.y/2]}else if(s===L.POLYGON||s===L.POLYLINE||s===L.TRIANGLE){if(!ku()||o||e.uniform)return null;let E=s!==L.POLYLINE,M;if(s===L.TRIANGLE){let I=a.x,G=a.y;if(!(I>0)||!(G>0))return null;M=[{x:0,y:-G/2},{x:I/2,y:G/2},{x:-I/2,y:G/2}]}else{let I=Array.isArray(i.points)?i.points:[];if(I.length<(E?3:2))return null;M=[];for(let G of I){let $=Number(G?.x),V=Number(G?.y);if(!Number.isFinite($)||!Number.isFinite(V))return null;M.push({x:$,y:V})}}let k=1/0,A=1/0,O=-1/0,F=-1/0;for(let I of M)k>I.x&&(k=I.x),A>I.y&&(A=I.y),O<I.x&&(O=I.x),F<I.y&&(F=I.y);let W=(k+O)/2,z=(A+F)/2,_=M.map(I=>({x:I.x-W,y:I.y-z})),D=0;if(e.lineJoin==="round"){if(!E&&e.lineCap!=="round")return null;let I=SS(_,E,u);if(!I)return null;h=I.segments,d=I.marginX,f=I.marginY}else if(e.lineJoin==="miter"){if(!E&&e.lineCap!=="butt")return null;let I=rp(_,E,u,e.miterLimit);if(!I)return null;h=I.segments,d=I.marginX,f=I.marginY,D=1}else return null;c=[0,0,0,0],m=D}else return null;let p=l===op?m:xS[e.lineCap]??0,b=l+(p<<3)+(e.uniform?64:0),g=n.matrix,x=Math.max(1e-6,t*r),S=Math.hypot(g[0],g[1]),w=Math.hypot(g[2],g[3]),y=Math.max(Math.min(S,w),1e-6),v=1/(y*x),R=(e.uniform?u/y:d)+4*v,P=(e.uniform?u/y:f)+4*v,T=a.x+2*R,C=a.y+2*P;return!Number.isFinite(T)||!Number.isFinite(C)?null:{halfW:u,code:-b,shape:c,quadW:T,quadH:C,dash:o,segments:h}};var vS=2,wS=4,ya={butt:0,round:1,square:2},TS=(n,e,t)=>{let r=Math.max(1e-6,e*t),o=Math.hypot(n[0],n[1]),i=Math.hypot(n[2],n[3]),s=Math.max(Math.min(o,i),1e-6);return{aa:1/(s*r),minAxis:s}},sp=n=>{if(!n.dashArray)return{dash:null,ok:!0};if(!hi())return{dash:null,ok:!1};if(n.dashArray.length>2)return{dash:null,ok:!1};if(n.lineCap!=="butt"&&n.lineCap!=="square")return{dash:null,ok:!1};if(n.uniform)return{dash:null,ok:!1};let e=n.dashArray[0],t=n.dashArray.length>1?n.dashArray[1]:e;return e+t<=0?{dash:null,ok:!0}:{dash:[e,e+t,n.dashOffset],ok:!0}},Sa=(n,e,t,r,o,i,s,a,l,u)=>{let c=(n+t)/2,h=(e+r)/2,d=s?o/u:o,f=Math.abs(t-n)+2*(d+l),m=Math.abs(r-e)+2*(d+l);return{centerX:c,centerY:h,shape:[n-c,e-h,t-c,r-h],halfW:o,code:-(vS+(i<<3)+(s?64:0)),quadW:f,quadH:m,dash:a,segments:null}},ES=(n,e)=>{let t=1/0,r=1/0,o=-1/0,i=-1/0;for(let c of n)t>c.x&&(t=c.x),r>c.y&&(r=c.y),o<c.x&&(o=c.x),i<c.y&&(i=c.y);let s=(t+o)/2,a=(r+i)/2,l=[n[0],n[1],n[2],n[0]],u=new Float32Array(12);for(let c=0;c<3;c++)u[c*4]=l[c].x-s,u[c*4+1]=l[c].y-a,u[c*4+2]=l[c+1].x-s,u[c*4+3]=l[c+1].y-a;return{centerX:s,centerY:a,shape:[0,0,0,0],halfW:0,code:-(wS+8),quadW:o-t+2*e,quadH:i-r+2*e,dash:null,segments:{data:u,count:3,hash:$r(u)}}},CS=n=>{let e=Number(n.x1),t=Number(n.y1),r=Number(n.x2),o=Number(n.y2);return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o)||e===r&&t===o?null:{x1:e,y1:t,x2:r,y2:o}},ap=(n,e,t,r,o)=>{let i=se(n);if(i!==L.ARROW&&i!==L.DIMENSION||!Au())return null;let s=CS(n);if(!s||e.alignment!=="center")return null;let{aa:a,minAxis:l}=TS(t,r,o),u=4*a,c=e.width,h=(s.x2-s.x1)/Math.hypot(s.x2-s.x1,s.y2-s.y1),d=(s.y2-s.y1)/Math.hypot(s.x2-s.x1,s.y2-s.y1);if(i===L.ARROW){let T=Number(n.arrowWidth)||15,C=Number(n.arrowHeight)||22.5,E=n.arrowType==="start"||n.arrowType==="both"?n.arrowType:"end",M=Math.sqrt(c),k=T*M,A=C*M,O=E==="start"||E==="both",F=E==="end"||E==="both",{dash:W,ok:z}=sp(e);if(!z)return null;let _=s.x1+h*(O?A:0),D=s.y1+d*(O?A:0),I=s.x2-h*(F?A:0),G=s.y2-d*(F?A:0),V=[Sa(_,D,I,G,c/2,ya[e.lineCap]??0,e.uniform,W,u,l)],H=(Y,X,Z,B)=>{let q=Y-Z*A,U=X-B*A;return ES([{x:Y,y:X},{x:q+-B*(k/2),y:U+Z*(k/2)},{x:q- -B*(k/2),y:U-Z*(k/2)}],u)};return F&&V.push(H(s.x2,s.y2,h,d)),O&&V.push(H(s.x1,s.y1,-h,-d)),{pieces:V,text:null}}let{dash:f,ok:m}=sp(e);if(!m)return null;let p=Sa(s.x1,s.y1,s.x2,s.y2,c/2,ya[e.lineCap]??0,e.uniform,f,u,l),b=Number(n.textFontSize)||50,g=-d,x=h,S=b/2,w=Sa(s.x1-g*S,s.y1-x*S,s.x1+g*S,s.y1+x*S,c/2,ya.round,!1,null,u,l),y=Sa(s.x2-g*S,s.y2-x*S,s.x2+g*S,s.y2+x*S,c/2,ya.round,!1,null,u,l),v=typeof n.text=="string"&&n.text.trim()?n.text:"50cm",R=Number(n.textPadding)||4,P=b+c/2+5;return{pieces:[p,w,y],text:{text:v,fontPx:b,w:0,h:b+R*2,cx:(s.x1+s.x2)/2+g*P,cy:(s.y1+s.y2)/2+x*P,angle:Math.atan2(s.y2-s.y1,s.x2-s.x1),color:typeof n.textColor=="string"?n.textColor:"#333333",bg:typeof n.textBackgroundColor=="string"?n.textBackgroundColor:"#ffffff",follow:n.textFollowLine!==!1,pad:R}}};var In=class{constructor(e){this.requestRender=e}requestRender;lastInteractionAt=-1/0;settleTimer=null;noteInteraction(){this.lastInteractionAt=performance.now(),this.settleTimer!==null&&clearTimeout(this.settleTimer),this.settleTimer=window.setTimeout(()=>{this.settleTimer=null,this.requestRender()},160)}isSettling(e=performance.now()){return e-this.lastInteractionAt<160||this.settleTimer!==null}dispose(){this.settleTimer!==null&&clearTimeout(this.settleTimer),this.settleTimer=null,this.lastInteractionAt=-1/0}};var lp=n=>n?120:6,cp=(n,e,t)=>{if(n===e)return!0;if(!(t>0))return!1;let r=Number(n),o=Number(e);return!Number.isFinite(r)||!Number.isFinite(o)||o<=0?!1:r/o>=t},va=(n,e,t,r)=>!n.isExporting()&&e.isSettling(r)||r>t.bakeDeadline;var wa=class{host;frame;settle;liveTexes=new Set;strokeBakes=new WeakMap;lineDecoTextBakes=new WeakMap;constructor(e,t,r=new In(()=>e.requestRenderAll())){this.host=e,this.frame=t,this.settle=r}noteVptChange(){this.settle.noteInteraction()}render(e){let t=e.strokeDecl;if(!t)return;let r=ap(e.raw,t,e.matrix,this.host.zoom,this.host.dpr);if(r&&(!r.pieces.some(h=>h.segments)||this.host.batch.canPushSegments())){let h=t.rgba,d=[h[0],h[1],h[2],h[3]*e.renderOpacity];for(let f of r.pieces){let m=f.centerX===0&&f.centerY===0?e.matrix:j(e.matrix,[1,0,0,1,f.centerX,f.centerY]);this.host.batch.pushQuad(m,f.quadW,f.quadH,d,null,f.shape,[f.halfW,f.code],e,f.dash,f.segments)}r.text&&this.renderLineDecoText(e,r.text);return}let o=ip(e,t,this.host.zoom,this.host.dpr);if(o&&(!o.segments||this.host.batch.canPushSegments())){let h=t.rgba;this.host.batch.pushQuad(e.matrix,o.quadW,o.quadH,[h[0],h[1],h[2],h[3]*e.renderOpacity],null,o.shape,[o.halfW,o.code],e,o.dash,o.segments);return}let i=e.raw,s=e.matrix,a=JSON.stringify([i.type,i.path,i.points,i.rx,i.ry,i.radius,e.dims.x,e.dims.y]),l=(this.host.zoom*this.host.dpr).toFixed(4),u=[Qu(t),s.join(","),a].join(";"),c=this.strokeBakes.get(e);if(c&&c.sigBase!==u)this.deleteBakeTex(c.tex),c=void 0;else if(c){let h=this.host.bakeKReuseFloor??0,d=c.k===l&&c.snapped?Ci(s,this.host.zoom,this.host.dpr,this.host.viewportTransform,c.sceneW,c.sceneH):null;if(!cp(c.k,l,h)||d&&(d.lx!==c.lx||d.ly!==c.ly)){if(va(this.host,this.settle,this.frame,performance.now())){this.frame.bakeMore=!0,this.host.batch.pushQuad([1,0,0,1,c.lx+c.w/2,c.ly+c.h/2],c.w,c.h,[1,1,1,e.renderOpacity],c.tex);return}this.deleteBakeTex(c.tex),c=void 0}}if(!c){let h=Ju(e,{zoom:this.host.zoom,dpr:this.host.dpr,vpt:this.host.viewportTransform});if(!h){this.strokeBakes.set(e,void 0);return}let d=Ae(this.host.gl,h.canvas);if(!d)return;this.liveTexes.add(d),c={sigBase:u,k:l,tex:d,w:h.w,h:h.h,lx:h.lx,ly:h.ly,sceneW:h.sceneW,sceneH:h.sceneH,snapped:h.snapped},this.strokeBakes.set(e,c)}this.host.batch.pushQuad([1,0,0,1,c.lx+c.w/2,c.ly+c.h/2],c.w,c.h,[1,1,1,e.renderOpacity],c.tex)}deleteBakeTex(e){this.host.gl.deleteTexture(e),this.liveTexes.delete(e)}renderLineDecoText(e,t){let r=`${t.fontPx}px Arial, sans-serif`,o=no(r,t.text)+t.pad*2;if(!(o>0)||!(t.h>0))return;let i=e.worldScale,s=Ht(this.host.zoom*this.host.dpr*Math.max(i.x,i.y,1e-6)),a=[t.text,t.fontPx,t.color,t.bg,t.follow,t.angle.toFixed(4),t.cx.toFixed(3),t.cy.toFixed(3),s].join(";"),l=this.lineDecoTextBakes.get(e);if(l&&l.sig!==a&&(this.deleteBakeTex(l.tex),l=void 0),!l){let d=document.createElement("canvas");d.width=Math.ceil(o*s),d.height=Math.ceil(t.h*s);let f=d.getContext("2d");if(!f)return;f.setTransform(s,0,0,s,d.width/2,d.height/2),t.bg&&(f.fillStyle=t.bg,f.fillRect(-o/2,-t.h/2,o,t.h)),f.font=r,f.textAlign="center",f.textBaseline="middle",f.fillStyle=t.color,f.fillText(t.text,0,0);let m=Ae(this.host.gl,d);if(!m)return;this.liveTexes.add(m),l={sig:a,tex:m,w:d.width/s,h:d.height/s},this.lineDecoTextBakes.set(e,l)}let u=t.follow?t.angle:0,c=Math.cos(u),h=Math.sin(u);this.host.batch.pushQuad(j(e.matrix,[c,h,-h,c,t.cx,t.cy]),l.w,l.h,[1,1,1,e.renderOpacity],l.tex)}invalidate(){for(let e of this.liveTexes)this.host.gl.deleteTexture(e);this.liveTexes.clear(),this.strokeBakes=new WeakMap,this.lineDecoTextBakes=new WeakMap,this.host.renderEpoch?.bump("stroke-bake-invalidate")}};var MS=new Set([...Un,L.RECT,L.FABRICRECT]),Uc=n=>{let e=n.raw.clipPath;return!e||typeof e!="object"||Array.isArray(e)||!MS.has(se(e))?null:e},Ta=class{enabled=!1;depth=0;silhouettes=new WeakMap;resetFrame(){this.enabled=Ru(),this.depth=0}begin(e,t,r){if(!this.enabled||!t.batchOrder||r.rasterMask)return!1;let o=this.silhouetteOf(e);if(!o||o.inverted&&this.depth>0)return!1;let i=t.gl,s=++this.depth,a=o.inverted;return t.batchOrder.recordState(()=>{i.enable(i.STENCIL_TEST),i.stencilFunc(i.ALWAYS,s,255),i.stencilOp(i.KEEP,i.KEEP,i.REPLACE),i.colorMask(!1,!1,!1,!1)}),t.meshBatch.pushMesh(o.clipWorld,[1,1,1,1],o.verts,o.triangles,null,e),t.meshBatch.flush(),t.batchOrder.recordState(()=>{i.colorMask(!0,!0,!0,!0),i.stencilFunc(a?i.NOTEQUAL:i.EQUAL,s,255),i.stencilOp(i.KEEP,i.KEEP,i.KEEP)}),!0}end(e){let t=--this.depth,r=e.gl;e.batchOrder?.recordState(()=>{t<=0?r.disable(r.STENCIL_TEST):r.stencilFunc(r.EQUAL,t,255)})}silhouetteOf(e){let t=Uc(e);if(!t)return null;let r=this.silhouettes.get(e);if(r&&r.decl===t&&r.hostMatrix===e.matrix)return r;let o=this.buildSilhouette(e,t);return o&&this.silhouettes.set(e,o),o}buildSilhouette(e,t){let r=Ct(t);if(!r)return null;let i=t.absolutePositioned===!0?r.matrix:j(e.matrix,r.matrix),s=t.inverted===!0,a=r instanceof yn||!r.dims.x||!r.dims.y?null:it(r.raw,r.dims.x,r.dims.y),l=r instanceof yn?r.shapeMesh:a?Ou(r.dims.x,r.dims.y,a.rx,a.ry):null;if(l)return{decl:t,hostMatrix:e.matrix,clipWorld:i,inverted:s,verts:l.verts,triangles:l.triangles};if(r.dims.x>0&&r.dims.y>0){let u=r.dims.x/2,c=r.dims.y/2;return{decl:t,hostMatrix:e.matrix,clipWorld:i,inverted:s,verts:new Float32Array([-u,-c,u,-c,u,c,-u,c]),triangles:new Uint32Array([0,1,2,0,2,3])}}return null}};var RS=`#version 300 es
411
+ }`,fS=n=>{let e=n.cropRect?`${n.cropRect.sx},${n.cropRect.sy},${n.cropRect.sw},${n.cropRect.sh}`:"",t=n.isTextType?`${n.raw.renderSrc??""}|${n.raw.text??""}|${n.raw.fontSize??""}`:typeof n.raw.src=="string"?`${n.raw.src}|${e}`:e,r=n instanceof ie?`v${n.contentVersion}`:"";return`${n.raw.type};${t};${r};${Fi(n)}`},mS=(n,e,t,r)=>{let o=n.matrix;return[fS(n),n.dims.x,n.dims.y,pS(e),t,r,o[0].toFixed(4),o[1].toFixed(4),o[2].toFixed(4),o[3].toFixed(4)].join(";")},pS=n=>[n.rgba.join(","),n.blur,n.offsetX,n.offsetY,n.nonScaling?1:0].join("|"),ba=class{constructor(e){this.epoch=e}epoch;silhouettes=new WeakMap;targets=new WeakMap;blurProg=null;finalProg=null;b1=null;b2=null;liveRts=new Set;liveSilTexes=new Set;invalidate(e){for(let t of this.liveRts)e.isTexture(t.tex)&&e.deleteTexture(t.tex),e.isFramebuffer(t.fb)&&e.deleteFramebuffer(t.fb);this.liveRts.clear();for(let t of this.liveSilTexes)e.isTexture(t)&&e.deleteTexture(t);this.liveSilTexes.clear(),this.blurProg=null,this.finalProg=null,this.b1=null,this.b2=null,this.silhouettes=new WeakMap,this.targets=new WeakMap}compile(e,t,r){let o=(l,u)=>{let c=e.createShader(l);return c?(e.shaderSource(c,u),e.compileShader(c),e.getShaderParameter(c,e.COMPILE_STATUS)?c:(console.warn("[GpuShadowBaker] shader:",e.getShaderInfoLog(c)),e.deleteShader(c),null)):null},i=o(e.VERTEX_SHADER,t),s=o(e.FRAGMENT_SHADER,r),a=e.createProgram();return!i||!s||!a?null:(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),e.getProgramParameter(a,e.LINK_STATUS)?a:(console.warn("[GpuShadowBaker] link:",e.getProgramInfoLog(a)),null))}ensurePrograms(e){return this.blurProg&&this.finalProg?!0:(this.blurProg=this.blurProg??this.compile(e,rp,hS),this.finalProg=this.finalProg??this.compile(e,rp,dS),!!(this.blurProg&&this.finalProg))}ensureTarget(e,t,r,o){if(t&&t.w===r&&t.h===o)return t;t&&(e.deleteFramebuffer(t.fb),e.deleteTexture(t.tex),this.liveRts.delete(t));let i=e.createTexture();if(!i)return null;e.bindTexture(e.TEXTURE_2D,i),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r,o,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);let s=e.createFramebuffer();if(!s)return e.deleteTexture(i),null;e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.bindFramebuffer(e.FRAMEBUFFER,null);let a={fb:s,tex:i,w:r,h:o};return this.liveRts.add(a),a}silhouette(e,t,r,o,i){let s=this.silhouettes.get(t);if(s&&s.sig!==r&&(e.deleteTexture(s.tex),this.liveSilTexes.delete(s.tex),this.epoch?.bump("gpu-shadow-silhouette-rebake"),s=void 0),!s){let a=document.createElement("canvas");a.width=o,a.height=i;let l=a.getContext("2d");if(!l)return null;let u=t.matrix;l.setTransform(u[0],u[1],u[2],u[3],o/2,i/2),Di(l,t,"#ffffff");let c=Ae(e,a);if(!c)return null;this.liveSilTexes.add(c),s={sig:r,tex:c,w:o,h:i},this.silhouettes.set(t,s)}return s.tex}fullscreenPass(e,t,r,o){e.bindFramebuffer(e.FRAMEBUFFER,r.fb),e.viewport(0,0,r.w,r.h),e.useProgram(t),o(t),e.disable(e.BLEND),e.bindVertexArray(null),e.drawArrays(e.TRIANGLES,0,3)}render(e,t,r,o,i){if(!this.ensurePrograms(e))return null;let s=e.getParameter(e.FRAMEBUFFER_BINDING),a=Lt(r,t.raw.scaleX??1,t.raw.scaleY??1),l=_i(a)+(t.isTextType?Math.ceil((t.raw.fontSize??40)*.5):0),u=xl(t),c=Math.ceil(u.x+l*2),h=Math.ceil(u.y+l*2);if(!(c>0)||!(h>0)||c>8192||h>8192)return null;let d=mS(t,r,c,h);try{let f=this.targets.get(t);if(f&&f.sig!==d&&(e.deleteFramebuffer(f.rt.fb),e.deleteTexture(f.rt.tex),this.liveRts.delete(f.rt),this.epoch?.bump("gpu-shadow-rebake"),f=void 0),!f){let w=this.ensureTarget(e,null,c,h);if(!w)return null;f={sig:d,rt:w},this.targets.set(t,f)}let m=this.silhouette(e,t,d,c,h);if(!m)return null;this.b1=this.ensureTarget(e,this.b1,c,h),this.b2=this.ensureTarget(e,this.b2,c,h);let p=this.b1,b=this.b2;if(!p||!b)return null;let g=a.blur/2,x=g<.05?1:Math.max(1,Math.min(64,Math.round(Math.sqrt(4*g*g+1)))),S=(w,y,v,R)=>{this.fullscreenPass(e,this.blurProg,y,P=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,w),e.uniform1i(e.getUniformLocation(P,"uSrc"),0),e.uniform2f(e.getUniformLocation(P,"uDir"),v,R),e.uniform1i(e.getUniformLocation(P,"uBoxW"),x)})};return S(m,p,1/c,0),S(p.tex,b,1/c,0),S(b.tex,p,1/c,0),S(p.tex,b,0,1/h),S(b.tex,p,0,1/h),S(p.tex,b,0,1/h),this.fullscreenPass(e,this.finalProg,f.rt,w=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,b.tex),e.uniform1i(e.getUniformLocation(w,"uBlur"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,m),e.uniform1i(e.getUniformLocation(w,"uSil"),1),e.uniform2f(e.getUniformLocation(w,"uOffUv"),-a.offX/c,-a.offY/h),e.uniform4f(e.getUniformLocation(w,"uColor"),r.rgba[0],r.rgba[1],r.rgba[2],r.rgba[3])}),{tex:f.rt.tex,w:c,h}}finally{e.bindFramebuffer(e.FRAMEBUFFER,s),e.viewport(0,0,o,i),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)}}};var ga=class{host;shadowBakes=new WeakMap;liveTexes=new Set;gpuShadowBaker=null;constructor(e){this.host=e}render(e){let t=Th(e.raw.shadow);if(!t)return;let r=e.cropRect?`${e.cropRect.sx},${e.cropRect.sy},${e.cropRect.sw},${e.cropRect.sh}`:"",o=e.isTextType?`${e.raw.renderSrc??""}|${e.raw.text??""}|${e.raw.fontSize??""}`:typeof e.raw.src=="string"?`${e.raw.src}|${r}${Wi(e)}`:r,i=e instanceof ie?`v${e.contentVersion}`:"",s=[Eh(t),e.raw.type,e.matrix.join(","),e.dims.x,e.dims.y,Fi(e),o,i].join(";");if(Ru()){this.gpuShadowBaker||(this.gpuShadowBaker=new ba(this.host.renderEpoch));let u=this.gpuShadowBaker.render(this.host.gl,e,t,this.host.canvasEl.width,this.host.canvasEl.height);u&&this.host.batch.pushQuad([1,0,0,1,e.matrix[4],e.matrix[5]],u.w,u.h,[1,1,1,e.renderOpacity],u.tex);return}let a=this.shadowBakes.get(e);if(a&&a.sig!==s&&(a.tex&&(this.host.gl.deleteTexture(a.tex),this.liveTexes.delete(a.tex)),a=void 0),!a){let u=Ch(e,t);if(!u)return;let c=Ae(this.host.gl,u.canvas,{mipmap:!0});if(!c)return;this.liveTexes.add(c),a={sig:s,tex:c,w:u.w,h:u.h},this.shadowBakes.set(e,a)}if(!a.tex)return;let l=e.matrix;this.host.batch.pushQuad([1,0,0,1,l[4],l[5]],a.w,a.h,[1,1,1,e.renderOpacity],a.tex)}invalidate(){for(let e of this.liveTexes)this.host.gl.deleteTexture(e);this.liveTexes.clear(),this.shadowBakes=new WeakMap,this.host.renderEpoch?.bump("shadow-bake-invalidate"),this.gpuShadowBaker?.invalidate(this.host.gl)}};var op=(n,e,t,r)=>{let o=[];for(let T of n){if(!Number.isFinite(T.x)||!Number.isFinite(T.y))return null;let C=o[o.length-1];C&&C.x===T.x&&C.y===T.y||o.push({x:T.x,y:T.y})}if(e&&o.length>1){let T=o[0],C=o[o.length-1];T.x===C.x&&T.y===C.y&&o.pop()}let i=o.length;if(i<(e?3:2))return null;let s=e?i:i-1,a=[],l=[];for(let T=0;T<s;T++){let C=o[T],E=o[(T+1)%i],M=Math.hypot(E.x-C.x,E.y-C.y);if(!(M>1e-12))return null;a.push((E.x-C.x)/M),l.push((E.y-C.y)/M)}let u=[],c=[],h=[],d=[];for(let T=0;T<i;T++){let C=o[T],E=e||T>0,M=e||T<s;if(!E||!M){let D=E?T-1:0,I=-l[D],G=a[D];u.push(C.x+t*I),c.push(C.y+t*G),h.push(C.x-t*I),d.push(C.y-t*G);continue}let k=a[(T-1+s)%s],A=l[(T-1+s)%s],O=a[T%s],F=l[T%s],W=-(k*O+A*F),z=Math.sqrt(Math.max(0,(1-W)/2));if(1/Math.max(z,1e-300)>r*(1+1e-9))return null;let _=k*F-A*O;for(let D of[1,-1]){let I=o[(T-1+i)%i].x+t*D*-A,G=o[(T-1+i)%i].y+t*D*k,$=C.x+t*D*-F,V=C.y+t*D*O;if(Math.abs(_)<1e-12){let q=C.x+t*D*-F,U=C.y+t*D*O;if(!Number.isFinite(q)||!Number.isFinite(U))return null;D===1?(u.push(q),c.push(U)):(h.push(q),d.push(U));continue}let H=$-I,Y=V-G,X=(H*F-Y*O)/_,Z=I+X*k,B=G+X*A;if(!Number.isFinite(Z)||!Number.isFinite(B))return null;D===1?(u.push(Z),c.push(B)):(h.push(Z),d.push(B))}}for(let T=0;T<s;T++){let C=T+1;if((u[C]-u[T])*a[T]+(c[C]-c[T])*l[T]<=0||(h[C]-h[T])*a[T]+(d[C]-d[T])*l[T]<=0)return null}h.reverse(),d.reverse();let f=2*i;if(f>64||f<3)return null;let m=[],p=[],b=(T,C,E)=>{for(let M=0;M+1<T.length;M++)m.push(T[M],T[M+1]),p.push(C[M],C[M+1]);E&&T.length>2&&(m.push(T[T.length-1],T[0]),p.push(C[C.length-1],C[0]))};b(u,c,e),b(h,d,e),e||(m.push(u[u.length-1],h[0]),p.push(c[c.length-1],d[0]),m.push(h[h.length-1],u[0]),p.push(d[d.length-1],c[0]));let g=m.length/2;if(g!==f||g>64)return null;let x=(T,C,E,M,k,A)=>(E-T)*(A-C)-(M-C)*(k-T),S=(T,C)=>{let E=m[T*2],M=p[T*2],k=m[T*2+1],A=p[T*2+1],O=m[C*2],F=p[C*2],W=m[C*2+1],z=p[C*2+1];if(E===k&&M===A||O===W&&F===z)return!1;let _=x(E,M,k,A,O,F),D=x(E,M,k,A,W,z),I=x(O,F,W,z,E,M),G=x(O,F,W,z,k,A);return(_>0&&D<0||_<0&&D>0)&&(I>0&&G<0||I<0&&G>0)};for(let T=0;T<g;T++)for(let C=T+2;C<g;C++)if(S(T,C))return null;let w=new Float32Array(g*4),y=0,v=0,R=0,P=0;for(let T=0;T<g;T++)w[T*4]=m[T*2],w[T*4+1]=p[T*2],w[T*4+2]=m[T*2+1],w[T*4+3]=p[T*2+1],y=Math.max(y,Math.abs(m[T*2]),Math.abs(m[T*2+1])),v=Math.max(v,Math.abs(p[T*2]),Math.abs(p[T*2+1]));for(let T of o)R=Math.max(R,Math.abs(T.x)),P=Math.max(P,Math.abs(T.y));return!(R>0)||!(P>0)?null:{segments:{data:w,count:g,hash:$r(w)},marginX:y-R,marginY:v-P}};var bS=1,gS=2,xS=3,ip=4,yS={butt:0,round:1,square:2},SS=1.5,vS=(n,e,t)=>{let r=e?n.length:n.length-1;if(r<1)return null;let o=[],i=[],s=[],a=[];for(let m=0;m<r;m++){let p=n[m],b=n[(m+1)%n.length],g=b.x-p.x,x=b.y-p.y;g*g+x*x<1e-18||(o.push(p.x),i.push(p.y),s.push(b.x),a.push(b.y))}let l=o.length;if(l<1||l>64)return null;let u=new Float32Array(l*4),c=0,h=0;for(let m=0;m<l;m++)u[m*4]=o[m],u[m*4+1]=i[m],u[m*4+2]=s[m],u[m*4+3]=a[m],c=Math.max(c,Math.abs(o[m]),Math.abs(s[m])),h=Math.max(h,Math.abs(i[m]),Math.abs(a[m]));let d=0,f=0;for(let m of n)d=Math.max(d,Math.abs(m.x)),f=Math.max(f,Math.abs(m.y));return!(d>0)||!(f>0)?null:{segments:{data:u,count:l,hash:$r(u)},marginX:c+t-d,marginY:h+t-f}},sp=(n,e,t,r)=>{let o=null;if(e.dashArray){if(!hi()||e.dashArray.length>2||e.lineCap!=="butt"&&e.lineCap!=="square"||e.uniform)return null;let E=e.dashArray[0],M=e.dashArray.length>1?e.dashArray[1]:E;E+M>0&&(o=[E,E+M,e.dashOffset])}if(e.alignment!=="center")return null;let i=n.raw,s=se(i),a=n.dims;if(s!==L.LINE&&(!(a.x>0)||!(a.y>0)))return null;let l=s===L.LINE?gS:s===L.ELLIPSE||s===L.CIRCLE?xS:s===L.POLYGON||s===L.POLYLINE||s===L.TRIANGLE?ip:bS,u=e.width/2,c,h=null,d=u,f=u,m=0;if(s===L.RECT||s===L.FABRICRECT){let E=it(i,a.x,a.y),M=E?.rx??0,k=E?.ry??0;if(M<1e-4&&k<1e-4&&(e.lineJoin!=="miter"||e.miterLimit<SS)||o&&Math.abs(M-k)>=1e-4)return null;c=[M,k,a.x/2,a.y/2]}else if(s===L.LINE){let E=Number(i.x1),M=Number(i.y1),k=Number(i.x2),A=Number(i.y2);if(!Number.isFinite(E)||!Number.isFinite(M)||!Number.isFinite(k)||!Number.isFinite(A)||E===k&&M===A)return null;c=[E,M,k,A]}else if(s===L.ELLIPSE||s===L.CIRCLE){if(o)return null;c=[0,0,a.x/2,a.y/2]}else if(s===L.POLYGON||s===L.POLYLINE||s===L.TRIANGLE){if(!Au()||o||e.uniform)return null;let E=s!==L.POLYLINE,M;if(s===L.TRIANGLE){let I=a.x,G=a.y;if(!(I>0)||!(G>0))return null;M=[{x:0,y:-G/2},{x:I/2,y:G/2},{x:-I/2,y:G/2}]}else{let I=Array.isArray(i.points)?i.points:[];if(I.length<(E?3:2))return null;M=[];for(let G of I){let $=Number(G?.x),V=Number(G?.y);if(!Number.isFinite($)||!Number.isFinite(V))return null;M.push({x:$,y:V})}}let k=1/0,A=1/0,O=-1/0,F=-1/0;for(let I of M)k>I.x&&(k=I.x),A>I.y&&(A=I.y),O<I.x&&(O=I.x),F<I.y&&(F=I.y);let W=(k+O)/2,z=(A+F)/2,_=M.map(I=>({x:I.x-W,y:I.y-z})),D=0;if(e.lineJoin==="round"){if(!E&&e.lineCap!=="round")return null;let I=vS(_,E,u);if(!I)return null;h=I.segments,d=I.marginX,f=I.marginY}else if(e.lineJoin==="miter"){if(!E&&e.lineCap!=="butt")return null;let I=op(_,E,u,e.miterLimit);if(!I)return null;h=I.segments,d=I.marginX,f=I.marginY,D=1}else return null;c=[0,0,0,0],m=D}else return null;let p=l===ip?m:yS[e.lineCap]??0,b=l+(p<<3)+(e.uniform?64:0),g=n.matrix,x=Math.max(1e-6,t*r),S=Math.hypot(g[0],g[1]),w=Math.hypot(g[2],g[3]),y=Math.max(Math.min(S,w),1e-6),v=1/(y*x),R=(e.uniform?u/y:d)+4*v,P=(e.uniform?u/y:f)+4*v,T=a.x+2*R,C=a.y+2*P;return!Number.isFinite(T)||!Number.isFinite(C)?null:{halfW:u,code:-b,shape:c,quadW:T,quadH:C,dash:o,segments:h}};var wS=2,TS=4,ya={butt:0,round:1,square:2},ES=(n,e,t)=>{let r=Math.max(1e-6,e*t),o=Math.hypot(n[0],n[1]),i=Math.hypot(n[2],n[3]),s=Math.max(Math.min(o,i),1e-6);return{aa:1/(s*r),minAxis:s}},ap=n=>{if(!n.dashArray)return{dash:null,ok:!0};if(!hi())return{dash:null,ok:!1};if(n.dashArray.length>2)return{dash:null,ok:!1};if(n.lineCap!=="butt"&&n.lineCap!=="square")return{dash:null,ok:!1};if(n.uniform)return{dash:null,ok:!1};let e=n.dashArray[0],t=n.dashArray.length>1?n.dashArray[1]:e;return e+t<=0?{dash:null,ok:!0}:{dash:[e,e+t,n.dashOffset],ok:!0}},Sa=(n,e,t,r,o,i,s,a,l,u)=>{let c=(n+t)/2,h=(e+r)/2,d=s?o/u:o,f=Math.abs(t-n)+2*(d+l),m=Math.abs(r-e)+2*(d+l);return{centerX:c,centerY:h,shape:[n-c,e-h,t-c,r-h],halfW:o,code:-(wS+(i<<3)+(s?64:0)),quadW:f,quadH:m,dash:a,segments:null}},CS=(n,e)=>{let t=1/0,r=1/0,o=-1/0,i=-1/0;for(let c of n)t>c.x&&(t=c.x),r>c.y&&(r=c.y),o<c.x&&(o=c.x),i<c.y&&(i=c.y);let s=(t+o)/2,a=(r+i)/2,l=[n[0],n[1],n[2],n[0]],u=new Float32Array(12);for(let c=0;c<3;c++)u[c*4]=l[c].x-s,u[c*4+1]=l[c].y-a,u[c*4+2]=l[c+1].x-s,u[c*4+3]=l[c+1].y-a;return{centerX:s,centerY:a,shape:[0,0,0,0],halfW:0,code:-(TS+8),quadW:o-t+2*e,quadH:i-r+2*e,dash:null,segments:{data:u,count:3,hash:$r(u)}}},MS=n=>{let e=Number(n.x1),t=Number(n.y1),r=Number(n.x2),o=Number(n.y2);return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o)||e===r&&t===o?null:{x1:e,y1:t,x2:r,y2:o}},lp=(n,e,t,r,o)=>{let i=se(n);if(i!==L.ARROW&&i!==L.DIMENSION||!Nu())return null;let s=MS(n);if(!s||e.alignment!=="center")return null;let{aa:a,minAxis:l}=ES(t,r,o),u=4*a,c=e.width,h=(s.x2-s.x1)/Math.hypot(s.x2-s.x1,s.y2-s.y1),d=(s.y2-s.y1)/Math.hypot(s.x2-s.x1,s.y2-s.y1);if(i===L.ARROW){let T=Number(n.arrowWidth)||15,C=Number(n.arrowHeight)||22.5,E=n.arrowType==="start"||n.arrowType==="both"?n.arrowType:"end",M=Math.sqrt(c),k=T*M,A=C*M,O=E==="start"||E==="both",F=E==="end"||E==="both",{dash:W,ok:z}=ap(e);if(!z)return null;let _=s.x1+h*(O?A:0),D=s.y1+d*(O?A:0),I=s.x2-h*(F?A:0),G=s.y2-d*(F?A:0),V=[Sa(_,D,I,G,c/2,ya[e.lineCap]??0,e.uniform,W,u,l)],H=(Y,X,Z,B)=>{let q=Y-Z*A,U=X-B*A;return CS([{x:Y,y:X},{x:q+-B*(k/2),y:U+Z*(k/2)},{x:q- -B*(k/2),y:U-Z*(k/2)}],u)};return F&&V.push(H(s.x2,s.y2,h,d)),O&&V.push(H(s.x1,s.y1,-h,-d)),{pieces:V,text:null}}let{dash:f,ok:m}=ap(e);if(!m)return null;let p=Sa(s.x1,s.y1,s.x2,s.y2,c/2,ya[e.lineCap]??0,e.uniform,f,u,l),b=Number(n.textFontSize)||50,g=-d,x=h,S=b/2,w=Sa(s.x1-g*S,s.y1-x*S,s.x1+g*S,s.y1+x*S,c/2,ya.round,!1,null,u,l),y=Sa(s.x2-g*S,s.y2-x*S,s.x2+g*S,s.y2+x*S,c/2,ya.round,!1,null,u,l),v=typeof n.text=="string"&&n.text.trim()?n.text:"50cm",R=Number(n.textPadding)||4,P=b+c/2+5;return{pieces:[p,w,y],text:{text:v,fontPx:b,w:0,h:b+R*2,cx:(s.x1+s.x2)/2+g*P,cy:(s.y1+s.y2)/2+x*P,angle:Math.atan2(s.y2-s.y1,s.x2-s.x1),color:typeof n.textColor=="string"?n.textColor:"#333333",bg:typeof n.textBackgroundColor=="string"?n.textBackgroundColor:"#ffffff",follow:n.textFollowLine!==!1,pad:R}}};var In=class{constructor(e){this.requestRender=e}requestRender;lastInteractionAt=-1/0;settleTimer=null;noteInteraction(){this.lastInteractionAt=performance.now(),this.settleTimer!==null&&clearTimeout(this.settleTimer),this.settleTimer=window.setTimeout(()=>{this.settleTimer=null,this.requestRender()},160)}isSettling(e=performance.now()){return e-this.lastInteractionAt<160||this.settleTimer!==null}dispose(){this.settleTimer!==null&&clearTimeout(this.settleTimer),this.settleTimer=null,this.lastInteractionAt=-1/0}};var cp=n=>n?120:6,up=(n,e,t)=>{if(n===e)return!0;if(!(t>0))return!1;let r=Number(n),o=Number(e);return!Number.isFinite(r)||!Number.isFinite(o)||o<=0?!1:r/o>=t},va=(n,e,t,r)=>!n.isExporting()&&e.isSettling(r)||r>t.bakeDeadline;var wa=class{host;frame;settle;liveTexes=new Set;strokeBakes=new WeakMap;lineDecoTextBakes=new WeakMap;constructor(e,t,r=new In(()=>e.requestRenderAll())){this.host=e,this.frame=t,this.settle=r}noteVptChange(){this.settle.noteInteraction()}render(e){let t=e.strokeDecl;if(!t)return;let r=lp(e.raw,t,e.matrix,this.host.zoom,this.host.dpr);if(r&&(!r.pieces.some(h=>h.segments)||this.host.batch.canPushSegments())){let h=t.rgba,d=[h[0],h[1],h[2],h[3]*e.renderOpacity];for(let f of r.pieces){let m=f.centerX===0&&f.centerY===0?e.matrix:j(e.matrix,[1,0,0,1,f.centerX,f.centerY]);this.host.batch.pushQuad(m,f.quadW,f.quadH,d,null,f.shape,[f.halfW,f.code],e,f.dash,f.segments)}r.text&&this.renderLineDecoText(e,r.text);return}let o=sp(e,t,this.host.zoom,this.host.dpr);if(o&&(!o.segments||this.host.batch.canPushSegments())){let h=t.rgba;this.host.batch.pushQuad(e.matrix,o.quadW,o.quadH,[h[0],h[1],h[2],h[3]*e.renderOpacity],null,o.shape,[o.halfW,o.code],e,o.dash,o.segments);return}let i=e.raw,s=e.matrix,a=JSON.stringify([i.type,i.path,i.points,i.rx,i.ry,i.radius,e.dims.x,e.dims.y]),l=(this.host.zoom*this.host.dpr).toFixed(4),u=[Zu(t),s.join(","),a].join(";"),c=this.strokeBakes.get(e);if(c&&c.sigBase!==u)this.deleteBakeTex(c.tex),c=void 0;else if(c){let h=this.host.bakeKReuseFloor??0,d=c.k===l&&c.snapped?Ci(s,this.host.zoom,this.host.dpr,this.host.viewportTransform,c.sceneW,c.sceneH):null;if(!up(c.k,l,h)||d&&(d.lx!==c.lx||d.ly!==c.ly)){if(va(this.host,this.settle,this.frame,performance.now())){this.frame.bakeMore=!0,this.host.batch.pushQuad([1,0,0,1,c.lx+c.w/2,c.ly+c.h/2],c.w,c.h,[1,1,1,e.renderOpacity],c.tex);return}this.deleteBakeTex(c.tex),c=void 0}}if(!c){let h=eh(e,{zoom:this.host.zoom,dpr:this.host.dpr,vpt:this.host.viewportTransform});if(!h){this.strokeBakes.set(e,void 0);return}let d=Ae(this.host.gl,h.canvas);if(!d)return;this.liveTexes.add(d),c={sigBase:u,k:l,tex:d,w:h.w,h:h.h,lx:h.lx,ly:h.ly,sceneW:h.sceneW,sceneH:h.sceneH,snapped:h.snapped},this.strokeBakes.set(e,c)}this.host.batch.pushQuad([1,0,0,1,c.lx+c.w/2,c.ly+c.h/2],c.w,c.h,[1,1,1,e.renderOpacity],c.tex)}deleteBakeTex(e){this.host.gl.deleteTexture(e),this.liveTexes.delete(e)}renderLineDecoText(e,t){let r=`${t.fontPx}px Arial, sans-serif`,o=no(r,t.text)+t.pad*2;if(!(o>0)||!(t.h>0))return;let i=e.worldScale,s=Ht(this.host.zoom*this.host.dpr*Math.max(i.x,i.y,1e-6)),a=[t.text,t.fontPx,t.color,t.bg,t.follow,t.angle.toFixed(4),t.cx.toFixed(3),t.cy.toFixed(3),s].join(";"),l=this.lineDecoTextBakes.get(e);if(l&&l.sig!==a&&(this.deleteBakeTex(l.tex),l=void 0),!l){let d=document.createElement("canvas");d.width=Math.ceil(o*s),d.height=Math.ceil(t.h*s);let f=d.getContext("2d");if(!f)return;f.setTransform(s,0,0,s,d.width/2,d.height/2),t.bg&&(f.fillStyle=t.bg,f.fillRect(-o/2,-t.h/2,o,t.h)),f.font=r,f.textAlign="center",f.textBaseline="middle",f.fillStyle=t.color,f.fillText(t.text,0,0);let m=Ae(this.host.gl,d);if(!m)return;this.liveTexes.add(m),l={sig:a,tex:m,w:d.width/s,h:d.height/s},this.lineDecoTextBakes.set(e,l)}let u=t.follow?t.angle:0,c=Math.cos(u),h=Math.sin(u);this.host.batch.pushQuad(j(e.matrix,[c,h,-h,c,t.cx,t.cy]),l.w,l.h,[1,1,1,e.renderOpacity],l.tex)}invalidate(){for(let e of this.liveTexes)this.host.gl.deleteTexture(e);this.liveTexes.clear(),this.strokeBakes=new WeakMap,this.lineDecoTextBakes=new WeakMap,this.host.renderEpoch?.bump("stroke-bake-invalidate")}};var RS=new Set([...Un,L.RECT,L.FABRICRECT]),$c=n=>{let e=n.raw.clipPath;return!e||typeof e!="object"||Array.isArray(e)||!RS.has(se(e))?null:e},Ta=class{enabled=!1;depth=0;silhouettes=new WeakMap;resetFrame(){this.enabled=Pu(),this.depth=0}begin(e,t,r){if(!this.enabled||!t.batchOrder||r.rasterMask)return!1;let o=this.silhouetteOf(e);if(!o||o.inverted&&this.depth>0)return!1;let i=t.gl,s=++this.depth,a=o.inverted;return t.batchOrder.recordState(()=>{i.enable(i.STENCIL_TEST),i.stencilFunc(i.ALWAYS,s,255),i.stencilOp(i.KEEP,i.KEEP,i.REPLACE),i.colorMask(!1,!1,!1,!1)}),t.meshBatch.pushMesh(o.clipWorld,[1,1,1,1],o.verts,o.triangles,null,e),t.meshBatch.flush(),t.batchOrder.recordState(()=>{i.colorMask(!0,!0,!0,!0),i.stencilFunc(a?i.NOTEQUAL:i.EQUAL,s,255),i.stencilOp(i.KEEP,i.KEEP,i.KEEP)}),!0}end(e){let t=--this.depth,r=e.gl;e.batchOrder?.recordState(()=>{t<=0?r.disable(r.STENCIL_TEST):r.stencilFunc(r.EQUAL,t,255)})}silhouetteOf(e){let t=$c(e);if(!t)return null;let r=this.silhouettes.get(e);if(r&&r.decl===t&&r.hostMatrix===e.matrix)return r;let o=this.buildSilhouette(e,t);return o&&this.silhouettes.set(e,o),o}buildSilhouette(e,t){let r=Ct(t);if(!r)return null;let i=t.absolutePositioned===!0?r.matrix:j(e.matrix,r.matrix),s=t.inverted===!0,a=r instanceof yn||!r.dims.x||!r.dims.y?null:it(r.raw,r.dims.x,r.dims.y),l=r instanceof yn?r.shapeMesh:a?Bu(r.dims.x,r.dims.y,a.rx,a.ry):null;if(l)return{decl:t,hostMatrix:e.matrix,clipWorld:i,inverted:s,verts:l.verts,triangles:l.triangles};if(r.dims.x>0&&r.dims.y>0){let u=r.dims.x/2,c=r.dims.y/2;return{decl:t,hostMatrix:e.matrix,clipWorld:i,inverted:s,verts:new Float32Array([-u,-c,u,-c,u,c,-u,c]),triangles:new Uint32Array([0,1,2,0,2,3])}}return null}};var PS=`#version 300 es
412
412
  out vec2 vUv;
413
413
  void main() {
414
414
  vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
415
415
  vUv = p;
416
416
  gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
417
- }`,PS=`#version 300 es
417
+ }`,kS=`#version 300 es
418
418
  precision mediump float;
419
419
  in vec2 vUv;
420
420
  uniform sampler2D uClipTex;
@@ -446,13 +446,13 @@ corner = 1.0 - smoothstep(-1.0, 0.0, dist);
446
446
  float maskA = inClip ? texture(uMaskTex, vUv).a : 0.0;
447
447
  float a = c.a * maskA * corner;
448
448
  outColor = vec4(c.rgb, a);
449
- }`,Zo=4096,kS=(n,e,t,r,o)=>{let i=Math.min(4,Math.max(1,r*t*o)),s=n*i,a=e*i;if(s>0&&a>0){let l=Math.min(1,Zo/Math.max(s,a)),u=Math.min(1,Math.sqrt(Zo*Zo/(s*a)));return i*Math.min(l,u)}return i},AS=(n,e,t)=>{let r=n.raw,o=n.clipImageRaw,i=Number(r.width)||0,s=Number(r.height)||0,a=o?.scaleX??1,l=o?.scaleY??1,u=o?.flipX?-1:1,c=o?.flipY?-1:1,h=(o?.angle??0)*Math.PI/180,d=r.clipX??0,f=r.clipY??0,m=Math.cos(h),p=Math.sin(h),b=[1,0,0,1,i/2,s/2],g=[m,p,-p,m,0,0],x=[a*u,0,0,l*c,0,0],S=[1,0,0,1,d/(a||1),f/(l||1)],w=[1,0,0,1,-e/2,-t/2];return ve(j(j(j(j(b,g),x),S),w))},Ea=class{prog=null;targets=new WeakMap;activeThisFrame=!1;ensureProgram(e){if(this.prog)return!0;let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[MaskCompositeGpu] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,RS),o=t(e.FRAGMENT_SHADER,PS),i=e.createProgram();return!r||!o||!i?!1:(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),e.getProgramParameter(i,e.LINK_STATUS)?(this.prog=i,!0):(console.warn("[MaskCompositeGpu] link:",e.getProgramInfoLog(i)),!1))}ensureTarget(e,t,r,o){let i=this.targets.get(t);if(i&&i.wPx===r&&i.hPx===o)return i;i&&(e.deleteFramebuffer(i.fb),e.deleteTexture(i.tex));let s=e.createTexture(),a=e.createFramebuffer();if(!s||!a)return null;e.bindTexture(e.TEXTURE_2D,s),e.texImage2D(e.TEXTURE_2D,0,e.RGBA8,r,o,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0),e.bindFramebuffer(e.FRAMEBUFFER,null);let l={fb:a,tex:s,wPx:r,hPx:o};return this.targets.set(t,l),l}render(e,t,r,o,i){let s=e.raw,a=e.clipImageRaw;if(!a)return null;let l=Number(s.width)||0,u=Number(s.height)||0;if(l<=0||u<=0||i.clipW<=0||i.clipH<=0||!this.ensureProgram(t))return null;let c=Math.max(Math.abs(a.scaleX??1),Math.abs(a.scaleY??1)),h=kS(l,u,r,o,c),d=64,f=Math.min(Zo,Math.max(d,Math.ceil(l*h/d)*d)),m=Math.min(Zo,Math.max(d,Math.ceil(u*h/d)*d)),p=t.getParameter(t.FRAMEBUFFER_BINDING),b=t.getParameter(t.VIEWPORT),g=t.getParameter(t.BLEND),x=t.getParameter(t.CURRENT_PROGRAM),S=t.getParameter(t.TEXTURE_BINDING_2D),w=this.ensureTarget(t,e,f,m);if(!w)return null;t.bindFramebuffer(t.FRAMEBUFFER,w.fb),t.viewport(0,0,f,m),t.disable(t.BLEND),t.useProgram(this.prog);let y=AS(e,i.clipW,i.clipH);t.uniformMatrix3fv(t.getUniformLocation(this.prog,"uClip"),!1,new Float32Array([y[0],y[1],0,y[2],y[3],0,y[4],y[5],1])),t.uniform1i(t.getUniformLocation(this.prog,"uClipTex"),0),t.uniform1i(t.getUniformLocation(this.prog,"uMaskTex"),1),t.uniform2f(t.getUniformLocation(this.prog,"uClipSize"),i.clipW,i.clipH),t.uniform2f(t.getUniformLocation(this.prog,"uSize"),l,u),t.uniform2f(t.getUniformLocation(this.prog,"uPxSize"),f,m);let v=Math.max(0,Math.min(s.cornerRadius||0,Math.min(l,u)/2));return t.uniform1f(t.getUniformLocation(this.prog,"uRadiusPx"),v*h),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,i.clipTex),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,i.maskTex),t.drawArrays(t.TRIANGLES,0,3),t.bindFramebuffer(t.FRAMEBUFFER,p),t.viewport(b[0],b[1],b[2],b[3]),g&&t.enable(t.BLEND),t.useProgram(x),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,S),this.activeThisFrame=!0,{tex:w.tex,w:l,h:u}}invalidate(){this.targets=new WeakMap,this.prog=null}};var _n=(n,e,t,r,o=0,i=0)=>{let s=e.raw,a=o||i?j(e.matrix,[1,0,0,1,o,i]):e.matrix;if(!n||s.angle||(s.scaleX??1)!==1||(s.scaleY??1)!==1)return{matrix:a,w:t,h:r,uv:[0,0,1,1]};let l=(s.left??0)+o,u=(s.top??0)+i,c=Math.max(l-t/2,-n.hw),h=Math.min(l+t/2,n.hw),d=Math.max(u-r/2,-n.hh),f=Math.min(u+r/2,n.hh);if(!(h-c>0)||!(f-d>0))return null;let m=[(c-(l-t/2))/t,(d-(u-r/2))/r,(h-(l-t/2))/t,(f-(u-r/2))/r],p=(c+h)/2-l,b=(d+f)/2-u,g=a;return{matrix:[g[0],g[1],g[2],g[3],g[0]*p+g[2]*b+g[4],g[1]*p+g[3]*b+g[5]],w:h-c,h:f-d,uv:m}};var up=new WeakMap,NS=n=>{let e=up.get(n);return e||(e=Object.create(n),Object.defineProperty(e,"matrix",{get:()=>{let t=n.bitmapRect,r=n.matrix;return(t.x!==0||t.y!==0)&&(r=j(r,[1,0,0,1,t.x,t.y])),t.angle&&(r=j(r,At({angle:-t.angle}))),r}}),up.set(n,e)),e},Ca=class{host;frame;gpu;getPuzzleBox;psdBakes=new WeakMap;settle;blendComposite;cpuTexes=new Set;patterns;constructor(e,t,r,o,i=new In(()=>e.requestRenderAll()),s=()=>{},a=null){this.host=e,this.frame=t,this.gpu=r,this.getPuzzleBox=o,this.settle=i,this.patterns=a,this.blendComposite=s}noteVptScaleChange(){this.settle.noteInteraction()}render(e,t){let r=e.isTextType&&e instanceof ye,o=r&&Kt(e)&&e!==this.host.editingNode&&!!e.imageEl,i=e instanceof ae;if(!e.isImageType&&e.typeKey!==L.PATH&&!r&&!i||t==="above"&&!e.isImageType&&!r&&!i&&e.typeKey!==L.PATH||e.isImageType&&!(e instanceof ie)&&!e.imageEl)return;let s=Mt(e.raw.effects,r?{text:!0}:{});if(!s)return;let a=e.cropRect?`${e.cropRect.sx},${e.cropRect.sy},${e.cropRect.sw},${e.cropRect.sh}`:"",l=o?`bmp:${e.raw.renderSrc}`:r?JSON.stringify([e.raw.text,e.raw.styles,e.raw.fontFamily,e.raw.fontSize,e.raw.fontWeight,e.raw.fontStyle,e.raw.lineHeight,e.raw.charSpacing,e.raw.textAlign,e.raw.paragraph??null,e.raw.width,e.raw.height]):typeof e.raw.src=="string"?`${e.raw.src}|${a}${Wi(e)}${Nh(e)}`:a,u=e instanceof ie?`v${e.contentVersion}`:"",c=r&&!o?Math.max(1,Ht(this.host.zoom*this.host.dpr*Math.max(e.worldScale.x,e.worldScale.y))):1,h=o?NS(e):e,d=_r(s);if(d.length>0&&this.patterns&&!this.patterns.patternSourcesReady(d)){let y=this.psdBakes.get(e);y&&this.renderPsdBakeQuads(h,y,t,!0);return}let f=h.matrix,m=[wn(s),`${f[0]},${f[1]},${f[2]},${f[3]}`,`${h.dims.x},${h.dims.y}`,l,u],p=m.join(";"),b=this.host.document?.transformGestureAt??-1/0,x=!this.host.isExporting()&&performance.now()-b<160||va(this.host,this.settle,this.frame,performance.now()),S=this.psdBakes.get(e),w=y=>{for(let v of y.shadows)this.deleteBakeTex(v.tex);for(let v of y.innerShadows)this.deleteBakeTex(v.tex);for(let v of y.fills)this.deleteBakeTex(v.tex);for(let v of y.strokes)this.deleteBakeTex(v.tex);y.bevelShadow&&this.deleteBakeTex(y.bevelShadow.tex),y.bevelHighlight&&this.deleteBakeTex(y.bevelHighlight.tex)};if(S&&S.sigBase!==p){if(m[0]===S.sigParts[0]&&m[3]===S.sigParts[3]&&m[4]===S.sigParts[4]&&x){this.frame.bakeMore=!0,this.renderPsdBakeQuads(h,S,t,!0);return}w(S),S=void 0}if(S&&S.bucket!==c){if(x){this.frame.bakeMore=!0,this.renderPsdBakeQuads(h,S,t);return}w(S),S=void 0}if(!S){let y=this.host.gl,v=e instanceof ae?e.imageEl:e instanceof ie?e.paintSource:e.isImageType||o?e.imageEl:null,R=v?1:c,P=v&&!o?1:Math.min(Math.max(2,c),Bi(e)),T=v??(r?mo(e,R):null),C=v??(r?mo(e,P):null),E=!T&&!i&&e.typeKey===L.PATH&&(s.solidFills.length>0||s.innerShadows.length>0||s.bevel)?Dh(h):null,M=T??E,k=v?1:R,A=v?e.cropRect:null,O=ja()||Va()?this.gpu.fx:null,F=!T&&!i,W=[];for(let H of s.dropShadows){let Y=W[W.length-1];Y&&Y.mode===H.blendMode?Y.group.push(H):W.push({mode:H.blendMode,group:[H]})}let z=[],_=W.length===1&&!W[0].mode;for(let H of W){if(ja()&&O&&_){let X=O.bakeDropShadows(y,h,H.group,{source:T,sourceRect:A,rs:R,pathMode:F,sig:p,viewportW:this.host.canvasEl.width,viewportH:this.host.canvasEl.height});if(X){z.push({tex:X.tex,w:X.w/R,h:X.h/R,mode:void 0});continue}}let Y=T?Hi(h,H.group,T,R,A):_h(e,H.group);if(Y){let X=Ae(y,Y.canvas,{mipmap:!0});X&&(this.cpuTexes.add(X),z.push({tex:X,w:Y.quadW,h:Y.quadH,mode:H.mode}))}}let D=[];if(M)for(let H of s.innerShadows){let Y=wr(h,H,M,k,A);if(!Y)continue;let X=Ae(y,Y);X&&(this.cpuTexes.add(X),D.push({tex:X,mode:H.blendMode}))}let I,G;if(s.bevel&&(C||E)){let H=Fh(h,s.bevel,C??E,P,A);if(H){let Y=Ae(y,H.shadow),X=Ae(y,H.highlight);Y&&(this.cpuTexes.add(Y),I={tex:Y,w:H.quadW,h:H.quadH,mode:s.bevel.shadow.blendMode}),X&&(this.cpuTexes.add(X),G={tex:X,w:H.quadW,h:H.quadH,mode:s.bevel.highlight.blendMode})}}let $=[];if(M)for(let H of s.solidFills){if(Va()&&O&&H.kind==="solid"&&!A&&!H.blendMode&&!It(h)){let Z=Math.max(1,Math.ceil(h.dims.x*R)),B=Math.max(1,Math.ceil(h.dims.y*R)),q=O.uploadLocalSource(y,h,M,`${p}|fillsrc`,Z,B),U=q?O.bakeSolidFill(y,h,H,q,Z,B,p,`fill${$.length}`,this.host.canvasEl.width,this.host.canvasEl.height):null;if(U){$.push({tex:U,dx:H.offset.x,dy:H.offset.y,mode:void 0});continue}}let Y=vr(h,H,M,k,A);if(!Y)continue;let X=Ae(y,Y);X&&(this.cpuTexes.add(X),$.push({tex:X,dx:H.offset.x,dy:H.offset.y,mode:H.blendMode}))}let V=[];if(C){let H=bn(h,s.strokes,C,!r&&!i&&s.solidFills.length===0,P,A,r);for(let Y=0;Y<H.length;Y++){let X=H[Y],Z=Ae(y,X.canvas);Z&&(this.cpuTexes.add(Z),V.push({tex:Z,w:X.quadW,h:X.quadH,dx:X.dx,dy:X.dy,mode:s.strokes[s.strokes.length-1-Y]?.blendMode}))}}S={sigBase:p,sigParts:m,bucket:c,basis:{lin:[f[0],f[1],f[2],f[3]],dims:{x:h.dims.x,y:h.dims.y}},shadows:z,innerShadows:D,fills:$,strokes:V,...I?{bevelShadow:I}:{},...G?{bevelHighlight:G}:{}},this.psdBakes.set(e,S)}this.renderPsdBakeQuads(h,S,t)}renderPsdBakeQuads(e,t,r,o=!1){let i=e.renderOpacity,s=e.dims,a=o&&t.basis.dims.x>0?s.x/t.basis.dims.x:1,l=o&&t.basis.dims.y>0?s.y/t.basis.dims.y:1,u=null,c=1,h=1;if(o){let x=t.basis.lin,S=e.matrix,w=Math.atan2(S[1],S[0])-Math.atan2(x[1],x[0]),y=Math.cos(w),v=Math.sin(w);u=[y,v,-v,y,S[4],S[5]];let R=Math.abs(x[0])*t.basis.dims.x+Math.abs(x[2])*t.basis.dims.y||1,P=Math.abs(x[1])*t.basis.dims.x+Math.abs(x[3])*t.basis.dims.y||1;c=(Math.abs(S[0])*s.x+Math.abs(S[2])*s.y)/R,h=(Math.abs(S[1])*s.x+Math.abs(S[3])*s.y)/P}let f=e instanceof ae?1:i,m=null,p=[],b=()=>{if(!p.length){m=null;return}let x=m;m=null;let S=p.splice(0);if(x==null){for(let y of S)y();return}let w=pa(x);if(w==null){for(let y of S)y();return}this.blendComposite(w,()=>{for(let y of S)y()})},g=(x,S)=>{x!==m&&(b(),m=x),p.push(S)};if(r==="below")for(let x of t.shadows){let S=e.matrix;if(u){let w=u;g(x.mode,()=>this.host.batch.pushQuad(w,x.w*c,x.h*h,[1,1,1,f],x.tex))}else g(x.mode,()=>this.host.batch.pushQuad([1,0,0,1,S[4],S[5]],x.w,x.h,[1,1,1,f],x.tex))}else{for(let x of t.innerShadows){let S=_n(this.getPuzzleBox(),e,e.dims.x,e.dims.y,0,0);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,f],x.tex,S.uv))}if(t.bevelShadow){let x=t.bevelShadow,S=_n(this.getPuzzleBox(),e,x.w,x.h,0,0);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,f],x.tex,S.uv))}if(t.bevelHighlight){let x=t.bevelHighlight,S=_n(this.getPuzzleBox(),e,x.w,x.h,0,0);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,f],x.tex,S.uv))}for(let x of t.fills){let S=_n(this.getPuzzleBox(),e,e.dims.x,e.dims.y,x.dx,x.dy);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,f],x.tex,S.uv))}for(let x of t.strokes){let S=_n(this.getPuzzleBox(),e,o?x.w*a:x.w,o?x.h*l:x.h,x.dx,x.dy);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,i],x.tex,S.uv))}}b()}deleteBakeTex(e){this.cpuTexes.has(e)&&(this.host.gl.deleteTexture(e),this.cpuTexes.delete(e))}invalidate(){for(let e of this.cpuTexes)this.host.gl.deleteTexture(e);this.cpuTexes.clear(),this.psdBakes=new WeakMap,this.host.renderEpoch?.bump("psd-bake-invalidate")}};var LS=`#version 300 es
449
+ }`,Zo=4096,AS=(n,e,t,r,o)=>{let i=Math.min(4,Math.max(1,r*t*o)),s=n*i,a=e*i;if(s>0&&a>0){let l=Math.min(1,Zo/Math.max(s,a)),u=Math.min(1,Math.sqrt(Zo*Zo/(s*a)));return i*Math.min(l,u)}return i},NS=(n,e,t)=>{let r=n.raw,o=n.clipImageRaw,i=Number(r.width)||0,s=Number(r.height)||0,a=o?.scaleX??1,l=o?.scaleY??1,u=o?.flipX?-1:1,c=o?.flipY?-1:1,h=(o?.angle??0)*Math.PI/180,d=r.clipX??0,f=r.clipY??0,m=Math.cos(h),p=Math.sin(h),b=[1,0,0,1,i/2,s/2],g=[m,p,-p,m,0,0],x=[a*u,0,0,l*c,0,0],S=[1,0,0,1,d/(a||1),f/(l||1)],w=[1,0,0,1,-e/2,-t/2];return ve(j(j(j(j(b,g),x),S),w))},Ea=class{prog=null;targets=new WeakMap;activeThisFrame=!1;ensureProgram(e){if(this.prog)return!0;let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[MaskCompositeGpu] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,PS),o=t(e.FRAGMENT_SHADER,kS),i=e.createProgram();return!r||!o||!i?!1:(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),e.getProgramParameter(i,e.LINK_STATUS)?(this.prog=i,!0):(console.warn("[MaskCompositeGpu] link:",e.getProgramInfoLog(i)),!1))}ensureTarget(e,t,r,o){let i=this.targets.get(t);if(i&&i.wPx===r&&i.hPx===o)return i;i&&(e.deleteFramebuffer(i.fb),e.deleteTexture(i.tex));let s=e.createTexture(),a=e.createFramebuffer();if(!s||!a)return null;e.bindTexture(e.TEXTURE_2D,s),e.texImage2D(e.TEXTURE_2D,0,e.RGBA8,r,o,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0),e.bindFramebuffer(e.FRAMEBUFFER,null);let l={fb:a,tex:s,wPx:r,hPx:o};return this.targets.set(t,l),l}render(e,t,r,o,i){let s=e.raw,a=e.clipImageRaw;if(!a)return null;let l=Number(s.width)||0,u=Number(s.height)||0;if(l<=0||u<=0||i.clipW<=0||i.clipH<=0||!this.ensureProgram(t))return null;let c=Math.max(Math.abs(a.scaleX??1),Math.abs(a.scaleY??1)),h=AS(l,u,r,o,c),d=64,f=Math.min(Zo,Math.max(d,Math.ceil(l*h/d)*d)),m=Math.min(Zo,Math.max(d,Math.ceil(u*h/d)*d)),p=t.getParameter(t.FRAMEBUFFER_BINDING),b=t.getParameter(t.VIEWPORT),g=t.getParameter(t.BLEND),x=t.getParameter(t.CURRENT_PROGRAM),S=t.getParameter(t.TEXTURE_BINDING_2D),w=this.ensureTarget(t,e,f,m);if(!w)return null;t.bindFramebuffer(t.FRAMEBUFFER,w.fb),t.viewport(0,0,f,m),t.disable(t.BLEND),t.useProgram(this.prog);let y=NS(e,i.clipW,i.clipH);t.uniformMatrix3fv(t.getUniformLocation(this.prog,"uClip"),!1,new Float32Array([y[0],y[1],0,y[2],y[3],0,y[4],y[5],1])),t.uniform1i(t.getUniformLocation(this.prog,"uClipTex"),0),t.uniform1i(t.getUniformLocation(this.prog,"uMaskTex"),1),t.uniform2f(t.getUniformLocation(this.prog,"uClipSize"),i.clipW,i.clipH),t.uniform2f(t.getUniformLocation(this.prog,"uSize"),l,u),t.uniform2f(t.getUniformLocation(this.prog,"uPxSize"),f,m);let v=Math.max(0,Math.min(s.cornerRadius||0,Math.min(l,u)/2));return t.uniform1f(t.getUniformLocation(this.prog,"uRadiusPx"),v*h),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,i.clipTex),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,i.maskTex),t.drawArrays(t.TRIANGLES,0,3),t.bindFramebuffer(t.FRAMEBUFFER,p),t.viewport(b[0],b[1],b[2],b[3]),g&&t.enable(t.BLEND),t.useProgram(x),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,S),this.activeThisFrame=!0,{tex:w.tex,w:l,h:u}}invalidate(){this.targets=new WeakMap,this.prog=null}};var _n=(n,e,t,r,o=0,i=0)=>{let s=e.raw,a=o||i?j(e.matrix,[1,0,0,1,o,i]):e.matrix;if(!n||s.angle||(s.scaleX??1)!==1||(s.scaleY??1)!==1)return{matrix:a,w:t,h:r,uv:[0,0,1,1]};let l=(s.left??0)+o,u=(s.top??0)+i,c=Math.max(l-t/2,-n.hw),h=Math.min(l+t/2,n.hw),d=Math.max(u-r/2,-n.hh),f=Math.min(u+r/2,n.hh);if(!(h-c>0)||!(f-d>0))return null;let m=[(c-(l-t/2))/t,(d-(u-r/2))/r,(h-(l-t/2))/t,(f-(u-r/2))/r],p=(c+h)/2-l,b=(d+f)/2-u,g=a;return{matrix:[g[0],g[1],g[2],g[3],g[0]*p+g[2]*b+g[4],g[1]*p+g[3]*b+g[5]],w:h-c,h:f-d,uv:m}};var hp=new WeakMap,LS=n=>{let e=hp.get(n);return e||(e=Object.create(n),Object.defineProperty(e,"matrix",{get:()=>{let t=n.bitmapRect,r=n.matrix;return(t.x!==0||t.y!==0)&&(r=j(r,[1,0,0,1,t.x,t.y])),t.angle&&(r=j(r,At({angle:-t.angle}))),r}}),hp.set(n,e)),e},Ca=class{host;frame;gpu;getPuzzleBox;psdBakes=new WeakMap;settle;blendComposite;cpuTexes=new Set;patterns;constructor(e,t,r,o,i=new In(()=>e.requestRenderAll()),s=()=>{},a=null){this.host=e,this.frame=t,this.gpu=r,this.getPuzzleBox=o,this.settle=i,this.patterns=a,this.blendComposite=s}noteVptScaleChange(){this.settle.noteInteraction()}render(e,t){let r=e.isTextType&&e instanceof ye,o=r&&Kt(e)&&e!==this.host.editingNode&&!!e.imageEl,i=e instanceof ae;if(!e.isImageType&&e.typeKey!==L.PATH&&!r&&!i||t==="above"&&!e.isImageType&&!r&&!i&&e.typeKey!==L.PATH||e.isImageType&&!(e instanceof ie)&&!e.imageEl)return;let s=Mt(e.raw.effects,r?{text:!0}:{});if(!s)return;let a=e.cropRect?`${e.cropRect.sx},${e.cropRect.sy},${e.cropRect.sw},${e.cropRect.sh}`:"",l=o?`bmp:${e.raw.renderSrc}`:r?JSON.stringify([e.raw.text,e.raw.styles,e.raw.fontFamily,e.raw.fontSize,e.raw.fontWeight,e.raw.fontStyle,e.raw.lineHeight,e.raw.charSpacing,e.raw.textAlign,e.raw.paragraph??null,e.raw.width,e.raw.height]):typeof e.raw.src=="string"?`${e.raw.src}|${a}${Wi(e)}${Lh(e)}`:a,u=e instanceof ie?`v${e.contentVersion}`:"",c=r&&!o?Math.max(1,Ht(this.host.zoom*this.host.dpr*Math.max(e.worldScale.x,e.worldScale.y))):1,h=o?LS(e):e,d=_r(s);if(d.length>0&&this.patterns&&!this.patterns.patternSourcesReady(d)){let y=this.psdBakes.get(e);y&&this.renderPsdBakeQuads(h,y,t,!0);return}let f=h.matrix,m=[wn(s),`${f[0]},${f[1]},${f[2]},${f[3]}`,`${h.dims.x},${h.dims.y}`,l,u],p=m.join(";"),b=this.host.document?.transformGestureAt??-1/0,x=!this.host.isExporting()&&performance.now()-b<160||va(this.host,this.settle,this.frame,performance.now()),S=this.psdBakes.get(e),w=y=>{for(let v of y.shadows)this.deleteBakeTex(v.tex);for(let v of y.innerShadows)this.deleteBakeTex(v.tex);for(let v of y.fills)this.deleteBakeTex(v.tex);for(let v of y.strokes)this.deleteBakeTex(v.tex);y.bevelShadow&&this.deleteBakeTex(y.bevelShadow.tex),y.bevelHighlight&&this.deleteBakeTex(y.bevelHighlight.tex)};if(S&&S.sigBase!==p){if(m[0]===S.sigParts[0]&&m[3]===S.sigParts[3]&&m[4]===S.sigParts[4]&&x){this.frame.bakeMore=!0,this.renderPsdBakeQuads(h,S,t,!0);return}w(S),S=void 0}if(S&&S.bucket!==c){if(x){this.frame.bakeMore=!0,this.renderPsdBakeQuads(h,S,t);return}w(S),S=void 0}if(!S){let y=this.host.gl,v=e instanceof ae?e.imageEl:e instanceof ie?e.paintSource:e.isImageType||o?e.imageEl:null,R=v?1:c,P=v&&!o?1:Math.min(Math.max(2,c),Bi(e)),T=v??(r?mo(e,R):null),C=v??(r?mo(e,P):null),E=!T&&!i&&e.typeKey===L.PATH&&(s.solidFills.length>0||s.innerShadows.length>0||s.bevel)?Fh(h):null,M=T??E,k=v?1:R,A=v?e.cropRect:null,O=ja()||Va()?this.gpu.fx:null,F=!T&&!i,W=[];for(let H of s.dropShadows){let Y=W[W.length-1];Y&&Y.mode===H.blendMode?Y.group.push(H):W.push({mode:H.blendMode,group:[H]})}let z=[],_=W.length===1&&!W[0].mode;for(let H of W){if(ja()&&O&&_){let X=O.bakeDropShadows(y,h,H.group,{source:T,sourceRect:A,rs:R,pathMode:F,sig:p,viewportW:this.host.canvasEl.width,viewportH:this.host.canvasEl.height});if(X){z.push({tex:X.tex,w:X.w/R,h:X.h/R,mode:void 0});continue}}let Y=T?Hi(h,H.group,T,R,A):Dh(e,H.group);if(Y){let X=Ae(y,Y.canvas,{mipmap:!0});X&&(this.cpuTexes.add(X),z.push({tex:X,w:Y.quadW,h:Y.quadH,mode:H.mode}))}}let D=[];if(M)for(let H of s.innerShadows){let Y=wr(h,H,M,k,A);if(!Y)continue;let X=Ae(y,Y);X&&(this.cpuTexes.add(X),D.push({tex:X,mode:H.blendMode}))}let I,G;if(s.bevel&&(C||E)){let H=Oh(h,s.bevel,C??E,P,A);if(H){let Y=Ae(y,H.shadow),X=Ae(y,H.highlight);Y&&(this.cpuTexes.add(Y),I={tex:Y,w:H.quadW,h:H.quadH,mode:s.bevel.shadow.blendMode}),X&&(this.cpuTexes.add(X),G={tex:X,w:H.quadW,h:H.quadH,mode:s.bevel.highlight.blendMode})}}let $=[];if(M)for(let H of s.solidFills){if(Va()&&O&&H.kind==="solid"&&!A&&!H.blendMode&&!It(h)){let Z=Math.max(1,Math.ceil(h.dims.x*R)),B=Math.max(1,Math.ceil(h.dims.y*R)),q=O.uploadLocalSource(y,h,M,`${p}|fillsrc`,Z,B),U=q?O.bakeSolidFill(y,h,H,q,Z,B,p,`fill${$.length}`,this.host.canvasEl.width,this.host.canvasEl.height):null;if(U){$.push({tex:U,dx:H.offset.x,dy:H.offset.y,mode:void 0});continue}}let Y=vr(h,H,M,k,A);if(!Y)continue;let X=Ae(y,Y);X&&(this.cpuTexes.add(X),$.push({tex:X,dx:H.offset.x,dy:H.offset.y,mode:H.blendMode}))}let V=[];if(C){let H=bn(h,s.strokes,C,!r&&!i&&s.solidFills.length===0,P,A,r);for(let Y=0;Y<H.length;Y++){let X=H[Y],Z=Ae(y,X.canvas);Z&&(this.cpuTexes.add(Z),V.push({tex:Z,w:X.quadW,h:X.quadH,dx:X.dx,dy:X.dy,mode:s.strokes[s.strokes.length-1-Y]?.blendMode}))}}S={sigBase:p,sigParts:m,bucket:c,basis:{lin:[f[0],f[1],f[2],f[3]],dims:{x:h.dims.x,y:h.dims.y}},shadows:z,innerShadows:D,fills:$,strokes:V,...I?{bevelShadow:I}:{},...G?{bevelHighlight:G}:{}},this.psdBakes.set(e,S)}this.renderPsdBakeQuads(h,S,t)}renderPsdBakeQuads(e,t,r,o=!1){let i=e.renderOpacity,s=e.dims,a=o&&t.basis.dims.x>0?s.x/t.basis.dims.x:1,l=o&&t.basis.dims.y>0?s.y/t.basis.dims.y:1,u=null,c=1,h=1;if(o){let x=t.basis.lin,S=e.matrix,w=Math.atan2(S[1],S[0])-Math.atan2(x[1],x[0]),y=Math.cos(w),v=Math.sin(w);u=[y,v,-v,y,S[4],S[5]];let R=Math.abs(x[0])*t.basis.dims.x+Math.abs(x[2])*t.basis.dims.y||1,P=Math.abs(x[1])*t.basis.dims.x+Math.abs(x[3])*t.basis.dims.y||1;c=(Math.abs(S[0])*s.x+Math.abs(S[2])*s.y)/R,h=(Math.abs(S[1])*s.x+Math.abs(S[3])*s.y)/P}let f=e instanceof ae?1:i,m=null,p=[],b=()=>{if(!p.length){m=null;return}let x=m;m=null;let S=p.splice(0);if(x==null){for(let y of S)y();return}let w=pa(x);if(w==null){for(let y of S)y();return}this.blendComposite(w,()=>{for(let y of S)y()})},g=(x,S)=>{x!==m&&(b(),m=x),p.push(S)};if(r==="below")for(let x of t.shadows){let S=e.matrix;if(u){let w=u;g(x.mode,()=>this.host.batch.pushQuad(w,x.w*c,x.h*h,[1,1,1,f],x.tex))}else g(x.mode,()=>this.host.batch.pushQuad([1,0,0,1,S[4],S[5]],x.w,x.h,[1,1,1,f],x.tex))}else{for(let x of t.innerShadows){let S=_n(this.getPuzzleBox(),e,e.dims.x,e.dims.y,0,0);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,f],x.tex,S.uv))}if(t.bevelShadow){let x=t.bevelShadow,S=_n(this.getPuzzleBox(),e,x.w,x.h,0,0);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,f],x.tex,S.uv))}if(t.bevelHighlight){let x=t.bevelHighlight,S=_n(this.getPuzzleBox(),e,x.w,x.h,0,0);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,f],x.tex,S.uv))}for(let x of t.fills){let S=_n(this.getPuzzleBox(),e,e.dims.x,e.dims.y,x.dx,x.dy);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,f],x.tex,S.uv))}for(let x of t.strokes){let S=_n(this.getPuzzleBox(),e,o?x.w*a:x.w,o?x.h*l:x.h,x.dx,x.dy);S&&g(x.mode,()=>this.host.batch.pushQuad(S.matrix,S.w,S.h,[1,1,1,i],x.tex,S.uv))}}b()}deleteBakeTex(e){this.cpuTexes.has(e)&&(this.host.gl.deleteTexture(e),this.cpuTexes.delete(e))}invalidate(){for(let e of this.cpuTexes)this.host.gl.deleteTexture(e);this.cpuTexes.clear(),this.psdBakes=new WeakMap,this.host.renderEpoch?.bump("psd-bake-invalidate")}};var IS=`#version 300 es
450
450
  out vec2 vUv;
451
451
  void main() {
452
452
  vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
453
453
  vUv = p;
454
454
  gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
455
- }`,IS=`#version 300 es
455
+ }`,_S=`#version 300 es
456
456
  precision mediump float;
457
457
  in vec2 vUv;
458
458
  uniform sampler2D uSrc;
@@ -466,7 +466,7 @@ if (k >= uBoxW) break;
466
466
  acc += texture(uSrc, vUv + uDir * (float(k) - float(uBoxW - 1) * 0.5)).a;
467
467
  }
468
468
  outColor = vec4(0.0, 0.0, 0.0, acc / float(uBoxW));
469
- }`,_S=`#version 300 es
469
+ }`,DS=`#version 300 es
470
470
  precision mediump float;
471
471
  in vec2 vUv;
472
472
  uniform sampler2D uMask;
@@ -476,7 +476,7 @@ out vec4 outColor;
476
476
  void main() {
477
477
  float m = texture(uMask, vUv + uOffUv).a;
478
478
  outColor = vec4(uColor.rgb, m * uColor.a);
479
- }`,DS=`#version 300 es
479
+ }`,FS=`#version 300 es
480
480
  precision mediump float;
481
481
  in vec2 vUv;
482
482
  uniform sampler2D uSrc;
@@ -484,7 +484,7 @@ uniform vec4 uColor;
484
484
  out vec4 outColor;
485
485
  void main() {
486
486
  outColor = vec4(uColor.rgb, texture(uSrc, vUv).a * uColor.a);
487
- }`,FS=`#version 300 es
487
+ }`,OS=`#version 300 es
488
488
  precision mediump float;
489
489
  in vec2 vUv;
490
490
  uniform sampler2D uAcc;
@@ -494,19 +494,19 @@ out vec4 outColor;
494
494
  void main() {
495
495
  vec4 acc = texture(uAcc, vUv);
496
496
  outColor = vec4(acc.rgb, acc.a * mix(1.0, 1.0 - texture(uSil, vUv).a, uErase));
497
- }`,OS=`#version 300 es
497
+ }`,BS=`#version 300 es
498
498
  in vec2 aPos;
499
499
  uniform mat3 uM;
500
500
  uniform vec2 uSize;
501
501
  void main() {
502
502
  vec2 px = (uM * vec3(aPos, 1.0)).xy;
503
503
  gl_Position = vec4(px.x / uSize.x * 2.0 - 1.0, 1.0 - px.y / uSize.y * 2.0, 0.0, 1.0);
504
- }`,BS=`#version 300 es
504
+ }`,WS=`#version 300 es
505
505
  precision mediump float;
506
506
  out vec4 outColor;
507
507
  void main() {
508
508
  outColor = vec4(1.0, 1.0, 1.0, 1.0);
509
- }`,WS=`#version 300 es
509
+ }`,HS=`#version 300 es
510
510
  precision mediump float;
511
511
  in vec2 vUv;
512
512
  uniform sampler2D uSrc;
@@ -518,14 +518,14 @@ vec4 b = texture(uSrc, vUv + vec2(uHalfTexel.x, -uHalfTexel.y));
518
518
  vec4 c = texture(uSrc, vUv + vec2(-uHalfTexel.x, uHalfTexel.y));
519
519
  vec4 d = texture(uSrc, vUv + uHalfTexel);
520
520
  outColor = (a + b + c + d) * 0.25;
521
- }`,Ma=class{constructor(e){this.epoch=e}epoch;sources=new WeakMap;liveSrcTexes=new Set;liveTargetRts=new Set;targets=new WeakMap;slot(e,t,r,o,i,s){let a=this.targets.get(t);if(a&&a.sigBase!==r){for(let u of a.map.values())e.deleteFramebuffer(u.fb),e.deleteTexture(u.tex),this.liveTargetRts.delete(u);this.epoch?.bump("fx-slot-group-rebuild"),a=void 0}a||(a={sigBase:r,map:new Map},this.targets.set(t,a));let l=a.map.get(o);return l&&l.w===i&&l.h===s&&e.isTexture(l.tex)?l:(l&&(e.deleteFramebuffer(l.fb),e.deleteTexture(l.tex),this.liveTargetRts.delete(l)),l=this.allocTarget(e,i,s),l?(this.liveTargetRts.add(l),a.map.set(o,l),l):null)}maskProg=null;downProg=null;maskRt=null;maskMsaa=null;meshBufs=new WeakMap;blurProg=null;tintProg=null;fillProg=null;finishProg=null;scratch=[];invalidateTextDerivedBakes(e){for(let t of this.liveSrcTexes)e.isTexture(t)&&e.deleteTexture(t);this.liveSrcTexes.clear();for(let t of this.liveTargetRts)e.isTexture(t.tex)&&e.deleteTexture(t.tex),e.isFramebuffer(t.fb)&&e.deleteFramebuffer(t.fb);this.liveTargetRts.clear(),this.sources=new WeakMap,this.targets=new WeakMap}invalidate(e){this.invalidateTextDerivedBakes(e),this.maskProg=null,this.downProg=null,this.blurProg=null,this.tintProg=null,this.fillProg=null,this.finishProg=null,this.maskRt=null,this.maskMsaa=null,this.scratch=[],this.meshBufs=new WeakMap}compile(e,t,r=LS){let o=(l,u)=>{let c=e.createShader(l);return c?(e.shaderSource(c,u),e.compileShader(c),e.getShaderParameter(c,e.COMPILE_STATUS)?c:(console.warn("[GpuFxPainter] shader:",e.getShaderInfoLog(c)),e.deleteShader(c),null)):null},i=o(e.VERTEX_SHADER,r),s=o(e.FRAGMENT_SHADER,t),a=e.createProgram();return!i||!s||!a?null:(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),e.getProgramParameter(a,e.LINK_STATUS)?a:(console.warn("[GpuFxPainter] link:",e.getProgramInfoLog(a)),null))}ensurePrograms(e){return this.maskProg&&this.downProg&&this.blurProg&&this.tintProg&&this.fillProg&&this.finishProg?!0:(this.maskProg=this.maskProg??this.compile(e,BS,OS),this.downProg=this.downProg??this.compile(e,WS),this.blurProg=this.blurProg??this.compile(e,IS),this.tintProg=this.tintProg??this.compile(e,_S),this.fillProg=this.fillProg??this.compile(e,DS),this.finishProg=this.finishProg??this.compile(e,FS),!!(this.blurProg&&this.tintProg&&this.fillProg&&this.finishProg))}ensureTarget(e,t,r,o){let i=this.scratch[t];if(i&&i.w===r&&i.h===o)return i;i&&(e.deleteFramebuffer(i.fb),e.deleteTexture(i.tex));let s=this.allocTarget(e,r,o);return s&&(this.scratch[t]=s),s}allocTarget(e,t,r){let o=e.createTexture();if(!o)return null;e.bindTexture(e.TEXTURE_2D,o),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);let i=e.createFramebuffer();return i?(e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,o,0),e.bindFramebuffer(e.FRAMEBUFFER,null),{fb:i,tex:o,w:t,h:r}):(e.deleteTexture(o),null)}pass(e,t,r,o,i=!1){e.bindFramebuffer(e.FRAMEBUFFER,r.fb),e.viewport(0,0,r.w,r.h),e.useProgram(t),o(t),i?(e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)):e.disable(e.BLEND),e.bindVertexArray(null),e.drawArrays(e.TRIANGLES,0,3)}restoreFb=null;restore(e){e.bindFramebuffer(e.FRAMEBUFFER,this.restoreFb),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)}blurChain(e,t,r,o,i,s,a,l){let u=i<.05?1:Math.max(1,Math.min(64,Math.round(Math.sqrt(4*i*i+1)))),c=[this.ensureTarget(e,s,r,o),this.ensureTarget(e,a,r,o),this.ensureTarget(e,l,r,o)];if(!c[0]||!c[1]||!c[2])return null;let h=(d,f,m,p)=>this.pass(e,this.blurProg,f,b=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,d),e.uniform1i(e.getUniformLocation(b,"uSrc"),0),e.uniform2f(e.getUniformLocation(b,"uDir"),m,p),e.uniform1i(e.getUniformLocation(b,"uBoxW"),u)});return h(t,c[0],1/r,0),h(c[0].tex,c[1],1/r,0),h(c[1].tex,c[0],1/r,0),h(c[0].tex,c[1],0,1/o),h(c[1].tex,c[0],0,1/o),h(c[0].tex,c[1],0,1/o),c[1].tex}source(e,t,r,o,i,s,a,l,u=null){let c=this.sources.get(t);if(c&&(c.sig!==r||!e.isTexture(c.tex))&&(e.deleteTexture(c.tex),c=void 0),!c){let h=document.createElement("canvas");h.width=o,h.height=i;let d=h.getContext("2d");if(!d)return null;let f=t.matrix;if(d.setTransform(f[0]*a,f[1]*a,f[2]*a,f[3]*a,o/2,i/2),l){if(d.fillStyle=to(t,d),!xr(d,t))return null;d.fill()}else if(s){let p=t.dims.x,b=t.dims.y;u?d.drawImage(s,u.sx,u.sy,u.sw,u.sh,-p/2,-b/2,p,b):d.drawImage(s,-p/2,-b/2,p,b)}else return null;let m=e.createTexture();if(!m)return null;e.bindTexture(e.TEXTURE_2D,m),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,h),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),c={sig:r,tex:m,w:o,h:i},this.sources.set(t,c)}return c.tex}uploadLocalSource(e,t,r,o,i,s){let a=this.sources.get(t);if(a&&(a.sig!==o||!e.isTexture(a.tex))&&(e.deleteTexture(a.tex),this.liveSrcTexes.delete(a.tex),a=void 0),!a){let l=e.createTexture();if(!l)return null;e.bindTexture(e.TEXTURE_2D,l),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.liveSrcTexes.add(l),a={sig:o,tex:l,w:i,h:s},this.sources.set(t,a)}return a.tex}bakeDropShadows(e,t,r,o){if(this.restoreFb=e.getParameter(e.FRAMEBUFFER_BINDING),!this.ensurePrograms(e)||r.length===0)return null;let{rs:i,pathMode:s}=o,a=t.raw.scaleX??1,l=t.raw.scaleY??1,u=4;for(let T of r){let C=s?{blur:T.blur,offX:T.offsetX,offY:T.offsetY}:Lt(dp(T),a,l);u=Math.max(u,Math.ceil(C.blur*2+Math.max(Math.abs(C.offX),Math.abs(C.offY))+4))}let c=t.matrix,h=Math.abs(c[0])*t.dims.x+Math.abs(c[2])*t.dims.y,d=Math.abs(c[1])*t.dims.x+Math.abs(c[3])*t.dims.y,f=Math.ceil(h+u*2),m=Math.ceil(d+u*2),p=Math.ceil(f*i),b=Math.ceil(m*i);if(!(f>0)||!(m>0)||p>8192||b>8192)return null;let g=It(t),x=o.source,S=o.sourceRect??null;g&&x&&(x=fo(x,S,g*i,Math.max(1,Math.ceil(t.dims.x*i)),Math.max(1,Math.ceil(t.dims.y*i))),S=null);let w=this.source(e,t,`${o.sig}|src`,p,b,x,i,s,S);if(!w)return null;let y=this.ensureTarget(e,3,p,b);if(!y)return null;let v=this.slot(e,t,o.sig,"shadow",p,b);if(!v)return null;e.bindFramebuffer(e.FRAMEBUFFER,y.fb),e.viewport(0,0,p,b),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT);for(let T of r){let C=s?{blur:T.blur,offX:T.offsetX,offY:T.offsetY}:Lt(dp(T),a,l),E=this.blurChain(e,w,p,b,C.blur*i/2,0,1,2);if(!E)return null;this.pass(e,this.tintProg,y,M=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,E),e.uniform1i(e.getUniformLocation(M,"uMask"),0),e.uniform2f(e.getUniformLocation(M,"uOffUv"),-C.offX*i/p,-C.offY*i/b),e.uniform4f(e.getUniformLocation(M,"uColor"),T.rgba[0],T.rgba[1],T.rgba[2],T.rgba[3])},!0),this.pass(e,this.fillProg,y,M=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,w),e.uniform1i(e.getUniformLocation(M,"uSrc"),0),e.uniform4f(e.getUniformLocation(M,"uColor"),1,1,1,1)},!0)}let R=y.tex,P=w;return this.pass(e,this.finishProg,v,T=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,R),e.uniform1i(e.getUniformLocation(T,"uAcc"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,P),e.uniform1i(e.getUniformLocation(T,"uSil"),1),e.uniform1f(e.getUniformLocation(T,"uErase"),s?0:1)}),e.viewport(0,0,o.viewportW,o.viewportH),this.restore(e),{tex:v.tex,w:p,h:b}}bakeSolidFill(e,t,r,o,i,s,a,l,u,c){if(this.restoreFb=e.getParameter(e.FRAMEBUFFER_BINDING),!this.ensurePrograms(e))return null;let h=this.slot(e,t,a,l,i,s);if(!h)return null;let d=o;return this.pass(e,this.fillProg,h,f=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,d),e.uniform1i(e.getUniformLocation(f,"uSrc"),0),e.uniform4f(e.getUniformLocation(f,"uColor"),r.rgba[0],r.rgba[1],r.rgba[2],r.rgba[3])}),e.viewport(0,0,u,c),this.restore(e),h.tex}},dp=n=>({color:n.color,rgba:n.rgba,blur:n.blur,offsetX:n.offsetX,offsetY:n.offsetY,nonScaling:!1});var mp=`attribute vec2 aPosition;
521
+ }`,Ma=class{constructor(e){this.epoch=e}epoch;sources=new WeakMap;liveSrcTexes=new Set;liveTargetRts=new Set;targets=new WeakMap;slot(e,t,r,o,i,s){let a=this.targets.get(t);if(a&&a.sigBase!==r){for(let u of a.map.values())e.deleteFramebuffer(u.fb),e.deleteTexture(u.tex),this.liveTargetRts.delete(u);this.epoch?.bump("fx-slot-group-rebuild"),a=void 0}a||(a={sigBase:r,map:new Map},this.targets.set(t,a));let l=a.map.get(o);return l&&l.w===i&&l.h===s&&e.isTexture(l.tex)?l:(l&&(e.deleteFramebuffer(l.fb),e.deleteTexture(l.tex),this.liveTargetRts.delete(l)),l=this.allocTarget(e,i,s),l?(this.liveTargetRts.add(l),a.map.set(o,l),l):null)}maskProg=null;downProg=null;maskRt=null;maskMsaa=null;meshBufs=new WeakMap;blurProg=null;tintProg=null;fillProg=null;finishProg=null;scratch=[];invalidateTextDerivedBakes(e){for(let t of this.liveSrcTexes)e.isTexture(t)&&e.deleteTexture(t);this.liveSrcTexes.clear();for(let t of this.liveTargetRts)e.isTexture(t.tex)&&e.deleteTexture(t.tex),e.isFramebuffer(t.fb)&&e.deleteFramebuffer(t.fb);this.liveTargetRts.clear(),this.sources=new WeakMap,this.targets=new WeakMap}invalidate(e){this.invalidateTextDerivedBakes(e),this.maskProg=null,this.downProg=null,this.blurProg=null,this.tintProg=null,this.fillProg=null,this.finishProg=null,this.maskRt=null,this.maskMsaa=null,this.scratch=[],this.meshBufs=new WeakMap}compile(e,t,r=IS){let o=(l,u)=>{let c=e.createShader(l);return c?(e.shaderSource(c,u),e.compileShader(c),e.getShaderParameter(c,e.COMPILE_STATUS)?c:(console.warn("[GpuFxPainter] shader:",e.getShaderInfoLog(c)),e.deleteShader(c),null)):null},i=o(e.VERTEX_SHADER,r),s=o(e.FRAGMENT_SHADER,t),a=e.createProgram();return!i||!s||!a?null:(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),e.getProgramParameter(a,e.LINK_STATUS)?a:(console.warn("[GpuFxPainter] link:",e.getProgramInfoLog(a)),null))}ensurePrograms(e){return this.maskProg&&this.downProg&&this.blurProg&&this.tintProg&&this.fillProg&&this.finishProg?!0:(this.maskProg=this.maskProg??this.compile(e,WS,BS),this.downProg=this.downProg??this.compile(e,HS),this.blurProg=this.blurProg??this.compile(e,_S),this.tintProg=this.tintProg??this.compile(e,DS),this.fillProg=this.fillProg??this.compile(e,FS),this.finishProg=this.finishProg??this.compile(e,OS),!!(this.blurProg&&this.tintProg&&this.fillProg&&this.finishProg))}ensureTarget(e,t,r,o){let i=this.scratch[t];if(i&&i.w===r&&i.h===o)return i;i&&(e.deleteFramebuffer(i.fb),e.deleteTexture(i.tex));let s=this.allocTarget(e,r,o);return s&&(this.scratch[t]=s),s}allocTarget(e,t,r){let o=e.createTexture();if(!o)return null;e.bindTexture(e.TEXTURE_2D,o),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);let i=e.createFramebuffer();return i?(e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,o,0),e.bindFramebuffer(e.FRAMEBUFFER,null),{fb:i,tex:o,w:t,h:r}):(e.deleteTexture(o),null)}pass(e,t,r,o,i=!1){e.bindFramebuffer(e.FRAMEBUFFER,r.fb),e.viewport(0,0,r.w,r.h),e.useProgram(t),o(t),i?(e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)):e.disable(e.BLEND),e.bindVertexArray(null),e.drawArrays(e.TRIANGLES,0,3)}restoreFb=null;restore(e){e.bindFramebuffer(e.FRAMEBUFFER,this.restoreFb),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA)}blurChain(e,t,r,o,i,s,a,l){let u=i<.05?1:Math.max(1,Math.min(64,Math.round(Math.sqrt(4*i*i+1)))),c=[this.ensureTarget(e,s,r,o),this.ensureTarget(e,a,r,o),this.ensureTarget(e,l,r,o)];if(!c[0]||!c[1]||!c[2])return null;let h=(d,f,m,p)=>this.pass(e,this.blurProg,f,b=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,d),e.uniform1i(e.getUniformLocation(b,"uSrc"),0),e.uniform2f(e.getUniformLocation(b,"uDir"),m,p),e.uniform1i(e.getUniformLocation(b,"uBoxW"),u)});return h(t,c[0],1/r,0),h(c[0].tex,c[1],1/r,0),h(c[1].tex,c[0],1/r,0),h(c[0].tex,c[1],0,1/o),h(c[1].tex,c[0],0,1/o),h(c[0].tex,c[1],0,1/o),c[1].tex}source(e,t,r,o,i,s,a,l,u=null){let c=this.sources.get(t);if(c&&(c.sig!==r||!e.isTexture(c.tex))&&(e.deleteTexture(c.tex),c=void 0),!c){let h=document.createElement("canvas");h.width=o,h.height=i;let d=h.getContext("2d");if(!d)return null;let f=t.matrix;if(d.setTransform(f[0]*a,f[1]*a,f[2]*a,f[3]*a,o/2,i/2),l){if(d.fillStyle=to(t,d),!xr(d,t))return null;d.fill()}else if(s){let p=t.dims.x,b=t.dims.y;u?d.drawImage(s,u.sx,u.sy,u.sw,u.sh,-p/2,-b/2,p,b):d.drawImage(s,-p/2,-b/2,p,b)}else return null;let m=e.createTexture();if(!m)return null;e.bindTexture(e.TEXTURE_2D,m),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,h),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),c={sig:r,tex:m,w:o,h:i},this.sources.set(t,c)}return c.tex}uploadLocalSource(e,t,r,o,i,s){let a=this.sources.get(t);if(a&&(a.sig!==o||!e.isTexture(a.tex))&&(e.deleteTexture(a.tex),this.liveSrcTexes.delete(a.tex),a=void 0),!a){let l=e.createTexture();if(!l)return null;e.bindTexture(e.TEXTURE_2D,l),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.liveSrcTexes.add(l),a={sig:o,tex:l,w:i,h:s},this.sources.set(t,a)}return a.tex}bakeDropShadows(e,t,r,o){if(this.restoreFb=e.getParameter(e.FRAMEBUFFER_BINDING),!this.ensurePrograms(e)||r.length===0)return null;let{rs:i,pathMode:s}=o,a=t.raw.scaleX??1,l=t.raw.scaleY??1,u=4;for(let T of r){let C=s?{blur:T.blur,offX:T.offsetX,offY:T.offsetY}:Lt(fp(T),a,l);u=Math.max(u,Math.ceil(C.blur*2+Math.max(Math.abs(C.offX),Math.abs(C.offY))+4))}let c=t.matrix,h=Math.abs(c[0])*t.dims.x+Math.abs(c[2])*t.dims.y,d=Math.abs(c[1])*t.dims.x+Math.abs(c[3])*t.dims.y,f=Math.ceil(h+u*2),m=Math.ceil(d+u*2),p=Math.ceil(f*i),b=Math.ceil(m*i);if(!(f>0)||!(m>0)||p>8192||b>8192)return null;let g=It(t),x=o.source,S=o.sourceRect??null;g&&x&&(x=fo(x,S,g*i,Math.max(1,Math.ceil(t.dims.x*i)),Math.max(1,Math.ceil(t.dims.y*i))),S=null);let w=this.source(e,t,`${o.sig}|src`,p,b,x,i,s,S);if(!w)return null;let y=this.ensureTarget(e,3,p,b);if(!y)return null;let v=this.slot(e,t,o.sig,"shadow",p,b);if(!v)return null;e.bindFramebuffer(e.FRAMEBUFFER,y.fb),e.viewport(0,0,p,b),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT);for(let T of r){let C=s?{blur:T.blur,offX:T.offsetX,offY:T.offsetY}:Lt(fp(T),a,l),E=this.blurChain(e,w,p,b,C.blur*i/2,0,1,2);if(!E)return null;this.pass(e,this.tintProg,y,M=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,E),e.uniform1i(e.getUniformLocation(M,"uMask"),0),e.uniform2f(e.getUniformLocation(M,"uOffUv"),-C.offX*i/p,-C.offY*i/b),e.uniform4f(e.getUniformLocation(M,"uColor"),T.rgba[0],T.rgba[1],T.rgba[2],T.rgba[3])},!0),this.pass(e,this.fillProg,y,M=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,w),e.uniform1i(e.getUniformLocation(M,"uSrc"),0),e.uniform4f(e.getUniformLocation(M,"uColor"),1,1,1,1)},!0)}let R=y.tex,P=w;return this.pass(e,this.finishProg,v,T=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,R),e.uniform1i(e.getUniformLocation(T,"uAcc"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,P),e.uniform1i(e.getUniformLocation(T,"uSil"),1),e.uniform1f(e.getUniformLocation(T,"uErase"),s?0:1)}),e.viewport(0,0,o.viewportW,o.viewportH),this.restore(e),{tex:v.tex,w:p,h:b}}bakeSolidFill(e,t,r,o,i,s,a,l,u,c){if(this.restoreFb=e.getParameter(e.FRAMEBUFFER_BINDING),!this.ensurePrograms(e))return null;let h=this.slot(e,t,a,l,i,s);if(!h)return null;let d=o;return this.pass(e,this.fillProg,h,f=>{e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,d),e.uniform1i(e.getUniformLocation(f,"uSrc"),0),e.uniform4f(e.getUniformLocation(f,"uColor"),r.rgba[0],r.rgba[1],r.rgba[2],r.rgba[3])}),e.viewport(0,0,u,c),this.restore(e),h.tex}},fp=n=>({color:n.color,rgba:n.rgba,blur:n.blur,offsetX:n.offsetX,offsetY:n.offsetY,nonScaling:!1});var pp=`attribute vec2 aPosition;
522
522
  varying vec2 vTexCoord;
523
523
  void main() {
524
524
  vTexCoord = aPosition;
525
525
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
526
526
  }`,je=`precision highp float;
527
527
  uniform sampler2D uTexture;
528
- varying vec2 vTexCoord;`,fp=`
528
+ varying vec2 vTexCoord;`,mp=`
529
529
  vec3 rgb2hsl(vec3 c) {
530
530
  float maxc = max(c.r, max(c.g, c.b));
531
531
  float minc = min(c.r, min(c.g, c.b));
@@ -567,7 +567,7 @@ vec3 hsl2rgb(vec3 hsl) {
567
567
  hslChannel(p, q, h - 1.0 / 3.0)
568
568
  );
569
569
  }
570
- `,HS=n=>{let e=n/2;return e<.05?1:Math.max(1,Math.min(64,Math.round(Math.sqrt(4*e*e+1))))};function pp(n,e,t){let r=[];for(let o of n)switch(o.kind){case"Brightness":r.push({source:`${je}
570
+ `,GS=n=>{let e=n/2;return e<.05?1:Math.max(1,Math.min(64,Math.round(Math.sqrt(4*e*e+1))))};function bp(n,e,t){let r=[];for(let o of n)switch(o.kind){case"Brightness":r.push({source:`${je}
571
571
  uniform float uW;
572
572
  void main() {
573
573
  vec4 color = texture2D(uTexture, vTexCoord);
@@ -585,7 +585,7 @@ color.rgb = clamp((color.rgb - 0.5) * uM + 0.5, 0.0, 1.0);
585
585
  gl_FragColor = color;
586
586
  }`,setup:(i,s)=>i.uniform1f(s.uM,o.contrast>=0?1/Math.max(1e-4,1-o.contrast):1+o.contrast)});break;case"Saturation":r.push({source:`${je}
587
587
  uniform float uSat;
588
- ${fp}
588
+ ${mp}
589
589
  void main() {
590
590
  vec4 color = texture2D(uTexture, vTexCoord);
591
591
  vec3 hsl = rgb2hsl(color.rgb);
@@ -606,14 +606,14 @@ color.rgb = lum + (color.rgb - lum) * factor;
606
606
  gl_FragColor = color;
607
607
  }`,setup:(i,s)=>i.uniform1f(s.uV,o.vibrance)});break;case"HueRotation":r.push({source:`${je}
608
608
  uniform float uShift;
609
- ${fp}
609
+ ${mp}
610
610
  void main() {
611
611
  vec4 color = texture2D(uTexture, vTexCoord);
612
612
  vec3 hsl = rgb2hsl(color.rgb);
613
613
  hsl.x = fract(hsl.x + uShift / 360.0);
614
614
  color.rgb = hsl2rgb(hsl);
615
615
  gl_FragColor = color;
616
- }`,setup:(i,s)=>i.uniform1f(s.uShift,o.rotation*100)});break;case"ColorMatrix":r.push(GS(Rh[o.matrixId]));break;case"Grayscale":{let i=o.mode==="lightness"?`
616
+ }`,setup:(i,s)=>i.uniform1f(s.uShift,o.rotation*100)});break;case"ColorMatrix":r.push(XS(Ph[o.matrixId]));break;case"Grayscale":{let i=o.mode==="lightness"?`
617
617
  vec4 col = texture2D(uTexture, vTexCoord);
618
618
  float average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;
619
619
  gl_FragColor = vec4(average, average, average, col.a);`:o.mode==="luminosity"?`
@@ -638,7 +638,7 @@ gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 - color.b,color.a);
638
638
  } else {
639
639
  gl_FragColor = color;
640
640
  }
641
- }`,setup:(i,s)=>{i.uniform1i(s.uInvert,o.invert?1:0),i.uniform1i(s.uAlpha,o.alphaOnly?1:0)}});break;case"Blur":{let i=HS(o.blur),s=`precision highp float;
641
+ }`,setup:(i,s)=>{i.uniform1i(s.uInvert,o.invert?1:0),i.uniform1i(s.uAlpha,o.alphaOnly?1:0)}});break;case"Blur":{let i=GS(o.blur),s=`precision highp float;
642
642
  uniform sampler2D uTexture;
643
643
  uniform vec2 uTexSize;
644
644
  uniform vec2 uDir;
@@ -1024,7 +1024,7 @@ vec3 lin = pow(color.rgb, vec3(2.2));
1024
1024
  lin = clamp(lin * pow(2.0, uExposure) + vec3(uOffset), 0.0, 1.0);
1025
1025
  color.rgb = pow(lin, vec3(1.0 / (max(0.01, uGamma) * 2.2)));
1026
1026
  gl_FragColor = color;
1027
- }`,setup:(i,s)=>{i.uniform1f(s.uExposure,o.exposure),i.uniform1f(s.uOffset,o.offset),i.uniform1f(s.uGamma,o.gamma)}});break}return r}function GS(n){return{source:`precision highp float;
1027
+ }`,setup:(i,s)=>{i.uniform1f(s.uExposure,o.exposure),i.uniform1f(s.uOffset,o.offset),i.uniform1f(s.uGamma,o.gamma)}});break}return r}function XS(n){return{source:`precision highp float;
1028
1028
  uniform sampler2D uTexture;
1029
1029
  varying vec2 vTexCoord;
1030
1030
  uniform mat4 uColorMatrix;
@@ -1034,14 +1034,14 @@ vec4 color = texture2D(uTexture, vTexCoord);
1034
1034
  color *= uColorMatrix;
1035
1035
  color += uConstants;
1036
1036
  gl_FragColor = color;
1037
- }`,setup:(e,t)=>{e.uniformMatrix4fv(t.uColorMatrix,!1,new Float32Array([n[0],n[1],n[2],n[3],n[5],n[6],n[7],n[8],n[10],n[11],n[12],n[13],n[15],n[16],n[17],n[18]])),e.uniform4f(t.uConstants,n[4],n[9],n[14],n[19])}}}var Ra=class{gl;programs=new Map;cache=new WeakMap;quadBuffer=null;vertexShader=null;disposed=!1;constructor(e){this.gl=e}getFilteredTexture(e,t,r,o,i){if(this.disposed||r<=0||o<=0)return null;let s=`${r}x${o}|${Oi(i)}`,a=this.cache.get(e);return a&&a.sig===s&&a.source===t?a.outTex:(a&&(this.gl.deleteTexture(a.sourceTex),this.gl.deleteTexture(a.outTex)),this.runChain(e,t,r,o,i,s))}runChain(e,t,r,o,i,s){let a=this.gl,l=pp(i,r,o);if(!l.length)return null;let u=a.getParameter(a.VIEWPORT),c=a.isEnabled(a.BLEND),h=a.getParameter(a.CURRENT_PROGRAM),d=a.getParameter(a.FRAMEBUFFER_BINDING),f=a.getParameter(a.ARRAY_BUFFER_BINDING),m=a.getParameter(a.TEXTURE_BINDING_2D),p=a.getParameter(a.VERTEX_ARRAY_BINDING);a.bindVertexArray(null),a.disable(a.BLEND),a.viewport(0,0,r,o);let b=a.createTexture();if(!b)return null;a.bindTexture(a.TEXTURE_2D,b),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,t);let g=()=>{let M=a.createTexture();return M?(a.bindTexture(a.TEXTURE_2D,M),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,r,o,0,a.RGBA,a.UNSIGNED_BYTE,null),M):null},x=g(),S=g(),w=a.createFramebuffer(),y=a.createFramebuffer();if(!x||!S||!w||!y)return null;let v=this.ensureQuad(),R=b,P=x,T=w;for(let M of l){let k=this.ensureProgram(M.source);if(!k)break;a.useProgram(k.program),a.bindFramebuffer(a.FRAMEBUFFER,T),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,P,0),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,R),a.uniform1i(k.uniforms.uTexture,0),k.uniforms.uStepW&&a.uniform1f(k.uniforms.uStepW,1/r),k.uniforms.uStepH&&a.uniform1f(k.uniforms.uStepH,1/o),M.setup(a,k.uniforms),a.bindBuffer(a.ARRAY_BUFFER,v),a.enableVertexAttribArray(k.aPosition),a.vertexAttribPointer(k.aPosition,2,a.FLOAT,!1,0,0),a.drawArrays(a.TRIANGLE_STRIP,0,4),R=P,T===w?(P=S,T=y):(P=x,T=w)}let C=R;a.bindVertexArray(p),a.bindFramebuffer(a.FRAMEBUFFER,d),a.viewport(u[0],u[1],u[2],u[3]),c&&a.enable(a.BLEND),a.useProgram(h),a.bindBuffer(a.ARRAY_BUFFER,f),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,m),a.deleteFramebuffer(w),a.deleteFramebuffer(y);let E=C===x?S:x;return a.deleteTexture(E),a.bindTexture(a.TEXTURE_2D,C),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR_MIPMAP_LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.generateMipmap(a.TEXTURE_2D),a.bindTexture(a.TEXTURE_2D,m),this.cache.set(e,{sig:s,source:t,sourceTex:b,outTex:C}),C}ensureQuad(){let e=this.gl;return this.quadBuffer||(this.quadBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,1]),e.STATIC_DRAW)),this.quadBuffer}ensureProgram(e){let t=this.programs.get(e);if(t)return t;let r=this.gl;if(!this.vertexShader){let h=r.createShader(r.VERTEX_SHADER);if(!h)return null;r.shaderSource(h,mp),r.compileShader(h),this.vertexShader=h}let o=this.vertexShader,i=r.createShader(r.FRAGMENT_SHADER),s=r.createProgram();if(!i||!s)return null;if(r.shaderSource(i,e),r.compileShader(i),r.attachShader(s,o),r.attachShader(s,i),r.linkProgram(s),r.deleteShader(i),!r.getProgramParameter(s,r.LINK_STATUS))return console.warn("[gpuImageFilters] program link failed:",r.getProgramInfoLog(s)),r.deleteProgram(s),null;let l={},u=r.getProgramParameter(s,r.ACTIVE_UNIFORMS);for(let h=0;h<u;h++){let d=r.getActiveUniform(s,h);if(!d)continue;let f=d.name.replace(/\[0\]$/,"");l[f]=r.getUniformLocation(s,d.name)}let c={program:s,aPosition:r.getAttribLocation(s,"aPosition"),uniforms:l};return this.programs.set(e,c),c}invalidate(){this.cache=new WeakMap,this.programs.clear(),this.vertexShader=null,this.quadBuffer=null}dispose(){this.disposed=!0;let e=this.gl;for(let t of this.programs.values())e.deleteProgram(t.program);this.programs.clear(),this.invalidate()}};var Pa=class{constructor(e,t){this.gl=e;this.epoch=t}gl;epoch;fxPainter=null;filterChain=null;get fx(){return this.fxPainter||(this.fxPainter=new Ma(this.epoch)),this.fxPainter}get filters(){return this.filterChain||(this.filterChain=new Ra(this.gl)),this.filterChain}invalidate(){this.fxPainter?.invalidate(this.gl),this.filterChain?.invalidate()}invalidateTextDerivedBakes(){this.fxPainter?.invalidateTextDerivedBakes(this.gl)}};var XS=[.914,.914,.914,1],ka=class{host;sources;text;frame={bakeDeadline:0,bakeMore:!1,animationActive:!1};settle;flatFrame=!0;shadow;psd;stroke;gpu;isolator=null;isolating=!1;blender=null;blendWrapNode=null;clipContentNode=null;cropGhostPreDrawn=null;puzzleBox=null;stencilClip=new Ta;maskGpu=new Ea;constructor(e,t,r){this.host=e,this.sources=t,this.text=r,this.gpu=new Pa(e.gl,e.renderEpoch),this.shadow=new ga(e),this.settle=new In(()=>this.host.requestRenderAll()),this.stroke=new wa(e,this.frame,this.settle),this.psd=new Ca(e,this.frame,this.gpu,()=>this.puzzleBox,this.settle,this.compositeFxBlended,this.sources)}beginFrame(e){this.frame.animationActive=!1,this.frame.bakeDeadline=e+lp(this.host.isExporting()),this.frame.bakeMore=!1,this.stencilClip.resetFrame(),this.maskGpu.activeThisFrame=!1}noteVptChange(){this.settle.noteInteraction()}noteExternalInteraction(){this.settle.noteInteraction()}groupMask(e){let t=e.raw.mask;if(!t||t.disabled===!0||typeof t.src!="string")return null;let r=this.sources.maskTexture(t.src);if(!r)return null;let o=t.defaultColor===255,i=e.dims.x,s=e.dims.y,a=(Number(t.offsetX)||0)-i/2,l=(Number(t.offsetY)||0)-s/2,u=(Number(t.width)||0)*(Number(t.scaleX)||1),c=(Number(t.height)||0)*(Number(t.scaleY)||1);if(!(u>0)||!(c>0))return null;let h=e.matrix,d=this.host.canvasEl.width,f=this.host.canvasEl.height,m=[d/this.host.dpr,0,0,-f/this.host.dpr,0,f/this.host.dpr],p=ve(this.host.viewportTransform),b=ve(h),g=[1/u,0,0,1/c,-a/u,-l/c];if(!p||!b)return null;let x=j(g,j(b,j(p,m))),S=[x[0],x[1],0,x[2],x[3],0,x[4],x[5],1];return{tex:r,maskInv:S,coversHost:o}}renderPuzzleChildren(e,t){if(!(e instanceof le)){t();return}let r=this.puzzleBox;this.puzzleBox={hw:e.dims.x/2,hh:e.dims.y/2};try{t()}finally{this.puzzleBox=r}}puzzleClampedQuad(e,t,r,o=0,i=0){return _n(this.puzzleBox,e,t,r,o,i)}renderIsolatedGroup(e,t){let r=this.host.gl;this.flatFrame=!1,this.isolator||(this.isolator=new ma),this.host.batchOrder.flushAll();let o=()=>{if(e instanceof J)for(let s of e.children)this.renderSceneNode(s);else this.renderSceneNodeContentOnly(e)};if(!this.isolator.begin(r,this.host.canvasEl.width,this.host.canvasEl.height)){this.renderPuzzleChildren(e,o);return}this.isolating=!0;let i=1;if(e instanceof J){let s=()=>{for(let a of e.children)a.setIsolation(!0);o();for(let a of e.children)a.setIsolation(!1)};this.renderPuzzleChildren(e,s),i=e.renderOpacity}else o();this.host.batchOrder.flushAll(),this.isolating=!1,this.isolator.end(r),r.viewport(0,0,this.host.canvasEl.width,this.host.canvasEl.height),this.isolator.composite(r,i,t)}renderSceneNodeContentOnly(e){this.renderSceneNode(e)}renderBlendedNode(e,t){let r=this.host.gl;this.flatFrame=!1,this.blender||(this.blender=new Qo),this.host.batchOrder.flushAll();let o=this.host.canvasEl.width,i=this.host.canvasEl.height,s=this.blendWrapNode;this.blendWrapNode=e;try{if(!this.blender.begin(r,o,i)){this.renderSceneNode(e);return}this.renderSceneNode(e),this.host.batchOrder.flushAll(),this.blender.end(r),r.viewport(0,0,o,i),this.blender.composite(r,t)}finally{this.blendWrapNode=s}}compositeFxBlended=(e,t)=>{let r=this.host.gl;this.flatFrame=!1,this.blender||(this.blender=new Qo),this.host.batchOrder.flushAll();let o=this.host.canvasEl.width,i=this.host.canvasEl.height;if(!this.blender.begin(r,o,i)){t();return}t(),this.host.batchOrder.flushAll(),this.blender.end(r),r.viewport(0,0,o,i),this.blender.composite(r,e)};renderSceneNode(e){if(e.visible&&e!==this.host.warpSessionTarget){if(this.blendWrapNode!==e){let t=pa(e.raw.globalCompositeOperation);if(t!==null){this.renderBlendedNode(e,t);return}}if(e instanceof J){if(this.stencilClip.begin(e,this.host,{rasterMask:ko(e)!==null})){let o=this.groupMask(e);!this.isolating&&((e.raw.opacity??1)<1||!!o)?this.renderIsolatedGroup(e,o):this.renderPuzzleChildren(e,()=>{for(let s of e.children)this.renderSceneNode(s)}),this.stencilClip.end(this.host);return}let t=this.groupMask(e);if(!this.isolating&&((e.raw.opacity??1)<1||!!t)){this.renderIsolatedGroup(e,t);return}this.renderPuzzleChildren(e,()=>{for(let o of e.children)this.renderSceneNode(o)});return}if(this.clipContentNode!==e&&Uc(e)){if(this.preDrawCropGhost(e),this.stencilClip.begin(e,this.host,{rasterMask:!1})){let r=this.isolating;this.clipContentNode=e,this.isolating=!0,this.renderSceneNodeContentOnly(e),this.clipContentNode=null,this.isolating=r,this.stencilClip.end(this.host),this.cropGhostPreDrawn=null;return}let t=this.clipContentNode;this.clipContentNode=e,this.renderSceneNodeContentOnly(e),this.clipContentNode=t,this.cropGhostPreDrawn=null;return}if(!this.isolating&&ko(e)){let t=this.groupMask(e);if(t){this.renderIsolatedGroup(e,t);return}}if(e.isTextType){if(this.text.renderTextPathBackground(e,this.host.zoom*this.host.dpr),typeof e.raw.renderSrc=="string"&&e!==this.host.editingNode){let i=e.imageEl?this.host.textures.get(e.imageEl):null;if(i){let s=e.bitmapRect,a=s.x!==0||s.y!==0?j(e.matrix,[1,0,0,1,s.x,s.y]):e.matrix;s.angle&&(a=j(a,At({angle:-s.angle}))),this.shadow.render(e),this.psd.render(e,"below");let l=Po(e.raw);this.host.batch.pushQuad(a,s.w,s.h,[1,1,1,e.renderOpacity*l],i,[0,0,1,1],null,e),this.psd.render(e,"above");return}if(this.sources.isImagePending(e)){this.renderImagePlaceholder(e);return}}let t=Oh(e.raw);if(t&&e!==this.host.editingNode){this.text.renderWarpedText(e,t);return}let r=Zn(e.raw);if(r&&e!==this.host.editingNode){this.text.renderPsdWarpedText(e,r);return}let o=Xe(e.raw);if(o&&e!==this.host.editingNode){this.text.renderArcText(e,o,this.host.zoom*this.host.dpr);return}this.shadow.render(e),this.psd.render(e,"below"),this.text.renderTextGlyphs(e,this.host.zoom*this.host.dpr,e===this.host.editingNode),this.psd.render(e,"above");return}if(e.isShapeType){let t=e.strokeDecl,r=e.shapeMesh;if(r||t){this.shadow.render(e),this.psd.render(e,"below");let o=()=>{this.stroke.render(e)};if(t){let i=t.paintFirst==="stroke";if(i&&o(),r){let s=this.paintParams(e);s?this.host.meshBatch.pushMesh(e.matrix,[1,1,1,e.renderOpacity],r.verts,r.triangles,s,e):this.host.meshBatch.pushMesh(e.matrix,e.drawColor,r.verts,r.triangles,void 0,e)}i||o()}else if(r){let i=this.paintParams(e);i?this.host.meshBatch.pushMesh(e.matrix,[1,1,1,e.renderOpacity],r.verts,r.triangles,i,e):this.host.meshBatch.pushMesh(e.matrix,e.drawColor,r.verts,r.triangles,void 0,e)}}this.psd.render(e,"above");return}if(e.isLineType){this.shadow.render(e),this.stroke.render(e);return}if(e instanceof ae){this.renderMaskNode(e);return}if(e instanceof ie&&e.paintSource){this.renderAnimatedNode(e);return}if(e.isImageType&&!e.imageEl){this.sources.isImagePending(e)&&this.renderImagePlaceholder(e);return}this.renderImageFamily(e)}}renderImageFamily(e){if(this.shadow.render(e),this.psd.render(e,"below"),e.isSolidType){let a=e.strokeDecl?.paintFirst==="stroke";a&&this.stroke.render(e);let l=this.paintParams(e);if(l){this.host.batch.pushPaintQuad(e.matrix,e.dims.x,e.dims.y,l,e.renderOpacity,this.solidRadii(e)),a||this.stroke.render(e);return}}let t=this.imageTextureOf(e);e===this.host.cropGhostNode&&e!==this.cropGhostPreDrawn&&e.imageEl&&t&&this.drawCropGhost(e,t);let r=e.cropRect,o=r&&e.imageEl?[r.sx/e.imageEl.naturalWidth,r.sy/e.imageEl.naturalHeight,(r.sx+r.sw)/e.imageEl.naturalWidth,(r.sy+r.sh)/e.imageEl.naturalHeight]:[0,0,1,1],i=bd(e.raw),s=i===1?e.drawColor:[1,1,1,e.renderOpacity*i];this.host.batch.pushQuad(e.matrix,e.dims.x,e.dims.y,s,t,o,this.quadRadii(e),e),e.isSolidType&&e.strokeDecl?.paintFirst!=="stroke"&&this.stroke.render(e),this.psd.render(e,"above")}imageTextureOf(e){let t=e.isImageType&&!(e instanceof ie)?ho(e.raw.filters):[],r=t.length&&e.imageEl?this.gpu.filters.getFilteredTexture(e,e.imageEl,e.imageEl.naturalWidth||e.imageEl.width,e.imageEl.naturalHeight||e.imageEl.height,t):null,o=t.length?e.imageEl:this.sources.svgRasterSource(e,this.host.zoom,this.host.dpr);return r??(o?this.host.textures.get(o):null)}drawCropGhost(e,t){if(!e.imageEl)return;let r=e.dims,o=e.raw.cropX??0,i=e.raw.cropY??0,s=e.imageEl.naturalWidth,a=e.imageEl.naturalHeight,l={x:-r.x/2-o+s/2,y:-r.y/2-i+a/2},u=j(e.matrix,[1,0,0,1,l.x,l.y]);this.host.batch.pushQuad(u,s,a,[1,1,1,.5*e.renderOpacity],t)}preDrawCropGhost(e){if(e!==this.host.cropGhostNode||!e.imageEl)return;let t=this.imageTextureOf(e);t&&(this.cropGhostPreDrawn=e,this.drawCropGhost(e,t))}renderMaskNode(e){let t=e.clipImageRaw;if(e.clipDynamicKind){e.tickDynamicClip(performance.now());let f=e.dynamicClipSource();if(!f||!e.imageEl){this.sources.isImagePending(e)&&this.renderImagePlaceholder(e);return}this.psd.render(e,"below");let m=f;this.host.textures.update(m);let p=this.host.textures.get(m),b=this.host.textures.get(e.imageEl),g=m,x=g.videoWidth||g.width||0,S=g.videoHeight||g.height||0;if(p&&b&&x&&S){let w=this.maskGpu.render(e,this.host.gl,this.host.zoom,this.host.dpr,{maskTex:b,clipTex:p,clipW:x,clipH:S});if(w){this.flatFrame=!1;let y=this.puzzleClampedQuad(e,w.w,w.h);y&&this.host.batch.pushQuad(y.matrix,y.w,y.h,[1,1,1,e.renderOpacity],w.tex,y.uv,null,e),this.psd.render(e,"above"),e.clipAnimating&&(this.frame.animationActive=!0);return}}return}if(!t){if(this.shadow.render(e),!e.imageEl){this.sources.isImagePending(e)&&this.renderImagePlaceholder(e);return}this.psd.render(e,"below");let f=this.sources.svgRasterSource(e,this.host.zoom,this.host.dpr)??e.imageEl,m=this.host.textures.get(f),p=this.puzzleClampedQuad(e,e.dims.x,e.dims.y);p&&this.host.batch.pushQuad(p.matrix,p.w,p.h,[1,1,1,e.renderOpacity],m,p.uv,null,e),this.psd.render(e,"above");return}let r=e.clipImageEl;if(!r||!e.imageEl){this.sources.isImagePending(e)&&this.renderImagePlaceholder(e);return}let o=ho(t.filters),i=r,s=i.naturalWidth||i.videoWidth||i.width||t.width||0,a=i.naturalHeight||i.videoHeight||i.height||t.height||0,l=o.length?this.gpu.filters.getFilteredTexture(e,r,s,a,o):this.host.textures.get(r),u=this.host.textures.get(e.imageEl);if(!l||!u||!s||!a)return;let c=this.maskGpu.render(e,this.host.gl,this.host.zoom,this.host.dpr,{maskTex:u,clipTex:l,clipW:s,clipH:a});if(!c)return;this.psd.render(e,"below");let h=this.puzzleClampedQuad(e,c.w,c.h),d=e===this.host.maskCropNode?.5:1;h&&this.host.batch.pushQuad(h.matrix,h.w,h.h,[1,1,1,d*e.renderOpacity],c.tex,h.uv,null,e),this.psd.render(e,"above")}renderAnimatedNode(e){let t=e.tick(performance.now()),r=e.paintSource;if(!r)return;let o=this.host.textures.get(r);o&&t&&this.host.textures.update(r),this.shadow.render(e),this.psd.render(e,"below"),this.host.batch.pushQuad(e.matrix,e.dims.x,e.dims.y,e.drawColor,o,[0,0,1,1],this.quadRadii(e),e),this.psd.render(e,"above"),e.animating&&(this.frame.animationActive=!0)}renderImagePlaceholder(e){let{x:t,y:r}=e.dims;if(!(t>0)||!(r>0))return;let o=e.renderOpacity,i=ee(e.raw.fill),s=i[3]>0?i:XS;this.host.batch.pushQuad(e.matrix,t,r,[s[0],s[1],s[2],s[3]*o],null,[0,0,1,1],this.quadRadii(e),e)}quadRadii(e){if(e.isSolidType){let t=it(e.raw,e.dims.x,e.dims.y);return t?[t.rx,t.ry]:null}if(e.isImageType&&!(e instanceof ie)){let t=br(e.raw,e.dims.x,e.dims.y);return t?[t,t]:null}return null}solidRadii(e){let t=it(e.raw,e.dims.x,e.dims.y);return t?[t.rx,t.ry]:null}paintParams(e){let t=e.fillPaint;if(!t)return null;if(t.kind==="gradient"){let r=this.host.gradientRamps.get(t.decl);return r?{kind:"gradient",decl:t.decl,inv:ve(fi(t.decl,e.dims.x,e.dims.y)),tex:r}:null}if(t.kind==="pattern"){let r=this.sources.patternTexture(t.decl.src);return r?{kind:"pattern",inv:ve(bi(t.decl,e.dims.x,e.dims.y)),tex:r.tex,size:[r.w,r.h],repeat:_u(t.decl.repeat)}:null}return null}invalidateGlResources(){this.shadow.invalidate(),this.psd.invalidate(),this.stroke.invalidate(),this.maskGpu.invalidate(),this.isolator&&(this.isolator.dispose(this.host.gl),this.isolator=null),this.blender&&(this.blender.dispose(this.host.gl),this.blender=null),this.gpu.invalidate()}invalidateTextDerivedBakes(){this.shadow.invalidate(),this.psd.invalidate(),this.stroke.invalidate(),this.gpu.invalidateTextDerivedBakes()}};var $c=n=>{let e=n.mask;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.disabled===!0||typeof t.src!="string"||!t.src)return null;let r=Number(t.width),o=Number(t.height);return!(r>0)||!(o>0)?null:{src:t.src,width:r,height:o,left:typeof t.left=="number"?t.left:void 0,top:typeof t.top=="number"?t.top:void 0,offsetX:typeof t.offsetX=="number"?t.offsetX:void 0,offsetY:typeof t.offsetY=="number"?t.offsetY:void 0,defaultColor:typeof t.defaultColor=="number"?t.defaultColor:void 0,crossOrigin:typeof t.crossOrigin=="string"?t.crossOrigin:null}},bp=n=>n.startsWith("resource/")?n.replace("resource/","/resource/"):n,gp=n=>{for(let e=0;e<n.length;e+=4){let t=n[e],r=n[e+1],o=n[e+2];t===r&&r===o?n[e+3]=t:t===0&&r===0&&o===0&&(n[e+3]=0)}},xp=(n,e,t)=>({x:typeof n.offsetX=="number"&&Number.isFinite(n.offsetX)?n.offsetX:(n.left??e)-e,y:typeof n.offsetY=="number"&&Number.isFinite(n.offsetY)?n.offsetY:(n.top??t)-t}),yp=(n,e,t,r,o,i)=>{if(r<=0&&t<=0&&i+r>=e&&o+t>=n)return[];let s=[];return r>0&&s.push([0,0,n,r]),t>0&&s.push([0,0,t,e]),r+i<e&&s.push([0,r+i,n,e-i-r]),t+o<n&&s.push([t+o,0,n-o-t,e]),s},Sp=(n,e,t,r,o,i)=>{let s=Math.max(1,Math.round(e.x)),a=Math.max(1,Math.round(e.y)),l=document.createElement("canvas");l.width=t.width,l.height=t.height;let u=l.getContext("2d",{willReadFrequently:!0}),c=document.createElement("canvas");c.width=s,c.height=a;let h=c.getContext("2d");if(!u||!h)return null;try{u.drawImage(r,0,0);let f=u.getImageData(0,0,t.width,t.height);gp(f.data),u.putImageData(f,0,0)}catch{return null}let d=xp(t,o,i);if(h.drawImage(l,d.x,d.y),t.defaultColor===255){h.fillStyle="#000000";for(let[f,m,p,b]of yp(s,a,d.x,d.y,t.width,t.height))h.fillRect(f,m,p,b)}return h.globalCompositeOperation="source-in",h.drawImage(n,0,0),c},vp=n=>new Promise(e=>{n.toBlob(t=>{if(!t){e(null);return}let r=URL.createObjectURL(t),o=new Image;o.onload=()=>{URL.revokeObjectURL(r),e(o)},o.onerror=()=>{URL.revokeObjectURL(r),e(null)},o.src=r})});var Jo={create(n,e){if(typeof document<"u"){let t=document.createElement("canvas");return t.width=n,t.height=e,t}if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(n,e);throw new Error("Canvas is not available")}},Dn=n=>{let e=n.getContext("2d");if(!e)throw new Error("Failed to get canvas context");return e},ei=n=>{n.width=0,n.height=0},wp=n=>{"close"in n?n.close():ei(n)};var Aa=640,ti=80,Tp=async(n,e={})=>{let{parseGIF:t,decompressFrame:r}=await import("gifuct-js"),o=t(n),i=null,s=(o.frames??[]).map(E=>E.image?(!E.gce&&i&&(E.gce=i),i=null,r(E,o.gct,!0)):(E.gce&&(i=E.gce),null)).filter(E=>E!==null);if(!s||!s.length)throw new Error("No frames available");let a=o.lsd,l=a?.width??s[0].dims.width,u=a?.height??s[0].dims.height,c=Math.max(l,u),h=c>Aa?Aa/c:1,d=Math.max(1,Math.round(l*h)),f=Math.max(1,Math.round(u*h)),m=s.reduce((E,M)=>E+(M.delay||0),0)/1e3,p=s.length>ti?s.slice(0,ti):s,b=p.reduce((E,M)=>E+(M.delay||0),0),g=p.length>0?b/p.length:100,x=e.canvasFactory??Jo,S=x.create(1,1),w=Dn(S),y=x.create(l,u),v=Dn(y),R=x.create(d*p.length,f),P=Dn(R);if(!w||!v||!P)throw new Error("Failed to get canvas context");y.width=l,y.height=u,R.width=d*p.length,R.height=f;let T,C;return p.forEach((E,M)=>{T?.disposalType===2?v.clearRect(T.dims.left,T.dims.top,T.dims.width,T.dims.height):T?.disposalType===3&&C&&v.putImageData(C,0,0),C=E.disposalType===3?v.getImageData(0,0,l,u):void 0,S.width=E.dims.width,S.height=E.dims.height;let k=w.createImageData(E.dims.width,E.dims.height);k.data.set(E.patch),w.putImageData(k,0,0),v.drawImage(S,E.dims.left,E.dims.top),P.drawImage(y,0,0,l,u,d*M,0,d,f),T=E}),ei(S),ei(y),{canvas:R,frameWidth:d,framesLength:p.length,delay:g,frameDelays:p.map(E=>E.delay||100),duration:m}},Ep=(n,e,t,r,o={})=>{if(!n.length)throw new Error("No frames available");let i=o.canvasFactory??Jo,s=Math.max(e,t),a=s>Aa?Aa/s:1,l=Math.max(1,Math.round(e*a)),u=Math.max(1,Math.round(t*a)),c=i.create(e,t),h=Dn(c),d=i.create(l*Math.min(n.length,ti),u),f=Dn(d);if(!h||!f)throw new Error("Failed to get canvas context");c.width=e,c.height=t,d.width=l*Math.min(n.length,ti),d.height=u;let m=n.slice(0,ti);m.forEach((b,g)=>{let x=h.createImageData(e,t);x.data.set(new Uint8ClampedArray(b)),h.putImageData(x,0,0),f.drawImage(c,0,0,e,t,l*g,0,l,u)}),ei(c);let p=m.map((b,g)=>Math.max(1,r[g]??100));return{canvas:d,frameWidth:l,framesLength:m.length,delay:p.reduce((b,g)=>b+g,0)/p.length,frameDelays:p,duration:p.reduce((b,g)=>b+g,0)/1e3}};var zS=[137,80,78,71,13,10,26,10],jr=n=>{let e=new Uint8Array(n);if(e.length<8||!zS.every((r,o)=>e[o]===r))return!1;let t=new DataView(n);for(let r=8;r+12<=e.length;){let o=t.getUint32(r),i=r+o+12;if(i>e.length)return!1;let s=String.fromCharCode(...e.subarray(r+4,r+8));if(s==="acTL")return o===8&&t.getUint32(r+8)>0;if(s==="IDAT"||s==="IEND")return!1;r=i}return!1},YS=async n=>jr(await n.arrayBuffer()),US=async n=>{try{let e=await fetch(n);return e.ok&&jr(await e.arrayBuffer())}catch{return!1}},Cp=async(n,e={})=>{if(!jr(n))throw new Error("Not an animated PNG");let{default:t}=await import("upng-js"),r=t.decode(n);return r.frames=r.frames.slice(0,80),Ep(t.toRGBA8(r),r.width,r.height,r.frames.map(o=>o.delay),e)};var Mp=640,$S=80,Na=100,jc=(n,e)=>String.fromCharCode(n[e],n[e+1],n[e+2],n[e+3]),Vc=n=>{if(n.byteLength<12)return!1;let e=new Uint8Array(n,0,12);return jc(e,0)==="RIFF"&&jc(e,8)==="WEBP"},Pp=n=>{if(!Vc(n))return!1;let e=new Uint8Array(n,0,Math.min(n.byteLength,512)),t=12;for(;t+8<=e.length;){let r=jc(e,t);if(r==="VP8X")return t+8<e.length&&(e[t+8]&2)!==0;if(r==="ANIM"||r==="ANMF")return!0;if(r==="VP8 "||r==="VP8L")return!1;let o=e[t+4]|e[t+5]<<8|e[t+6]<<16|e[t+7]<<24;if(o<0)return!1;t+=8+o+o%2}return!1},jS=async n=>Pp(await n.slice(0,512).arrayBuffer()),VS=async n=>{try{let e=await fetch(n,{headers:{Range:"bytes=0-511"}});return e.ok?Pp(await e.arrayBuffer()):!1}catch{return!1}},kp=(n,e,t,r={})=>{let o=(r.canvasFactory??Jo).create(n*t,e);o.width=n*t,o.height=e;let i=Dn(o);if(!i)throw new Error("Failed to get canvas context");return{canvas:o,ctx:i}},Ap=(n,e)=>{let t=Math.max(n,e),r=t>Mp?Mp/t:1;return{width:Math.max(1,Math.round(n*r)),height:Math.max(1,Math.round(e*r))}},Rp=async(n,e={})=>{let t=URL.createObjectURL(new Blob([n],{type:"image/webp"}));try{let r=await new Promise((l,u)=>{let c=new Image;c.onload=()=>l(c),c.onerror=()=>u(new Error("Failed to load WebP")),c.src=t}),{width:o,height:i}=Ap(r.naturalWidth,r.naturalHeight),{canvas:s,ctx:a}=kp(o,i,1,e);return a.drawImage(r,0,0,o,i),{canvas:s,frameWidth:o,framesLength:1,delay:Na,frameDelays:[Na],duration:0}}finally{URL.revokeObjectURL(t)}},Np=async(n,e={})=>{let t=globalThis.ImageDecoder;if(!t||!await t.isTypeSupported("image/webp"))return Rp(n,e);let r=new t({data:n,type:"image/webp",preferAnimation:!0});try{await r.tracks.ready;let o=r.tracks.selectedTrack;if(!o?.frameCount||o.frameCount<2)return Rp(n,e);let i=Math.min(o.frameCount,$S),s=await r.decode({frameIndex:0}),{width:a,height:l}=Ap(s.image.displayWidth,s.image.displayHeight),{canvas:u,ctx:c}=kp(a,l,i,e),h=[];for(let d=0;d<i;d++){let{image:f}=d===0?s:await r.decode({frameIndex:d}),m=typeof f.duration=="number"&&f.duration>0?f.duration/1e3:Na;h.push(m),c.drawImage(f,a*d,0,a,l),f.close()}return{canvas:u,frameWidth:a,framesLength:i,delay:h[0]||Na,frameDelays:h,duration:h.reduce((d,f)=>d+f,0)/1e3}}finally{r.close()}};var qc=async(n,e={})=>{if(Vc(n))return Np(n,e);if(jr(n))return Cp(n,e);let t=new Uint8Array(n,0,Math.min(6,n.byteLength)),r=String.fromCharCode(...t);if(r==="GIF87a"||r==="GIF89a")return Tp(n,e);throw new Error("Unsupported animated image (expected GIF, animated WebP or APNG)")};var La=class{host;patternSources=new Map;patternLoads=new Map;patternFailed=new Set;gifSprites=new Map;animatedNodes=new Set;pendingImageNodes=new WeakSet;patternTextures=new Map;maskTextures=new Map;svgRasters=new WeakMap;svgMaxRasterPx;loadGeneration=0;constructor(e){this.host=e;let t=Number(e.gl.getParameter(e.gl.MAX_TEXTURE_SIZE))||4096;this.svgMaxRasterPx=Math.min(t,4096)}async loadGroupMasks(e){let t=new Set,r=s=>{let a=s.raw.mask;a&&a.disabled!==!0&&typeof a.src=="string"&&!this.maskTextures.has(a.src)&&t.add(a.src)},o=s=>{for(let a of s)a instanceof J?(r(a),o(a.children)):ko(a)&&r(a)};if(o(e),t.size===0)return;let i=this.host.gl;await Promise.all([...t].map(async s=>{try{let a=await Je(s,"anonymous"),l=Ae(i,a);if(!l)return;this.maskTextures.set(s,l)}catch{console.warn("[engine] group mask skipped (load failed):",s)}}))}async loadAnimatedSources(e){let t=++this.loadGeneration,r=a=>this.host.document.nodes.some(l=>l===a||l instanceof J&&l.containsDeep(a)),o=a=>this.loadGeneration===t&&e.includes(a)&&r(a),i=e.filter(a=>a instanceof ae&&!!a.clipDynamicKind&&!a.hasDynamicClip);for(let a of i)(async()=>{let l=a.clipImageRaw;try{let u=a.clipDynamicKind==="gif"?await this.loadGifSprite(l.src):await this.loadVideoElement(l.src,l.crossOrigin,l.loop===!0);if(!o(a))return;a.clipDynamicKind==="gif"?a.attachClipSprite(u,()=>this.host.requestRenderAll()):a.attachClipVideo(u,()=>this.host.requestRenderAll()),this.dynamicClipMasks.add(a),this.host.requestRenderAll()}catch(u){if(console.warn("[engine] mask dynamic clip skipped (load failed):",u.message),!o(a))return;try{a.clipImageEl=await Je(l.src,l.crossOrigin)}catch{}this.host.requestRenderAll()}})();let s=e.filter(a=>a instanceof ie);s.length!==0&&(await Promise.all(s.map(async a=>{let l=a.raw.src;try{let u=a.animatedKind==="gif"?await this.loadGifSprite(l):await this.loadVideoElement(l,a.raw.crossOrigin,a.raw.loop===!0);if(!o(a))return;a.animatedKind==="gif"?a.attachSprite(u,()=>this.host.requestRenderAll()):a.attachVideo(u,()=>this.host.requestRenderAll()),this.animatedNodes.add(a),this.pendingImageNodes.delete(a),this.host.requestRenderAll()}catch(u){if(console.warn("[engine] animated source skipped (load failed):",u.message),!o(a))return;try{a.imageEl=await Je(l,a.raw.crossOrigin)}catch{}this.pendingImageNodes.delete(a),this.host.requestRenderAll()}})),this.host.document.refreshHitIndex())}loadGifSprite(e){if(this.disposed)return Promise.reject(new Error("SourceManager disposed"));let t=this.gifSprites.get(e);if(t)return t;let r=fetch(e).then(async o=>{if(!o.ok)throw new Error(`GIF load failed: ${o.status} ${o.statusText}`);let i=await o.arrayBuffer(),s=this.host.decodeAnimated;if(s)try{return await s(i)}catch(a){console.warn("[engine] injected animated decoder failed, falling back:",a.message)}return qc(i)}).catch(o=>{throw this.gifSprites.delete(e),o});return this.gifSprites.set(e,r),r}loadVideoElement(e,t,r,o=0){return new Promise((i,s)=>{let a=document.createElement("video");a.crossOrigin=t||"anonymous",a.muted=!0,a.playsInline=!0,a.setAttribute("playsinline","true"),a.setAttribute("webkit-playsinline","true"),a.loop=r,a.preload="auto",a.addEventListener("loadeddata",()=>i(a),{once:!0}),a.addEventListener("error",()=>{a.removeAttribute("src"),a.load(),o<2?setTimeout(()=>{this.loadVideoElement(e,t,r,o+1).then(i,s)},120):s(new Error(`[engine] video load failed: ${e.slice(0,80)}`))},{once:!0}),a.src=e})}releaseAnimatedSources(){this.loadGeneration++;for(let e of[...this.animatedNodes])this.releaseAnimatedNode(e);for(let e of this.dynamicClipMasks)e.detachDynamicClip();this.dynamicClipMasks.clear()}dynamicClipMasks=new Set;releaseAnimatedNode(e){if(!this.animatedNodes.has(e))return;this.animatedNodes.delete(e);let t=e.paintSource;e.detach(),t&&this.host.textures.remove(t)}async loadPatternSources(e){let t=new Set;for(let r of e){let o=r.fillPaint;o?.kind==="pattern"&&t.add(o.decl.src);for(let i of _r(Mt(r.raw.effects)))t.add(i)}if(t.size!==0){for(let r of t)this.patternFailed.delete(r);await Promise.all([...t].map(r=>this.loadPatternSource(r)))}}loadPatternSource(e){let t=this.patternLoads.get(e);if(t)return t;let r=Je(e,"anonymous").then(o=>{this.patternSources.set(e,o),Ph(e,o)}).catch(o=>{this.patternFailed.add(e),console.warn("[engine] pattern source skipped (load failed):",o.message)}).finally(()=>{this.patternLoads.delete(e),this.host.requestRenderAll()});return this.patternLoads.set(e,r),r}patternSourcesReady(e){let t=!0;for(let r of e)this.patternSources.has(r)||this.patternFailed.has(r)||(t=!1,this.loadPatternSource(r));return t}patternTexture(e){let t=this.patternTextures.get(e);if(t)return t;let r=this.patternSources.get(e);if(!r||!r.naturalWidth)return null;let o=Ae(this.host.gl,r,{mipmap:!0,repeat:!0});if(!o)return null;let i={tex:o,w:r.naturalWidth,h:r.naturalHeight};return this.patternTextures.set(e,i),i}maskTexture(e){return this.maskTextures.get(e)??null}markImagePending(e){this.pendingImageNodes.add(e)}isImagePending(e){return this.pendingImageNodes.has(e)}svgRasterSource(e,t,r){let o=e.imageEl;if(!o)return null;if(!os(e.raw.src))return o;let i=o.naturalWidth||o.width,s=o.naturalHeight||o.height;if(!(i>0)||!(s>0))return o;let a=e.worldScale,l=this.svgRasters.get(e);l&&(l.source!==o||l.sourceSrc!==o.src)&&(this.svgRasters.delete(e),this.host.textures.remove(l.canvas),l=void 0);let u=wd({w:i,h:s},{w:i*Math.abs(a.x)*t*r,h:s*Math.abs(a.y)*t*r},l?.factor??1,this.svgMaxRasterPx);if(!u.needsRaster)return l?.canvas??o;if(u.factor===1)return l&&(this.svgRasters.delete(e),this.host.textures.remove(l.canvas)),o;let c=Td(o,u.factor);return l&&this.host.textures.remove(l.canvas),this.svgRasters.set(e,{canvas:c,factor:u.factor,source:o,sourceSrc:o.src}),c}svgRasterFactorOf(e){return this.svgRasters.get(e)?.factor??null}async applyImageMask(e,t){let r=$c(e.raw);if(!r)return!1;try{let o=await Je(bp(r.src),r.crossOrigin),i=e.dims;if(!(i.x>0)||!(i.y>0))return!1;let s=Sp(t,i,r,o,e.raw.left??0,e.raw.top??0);if(!s)return!1;let a=await vp(s);return a?(e.imageEl=a,!0):!1}catch(o){return console.warn("[engine] image mask bake skipped (load failed):",o.message),!1}}async reloadNodeImage(e){let t=e.raw.src,r=e.imageEl,o=this.svgRasters.get(e);o&&(this.svgRasters.delete(e),this.host.textures.remove(o.canvas));try{let i=await Je(t,e.raw.crossOrigin);return e.imageEl=i,await this.applyImageMask(e,i),r&&this.host.textures.remove(r),this.host.document.refreshHitIndex(),this.host.requestRenderAll(),e.imageEl}catch(i){return console.warn("[engine] image reload skipped (load failed):",i.message),null}}async reloadMaskClipImage(e){let t=e.clipImageRaw;if(!t||e.clipDynamicKind)return null;let r=e.clipImageEl;try{let o=await Je(t.src,t.crossOrigin??null);return e.clipImageEl=o,r&&this.host.textures.remove(r),this.host.document.refreshHitIndex(),this.host.requestRenderAll(),o}catch(o){return console.warn("[engine] mask clipImage reload skipped (load failed):",o.message),null}}async loadImages(e){let t=s=>s instanceof ie?!1:s instanceof ae?!s.imageEl||!!s.clipImageRaw&&!s.clipDynamicKind&&!s.clipImageEl:s.isTextType?typeof s.raw.renderSrc=="string"&&!s.imageEl:s.isImageType&&!s.imageEl,r=e.filter(t);if(r.length===0)return;let o=new Map,i=!1;await Promise.all(r.map(async s=>{let a=s.isTextType&&typeof s.raw.renderSrc=="string",l=a?s.raw.renderSrc:s.raw.src,u=()=>{this.pendingImageNodes.delete(s),this.host.requestRenderAll()};try{if(s instanceof ae){if(!s.imageEl){let d=o.get(l);d||(d=await Je(l,s.raw.crossOrigin),o.set(l,d)),s.imageEl=d,i=!0}let h=s.clipImageRaw;if(h&&!s.clipDynamicKind&&!s.clipImageEl){let d=h.src,f=o.get(d);f||(f=await Je(d,h.crossOrigin),o.set(d,f)),s.clipImageEl=f}u();return}if(a){let h=o.get(l);h||(h=await Je(l,s.raw.crossOrigin),o.set(l,h)),s.imageEl=h,i=!0,u();return}let c=o.get(l);c||(c=await Je(l,s.raw.crossOrigin),o.set(l,c)),s.imageEl=c,await this.applyImageMask(s,c),i=!0,u()}catch(c){console.warn("[engine] image node skipped (load failed):",c.message),u()}})),i&&this.host.document.refreshHitIndex()}invalidateGlTextures(){for(let{tex:e}of this.patternTextures.values())this.host.gl.deleteTexture(e);this.patternTextures.clear()}dispose(){this.disposed=!0,this.loadGeneration++;for(let e of this.gifSprites.values())e.then(t=>wp(t.canvas),()=>{});this.gifSprites.clear();for(let{tex:e}of this.patternTextures.values())this.host.gl.deleteTexture(e);this.patternTextures.clear(),this.patternSources.clear(),this.patternLoads.clear(),this.patternFailed.clear()}disposed=!1};function Kc(n){let e=[],t=r=>{for(let o of r)e.push(o),o instanceof J&&t(o.children)};return t([...n]),e}async function Qc(n,e,t){for(let r of n)r instanceof ie?r.paintSource||e.markImagePending(r):r instanceof ae?(!r.imageEl||r.clipImageRaw&&!r.clipImageEl)&&e.markImagePending(r):r.isTextType&&typeof r.raw.renderSrc=="string"?r.imageEl||e.markImagePending(r):r.isImageType&&!r.imageEl&&e.markImagePending(r);t(),await e.loadImages(n),await e.loadGroupMasks(n),await e.loadAnimatedSources(n),await e.loadPatternSources(n),t()}var He=2,qS=4*He,KS=384,QS=(n,e,t,r,o,i)=>{let s=1/0,a=-1/0,l=1/0,u=-1/0,c=8;for(let h=0;h<=c;h++){let d=r+(o-r)*h/c;for(let f=0;f<=c;f++){let m=e+(t-e)*f/c,p=Ni(n,m,d),b=i[0]*p.x+i[2]*p.y+i[4],g=i[1]*p.x+i[3]*p.y+i[5];s=Math.min(s,b),a=Math.max(a,b),l=Math.min(l,g),u=Math.max(u,g)}}return{minX:s,maxX:a,minY:l,maxY:u}},Zc=(n,e,t=null)=>{let r=n.textLayout,o=Number(n.raw.fontSize)||40,i=typeof n.raw.width=="number"?n.raw.width:r.width,s=typeof n.raw.height=="number"?n.raw.height:r.height;if(!(i>0)||!(s>0))return null;let a=o*.6,l=Math.max(r.width,i,o),u=Math.max(s,o),c=t?Tr(t):0,h=Math.ceil(l+a*2+c*2),d=Math.ceil(u+a*2+c*2),f=h*He,m=d*He;if(!(f>0)||!(m>0)||f>8192||m>8192)return null;let p=ml(e,i,s);if(!p)return null;let b=document.createElement("canvas");b.width=f,b.height=m;let g=b.getContext("2d",{willReadFrequently:!0});if(!g)return null;g.setTransform(He,0,0,He,f/2,m/2),n.raw.vertical===!0?Gi(g,n):po(g,n),bo(g,n,t);let x=g.getImageData(0,0,f,m),S=new Uint32Array(x.data.buffer),w=f,y=0,v=m,R=0,P=!1;for(let ke=0;ke<m;ke++)for(let Ee=0;Ee<f;Ee++)(S[ke*f+Ee]>>>24&255)>10&&(P=!0,Ee<w&&(w=Ee),Ee>y&&(y=Ee),ke<v&&(v=ke),ke>R&&(R=ke));if(!P)return null;let T=w,C=v,E=y+1-w,M=R+1-v,k=(h-i)/2*He,A=(d-s)/2*He,O=[He,0,0,He,k,A],F=(T-k)/He,W=(T+E-k)/He,z=(C-A)/He,_=(C+M-A)/He,D=F/i,I=W/i,G=z/s,$=_/s,V=QS(p,D,I,G,$,O),H=Math.floor(V.minX)-1,Y=Math.floor(V.minY)-1,X=Math.max(1,Math.ceil(V.maxX+1)-H),Z=Math.max(1,Math.ceil(V.maxY+1)-Y);if(X>8192||Z>8192)return null;let B=pl(p,0,0,i,s,F,z,W,_,E,M,[He,0,0,He,k-H,A-Y],qS,KS);if(!B)return null;let q=g.createImageData(X,Z),U=new Uint32Array(q.data.buffer),oe=new Uint8Array(X*Z),ne=(ke,Ee)=>{let ue=Math.min(E-1,Math.max(0,ke)),xe=Math.min(M-1,Math.max(0,Ee)),pe=Math.floor(ue),Te=Math.floor(xe),rt=Math.min(E-1,pe+1),Ke=Math.min(M-1,Te+1),Ue=ue-pe,bt=xe-Te,gt=S[(C+Te)*f+(T+pe)],xt=S[(C+Te)*f+(T+rt)],yt=S[(C+Ke)*f+(T+rt)],St=S[(C+Ke)*f+(T+pe)],Bn=gt>>>24&255,Wn=xt>>>24&255,ii=yt>>>24&255,si=St>>>24&255;if(Bn<=10&&Wn<=10&&ii<=10&&si<=10)return 0;let $e=(vt,Ha,Ga)=>vt+(Ha-vt)*Ga,fr=Math.round($e($e(gt&255,xt&255,Ue),$e(St&255,yt&255,Ue),bt)),Qr=Math.round($e($e(gt>>>8&255,xt>>>8&255,Ue),$e(St>>>8&255,yt>>>8&255,Ue),bt)),ai=Math.round($e($e(gt>>>16&255,xt>>>16&255,Ue),$e(St>>>16&255,yt>>>16&255,Ue),bt));return Math.round($e($e(Bn,Wn,Ue),$e(si,ii,Ue),bt))<<24|ai<<16|Qr<<8|fr};for(let ke=0;ke+1<B.rows;ke++)for(let Ee=0;Ee+1<B.columns;Ee++){let ue=ke*B.columns+Ee,xe=ue+1,pe=ue+B.columns,Te=pe+1,rt=B.docXs[ue],Ke=B.docYs[ue],Ue=B.docXs[xe],bt=B.docYs[xe],gt=B.docXs[Te],xt=B.docYs[Te],yt=B.docXs[pe],St=B.docYs[pe],Bn=Math.max(0,Math.floor(Math.min(rt,Ue,gt,yt))),Wn=Math.min(X-1,Math.ceil(Math.max(rt,Ue,gt,yt))),ii=Math.max(0,Math.floor(Math.min(Ke,bt,xt,St))),si=Math.min(Z-1,Math.ceil(Math.max(Ke,bt,xt,St)));for(let $e=ii;$e<=si;$e++)for(let fr=Bn;fr<=Wn;fr++){let Qr=$e*X+fr;if(oe[Qr])continue;let ai=bl(fr+.5,$e+.5,rt,Ke,Ue,bt,gt,xt,yt,St);if(!ai)continue;oe[Qr]=1;let{s:Yt,t:vt}=ai,Ha=(1-Yt)*(1-vt)*B.sourceXs[ue]+Yt*(1-vt)*B.sourceXs[xe]+Yt*vt*B.sourceXs[Te]+(1-Yt)*vt*B.sourceXs[pe],Ga=(1-Yt)*(1-vt)*B.sourceYs[ue]+Yt*(1-vt)*B.sourceYs[xe]+Yt*vt*B.sourceYs[Te]+(1-Yt)*vt*B.sourceYs[pe];U[Qr]=ne(Ha,Ga)}}let de=document.createElement("canvas");de.width=X,de.height=Z;let Pe=de.getContext("2d");if(!Pe)return null;Pe.putImageData(q,0,0);let De=(H+X/2)/He-h/2,nt=(Y+Z/2)/He-d/2;return{canvas:de,logicalW:X/He,logicalH:Z/He,offsetX:De,offsetY:nt}};var Ip=new Map,ni=(n,e)=>{let t=n.worldScale,r=_p(n);return e*Math.max(t.x*Math.abs(r.x),t.y*Math.abs(r.y),1e-6)},_p=n=>{let e=Number(n.raw.textScaleX)||1,t=Number(n.raw.textScaleY)||1;return{x:e,y:t}},ur=n=>{let{x:e,y:t}=_p(n);return e===1&&t===1?n.matrix:j(n.matrix,[e,0,0,t,0,0])},Vr=(n,e)=>{let t=Ip.get(n);if(!t){let r=ee(n);t=[r[0],r[1],r[2],r[3]],Ip.set(n,t)}return[t[0],t[1],t[2],t[3]*e[3]]},Ia=class{gl;batch;glyphAtlas;warpBakes=new WeakMap;psdWarpBakes=new WeakMap;arcBakes=new WeakMap;textDashBakes=new WeakMap;scrollBakes=new WeakMap;highlightBakes=new WeakMap;pathBgBakes=new WeakMap;patternSources=null;constructor(e,t,r){this.gl=e,this.batch=t,this.glyphAtlas=r}attachPatternSources(e){this.patternSources=e}patternSourcesPending(e){if(!this.patternSources||!e)return!1;let t=_r(e);return t.length>0&&!this.patternSources.patternSourcesReady(t)}invalidateNodeBakes(e){for(let t of[this.warpBakes,this.psdWarpBakes,this.arcBakes,this.textDashBakes,this.scrollBakes,this.highlightBakes,this.pathBgBakes]){let r=t.get(e);r?.tex&&this.gl.deleteTexture(r.tex),t.delete(e)}}renderWarpedText(e,t){let r=Mt(e.raw.effects,{text:!0}),o=[e.raw.type,e.raw.textTransform,e.raw.text,e.raw.warpStrength,e.raw.fontSize,e.raw.fontFamily,e.raw.width,e.raw.height,e.raw.fill,e.raw.stroke,e.raw.strokeWidth,JSON.stringify(e.raw.styles??null),JSON.stringify(e.raw.paragraph??null),r?wn(r):""].join(";"),i=this.warpBakes.get(e);if(this.patternSourcesPending(r)){i&&this.batch.pushQuad(e.matrix,i.w,i.h,[1,1,1,e.renderOpacity],i.tex);return}if(i&&i.sig!==o&&(this.gl.deleteTexture(i.tex),i=void 0),!i){let s=Cl(e,t,r);if(!s){this.warpBakes.set(e,void 0);return}let a=Ae(this.gl,s.canvas);if(!a)return;i={sig:o,tex:a,w:s.logicalW,h:s.logicalH},this.warpBakes.set(e,i)}this.batch.pushQuad(e.matrix,i.w,i.h,[1,1,1,e.renderOpacity],i.tex)}renderPsdWarpedText(e,t){let r=Mt(e.raw.effects,{text:!0}),o=[e.raw.type,e.raw.text,JSON.stringify(e.raw.psdWarp??null),e.raw.fontSize,e.raw.fontFamily,e.raw.fontWeight,e.raw.fontStyle,e.raw.width,e.raw.height,e.raw.lineHeight,e.raw.charSpacing,e.raw.vertical===!0?1:0,e.raw.fill,e.raw.stroke,e.raw.strokeWidth,JSON.stringify(e.raw.styles??null),JSON.stringify(e.raw.paragraph??null),r?wn(r):""].join(";"),i=this.psdWarpBakes.get(e),s=a=>{let l=a.offX!==0||a.offY!==0?j(e.matrix,At({translateX:a.offX,translateY:a.offY})):e.matrix;this.batch.pushQuad(l,a.w,a.h,[1,1,1,e.renderOpacity],a.tex)};if(this.patternSourcesPending(r)){i&&s(i);return}if(i&&i.sig!==o&&(this.gl.deleteTexture(i.tex),i=void 0),!i){let a=Zc(e,t,r);if(!a){this.psdWarpBakes.set(e,void 0);return}let l=Ae(this.gl,a.canvas);if(!l)return;i={sig:o,tex:l,w:a.logicalW,h:a.logicalH,offX:a.offsetX,offY:a.offsetY},this.psdWarpBakes.set(e,i)}s(i)}renderArcText(e,t,r){let o=Mt(e.raw.effects,{text:!0}),i=!!o&&(o.dropShadows.length>0||o.solidFills.length>0||o.strokes.length>0);if(Pu()&&!i){this.renderArcGlyphs(e,t,r);return}let s=Ht(ni(e,r)),a=[e.raw.type,e.raw.textTransform,e.raw.text,e.raw.curvature,e.raw.circleSize,e.raw.circleStartAngle,e.raw.circleSweep,e.raw.circleEccentricity,e.raw.circleDirection,e.raw.fontSize,e.raw.fontFamily,e.raw.fontWeight,e.raw.fontStyle,e.raw.lineHeight,e.raw.textAlign,e.raw.fill,e.raw.stroke,e.raw.strokeWidth,e.raw.strokeVisible,e.raw.paintFirst,JSON.stringify(e.raw.styles??null),o?wn(o):"",s].join(";"),l=this.arcBakes.get(e);if(this.patternSourcesPending(o)){l&&this.batch.pushQuad(e.matrix,l.w,l.h,[1,1,1,e.renderOpacity],l.tex);return}if(l&&l.sig!==a&&(this.gl.deleteTexture(l.tex),l=void 0),!l){let u=Ml(e,t,o,s);if(!u){this.arcBakes.set(e,void 0);return}let c=Ae(this.gl,u.canvas);if(!c)return;l={sig:a,tex:c,w:u.logicalW,h:u.logicalH},this.arcBakes.set(e,l)}this.batch.pushQuad(e.matrix,l.w,l.h,[1,1,1,e.renderOpacity],l.tex)}renderArcGlyphs(e,t,r){let o=Et(e.textLayout,e.raw,e.textStyle.lineHeight??1.16),i=Ht(ni(e,r)),s=e.textStyle,a=e.textStroke,l=e.raw.strokeVisible===!0,u=e.paintFirst==="stroke",c=typeof e.raw.fill=="string"?e.raw.fill:"",h=e.matrix,d=[1,1,1,e.renderOpacity];for(let f of o.chars){let m=e.textLayout.lines[f.line]?.charStyles[f.index],p=gn(s,m),b=typeof m?.fill=="string"&&m.fill?m.fill:c,g=l?Oe(a,m):null,x=f.x-o.contentOffsetX,S=f.y-o.contentOffsetY,w=Math.cos(f.rotation),y=Math.sin(f.rotation),v=R=>{if(R){if(!g||g.width<=0)return}else if(!b)return;let{rs:P,scale:T}=ra(p.fontSize,i),C=this.glyphAtlas.get(p,P,f.char,R?g:null);if(!C)return;let E=C.wPx/T,M=C.hPx/T,k=(C.inkLeftPx-C.advancePx/2-C.padPx)/T+E/2,A=-(C.ascentPx+C.padPx)/T+M/2,O=Vr(R?g.color:b,d),F=j(h,j([1,0,0,1,x,S],j([w,y,-y,w,0,0],[1,0,0,1,k,A])));this.batch.pushQuad(F,E,M,O,this.glyphAtlas.textureOf(C),[C.u0,C.v0,C.u1,C.v1])};u?(v(!0),v(!1)):(v(!1),v(!0))}}renderTextGlyphs(e,t,r=!1){if(Er(e.raw)?.enabled&&!r){this.renderScrollText(e,t);return}let i=e.textLayout,s=e.textStroke,a=!!e.raw.fill||i.lines.some(u=>u.charStyles.some(c=>c?.fill)),l=Ht(ni(e,t));this.renderTextBackgrounds(e),this.renderTextDecorations(e,"underline"),this.renderTextHighlight(e,l),s&&e.paintFirst==="stroke"?(this.renderGlyphPass(e,"stroke",l),a&&this.renderGlyphPass(e,"fill",l)):(a&&this.renderGlyphPass(e,"fill",l),s&&this.renderGlyphPass(e,"stroke",l)),this.renderTextDecorations(e,"overline"),this.renderTextDecorations(e,"linethrough")}renderScrollText(e,t){this.renderTextBackgrounds(e),this.renderTextDecorations(e,"underline");let r=Ht(ni(e,t)),o=e.raw,i=[o.text,o.width,o.height,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.lineHeight,o.charSpacing,o.textAlign,o.splitByGrapheme,o.vertical,typeof o.fill=="string"?o.fill:"gradient",o.stroke,o.strokeWidth,Array.isArray(o.strokeDashArray)?o.strokeDashArray.join(","):"",o.strokeDashOffset,o.paintFirst,JSON.stringify(o.styles??null),o.scrollDirection,JSON.stringify(o.paragraph??null),e.scrollOffset.toFixed(3),e.textTotalWidth.toFixed(3),r].join(";"),s=this.scrollBakes.get(e);if(s&&s.sig!==i&&(this.gl.deleteTexture(s.tex),s=void 0),!s){let a=Xh(e,r,e.scrollOffset);if(!a){this.scrollBakes.set(e,void 0);return}let l=Ae(this.gl,a.canvas);if(!l)return;s={sig:i,tex:l,w:a.logicalW,h:a.logicalH},this.scrollBakes.set(e,s)}this.batch.pushQuad(ur(e),s.w,s.h,[1,1,1,e.renderOpacity],s.tex),this.renderTextDecorations(e,"overline"),this.renderTextDecorations(e,"linethrough")}renderTextPathBackground(e,t){let r=Ii(e);if(!r)return;let o=Ht(ni(e,t)),i=`${r.sigBase};${o}`,s=this.pathBgBakes.get(e);if(s&&s.sig!==i&&(this.gl.deleteTexture(s.tex),s=void 0),!s){let a=vh(r,o);if(!a){this.pathBgBakes.set(e,void 0);return}let l=Ae(this.gl,a.canvas);if(!l)return;s={sig:i,tex:l,w:a.logicalW,h:a.logicalH},this.pathBgBakes.set(e,s)}this.batch.pushQuad(e.matrix,s.w,s.h,[1,1,1,e.renderOpacity],s.tex)}renderTextBackgrounds(e){let t=e.textLayout,r=e.renderOpacity,o=ur(e),i=typeof e.raw.textBackgroundColor=="string"?e.raw.textBackgroundColor:"";if(!(!i&&!t.lines.some(s=>s.charStyles.some(a=>a?.textBackgroundColor))))for(let s of t.lines){let a=-t.width/2+s.leftOffset,l=e.contentTopY+s.top,u=m=>s.charStyles[m]?.textBackgroundColor??i,c=0,h=0,d=u(0),f=()=>{if(!d||h<=0)return;let m=a+s.boxes[c].left,p=ee(d),b=[p[0],p[1],p[2],p[3]*r],g=j(o,[1,0,0,1,m+h/2,l+s.implHeight/2]);this.batch.pushQuad(g,h,s.implHeight,b,null)};for(let m=0;m<s.graphemes.length;m++){let p=u(m);p!==d?(f(),c=m,h=s.boxes[m].width,d=p):h+=s.boxes[m].kernedWidth}f()}}renderTextDecorations(e,t){let r=e.textLayout,o=e.decorationDefaults,i=[1,1,1,e.renderOpacity],s=ur(e);for(let a of r.lines){let l=hl(a,t,o);if(l.length===0)continue;let u=-r.width/2+a.leftOffset,c=e.contentTopY+a.baseline;for(let h of l){let d=u+h.x+h.width/2,f=c+h.y+h.thickness/2;this.batch.pushQuad(j(s,[1,0,0,1,d,f]),h.width,h.thickness,Vr(h.color,i),null)}}}textHasDashStroke(e){return Array.isArray(e.raw.strokeDashArray)&&e.raw.strokeDashArray.length>0}renderTextDashStroke(e,t){let r=e.textLayout,o=e.textStyle,i=e.raw.strokeDashArray,s=e.textStroke,a=s?s.width:0;if(!s||a<=0)return;let l=Number(e.raw.charSpacing)||0,u=$t(e.raw.textAlign),c=e.raw.textAlign===fe.DISPERSE,h=Number(e.raw.textOffsetY)||0,d=ih(h,e.textStyle,r.lines),f=a+4+Math.ceil(d),m=Math.ceil(r.width+f*2),p=Math.ceil(r.height+f*2);if(!(m>0)||!(p>0)||m>8192||p>8192)return;let b=[e.raw.text,r.width,r.height,s.color,s.width,i.join(","),Number(e.raw.strokeDashOffset)||0,t,l,u,e.raw.textAlign,e.raw.vertical===!0,h,JSON.stringify(e.raw.paragraph??null)].join(";"),g=this.textDashBakes.get(e);if(g&&g.sig!==b&&(this.gl.deleteTexture(g.tex),g=void 0),!g){let x=document.createElement("canvas");x.width=Math.ceil(m*t),x.height=Math.ceil(p*t);let S=x.getContext("2d");if(!S)return;S.setTransform(t,0,0,t,0,0),S.textBaseline="alphabetic",S.setLineDash(i),S.lineDashOffset=Number(e.raw.strokeDashOffset)||0,S.lineJoin=typeof e.raw.strokeLineJoin=="string"?e.raw.strokeLineJoin:"miter",S.lineCap=typeof e.raw.strokeLineCap=="string"?e.raw.strokeLineCap:"butt",S.miterLimit=Number(e.raw.strokeMiterLimit)||4;let w=r.width/2+f,y=r.height/2+f+e.contentTopY,v=e.raw.vertical===!0,R=0;for(let T of r.lines){let C=-r.width/2+T.leftOffset,E=y+T.baseline;if(v){T.prefix&&Tt(S,T,w+C,E,{stroke:Oe(s,T.charStyles[0])});let D=Vt(T,C,E,o,l);for(let I=0;I<D.length;I++){let G=Oe(s,T.charStyles[I]);if(!G||G.width<=0)continue;let $=fn(o,T.charStyles[I]);S.font=Me($,$.fontSize),S.lineWidth=G.width,S.strokeStyle=G.color,qt(S,{...D[I],y:D[I].y+wt(h,$.fontSize,R+I)},"strokeText")}R+=T.graphemes.length;continue}let M=ro(e.raw.textAlign)&&T.graphemes.some(D=>ao.test(D)),k="",A=T.prefix?Tt(S,T,w+C,E,{stroke:Oe(s,T.charStyles[0])}):0,O=0,F="",W=null,z,_=D=>{if(!k)return;let I=W;I&&I.width>0&&(S.font=F,S.lineWidth=I.width,S.strokeStyle=I.color,S.strokeText(k,w+C+A,E+O)),k="",D<T.boxes.length&&(A=T.boxes[D].left)};for(let D=0;D<T.graphemes.length;D++){let I=T.charStyles[D],$=I!==void 0&&(I.fontSize!==void 0||I.fontFamily!==void 0||I.fontWeight!==void 0||I.fontStyle!==void 0)&&I?{...o,fontSize:I.fontSize??o.fontSize,fontFamily:I.fontFamily??o.fontFamily,fontWeight:I.fontWeight??o.fontWeight,fontStyle:I.fontStyle??o.fontStyle}:o,V=Me($,$.fontSize),H=Oe(s,I),Y=I?.fill??"",X=W;k&&(V!==F||H?.color!==X?.color||H?.width!==X?.width||Y!==z)&&_(D),k||(F=V,W=H,z=Y,O=wt(h,$.fontSize,R+D)),k+=T.graphemes[D],(l||h!==0||(u||c)&&/[ \t\r]/.test(T.graphemes[D])||M)&&_(D+1)}_(T.graphemes.length),R+=T.graphemes.length}let P=Ae(this.gl,x);if(!P)return;g={sig:b,tex:P,w:m,h:p},this.textDashBakes.set(e,g)}this.batch.pushQuad(ur(e),g.w,g.h,[1,1,1,e.renderOpacity],g.tex)}renderTextHighlight(e,t){let r=e.raw;if(!Array.isArray(r.texts)||r.texts.length===0||r.vertical===!0)return;let o=e.textLayout,i=[r.text,o.width,o.height,r.fontSize,r.fontFamily,r.fontWeight,r.fontStyle,r.lineHeight,r.charSpacing,r.textAlign,r.splitByGrapheme,JSON.stringify(r.styles??null),e.dims.y,JSON.stringify(r.texts??null),JSON.stringify(r.paragraph??null),t].join(";"),s=this.highlightBakes.get(e);if(s&&s.sig!==i&&(this.gl.deleteTexture(s.tex),s=void 0),!s){let a=Jn(r.text??"",o,r.texts,e.contentTopY,e.textStyle.fontSize);if(!a){this.highlightBakes.set(e,void 0);return}let l=Sh(a,o,e.contentTopY,t);if(!l)return;let u=Ae(this.gl,l.canvas);if(!u)return;s={sig:i,tex:u,w:l.logicalW,h:l.logicalH,centerY:e.contentTopY-a.padY+l.logicalH/2},this.highlightBakes.set(e,s)}this.batch.pushQuad(j(ur(e),[1,0,0,1,0,s.centerY]),s.w,s.h,[1,1,1,e.renderOpacity],s.tex)}renderGlyphPass(e,t,r){if(t==="stroke"&&this.textHasDashStroke(e)){this.renderTextDashStroke(e,r);return}let o=e.textLayout,i=e.textStyle,s=ur(e),a=e.renderOpacity,l=e.fillPaint,u=l?.kind==="gradient"?[l.decl.stops[0].color[0],l.decl.stops[0].color[1],l.decl.stops[0].color[2],l.decl.stops[0].color[3]*a]:e.drawColor,c=!!e.raw.fill,h=e.textStroke,d=[1,1,1,a],f=e.raw.vertical===!0,m=f&&i.charSpacing?i.fontSize*i.charSpacing/1e3:0,p=Number(e.raw.textOffsetY)||0,b=0;for(let g of o.lines){let x=-o.width/2+g.leftOffset,S=e.contentTopY+g.baseline;if(g.prefix)if(t==="stroke"){let y=Oe(h,g.charStyles[0]);y&&y.width>0&&this.pushPrefixGlyphs(e,g.prefix,x,S,y,Vr(y.color,d),r)}else{let y=g.charStyles[0]?.fill;(y||c)&&this.pushPrefixGlyphs(e,g.prefix,x,S,null,y?Vr(y,u):u,r)}let w=0;for(let y=0;y<g.graphemes.length;y++){let v=g.charStyles[y],R,P=null;if(t==="stroke"){if(P=Oe(h,v),!P)continue;R=Vr(P.color,d)}else{let _=v?.fill;if(!_&&!c)continue;R=_?Vr(_,u):u}let C=v!==void 0&&(v.fontSize!==void 0||v.fontFamily!==void 0||v.fontWeight!==void 0||v.fontStyle!==void 0)&&v?{...i,fontSize:v.fontSize??i.fontSize,fontFamily:v.fontFamily??i.fontFamily,fontWeight:v.fontWeight??i.fontWeight,fontStyle:v.fontStyle??i.fontStyle}:i,E=wt(p,C.fontSize,b+y),{rs:M,scale:k}=ra(C.fontSize,r),A=this.glyphAtlas.get(C,M,g.graphemes[y],P);if(!A)continue;let O=g.boxes[y],F=A.wPx/k,W=A.hPx/k,z;if(f){let _=g.graphemes[y],D=qn(_),I=C.fontSize,G=Kn(_,O,m);if(D==="latin"||D==="bracket"){let V=x+w+(D==="latin"?O.kernedWidth-O.width:0)+(A.inkLeftPx-A.padPx)/k,H=S+E-(A.ascentPx+A.padPx)/k;z=j(s,[1,0,0,1,V+F/2,H+W/2])}else{let $=x+w+un(I),V=S+E+yr(D,O,I),H=(A.inkLeftPx-A.padPx)/k+F/2,Y=W/2-(A.ascentPx+A.padPx)/k;z=j(s,j([1,0,0,1,$,V],j([0,-1,1,0,0,0],[1,0,0,1,H,Y])))}w+=G}else{let D=x+O.left+(A.inkLeftPx-A.padPx)/k,I=S+E-(A.ascentPx+A.padPx)/k;z=j(s,[1,0,0,1,D+F/2,I+W/2])}this.batch.pushQuad(z,F,W,R,this.glyphAtlas.textureOf(A),[A.u0,A.v0,A.u1,A.v1])}b+=g.graphemes.length}}pushPrefixGlyphs(e,t,r,o,i,s,a){let l=Nt(t.text),u=r;for(let c=0;c<l.length;c++){let{rs:h,scale:d}=ra(t.style.fontSize,a),f=this.glyphAtlas.get(t.style,h,l[c],i);if(f){let m=f.wPx/d,p=f.hPx/d,b=u+(f.inkLeftPx-f.padPx)/d,g=o-(f.ascentPx+f.padPx)/d;this.batch.pushQuad(j(ur(e),[1,0,0,1,b+m/2,g+p/2]),m,p,s,this.glyphAtlas.textureOf(f),[f.u0,f.v0,f.u1,f.v1])}u+=t.advances[c]??0}}};var Dp=(n,e,t)=>{let r=n.createRenderbuffer();if(!r)throw new Error("Unable to allocate export stencil");return n.bindRenderbuffer(n.RENDERBUFFER,r),n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH24_STENCIL8,e,t),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,r),r},Fp=n=>{let e=n.getParameter(n.RENDERBUFFER_BINDING),t=n.isEnabled(n.STENCIL_TEST),r=n.getParameter(n.STENCIL_CLEAR_VALUE),o=n.getParameter(n.COLOR_WRITEMASK),i=n.isEnabled(n.SCISSOR_TEST),s=[n.STENCIL_FUNC,n.STENCIL_REF,n.STENCIL_VALUE_MASK,n.STENCIL_WRITEMASK,n.STENCIL_FAIL,n.STENCIL_PASS_DEPTH_FAIL,n.STENCIL_PASS_DEPTH_PASS].map(l=>n.getParameter(l)),a=[n.STENCIL_BACK_FUNC,n.STENCIL_BACK_REF,n.STENCIL_BACK_VALUE_MASK,n.STENCIL_BACK_WRITEMASK,n.STENCIL_BACK_FAIL,n.STENCIL_BACK_PASS_DEPTH_FAIL,n.STENCIL_BACK_PASS_DEPTH_PASS].map(l=>n.getParameter(l));return()=>{n.bindRenderbuffer(n.RENDERBUFFER,e),n.clearStencil(r),n.colorMask(o[0],o[1],o[2],o[3]);for(let[l,u]of[[n.FRONT,s],[n.BACK,a]])n.stencilFuncSeparate(l,u[0],u[1],u[2]),n.stencilMaskSeparate(l,u[3]),n.stencilOpSeparate(l,u[4],u[5],u[6]);t?n.enable(n.STENCIL_TEST):n.disable(n.STENCIL_TEST),i?n.enable(n.SCISSOR_TEST):n.disable(n.SCISSOR_TEST)}},Op=n=>{n.disable(n.SCISSOR_TEST),n.disable(n.STENCIL_TEST),n.colorMask(!0,!0,!0,!0),n.stencilMask(255),n.clearStencil(0),n.clear(n.COLOR_BUFFER_BIT|n.STENCIL_BUFFER_BIT)};var Bp=(n,e)=>{let t=n.multiplier&&n.multiplier>0?n.multiplier:1,r=n.width,o=n.height;if(!(r>0)||!(o>0)||!(e>0))return null;let i=Math.max(1,Math.round(r*t)),s=Math.max(1,Math.round(o*t)),a=Math.max(i,s);if(a>e){let u=e/a;i=Math.max(1,Math.floor(i*u)),s=Math.max(1,Math.floor(s*u))}let l=Math.min(i/r,s/o);return{outWidth:i,outHeight:s,multiplier:l}},Jc=(n,e)=>{let t=e.outWidth/n.width,r=e.outHeight/n.height;return[t,0,0,r,-n.left*t,-n.top*r]},Wp=(n,e)=>Zr(Jc(n,e),e.outWidth,e.outHeight,1),_a=(n,e,t)=>{let r=new Uint8ClampedArray(e*t*4);for(let o=0;o<t;o++){let i=(t-1-o)*e*4,s=o*e*4;for(let a=0;a<e*4;a+=4){let l=n[i+a+3];if(l===0){r[s+a]=0,r[s+a+1]=0,r[s+a+2]=0,r[s+a+3]=0;continue}let u=c=>Math.min(255,Math.round(c*255/l));r[s+a]=u(n[i+a]),r[s+a+1]=u(n[i+a+1]),r[s+a+2]=u(n[i+a+2]),r[s+a+3]=l}}return r};var Hp=n=>typeof n.fenceSync=="function"&&typeof n.clientWaitSync=="function"&&typeof n.getBufferSubData=="function",Gp=(n,e)=>new Promise(t=>{let r=performance.now(),o=!0,i=()=>{let s;try{s=n.clientWaitSync(e,o?n.SYNC_FLUSH_COMMANDS_BIT:0,0)}catch{return t()}if(o=!1,s===n.ALREADY_SIGNALED||s===n.CONDITION_SATISFIED||s===n.WAIT_FAILED||performance.now()-r>1e3)return t();setTimeout(i,4)};i()}),Da=class{constructor(e){this.host=e}host;exportToPixels(e){let t=this.renderAndStage(e,!1);return t?{width:t.outWidth,height:t.outHeight,data:_a(t.raw,t.outWidth,t.outHeight)}:null}async exportToPixelsAsync(e){let t=await this.stageAndDrain(e);return t?{width:t.outWidth,height:t.outHeight,data:_a(t.raw,t.outWidth,t.outHeight)}:null}async exportRawPixelsAsync(e){let t=await this.stageAndDrain(e);return t?{width:t.outWidth,height:t.outHeight,raw:t.raw}:null}async stageAndDrain(e){let t=this.renderAndStage(e,!0);if(!t)return null;if(!t.stagedReadback)return{outWidth:t.outWidth,outHeight:t.outHeight,raw:t.raw};let r=await this.drainStagedReadback(t.stagedReadback);return r?{outWidth:t.outWidth,outHeight:t.outHeight,raw:r}:null}renderRounds(e,t,r){let o=this.host.gl,i=0;do{this.host.renderer.beginFrame(performance.now()),o.bindFramebuffer(o.FRAMEBUFFER,e),o.clearColor(t[0],t[1],t[2],t[3]),Op(o),this.host.batch.begin(r,this.host.zoom*this.host.dpr),this.host.meshBatch.begin(r);for(let s of this.host.sceneNodes)o.bindFramebuffer(o.FRAMEBUFFER,e),this.host.renderer.renderSceneNode(s);o.bindFramebuffer(o.FRAMEBUFFER,e),this.host.batchOrder.flushAll()}while(this.host.renderer.frame.bakeMore&&++i<64)}renderAndStage(e,t){if(!this.host.exportReady)return null;let r=Bp(e,this.host.capabilities.maxTextureSize);if(!r)return null;let o=this.host.gl,{outWidth:i,outHeight:s}=r,a=e.background??[0,0,0,0],l=i*s*4,u=this.host.bakeKReuseFloor;this.host.bakeKReuseFloor=e.bakeScaleTolerance??0;let c={framebuffer:o.getParameter(o.FRAMEBUFFER_BINDING),viewport:o.getParameter(o.VIEWPORT),clearColor:o.getParameter(o.COLOR_CLEAR_VALUE),program:o.getParameter(o.CURRENT_PROGRAM),activeTexture:o.getParameter(o.ACTIVE_TEXTURE),textureBinding:o.getParameter(o.TEXTURE_BINDING_2D),packBuffer:o.getParameter(o.PIXEL_PACK_BUFFER_BINDING),blendEnabled:o.isEnabled(o.BLEND),blendSrcRgb:o.getParameter(o.BLEND_SRC_RGB),blendDstRgb:o.getParameter(o.BLEND_DST_RGB),blendSrcAlpha:o.getParameter(o.BLEND_SRC_ALPHA),blendDstAlpha:o.getParameter(o.BLEND_DST_ALPHA)},h=Fp(o),d=null,f=o.createTexture(),m=o.createFramebuffer(),p=null,b=new Uint8Array(0),g=null,x=!1;try{if(o.bindTexture(o.TEXTURE_2D,f),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,i,s,0,o.RGBA,o.UNSIGNED_BYTE,null),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindFramebuffer(o.FRAMEBUFFER,m),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,f,0),d=Dp(o,i,s),o.checkFramebufferStatus(o.FRAMEBUFFER)!==o.FRAMEBUFFER_COMPLETE)return null;p=this.host.applyExportViewport(Jc(e,r),i,s);let S=Wp(e,r);if(o.viewport(0,0,i,s),this.renderRounds(m,a,S),o.bindFramebuffer(o.FRAMEBUFFER,m),t&&Hp(o)){let w=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,w),o.bufferData(o.PIXEL_PACK_BUFFER,l,o.STREAM_READ),o.readPixels(0,0,i,s,o.RGBA,o.UNSIGNED_BYTE,0);let y=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);o.flush(),o.bindBuffer(o.PIXEL_PACK_BUFFER,c.packBuffer),g={gl:o,pbo:w,fence:y,byteLength:l},x=!0}else b=new Uint8Array(l),o.readPixels(0,0,i,s,o.RGBA,o.UNSIGNED_BYTE,b)}finally{o.bindFramebuffer(o.FRAMEBUFFER,c.framebuffer),o.viewport(c.viewport[0],c.viewport[1],c.viewport[2],c.viewport[3]),o.clearColor(c.clearColor[0],c.clearColor[1],c.clearColor[2],c.clearColor[3]),o.useProgram(c.program),o.activeTexture(c.activeTexture),o.bindTexture(o.TEXTURE_2D,c.textureBinding&&o.isTexture(c.textureBinding)?c.textureBinding:null),o.bindBuffer(o.PIXEL_PACK_BUFFER,c.packBuffer),c.blendEnabled?o.enable(o.BLEND):o.disable(o.BLEND),o.blendFuncSeparate(c.blendSrcRgb,c.blendDstRgb,c.blendSrcAlpha,c.blendDstAlpha),h(),p?.(),d&&o.deleteRenderbuffer(d),m&&o.deleteFramebuffer(m),f&&o.deleteTexture(f),g&&!x&&(o.deleteBuffer(g.pbo),g.fence&&o.deleteSync(g.fence)),this.host.bakeKReuseFloor=u,this.host.requestRenderAll()}return g?{outWidth:i,outHeight:s,raw:b,stagedReadback:g}:b.length?{outWidth:i,outHeight:s,raw:b,stagedReadback:null}:null}async drainGpuBacklog(){let e=this.host.gl;if(!Hp(e))return;let t=null;try{if(t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0),!t)return;await Gp(e,t)}catch{}finally{t&&e.deleteSync(t)}}async drainStagedReadback(e){let{gl:t,pbo:r,fence:o,byteLength:i}=e;try{if(o&&await Gp(t,o),!this.host.exportReady)return null;let s=new Uint8Array(i),a=t.getParameter(t.PIXEL_PACK_BUFFER_BINDING);return t.bindBuffer(t.PIXEL_PACK_BUFFER,r),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,s),t.bindBuffer(t.PIXEL_PACK_BUFFER,a),s}catch{return null}finally{t.deleteBuffer(r),o&&t.deleteSync(o)}}exportToCanvas(e){let t=this.exportToPixels(e);if(!t)return null;let r=document.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");if(!o)return null;let i=o.createImageData(t.width,t.height);return i.data.set(t.data),o.putImageData(i,0,0),r}exportToDataURL(e,t="image/png",r){let o=this.exportToCanvas(e);return o?o.toDataURL(t,r):null}};var eu=[.8705882352941177,.8627450980392157,.8627450980392157],ZS=8,JS=`#version 300 es
1037
+ }`,setup:(e,t)=>{e.uniformMatrix4fv(t.uColorMatrix,!1,new Float32Array([n[0],n[1],n[2],n[3],n[5],n[6],n[7],n[8],n[10],n[11],n[12],n[13],n[15],n[16],n[17],n[18]])),e.uniform4f(t.uConstants,n[4],n[9],n[14],n[19])}}}var Ra=class{gl;programs=new Map;cache=new WeakMap;quadBuffer=null;vertexShader=null;disposed=!1;constructor(e){this.gl=e}getFilteredTexture(e,t,r,o,i){if(this.disposed||r<=0||o<=0)return null;let s=`${r}x${o}|${Oi(i)}`,a=this.cache.get(e);return a&&a.sig===s&&a.source===t?a.outTex:(a&&(this.gl.deleteTexture(a.sourceTex),this.gl.deleteTexture(a.outTex)),this.runChain(e,t,r,o,i,s))}runChain(e,t,r,o,i,s){let a=this.gl,l=bp(i,r,o);if(!l.length)return null;let u=a.getParameter(a.VIEWPORT),c=a.isEnabled(a.BLEND),h=a.getParameter(a.CURRENT_PROGRAM),d=a.getParameter(a.FRAMEBUFFER_BINDING),f=a.getParameter(a.ARRAY_BUFFER_BINDING),m=a.getParameter(a.TEXTURE_BINDING_2D),p=a.getParameter(a.VERTEX_ARRAY_BINDING);a.bindVertexArray(null),a.disable(a.BLEND),a.viewport(0,0,r,o);let b=a.createTexture();if(!b)return null;a.bindTexture(a.TEXTURE_2D,b),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,t);let g=()=>{let M=a.createTexture();return M?(a.bindTexture(a.TEXTURE_2D,M),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,r,o,0,a.RGBA,a.UNSIGNED_BYTE,null),M):null},x=g(),S=g(),w=a.createFramebuffer(),y=a.createFramebuffer();if(!x||!S||!w||!y)return null;let v=this.ensureQuad(),R=b,P=x,T=w;for(let M of l){let k=this.ensureProgram(M.source);if(!k)break;a.useProgram(k.program),a.bindFramebuffer(a.FRAMEBUFFER,T),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,P,0),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,R),a.uniform1i(k.uniforms.uTexture,0),k.uniforms.uStepW&&a.uniform1f(k.uniforms.uStepW,1/r),k.uniforms.uStepH&&a.uniform1f(k.uniforms.uStepH,1/o),M.setup(a,k.uniforms),a.bindBuffer(a.ARRAY_BUFFER,v),a.enableVertexAttribArray(k.aPosition),a.vertexAttribPointer(k.aPosition,2,a.FLOAT,!1,0,0),a.drawArrays(a.TRIANGLE_STRIP,0,4),R=P,T===w?(P=S,T=y):(P=x,T=w)}let C=R;a.bindVertexArray(p),a.bindFramebuffer(a.FRAMEBUFFER,d),a.viewport(u[0],u[1],u[2],u[3]),c&&a.enable(a.BLEND),a.useProgram(h),a.bindBuffer(a.ARRAY_BUFFER,f),a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,m),a.deleteFramebuffer(w),a.deleteFramebuffer(y);let E=C===x?S:x;return a.deleteTexture(E),a.bindTexture(a.TEXTURE_2D,C),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR_MIPMAP_LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.generateMipmap(a.TEXTURE_2D),a.bindTexture(a.TEXTURE_2D,m),this.cache.set(e,{sig:s,source:t,sourceTex:b,outTex:C}),C}ensureQuad(){let e=this.gl;return this.quadBuffer||(this.quadBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.quadBuffer),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,1]),e.STATIC_DRAW)),this.quadBuffer}ensureProgram(e){let t=this.programs.get(e);if(t)return t;let r=this.gl;if(!this.vertexShader){let h=r.createShader(r.VERTEX_SHADER);if(!h)return null;r.shaderSource(h,pp),r.compileShader(h),this.vertexShader=h}let o=this.vertexShader,i=r.createShader(r.FRAGMENT_SHADER),s=r.createProgram();if(!i||!s)return null;if(r.shaderSource(i,e),r.compileShader(i),r.attachShader(s,o),r.attachShader(s,i),r.linkProgram(s),r.deleteShader(i),!r.getProgramParameter(s,r.LINK_STATUS))return console.warn("[gpuImageFilters] program link failed:",r.getProgramInfoLog(s)),r.deleteProgram(s),null;let l={},u=r.getProgramParameter(s,r.ACTIVE_UNIFORMS);for(let h=0;h<u;h++){let d=r.getActiveUniform(s,h);if(!d)continue;let f=d.name.replace(/\[0\]$/,"");l[f]=r.getUniformLocation(s,d.name)}let c={program:s,aPosition:r.getAttribLocation(s,"aPosition"),uniforms:l};return this.programs.set(e,c),c}invalidate(){this.cache=new WeakMap,this.programs.clear(),this.vertexShader=null,this.quadBuffer=null}dispose(){this.disposed=!0;let e=this.gl;for(let t of this.programs.values())e.deleteProgram(t.program);this.programs.clear(),this.invalidate()}};var Pa=class{constructor(e,t){this.gl=e;this.epoch=t}gl;epoch;fxPainter=null;filterChain=null;get fx(){return this.fxPainter||(this.fxPainter=new Ma(this.epoch)),this.fxPainter}get filters(){return this.filterChain||(this.filterChain=new Ra(this.gl)),this.filterChain}invalidate(){this.fxPainter?.invalidate(this.gl),this.filterChain?.invalidate()}invalidateTextDerivedBakes(){this.fxPainter?.invalidateTextDerivedBakes(this.gl)}};var zS=[.914,.914,.914,1],ka=class{host;sources;text;frame={bakeDeadline:0,bakeMore:!1,animationActive:!1};settle;flatFrame=!0;shadow;psd;stroke;gpu;isolator=null;isolating=!1;blender=null;blendWrapNode=null;clipContentNode=null;cropGhostPreDrawn=null;puzzleBox=null;stencilClip=new Ta;maskGpu=new Ea;constructor(e,t,r){this.host=e,this.sources=t,this.text=r,this.gpu=new Pa(e.gl,e.renderEpoch),this.shadow=new ga(e),this.settle=new In(()=>this.host.requestRenderAll()),this.stroke=new wa(e,this.frame,this.settle),this.psd=new Ca(e,this.frame,this.gpu,()=>this.puzzleBox,this.settle,this.compositeFxBlended,this.sources)}beginFrame(e){this.frame.animationActive=!1,this.frame.bakeDeadline=e+cp(this.host.isExporting()),this.frame.bakeMore=!1,this.stencilClip.resetFrame(),this.maskGpu.activeThisFrame=!1}noteVptChange(){this.settle.noteInteraction()}noteExternalInteraction(){this.settle.noteInteraction()}groupMask(e){let t=e.raw.mask;if(!t||t.disabled===!0||typeof t.src!="string")return null;let r=this.sources.maskTexture(t.src);if(!r)return null;let o=t.defaultColor===255,i=e.dims.x,s=e.dims.y,a=(Number(t.offsetX)||0)-i/2,l=(Number(t.offsetY)||0)-s/2,u=(Number(t.width)||0)*(Number(t.scaleX)||1),c=(Number(t.height)||0)*(Number(t.scaleY)||1);if(!(u>0)||!(c>0))return null;let h=e.matrix,d=this.host.canvasEl.width,f=this.host.canvasEl.height,m=[d/this.host.dpr,0,0,-f/this.host.dpr,0,f/this.host.dpr],p=ve(this.host.viewportTransform),b=ve(h),g=[1/u,0,0,1/c,-a/u,-l/c];if(!p||!b)return null;let x=j(g,j(b,j(p,m))),S=[x[0],x[1],0,x[2],x[3],0,x[4],x[5],1];return{tex:r,maskInv:S,coversHost:o}}renderPuzzleChildren(e,t){if(!(e instanceof le)){t();return}let r=this.puzzleBox;this.puzzleBox={hw:e.dims.x/2,hh:e.dims.y/2};try{t()}finally{this.puzzleBox=r}}puzzleClampedQuad(e,t,r,o=0,i=0){return _n(this.puzzleBox,e,t,r,o,i)}renderIsolatedGroup(e,t){let r=this.host.gl;this.flatFrame=!1,this.isolator||(this.isolator=new ma),this.host.batchOrder.flushAll();let o=()=>{if(e instanceof J)for(let s of e.children)this.renderSceneNode(s);else this.renderSceneNodeContentOnly(e)};if(!this.isolator.begin(r,this.host.canvasEl.width,this.host.canvasEl.height)){this.renderPuzzleChildren(e,o);return}this.isolating=!0;let i=1;if(e instanceof J){let s=()=>{for(let a of e.children)a.setIsolation(!0);o();for(let a of e.children)a.setIsolation(!1)};this.renderPuzzleChildren(e,s),i=e.renderOpacity}else o();this.host.batchOrder.flushAll(),this.isolating=!1,this.isolator.end(r),r.viewport(0,0,this.host.canvasEl.width,this.host.canvasEl.height),this.isolator.composite(r,i,t)}renderSceneNodeContentOnly(e){this.renderSceneNode(e)}renderBlendedNode(e,t){let r=this.host.gl;this.flatFrame=!1,this.blender||(this.blender=new Qo),this.host.batchOrder.flushAll();let o=this.host.canvasEl.width,i=this.host.canvasEl.height,s=this.blendWrapNode;this.blendWrapNode=e;try{if(!this.blender.begin(r,o,i)){this.renderSceneNode(e);return}this.renderSceneNode(e),this.host.batchOrder.flushAll(),this.blender.end(r),r.viewport(0,0,o,i),this.blender.composite(r,t)}finally{this.blendWrapNode=s}}compositeFxBlended=(e,t)=>{let r=this.host.gl;this.flatFrame=!1,this.blender||(this.blender=new Qo),this.host.batchOrder.flushAll();let o=this.host.canvasEl.width,i=this.host.canvasEl.height;if(!this.blender.begin(r,o,i)){t();return}t(),this.host.batchOrder.flushAll(),this.blender.end(r),r.viewport(0,0,o,i),this.blender.composite(r,e)};renderSceneNode(e){if(e.visible&&e!==this.host.warpSessionTarget){if(this.blendWrapNode!==e){let t=pa(e.raw.globalCompositeOperation);if(t!==null){this.renderBlendedNode(e,t);return}}if(e instanceof J){if(this.stencilClip.begin(e,this.host,{rasterMask:ko(e)!==null})){let o=this.groupMask(e);!this.isolating&&((e.raw.opacity??1)<1||!!o)?this.renderIsolatedGroup(e,o):this.renderPuzzleChildren(e,()=>{for(let s of e.children)this.renderSceneNode(s)}),this.stencilClip.end(this.host);return}let t=this.groupMask(e);if(!this.isolating&&((e.raw.opacity??1)<1||!!t)){this.renderIsolatedGroup(e,t);return}this.renderPuzzleChildren(e,()=>{for(let o of e.children)this.renderSceneNode(o)});return}if(this.clipContentNode!==e&&$c(e)){if(this.preDrawCropGhost(e),this.stencilClip.begin(e,this.host,{rasterMask:!1})){let r=this.isolating;this.clipContentNode=e,this.isolating=!0,this.renderSceneNodeContentOnly(e),this.clipContentNode=null,this.isolating=r,this.stencilClip.end(this.host),this.cropGhostPreDrawn=null;return}let t=this.clipContentNode;this.clipContentNode=e,this.renderSceneNodeContentOnly(e),this.clipContentNode=t,this.cropGhostPreDrawn=null;return}if(!this.isolating&&ko(e)){let t=this.groupMask(e);if(t){this.renderIsolatedGroup(e,t);return}}if(e.isTextType){if(this.text.renderTextPathBackground(e,this.host.zoom*this.host.dpr),typeof e.raw.renderSrc=="string"&&e!==this.host.editingNode){let i=e.imageEl?this.host.textures.get(e.imageEl):null;if(i){let s=e.bitmapRect,a=s.x!==0||s.y!==0?j(e.matrix,[1,0,0,1,s.x,s.y]):e.matrix;s.angle&&(a=j(a,At({angle:-s.angle}))),this.shadow.render(e),this.psd.render(e,"below");let l=Po(e.raw);this.host.batch.pushQuad(a,s.w,s.h,[1,1,1,e.renderOpacity*l],i,[0,0,1,1],null,e),this.psd.render(e,"above");return}if(this.sources.isImagePending(e)){this.renderImagePlaceholder(e);return}}let t=Bh(e.raw);if(t&&e!==this.host.editingNode){this.text.renderWarpedText(e,t);return}let r=Zn(e.raw);if(r&&e!==this.host.editingNode){this.text.renderPsdWarpedText(e,r);return}let o=Xe(e.raw);if(o&&e!==this.host.editingNode){this.text.renderArcText(e,o,this.host.zoom*this.host.dpr);return}this.shadow.render(e),this.psd.render(e,"below"),this.text.renderTextGlyphs(e,this.host.zoom*this.host.dpr,e===this.host.editingNode),this.psd.render(e,"above");return}if(e.isShapeType){let t=e.strokeDecl,r=e.shapeMesh;if(r||t){this.shadow.render(e),this.psd.render(e,"below");let o=()=>{this.stroke.render(e)};if(t){let i=t.paintFirst==="stroke";if(i&&o(),r){let s=this.paintParams(e);s?this.host.meshBatch.pushMesh(e.matrix,[1,1,1,e.renderOpacity],r.verts,r.triangles,s,e):this.host.meshBatch.pushMesh(e.matrix,e.drawColor,r.verts,r.triangles,void 0,e)}i||o()}else if(r){let i=this.paintParams(e);i?this.host.meshBatch.pushMesh(e.matrix,[1,1,1,e.renderOpacity],r.verts,r.triangles,i,e):this.host.meshBatch.pushMesh(e.matrix,e.drawColor,r.verts,r.triangles,void 0,e)}}this.psd.render(e,"above");return}if(e.isLineType){this.shadow.render(e),this.stroke.render(e);return}if(e instanceof ae){this.renderMaskNode(e);return}if(e instanceof ie&&e.paintSource){this.renderAnimatedNode(e);return}if(e.isImageType&&!e.imageEl){this.sources.isImagePending(e)&&this.renderImagePlaceholder(e);return}this.renderImageFamily(e)}}renderImageFamily(e){if(this.shadow.render(e),this.psd.render(e,"below"),e.isSolidType){let a=e.strokeDecl?.paintFirst==="stroke";a&&this.stroke.render(e);let l=this.paintParams(e);if(l){this.host.batch.pushPaintQuad(e.matrix,e.dims.x,e.dims.y,l,e.renderOpacity,this.solidRadii(e)),a||this.stroke.render(e);return}}let t=this.imageTextureOf(e);e===this.host.cropGhostNode&&e!==this.cropGhostPreDrawn&&e.imageEl&&t&&this.drawCropGhost(e,t);let r=e.cropRect,o=r&&e.imageEl?[r.sx/e.imageEl.naturalWidth,r.sy/e.imageEl.naturalHeight,(r.sx+r.sw)/e.imageEl.naturalWidth,(r.sy+r.sh)/e.imageEl.naturalHeight]:[0,0,1,1],i=gd(e.raw),s=i===1?e.drawColor:[1,1,1,e.renderOpacity*i];this.host.batch.pushQuad(e.matrix,e.dims.x,e.dims.y,s,t,o,this.quadRadii(e),e),e.isSolidType&&e.strokeDecl?.paintFirst!=="stroke"&&this.stroke.render(e),this.psd.render(e,"above")}imageTextureOf(e){let t=e.isImageType&&!(e instanceof ie)?ho(e.raw.filters):[],r=t.length&&e.imageEl?this.gpu.filters.getFilteredTexture(e,e.imageEl,e.imageEl.naturalWidth||e.imageEl.width,e.imageEl.naturalHeight||e.imageEl.height,t):null,o=t.length?e.imageEl:this.sources.svgRasterSource(e,this.host.zoom,this.host.dpr);return r??(o?this.host.textures.get(o):null)}drawCropGhost(e,t){if(!e.imageEl)return;let r=e.dims,o=e.raw.cropX??0,i=e.raw.cropY??0,s=e.imageEl.naturalWidth,a=e.imageEl.naturalHeight,l={x:-r.x/2-o+s/2,y:-r.y/2-i+a/2},u=j(e.matrix,[1,0,0,1,l.x,l.y]);this.host.batch.pushQuad(u,s,a,[1,1,1,.5*e.renderOpacity],t)}preDrawCropGhost(e){if(e!==this.host.cropGhostNode||!e.imageEl)return;let t=this.imageTextureOf(e);t&&(this.cropGhostPreDrawn=e,this.drawCropGhost(e,t))}renderMaskNode(e){let t=e.clipImageRaw;if(e.clipDynamicKind){e.tickDynamicClip(performance.now());let f=e.dynamicClipSource();if(!f||!e.imageEl){this.sources.isImagePending(e)&&this.renderImagePlaceholder(e);return}this.psd.render(e,"below");let m=f;this.host.textures.update(m);let p=this.host.textures.get(m),b=this.host.textures.get(e.imageEl),g=m,x=g.videoWidth||g.width||0,S=g.videoHeight||g.height||0;if(p&&b&&x&&S){let w=this.maskGpu.render(e,this.host.gl,this.host.zoom,this.host.dpr,{maskTex:b,clipTex:p,clipW:x,clipH:S});if(w){this.flatFrame=!1;let y=this.puzzleClampedQuad(e,w.w,w.h);y&&this.host.batch.pushQuad(y.matrix,y.w,y.h,[1,1,1,e.renderOpacity],w.tex,y.uv,null,e),this.psd.render(e,"above"),e.clipAnimating&&(this.frame.animationActive=!0);return}}return}if(!t){if(this.shadow.render(e),!e.imageEl){this.sources.isImagePending(e)&&this.renderImagePlaceholder(e);return}this.psd.render(e,"below");let f=this.sources.svgRasterSource(e,this.host.zoom,this.host.dpr)??e.imageEl,m=this.host.textures.get(f),p=this.puzzleClampedQuad(e,e.dims.x,e.dims.y);p&&this.host.batch.pushQuad(p.matrix,p.w,p.h,[1,1,1,e.renderOpacity],m,p.uv,null,e),this.psd.render(e,"above");return}let r=e.clipImageEl;if(!r||!e.imageEl){this.sources.isImagePending(e)&&this.renderImagePlaceholder(e);return}let o=ho(t.filters),i=r,s=i.naturalWidth||i.videoWidth||i.width||t.width||0,a=i.naturalHeight||i.videoHeight||i.height||t.height||0,l=o.length?this.gpu.filters.getFilteredTexture(e,r,s,a,o):this.host.textures.get(r),u=this.host.textures.get(e.imageEl);if(!l||!u||!s||!a)return;let c=this.maskGpu.render(e,this.host.gl,this.host.zoom,this.host.dpr,{maskTex:u,clipTex:l,clipW:s,clipH:a});if(!c)return;this.psd.render(e,"below");let h=this.puzzleClampedQuad(e,c.w,c.h),d=e===this.host.maskCropNode?.5:1;h&&this.host.batch.pushQuad(h.matrix,h.w,h.h,[1,1,1,d*e.renderOpacity],c.tex,h.uv,null,e),this.psd.render(e,"above")}renderAnimatedNode(e){let t=e.tick(performance.now()),r=e.paintSource;if(!r)return;let o=this.host.textures.get(r);o&&t&&this.host.textures.update(r),this.shadow.render(e),this.psd.render(e,"below"),this.host.batch.pushQuad(e.matrix,e.dims.x,e.dims.y,e.drawColor,o,[0,0,1,1],this.quadRadii(e),e),this.psd.render(e,"above"),e.animating&&(this.frame.animationActive=!0)}renderImagePlaceholder(e){let{x:t,y:r}=e.dims;if(!(t>0)||!(r>0))return;let o=e.renderOpacity,i=ee(e.raw.fill),s=i[3]>0?i:zS;this.host.batch.pushQuad(e.matrix,t,r,[s[0],s[1],s[2],s[3]*o],null,[0,0,1,1],this.quadRadii(e),e)}quadRadii(e){if(e.isSolidType){let t=it(e.raw,e.dims.x,e.dims.y);return t?[t.rx,t.ry]:null}if(e.isImageType&&!(e instanceof ie)){let t=br(e.raw,e.dims.x,e.dims.y);return t?[t,t]:null}return null}solidRadii(e){let t=it(e.raw,e.dims.x,e.dims.y);return t?[t.rx,t.ry]:null}paintParams(e){let t=e.fillPaint;if(!t)return null;if(t.kind==="gradient"){let r=this.host.gradientRamps.get(t.decl);return r?{kind:"gradient",decl:t.decl,inv:ve(fi(t.decl,e.dims.x,e.dims.y)),tex:r}:null}if(t.kind==="pattern"){let r=this.sources.patternTexture(t.decl.src);return r?{kind:"pattern",inv:ve(bi(t.decl,e.dims.x,e.dims.y)),tex:r.tex,size:[r.w,r.h],repeat:Du(t.decl.repeat)}:null}return null}invalidateGlResources(){this.shadow.invalidate(),this.psd.invalidate(),this.stroke.invalidate(),this.maskGpu.invalidate(),this.isolator&&(this.isolator.dispose(this.host.gl),this.isolator=null),this.blender&&(this.blender.dispose(this.host.gl),this.blender=null),this.gpu.invalidate()}invalidateTextDerivedBakes(){this.shadow.invalidate(),this.psd.invalidate(),this.stroke.invalidate(),this.gpu.invalidateTextDerivedBakes()}};var jc=n=>{let e=n.mask;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.disabled===!0||typeof t.src!="string"||!t.src)return null;let r=Number(t.width),o=Number(t.height);return!(r>0)||!(o>0)?null:{src:t.src,width:r,height:o,left:typeof t.left=="number"?t.left:void 0,top:typeof t.top=="number"?t.top:void 0,offsetX:typeof t.offsetX=="number"?t.offsetX:void 0,offsetY:typeof t.offsetY=="number"?t.offsetY:void 0,defaultColor:typeof t.defaultColor=="number"?t.defaultColor:void 0,crossOrigin:typeof t.crossOrigin=="string"?t.crossOrigin:null}},gp=n=>n.startsWith("resource/")?n.replace("resource/","/resource/"):n,xp=n=>{for(let e=0;e<n.length;e+=4){let t=n[e],r=n[e+1],o=n[e+2];t===r&&r===o?n[e+3]=t:t===0&&r===0&&o===0&&(n[e+3]=0)}},yp=(n,e,t)=>({x:typeof n.offsetX=="number"&&Number.isFinite(n.offsetX)?n.offsetX:(n.left??e)-e,y:typeof n.offsetY=="number"&&Number.isFinite(n.offsetY)?n.offsetY:(n.top??t)-t}),Sp=(n,e,t,r,o,i)=>{if(r<=0&&t<=0&&i+r>=e&&o+t>=n)return[];let s=[];return r>0&&s.push([0,0,n,r]),t>0&&s.push([0,0,t,e]),r+i<e&&s.push([0,r+i,n,e-i-r]),t+o<n&&s.push([t+o,0,n-o-t,e]),s},vp=(n,e,t,r,o,i)=>{let s=Math.max(1,Math.round(e.x)),a=Math.max(1,Math.round(e.y)),l=document.createElement("canvas");l.width=t.width,l.height=t.height;let u=l.getContext("2d",{willReadFrequently:!0}),c=document.createElement("canvas");c.width=s,c.height=a;let h=c.getContext("2d");if(!u||!h)return null;try{u.drawImage(r,0,0);let f=u.getImageData(0,0,t.width,t.height);xp(f.data),u.putImageData(f,0,0)}catch{return null}let d=yp(t,o,i);if(h.drawImage(l,d.x,d.y),t.defaultColor===255){h.fillStyle="#000000";for(let[f,m,p,b]of Sp(s,a,d.x,d.y,t.width,t.height))h.fillRect(f,m,p,b)}return h.globalCompositeOperation="source-in",h.drawImage(n,0,0),c},wp=n=>new Promise(e=>{n.toBlob(t=>{if(!t){e(null);return}let r=URL.createObjectURL(t),o=new Image;o.onload=()=>{URL.revokeObjectURL(r),e(o)},o.onerror=()=>{URL.revokeObjectURL(r),e(null)},o.src=r})});var Jo={create(n,e){if(typeof document<"u"){let t=document.createElement("canvas");return t.width=n,t.height=e,t}if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(n,e);throw new Error("Canvas is not available")}},Dn=n=>{let e=n.getContext("2d");if(!e)throw new Error("Failed to get canvas context");return e},ei=n=>{n.width=0,n.height=0},Tp=n=>{"close"in n?n.close():ei(n)};var Aa=640,ti=80,Ep=async(n,e={})=>{let{parseGIF:t,decompressFrame:r}=await import("gifuct-js"),o=t(n),i=null,s=(o.frames??[]).map(E=>E.image?(!E.gce&&i&&(E.gce=i),i=null,r(E,o.gct,!0)):(E.gce&&(i=E.gce),null)).filter(E=>E!==null);if(!s||!s.length)throw new Error("No frames available");let a=o.lsd,l=a?.width??s[0].dims.width,u=a?.height??s[0].dims.height,c=Math.max(l,u),h=c>Aa?Aa/c:1,d=Math.max(1,Math.round(l*h)),f=Math.max(1,Math.round(u*h)),m=s.reduce((E,M)=>E+(M.delay||0),0)/1e3,p=s.length>ti?s.slice(0,ti):s,b=p.reduce((E,M)=>E+(M.delay||0),0),g=p.length>0?b/p.length:100,x=e.canvasFactory??Jo,S=x.create(1,1),w=Dn(S),y=x.create(l,u),v=Dn(y),R=x.create(d*p.length,f),P=Dn(R);if(!w||!v||!P)throw new Error("Failed to get canvas context");y.width=l,y.height=u,R.width=d*p.length,R.height=f;let T,C;return p.forEach((E,M)=>{T?.disposalType===2?v.clearRect(T.dims.left,T.dims.top,T.dims.width,T.dims.height):T?.disposalType===3&&C&&v.putImageData(C,0,0),C=E.disposalType===3?v.getImageData(0,0,l,u):void 0,S.width=E.dims.width,S.height=E.dims.height;let k=w.createImageData(E.dims.width,E.dims.height);k.data.set(E.patch),w.putImageData(k,0,0),v.drawImage(S,E.dims.left,E.dims.top),P.drawImage(y,0,0,l,u,d*M,0,d,f),T=E}),ei(S),ei(y),{canvas:R,frameWidth:d,framesLength:p.length,delay:g,frameDelays:p.map(E=>E.delay||100),duration:m}},Cp=(n,e,t,r,o={})=>{if(!n.length)throw new Error("No frames available");let i=o.canvasFactory??Jo,s=Math.max(e,t),a=s>Aa?Aa/s:1,l=Math.max(1,Math.round(e*a)),u=Math.max(1,Math.round(t*a)),c=i.create(e,t),h=Dn(c),d=i.create(l*Math.min(n.length,ti),u),f=Dn(d);if(!h||!f)throw new Error("Failed to get canvas context");c.width=e,c.height=t,d.width=l*Math.min(n.length,ti),d.height=u;let m=n.slice(0,ti);m.forEach((b,g)=>{let x=h.createImageData(e,t);x.data.set(new Uint8ClampedArray(b)),h.putImageData(x,0,0),f.drawImage(c,0,0,e,t,l*g,0,l,u)}),ei(c);let p=m.map((b,g)=>Math.max(1,r[g]??100));return{canvas:d,frameWidth:l,framesLength:m.length,delay:p.reduce((b,g)=>b+g,0)/p.length,frameDelays:p,duration:p.reduce((b,g)=>b+g,0)/1e3}};var YS=[137,80,78,71,13,10,26,10],jr=n=>{let e=new Uint8Array(n);if(e.length<8||!YS.every((r,o)=>e[o]===r))return!1;let t=new DataView(n);for(let r=8;r+12<=e.length;){let o=t.getUint32(r),i=r+o+12;if(i>e.length)return!1;let s=String.fromCharCode(...e.subarray(r+4,r+8));if(s==="acTL")return o===8&&t.getUint32(r+8)>0;if(s==="IDAT"||s==="IEND")return!1;r=i}return!1},US=async n=>jr(await n.arrayBuffer()),$S=async n=>{try{let e=await fetch(n);return e.ok&&jr(await e.arrayBuffer())}catch{return!1}},Mp=async(n,e={})=>{if(!jr(n))throw new Error("Not an animated PNG");let{default:t}=await import("upng-js"),r=t.decode(n);return r.frames=r.frames.slice(0,80),Cp(t.toRGBA8(r),r.width,r.height,r.frames.map(o=>o.delay),e)};var Rp=640,jS=80,Na=100,Vc=(n,e)=>String.fromCharCode(n[e],n[e+1],n[e+2],n[e+3]),qc=n=>{if(n.byteLength<12)return!1;let e=new Uint8Array(n,0,12);return Vc(e,0)==="RIFF"&&Vc(e,8)==="WEBP"},kp=n=>{if(!qc(n))return!1;let e=new Uint8Array(n,0,Math.min(n.byteLength,512)),t=12;for(;t+8<=e.length;){let r=Vc(e,t);if(r==="VP8X")return t+8<e.length&&(e[t+8]&2)!==0;if(r==="ANIM"||r==="ANMF")return!0;if(r==="VP8 "||r==="VP8L")return!1;let o=e[t+4]|e[t+5]<<8|e[t+6]<<16|e[t+7]<<24;if(o<0)return!1;t+=8+o+o%2}return!1},VS=async n=>kp(await n.slice(0,512).arrayBuffer()),qS=async n=>{try{let e=await fetch(n,{headers:{Range:"bytes=0-511"}});return e.ok?kp(await e.arrayBuffer()):!1}catch{return!1}},Ap=(n,e,t,r={})=>{let o=(r.canvasFactory??Jo).create(n*t,e);o.width=n*t,o.height=e;let i=Dn(o);if(!i)throw new Error("Failed to get canvas context");return{canvas:o,ctx:i}},Np=(n,e)=>{let t=Math.max(n,e),r=t>Rp?Rp/t:1;return{width:Math.max(1,Math.round(n*r)),height:Math.max(1,Math.round(e*r))}},Pp=async(n,e={})=>{let t=URL.createObjectURL(new Blob([n],{type:"image/webp"}));try{let r=await new Promise((l,u)=>{let c=new Image;c.onload=()=>l(c),c.onerror=()=>u(new Error("Failed to load WebP")),c.src=t}),{width:o,height:i}=Np(r.naturalWidth,r.naturalHeight),{canvas:s,ctx:a}=Ap(o,i,1,e);return a.drawImage(r,0,0,o,i),{canvas:s,frameWidth:o,framesLength:1,delay:Na,frameDelays:[Na],duration:0}}finally{URL.revokeObjectURL(t)}},Lp=async(n,e={})=>{let t=globalThis.ImageDecoder;if(!t||!await t.isTypeSupported("image/webp"))return Pp(n,e);let r=new t({data:n,type:"image/webp",preferAnimation:!0});try{await r.tracks.ready;let o=r.tracks.selectedTrack;if(!o?.frameCount||o.frameCount<2)return Pp(n,e);let i=Math.min(o.frameCount,jS),s=await r.decode({frameIndex:0}),{width:a,height:l}=Np(s.image.displayWidth,s.image.displayHeight),{canvas:u,ctx:c}=Ap(a,l,i,e),h=[];for(let d=0;d<i;d++){let{image:f}=d===0?s:await r.decode({frameIndex:d}),m=typeof f.duration=="number"&&f.duration>0?f.duration/1e3:Na;h.push(m),c.drawImage(f,a*d,0,a,l),f.close()}return{canvas:u,frameWidth:a,framesLength:i,delay:h[0]||Na,frameDelays:h,duration:h.reduce((d,f)=>d+f,0)/1e3}}finally{r.close()}};var Kc=async(n,e={})=>{if(qc(n))return Lp(n,e);if(jr(n))return Mp(n,e);let t=new Uint8Array(n,0,Math.min(6,n.byteLength)),r=String.fromCharCode(...t);if(r==="GIF87a"||r==="GIF89a")return Ep(n,e);throw new Error("Unsupported animated image (expected GIF, animated WebP or APNG)")};var La=class{host;patternSources=new Map;patternLoads=new Map;patternFailed=new Set;gifSprites=new Map;animatedNodes=new Set;pendingImageNodes=new WeakSet;patternTextures=new Map;maskTextures=new Map;svgRasters=new WeakMap;svgMaxRasterPx;loadGeneration=0;constructor(e){this.host=e;let t=Number(e.gl.getParameter(e.gl.MAX_TEXTURE_SIZE))||4096;this.svgMaxRasterPx=Math.min(t,4096)}async loadGroupMasks(e){let t=new Set,r=s=>{let a=s.raw.mask;a&&a.disabled!==!0&&typeof a.src=="string"&&!this.maskTextures.has(a.src)&&t.add(a.src)},o=s=>{for(let a of s)a instanceof J?(r(a),o(a.children)):ko(a)&&r(a)};if(o(e),t.size===0)return;let i=this.host.gl;await Promise.all([...t].map(async s=>{try{let a=await Je(s,"anonymous"),l=Ae(i,a);if(!l)return;this.maskTextures.set(s,l)}catch{console.warn("[engine] group mask skipped (load failed):",s)}}))}async loadAnimatedSources(e){let t=++this.loadGeneration,r=a=>this.host.document.nodes.some(l=>l===a||l instanceof J&&l.containsDeep(a)),o=a=>this.loadGeneration===t&&e.includes(a)&&r(a),i=e.filter(a=>a instanceof ae&&!!a.clipDynamicKind&&!a.hasDynamicClip);for(let a of i)(async()=>{let l=a.clipImageRaw;try{let u=a.clipDynamicKind==="gif"?await this.loadGifSprite(l.src):await this.loadVideoElement(l.src,l.crossOrigin,l.loop===!0);if(!o(a))return;a.clipDynamicKind==="gif"?a.attachClipSprite(u,()=>this.host.requestRenderAll()):a.attachClipVideo(u,()=>this.host.requestRenderAll()),this.dynamicClipMasks.add(a),this.host.requestRenderAll()}catch(u){if(console.warn("[engine] mask dynamic clip skipped (load failed):",u.message),!o(a))return;try{a.clipImageEl=await Je(l.src,l.crossOrigin)}catch{}this.host.requestRenderAll()}})();let s=e.filter(a=>a instanceof ie);s.length!==0&&(await Promise.all(s.map(async a=>{let l=a.raw.src;try{let u=a.animatedKind==="gif"?await this.loadGifSprite(l):await this.loadVideoElement(l,a.raw.crossOrigin,a.raw.loop===!0);if(!o(a))return;a.animatedKind==="gif"?a.attachSprite(u,()=>this.host.requestRenderAll()):a.attachVideo(u,()=>this.host.requestRenderAll()),this.animatedNodes.add(a),this.pendingImageNodes.delete(a),this.host.requestRenderAll()}catch(u){if(console.warn("[engine] animated source skipped (load failed):",u.message),!o(a))return;try{a.imageEl=await Je(l,a.raw.crossOrigin)}catch{}this.pendingImageNodes.delete(a),this.host.requestRenderAll()}})),this.host.document.refreshHitIndex())}loadGifSprite(e){if(this.disposed)return Promise.reject(new Error("SourceManager disposed"));let t=this.gifSprites.get(e);if(t)return t;let r=fetch(e).then(async o=>{if(!o.ok)throw new Error(`GIF load failed: ${o.status} ${o.statusText}`);let i=await o.arrayBuffer(),s=this.host.decodeAnimated;if(s)try{return await s(i)}catch(a){console.warn("[engine] injected animated decoder failed, falling back:",a.message)}return Kc(i)}).catch(o=>{throw this.gifSprites.delete(e),o});return this.gifSprites.set(e,r),r}loadVideoElement(e,t,r,o=0){return new Promise((i,s)=>{let a=document.createElement("video");a.crossOrigin=t||"anonymous",a.muted=!0,a.playsInline=!0,a.setAttribute("playsinline","true"),a.setAttribute("webkit-playsinline","true"),a.loop=r,a.preload="auto",a.addEventListener("loadeddata",()=>i(a),{once:!0}),a.addEventListener("error",()=>{a.removeAttribute("src"),a.load(),o<2?setTimeout(()=>{this.loadVideoElement(e,t,r,o+1).then(i,s)},120):s(new Error(`[engine] video load failed: ${e.slice(0,80)}`))},{once:!0}),a.src=e})}releaseAnimatedSources(){this.loadGeneration++;for(let e of[...this.animatedNodes])this.releaseAnimatedNode(e);for(let e of this.dynamicClipMasks)e.detachDynamicClip();this.dynamicClipMasks.clear()}dynamicClipMasks=new Set;releaseAnimatedNode(e){if(!this.animatedNodes.has(e))return;this.animatedNodes.delete(e);let t=e.paintSource;e.detach(),t&&this.host.textures.remove(t)}async loadPatternSources(e){let t=new Set;for(let r of e){let o=r.fillPaint;o?.kind==="pattern"&&t.add(o.decl.src);for(let i of _r(Mt(r.raw.effects)))t.add(i)}if(t.size!==0){for(let r of t)this.patternFailed.delete(r);await Promise.all([...t].map(r=>this.loadPatternSource(r)))}}loadPatternSource(e){let t=this.patternLoads.get(e);if(t)return t;let r=Je(e,"anonymous").then(o=>{this.patternSources.set(e,o),kh(e,o)}).catch(o=>{this.patternFailed.add(e),console.warn("[engine] pattern source skipped (load failed):",o.message)}).finally(()=>{this.patternLoads.delete(e),this.host.requestRenderAll()});return this.patternLoads.set(e,r),r}patternSourcesReady(e){let t=!0;for(let r of e)this.patternSources.has(r)||this.patternFailed.has(r)||(t=!1,this.loadPatternSource(r));return t}patternTexture(e){let t=this.patternTextures.get(e);if(t)return t;let r=this.patternSources.get(e);if(!r||!r.naturalWidth)return null;let o=Ae(this.host.gl,r,{mipmap:!0,repeat:!0});if(!o)return null;let i={tex:o,w:r.naturalWidth,h:r.naturalHeight};return this.patternTextures.set(e,i),i}maskTexture(e){return this.maskTextures.get(e)??null}markImagePending(e){this.pendingImageNodes.add(e)}isImagePending(e){return this.pendingImageNodes.has(e)}svgRasterSource(e,t,r){let o=e.imageEl;if(!o)return null;if(!os(e.raw.src))return o;let i=o.naturalWidth||o.width,s=o.naturalHeight||o.height;if(!(i>0)||!(s>0))return o;let a=e.worldScale,l=this.svgRasters.get(e);l&&(l.source!==o||l.sourceSrc!==o.src)&&(this.svgRasters.delete(e),this.host.textures.remove(l.canvas),l=void 0);let u=Td({w:i,h:s},{w:i*Math.abs(a.x)*t*r,h:s*Math.abs(a.y)*t*r},l?.factor??1,this.svgMaxRasterPx);if(!u.needsRaster)return l?.canvas??o;if(u.factor===1)return l&&(this.svgRasters.delete(e),this.host.textures.remove(l.canvas)),o;let c=Ed(o,u.factor);return l&&this.host.textures.remove(l.canvas),this.svgRasters.set(e,{canvas:c,factor:u.factor,source:o,sourceSrc:o.src}),c}svgRasterFactorOf(e){return this.svgRasters.get(e)?.factor??null}async applyImageMask(e,t){let r=jc(e.raw);if(!r)return!1;try{let o=await Je(gp(r.src),r.crossOrigin),i=e.dims;if(!(i.x>0)||!(i.y>0))return!1;let s=vp(t,i,r,o,e.raw.left??0,e.raw.top??0);if(!s)return!1;let a=await wp(s);return a?(e.imageEl=a,!0):!1}catch(o){return console.warn("[engine] image mask bake skipped (load failed):",o.message),!1}}async reloadNodeImage(e){let t=e.raw.src,r=e.imageEl,o=this.svgRasters.get(e);o&&(this.svgRasters.delete(e),this.host.textures.remove(o.canvas));try{let i=await Je(t,e.raw.crossOrigin);return e.imageEl=i,await this.applyImageMask(e,i),r&&this.host.textures.remove(r),this.host.document.refreshHitIndex(),this.host.requestRenderAll(),e.imageEl}catch(i){return console.warn("[engine] image reload skipped (load failed):",i.message),null}}async reloadMaskClipImage(e){let t=e.clipImageRaw;if(!t||e.clipDynamicKind)return null;let r=e.clipImageEl;try{let o=await Je(t.src,t.crossOrigin??null);return e.clipImageEl=o,r&&this.host.textures.remove(r),this.host.document.refreshHitIndex(),this.host.requestRenderAll(),o}catch(o){return console.warn("[engine] mask clipImage reload skipped (load failed):",o.message),null}}async loadImages(e){let t=s=>s instanceof ie?!1:s instanceof ae?!s.imageEl||!!s.clipImageRaw&&!s.clipDynamicKind&&!s.clipImageEl:s.isTextType?typeof s.raw.renderSrc=="string"&&!s.imageEl:s.isImageType&&!s.imageEl,r=e.filter(t);if(r.length===0)return;let o=new Map,i=!1;await Promise.all(r.map(async s=>{let a=s.isTextType&&typeof s.raw.renderSrc=="string",l=a?s.raw.renderSrc:s.raw.src,u=()=>{this.pendingImageNodes.delete(s),this.host.requestRenderAll()};try{if(s instanceof ae){if(!s.imageEl){let d=o.get(l);d||(d=await Je(l,s.raw.crossOrigin),o.set(l,d)),s.imageEl=d,i=!0}let h=s.clipImageRaw;if(h&&!s.clipDynamicKind&&!s.clipImageEl){let d=h.src,f=o.get(d);f||(f=await Je(d,h.crossOrigin),o.set(d,f)),s.clipImageEl=f}u();return}if(a){let h=o.get(l);h||(h=await Je(l,s.raw.crossOrigin),o.set(l,h)),s.imageEl=h,i=!0,u();return}let c=o.get(l);c||(c=await Je(l,s.raw.crossOrigin),o.set(l,c)),s.imageEl=c,await this.applyImageMask(s,c),i=!0,u()}catch(c){console.warn("[engine] image node skipped (load failed):",c.message),u()}})),i&&this.host.document.refreshHitIndex()}invalidateGlTextures(){for(let{tex:e}of this.patternTextures.values())this.host.gl.deleteTexture(e);this.patternTextures.clear()}dispose(){this.disposed=!0,this.loadGeneration++;for(let e of this.gifSprites.values())e.then(t=>Tp(t.canvas),()=>{});this.gifSprites.clear();for(let{tex:e}of this.patternTextures.values())this.host.gl.deleteTexture(e);this.patternTextures.clear(),this.patternSources.clear(),this.patternLoads.clear(),this.patternFailed.clear()}disposed=!1};function Qc(n){let e=[],t=r=>{for(let o of r)e.push(o),o instanceof J&&t(o.children)};return t([...n]),e}async function Zc(n,e,t){for(let r of n)r instanceof ie?r.paintSource||e.markImagePending(r):r instanceof ae?(!r.imageEl||r.clipImageRaw&&!r.clipImageEl)&&e.markImagePending(r):r.isTextType&&typeof r.raw.renderSrc=="string"?r.imageEl||e.markImagePending(r):r.isImageType&&!r.imageEl&&e.markImagePending(r);t(),await e.loadImages(n),await e.loadGroupMasks(n),await e.loadAnimatedSources(n),await e.loadPatternSources(n),t()}var He=2,KS=4*He,QS=384,ZS=(n,e,t,r,o,i)=>{let s=1/0,a=-1/0,l=1/0,u=-1/0,c=8;for(let h=0;h<=c;h++){let d=r+(o-r)*h/c;for(let f=0;f<=c;f++){let m=e+(t-e)*f/c,p=Ni(n,m,d),b=i[0]*p.x+i[2]*p.y+i[4],g=i[1]*p.x+i[3]*p.y+i[5];s=Math.min(s,b),a=Math.max(a,b),l=Math.min(l,g),u=Math.max(u,g)}}return{minX:s,maxX:a,minY:l,maxY:u}},Jc=(n,e,t=null)=>{let r=n.textLayout,o=Number(n.raw.fontSize)||40,i=typeof n.raw.width=="number"?n.raw.width:r.width,s=typeof n.raw.height=="number"?n.raw.height:r.height;if(!(i>0)||!(s>0))return null;let a=o*.6,l=Math.max(r.width,i,o),u=Math.max(s,o),c=t?Tr(t):0,h=Math.ceil(l+a*2+c*2),d=Math.ceil(u+a*2+c*2),f=h*He,m=d*He;if(!(f>0)||!(m>0)||f>8192||m>8192)return null;let p=ml(e,i,s);if(!p)return null;let b=document.createElement("canvas");b.width=f,b.height=m;let g=b.getContext("2d",{willReadFrequently:!0});if(!g)return null;g.setTransform(He,0,0,He,f/2,m/2),n.raw.vertical===!0?Gi(g,n):po(g,n),bo(g,n,t);let x=g.getImageData(0,0,f,m),S=new Uint32Array(x.data.buffer),w=f,y=0,v=m,R=0,P=!1;for(let ke=0;ke<m;ke++)for(let Ee=0;Ee<f;Ee++)(S[ke*f+Ee]>>>24&255)>10&&(P=!0,Ee<w&&(w=Ee),Ee>y&&(y=Ee),ke<v&&(v=ke),ke>R&&(R=ke));if(!P)return null;let T=w,C=v,E=y+1-w,M=R+1-v,k=(h-i)/2*He,A=(d-s)/2*He,O=[He,0,0,He,k,A],F=(T-k)/He,W=(T+E-k)/He,z=(C-A)/He,_=(C+M-A)/He,D=F/i,I=W/i,G=z/s,$=_/s,V=ZS(p,D,I,G,$,O),H=Math.floor(V.minX)-1,Y=Math.floor(V.minY)-1,X=Math.max(1,Math.ceil(V.maxX+1)-H),Z=Math.max(1,Math.ceil(V.maxY+1)-Y);if(X>8192||Z>8192)return null;let B=pl(p,0,0,i,s,F,z,W,_,E,M,[He,0,0,He,k-H,A-Y],KS,QS);if(!B)return null;let q=g.createImageData(X,Z),U=new Uint32Array(q.data.buffer),oe=new Uint8Array(X*Z),ne=(ke,Ee)=>{let ue=Math.min(E-1,Math.max(0,ke)),xe=Math.min(M-1,Math.max(0,Ee)),pe=Math.floor(ue),Te=Math.floor(xe),rt=Math.min(E-1,pe+1),Ke=Math.min(M-1,Te+1),Ue=ue-pe,bt=xe-Te,gt=S[(C+Te)*f+(T+pe)],xt=S[(C+Te)*f+(T+rt)],yt=S[(C+Ke)*f+(T+rt)],St=S[(C+Ke)*f+(T+pe)],Bn=gt>>>24&255,Wn=xt>>>24&255,ii=yt>>>24&255,si=St>>>24&255;if(Bn<=10&&Wn<=10&&ii<=10&&si<=10)return 0;let $e=(vt,Ha,Ga)=>vt+(Ha-vt)*Ga,fr=Math.round($e($e(gt&255,xt&255,Ue),$e(St&255,yt&255,Ue),bt)),Qr=Math.round($e($e(gt>>>8&255,xt>>>8&255,Ue),$e(St>>>8&255,yt>>>8&255,Ue),bt)),ai=Math.round($e($e(gt>>>16&255,xt>>>16&255,Ue),$e(St>>>16&255,yt>>>16&255,Ue),bt));return Math.round($e($e(Bn,Wn,Ue),$e(si,ii,Ue),bt))<<24|ai<<16|Qr<<8|fr};for(let ke=0;ke+1<B.rows;ke++)for(let Ee=0;Ee+1<B.columns;Ee++){let ue=ke*B.columns+Ee,xe=ue+1,pe=ue+B.columns,Te=pe+1,rt=B.docXs[ue],Ke=B.docYs[ue],Ue=B.docXs[xe],bt=B.docYs[xe],gt=B.docXs[Te],xt=B.docYs[Te],yt=B.docXs[pe],St=B.docYs[pe],Bn=Math.max(0,Math.floor(Math.min(rt,Ue,gt,yt))),Wn=Math.min(X-1,Math.ceil(Math.max(rt,Ue,gt,yt))),ii=Math.max(0,Math.floor(Math.min(Ke,bt,xt,St))),si=Math.min(Z-1,Math.ceil(Math.max(Ke,bt,xt,St)));for(let $e=ii;$e<=si;$e++)for(let fr=Bn;fr<=Wn;fr++){let Qr=$e*X+fr;if(oe[Qr])continue;let ai=bl(fr+.5,$e+.5,rt,Ke,Ue,bt,gt,xt,yt,St);if(!ai)continue;oe[Qr]=1;let{s:Yt,t:vt}=ai,Ha=(1-Yt)*(1-vt)*B.sourceXs[ue]+Yt*(1-vt)*B.sourceXs[xe]+Yt*vt*B.sourceXs[Te]+(1-Yt)*vt*B.sourceXs[pe],Ga=(1-Yt)*(1-vt)*B.sourceYs[ue]+Yt*(1-vt)*B.sourceYs[xe]+Yt*vt*B.sourceYs[Te]+(1-Yt)*vt*B.sourceYs[pe];U[Qr]=ne(Ha,Ga)}}let de=document.createElement("canvas");de.width=X,de.height=Z;let Pe=de.getContext("2d");if(!Pe)return null;Pe.putImageData(q,0,0);let De=(H+X/2)/He-h/2,nt=(Y+Z/2)/He-d/2;return{canvas:de,logicalW:X/He,logicalH:Z/He,offsetX:De,offsetY:nt}};var _p=new Map,ni=(n,e)=>{let t=n.worldScale,r=Dp(n);return e*Math.max(t.x*Math.abs(r.x),t.y*Math.abs(r.y),1e-6)},Dp=n=>{let e=Number(n.raw.textScaleX)||1,t=Number(n.raw.textScaleY)||1;return{x:e,y:t}},ur=n=>{let{x:e,y:t}=Dp(n);return e===1&&t===1?n.matrix:j(n.matrix,[e,0,0,t,0,0])},Vr=(n,e)=>{let t=_p.get(n);if(!t){let r=ee(n);t=[r[0],r[1],r[2],r[3]],_p.set(n,t)}return[t[0],t[1],t[2],t[3]*e[3]]},Ia=class{gl;batch;glyphAtlas;warpBakes=new WeakMap;psdWarpBakes=new WeakMap;arcBakes=new WeakMap;textDashBakes=new WeakMap;scrollBakes=new WeakMap;highlightBakes=new WeakMap;pathBgBakes=new WeakMap;patternSources=null;constructor(e,t,r){this.gl=e,this.batch=t,this.glyphAtlas=r}attachPatternSources(e){this.patternSources=e}patternSourcesPending(e){if(!this.patternSources||!e)return!1;let t=_r(e);return t.length>0&&!this.patternSources.patternSourcesReady(t)}invalidateNodeBakes(e){for(let t of[this.warpBakes,this.psdWarpBakes,this.arcBakes,this.textDashBakes,this.scrollBakes,this.highlightBakes,this.pathBgBakes]){let r=t.get(e);r?.tex&&this.gl.deleteTexture(r.tex),t.delete(e)}}renderWarpedText(e,t){let r=Mt(e.raw.effects,{text:!0}),o=[e.raw.type,e.raw.textTransform,e.raw.text,e.raw.warpStrength,e.raw.fontSize,e.raw.fontFamily,e.raw.width,e.raw.height,e.raw.fill,e.raw.stroke,e.raw.strokeWidth,JSON.stringify(e.raw.styles??null),JSON.stringify(e.raw.paragraph??null),r?wn(r):""].join(";"),i=this.warpBakes.get(e);if(this.patternSourcesPending(r)){i&&this.batch.pushQuad(e.matrix,i.w,i.h,[1,1,1,e.renderOpacity],i.tex);return}if(i&&i.sig!==o&&(this.gl.deleteTexture(i.tex),i=void 0),!i){let s=Cl(e,t,r);if(!s){this.warpBakes.set(e,void 0);return}let a=Ae(this.gl,s.canvas);if(!a)return;i={sig:o,tex:a,w:s.logicalW,h:s.logicalH},this.warpBakes.set(e,i)}this.batch.pushQuad(e.matrix,i.w,i.h,[1,1,1,e.renderOpacity],i.tex)}renderPsdWarpedText(e,t){let r=Mt(e.raw.effects,{text:!0}),o=[e.raw.type,e.raw.text,JSON.stringify(e.raw.psdWarp??null),e.raw.fontSize,e.raw.fontFamily,e.raw.fontWeight,e.raw.fontStyle,e.raw.width,e.raw.height,e.raw.lineHeight,e.raw.charSpacing,e.raw.vertical===!0?1:0,e.raw.fill,e.raw.stroke,e.raw.strokeWidth,JSON.stringify(e.raw.styles??null),JSON.stringify(e.raw.paragraph??null),r?wn(r):""].join(";"),i=this.psdWarpBakes.get(e),s=a=>{let l=a.offX!==0||a.offY!==0?j(e.matrix,At({translateX:a.offX,translateY:a.offY})):e.matrix;this.batch.pushQuad(l,a.w,a.h,[1,1,1,e.renderOpacity],a.tex)};if(this.patternSourcesPending(r)){i&&s(i);return}if(i&&i.sig!==o&&(this.gl.deleteTexture(i.tex),i=void 0),!i){let a=Jc(e,t,r);if(!a){this.psdWarpBakes.set(e,void 0);return}let l=Ae(this.gl,a.canvas);if(!l)return;i={sig:o,tex:l,w:a.logicalW,h:a.logicalH,offX:a.offsetX,offY:a.offsetY},this.psdWarpBakes.set(e,i)}s(i)}renderArcText(e,t,r){let o=Mt(e.raw.effects,{text:!0}),i=!!o&&(o.dropShadows.length>0||o.solidFills.length>0||o.strokes.length>0);if(ku()&&!i){this.renderArcGlyphs(e,t,r);return}let s=Ht(ni(e,r)),a=[e.raw.type,e.raw.textTransform,e.raw.text,e.raw.curvature,e.raw.circleSize,e.raw.circleStartAngle,e.raw.circleSweep,e.raw.circleEccentricity,e.raw.circleDirection,e.raw.fontSize,e.raw.fontFamily,e.raw.fontWeight,e.raw.fontStyle,e.raw.lineHeight,e.raw.textAlign,e.raw.fill,e.raw.stroke,e.raw.strokeWidth,e.raw.strokeVisible,e.raw.paintFirst,JSON.stringify(e.raw.styles??null),o?wn(o):"",s].join(";"),l=this.arcBakes.get(e);if(this.patternSourcesPending(o)){l&&this.batch.pushQuad(e.matrix,l.w,l.h,[1,1,1,e.renderOpacity],l.tex);return}if(l&&l.sig!==a&&(this.gl.deleteTexture(l.tex),l=void 0),!l){let u=Ml(e,t,o,s);if(!u){this.arcBakes.set(e,void 0);return}let c=Ae(this.gl,u.canvas);if(!c)return;l={sig:a,tex:c,w:u.logicalW,h:u.logicalH},this.arcBakes.set(e,l)}this.batch.pushQuad(e.matrix,l.w,l.h,[1,1,1,e.renderOpacity],l.tex)}renderArcGlyphs(e,t,r){let o=Et(e.textLayout,e.raw,e.textStyle.lineHeight??1.16),i=Ht(ni(e,r)),s=e.textStyle,a=e.textStroke,l=e.raw.strokeVisible===!0,u=e.paintFirst==="stroke",c=typeof e.raw.fill=="string"?e.raw.fill:"",h=e.matrix,d=[1,1,1,e.renderOpacity];for(let f of o.chars){let m=e.textLayout.lines[f.line]?.charStyles[f.index],p=gn(s,m),b=typeof m?.fill=="string"&&m.fill?m.fill:c,g=l?Oe(a,m):null,x=f.x-o.contentOffsetX,S=f.y-o.contentOffsetY,w=Math.cos(f.rotation),y=Math.sin(f.rotation),v=R=>{if(R){if(!g||g.width<=0)return}else if(!b)return;let{rs:P,scale:T}=ra(p.fontSize,i),C=this.glyphAtlas.get(p,P,f.char,R?g:null);if(!C)return;let E=C.wPx/T,M=C.hPx/T,k=(C.inkLeftPx-C.advancePx/2-C.padPx)/T+E/2,A=-(C.ascentPx+C.padPx)/T+M/2,O=Vr(R?g.color:b,d),F=j(h,j([1,0,0,1,x,S],j([w,y,-y,w,0,0],[1,0,0,1,k,A])));this.batch.pushQuad(F,E,M,O,this.glyphAtlas.textureOf(C),[C.u0,C.v0,C.u1,C.v1])};u?(v(!0),v(!1)):(v(!1),v(!0))}}renderTextGlyphs(e,t,r=!1){if(Er(e.raw)?.enabled&&!r){this.renderScrollText(e,t);return}let i=e.textLayout,s=e.textStroke,a=!!e.raw.fill||i.lines.some(u=>u.charStyles.some(c=>c?.fill)),l=Ht(ni(e,t));this.renderTextBackgrounds(e),this.renderTextDecorations(e,"underline"),this.renderTextHighlight(e,l),s&&e.paintFirst==="stroke"?(this.renderGlyphPass(e,"stroke",l),a&&this.renderGlyphPass(e,"fill",l)):(a&&this.renderGlyphPass(e,"fill",l),s&&this.renderGlyphPass(e,"stroke",l)),this.renderTextDecorations(e,"overline"),this.renderTextDecorations(e,"linethrough")}renderScrollText(e,t){this.renderTextBackgrounds(e),this.renderTextDecorations(e,"underline");let r=Ht(ni(e,t)),o=e.raw,i=[o.text,o.width,o.height,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.lineHeight,o.charSpacing,o.textAlign,o.splitByGrapheme,o.vertical,typeof o.fill=="string"?o.fill:"gradient",o.stroke,o.strokeWidth,Array.isArray(o.strokeDashArray)?o.strokeDashArray.join(","):"",o.strokeDashOffset,o.paintFirst,JSON.stringify(o.styles??null),o.scrollDirection,JSON.stringify(o.paragraph??null),e.scrollOffset.toFixed(3),e.textTotalWidth.toFixed(3),r].join(";"),s=this.scrollBakes.get(e);if(s&&s.sig!==i&&(this.gl.deleteTexture(s.tex),s=void 0),!s){let a=zh(e,r,e.scrollOffset);if(!a){this.scrollBakes.set(e,void 0);return}let l=Ae(this.gl,a.canvas);if(!l)return;s={sig:i,tex:l,w:a.logicalW,h:a.logicalH},this.scrollBakes.set(e,s)}this.batch.pushQuad(ur(e),s.w,s.h,[1,1,1,e.renderOpacity],s.tex),this.renderTextDecorations(e,"overline"),this.renderTextDecorations(e,"linethrough")}renderTextPathBackground(e,t){let r=Ii(e);if(!r)return;let o=Ht(ni(e,t)),i=`${r.sigBase};${o}`,s=this.pathBgBakes.get(e);if(s&&s.sig!==i&&(this.gl.deleteTexture(s.tex),s=void 0),!s){let a=wh(r,o);if(!a){this.pathBgBakes.set(e,void 0);return}let l=Ae(this.gl,a.canvas);if(!l)return;s={sig:i,tex:l,w:a.logicalW,h:a.logicalH},this.pathBgBakes.set(e,s)}this.batch.pushQuad(e.matrix,s.w,s.h,[1,1,1,e.renderOpacity],s.tex)}renderTextBackgrounds(e){let t=e.textLayout,r=e.renderOpacity,o=ur(e),i=typeof e.raw.textBackgroundColor=="string"?e.raw.textBackgroundColor:"";if(!(!i&&!t.lines.some(s=>s.charStyles.some(a=>a?.textBackgroundColor))))for(let s of t.lines){let a=-t.width/2+s.leftOffset,l=e.contentTopY+s.top,u=m=>s.charStyles[m]?.textBackgroundColor??i,c=0,h=0,d=u(0),f=()=>{if(!d||h<=0)return;let m=a+s.boxes[c].left,p=ee(d),b=[p[0],p[1],p[2],p[3]*r],g=j(o,[1,0,0,1,m+h/2,l+s.implHeight/2]);this.batch.pushQuad(g,h,s.implHeight,b,null)};for(let m=0;m<s.graphemes.length;m++){let p=u(m);p!==d?(f(),c=m,h=s.boxes[m].width,d=p):h+=s.boxes[m].kernedWidth}f()}}renderTextDecorations(e,t){let r=e.textLayout,o=e.decorationDefaults,i=[1,1,1,e.renderOpacity],s=ur(e);for(let a of r.lines){let l=hl(a,t,o);if(l.length===0)continue;let u=-r.width/2+a.leftOffset,c=e.contentTopY+a.baseline;for(let h of l){let d=u+h.x+h.width/2,f=c+h.y+h.thickness/2;this.batch.pushQuad(j(s,[1,0,0,1,d,f]),h.width,h.thickness,Vr(h.color,i),null)}}}textHasDashStroke(e){return Array.isArray(e.raw.strokeDashArray)&&e.raw.strokeDashArray.length>0}renderTextDashStroke(e,t){let r=e.textLayout,o=e.textStyle,i=e.raw.strokeDashArray,s=e.textStroke,a=s?s.width:0;if(!s||a<=0)return;let l=Number(e.raw.charSpacing)||0,u=$t(e.raw.textAlign),c=e.raw.textAlign===fe.DISPERSE,h=Number(e.raw.textOffsetY)||0,d=sh(h,e.textStyle,r.lines),f=a+4+Math.ceil(d),m=Math.ceil(r.width+f*2),p=Math.ceil(r.height+f*2);if(!(m>0)||!(p>0)||m>8192||p>8192)return;let b=[e.raw.text,r.width,r.height,s.color,s.width,i.join(","),Number(e.raw.strokeDashOffset)||0,t,l,u,e.raw.textAlign,e.raw.vertical===!0,h,JSON.stringify(e.raw.paragraph??null)].join(";"),g=this.textDashBakes.get(e);if(g&&g.sig!==b&&(this.gl.deleteTexture(g.tex),g=void 0),!g){let x=document.createElement("canvas");x.width=Math.ceil(m*t),x.height=Math.ceil(p*t);let S=x.getContext("2d");if(!S)return;S.setTransform(t,0,0,t,0,0),S.textBaseline="alphabetic",S.setLineDash(i),S.lineDashOffset=Number(e.raw.strokeDashOffset)||0,S.lineJoin=typeof e.raw.strokeLineJoin=="string"?e.raw.strokeLineJoin:"miter",S.lineCap=typeof e.raw.strokeLineCap=="string"?e.raw.strokeLineCap:"butt",S.miterLimit=Number(e.raw.strokeMiterLimit)||4;let w=r.width/2+f,y=r.height/2+f+e.contentTopY,v=e.raw.vertical===!0,R=0;for(let T of r.lines){let C=-r.width/2+T.leftOffset,E=y+T.baseline;if(v){T.prefix&&Tt(S,T,w+C,E,{stroke:Oe(s,T.charStyles[0])});let D=Vt(T,C,E,o,l);for(let I=0;I<D.length;I++){let G=Oe(s,T.charStyles[I]);if(!G||G.width<=0)continue;let $=fn(o,T.charStyles[I]);S.font=Me($,$.fontSize),S.lineWidth=G.width,S.strokeStyle=G.color,qt(S,{...D[I],y:D[I].y+wt(h,$.fontSize,R+I)},"strokeText")}R+=T.graphemes.length;continue}let M=ro(e.raw.textAlign)&&T.graphemes.some(D=>ao.test(D)),k="",A=T.prefix?Tt(S,T,w+C,E,{stroke:Oe(s,T.charStyles[0])}):0,O=0,F="",W=null,z,_=D=>{if(!k)return;let I=W;I&&I.width>0&&(S.font=F,S.lineWidth=I.width,S.strokeStyle=I.color,S.strokeText(k,w+C+A,E+O)),k="",D<T.boxes.length&&(A=T.boxes[D].left)};for(let D=0;D<T.graphemes.length;D++){let I=T.charStyles[D],$=I!==void 0&&(I.fontSize!==void 0||I.fontFamily!==void 0||I.fontWeight!==void 0||I.fontStyle!==void 0)&&I?{...o,fontSize:I.fontSize??o.fontSize,fontFamily:I.fontFamily??o.fontFamily,fontWeight:I.fontWeight??o.fontWeight,fontStyle:I.fontStyle??o.fontStyle}:o,V=Me($,$.fontSize),H=Oe(s,I),Y=I?.fill??"",X=W;k&&(V!==F||H?.color!==X?.color||H?.width!==X?.width||Y!==z)&&_(D),k||(F=V,W=H,z=Y,O=wt(h,$.fontSize,R+D)),k+=T.graphemes[D],(l||h!==0||(u||c)&&/[ \t\r]/.test(T.graphemes[D])||M)&&_(D+1)}_(T.graphemes.length),R+=T.graphemes.length}let P=Ae(this.gl,x);if(!P)return;g={sig:b,tex:P,w:m,h:p},this.textDashBakes.set(e,g)}this.batch.pushQuad(ur(e),g.w,g.h,[1,1,1,e.renderOpacity],g.tex)}renderTextHighlight(e,t){let r=e.raw;if(!Array.isArray(r.texts)||r.texts.length===0||r.vertical===!0)return;let o=e.textLayout,i=[r.text,o.width,o.height,r.fontSize,r.fontFamily,r.fontWeight,r.fontStyle,r.lineHeight,r.charSpacing,r.textAlign,r.splitByGrapheme,JSON.stringify(r.styles??null),e.dims.y,JSON.stringify(r.texts??null),JSON.stringify(r.paragraph??null),t].join(";"),s=this.highlightBakes.get(e);if(s&&s.sig!==i&&(this.gl.deleteTexture(s.tex),s=void 0),!s){let a=Jn(r.text??"",o,r.texts,e.contentTopY,e.textStyle.fontSize);if(!a){this.highlightBakes.set(e,void 0);return}let l=vh(a,o,e.contentTopY,t);if(!l)return;let u=Ae(this.gl,l.canvas);if(!u)return;s={sig:i,tex:u,w:l.logicalW,h:l.logicalH,centerY:e.contentTopY-a.padY+l.logicalH/2},this.highlightBakes.set(e,s)}this.batch.pushQuad(j(ur(e),[1,0,0,1,0,s.centerY]),s.w,s.h,[1,1,1,e.renderOpacity],s.tex)}renderGlyphPass(e,t,r){if(t==="stroke"&&this.textHasDashStroke(e)){this.renderTextDashStroke(e,r);return}let o=e.textLayout,i=e.textStyle,s=ur(e),a=e.renderOpacity,l=e.fillPaint,u=l?.kind==="gradient"?[l.decl.stops[0].color[0],l.decl.stops[0].color[1],l.decl.stops[0].color[2],l.decl.stops[0].color[3]*a]:e.drawColor,c=!!e.raw.fill,h=e.textStroke,d=[1,1,1,a],f=e.raw.vertical===!0,m=f&&i.charSpacing?i.fontSize*i.charSpacing/1e3:0,p=Number(e.raw.textOffsetY)||0,b=0;for(let g of o.lines){let x=-o.width/2+g.leftOffset,S=e.contentTopY+g.baseline;if(g.prefix)if(t==="stroke"){let y=Oe(h,g.charStyles[0]);y&&y.width>0&&this.pushPrefixGlyphs(e,g.prefix,x,S,y,Vr(y.color,d),r)}else{let y=g.charStyles[0]?.fill;(y||c)&&this.pushPrefixGlyphs(e,g.prefix,x,S,null,y?Vr(y,u):u,r)}let w=0;for(let y=0;y<g.graphemes.length;y++){let v=g.charStyles[y],R,P=null;if(t==="stroke"){if(P=Oe(h,v),!P)continue;R=Vr(P.color,d)}else{let _=v?.fill;if(!_&&!c)continue;R=_?Vr(_,u):u}let C=v!==void 0&&(v.fontSize!==void 0||v.fontFamily!==void 0||v.fontWeight!==void 0||v.fontStyle!==void 0)&&v?{...i,fontSize:v.fontSize??i.fontSize,fontFamily:v.fontFamily??i.fontFamily,fontWeight:v.fontWeight??i.fontWeight,fontStyle:v.fontStyle??i.fontStyle}:i,E=wt(p,C.fontSize,b+y),{rs:M,scale:k}=ra(C.fontSize,r),A=this.glyphAtlas.get(C,M,g.graphemes[y],P);if(!A)continue;let O=g.boxes[y],F=A.wPx/k,W=A.hPx/k,z;if(f){let _=g.graphemes[y],D=qn(_),I=C.fontSize,G=Kn(_,O,m);if(D==="latin"||D==="bracket"){let V=x+w+(D==="latin"?O.kernedWidth-O.width:0)+(A.inkLeftPx-A.padPx)/k,H=S+E-(A.ascentPx+A.padPx)/k;z=j(s,[1,0,0,1,V+F/2,H+W/2])}else{let $=x+w+un(I),V=S+E+yr(D,O,I),H=(A.inkLeftPx-A.padPx)/k+F/2,Y=W/2-(A.ascentPx+A.padPx)/k;z=j(s,j([1,0,0,1,$,V],j([0,-1,1,0,0,0],[1,0,0,1,H,Y])))}w+=G}else{let D=x+O.left+(A.inkLeftPx-A.padPx)/k,I=S+E-(A.ascentPx+A.padPx)/k;z=j(s,[1,0,0,1,D+F/2,I+W/2])}this.batch.pushQuad(z,F,W,R,this.glyphAtlas.textureOf(A),[A.u0,A.v0,A.u1,A.v1])}b+=g.graphemes.length}}pushPrefixGlyphs(e,t,r,o,i,s,a){let l=Nt(t.text),u=r;for(let c=0;c<l.length;c++){let{rs:h,scale:d}=ra(t.style.fontSize,a),f=this.glyphAtlas.get(t.style,h,l[c],i);if(f){let m=f.wPx/d,p=f.hPx/d,b=u+(f.inkLeftPx-f.padPx)/d,g=o-(f.ascentPx+f.padPx)/d;this.batch.pushQuad(j(ur(e),[1,0,0,1,b+m/2,g+p/2]),m,p,s,this.glyphAtlas.textureOf(f),[f.u0,f.v0,f.u1,f.v1])}u+=t.advances[c]??0}}};var Fp=(n,e,t)=>{let r=n.createRenderbuffer();if(!r)throw new Error("Unable to allocate export stencil");return n.bindRenderbuffer(n.RENDERBUFFER,r),n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH24_STENCIL8,e,t),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,r),r},Op=n=>{let e=n.getParameter(n.RENDERBUFFER_BINDING),t=n.isEnabled(n.STENCIL_TEST),r=n.getParameter(n.STENCIL_CLEAR_VALUE),o=n.getParameter(n.COLOR_WRITEMASK),i=n.isEnabled(n.SCISSOR_TEST),s=[n.STENCIL_FUNC,n.STENCIL_REF,n.STENCIL_VALUE_MASK,n.STENCIL_WRITEMASK,n.STENCIL_FAIL,n.STENCIL_PASS_DEPTH_FAIL,n.STENCIL_PASS_DEPTH_PASS].map(l=>n.getParameter(l)),a=[n.STENCIL_BACK_FUNC,n.STENCIL_BACK_REF,n.STENCIL_BACK_VALUE_MASK,n.STENCIL_BACK_WRITEMASK,n.STENCIL_BACK_FAIL,n.STENCIL_BACK_PASS_DEPTH_FAIL,n.STENCIL_BACK_PASS_DEPTH_PASS].map(l=>n.getParameter(l));return()=>{n.bindRenderbuffer(n.RENDERBUFFER,e),n.clearStencil(r),n.colorMask(o[0],o[1],o[2],o[3]);for(let[l,u]of[[n.FRONT,s],[n.BACK,a]])n.stencilFuncSeparate(l,u[0],u[1],u[2]),n.stencilMaskSeparate(l,u[3]),n.stencilOpSeparate(l,u[4],u[5],u[6]);t?n.enable(n.STENCIL_TEST):n.disable(n.STENCIL_TEST),i?n.enable(n.SCISSOR_TEST):n.disable(n.SCISSOR_TEST)}},Bp=n=>{n.disable(n.SCISSOR_TEST),n.disable(n.STENCIL_TEST),n.colorMask(!0,!0,!0,!0),n.stencilMask(255),n.clearStencil(0),n.clear(n.COLOR_BUFFER_BIT|n.STENCIL_BUFFER_BIT)};var Wp=(n,e)=>{let t=n.multiplier&&n.multiplier>0?n.multiplier:1,r=n.width,o=n.height;if(!(r>0)||!(o>0)||!(e>0))return null;let i=Math.max(1,Math.round(r*t)),s=Math.max(1,Math.round(o*t)),a=Math.max(i,s);if(a>e){let u=e/a;i=Math.max(1,Math.floor(i*u)),s=Math.max(1,Math.floor(s*u))}let l=Math.min(i/r,s/o);return{outWidth:i,outHeight:s,multiplier:l}},eu=(n,e)=>{let t=e.outWidth/n.width,r=e.outHeight/n.height;return[t,0,0,r,-n.left*t,-n.top*r]},Hp=(n,e)=>Zr(eu(n,e),e.outWidth,e.outHeight,1),_a=(n,e,t)=>{let r=new Uint8ClampedArray(e*t*4);for(let o=0;o<t;o++){let i=(t-1-o)*e*4,s=o*e*4;for(let a=0;a<e*4;a+=4){let l=n[i+a+3];if(l===0){r[s+a]=0,r[s+a+1]=0,r[s+a+2]=0,r[s+a+3]=0;continue}let u=c=>Math.min(255,Math.round(c*255/l));r[s+a]=u(n[i+a]),r[s+a+1]=u(n[i+a+1]),r[s+a+2]=u(n[i+a+2]),r[s+a+3]=l}}return r};var Gp=n=>typeof n.fenceSync=="function"&&typeof n.clientWaitSync=="function"&&typeof n.getBufferSubData=="function",Xp=(n,e)=>new Promise(t=>{let r=performance.now(),o=!0,i=()=>{let s;try{s=n.clientWaitSync(e,o?n.SYNC_FLUSH_COMMANDS_BIT:0,0)}catch{return t()}if(o=!1,s===n.ALREADY_SIGNALED||s===n.CONDITION_SATISFIED||s===n.WAIT_FAILED||performance.now()-r>1e3)return t();setTimeout(i,4)};i()}),Da=class{constructor(e){this.host=e}host;exportToPixels(e){let t=this.renderAndStage(e,!1);return t?{width:t.outWidth,height:t.outHeight,data:_a(t.raw,t.outWidth,t.outHeight)}:null}async exportToPixelsAsync(e){let t=await this.stageAndDrain(e);return t?{width:t.outWidth,height:t.outHeight,data:_a(t.raw,t.outWidth,t.outHeight)}:null}async exportRawPixelsAsync(e){let t=await this.stageAndDrain(e);return t?{width:t.outWidth,height:t.outHeight,raw:t.raw}:null}async stageAndDrain(e){let t=this.renderAndStage(e,!0);if(!t)return null;if(!t.stagedReadback)return{outWidth:t.outWidth,outHeight:t.outHeight,raw:t.raw};let r=await this.drainStagedReadback(t.stagedReadback);return r?{outWidth:t.outWidth,outHeight:t.outHeight,raw:r}:null}renderRounds(e,t,r){let o=this.host.gl,i=0;do{this.host.renderer.beginFrame(performance.now()),o.bindFramebuffer(o.FRAMEBUFFER,e),o.clearColor(t[0],t[1],t[2],t[3]),Bp(o),this.host.batch.begin(r,this.host.zoom*this.host.dpr),this.host.meshBatch.begin(r);for(let s of this.host.sceneNodes)o.bindFramebuffer(o.FRAMEBUFFER,e),this.host.renderer.renderSceneNode(s);o.bindFramebuffer(o.FRAMEBUFFER,e),this.host.batchOrder.flushAll()}while(this.host.renderer.frame.bakeMore&&++i<64)}renderAndStage(e,t){if(!this.host.exportReady)return null;let r=Wp(e,this.host.capabilities.maxTextureSize);if(!r)return null;let o=this.host.gl,{outWidth:i,outHeight:s}=r,a=e.background??[0,0,0,0],l=i*s*4,u=this.host.bakeKReuseFloor;this.host.bakeKReuseFloor=e.bakeScaleTolerance??0;let c={framebuffer:o.getParameter(o.FRAMEBUFFER_BINDING),viewport:o.getParameter(o.VIEWPORT),clearColor:o.getParameter(o.COLOR_CLEAR_VALUE),program:o.getParameter(o.CURRENT_PROGRAM),activeTexture:o.getParameter(o.ACTIVE_TEXTURE),textureBinding:o.getParameter(o.TEXTURE_BINDING_2D),packBuffer:o.getParameter(o.PIXEL_PACK_BUFFER_BINDING),blendEnabled:o.isEnabled(o.BLEND),blendSrcRgb:o.getParameter(o.BLEND_SRC_RGB),blendDstRgb:o.getParameter(o.BLEND_DST_RGB),blendSrcAlpha:o.getParameter(o.BLEND_SRC_ALPHA),blendDstAlpha:o.getParameter(o.BLEND_DST_ALPHA)},h=Op(o),d=null,f=o.createTexture(),m=o.createFramebuffer(),p=null,b=new Uint8Array(0),g=null,x=!1;try{if(o.bindTexture(o.TEXTURE_2D,f),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,i,s,0,o.RGBA,o.UNSIGNED_BYTE,null),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindFramebuffer(o.FRAMEBUFFER,m),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,f,0),d=Fp(o,i,s),o.checkFramebufferStatus(o.FRAMEBUFFER)!==o.FRAMEBUFFER_COMPLETE)return null;p=this.host.applyExportViewport(eu(e,r),i,s);let S=Hp(e,r);if(o.viewport(0,0,i,s),this.renderRounds(m,a,S),o.bindFramebuffer(o.FRAMEBUFFER,m),t&&Gp(o)){let w=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,w),o.bufferData(o.PIXEL_PACK_BUFFER,l,o.STREAM_READ),o.readPixels(0,0,i,s,o.RGBA,o.UNSIGNED_BYTE,0);let y=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);o.flush(),o.bindBuffer(o.PIXEL_PACK_BUFFER,c.packBuffer),g={gl:o,pbo:w,fence:y,byteLength:l},x=!0}else b=new Uint8Array(l),o.readPixels(0,0,i,s,o.RGBA,o.UNSIGNED_BYTE,b)}finally{o.bindFramebuffer(o.FRAMEBUFFER,c.framebuffer),o.viewport(c.viewport[0],c.viewport[1],c.viewport[2],c.viewport[3]),o.clearColor(c.clearColor[0],c.clearColor[1],c.clearColor[2],c.clearColor[3]),o.useProgram(c.program),o.activeTexture(c.activeTexture),o.bindTexture(o.TEXTURE_2D,c.textureBinding&&o.isTexture(c.textureBinding)?c.textureBinding:null),o.bindBuffer(o.PIXEL_PACK_BUFFER,c.packBuffer),c.blendEnabled?o.enable(o.BLEND):o.disable(o.BLEND),o.blendFuncSeparate(c.blendSrcRgb,c.blendDstRgb,c.blendSrcAlpha,c.blendDstAlpha),h(),p?.(),d&&o.deleteRenderbuffer(d),m&&o.deleteFramebuffer(m),f&&o.deleteTexture(f),g&&!x&&(o.deleteBuffer(g.pbo),g.fence&&o.deleteSync(g.fence)),this.host.bakeKReuseFloor=u,this.host.requestRenderAll()}return g?{outWidth:i,outHeight:s,raw:b,stagedReadback:g}:b.length?{outWidth:i,outHeight:s,raw:b,stagedReadback:null}:null}async drainGpuBacklog(){let e=this.host.gl;if(!Gp(e))return;let t=null;try{if(t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0),!t)return;await Xp(e,t)}catch{}finally{t&&e.deleteSync(t)}}async drainStagedReadback(e){let{gl:t,pbo:r,fence:o,byteLength:i}=e;try{if(o&&await Xp(t,o),!this.host.exportReady)return null;let s=new Uint8Array(i),a=t.getParameter(t.PIXEL_PACK_BUFFER_BINDING);return t.bindBuffer(t.PIXEL_PACK_BUFFER,r),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,s),t.bindBuffer(t.PIXEL_PACK_BUFFER,a),s}catch{return null}finally{t.deleteBuffer(r),o&&t.deleteSync(o)}}exportToCanvas(e){let t=this.exportToPixels(e);if(!t)return null;let r=document.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");if(!o)return null;let i=o.createImageData(t.width,t.height);return i.data.set(t.data),o.putImageData(i,0,0),r}exportToDataURL(e,t="image/png",r){let o=this.exportToCanvas(e);return o?o.toDataURL(t,r):null}};var tu=[.8705882352941177,.8627450980392157,.8627450980392157],JS=8,ev=`#version 300 es
1038
1038
  layout(location = 0) in vec2 aPos;
1039
1039
  uniform mat3 uView;
1040
1040
  out vec2 vScene;
1041
1041
  void main() {
1042
1042
  vScene = aPos;
1043
1043
  gl_Position = vec4(uView * vec3(aPos, 1.0), 1.0);
1044
- }`,ev=`#version 300 es
1044
+ }`,tv=`#version 300 es
1045
1045
  precision highp float;
1046
1046
  in vec2 vScene;
1047
1047
  uniform mat3 uVpt;
@@ -1061,14 +1061,14 @@ float inside = 1.0 - smoothstep(-uAa, uAa, d);
1061
1061
  vec2 screen = (uVpt * vec3(vScene, 1.0)).xy;
1062
1062
  float parity = mod(floor(screen.x / uTile) + floor(screen.y / uTile), 2.0);
1063
1063
  outColor = vec4(mix(vec3(1.0), uDark, parity), inside);
1064
- }`,Fa=class{program=null;vao=null;vertexBuffer=null;corners=new Float32Array(12);invalidate(){this.program=null,this.vao=null,this.vertexBuffer=null}init(e){let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[WorkspaceChecker] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,JS),o=t(e.FRAGMENT_SHADER,ev),i=e.createProgram();return!r||!o||!i?(r&&e.deleteShader(r),o&&e.deleteShader(o),!1):(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),e.getProgramParameter(i,e.LINK_STATUS)?(this.program=i,this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.corners.byteLength,e.DYNAMIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null),!0):(console.warn("[WorkspaceChecker] link:",e.getProgramInfoLog(i)),e.deleteProgram(i),!1))}draw(e,t){if(!this.program&&!this.init(e))return;let{view:r,vpt:o,left:i,top:s,width:a,height:l,zoom:u,dpr:c}=t;if(!(u>0)||!(c>0)||!(a>0)||!(l>0))return;let h=1.5/(u*c),d=i,f=s,m=i+a,p=s+l,b=this.corners;b[0]=d,b[1]=f,b[2]=m,b[3]=f,b[4]=m,b[5]=p,b[6]=d,b[7]=f,b[8]=m,b[9]=p,b[10]=d,b[11]=p;let g=this.program;e.useProgram(g),e.bindVertexArray(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,b);let x=new Float32Array([r[0],r[1],0,r[2],r[3],0,r[4],r[5],1]),S=new Float32Array([o[0],o[1],0,o[2],o[3],0,o[4],o[5],1]);e.uniformMatrix3fv(e.getUniformLocation(g,"uView"),!1,x),e.uniformMatrix3fv(e.getUniformLocation(g,"uVpt"),!1,S),e.uniform2f(e.getUniformLocation(g,"uCenter"),i+a/2,s+l/2),e.uniform2f(e.getUniformLocation(g,"uHalf"),a/2,l/2),e.uniform1f(e.getUniformLocation(g,"uAa"),h),e.uniform1f(e.getUniformLocation(g,"uTile"),ZS),e.uniform3f(e.getUniformLocation(g,"uDark"),eu[0],eu[1],eu[2]),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLES,0,6),e.bindVertexArray(null)}};var tu=[243/255,243/255,243/255],tv=8,nv=.07,rv=`#version 300 es
1064
+ }`,Fa=class{program=null;vao=null;vertexBuffer=null;corners=new Float32Array(12);invalidate(){this.program=null,this.vao=null,this.vertexBuffer=null}init(e){let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[WorkspaceChecker] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,ev),o=t(e.FRAGMENT_SHADER,tv),i=e.createProgram();return!r||!o||!i?(r&&e.deleteShader(r),o&&e.deleteShader(o),!1):(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),e.getProgramParameter(i,e.LINK_STATUS)?(this.program=i,this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.corners.byteLength,e.DYNAMIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null),!0):(console.warn("[WorkspaceChecker] link:",e.getProgramInfoLog(i)),e.deleteProgram(i),!1))}draw(e,t){if(!this.program&&!this.init(e))return;let{view:r,vpt:o,left:i,top:s,width:a,height:l,zoom:u,dpr:c}=t;if(!(u>0)||!(c>0)||!(a>0)||!(l>0))return;let h=1.5/(u*c),d=i,f=s,m=i+a,p=s+l,b=this.corners;b[0]=d,b[1]=f,b[2]=m,b[3]=f,b[4]=m,b[5]=p,b[6]=d,b[7]=f,b[8]=m,b[9]=p,b[10]=d,b[11]=p;let g=this.program;e.useProgram(g),e.bindVertexArray(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,b);let x=new Float32Array([r[0],r[1],0,r[2],r[3],0,r[4],r[5],1]),S=new Float32Array([o[0],o[1],0,o[2],o[3],0,o[4],o[5],1]);e.uniformMatrix3fv(e.getUniformLocation(g,"uView"),!1,x),e.uniformMatrix3fv(e.getUniformLocation(g,"uVpt"),!1,S),e.uniform2f(e.getUniformLocation(g,"uCenter"),i+a/2,s+l/2),e.uniform2f(e.getUniformLocation(g,"uHalf"),a/2,l/2),e.uniform1f(e.getUniformLocation(g,"uAa"),h),e.uniform1f(e.getUniformLocation(g,"uTile"),JS),e.uniform3f(e.getUniformLocation(g,"uDark"),tu[0],tu[1],tu[2]),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLES,0,6),e.bindVertexArray(null)}};var nu=[243/255,243/255,243/255],nv=8,rv=.07,ov=`#version 300 es
1065
1065
  layout(location = 0) in vec2 aPos;
1066
1066
  uniform mat3 uView;
1067
1067
  out vec2 vScene;
1068
1068
  void main() {
1069
1069
  vScene = aPos;
1070
1070
  gl_Position = vec4(uView * vec3(aPos, 1.0), 1.0);
1071
- }`,ov=`#version 300 es
1071
+ }`,iv=`#version 300 es
1072
1072
  precision highp float;
1073
1073
  in vec2 vScene;
1074
1074
  uniform vec2 uCenter;
@@ -1088,9 +1088,9 @@ float outside = smoothstep(-uAa, uAa, d);
1088
1088
  float t = clamp(d / uBlur, 0.0, 1.0);
1089
1089
  float glow = (1.0 - t) * (1.0 - t) * outside;
1090
1090
  outColor = vec4(uMask * (1.0 - glow * uGlow), outside);
1091
- }`,Oa=class{program=null;vao=null;vertexBuffer=null;corners=new Float32Array(12);invalidate(){this.program=null,this.vao=null,this.vertexBuffer=null}init(e){let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[WorkspaceGlow] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,rv),o=t(e.FRAGMENT_SHADER,ov),i=e.createProgram();return!r||!o||!i?(r&&e.deleteShader(r),o&&e.deleteShader(o),!1):(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),e.getProgramParameter(i,e.LINK_STATUS)?(this.program=i,this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.corners.byteLength,e.DYNAMIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null),!0):(console.warn("[WorkspaceGlow] link:",e.getProgramInfoLog(i)),e.deleteProgram(i),!1))}draw(e,t){if(!this.program&&!this.init(e))return;let{view:r,vpt:o,cssWidth:i,cssHeight:s,left:a,top:l,width:u,height:c,zoom:h,dpr:d}=t;if(!(h>0)||!(d>0)||!(u>0)||!(c>0))return;let f=tv/h,m=1.5/(h*d),p=ve(o),b=Q(p,0,0),g=Q(p,i,s),x=Math.min(b.x,g.x),S=Math.min(b.y,g.y),w=Math.max(b.x,g.x),y=Math.max(b.y,g.y),v=this.corners;v[0]=x,v[1]=S,v[2]=w,v[3]=S,v[4]=w,v[5]=y,v[6]=x,v[7]=S,v[8]=w,v[9]=y,v[10]=x,v[11]=y;let R=this.program;e.useProgram(R),e.bindVertexArray(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,v);let P=new Float32Array([r[0],r[1],0,r[2],r[3],0,r[4],r[5],1]);e.uniformMatrix3fv(e.getUniformLocation(R,"uView"),!1,P),e.uniform2f(e.getUniformLocation(R,"uCenter"),a+u/2,l+c/2),e.uniform2f(e.getUniformLocation(R,"uHalf"),u/2,c/2),e.uniform1f(e.getUniformLocation(R,"uBlur"),f),e.uniform1f(e.getUniformLocation(R,"uAa"),m),e.uniform3f(e.getUniformLocation(R,"uMask"),tu[0],tu[1],tu[2]),e.uniform1f(e.getUniformLocation(R,"uGlow"),nv),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLES,0,6),e.bindVertexArray(null)}};var Ba=class{constructor(e){this.doc=e}doc;glow=new Oa;checker=new Fa;invalidate(){this.glow.invalidate(),this.checker.invalidate()}drawChecker(e,t,r){let o=this.findWorkspaceNode()?.bounds;o&&this.checker.draw(e,{view:t,vpt:r.vpt,left:o.left,top:o.top,width:o.width,height:o.height,zoom:Math.hypot(r.vpt[0],r.vpt[1]),dpr:r.dpr})}drawBackdrop(e,t,r){let o=this.findWorkspaceNode()?.bounds;o&&this.glow.draw(e,{view:t,vpt:r.vpt,cssWidth:r.cssWidth,cssHeight:r.cssHeight,left:o.left,top:o.top,width:o.width,height:o.height,zoom:Math.hypot(r.vpt[0],r.vpt[1]),dpr:r.dpr})}findWorkspaceNode(){let e=this.doc.nodes.find(t=>String(t.raw.id??"")===Sn);return!e||!e.visible||!(e.bounds.width>0)||!(e.bounds.height>0)?null:e}};var iv=.02,sv=256,nu=class n{domCanvasEl;exportStandInEl=null;get canvasEl(){return this.exportStandInEl??this.domCanvasEl}isExporting(){return this.exportStandInEl!==null}handle;batch;meshBatch;batchOrder;progressiveLoad=new da({render:()=>this.render(),nodeCount:()=>this.doc.nodes.length,alive:()=>!this.disposed&&!this.contextLost,onProgressiveDone:e=>this.bus.fire("engine:progressive-done",e)});textures;gradientRamps;glyphAtlas;renderEpoch=new Nn;bakeKReuseFloor=0;decodeAnimated=null;sources;textRenderer;renderer;exporter;workspaceBackdrop;bus=new Hn;doc=new Ao;dpr;mobileControls;interactive;editorScroll;vpt=[1,0,0,1,0,0];cssWidth=300;cssHeight=150;background;rafId=null;renderTimerId=null;contextLost=!1;disposed=!1;fontInvalidation;retainedFrame;chromeCache=null;interactions;interactionSuspended=!1;marquee=null;panning=!1;textEditing;tableCellEditing;snapGuide;rulerVisibleValue=!1;cropSessionController;expandSessionController;pathSessionController;warpSessionController;onWarpHistoryChange;animationPlaybackController;cellSelectionSink;constructor(e,t,r){Eu(),this.domCanvasEl=e,this.domCanvasEl.style.display="block",this.handle=t,this.batch=new tn(t.gl),this.meshBatch=new ca(t.gl),this.batchOrder=new la(this.batch,this.meshBatch),this.batch.order=this.batchOrder,this.meshBatch.order=this.batchOrder,this.textures=new ia(t.gl,{epoch:this.renderEpoch}),this.gradientRamps=new oa(t.gl),this.glyphAtlas=new na(t.gl,()=>this.requestRenderAll(),o=>this.fontInvalidation.queueSettle(o),this.renderEpoch),this.dpr=r.dpr??(typeof window<"u"&&window.devicePixelRatio||1),this.mobileControls=r.mobileControls??!1,this.interactive=r.interactive??!0,this.background=r.background??[0,0,0,0],this.sources=new La(this),this.textRenderer=new Ia(t.gl,this.batch,this.glyphAtlas),this.renderer=new ka(this,this.sources,this.textRenderer),this.textRenderer.attachPatternSources(this.sources),this.fontInvalidation=new ta(this,this.textRenderer,this.glyphAtlas,this.renderer),this.retainedFrame=new fa(this),this.exporter=new Da(this),this.workspaceBackdrop=new Ba(this.doc),this.textEditing=new Js(this),this.tableCellEditing=new Zs(this),this.snapGuide=new qs(this,qa),this.cropSessionController=new Gs(this),this.expandSessionController=new Xs(this),this.pathSessionController=new Ys(this),this.warpSessionController=new Us(this),this.editorScroll=r.editorScroll!==!1,this.animationPlaybackController=new Qs(this),this.interactions=new Ds(this,this.snapGuide,this.sources,this.interactive),this.cellSelectionSink=o=>{this.doc.events.fire("table:cellselection",o)},te.cellSelectionSink=this.cellSelectionSink}static create(e,t={}){let r=null,o=Fm(e,{onLost:()=>r?.onContextLost(),onRestored:()=>r?.onContextRestored()});return o?(r=new n(e,o,t),r):null}onContextLost(){this.contextLost=!0,this.bus.fire("engine:context-lost")}onContextRestored(){this.contextLost=!1,this.recoverGlResources(),this.bus.fire("engine:context-restored"),this.requestRenderAll()}recoverGlResources(){this.retainedFrame.invalidate(),this.batch.rebuild(),this.meshBatch.rebuild(),this.textures.invalidateAll(),this.gradientRamps.invalidateAll(),this.glyphAtlas.reset(),this.sources.invalidateGlTextures(),this.renderer.invalidateGlResources(),this.workspaceBackdrop.invalidate()}invalidateNodeTextBakes(e){this.fontInvalidation.invalidateNodeTextBakes(e)}handleFontsLoaded(e){this.fontInvalidation.handleFontsLoaded(e)}get engineDisposed(){return this.disposed}get engineContextLost(){return this.contextLost}get pointerActive(){return this.interactions.pointerActive}get events(){return this.bus}get document(){return this.doc}get capabilities(){return{maxTextureSize:this.handle.capabilities.maxTextureSize,renderer:this.handle.capabilities.renderer}}get viewportTransform(){return[...this.vpt]}get zoom(){return this.vpt[0]}get gl(){return this.handle.gl}get viewSize(){return{width:this.cssWidth,height:this.cssHeight}}workspaceRect(){let e=this.doc.nodes.find(t=>String(t.raw.id??"")===Sn)?.bounds;return e&&e.width>0&&e.height>0?{left:e.left,top:e.top,width:e.width,height:e.height}:{left:0,top:0,width:0,height:0}}cursorPoint(e){let t=this.canvasEl.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}get cropSession(){return this.cropSessionController.active?this.cropSessionController:null}get cropGhostNode(){return this.cropSessionController.target}get maskCropNode(){let e=this.cropSessionController.target;return e instanceof ae?e:null}get expandSession(){return this.expandSessionController.active?this.expandSessionController:null}get pathSession(){return this.pathSessionController.active?this.pathSessionController:null}get warpSession(){return this.warpSessionController.active?this.warpSessionController:null}get warpDebugSample(){return this.warpSessionController.debugBoundsSample}get warpDebugPreview(){return this.warpSessionController.debugPreviewInfo}get warpDebugAnchors(){return this.warpSessionController.debugAnchors}get warpSessionTarget(){return this.warpSessionController.target}get editingNode(){return this.doc.editingNode}get stats(){return{nodeCount:this.doc.nodes.length,skippedTypes:{...this.doc.skippedTypes}}}get diagnostics(){return{glError:this.handle.gl.getError(),drawnInstances:this.batch.drawnInstances,contextLost:this.contextLost}}get textureBudgetInfo(){return{textures:this.textures.stats(),atlas:this.glyphAtlas.stats()}}setTextureBudget(e){this.textures.setBudget(e)}toScene(e,t){return{x:(e-this.vpt[4])/this.vpt[0],y:(t-this.vpt[5])/this.vpt[3]}}toScreen(e,t){return{x:this.vpt[0]*e+this.vpt[4],y:this.vpt[3]*t+this.vpt[5]}}resize(e,t){e<=1||t<=1||(this.cssWidth=Math.max(1,e),this.cssHeight=Math.max(1,t),this.canvasEl.width=Math.round(this.cssWidth*this.dpr),this.canvasEl.height=Math.round(this.cssHeight*this.dpr),this.canvasEl.style.width=`${this.cssWidth}px`,this.canvasEl.style.height=`${this.cssHeight}px`,this.render())}progressiveFirstFrame(e=1e3,t=800){this.progressiveLoad.start(e,t)}async loadObjects(e){this.sources.releaseAnimatedSources(),this.animationPlaybackController.reset(),this.doc.loadObjects(e),await Qc(Kc([...this.doc.nodes]),this.sources,()=>this.requestRenderAll())}async ensureNodeSources(e){await Qc(Kc(e),this.sources,()=>this.requestRenderAll())}setViewportTransform(e){let t=this.vpt[0];this.vpt=[...e],this.renderer.noteVptChange(),e[0]!==t&&this.doc.setViewportZoom(e[0]),this.requestRenderAll()}zoomAt(e,t,r){let o=Math.min(sv,Math.max(iv,this.vpt[0]*r)),i=o/this.vpt[0];this.vpt=[o,0,0,o,e-i*(e-this.vpt[4]),t-i*(t-this.vpt[5])],this.renderer.noteVptChange(),this.doc.setViewportZoom(o),this.requestRenderAll()}pan(e,t){this.vpt[4]+=e,this.vpt[5]+=t,this.renderer.noteVptChange(),this.requestRenderAll()}noteExternalGesture(){this.renderer.noteExternalInteraction()}requestRenderAll(){this.progressiveLoad.absorbExternalRenderRequest(),!(this.rafId!==null||this.renderTimerId!==null||this.disposed||this.contextLost)&&(this.rafId=requestAnimationFrame(()=>{this.rafId=null,this.renderTimerId!==null&&(clearTimeout(this.renderTimerId),this.renderTimerId=null),this.render()}),this.renderTimerId=setTimeout(()=>{this.renderTimerId=null,this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.render()},250))}workspaceChromeNodes(){let e=this.doc.structureVersion;return(!this.chromeCache||this.chromeCache.version!==e)&&(this.chromeCache={version:e,nodes:this.doc.nodes.filter(rr)}),this.chromeCache.nodes}render(){if(this.disposed||this.contextLost||!this.batch.valid)return;this.fontInvalidation.consumePendingSettle(),this.textures.markFrame(this.pointerActive),this.glyphAtlas.markFrame(),this.snapGuide.settleMoveSnap();let e=performance.now();this.renderer.beginFrame(e),this.tickAnimation(e),Ua("engine.render",()=>{let t=this.handle.gl;t.viewport(0,0,this.canvasEl.width,this.canvasEl.height),t.clearColor(...this.background),t.clearStencil(0),t.clear(t.COLOR_BUFFER_BIT|t.STENCIL_BUFFER_BIT);let r=Zr(this.vpt,this.cssWidth,this.cssHeight,this.dpr);this.workspaceBackdrop.drawChecker(this.handle.gl,r,{vpt:this.vpt,cssWidth:this.cssWidth,cssHeight:this.cssHeight,dpr:this.dpr}),this.batch.begin(r,this.zoom*this.dpr),this.meshBatch.begin(r),this.batch.deferDraws=!0,this.meshBatch.deferDraws=!0,this.batchOrder.reset();let o=this.expandSessionController.active?this.expandSessionController.target:null;if(!(!o&&this.retainedFrame.tryRetainedFrame())){this.batch.begin(r,this.zoom*this.dpr),this.meshBatch.begin(r),this.batch.deferDraws=!0,this.meshBatch.deferDraws=!0,this.batchOrder.reset();let i=this.progressiveLoad.limit>=0?Math.min(this.progressiveLoad.limit,this.doc.nodes.length):this.doc.nodes.length;Jm(this.batch,this.renderer,this.doc.nodes,o?{target:o,underlay:()=>this.expandSessionController.buildUnderlay()}:null,i),this.batchOrder.requestSnapshot=!0,this.batchOrder.flushAll(),this.retainedFrame.captureSnapshot()}this.doc.drainRenderDirty(),this.workspaceBackdrop.drawBackdrop(this.handle.gl,r,{vpt:this.vpt,cssWidth:this.cssWidth,cssHeight:this.cssHeight,dpr:this.dpr}),ep(this.renderer,this.workspaceChromeNodes()),tp(this)}),this.retainedFrame.noteFrameRendered(),this.renderer.frame.bakeMore&&this.requestRenderAll(),this.bus.fire("engine:render",performance.now()-e)}readPixels(){return qd(this.canvasEl)}exportToPixels(e){return this.retainedFrame.invalidate(),this.exporter.exportToPixels(e)}async exportToPixelsAsync(e){return this.retainedFrame.invalidate(),this.exporter.exportToPixelsAsync(e)}async exportRawPixelsAsync(e){return this.retainedFrame.invalidate(),this.exporter.exportRawPixelsAsync(e)}exportToCanvas(e){return this.retainedFrame.invalidate(),this.exporter.exportToCanvas(e)}drainGpuBacklog(){return this.exporter.drainGpuBacklog()}exportToDataURL(e,t="image/png",r){return this.retainedFrame.invalidate(),this.exporter.exportToDataURL(e,t,r)}get exportReady(){return!this.disposed&&!this.contextLost&&this.batch.valid}get sceneNodes(){return this.doc.nodes}applyExportViewport(e,t,r){let o=this.vpt,i=this.exportStandInEl;this.vpt=[...e];let s=document.createElement("canvas");return s.width=t,s.height=r,this.exportStandInEl=s,()=>{this.vpt=o,this.exportStandInEl=i}}measureFrames(e){return Vd(e,()=>this.render())}getSceneSummary(){return jd(this.doc)}getTableCellEditingInfo(){return this.tableCellEditing.info}getTableSelectionInfo(){let e=this.doc.selection.length===1&&this.doc.selection[0]instanceof te?this.doc.selection[0]:null;return e?{tableId:e.id,cells:e.selectedCells.map(t=>({row:t.row,col:t.col})),anchor:e.cellAnchor?{...e.cellAnchor}:null,range:e.cellRange?{...e.cellRange}:null}:null}getSnapGuideInfo(){return this.snapGuide.info}enterExpandMode(e){this.cropSessionController.active&&this.cropSessionController.exit(),this.pathSessionController.active&&this.pathSessionController.exit();let t=e??this.doc.selection[0];return t?this.expandSessionController.enter(t):!1}exitExpandMode(){this.expandSessionController.exit()}getExpandInfo(){return this.expandSessionController.info}async applyExpandResult(e,t,r){let o=this.findNodeById(e);return!o||!o.isImageType&&!(o instanceof ae)?!1:this.expandSessionController.applyResult(o,t,r)}reloadImageElement(e){return this.sources.reloadNodeImage(e)}findNodeById(e){return this.doc.findNodeDeep(e)?.node??null}async reloadNodeImage(e){let t=this.findNodeById(e);return t?!!await this.sources.reloadNodeImage(t):!1}async reloadMaskClipImage(e){let t=this.findNodeById(e);return t instanceof ae?!!await this.sources.reloadMaskClipImage(t):!1}getCropInfo(){return this.cropSessionController.info}enterCropMode(e,t){this.pathSessionController.active&&this.pathSessionController.exit();let r=e??this.doc.selection[0];return r?this.cropSessionController.enter(r,t):!1}exitCropMode(){this.cropSessionController.exit()}setCropShape(e){this.cropSessionController.setCropShape(e)}updateCropScale(e){return this.cropSessionController.setScale(e)}setCropAspectRatio(e){this.cropSessionController.setAspectRatio(e)}enterPathEditMode(e){this.cropSessionController.active&&this.cropSessionController.exit(),this.expandSessionController.active&&this.expandSessionController.exit();let t=e??this.doc.selection[0];return t?this.pathSessionController.enter(t):!1}async enterWarpMode(e,t){this.cropSessionController.active&&this.cropSessionController.exit(),this.expandSessionController.active&&this.expandSessionController.exit(),this.pathSessionController.active&&this.pathSessionController.exit();let r=e??this.doc.selection[0];return r?this.warpSessionController.enter(r,t):!1}async loadImage(e,t){try{return await Je(e,t??null)}catch{return null}}async exitWarpMode(e){return this.warpSessionController.exit(e)}warpUndo(){return this.warpSessionController.undo()}warpRedo(){return this.warpSessionController.redo()}exitPathEditMode(){this.pathSessionController.exit()}getPathEditInfo(){return this.pathSessionController.info}setPathAnchorType(e,t,r){return this.pathSessionController.target===e?this.pathSessionController.setAnchorType(t,r):!1}highlightPathAnchor(e,t){this.pathSessionController.target===e&&this.pathSessionController.setActiveAnchor(t)}resetPathAnchorStyles(e){this.pathSessionController.target===e&&this.pathSessionController.resetAnchorStyles()}get rulerEnabled(){return this.rulerVisible}get rulerVisible(){return this.rulerVisibleValue}referenceLineDrag=null;rotateDrag=null;setRulerVisible(e){this.rulerVisibleValue!==e&&(this.rulerVisibleValue=e,this.requestRenderAll())}selectAll(){return Kd(this.doc,()=>this.requestRenderAll())}deleteSelection(){return Qd(this.doc,()=>this.requestRenderAll())}nudgeSelection(e,t){return Zd(this.doc,e,t,()=>this.requestRenderAll())}getSelectionInfo(){return Yd(this.doc,this.marquee,this.zoom,(e,t)=>this.toScreen(e,t))}getActiveGroupChildInfo(){return Ud(this.doc)}getSvgRasterInfo(){return $d(this.doc,e=>this.sources.svgRasterFactorOf(e))}toObjects(){return this.doc.toObjects()}playAnimations(){this.animationPlaybackController.play()}pauseAnimations(){this.animationPlaybackController.pause()}stopAnimations(){this.animationPlaybackController.stop()}seekAnimations(e){this.animationPlaybackController.seek(e)}getAnimationPlaybackInfo(){return this.animationPlaybackController.info}getScrollTextPlaybackInfo(){return this.animationPlaybackController.scrollTextInfo}playSingleAnimation(e,t,r){return this.animationPlaybackController.playSingleAnimation(e,t,r)}stopSingleAnimation(e){this.animationPlaybackController.stopSingleAnimation(e)}getSingleAnimationPreviewInfo(){return this.animationPlaybackController.singlePreviewInfo}tickAnimation(e){this.animationPlaybackController.tick(e)&&(this.renderer.frame.animationActive=!0)}setEditingSelection(e,t){this.textEditing.setSelection(e,t)}settleMoveSnap(){this.snapGuide.settleMoveSnap()}finishSnapGesture(){this.snapGuide.finishGesture()}registerScalingSnap(e,t){this.snapGuide.registerScaling(e,t)}startCellEditing(e,t,r,o){return this.tableCellEditing.startEditing(e,t,r,o)}enterTextEditingAtClick(e,t,r){this.textEditing.enterEditingAtClick(e,t,r)}dispose(){this.disposed||(this.disposed=!0,this.cellSelectionSink&&te.cellSelectionSink===this.cellSelectionSink&&(te.cellSelectionSink=null),this.rafId!==null&&cancelAnimationFrame(this.rafId),this.renderTimerId!==null&&clearTimeout(this.renderTimerId),this.retainedFrame.dispose(),this.progressiveLoad.dispose(),this.interactions.dispose(),this.tableCellEditing.dispose(),this.cropSessionController.dispose(),this.expandSessionController.dispose(),this.pathSessionController.dispose(),this.textEditing.dispose(),this.bus.clear(),this.sources.releaseAnimatedSources(),this.batch.dispose(),this.meshBatch.dispose(),this.textures.dispose(),this.gradientRamps.dispose(),this.sources.dispose(),this.glyphAtlas.dispose(),this.handle.dispose())}};var nn=class n{constructor(e=0,t=0){this.x=e;this.y=t}x;y;add(e){return new n(this.x+e.x,this.y+e.y)}subtract(e){return new n(this.x-e.x,this.y-e.y)}scalarDivide(e){return new n(this.x/e,this.y/e)}rotate(e,t={x:0,y:0}){let r=Math.sin(e),o=Math.cos(e),i=this.subtract(t);return new n(i.x*o-i.y*r,i.x*r+i.y*o).add(t)}},ru=class n{constructor(e=0,t=0){typeof e=="number"?(this.x=e,this.y=t):(this.x=e.x,this.y=e.y)}x=0;y=0;add(e){return new n(this.x+e.x,this.y+e.y)}subtract(e){return new n(this.x-e.x,this.y-e.y)}multiply(e){return new n(this.x*e.x,this.y*e.y)}divide(e){return new n(this.x/e.x,this.y/e.y)}scalarAdd(e){return new n(this.x+e,this.y+e)}scalarSubtract(e){return new n(this.x-e,this.y-e)}scalarMultiply(e){return new n(this.x*e,this.y*e)}scalarDivide(e){return new n(this.x/e,this.y/e)}rotate(e){let t=e*Math.PI/180,r=Math.cos(t),o=Math.sin(t);return new n(this.x*r-this.y*o,this.x*o+this.y*r)}dot(e){return this.x*e.x+this.y*e.y}midPointFrom(e){return new n((this.x+e.x)/2,(this.y+e.y)/2)}static lerp(e,t,r){return new n(e.x+(t.x-e.x)*r,e.y+(t.y-e.y)*r)}lerp(e,t){return new n(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)}eq(e){return this.x===e.x&&this.y===e.y}lt(e){return this.x<e.x&&this.y<e.y}gt(e){return this.x>e.x&&this.y>e.y}lte(e){return this.x<=e.x&&this.y<=e.y}gte(e){return this.x>=e.x&&this.y>=e.y}distanceFrom(e){return Math.hypot(this.x-e.x,this.y-e.y)}clone(){return new n(this.x,this.y)}toString(){return`${this.x} ${this.y}`}transform(e,t=!1){return t?new n(e[0]*this.x+e[2]*this.y,e[1]*this.x+e[3]*this.y):new n(e[0]*this.x+e[2]*this.y+e[4],e[1]*this.x+e[3]*this.y+e[5])}};var rn=(n,e=0)=>typeof n=="number"&&Number.isFinite(n)?n:e,av=n=>({sx:rn(n.scaleX,1)||1,sy:rn(n.scaleY,1)||1}),Xp=n=>{let e=n.pathOffset;return!e||typeof e.x!="number"||typeof e.y!="number"?null:{x:e.x,y:e.y}},lv=n=>{let e=Ce(n),t=e?Fe(e):null;return t?{x:(t.left+t.right)/2,y:(t.top+t.bottom)/2}:null},cv=n=>{if(n.length===0)return null;let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)e>i.x&&(e=i.x),t>i.y&&(t=i.y),r<i.x&&(r=i.x),o<i.y&&(o=i.y);return{x:(e+r)/2,y:(t+o)/2}},uv=(n,e,t,r)=>`M ${t} 0 L ${n-t} 0 A ${t} ${r} 0 0 1 ${n} ${r} L ${n} ${e-r} A ${t} ${r} 0 0 1 ${n-t} ${e} L ${t} ${e} A ${t} ${r} 0 0 1 0 ${e-r} L 0 ${r} A ${t} ${r} 0 0 1 ${t} 0 Z`,zp=(n,e)=>`M 0 ${-e} A ${n} ${e} 0 1 1 0 ${e} A ${n} ${e} 0 1 1 0 ${-e} Z`,ou=n=>{if(n.isTextType)return;let e=n.raw,t=se(e),{sx:r,sy:o}=av(e);if(t===L.PATH){let a="";if(typeof e.path=="string")a=e.path;else if(Array.isArray(e.path)){let l=[];for(let u of e.path)!Array.isArray(u)||typeof u[0]!="string"||l.push(u.length===1?u[0]:`${u[0]} ${u.slice(1).join(" ")}`);a=l.join(" ")}return a.trim()?{path:a,pathOffset:Xp(e)??lv(a)??{x:0,y:0}}:void 0}if(t===L.RECT||t===L.FABRICRECT){let a=n.dims.x*r,l=n.dims.y*o;if(!(a>0)||!(l>0))return;let u=it(e,n.dims.x,n.dims.y),c=u?Math.min(u.rx*r,a/2):0,h=u?Math.min(u.ry*o,l/2):0;return{path:c>0||h>0?uv(a,l,c,h):`M 0 0 L ${a} 0 L ${a} ${l} L 0 ${l} Z`,pathOffset:{x:a/2,y:l/2}}}if(t===L.CIRCLE){let a=rn(e.radius);return a>0?{path:zp(a*r,a*o),pathOffset:{x:0,y:0}}:void 0}if(t===L.ELLIPSE){let a=(rn(e.rx)||n.dims.x/2)*r,l=(rn(e.ry)||n.dims.y/2)*o;return!(a>0)||!(l>0)?void 0:{path:zp(a,l),pathOffset:{x:0,y:0}}}if(t===L.TRIANGLE){let a=n.dims.x*r,l=n.dims.y*o;return!(a>0)||!(l>0)?void 0:{path:`M ${-a/2} ${l/2} L 0 ${-l/2} L ${a/2} ${l/2} Z`,pathOffset:{x:0,y:0}}}if(t===L.POLYGON||t===L.POLYLINE){let a=Array.isArray(e.points)?e.points:[];return a.length===0?{path:"M 0 0",pathOffset:{x:0,y:0}}:{path:a.map((u,c)=>`${c===0?"M":"L"} ${u.x} ${u.y}`).join(" ")+(t===L.POLYGON?" Z":""),pathOffset:Xp(e)??cv(a)??{x:0,y:0}}}if(t===L.LINE){let a=rn(e.x1),l=rn(e.y1),u=rn(e.x2),c=rn(e.y2);return{path:`M ${a} ${l} L ${u} ${c}`,pathOffset:{x:0,y:0}}}let i=n.dims.x*r,s=n.dims.y*o;if(!(!(i>0)||!(s>0)))return{path:`M 0 0 L ${i} 0 L ${i} ${s} L 0 ${s} Z`,pathOffset:{x:i/2,y:s/2}}};var Yp=n=>{if(!(!n||n.length<8||n.some(e=>typeof e!="number"||!Number.isFinite(e))))return{tl:{x:n[0],y:n[1]},tr:{x:n[2],y:n[3]},br:{x:n[4],y:n[5]},bl:{x:n[6],y:n[7]}}},Up=n=>{let e=[n.tl,n.tr,n.br,n.bl],t=Math.min(...e.map(s=>s.x)),r=Math.min(...e.map(s=>s.y)),o=Math.max(...e.map(s=>s.x)),i=Math.max(...e.map(s=>s.y));return{minX:t,minY:r,width:Math.max(1,Math.ceil(o-t)),height:Math.max(1,Math.ceil(i-r))}},$p=(n,e,t)=>({tl:{x:n.tl.x+e,y:n.tl.y+t},tr:{x:n.tr.x+e,y:n.tr.y+t},br:{x:n.br.x+e,y:n.br.y+t},bl:{x:n.bl.x+e,y:n.bl.y+t}}),jp=n=>{let e=n.tr.x+n.bl.x-n.tl.x,t=n.tr.y+n.bl.y-n.tl.y;return Math.abs(e-n.br.x)<.01&&Math.abs(t-n.br.y)<.01},iu=n=>{let e=n.tl.x-n.tr.x+n.br.x-n.bl.x,t=n.tl.y-n.tr.y+n.br.y-n.bl.y;if(Math.abs(e)<1e-6&&Math.abs(t)<1e-6)return{a:n.tr.x-n.tl.x,b:n.bl.x-n.tl.x,c:n.tl.x,d:n.tr.y-n.tl.y,e:n.bl.y-n.tl.y,f:n.tl.y,g:0,h:0};let r=n.tr.x-n.br.x,o=n.tr.y-n.br.y,i=n.bl.x-n.br.x,s=n.bl.y-n.br.y,a=r*s-i*o;if(Math.abs(a)<1e-6)return;let l=(e*s-i*t)/a,u=(r*t-e*o)/a;return{a:n.tr.x-n.tl.x+l*n.tr.x,b:n.bl.x-n.tl.x+u*n.bl.x,c:n.tl.x,d:n.tr.y-n.tl.y+l*n.tr.y,e:n.bl.y-n.tl.y+u*n.bl.y,f:n.tl.y,g:l,h:u}},qr=(n,e,t)=>{let r=n.g*e+n.h*t+1;return{x:(n.a*e+n.b*t+n.c)/r,y:(n.d*e+n.e*t+n.f)/r}},Vp=n=>{let{a:e,b:t,c:r,d:o,e:i,f:s,g:a,h:l}=n,u=e*(i-s*l)-t*(o-s*a)+r*(o*l-i*a);if(Math.abs(u)<1e-6)return;let c=(i-s*l)/u,h=(r*l-t)/u,d=(t*s-r*i)/u,f=(s*a-o)/u,m=(e-r*a)/u,p=(r*o-e*s)/u,b=(o*l-i*a)/u,g=(t*a-e*l)/u,x=(e*i-t*o)/u;if(!(Math.abs(x)<1e-6))return{a:c/x,b:h/x,c:d/x,d:f/x,e:m/x,f:p/x,g:b/x,h:g/x}};var qp=32,Kp=120,su=1e-6,hv=()=>{let n=document.createElement("canvas");if(!n||typeof n.getContext>"u")throw new Error("Failed to create `canvas` element");return n},dv=n=>{let e=hv();return e.width=n.width,e.height=n.height,e.getContext("2d",{willReadFrequently:!0})?.drawImage(n,0,0),e},fv=(n,e,t)=>n.toDataURL?.(`image/${e}`,t),mv=n=>new Promise((e,t)=>{let r=new FileReader;r.onload=()=>e(String(r.result)),r.onerror=()=>t(r.error),r.readAsDataURL(n)}),Qp=async(n,e,t)=>{try{let r=await new Promise(o=>n.toBlob(o,`image/${e}`,t));if(r)return await mv(r)}catch{}return fv(n,e,t)},pv=(n,e,t)=>{let r=Math.max(1,n.width),o=Math.max(1,n.height),i=Math.max(1,Math.round(e)),s=Math.max(1,Math.round(t));if(Math.abs(r-i)<su&&Math.abs(o-s)<su)return n;let a=document.createElement("canvas");a.width=i,a.height=s;let l=a.getContext("2d");return l?(l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.drawImage(n,0,0,r,o,0,0,i,s),a):n},bv=(n,e,t,r,o)=>{let i=Math.max(0,Math.min(e-1,r)),s=Math.max(0,Math.min(t-1,o)),a=Math.floor(i),l=Math.floor(s),u=Math.min(e-1,a+1),c=Math.min(t-1,l+1),h=i-a,d=s-l,f=(l*e+a)*4,m=(l*e+u)*4,p=(c*e+a)*4,b=(c*e+u)*4,g=1-d,x=1-h,S=x*g,w=h*g,y=x*d,v=h*d;return[n[f]*S+n[m]*w+n[p]*y+n[b]*v,n[f+1]*S+n[m+1]*w+n[p+1]*y+n[b+1]*v,n[f+2]*S+n[m+2]*w+n[p+2]*y+n[b+2]*v,n[f+3]*S+n[m+3]*w+n[p+3]*y+n[b+3]*v]},gv=(n,e,t)=>{let r=iu(t),o=r?Vp(r):void 0;if(!o){Jp(n,e,t,qp);return}let i=Math.max(1,e.width),s=Math.max(1,e.height),a=e.getContext("2d",{willReadFrequently:!0});if(!a){Jp(n,e,t,qp);return}let l=a.getImageData(0,0,i,s),u=n.createImageData(n.canvas.width,n.canvas.height),c=u.data;for(let h=0;h<n.canvas.height;h++)for(let d=0;d<n.canvas.width;d++){let f=qr(o,d+.5,h+.5);if(f.x<0||f.x>1||f.y<0||f.y>1)continue;let m=f.x*(i-1),p=f.y*(s-1),b=bv(l.data,i,s,m,p),g=(h*n.canvas.width+d)*4;c[g]=b[0],c[g+1]=b[1],c[g+2]=b[2],c[g+3]=b[3]}n.putImageData(u,0,0)},Zp=(n,e,t,r)=>{let[o,i,s]=t,[a,l,u]=r,c=o.x*(i.y-s.y)+i.x*(s.y-o.y)+s.x*(o.y-i.y);if(Math.abs(c)<su)return;let h=(a.x*(i.y-s.y)+l.x*(s.y-o.y)+u.x*(o.y-i.y))/c,d=(a.y*(i.y-s.y)+l.y*(s.y-o.y)+u.y*(o.y-i.y))/c,f=(a.x*(s.x-i.x)+l.x*(o.x-s.x)+u.x*(i.x-o.x))/c,m=(a.y*(s.x-i.x)+l.y*(o.x-s.x)+u.y*(i.x-o.x))/c,p=(a.x*(i.x*s.y-s.x*i.y)+l.x*(s.x*o.y-o.x*s.y)+u.x*(o.x*i.y-i.x*o.y))/c,b=(a.y*(i.x*s.y-s.x*i.y)+l.y*(s.x*o.y-o.x*s.y)+u.y*(o.x*i.y-i.x*o.y))/c;n.save(),n.beginPath(),n.moveTo(a.x,a.y),n.lineTo(l.x,l.y),n.lineTo(u.x,u.y),n.closePath(),n.clip(),n.setTransform(h,d,f,m,p,b),n.drawImage(e,0,0),n.restore()},Jp=(n,e,t,r)=>{let o=iu(t);if(!o){n.drawImage(e,0,0,n.canvas.width,n.canvas.height);return}let i=Math.max(1,e.width),s=Math.max(1,e.height),a=Math.min(Kp,Math.max(1,Math.ceil(i/r))),l=Math.min(Kp,Math.max(1,Math.ceil(s/r)));for(let u=0;u<l;u++){let c=u/l,h=(u+1)/l,d=c*s,f=h*s;for(let m=0;m<a;m++){let p=m/a,b=(m+1)/a,g=p*i,x=b*i,S=qr(o,p,c),w=qr(o,b,c),y=qr(o,b,h),v=qr(o,p,h);Zp(n,e,[{x:g,y:d},{x,y:d},{x,y:f}],[S,w,y]),Zp(n,e,[{x:g,y:d},{x,y:f},{x:g,y:f}],[S,y,v])}}},xv=async(n,e,t={})=>{let r=t.quality??.92,o=t.format||"webp",i=Math.max(1,n.width),s=Math.max(1,n.height),a=Math.max(1,e?.width||i),l=Math.max(1,e?.height||s),u=pv(n,a,l),c=Yp(e?.nonAffineTransform||e?.transform);if(!c){let g=dv(n);return{src:await Qp(g,o,r),width:i,height:s,sourceWidth:a,sourceHeight:l}}let h=Up(c),d=$p(c,-h.minX,-h.minY),f=t.objectBounds,m=document.createElement("canvas");m.width=h.width,m.height=h.height;let p=m.getContext("2d");if(!p)throw new Error("无法创建智能对象渲染画布");if(p.imageSmoothingEnabled=!0,p.imageSmoothingQuality="high",jp(d)){let g=(d.tr.x-d.tl.x)/a,x=(d.tr.y-d.tl.y)/a,S=(d.bl.x-d.tl.x)/l,w=(d.bl.y-d.tl.y)/l,y=d.tl.x,v=d.tl.y;p.setTransform(g,x,S,w,y,v),p.drawImage(u,0,0)}else gv(p,u,d);let b;if(f){let g=Math.round(f.left-h.minX),x=Math.round(f.top-h.minY),S=Math.max(1,Math.round(f.width)),w=Math.max(1,Math.round(f.height));if(g>=0&&x>=0&&g+S<=h.width+1&&x+w<=h.height+1){b=document.createElement("canvas"),b.width=S,b.height=w;let v=b.getContext("2d");v&&v.drawImage(m,g,x,S,w,0,0,S,w)}else{b=document.createElement("canvas"),b.width=S,b.height=w;let v=b.getContext("2d");v&&(v.imageSmoothingEnabled=!0,v.imageSmoothingQuality="high",v.drawImage(m,0,0,h.width,h.height,0,0,S,w))}}else b=m;return{src:await Qp(b,o,r),width:b.width,height:b.height,sourceWidth:a,sourceHeight:l}};var ce=n=>n.node instanceof te?n.node:null,Be=n=>n.raw,kt=n=>{n.canvas?.requestRenderAll?.()},Ve=(n,e)=>{let t=Be(e);n.set({cellData:t.cellData??[],rows:t.rows,cols:t.cols}),kt(n)},au=n=>n.rows??3,lu=n=>n.cols??3,Kr=n=>(Array.isArray(n.cellData)||(n.cellData=[]),n.cellData),ri=(n,e,t)=>{let r=we(n.cellMap,e,t);if(r)return r.isMerged&&r.mergeParent?we(n.cellMap,r.mergeParent.row,r.mergeParent.col):r},Xt=(n,e)=>{let t=ce(n);if(!t||!t.selectedCells.length)return;let r=new Set;for(let o of t.selectedCells){let i=lt(t.cellMap,o.row,o.col),s=`${i.row},${i.col}`;if(r.has(s))continue;r.add(s);let a=we(t.cellMap,i.row,i.col);a&&e(a)}Ve(n,t)},cu=(n,e,t)=>({get id(){return`${n.id}-r${e.row}c${e.col}-rect`},get _isCell(){return!0},get _row(){return e.row},get _col(){return e.col},get fill(){return e.fill},set fill(r){e.fill=r,t()},get stroke(){return e.stroke},set stroke(r){e.stroke=r,t()},get strokeWidth(){return e.strokeWidth??1},set strokeWidth(r){e.strokeWidth=r,t()},get _colspan(){return e.colspan??1},set _colspan(r){e.colspan=r,t()},get _rowspan(){return e.rowspan??1},set _rowspan(r){e.rowspan=r,t()},get _isMerged(){return e.isMerged??!1},set _isMerged(r){e.isMerged=r,t()},get _mergeParent(){return e.mergeParent??null},set _mergeParent(r){e.mergeParent=r,t()},get _hasCustomFill(){return e.hasCustomFill??!1},set _hasCustomFill(r){e.hasCustomFill=r,t()},get _hasCustomStroke(){return e.hasCustomStroke??!1},set _hasCustomStroke(r){e.hasCustomStroke=r,t()},set(r){for(let[o,i]of Object.entries(r))o!=="dirty"&&(e[o]=i);t()},get(r){return e[r]}}),eb=(n,e,t)=>({get id(){return`${n.id}-r${e.row}c${e.col}-text`},get _isCellText(){return!0},get _row(){return e.row},get _col(){return e.col},get text(){return e.text??""},set text(r){e.text=r,t()},get fill(){return e.textFill},set fill(r){e.textFill=r,t()},get fontSize(){return e.fontSize??Be(n).fontSize??14},set fontSize(r){e.fontSize=r,t()},get fontWeight(){return e.fontWeight},set fontWeight(r){e.fontWeight=r,t()},get fontFamily(){return e.fontFamily},set fontFamily(r){e.fontFamily=r,t()},get fontStyle(){return e.fontStyle},set fontStyle(r){e.fontStyle=r,t()},get textAlign(){return e.textAlign},set textAlign(r){e.textAlign=r,t()},get underline(){return e.underline??!1},set underline(r){e.underline=r,t()},get linethrough(){return e.linethrough??!1},set linethrough(r){e.linethrough=r,t()},get verticalAlign(){return e.verticalAlign??"middle"},set verticalAlign(r){e.verticalAlign=r,t()},set(r){for(let[o,i]of Object.entries(r))o!=="dirty"&&(o==="fill"?e.textFill=i:e[o]=i);t()},get(r){return r==="fill"?e.textFill:e[r]},setFontFamily(r){e.fontFamily=r,t()},refreshTextDimensions(){}}),yv={canMergeCells(){let n=ce(this);return!!n&&n.selectedCells.length>1},canUseMergeCells(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=new Set,t=!1;for(let{row:r,col:o}of n.selectedCells){let i=ri(n,r,o);if(!i)return!1;(i.colspan??1)>1||(i.rowspan??1)>1?e.add(`${i.row},${i.col}`):t=!0}return!t&&e.size===1},canSplitRows(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=n.selectedCells[0],t=ri(n,e.row,e.col);return!!t&&(t.rowspan??1)>1},canSplitColumns(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=n.selectedCells[0],t=ri(n,e.row,e.col);return!!t&&(t.colspan??1)>1},isSelectColumn(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=new Set(n.selectedCells.map(r=>r.row)),t=new Set(n.selectedCells.map(r=>r.col));if(t.size===1){let r=Array.from(e),o=Math.min(...r),i=Math.max(...r),s=o===0&&i===au(Be(n))-1,a=e.size>=2,l=!1;for(let u of n.selectedCells)if((ri(n,u.row,u.col)?.rowspan??1)>1){l=!0;break}return s||a||l}return t.size>1?e.size===1?!1:e.size<=t.size:!1},isSelectRow(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=new Set(n.selectedCells.map(r=>r.row)),t=new Set(n.selectedCells.map(r=>r.col));if(e.size===1){let r=Array.from(t),o=Math.min(...r),i=Math.max(...r),s=o===0&&i===lu(Be(n))-1,a=t.size>=2,l=!1;for(let u of n.selectedCells)if((ri(n,u.row,u.col)?.colspan??1)>1){l=!0;break}return s||a||l}return e.size>1?t.size===1?!1:e.size>t.size:!1},isRowSelected(n){let e=ce(this);return e?Ar(e.cellMap,e.selectedCells).rows.has(n):!1},isColumnSelected(n){let e=ce(this);return e?Ar(e.cellMap,e.selectedCells).cols.has(n):!1},selectCell(n,e,t=!1){let r=ce(this);if(r){if(t){if(r.cellAnchor){let o=r.cellAnchor,i=xn(r.cellMap,o,{row:n,col:e});r.setCellSelection(i,o,{r1:Math.min(o.row,n),r2:Math.max(o.row,n),c1:Math.min(o.col,e),c2:Math.max(o.col,e)})}}else{let o={row:n,col:e};r.setCellSelection([o],o,{r1:n,r2:n,c1:e,c2:e})}kt(this)}},selectColumn(n){let e=ce(this);e&&(e.setColumnSelection(n),kt(this))},selectRow(n){let e=ce(this);e&&(e.setRowSelection(n),kt(this))},selectAllCells(){let n=ce(this);if(!n)return;let e=n.tableView,t=Mo(n.cellMap,e.rows,e.cols);n.setCellSelection(t,t[0]??null,ze(t)),kt(this)},clearCellSelection(){let n=ce(this);n&&(n.clearCellSelection(),kt(this))},buildSelectionRange(n,e){let t=ce(this);return t?xn(t.cellMap,n,e):[]},mergeCells(n,e,t,r){let o=ce(this);if(!o)return;let i=So(o.raw,n,e,t,r),s={row:i.r1,col:i.c1};o.setCellSelection([s],s,i),Ve(this,o)},unmergeCells(n,e){let t=ce(this);if(!t||!vo(t.raw,n,e))return;let r={row:n,col:e};t.setCellSelection([r],r,{r1:n,r2:n,c1:e,c2:e}),Ve(this,t)},addRow(n){let e=ce(this);e&&(wo(e.raw,n??au(Be(e))),Ve(this,e))},removeRow(n){let e=ce(this);if(!e)return;let t=n??au(Be(e))-1;if(!Il(e.raw,t))return;let r=Vi(e.selectedCells,e.cellRange,t,"row");r?e.setCellSelection(r.cells,r.cells[0]??null,r.range):e.clearCellSelection(),Ve(this,e)},addColumn(n){let e=ce(this);e&&(To(e.raw,n??lu(Be(e))),Ve(this,e))},removeColumn(n){let e=ce(this);if(!e)return;let t=n??lu(Be(e))-1;if(!_l(e.raw,t))return;let r=Vi(e.selectedCells,e.cellRange,t,"col");r?e.setCellSelection(r.cells,r.cells[0]??null,r.range):e.clearCellSelection(),Ve(this,e)},setColumnWidth(n,e){let t=ce(this);t&&(xo(t.raw,n,e),this.set({columnWidths:Be(t).columnWidths??[]}),kt(this))},setRowHeight(n,e){let t=ce(this);t&&(yo(t.raw,n,e),this.set({manualRowHeights:Be(t).manualRowHeights??[]}),kt(this))},setSelectWidth(n){let e=ce(this);if(!e)return;let t=e.cellRange,r=Be(e),o=e.tableView;if(!t||o.cols<=0){this.setTableWidth(n);return}let i=r.minCellWidth??40,s=r.cellStrokeWidth??0,a=0;for(let c=t.c1;c<=t.c2;c++)a+=o.columnWidths[c]??0;if(a<=0)return;let l=(n-s-(t.c2-t.c1)*o.cellSpacing)/a,u=[...o.columnWidths];for(let c=t.c1;c<=t.c2;c++)u[c]=Math.max(i,(u[c]??0)*l);this.set({columnWidths:u}),kt(this)},setSelectHeight(n){let e=ce(this);if(!e)return;let t=e.cellRange,r=Be(e),o=e.tableView;if(!t||o.rows<=0){this.setTableHeight(n);return}let i=r.minCellHeight??40,s=r.cellStrokeWidth??0,a=0;for(let c=t.r1;c<=t.r2;c++)a+=o.rowHeights[c]??0;if(a<=0)return;let l=(n-s-(t.r2-t.r1)*o.cellSpacing)/a,u=Array.from({length:o.rows},(c,h)=>{let d=Array.isArray(r.manualRowHeights)?r.manualRowHeights[h]:null;return typeof d=="number"?d:null});for(let c=t.r1;c<=t.r2;c++)u[c]=Math.max(i,(o.rowHeights[c]??0)*l);this.set({manualRowHeights:u}),kt(this)},getColumnWidth(n){let e=ce(this);return e?e.tableView.columnWidths[n]??0:0},getRowHeight(n){let e=ce(this);return e?e.tableView.rowHeights[n]??0:0},getRowMinHeight(n){let e=ce(this);return e?e.getRowMinHeight(n):0},relayout(){let n=ce(this);n&&(n.rebuildTable(),kt(this))},previewLayout(){this.relayout()},getCell(n,e){let t=ce(this);if(!t)return;let r=we(t.cellMap,n,e);return r?cu(t,r,()=>Ve(this,t)):void 0},getCellText(n,e){let t=ce(this);if(!t)return;let r=we(t.cellMap,n,e);return r?eb(t,r,()=>Ve(this,t)):void 0},setSelectionTextAlign(n){Xt(this,e=>{e.textAlign=n})},setSelectionFontSize(n){Xt(this,e=>{e.fontSize=n})},changeSelectionFontSize(n){let e=ce(this);if(!e)return;let t=Be(e).fontSize??14;Xt(this,r=>{let o=Number(r.fontSize)||t;r.fontSize=n==="+"?o+1:Math.max(1,o-1)})},setSelectionFontWeight(n){Xt(this,e=>{e.fontWeight=n})},setSelectionFontStyle(n){Xt(this,e=>{e.fontStyle=n})},setSelectionUnderline(n){Xt(this,e=>{e.underline=n})},setSelectionLinethrough(n){Xt(this,e=>{e.linethrough=n})},setSelectionCellFill(n){Xt(this,e=>{e.fill=n,e.hasCustomFill=!0})},setSelectionCellStroke(n){Xt(this,e=>{e.stroke=n,e.hasCustomStroke=!0})},setSelectionCellStrokeWidth(n){Xt(this,e=>{e.strokeWidth=n,e.hasCustomStroke=!0})},updateCellFill(n){let e=ce(this);if(!e)return;let t=Be(e);t.cellFill=n;for(let r of Kr(t))!r.isMerged&&!r.hasCustomFill&&(r.fill=n);Ve(this,e)},updateCellTextFill(n){let e=ce(this);if(!e)return;let t=Be(e);t.textFill=n;for(let r of Kr(t))r.hasCustomTextFill||(r.textFill=n);Ve(this,e)},updateCellStroke(n){let e=ce(this);if(!e)return;let t=Be(e);t.cellStroke=n;for(let r of Kr(t))r.hasCustomStroke||(r.stroke=n);Ve(this,e)},updateBorderWidth(n){let e=ce(this);e&&(Be(e).cellStrokeWidth=n,Ve(this,e))},applyTextStylesToAll(n){let e=ce(this);if(!e)return;let t=Be(e),r={...t.textDefaults??{}};for(let[o,i]of Object.entries(n))r[o]=i;t.textDefaults=r;for(let o of Kr(t))for(let[i,s]of Object.entries(n))i==="fill"?o.textFill=s:o[i]=s;Ve(this,e)}},Sv={selectedCells(){let n=ce(this);if(n)return n.selectedCells.map(e=>{let t=we(n.cellMap,e.row,e.col);return t?cu(n,t,()=>Ve(this,n)):void 0}).filter(e=>e!==void 0)},_selectedCells(){let n=ce(this);return n?n.selectedCells:void 0},_selectionRange(){let n=ce(this);return n?n.cellRange:void 0},hasSelection(){let n=ce(this);return n?n.hasCellSelection:!1},selectionCount(){let n=ce(this);return n?n.selectedCells.length:0},cellTexts(){let n=ce(this);if(!n)return;let e=()=>Ve(this,n);return Kr(Be(n)).map(t=>eb(n,t,e))},cells(){let n=ce(this);if(!n)return;let e=()=>Ve(this,n);return Kr(Be(n)).map(t=>cu(n,t,e))},columnWidths(){let n=ce(this);return n?[...n.tableView.columnWidths]:void 0},rowHeights(){let n=ce(this);return n?[...n.tableView.rowHeights]:void 0}},uu=n=>{for(let[e,t]of Object.entries(yv))Object.assign(n,{[e]:t});for(let[e,t]of Object.entries(Sv))Object.defineProperty(n,e,{get:t,configurable:!0,enumerable:!1})};var hu=(n,e,t)=>{let r=Xe(e);if(!r)return null;let o=Et(n,e,t),i=r==="circle"||(typeof e.curvature=="number"?e.curvature:300)>0,s=o.contentOffsetX-o.width/2,a=o.contentOffsetX+o.width/2,l=o.contentOffsetY-o.height/2,u=o.contentOffsetY+o.height/2,c=n.lines.map(()=>[]);for(let h of o.chars){let d=c[h.line];if(!d)continue;let f={char:h.char,charAngle:i?-h.rotation:-(h.rotation+Math.PI),leftAngle:0,rightAngle:0,charRadius:0,bottomRadius:0,topRadius:0,lineRadius:0,cl:{x:h.x,y:h.y},tl:{x:s,y:l},br:{x:a,y:u},bl:{x:h.x,y:h.y},tr:{x:h.x,y:h.y},nl:{x:h.x,y:h.y},nr:{x:h.x,y:h.y},lc:{x:h.x,y:h.y}};d.push(f)}for(let h of c){let d=h[h.length-1];h.push({char:"",charAngle:0,leftAngle:0,rightAngle:0,charRadius:0,bottomRadius:0,topRadius:0,lineRadius:0,cl:d?{...d.cl}:{x:s,y:l},tl:{x:s,y:l},br:{x:a,y:u},bl:{x:s,y:l},tr:{x:a,y:u},nl:{x:s,y:l},nr:{x:a,y:u},lc:{x:s,y:l}})}return c};var vv=n=>{let e=n.textLines,t=n.charBounds,r=n.lineHeights;if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(r)||e.length===0||t.length!==e.length||r.length!==e.length)return!1;for(let o=0;o<e.length;o++)if(typeof e[o]!="string"||!Array.isArray(t[o])||t[o].length===0||typeof r[o]!="number"||!Number.isFinite(r[o]))return!1;return!0},hr=class{node;ctx;constructor(e,t){this.node=e,this.ctx=t}set(e,t){let r=typeof e=="string"?{[e]:t}:{...e},o=r.__isCropping&&this.ctx.cropSessionNodeId?.()!==this.node.id?this.toObject():void 0;if("cropAspectRatio"in r){let s={cropAspectRatio:r.cropAspectRatio};delete r.cropAspectRatio,this.ctx.setNodeProps(this.node,s)}if("_cropKey"in r){let s=r._cropKey;delete r._cropKey,this.ctx.applyCropShape?.(this.node,typeof s=="string"&&s?s:null)}if("__isCropping"in r){let s=!!r.__isCropping;delete r.__isCropping,this.clearSessionFlagDirty("__isCropping"),this.__isCropping=s,o&&this.__isCropping&&(this.cropBeforeState=o)}if("__isExpand"in r){let s=!!r.__isExpand;delete r.__isExpand,this.clearSessionFlagDirty("__isExpand"),this.__isExpand=s}if(typeof r.width=="number"&&Wr(this.node)){let s=r.width;delete r.width,this.ctx.setGroupWidth?this.ctx.setGroupWidth(this.node,s):this.ctx.setNodeProps(this.node,{width:s})}this.bumpTextboxWidthToLayoutBox(r),this.bridgeImageSizeProps(r);let i=r;if((typeof r.width=="number"||typeof r.height=="number"||typeof r.scaleX=="number"||typeof r.scaleY=="number")&&!("clipImage"in r)&&ot.has(se(this.node.raw))){let s=zt(this.node),a=this.node.raw,l=Number(a.width)||0,u=Number(a.height)||0,c=this.node.clipImageEl,h=c?.naturalWidth||Number(s?.width)||0,d=c?.naturalHeight||Number(s?.height)||0;if(s&&l>0&&u>0&&h>0&&d>0){typeof r.scaleX=="number"&&r.scaleX>0&&!("width"in r)&&(r.width=l*r.scaleX,r.scaleX=1),typeof r.scaleY=="number"&&r.scaleY>0&&!("height"in r)&&(r.height=u*r.scaleY,r.scaleY=1);let f=typeof r.width=="number"?r.width:l,m=typeof r.height=="number"?r.height:u;if(f>0&&m>0){let p=(x,S)=>Math.max(x/h,S/d),b=Number(s.scaleX)||1,g=p(f,m)*(b/p(l,u));i={...r,clipImage:{...s,scaleX:g,scaleY:g}}}}}return Object.keys(i).length>0&&this.ctx.setNodeProps(this.node,i),this}bumpTextboxWidthToLayoutBox(e){if(typeof e.width!="number"||!(this.node instanceof ye)||e.width<0||se(this.node.raw)!==L.TEXTBOX||Xe(this.node.raw))return;let r=e.width;delete e.width,this.ctx.setNodeProps(this.node,{width:r});let o=this.node.dims.x;Number.isFinite(o)&&o>r+.01&&this.ctx.setNodeProps(this.node,{width:o})}clearSessionFlagDirty(e){this.node.raw[e]!==void 0&&this.ctx.setNodeProps(this.node,{[e]:void 0})}get(e){return this.node.raw[e]}setCoords(){}getCenterPoint(){return{...this.node.center}}getRelativeCenterPoint(){return new nn(this.node.center.x,this.node.center.y)}translateToOriginPoint(e,t="center",r="center"){let o=c=>c==="left"||c==="top"?-.5:c==="right"||c==="bottom"?.5:0,i=o(t),s=o(r),a=i||s?this._getTransformedDimensions():new nn(0,0),l=new nn(e.x+i*a.x,e.y+s*a.y),u=this.node.raw.angle;return typeof u=="number"&&u&&(l=l.rotate(u*Math.PI/180,e)),l}toPath(){let e=this.ctx.getTextGlyphPath?.(this.node);return e||ou(this.node)}toPathDecorations(){return this.ctx.getTextDecorations?.(this.node)??[]}toPathEffectLayers(e){return[]}_getTransformedDimensions(){let e=this.node.raw;return new nn(this.node.dims.x*(e.scaleX??1),this.node.dims.y*(e.scaleY??1))}getBoundingRect(){let e=this.node.bounds;return{left:e.left,top:e.top,width:e.right-e.left,height:e.bottom-e.top}}getInkRect(){let e=Xn(this.node.inkACoords);return{left:e.left,top:e.top,width:e.width,height:e.height}}get aCoords(){return this.node.aCoords}getCoords(){let e=this.node.aCoords;return[e.tl,e.tr,e.br,e.bl]}calcOCoords(){let e=this.ctx.getViewportTransform?.()??[1,0,0,1,0,0],t=o=>({x:e[0]*o.x+e[2]*o.y+e[4],y:e[1]*o.x+e[3]*o.y+e[5]}),r=this.node.aCoords;return{tl:t(r.tl),tr:t(r.tr),br:t(r.br),bl:t(r.bl)}}rotate(e){let{angle:t,left:r,top:o}=this.node.rotateAroundCenter(e);return this.set({angle:t,left:r,top:o})}setPositionByOrigin(e,t,r){let o=this.node.raw,i=typeof o.scaleX=="number"?o.scaleX:1,s=typeof o.scaleY=="number"?o.scaleY:1,a=this.node.dims.x*i,l=this.node.dims.y*s,u=t==="center"?0:t==="right"?.5:-.5,c=r==="center"?0:r==="bottom"?.5:-.5,h=u*a,d=c*l,f=(typeof o.angle=="number"?o.angle:0)*Math.PI/180,m=Math.cos(f),p=Math.sin(f),b={x:e.x-(h*m-d*p),y:e.y-(h*p+d*m)},g=ge({...o},b);return this.set({left:g.x,top:g.y})}scale(e){let t=this.node.raw;return this.set({scaleX:(t.scaleX??1)*e,scaleY:(t.scaleY??1)*e})}getScaledWidth(){return this.node.dims.x*(this.node.raw.scaleX??1)}getScaledHeight(){return this.node.dims.y*(this.node.raw.scaleY??1)}getObjectScaling(){let e=this.node.raw;return{scaleX:e.scaleX??1,scaleY:e.scaleY??1}}get getObjects(){if(this.node instanceof J)return()=>this.node.children.map(e=>this.ctx.wrapNode(e))}get _objects(){if(this.node instanceof J)return this.node.children.map(e=>this.ctx.wrapNode(e))}get ref(){return this}get isImageLikeNode(){let e=se(this.node.raw);return dt.has(e)||ot.has(e)||e===L.GIF||e===L.VIDEO}get getSrc(){if(this.isImageLikeNode)return()=>{let e=this.node.raw;return typeof e.originalSrc=="string"&&e.originalSrc?e.originalSrc:typeof e.src=="string"?e.src:""}}get getRealSrc(){let e=this.getSrc;if(e)return()=>e()}get replaceSrc(){if(this.isImageLikeNode)return async e=>(this.set({src:e,crossOrigin:"anonymous",originalSrc:e}),await this.ctx.reloadNodeImage?.(this.node),this)}get setElement(){if(this.isImageLikeNode)return(e,t)=>(this.node.imageEl=e,t&&this.set(t),this)}get getElement(){if(!this.isImageLikeNode)return;let e=this.node;return e instanceof ie?()=>e.paintSource??e.imageEl:()=>e.imageEl}get _element(){if(this.isImageLikeNode)return this.node.imageEl}get clipImage(){return zt(this.node)?Tv(this.node,this.ctx):void 0}set clipImage(e){let t=e&&typeof e=="object"&&typeof e.toObject=="function"?e.toObject(this.serializationProps()):e;this.ctx.setNodeProps(this.node,{clipImage:t})}getWidthHeight(e=!1){let t=this._getTransformedDimensions(),r=(this.node.raw.strokeWidth??0)||0;return{x:t.x-r,y:t.y-r}}getWidth(){return this.getWidthHeight().x}getHeight(){return this.getWidthHeight().y}sourceNaturalSize(){let e=this.node.imageEl;if(e)return{width:e.naturalWidth||e.width||0,height:e.naturalHeight||e.height||0};if(this.node instanceof ie){let t=this.node.paintSource;if(t)return{width:("videoWidth"in t?t.videoWidth:t.width)||t.width||0,height:("videoHeight"in t?t.videoHeight:t.height)||t.height||0}}return{width:0,height:0}}getOriginalElementWidth(){return this.sourceNaturalSize().width}getOriginalElementHeight(){return this.sourceNaturalSize().height}getElementWidth(){return this.sourceNaturalSize().width}getElementHeight(){return this.sourceNaturalSize().height}cropOffset(){if(!this.isImageLikeNode)return{x:0,y:0};let e=this.node.raw;return e.cropSizeMode==="visible"?{x:0,y:0}:{x:Number(e.cropX)||0,y:Number(e.cropY)||0}}get left(){return this.node.raw.left??0}set left(e){this.set({left:e})}get top(){return this.node.raw.top??0}set top(e){this.set({top:e})}get scaleX(){return this.node.raw.scaleX??1}set scaleX(e){this.set({scaleX:e})}get scaleY(){return this.node.raw.scaleY??1}set scaleY(e){this.set({scaleY:e})}get angle(){return this.node.raw.angle??0}set angle(e){this.set({angle:e})}get skewX(){return this.node.raw.skewX??0}set skewX(e){this.set({skewX:e})}get skewY(){return this.node.raw.skewY??0}set skewY(e){this.set({skewY:e})}get flipX(){return this.node.raw.flipX??!1}set flipX(e){this.set({flipX:e})}get flipY(){return this.node.raw.flipY??!1}set flipY(e){this.set({flipY:e})}get originX(){return this.node.raw.originX??"left"}set originX(e){this.set({originX:e})}get originY(){return this.node.raw.originY??"top"}set originY(e){this.set({originY:e})}get width(){return(this.node.raw.width??0)-this.cropOffset().x}set width(e){if(Wr(this.node)){if(this.ctx.setGroupWidth){this.ctx.setGroupWidth(this.node,e);return}this.ctx.setNodeProps(this.node,{width:e});return}let t=this.cropOffset();this.ctx.setNodeProps(this.node,{width:e+t.x})}get height(){return(this.node.raw.height??0)-this.cropOffset().y}set height(e){let t=this.cropOffset();this.ctx.setNodeProps(this.node,{height:e+t.y})}bridgeImageSizeProps(e){if(!this.isImageLikeNode)return;let t=this.node.raw;if(t.cropSizeMode==="visible")return;let r=typeof e.cropX=="number"?e.cropX:Number(t.cropX)||0,o=typeof e.cropY=="number"?e.cropY:Number(t.cropY)||0;typeof e.width=="number"&&r>0&&(e.width=e.width+r),typeof e.height=="number"&&o>0&&(e.height=e.height+o)}cropBeforeState;get __isCropping(){return this.isImageLikeNode&&this.ctx.cropSessionNodeId?.()===this.node.id}set __isCropping(e){if(this.isImageLikeNode)if(e){let t=this.ctx.cropSessionNodeId?.()!==this.node.id;if(t&&(this.cropBeforeState=this.toObject()),!this.ctx.enterCropSession?.(this.node)){t&&(this.cropBeforeState=void 0);return}let r=this.node.raw.cropAspectRatio;typeof r=="number"&&r>0&&this.ctx.setCropSessionAspectRatio?.(r)}else this.ctx.exitCropSession?.(this.node),this.cropBeforeState=void 0}get __isExpand(){return this.isImageLikeNode&&this.ctx.expandSessionNodeId?.()===this.node.id}set __isExpand(e){this.isImageLikeNode&&(e?this.ctx.enterExpandSession?.(this.node):this.ctx.exitExpandSession?.(this.node))}get beforeState(){return this.cropBeforeState}onDeselectEvent(){this.ctx.exitCropSession?.(this.node),this.ctx.exitExpandSession?.(this.node),this.cropBeforeState=void 0}expandOffsetOf(e){let t=this.ctx.expandSessionOffsets?.(this.node);if(t)return t[e];let r=e==="left"?"Left":e==="right"?"Right":e==="top"?"Top":"Bottom",o=this.node.raw[`expand${r}Offset`];return typeof o=="number"?o:void 0}get expandLeftOffset(){return this.isImageLikeNode?this.expandOffsetOf("left"):void 0}get expandRightOffset(){return this.isImageLikeNode?this.expandOffsetOf("right"):void 0}get expandTopOffset(){return this.isImageLikeNode?this.expandOffsetOf("top"):void 0}get expandBottomOffset(){return this.isImageLikeNode?this.expandOffsetOf("bottom"):void 0}setExpandOffset(){let e=this.ctx.expandSessionOffsets?.(this.node);e&&this.set({expandLeftOffset:e.left,expandRightOffset:e.right,expandTopOffset:e.top,expandBottomOffset:e.bottom})}updateCropScale(e){if(!this.__isCropping||!(e>0)||!Number.isFinite(e))return!1;if(this.ctx.updateCropSessionScale)return this.ctx.updateCropSessionScale(e);let t=this.node.imageEl;if(!t)return!1;let r=this.node.raw,o=t.naturalWidth||t.width,i=t.naturalHeight||t.height,s=r.scaleX??1,a=e/s,l=e/(r.scaleY??1),u=this.width,c=this.height,h=u/a,d=c/l,f=(r.cropX??0)+u/2-h/2,m=(r.cropY??0)+c/2-d/2;return h<Math.min(8,o)||d<Math.min(8,i)||f<0||m<0||f+h>o||m+d>i?!1:(this.set({cropScale:e,scaleX:e,scaleY:e,width:h,height:d,cropX:f,cropY:m}),!0)}getMaxEffectPadding(){let e=this.node.raw,t=0,r=e.effects??{},o=c=>(c??[]).filter(h=>h.enabled&&h.showInDialog),i=o(r.solidFill);i.length>0&&(t=Math.max(t,i.reduce((c,h)=>Math.max(c,Math.abs(Number(h.offsetX)||0),Math.abs(Number(h.offsetY)||0)),0)));let s=o(r.dropShadow);s.length>0&&(t=Math.max(t,s.reduce((c,h)=>{let d=(Number(h.blur)||0)*2;return Math.max(c,Math.abs(Number(h.offsetX)||0)+d,Math.abs(Number(h.offsetY)||0)+d)},0)));let a=o(r.stroke);a.length>0&&(t=Math.max(t,a.reduce((c,h)=>{let d=h.size,f=Number(h.strokeWidth)||Number(d?.value)||0;return Math.max(c,f+Math.abs(Number(h.offsetX)||0),f+Math.abs(Number(h.offsetY)||0))},0)));let l=e.shadow;if(l){let c=(Number(l.blur)||0)*2;t=Math.max(t,Math.abs(Number(l.offsetX)||0)+c,Math.abs(Number(l.offsetY)||0)+c)}let u=Number(e.strokeWidth)||0;if(e.stroke&&u){let c=e.strokeAlignment==="outside"?u*2:u;t=Math.max(t,c)}return t}isType(...e){let t=se(this.node.raw);return e.some(r=>r.toLowerCase()===t)}getStyleAtPosition(e){if(!(this.node instanceof ye))return{};let t=typeof this.node.raw.text=="string"?this.node.raw.text:"";if(e<0||e>=t.length)return{};let r=e,o=t.split(`
1091
+ }`,Oa=class{program=null;vao=null;vertexBuffer=null;corners=new Float32Array(12);invalidate(){this.program=null,this.vao=null,this.vertexBuffer=null}init(e){let t=(s,a)=>{let l=e.createShader(s);return l?(e.shaderSource(l,a),e.compileShader(l),e.getShaderParameter(l,e.COMPILE_STATUS)?l:(console.warn("[WorkspaceGlow] shader:",e.getShaderInfoLog(l)),e.deleteShader(l),null)):null},r=t(e.VERTEX_SHADER,ov),o=t(e.FRAGMENT_SHADER,iv),i=e.createProgram();return!r||!o||!i?(r&&e.deleteShader(r),o&&e.deleteShader(o),!1):(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.deleteShader(r),e.deleteShader(o),e.getProgramParameter(i,e.LINK_STATUS)?(this.program=i,this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.corners.byteLength,e.DYNAMIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null),!0):(console.warn("[WorkspaceGlow] link:",e.getProgramInfoLog(i)),e.deleteProgram(i),!1))}draw(e,t){if(!this.program&&!this.init(e))return;let{view:r,vpt:o,cssWidth:i,cssHeight:s,left:a,top:l,width:u,height:c,zoom:h,dpr:d}=t;if(!(h>0)||!(d>0)||!(u>0)||!(c>0))return;let f=nv/h,m=1.5/(h*d),p=ve(o),b=Q(p,0,0),g=Q(p,i,s),x=Math.min(b.x,g.x),S=Math.min(b.y,g.y),w=Math.max(b.x,g.x),y=Math.max(b.y,g.y),v=this.corners;v[0]=x,v[1]=S,v[2]=w,v[3]=S,v[4]=w,v[5]=y,v[6]=x,v[7]=S,v[8]=w,v[9]=y,v[10]=x,v[11]=y;let R=this.program;e.useProgram(R),e.bindVertexArray(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,v);let P=new Float32Array([r[0],r[1],0,r[2],r[3],0,r[4],r[5],1]);e.uniformMatrix3fv(e.getUniformLocation(R,"uView"),!1,P),e.uniform2f(e.getUniformLocation(R,"uCenter"),a+u/2,l+c/2),e.uniform2f(e.getUniformLocation(R,"uHalf"),u/2,c/2),e.uniform1f(e.getUniformLocation(R,"uBlur"),f),e.uniform1f(e.getUniformLocation(R,"uAa"),m),e.uniform3f(e.getUniformLocation(R,"uMask"),nu[0],nu[1],nu[2]),e.uniform1f(e.getUniformLocation(R,"uGlow"),rv),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLES,0,6),e.bindVertexArray(null)}};var Ba=class{constructor(e){this.doc=e}doc;glow=new Oa;checker=new Fa;invalidate(){this.glow.invalidate(),this.checker.invalidate()}drawChecker(e,t,r){let o=this.findWorkspaceNode()?.bounds;o&&this.checker.draw(e,{view:t,vpt:r.vpt,left:o.left,top:o.top,width:o.width,height:o.height,zoom:Math.hypot(r.vpt[0],r.vpt[1]),dpr:r.dpr})}drawBackdrop(e,t,r){let o=this.findWorkspaceNode()?.bounds;o&&this.glow.draw(e,{view:t,vpt:r.vpt,cssWidth:r.cssWidth,cssHeight:r.cssHeight,left:o.left,top:o.top,width:o.width,height:o.height,zoom:Math.hypot(r.vpt[0],r.vpt[1]),dpr:r.dpr})}findWorkspaceNode(){let e=this.doc.nodes.find(t=>String(t.raw.id??"")===Sn);return!e||!e.visible||!(e.bounds.width>0)||!(e.bounds.height>0)?null:e}};var sv=.02,av=256,ru=class n{domCanvasEl;exportStandInEl=null;get canvasEl(){return this.exportStandInEl??this.domCanvasEl}isExporting(){return this.exportStandInEl!==null}handle;batch;meshBatch;batchOrder;progressiveLoad=new da({render:()=>this.render(),nodeCount:()=>this.doc.nodes.length,alive:()=>!this.disposed&&!this.contextLost,onProgressiveDone:e=>this.bus.fire("engine:progressive-done",e)});textures;gradientRamps;glyphAtlas;renderEpoch=new Nn;bakeKReuseFloor=0;decodeAnimated=null;sources;textRenderer;renderer;exporter;workspaceBackdrop;bus=new Hn;doc=new Ao;dpr;mobileControls;interactive;editorScroll;vpt=[1,0,0,1,0,0];cssWidth=300;cssHeight=150;background;rafId=null;renderTimerId=null;contextLost=!1;disposed=!1;fontInvalidation;retainedFrame;chromeCache=null;interactions;interactionSuspended=!1;marquee=null;panning=!1;textEditing;tableCellEditing;snapGuide;rulerVisibleValue=!1;cropSessionController;expandSessionController;pathSessionController;warpSessionController;onWarpHistoryChange;animationPlaybackController;cellSelectionSink;constructor(e,t,r){Cu(),this.domCanvasEl=e,this.domCanvasEl.style.display="block",this.handle=t,this.batch=new tn(t.gl),this.meshBatch=new ca(t.gl),this.batchOrder=new la(this.batch,this.meshBatch),this.batch.order=this.batchOrder,this.meshBatch.order=this.batchOrder,this.textures=new ia(t.gl,{epoch:this.renderEpoch}),this.gradientRamps=new oa(t.gl),this.glyphAtlas=new na(t.gl,()=>this.requestRenderAll(),o=>this.fontInvalidation.queueSettle(o),this.renderEpoch),this.dpr=r.dpr??(typeof window<"u"&&window.devicePixelRatio||1),this.mobileControls=r.mobileControls??!1,this.interactive=r.interactive??!0,this.background=r.background??[0,0,0,0],this.sources=new La(this),this.textRenderer=new Ia(t.gl,this.batch,this.glyphAtlas),this.renderer=new ka(this,this.sources,this.textRenderer),this.textRenderer.attachPatternSources(this.sources),this.fontInvalidation=new ta(this,this.textRenderer,this.glyphAtlas,this.renderer),this.retainedFrame=new fa(this),this.exporter=new Da(this),this.workspaceBackdrop=new Ba(this.doc),this.textEditing=new Js(this),this.tableCellEditing=new Zs(this),this.snapGuide=new qs(this,qa),this.cropSessionController=new Gs(this),this.expandSessionController=new Xs(this),this.pathSessionController=new Ys(this),this.warpSessionController=new Us(this),this.editorScroll=r.editorScroll!==!1,this.animationPlaybackController=new Qs(this),this.interactions=new Ds(this,this.snapGuide,this.sources,this.interactive),this.cellSelectionSink=o=>{this.doc.events.fire("table:cellselection",o)},te.cellSelectionSink=this.cellSelectionSink}static create(e,t={}){let r=null,o=Om(e,{onLost:()=>r?.onContextLost(),onRestored:()=>r?.onContextRestored()});return o?(r=new n(e,o,t),r):null}onContextLost(){this.contextLost=!0,this.bus.fire("engine:context-lost")}onContextRestored(){this.contextLost=!1,this.recoverGlResources(),this.bus.fire("engine:context-restored"),this.requestRenderAll()}recoverGlResources(){this.retainedFrame.invalidate(),this.batch.rebuild(),this.meshBatch.rebuild(),this.textures.invalidateAll(),this.gradientRamps.invalidateAll(),this.glyphAtlas.reset(),this.sources.invalidateGlTextures(),this.renderer.invalidateGlResources(),this.workspaceBackdrop.invalidate()}invalidateNodeTextBakes(e){this.fontInvalidation.invalidateNodeTextBakes(e)}handleFontsLoaded(e){this.fontInvalidation.handleFontsLoaded(e)}get engineDisposed(){return this.disposed}get engineContextLost(){return this.contextLost}get pointerActive(){return this.interactions.pointerActive}get events(){return this.bus}get document(){return this.doc}get capabilities(){return{maxTextureSize:this.handle.capabilities.maxTextureSize,renderer:this.handle.capabilities.renderer}}get viewportTransform(){return[...this.vpt]}get zoom(){return this.vpt[0]}get gl(){return this.handle.gl}get viewSize(){return{width:this.cssWidth,height:this.cssHeight}}workspaceRect(){let e=this.doc.nodes.find(t=>String(t.raw.id??"")===Sn)?.bounds;return e&&e.width>0&&e.height>0?{left:e.left,top:e.top,width:e.width,height:e.height}:{left:0,top:0,width:0,height:0}}cursorPoint(e){let t=this.canvasEl.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}get cropSession(){return this.cropSessionController.active?this.cropSessionController:null}get cropGhostNode(){return this.cropSessionController.target}get maskCropNode(){let e=this.cropSessionController.target;return e instanceof ae?e:null}get expandSession(){return this.expandSessionController.active?this.expandSessionController:null}get pathSession(){return this.pathSessionController.active?this.pathSessionController:null}get warpSession(){return this.warpSessionController.active?this.warpSessionController:null}get warpDebugSample(){return this.warpSessionController.debugBoundsSample}get warpDebugPreview(){return this.warpSessionController.debugPreviewInfo}get warpDebugAnchors(){return this.warpSessionController.debugAnchors}get warpSessionTarget(){return this.warpSessionController.target}get editingNode(){return this.doc.editingNode}get stats(){return{nodeCount:this.doc.nodes.length,skippedTypes:{...this.doc.skippedTypes}}}get diagnostics(){return{glError:this.handle.gl.getError(),drawnInstances:this.batch.drawnInstances,contextLost:this.contextLost}}get textureBudgetInfo(){return{textures:this.textures.stats(),atlas:this.glyphAtlas.stats()}}setTextureBudget(e){this.textures.setBudget(e)}toScene(e,t){return{x:(e-this.vpt[4])/this.vpt[0],y:(t-this.vpt[5])/this.vpt[3]}}toScreen(e,t){return{x:this.vpt[0]*e+this.vpt[4],y:this.vpt[3]*t+this.vpt[5]}}resize(e,t){e<=1||t<=1||(this.cssWidth=Math.max(1,e),this.cssHeight=Math.max(1,t),this.canvasEl.width=Math.round(this.cssWidth*this.dpr),this.canvasEl.height=Math.round(this.cssHeight*this.dpr),this.canvasEl.style.width=`${this.cssWidth}px`,this.canvasEl.style.height=`${this.cssHeight}px`,this.render())}progressiveFirstFrame(e=1e3,t=800){this.progressiveLoad.start(e,t)}async loadObjects(e){this.sources.releaseAnimatedSources(),this.animationPlaybackController.reset(),this.doc.loadObjects(e),await Zc(Qc([...this.doc.nodes]),this.sources,()=>this.requestRenderAll())}async ensureNodeSources(e){await Zc(Qc(e),this.sources,()=>this.requestRenderAll())}setViewportTransform(e){let t=this.vpt[0];this.vpt=[...e],this.renderer.noteVptChange(),e[0]!==t&&this.doc.setViewportZoom(e[0]),this.requestRenderAll()}zoomAt(e,t,r){let o=Math.min(av,Math.max(sv,this.vpt[0]*r)),i=o/this.vpt[0];this.vpt=[o,0,0,o,e-i*(e-this.vpt[4]),t-i*(t-this.vpt[5])],this.renderer.noteVptChange(),this.doc.setViewportZoom(o),this.requestRenderAll()}pan(e,t){this.vpt[4]+=e,this.vpt[5]+=t,this.renderer.noteVptChange(),this.requestRenderAll()}noteExternalGesture(){this.renderer.noteExternalInteraction()}requestRenderAll(){this.progressiveLoad.absorbExternalRenderRequest(),!(this.rafId!==null||this.renderTimerId!==null||this.disposed||this.contextLost)&&(this.rafId=requestAnimationFrame(()=>{this.rafId=null,this.renderTimerId!==null&&(clearTimeout(this.renderTimerId),this.renderTimerId=null),this.render()}),this.renderTimerId=setTimeout(()=>{this.renderTimerId=null,this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.render()},250))}workspaceChromeNodes(){let e=this.doc.structureVersion;return(!this.chromeCache||this.chromeCache.version!==e)&&(this.chromeCache={version:e,nodes:this.doc.nodes.filter(rr)}),this.chromeCache.nodes}render(){if(this.disposed||this.contextLost||!this.batch.valid)return;this.fontInvalidation.consumePendingSettle(),this.textures.markFrame(this.pointerActive),this.glyphAtlas.markFrame(),this.snapGuide.settleMoveSnap();let e=performance.now();this.renderer.beginFrame(e),this.tickAnimation(e),Ua("engine.render",()=>{let t=this.handle.gl;t.viewport(0,0,this.canvasEl.width,this.canvasEl.height),t.clearColor(...this.background),t.clearStencil(0),t.clear(t.COLOR_BUFFER_BIT|t.STENCIL_BUFFER_BIT);let r=Zr(this.vpt,this.cssWidth,this.cssHeight,this.dpr);this.workspaceBackdrop.drawChecker(this.handle.gl,r,{vpt:this.vpt,cssWidth:this.cssWidth,cssHeight:this.cssHeight,dpr:this.dpr}),this.batch.begin(r,this.zoom*this.dpr),this.meshBatch.begin(r),this.batch.deferDraws=!0,this.meshBatch.deferDraws=!0,this.batchOrder.reset();let o=this.expandSessionController.active?this.expandSessionController.target:null;if(!(!o&&this.retainedFrame.tryRetainedFrame())){this.batch.begin(r,this.zoom*this.dpr),this.meshBatch.begin(r),this.batch.deferDraws=!0,this.meshBatch.deferDraws=!0,this.batchOrder.reset();let i=this.progressiveLoad.limit>=0?Math.min(this.progressiveLoad.limit,this.doc.nodes.length):this.doc.nodes.length;ep(this.batch,this.renderer,this.doc.nodes,o?{target:o,underlay:()=>this.expandSessionController.buildUnderlay()}:null,i),this.batchOrder.requestSnapshot=!0,this.batchOrder.flushAll(),this.retainedFrame.captureSnapshot()}this.doc.drainRenderDirty(),this.workspaceBackdrop.drawBackdrop(this.handle.gl,r,{vpt:this.vpt,cssWidth:this.cssWidth,cssHeight:this.cssHeight,dpr:this.dpr}),tp(this.renderer,this.workspaceChromeNodes()),np(this)}),this.retainedFrame.noteFrameRendered(),this.renderer.frame.bakeMore&&this.requestRenderAll(),this.bus.fire("engine:render",performance.now()-e)}readPixels(){return Kd(this.canvasEl)}exportToPixels(e){return this.retainedFrame.invalidate(),this.exporter.exportToPixels(e)}async exportToPixelsAsync(e){return this.retainedFrame.invalidate(),this.exporter.exportToPixelsAsync(e)}async exportRawPixelsAsync(e){return this.retainedFrame.invalidate(),this.exporter.exportRawPixelsAsync(e)}exportToCanvas(e){return this.retainedFrame.invalidate(),this.exporter.exportToCanvas(e)}drainGpuBacklog(){return this.exporter.drainGpuBacklog()}exportToDataURL(e,t="image/png",r){return this.retainedFrame.invalidate(),this.exporter.exportToDataURL(e,t,r)}get exportReady(){return!this.disposed&&!this.contextLost&&this.batch.valid}get sceneNodes(){return this.doc.nodes}applyExportViewport(e,t,r){let o=this.vpt,i=this.exportStandInEl;this.vpt=[...e];let s=document.createElement("canvas");return s.width=t,s.height=r,this.exportStandInEl=s,()=>{this.vpt=o,this.exportStandInEl=i}}measureFrames(e){return qd(e,()=>this.render())}getSceneSummary(){return Vd(this.doc)}getTableCellEditingInfo(){return this.tableCellEditing.info}getTableSelectionInfo(){let e=this.doc.selection.length===1&&this.doc.selection[0]instanceof te?this.doc.selection[0]:null;return e?{tableId:e.id,cells:e.selectedCells.map(t=>({row:t.row,col:t.col})),anchor:e.cellAnchor?{...e.cellAnchor}:null,range:e.cellRange?{...e.cellRange}:null}:null}getSnapGuideInfo(){return this.snapGuide.info}enterExpandMode(e){this.cropSessionController.active&&this.cropSessionController.exit(),this.pathSessionController.active&&this.pathSessionController.exit();let t=e??this.doc.selection[0];return t?this.expandSessionController.enter(t):!1}exitExpandMode(){this.expandSessionController.exit()}getExpandInfo(){return this.expandSessionController.info}async applyExpandResult(e,t,r){let o=this.findNodeById(e);return!o||!o.isImageType&&!(o instanceof ae)?!1:this.expandSessionController.applyResult(o,t,r)}reloadImageElement(e){return this.sources.reloadNodeImage(e)}findNodeById(e){return this.doc.findNodeDeep(e)?.node??null}async reloadNodeImage(e){let t=this.findNodeById(e);return t?!!await this.sources.reloadNodeImage(t):!1}async reloadMaskClipImage(e){let t=this.findNodeById(e);return t instanceof ae?!!await this.sources.reloadMaskClipImage(t):!1}getCropInfo(){return this.cropSessionController.info}enterCropMode(e,t){this.pathSessionController.active&&this.pathSessionController.exit();let r=e??this.doc.selection[0];return r?this.cropSessionController.enter(r,t):!1}exitCropMode(){this.cropSessionController.exit()}setCropShape(e){this.cropSessionController.setCropShape(e)}updateCropScale(e){return this.cropSessionController.setScale(e)}setCropAspectRatio(e){this.cropSessionController.setAspectRatio(e)}enterPathEditMode(e){this.cropSessionController.active&&this.cropSessionController.exit(),this.expandSessionController.active&&this.expandSessionController.exit();let t=e??this.doc.selection[0];return t?this.pathSessionController.enter(t):!1}async enterWarpMode(e,t){this.cropSessionController.active&&this.cropSessionController.exit(),this.expandSessionController.active&&this.expandSessionController.exit(),this.pathSessionController.active&&this.pathSessionController.exit();let r=e??this.doc.selection[0];return r?this.warpSessionController.enter(r,t):!1}async loadImage(e,t){try{return await Je(e,t??null)}catch{return null}}async exitWarpMode(e){return this.warpSessionController.exit(e)}warpUndo(){return this.warpSessionController.undo()}warpRedo(){return this.warpSessionController.redo()}exitPathEditMode(){this.pathSessionController.exit()}getPathEditInfo(){return this.pathSessionController.info}setPathAnchorType(e,t,r){return this.pathSessionController.target===e?this.pathSessionController.setAnchorType(t,r):!1}highlightPathAnchor(e,t){this.pathSessionController.target===e&&this.pathSessionController.setActiveAnchor(t)}resetPathAnchorStyles(e){this.pathSessionController.target===e&&this.pathSessionController.resetAnchorStyles()}get rulerEnabled(){return this.rulerVisible}get rulerVisible(){return this.rulerVisibleValue}referenceLineDrag=null;rotateDrag=null;setRulerVisible(e){this.rulerVisibleValue!==e&&(this.rulerVisibleValue=e,this.requestRenderAll())}selectAll(){return Qd(this.doc,()=>this.requestRenderAll())}deleteSelection(){return Zd(this.doc,()=>this.requestRenderAll())}nudgeSelection(e,t){return Jd(this.doc,e,t,()=>this.requestRenderAll())}getSelectionInfo(){return Ud(this.doc,this.marquee,this.zoom,(e,t)=>this.toScreen(e,t))}getActiveGroupChildInfo(){return $d(this.doc)}getSvgRasterInfo(){return jd(this.doc,e=>this.sources.svgRasterFactorOf(e))}toObjects(){return this.doc.toObjects()}playAnimations(){this.animationPlaybackController.play()}pauseAnimations(){this.animationPlaybackController.pause()}stopAnimations(){this.animationPlaybackController.stop()}seekAnimations(e){this.animationPlaybackController.seek(e)}getAnimationPlaybackInfo(){return this.animationPlaybackController.info}getScrollTextPlaybackInfo(){return this.animationPlaybackController.scrollTextInfo}playSingleAnimation(e,t,r){return this.animationPlaybackController.playSingleAnimation(e,t,r)}stopSingleAnimation(e){this.animationPlaybackController.stopSingleAnimation(e)}getSingleAnimationPreviewInfo(){return this.animationPlaybackController.singlePreviewInfo}tickAnimation(e){this.animationPlaybackController.tick(e)&&(this.renderer.frame.animationActive=!0)}setEditingSelection(e,t){this.textEditing.setSelection(e,t)}settleMoveSnap(){this.snapGuide.settleMoveSnap()}finishSnapGesture(){this.snapGuide.finishGesture()}registerScalingSnap(e,t){this.snapGuide.registerScaling(e,t)}startCellEditing(e,t,r,o){return this.tableCellEditing.startEditing(e,t,r,o)}enterTextEditingAtClick(e,t,r){this.textEditing.enterEditingAtClick(e,t,r)}dispose(){this.disposed||(this.disposed=!0,this.cellSelectionSink&&te.cellSelectionSink===this.cellSelectionSink&&(te.cellSelectionSink=null),this.rafId!==null&&cancelAnimationFrame(this.rafId),this.renderTimerId!==null&&clearTimeout(this.renderTimerId),this.retainedFrame.dispose(),this.progressiveLoad.dispose(),this.interactions.dispose(),this.tableCellEditing.dispose(),this.cropSessionController.dispose(),this.expandSessionController.dispose(),this.pathSessionController.dispose(),this.textEditing.dispose(),this.bus.clear(),this.sources.releaseAnimatedSources(),this.batch.dispose(),this.meshBatch.dispose(),this.textures.dispose(),this.gradientRamps.dispose(),this.sources.dispose(),this.glyphAtlas.dispose(),this.handle.dispose())}};var nn=class n{constructor(e=0,t=0){this.x=e;this.y=t}x;y;add(e){return new n(this.x+e.x,this.y+e.y)}subtract(e){return new n(this.x-e.x,this.y-e.y)}scalarDivide(e){return new n(this.x/e,this.y/e)}rotate(e,t={x:0,y:0}){let r=Math.sin(e),o=Math.cos(e),i=this.subtract(t);return new n(i.x*o-i.y*r,i.x*r+i.y*o).add(t)}},ou=class n{constructor(e=0,t=0){typeof e=="number"?(this.x=e,this.y=t):(this.x=e.x,this.y=e.y)}x=0;y=0;add(e){return new n(this.x+e.x,this.y+e.y)}subtract(e){return new n(this.x-e.x,this.y-e.y)}multiply(e){return new n(this.x*e.x,this.y*e.y)}divide(e){return new n(this.x/e.x,this.y/e.y)}scalarAdd(e){return new n(this.x+e,this.y+e)}scalarSubtract(e){return new n(this.x-e,this.y-e)}scalarMultiply(e){return new n(this.x*e,this.y*e)}scalarDivide(e){return new n(this.x/e,this.y/e)}rotate(e){let t=e*Math.PI/180,r=Math.cos(t),o=Math.sin(t);return new n(this.x*r-this.y*o,this.x*o+this.y*r)}dot(e){return this.x*e.x+this.y*e.y}midPointFrom(e){return new n((this.x+e.x)/2,(this.y+e.y)/2)}static lerp(e,t,r){return new n(e.x+(t.x-e.x)*r,e.y+(t.y-e.y)*r)}lerp(e,t){return new n(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)}eq(e){return this.x===e.x&&this.y===e.y}lt(e){return this.x<e.x&&this.y<e.y}gt(e){return this.x>e.x&&this.y>e.y}lte(e){return this.x<=e.x&&this.y<=e.y}gte(e){return this.x>=e.x&&this.y>=e.y}distanceFrom(e){return Math.hypot(this.x-e.x,this.y-e.y)}clone(){return new n(this.x,this.y)}toString(){return`${this.x} ${this.y}`}transform(e,t=!1){return t?new n(e[0]*this.x+e[2]*this.y,e[1]*this.x+e[3]*this.y):new n(e[0]*this.x+e[2]*this.y+e[4],e[1]*this.x+e[3]*this.y+e[5])}};var rn=(n,e=0)=>typeof n=="number"&&Number.isFinite(n)?n:e,lv=n=>({sx:rn(n.scaleX,1)||1,sy:rn(n.scaleY,1)||1}),zp=n=>{let e=n.pathOffset;return!e||typeof e.x!="number"||typeof e.y!="number"?null:{x:e.x,y:e.y}},cv=n=>{let e=Ce(n),t=e?Fe(e):null;return t?{x:(t.left+t.right)/2,y:(t.top+t.bottom)/2}:null},uv=n=>{if(n.length===0)return null;let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)e>i.x&&(e=i.x),t>i.y&&(t=i.y),r<i.x&&(r=i.x),o<i.y&&(o=i.y);return{x:(e+r)/2,y:(t+o)/2}},hv=(n,e,t,r)=>`M ${t} 0 L ${n-t} 0 A ${t} ${r} 0 0 1 ${n} ${r} L ${n} ${e-r} A ${t} ${r} 0 0 1 ${n-t} ${e} L ${t} ${e} A ${t} ${r} 0 0 1 0 ${e-r} L 0 ${r} A ${t} ${r} 0 0 1 ${t} 0 Z`,Yp=(n,e)=>`M 0 ${-e} A ${n} ${e} 0 1 1 0 ${e} A ${n} ${e} 0 1 1 0 ${-e} Z`,iu=n=>{if(n.isTextType)return;let e=n.raw,t=se(e),{sx:r,sy:o}=lv(e);if(t===L.PATH){let a="";if(typeof e.path=="string")a=e.path;else if(Array.isArray(e.path)){let l=[];for(let u of e.path)!Array.isArray(u)||typeof u[0]!="string"||l.push(u.length===1?u[0]:`${u[0]} ${u.slice(1).join(" ")}`);a=l.join(" ")}return a.trim()?{path:a,pathOffset:zp(e)??cv(a)??{x:0,y:0}}:void 0}if(t===L.RECT||t===L.FABRICRECT){let a=n.dims.x*r,l=n.dims.y*o;if(!(a>0)||!(l>0))return;let u=it(e,n.dims.x,n.dims.y),c=u?Math.min(u.rx*r,a/2):0,h=u?Math.min(u.ry*o,l/2):0;return{path:c>0||h>0?hv(a,l,c,h):`M 0 0 L ${a} 0 L ${a} ${l} L 0 ${l} Z`,pathOffset:{x:a/2,y:l/2}}}if(t===L.CIRCLE){let a=rn(e.radius);return a>0?{path:Yp(a*r,a*o),pathOffset:{x:0,y:0}}:void 0}if(t===L.ELLIPSE){let a=(rn(e.rx)||n.dims.x/2)*r,l=(rn(e.ry)||n.dims.y/2)*o;return!(a>0)||!(l>0)?void 0:{path:Yp(a,l),pathOffset:{x:0,y:0}}}if(t===L.TRIANGLE){let a=n.dims.x*r,l=n.dims.y*o;return!(a>0)||!(l>0)?void 0:{path:`M ${-a/2} ${l/2} L 0 ${-l/2} L ${a/2} ${l/2} Z`,pathOffset:{x:0,y:0}}}if(t===L.POLYGON||t===L.POLYLINE){let a=Array.isArray(e.points)?e.points:[];return a.length===0?{path:"M 0 0",pathOffset:{x:0,y:0}}:{path:a.map((u,c)=>`${c===0?"M":"L"} ${u.x} ${u.y}`).join(" ")+(t===L.POLYGON?" Z":""),pathOffset:zp(e)??uv(a)??{x:0,y:0}}}if(t===L.LINE){let a=rn(e.x1),l=rn(e.y1),u=rn(e.x2),c=rn(e.y2);return{path:`M ${a} ${l} L ${u} ${c}`,pathOffset:{x:0,y:0}}}let i=n.dims.x*r,s=n.dims.y*o;if(!(!(i>0)||!(s>0)))return{path:`M 0 0 L ${i} 0 L ${i} ${s} L 0 ${s} Z`,pathOffset:{x:i/2,y:s/2}}};var Up=n=>{if(!(!n||n.length<8||n.some(e=>typeof e!="number"||!Number.isFinite(e))))return{tl:{x:n[0],y:n[1]},tr:{x:n[2],y:n[3]},br:{x:n[4],y:n[5]},bl:{x:n[6],y:n[7]}}},$p=n=>{let e=[n.tl,n.tr,n.br,n.bl],t=Math.min(...e.map(s=>s.x)),r=Math.min(...e.map(s=>s.y)),o=Math.max(...e.map(s=>s.x)),i=Math.max(...e.map(s=>s.y));return{minX:t,minY:r,width:Math.max(1,Math.ceil(o-t)),height:Math.max(1,Math.ceil(i-r))}},jp=(n,e,t)=>({tl:{x:n.tl.x+e,y:n.tl.y+t},tr:{x:n.tr.x+e,y:n.tr.y+t},br:{x:n.br.x+e,y:n.br.y+t},bl:{x:n.bl.x+e,y:n.bl.y+t}}),Vp=n=>{let e=n.tr.x+n.bl.x-n.tl.x,t=n.tr.y+n.bl.y-n.tl.y;return Math.abs(e-n.br.x)<.01&&Math.abs(t-n.br.y)<.01},su=n=>{let e=n.tl.x-n.tr.x+n.br.x-n.bl.x,t=n.tl.y-n.tr.y+n.br.y-n.bl.y;if(Math.abs(e)<1e-6&&Math.abs(t)<1e-6)return{a:n.tr.x-n.tl.x,b:n.bl.x-n.tl.x,c:n.tl.x,d:n.tr.y-n.tl.y,e:n.bl.y-n.tl.y,f:n.tl.y,g:0,h:0};let r=n.tr.x-n.br.x,o=n.tr.y-n.br.y,i=n.bl.x-n.br.x,s=n.bl.y-n.br.y,a=r*s-i*o;if(Math.abs(a)<1e-6)return;let l=(e*s-i*t)/a,u=(r*t-e*o)/a;return{a:n.tr.x-n.tl.x+l*n.tr.x,b:n.bl.x-n.tl.x+u*n.bl.x,c:n.tl.x,d:n.tr.y-n.tl.y+l*n.tr.y,e:n.bl.y-n.tl.y+u*n.bl.y,f:n.tl.y,g:l,h:u}},qr=(n,e,t)=>{let r=n.g*e+n.h*t+1;return{x:(n.a*e+n.b*t+n.c)/r,y:(n.d*e+n.e*t+n.f)/r}},qp=n=>{let{a:e,b:t,c:r,d:o,e:i,f:s,g:a,h:l}=n,u=e*(i-s*l)-t*(o-s*a)+r*(o*l-i*a);if(Math.abs(u)<1e-6)return;let c=(i-s*l)/u,h=(r*l-t)/u,d=(t*s-r*i)/u,f=(s*a-o)/u,m=(e-r*a)/u,p=(r*o-e*s)/u,b=(o*l-i*a)/u,g=(t*a-e*l)/u,x=(e*i-t*o)/u;if(!(Math.abs(x)<1e-6))return{a:c/x,b:h/x,c:d/x,d:f/x,e:m/x,f:p/x,g:b/x,h:g/x}};var Kp=32,Qp=120,au=1e-6,dv=()=>{let n=document.createElement("canvas");if(!n||typeof n.getContext>"u")throw new Error("Failed to create `canvas` element");return n},fv=n=>{let e=dv();return e.width=n.width,e.height=n.height,e.getContext("2d",{willReadFrequently:!0})?.drawImage(n,0,0),e},mv=(n,e,t)=>n.toDataURL?.(`image/${e}`,t),pv=n=>new Promise((e,t)=>{let r=new FileReader;r.onload=()=>e(String(r.result)),r.onerror=()=>t(r.error),r.readAsDataURL(n)}),Zp=async(n,e,t)=>{try{let r=await new Promise(o=>n.toBlob(o,`image/${e}`,t));if(r)return await pv(r)}catch{}return mv(n,e,t)},bv=(n,e,t)=>{let r=Math.max(1,n.width),o=Math.max(1,n.height),i=Math.max(1,Math.round(e)),s=Math.max(1,Math.round(t));if(Math.abs(r-i)<au&&Math.abs(o-s)<au)return n;let a=document.createElement("canvas");a.width=i,a.height=s;let l=a.getContext("2d");return l?(l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.drawImage(n,0,0,r,o,0,0,i,s),a):n},gv=(n,e,t,r,o)=>{let i=Math.max(0,Math.min(e-1,r)),s=Math.max(0,Math.min(t-1,o)),a=Math.floor(i),l=Math.floor(s),u=Math.min(e-1,a+1),c=Math.min(t-1,l+1),h=i-a,d=s-l,f=(l*e+a)*4,m=(l*e+u)*4,p=(c*e+a)*4,b=(c*e+u)*4,g=1-d,x=1-h,S=x*g,w=h*g,y=x*d,v=h*d;return[n[f]*S+n[m]*w+n[p]*y+n[b]*v,n[f+1]*S+n[m+1]*w+n[p+1]*y+n[b+1]*v,n[f+2]*S+n[m+2]*w+n[p+2]*y+n[b+2]*v,n[f+3]*S+n[m+3]*w+n[p+3]*y+n[b+3]*v]},xv=(n,e,t)=>{let r=su(t),o=r?qp(r):void 0;if(!o){eb(n,e,t,Kp);return}let i=Math.max(1,e.width),s=Math.max(1,e.height),a=e.getContext("2d",{willReadFrequently:!0});if(!a){eb(n,e,t,Kp);return}let l=a.getImageData(0,0,i,s),u=n.createImageData(n.canvas.width,n.canvas.height),c=u.data;for(let h=0;h<n.canvas.height;h++)for(let d=0;d<n.canvas.width;d++){let f=qr(o,d+.5,h+.5);if(f.x<0||f.x>1||f.y<0||f.y>1)continue;let m=f.x*(i-1),p=f.y*(s-1),b=gv(l.data,i,s,m,p),g=(h*n.canvas.width+d)*4;c[g]=b[0],c[g+1]=b[1],c[g+2]=b[2],c[g+3]=b[3]}n.putImageData(u,0,0)},Jp=(n,e,t,r)=>{let[o,i,s]=t,[a,l,u]=r,c=o.x*(i.y-s.y)+i.x*(s.y-o.y)+s.x*(o.y-i.y);if(Math.abs(c)<au)return;let h=(a.x*(i.y-s.y)+l.x*(s.y-o.y)+u.x*(o.y-i.y))/c,d=(a.y*(i.y-s.y)+l.y*(s.y-o.y)+u.y*(o.y-i.y))/c,f=(a.x*(s.x-i.x)+l.x*(o.x-s.x)+u.x*(i.x-o.x))/c,m=(a.y*(s.x-i.x)+l.y*(o.x-s.x)+u.y*(i.x-o.x))/c,p=(a.x*(i.x*s.y-s.x*i.y)+l.x*(s.x*o.y-o.x*s.y)+u.x*(o.x*i.y-i.x*o.y))/c,b=(a.y*(i.x*s.y-s.x*i.y)+l.y*(s.x*o.y-o.x*s.y)+u.y*(o.x*i.y-i.x*o.y))/c;n.save(),n.beginPath(),n.moveTo(a.x,a.y),n.lineTo(l.x,l.y),n.lineTo(u.x,u.y),n.closePath(),n.clip(),n.setTransform(h,d,f,m,p,b),n.drawImage(e,0,0),n.restore()},eb=(n,e,t,r)=>{let o=su(t);if(!o){n.drawImage(e,0,0,n.canvas.width,n.canvas.height);return}let i=Math.max(1,e.width),s=Math.max(1,e.height),a=Math.min(Qp,Math.max(1,Math.ceil(i/r))),l=Math.min(Qp,Math.max(1,Math.ceil(s/r)));for(let u=0;u<l;u++){let c=u/l,h=(u+1)/l,d=c*s,f=h*s;for(let m=0;m<a;m++){let p=m/a,b=(m+1)/a,g=p*i,x=b*i,S=qr(o,p,c),w=qr(o,b,c),y=qr(o,b,h),v=qr(o,p,h);Jp(n,e,[{x:g,y:d},{x,y:d},{x,y:f}],[S,w,y]),Jp(n,e,[{x:g,y:d},{x,y:f},{x:g,y:f}],[S,y,v])}}},yv=async(n,e,t={})=>{let r=t.quality??.92,o=t.format||"webp",i=Math.max(1,n.width),s=Math.max(1,n.height),a=Math.max(1,e?.width||i),l=Math.max(1,e?.height||s),u=bv(n,a,l),c=Up(e?.nonAffineTransform||e?.transform);if(!c){let g=fv(n);return{src:await Zp(g,o,r),width:i,height:s,sourceWidth:a,sourceHeight:l}}let h=$p(c),d=jp(c,-h.minX,-h.minY),f=t.objectBounds,m=document.createElement("canvas");m.width=h.width,m.height=h.height;let p=m.getContext("2d");if(!p)throw new Error("无法创建智能对象渲染画布");if(p.imageSmoothingEnabled=!0,p.imageSmoothingQuality="high",Vp(d)){let g=(d.tr.x-d.tl.x)/a,x=(d.tr.y-d.tl.y)/a,S=(d.bl.x-d.tl.x)/l,w=(d.bl.y-d.tl.y)/l,y=d.tl.x,v=d.tl.y;p.setTransform(g,x,S,w,y,v),p.drawImage(u,0,0)}else xv(p,u,d);let b;if(f){let g=Math.round(f.left-h.minX),x=Math.round(f.top-h.minY),S=Math.max(1,Math.round(f.width)),w=Math.max(1,Math.round(f.height));if(g>=0&&x>=0&&g+S<=h.width+1&&x+w<=h.height+1){b=document.createElement("canvas"),b.width=S,b.height=w;let v=b.getContext("2d");v&&v.drawImage(m,g,x,S,w,0,0,S,w)}else{b=document.createElement("canvas"),b.width=S,b.height=w;let v=b.getContext("2d");v&&(v.imageSmoothingEnabled=!0,v.imageSmoothingQuality="high",v.drawImage(m,0,0,h.width,h.height,0,0,S,w))}}else b=m;return{src:await Zp(b,o,r),width:b.width,height:b.height,sourceWidth:a,sourceHeight:l}};var ce=n=>n.node instanceof te?n.node:null,Be=n=>n.raw,kt=n=>{n.canvas?.requestRenderAll?.()},Ve=(n,e)=>{let t=Be(e);n.set({cellData:t.cellData??[],rows:t.rows,cols:t.cols}),kt(n)},lu=n=>n.rows??3,cu=n=>n.cols??3,Kr=n=>(Array.isArray(n.cellData)||(n.cellData=[]),n.cellData),ri=(n,e,t)=>{let r=we(n.cellMap,e,t);if(r)return r.isMerged&&r.mergeParent?we(n.cellMap,r.mergeParent.row,r.mergeParent.col):r},Xt=(n,e)=>{let t=ce(n);if(!t||!t.selectedCells.length)return;let r=new Set;for(let o of t.selectedCells){let i=lt(t.cellMap,o.row,o.col),s=`${i.row},${i.col}`;if(r.has(s))continue;r.add(s);let a=we(t.cellMap,i.row,i.col);a&&e(a)}Ve(n,t)},uu=(n,e,t)=>({get id(){return`${n.id}-r${e.row}c${e.col}-rect`},get _isCell(){return!0},get _row(){return e.row},get _col(){return e.col},get fill(){return e.fill},set fill(r){e.fill=r,t()},get stroke(){return e.stroke},set stroke(r){e.stroke=r,t()},get strokeWidth(){return e.strokeWidth??1},set strokeWidth(r){e.strokeWidth=r,t()},get _colspan(){return e.colspan??1},set _colspan(r){e.colspan=r,t()},get _rowspan(){return e.rowspan??1},set _rowspan(r){e.rowspan=r,t()},get _isMerged(){return e.isMerged??!1},set _isMerged(r){e.isMerged=r,t()},get _mergeParent(){return e.mergeParent??null},set _mergeParent(r){e.mergeParent=r,t()},get _hasCustomFill(){return e.hasCustomFill??!1},set _hasCustomFill(r){e.hasCustomFill=r,t()},get _hasCustomStroke(){return e.hasCustomStroke??!1},set _hasCustomStroke(r){e.hasCustomStroke=r,t()},set(r){for(let[o,i]of Object.entries(r))o!=="dirty"&&(e[o]=i);t()},get(r){return e[r]}}),tb=(n,e,t)=>({get id(){return`${n.id}-r${e.row}c${e.col}-text`},get _isCellText(){return!0},get _row(){return e.row},get _col(){return e.col},get text(){return e.text??""},set text(r){e.text=r,t()},get fill(){return e.textFill},set fill(r){e.textFill=r,t()},get fontSize(){return e.fontSize??Be(n).fontSize??14},set fontSize(r){e.fontSize=r,t()},get fontWeight(){return e.fontWeight},set fontWeight(r){e.fontWeight=r,t()},get fontFamily(){return e.fontFamily},set fontFamily(r){e.fontFamily=r,t()},get fontStyle(){return e.fontStyle},set fontStyle(r){e.fontStyle=r,t()},get textAlign(){return e.textAlign},set textAlign(r){e.textAlign=r,t()},get underline(){return e.underline??!1},set underline(r){e.underline=r,t()},get linethrough(){return e.linethrough??!1},set linethrough(r){e.linethrough=r,t()},get verticalAlign(){return e.verticalAlign??"middle"},set verticalAlign(r){e.verticalAlign=r,t()},set(r){for(let[o,i]of Object.entries(r))o!=="dirty"&&(o==="fill"?e.textFill=i:e[o]=i);t()},get(r){return r==="fill"?e.textFill:e[r]},setFontFamily(r){e.fontFamily=r,t()},refreshTextDimensions(){}}),Sv={canMergeCells(){let n=ce(this);return!!n&&n.selectedCells.length>1},canUseMergeCells(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=new Set,t=!1;for(let{row:r,col:o}of n.selectedCells){let i=ri(n,r,o);if(!i)return!1;(i.colspan??1)>1||(i.rowspan??1)>1?e.add(`${i.row},${i.col}`):t=!0}return!t&&e.size===1},canSplitRows(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=n.selectedCells[0],t=ri(n,e.row,e.col);return!!t&&(t.rowspan??1)>1},canSplitColumns(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=n.selectedCells[0],t=ri(n,e.row,e.col);return!!t&&(t.colspan??1)>1},isSelectColumn(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=new Set(n.selectedCells.map(r=>r.row)),t=new Set(n.selectedCells.map(r=>r.col));if(t.size===1){let r=Array.from(e),o=Math.min(...r),i=Math.max(...r),s=o===0&&i===lu(Be(n))-1,a=e.size>=2,l=!1;for(let u of n.selectedCells)if((ri(n,u.row,u.col)?.rowspan??1)>1){l=!0;break}return s||a||l}return t.size>1?e.size===1?!1:e.size<=t.size:!1},isSelectRow(){let n=ce(this);if(!n||!n.selectedCells.length)return!1;let e=new Set(n.selectedCells.map(r=>r.row)),t=new Set(n.selectedCells.map(r=>r.col));if(e.size===1){let r=Array.from(t),o=Math.min(...r),i=Math.max(...r),s=o===0&&i===cu(Be(n))-1,a=t.size>=2,l=!1;for(let u of n.selectedCells)if((ri(n,u.row,u.col)?.colspan??1)>1){l=!0;break}return s||a||l}return e.size>1?t.size===1?!1:e.size>t.size:!1},isRowSelected(n){let e=ce(this);return e?Ar(e.cellMap,e.selectedCells).rows.has(n):!1},isColumnSelected(n){let e=ce(this);return e?Ar(e.cellMap,e.selectedCells).cols.has(n):!1},selectCell(n,e,t=!1){let r=ce(this);if(r){if(t){if(r.cellAnchor){let o=r.cellAnchor,i=xn(r.cellMap,o,{row:n,col:e});r.setCellSelection(i,o,{r1:Math.min(o.row,n),r2:Math.max(o.row,n),c1:Math.min(o.col,e),c2:Math.max(o.col,e)})}}else{let o={row:n,col:e};r.setCellSelection([o],o,{r1:n,r2:n,c1:e,c2:e})}kt(this)}},selectColumn(n){let e=ce(this);e&&(e.setColumnSelection(n),kt(this))},selectRow(n){let e=ce(this);e&&(e.setRowSelection(n),kt(this))},selectAllCells(){let n=ce(this);if(!n)return;let e=n.tableView,t=Mo(n.cellMap,e.rows,e.cols);n.setCellSelection(t,t[0]??null,ze(t)),kt(this)},clearCellSelection(){let n=ce(this);n&&(n.clearCellSelection(),kt(this))},buildSelectionRange(n,e){let t=ce(this);return t?xn(t.cellMap,n,e):[]},mergeCells(n,e,t,r){let o=ce(this);if(!o)return;let i=So(o.raw,n,e,t,r),s={row:i.r1,col:i.c1};o.setCellSelection([s],s,i),Ve(this,o)},unmergeCells(n,e){let t=ce(this);if(!t||!vo(t.raw,n,e))return;let r={row:n,col:e};t.setCellSelection([r],r,{r1:n,r2:n,c1:e,c2:e}),Ve(this,t)},addRow(n){let e=ce(this);e&&(wo(e.raw,n??lu(Be(e))),Ve(this,e))},removeRow(n){let e=ce(this);if(!e)return;let t=n??lu(Be(e))-1;if(!Il(e.raw,t))return;let r=Vi(e.selectedCells,e.cellRange,t,"row");r?e.setCellSelection(r.cells,r.cells[0]??null,r.range):e.clearCellSelection(),Ve(this,e)},addColumn(n){let e=ce(this);e&&(To(e.raw,n??cu(Be(e))),Ve(this,e))},removeColumn(n){let e=ce(this);if(!e)return;let t=n??cu(Be(e))-1;if(!_l(e.raw,t))return;let r=Vi(e.selectedCells,e.cellRange,t,"col");r?e.setCellSelection(r.cells,r.cells[0]??null,r.range):e.clearCellSelection(),Ve(this,e)},setColumnWidth(n,e){let t=ce(this);t&&(xo(t.raw,n,e),this.set({columnWidths:Be(t).columnWidths??[]}),kt(this))},setRowHeight(n,e){let t=ce(this);t&&(yo(t.raw,n,e),this.set({manualRowHeights:Be(t).manualRowHeights??[]}),kt(this))},setSelectWidth(n){let e=ce(this);if(!e)return;let t=e.cellRange,r=Be(e),o=e.tableView;if(!t||o.cols<=0){this.setTableWidth(n);return}let i=r.minCellWidth??40,s=r.cellStrokeWidth??0,a=0;for(let c=t.c1;c<=t.c2;c++)a+=o.columnWidths[c]??0;if(a<=0)return;let l=(n-s-(t.c2-t.c1)*o.cellSpacing)/a,u=[...o.columnWidths];for(let c=t.c1;c<=t.c2;c++)u[c]=Math.max(i,(u[c]??0)*l);this.set({columnWidths:u}),kt(this)},setSelectHeight(n){let e=ce(this);if(!e)return;let t=e.cellRange,r=Be(e),o=e.tableView;if(!t||o.rows<=0){this.setTableHeight(n);return}let i=r.minCellHeight??40,s=r.cellStrokeWidth??0,a=0;for(let c=t.r1;c<=t.r2;c++)a+=o.rowHeights[c]??0;if(a<=0)return;let l=(n-s-(t.r2-t.r1)*o.cellSpacing)/a,u=Array.from({length:o.rows},(c,h)=>{let d=Array.isArray(r.manualRowHeights)?r.manualRowHeights[h]:null;return typeof d=="number"?d:null});for(let c=t.r1;c<=t.r2;c++)u[c]=Math.max(i,(o.rowHeights[c]??0)*l);this.set({manualRowHeights:u}),kt(this)},getColumnWidth(n){let e=ce(this);return e?e.tableView.columnWidths[n]??0:0},getRowHeight(n){let e=ce(this);return e?e.tableView.rowHeights[n]??0:0},getRowMinHeight(n){let e=ce(this);return e?e.getRowMinHeight(n):0},relayout(){let n=ce(this);n&&(n.rebuildTable(),kt(this))},previewLayout(){this.relayout()},getCell(n,e){let t=ce(this);if(!t)return;let r=we(t.cellMap,n,e);return r?uu(t,r,()=>Ve(this,t)):void 0},getCellText(n,e){let t=ce(this);if(!t)return;let r=we(t.cellMap,n,e);return r?tb(t,r,()=>Ve(this,t)):void 0},setSelectionTextAlign(n){Xt(this,e=>{e.textAlign=n})},setSelectionFontSize(n){Xt(this,e=>{e.fontSize=n})},changeSelectionFontSize(n){let e=ce(this);if(!e)return;let t=Be(e).fontSize??14;Xt(this,r=>{let o=Number(r.fontSize)||t;r.fontSize=n==="+"?o+1:Math.max(1,o-1)})},setSelectionFontWeight(n){Xt(this,e=>{e.fontWeight=n})},setSelectionFontStyle(n){Xt(this,e=>{e.fontStyle=n})},setSelectionUnderline(n){Xt(this,e=>{e.underline=n})},setSelectionLinethrough(n){Xt(this,e=>{e.linethrough=n})},setSelectionCellFill(n){Xt(this,e=>{e.fill=n,e.hasCustomFill=!0})},setSelectionCellStroke(n){Xt(this,e=>{e.stroke=n,e.hasCustomStroke=!0})},setSelectionCellStrokeWidth(n){Xt(this,e=>{e.strokeWidth=n,e.hasCustomStroke=!0})},updateCellFill(n){let e=ce(this);if(!e)return;let t=Be(e);t.cellFill=n;for(let r of Kr(t))!r.isMerged&&!r.hasCustomFill&&(r.fill=n);Ve(this,e)},updateCellTextFill(n){let e=ce(this);if(!e)return;let t=Be(e);t.textFill=n;for(let r of Kr(t))r.hasCustomTextFill||(r.textFill=n);Ve(this,e)},updateCellStroke(n){let e=ce(this);if(!e)return;let t=Be(e);t.cellStroke=n;for(let r of Kr(t))r.hasCustomStroke||(r.stroke=n);Ve(this,e)},updateBorderWidth(n){let e=ce(this);e&&(Be(e).cellStrokeWidth=n,Ve(this,e))},applyTextStylesToAll(n){let e=ce(this);if(!e)return;let t=Be(e),r={...t.textDefaults??{}};for(let[o,i]of Object.entries(n))r[o]=i;t.textDefaults=r;for(let o of Kr(t))for(let[i,s]of Object.entries(n))i==="fill"?o.textFill=s:o[i]=s;Ve(this,e)}},vv={selectedCells(){let n=ce(this);if(n)return n.selectedCells.map(e=>{let t=we(n.cellMap,e.row,e.col);return t?uu(n,t,()=>Ve(this,n)):void 0}).filter(e=>e!==void 0)},_selectedCells(){let n=ce(this);return n?n.selectedCells:void 0},_selectionRange(){let n=ce(this);return n?n.cellRange:void 0},hasSelection(){let n=ce(this);return n?n.hasCellSelection:!1},selectionCount(){let n=ce(this);return n?n.selectedCells.length:0},cellTexts(){let n=ce(this);if(!n)return;let e=()=>Ve(this,n);return Kr(Be(n)).map(t=>tb(n,t,e))},cells(){let n=ce(this);if(!n)return;let e=()=>Ve(this,n);return Kr(Be(n)).map(t=>uu(n,t,e))},columnWidths(){let n=ce(this);return n?[...n.tableView.columnWidths]:void 0},rowHeights(){let n=ce(this);return n?[...n.tableView.rowHeights]:void 0}},hu=n=>{for(let[e,t]of Object.entries(Sv))Object.assign(n,{[e]:t});for(let[e,t]of Object.entries(vv))Object.defineProperty(n,e,{get:t,configurable:!0,enumerable:!1})};var du=(n,e,t)=>{let r=Xe(e);if(!r)return null;let o=Et(n,e,t),i=r==="circle"||(typeof e.curvature=="number"?e.curvature:300)>0,s=o.contentOffsetX-o.width/2,a=o.contentOffsetX+o.width/2,l=o.contentOffsetY-o.height/2,u=o.contentOffsetY+o.height/2,c=n.lines.map(()=>[]);for(let h of o.chars){let d=c[h.line];if(!d)continue;let f={char:h.char,charAngle:i?-h.rotation:-(h.rotation+Math.PI),leftAngle:0,rightAngle:0,charRadius:0,bottomRadius:0,topRadius:0,lineRadius:0,cl:{x:h.x,y:h.y},tl:{x:s,y:l},br:{x:a,y:u},bl:{x:h.x,y:h.y},tr:{x:h.x,y:h.y},nl:{x:h.x,y:h.y},nr:{x:h.x,y:h.y},lc:{x:h.x,y:h.y}};d.push(f)}for(let h of c){let d=h[h.length-1];h.push({char:"",charAngle:0,leftAngle:0,rightAngle:0,charRadius:0,bottomRadius:0,topRadius:0,lineRadius:0,cl:d?{...d.cl}:{x:s,y:l},tl:{x:s,y:l},br:{x:a,y:u},bl:{x:s,y:l},tr:{x:a,y:u},nl:{x:s,y:l},nr:{x:a,y:u},lc:{x:s,y:l}})}return c};var wv=n=>{let e=n.textLines,t=n.charBounds,r=n.lineHeights;if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(r)||e.length===0||t.length!==e.length||r.length!==e.length)return!1;for(let o=0;o<e.length;o++)if(typeof e[o]!="string"||!Array.isArray(t[o])||t[o].length===0||typeof r[o]!="number"||!Number.isFinite(r[o]))return!1;return!0},hr=class{node;ctx;constructor(e,t){this.node=e,this.ctx=t}set(e,t){let r=typeof e=="string"?{[e]:t}:{...e},o=r.__isCropping&&this.ctx.cropSessionNodeId?.()!==this.node.id?this.toObject():void 0;if("cropAspectRatio"in r){let s={cropAspectRatio:r.cropAspectRatio};delete r.cropAspectRatio,this.ctx.setNodeProps(this.node,s)}if("_cropKey"in r){let s=r._cropKey;delete r._cropKey,this.ctx.applyCropShape?.(this.node,typeof s=="string"&&s?s:null)}if("__isCropping"in r){let s=!!r.__isCropping;delete r.__isCropping,this.clearSessionFlagDirty("__isCropping"),this.__isCropping=s,o&&this.__isCropping&&(this.cropBeforeState=o)}if("__isExpand"in r){let s=!!r.__isExpand;delete r.__isExpand,this.clearSessionFlagDirty("__isExpand"),this.__isExpand=s}if(typeof r.width=="number"&&Wr(this.node)){let s=r.width;delete r.width,this.ctx.setGroupWidth?this.ctx.setGroupWidth(this.node,s):this.ctx.setNodeProps(this.node,{width:s})}this.bumpTextboxWidthToLayoutBox(r),this.bridgeImageSizeProps(r);let i=r;if((typeof r.width=="number"||typeof r.height=="number"||typeof r.scaleX=="number"||typeof r.scaleY=="number")&&!("clipImage"in r)&&ot.has(se(this.node.raw))){let s=zt(this.node),a=this.node.raw,l=Number(a.width)||0,u=Number(a.height)||0,c=this.node.clipImageEl,h=c?.naturalWidth||Number(s?.width)||0,d=c?.naturalHeight||Number(s?.height)||0;if(s&&l>0&&u>0&&h>0&&d>0){typeof r.scaleX=="number"&&r.scaleX>0&&!("width"in r)&&(r.width=l*r.scaleX,r.scaleX=1),typeof r.scaleY=="number"&&r.scaleY>0&&!("height"in r)&&(r.height=u*r.scaleY,r.scaleY=1);let f=typeof r.width=="number"?r.width:l,m=typeof r.height=="number"?r.height:u;if(f>0&&m>0){let p=(x,S)=>Math.max(x/h,S/d),b=Number(s.scaleX)||1,g=p(f,m)*(b/p(l,u));i={...r,clipImage:{...s,scaleX:g,scaleY:g}}}}}return Object.keys(i).length>0&&this.ctx.setNodeProps(this.node,i),this}bumpTextboxWidthToLayoutBox(e){if(typeof e.width!="number"||!(this.node instanceof ye)||e.width<0||se(this.node.raw)!==L.TEXTBOX||Xe(this.node.raw))return;let r=e.width;delete e.width,this.ctx.setNodeProps(this.node,{width:r});let o=this.node.dims.x;Number.isFinite(o)&&o>r+.01&&this.ctx.setNodeProps(this.node,{width:o})}clearSessionFlagDirty(e){this.node.raw[e]!==void 0&&this.ctx.setNodeProps(this.node,{[e]:void 0})}get(e){return this.node.raw[e]}setCoords(){}getCenterPoint(){return{...this.node.center}}getRelativeCenterPoint(){return new nn(this.node.center.x,this.node.center.y)}translateToOriginPoint(e,t="center",r="center"){let o=c=>c==="left"||c==="top"?-.5:c==="right"||c==="bottom"?.5:0,i=o(t),s=o(r),a=i||s?this._getTransformedDimensions():new nn(0,0),l=new nn(e.x+i*a.x,e.y+s*a.y),u=this.node.raw.angle;return typeof u=="number"&&u&&(l=l.rotate(u*Math.PI/180,e)),l}toPath(){let e=this.ctx.getTextGlyphPath?.(this.node);return e||iu(this.node)}toPathDecorations(){return this.ctx.getTextDecorations?.(this.node)??[]}toPathEffectLayers(e){return[]}_getTransformedDimensions(){let e=this.node.raw;return new nn(this.node.dims.x*(e.scaleX??1),this.node.dims.y*(e.scaleY??1))}getBoundingRect(){let e=this.node.bounds;return{left:e.left,top:e.top,width:e.right-e.left,height:e.bottom-e.top}}getInkRect(){let e=Xn(this.node.inkACoords);return{left:e.left,top:e.top,width:e.width,height:e.height}}get aCoords(){return this.node.aCoords}getCoords(){let e=this.node.aCoords;return[e.tl,e.tr,e.br,e.bl]}calcOCoords(){let e=this.ctx.getViewportTransform?.()??[1,0,0,1,0,0],t=o=>({x:e[0]*o.x+e[2]*o.y+e[4],y:e[1]*o.x+e[3]*o.y+e[5]}),r=this.node.aCoords;return{tl:t(r.tl),tr:t(r.tr),br:t(r.br),bl:t(r.bl)}}rotate(e){let{angle:t,left:r,top:o}=this.node.rotateAroundCenter(e);return this.set({angle:t,left:r,top:o})}setPositionByOrigin(e,t,r){let o=this.node.raw,i=typeof o.scaleX=="number"?o.scaleX:1,s=typeof o.scaleY=="number"?o.scaleY:1,a=this.node.dims.x*i,l=this.node.dims.y*s,u=t==="center"?0:t==="right"?.5:-.5,c=r==="center"?0:r==="bottom"?.5:-.5,h=u*a,d=c*l,f=(typeof o.angle=="number"?o.angle:0)*Math.PI/180,m=Math.cos(f),p=Math.sin(f),b={x:e.x-(h*m-d*p),y:e.y-(h*p+d*m)},g=ge({...o},b);return this.set({left:g.x,top:g.y})}scale(e){let t=this.node.raw;return this.set({scaleX:(t.scaleX??1)*e,scaleY:(t.scaleY??1)*e})}getScaledWidth(){return this.node.dims.x*(this.node.raw.scaleX??1)}getScaledHeight(){return this.node.dims.y*(this.node.raw.scaleY??1)}getObjectScaling(){let e=this.node.raw;return{scaleX:e.scaleX??1,scaleY:e.scaleY??1}}get getObjects(){if(this.node instanceof J)return()=>this.node.children.map(e=>this.ctx.wrapNode(e))}get _objects(){if(this.node instanceof J)return this.node.children.map(e=>this.ctx.wrapNode(e))}get ref(){return this}get isImageLikeNode(){let e=se(this.node.raw);return dt.has(e)||ot.has(e)||e===L.GIF||e===L.VIDEO}get getSrc(){if(this.isImageLikeNode)return()=>{let e=this.node.raw;return typeof e.originalSrc=="string"&&e.originalSrc?e.originalSrc:typeof e.src=="string"?e.src:""}}get getRealSrc(){let e=this.getSrc;if(e)return()=>e()}get replaceSrc(){if(this.isImageLikeNode)return async e=>(this.set({src:e,crossOrigin:"anonymous",originalSrc:e}),await this.ctx.reloadNodeImage?.(this.node),this)}get setElement(){if(this.isImageLikeNode)return(e,t)=>(this.node.imageEl=e,t&&this.set(t),this)}get getElement(){if(!this.isImageLikeNode)return;let e=this.node;return e instanceof ie?()=>e.paintSource??e.imageEl:()=>e.imageEl}get _element(){if(this.isImageLikeNode)return this.node.imageEl}get clipImage(){return zt(this.node)?Ev(this.node,this.ctx):void 0}set clipImage(e){let t=e&&typeof e=="object"&&typeof e.toObject=="function"?e.toObject(this.serializationProps()):e;this.ctx.setNodeProps(this.node,{clipImage:t})}getWidthHeight(e=!1){let t=this._getTransformedDimensions(),r=(this.node.raw.strokeWidth??0)||0;return{x:t.x-r,y:t.y-r}}getWidth(){return this.getWidthHeight().x}getHeight(){return this.getWidthHeight().y}sourceNaturalSize(){let e=this.node.imageEl;if(e)return{width:e.naturalWidth||e.width||0,height:e.naturalHeight||e.height||0};if(this.node instanceof ie){let t=this.node.paintSource;if(t)return{width:("videoWidth"in t?t.videoWidth:t.width)||t.width||0,height:("videoHeight"in t?t.videoHeight:t.height)||t.height||0}}return{width:0,height:0}}getOriginalElementWidth(){return this.sourceNaturalSize().width}getOriginalElementHeight(){return this.sourceNaturalSize().height}getElementWidth(){return this.sourceNaturalSize().width}getElementHeight(){return this.sourceNaturalSize().height}cropOffset(){if(!this.isImageLikeNode)return{x:0,y:0};let e=this.node.raw;return e.cropSizeMode==="visible"?{x:0,y:0}:{x:Number(e.cropX)||0,y:Number(e.cropY)||0}}get left(){return this.node.raw.left??0}set left(e){this.set({left:e})}get top(){return this.node.raw.top??0}set top(e){this.set({top:e})}get scaleX(){return this.node.raw.scaleX??1}set scaleX(e){this.set({scaleX:e})}get scaleY(){return this.node.raw.scaleY??1}set scaleY(e){this.set({scaleY:e})}get angle(){return this.node.raw.angle??0}set angle(e){this.set({angle:e})}get skewX(){return this.node.raw.skewX??0}set skewX(e){this.set({skewX:e})}get skewY(){return this.node.raw.skewY??0}set skewY(e){this.set({skewY:e})}get flipX(){return this.node.raw.flipX??!1}set flipX(e){this.set({flipX:e})}get flipY(){return this.node.raw.flipY??!1}set flipY(e){this.set({flipY:e})}get originX(){return this.node.raw.originX??"left"}set originX(e){this.set({originX:e})}get originY(){return this.node.raw.originY??"top"}set originY(e){this.set({originY:e})}get width(){return(this.node.raw.width??0)-this.cropOffset().x}set width(e){if(Wr(this.node)){if(this.ctx.setGroupWidth){this.ctx.setGroupWidth(this.node,e);return}this.ctx.setNodeProps(this.node,{width:e});return}let t=this.cropOffset();this.ctx.setNodeProps(this.node,{width:e+t.x})}get height(){let e=this.node.raw;if(this.node instanceof ye){let t=typeof e.height=="number"?e.height:0;return Math.max(this.node.textLayout.height,t)-this.cropOffset().y}return(e.height??0)-this.cropOffset().y}set height(e){let t=this.cropOffset();this.ctx.setNodeProps(this.node,{height:e+t.y})}bridgeImageSizeProps(e){if(!this.isImageLikeNode)return;let t=this.node.raw;if(t.cropSizeMode==="visible")return;let r=typeof e.cropX=="number"?e.cropX:Number(t.cropX)||0,o=typeof e.cropY=="number"?e.cropY:Number(t.cropY)||0;typeof e.width=="number"&&r>0&&(e.width=e.width+r),typeof e.height=="number"&&o>0&&(e.height=e.height+o)}cropBeforeState;get __isCropping(){return this.isImageLikeNode&&this.ctx.cropSessionNodeId?.()===this.node.id}set __isCropping(e){if(this.isImageLikeNode)if(e){let t=this.ctx.cropSessionNodeId?.()!==this.node.id;if(t&&(this.cropBeforeState=this.toObject()),!this.ctx.enterCropSession?.(this.node)){t&&(this.cropBeforeState=void 0);return}let r=this.node.raw.cropAspectRatio;typeof r=="number"&&r>0&&this.ctx.setCropSessionAspectRatio?.(r)}else this.ctx.exitCropSession?.(this.node),this.cropBeforeState=void 0}get __isExpand(){return this.isImageLikeNode&&this.ctx.expandSessionNodeId?.()===this.node.id}set __isExpand(e){this.isImageLikeNode&&(e?this.ctx.enterExpandSession?.(this.node):this.ctx.exitExpandSession?.(this.node))}get beforeState(){return this.cropBeforeState}onDeselectEvent(){this.ctx.exitCropSession?.(this.node),this.ctx.exitExpandSession?.(this.node),this.cropBeforeState=void 0}expandOffsetOf(e){let t=this.ctx.expandSessionOffsets?.(this.node);if(t)return t[e];let r=e==="left"?"Left":e==="right"?"Right":e==="top"?"Top":"Bottom",o=this.node.raw[`expand${r}Offset`];return typeof o=="number"?o:void 0}get expandLeftOffset(){return this.isImageLikeNode?this.expandOffsetOf("left"):void 0}get expandRightOffset(){return this.isImageLikeNode?this.expandOffsetOf("right"):void 0}get expandTopOffset(){return this.isImageLikeNode?this.expandOffsetOf("top"):void 0}get expandBottomOffset(){return this.isImageLikeNode?this.expandOffsetOf("bottom"):void 0}setExpandOffset(){let e=this.ctx.expandSessionOffsets?.(this.node);e&&this.set({expandLeftOffset:e.left,expandRightOffset:e.right,expandTopOffset:e.top,expandBottomOffset:e.bottom})}updateCropScale(e){if(!this.__isCropping||!(e>0)||!Number.isFinite(e))return!1;if(this.ctx.updateCropSessionScale)return this.ctx.updateCropSessionScale(e);let t=this.node.imageEl;if(!t)return!1;let r=this.node.raw,o=t.naturalWidth||t.width,i=t.naturalHeight||t.height,s=r.scaleX??1,a=e/s,l=e/(r.scaleY??1),u=this.width,c=this.height,h=u/a,d=c/l,f=(r.cropX??0)+u/2-h/2,m=(r.cropY??0)+c/2-d/2;return h<Math.min(8,o)||d<Math.min(8,i)||f<0||m<0||f+h>o||m+d>i?!1:(this.set({cropScale:e,scaleX:e,scaleY:e,width:h,height:d,cropX:f,cropY:m}),!0)}getMaxEffectPadding(){let e=this.node.raw,t=0,r=e.effects??{},o=c=>(c??[]).filter(h=>h.enabled&&h.showInDialog),i=o(r.solidFill);i.length>0&&(t=Math.max(t,i.reduce((c,h)=>Math.max(c,Math.abs(Number(h.offsetX)||0),Math.abs(Number(h.offsetY)||0)),0)));let s=o(r.dropShadow);s.length>0&&(t=Math.max(t,s.reduce((c,h)=>{let d=(Number(h.blur)||0)*2;return Math.max(c,Math.abs(Number(h.offsetX)||0)+d,Math.abs(Number(h.offsetY)||0)+d)},0)));let a=o(r.stroke);a.length>0&&(t=Math.max(t,a.reduce((c,h)=>{let d=h.size,f=Number(h.strokeWidth)||Number(d?.value)||0;return Math.max(c,f+Math.abs(Number(h.offsetX)||0),f+Math.abs(Number(h.offsetY)||0))},0)));let l=e.shadow;if(l){let c=(Number(l.blur)||0)*2;t=Math.max(t,Math.abs(Number(l.offsetX)||0)+c,Math.abs(Number(l.offsetY)||0)+c)}let u=Number(e.strokeWidth)||0;if(e.stroke&&u){let c=e.strokeAlignment==="outside"?u*2:u;t=Math.max(t,c)}return t}isType(...e){let t=se(this.node.raw);return e.some(r=>r.toLowerCase()===t)}getStyleAtPosition(e){if(!(this.node instanceof ye))return{};let t=typeof this.node.raw.text=="string"?this.node.raw.text:"";if(e<0||e>=t.length)return{};let r=e,o=t.split(`
1092
1092
  `);for(let i=0;i<o.length;i++){if(r<=o[i].length)return this.objectStyles()?.[i]?.[r]??{};r-=o[i].length+1}return{}}calcTransformMatrix(){return[...this.node.matrix]}setTableWidth(e){if(!(this.node instanceof te))return;let t=this.node.raw,r=t.cols??0,o=t.columnWidths;if(r<=0||!Array.isArray(o)||o.length===0)return;let i=t.cellStrokeWidth??0,s=t.cellSpacing??0,a=o.reduce((c,h)=>c+h,0);if(a<=0)return;let l=(e-i-(r-1)*s)/a,u=t.minCellWidth??0;this.set({columnWidths:o.map(c=>Math.max(u,c*l))})}setTableHeight(e){if(!(this.node instanceof te))return;let t=this.node.raw,r=t.rows??0,o=t.rowHeights;if(r<=0||!Array.isArray(o)||o.length===0)return;let i=t.cellStrokeWidth??0,s=t.cellSpacing??0,a=o.reduce((c,h)=>c+h,0);if(a<=0)return;let l=(e-i-(r-1)*s)/a,u=t.minCellHeight??0;this.set({manualRowHeights:o.map(c=>Math.max(u,c*l))})}cursor2D(e){let t=typeof this.node.raw.text=="string"?this.node.raw.text:"",r=Math.max(0,Math.min(e,t.length)),o=t.split(`
1093
1093
  `);for(let i=0;i<o.length;i++){if(r<=o[i].length)return{line:i,char:r};r-=o[i].length+1}return{line:Math.max(0,o.length-1),char:o[o.length-1]?.length??0}}stylesToEngineForm(e,t){return e}stylesToPersistForm(e,t){return e}serializationProps(){}stylesMap(){let e=this.node.raw;return Array.isArray(e.styles)&&(e.styles=this.stylesToEngineForm(e.styles,typeof e.text=="string"?e.text:"")??{}),e.styles||(e.styles={}),e.styles}objectStyles(){let e=this.node.raw;return Array.isArray(e.styles)&&(e.styles=this.stylesToEngineForm(e.styles,typeof e.text=="string"?e.text:"")??{}),e.styles}get selectionStart(){return this.ctx.getNodeSelectionRange?.(this.node)?.start??0}get selectionEnd(){return this.ctx.getNodeSelectionRange?.(this.node)?.end??0}cleanStyle(e){let t=this.node.raw,r=this.objectStyles();if(!r)return!1;let o=0,i,s,a=!0,l=0;for(let u in r){i=0;for(let c in r[u]){let h=r[u][c]||{},d=h[e]!==void 0;o++,d?(s===void 0?s=h[e]:h[e]!==s&&(a=!1),h[e]===t[e]&&delete h[e]):a=!1,Object.keys(h).length!==0?i++:delete r[u][c]}i===0&&delete r[u]}if(typeof t.text=="string")for(let u of t.text.split(`
1094
- `))l+=u.length;return a&&o===l&&o>0&&s!==void 0?(this.set({[e]:s}),this.removeStyle?.(e),!0):(o>0&&this.set({styles:t.styles}),!1)}removeStyle(e){let t=this.objectStyles();if(t){for(let r in t){let o=t[r];for(let i in o)delete o[i][e],Object.keys(o[i]).length===0&&delete o[i];Object.keys(o).length===0&&delete t[r]}this.set({styles:t})}}setSelectionStyles(e,t,r){if(!(this.node instanceof ye))return;let o=this.ctx.getNodeSelectionRange?.(this.node),i=t??o?.start??0,s=r??o?.end??0;if(s<=i)return;let a=this.stylesMap();for(let l=i;l<s;l++){let{line:u,char:c}=this.cursor2D(l);a[u]||(a[u]={});let d={...a[u][c]??{}};for(let f of Object.keys(e))e[f]!==void 0&&(d[f]=e[f]);a[u][c]=d}this.set({styles:this.stylesMap()})}getSelectionStyles(e,t){if(!(this.node instanceof ye))return[];let r=this.ctx.getNodeSelectionRange?.(this.node),o=e??r?.start??0,i=t??r?.end??o,s=[];for(let a=o;a<i;a++)s.push(this.getStyleAtPosition(a));return s}setFontFamily(e,t){this.set({fontFamily:e})}get fontFamily(){return String(this.node.raw.fontFamily??"")}get type(){return String(this.node.raw.type??"")}initDimensions(){}calcTextWidth(){return this.node instanceof ye?this.node.textLayout.lines.reduce((e,t)=>Math.max(e,t.width),0):0}refreshTextDimensions(){}replaceFontFamily(e,t){let r=this.node.raw,o=!1;if(r.fontFamily===e&&(this.set({fontFamily:t}),o=!0),r.styles){for(let i of Object.values(r.styles))if(i)for(let s of Object.values(i))s?.fontFamily===e&&(s.fontFamily=t,o=!0);o&&this.set({styles:r.styles})}return o}get rawTypeLower(){return se(this.node.raw)}get transformKind(){return Ge(this.node.raw)}get setRadius(){if(this.transformKind==="arc")return e=>this.set({curvature:e})}get setWarpStrength(){let e=this.transformKind;if(!(e!=="arch"&&e!=="waist"&&e!=="flag"))return t=>this.set({warpStrength:Math.max(-1,Math.min(1,t))})}get clearCache(){let e=this.transformKind;if(!(e!=="arch"&&e!=="waist"&&e!=="flag"))return()=>{this.ctx.invalidateNodeBakes?.(this.node),this.ctx.getCanvas?.()?.requestRenderAll?.()}}get setCircleParams(){if(this.transformKind==="circle")return e=>this.set(e)}get setTexts(){if(this.node instanceof ye)return e=>this.set({texts:e})}get texts(){if(!(this.node instanceof ye))return;let e=this.node.raw.texts;return Array.isArray(e)?e:[]}toObject(e){let t={...this.node.toObject()};if(this.isImageLikeNode){let r=this.sourceNaturalSize();t.width===void 0&&r.width>0&&(t.width=r.width),t.height===void 0&&r.height>0&&(t.height=r.height)}if(this.node instanceof ye){let r=this.node.textLayout,o=this.node.textStyle.lineHeight??1.16,i=hu(r,this.node.raw,o);i&&(t.charTransformations=i),r.lines.length>0&&!vv(t)&&(t.textLines=r.lines.map(a=>a.graphemes.join("")),t.charBounds=r.lines.map(a=>{let l=a.boxes.map(u=>({left:u.left,width:u.width,kernedWidth:u.kernedWidth,height:u.height}));if(l.length>0){let u=l.reduce((c,h)=>c+(h.kernedWidth||0),0);l.push({left:u,width:0,kernedWidth:0,height:l[l.length-1].height})}return l}),t.lineHeights=r.lines.map(a=>a.implHeight*o));let s=this.node.raw;t.styles=this.stylesToPersistForm(t.styles,typeof s.text=="string"?s.text:"")}if(e?.length){let r=this.node.raw,o=t;for(let i of e)o[i]===void 0&&r[i]!==void 0&&(o[i]=r[i])}return t}get id(){return this.node.id}get canvas(){return this.ctx.getCanvas?.()}get group(){let e=this.ctx.getCanvas?.(),t=fu(e?.document,this.node);return t?this.ctx.wrapNode(t):void 0}get topGroup(){let e=this.ctx.getCanvas?.(),t,r=this.node;for(;;){let o=fu(e?.document,r);if(!o)break;t=o,r=o}return t?this.ctx.wrapNode(t):void 0}get parent(){return this.group}get applyMaskParams(){if(this.node instanceof le)return e=>{this.node.applyMaskParams(e),this.ctx.getCanvas?.()?.requestRenderAll?.()}}get updateGapParams(){if(this.node instanceof le)return e=>{this.node.updateGapParams(e),this.ctx.getCanvas?.()?.requestRenderAll?.()}}get updateLayout(){if(this.node instanceof le)return e=>{this.node.updateLayout(e),this.ctx.getCanvas?.()?.requestRenderAll?.()}}get visible(){return this.node.visible}set visible(e){this.set({visible:e})}get opacity(){let e=this.node.raw.opacity;return typeof e=="number"?e:1}set opacity(e){this.set({opacity:e})}get strokeWidth(){let e=this.node.raw.strokeWidth;return typeof e=="number"?e:1}set strokeWidth(e){this.set({strokeWidth:e})}_createCacheCanvas(){}_removeCacheCanvas(){}get isEditing(){return this.ctx.isEditingNode(this.node)}enterEditing(){return this.node.isTextType&&this.ctx.enterNodeEditing(this.node),this}exitEditing(){return this.ctx.exitEditing(),this}bringToFront(){this.ctx.bringToFront(this.node)}sendToBack(){this.ctx.sendToBack(this.node)}bringForward(){this.ctx.bringForward(this.node)}sendBackwards(){this.ctx.sendBackwards(this.node)}moveTo(e){this.ctx.moveNodeTo(this.node,e)}remove(){this.ctx.removeNode(this.node)}get changeControls(){if(Bt(this.node))return(e,t=!0)=>{this.ctx.changeNodeControls(this.node,e)}}get isEditingPath(){return this.ctx.isPathEditingNode(this.node)}get setAnchorPointType(){if(Bt(this.node)==="path")return(e,t)=>this.ctx.setNodeAnchorType(this.node,e,t)}get getActiveAnchorKey(){if(Bt(this.node))return()=>this.ctx.getNodePathEditInfo(this.node)?.activeAnchorKey}get getActiveAnchorIndex(){if(Bt(this.node))return()=>this.ctx.getNodePathEditInfo(this.node)?.activeAnchorIndex}get getAnchorPointStyleByIndex(){if(Bt(this.node)==="path")return e=>_c(Ce(this.node.raw.path),e)}get highlightAnchor(){if(Bt(this.node))return e=>{this.ctx.highlightNodeAnchor(this.node,e)}}get resetAnchorStyles(){if(Bt(this.node))return()=>{this.ctx.resetNodeAnchorStyles(this.node)}}},zt=n=>{let e=n.raw;if(!ot.has(se(e)))return null;let t=e.clipImage;return!t||typeof t!="object"||typeof t.src!="string"?null:t},wv=new Set(["_cacheCanvas","dirty","canvas"]),du=class{constructor(e,t){this.node=e;this.ctx=t}node;ctx;set(e){let t=zt(this.node);if(!t)return this;let r={...t};for(let[o,i]of Object.entries(e))wv.has(o)||(r[o]=i);return this.ctx.setNodeProps(this.node,{clipImage:r}),this}toObject(e){let t=zt(this.node);return t?{...t}:{}}setCoords(){}getSrc(){let e=zt(this.node);return e&&typeof e.originalSrc=="string"&&e.originalSrc?e.originalSrc:e&&typeof e.src=="string"?e.src:""}get replaceSrc(){if(zt(this.node))return async e=>(this.set({src:e,crossOrigin:"anonymous",originalSrc:e}),await this.ctx.reloadMaskClipImage?.(this.node),this)}getRelativeCenterPoint(){let e=zt(this.node),t=a=>typeof a=="number"?a:0,r=a=>typeof a=="number"?a:1,o=a=>a==="center"?.5:a==="right"||a==="bottom"?1:0,i=t(e?.width)*r(e?.scaleX),s=t(e?.height)*r(e?.scaleY);return new nn(t(e?.left)+(.5-o(e?.originX))*i,t(e?.top)+(.5-o(e?.originY))*s)}getOriginalElementWidth(){let e=this.node.clipImageEl;return e?.naturalWidth||e?.width||Number(zt(this.node)?.width)||0}getOriginalElementHeight(){let e=this.node.clipImageEl;return e?.naturalHeight||e?.height||Number(zt(this.node)?.height)||0}},fu=(n,e)=>{if(!n)return;let t=r=>{for(let o of r){if(!(o instanceof J))continue;if(o.children.some(s=>s===e))return o;let i=t(o.children);if(i)return i}};return t(n.nodes)},Tv=(n,e)=>{let t=new du(n,e);return new Proxy(t,{get(r,o,i){if(typeof o=="symbol")return Reflect.get(r,o,i);if(o==="then")return;if(o in r)return Reflect.get(r,o,i);let s=zt(r.node);return s?s[o]:void 0},set(r,o,i,s){return typeof o=="symbol"||o in r?(Reflect.set(r,o,i,s),!0):(r.set({[o]:i}),!0)}})};uu(hr.prototype);var Ev=n=>{let e=n.raw,t=typeof e.width=="number"?e.width:n.dims.x,r=typeof e.height=="number"?e.height:n.dims.y,o=e.pathOffset;return{left:typeof e.left=="number"?e.left:0,top:typeof e.top=="number"?e.top:0,width:t,height:r,pathOffset:{x:typeof o?.x=="number"?o.x:t/2,y:typeof o?.y=="number"?o.y:r/2}}},Cv=(n,e)=>{let t=new hr(n,e);return n instanceof Nr&&(t._calcDimensions=()=>Ev(n)),new Proxy(t,{get(r,o,i){return typeof o=="symbol"?Reflect.get(r,o,i):o==="then"?void 0:o in r?Reflect.get(r,o,i):r.node.raw[o]},set(r,o,i,s){return typeof o=="symbol"||o in r?(Reflect.set(r,o,i,s),!0):(r.set({[o]:i}),!0)}})};var Mv=(n,e)=>{n.onWarpHistoryChange=(r,o)=>{e.setWarpUndoable(r),e.setWarpRedoable(o)};let t=()=>{let r=n.warpSession;e.setWarpUndoable(r?.undoable??!1),e.setWarpRedoable(r?.redoable??!1)};return{active:()=>!!n.warpSession,async enter(r){let o=r instanceof hr?r.node:r?.node;if(!o)return!1;let i=await n.enterWarpMode(o);return t(),i},undo(){let r=n.warpUndo();return t(),r},redo(){let r=n.warpRedo();return t(),r},async exit(r){let o=await n.exitWarpMode(r).then(i=>!!i?.committed);return t(),o}}};var db=new Set([L.ELLIPSE,L.CIRCLE]),Rv=new Set([L.TRIANGLE]),bu=new Set([L.POLYGON]),fb=new Set([L.POLYLINE]),nb=new Set([L.ARROW]),Pv=new Set([L.DIMENSION]),kv=new Set([L.GROUP,L.PUZZLE]),rb=new Set([...dt,L.GIF]),ob=new Set([L.TABLE]),mu=new Set(["multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]),Av=n=>{if(!(Number(n.warpStrength)||0))return null;let t=Ge(n);return t==="arch"||t==="waist"||t==="flag"?t:null},pu=n=>{let e=n.effects;return!!e&&typeof e=="object"&&!Array.isArray(e)},Nv=n=>typeof n.textBackgroundColor=="string"&&n.textBackgroundColor?!0:Array.isArray(n.texts)&&n.texts.length>0,Lv=new Set(["rect","Rect","fabricrect","ellipse","Ellipse","circle","Circle","polygon","Polygon","polyline","Polyline","Path","path"]),Iv=.222,K=(n,e,t)=>{let r=n[e];if(typeof r=="number")return Number.isFinite(r)?r:t;if(typeof r=="string"&&r.trim()!==""){let o=Number(r.trim());if(Number.isFinite(o))return o}return t},Ie=(n,e)=>{let t=n[e];return typeof t=="string"?t:void 0},N=n=>{let e=Math.round(n*1e4)/1e4;return Object.is(e,-0)?"0":String(e)},re=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),_v=/^(#[0-9a-fA-F]{3,8}|rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*(,\s*[\d.]+\s*)?\)|[a-zA-Z][a-zA-Z0-9_-]*)$/,sn=n=>_v.test(n.trim())?n.trim():null,On=n=>n==null||n===""||n==="transparent"||n==="rgba(0,0,0,0)"||n==="none",gu=n=>`matrix(${n.map(N).join(",")})`,Dv=(n,e)=>[1,0,0,1,n,e],ib=n=>n,sb=(n,e,t)=>Gn({...n,width:e,height:t}),on=n=>{let e=n.shadow;if(!e)return null;if(typeof e!="object"||Array.isArray(e))return;let t=e,r=typeof t.color=="string"?t.color:"rgb(0,0,0)";if(sn(r))return{color:r,blur:typeof t.blur=="number"&&Number.isFinite(t.blur)?t.blur:0,offsetX:typeof t.offsetX=="number"&&Number.isFinite(t.offsetX)?t.offsetX:0,offsetY:typeof t.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:0}},ab=(n,e)=>{let t=n.pathOffset,r=0,o=0;return t&&typeof t=="object"?(typeof t.x=="number"&&Number.isFinite(t.x)&&(r=t.x),typeof t.y=="number"&&Number.isFinite(t.y)&&(o=t.y)):e&&(r=e.x,o=e.y),r||o?Dv(-r,-o):null},Fv=n=>{let e=Fe(n);return e?{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}:null},Ov=n=>{if(!n.length)return null;let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)e>i.x&&(e=i.x),t>i.y&&(t=i.y),r<i.x&&(r=i.x),o<i.y&&(o=i.y);return{x:(e+r)/2,y:(t+o)/2}},Bv=n=>n.map(e=>e.length===1?e[0]:`${e[0]} ${e.slice(1).map(t=>N(Number(t))).join(" ")}`).join(" "),lb=(n,e,t)=>{let r=se(n);if($n.has(r)){let o=Math.min(K(n,"rx",0),e/2),i=Math.min(K(n,"ry",0),t/2),s=o>0||i>0?` rx="${N(o)}" ry="${N(i>0?i:o)}"`:"";return{open:`<rect x="${N(-e/2)}" y="${N(-t/2)}" width="${N(e)}" height="${N(t)}"${s}`,internalTransform:null}}if(db.has(r))return{open:`<ellipse cx="0" cy="0" rx="${N(e/2)}" ry="${N(t/2)}"`,internalTransform:null};if(Rv.has(r))return{open:`<polygon points="${N(-e/2)},${N(t/2)} 0,${N(-t/2)} ${N(e/2)},${N(t/2)}"`,internalTransform:null};if(r===L.PATH){let o=Ce(n.path);return o?{open:`<path d="${re(Bv(o))}"`,internalTransform:ab(n,Fv(o))}:null}if(bu.has(r)||fb.has(r)){let o=n.points;if(!Array.isArray(o)||o.length===0)return null;let i=[];for(let l of o){let u=l,c=typeof u.x=="number"?u.x:NaN,h=typeof u.y=="number"?u.y:NaN;Number.isFinite(c)&&Number.isFinite(h)&&i.push({x:c,y:h})}if(!i.length)return null;let s=i.map(l=>`${N(l.x)},${N(l.y)}`);return{open:`<${bu.has(r)?"polygon":"polyline"} points="${s.join(" ")}"`,internalTransform:ab(n,Ov(i))}}return ft.has(r)?{open:`<line x1="${N(K(n,"x1",0))}" y1="${N(K(n,"y1",0))}" x2="${N(K(n,"x2",0))}" y2="${N(K(n,"y2",0))}"`,internalTransform:null}:null},cb=(n,e,t)=>{let r=e&&n.internalTransform?j(e,n.internalTransform):e??n.internalTransform;return`${n.open}${r?` transform="${gu(r)}"`:""}${t}/>`},Wv=(n,e,t)=>{let r="";if(e!==null){r+=` fill="${re(e)}"`;let o=Ie(n,"fillRule");o&&(r+=` fill-rule="${re(o)}"`)}else r+=' fill="none"';if(t!==null){r+=` stroke="${re(t)}"`,r+=` stroke-width="${N(K(n,"strokeWidth",1))}"`;let o=n.strokeDashArray;if(Array.isArray(o)&&o.length>0){let l=o.map(u=>typeof u=="number"&&Number.isFinite(u)?N(u):null).filter(u=>u!==null);l.length&&(r+=` stroke-dasharray="${l.join(",")}"`)}let i=Ie(n,"strokeLineCap");i&&(r+=` stroke-linecap="${re(i)}"`);let s=Ie(n,"strokeLineJoin");s&&(r+=` stroke-linejoin="${re(s)}"`);let a=n.strokeMiterLimit;typeof a=="number"&&Number.isFinite(a)&&(r+=` stroke-miterlimit="${N(a)}"`),n.strokeUniform===!0&&(r+=' vector-effect="non-scaling-stroke"'),Ie(n,"paintFirst")==="stroke"&&(r+=' paint-order="stroke"')}return r},Hv=n=>!On(n.stroke)&&K(n,"strokeWidth",1)>0,ub=n=>{let e=new Map;return(t,r)=>{let o=/([\d.]+)px\s+([\s\S]+)$/.exec(t);if(!o)return 0;let i=Number(o[1]),s=o[2].replace(/^["']+|["']+$/g,""),a=`${s}|${i}|${r}`,l=e.get(a);if(l!==void 0)return l;let u=n.getFont(s)??n.getSubsetFont?.(s,r[0]??"")??null,c=u&&typeof u.getAdvanceWidth=="function"?u.getAdvanceWidth(r,i):0;return e.set(a,c),c}},Gv=(n,e)=>{let t=0;for(let r of n)t+=r.charCodeAt(0)>255?1:.55;return t*e},mb=n=>{let e=n.textLines,t=n.charBounds,r=n.lineHeights;if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(r)||e.length===0||t.length!==e.length||r.length!==e.length)return null;for(let o=0;o<e.length;o++)if(typeof e[o]!="string"||!Array.isArray(t[o])||typeof r[o]!="number"||!Number.isFinite(r[o]))return null;return{textLines:e,charBounds:t,lineHeights:r}},pb=n=>{let e=n.map(o=>Nt(o).length),t=[],r=0;for(let o of e)t.push(r),r+=o;return{starts:t,counts:e}},Xv=(n,e)=>{let{starts:t,counts:r}=n;if(t.length===0||e<0)return null;let o=0,i=t.length-1;for(;o<i;){let a=o+i+1>>1;t[a]<=e?o=a:i=a-1}let s=e-t[o];return s<0||s>=r[o]?null:[o,s]},zv=(n,e)=>{let t=n.styles;if(!Array.isArray(t))return{};for(let r of t){if(!r||typeof r!="object")continue;let o=r,i=typeof o.start=="number"?o.start:-1,s=typeof o.end=="number"?o.end:-1;if(e>=i&&e<s&&o.style&&typeof o.style=="object")return o.style}return{}},hb=(n,e)=>{let t=zv(n,e),r=(o,i)=>t[o]!==void 0?t[o]:i;return{fontFamily:r("fontFamily",Ie(n,"fontFamily")??"Arial"),fontSize:r("fontSize",K(n,"fontSize",40)),fontWeight:r("fontWeight",String(Ie(n,"fontWeight")??"normal")),fontStyle:r("fontStyle",Ie(n,"fontStyle")??"normal"),fill:r("fill",n.fill),stroke:r("stroke",n.stroke),strokeWidth:r("strokeWidth",K(n,"strokeWidth",1)),underline:r("underline",n.underline===!0),linethrough:r("linethrough",n.linethrough===!0),overline:r("overline",n.overline===!0)}},Fn=n=>({fontFamily:n.fontFamily??"Times New Roman",fontSize:n.fontSize??40,fontWeight:n.fontWeight,fontStyle:n.fontStyle??void 0,lineHeight:n.lineHeight??1.16,charSpacing:n.charSpacing??0,textAlign:n.textAlign??fe.LEFT}),oi=(n,e,t)=>({fontFamily:e?.fontFamily??n.fontFamily,fontSize:e?.fontSize??n.fontSize,fontWeight:String(e?.fontWeight??n.fontWeight??"normal"),fontStyle:e?.fontStyle??n.fontStyle??"normal",fill:e?.fill??t.fill,stroke:t.stroke,strokeWidth:K(t,"strokeWidth",1),underline:t.underline===!0,linethrough:t.linethrough===!0,overline:t.overline===!0}),Yv=(n,e)=>{if(!Array.isArray(e)||e.length===0)return e&&typeof e=="object"?e:void 0;let t=pb(n.split(`
1095
- `)),r={};for(let o of e){if(!o||typeof o!="object")continue;let i=typeof o.start=="number"?o.start:-1,s=typeof o.end=="number"?o.end:-1;if(!(i<0||s<=i||!o.style||typeof o.style!="object"))for(let a=i;a<s;a++){let l=Xv(t,a);l&&((r[l[0]]??={})[l[1]]=o.style)}}return Object.keys(r).length>0?r:void 0},Uv=(n,e,t,r)=>{let o=n??fe.LEFT;return $t(o)?r?o===fe.JUSTIFY_CENTER?(e-t)/2:o===fe.JUSTIFY_RIGHT?e-t:0:0:o===fe.CENTER?(e-t)/2:o===fe.RIGHT?e-t:0},xu=n=>{let e=[];for(let t of n)switch(t.type){case"M":e.push(`M${N(t.x??0)} ${N(t.y??0)}`);break;case"L":e.push(`L${N(t.x??0)} ${N(t.y??0)}`);break;case"Q":e.push(`Q${N(t.x1??0)} ${N(t.y1??0)} ${N(t.x??0)} ${N(t.y??0)}`);break;case"C":e.push(`C${N(t.x1??0)} ${N(t.y1??0)} ${N(t.x2??0)} ${N(t.y2??0)} ${N(t.x??0)} ${N(t.y??0)}`);break;case"Z":e.push("Z");break;default:break}return e.join("")},bb=(n,e,t,r,o={})=>{let i=-1;for(let f=0;f<e.textLines.length;f++)e.textLines[f].length>0&&(i=f);let s=K(n,"lineHeight",1.16)||1.16,a=Ie(n,"textAlign"),l=-t/2,u=-r/2,c=[],h=pb(e.textLines),d=0;for(let f=0;f<e.textLines.length;f++){let m=e.textLines[f],p=Nt(m),b=e.charBounds[f],g=e.lineHeights[f],x=g/s,S=u+d+x-g*Iv/s,w=0;for(let C of b)!C||typeof C.left!="number"||typeof C.kernedWidth!="number"||(w=Math.max(w,C.left+C.kernedWidth));let y=Uv(a,t,w,f>=i),v=o.lineLefts?.[f]??l+y,R=o.anchor==="boxLeft",P=v,T=0;for(let C=0;C<p.length;C++){let E=p[C],M=b[C];if(!M||typeof M.width!="number"||typeof M.kernedWidth!="number")continue;let k=h.starts[f]+C;if(R){c.push({char:E,x:v+(M.left||0),y:S,style:hb(n,k)});continue}T===0?(P+=M.kernedWidth-M.width,T=M.width):T+=M.width,c.push({char:E,x:P,y:S,style:hb(n,k)}),P+=T,T=0}d+=g}return c},$v=(n,e,t={})=>{if(!e)return null;let r=n,o=K(r,"width",NaN),i=K(r,"height",NaN);if(!Number.isFinite(o)||!Number.isFinite(i)||r.vertical===!0||typeof r.direction=="string"&&r.direction!=="ltr")return null;let s=mb(r);if(!s)return null;let a=[];for(let{char:l,x:u,y:c,style:h}of bb(r,s,o,i,t)){if(!l.trim())continue;let d=e.getFont(h.fontFamily)??e.getSubsetFont?.(h.fontFamily,l)??null;if(!d)return null;let f=xu(d.getPath(l,u,c,h.fontSize).commands);a.push(f.endsWith("Z")?f:`${f} Z`)}return a.length>0?{path:a.join(" ")}:null},Wa=class{options;defs=[];idSeq=0;skipped={};constructor(e){this.options=e}exportPage(e){this.defs=[],this.idSeq=0,this.skipped={};let t=[];for(let a of e.objects){if(!a||typeof a!="object"||typeof a.type!="string")continue;let l=this.emitNode(a);l!==null&&l&&t.push(l)}let r=e.background&&!On(e.background)?sn(e.background):null,o=r?`<rect x="${N(e.viewBox.x)}" y="${N(e.viewBox.y)}" width="${N(e.viewBox.width)}" height="${N(e.viewBox.height)}" fill="${re(r)}"/>`:"",i=this.defs.length?`<defs>${this.defs.join("")}</defs>`:"";return{svg:`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${N(e.width)}px" height="${N(e.height)}px" viewBox="${N(e.viewBox.x)} ${N(e.viewBox.y)} ${N(e.viewBox.width)} ${N(e.viewBox.height)}" data-engine-svg="1">`+o+i+t.join("")+"</svg>",skippedTypes:this.skipped}}skip(e){this.skipped[e]=(this.skipped[e]??0)+1}nextId(e){return this.idSeq+=1,`${e}${this.idSeq}`}emitGradientDef(e,t,r){let o=this.nextId("esvg-g"),i=fi(e,t,r),s=` gradientTransform="matrix(${N(i[0])},${N(i[1])},${N(i[2])},${N(i[3])},${N(i[4])},${N(i[5])})"`,a=e.stops.map(l=>{let[u,c,h,d]=l.color,f=`rgb(${Math.round(u*255)},${Math.round(c*255)},${Math.round(h*255)})`;return`<stop offset="${N(l.offset)}" stop-color="${f}"${d<1?` stop-opacity="${N(d)}"`:""}/>`}).join("");return e.kind==="linear"?this.defs.push(`<linearGradient id="${o}" gradientUnits="userSpaceOnUse" x1="${N(e.x1)}" y1="${N(e.y1)}" x2="${N(e.x2)}" y2="${N(e.y2)}"${s}>${a}</linearGradient>`):this.defs.push(`<radialGradient id="${o}" gradientUnits="userSpaceOnUse" cx="${N(e.x2)}" cy="${N(e.y2)}" r="${N(e.r2)}" fx="${N(e.x1)}" fy="${N(e.y1)}"${e.r1>0?` fr="${N(e.r1)}"`:""}${s}>${a}</radialGradient>`),`url(#${o})`}resolvePaint(e,t,r){if(On(e))return null;if(typeof e=="string")return sn(e)??void 0;if(!e||typeof e!="object"||Array.isArray(e))return;let o=Yn(e);if(o)return this.emitGradientDef(o,t,r);let i=pr(e);if(i)return this.emitPatternDef(i,t,r)}emitPatternDef(e,t,r){let o=this.options.naturalSizes?.get(e.src);if(!o||o.width<=0||o.height<=0)return;let i=this.nextId("esvg-pt"),s=bi(e,t,r);return this.defs.push(`<pattern id="${i}" patternUnits="userSpaceOnUse" width="${N(o.width)}" height="${N(o.height)}" patternTransform="${gu(s)}"><image href="${re(e.src)}" xlink:href="${re(e.src)}" x="0" y="0" width="${N(o.width)}" height="${N(o.height)}"/></pattern>`),`url(#${i})`}emitShadowFilter(e){let t=this.nextId("esvg-s");return this.defs.push(`<filter id="${t}" x="-50%" y="-50%" width="200%" height="200%"><feDropShadow dx="${N(e.offsetX)}" dy="${N(e.offsetY)}" stdDeviation="${N(e.blur/2)}" flood-color="${re(e.color)}"/></filter>`),t}emitClipPath(e,t){let r=e.clipPath;if(!r||typeof r!="object"||Array.isArray(r))return null;let o=r;if(typeof o.type!="string"||!Lv.has(o.type)||o.inverted===!0)return null;let i=K(o,"width",0),s=K(o,"height",0),a=lb(o,i,s);if(!a)return null;let l=sb(o,i,s),u=o.absolutePositioned===!0?j(ve(t),l):l,c=this.nextId("esvg-c");return this.defs.push(`<clipPath id="${c}">${cb(a,u,"")}</clipPath>`),` clip-path="url(#${c})"`}emitBakedTextImage(e,t){let r=on(e);if(r===void 0)return this.skip("shadow-unsupported"),null;let o=-t.width/2+(t.offsetX??0),i=-t.height/2+(t.offsetY??0),s=`<image href="${re(t.dataUrl)}" xlink:href="${re(t.dataUrl)}" x="${N(o)}" y="${N(i)}" width="${N(t.width)}" height="${N(t.height)}"/>`;r&&(s=`<g filter="url(#${this.emitShadowFilter(r)})">${s}</g>`);let a=K(e,"textScaleX",1)||1,l=K(e,"textScaleY",1)||1;return(Math.abs(a-1)>1e-9||Math.abs(l-1)>1e-9)&&(s=`<g transform="scale(${N(a)},${N(l)})">${s}</g>`),s}emitText(e){if(Xe(e))return this.emitArcText(e);if(e.vertical===!0)return this.emitVerticalText(e);let t=Av(e);if(t)return this.emitWarpedText(e,t);if(Zn(e)){let m=this.options.bakeTextBitmap?.(e,"psd")??null;if(m)return this.emitBakedTextImage(e,m);this.skip("text-psdwarp-bitmap-fallback")}let r=K(e,"width",NaN),o=K(e,"height",NaN);if(!Number.isFinite(r)||!Number.isFinite(o)){if(Number.isFinite(r)&&!Number.isFinite(o)){let m=this.engineLayoutOf(e,!1);if(m)return this.emitTextFromEngineLayout(e,m)}return this.skip("text-dims-missing"),null}if(typeof e.direction=="string"&&e.direction!=="ltr")return this.skip("text-vertical-or-rtl"),null;let i=this.pathBackgroundMarkup(e);if(pu(e)){let m=this.options.bakeTextBitmap?.(e,"plain")??null;if(m)return i+this.emitBakedTextImage(e,m)}if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("text-effects"),null;if(Nv(e)){let m=this.engineLayoutOf(e,!1);if(m)return this.emitTextFromEngineLayout(e,m)}let s=mb(e);if(!s){let m=Ie(e,"text");if(!m||!Array.from(m).some(b=>b!==`
1096
- `))return'<text xml:space="preserve"></text>';let p=this.engineLayoutOf(e,!1);return p?this.emitTextFromEngineLayout(e,p):(this.skip("text-layout-missing"),null)}let a=on(e);if(a===void 0)return this.skip("shadow-unsupported"),null;let l=K(e,"textScaleX",1)||1,u=K(e,"textScaleY",1)||1,c=Math.abs(l-1)>1e-9||Math.abs(u-1)>1e-9,h=bb(e,s,r,o),d=this.emitAnchorGlyphs(h,r,o);if(d===null)return null;let f=d;return a&&(f=`<g filter="url(#${this.emitShadowFilter(a)})">${f}</g>`),c&&(f=`<g transform="scale(${N(l)},${N(u)})">${f}</g>`),this.pathBackgroundMarkup(e)+f}emitAnchorGlyphs(e,t,r){let o=[],i=[],s=[];for(let{char:l,x:u,y:c,rotation:h,centerX:d,scaleY:f,style:m}of e){let p=h!==void 0||d===!0||f!==void 0,b=h!==void 0?h*180/Math.PI:0;if(this.options.textMode==="paths"){if(l.trim()){let g=this.options.fonts?.getFont(m.fontFamily)??this.options.fonts?.getSubsetFont?.(m.fontFamily,l)??null;if(!g)return this.skip(`text-font-missing:${m.fontFamily}`),null;let x=this.resolvePaint(m.fill,t,r);if(x===void 0)return this.skip("text-fill-unsupported"),null;let S=x!==null?` fill="${re(x)}"`:' fill="none"';if(typeof m.stroke=="string"&&!On(m.stroke)&&m.strokeWidth>0&&(S+=` stroke="${re(m.stroke)}" stroke-width="${N(m.strokeWidth)}"`),p){let w=d?-((g.getAdvanceWidth?.(l,m.fontSize)??0)/2):0,y=xu(g.getPath(l,w,0,m.fontSize).commands),v=`translate(${N(u)},${N(c)})`;h!==void 0&&(v+=` rotate(${N(b)})`),f!==void 0&&(v+=` scale(1,${N(f)})`),o.push(`<g transform="${v}"><path d="${y}"${S}/></g>`)}else{let w=xu(g.getPath(l,u,c,m.fontSize).commands);o.push(`<path d="${w}"${S}/>`)}}}else{let g=this.resolvePaint(m.fill,t,r);if(g===void 0)return this.skip("text-fill-unsupported"),null;if(p){let x=` transform="translate(${N(u)},${N(c)})${h!==void 0?` rotate(${N(b)})`:""}${f!==void 0?` scale(1,${N(f)})`:""}"`;d&&(x+=' text-anchor="middle"'),x+=` font-family="${re(m.fontFamily)}"`,x+=` font-size="${N(m.fontSize)}"`,m.fontWeight!=="normal"&&(x+=` font-weight="${re(m.fontWeight)}"`),m.fontStyle!=="normal"&&(x+=` font-style="${re(m.fontStyle)}"`),x+=g!==null?` fill="${re(g)}"`:' fill="none"',typeof m.stroke=="string"&&!On(m.stroke)&&m.strokeWidth>0&&(x+=` stroke="${re(m.stroke)}" stroke-width="${N(m.strokeWidth)}"`),s.push(`<text xml:space="preserve"${x}>${re(l)}</text>`)}else{let x=` x="${N(u)}" y="${N(c)}"`;x+=` font-family="${re(m.fontFamily)}"`,x+=` font-size="${N(m.fontSize)}"`,m.fontWeight!=="normal"&&(x+=` font-weight="${re(m.fontWeight)}"`),m.fontStyle!=="normal"&&(x+=` font-style="${re(m.fontStyle)}"`),x+=g!==null?` fill="${re(g)}"`:' fill="none"',typeof m.stroke=="string"&&!On(m.stroke)&&m.strokeWidth>0&&(x+=` stroke="${re(m.stroke)}" stroke-width="${N(m.strokeWidth)}"`);let S=[m.underline?"underline":"",m.overline?"overline":"",m.linethrough?"line-through":""].filter(Boolean);S.length&&(x+=` text-decoration="${S.join(" ")}"`),i.push(`<tspan${x}>${re(l)}</tspan>`)}}}if(this.options.textMode==="paths")return o.join("");let a=i.length>0?`<text xml:space="preserve">${i.join("")}</text>`:"";return s.length>0?s.join("")+a:a}emitArcText(e){if(pu(e)){let a=this.options.bakeTextBitmap?.(e,Xe(e)??"arc")??null;if(a)return this.emitBakedTextImage(e,a)}if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("text-effects"),null;let t=this.arcLayoutOf(e);if(!t)return this.skip(`text-font-missing:${Ie(e,"fontFamily")??""}`),null;let r=on(e);if(r===void 0)return this.skip("shadow-unsupported"),null;let o=Fn(e),i=[];for(let a of t.arc.chars)i.push({char:a.char,x:a.x-t.arc.contentOffsetX,y:a.y-t.arc.contentOffsetY,rotation:a.rotation,centerX:!0,style:oi(o,t.layout.lines[a.line]?.charStyles?.[a.index],e)});let s=this.emitAnchorGlyphs(i,K(e,"width",0)||t.arc.width,t.arc.height);return s===null?null:r?`<g filter="url(#${this.emitShadowFilter(r)})">${s}</g>`:s}emitVerticalText(e){if(pu(e)){let b=this.options.bakeTextBitmap?.(e,"vertical")??null;if(b)return this.emitBakedTextImage(e,b)}if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("text-effects"),null;let t=this.engineLayoutOf(e,!0);if(!t)return this.skip(`text-font-missing:${Ie(e,"fontFamily")??""}`),null;let r=on(e);if(r===void 0)return this.skip("shadow-unsupported"),null;let o=Fn(e),i=o.charSpacing?o.fontSize*o.charSpacing/1e3:0,s=Number(e.textOffsetY)||0,a=Math.max(t.height,K(e,"height",0)),l=[],u=0;for(let b of t.lines){let g=-t.width/2+b.leftOffset,x=-a/2+b.baseline,S=0;for(let w=0;w<b.graphemes.length;w++){let y=b.graphemes[w],v=b.charStyles[w],R=v?.fontSize??o.fontSize,P=wt(s,R,u+w),T=b.boxes[w],C=qn(y);if(C==="latin"||C==="bracket"){let E=g+S+(C==="latin"?T.kernedWidth-T.width:0);l.push({char:y,x:E,y:x+P,style:oi(o,v,e)})}else{let E=g+S+un(R),M=x+P+yr(C,T,R);l.push({char:y,x:E,y:M,rotation:-Math.PI/2,style:oi(o,v,e)})}S+=Kn(y,T,i)}u+=b.graphemes.length}let c=this.emitAnchorGlyphs(l,t.width,a);if(c===null)return null;let h=this.emitTextDecorations(e,t,a),d=K(e,"textScaleX",1)||1,f=K(e,"textScaleY",1)||1,m=c;r&&(m=`<g filter="url(#${this.emitShadowFilter(r)})">${m}</g>`);let p=h+m;return(Math.abs(d-1)>1e-9||Math.abs(f-1)>1e-9)&&(p=`<g transform="scale(${N(d)},${N(f)})">${p}</g>`),p}emitWarpedText(e,t){let r=this.options.bakeTextBitmap?.(e,t)??null;if(r)return this.emitBakedTextImage(e,r);if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("text-effects"),null;let o=this.engineLayoutOf(e,!1);if(!o)return this.skip(`text-font-missing:${Ie(e,"fontFamily")??""}`),null;let i=on(e);if(i===void 0)return this.skip("shadow-unsupported"),null;let s=K(e,"fontSize",40)||40,a=Math.max(-1,Math.min(1,K(e,"warpStrength",0)||0)),l=K(e,"width",0),u=K(e,"height",0),c=Math.max(o.height,u),h=Math.max(o.width,l,s),d=t==="flag"?Math.abs(a)*(u||s)*.3:0,f=h/2,m=c/2,p=Fn(e),b=[];for(let y of o.lines){let v=-o.width/2+y.leftOffset,R=-c/2+y.baseline;for(let P=0;P<y.graphemes.length;P++){let T=y.boxes[P],C=oi(p,y.charStyles[P],e),E=v+T.left,M=E+T.width/2,k=f>0?M/f:0;if(t==="flag"){let A=Math.sin(k*Math.PI)*d*a;b.push({char:y.graphemes[P],x:E,y:R+A,style:C})}else if(t==="arch"){let A=Math.max(-1,Math.min(1,k)),O=Math.sqrt(Math.max(0,1-A*A)),F=O*O*(3-2*O),W=a>0?Math.pow(F,2.5):F,z=Math.min(1+Math.max(0,a),Math.max(.05,1+a*W));b.push({char:y.graphemes[P],x:E,y:z*R+m*(1-z),scaleY:z,style:C})}else{let A=Math.min(1+Math.abs(a),Math.max(.4,1+a*(k*k-.5)));b.push({char:y.graphemes[P],x:E,y:A*R,scaleY:A,style:C})}}}let g=this.emitAnchorGlyphs(b,h,c);if(g===null)return null;let x=K(e,"textScaleX",1)||1,S=K(e,"textScaleY",1)||1,w=g;return i&&(w=`<g filter="url(#${this.emitShadowFilter(i)})">${w}</g>`),(Math.abs(x-1)>1e-9||Math.abs(S-1)>1e-9)&&(w=`<g transform="scale(${N(x)},${N(S)})">${w}</g>`),w}emitMask(e){let t=Ie(e,"src");if(!t)return this.skip("image-src-missing"),null;let r=K(e,"width",0),o=K(e,"height",0);if(!(r>0)||!(o>0))return this.skip("image-dims-missing"),null;let i=e.clipImage,s=i&&typeof i=="object"?i:null,a=s?Ie(s,"src"):void 0;if(!s||!a){let v=on(e);if(v===void 0)return this.skip("shadow-unsupported"),null;let R=`<image href="${re(t)}" xlink:href="${re(t)}" x="${N(-r/2)}" y="${N(-o/2)}" width="${N(r)}" height="${N(o)}"/>`;return v&&(R=`<g filter="url(#${this.emitShadowFilter(v)})">${R}</g>`),R}let l=this.options.naturalSizes?.get(a);if(!l||l.width<=0||l.height<=0)return this.skip("image-natural-missing"),null;let u=l.width,c=l.height,h=this.nextId("esvg-mk");this.defs.push(`<mask id="${h}" maskUnits="userSpaceOnUse" mask-type="alpha" x="${N(-r/2)}" y="${N(-o/2)}" width="${N(r)}" height="${N(o)}"><image href="${re(t)}" xlink:href="${re(t)}" x="${N(-r/2)}" y="${N(-o/2)}" width="${N(r)}" height="${N(o)}"/></mask>`);let d=`<g transform="translate(${N(-r/2)},${N(-o/2)})" mask="url(#${h})"`,f=Math.max(0,Math.min(K(e,"cornerRadius",0),Math.min(r,o)/2));if(f>0){let v=this.nextId("esvg-mc");this.defs.push(`<clipPath id="${v}"><path d="M ${N(f)} 0 L ${N(r-f)} 0 Q ${N(r)} 0 ${N(r)} ${N(f)} L ${N(r)} ${N(o-f)} Q ${N(r)} ${N(o)} ${N(r-f)} ${N(o)} L ${N(f)} ${N(o)} Q 0 ${N(o)} 0 ${N(o-f)} L 0 ${N(f)} Q 0 0 ${N(f)} 0 Z"/></clipPath>`),d+=` clip-path="url(#${v})"`}d+=">";let m=K(s,"angle",0),p=K(s,"scaleX",1)||1,b=K(s,"scaleY",1)||1,g=s.flipX===!0?-1:1,x=s.flipY===!0?-1:1,S=K(e,"clipX",0),w=K(e,"clipY",0),y=`translate(${N(r/2)},${N(o/2)}) rotate(${N(m)}) scale(${N(p*g)},${N(b*x)}) translate(${N(S/(p||1))},${N(w/(b||1))}) translate(${N(-u/2)},${N(-c/2)})`;return d+`<g transform="${y}"><image href="${re(a)}" xlink:href="${re(a)}" x="0" y="0" width="${N(u)}" height="${N(c)}"/></g></g>`}emitTable(e){let t=this.tableLayoutOf(e);if(!t)return this.skip(`text-font-missing:${typeof e.fontFamily=="string"?e.fontFamily:""}`),null;let r=[];for(let o of t.children){if(!o||typeof o!="object"||typeof o.type!="string")continue;let i=this.emitNode(o);if(i===null)return null;i&&r.push(i)}return r.join("")}pathBackgroundMarkup(e,t){let r=co(e);if(!r||!r.fill)return"";let o=t??this.engineLayoutOf(e,!1);if(!o)return"";let i=o.width,s=Math.max(o.height,K(e,"height",0));if(!(i>0)||!(s>0))return"";let a=Ce(r.path);if(!a)return"";let l=Fe(a);if(!l)return"";let u=l.right-l.left,c=l.bottom-l.top;if(!(u>0)||!(c>0))return"";let h=i/r.width,d=s/r.height,f=(l.left+l.right)/2,m=(l.top+l.bottom)/2,[p,b,g,x]=ee(r.fill),S=`rgba(${Math.round(p*255)},${Math.round(b*255)},${Math.round(g*255)},${N(x)})`;return`<path d="${re(r.path)}" transform="matrix(${N(h)} 0 0 ${N(d)} ${N(-f*h)} ${N(-m*d)})" fill="${S}"/>`}emitTextDecorations(e,t,r){let o=[],i=-r/2,s=typeof e.textBackgroundColor=="string"?e.textBackgroundColor:"";if(s||t.lines.some(a=>a.charStyles.some(l=>l?.textBackgroundColor)))for(let a of t.lines){let l=-t.width/2+a.leftOffset,u=i+a.top,c=p=>a.charStyles[p]?.textBackgroundColor??s,h=0,d=0,f=c(0),m=()=>{if(!f||d<=0)return;let p=sn(f);p&&o.push(`<rect x="${N(l+a.boxes[h].left)}" y="${N(u)}" width="${N(d)}" height="${N(a.implHeight)}" fill="${re(p)}"/>`)};for(let p=0;p<a.graphemes.length;p++){let b=c(p);b!==f?(m(),h=p,d=a.boxes[p].width,f=b):d+=a.boxes[p].kernedWidth}m()}if(Array.isArray(e.texts)&&e.texts.length>0&&e.vertical!==!0){let a=Jn(e.text??"",t,e.texts,i,Fn(e).fontSize);if(a)for(let l of a.ops){let u=l.isFill?`<path d="${re(l.d)}" fill="${re(sn(l.fill)??l.fill)}"/>`:`<path d="${re(l.d)}" fill="none" stroke="${re(sn(l.stroke)??l.stroke)}" stroke-width="${N(l.strokeWidth)}"/>`;o.push(`<g transform="translate(${N(l.translateX)},${N(l.translateY)}) scale(${N(l.scaleX)},${N(l.scaleY)})">${u}</g>`)}}return o.join("")}emitTextFromEngineLayout(e,t){let r=on(e);if(r===void 0)return this.skip("shadow-unsupported"),null;let o=Fn(e),i=Math.max(t.height,K(e,"height",0)),s=[];for(let f of t.lines){let m=-t.width/2+f.leftOffset,p=-i/2+f.baseline;for(let b=0;b<f.graphemes.length;b++)s.push({char:f.graphemes[b],x:m+f.boxes[b].left,y:p,style:oi(o,f.charStyles[b],e)})}let a=this.emitAnchorGlyphs(s,t.width,i);if(a===null)return null;let l=K(e,"textScaleX",1)||1,u=K(e,"textScaleY",1)||1,c=this.emitTextDecorations(e,t,i),h=a;r&&(h=`<g filter="url(#${this.emitShadowFilter(r)})">${h}</g>`);let d=c+h;return(Math.abs(l-1)>1e-9||Math.abs(u-1)>1e-9)&&(d=`<g transform="scale(${N(l)},${N(u)})">${d}</g>`),this.pathBackgroundMarkup(e,t)+d}tableCache=new Map;tableLayoutOf(e){let t=this.tableCache.get(e);if(t!==void 0)return t;if(this.layoutMeasure===void 0&&(this.layoutMeasure=this.options.measure??(this.options.fonts?ub(this.options.fonts):null)),!this.layoutMeasure)return null;let r;try{r=Ro(e,this.layoutMeasure)}catch{r=null}return this.tableCache.set(e,r),r}arcCache=new Map;layoutMeasure;engineLayoutOf(e,t){if(this.layoutMeasure===void 0&&(this.layoutMeasure=this.options.measure??(this.options.fonts?ub(this.options.fonts):null)),!this.layoutMeasure)return null;if(!this.options.measure){let i=Fn(e).fontFamily;if(!this.options.fonts?.getFont(i))return null}let r=e.text??"",o=se(e)===L.TEXTBOX&&Ge(e)===null;return jt(r,Fn(e),{measure:this.layoutMeasure,boxWidth:o?e.width??0:null,styles:Yv(r,e.styles),splitByGrapheme:e.splitByGrapheme===!0,vertical:t,paragraph:Xe(e)?void 0:e.paragraph})}arcLayoutOf(e){let t=this.arcCache.get(e);if(t!==void 0)return t;let r=this.engineLayoutOf(e,!1),o=r?{layout:r,arc:Et(r,e,Fn(e).lineHeight??1.16)}:null;return this.arcCache.set(e,o),o}emitImage(e){let t=Ie(e,"src");if(!t)return this.skip("image-src-missing"),null;if(Array.isArray(e.filters)&&e.filters.length>0)return this.skip("image-filters"),null;if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("image-effects"),null;let r=Ie(e,"globalCompositeOperation");if(r&&r!=="source-over"&&!mu.has(r))return this.skip("image-gco"),null;let o=ts(ib(e));if(o){let h=this.options.naturalSizes?.get(t);if(!h)return this.skip("image-natural-missing"),null;let d=o.sw,f=o.sh;if(d<=0||f<=0)return this.skip("image-crop-empty"),null;let m=d/o.sw,p=f/o.sh,b=-d/2-o.sx*m,g=-f/2-o.sy*p,x=this.nextId("esvg-ic"),S=K(e,"rx",0),w=K(e,"ry",0),y=S>0||w>0?` rx="${N(S)}" ry="${N(w)}"`:"";return this.defs.push(`<clipPath id="${x}"><rect x="${N(-d/2)}" y="${N(-f/2)}" width="${N(d)}" height="${N(f)}"${y}/></clipPath>`),`<g clip-path="url(#${x})"><image xlink:href="${re(t)}" x="${N(b)}" y="${N(g)}" width="${N(h.width*m)}" height="${N(h.height*p)}"/></g>`}let i=K(e,"width",NaN),s=K(e,"height",NaN);if(!Number.isFinite(i)||!Number.isFinite(s))return this.skip("image-dims-missing"),null;let a=on(e);if(a===void 0)return this.skip("shadow-unsupported"),null;let l=`<image xlink:href="${re(t)}" x="${N(-i/2)}" y="${N(-s/2)}" width="${N(i)}" height="${N(s)}"/>`,u=K(e,"rx",0),c=K(e,"ry",0);if(u>0||c>0){let h=this.nextId("esvg-ir");this.defs.push(`<clipPath id="${h}"><rect x="${N(-i/2)}" y="${N(-s/2)}" width="${N(i)}" height="${N(s)}" rx="${N(u)}" ry="${N(c)}"/></clipPath>`),l=`<g clip-path="url(#${h})">${l}</g>`}return a&&(l=`<g filter="url(#${this.emitShadowFilter(a)})">${l}</g>`),l}emitObjectContent(e,t,r,o){let i=se(e);if(kv.has(i)){let d=e.objects;if(!Array.isArray(d))return this.skip("group-objects-missing"),null;let f=[];for(let m of d){if(!m||typeof m!="object"||typeof m.type!="string")continue;let p=this.emitNode(m);if(p===null)return null;p&&f.push(p)}return f.join("")}if(ob.has(i))return this.emitTable(e);if(ot.has(i))return this.emitMask(e);if(rb.has(i))return this.emitImage(e);if(i===L.TEXTIMAGE&&typeof e.renderSrc=="string"){let d=e.renderRect,f=typeof d?.w=="number"&&d.w>0?d.w:K(e,"width",NaN),m=typeof d?.h=="number"&&d.h>0?d.h:K(e,"height",NaN);if(!Number.isFinite(f)||!Number.isFinite(m)||f<=0||m<=0)return this.skip("textimage-dims-missing"),null;let p=-f/2+(typeof d?.x=="number"?d.x:0),b=-m/2+(typeof d?.y=="number"?d.y:0),g=Po(e),x=`<image xlink:href="${re(Ie(e,"renderSrc")??"")}" x="${N(p)}" y="${N(b)}" width="${N(f)}" height="${N(m)}"${g<1?` opacity="${N(g)}"`:""}/>`,S=typeof d?.angle=="number"&&Number.isFinite(d.angle)?d.angle:0;return S&&(x=`<g transform="rotate(${N(-S)})">${x}</g>`),x}if(an.has(i))return this.emitText(e);let s=Ie(e,"globalCompositeOperation");if(s&&s!=="source-over"&&!mu.has(s))return this.skip("shape-gco"),null;if(typeof e.strokeAlignment=="string"&&e.strokeAlignment!=="center"&&!On(e.stroke))return this.skip("shape-stroke-alignment"),null;if(nb.has(i)||Pv.has(i))return this.emitLineDecoration(e,nb.has(i));let a=lb(e,r,o);if(!a)return this.skip(`type:${String(e.type??"")}`),null;let l=this.resolvePaint(e.fill,r,o);if(l===void 0)return this.skip("fill-unsupported"),null;let u=null;if(Hv(e)){let d=this.resolvePaint(e.stroke,r,o);if(d===void 0)return this.skip("stroke-unsupported"),null;u=d}let c=on(e);if(c===void 0)return this.skip("shadow-unsupported"),null;let h=Wv(e,l,u)+(c?` filter="url(#${this.emitShadowFilter(c)})"`:"");return cb(a,null,h)}emitLineDecoration(e,t){let r=K(e,"x1",NaN),o=K(e,"y1",NaN),i=K(e,"x2",NaN),s=K(e,"y2",NaN);if(!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s))return this.skip(`dims-missing:${String(e.type??"")}`),null;let a=e.stroke,l=typeof a=="string"&&!On(a)?a:"#000000";if(!sn(l))return this.skip("stroke-unsupported"),null;let u=K(e,"strokeWidth",1),c=e.strokeDashArray,h=Array.isArray(c)&&c.length>0?` stroke-dasharray="${c.map(G=>typeof G=="number"&&Number.isFinite(G)?N(G):null).filter(G=>G!==null).join(",")}"`:"",d=i-r,f=s-o,m=Math.atan2(f,d),p=Math.cos(m),b=Math.sin(m);if(t){let G=e.arrowType==="start"||e.arrowType==="both"?e.arrowType:"end",$=G==="start"||G==="both",V=G==="end"||G==="both",H=Math.sqrt(u),Y=K(e,"arrowWidth",15)*H,X=K(e,"arrowHeight",22.5)*H,Z=r+p*($?X:0),B=o+b*($?X:0),q=i-p*(V?X:0),U=s-b*(V?X:0),oe=` stroke="${re(l)}" stroke-width="${N(u)}"${h}`,ne=[`<line x1="${N(Z)}" y1="${N(B)}" x2="${N(q)}" y2="${N(U)}"${oe} fill="none"/>`],de=(Pe,De,nt)=>{let ke=Math.cos(nt),Ee=Math.sin(nt),ue=Pe-X*ke+Y/2*Ee,xe=De-X*Ee-Y/2*ke,pe=Pe-X*ke-Y/2*Ee,Te=De-X*Ee+Y/2*ke;ne.push(`<path d="M ${N(Pe)} ${N(De)} L ${N(ue)} ${N(xe)} L ${N(pe)} ${N(Te)} Z" fill="${re(l)}"/>`)};return V&&de(i,s,m),$&&de(r,o,m+Math.PI),ne.join("")}let g=` stroke="${re(l)}" stroke-width="${N(u)}"${h}`,x=Ie(e,"strokeLineCap");x&&(g+=` stroke-linecap="${re(x)}"`);let S=Ie(e,"strokeLineJoin");S&&(g+=` stroke-linejoin="${re(S)}"`);let w=e.strokeMiterLimit;typeof w=="number"&&Number.isFinite(w)&&(g+=` stroke-miterlimit="${N(w)}"`);let y=[`<line x1="${N(r)}" y1="${N(o)}" x2="${N(i)}" y2="${N(s)}"${g} fill="none"/>`],v=(K(e,"textFontSize",50)||50)/2,R=-b,P=p,T=` stroke="${re(l)}" stroke-width="${N(u)}" stroke-linecap="round"`;for(let[G,$]of[[r,o],[i,s]])y.push(`<line x1="${N(G-R*v)}" y1="${N($-P*v)}" x2="${N(G+R*v)}" y2="${N($+P*v)}"${T} fill="none"/>`);let C=K(e,"textFontSize",50)||50,E=typeof e.text=="string"&&e.text.trim()?e.text:"50cm",M=K(e,"textPadding",4),k=Gv(E,C)+M*2,A=C+M*2,O=C+u/2+5,F=(r+i)/2+R*O,W=(o+s)/2+P*O,z=e.textFollowLine===!1?0:m*180/Math.PI,_=typeof e.textColor=="string"&&sn(e.textColor)?e.textColor:"#333333",D=typeof e.textBackgroundColor=="string"?e.textBackgroundColor:"#ffffff",I=sn(D);return y.push(`<g transform="translate(${N(F)},${N(W)}) rotate(${N(z)})">`+(D&&I?`<rect x="${N(-k/2)}" y="${N(-A/2)}" width="${N(k)}" height="${N(A)}" fill="${re(I)}"/>`:"")+`<text text-anchor="middle" dominant-baseline="central" font-family="Arial, sans-serif" font-size="${N(C)}" fill="${re(_)}">${re(E)}</text></g>`),y.join("")}emitNode(e){if(Ir.has(Ie(e,"id")??"")||e.excludeFromExport===!0||e.visible===!1)return"";let t=se(e),r=K(e,"width",NaN),o=K(e,"height",NaN);if(rb.has(t)){let h=ts(ib(e));if(h)r=h.sw,o=h.sh;else if(!Number.isFinite(r)||!Number.isFinite(o)){let d=this.options.naturalSizes?.get(Ie(e,"src")??"");r=d?.width??NaN,o=d?.height??NaN}}else if(ft.has(t)&&(!Number.isFinite(r)||!Number.isFinite(o)))r=Math.abs(K(e,"x2",0)-K(e,"x1",0)),o=Math.abs(K(e,"y2",0)-K(e,"y1",0));else if(db.has(t)&&(!Number.isFinite(r)||!Number.isFinite(o)))if(t===L.CIRCLE){let h=2*K(e,"radius",NaN);Number.isFinite(r)||(r=h),Number.isFinite(o)||(o=h)}else Number.isFinite(r)||(r=2*K(e,"rx",NaN)),Number.isFinite(o)||(o=2*K(e,"ry",NaN));else if((bu.has(t)||fb.has(t))&&(!Number.isFinite(r)||!Number.isFinite(o))){let h=e.points;if(Array.isArray(h)&&h.length>0){let d=1/0,f=1/0,m=-1/0,p=-1/0;for(let b of h){let g=typeof b?.x=="number"&&Number.isFinite(b.x)?b.x:NaN,x=typeof b?.y=="number"&&Number.isFinite(b.y)?b.y:NaN;!Number.isFinite(g)||!Number.isFinite(x)||(d>g&&(d=g),f>x&&(f=x),m<g&&(m=g),p<x&&(p=x))}Number.isFinite(d)&&Number.isFinite(f)&&(Number.isFinite(r)||(r=m-d),Number.isFinite(o)||(o=p-f))}}else if(an.has(t)&&!Number.isFinite(o))if(Array.isArray(e.lineHeights))o=e.lineHeights.reduce((h,d)=>h+(typeof d=="number"&&Number.isFinite(d)?d:0),0);else{let h=this.engineLayoutOf(e,!1);h&&(o=h.height)}if(Xe(e)){let h=this.arcLayoutOf(e);h&&(r=h.arc.width,o=h.arc.height)}if(ob.has(t)){let h=this.tableLayoutOf(e);h&&(r=h.width,o=h.height)}if(!Number.isFinite(r)||!Number.isFinite(o))return this.skip(`dims-missing:${String(e.type??"")}`),null;let i=sb(e,r,o),s=this.emitObjectContent(e,i,r,o);if(s===null)return null;if(s==="")return"";let a=`<g transform="${gu(i)}"`,l=Ie(e,"globalCompositeOperation");l&&l!=="source-over"&&mu.has(l)&&(a+=` style="mix-blend-mode:${re(l)}"`);let u=K(e,"opacity",1);u<1&&(a+=` opacity="${N(u)}"`);let c=this.emitClipPath(e,i);return c===null&&e.clipPath?(this.skip("clip-unsupported"),null):(c&&(a+=c),`${a}>${s}</g>`)}},jv=n=>new Wa({textMode:n.textMode,fonts:n.fonts,naturalSizes:n.naturalSizes,measure:n.measure,bakeTextBitmap:n.bakeTextBitmap}).exportPage(n);var gb=n=>n==="center"?0:n==="right"?.5:-.5,xb=n=>typeof n=="number"?n:0,Vv=(n,e={})=>{let t=1/0,r=1/0,o=-1/0,i=-1/0,s=[];for(let p of n){let b=Ct(p);if(!b)continue;s.push(b);let g=b.contentBoxCorners();for(let x of[g.tl,g.tr,g.br,g.bl])x.x<t&&(t=x.x),x.y<r&&(r=x.y),x.x>o&&(o=x.x),x.y>i&&(i=x.y)}let a=!s.length||!Number.isFinite(t),l=a?0:o-t,u=a?0:i-r,c=a?0:(t+o)/2,h=a?0:(r+i)/2,d=n.map(p=>({...p,left:xb(p.left)-c,top:xb(p.top)-h})),f=typeof e.left=="number"?e.left:c+l*gb(e.originX),m=typeof e.top=="number"?e.top:h+u*gb(e.originY);return{...e,type:e.type??"Group",width:l,height:u,left:f,top:m,objects:d}};var dr=n=>n==="center"?0:n==="right"?.5:-.5,qv=(n,e={})=>{let t=Ce(n),r=t?Fe(t):null,o=r?r.right-r.left:0,i=r?r.bottom-r.top:0,s={x:r?(r.left+r.right)/2:0,y:r?(r.top+r.bottom)/2:0},a=typeof e.strokeWidth=="number"?e.strokeWidth:1,l=typeof e.left=="number"?e.left:s.x+(o+a)*dr(e.originX),u=typeof e.top=="number"?e.top:s.y+(i+a)*dr(e.originY);return{...e,type:e.type??"Path",path:t??[],width:o,height:i,pathOffset:s,left:l,top:u}};var Kv=(n,e={})=>{let[t,r,o,i]=n,s=Math.abs(o-t),a=Math.abs(i-r),l=(t+o)/2,u=(r+i)/2,c=typeof e.strokeWidth=="number"?e.strokeWidth:1,h=typeof e.left=="number"?e.left:l+(s+c)*dr(e.originX),d=typeof e.top=="number"?e.top:u+(a+c)*dr(e.originY),f=t<=o?-1:1,m=r<=i?-1:1;return{...e,type:e.type??"Line",width:s,height:a,left:h,top:d,x1:f*s/2||0,y1:m*a/2||0,x2:-f*s/2||0,y2:-m*a/2||0}},Qv=(n,e={},t="Polygon")=>{let r=1/0,o=1/0,i=-1/0,s=-1/0;for(let m of n)m.x<r&&(r=m.x),m.y<o&&(o=m.y),m.x>i&&(i=m.x),m.y>s&&(s=m.y);let a=!Number.isFinite(r),l=a?0:i-r,u=a?0:s-o,c={x:a?0:(r+i)/2,y:a?0:(o+s)/2},h=typeof e.strokeWidth=="number"?e.strokeWidth:1,d=typeof e.left=="number"?e.left:c.x+(l+h)*dr(e.originX),f=typeof e.top=="number"?e.top:c.y+(u+h)*dr(e.originY);return{...e,type:e.type??t,points:n,width:l,height:u,pathOffset:c,left:d,top:f}};export{ie as AnimatedNode,ny as COMPAT_PROTOCOL_VERSION,Le as CompatHistoryActions,hr as CompatObject,nn as CompatPoint,L as ElementTypes,nu as EngineCanvas,Ao as EngineDocument,Hn as EventBus,xi as GIF_TYPES,J as GroupNode,dt as IMAGE_LIKE_TYPES,ft as LINE_TYPES,Lr as LineNode,ot as MASK_TYPES,ae as MaskNode,gi as PUZZLE_TYPES,Nr as PathNode,ru as Point,le as PuzzleNode,Un as SHAPE_TYPES,$n as SOLID_TYPES,_s as ScaleLimit,ct as SceneNode,yn as ShapeNode,Wa as SvgExporter,sg as TEXT_ALIGN_VALUES,an as TEXT_TYPES,te as TableNode,fe as TextAlignValues,ye as TextNode,yi as VIDEO_TYPES,Zn as activePsdTextWarp,_c as anchorStyleAt,xh as applyWarpDistortion,Xe as arcTextKind,Vv as assembleGroupRaw,ry as attachDocumentEventBridge,uu as attachTableFacade,Ml as bakeArcText,Zc as bakePsdWarpText,Bg as bakeTextEffects,Cl as bakeWarpedText,Xn as boundsFromACoors,Mo as buildAllSelection,ou as buildEngineShapePath,Kv as buildLineRaw,qv as buildPathRaw,Qv as buildPolyRaw,zl as buildScene,xn as buildSelectionRange,$v as buildTextGlyphPathData,pl as buildWarpSurfaceGridOverWindow,Sx as clearAlphaHitMask,At as composeMatrix,bo as compositeWarpEffects,Et as computeArcTextLayout,Rl as computePuzzleItems,Mv as createEngineWarpvasFacade,Ct as createNode,qc as decodeAnimatedImage,Ab as decomposeOwnMatrix,hu as deriveArcCharTransformations,Ni as evaluateWarpMesh,_a as fboPixelsToImageData,fu as findParentGroupOf,ml as generatePsdWarpMesh,gh as generateStyleWarpMesh,Fe as getBoundsOfPath,we as getCellData,fn as glyphStyleAt,gn as glyphStyleOf,dn as identityWarpMesh,$c as imageMaskDeclOf,xp as imageMaskOffset,To as insertTableColumn,wo as insertTableRow,ve as invert,bl as invertBilinearCell,jr as isAnimatedPng,YS as isAnimatedPngFile,US as isAnimatedPngUrl,jS as isAnimatedWebPFile,VS as isAnimatedWebPUrl,wu as isCanvasPerfEnabled,Nb as isEngineRasterExportEnabled,Lb as isEngineSvgExportEnabled,fl as isGeneratableWarpStyle,Wr as isGroupWidthHandleNode,$t as isJustifyFamilyAlign,sl as isJustifyVariantAlign,qa as isSnapGuideEnabled,ro as isStretchAlign,Kt as isTextBitmapState,jt as layoutTextbox,hl as lineDecorationRuns,Je as loadImageElement,Tu as markCanvasPerfCounter,yp as maskOutsideRects,gp as maskPixelsToAlpha,lt as masterPosition,So as mergeTableCells,j as multiply,Vi as normalizeSelectionAfterRemove,$a as objectACoors,Ut as objectCenter,ge as objectOriginFromCenter,Gn as objectOwnMatrix,ee as parseColor,Ce as parsePathData,Mt as parsePsdEffects,co as pathBackgroundSpecOf,Bt as pathEditKindOf,Jn as planTextHighlight,li as recordCanvasPerfDuration,it as rectCornerRadii,ss as refitGroupShells,_l as removeTableColumn,Il as removeTableRow,xv as renderPlacedSmartObjectLayer,po as renderTextRuns,Gi as renderVerticalRuns,Ar as rowColCoverage,Zr as sceneToClipMatrix,ze as selectionBounds,jv as serializePageToSvg,dy as setGroupWidth,xo as setTableColumnWidth,yo as setTableRowHeight,Po as textBitmapFillAlpha,Ge as textTransformKindOf,Q as transformPoint,ui as transformedDimensions,se as typeKeyOf,vo as unmergeTableCells,Vt as verticalGlyphOps,Cv as wrapCompatObject};
1094
+ `))l+=u.length;return a&&o===l&&o>0&&s!==void 0?(this.set({[e]:s}),this.removeStyle?.(e),!0):(o>0&&this.set({styles:t.styles}),!1)}removeStyle(e){let t=this.objectStyles();if(t){for(let r in t){let o=t[r];for(let i in o)delete o[i][e],Object.keys(o[i]).length===0&&delete o[i];Object.keys(o).length===0&&delete t[r]}this.set({styles:t})}}setSelectionStyles(e,t,r){if(!(this.node instanceof ye))return;let o=this.ctx.getNodeSelectionRange?.(this.node),i=t??o?.start??0,s=r??o?.end??0;if(s<=i)return;let a=this.stylesMap();for(let l=i;l<s;l++){let{line:u,char:c}=this.cursor2D(l);a[u]||(a[u]={});let d={...a[u][c]??{}};for(let f of Object.keys(e))e[f]!==void 0&&(d[f]=e[f]);a[u][c]=d}this.set({styles:this.stylesMap()})}getSelectionStyles(e,t){if(!(this.node instanceof ye))return[];let r=this.ctx.getNodeSelectionRange?.(this.node),o=e??r?.start??0,i=t??r?.end??o,s=[];for(let a=o;a<i;a++)s.push(this.getStyleAtPosition(a));return s}setFontFamily(e,t){this.set({fontFamily:e})}get fontFamily(){return String(this.node.raw.fontFamily??"")}get type(){return String(this.node.raw.type??"")}initDimensions(){}calcTextWidth(){return this.node instanceof ye?this.node.textLayout.lines.reduce((e,t)=>Math.max(e,t.width),0):0}refreshTextDimensions(){}replaceFontFamily(e,t){let r=this.node.raw,o=!1;if(r.fontFamily===e&&(this.set({fontFamily:t}),o=!0),r.styles){for(let i of Object.values(r.styles))if(i)for(let s of Object.values(i))s?.fontFamily===e&&(s.fontFamily=t,o=!0);o&&this.set({styles:r.styles})}return o}get rawTypeLower(){return se(this.node.raw)}get transformKind(){return Ge(this.node.raw)}get setRadius(){if(this.transformKind==="arc")return e=>this.set({curvature:e})}get setWarpStrength(){let e=this.transformKind;if(!(e!=="arch"&&e!=="waist"&&e!=="flag"))return t=>this.set({warpStrength:Math.max(-1,Math.min(1,t))})}get clearCache(){let e=this.transformKind;if(!(e!=="arch"&&e!=="waist"&&e!=="flag"))return()=>{this.ctx.invalidateNodeBakes?.(this.node),this.ctx.getCanvas?.()?.requestRenderAll?.()}}get setCircleParams(){if(this.transformKind==="circle")return e=>this.set(e)}get setTexts(){if(this.node instanceof ye)return e=>this.set({texts:e})}get texts(){if(!(this.node instanceof ye))return;let e=this.node.raw.texts;return Array.isArray(e)?e:[]}toObject(e){let t={...this.node.toObject()};if(this.isImageLikeNode){let r=this.sourceNaturalSize();t.width===void 0&&r.width>0&&(t.width=r.width),t.height===void 0&&r.height>0&&(t.height=r.height)}if(this.node instanceof ye){let r=this.node.textLayout,o=this.node.textStyle.lineHeight??1.16,i=du(r,this.node.raw,o);i&&(t.charTransformations=i),r.lines.length>0&&!wv(t)&&(t.textLines=r.lines.map(a=>a.graphemes.join("")),t.charBounds=r.lines.map(a=>{let l=a.boxes.map(u=>({left:u.left,width:u.width,kernedWidth:u.kernedWidth,height:u.height}));if(l.length>0){let u=l.reduce((c,h)=>c+(h.kernedWidth||0),0);l.push({left:u,width:0,kernedWidth:0,height:l[l.length-1].height})}return l}),t.lineHeights=r.lines.map(a=>a.implHeight*o));let s=this.node.raw;t.styles=this.stylesToPersistForm(t.styles,typeof s.text=="string"?s.text:"")}if(e?.length){let r=this.node.raw,o=t;for(let i of e)o[i]===void 0&&r[i]!==void 0&&(o[i]=r[i])}return t}get id(){return this.node.id}get canvas(){return this.ctx.getCanvas?.()}get group(){let e=this.ctx.getCanvas?.(),t=mu(e?.document,this.node);return t?this.ctx.wrapNode(t):void 0}get topGroup(){let e=this.ctx.getCanvas?.(),t,r=this.node;for(;;){let o=mu(e?.document,r);if(!o)break;t=o,r=o}return t?this.ctx.wrapNode(t):void 0}get parent(){return this.group}get applyMaskParams(){if(this.node instanceof le)return e=>{this.node.applyMaskParams(e),this.ctx.getCanvas?.()?.requestRenderAll?.()}}get updateGapParams(){if(this.node instanceof le)return e=>{this.node.updateGapParams(e),this.ctx.getCanvas?.()?.requestRenderAll?.()}}get updateLayout(){if(this.node instanceof le)return e=>{this.node.updateLayout(e),this.ctx.getCanvas?.()?.requestRenderAll?.()}}get visible(){return this.node.visible}set visible(e){this.set({visible:e})}get opacity(){let e=this.node.raw.opacity;return typeof e=="number"?e:1}set opacity(e){this.set({opacity:e})}get strokeWidth(){let e=this.node.raw.strokeWidth;return typeof e=="number"?e:1}set strokeWidth(e){this.set({strokeWidth:e})}_createCacheCanvas(){}_removeCacheCanvas(){}get isEditing(){return this.ctx.isEditingNode(this.node)}enterEditing(){return this.node.isTextType&&this.ctx.enterNodeEditing(this.node),this}exitEditing(){return this.ctx.exitEditing(),this}bringToFront(){this.ctx.bringToFront(this.node)}sendToBack(){this.ctx.sendToBack(this.node)}bringForward(){this.ctx.bringForward(this.node)}sendBackwards(){this.ctx.sendBackwards(this.node)}moveTo(e){this.ctx.moveNodeTo(this.node,e)}remove(){this.ctx.removeNode(this.node)}get changeControls(){if(Bt(this.node))return(e,t=!0)=>{this.ctx.changeNodeControls(this.node,e)}}get isEditingPath(){return this.ctx.isPathEditingNode(this.node)}get setAnchorPointType(){if(Bt(this.node)==="path")return(e,t)=>this.ctx.setNodeAnchorType(this.node,e,t)}get getActiveAnchorKey(){if(Bt(this.node))return()=>this.ctx.getNodePathEditInfo(this.node)?.activeAnchorKey}get getActiveAnchorIndex(){if(Bt(this.node))return()=>this.ctx.getNodePathEditInfo(this.node)?.activeAnchorIndex}get getAnchorPointStyleByIndex(){if(Bt(this.node)==="path")return e=>Dc(Ce(this.node.raw.path),e)}get highlightAnchor(){if(Bt(this.node))return e=>{this.ctx.highlightNodeAnchor(this.node,e)}}get resetAnchorStyles(){if(Bt(this.node))return()=>{this.ctx.resetNodeAnchorStyles(this.node)}}},zt=n=>{let e=n.raw;if(!ot.has(se(e)))return null;let t=e.clipImage;return!t||typeof t!="object"||typeof t.src!="string"?null:t},Tv=new Set(["_cacheCanvas","dirty","canvas"]),fu=class{constructor(e,t){this.node=e;this.ctx=t}node;ctx;set(e){let t=zt(this.node);if(!t)return this;let r={...t};for(let[o,i]of Object.entries(e))Tv.has(o)||(r[o]=i);return this.ctx.setNodeProps(this.node,{clipImage:r}),this}toObject(e){let t=zt(this.node);return t?{...t}:{}}setCoords(){}getSrc(){let e=zt(this.node);return e&&typeof e.originalSrc=="string"&&e.originalSrc?e.originalSrc:e&&typeof e.src=="string"?e.src:""}get replaceSrc(){if(zt(this.node))return async e=>(this.set({src:e,crossOrigin:"anonymous",originalSrc:e}),await this.ctx.reloadMaskClipImage?.(this.node),this)}getRelativeCenterPoint(){let e=zt(this.node),t=a=>typeof a=="number"?a:0,r=a=>typeof a=="number"?a:1,o=a=>a==="center"?.5:a==="right"||a==="bottom"?1:0,i=t(e?.width)*r(e?.scaleX),s=t(e?.height)*r(e?.scaleY);return new nn(t(e?.left)+(.5-o(e?.originX))*i,t(e?.top)+(.5-o(e?.originY))*s)}getOriginalElementWidth(){let e=this.node.clipImageEl;return e?.naturalWidth||e?.width||Number(zt(this.node)?.width)||0}getOriginalElementHeight(){let e=this.node.clipImageEl;return e?.naturalHeight||e?.height||Number(zt(this.node)?.height)||0}},mu=(n,e)=>{if(!n)return;let t=r=>{for(let o of r){if(!(o instanceof J))continue;if(o.children.some(s=>s===e))return o;let i=t(o.children);if(i)return i}};return t(n.nodes)},Ev=(n,e)=>{let t=new fu(n,e);return new Proxy(t,{get(r,o,i){if(typeof o=="symbol")return Reflect.get(r,o,i);if(o==="then")return;if(o in r)return Reflect.get(r,o,i);let s=zt(r.node);return s?s[o]:void 0},set(r,o,i,s){return typeof o=="symbol"||o in r?(Reflect.set(r,o,i,s),!0):(r.set({[o]:i}),!0)}})};hu(hr.prototype);var Cv=n=>{let e=n.raw,t=typeof e.width=="number"?e.width:n.dims.x,r=typeof e.height=="number"?e.height:n.dims.y,o=e.pathOffset;return{left:typeof e.left=="number"?e.left:0,top:typeof e.top=="number"?e.top:0,width:t,height:r,pathOffset:{x:typeof o?.x=="number"?o.x:t/2,y:typeof o?.y=="number"?o.y:r/2}}},Mv=(n,e)=>{let t=new hr(n,e);return n instanceof Nr&&(t._calcDimensions=()=>Cv(n)),new Proxy(t,{get(r,o,i){return typeof o=="symbol"?Reflect.get(r,o,i):o==="then"?void 0:o in r?Reflect.get(r,o,i):r.node.raw[o]},set(r,o,i,s){return typeof o=="symbol"||o in r?(Reflect.set(r,o,i,s),!0):(r.set({[o]:i}),!0)}})};var Rv=(n,e)=>{n.onWarpHistoryChange=(r,o)=>{e.setWarpUndoable(r),e.setWarpRedoable(o)};let t=()=>{let r=n.warpSession;e.setWarpUndoable(r?.undoable??!1),e.setWarpRedoable(r?.redoable??!1)};return{active:()=>!!n.warpSession,async enter(r){let o=r instanceof hr?r.node:r?.node;if(!o)return!1;let i=await n.enterWarpMode(o);return t(),i},undo(){let r=n.warpUndo();return t(),r},redo(){let r=n.warpRedo();return t(),r},async exit(r){let o=await n.exitWarpMode(r).then(i=>!!i?.committed);return t(),o}}};var fb=new Set([L.ELLIPSE,L.CIRCLE]),Pv=new Set([L.TRIANGLE]),gu=new Set([L.POLYGON]),mb=new Set([L.POLYLINE]),rb=new Set([L.ARROW]),kv=new Set([L.DIMENSION]),Av=new Set([L.GROUP,L.PUZZLE]),ob=new Set([...dt,L.GIF]),ib=new Set([L.TABLE]),pu=new Set(["multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]),Nv=n=>{if(!(Number(n.warpStrength)||0))return null;let t=Ge(n);return t==="arch"||t==="waist"||t==="flag"?t:null},bu=n=>{let e=n.effects;return!!e&&typeof e=="object"&&!Array.isArray(e)},Lv=n=>typeof n.textBackgroundColor=="string"&&n.textBackgroundColor?!0:Array.isArray(n.texts)&&n.texts.length>0,Iv=new Set(["rect","Rect","fabricrect","ellipse","Ellipse","circle","Circle","polygon","Polygon","polyline","Polyline","Path","path"]),_v=.222,K=(n,e,t)=>{let r=n[e];if(typeof r=="number")return Number.isFinite(r)?r:t;if(typeof r=="string"&&r.trim()!==""){let o=Number(r.trim());if(Number.isFinite(o))return o}return t},Ie=(n,e)=>{let t=n[e];return typeof t=="string"?t:void 0},N=n=>{let e=Math.round(n*1e4)/1e4;return Object.is(e,-0)?"0":String(e)},re=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),Dv=/^(#[0-9a-fA-F]{3,8}|rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*(,\s*[\d.]+\s*)?\)|[a-zA-Z][a-zA-Z0-9_-]*)$/,sn=n=>Dv.test(n.trim())?n.trim():null,On=n=>n==null||n===""||n==="transparent"||n==="rgba(0,0,0,0)"||n==="none",xu=n=>`matrix(${n.map(N).join(",")})`,Fv=(n,e)=>[1,0,0,1,n,e],sb=n=>n,ab=(n,e,t)=>Gn({...n,width:e,height:t}),on=n=>{let e=n.shadow;if(!e)return null;if(typeof e!="object"||Array.isArray(e))return;let t=e,r=typeof t.color=="string"?t.color:"rgb(0,0,0)";if(sn(r))return{color:r,blur:typeof t.blur=="number"&&Number.isFinite(t.blur)?t.blur:0,offsetX:typeof t.offsetX=="number"&&Number.isFinite(t.offsetX)?t.offsetX:0,offsetY:typeof t.offsetY=="number"&&Number.isFinite(t.offsetY)?t.offsetY:0}},lb=(n,e)=>{let t=n.pathOffset,r=0,o=0;return t&&typeof t=="object"?(typeof t.x=="number"&&Number.isFinite(t.x)&&(r=t.x),typeof t.y=="number"&&Number.isFinite(t.y)&&(o=t.y)):e&&(r=e.x,o=e.y),r||o?Fv(-r,-o):null},Ov=n=>{let e=Fe(n);return e?{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}:null},Bv=n=>{if(!n.length)return null;let e=1/0,t=1/0,r=-1/0,o=-1/0;for(let i of n)e>i.x&&(e=i.x),t>i.y&&(t=i.y),r<i.x&&(r=i.x),o<i.y&&(o=i.y);return{x:(e+r)/2,y:(t+o)/2}},Wv=n=>n.map(e=>e.length===1?e[0]:`${e[0]} ${e.slice(1).map(t=>N(Number(t))).join(" ")}`).join(" "),cb=(n,e,t)=>{let r=se(n);if($n.has(r)){let o=Math.min(K(n,"rx",0),e/2),i=Math.min(K(n,"ry",0),t/2),s=o>0||i>0?` rx="${N(o)}" ry="${N(i>0?i:o)}"`:"";return{open:`<rect x="${N(-e/2)}" y="${N(-t/2)}" width="${N(e)}" height="${N(t)}"${s}`,internalTransform:null}}if(fb.has(r))return{open:`<ellipse cx="0" cy="0" rx="${N(e/2)}" ry="${N(t/2)}"`,internalTransform:null};if(Pv.has(r))return{open:`<polygon points="${N(-e/2)},${N(t/2)} 0,${N(-t/2)} ${N(e/2)},${N(t/2)}"`,internalTransform:null};if(r===L.PATH){let o=Ce(n.path);return o?{open:`<path d="${re(Wv(o))}"`,internalTransform:lb(n,Ov(o))}:null}if(gu.has(r)||mb.has(r)){let o=n.points;if(!Array.isArray(o)||o.length===0)return null;let i=[];for(let l of o){let u=l,c=typeof u.x=="number"?u.x:NaN,h=typeof u.y=="number"?u.y:NaN;Number.isFinite(c)&&Number.isFinite(h)&&i.push({x:c,y:h})}if(!i.length)return null;let s=i.map(l=>`${N(l.x)},${N(l.y)}`);return{open:`<${gu.has(r)?"polygon":"polyline"} points="${s.join(" ")}"`,internalTransform:lb(n,Bv(i))}}return ft.has(r)?{open:`<line x1="${N(K(n,"x1",0))}" y1="${N(K(n,"y1",0))}" x2="${N(K(n,"x2",0))}" y2="${N(K(n,"y2",0))}"`,internalTransform:null}:null},ub=(n,e,t)=>{let r=e&&n.internalTransform?j(e,n.internalTransform):e??n.internalTransform;return`${n.open}${r?` transform="${xu(r)}"`:""}${t}/>`},Hv=(n,e,t)=>{let r="";if(e!==null){r+=` fill="${re(e)}"`;let o=Ie(n,"fillRule");o&&(r+=` fill-rule="${re(o)}"`)}else r+=' fill="none"';if(t!==null){r+=` stroke="${re(t)}"`,r+=` stroke-width="${N(K(n,"strokeWidth",1))}"`;let o=n.strokeDashArray;if(Array.isArray(o)&&o.length>0){let l=o.map(u=>typeof u=="number"&&Number.isFinite(u)?N(u):null).filter(u=>u!==null);l.length&&(r+=` stroke-dasharray="${l.join(",")}"`)}let i=Ie(n,"strokeLineCap");i&&(r+=` stroke-linecap="${re(i)}"`);let s=Ie(n,"strokeLineJoin");s&&(r+=` stroke-linejoin="${re(s)}"`);let a=n.strokeMiterLimit;typeof a=="number"&&Number.isFinite(a)&&(r+=` stroke-miterlimit="${N(a)}"`),n.strokeUniform===!0&&(r+=' vector-effect="non-scaling-stroke"'),Ie(n,"paintFirst")==="stroke"&&(r+=' paint-order="stroke"')}return r},Gv=n=>!On(n.stroke)&&K(n,"strokeWidth",1)>0,hb=n=>{let e=new Map;return(t,r)=>{let o=/([\d.]+)px\s+([\s\S]+)$/.exec(t);if(!o)return 0;let i=Number(o[1]),s=o[2].replace(/^["']+|["']+$/g,""),a=`${s}|${i}|${r}`,l=e.get(a);if(l!==void 0)return l;let u=n.getFont(s)??n.getSubsetFont?.(s,r[0]??"")??null,c=u&&typeof u.getAdvanceWidth=="function"?u.getAdvanceWidth(r,i):0;return e.set(a,c),c}},Xv=(n,e)=>{let t=0;for(let r of n)t+=r.charCodeAt(0)>255?1:.55;return t*e},pb=n=>{let e=n.textLines,t=n.charBounds,r=n.lineHeights;if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(r)||e.length===0||t.length!==e.length||r.length!==e.length)return null;for(let o=0;o<e.length;o++)if(typeof e[o]!="string"||!Array.isArray(t[o])||typeof r[o]!="number"||!Number.isFinite(r[o]))return null;return{textLines:e,charBounds:t,lineHeights:r}},bb=n=>{let e=n.map(o=>Nt(o).length),t=[],r=0;for(let o of e)t.push(r),r+=o;return{starts:t,counts:e}},zv=(n,e)=>{let{starts:t,counts:r}=n;if(t.length===0||e<0)return null;let o=0,i=t.length-1;for(;o<i;){let a=o+i+1>>1;t[a]<=e?o=a:i=a-1}let s=e-t[o];return s<0||s>=r[o]?null:[o,s]},Yv=(n,e)=>{let t=n.styles;if(!Array.isArray(t))return{};for(let r of t){if(!r||typeof r!="object")continue;let o=r,i=typeof o.start=="number"?o.start:-1,s=typeof o.end=="number"?o.end:-1;if(e>=i&&e<s&&o.style&&typeof o.style=="object")return o.style}return{}},db=(n,e)=>{let t=Yv(n,e),r=(o,i)=>t[o]!==void 0?t[o]:i;return{fontFamily:r("fontFamily",Ie(n,"fontFamily")??"Arial"),fontSize:r("fontSize",K(n,"fontSize",40)),fontWeight:r("fontWeight",String(Ie(n,"fontWeight")??"normal")),fontStyle:r("fontStyle",Ie(n,"fontStyle")??"normal"),fill:r("fill",n.fill),stroke:r("stroke",n.stroke),strokeWidth:r("strokeWidth",K(n,"strokeWidth",1)),underline:r("underline",n.underline===!0),linethrough:r("linethrough",n.linethrough===!0),overline:r("overline",n.overline===!0)}},Fn=n=>({fontFamily:n.fontFamily??"Times New Roman",fontSize:n.fontSize??40,fontWeight:n.fontWeight,fontStyle:n.fontStyle??void 0,lineHeight:n.lineHeight??1.16,charSpacing:n.charSpacing??0,textAlign:n.textAlign??fe.LEFT}),oi=(n,e,t)=>({fontFamily:e?.fontFamily??n.fontFamily,fontSize:e?.fontSize??n.fontSize,fontWeight:String(e?.fontWeight??n.fontWeight??"normal"),fontStyle:e?.fontStyle??n.fontStyle??"normal",fill:e?.fill??t.fill,stroke:t.stroke,strokeWidth:K(t,"strokeWidth",1),underline:t.underline===!0,linethrough:t.linethrough===!0,overline:t.overline===!0}),Uv=(n,e)=>{if(!Array.isArray(e)||e.length===0)return e&&typeof e=="object"?e:void 0;let t=bb(n.split(`
1095
+ `)),r={};for(let o of e){if(!o||typeof o!="object")continue;let i=typeof o.start=="number"?o.start:-1,s=typeof o.end=="number"?o.end:-1;if(!(i<0||s<=i||!o.style||typeof o.style!="object"))for(let a=i;a<s;a++){let l=zv(t,a);l&&((r[l[0]]??={})[l[1]]=o.style)}}return Object.keys(r).length>0?r:void 0},$v=(n,e,t,r)=>{let o=n??fe.LEFT;return $t(o)?r?o===fe.JUSTIFY_CENTER?(e-t)/2:o===fe.JUSTIFY_RIGHT?e-t:0:0:o===fe.CENTER?(e-t)/2:o===fe.RIGHT?e-t:0},yu=n=>{let e=[];for(let t of n)switch(t.type){case"M":e.push(`M${N(t.x??0)} ${N(t.y??0)}`);break;case"L":e.push(`L${N(t.x??0)} ${N(t.y??0)}`);break;case"Q":e.push(`Q${N(t.x1??0)} ${N(t.y1??0)} ${N(t.x??0)} ${N(t.y??0)}`);break;case"C":e.push(`C${N(t.x1??0)} ${N(t.y1??0)} ${N(t.x2??0)} ${N(t.y2??0)} ${N(t.x??0)} ${N(t.y??0)}`);break;case"Z":e.push("Z");break;default:break}return e.join("")},gb=(n,e,t,r,o={})=>{let i=-1;for(let f=0;f<e.textLines.length;f++)e.textLines[f].length>0&&(i=f);let s=K(n,"lineHeight",1.16)||1.16,a=Ie(n,"textAlign"),l=-t/2,u=-r/2,c=[],h=bb(e.textLines),d=0;for(let f=0;f<e.textLines.length;f++){let m=e.textLines[f],p=Nt(m),b=e.charBounds[f],g=e.lineHeights[f],x=g/s,S=u+d+x-g*_v/s,w=0;for(let C of b)!C||typeof C.left!="number"||typeof C.kernedWidth!="number"||(w=Math.max(w,C.left+C.kernedWidth));let y=$v(a,t,w,f>=i),v=o.lineLefts?.[f]??l+y,R=o.anchor==="boxLeft",P=v,T=0;for(let C=0;C<p.length;C++){let E=p[C],M=b[C];if(!M||typeof M.width!="number"||typeof M.kernedWidth!="number")continue;let k=h.starts[f]+C;if(R){c.push({char:E,x:v+(M.left||0),y:S,style:db(n,k)});continue}T===0?(P+=M.kernedWidth-M.width,T=M.width):T+=M.width,c.push({char:E,x:P,y:S,style:db(n,k)}),P+=T,T=0}d+=g}return c},jv=(n,e,t={})=>{if(!e)return null;let r=n,o=K(r,"width",NaN),i=K(r,"height",NaN);if(!Number.isFinite(o)||!Number.isFinite(i)||r.vertical===!0||typeof r.direction=="string"&&r.direction!=="ltr")return null;let s=pb(r);if(!s)return null;let a=[];for(let{char:l,x:u,y:c,style:h}of gb(r,s,o,i,t)){if(!l.trim())continue;let d=e.getFont(h.fontFamily)??e.getSubsetFont?.(h.fontFamily,l)??null;if(!d)return null;let f=yu(d.getPath(l,u,c,h.fontSize).commands);a.push(f.endsWith("Z")?f:`${f} Z`)}return a.length>0?{path:a.join(" ")}:null},Wa=class{options;defs=[];idSeq=0;skipped={};constructor(e){this.options=e}exportPage(e){this.defs=[],this.idSeq=0,this.skipped={};let t=[];for(let a of e.objects){if(!a||typeof a!="object"||typeof a.type!="string")continue;let l=this.emitNode(a);l!==null&&l&&t.push(l)}let r=e.background&&!On(e.background)?sn(e.background):null,o=r?`<rect x="${N(e.viewBox.x)}" y="${N(e.viewBox.y)}" width="${N(e.viewBox.width)}" height="${N(e.viewBox.height)}" fill="${re(r)}"/>`:"",i=this.defs.length?`<defs>${this.defs.join("")}</defs>`:"";return{svg:`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${N(e.width)}px" height="${N(e.height)}px" viewBox="${N(e.viewBox.x)} ${N(e.viewBox.y)} ${N(e.viewBox.width)} ${N(e.viewBox.height)}" data-engine-svg="1">`+o+i+t.join("")+"</svg>",skippedTypes:this.skipped}}skip(e){this.skipped[e]=(this.skipped[e]??0)+1}nextId(e){return this.idSeq+=1,`${e}${this.idSeq}`}emitGradientDef(e,t,r){let o=this.nextId("esvg-g"),i=fi(e,t,r),s=` gradientTransform="matrix(${N(i[0])},${N(i[1])},${N(i[2])},${N(i[3])},${N(i[4])},${N(i[5])})"`,a=e.stops.map(l=>{let[u,c,h,d]=l.color,f=`rgb(${Math.round(u*255)},${Math.round(c*255)},${Math.round(h*255)})`;return`<stop offset="${N(l.offset)}" stop-color="${f}"${d<1?` stop-opacity="${N(d)}"`:""}/>`}).join("");return e.kind==="linear"?this.defs.push(`<linearGradient id="${o}" gradientUnits="userSpaceOnUse" x1="${N(e.x1)}" y1="${N(e.y1)}" x2="${N(e.x2)}" y2="${N(e.y2)}"${s}>${a}</linearGradient>`):this.defs.push(`<radialGradient id="${o}" gradientUnits="userSpaceOnUse" cx="${N(e.x2)}" cy="${N(e.y2)}" r="${N(e.r2)}" fx="${N(e.x1)}" fy="${N(e.y1)}"${e.r1>0?` fr="${N(e.r1)}"`:""}${s}>${a}</radialGradient>`),`url(#${o})`}resolvePaint(e,t,r){if(On(e))return null;if(typeof e=="string")return sn(e)??void 0;if(!e||typeof e!="object"||Array.isArray(e))return;let o=Yn(e);if(o)return this.emitGradientDef(o,t,r);let i=pr(e);if(i)return this.emitPatternDef(i,t,r)}emitPatternDef(e,t,r){let o=this.options.naturalSizes?.get(e.src);if(!o||o.width<=0||o.height<=0)return;let i=this.nextId("esvg-pt"),s=bi(e,t,r);return this.defs.push(`<pattern id="${i}" patternUnits="userSpaceOnUse" width="${N(o.width)}" height="${N(o.height)}" patternTransform="${xu(s)}"><image href="${re(e.src)}" xlink:href="${re(e.src)}" x="0" y="0" width="${N(o.width)}" height="${N(o.height)}"/></pattern>`),`url(#${i})`}emitShadowFilter(e){let t=this.nextId("esvg-s");return this.defs.push(`<filter id="${t}" x="-50%" y="-50%" width="200%" height="200%"><feDropShadow dx="${N(e.offsetX)}" dy="${N(e.offsetY)}" stdDeviation="${N(e.blur/2)}" flood-color="${re(e.color)}"/></filter>`),t}emitClipPath(e,t){let r=e.clipPath;if(!r||typeof r!="object"||Array.isArray(r))return null;let o=r;if(typeof o.type!="string"||!Iv.has(o.type)||o.inverted===!0)return null;let i=K(o,"width",0),s=K(o,"height",0),a=cb(o,i,s);if(!a)return null;let l=ab(o,i,s),u=o.absolutePositioned===!0?j(ve(t),l):l,c=this.nextId("esvg-c");return this.defs.push(`<clipPath id="${c}">${ub(a,u,"")}</clipPath>`),` clip-path="url(#${c})"`}emitBakedTextImage(e,t){let r=on(e);if(r===void 0)return this.skip("shadow-unsupported"),null;let o=-t.width/2+(t.offsetX??0),i=-t.height/2+(t.offsetY??0),s=`<image href="${re(t.dataUrl)}" xlink:href="${re(t.dataUrl)}" x="${N(o)}" y="${N(i)}" width="${N(t.width)}" height="${N(t.height)}"/>`;r&&(s=`<g filter="url(#${this.emitShadowFilter(r)})">${s}</g>`);let a=K(e,"textScaleX",1)||1,l=K(e,"textScaleY",1)||1;return(Math.abs(a-1)>1e-9||Math.abs(l-1)>1e-9)&&(s=`<g transform="scale(${N(a)},${N(l)})">${s}</g>`),s}emitText(e){if(Xe(e))return this.emitArcText(e);if(e.vertical===!0)return this.emitVerticalText(e);let t=Nv(e);if(t)return this.emitWarpedText(e,t);if(Zn(e)){let m=this.options.bakeTextBitmap?.(e,"psd")??null;if(m)return this.emitBakedTextImage(e,m);this.skip("text-psdwarp-bitmap-fallback")}let r=K(e,"width",NaN),o=K(e,"height",NaN);if(!Number.isFinite(r)||!Number.isFinite(o)){if(Number.isFinite(r)&&!Number.isFinite(o)){let m=this.engineLayoutOf(e,!1);if(m)return this.emitTextFromEngineLayout(e,m)}return this.skip("text-dims-missing"),null}if(typeof e.direction=="string"&&e.direction!=="ltr")return this.skip("text-vertical-or-rtl"),null;let i=this.pathBackgroundMarkup(e);if(bu(e)){let m=this.options.bakeTextBitmap?.(e,"plain")??null;if(m)return i+this.emitBakedTextImage(e,m)}if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("text-effects"),null;if(Lv(e)){let m=this.engineLayoutOf(e,!1);if(m)return this.emitTextFromEngineLayout(e,m)}let s=pb(e);if(!s){let m=Ie(e,"text");if(!m||!Array.from(m).some(b=>b!==`
1096
+ `))return'<text xml:space="preserve"></text>';let p=this.engineLayoutOf(e,!1);return p?this.emitTextFromEngineLayout(e,p):(this.skip("text-layout-missing"),null)}let a=on(e);if(a===void 0)return this.skip("shadow-unsupported"),null;let l=K(e,"textScaleX",1)||1,u=K(e,"textScaleY",1)||1,c=Math.abs(l-1)>1e-9||Math.abs(u-1)>1e-9,h=gb(e,s,r,o),d=this.emitAnchorGlyphs(h,r,o);if(d===null)return null;let f=d;return a&&(f=`<g filter="url(#${this.emitShadowFilter(a)})">${f}</g>`),c&&(f=`<g transform="scale(${N(l)},${N(u)})">${f}</g>`),this.pathBackgroundMarkup(e)+f}emitAnchorGlyphs(e,t,r){let o=[],i=[],s=[];for(let{char:l,x:u,y:c,rotation:h,centerX:d,scaleY:f,style:m}of e){let p=h!==void 0||d===!0||f!==void 0,b=h!==void 0?h*180/Math.PI:0;if(this.options.textMode==="paths"){if(l.trim()){let g=this.options.fonts?.getFont(m.fontFamily)??this.options.fonts?.getSubsetFont?.(m.fontFamily,l)??null;if(!g)return this.skip(`text-font-missing:${m.fontFamily}`),null;let x=this.resolvePaint(m.fill,t,r);if(x===void 0)return this.skip("text-fill-unsupported"),null;let S=x!==null?` fill="${re(x)}"`:' fill="none"';if(typeof m.stroke=="string"&&!On(m.stroke)&&m.strokeWidth>0&&(S+=` stroke="${re(m.stroke)}" stroke-width="${N(m.strokeWidth)}"`),p){let w=d?-((g.getAdvanceWidth?.(l,m.fontSize)??0)/2):0,y=yu(g.getPath(l,w,0,m.fontSize).commands),v=`translate(${N(u)},${N(c)})`;h!==void 0&&(v+=` rotate(${N(b)})`),f!==void 0&&(v+=` scale(1,${N(f)})`),o.push(`<g transform="${v}"><path d="${y}"${S}/></g>`)}else{let w=yu(g.getPath(l,u,c,m.fontSize).commands);o.push(`<path d="${w}"${S}/>`)}}}else{let g=this.resolvePaint(m.fill,t,r);if(g===void 0)return this.skip("text-fill-unsupported"),null;if(p){let x=` transform="translate(${N(u)},${N(c)})${h!==void 0?` rotate(${N(b)})`:""}${f!==void 0?` scale(1,${N(f)})`:""}"`;d&&(x+=' text-anchor="middle"'),x+=` font-family="${re(m.fontFamily)}"`,x+=` font-size="${N(m.fontSize)}"`,m.fontWeight!=="normal"&&(x+=` font-weight="${re(m.fontWeight)}"`),m.fontStyle!=="normal"&&(x+=` font-style="${re(m.fontStyle)}"`),x+=g!==null?` fill="${re(g)}"`:' fill="none"',typeof m.stroke=="string"&&!On(m.stroke)&&m.strokeWidth>0&&(x+=` stroke="${re(m.stroke)}" stroke-width="${N(m.strokeWidth)}"`),s.push(`<text xml:space="preserve"${x}>${re(l)}</text>`)}else{let x=` x="${N(u)}" y="${N(c)}"`;x+=` font-family="${re(m.fontFamily)}"`,x+=` font-size="${N(m.fontSize)}"`,m.fontWeight!=="normal"&&(x+=` font-weight="${re(m.fontWeight)}"`),m.fontStyle!=="normal"&&(x+=` font-style="${re(m.fontStyle)}"`),x+=g!==null?` fill="${re(g)}"`:' fill="none"',typeof m.stroke=="string"&&!On(m.stroke)&&m.strokeWidth>0&&(x+=` stroke="${re(m.stroke)}" stroke-width="${N(m.strokeWidth)}"`);let S=[m.underline?"underline":"",m.overline?"overline":"",m.linethrough?"line-through":""].filter(Boolean);S.length&&(x+=` text-decoration="${S.join(" ")}"`),i.push(`<tspan${x}>${re(l)}</tspan>`)}}}if(this.options.textMode==="paths")return o.join("");let a=i.length>0?`<text xml:space="preserve">${i.join("")}</text>`:"";return s.length>0?s.join("")+a:a}emitArcText(e){if(bu(e)){let a=this.options.bakeTextBitmap?.(e,Xe(e)??"arc")??null;if(a)return this.emitBakedTextImage(e,a)}if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("text-effects"),null;let t=this.arcLayoutOf(e);if(!t)return this.skip(`text-font-missing:${Ie(e,"fontFamily")??""}`),null;let r=on(e);if(r===void 0)return this.skip("shadow-unsupported"),null;let o=Fn(e),i=[];for(let a of t.arc.chars)i.push({char:a.char,x:a.x-t.arc.contentOffsetX,y:a.y-t.arc.contentOffsetY,rotation:a.rotation,centerX:!0,style:oi(o,t.layout.lines[a.line]?.charStyles?.[a.index],e)});let s=this.emitAnchorGlyphs(i,K(e,"width",0)||t.arc.width,t.arc.height);return s===null?null:r?`<g filter="url(#${this.emitShadowFilter(r)})">${s}</g>`:s}emitVerticalText(e){if(bu(e)){let b=this.options.bakeTextBitmap?.(e,"vertical")??null;if(b)return this.emitBakedTextImage(e,b)}if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("text-effects"),null;let t=this.engineLayoutOf(e,!0);if(!t)return this.skip(`text-font-missing:${Ie(e,"fontFamily")??""}`),null;let r=on(e);if(r===void 0)return this.skip("shadow-unsupported"),null;let o=Fn(e),i=o.charSpacing?o.fontSize*o.charSpacing/1e3:0,s=Number(e.textOffsetY)||0,a=Math.max(t.height,K(e,"height",0)),l=[],u=0;for(let b of t.lines){let g=-t.width/2+b.leftOffset,x=-a/2+b.baseline,S=0;for(let w=0;w<b.graphemes.length;w++){let y=b.graphemes[w],v=b.charStyles[w],R=v?.fontSize??o.fontSize,P=wt(s,R,u+w),T=b.boxes[w],C=qn(y);if(C==="latin"||C==="bracket"){let E=g+S+(C==="latin"?T.kernedWidth-T.width:0);l.push({char:y,x:E,y:x+P,style:oi(o,v,e)})}else{let E=g+S+un(R),M=x+P+yr(C,T,R);l.push({char:y,x:E,y:M,rotation:-Math.PI/2,style:oi(o,v,e)})}S+=Kn(y,T,i)}u+=b.graphemes.length}let c=this.emitAnchorGlyphs(l,t.width,a);if(c===null)return null;let h=this.emitTextDecorations(e,t,a),d=K(e,"textScaleX",1)||1,f=K(e,"textScaleY",1)||1,m=c;r&&(m=`<g filter="url(#${this.emitShadowFilter(r)})">${m}</g>`);let p=h+m;return(Math.abs(d-1)>1e-9||Math.abs(f-1)>1e-9)&&(p=`<g transform="scale(${N(d)},${N(f)})">${p}</g>`),p}emitWarpedText(e,t){let r=this.options.bakeTextBitmap?.(e,t)??null;if(r)return this.emitBakedTextImage(e,r);if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("text-effects"),null;let o=this.engineLayoutOf(e,!1);if(!o)return this.skip(`text-font-missing:${Ie(e,"fontFamily")??""}`),null;let i=on(e);if(i===void 0)return this.skip("shadow-unsupported"),null;let s=K(e,"fontSize",40)||40,a=Math.max(-1,Math.min(1,K(e,"warpStrength",0)||0)),l=K(e,"width",0),u=K(e,"height",0),c=Math.max(o.height,u),h=Math.max(o.width,l,s),d=t==="flag"?Math.abs(a)*(u||s)*.3:0,f=h/2,m=c/2,p=Fn(e),b=[];for(let y of o.lines){let v=-o.width/2+y.leftOffset,R=-c/2+y.baseline;for(let P=0;P<y.graphemes.length;P++){let T=y.boxes[P],C=oi(p,y.charStyles[P],e),E=v+T.left,M=E+T.width/2,k=f>0?M/f:0;if(t==="flag"){let A=Math.sin(k*Math.PI)*d*a;b.push({char:y.graphemes[P],x:E,y:R+A,style:C})}else if(t==="arch"){let A=Math.max(-1,Math.min(1,k)),O=Math.sqrt(Math.max(0,1-A*A)),F=O*O*(3-2*O),W=a>0?Math.pow(F,2.5):F,z=Math.min(1+Math.max(0,a),Math.max(.05,1+a*W));b.push({char:y.graphemes[P],x:E,y:z*R+m*(1-z),scaleY:z,style:C})}else{let A=Math.min(1+Math.abs(a),Math.max(.4,1+a*(k*k-.5)));b.push({char:y.graphemes[P],x:E,y:A*R,scaleY:A,style:C})}}}let g=this.emitAnchorGlyphs(b,h,c);if(g===null)return null;let x=K(e,"textScaleX",1)||1,S=K(e,"textScaleY",1)||1,w=g;return i&&(w=`<g filter="url(#${this.emitShadowFilter(i)})">${w}</g>`),(Math.abs(x-1)>1e-9||Math.abs(S-1)>1e-9)&&(w=`<g transform="scale(${N(x)},${N(S)})">${w}</g>`),w}emitMask(e){let t=Ie(e,"src");if(!t)return this.skip("image-src-missing"),null;let r=K(e,"width",0),o=K(e,"height",0);if(!(r>0)||!(o>0))return this.skip("image-dims-missing"),null;let i=e.clipImage,s=i&&typeof i=="object"?i:null,a=s?Ie(s,"src"):void 0;if(!s||!a){let v=on(e);if(v===void 0)return this.skip("shadow-unsupported"),null;let R=`<image href="${re(t)}" xlink:href="${re(t)}" x="${N(-r/2)}" y="${N(-o/2)}" width="${N(r)}" height="${N(o)}"/>`;return v&&(R=`<g filter="url(#${this.emitShadowFilter(v)})">${R}</g>`),R}let l=this.options.naturalSizes?.get(a);if(!l||l.width<=0||l.height<=0)return this.skip("image-natural-missing"),null;let u=l.width,c=l.height,h=this.nextId("esvg-mk");this.defs.push(`<mask id="${h}" maskUnits="userSpaceOnUse" mask-type="alpha" x="${N(-r/2)}" y="${N(-o/2)}" width="${N(r)}" height="${N(o)}"><image href="${re(t)}" xlink:href="${re(t)}" x="${N(-r/2)}" y="${N(-o/2)}" width="${N(r)}" height="${N(o)}"/></mask>`);let d=`<g transform="translate(${N(-r/2)},${N(-o/2)})" mask="url(#${h})"`,f=Math.max(0,Math.min(K(e,"cornerRadius",0),Math.min(r,o)/2));if(f>0){let v=this.nextId("esvg-mc");this.defs.push(`<clipPath id="${v}"><path d="M ${N(f)} 0 L ${N(r-f)} 0 Q ${N(r)} 0 ${N(r)} ${N(f)} L ${N(r)} ${N(o-f)} Q ${N(r)} ${N(o)} ${N(r-f)} ${N(o)} L ${N(f)} ${N(o)} Q 0 ${N(o)} 0 ${N(o-f)} L 0 ${N(f)} Q 0 0 ${N(f)} 0 Z"/></clipPath>`),d+=` clip-path="url(#${v})"`}d+=">";let m=K(s,"angle",0),p=K(s,"scaleX",1)||1,b=K(s,"scaleY",1)||1,g=s.flipX===!0?-1:1,x=s.flipY===!0?-1:1,S=K(e,"clipX",0),w=K(e,"clipY",0),y=`translate(${N(r/2)},${N(o/2)}) rotate(${N(m)}) scale(${N(p*g)},${N(b*x)}) translate(${N(S/(p||1))},${N(w/(b||1))}) translate(${N(-u/2)},${N(-c/2)})`;return d+`<g transform="${y}"><image href="${re(a)}" xlink:href="${re(a)}" x="0" y="0" width="${N(u)}" height="${N(c)}"/></g></g>`}emitTable(e){let t=this.tableLayoutOf(e);if(!t)return this.skip(`text-font-missing:${typeof e.fontFamily=="string"?e.fontFamily:""}`),null;let r=[];for(let o of t.children){if(!o||typeof o!="object"||typeof o.type!="string")continue;let i=this.emitNode(o);if(i===null)return null;i&&r.push(i)}return r.join("")}pathBackgroundMarkup(e,t){let r=co(e);if(!r||!r.fill)return"";let o=t??this.engineLayoutOf(e,!1);if(!o)return"";let i=o.width,s=Math.max(o.height,K(e,"height",0));if(!(i>0)||!(s>0))return"";let a=Ce(r.path);if(!a)return"";let l=Fe(a);if(!l)return"";let u=l.right-l.left,c=l.bottom-l.top;if(!(u>0)||!(c>0))return"";let h=i/r.width,d=s/r.height,f=(l.left+l.right)/2,m=(l.top+l.bottom)/2,[p,b,g,x]=ee(r.fill),S=`rgba(${Math.round(p*255)},${Math.round(b*255)},${Math.round(g*255)},${N(x)})`;return`<path d="${re(r.path)}" transform="matrix(${N(h)} 0 0 ${N(d)} ${N(-f*h)} ${N(-m*d)})" fill="${S}"/>`}emitTextDecorations(e,t,r){let o=[],i=-r/2,s=typeof e.textBackgroundColor=="string"?e.textBackgroundColor:"";if(s||t.lines.some(a=>a.charStyles.some(l=>l?.textBackgroundColor)))for(let a of t.lines){let l=-t.width/2+a.leftOffset,u=i+a.top,c=p=>a.charStyles[p]?.textBackgroundColor??s,h=0,d=0,f=c(0),m=()=>{if(!f||d<=0)return;let p=sn(f);p&&o.push(`<rect x="${N(l+a.boxes[h].left)}" y="${N(u)}" width="${N(d)}" height="${N(a.implHeight)}" fill="${re(p)}"/>`)};for(let p=0;p<a.graphemes.length;p++){let b=c(p);b!==f?(m(),h=p,d=a.boxes[p].width,f=b):d+=a.boxes[p].kernedWidth}m()}if(Array.isArray(e.texts)&&e.texts.length>0&&e.vertical!==!0){let a=Jn(e.text??"",t,e.texts,i,Fn(e).fontSize);if(a)for(let l of a.ops){let u=l.isFill?`<path d="${re(l.d)}" fill="${re(sn(l.fill)??l.fill)}"/>`:`<path d="${re(l.d)}" fill="none" stroke="${re(sn(l.stroke)??l.stroke)}" stroke-width="${N(l.strokeWidth)}"/>`;o.push(`<g transform="translate(${N(l.translateX)},${N(l.translateY)}) scale(${N(l.scaleX)},${N(l.scaleY)})">${u}</g>`)}}return o.join("")}emitTextFromEngineLayout(e,t){let r=on(e);if(r===void 0)return this.skip("shadow-unsupported"),null;let o=Fn(e),i=Math.max(t.height,K(e,"height",0)),s=[];for(let f of t.lines){let m=-t.width/2+f.leftOffset,p=-i/2+f.baseline;for(let b=0;b<f.graphemes.length;b++)s.push({char:f.graphemes[b],x:m+f.boxes[b].left,y:p,style:oi(o,f.charStyles[b],e)})}let a=this.emitAnchorGlyphs(s,t.width,i);if(a===null)return null;let l=K(e,"textScaleX",1)||1,u=K(e,"textScaleY",1)||1,c=this.emitTextDecorations(e,t,i),h=a;r&&(h=`<g filter="url(#${this.emitShadowFilter(r)})">${h}</g>`);let d=c+h;return(Math.abs(l-1)>1e-9||Math.abs(u-1)>1e-9)&&(d=`<g transform="scale(${N(l)},${N(u)})">${d}</g>`),this.pathBackgroundMarkup(e,t)+d}tableCache=new Map;tableLayoutOf(e){let t=this.tableCache.get(e);if(t!==void 0)return t;if(this.layoutMeasure===void 0&&(this.layoutMeasure=this.options.measure??(this.options.fonts?hb(this.options.fonts):null)),!this.layoutMeasure)return null;let r;try{r=Ro(e,this.layoutMeasure)}catch{r=null}return this.tableCache.set(e,r),r}arcCache=new Map;layoutMeasure;engineLayoutOf(e,t){if(this.layoutMeasure===void 0&&(this.layoutMeasure=this.options.measure??(this.options.fonts?hb(this.options.fonts):null)),!this.layoutMeasure)return null;if(!this.options.measure){let i=Fn(e).fontFamily;if(!this.options.fonts?.getFont(i))return null}let r=e.text??"",o=se(e)===L.TEXTBOX&&Ge(e)===null;return jt(r,Fn(e),{measure:this.layoutMeasure,boxWidth:o?e.width??0:null,styles:Uv(r,e.styles),splitByGrapheme:e.splitByGrapheme===!0,vertical:t,paragraph:Xe(e)?void 0:e.paragraph})}arcLayoutOf(e){let t=this.arcCache.get(e);if(t!==void 0)return t;let r=this.engineLayoutOf(e,!1),o=r?{layout:r,arc:Et(r,e,Fn(e).lineHeight??1.16)}:null;return this.arcCache.set(e,o),o}emitImage(e){let t=Ie(e,"src");if(!t)return this.skip("image-src-missing"),null;if(Array.isArray(e.filters)&&e.filters.length>0)return this.skip("image-filters"),null;if(Array.isArray(e.effects)&&e.effects.length>0)return this.skip("image-effects"),null;let r=Ie(e,"globalCompositeOperation");if(r&&r!=="source-over"&&!pu.has(r))return this.skip("image-gco"),null;let o=ts(sb(e));if(o){let h=this.options.naturalSizes?.get(t);if(!h)return this.skip("image-natural-missing"),null;let d=o.sw,f=o.sh;if(d<=0||f<=0)return this.skip("image-crop-empty"),null;let m=d/o.sw,p=f/o.sh,b=-d/2-o.sx*m,g=-f/2-o.sy*p,x=this.nextId("esvg-ic"),S=K(e,"rx",0),w=K(e,"ry",0),y=S>0||w>0?` rx="${N(S)}" ry="${N(w)}"`:"";return this.defs.push(`<clipPath id="${x}"><rect x="${N(-d/2)}" y="${N(-f/2)}" width="${N(d)}" height="${N(f)}"${y}/></clipPath>`),`<g clip-path="url(#${x})"><image xlink:href="${re(t)}" x="${N(b)}" y="${N(g)}" width="${N(h.width*m)}" height="${N(h.height*p)}"/></g>`}let i=K(e,"width",NaN),s=K(e,"height",NaN);if(!Number.isFinite(i)||!Number.isFinite(s))return this.skip("image-dims-missing"),null;let a=on(e);if(a===void 0)return this.skip("shadow-unsupported"),null;let l=`<image xlink:href="${re(t)}" x="${N(-i/2)}" y="${N(-s/2)}" width="${N(i)}" height="${N(s)}"/>`,u=K(e,"rx",0),c=K(e,"ry",0);if(u>0||c>0){let h=this.nextId("esvg-ir");this.defs.push(`<clipPath id="${h}"><rect x="${N(-i/2)}" y="${N(-s/2)}" width="${N(i)}" height="${N(s)}" rx="${N(u)}" ry="${N(c)}"/></clipPath>`),l=`<g clip-path="url(#${h})">${l}</g>`}return a&&(l=`<g filter="url(#${this.emitShadowFilter(a)})">${l}</g>`),l}emitObjectContent(e,t,r,o){let i=se(e);if(Av.has(i)){let d=e.objects;if(!Array.isArray(d))return this.skip("group-objects-missing"),null;let f=[];for(let m of d){if(!m||typeof m!="object"||typeof m.type!="string")continue;let p=this.emitNode(m);if(p===null)return null;p&&f.push(p)}return f.join("")}if(ib.has(i))return this.emitTable(e);if(ot.has(i))return this.emitMask(e);if(ob.has(i))return this.emitImage(e);if(i===L.TEXTIMAGE&&typeof e.renderSrc=="string"){let d=e.renderRect,f=typeof d?.w=="number"&&d.w>0?d.w:K(e,"width",NaN),m=typeof d?.h=="number"&&d.h>0?d.h:K(e,"height",NaN);if(!Number.isFinite(f)||!Number.isFinite(m)||f<=0||m<=0)return this.skip("textimage-dims-missing"),null;let p=-f/2+(typeof d?.x=="number"?d.x:0),b=-m/2+(typeof d?.y=="number"?d.y:0),g=Po(e),x=`<image xlink:href="${re(Ie(e,"renderSrc")??"")}" x="${N(p)}" y="${N(b)}" width="${N(f)}" height="${N(m)}"${g<1?` opacity="${N(g)}"`:""}/>`,S=typeof d?.angle=="number"&&Number.isFinite(d.angle)?d.angle:0;return S&&(x=`<g transform="rotate(${N(-S)})">${x}</g>`),x}if(an.has(i))return this.emitText(e);let s=Ie(e,"globalCompositeOperation");if(s&&s!=="source-over"&&!pu.has(s))return this.skip("shape-gco"),null;if(typeof e.strokeAlignment=="string"&&e.strokeAlignment!=="center"&&!On(e.stroke))return this.skip("shape-stroke-alignment"),null;if(rb.has(i)||kv.has(i))return this.emitLineDecoration(e,rb.has(i));let a=cb(e,r,o);if(!a)return this.skip(`type:${String(e.type??"")}`),null;let l=this.resolvePaint(e.fill,r,o);if(l===void 0)return this.skip("fill-unsupported"),null;let u=null;if(Gv(e)){let d=this.resolvePaint(e.stroke,r,o);if(d===void 0)return this.skip("stroke-unsupported"),null;u=d}let c=on(e);if(c===void 0)return this.skip("shadow-unsupported"),null;let h=Hv(e,l,u)+(c?` filter="url(#${this.emitShadowFilter(c)})"`:"");return ub(a,null,h)}emitLineDecoration(e,t){let r=K(e,"x1",NaN),o=K(e,"y1",NaN),i=K(e,"x2",NaN),s=K(e,"y2",NaN);if(!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s))return this.skip(`dims-missing:${String(e.type??"")}`),null;let a=e.stroke,l=typeof a=="string"&&!On(a)?a:"#000000";if(!sn(l))return this.skip("stroke-unsupported"),null;let u=K(e,"strokeWidth",1),c=e.strokeDashArray,h=Array.isArray(c)&&c.length>0?` stroke-dasharray="${c.map(G=>typeof G=="number"&&Number.isFinite(G)?N(G):null).filter(G=>G!==null).join(",")}"`:"",d=i-r,f=s-o,m=Math.atan2(f,d),p=Math.cos(m),b=Math.sin(m);if(t){let G=e.arrowType==="start"||e.arrowType==="both"?e.arrowType:"end",$=G==="start"||G==="both",V=G==="end"||G==="both",H=Math.sqrt(u),Y=K(e,"arrowWidth",15)*H,X=K(e,"arrowHeight",22.5)*H,Z=r+p*($?X:0),B=o+b*($?X:0),q=i-p*(V?X:0),U=s-b*(V?X:0),oe=` stroke="${re(l)}" stroke-width="${N(u)}"${h}`,ne=[`<line x1="${N(Z)}" y1="${N(B)}" x2="${N(q)}" y2="${N(U)}"${oe} fill="none"/>`],de=(Pe,De,nt)=>{let ke=Math.cos(nt),Ee=Math.sin(nt),ue=Pe-X*ke+Y/2*Ee,xe=De-X*Ee-Y/2*ke,pe=Pe-X*ke-Y/2*Ee,Te=De-X*Ee+Y/2*ke;ne.push(`<path d="M ${N(Pe)} ${N(De)} L ${N(ue)} ${N(xe)} L ${N(pe)} ${N(Te)} Z" fill="${re(l)}"/>`)};return V&&de(i,s,m),$&&de(r,o,m+Math.PI),ne.join("")}let g=` stroke="${re(l)}" stroke-width="${N(u)}"${h}`,x=Ie(e,"strokeLineCap");x&&(g+=` stroke-linecap="${re(x)}"`);let S=Ie(e,"strokeLineJoin");S&&(g+=` stroke-linejoin="${re(S)}"`);let w=e.strokeMiterLimit;typeof w=="number"&&Number.isFinite(w)&&(g+=` stroke-miterlimit="${N(w)}"`);let y=[`<line x1="${N(r)}" y1="${N(o)}" x2="${N(i)}" y2="${N(s)}"${g} fill="none"/>`],v=(K(e,"textFontSize",50)||50)/2,R=-b,P=p,T=` stroke="${re(l)}" stroke-width="${N(u)}" stroke-linecap="round"`;for(let[G,$]of[[r,o],[i,s]])y.push(`<line x1="${N(G-R*v)}" y1="${N($-P*v)}" x2="${N(G+R*v)}" y2="${N($+P*v)}"${T} fill="none"/>`);let C=K(e,"textFontSize",50)||50,E=typeof e.text=="string"&&e.text.trim()?e.text:"50cm",M=K(e,"textPadding",4),k=Xv(E,C)+M*2,A=C+M*2,O=C+u/2+5,F=(r+i)/2+R*O,W=(o+s)/2+P*O,z=e.textFollowLine===!1?0:m*180/Math.PI,_=typeof e.textColor=="string"&&sn(e.textColor)?e.textColor:"#333333",D=typeof e.textBackgroundColor=="string"?e.textBackgroundColor:"#ffffff",I=sn(D);return y.push(`<g transform="translate(${N(F)},${N(W)}) rotate(${N(z)})">`+(D&&I?`<rect x="${N(-k/2)}" y="${N(-A/2)}" width="${N(k)}" height="${N(A)}" fill="${re(I)}"/>`:"")+`<text text-anchor="middle" dominant-baseline="central" font-family="Arial, sans-serif" font-size="${N(C)}" fill="${re(_)}">${re(E)}</text></g>`),y.join("")}emitNode(e){if(Ir.has(Ie(e,"id")??"")||e.excludeFromExport===!0||e.visible===!1)return"";let t=se(e),r=K(e,"width",NaN),o=K(e,"height",NaN);if(ob.has(t)){let h=ts(sb(e));if(h)r=h.sw,o=h.sh;else if(!Number.isFinite(r)||!Number.isFinite(o)){let d=this.options.naturalSizes?.get(Ie(e,"src")??"");r=d?.width??NaN,o=d?.height??NaN}}else if(ft.has(t)&&(!Number.isFinite(r)||!Number.isFinite(o)))r=Math.abs(K(e,"x2",0)-K(e,"x1",0)),o=Math.abs(K(e,"y2",0)-K(e,"y1",0));else if(fb.has(t)&&(!Number.isFinite(r)||!Number.isFinite(o)))if(t===L.CIRCLE){let h=2*K(e,"radius",NaN);Number.isFinite(r)||(r=h),Number.isFinite(o)||(o=h)}else Number.isFinite(r)||(r=2*K(e,"rx",NaN)),Number.isFinite(o)||(o=2*K(e,"ry",NaN));else if((gu.has(t)||mb.has(t))&&(!Number.isFinite(r)||!Number.isFinite(o))){let h=e.points;if(Array.isArray(h)&&h.length>0){let d=1/0,f=1/0,m=-1/0,p=-1/0;for(let b of h){let g=typeof b?.x=="number"&&Number.isFinite(b.x)?b.x:NaN,x=typeof b?.y=="number"&&Number.isFinite(b.y)?b.y:NaN;!Number.isFinite(g)||!Number.isFinite(x)||(d>g&&(d=g),f>x&&(f=x),m<g&&(m=g),p<x&&(p=x))}Number.isFinite(d)&&Number.isFinite(f)&&(Number.isFinite(r)||(r=m-d),Number.isFinite(o)||(o=p-f))}}else if(an.has(t)&&!Number.isFinite(o))if(Array.isArray(e.lineHeights))o=e.lineHeights.reduce((h,d)=>h+(typeof d=="number"&&Number.isFinite(d)?d:0),0);else{let h=this.engineLayoutOf(e,!1);h&&(o=h.height)}if(Xe(e)){let h=this.arcLayoutOf(e);h&&(r=h.arc.width,o=h.arc.height)}if(ib.has(t)){let h=this.tableLayoutOf(e);h&&(r=h.width,o=h.height)}if(!Number.isFinite(r)||!Number.isFinite(o))return this.skip(`dims-missing:${String(e.type??"")}`),null;let i=ab(e,r,o),s=this.emitObjectContent(e,i,r,o);if(s===null)return null;if(s==="")return"";let a=`<g transform="${xu(i)}"`,l=Ie(e,"globalCompositeOperation");l&&l!=="source-over"&&pu.has(l)&&(a+=` style="mix-blend-mode:${re(l)}"`);let u=K(e,"opacity",1);u<1&&(a+=` opacity="${N(u)}"`);let c=this.emitClipPath(e,i);return c===null&&e.clipPath?(this.skip("clip-unsupported"),null):(c&&(a+=c),`${a}>${s}</g>`)}},Vv=n=>new Wa({textMode:n.textMode,fonts:n.fonts,naturalSizes:n.naturalSizes,measure:n.measure,bakeTextBitmap:n.bakeTextBitmap}).exportPage(n);var xb=n=>n==="center"?0:n==="right"?.5:-.5,yb=n=>typeof n=="number"?n:0,qv=(n,e={})=>{let t=1/0,r=1/0,o=-1/0,i=-1/0,s=[];for(let p of n){let b=Ct(p);if(!b)continue;s.push(b);let g=b.contentBoxCorners();for(let x of[g.tl,g.tr,g.br,g.bl])x.x<t&&(t=x.x),x.y<r&&(r=x.y),x.x>o&&(o=x.x),x.y>i&&(i=x.y)}let a=!s.length||!Number.isFinite(t),l=a?0:o-t,u=a?0:i-r,c=a?0:(t+o)/2,h=a?0:(r+i)/2,d=n.map(p=>({...p,left:yb(p.left)-c,top:yb(p.top)-h})),f=typeof e.left=="number"?e.left:c+l*xb(e.originX),m=typeof e.top=="number"?e.top:h+u*xb(e.originY);return{...e,type:e.type??"Group",width:l,height:u,left:f,top:m,objects:d}};var dr=n=>n==="center"?0:n==="right"?.5:-.5,Kv=(n,e={})=>{let t=Ce(n),r=t?Fe(t):null,o=r?r.right-r.left:0,i=r?r.bottom-r.top:0,s={x:r?(r.left+r.right)/2:0,y:r?(r.top+r.bottom)/2:0},a=typeof e.strokeWidth=="number"?e.strokeWidth:1,l=typeof e.left=="number"?e.left:s.x+(o+a)*dr(e.originX),u=typeof e.top=="number"?e.top:s.y+(i+a)*dr(e.originY);return{...e,type:e.type??"Path",path:t??[],width:o,height:i,pathOffset:s,left:l,top:u}};var Qv=(n,e={})=>{let[t,r,o,i]=n,s=Math.abs(o-t),a=Math.abs(i-r),l=(t+o)/2,u=(r+i)/2,c=typeof e.strokeWidth=="number"?e.strokeWidth:1,h=typeof e.left=="number"?e.left:l+(s+c)*dr(e.originX),d=typeof e.top=="number"?e.top:u+(a+c)*dr(e.originY),f=t<=o?-1:1,m=r<=i?-1:1;return{...e,type:e.type??"Line",width:s,height:a,left:h,top:d,x1:f*s/2||0,y1:m*a/2||0,x2:-f*s/2||0,y2:-m*a/2||0}},Zv=(n,e={},t="Polygon")=>{let r=1/0,o=1/0,i=-1/0,s=-1/0;for(let m of n)m.x<r&&(r=m.x),m.y<o&&(o=m.y),m.x>i&&(i=m.x),m.y>s&&(s=m.y);let a=!Number.isFinite(r),l=a?0:i-r,u=a?0:s-o,c={x:a?0:(r+i)/2,y:a?0:(o+s)/2},h=typeof e.strokeWidth=="number"?e.strokeWidth:1,d=typeof e.left=="number"?e.left:c.x+(l+h)*dr(e.originX),f=typeof e.top=="number"?e.top:c.y+(u+h)*dr(e.originY);return{...e,type:e.type??t,points:n,width:l,height:u,pathOffset:c,left:d,top:f}};export{ie as AnimatedNode,ry as COMPAT_PROTOCOL_VERSION,Le as CompatHistoryActions,hr as CompatObject,nn as CompatPoint,L as ElementTypes,ru as EngineCanvas,Ao as EngineDocument,Hn as EventBus,xi as GIF_TYPES,J as GroupNode,dt as IMAGE_LIKE_TYPES,ft as LINE_TYPES,Lr as LineNode,ot as MASK_TYPES,ae as MaskNode,gi as PUZZLE_TYPES,Nr as PathNode,ou as Point,le as PuzzleNode,Un as SHAPE_TYPES,$n as SOLID_TYPES,_s as ScaleLimit,ct as SceneNode,yn as ShapeNode,Wa as SvgExporter,ag as TEXT_ALIGN_VALUES,an as TEXT_TYPES,te as TableNode,fe as TextAlignValues,ye as TextNode,yi as VIDEO_TYPES,Zn as activePsdTextWarp,Dc as anchorStyleAt,yh as applyWarpDistortion,Xe as arcTextKind,qv as assembleGroupRaw,oy as attachDocumentEventBridge,hu as attachTableFacade,Ml as bakeArcText,Jc as bakePsdWarpText,Wg as bakeTextEffects,Cl as bakeWarpedText,Xn as boundsFromACoors,Mo as buildAllSelection,iu as buildEngineShapePath,Qv as buildLineRaw,Kv as buildPathRaw,Zv as buildPolyRaw,Yl as buildScene,xn as buildSelectionRange,jv as buildTextGlyphPathData,pl as buildWarpSurfaceGridOverWindow,vx as clearAlphaHitMask,At as composeMatrix,bo as compositeWarpEffects,Et as computeArcTextLayout,Rl as computePuzzleItems,Rv as createEngineWarpvasFacade,Ct as createNode,Kc as decodeAnimatedImage,Nb as decomposeOwnMatrix,du as deriveArcCharTransformations,Ni as evaluateWarpMesh,_a as fboPixelsToImageData,mu as findParentGroupOf,ml as generatePsdWarpMesh,xh as generateStyleWarpMesh,Fe as getBoundsOfPath,we as getCellData,fn as glyphStyleAt,gn as glyphStyleOf,dn as identityWarpMesh,jc as imageMaskDeclOf,yp as imageMaskOffset,To as insertTableColumn,wo as insertTableRow,ve as invert,bl as invertBilinearCell,jr as isAnimatedPng,US as isAnimatedPngFile,$S as isAnimatedPngUrl,VS as isAnimatedWebPFile,qS as isAnimatedWebPUrl,Tu as isCanvasPerfEnabled,Lb as isEngineRasterExportEnabled,Ib as isEngineSvgExportEnabled,fl as isGeneratableWarpStyle,Wr as isGroupWidthHandleNode,$t as isJustifyFamilyAlign,sl as isJustifyVariantAlign,qa as isSnapGuideEnabled,ro as isStretchAlign,Kt as isTextBitmapState,jt as layoutTextbox,hl as lineDecorationRuns,Je as loadImageElement,Eu as markCanvasPerfCounter,Sp as maskOutsideRects,xp as maskPixelsToAlpha,lt as masterPosition,So as mergeTableCells,j as multiply,Vi as normalizeSelectionAfterRemove,$a as objectACoors,Ut as objectCenter,ge as objectOriginFromCenter,Gn as objectOwnMatrix,ee as parseColor,Ce as parsePathData,Mt as parsePsdEffects,co as pathBackgroundSpecOf,Bt as pathEditKindOf,Jn as planTextHighlight,li as recordCanvasPerfDuration,it as rectCornerRadii,ss as refitGroupShells,_l as removeTableColumn,Il as removeTableRow,yv as renderPlacedSmartObjectLayer,po as renderTextRuns,Gi as renderVerticalRuns,Ar as rowColCoverage,Zr as sceneToClipMatrix,ze as selectionBounds,Vv as serializePageToSvg,fy as setGroupWidth,xo as setTableColumnWidth,yo as setTableRowHeight,Po as textBitmapFillAlpha,Ge as textTransformKindOf,Q as transformPoint,ui as transformedDimensions,se as typeKeyOf,vo as unmergeTableCells,Vt as verticalGlyphOps,Mv as wrapCompatObject};