calcplot 0.0.1 → 0.0.2
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/README.md +82 -52
- package/dist/calcplot-client-deno.js +46 -1
- package/dist/calcplot-client.js +46 -1
- package/dist/calcplot.js +9 -10
- package/dist/index.js +9 -10
- package/package.json +19 -9
- package/dist/calcplot-client-deno.js.map +0 -7
- package/dist/calcplot-client.js.map +0 -7
package/dist/calcplot-client.js
CHANGED
|
@@ -1 +1,46 @@
|
|
|
1
|
-
"use strict";var CalcPlotClient=(()=>{var b=class{static parseFunction(t){let e=t.trim(),i=e.match(/^\(([^)]+)\)\s*=>\s*\{([\s\S]*)\}$/);if(i)return i[2].trim();let n=e.match(/^(\w+)\s*=>\s*\{([\s\S]*)\}$/);if(n)return n[2].trim();let r=e.match(/^\(([^)]+)\)\s*=>\s*(.+)$/s);if(r)return`return ${r[2].trim()}`;let s=e.match(/^(\w+)\s*=>\s*(.+)$/s);if(s)return`return ${s[2].trim()}`;let c=e.match(/^function\s*\([^)]*\)\s*\{([\s\S]*)\}$/);return c?c[1].trim():e}static createFunction(t,e){return new Function(...t,e)}static parseAndCreateFunction(t,e){let i=this.parseFunction(e);return this.createFunction(t,i)}};function _(u){return{state:u.state,params:u.params,derivatives:D(u.derivatives),events:u.events?D(u.events):void 0}}function X(u){let t={};for(let[e,i]of Object.entries(u))t[e]={type:i.type||"slider",min:i.min,max:i.max,default:i.default,label:i.label||e,step:i.step||.01};return t}function J(u){return{times:u.times,states:u.states}}function K(u){let t={};for(let[e,i]of Object.entries(u))t[e]=i.default;return t}function Q(serialized){let functions={};for(let[key,fnStr]of Object.entries(serialized))try{fnStr.includes("=>")?functions[key]=eval(`(${fnStr})`):fnStr.startsWith("function")?functions[key]=eval(`(${fnStr})`):functions[key]=eval(`(state, params) => ${fnStr}`)}catch(u){console.error("Error deserializing function",key,u),functions[key]=()=>0}return functions}function D(u){let t={};for(let[e,i]of Object.entries(u))typeof i=="function"?t[e]=i.toString():typeof i=="object"&&i!==null?t[e]=JSON.stringify(i):t[e]=String(i);return t}var R=class{constructor(t){this.log=t}simulateTrajectory(t,e,i){if(!e||typeof e!="object")throw new Error(`Invalid initialState: expected object, got ${typeof e}. Value: ${e}`);let s={...t.model?.params||{},...i||{}},{dt:c=.01,maxTime:a=10}=t.options||{},o=[],l={};Object.keys(e).forEach(p=>{l[p]=[]});let h={...e},d=0,f=t.model?.derivatives||t.derivatives;if(!f)throw new Error("No derivatives found in data.model.derivatives or data.derivatives");let x={};for(Object.entries(f).forEach(([p,m])=>{x[p]=b.parseAndCreateFunction(["s","p"],m)});d<=a&&h.y>=0;){o.push(d),Object.keys(h).forEach(m=>{l[m].push(h[m])});let p={};Object.entries(x).forEach(([m,v])=>{p[m]=v(h,s)}),Object.keys(h).forEach(m=>{p[m]!==void 0&&(h[m]+=p[m]*c)}),d+=c}return{times:o,states:l}}parseInitialFunction(t){try{return b.parseAndCreateFunction(["p"],t)}catch(e){throw console.error("\u274C parseInitialFunction error:",e),e}}};var k=class{constructor(t,e,i=.1){this.canvasWidth=t;this.canvasHeight=e;this.padding=i;this.dataBounds={x:[0,1],y:[0,1]};this.viewBounds={x:[0,1],y:[0,1]};this.plotArea=this.calculateDefaultPlotArea(),this.originalViewBounds={...this.viewBounds}}calculateDefaultPlotArea(){let e=this.canvasWidth-50,i=50,n=this.canvasHeight-80;return{left:80,top:i,right:e,bottom:n,width:e-80,height:n-i}}updateDataBounds(t,e){if(t.length===0||e.length===0)return;let i=Math.min(...t),n=Math.max(...t),r=Math.min(...e),s=Math.max(...e);i===n?this.dataBounds.x=[i-1,n+1]:this.dataBounds.x=[i,n],r===s?this.dataBounds.y=[r-1,s+1]:this.dataBounds.y=[r,s]}autoScale(){let[t,e]=this.dataBounds.x,[i,n]=this.dataBounds.y,r=e-t||1,s=n-i||1;this.originalViewBounds={x:[t-r*this.padding,e+r*this.padding],y:[i-s*this.padding,n+s*this.padding]},this.viewBounds={...this.originalViewBounds}}adjustAspectRatio(t="auto"){if(t==="auto"){this.originalViewBounds&&(this.viewBounds={...this.originalViewBounds});return}let[e,i]=this.viewBounds.x,[n,r]=this.viewBounds.y,s=i-e,c=r-n;if(s===0||c===0)return;let a=this.plotArea.width/s,o=this.plotArea.height/c;if(a!==o)if(a<o){let l=s*(this.plotArea.height/this.plotArea.width),h=(n+r)/2;this.viewBounds.y=[h-l/2,h+l/2]}else{let l=c*(this.plotArea.width/this.plotArea.height),h=(e+i)/2;this.viewBounds.x=[h-l/2,h+l/2]}}toCanvas(t,e){let[i,n]=this.viewBounds.x,[r,s]=this.viewBounds.y,c=n-i||1,a=s-r||1,o=this.plotArea.left+(t-i)/c*this.plotArea.width,l=this.plotArea.bottom-(e-r)/a*this.plotArea.height;return[o,l]}getViewBounds(){return{...this.viewBounds}}getPlotArea(){return{...this.plotArea}}setViewBounds(t){this.viewBounds={...t},this.originalViewBounds={...t}}updatePlotArea(t){this.plotArea={...this.plotArea,...t,width:(t.right??this.plotArea.right)-(t.left??this.plotArea.left),height:(t.bottom??this.plotArea.bottom)-(t.top??this.plotArea.top)}}isInPlotArea(t,e){let[i,n]=this.toCanvas(t,e);return i>=this.plotArea.left&&i<=this.plotArea.right&&n>=this.plotArea.top&&n<=this.plotArea.bottom}getDataCenter(){let[t,e]=this.dataBounds.x,[i,n]=this.dataBounds.y;return[(t+e)/2,(i+n)/2]}};var y=class{static calculateNiceStep(t,e){if(t<=0)return 1;let i=t/e,n=Math.floor(Math.log10(i)),r=i/Math.pow(10,n),s;return r<=1.5?s=1:r<=3?s=2:r<=7?s=5:s=10,s*Math.pow(10,n)}static formatTickLabel(t,e){if(e>=1e3||e<.01&&e>0)return t.toExponential(1);let i=0;return e<1&&(i=Math.ceil(-Math.log10(e))),t.toFixed(i).replace(/\.0+$/,"")}static interpolateData(t,e,i=100){if(t.length<2)return{x:t,y:e};let n=[],r=[];for(let s=0;s<i;s++){let a=s/(i-1)*(t.length-1),o=Math.floor(a),l=Math.min(o+1,t.length-1),h=a-o;n.push(t[o]*(1-h)+t[l]*h),r.push(e[o]*(1-h)+e[l]*h)}return{x:n,y:r}}static getColorByIndex(t){let e=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];return e[t%e.length]}};var E=class{constructor(t,e,i,n){this.ctx=t;this.getBounds=e;this.toCanvas=i;this.getPlotArea=n}drawGrid(t={}){let{showGrid:e=!0,gridColor:i="#e0e0e0"}=t;if(!e)return;let n=this.getBounds(),r=this.getPlotArea(),{xTicks:s,yTicks:c}=this.calculateTicks();this.ctx.save(),this.ctx.strokeStyle=i,this.ctx.lineWidth=1,this.ctx.setLineDash([2,2]),s.values.forEach(a=>{if(a===0)return;let[o,l]=this.toCanvas(a,n.y[0]),[,h]=this.toCanvas(a,n.y[1]);this.ctx.beginPath(),this.ctx.moveTo(o,Math.max(l,r.top)),this.ctx.lineTo(o,Math.min(h,r.bottom)),this.ctx.stroke()}),c.values.forEach(a=>{if(a===0)return;let[o,l]=this.toCanvas(n.x[0],a),[h]=this.toCanvas(n.x[1],a);this.ctx.beginPath(),this.ctx.moveTo(Math.max(o,r.left),l),this.ctx.lineTo(Math.min(h,r.right),l),this.ctx.stroke()}),this.ctx.restore()}drawAxes(t,e,i={}){let{showTicks:n=!0,showLabels:r=!0}=i,{xTicks:s,yTicks:c}=this.calculateTicks();this.ctx.save(),this.ctx.strokeStyle="#666",this.ctx.fillStyle="#666",this.ctx.lineWidth=2,this.ctx.font="12px sans-serif";let[a,o]=this.toCanvas(0,0),[l,h]=this.toCanvas(0,0),d=this.getPlotArea();o>=d.top&&o<=d.bottom&&(this.ctx.beginPath(),this.ctx.moveTo(d.left,o),this.ctx.lineTo(d.right,o),this.ctx.stroke()),l>=d.left&&l<=d.right&&(this.ctx.beginPath(),this.ctx.moveTo(l,d.top),this.ctx.lineTo(l,d.bottom),this.ctx.stroke()),(n||r)&&(this.ctx.textAlign="center",this.ctx.textBaseline="top",s.values.forEach(f=>{let[x,p]=this.toCanvas(f,0),m=this.getPlotArea();x>=m.left&&x<=m.right&&(n&&(this.ctx.beginPath(),this.ctx.moveTo(x,p-5),this.ctx.lineTo(x,p+5),this.ctx.stroke()),r&&f!==0&&this.ctx.fillText(s.labels[s.values.indexOf(f)],x,p+10))}),this.ctx.textAlign="right",this.ctx.textBaseline="middle",c.values.forEach(f=>{let[x,p]=this.toCanvas(0,f),m=this.getPlotArea();p>=m.top&&p<=m.bottom&&(n&&(this.ctx.beginPath(),this.ctx.moveTo(x-5,p),this.ctx.lineTo(x+5,p),this.ctx.stroke()),r&&f!==0&&this.ctx.fillText(c.labels[c.values.indexOf(f)],x-10,p))})),this.ctx.restore(),(t||e)&&(this.ctx.save(),this.ctx.fillStyle="#333",this.ctx.font="14px sans-serif",t&&(this.ctx.textAlign="center",this.ctx.textBaseline="top",this.ctx.fillText(t,d.left+d.width/2,d.bottom+40)),e&&(this.ctx.save(),this.ctx.textAlign="center",this.ctx.translate(25,d.top+d.height/2),this.ctx.rotate(-Math.PI/2),this.ctx.fillText(e,0,0),this.ctx.restore()),this.ctx.restore())}calculateTicks(){let t=this.getBounds(),e=t.x[1]-t.x[0],i=t.y[1]-t.y[0],n=y.calculateNiceStep(e,6),r=y.calculateNiceStep(i,5),s=Math.ceil(t.x[0]/n)*n,c=Math.ceil(t.y[0]/r)*r,a=[],o=[];for(let l=s;l<=t.x[1];l+=n)a.push(l);for(let l=c;l<=t.y[1];l+=r)o.push(l);return{xTicks:{values:a,labels:a.map(l=>y.formatTickLabel(l,n)),step:n},yTicks:{values:o,labels:o.map(l=>y.formatTickLabel(l,r)),step:r}}}};var z=class{constructor(t,e,i){this.ctx=t;this.toCanvas=e;this.getPlotArea=i}plot(t,e,i={}){if(t.length===0)return;let{lineColor:n="#3b82f6",lineWidth:r=2,marker:s="none",smooth:c=!0}=i;this.ctx.save(),this.ctx.beginPath(),this.ctx.rect(this.getPlotArea().left,this.getPlotArea().top,this.getPlotArea().width,this.getPlotArea().height),this.ctx.clip(),this.ctx.strokeStyle=n,this.ctx.fillStyle=n,this.ctx.lineWidth=r,this.ctx.lineJoin="round",this.ctx.lineCap="round";let a=c&&t.length>2?y.interpolateData(t,e):{x:t,y:e};this.ctx.beginPath();for(let o=0;o<a.x.length;o++){let[l,h]=this.toCanvas(a.x[o],a.y[o]);o===0?this.ctx.moveTo(l,h):this.ctx.lineTo(l,h)}if(this.ctx.stroke(),s!=="none")for(let o=0;o<t.length;o++){let[l,h]=this.toCanvas(t[o],e[o]);s==="circle"?(this.ctx.beginPath(),this.ctx.arc(l,h,3,0,Math.PI*2),this.ctx.fill()):s==="square"&&this.ctx.fillRect(l-3,h-3,6,6)}this.ctx.restore()}drawVectors(t,e,i,n,r={}){let{scale:s=this.calculateAutoScale(i,n),color:c="#10b981",headSize:a=8}=r;this.ctx.save(),this.ctx.beginPath(),this.ctx.rect(this.getPlotArea().left,this.getPlotArea().top,this.getPlotArea().width,this.getPlotArea().height),this.ctx.clip(),this.ctx.strokeStyle=c,this.ctx.fillStyle=c,this.ctx.lineWidth=2;for(let o=0;o<t.length;o++){let l=this.toCanvas(t[o],e[o]),h=this.toCanvas(t[o]+i[o]/s,e[o]+n[o]/s);this.ctx.beginPath(),this.ctx.moveTo(l[0],l[1]),this.ctx.lineTo(h[0],h[1]),this.ctx.stroke(),this.drawArrowhead(h[0],h[1],l,a)}this.ctx.restore()}calculateAutoScale(t,e){let i=t.map((r,s)=>Math.sqrt(r*r+e[s]*e[s])),n=Math.max(...i);return n>0?n/30:1}drawArrowhead(t,e,i,n){let r=Math.atan2(e-i[1],t-i[0]);this.ctx.beginPath(),this.ctx.moveTo(t,e),this.ctx.lineTo(t-n*Math.cos(r-Math.PI/6),e-n*Math.sin(r-Math.PI/6)),this.ctx.lineTo(t-n*Math.cos(r+Math.PI/6),e-n*Math.sin(r+Math.PI/6)),this.ctx.closePath(),this.ctx.fill()}};var L=class{constructor(t,e){this.ctx=t;this.getPlotArea=e}drawTitle(t){this.ctx.save(),this.ctx.font="bold 16px sans-serif",this.ctx.fillStyle="#333",this.ctx.textAlign="center",this.ctx.fillText(t,this.getPlotArea().left+this.getPlotArea().width/2,25),this.ctx.restore()}drawAxisLabels(t,e){this.ctx.save(),this.ctx.fillStyle="#333",this.ctx.font="14px sans-serif",t&&(this.ctx.textAlign="center",this.ctx.fillText(t,this.getPlotArea().left+this.getPlotArea().width/2,this.getPlotArea().bottom+40)),e&&(this.ctx.save(),this.ctx.textAlign="center",this.ctx.translate(25,this.getPlotArea().top+this.getPlotArea().height/2),this.ctx.rotate(-Math.PI/2),this.ctx.fillText(e,0,0),this.ctx.restore()),this.ctx.restore()}drawLegend(t,e="top-right"){if(t.length===0)return;this.ctx.save(),this.ctx.font="12px sans-serif";let i=20,n=10,r=30,c=Math.max(...t.map(d=>this.ctx.measureText(d.label).width))+r+n*3,a=t.length*i+n*2,o,l,h=10;switch(e){case"top-right":o=this.getPlotArea().right-c-h,l=this.getPlotArea().top+h;break;case"top-left":o=this.getPlotArea().left+h,l=this.getPlotArea().top+h;break;case"bottom-right":o=this.getPlotArea().right-c-h,l=this.getPlotArea().bottom-a-h;break;case"bottom-left":o=this.getPlotArea().left+h,l=this.getPlotArea().bottom-a-h;break;default:o=this.getPlotArea().right-c-h,l=this.getPlotArea().top+h}this.ctx.fillStyle="rgba(255, 255, 255, 0.95)",this.ctx.strokeStyle="#ccc",this.ctx.lineWidth=1,this.ctx.fillRect(o,l,c,a),this.ctx.strokeRect(o,l,c,a),t.forEach((d,f)=>{let x=l+n+f*i+i/2;this.ctx.strokeStyle=d.color,this.ctx.lineWidth=d.lineStyle?.width||2,d.lineStyle?.dash?this.ctx.setLineDash(d.lineStyle.dash):this.ctx.setLineDash([]),this.ctx.beginPath(),this.ctx.moveTo(o+n,x),this.ctx.lineTo(o+n+r,x),this.ctx.stroke(),this.ctx.fillStyle="#333",this.ctx.setLineDash([]),this.ctx.fillText(d.label,o+n+r+10,x+4)}),this.ctx.restore()}};var T=class{constructor(t,e,i){this.ctx=t;this.width=e;this.height=i;this.bounds=new k(e,i),this.axisRenderer=new E(t,()=>this.bounds.getViewBounds(),(n,r)=>this.bounds.toCanvas(n,r),()=>this.bounds.getPlotArea()),this.data=new z(t,(n,r)=>this.bounds.toCanvas(n,r),()=>this.bounds.getPlotArea()),this.labels=new L(t,()=>this.bounds.getPlotArea())}plot(t,e,i={}){return this.clear(),this.bounds.updateDataBounds(t,e),i.autoScale!==!1&&this.bounds.autoScale(),i.aspectRatio==="equal"?this.bounds.adjustAspectRatio("equal"):this.bounds.adjustAspectRatio("auto"),this.axisRenderer.drawGrid(i),this.axisRenderer.drawAxes(i.xLabel,i.yLabel,i),this.data.plot(t,e,i),i.title&&this.labels.drawTitle(i.title),this.labels.drawAxisLabels(i.xLabel,i.yLabel),this}plotMultiple(t,e={}){this.clear();let i=[],n=[];return t.forEach(r=>{i.push(...r.x),n.push(...r.y)}),this.bounds.updateDataBounds(i,n),e.autoScale!==!1&&this.bounds.autoScale(),e.aspectRatio==="equal"?this.bounds.adjustAspectRatio("equal"):this.bounds.adjustAspectRatio("auto"),this.axisRenderer.drawGrid(e),this.axisRenderer.drawAxes(e.xLabel,e.yLabel,e),t.forEach((r,s)=>{this.data.plot(r.x,r.y,{...e,lineColor:r.color||y.getColorByIndex(s)})}),e.title&&this.labels.drawTitle(e.title),this.labels.drawAxisLabels(e.xLabel,e.yLabel),this}drawVectors(t,e,i,n,r={}){return this.data.drawVectors(t,e,i,n,r),this}addLegend(t,e="top-right"){this.labels.drawLegend(t,e)}clear(){this.ctx.fillStyle="#f8f9fa",this.ctx.fillRect(0,0,this.width,this.height)}setBounds(t){this.bounds.setViewBounds(t)}getPlotArea(){return this.bounds.getPlotArea()}drawGrid(t={}){this.axisRenderer.drawGrid(t)}drawAxis(t={}){this.axisRenderer.drawAxes(t.x,t.y,t)}setBoundsWithAuto(t,e){t.x&&Array.isArray(t.x)?this.setBounds(t):e&&this.setBounds(e)}setBoundsWithAutoAndAspectRatio(t,e){t.x&&Array.isArray(t.x)?this.setBounds(t):e&&(this.setBounds(e),this.bounds.adjustAspectRatio("equal"))}createDrawContext(){let t=this;return{plot:(e,i,n={})=>{t.data.plot(e,i,n)},line:(e,i,n={})=>{let[r,s]=t.bounds.toCanvas(e[0],e[1]),[c,a]=t.bounds.toCanvas(i[0],i[1]);t.ctx.beginPath(),t.ctx.moveTo(r,s),t.ctx.lineTo(c,a),t.ctx.strokeStyle=n.color||"#2563eb",t.ctx.lineWidth=n.width||1,n.dash?t.ctx.setLineDash(n.dash):t.ctx.setLineDash([]),t.ctx.stroke()},circle:(e,i,n={})=>{let[r,s]=t.bounds.toCanvas(e[0],e[1]),c=t.bounds.getViewBounds(),a=t.bounds.getPlotArea(),o=c.x[1]-c.x[0],l=a.width/o,h=i*l;t.ctx.beginPath(),t.ctx.arc(r,s,h,0,2*Math.PI),n.fill&&(t.ctx.fillStyle=n.fill,t.ctx.fill()),n.stroke&&(t.ctx.strokeStyle=n.stroke,t.ctx.lineWidth=n.width||1,t.ctx.stroke())},arrow:(e,i,n={})=>{let[r,s]=t.bounds.toCanvas(e[0],e[1]),[c,a]=t.bounds.toCanvas(i[0],i[1]),o=n.headSize||10;t.ctx.beginPath(),t.ctx.moveTo(r,s),t.ctx.lineTo(c,a),t.ctx.strokeStyle=n.color||"#2563eb",t.ctx.lineWidth=n.width||2,t.ctx.stroke();let l=Math.atan2(a-s,c-r);t.ctx.beginPath(),t.ctx.moveTo(c,a),t.ctx.lineTo(c-o*Math.cos(l-Math.PI/6),a-o*Math.sin(l-Math.PI/6)),t.ctx.moveTo(c,a),t.ctx.lineTo(c-o*Math.cos(l+Math.PI/6),a-o*Math.sin(l+Math.PI/6)),t.ctx.stroke()},text:(e,i,n={})=>{let[r,s]=t.bounds.toCanvas(e[0],e[1]);t.ctx.font=`${n.size||14}px ${n.font||"system-ui"}`,t.ctx.fillStyle=n.color||"#1f2937",t.ctx.fillText(i,r,s)}}}debugInfo(){return{viewBounds:this.bounds.getViewBounds(),plotArea:this.bounds.getPlotArea(),dataBounds:this.bounds.dataBounds}}};var w=class{constructor(t,e=800,i=600,n){this.container=t,this.log=n,this.targetWidth=e,this.targetHeight=i,this.canvas=this.createCanvas(e,i),this.renderer=new T(this.canvas.getContext("2d"),this.canvas.width,this.canvas.height),this.setupResizeObserver()}createCanvas(t,e){let i=document.createElement("div");i.innerHTML=`<canvas width="${t}" height="${e}"></canvas>`;let n=i.firstChild;return n.style&&(n.style.width="100%",n.style.height="100%",n.style.display="block"),this.container.appendChild(n),n}setupResizeObserver(){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(t=>{for(let e of t){let{width:i,height:n}=e.contentRect;(i!==this.targetWidth||n!==this.targetHeight)&&this.updateCanvasSize(i,n)}}),this.resizeObserver.observe(this.container))}updateCanvasSize(t,e){this.canvas.width=Math.floor(t),this.canvas.height=Math.floor(e),this.targetWidth=Math.floor(t),this.targetHeight=Math.floor(e),this.renderer=new T(this.canvas.getContext("2d"),this.canvas.width,this.canvas.height),this.currentData&&this.renderInternal(this.currentData)}renderInternal(t){let e=t.layers||[];t.viewDescriptor&&t.viewDescriptor.layers&&(e=t.viewDescriptor.layers),this.renderer.clear();let i=e.find(a=>a.type==="bounds");if(i&&i.bounds){console.log("Found explicit bounds:",JSON.stringify(i.bounds));let a=this.calculateBoundsFromTimeline(t.timeline),l=e.find(h=>h.type==="axis")?.options?.aspectRatio==="equal";console.log("Has aspectRatio equal:",l),l?this.renderer.setBoundsWithAutoAndAspectRatio(i.bounds,a):this.renderer.setBoundsWithAuto(i.bounds,a)}else{console.log("No explicit bounds found, using auto bounds");let a=this.calculateBoundsFromTimeline(t.timeline,e);this.renderer.setBounds(a)}let n={grid:1,axis:2,plot:3},r=e.filter(a=>a.type!=="bounds").sort((a,o)=>(n[a.type]||999)-(n[o.type]||999)),s=[],c=[];if(r.forEach((a,o)=>{switch(a.type){case"grid":this.renderer.drawGrid(a.options||{});break;case"axis":this.renderer.drawAxis(a.options||{});break;case"plot":if(a.selector){a.options?.label&&s.push({label:a.options.label,color:a.options.color||"#2563eb",lineStyle:{width:a.options.lineWidth||2,dash:a.options.dash||[]}});let l=this.extractPlotData(t.timeline,a);l&&c.push({x:l.xValues,y:l.yValues,color:a.options?.color})}break;case"scene":a.draw&&this.renderScene(t.timeline,a);break;default:break}}),c.length>0){let a={},o=r.find(l=>l.type==="axis");o&&(a=o.options||{}),this.renderer.plotMultiple(c,{...t.options,aspectRatio:a.aspectRatio,autoScale:!1})}s.length>0&&this.renderer.addLegend(s,"top-right")}render(t){t.timeline&&(this.currentData=t,this.renderInternal(t))}extractPlotData(t,e){let{selector:i}=e,n=!1;try{let s={x:0,y:0},c=b.parseAndCreateFunction(["s"],i)(s);n=Array.isArray(c)&&c.length===2}catch{n=!1}let r;try{r=b.parseAndCreateFunction(["s"],i)}catch(s){return this.log("\u26A0\uFE0F Failed to compile selector:",s),null}if(n){let c=t.times.map((l,h)=>{let d=Object.keys(t.states).reduce((f,x)=>(f[x]=t.states[x][h],f),{});return r(d)}).filter(l=>Array.isArray(l)&&l.length===2&&typeof l[0]=="number"&&typeof l[1]=="number"),a=c.map(l=>l[0]),o=c.map(l=>l[1]);return{xValues:a,yValues:o}}else{let s=t.times.map((c,a)=>{let o=Object.keys(t.states).reduce((l,h)=>(l[h]=t.states[h][a],l),{});return r(o)});return{xValues:t.times,yValues:s}}}renderPlot(t,e){let{selector:i,options:n={}}=e,r=!1;try{let c={x:0,y:0},a=b.parseAndCreateFunction(["s"],i)(c);r=Array.isArray(a)&&a.length===2}catch{r=!1}let s;try{s=b.parseAndCreateFunction(["s"],i),this.log("\u2705 selector created successfully")}catch(c){this.log("\u26A0\uFE0F Failed to compile selector:",c),s=a=>0}if(r){let a=t.times.map((h,d)=>{let f=Object.keys(t.states).reduce((x,p)=>(x[p]=t.states[p][d],x),{});return s(f)}).filter(h=>Array.isArray(h)&&h.length===2&&typeof h[0]=="number"&&typeof h[1]=="number"),o=a.map(h=>h[0]),l=a.map(h=>h[1]);this.renderer.plot(o,l,n)}else{let c=t.times.map((a,o)=>{let l=Object.keys(t.states).reduce((h,d)=>(h[d]=t.states[d][o],h),{});return s(l)});this.renderer.plot(t.times,c,n)}}renderScene(t,e){let{draw:i}=e;if(!i)return;let n;try{n=b.parseAndCreateFunction(["ctx","state"],i)}catch(r){this.log("\u26A0\uFE0F Failed to compile scene function:",r);return}t.times.forEach((r,s)=>{let c=Object.keys(t.states).reduce((a,o)=>(a[o]=t.states[o][s],a),{});try{n(this.renderer.createDrawContext(),c)}catch(a){this.log("\u26A0\uFE0F Error in scene function:",a)}})}renderExplore(t,e){this.currentTimeline=e,this.render({type:"view",timeline:e,layers:t.layers,options:t.options,viewDescriptor:t.viewDescriptor})}calculateBoundsFromTimeline(t,e){let i=1/0,n=-1/0,r=1/0,s=-1/0;if(e){let o=e.filter(l=>l.type==="plot"&&l.selector);for(let l of o)try{let h=b.parseAndCreateFunction(["s"],l.selector),f=h({x:0,y:0});if(Array.isArray(f)&&f.length===2){let p=t.times.map((m,v)=>{let O=Object.keys(t.states).reduce((C,S)=>(C[S]=t.states[S][v],C),{});return h(O)}).filter(m=>Array.isArray(m)&&m.length===2&&typeof m[0]=="number"&&typeof m[1]=="number");for(let m of p)i=Math.min(i,m[0]),n=Math.max(n,m[0]),r=Math.min(r,m[1]),s=Math.max(s,m[1])}else{let p=t.times.map((m,v)=>{let O=Object.keys(t.states).reduce((C,S)=>(C[S]=t.states[S][v],C),{});return h(O)}).filter(m=>typeof m=="number");i=Math.min(i,...t.times),n=Math.max(n,...t.times),r=Math.min(r,...p),s=Math.max(s,...p)}}catch(h){this.log("\u26A0\uFE0F Failed to analyze selector for bounds:",h)}}i===1/0&&t.times&&(i=Math.min(...t.times),n=Math.max(...t.times)),i===1/0&&(i=0),n===-1/0&&(n=10),r===1/0&&(r=-10),s===-1/0&&(s=10);let c=(n-i)*.1||1,a=(s-r)*.1||1;return{x:[i-c,n+c],y:[r-a,s+a]}}};function g(u,t={},...e){let i=document.createElement(u);return Object.entries(t).forEach(([n,r])=>{n==="className"?i.className=r:n.startsWith("data-")?i.setAttribute(n,String(r)):n in i?i[n]=r:i.setAttribute(n,String(r))}),e.flat().forEach(n=>{typeof n=="string"?i.appendChild(document.createTextNode(n)):n instanceof HTMLElement&&i.appendChild(n)}),i}var V=(u={},...t)=>g("div",u,...t),j=(u={},...t)=>g("span",u,...t),F=(u={})=>g("input",u),H=(u={},...t)=>g("label",u,...t);function A(u,t){let e=`input-${t.id}`,i=`val-${t.id}`,n=j({className:"value-display",id:i},typeof t.value=="number"?t.value.toFixed(2):String(t.value)),r=F({type:"range",id:e,min:String(t.control.min),max:String(t.control.max),step:String(t.control.step||.01),value:String(t.value),"data-slider-id":t.id});r.addEventListener("input",a=>{let o=parseFloat(a.target.value);n.textContent=o.toFixed(2),t.onChange&&t.onChange(t.id,o)});let s=H({htmlFor:e},t.control.label),c=V({className:"control-group"},s,r,n);return u.appendChild(c),r}function M(u,t){let e=`input-${t.id}`,i=F({type:"checkbox",id:e,checked:t.value||!1,"data-checkbox-id":t.id});i.addEventListener("change",s=>{let c=s.target.checked;t.onChange&&t.onChange(t.id,c)});let n=H({htmlFor:e},t.control.label),r=V({className:"control-group"},n,i);return u.appendChild(r),i}var I=class{constructor(t){this.layers=[];this.timeline=t}scene(t){return this.layers.push({type:"scene",draw:this.serializeFunction(t)}),this}plot(t,e={}){let i=this.detectParametricSelector(t);return this.layers.push({type:"plot",selector:this.serializeFunction(t),parametric:i,options:{color:"#2563eb",lineWidth:2,fill:!1,dash:[],label:"",alpha:1,...e}}),this}vector(t,e,i={}){return this.layers.push({type:"vector",at:this.serializeFunction(t),dir:this.serializeFunction(e),options:{color:"#0ff",scale:1,width:2,...i}}),this}bounds(t){return this.layers.push({type:"bounds",bounds:t}),this}grid(t={}){return this.layers.push({type:"grid",options:t}),this}axis(t={}){return this.layers.push({type:"axis",options:t}),this}getLayers(){return[...this.layers]}getTimeline(){return this.timeline}setTimeline(t){this.timeline=t}serializeFunction(t){return t.toString()}detectParametricSelector(t){try{let i=t({x:1,y:2,z:3});return Array.isArray(i)&&i.length===2}catch{return!1}}toDescriptor(){return{timeline:{times:this.timeline?.times||[],states:this.timeline?.states||{}},layers:this.layers}}executeWithTimeline(t){let e=this.timeline;this.timeline=t;let i=this.toDescriptor();return this.timeline=e,i}};function P(u){return new I(u)}typeof globalThis<"u"&&(globalThis.CalcPlotComponents={createSlider:A,createCheckbox:M,view:P});function $(u,t,e,i){i(" Creating controls for:",Object.keys(u.params));let n=g("div",{style:"padding: 10px; border-bottom: 1px solid #ccc;"});t.appendChild(n),Object.entries(u.params).forEach(([r,s])=>{if(s.type==="slider"){let c=window.CalcPlotComponents.createSlider;c?c(n,{id:r,control:s,value:s.default,onChange:(a,o)=>{e()}}):i("\u274C createSlider not available")}else if(s.type==="checkbox"){let c=window.CalcPlotComponents.createCheckbox;c?c(n,{id:r,control:s,value:s.default,onChange:(a,o)=>{i(`\u2611\uFE0F Checkbox ${a} changed to ${o}`),e()}}):i("\u274C createCheckbox not available")}})}function W(u,t,e,i){let n=g("div",{style:"display: flex; width: 100%; height: 100%;"});return u.appendChild(n),n}function N(u,t,e,i,n){let r={columns:u.length,rows:1,gaps:10};return u.map(s=>{let c=g("div",{style:"flex: 1; width: 0; height: 100%;"});return t.appendChild(c),new w(c,e/r.columns,i/r.rows,n)})}function q(u,t,e,i,n,r){let s={columns:t.length,rows:1,gaps:10};t.forEach((c,a)=>{let o;if(c.layers&&Array.isArray(c.layers))o={timeline:{times:e.times,states:e.states},layers:c.layers};else throw new Error("Invalid view configuration: expected layers array");u[a].render({type:"view",timeline:e,layers:o.layers,width:n/s.columns,height:r/s.rows})})}function G(u,t,e){e(" Initializing explore mode...");try{let l=function(){let h={};Object.entries(u.params).forEach(([d,f])=>{let x=document.getElementById(`input-${d}`);x?h[d]=parseFloat(x.value):h[d]=f.default});try{let d=new R(e),x=d.parseInitialFunction(u.initial)(h),p=d.simulateTrajectory(u,x,h);if(r)q(o,n,p,h,s,c);else{let m=n[0];if(m){let v;if(m.layers&&Array.isArray(m.layers))v={timeline:{times:p.times,states:p.states},layers:m.layers};else throw new Error("Invalid view configuration: expected layers array");o[0].render({type:"view",timeline:p,layers:v.layers,width:s,height:c})}}}catch(d){e("\u274C Error in simulation:",d.message)}};var i=l;let n=u.views||[],r=n.length>1,s=u.width||800,c=u.height||600;u.params&&$(u,t,l,e);let a=r?W(t,s,c,10):t,o=r?N(n,a,s,c,e):[new w(a,s,c,e)];l(),e(`\u2705 ${r?"Multi-view":"Single"} explore mode initialized`)}catch(n){e("\u274C Error in explore initialization:",n.message)}}function U(u,t,e){e("\u{1F4CA} Initializing show mode...");try{let i=u.views||[];if(i.length>1){let r=u.layout||{columns:i.length,rows:1,gaps:10},s=u.width||800,c=u.height||600,a=g("div",{style:`display: flex; flex-wrap: wrap; gap: ${r.gaps}px; width: ${s}px; height: ${c}px;`});t.appendChild(a),i.forEach(o=>{let l=g("div",{style:"flex: 1 1 calc(50% - 5px); min-width: 300px; height: calc(50% - 5px);"});a.appendChild(l),new w(l,o.width||s/r.columns,o.height||c/r.rows,e).render(o)}),e("\u2705 Multi-view show mode initialized")}else{let r=i[0];r&&new w(t,r.width||800,r.height||600,e).render(r),e("\u2705 Show mode initialized")}}catch(i){e("\u274C Error in show initialization:",i.message)}}function Y(u,t,e){e("\u{1F4CA} Initializing compare mode...");try{new w(t,u.width||800,u.height||600,e).render(u),e("\u2705 Compare mode initialized")}catch(i){e("\u274C Error in compare initialization:",i.message)}}function B(u,t,e){let i=e||function(...r){console.log("[calcplot]",...r)};i("\u{1F680} Starting CalcPlot...");let n=t||window.calcPlotData;if(!n){i("\u274C No calcplot data found");return}if(!u){i("\u274C No container provided - visualization skipped");return}i("\u{1F4E6} Data received:",n.type),i("\u{1F4E6} Using container:",u.id||"unnamed"),n.type==="explore"?G(n,u,i):n.type==="show"?U(n,u,i):n.type==="compare"?Y(n,u,i):i("\u274C Unknown data type:",n.type)}typeof globalThis<"u"&&(globalThis.CalcPlotComponents={initializeClient:B,createSlider:A,createCheckbox:M,view:P});typeof globalThis<"u"&&(globalThis.CalcPlotClient={initializeClient:B,createCheckbox:M,createSlider:A,view:P});})();
|
|
1
|
+
"use strict";var CalcPlotClient=(()=>{function P(t,e={},...r){let n=document.createElement(t);return Object.entries(e).forEach(([i,o])=>{i==="className"?n.className=o:i.startsWith("data-")?n.setAttribute(i,String(o)):i in n?n[i]=o:n.setAttribute(i,String(o))}),r.flat().forEach(i=>{typeof i=="string"?n.appendChild(document.createTextNode(i)):i instanceof HTMLElement&&n.appendChild(i)}),n}var Qt=(t={},...e)=>P("div",t,...e),Nr=(t={},...e)=>P("span",t,...e),Jt=(t={})=>P("input",t),te=(t={},...e)=>P("label",t,...e);function tt(t,e){let r=`input-${e.id}`,n=`val-${e.id}`,i=Nr({className:"value-display",id:n},typeof e.value=="number"?e.value.toFixed(2):String(e.value||0)),o=Jt({type:"range",id:r,min:String(e.control.min),max:String(e.control.max),step:String(e.control.step||.01),value:String(e.value||e.control.default),"data-slider-id":e.id});o.addEventListener("input",l=>{let u=parseFloat(l.target.value);i.textContent=u.toFixed(2),e.onChange&&e.onChange(e.id,u)});let a=te({htmlFor:r},e.control.label),s=Qt({className:"control-group"},a,o,i);return t.appendChild(s),o}function et(t,e){let r=`input-${e.id}`,n=Jt({type:"checkbox",id:r,checked:e.value!==void 0?e.value:e.control.default,"data-checkbox-id":e.id});n.addEventListener("change",a=>{let s=a.target.checked;e.onChange&&e.onChange(e.id,s)});let i=te({htmlFor:r},e.control.label),o=Qt({className:"control-group"},i,n);return t.appendChild(o),n}function Fr(t,e,r){let n={};return e===void 0?n={}:typeof e=="string"?r!==void 0?n={color:e,label:r}:e.startsWith("#")||/^#[0-9A-F]{6}$/i.test(e)?n={color:e}:n={label:e}:n=e,{selector:t,options:n}}function Ir(t,e,r){let n={};return t===void 0?n={}:typeof t=="number"?n={aspectRatio:t}:typeof t=="string"?typeof e=="string"&&typeof r=="number"?n={xLabel:t,yLabel:e,aspectRatio:r}:typeof e=="string"?n={xLabel:t,yLabel:e}:n={xLabel:t}:n=t,{options:n}}var Ze=class{constructor(e){this.layers=[];this.timeline=e}scene(e){return this.layers.push({type:"scene",draw:this.serializeFunction(e)}),this}vector(e,r,n={}){return this.layers.push({type:"vector",at:this.serializeFunction(e),dir:this.serializeFunction(r),options:{color:"#0ff",scale:1,width:2,...n}}),this}bounds(e){return this.layers.push({type:"bounds",bounds:e}),this}grid(e={}){return this.layers.push({type:"grid",options:e}),this}axis(e,r,n){let{options:i}=Ir(e,r,n);return this.layers.push({type:"axis",options:i}),this}plot(e,r,n){let{selector:i,options:o}=Fr(e,r,n),a=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],s=this.detectParametricSelector(i),l=this.layers.filter(u=>u.type==="plot").length;return this.layers.push({type:"plot",selector:this.serializeFunction(i),parametric:s,options:{color:o.color||a[l%a.length],lineWidth:1.5,opacity:1,dash:[],label:"",...o}}),this}phase(e,r={}){return this.plot(e,{color:"#d62728",lineWidth:2,...r})}fill(e,r={}){return this.layers.push({type:"fill",selector:this.serializeFunction(e),options:{color:r.color||"blue",alpha:r.alpha||.2}}),this}axhline(e,r={}){return this.layers.push({type:"refline",options:{orientation:"horizontal",value:e,color:r.color||"gray",linestyle:r.linestyle||"solid",linewidth:r.linewidth||1,label:r.label||"",labelPosition:r.labelPosition||"auto",labelOffset:r.labelOffset||8}}),this}axvline(e,r={}){return this.layers.push({type:"refline",options:{orientation:"vertical",value:e,color:r.color||"gray",linestyle:r.linestyle||"solid",linewidth:r.linewidth||1,label:r.label||"",labelPosition:r.labelPosition||"auto",labelOffset:r.labelOffset||8}}),this}title(e){return this.layers.push({type:"title",options:{text:e}}),this}legend(e={}){return this.layers.push({type:"legend",options:{loc:e.loc||"upper right",frame:e.frame!==!1,alpha:e.alpha||1}}),this}vectorField(e,r={}){return this.layers.push({type:"vectorField",selector:this.serializeFunction(e),options:{gridSize:r.gridSize||20,color:r.color||"gray",alpha:r.alpha||.6,normalize:r.normalize!==!1,scale:r.scale||1}}),this}nullcline(e,r={}){return this.layers.push({type:"nullcline",options:{variable:e,color:r.color||"blue",linestyle:r.linestyle||"dashed",linewidth:r.linewidth||1,label:r.label||""}}),this}poincare(e,r={section:()=>!1}){return this.layers.push({type:"poincare",selector:this.serializeFunction(e),options:{section:e,direction:r.direction||"positive",marker:r.marker||"circle",color:r.color||"red",size:r.size||4}}),this}defaults(){return this.grid().axis()}getLayers(){return[...this.layers]}getTimeline(){return this.timeline}setTimeline(e){this.timeline=e}serializeFunction(e){return e.toString()}detectParametricSelector(e){try{let n=e({x:1,y:2,z:3});return Array.isArray(n)&&n.length===2}catch{return!1}}toDescriptor(){return{timeline:{times:this.timeline?.times||[],states:this.timeline?.states||{}},layers:this.layers}}executeWithTimeline(e){let r=this.timeline;this.timeline=e;let n=this.toDescriptor();return this.timeline=r,n}};function ee(t){return new Ze(t)}var A=class{static parseFunction(e){let r=e.trim(),n=r.match(/^\(([^)]+)\)\s*=>\s*\{([\s\S]*)\}$/);if(n)return n[2].trim();let i=r.match(/^(\w+)\s*=>\s*\{([\s\S]*)\}$/);if(i)return i[2].trim();let o=r.match(/^\(([^)]+)\)\s*=>\s*(.+)$/s);if(o)return`return ${o[2].trim()}`;let a=r.match(/^(\w+)\s*=>\s*(.+)$/s);if(a)return`return ${a[2].trim()}`;let s=r.match(/^function\s*\([^)]*\)\s*\{([\s\S]*)\}$/);return s?s[1].trim():r}static createFunction(e,r){return new Function(...e,r)}static parseAndCreateFunction(e,r){let n=this.parseFunction(r);return this.createFunction(e,n)}};function ao(t){let e={};for(let[r,n]of Object.entries(t))n&&typeof n.when=="function"&&typeof n.then=="function"?e[r]=JSON.stringify({when:n.when.toString(),then:n.then.toString(),once:n.once||!1}):console.warn(`Invalid event ${r}: when and then must be functions`);return e}function Ks(t){return{state:t.state,params:t.params,derivatives:so(t.derivatives),events:t.events?ao(t.events):void 0}}function Zs(t){let e={};if(!t)return e;for(let[r,n]of Object.entries(t))n.type==="slider"?e[r]={type:n.type,min:n.min,max:n.max,default:n.default,label:n.label||r,step:n.step||.01,scale:n.scale}:e[r]={type:n.type,default:n.default,label:n.label||r};return e}function Qs(t){return{times:t.times,states:t.states}}function Js(t){let e={};for(let[r,n]of Object.entries(t))n.type==="slider"?e[r]=n.default:n.type==="checkbox"&&(e[r]=n.default?1:0);return e}function Pr(serialized){let events={};for(let[key,eventStr]of Object.entries(serialized))try{let eventObj=JSON.parse(eventStr);eventObj.when&&eventObj.then&&(events[key]={when:eval(`(${eventObj.when})`),then:eval(`(${eventObj.then})`),once:eventObj.once||!1})}catch(t){console.error("Error deserializing event",key,t)}return events}function tl(serialized){let functions={};for(let[key,fnStr]of Object.entries(serialized))try{fnStr.includes("=>")?functions[key]=eval(`(${fnStr})`):fnStr.startsWith("function")?functions[key]=eval(`(${fnStr})`):functions[key]=eval(`(state, params) => ${fnStr}`)}catch(t){console.error("Error deserializing function",key,t),functions[key]=()=>0}return functions}function so(t){let e={};for(let[r,n]of Object.entries(t))typeof n=="function"?e[r]=n.toString():n!=null?e[r]=String(n):console.warn(`Skipping undefined/null value for key: ${r}`);return e}var re=class{constructor(e){this.log=e}simulateTrajectory(e,r,n){if(!r||typeof r!="object")throw new Error(`Invalid initialState: expected object, got ${typeof r}. Value: ${r}`);let a={...e.model?.params||{},...n||{}},{timeRange:s=[0,10],timeStep:l=.01}=e.options||{},u=[],c={};Object.keys(r).forEach(v=>{c[v]=[]});let f={...r},p=s[0],m=e.model?.derivatives||e.derivatives;if(!m)throw new Error("No derivatives found in data.model.derivatives or data.derivatives");let h={};Object.entries(m).forEach(([v,y])=>{h[v]=A.parseAndCreateFunction(["s","p"],y)});let d=e.model?.events,g={};for(d&&(g=d);p<=s[1];){let v=!1;if(d&&Object.keys(g).length>0){for(let[x,b]of Object.entries(g))if(b.when(f)<0){let _=b.then(f,a);if(_===null||b.once){v=!0;break}_!==null&&(f=_)}}if(v)break;u.push(p),Object.keys(f).forEach(x=>{c[x].push(f[x])});let y={};Object.entries(h).forEach(([x,b])=>{y[x]=b(f,a)}),Object.keys(f).forEach(x=>{y[x]!==void 0&&(f[x]+=y[x]*l)}),p+=l}return{times:u,states:c}}parseInitialFunction(e){try{return A.parseAndCreateFunction(["p"],e)}catch(r){throw console.error("parseInitialFunction error:",r),r}}};function rt(t,e){return t==null||e==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function Qe(t,e){return t==null||e==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function ne(t){let e,r,n;t.length!==2?(e=rt,r=(s,l)=>rt(t(s),l),n=(s,l)=>t(s)-l):(e=t===rt||t===Qe?t:lo,r=t,n=t);function i(s,l,u=0,c=s.length){if(u<c){if(e(l,l)!==0)return c;do{let f=u+c>>>1;r(s[f],l)<0?u=f+1:c=f}while(u<c)}return u}function o(s,l,u=0,c=s.length){if(u<c){if(e(l,l)!==0)return c;do{let f=u+c>>>1;r(s[f],l)<=0?u=f+1:c=f}while(u<c)}return u}function a(s,l,u=0,c=s.length){let f=i(s,l,u,c-1);return f>u&&n(s[f-1],l)>-n(s[f],l)?f-1:f}return{left:i,center:a,right:o}}function lo(){return 0}function Je(t){return t===null?NaN:+t}var Dr=ne(rt),Vr=Dr.right,uo=Dr.left,co=ne(Je).center,tr=Vr;var fo=Math.sqrt(50),po=Math.sqrt(10),mo=Math.sqrt(2);function ie(t,e,r){let n=(e-t)/Math.max(0,r),i=Math.floor(Math.log10(n)),o=n/Math.pow(10,i),a=o>=fo?10:o>=po?5:o>=mo?2:1,s,l,u;return i<0?(u=Math.pow(10,-i)/a,s=Math.round(t*u),l=Math.round(e*u),s/u<t&&++s,l/u>e&&--l,u=-u):(u=Math.pow(10,i)*a,s=Math.round(t/u),l=Math.round(e/u),s*u<t&&++s,l*u>e&&--l),l<s&&.5<=r&&r<2?ie(t,e,r*2):[s,l,u]}function oe(t,e,r){if(e=+e,t=+t,r=+r,!(r>0))return[];if(t===e)return[t];let n=e<t,[i,o,a]=n?ie(e,t,r):ie(t,e,r);if(!(o>=i))return[];let s=o-i+1,l=new Array(s);if(n)if(a<0)for(let u=0;u<s;++u)l[u]=(o-u)/-a;else for(let u=0;u<s;++u)l[u]=(o-u)*a;else if(a<0)for(let u=0;u<s;++u)l[u]=(i+u)/-a;else for(let u=0;u<s;++u)l[u]=(i+u)*a;return l}function Ct(t,e,r){return e=+e,t=+t,r=+r,ie(t,e,r)[2]}function er(t,e,r){e=+e,t=+t,r=+r;let n=e<t,i=n?Ct(e,t,r):Ct(t,e,r);return(n?-1:1)*(i<0?1/-i:i)}var ho={value:()=>{}};function Br(){for(var t=0,e=arguments.length,r={},n;t<e;++t){if(!(n=arguments[t]+"")||n in r||/[\s.]/.test(n))throw new Error("illegal type: "+n);r[n]=[]}return new ae(r)}function ae(t){this._=t}function go(t,e){return t.trim().split(/^|\s+/).map(function(r){var n="",i=r.indexOf(".");if(i>=0&&(n=r.slice(i+1),r=r.slice(0,i)),r&&!e.hasOwnProperty(r))throw new Error("unknown type: "+r);return{type:r,name:n}})}ae.prototype=Br.prototype={constructor:ae,on:function(t,e){var r=this._,n=go(t+"",r),i,o=-1,a=n.length;if(arguments.length<2){for(;++o<a;)if((i=(t=n[o]).type)&&(i=yo(r[i],t.name)))return i;return}if(e!=null&&typeof e!="function")throw new Error("invalid callback: "+e);for(;++o<a;)if(i=(t=n[o]).type)r[i]=Hr(r[i],t.name,e);else if(e==null)for(i in r)r[i]=Hr(r[i],t.name,null);return this},copy:function(){var t={},e=this._;for(var r in e)t[r]=e[r].slice();return new ae(t)},call:function(t,e){if((i=arguments.length-2)>0)for(var r=new Array(i),n=0,i,o;n<i;++n)r[n]=arguments[n+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(o=this._[t],n=0,i=o.length;n<i;++n)o[n].value.apply(e,r)},apply:function(t,e,r){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var n=this._[t],i=0,o=n.length;i<o;++i)n[i].value.apply(e,r)}};function yo(t,e){for(var r=0,n=t.length,i;r<n;++r)if((i=t[r]).name===e)return i.value}function Hr(t,e,r){for(var n=0,i=t.length;n<i;++n)if(t[n].name===e){t[n]=ho,t=t.slice(0,n).concat(t.slice(n+1));break}return r!=null&&t.push({name:e,value:r}),t}var rr=Br;var se="http://www.w3.org/1999/xhtml",nr={svg:"http://www.w3.org/2000/svg",xhtml:se,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function q(t){var e=t+="",r=e.indexOf(":");return r>=0&&(e=t.slice(0,r))!=="xmlns"&&(t=t.slice(r+1)),nr.hasOwnProperty(e)?{space:nr[e],local:t}:t}function xo(t){return function(){var e=this.ownerDocument,r=this.namespaceURI;return r===se&&e.documentElement.namespaceURI===se?e.createElement(t):e.createElementNS(r,t)}}function bo(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function le(t){var e=q(t);return(e.local?bo:xo)(e)}function vo(){}function nt(t){return t==null?vo:function(){return this.querySelector(t)}}function Wr(t){typeof t!="function"&&(t=nt(t));for(var e=this._groups,r=e.length,n=new Array(r),i=0;i<r;++i)for(var o=e[i],a=o.length,s=n[i]=new Array(a),l,u,c=0;c<a;++c)(l=o[c])&&(u=t.call(l,l.__data__,c,o))&&("__data__"in l&&(u.__data__=l.__data__),s[c]=u);return new M(n,this._parents)}function ir(t){return t==null?[]:Array.isArray(t)?t:Array.from(t)}function wo(){return[]}function At(t){return t==null?wo:function(){return this.querySelectorAll(t)}}function _o(t){return function(){return ir(t.apply(this,arguments))}}function qr(t){typeof t=="function"?t=_o(t):t=At(t);for(var e=this._groups,r=e.length,n=[],i=[],o=0;o<r;++o)for(var a=e[o],s=a.length,l,u=0;u<s;++u)(l=a[u])&&(n.push(t.call(l,l.__data__,u,a)),i.push(l));return new M(n,i)}function Rt(t){return function(){return this.matches(t)}}function ue(t){return function(e){return e.matches(t)}}var So=Array.prototype.find;function ko(t){return function(){return So.call(this.children,t)}}function Mo(){return this.firstElementChild}function Gr(t){return this.select(t==null?Mo:ko(typeof t=="function"?t:ue(t)))}var Co=Array.prototype.filter;function Ao(){return Array.from(this.children)}function Ro(t){return function(){return Co.call(this.children,t)}}function Xr(t){return this.selectAll(t==null?Ao:Ro(typeof t=="function"?t:ue(t)))}function Yr(t){typeof t!="function"&&(t=Rt(t));for(var e=this._groups,r=e.length,n=new Array(r),i=0;i<r;++i)for(var o=e[i],a=o.length,s=n[i]=[],l,u=0;u<a;++u)(l=o[u])&&t.call(l,l.__data__,u,o)&&s.push(l);return new M(n,this._parents)}function ce(t){return new Array(t.length)}function Ur(){return new M(this._enter||this._groups.map(ce),this._parents)}function zt(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e}zt.prototype={constructor:zt,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};function jr(t){return function(){return t}}function zo(t,e,r,n,i,o){for(var a=0,s,l=e.length,u=o.length;a<u;++a)(s=e[a])?(s.__data__=o[a],n[a]=s):r[a]=new zt(t,o[a]);for(;a<l;++a)(s=e[a])&&(i[a]=s)}function Eo(t,e,r,n,i,o,a){var s,l,u=new Map,c=e.length,f=o.length,p=new Array(c),m;for(s=0;s<c;++s)(l=e[s])&&(p[s]=m=a.call(l,l.__data__,s,e)+"",u.has(m)?i[s]=l:u.set(m,l));for(s=0;s<f;++s)m=a.call(t,o[s],s,o)+"",(l=u.get(m))?(n[s]=l,l.__data__=o[s],u.delete(m)):r[s]=new zt(t,o[s]);for(s=0;s<c;++s)(l=e[s])&&u.get(p[s])===l&&(i[s]=l)}function To(t){return t.__data__}function Kr(t,e){if(!arguments.length)return Array.from(this,To);var r=e?Eo:zo,n=this._parents,i=this._groups;typeof t!="function"&&(t=jr(t));for(var o=i.length,a=new Array(o),s=new Array(o),l=new Array(o),u=0;u<o;++u){var c=n[u],f=i[u],p=f.length,m=Lo(t.call(c,c&&c.__data__,u,n)),h=m.length,d=s[u]=new Array(h),g=a[u]=new Array(h),v=l[u]=new Array(p);r(c,f,d,g,v,m,e);for(var y=0,x=0,b,w;y<h;++y)if(b=d[y]){for(y>=x&&(x=y+1);!(w=g[x])&&++x<h;);b._next=w||null}}return a=new M(a,n),a._enter=s,a._exit=l,a}function Lo(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function Zr(){return new M(this._exit||this._groups.map(ce),this._parents)}function Qr(t,e,r){var n=this.enter(),i=this,o=this.exit();return typeof t=="function"?(n=t(n),n&&(n=n.selection())):n=n.append(t+""),e!=null&&(i=e(i),i&&(i=i.selection())),r==null?o.remove():r(o),n&&i?n.merge(i).order():i}function Jr(t){for(var e=t.selection?t.selection():t,r=this._groups,n=e._groups,i=r.length,o=n.length,a=Math.min(i,o),s=new Array(i),l=0;l<a;++l)for(var u=r[l],c=n[l],f=u.length,p=s[l]=new Array(f),m,h=0;h<f;++h)(m=u[h]||c[h])&&(p[h]=m);for(;l<i;++l)s[l]=r[l];return new M(s,this._parents)}function tn(){for(var t=this._groups,e=-1,r=t.length;++e<r;)for(var n=t[e],i=n.length-1,o=n[i],a;--i>=0;)(a=n[i])&&(o&&a.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(a,o),o=a);return this}function en(t){t||(t=$o);function e(f,p){return f&&p?t(f.__data__,p.__data__):!f-!p}for(var r=this._groups,n=r.length,i=new Array(n),o=0;o<n;++o){for(var a=r[o],s=a.length,l=i[o]=new Array(s),u,c=0;c<s;++c)(u=a[c])&&(l[c]=u);l.sort(e)}return new M(i,this._parents).order()}function $o(t,e){return t<e?-1:t>e?1:t>=e?0:NaN}function rn(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this}function nn(){return Array.from(this)}function on(){for(var t=this._groups,e=0,r=t.length;e<r;++e)for(var n=t[e],i=0,o=n.length;i<o;++i){var a=n[i];if(a)return a}return null}function an(){let t=0;for(let e of this)++t;return t}function sn(){return!this.node()}function ln(t){for(var e=this._groups,r=0,n=e.length;r<n;++r)for(var i=e[r],o=0,a=i.length,s;o<a;++o)(s=i[o])&&t.call(s,s.__data__,o,i);return this}function Oo(t){return function(){this.removeAttribute(t)}}function No(t){return function(){this.removeAttributeNS(t.space,t.local)}}function Fo(t,e){return function(){this.setAttribute(t,e)}}function Io(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function Po(t,e){return function(){var r=e.apply(this,arguments);r==null?this.removeAttribute(t):this.setAttribute(t,r)}}function Do(t,e){return function(){var r=e.apply(this,arguments);r==null?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,r)}}function un(t,e){var r=q(t);if(arguments.length<2){var n=this.node();return r.local?n.getAttributeNS(r.space,r.local):n.getAttribute(r)}return this.each((e==null?r.local?No:Oo:typeof e=="function"?r.local?Do:Po:r.local?Io:Fo)(r,e))}function fe(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function Vo(t){return function(){this.style.removeProperty(t)}}function Ho(t,e,r){return function(){this.style.setProperty(t,e,r)}}function Bo(t,e,r){return function(){var n=e.apply(this,arguments);n==null?this.style.removeProperty(t):this.style.setProperty(t,n,r)}}function cn(t,e,r){return arguments.length>1?this.each((e==null?Vo:typeof e=="function"?Bo:Ho)(t,e,r??"")):j(this.node(),t)}function j(t,e){return t.style.getPropertyValue(e)||fe(t).getComputedStyle(t,null).getPropertyValue(e)}function Wo(t){return function(){delete this[t]}}function qo(t,e){return function(){this[t]=e}}function Go(t,e){return function(){var r=e.apply(this,arguments);r==null?delete this[t]:this[t]=r}}function fn(t,e){return arguments.length>1?this.each((e==null?Wo:typeof e=="function"?Go:qo)(t,e)):this.node()[t]}function pn(t){return t.trim().split(/^|\s+/)}function or(t){return t.classList||new mn(t)}function mn(t){this._node=t,this._names=pn(t.getAttribute("class")||"")}mn.prototype={add:function(t){var e=this._names.indexOf(t);e<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")))},remove:function(t){var e=this._names.indexOf(t);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};function hn(t,e){for(var r=or(t),n=-1,i=e.length;++n<i;)r.add(e[n])}function dn(t,e){for(var r=or(t),n=-1,i=e.length;++n<i;)r.remove(e[n])}function Xo(t){return function(){hn(this,t)}}function Yo(t){return function(){dn(this,t)}}function Uo(t,e){return function(){(e.apply(this,arguments)?hn:dn)(this,t)}}function gn(t,e){var r=pn(t+"");if(arguments.length<2){for(var n=or(this.node()),i=-1,o=r.length;++i<o;)if(!n.contains(r[i]))return!1;return!0}return this.each((typeof e=="function"?Uo:e?Xo:Yo)(r,e))}function jo(){this.textContent=""}function Ko(t){return function(){this.textContent=t}}function Zo(t){return function(){var e=t.apply(this,arguments);this.textContent=e??""}}function yn(t){return arguments.length?this.each(t==null?jo:(typeof t=="function"?Zo:Ko)(t)):this.node().textContent}function Qo(){this.innerHTML=""}function Jo(t){return function(){this.innerHTML=t}}function ta(t){return function(){var e=t.apply(this,arguments);this.innerHTML=e??""}}function xn(t){return arguments.length?this.each(t==null?Qo:(typeof t=="function"?ta:Jo)(t)):this.node().innerHTML}function ea(){this.nextSibling&&this.parentNode.appendChild(this)}function bn(){return this.each(ea)}function ra(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function vn(){return this.each(ra)}function wn(t){var e=typeof t=="function"?t:le(t);return this.select(function(){return this.appendChild(e.apply(this,arguments))})}function na(){return null}function _n(t,e){var r=typeof t=="function"?t:le(t),n=e==null?na:typeof e=="function"?e:nt(e);return this.select(function(){return this.insertBefore(r.apply(this,arguments),n.apply(this,arguments)||null)})}function ia(){var t=this.parentNode;t&&t.removeChild(this)}function Sn(){return this.each(ia)}function oa(){var t=this.cloneNode(!1),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function aa(){var t=this.cloneNode(!0),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function kn(t){return this.select(t?aa:oa)}function Mn(t){return arguments.length?this.property("__data__",t):this.node().__data__}function sa(t){return function(e){t.call(this,e,this.__data__)}}function la(t){return t.trim().split(/^|\s+/).map(function(e){var r="",n=e.indexOf(".");return n>=0&&(r=e.slice(n+1),e=e.slice(0,n)),{type:e,name:r}})}function ua(t){return function(){var e=this.__on;if(e){for(var r=0,n=-1,i=e.length,o;r<i;++r)o=e[r],(!t.type||o.type===t.type)&&o.name===t.name?this.removeEventListener(o.type,o.listener,o.options):e[++n]=o;++n?e.length=n:delete this.__on}}}function ca(t,e,r){return function(){var n=this.__on,i,o=sa(e);if(n){for(var a=0,s=n.length;a<s;++a)if((i=n[a]).type===t.type&&i.name===t.name){this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=o,i.options=r),i.value=e;return}}this.addEventListener(t.type,o,r),i={type:t.type,name:t.name,value:e,listener:o,options:r},n?n.push(i):this.__on=[i]}}function Cn(t,e,r){var n=la(t+""),i,o=n.length,a;if(arguments.length<2){var s=this.node().__on;if(s){for(var l=0,u=s.length,c;l<u;++l)for(i=0,c=s[l];i<o;++i)if((a=n[i]).type===c.type&&a.name===c.name)return c.value}return}for(s=e?ca:ua,i=0;i<o;++i)this.each(s(n[i],e,r));return this}function An(t,e,r){var n=fe(t),i=n.CustomEvent;typeof i=="function"?i=new i(e,r):(i=n.document.createEvent("Event"),r?(i.initEvent(e,r.bubbles,r.cancelable),i.detail=r.detail):i.initEvent(e,!1,!1)),t.dispatchEvent(i)}function fa(t,e){return function(){return An(this,t,e)}}function pa(t,e){return function(){return An(this,t,e.apply(this,arguments))}}function Rn(t,e){return this.each((typeof e=="function"?pa:fa)(t,e))}function*zn(){for(var t=this._groups,e=0,r=t.length;e<r;++e)for(var n=t[e],i=0,o=n.length,a;i<o;++i)(a=n[i])&&(yield a)}var ar=[null];function M(t,e){this._groups=t,this._parents=e}function En(){return new M([[document.documentElement]],ar)}function ma(){return this}M.prototype=En.prototype={constructor:M,select:Wr,selectAll:qr,selectChild:Gr,selectChildren:Xr,filter:Yr,data:Kr,enter:Ur,exit:Zr,join:Qr,merge:Jr,selection:ma,order:tn,sort:en,call:rn,nodes:nn,node:on,size:an,empty:sn,each:ln,attr:un,style:cn,property:fn,classed:gn,text:yn,html:xn,raise:bn,lower:vn,append:wn,insert:_n,remove:Sn,clone:kn,datum:Mn,on:Cn,dispatch:Rn,[Symbol.iterator]:zn};var G=En;function sr(t){return typeof t=="string"?new M([[document.querySelector(t)]],[document.documentElement]):new M([[t]],ar)}function pe(t,e,r){t.prototype=e.prototype=r,r.constructor=t}function lr(t,e){var r=Object.create(t.prototype);for(var n in e)r[n]=e[n];return r}function Lt(){}var Et=.7,de=1/Et,gt="\\s*([+-]?\\d+)\\s*",Tt="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",D="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",ha=/^#([0-9a-f]{3,8})$/,da=new RegExp(`^rgb\\(${gt},${gt},${gt}\\)$`),ga=new RegExp(`^rgb\\(${D},${D},${D}\\)$`),ya=new RegExp(`^rgba\\(${gt},${gt},${gt},${Tt}\\)$`),xa=new RegExp(`^rgba\\(${D},${D},${D},${Tt}\\)$`),ba=new RegExp(`^hsl\\(${Tt},${D},${D}\\)$`),va=new RegExp(`^hsla\\(${Tt},${D},${D},${Tt}\\)$`),Tn={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};pe(Lt,F,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:Ln,formatHex:Ln,formatHex8:wa,formatHsl:_a,formatRgb:$n,toString:$n});function Ln(){return this.rgb().formatHex()}function wa(){return this.rgb().formatHex8()}function _a(){return Dn(this).formatHsl()}function $n(){return this.rgb().formatRgb()}function F(t){var e,r;return t=(t+"").trim().toLowerCase(),(e=ha.exec(t))?(r=e[1].length,e=parseInt(e[1],16),r===6?On(e):r===3?new $(e>>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):r===8?me(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):r===4?me(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=da.exec(t))?new $(e[1],e[2],e[3],1):(e=ga.exec(t))?new $(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=ya.exec(t))?me(e[1],e[2],e[3],e[4]):(e=xa.exec(t))?me(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=ba.exec(t))?In(e[1],e[2]/100,e[3]/100,1):(e=va.exec(t))?In(e[1],e[2]/100,e[3]/100,e[4]):Tn.hasOwnProperty(t)?On(Tn[t]):t==="transparent"?new $(NaN,NaN,NaN,0):null}function On(t){return new $(t>>16&255,t>>8&255,t&255,1)}function me(t,e,r,n){return n<=0&&(t=e=r=NaN),new $(t,e,r,n)}function Sa(t){return t instanceof Lt||(t=F(t)),t?(t=t.rgb(),new $(t.r,t.g,t.b,t.opacity)):new $}function yt(t,e,r,n){return arguments.length===1?Sa(t):new $(t,e,r,n??1)}function $(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}pe($,yt,lr(Lt,{brighter(t){return t=t==null?de:Math.pow(de,t),new $(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?Et:Math.pow(Et,t),new $(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new $(ot(this.r),ot(this.g),ot(this.b),ge(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Nn,formatHex:Nn,formatHex8:ka,formatRgb:Fn,toString:Fn}));function Nn(){return`#${it(this.r)}${it(this.g)}${it(this.b)}`}function ka(){return`#${it(this.r)}${it(this.g)}${it(this.b)}${it((isNaN(this.opacity)?1:this.opacity)*255)}`}function Fn(){let t=ge(this.opacity);return`${t===1?"rgb(":"rgba("}${ot(this.r)}, ${ot(this.g)}, ${ot(this.b)}${t===1?")":`, ${t})`}`}function ge(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function ot(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function it(t){return t=ot(t),(t<16?"0":"")+t.toString(16)}function In(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new N(t,e,r,n)}function Dn(t){if(t instanceof N)return new N(t.h,t.s,t.l,t.opacity);if(t instanceof Lt||(t=F(t)),!t)return new N;if(t instanceof N)return t;t=t.rgb();var e=t.r/255,r=t.g/255,n=t.b/255,i=Math.min(e,r,n),o=Math.max(e,r,n),a=NaN,s=o-i,l=(o+i)/2;return s?(e===o?a=(r-n)/s+(r<n)*6:r===o?a=(n-e)/s+2:a=(e-r)/s+4,s/=l<.5?o+i:2-o-i,a*=60):s=l>0&&l<1?0:a,new N(a,s,l,t.opacity)}function Vn(t,e,r,n){return arguments.length===1?Dn(t):new N(t,e,r,n??1)}function N(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}pe(N,Vn,lr(Lt,{brighter(t){return t=t==null?de:Math.pow(de,t),new N(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?Et:Math.pow(Et,t),new N(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,i=2*r-n;return new $(ur(t>=240?t-240:t+120,i,n),ur(t,i,n),ur(t<120?t+240:t-120,i,n),this.opacity)},clamp(){return new N(Pn(this.h),he(this.s),he(this.l),ge(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let t=ge(this.opacity);return`${t===1?"hsl(":"hsla("}${Pn(this.h)}, ${he(this.s)*100}%, ${he(this.l)*100}%${t===1?")":`, ${t})`}`}}));function Pn(t){return t=(t||0)%360,t<0?t+360:t}function he(t){return Math.max(0,Math.min(1,t||0))}function ur(t,e,r){return(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)*255}function cr(t,e,r,n,i){var o=t*t,a=o*t;return((1-3*t+3*o-a)*e+(4-6*o+3*a)*r+(1+3*t+3*o-3*a)*n+a*i)/6}function Hn(t){var e=t.length-1;return function(r){var n=r<=0?r=0:r>=1?(r=1,e-1):Math.floor(r*e),i=t[n],o=t[n+1],a=n>0?t[n-1]:2*i-o,s=n<e-1?t[n+2]:2*o-i;return cr((r-n/e)*e,a,i,o,s)}}function Bn(t){var e=t.length;return function(r){var n=Math.floor(((r%=1)<0?++r:r)*e),i=t[(n+e-1)%e],o=t[n%e],a=t[(n+1)%e],s=t[(n+2)%e];return cr((r-n/e)*e,i,o,a,s)}}var $t=t=>()=>t;function Ma(t,e){return function(r){return t+r*e}}function Ca(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(n){return Math.pow(t+n*e,r)}}function Wn(t){return(t=+t)==1?ye:function(e,r){return r-e?Ca(e,r,t):$t(isNaN(e)?r:e)}}function ye(t,e){var r=e-t;return r?Ma(t,r):$t(isNaN(t)?e:t)}var at=(function t(e){var r=Wn(e);function n(i,o){var a=r((i=yt(i)).r,(o=yt(o)).r),s=r(i.g,o.g),l=r(i.b,o.b),u=ye(i.opacity,o.opacity);return function(c){return i.r=a(c),i.g=s(c),i.b=l(c),i.opacity=u(c),i+""}}return n.gamma=t,n})(1);function qn(t){return function(e){var r=e.length,n=new Array(r),i=new Array(r),o=new Array(r),a,s;for(a=0;a<r;++a)s=yt(e[a]),n[a]=s.r||0,i[a]=s.g||0,o[a]=s.b||0;return n=t(n),i=t(i),o=t(o),s.opacity=1,function(l){return s.r=n(l),s.g=i(l),s.b=o(l),s+""}}}var Aa=qn(Hn),Ra=qn(Bn);function Gn(t,e){e||(e=[]);var r=t?Math.min(e.length,t.length):0,n=e.slice(),i;return function(o){for(i=0;i<r;++i)n[i]=t[i]*(1-o)+e[i]*o;return n}}function Xn(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Yn(t,e){var r=e?e.length:0,n=t?Math.min(r,t.length):0,i=new Array(n),o=new Array(r),a;for(a=0;a<n;++a)i[a]=st(t[a],e[a]);for(;a<r;++a)o[a]=e[a];return function(s){for(a=0;a<n;++a)o[a]=i[a](s);return o}}function Un(t,e){var r=new Date;return t=+t,e=+e,function(n){return r.setTime(t*(1-n)+e*n),r}}function z(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}function jn(t,e){var r={},n={},i;(t===null||typeof t!="object")&&(t={}),(e===null||typeof e!="object")&&(e={});for(i in e)i in t?r[i]=st(t[i],e[i]):n[i]=e[i];return function(o){for(i in r)n[i]=r[i](o);return n}}var pr=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,fr=new RegExp(pr.source,"g");function za(t){return function(){return t}}function Ea(t){return function(e){return t(e)+""}}function Ot(t,e){var r=pr.lastIndex=fr.lastIndex=0,n,i,o,a=-1,s=[],l=[];for(t=t+"",e=e+"";(n=pr.exec(t))&&(i=fr.exec(e));)(o=i.index)>r&&(o=e.slice(r,o),s[a]?s[a]+=o:s[++a]=o),(n=n[0])===(i=i[0])?s[a]?s[a]+=i:s[++a]=i:(s[++a]=null,l.push({i:a,x:z(n,i)})),r=fr.lastIndex;return r<e.length&&(o=e.slice(r),s[a]?s[a]+=o:s[++a]=o),s.length<2?l[0]?Ea(l[0].x):za(e):(e=l.length,function(u){for(var c=0,f;c<e;++c)s[(f=l[c]).i]=f.x(u);return s.join("")})}function st(t,e){var r=typeof e,n;return e==null||r==="boolean"?$t(e):(r==="number"?z:r==="string"?(n=F(e))?(e=n,at):Ot:e instanceof F?at:e instanceof Date?Un:Xn(e)?Gn:Array.isArray(e)?Yn:typeof e.valueOf!="function"&&typeof e.toString!="function"||isNaN(e)?jn:z)(t,e)}function mr(t,e){return t=+t,e=+e,function(r){return Math.round(t*(1-r)+e*r)}}var Kn=180/Math.PI,xe={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function hr(t,e,r,n,i,o){var a,s,l;return(a=Math.sqrt(t*t+e*e))&&(t/=a,e/=a),(l=t*r+e*n)&&(r-=t*l,n-=e*l),(s=Math.sqrt(r*r+n*n))&&(r/=s,n/=s,l/=s),t*n<e*r&&(t=-t,e=-e,l=-l,a=-a),{translateX:i,translateY:o,rotate:Math.atan2(e,t)*Kn,skewX:Math.atan(l)*Kn,scaleX:a,scaleY:s}}var be;function Zn(t){let e=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(t+"");return e.isIdentity?xe:hr(e.a,e.b,e.c,e.d,e.e,e.f)}function Qn(t){return t==null?xe:(be||(be=document.createElementNS("http://www.w3.org/2000/svg","g")),be.setAttribute("transform",t),(t=be.transform.baseVal.consolidate())?(t=t.matrix,hr(t.a,t.b,t.c,t.d,t.e,t.f)):xe)}function Jn(t,e,r,n){function i(u){return u.length?u.pop()+" ":""}function o(u,c,f,p,m,h){if(u!==f||c!==p){var d=m.push("translate(",null,e,null,r);h.push({i:d-4,x:z(u,f)},{i:d-2,x:z(c,p)})}else(f||p)&&m.push("translate("+f+e+p+r)}function a(u,c,f,p){u!==c?(u-c>180?c+=360:c-u>180&&(u+=360),p.push({i:f.push(i(f)+"rotate(",null,n)-2,x:z(u,c)})):c&&f.push(i(f)+"rotate("+c+n)}function s(u,c,f,p){u!==c?p.push({i:f.push(i(f)+"skewX(",null,n)-2,x:z(u,c)}):c&&f.push(i(f)+"skewX("+c+n)}function l(u,c,f,p,m,h){if(u!==f||c!==p){var d=m.push(i(m)+"scale(",null,",",null,")");h.push({i:d-4,x:z(u,f)},{i:d-2,x:z(c,p)})}else(f!==1||p!==1)&&m.push(i(m)+"scale("+f+","+p+")")}return function(u,c){var f=[],p=[];return u=t(u),c=t(c),o(u.translateX,u.translateY,c.translateX,c.translateY,f,p),a(u.rotate,c.rotate,f,p),s(u.skewX,c.skewX,f,p),l(u.scaleX,u.scaleY,c.scaleX,c.scaleY,f,p),u=c=null,function(m){for(var h=-1,d=p.length,g;++h<d;)f[(g=p[h]).i]=g.x(m);return f.join("")}}}var dr=Jn(Zn,"px, ","px)","deg)"),gr=Jn(Qn,", ",")",")");var xt=0,Ft=0,Nt=0,ei=1e3,ve,It,we=0,lt=0,_e=0,Pt=typeof performance=="object"&&performance.now?performance:Date,ri=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function Vt(){return lt||(ri(Ta),lt=Pt.now()+_e)}function Ta(){lt=0}function Dt(){this._call=this._time=this._next=null}Dt.prototype=Se.prototype={constructor:Dt,restart:function(t,e,r){if(typeof t!="function")throw new TypeError("callback is not a function");r=(r==null?Vt():+r)+(e==null?0:+e),!this._next&&It!==this&&(It?It._next=this:ve=this,It=this),this._call=t,this._time=r,yr()},stop:function(){this._call&&(this._call=null,this._time=1/0,yr())}};function Se(t,e,r){var n=new Dt;return n.restart(t,e,r),n}function ni(){Vt(),++xt;for(var t=ve,e;t;)(e=lt-t._time)>=0&&t._call.call(void 0,e),t=t._next;--xt}function ti(){lt=(we=Pt.now())+_e,xt=Ft=0;try{ni()}finally{xt=0,$a(),lt=0}}function La(){var t=Pt.now(),e=t-we;e>ei&&(_e-=e,we=t)}function $a(){for(var t,e=ve,r,n=1/0;e;)e._call?(n>e._time&&(n=e._time),t=e,e=e._next):(r=e._next,e._next=null,e=t?t._next=r:ve=r);It=t,yr(n)}function yr(t){if(!xt){Ft&&(Ft=clearTimeout(Ft));var e=t-lt;e>24?(t<1/0&&(Ft=setTimeout(ti,t-Pt.now()-_e)),Nt&&(Nt=clearInterval(Nt))):(Nt||(we=Pt.now(),Nt=setInterval(La,ei)),xt=1,ri(ti))}}function ke(t,e,r){var n=new Dt;return e=e==null?0:+e,n.restart(i=>{n.stop(),t(i+e)},e,r),n}var Oa=rr("start","end","cancel","interrupt"),Na=[],ai=0,ii=1,Ce=2,Me=3,oi=4,Ae=5,Ht=6;function K(t,e,r,n,i,o){var a=t.__transition;if(!a)t.__transition={};else if(r in a)return;Fa(t,r,{name:e,index:n,group:i,on:Oa,tween:Na,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:ai})}function Bt(t,e){var r=R(t,e);if(r.state>ai)throw new Error("too late; already scheduled");return r}function E(t,e){var r=R(t,e);if(r.state>Me)throw new Error("too late; already running");return r}function R(t,e){var r=t.__transition;if(!r||!(r=r[e]))throw new Error("transition not found");return r}function Fa(t,e,r){var n=t.__transition,i;n[e]=r,r.timer=Se(o,0,r.time);function o(u){r.state=ii,r.timer.restart(a,r.delay,r.time),r.delay<=u&&a(u-r.delay)}function a(u){var c,f,p,m;if(r.state!==ii)return l();for(c in n)if(m=n[c],m.name===r.name){if(m.state===Me)return ke(a);m.state===oi?(m.state=Ht,m.timer.stop(),m.on.call("interrupt",t,t.__data__,m.index,m.group),delete n[c]):+c<e&&(m.state=Ht,m.timer.stop(),m.on.call("cancel",t,t.__data__,m.index,m.group),delete n[c])}if(ke(function(){r.state===Me&&(r.state=oi,r.timer.restart(s,r.delay,r.time),s(u))}),r.state=Ce,r.on.call("start",t,t.__data__,r.index,r.group),r.state===Ce){for(r.state=Me,i=new Array(p=r.tween.length),c=0,f=-1;c<p;++c)(m=r.tween[c].value.call(t,t.__data__,r.index,r.group))&&(i[++f]=m);i.length=f+1}}function s(u){for(var c=u<r.duration?r.ease.call(null,u/r.duration):(r.timer.restart(l),r.state=Ae,1),f=-1,p=i.length;++f<p;)i[f].call(t,c);r.state===Ae&&(r.on.call("end",t,t.__data__,r.index,r.group),l())}function l(){r.state=Ht,r.timer.stop(),delete n[e];for(var u in n)return;delete t.__transition}}function Re(t,e){var r=t.__transition,n,i,o=!0,a;if(r){e=e==null?null:e+"";for(a in r){if((n=r[a]).name!==e){o=!1;continue}i=n.state>Ce&&n.state<Ae,n.state=Ht,n.timer.stop(),n.on.call(i?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete r[a]}o&&delete t.__transition}}function si(t){return this.each(function(){Re(this,t)})}function Ia(t,e){var r,n;return function(){var i=E(this,t),o=i.tween;if(o!==r){n=r=o;for(var a=0,s=n.length;a<s;++a)if(n[a].name===e){n=n.slice(),n.splice(a,1);break}}i.tween=n}}function Pa(t,e,r){var n,i;if(typeof r!="function")throw new Error;return function(){var o=E(this,t),a=o.tween;if(a!==n){i=(n=a).slice();for(var s={name:e,value:r},l=0,u=i.length;l<u;++l)if(i[l].name===e){i[l]=s;break}l===u&&i.push(s)}o.tween=i}}function li(t,e){var r=this._id;if(t+="",arguments.length<2){for(var n=R(this.node(),r).tween,i=0,o=n.length,a;i<o;++i)if((a=n[i]).name===t)return a.value;return null}return this.each((e==null?Ia:Pa)(r,t,e))}function bt(t,e,r){var n=t._id;return t.each(function(){var i=E(this,n);(i.value||(i.value={}))[e]=r.apply(this,arguments)}),function(i){return R(i,n).value[e]}}function ze(t,e){var r;return(typeof e=="number"?z:e instanceof F?at:(r=F(e))?(e=r,at):Ot)(t,e)}function Da(t){return function(){this.removeAttribute(t)}}function Va(t){return function(){this.removeAttributeNS(t.space,t.local)}}function Ha(t,e,r){var n,i=r+"",o;return function(){var a=this.getAttribute(t);return a===i?null:a===n?o:o=e(n=a,r)}}function Ba(t,e,r){var n,i=r+"",o;return function(){var a=this.getAttributeNS(t.space,t.local);return a===i?null:a===n?o:o=e(n=a,r)}}function Wa(t,e,r){var n,i,o;return function(){var a,s=r(this),l;return s==null?void this.removeAttribute(t):(a=this.getAttribute(t),l=s+"",a===l?null:a===n&&l===i?o:(i=l,o=e(n=a,s)))}}function qa(t,e,r){var n,i,o;return function(){var a,s=r(this),l;return s==null?void this.removeAttributeNS(t.space,t.local):(a=this.getAttributeNS(t.space,t.local),l=s+"",a===l?null:a===n&&l===i?o:(i=l,o=e(n=a,s)))}}function ui(t,e){var r=q(t),n=r==="transform"?gr:ze;return this.attrTween(t,typeof e=="function"?(r.local?qa:Wa)(r,n,bt(this,"attr."+t,e)):e==null?(r.local?Va:Da)(r):(r.local?Ba:Ha)(r,n,e))}function Ga(t,e){return function(r){this.setAttribute(t,e.call(this,r))}}function Xa(t,e){return function(r){this.setAttributeNS(t.space,t.local,e.call(this,r))}}function Ya(t,e){var r,n;function i(){var o=e.apply(this,arguments);return o!==n&&(r=(n=o)&&Xa(t,o)),r}return i._value=e,i}function Ua(t,e){var r,n;function i(){var o=e.apply(this,arguments);return o!==n&&(r=(n=o)&&Ga(t,o)),r}return i._value=e,i}function ci(t,e){var r="attr."+t;if(arguments.length<2)return(r=this.tween(r))&&r._value;if(e==null)return this.tween(r,null);if(typeof e!="function")throw new Error;var n=q(t);return this.tween(r,(n.local?Ya:Ua)(n,e))}function ja(t,e){return function(){Bt(this,t).delay=+e.apply(this,arguments)}}function Ka(t,e){return e=+e,function(){Bt(this,t).delay=e}}function fi(t){var e=this._id;return arguments.length?this.each((typeof t=="function"?ja:Ka)(e,t)):R(this.node(),e).delay}function Za(t,e){return function(){E(this,t).duration=+e.apply(this,arguments)}}function Qa(t,e){return e=+e,function(){E(this,t).duration=e}}function pi(t){var e=this._id;return arguments.length?this.each((typeof t=="function"?Za:Qa)(e,t)):R(this.node(),e).duration}function Ja(t,e){if(typeof e!="function")throw new Error;return function(){E(this,t).ease=e}}function mi(t){var e=this._id;return arguments.length?this.each(Ja(e,t)):R(this.node(),e).ease}function ts(t,e){return function(){var r=e.apply(this,arguments);if(typeof r!="function")throw new Error;E(this,t).ease=r}}function hi(t){if(typeof t!="function")throw new Error;return this.each(ts(this._id,t))}function di(t){typeof t!="function"&&(t=Rt(t));for(var e=this._groups,r=e.length,n=new Array(r),i=0;i<r;++i)for(var o=e[i],a=o.length,s=n[i]=[],l,u=0;u<a;++u)(l=o[u])&&t.call(l,l.__data__,u,o)&&s.push(l);return new T(n,this._parents,this._name,this._id)}function gi(t){if(t._id!==this._id)throw new Error;for(var e=this._groups,r=t._groups,n=e.length,i=r.length,o=Math.min(n,i),a=new Array(n),s=0;s<o;++s)for(var l=e[s],u=r[s],c=l.length,f=a[s]=new Array(c),p,m=0;m<c;++m)(p=l[m]||u[m])&&(f[m]=p);for(;s<n;++s)a[s]=e[s];return new T(a,this._parents,this._name,this._id)}function es(t){return(t+"").trim().split(/^|\s+/).every(function(e){var r=e.indexOf(".");return r>=0&&(e=e.slice(0,r)),!e||e==="start"})}function rs(t,e,r){var n,i,o=es(e)?Bt:E;return function(){var a=o(this,t),s=a.on;s!==n&&(i=(n=s).copy()).on(e,r),a.on=i}}function yi(t,e){var r=this._id;return arguments.length<2?R(this.node(),r).on.on(t):this.each(rs(r,t,e))}function ns(t){return function(){var e=this.parentNode;for(var r in this.__transition)if(+r!==t)return;e&&e.removeChild(this)}}function xi(){return this.on("end.remove",ns(this._id))}function bi(t){var e=this._name,r=this._id;typeof t!="function"&&(t=nt(t));for(var n=this._groups,i=n.length,o=new Array(i),a=0;a<i;++a)for(var s=n[a],l=s.length,u=o[a]=new Array(l),c,f,p=0;p<l;++p)(c=s[p])&&(f=t.call(c,c.__data__,p,s))&&("__data__"in c&&(f.__data__=c.__data__),u[p]=f,K(u[p],e,r,p,u,R(c,r)));return new T(o,this._parents,e,r)}function vi(t){var e=this._name,r=this._id;typeof t!="function"&&(t=At(t));for(var n=this._groups,i=n.length,o=[],a=[],s=0;s<i;++s)for(var l=n[s],u=l.length,c,f=0;f<u;++f)if(c=l[f]){for(var p=t.call(c,c.__data__,f,l),m,h=R(c,r),d=0,g=p.length;d<g;++d)(m=p[d])&&K(m,e,r,d,p,h);o.push(p),a.push(c)}return new T(o,a,e,r)}var is=G.prototype.constructor;function wi(){return new is(this._groups,this._parents)}function os(t,e){var r,n,i;return function(){var o=j(this,t),a=(this.style.removeProperty(t),j(this,t));return o===a?null:o===r&&a===n?i:i=e(r=o,n=a)}}function _i(t){return function(){this.style.removeProperty(t)}}function as(t,e,r){var n,i=r+"",o;return function(){var a=j(this,t);return a===i?null:a===n?o:o=e(n=a,r)}}function ss(t,e,r){var n,i,o;return function(){var a=j(this,t),s=r(this),l=s+"";return s==null&&(l=s=(this.style.removeProperty(t),j(this,t))),a===l?null:a===n&&l===i?o:(i=l,o=e(n=a,s))}}function ls(t,e){var r,n,i,o="style."+e,a="end."+o,s;return function(){var l=E(this,t),u=l.on,c=l.value[o]==null?s||(s=_i(e)):void 0;(u!==r||i!==c)&&(n=(r=u).copy()).on(a,i=c),l.on=n}}function Si(t,e,r){var n=(t+="")=="transform"?dr:ze;return e==null?this.styleTween(t,os(t,n)).on("end.style."+t,_i(t)):typeof e=="function"?this.styleTween(t,ss(t,n,bt(this,"style."+t,e))).each(ls(this._id,t)):this.styleTween(t,as(t,n,e),r).on("end.style."+t,null)}function us(t,e,r){return function(n){this.style.setProperty(t,e.call(this,n),r)}}function cs(t,e,r){var n,i;function o(){var a=e.apply(this,arguments);return a!==i&&(n=(i=a)&&us(t,a,r)),n}return o._value=e,o}function ki(t,e,r){var n="style."+(t+="");if(arguments.length<2)return(n=this.tween(n))&&n._value;if(e==null)return this.tween(n,null);if(typeof e!="function")throw new Error;return this.tween(n,cs(t,e,r??""))}function fs(t){return function(){this.textContent=t}}function ps(t){return function(){var e=t(this);this.textContent=e??""}}function Mi(t){return this.tween("text",typeof t=="function"?ps(bt(this,"text",t)):fs(t==null?"":t+""))}function ms(t){return function(e){this.textContent=t.call(this,e)}}function hs(t){var e,r;function n(){var i=t.apply(this,arguments);return i!==r&&(e=(r=i)&&ms(i)),e}return n._value=t,n}function Ci(t){var e="text";if(arguments.length<1)return(e=this.tween(e))&&e._value;if(t==null)return this.tween(e,null);if(typeof t!="function")throw new Error;return this.tween(e,hs(t))}function Ai(){for(var t=this._name,e=this._id,r=Ee(),n=this._groups,i=n.length,o=0;o<i;++o)for(var a=n[o],s=a.length,l,u=0;u<s;++u)if(l=a[u]){var c=R(l,e);K(l,t,r,u,a,{time:c.time+c.delay+c.duration,delay:0,duration:c.duration,ease:c.ease})}return new T(n,this._parents,t,r)}function Ri(){var t,e,r=this,n=r._id,i=r.size();return new Promise(function(o,a){var s={value:a},l={value:function(){--i===0&&o()}};r.each(function(){var u=E(this,n),c=u.on;c!==t&&(e=(t=c).copy(),e._.cancel.push(s),e._.interrupt.push(s),e._.end.push(l)),u.on=e}),i===0&&o()})}var ds=0;function T(t,e,r,n){this._groups=t,this._parents=e,this._name=r,this._id=n}function zi(t){return G().transition(t)}function Ee(){return++ds}var X=G.prototype;T.prototype=zi.prototype={constructor:T,select:bi,selectAll:vi,selectChild:X.selectChild,selectChildren:X.selectChildren,filter:di,merge:gi,selection:wi,transition:Ai,call:X.call,nodes:X.nodes,node:X.node,size:X.size,empty:X.empty,each:X.each,on:yi,attr:ui,attrTween:ci,style:Si,styleTween:ki,text:Mi,textTween:Ci,remove:xi,tween:li,delay:fi,duration:pi,ease:mi,easeVarying:hi,end:Ri,[Symbol.iterator]:X[Symbol.iterator]};function Te(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}var gs={time:null,delay:0,duration:250,ease:Te};function ys(t,e){for(var r;!(r=t.__transition)||!(r=r[e]);)if(!(t=t.parentNode))throw new Error(`transition ${e} not found`);return r}function Ei(t){var e,r;t instanceof T?(e=t._id,t=t._name):(e=Ee(),(r=gs).time=Vt(),t=t==null?null:t+"");for(var n=this._groups,i=n.length,o=0;o<i;++o)for(var a=n[o],s=a.length,l,u=0;u<s;++u)(l=a[u])&&K(l,t,e,u,a,r||ys(l,e));return new T(n,this._parents,t,e)}G.prototype.interrupt=si;G.prototype.transition=Ei;var{abs:Tm,max:Lm,min:$m}=Math;function Ti(t){return[+t[0],+t[1]]}function xs(t){return[Ti(t[0]),Ti(t[1])]}var Om={name:"x",handles:["w","e"].map(xr),input:function(t,e){return t==null?null:[[+t[0],e[0][1]],[+t[1],e[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},Nm={name:"y",handles:["n","s"].map(xr),input:function(t,e){return t==null?null:[[e[0][0],+t[0]],[e[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},Fm={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(xr),input:function(t){return t==null?null:xs(t)},output:function(t){return t}};function xr(t){return{type:t}}var br=Math.PI,vr=2*br,ut=1e-6,bs=vr-ut;function Li(t){this._+=t[0];for(let e=1,r=t.length;e<r;++e)this._+=arguments[e]+t[e]}function vs(t){let e=Math.floor(t);if(!(e>=0))throw new Error(`invalid digits: ${t}`);if(e>15)return Li;let r=10**e;return function(n){this._+=n[0];for(let i=1,o=n.length;i<o;++i)this._+=Math.round(arguments[i]*r)/r+n[i]}}var ct=class{constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?Li:vs(e)}moveTo(e,r){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+r}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(e,r){this._append`L${this._x1=+e},${this._y1=+r}`}quadraticCurveTo(e,r,n,i){this._append`Q${+e},${+r},${this._x1=+n},${this._y1=+i}`}bezierCurveTo(e,r,n,i,o,a){this._append`C${+e},${+r},${+n},${+i},${this._x1=+o},${this._y1=+a}`}arcTo(e,r,n,i,o){if(e=+e,r=+r,n=+n,i=+i,o=+o,o<0)throw new Error(`negative radius: ${o}`);let a=this._x1,s=this._y1,l=n-e,u=i-r,c=a-e,f=s-r,p=c*c+f*f;if(this._x1===null)this._append`M${this._x1=e},${this._y1=r}`;else if(p>ut)if(!(Math.abs(f*l-u*c)>ut)||!o)this._append`L${this._x1=e},${this._y1=r}`;else{let m=n-a,h=i-s,d=l*l+u*u,g=m*m+h*h,v=Math.sqrt(d),y=Math.sqrt(p),x=o*Math.tan((br-Math.acos((d+p-g)/(2*v*y)))/2),b=x/y,w=x/v;Math.abs(b-1)>ut&&this._append`L${e+b*c},${r+b*f}`,this._append`A${o},${o},0,0,${+(f*m>c*h)},${this._x1=e+w*l},${this._y1=r+w*u}`}}arc(e,r,n,i,o,a){if(e=+e,r=+r,n=+n,a=!!a,n<0)throw new Error(`negative radius: ${n}`);let s=n*Math.cos(i),l=n*Math.sin(i),u=e+s,c=r+l,f=1^a,p=a?i-o:o-i;this._x1===null?this._append`M${u},${c}`:(Math.abs(this._x1-u)>ut||Math.abs(this._y1-c)>ut)&&this._append`L${u},${c}`,n&&(p<0&&(p=p%vr+vr),p>bs?this._append`A${n},${n},0,1,${f},${e-s},${r-l}A${n},${n},0,1,${f},${this._x1=u},${this._y1=c}`:p>ut&&this._append`A${n},${n},0,${+(p>=br)},${f},${this._x1=e+n*Math.cos(o)},${this._y1=r+n*Math.sin(o)}`)}rect(e,r,n,i){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+r}h${n=+n}v${+i}h${-n}Z`}toString(){return this._}};function $i(){return new ct}$i.prototype=ct.prototype;function Oi(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function ft(t,e){if(!isFinite(t)||t===0)return null;var r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"),n=t.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+t.slice(r+1)]}function V(t){return t=ft(Math.abs(t)),t?t[1]:NaN}function Ni(t,e){return function(r,n){for(var i=r.length,o=[],a=0,s=t[0],l=0;i>0&&s>0&&(l+s+1>n&&(s=Math.max(1,n-l)),o.push(r.substring(i-=s,i+s)),!((l+=s+1)>n));)s=t[a=(a+1)%t.length];return o.reverse().join(e)}}function Fi(t){return function(e){return e.replace(/[0-9]/g,function(r){return t[+r]})}}var ws=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Z(t){if(!(e=ws.exec(t)))throw new Error("invalid format: "+t);var e;return new Le({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}Z.prototype=Le.prototype;function Le(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}Le.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function Ii(t){t:for(var e=t.length,r=1,n=-1,i;r<e;++r)switch(t[r]){case".":n=i=r;break;case"0":n===0&&(n=r),i=r;break;default:if(!+t[r])break t;n>0&&(n=0);break}return n>0?t.slice(0,n)+t.slice(i+1):t}var Wt;function Pi(t,e){var r=ft(t,e);if(!r)return Wt=void 0,t.toPrecision(e);var n=r[0],i=r[1],o=i-(Wt=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,a=n.length;return o===a?n:o>a?n+new Array(o-a+1).join("0"):o>0?n.slice(0,o)+"."+n.slice(o):"0."+new Array(1-o).join("0")+ft(t,Math.max(0,e+o-1))[0]}function wr(t,e){var r=ft(t,e);if(!r)return t+"";var n=r[0],i=r[1];return i<0?"0."+new Array(-i).join("0")+n:n.length>i+1?n.slice(0,i+1)+"."+n.slice(i+1):n+new Array(i-n.length+2).join("0")}var _r={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:Oi,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>wr(t*100,e),r:wr,s:Pi,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function Sr(t){return t}var Di=Array.prototype.map,Vi=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function Hi(t){var e=t.grouping===void 0||t.thousands===void 0?Sr:Ni(Di.call(t.grouping,Number),t.thousands+""),r=t.currency===void 0?"":t.currency[0]+"",n=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",o=t.numerals===void 0?Sr:Fi(Di.call(t.numerals,String)),a=t.percent===void 0?"%":t.percent+"",s=t.minus===void 0?"\u2212":t.minus+"",l=t.nan===void 0?"NaN":t.nan+"";function u(f,p){f=Z(f);var m=f.fill,h=f.align,d=f.sign,g=f.symbol,v=f.zero,y=f.width,x=f.comma,b=f.precision,w=f.trim,_=f.type;_==="n"?(x=!0,_="g"):_r[_]||(b===void 0&&(b=12),w=!0,_="g"),(v||m==="0"&&h==="=")&&(v=!0,m="0",h="=");var C=(p&&p.prefix!==void 0?p.prefix:"")+(g==="$"?r:g==="#"&&/[boxX]/.test(_)?"0"+_.toLowerCase():""),k=(g==="$"?n:/[%p]/.test(_)?a:"")+(p&&p.suffix!==void 0?p.suffix:""),O=_r[_],Mt=/[defgprs%]/.test(_);b=b===void 0?6:/[gprs]/.test(_)?Math.max(1,Math.min(21,b)):Math.max(0,Math.min(20,b));function ht(S){var B=C,L=k,U,dt,jt;if(_==="c")L=O(S)+L,S="";else{S=+S;var Kt=S<0||1/S<0;if(S=isNaN(S)?l:O(Math.abs(S),b),w&&(S=Ii(S)),Kt&&+S==0&&d!=="+"&&(Kt=!1),B=(Kt?d==="("?d:s:d==="-"||d==="("?"":d)+B,L=(_==="s"&&!isNaN(S)&&Wt!==void 0?Vi[8+Wt/3]:"")+L+(Kt&&d==="("?")":""),Mt){for(U=-1,dt=S.length;++U<dt;)if(jt=S.charCodeAt(U),48>jt||jt>57){L=(jt===46?i+S.slice(U+1):S.slice(U))+L,S=S.slice(0,U);break}}}x&&!v&&(S=e(S,1/0));var Zt=B.length+S.length+L.length,W=Zt<y?new Array(y-Zt+1).join(m):"";switch(x&&v&&(S=e(W+S,W.length?y-L.length:1/0),W=""),h){case"<":S=B+S+L+W;break;case"=":S=B+W+S+L;break;case"^":S=W.slice(0,Zt=W.length>>1)+B+S+L+W.slice(Zt);break;default:S=W+B+S+L;break}return o(S)}return ht.toString=function(){return f+""},ht}function c(f,p){var m=Math.max(-8,Math.min(8,Math.floor(V(p)/3)))*3,h=Math.pow(10,-m),d=u((f=Z(f),f.type="f",f),{suffix:Vi[8+m/3]});return function(g){return d(h*g)}}return{format:u,formatPrefix:c}}var $e,Oe,Ne;kr({thousands:",",grouping:[3],currency:["$",""]});function kr(t){return $e=Hi(t),Oe=$e.format,Ne=$e.formatPrefix,$e}function Mr(t){return Math.max(0,-V(Math.abs(t)))}function Cr(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(V(e)/3)))*3-V(Math.abs(t)))}function Ar(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,V(e)-V(t))+1}function Bi(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t);break}return this}function Rr(t){return function(){return t}}function zr(t){return+t}var Wi=[0,1];function vt(t){return t}function Er(t,e){return(e-=t=+t)?function(r){return(r-t)/e}:Rr(isNaN(e)?NaN:.5)}function _s(t,e){var r;return t>e&&(r=t,t=e,e=r),function(n){return Math.max(t,Math.min(e,n))}}function Ss(t,e,r){var n=t[0],i=t[1],o=e[0],a=e[1];return i<n?(n=Er(i,n),o=r(a,o)):(n=Er(n,i),o=r(o,a)),function(s){return o(n(s))}}function ks(t,e,r){var n=Math.min(t.length,e.length)-1,i=new Array(n),o=new Array(n),a=-1;for(t[n]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++a<n;)i[a]=Er(t[a],t[a+1]),o[a]=r(e[a],e[a+1]);return function(s){var l=tr(t,s,1,n)-1;return o[l](i[l](s))}}function qi(t,e){return e.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function Ms(){var t=Wi,e=Wi,r=st,n,i,o,a=vt,s,l,u;function c(){var p=Math.min(t.length,e.length);return a!==vt&&(a=_s(t[0],t[p-1])),s=p>2?ks:Ss,l=u=null,f}function f(p){return p==null||isNaN(p=+p)?o:(l||(l=s(t.map(n),e,r)))(n(a(p)))}return f.invert=function(p){return a(i((u||(u=s(e,t.map(n),z)))(p)))},f.domain=function(p){return arguments.length?(t=Array.from(p,zr),c()):t.slice()},f.range=function(p){return arguments.length?(e=Array.from(p),c()):e.slice()},f.rangeRound=function(p){return e=Array.from(p),r=mr,c()},f.clamp=function(p){return arguments.length?(a=p?!0:vt,c()):a!==vt},f.interpolate=function(p){return arguments.length?(r=p,c()):r},f.unknown=function(p){return arguments.length?(o=p,f):o},function(p,m){return n=p,i=m,c()}}function Tr(){return Ms()(vt,vt)}function Lr(t,e,r,n){var i=er(t,e,r),o;switch(n=Z(n??",f"),n.type){case"s":{var a=Math.max(Math.abs(t),Math.abs(e));return n.precision==null&&!isNaN(o=Cr(i,a))&&(n.precision=o),Ne(n,a)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(o=Ar(i,Math.max(Math.abs(t),Math.abs(e))))&&(n.precision=o-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(o=Mr(i))&&(n.precision=o-(n.type==="%")*2);break}}return Oe(n)}function Cs(t){var e=t.domain;return t.ticks=function(r){var n=e();return oe(n[0],n[n.length-1],r??10)},t.tickFormat=function(r,n){var i=e();return Lr(i[0],i[i.length-1],r??10,n)},t.nice=function(r){r==null&&(r=10);var n=e(),i=0,o=n.length-1,a=n[i],s=n[o],l,u,c=10;for(s<a&&(u=a,a=s,s=u,u=i,i=o,o=u);c-- >0;){if(u=Ct(a,s,r),u===l)return n[i]=a,n[o]=s,e(n);if(u>0)a=Math.floor(a/u)*u,s=Math.ceil(s/u)*u;else if(u<0)a=Math.ceil(a*u)/u,s=Math.floor(s*u)/u;else break;l=u}return t},t}function wt(){var t=Tr();return t.copy=function(){return qi(t,wt())},Bi.apply(t,arguments),Cs(t)}function pt(t){return function(){return t}}function Gi(t){let e=3;return t.digits=function(r){if(!arguments.length)return e;if(r==null)e=null;else{let n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);e=n}return t},()=>new ct(e)}var td=Array.prototype.slice;function Xi(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function Yi(t){this._context=t}Yi.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e);break}}};function Ui(t){return new Yi(t)}function ji(t){return t[0]}function Ki(t){return t[1]}function qt(t,e){var r=pt(!0),n=null,i=Ui,o=null,a=Gi(s);t=typeof t=="function"?t:t===void 0?ji:pt(t),e=typeof e=="function"?e:e===void 0?Ki:pt(e);function s(l){var u,c=(l=Xi(l)).length,f,p=!1,m;for(n==null&&(o=i(m=a())),u=0;u<=c;++u)!(u<c&&r(f=l[u],u,l))===p&&((p=!p)?o.lineStart():o.lineEnd()),p&&o.point(+t(f,u,l),+e(f,u,l));if(m)return o=null,m+""||null}return s.x=function(l){return arguments.length?(t=typeof l=="function"?l:pt(+l),s):t},s.y=function(l){return arguments.length?(e=typeof l=="function"?l:pt(+l),s):e},s.defined=function(l){return arguments.length?(r=typeof l=="function"?l:pt(!!l),s):r},s.curve=function(l){return arguments.length?(i=l,n!=null&&(o=i(n)),s):i},s.context=function(l){return arguments.length?(l==null?n=o=null:o=i(n=l),s):n},s}function Q(t,e,r){this.k=t,this.x=e,this.y=r}Q.prototype={constructor:Q,scale:function(t){return t===1?this:new Q(this.k*t,this.x,this.y)},translate:function(t,e){return t===0&e===0?this:new Q(this.k,this.x+this.k*t,this.y+this.k*e)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var $r=new Q(1,0,0);Or.prototype=Q.prototype;function Or(t){for(;!t.__zoom;)if(!(t=t.parentNode))return $r;return t.__zoom}var Gt=class{static calculateBoundsFromTimeline(e,r){let n=1/0,i=-1/0,o=1/0,a=-1/0;if(r){let u=r.filter(c=>c.type==="plot"&&c.selector);for(let c of u)try{let f=A.parseAndCreateFunction(["s"],c.selector),m=f({x:0,y:0});if(Array.isArray(m)&&m.length===2){let d=e.times.map((g,v)=>{let y=Object.keys(e.states).reduce((x,b)=>(x[b]=e.states[b][v],x),{});return f(y)}).filter(g=>Array.isArray(g)&&g.length===2&&typeof g[0]=="number"&&typeof g[1]=="number");for(let g of d)n=Math.min(n,g[0]),i=Math.max(i,g[0]),o=Math.min(o,g[1]),a=Math.max(a,g[1])}else{let d=e.times.map((g,v)=>{let y=Object.keys(e.states).reduce((x,b)=>(x[b]=e.states[b][v],x),{});return f(y)}).filter(g=>typeof g=="number");n=Math.min(n,...e.times),i=Math.max(i,...e.times),o=Math.min(o,...d),a=Math.max(a,...d)}}catch(f){console.warn("Failed to analyze selector for bounds:",f)}}n===1/0&&e.times&&(n=Math.min(...e.times),i=Math.max(...e.times)),n===1/0&&(n=0),i===-1/0&&(i=10),o===1/0&&(o=-10),a===-1/0&&(a=10);let s=(i-n)*.05||.5,l=(a-o)*.05||.5;return{x:[n-s,i+s],y:[o-l,a+l]}}static areBoundsValid(e){return e&&Array.isArray(e.x)&&e.x.length===2&&Array.isArray(e.y)&&e.y.length===2&&typeof e.x[0]=="number"&&typeof e.x[1]=="number"&&typeof e.y[0]=="number"&&typeof e.y[1]=="number"&&e.x[0]<e.x[1]&&e.y[0]<e.y[1]}};var mt=class{static filterValidData(e,r){let n=[],i=[];for(let o=0;o<e.length;o++)e[o]!==null&&e[o]!==void 0&&r[o]!==null&&r[o]!==void 0&&isFinite(e[o])&&isFinite(r[o])&&(n.push(e[o]),i.push(r[o]));return{xValues:n,yValues:i}}static filterValidPoints(e){return e.filter(r=>Array.isArray(r)&&r.length===2&&typeof r[0]=="number"&&typeof r[1]=="number"&&isFinite(r[0])&&isFinite(r[1]))}};var H=class{static getProportionalMargins(e,r){if(e<600||r<400){let n=Math.min(e/800,r/600);return{top:Math.max(30,Math.round(50*n)),right:Math.max(40,Math.round(50*n)),bottom:Math.max(60,Math.round(80*n)),left:Math.max(70,Math.round(100*n))}}return this.DEFAULT_MARGINS}static calculateDimensions(e,r,n=this.DEFAULT_MARGINS){return{width:e,height:r,margins:n,plotWidth:e-n.left-n.right,plotHeight:r-n.top-n.bottom}}static createXScale(e,r=[0,10]){return wt().domain(r).range([80,e-50])}static createYScale(e,r=[0,10]){return wt().domain(r).range([e-50,50])}static createScales(e,r,n=[0,10],i=[0,10]){let o=this.createXScale(e,n),a=this.createYScale(r,i);return{xScale:o,yScale:a}}static updateScaleDomains(e,r,n){e.xScale.domain(r),e.yScale.domain(n)}static updateScaleRanges(e,r,n,i){if(i==="equal"){let u=r-80-50,c=n-50-50,f=Math.min(u,c),p=(u-f)/2,m=(c-f)/2;e.xScale.range([80+p,r-50-p]),e.yScale.range([n-50-m,50+m])}else e.xScale.range([80,r-50]),e.yScale.range([n-50,50])}};H.DEFAULT_MARGINS={top:50,right:50,bottom:80,left:100};var Y=class{static calculateNiceStep(e,r){if(e<=0)return 1;let n=e/r,i=Math.floor(Math.log10(n)),o=n/Math.pow(10,i),a;return o<=1.5?a=1:o<=3?a=2:o<=7?a=5:a=10,a*Math.pow(10,i)}static formatTickLabel(e,r){if(r>=1e3||r<.01&&r>0)return e.toExponential(1);let n=0;return r<1&&(n=Math.ceil(-Math.log10(r))),e.toFixed(n).replace(/\\.0+$/,"")}static calculateTicks(e,r){let n=e[1]-e[0],i=r[1]-r[0],o=this.calculateNiceStep(n,6),a=this.calculateNiceStep(i,5),s=Math.ceil(e[0]/o)*o,l=Math.ceil(r[0]/a)*a,u=[],c=[];for(let f=s;f<=e[1];f+=o)u.push(f);for(let f=l;f<=r[1];f+=a)c.push(f);return{xTicks:{values:u,labels:u.map(f=>this.formatTickLabel(f,o)),step:o},yTicks:{values:c,labels:c.map(f=>this.formatTickLabel(f,a)),step:a}}}};var Xt=class{constructor(e,r={}){this.container=e;this.options=r;let n=this.options.width||800,i=this.options.height||600,o=H.createScales(n,i,this.options.defaultBounds?.x||[0,10],this.options.defaultBounds?.y||[0,10]);this.scales={x:o.xScale,y:o.yScale},this.dimensions=H.calculateDimensions(n,i,this.options.margins),this.svg=this.createSVG(),this.g=this.svg.append("g")}createSVG(){return sr(this.container).append("svg").attr("width",this.dimensions.width).attr("height",this.dimensions.height)}getContext(e){return{svg:this.svg,g:this.g,xScale:this.scales.x,yScale:this.scales.y,width:this.dimensions.width,height:this.dimensions.height,margins:{top:20,right:20,bottom:40,left:60},params:e}}resize(e,r){this.svg.attr("width",e).attr("height",r),this.dimensions=H.calculateDimensions(e,r,this.options.margins),this.updateScaleRanges()}updateScaleRanges(){if(this.aspectRatio==="equal"){let o=this.dimensions.width-80-50,a=this.dimensions.height-50-80,s=Math.min(o,a),l=(o-s)/2,u=(a-s)/2;this.scales.x.range([80+l,this.dimensions.width-50-l]),this.scales.y.range([this.dimensions.height-80-u,50+u])}else this.scales.x.range([80,this.dimensions.width-50]),this.scales.y.range([this.dimensions.height-80,50])}updateDomains(e,r,n){n!==void 0&&(this.aspectRatio=n),this.scales.x.domain(e),this.scales.y.domain(r),this.updateScaleRanges()}clear(){this.g.selectAll("*").remove()}getDimensions(){return this.dimensions}destroy(){this.svg.remove()}};var Yt=class{constructor(e,r,n={}){this.element=e;this.callback=r;this.options=n;let{debounceMs:i=16,minSizeChange:o=1}=n;this.debouncedCallback=this.debounce(r,i),this.setupObserver()}setupObserver(){typeof ResizeObserver<"u"&&(this.observer=new ResizeObserver(e=>{for(let r of e){let{width:n,height:i}=r.contentRect;this.shouldResize(n,i)&&(this.debouncedCallback(n,i),this.lastWidth=n,this.lastHeight=i)}}),this.observer.observe(this.element))}shouldResize(e,r){let{minSizeChange:n=1}=this.options;return this.lastWidth===void 0||this.lastHeight===void 0?!0:Math.abs(e-this.lastWidth)>n||Math.abs(r-this.lastHeight)>n}debounce(e,r){let n;return(...i)=>{n!==void 0&&clearTimeout(n),n=window.setTimeout(()=>{e(...i)},r)}}checkResize(){let e=this.element.getBoundingClientRect(),{width:r,height:n}=e;this.shouldResize(r,n)&&(this.callback(r,n),this.lastWidth=r,this.lastHeight=n)}updateCallback(e){this.callback=e,this.debouncedCallback=this.debounce(e,this.options.debounceMs||16)}destroy(){this.observer&&(this.observer.disconnect(),this.observer=void 0)}};var Ie=class{render(e,r){let n=e.options||{},i=n.showGrid!==!1,o=n.gridColor||"#e0e0e0",a=n.gridOpacity||.3,s=n.gridWidth||1,l=n.gridStyle||"dashed",u=n.showMinorGrid||!1,c=n.minorGridColor||"#f0f0f0",f=n.minorGridOpacity||.3;if(!i)return;let p=r.g.append("g").attr("class","grid-group");p.selectAll(".grid-line-x, .grid-line-y, .minor-grid-line-x, .minor-grid-line-y").remove();let m={x:[r.xScale.domain()[0],r.xScale.domain()[1]],y:[r.yScale.domain()[0],r.yScale.domain()[1]]},{xTicks:h,yTicks:d}=Y.calculateTicks(m.x,m.y),g="";switch(l){case"dashed":g="2,2";break;case"dotted":g="1,1";break;default:g="none"}if(h&&h.values&&h.values.length>0){let v=r.margins;p.selectAll(".grid-line-x").data(h.values).enter().append("line").attr("class","grid-line-x").attr("x1",y=>r.xScale(y)).attr("y1",v.top).attr("x2",y=>r.xScale(y)).attr("y2",r.height-v.bottom).attr("stroke",o).attr("stroke-opacity",a).attr("stroke-width",s).attr("stroke-dasharray",g).attr("shape-rendering","crispEdges")}if(d&&d.values&&d.values.length>0){let v=r.margins;p.selectAll(".grid-line-y").data(d.values).enter().append("line").attr("class","grid-line-y").attr("x1",v.left).attr("y1",y=>r.yScale(y)).attr("x2",r.width-v.right).attr("y2",y=>r.yScale(y)).attr("stroke",o).attr("stroke-opacity",a).attr("stroke-width",s).attr("stroke-dasharray",g).attr("shape-rendering","crispEdges")}if(u){let v=this.getMinorTicks(r.xScale),y=this.getMinorTicks(r.yScale);p.selectAll(".minor-grid-line-x").data(v).enter().append("line").attr("class","minor-grid-line-x").attr("x1",x=>r.xScale(x)).attr("y1",0).attr("x2",x=>r.xScale(x)).attr("y2",r.height).attr("stroke",c).attr("stroke-opacity",f).attr("stroke-width",s*.5).attr("shape-rendering","crispEdges"),p.selectAll(".minor-grid-line-y").data(y).enter().append("line").attr("class","minor-grid-line-y").attr("x1",0).attr("y1",x=>r.yScale(x)).attr("x2",r.width).attr("y2",x=>r.yScale(x)).attr("stroke",c).attr("stroke-opacity",f).attr("stroke-width",s*.5).attr("shape-rendering","crispEdges")}}getMinorTicks(e){let r=e.ticks();if(r.length<2)return[];let n=[];for(let i=0;i<r.length-1;i++){let o=r[i],s=(r[i+1]-o)/5;for(let l=1;l<5;l++)n.push(o+l*s)}return n}};var Pe=class{render(e,r){let n=e.options||{},i=n.showTicks!==!1,o=n.showLabels!==!1,a=n.xLabel,s=n.yLabel,l=n.tickSize||5,u=n.tickPadding||8,c=n.labelPadding||32,f=n.fontSize||12,p=n.tickColor||"#666",m=n.labelColor||"#333",h=n.axisColor||"#666",d=n.axisWidth||2,g=n.showSpine!==!1;r.g.selectAll(".plot-frame, .x-label, .y-label").remove();let v={x:[r.xScale.domain()[0],r.xScale.domain()[1]],y:[r.yScale.domain()[0],r.yScale.domain()[1]]},{xTicks:y,yTicks:x}=Y.calculateTicks(v.x,v.y);if(g){let b=r.margins,w=Math.max(0,r.width-b.left-b.right),_=Math.max(0,r.height-b.top-b.bottom);w>0&&_>0&&r.g.append("rect").attr("class","plot-frame calcplot-frame").attr("x",b.left).attr("y",b.top).attr("width",w).attr("height",_).attr("fill","none").attr("stroke",h).attr("stroke-width",d).attr("rx",2).attr("ry",2)}if(i||o){let b=r.g.append("g").attr("class","ticks-group"),w=r.margins,_=r.height-w.bottom;y.values.forEach(C=>{let k=r.xScale(C);i&&b.append("line").attr("class","calcplot-tick-line").attr("x1",k).attr("y1",_).attr("x2",k).attr("y2",_+l).attr("stroke",h).attr("stroke-width",d),o&&b.append("text").attr("class","calcplot-tick-text").attr("x",k).attr("y",_+l+u).attr("text-anchor","middle").attr("dominant-baseline","hanging").style("font-size",`${f}px`).style("fill",p).text(Y.formatTickLabel(C,y.step))})}if(i||o){let b=r.g.append("g").attr("class","y-ticks-group"),_=r.margins.left;x.values.forEach(C=>{let k=r.yScale(C);i&&b.append("line").attr("class","calcplot-tick-line").attr("x1",_).attr("y1",k).attr("x2",_-l).attr("y2",k).attr("stroke",h).attr("stroke-width",d),o&&b.append("text").attr("class","calcplot-tick-text").attr("x",_-l-u).attr("y",k).attr("text-anchor","end").attr("dominant-baseline","middle").style("font-size",`${f}px`).style("fill",p).text(Y.formatTickLabel(C,x.step))})}if(a||s){let b=r.g.append("g").attr("class","labels-group"),w=l+u+c,_=l+u+c;if(a&&o){let C=r.margins;b.append("text").attr("class","x-label calcplot-axis-label").attr("x",r.width/2).attr("y",r.height-C.bottom+w).style("font-weight","bold").style("font-size","14px").style("fill",m).text(a)}if(s&&o){let C=r.margins,k=(r.height-C.bottom+C.top)/2;b.append("text").attr("class","y-label calcplot-axis-label").attr("transform",`translate(${C.left-_}, ${k}) rotate(-90)`).attr("text-anchor","middle").style("font-weight","bold").style("font-size","14px").style("fill",m).text(s)}}}};var De=class{render(e,r,n){if(!n)return;let i=this.extractPlotData(n,e,r);if(i){let o=mt.filterValidData(i.xValues,i.yValues);if(o.xValues.length>0){let a=r.g.append("g").attr("class","plot-group"),s=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],l=e.options?.color||s[e.index%s.length],u=e.options?.lineWidth||1.5,c=e.options?.opacity||1,f=e.options?.dash||[],p=qt().x((m,h)=>r.xScale(o.xValues[h])).y((m,h)=>r.yScale(o.yValues[h]));a.append("path").datum(o.xValues).attr("class",`plot-line plot-${e.index}`).attr("d",p).attr("fill","none").attr("stroke",l).attr("stroke-width",u).attr("stroke-opacity",c).attr("stroke-dasharray",f.join(" ")).attr("shape-rendering","geometricPrecision")}}}extractPlotData(e,r,n){let{selector:i}=r,o=!1;try{let s={x:0,y:0},l=n.params||{},u=A.parseAndCreateFunction(["s","p"],i)(s,l);o=Array.isArray(u)&&u.length===2}catch{try{let l={x:0,y:0},u=A.parseAndCreateFunction(["s"],i)(l);o=Array.isArray(u)&&u.length===2}catch(l){return console.warn("Parametric check failed:",l),null}}let a;try{a=A.parseAndCreateFunction(["s","p"],i)}catch{a=A.parseAndCreateFunction(["s"],i)}if(o){let s=e.times.map((f,p)=>{let m=Object.keys(e.states).reduce((d,g)=>(d[g]=e.states[g][p],d),{});return a(m,n.params)}),l=mt.filterValidPoints(s),u=l.map(f=>f[0]),c=l.map(f=>f[1]);return{xValues:u,yValues:c}}else{let s=e.times.map((c,f)=>{let p=Object.keys(e.states).reduce((h,d)=>(h[d]=e.states[d][f],h),{});return a(p,n.params)}),l=e.times;return mt.filterValidData(l,s)}}};var Ve=class{render(e,r,n){if(!n)return;let{at:i,dir:o,options:a={}}=e;if(!i||!o)return;let s,l;try{s=A.parseAndCreateFunction(["s","p"],i)}catch{s=A.parseAndCreateFunction(["s"],i)}try{l=A.parseAndCreateFunction(["s","p"],o)}catch{l=A.parseAndCreateFunction(["s"],o)}let u=[];if(n.times.forEach((c,f)=>{let p=Object.keys(n.states).reduce((m,h)=>(m[h]=n.states[h][f],m),{});try{let m=s(p,r.params),h=l(p,r.params);Array.isArray(m)&&m.length===2&&Array.isArray(h)&&h.length===2&&u.push({x:m[0],y:m[1],vx:h[0],vy:h[1]})}catch(m){console.warn("Error in vector functions:",m)}}),u.length>0){let c=a.scale||1,f=a.color||"#666";r.svg.append("defs").append("marker").attr("id","arrowhead").attr("viewBox","-0 -5 10 10").attr("refX",8).attr("refY",0).attr("markerWidth",6).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0,-5 L 10,0 L 0,5").attr("fill",f),r.g.selectAll(".vector").data(u).enter().append("line").attr("class","vector").attr("x1",m=>r.xScale(m.x)).attr("y1",m=>r.yScale(m.y)).attr("x2",m=>r.xScale(m.x+m.vx*c)).attr("y2",m=>r.yScale(m.y+m.vy*c)).attr("stroke",f).attr("stroke-width",1.5).attr("marker-end","url(#arrowhead)")}}};var He=class{render(e,r,n){if(!n)return;let{draw:i}=e;if(!i)return;let o;try{o=A.parseAndCreateFunction(["ctx","state"],i)}catch(s){console.warn("Failed to compile scene function:",s);return}let a=this.createD3DrawContext(r);n.times.forEach((s,l)=>{let u=Object.keys(n.states).reduce((c,f)=>(c[f]=n.states[f][l],c),{});try{o(a,u)}catch(c){console.warn("Error in scene function:",c)}})}createD3DrawContext(e){return{plot:(r,n,i)=>{let o=i?.color||"#000",a=qt().x((s,l)=>e.xScale(r[l])).y((s,l)=>e.yScale(n[l]));e.g.append("path").datum(r).attr("d",a).attr("fill","none").attr("stroke",o).attr("stroke-width",i?.width||2)},line:(r,n,i)=>{e.g.append("line").attr("x1",e.xScale(r[0])).attr("y1",e.yScale(r[1])).attr("x2",e.xScale(n[0])).attr("y2",e.yScale(n[1])).attr("stroke",i?.color||"#000").attr("stroke-width",i?.width||1)},circle:(r,n,i)=>{e.g.append("circle").attr("cx",e.xScale(r[0])).attr("cy",e.yScale(r[1])).attr("r",n).attr("fill",i?.fill||"none").attr("stroke",i?.stroke||"#000").attr("stroke-width",i?.width||1)},arrow:(r,n,i)=>{let o=i?.color||"#000",a=i?.width||1;e.svg.select("#arrowhead-scene").node()||e.svg.append("defs").append("marker").attr("id","arrowhead-scene").attr("viewBox","-0 -5 10 10").attr("refX",8).attr("refY",0).attr("markerWidth",6).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0,-5 L 10,0 L 0,5").attr("fill",o),e.g.append("line").attr("x1",e.xScale(r[0])).attr("y1",e.yScale(r[1])).attr("x2",e.xScale(n[0])).attr("y2",e.yScale(n[1])).attr("stroke",o).attr("stroke-width",a).attr("marker-end","url(#arrowhead-scene)")},text:(r,n,i)=>{e.g.append("text").attr("x",e.xScale(r[0])).attr("y",e.yScale(r[1])).attr("fill",i?.color||"#000").attr("font-size",i?.size||12).attr("font-family",i?.font||"sans-serif").text(n)}}}};var Be=class{render(e,r){let n=e.options||{},i=e.items||[];if(i.length===0)return;let o=n.position||"top-right",a=n.backgroundColor||"rgba(255, 255, 255, 0.75)",s=n.borderColor||"#ccc",l=n.borderWidth||1,u=n.padding||10,c=n.itemHeight||20,f=n.itemWidth||30,p=n.fontSize||12,m=n.fontColor||"#333",h=n.opacity||1,d=r.g.append("text").style("font-size",`${p}px`).style("font-family",'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif').style("visibility","hidden"),g=0;i.forEach(_=>{d.text(_.label);let C=d.node()?.getBBox()?.width||0;g=Math.max(g,C)}),d.remove();let v=f+u*2+g+10,y=i.length*c+u*2,x=this.calculatePosition(o,v,y,r),b=r.g.append("g").attr("class","legend").attr("opacity",h);if(a){let k=Math.max(100,v),O=Math.max(30,y);b.append("rect").attr("class","legend-background").attr("x",x.x).attr("y",x.y).attr("width",k).attr("height",O).attr("fill",a).attr("stroke",s).attr("stroke-width",l).attr("rx",4)}let w=b.append("g").attr("class","legend-items");i.forEach((_,C)=>{let k=x.y+u+C*c+c/2;w.append("g").attr("class","legend-item").attr("transform",`translate(${x.x+u}, ${k})`).append("line").attr("x1",0).attr("x2",f).attr("y1",0).attr("y2",0).attr("stroke",_.color).attr("stroke-width",_.lineWidth||2).attr("stroke-dasharray",_.dash?_.dash.join(","):"none"),w.append("text").attr("class","legend-label").attr("x",x.x+u+f+5).attr("y",k).attr("dy","0.35em").style("font-size",`${p}px`).style("fill",m).text(_.label)})}calculatePosition(e,r,n,i){let s=i.margins,l=s.left+2,u=i.width-s.right-2,c=s.top+2,f=i.height-s.bottom-2,p;switch(e){case"top-left":p={x:l+10,y:c+10};break;case"top-right":p={x:u-r-10,y:c+10};break;case"bottom-left":p={x:l+10,y:f-n-10};break;case"bottom-right":p={x:u-r-10,y:f-n-10};break;default:p={x:u-r-10,y:c+10}}return p}};var We=class{render(e,r){let{svg:n,xScale:i,yScale:o}=r,{selector:a,options:s}=e;if(!a)return;let l=new Function("state",`return ${a}`),{color:u="blue",alpha:c=.2}=s,f=r.timeline;if(!f||!f.times||!f.states)return;let p=[],m=null;f.times.forEach((d,g)=>{let v={time:d,...Object.fromEntries(Object.keys(f.states).map(b=>[b,f.states[b][g]]))},y=i(v.x||0),x=o(v.y||0);l(v)?(m===null?p.push(`M ${y} ${x}`):p.push(`L ${y} ${x}`),m=y):m!==null&&(p.push(`L ${y} ${o(0)} L ${m} ${o(0)} Z`),m=null)}),m!==null&&p.push(`L ${m} ${o(0)} Z`);let h=document.createElementNS("http://www.w3.org/2000/svg","path");h.setAttribute("d",p.join(" ")),h.setAttribute("fill",u),h.setAttribute("fill-opacity",String(c)),h.setAttribute("stroke","none"),n.node().appendChild(h)}};var qe=class{render(e,r){let{g:n,xScale:i,yScale:o}=r,{options:a}=e,{orientation:s,value:l,color:u="gray",linestyle:c="solid",linewidth:f=1,label:p,labelPosition:m="auto",labelOffset:h=8}=a,d=2,g={left:(r.margins?.left||60)+d,right:r.width-(r.margins?.right||40)-d,top:(r.margins?.top||40)+d,bottom:r.height-(r.margins?.bottom||40)-d},v=i.domain(),y=o.domain(),x=n.append("g").attr("class","refline-group");if(s==="horizontal"){if(l>=y[0]&&l<=y[1]){let b=o(l);x.append("line").attr("class","refline").attr("x1",g.left).attr("x2",g.right).attr("y1",b).attr("y2",b).attr("stroke",u).attr("stroke-width",f).attr("stroke-dasharray",c==="dashed"?"5, 5":c==="dotted"?"2, 2":null),p&&this.renderLabel(n,s,l,p,u,g,m,h,i,o)}}else if(s==="vertical"&&l>=v[0]&&l<=v[1]){let b=i(l);x.append("line").attr("class","refline").attr("x1",b).attr("x2",b).attr("y1",g.top).attr("y2",g.bottom).attr("stroke",u).attr("stroke-width",f).attr("stroke-dasharray",c==="dashed"?"5, 5":c==="dotted"?"2, 2":null),p&&this.renderLabel(n,s,l,p,u,g,m,h,i,o)}}renderLabel(e,r,n,i,o,a,s,l,u,c){e.selectAll(".refline-label").remove();let f=s;if(f==="auto"&&(f=this.findBestLabelPosition(r,n,a,u,c)),r==="horizontal"){let p=c(n),m,h,d,g;switch(f){case"left":m=a.left+l,h=p-l/2,d="start",g="bottom";break;case"right":m=a.right-l,h=p-l/2,d="end",g="bottom";break;case"top":m=a.left+l,h=p-l,d="start",g="bottom";break;case"bottom":m=a.left+l,h=p+l,d="start",g="hanging";break;default:m=a.left+l,h=p-l,d="start",g="bottom"}e.append("text").attr("class","refline-label").attr("x",m).attr("y",h).attr("text-anchor",d).attr("dominant-baseline",g).attr("fill",o).attr("font-size","11").attr("font-family","Arial, sans-serif").attr("font-style","italic").text(i)}else if(r==="vertical"){let p=u(n),m,h,d,g;switch(f){case"top":m=p+l/2,h=a.top+l,d="start",g="hanging";break;case"bottom":m=p+l/2,h=a.bottom-l,d="start",g="bottom";break;case"left":m=p-l,h=a.top+l,d="end",g="hanging";break;case"right":m=p+l,h=a.top+l,d="start",g="hanging";break;default:m=p+l,h=a.top+l,d="start",g="hanging"}e.append("text").attr("class","refline-label").attr("x",m).attr("y",h).attr("text-anchor",d).attr("dominant-baseline",g).attr("fill",o).attr("font-size","11").attr("font-family","Arial, sans-serif").attr("font-style","italic").text(i)}}findBestLabelPosition(e,r,n,i,o){if(e==="horizontal"){let a=o(r),s=(n.top+n.bottom)/2;return a<s?"bottom":"top"}else{let a=i(r),s=(n.left+n.right)/2;return a<s?"right":"left"}}};var _t=class _t{render(e,r){let{svg:n,xScale:i,yScale:o}=r,{options:a}=e,{text:s}=a;if(!s)return;let l=`${s}_${r.width}_${r.height}`;if(_t.renderedTitles.has(l))return;_t.renderedTitles.add(l),n.selectAll(".plot-title").remove();let u=document.createElementNS("http://www.w3.org/2000/svg","text");u.setAttribute("class","plot-title");let c=(i.range()[0]+i.range()[1])/2,f=(r.margins?.top||40)/2;u.setAttribute("x",String(c)),u.setAttribute("y",String(f)),u.setAttribute("text-anchor","middle"),u.setAttribute("font-size","16px"),u.setAttribute("font-family","Arial, sans-serif"),u.setAttribute("font-weight","bold"),u.setAttribute("fill","#333"),u.textContent=s,n.node()?.appendChild(u)}static clearCache(){_t.renderedTitles.clear()}};_t.renderedTitles=new Set;var Ge=_t;var Xe=class{render(e,r){let{svg:n,xScale:i,yScale:o}=r,{selector:a,options:s}=e;if(!a)return;let l=new Function("state","params",`return ${a}`),{gridSize:u=20,color:c="gray",alpha:f=.6,normalize:p=!0,scale:m=1}=s,h=i.domain(),d=o.domain(),g=(h[1]-h[0])/u,v=(d[1]-d[0])/u;for(let y=0;y<u;y++)for(let x=0;x<u;x++){let b=h[0]+(y+.5)*g,w=d[0]+(x+.5)*v,C=l({x:b,y:w,v:w,time:0},{}),{dx:k,dy:O}=C,Mt=k,ht=O;if(p){let dt=Math.sqrt(k*k+O*O);dt>0&&(Mt=k/dt*m,ht=O/dt*m)}else Mt=k*m,ht=O*m;let S=i(b),B=o(w),L=i(b+Mt),U=o(w+ht);this.drawArrow(n,S,B,L,U,c,f)}}drawArrow(e,r,n,i,o,a,s){let l=document.createElementNS("http://www.w3.org/2000/svg","line");l.setAttribute("x1",String(r)),l.setAttribute("y1",String(n)),l.setAttribute("x2",String(i)),l.setAttribute("y2",String(o)),l.setAttribute("stroke",a),l.setAttribute("stroke-width","1"),l.setAttribute("stroke-opacity",String(s)),e.node().appendChild(l);let u=Math.atan2(o-n,i-r),c=6,f=Math.PI/6,p=i-c*Math.cos(u-f),m=o-c*Math.sin(u-f),h=i-c*Math.cos(u+f),d=o-c*Math.sin(u+f),g=document.createElementNS("http://www.w3.org/2000/svg","path");g.setAttribute("d",`M ${i} ${o} L ${p} ${m} M ${i} ${o} L ${h} ${d}`),g.setAttribute("stroke",a),g.setAttribute("stroke-width","1"),g.setAttribute("stroke-opacity",String(s)),e.node().appendChild(g)}};var Ye=class{render(e,r){let{svg:n,xScale:i,yScale:o}=r,{selector:a,options:s}=e;if(!a)return;let l=a,{color:u="red",linestyle:c="dashed",linewidth:f=1,label:p}=s,m=i.domain(),h=o.domain(),d=50,g=(m[1]-m[0])/d,v=(h[1]-h[0])/d,y=[];for(let x=0;x<=d;x++){let b=m[0]+(m[1]-m[0])*x/d,w;l==="x"?w=0:w=Math.sin(b)*2,w>=h[0]&&w<=h[1]&&y.push([b,w])}if(y.length>0){let x=document.createElementNS("http://www.w3.org/2000/svg","path");y.sort((w,_)=>w[0]-_[0]);let b=`M ${i(y[0][0])} ${o(y[0][1])}`;for(let w=1;w<y.length;w++)b+=` L ${i(y[w][0])} ${o(y[w][1])}`;if(x.setAttribute("d",b),x.setAttribute("stroke",u),x.setAttribute("stroke-width",String(f)),x.setAttribute("fill","none"),c==="dashed"?x.setAttribute("stroke-dasharray","5, 5"):c==="dotted"&&x.setAttribute("stroke-dasharray","2, 2"),n.node().appendChild(x),p&&y.length>0){let w=document.createElementNS("http://www.w3.org/2000/svg","text");w.setAttribute("x",String(i(y[Math.floor(y.length/2)][0]))),w.setAttribute("y",String(o(y[Math.floor(y.length/2)][1])-5)),w.setAttribute("fill",u),w.setAttribute("font-size","12"),w.setAttribute("font-family","Arial, sans-serif"),w.textContent=p,n.node().appendChild(w)}}}};var Ue=class{render(e,r){let{svg:n,xScale:i,yScale:o}=r,{selector:a,options:s}=e;if(!a)return;let l=new Function("state",`return ${a}`),{direction:u="positive",marker:c="circle",color:f="red",size:p=4}=s,m=r.timeline;if(!m)return;this.findPoincarePoints(m,l,u).forEach(d=>{let g=i(d.x),v=o(d.y);if(c==="circle"){let y=document.createElementNS("http://www.w3.org/2000/svg","circle");y.setAttribute("cx",String(g)),y.setAttribute("cy",String(v)),y.setAttribute("r",String(p)),y.setAttribute("fill",f),n.node().appendChild(y)}else if(c==="cross"){let y=document.createElementNS("http://www.w3.org/2000/svg","g");y.setAttribute("transform",`translate(${g}, ${v})`);let x=document.createElementNS("http://www.w3.org/2000/svg","line");x.setAttribute("x1",String(-p)),x.setAttribute("y1",String(-p)),x.setAttribute("x2",String(p)),x.setAttribute("y2",String(p)),x.setAttribute("stroke",f),x.setAttribute("stroke-width","2");let b=document.createElementNS("http://www.w3.org/2000/svg","line");b.setAttribute("x1",String(-p)),b.setAttribute("y1",String(p)),b.setAttribute("x2",String(p)),b.setAttribute("y2",String(-p)),b.setAttribute("stroke",f),b.setAttribute("stroke-width","2"),y.appendChild(x),y.appendChild(b),n.node().appendChild(y)}})}findPoincarePoints(e,r,n){let i=[],o=e.times,a=e.states,s=Object.keys(a);for(let l=1;l<o.length;l++){let u={time:o[l-1],...Object.fromEntries(s.map(m=>[m,a[m][l-1]]))},c={time:o[l],...Object.fromEntries(s.map(m=>[m,a[m][l]]))},f=r(u)?1:-1,p=r(c)?1:-1;if(f*p<0){let m=p>f?"positive":"negative";if(n==="both"||n===m){let h=Math.abs(f)/(Math.abs(p)+Math.abs(f)),d={time:u.time+h*(c.time-u.time),...Object.fromEntries(s.map(v=>[v,u[v]+h*(c[v]-u[v])]))},g={x:d.x||d.x1||0,y:d.y||d.x2||d.v||0,time:d.time};i.push(g)}}}return i}};var je=class{constructor(){this.renderers=new Map;this.registerDefaultRenderers()}registerDefaultRenderers(){this.register("grid",new Ie),this.register("axis",new Pe),this.register("plot",new De),this.register("vector",new Ve),this.register("scene",new He),this.register("legend",new Be),this.register("fill",new We),this.register("refline",new qe),this.register("title",new Ge),this.register("vectorField",new Xe),this.register("nullcline",new Ye),this.register("poincare",new Ue)}register(e,r){this.renderers.set(e,r)}getRenderer(e){let r=this.renderers.get(e);if(!r)throw new Error(`No renderer registered for type: ${e}`);return r}hasRenderer(e){return this.renderers.has(e)}getRegisteredTypes(){return Array.from(this.renderers.keys())}unregister(e){return this.renderers.delete(e)}clear(){this.renderers.clear()}reset(){this.clear(),this.registerDefaultRenderers()}};var Ke=!1,Zi=!1,I=class{constructor(e,r=800,n=480,i){this.isResizing=!1;this.container=e,this.log=i,this.targetWidth=r,this.targetHeight=n,this.applyCalcplotStyles(),this.svgManager=new Xt(e,{width:r,height:n,defaultBounds:{x:[0,10],y:[0,10]}}),this.resizeManager=new Yt(e,this.onResize.bind(this),{debounceMs:16}),this.layerRendererFactory=new je,this.boundsCalculator=Gt}applyCalcplotStyles(){this.container.classList.contains("calcplot-style")||this.container.classList.add("calcplot-style","calcplot-view"),!(Zi||Ke)&&(Ke=!0,fetch("/dist/calcplot-client.css").then(e=>{if(!e.ok)throw new Error(`Failed to load CSS: ${e.status}`);return e.text()}).then(e=>{let r=document.createElement("style");r.id="calcplot-styles",r.textContent=e,document.head.appendChild(r),Zi=!0,Ke=!1}).catch(e=>{console.warn("Failed to load calcplot styles:",e),Ke=!1}))}onResize(e,r){(e!==this.targetWidth||r!==this.targetHeight)&&!this.isResizing&&(this.resizeTimeout&&clearTimeout(this.resizeTimeout),this.resizeTimeout=window.setTimeout(()=>{this.updateSize(e,r)},16))}updateSize(e,r){if(!this.isResizing){if(this.isResizing=!0,Math.abs(e-this.targetWidth)<=1&&Math.abs(r-this.targetHeight)<=1){this.isResizing=!1;return}this.targetWidth=e,this.targetHeight=r,this.svgManager.resize(e,r),this.currentData&&this.renderInternal(this.currentData),setTimeout(()=>{this.isResizing=!1},50)}}extractLayers(e){let r=e.layers||[];return e.viewDescriptor&&e.viewDescriptor.layers&&(r=e.viewDescriptor.layers),r}renderInternal(e){this.svgManager.getContext().g.selectAll("*").remove();let n=this.extractLayers(e),i,o=n.find(u=>u.type==="bounds");o&&o.bounds?i=o.bounds:i=this.boundsCalculator.calculateBoundsFromTimeline(e.timeline,n),this.boundsCalculator.areBoundsValid(i)||(this.log("Invalid bounds, using defaults"),i={x:[0,10],y:[0,10]}),(i.x[1]<=i.x[0]||i.y[1]<=i.y[0])&&(this.log("Invalid bounds (negative or zero), using defaults"),i={x:[0,10],y:[0,10]});let s=n.find(u=>u.type==="axis")?.options?.aspectRatio;this.svgManager.updateDomains(i.x,i.y,s);let l=this.svgManager.getContext(e.params);l.margins=H.getProportionalMargins(l.width,l.height),this.renderLayers(n,l,e.timeline)}renderLayers(e,r,n){let i=new Map,o=[];e.forEach(s=>{i.has(s.type)||i.set(s.type,[]),s.type==="plot"&&s.options?.label&&o.push({label:s.options.label,color:s.options?.color||`hsl(${(s.index||0)*60}, 70%, 50%)`,dash:s.options?.dash||[],lineWidth:s.options?.lineWidth||2}),i.get(s.type).push(s)}),o.length>0&&(i.has("legend")||i.set("legend",[]),i.get("legend").push({type:"legend",items:o,options:{position:"top-right",backgroundColor:"rgba(255, 255, 255, 0.9)",borderColor:"#ccc",borderWidth:1,padding:10,fontSize:12,fontColor:"#333"}}));let a=["title","axis","grid","vectorField","nullcline","fill","plot","refline","poincare","legend"];for(let s of a){if(!i.has(s))continue;let l=i.get(s);if(this.layerRendererFactory.hasRenderer(s)){let u=this.layerRendererFactory.getRenderer(s);s==="plot"?l.forEach((c,f)=>{let p={...c,index:f};u.render(p,r,n)}):l.forEach(c=>{u.render(c,r,n)})}else this.log(`No renderer found for layer type: ${s}`)}}render(e){if(!e.timeline){this.log("No timeline in data!",e);return}this.currentData=e,this.renderInternal(e)}renderExplore(e,r){this.render({type:"view",timeline:r,layers:e.layers,options:e.options,viewDescriptor:e.viewDescriptor})}getLayerRendererFactory(){return this.layerRendererFactory}getSVGManager(){return this.svgManager}getRenderContext(){return this.svgManager.getContext(this.currentData?.params)}checkResize(){this.resizeManager.checkResize()}destroy(){this.resizeManager.destroy(),this.currentData=void 0}};function J(t,e,r,n=!1){if(t==="auto"&&n){let i=e.clientWidth;return i&&i>0?i:r}return typeof t=="number"?t:r}function Qi(t,e,r){let n=P("style",{textContent:`
|
|
2
|
+
.calcplot-controls {
|
|
3
|
+
margin: 16px 12px;
|
|
4
|
+
display: table;
|
|
5
|
+
border-collapse: collapse;
|
|
6
|
+
}
|
|
7
|
+
.control-group {
|
|
8
|
+
display: table-row;
|
|
9
|
+
height: 24px;
|
|
10
|
+
}
|
|
11
|
+
.control-group label {
|
|
12
|
+
display: table-cell;
|
|
13
|
+
font-weight: 500;
|
|
14
|
+
margin: 0;
|
|
15
|
+
font-size: 14px;
|
|
16
|
+
text-align: right;
|
|
17
|
+
padding-right: 12px;
|
|
18
|
+
padding-left: 2px;
|
|
19
|
+
vertical-align: middle;
|
|
20
|
+
white-space: nowrap;
|
|
21
|
+
}
|
|
22
|
+
.control-group input[type="range"] {
|
|
23
|
+
display: table-cell;
|
|
24
|
+
margin: 0;
|
|
25
|
+
vertical-align: middle;
|
|
26
|
+
width: 150px;
|
|
27
|
+
padding: 0;
|
|
28
|
+
}
|
|
29
|
+
.control-group .value-display {
|
|
30
|
+
display: table-cell;
|
|
31
|
+
text-align: left;
|
|
32
|
+
font-family: monospace;
|
|
33
|
+
font-size: 14px;
|
|
34
|
+
color: #374151;
|
|
35
|
+
vertical-align: middle;
|
|
36
|
+
width: 60px;
|
|
37
|
+
padding-left: 12px;
|
|
38
|
+
padding-right: 2px;
|
|
39
|
+
}
|
|
40
|
+
.control-group input[type="checkbox"] {
|
|
41
|
+
display: table-cell;
|
|
42
|
+
margin: 0;
|
|
43
|
+
transform: scale(1.2);
|
|
44
|
+
vertical-align: middle;
|
|
45
|
+
}
|
|
46
|
+
`});e.appendChild(n);let i=P("div",{className:"calcplot-controls"});e.appendChild(i),Object.entries(t.params).forEach(([o,a])=>{(a.type==="slider"||a.type==="checkbox")&&(a.value=a.default)}),Object.entries(t.params).forEach(([o,a])=>{if(a.type==="slider"){let s=window.CalcPlotComponents.createSlider;s?s(i,{id:o,control:a,value:a.default,onChange:(l,u)=>{t.params[l]&&(t.params[l].value=u),r?.onUpdate?.()}}):r?.log?.("createSlider not available")}else if(a.type==="checkbox"){let s=window.CalcPlotComponents.createCheckbox;s?s(i,{id:o,control:a,value:a.default,onChange:(l,u)=>{t.params[l]&&(t.params[l].value=u),r?.onUpdate?.()}}):r?.log?.("createCheckbox not available")}})}function Ji(t){let e={};return Object.entries(t.params).forEach(([r,n])=>{if(n.type==="slider"){let i=n;e[r]=i.value!==void 0?i.value:i.default}else if(n.type==="checkbox"){let i=n;e[r]=i.value!==void 0?i.value:i.default}}),e}function St(t){return typeof t=="number"?`${t}px`:t}function kt(t,e){if(typeof t=="number")return t;let r=parseInt(t);return isNaN(r)?e:r}function to(t,e,r,n){let i=P("div",{style:`display: flex; width: ${e}; min-height: ${r}; gap: ${n}px;`});return t.appendChild(i),i}function eo(t,e,r,n,i){let o=kt(r,800),a=kt(n,480),s=Math.floor(o/t.length),l=a;return t.map((u,c)=>{let f=P("div",{style:`width: ${s}px; min-height: ${l}px; flex: 1; min-width: 0;`});return e.appendChild(f),new I(f,s,l,i)})}function ro(t,e,r,n,i,o){let a={columns:e.length,rows:1,gaps:10},s=Math.floor(i/e.length),l=o;e.forEach((u,c)=>{let f;u.layers&&Array.isArray(u.layers)?f={type:"view",layers:u.layers,options:u.options}:f={type:"view",layers:[],options:{}};let p=t[c];p&&p.render({type:"view",timeline:r,layers:f.layers,viewDescriptor:f,options:f.options,width:s,height:l})})}function no(t,e,r){try{let h=function(){let d=Ji(t),g=Object.keys(d).length>0?{...t.model.params,...d}:t.model.params;try{let v=new re(r),x=v.parseInitialFunction(t.initial)(g);t.model?.events&&(t.model.events=Pr(t.model.events));let b=v.simulateTrajectory({model:t.model,params:g,derivatives:t.model.derivatives||{},options:{timeRange:t.options.timeRange,timeStep:t.options.timeStep}},x,g);if(o)ro(m,i,b,g,typeof a=="string"?parseInt(a):a,typeof s=="string"?parseInt(s):s);else{let w=i[0];w&&w.viewDescriptor&&Array.isArray(w.viewDescriptor.layers)&&m[0].render({type:"view",timeline:b,layers:w.viewDescriptor.layers,width:typeof a=="string"?parseInt(a):a,height:typeof s=="string"?parseInt(s):s})}}catch(v){r("Error in simulation:",v.message)}};var n=h;let i=t.views||[],o=i.length>1,a=t.options?.width||"auto",s=t.options?.height||"480px",l=St(s),u=St(a);Qi(t,e,{log:r,onUpdate:h});let c=o?to(e,u,l,10):e,f=kt(u,800),p=kt(l,480),m=o?eo(i,c,u,l,r):[new I(c,f,p,r)];h()}catch(i){r("Error in explore initialization:",i.message)}}function io(t,e,r){try{let n=t.views||[];if(n.length>1){let o=t.layout||{columns:n.length,rows:1,gaps:10},a=t.width||"auto",s=t.height||"480px",l=St(a),u=St(s),c=document.createElement("div");c.style.cssText=`display: flex; flex-wrap: wrap; gap: ${o.gaps}px; min-height: ${u};`,e.appendChild(c),n.forEach(f=>{let p=document.createElement("div");p.style.cssText="flex: 1 1 calc(50% - 5px); min-width: 300px; height: 100%;",c.appendChild(p),new I(p,J(f.width,e,800,!0),J(f.height,e,480),r).render(f)})}else{let o=n[0];o&&new I(e,J(o.width,e,800,!0),J(o.height,e,480),r).render(o)}}catch(n){r("Error in show initialization:",n.message)}}function oo(t,e,r){try{e._calcplotRenderer&&e._calcplotRenderer.destroy();let n=new I(e,J(t.width,e,800,!0),J(t.height,e,480),r);e._calcplotRenderer=n,n.render(t)}catch(n){r("Error in compare initialization:",n.message)}}typeof globalThis<"u"&&(globalThis.CalcPlotComponents={createSlider:tt,createCheckbox:et,view:ee});function Ut(t,e,r){let n=r||function(...o){console.log("[calcplot]",...o)},i=e||window.calcPlotData;if(!i){n("No calcplot data found");return}if(!t){n("No container provided - visualization skipped");return}i.type==="explore"?no(i,t,n):i.type==="show"?io(i,t,n):i.type==="compare"?oo(i,t,n):n("Unknown data type:",i.type)}typeof globalThis<"u"&&(globalThis.CalcPlotComponents={initializeClient:Ut,createCheckbox:et,createSlider:tt});typeof globalThis<"u"&&(globalThis.CalcPlotClient={initializeClient:Ut,createCheckbox:et,createSlider:tt,view:ee});})();
|
package/dist/calcplot.js
CHANGED
|
@@ -1,33 +1,32 @@
|
|
|
1
|
-
"use strict";var CalcPlot=(()=>{var
|
|
2
|
-
<div id="${
|
|
1
|
+
"use strict";var CalcPlot=(()=>{var oe=Object.create;var F=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var ae=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty;var j=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var ue=(n,e)=>{for(var t in e)F(n,t,{get:e[t],enumerable:!0})},k=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of le(e))!ce.call(n,i)&&i!==t&&F(n,i,{get:()=>e[i],enumerable:!(r=se(e,i))||r.enumerable});return n};var A=(n,e,t)=>(t=n!=null?oe(ae(n)):{},k(e||!n||!n.__esModule?F(t,"default",{value:n,enumerable:!0}):t,n)),pe=n=>k(F({},"__esModule",{value:!0}),n);var xe={};ue(xe,{Timeline:()=>h,ViewBuilder:()=>y,axis:()=>te,canvas:()=>ne,checkbox:()=>ie,compare:()=>W,defineIVP:()=>I,detectEnvironment:()=>V,explore:()=>X,grid:()=>ee,isDenoJupyter:()=>E,parseAxisArgs:()=>O,parsePlotArgs:()=>v,plot:()=>Z,scene:()=>Y,show:()=>K,simulate:()=>H,slider:()=>re,supportsHTMLOutput:()=>J,view:()=>Q});function I(n){return n}function z(n,e,t,r){let{timeRange:i=[0,10],timeStep:o=.01}=r,a=[i[0]],l=Object.fromEntries(Object.keys(e).map(p=>[p,[e[p]]])),s={...e},u=i[0],c=new Set(Object.keys(n.events||{})),m=new Map;for(;u<i[1];){let p=Math.min(o,i[1]-u),d=me(n,s,t,p),P=de(n,s,d,t,u,p,c,m);if(P.triggered){let{name:T,alpha:B,eventState:C}=P,g=u+B*p;L(l,a,g,C);let R=n.events[T],M=R.then(C,t);(M===null||R.once)&&c.delete(T),s=M??C,u=g,m.set(T,g),M!==null&&L(l,a,g,s)}else u+=p,s=d,L(l,a,u,s)}return{times:a,states:l}}function de(n,e,t,r,i,o,a,l){let s=null;for(let u of a){let c=n.events[u],m=c.when(e),p=c.when(t);if(m*p<0){if(i-(l.get(u)??-1/0)<1e-9)continue;let d=fe(c,e,t);(!s||d<s.alpha)&&(s={name:u,alpha:d,eventState:$(e,t,d)})}}return s?{triggered:!0,...s}:{triggered:!1}}function me(n,e,t,r){let i=c=>Object.fromEntries(Object.entries(n.derivatives).map(([m,p])=>[m,p(c,t)])),o=(c,m,p)=>Object.fromEntries(Object.keys(c).map(d=>[d,c[d]+(m[d]||0)*p])),a=i(e),l=i(o(e,a,.5*r)),s=i(o(e,l,.5*r)),u=i(o(e,s,r));return Object.fromEntries(Object.keys(e).map(c=>[c,e[c]+r/6*((a[c]||0)+2*(l[c]||0)+2*(s[c]||0)+(u[c]||0))]))}function fe(n,e,t){let r=0,i=1;for(let o=0;o<40;o++){let a=(r+i)/2;n.when(e)*n.when($(e,t,a))<0?i=a:r=a}return i}var $=(n,e,t)=>Object.fromEntries(Object.keys(n).map(r=>[r,n[r]+t*(e[r]-n[r])]));function L(n,e,t,r){e.push(t);for(let i in r)n[i].push(r[i])}var h=class{constructor(e,t){this.times=e,this.states=t}at(e){if(this.times.length===0)throw new Error("Timeline is empty");if(e<=this.times[0]){let l={};for(let s in this.states)l[s]=this.states[s][0];return l}if(e>=this.times[this.times.length-1]){let l={};for(let s in this.states)l[s]=this.states[s][this.states[s].length-1];return l}let t=0;for(;t<this.times.length-1&&this.times[t+1]<e;)t++;let r=this.times[t],i=this.times[t+1],o=(e-r)/(i-r),a={};for(let l in this.states){let s=this.states[l][t],u=this.states[l][t+1];a[l]=s+o*(u-s)}return a}serialize(){return JSON.stringify({times:this.times,states:this.states})}get duration(){return this.times.length>0?this.times[this.times.length-1]:0}get steps(){return this.times.length}};var D=class{constructor(e){this.model=e}initial(e){return this.initialState=e,this}params(e){return this.modelParams=e,this}run(e={}){if(!this.initialState)throw new Error("Initial state must be set before running simulation");let t=e.params||this.modelParams||this.model.params||{},{timeRange:r=[0,10],timeStep:i=.01}=e,{times:o,states:a}=z(this.model,this.initialState,t,e);return new h(o,a)}};function H(n,e){if(e){let{times:t,states:r}=z(n,n.state,n.params,e);return new h(t,r)}else return new D(n)}function w(n,e){let t="calcplot-"+Date.now()+"-"+Math.random().toString(36).substr(2,9);return`
|
|
2
|
+
<div id="${t}" class="calcplot"></div>
|
|
3
3
|
<script>
|
|
4
4
|
${e||""}
|
|
5
5
|
|
|
6
6
|
(function() {
|
|
7
|
-
|
|
8
|
-
const
|
|
9
|
-
const container = document.getElementById('${r}');
|
|
7
|
+
const data = ${JSON.stringify(n,null,0)};
|
|
8
|
+
const container = document.getElementById('${t}');
|
|
10
9
|
|
|
11
10
|
if (window.CalcPlotComponents && container) {
|
|
12
11
|
try {
|
|
13
12
|
window.CalcPlotComponents.initializeClient(container, data);
|
|
14
13
|
} catch (error) {
|
|
15
|
-
console.error('
|
|
14
|
+
console.error('initializeClient failed:', error);
|
|
16
15
|
}
|
|
17
16
|
} else {
|
|
18
17
|
if (!window.CalcPlotComponents) {
|
|
19
|
-
console.warn('
|
|
18
|
+
console.warn('CalcPlot Client not available');
|
|
20
19
|
}
|
|
21
20
|
if (!container) {
|
|
22
|
-
console.error('
|
|
21
|
+
console.error('Container not found:', '${t}');
|
|
23
22
|
}
|
|
24
23
|
}
|
|
25
24
|
})();
|
|
26
|
-
<\/script>`}function
|
|
25
|
+
<\/script>`}function V(){return typeof window<"u"&&typeof document<"u"?"browser":typeof Deno<"u"?"deno":"node"}function N(){let n=typeof globalThis.Deno<"u",e=n&&typeof globalThis.Deno.jupyter<"u",t=typeof window<"u"&&typeof document<"u",r=typeof globalThis.process<"u"&&globalThis.process.versions?.node;return{isDeno:n,isJupyter:e,isBrowser:t,isNode:!!r}}function E(){let n=N();return n.isDeno&&n.isJupyter}function J(){let n=N();return n.isDeno&&n.isJupyter||n.isBrowser}async function S(n,e){let t=typeof window<"u"&&typeof document<"u",r=E();if(t){let i=null;if(e&&(typeof e=="string"?i=document.getElementById(e)||document.querySelector(e):i=e),i)i.innerHTML=n,_(i);else{let o=document.getElementById("calcplot-default")||document.querySelector(".calcplot-container")||he();o.innerHTML=n,_(o)}}else if(r)try{typeof globalThis<"u"&&globalThis.Deno?.jupyter&&await globalThis.Deno.jupyter.broadcast("display_data",{data:{"text/html":n},metadata:{}})}catch(i){console.error("Jupyter HTML display failed:",i)}}function he(){if(!(typeof window<"u"&&typeof document<"u"))throw new Error("Cannot create DOM elements in non-browser environment");let n=document.createElement("div");return n.id="calcplot-default",n.className="calcplot-container",n.style.cssText=`
|
|
27
26
|
margin: 20px;
|
|
28
27
|
padding: 16px;
|
|
29
28
|
background: white;
|
|
30
29
|
border-radius: 8px;
|
|
31
30
|
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
|
32
31
|
font-family: system-ui, -apple-system, sans-serif;
|
|
33
|
-
`,document.body.appendChild(
|
|
32
|
+
`,document.body.appendChild(n),n}function ye(n){if(!(typeof window<"u"&&typeof document<"u"))return null;let e="calcplot-script-"+Math.abs(n.split("").reduce((t,r)=>(t=(t<<5)-t+r.charCodeAt(0),t&t),0));if(document.getElementById(e))return null;try{let t=document.createElement("script");return t.id=e,t.textContent=n,document.head.appendChild(t),!0}catch(t){return console.error("Script execution failed:",t),null}}function _(n){n.querySelectorAll("script").forEach(t=>{let r=t.innerHTML;r.trim()&&ye(r)})}var f=null;async function x(){if(f)return f;let n=V();switch(n){case"browser":try{let e=await fetch("/dist/calcplot-client.js");if(!e.ok)throw new Error(`Failed to load client bundle: ${e.status}`);return f=await e.text(),f}catch(e){throw console.error("Failed to load client bundle:",e),e}case"node":try{let e=await import("fs"),r=(await import("path")).join(process.cwd(),"dist/calcplot-client.js");return f=e.readFileSync(r,"utf-8"),f}catch(e){throw console.error("Failed to read client bundle:",e),e}case"deno":try{let e=`${Deno.cwd()}/dist/calcplot-client.js`;if(f=await Deno.readTextFile(e),f)return f;throw new Error("Bundle content is null")}catch(e){throw console.error("Failed to read client bundle:",e),e}default:throw new Error(`Unsupported environment: ${n}`)}}async function W(n,e,t={}){let r=be(n),i=e.executeWithTimeline(r),a=ge(r,{toDescriptor:()=>i},t),l=await x(),s=w(a,l);await S(s,t.target)}function be(n){let e={times:[],states:{},labels:Object.keys(n)};for(let[t,r]of Object.entries(n)){e.times.length===0&&(e.times=r.times.map((i,o)=>o));for(let[i,o]of Object.entries(r.states))e.states[`${t}_${i}`]=o}return e}function ge(n,e,t){let r;return e.getLayers?r=e.getLayers():e.toDescriptor?r=e.toDescriptor().layers||[]:r=[],{type:"compare",timeline:n,viewDescriptor:{timeline:n,layers:r},layers:r,labels:n.labels||[],width:t.width,height:t.height}}var q=class{static parseFunction(e){let t=e.trim(),r=t.match(/^\(([^)]+)\)\s*=>\s*\{([\s\S]*)\}$/);if(r)return r[2].trim();let i=t.match(/^(\w+)\s*=>\s*\{([\s\S]*)\}$/);if(i)return i[2].trim();let o=t.match(/^\(([^)]+)\)\s*=>\s*(.+)$/s);if(o)return`return ${o[2].trim()}`;let a=t.match(/^(\w+)\s*=>\s*(.+)$/s);if(a)return`return ${a[2].trim()}`;let l=t.match(/^function\s*\([^)]*\)\s*\{([\s\S]*)\}$/);return l?l[1].trim():t}static createFunction(e,t){return new Function(...e,t)}static parseAndCreateFunction(e,t){let r=this.parseFunction(t);return this.createFunction(e,r)}};function we(n){let e={};for(let[t,r]of Object.entries(n))r&&typeof r.when=="function"&&typeof r.then=="function"?e[t]=JSON.stringify({when:r.when.toString(),then:r.then.toString(),once:r.once||!1}):console.warn(`Invalid event ${t}: when and then must be functions`);return e}function G(n){return{state:n.state,params:n.params,derivatives:Se(n.derivatives),events:n.events?we(n.events):void 0}}function U(n){let e={};if(!n)return e;for(let[t,r]of Object.entries(n))r.type==="slider"?e[t]={type:r.type,min:r.min,max:r.max,default:r.default,label:r.label||t,step:r.step||.01,scale:r.scale}:e[t]={type:r.type,default:r.default,label:r.label||t};return e}function Ie(n){return{times:n.times,states:n.states}}function $e(n){let e={};for(let[t,r]of Object.entries(n))r.type==="slider"?e[t]=r.default:r.type==="checkbox"&&(e[t]=r.default?1:0);return e}function He(serialized){let events={};for(let[key,eventStr]of Object.entries(serialized))try{let eventObj=JSON.parse(eventStr);eventObj.when&&eventObj.then&&(events[key]={when:eval(`(${eventObj.when})`),then:eval(`(${eventObj.then})`),once:eventObj.once||!1})}catch(n){console.error("Error deserializing event",key,n)}return events}function Ne(serialized){let functions={};for(let[key,fnStr]of Object.entries(serialized))try{fnStr.includes("=>")?functions[key]=eval(`(${fnStr})`):fnStr.startsWith("function")?functions[key]=eval(`(${fnStr})`):functions[key]=eval(`(state, params) => ${fnStr}`)}catch(n){console.error("Error deserializing function",key,n),functions[key]=()=>0}return functions}function Se(n){let e={};for(let[t,r]of Object.entries(n))typeof r=="function"?e[t]=r.toString():r!=null?e[t]=String(r):console.warn(`Skipping undefined/null value for key: ${t}`);return e}async function X(n,e,t={}){let{params:r={},initial:i,timeRange:o=[0,10],timeStep:a=.01,view:l}=e,{width:s="auto",height:u=480,target:c}=t,p=(Array.isArray(l)?l:[l]).map(B=>{let C=B.toDescriptor(),g=B.getLayers();return{view:B.toString(),viewDescriptor:C,layers:g}}),d={type:"explore",model:G(n),params:U(r),initial:i?.toString()||"",views:p,options:{timeRange:o,timeStep:a,width:s,height:u}},P=await x(),T=w(d,P);await S(T,c)}async function K(n,e,t={}){let r=Array.isArray(e)?e:[e],o={type:"show",views:r.map(s=>{let c=s.executeWithTimeline(n);return{type:"show",timeline:{times:n.times,states:n.states},layers:c.layers,controls:[]}}),layout:t.layout||{columns:r.length,rows:1,gaps:10},width:t.width,height:t.height},a=await x(),l=w(o,a);await S(l,t.target)}function v(n,e,t){let r={};return e===void 0?r={}:typeof e=="string"?t!==void 0?r={color:e,label:t}:e.startsWith("#")||/^#[0-9A-F]{6}$/i.test(e)?r={color:e}:r={label:e}:r=e,{selector:n,options:r}}function O(n,e,t){let r={};return n===void 0?r={}:typeof n=="number"?r={aspectRatio:n}:typeof n=="string"?typeof e=="string"&&typeof t=="number"?r={xLabel:n,yLabel:e,aspectRatio:t}:typeof e=="string"?r={xLabel:n,yLabel:e}:r={xLabel:n}:r=n,{options:r}}var y=class{constructor(e){this.layers=[];this.timeline=e}scene(e){return this.layers.push({type:"scene",draw:this.serializeFunction(e)}),this}vector(e,t,r={}){return this.layers.push({type:"vector",at:this.serializeFunction(e),dir:this.serializeFunction(t),options:{color:"#0ff",scale:1,width:2,...r}}),this}bounds(e){return this.layers.push({type:"bounds",bounds:e}),this}grid(e={}){return this.layers.push({type:"grid",options:e}),this}axis(e,t,r){let{options:i}=O(e,t,r);return this.layers.push({type:"axis",options:i}),this}plot(e,t,r){let{selector:i,options:o}=v(e,t,r),a=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],l=this.detectParametricSelector(i),s=this.layers.filter(u=>u.type==="plot").length;return this.layers.push({type:"plot",selector:this.serializeFunction(i),parametric:l,options:{color:o.color||a[s%a.length],lineWidth:1.5,opacity:1,dash:[],label:"",...o}}),this}phase(e,t={}){return this.plot(e,{color:"#d62728",lineWidth:2,...t})}fill(e,t={}){return this.layers.push({type:"fill",selector:this.serializeFunction(e),options:{color:t.color||"blue",alpha:t.alpha||.2}}),this}axhline(e,t={}){return this.layers.push({type:"refline",options:{orientation:"horizontal",value:e,color:t.color||"gray",linestyle:t.linestyle||"solid",linewidth:t.linewidth||1,label:t.label||"",labelPosition:t.labelPosition||"auto",labelOffset:t.labelOffset||8}}),this}axvline(e,t={}){return this.layers.push({type:"refline",options:{orientation:"vertical",value:e,color:t.color||"gray",linestyle:t.linestyle||"solid",linewidth:t.linewidth||1,label:t.label||"",labelPosition:t.labelPosition||"auto",labelOffset:t.labelOffset||8}}),this}title(e){return this.layers.push({type:"title",options:{text:e}}),this}legend(e={}){return this.layers.push({type:"legend",options:{loc:e.loc||"upper right",frame:e.frame!==!1,alpha:e.alpha||1}}),this}vectorField(e,t={}){return this.layers.push({type:"vectorField",selector:this.serializeFunction(e),options:{gridSize:t.gridSize||20,color:t.color||"gray",alpha:t.alpha||.6,normalize:t.normalize!==!1,scale:t.scale||1}}),this}nullcline(e,t={}){return this.layers.push({type:"nullcline",options:{variable:e,color:t.color||"blue",linestyle:t.linestyle||"dashed",linewidth:t.linewidth||1,label:t.label||""}}),this}poincare(e,t={section:()=>!1}){return this.layers.push({type:"poincare",selector:this.serializeFunction(e),options:{section:e,direction:t.direction||"positive",marker:t.marker||"circle",color:t.color||"red",size:t.size||4}}),this}defaults(){return this.grid().axis()}getLayers(){return[...this.layers]}getTimeline(){return this.timeline}setTimeline(e){this.timeline=e}serializeFunction(e){return e.toString()}detectParametricSelector(e){try{let r=e({x:1,y:2,z:3});return Array.isArray(r)&&r.length===2}catch{return!1}}toDescriptor(){return{timeline:{times:this.timeline?.times||[],states:this.timeline?.states||{}},layers:this.layers}}executeWithTimeline(e){let t=this.timeline;this.timeline=e;let r=this.toDescriptor();return this.timeline=t,r}};function Q(n){return new y(n)}var b=class{constructor(){this.layers=[]}scene(e){return this.layers.push({type:"scene",method:"scene",args:[e]}),this}plot(e,t,r){let{selector:i,options:o}=v(e,t,r);return this.layers.push({type:"plot",method:"plot",args:[i,o],options:o}),this}grid(e){return this.layers.push({type:"grid",method:"grid",args:[e],options:{showGrid:!0,gridColor:"#e0e0e0",gridOpacity:.3,gridWidth:.5,...e}}),this}axis(e,t,r){let{options:i}=O(e,t,r);return this.layers.push({type:"axis",method:"axis",args:[i],options:i}),this}execute(e){let t=new y(e);for(let r of this.layers)switch(r.method){case"scene":t.scene(r.args[0]);break;case"plot":t.plot(r.args[0],r.args[1]);break;case"grid":t.grid(r.args[0]);break;case"axis":t.axis(r.args[0]);break}return t}};function Y(n){return new b().scene(n)}function Z(n,e,t){return new b().plot(n,e,t)}function ee(n){return new b().grid(n)}function te(n,e,t){return new b().axis(n,e,t)}function ne(n){return new b}function re(n,e,t,r,i=.01){return{type:"slider",label:r,default:t,min:n,max:e,step:i}}function ie(n,e=!1){return{type:"checkbox",label:n,default:e}}return pe(xe);})();
|