@stacksjs/charts 0.75.719 → 0.75.723

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chart.d.ts CHANGED
@@ -17,9 +17,12 @@ export declare class Chart {
17
17
  ctx: CanvasRenderingContext2D;
18
18
  private resizeObserver;
19
19
  private hitItems;
20
+ private plot;
21
+ private activeIndex;
20
22
  private tooltipEl;
21
23
  private boundMove;
22
24
  private boundLeave;
25
+ private boundKey;
23
26
  constructor(target: HTMLCanvasElement | CanvasRenderingContext2D, config: ChartConfig);
24
27
  update(): void;
25
28
  resize(): void;
@@ -31,7 +34,6 @@ export declare class Chart {
31
34
  private renderCartesian;
32
35
  private hasRightAxis;
33
36
  private computeAxis;
34
- private drawGridAndYAxis;
35
37
  private drawYAxis;
36
38
  private drawXAxis;
37
39
  private scaleX;
@@ -42,7 +44,11 @@ export declare class Chart {
42
44
  private renderRadial;
43
45
  private layoutLegend;
44
46
  private drawLegend;
47
+ private drawCrosshair;
48
+ private setActiveIndex;
49
+ private clearHover;
45
50
  private handleMouseMove;
51
+ private handleKeyDown;
46
52
  private findClosestByIndex;
47
53
  private showTooltip;
48
54
  private hideTooltip;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{scaleBand as H,scaleLinear as _}from"@ts-charts/scale";import{arc as X,area as G,curveLinear as V,curveMonotoneX as U,line as j,pie as J}from"@ts-charts/shape";var M=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316","#6366f1","#84cc16"];function y(t){return M[t%M.length]??M[0]}function R(t,e){if(t.startsWith("#")){let n=t.slice(1),i=Number.parseInt(n.slice(0,2),16),o=Number.parseInt(n.slice(2,4),16),s=Number.parseInt(n.slice(4,6),16);return`rgba(${i}, ${o}, ${s}, ${e})`}if(t.startsWith("rgb("))return t.replace("rgb(","rgba(").replace(")",`, ${e})`);return t}import{format as P}from"@ts-charts/format";import{scaleLinear as W}from"@ts-charts/scale";var Y=W;function B(t,e,n=8){if(!Number.isFinite(t)||!Number.isFinite(e)||e<=t)return[Number.isFinite(t)?t:0];let o=Y().domain([t,e]).nice(n).ticks(n);if(o.length===0)return[t,e];return o}var F=P("~s");function v(t){if(!Number.isFinite(t))return"";if(Math.abs(t)>=1000)return F(t).replace("G","B").toUpperCase();if(Number.isInteger(t))return t.toString();return t.toFixed(2)}function z(t,e,n){if(n.responsive===!1||!e||e.width<=0)return t;let i=e.width;if(n.maintainAspectRatio===!1&&e.height>0)return{width:i,height:e.height};let o=t.width>0&&t.height>0?t.width/t.height:2;return{width:i,height:i/o}}var N=_,Z=H,q="rgba(148, 163, 184, 0.18)",C="#64748b",K="rgba(15, 23, 42, 0.92)";class E{static instances=new WeakMap;static register(...t){}type;data;options;canvas;ctx;resizeObserver=null;hitItems=[];tooltipEl=null;boundMove=(t)=>this.handleMouseMove(t);boundLeave=()=>this.hideTooltip();constructor(t,e){this.canvas=t instanceof HTMLCanvasElement?t:t.canvas;let n=this.canvas.getContext("2d");if(!n)throw Error("Chart: 2D canvas context unavailable");this.ctx=n,this.type=e.type,this.data=e.data,this.options=e.options??{},E.instances.set(this.canvas,this),this.attachInteractions(),this.observeResize(),this.render()}update(){this.render()}resize(){this.render()}destroy(){if(this.resizeObserver)this.resizeObserver.disconnect(),this.resizeObserver=null;if(this.canvas.removeEventListener("mousemove",this.boundMove),this.canvas.removeEventListener("mouseleave",this.boundLeave),this.tooltipEl?.parentNode)this.tooltipEl.parentNode.removeChild(this.tooltipEl);this.tooltipEl=null,this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),E.instances.delete(this.canvas)}observeResize(){if(this.options.responsive===!1||typeof ResizeObserver>"u")return;this.resizeObserver=new ResizeObserver(()=>this.render()),this.resizeObserver.observe(this.canvas.parentElement??this.canvas)}attachInteractions(){if(this.options.plugins?.tooltip?.enabled===!1)return;this.canvas.addEventListener("mousemove",this.boundMove),this.canvas.addEventListener("mouseleave",this.boundLeave)}syncCanvasSize(){let t=typeof window<"u"?window.devicePixelRatio||1:1,e=this.canvas.getBoundingClientRect(),n=this.canvas.parentElement?.getBoundingClientRect(),i=z({width:e.width||this.canvas.clientWidth||this.canvas.width,height:e.height||this.canvas.clientHeight||this.canvas.height},n?{width:n.width,height:n.height}:void 0,this.options),{width:o,height:s}=i;if(this.options.responsive!==!1)this.canvas.style.display="block",this.canvas.style.width=`${o}px`,this.canvas.style.height=`${s}px`;let c=Math.max(1,Math.floor(o*t)),a=Math.max(1,Math.floor(s*t));if(this.canvas.width!==c)this.canvas.width=c;if(this.canvas.height!==a)this.canvas.height=a;return this.ctx.setTransform(t,0,0,t,0,0),{width:o,height:s}}render(){let{width:t,height:e}=this.syncCanvasSize();if(this.ctx.clearRect(0,0,t,e),this.hitItems=[],this.type==="doughnut"||this.type==="pie"){this.renderRadial(t,e);return}if(this.type==="radar"){this.renderCartesian(t,e,"line");return}this.renderCartesian(t,e,this.type)}renderCartesian(t,e,n){let i=this.data.labels??[],o=this.data.datasets,s=this.layoutLegend(t,e),a=8+(this.options.plugins?.title?.display?24:0)+(s.position==="top"?s.h:0),r=28+(s.position==="bottom"?s.h:0),l=48+(s.position==="left"?s.w:0),d=16+(s.position==="right"?s.w:0)+(this.hasRightAxis()?40:0),u={x:l,y:a,w:Math.max(1,t-l-d),h:Math.max(1,e-a-r)};if(this.options.plugins?.title?.display&&this.options.plugins.title.text){let h=this.options.plugins.title;this.ctx.fillStyle=h.color??C,this.ctx.font=`${h.font?.size??14}px system-ui, sans-serif`,this.ctx.textAlign="center",this.ctx.textBaseline="top",this.ctx.fillText(h.text??"",t/2,8)}this.drawLegend(s,o);let x=this.computeAxis(o.filter((h)=>(h.yAxisID??"y")==="y"),"y"),p=this.hasRightAxis()?this.computeAxis(o.filter((h)=>h.yAxisID==="y1"),"y1"):null;if(this.drawGridAndYAxis(u,x,"left"),p)this.drawYAxis(u,p,"right");if(this.drawXAxis(u,i),n==="bar")this.drawBars(u,i,o,x,p);else this.drawLines(u,i,o,x,p)}hasRightAxis(){return this.data.datasets.some((t)=>t.yAxisID==="y1")}computeAxis(t,e){let n=this.options.scales?.[e]??{},{POSITIVE_INFINITY:i,NEGATIVE_INFINITY:o}=Number;if(n.stacked){let c=this.data.labels??[];for(let a=0;a<c.length;a++){let r=0,l=0;for(let d of t){let u=d.data[a]??0;if(u>=0)r+=u;else l+=u}if(r>o)o=r;if(l<i)i=l}}else for(let c of t)for(let a of c.data){if(a<i)i=a;if(a>o)o=a}if(!Number.isFinite(i))i=0;if(!Number.isFinite(o))o=1;if(n.beginAtZero!==!1&&i>0)i=0;if(n.min!==void 0)i=n.min;if(n.max!==void 0)o=n.max;if(i===o)o=i+1;let s=B(i,o,n.ticks?.maxTicksLimit??6);return{ticks:s,min:s[0]??i,max:s[s.length-1]??o}}drawGridAndYAxis(t,e,n){let i=this.options.scales?.y??{},o=i.grid?.display!==!1,s=i.ticks?.color??C,c=i.grid?.color??q;this.ctx.save(),this.ctx.font=`${i.ticks?.font?.size??11}px system-ui, sans-serif`,this.ctx.textBaseline="middle";for(let a of e.ticks){let r=this.scaleY(t,e,a);if(o)this.ctx.strokeStyle=c,this.ctx.lineWidth=1,this.ctx.beginPath(),this.ctx.moveTo(t.x,r),this.ctx.lineTo(t.x+t.w,r),this.ctx.stroke();let l=i.ticks?.callback?i.ticks.callback(a,e.ticks.indexOf(a),e.ticks):v(a);this.ctx.fillStyle=s,this.ctx.textAlign=n==="left"?"right":"left";let d=n==="left"?t.x-8:t.x+t.w+8;this.ctx.fillText(String(l),d,r)}this.ctx.restore()}drawYAxis(t,e,n){let i=this.options.scales?.y1??{},o=i.ticks?.color??C;this.ctx.save(),this.ctx.font=`${i.ticks?.font?.size??11}px system-ui, sans-serif`,this.ctx.textBaseline="middle";for(let s of e.ticks){let c=this.scaleY(t,e,s),a=i.ticks?.callback?i.ticks.callback(s,e.ticks.indexOf(s),e.ticks):v(s);this.ctx.fillStyle=o,this.ctx.textAlign=n==="left"?"right":"left";let r=n==="left"?t.x-8:t.x+t.w+8;this.ctx.fillText(String(a),r,c)}this.ctx.restore()}drawXAxis(t,e){let n=this.options.scales?.x??{},i=n.ticks?.color??C;if(n.display===!1||e.length===0)return;this.ctx.save(),this.ctx.font=`${n.ticks?.font?.size??11}px system-ui, sans-serif`,this.ctx.textBaseline="top",this.ctx.textAlign="center",this.ctx.fillStyle=i;let o=Math.min(e.length,Math.max(2,Math.floor(t.w/60))),s=Math.max(1,Math.floor(e.length/o));for(let c=0;c<e.length;c+=s){let a=this.scaleX(t,e.length,c);this.ctx.fillText(e[c]??"",a,t.y+t.h+8)}this.ctx.restore()}scaleX(t,e,n){if(e<=1)return t.x+t.w/2;return N().domain([0,e-1]).range([t.x,t.x+t.w])(n)}scaleY(t,e,n){if(e.max===e.min)return t.y+t.h/2;return N().domain([e.min,e.max]).range([t.y+t.h,t.y])(n)}drawLines(t,e,n,i,o){n.forEach((s,c)=>{let a=s.yAxisID==="y1"&&o?o:i;if(s.type==="bar"){this.drawBarSeries(t,e,[s],i,o);return}let r=(typeof s.borderColor==="string"?s.borderColor:null)??y(c),l=s.backgroundColor&&typeof s.backgroundColor==="string"?s.backgroundColor:s.fill?R(r,0.15):null,d=s.data.map((h,b)=>({x:this.scaleX(t,e.length||s.data.length,b),y:this.scaleY(t,a,h),value:h}));if(d.length===0)return;let u=(s.tension??0)>0?U:V;if(l){let h=t.y+t.h,b=G().x((f)=>f.x).y0(()=>h).y1((f)=>f.y).curve(u).context(this.ctx);this.ctx.beginPath(),b(d),this.ctx.fillStyle=l,this.ctx.fill(),b.context(null)}let x=j().x((h)=>h.x).y((h)=>h.y).curve(u).context(this.ctx);this.ctx.beginPath(),x(d),this.ctx.lineWidth=s.borderWidth??2,this.ctx.strokeStyle=r,this.ctx.lineJoin="round",this.ctx.lineCap="round",this.ctx.stroke(),x.context(null);let p=s.pointRadius??0;if(p>0){this.ctx.fillStyle=s.pointBackgroundColor??r;for(let h of d)this.ctx.beginPath(),this.ctx.arc(h.x,h.y,p,0,Math.PI*2),this.ctx.fill()}d.forEach((h,b)=>{this.hitItems.push({datasetIndex:c,dataIndex:b,x:h.x,y:h.y,label:e[b]??String(b),value:h.value})})})}drawBars(t,e,n,i,o){this.drawBarSeries(t,e,n,i,o)}drawBarSeries(t,e,n,i,o){let s=e.length||(n[0]?.data.length??0);if(s===0)return;let a=!!this.options.scales?.y?.stacked,r=Array.from({length:s},(x,p)=>p),l=Z().domain(r).range([t.x,t.x+t.w]).paddingInner(0.3),d=l.bandwidth(),u=a?d:d/Math.max(1,n.length);for(let x=0;x<s;x++){let p=l(x),h=0,b=0;n.forEach((f,k)=>{let I=f.yAxisID==="y1"&&o?o:i,m=f.data[x]??0,g=a?m>=0?h:b:0,A=g+m,L=this.scaleY(t,I,g),T=this.scaleY(t,I,A),w=a?p:p+k*u,S=Math.min(L,T),D=Math.abs(T-L),O=Array.isArray(f.backgroundColor)?f.backgroundColor[x]??y(k):typeof f.backgroundColor==="string"?f.backgroundColor:y(k);if(this.ctx.fillStyle=O,this.ctx.fillRect(w,S,Math.max(1,u-2),D),f.borderWidth&&f.borderColor&&typeof f.borderColor==="string")this.ctx.lineWidth=f.borderWidth,this.ctx.strokeStyle=f.borderColor,this.ctx.strokeRect(w,S,Math.max(1,u-2),D);if(a)if(m>=0)h=A;else b=A;this.hitItems.push({datasetIndex:k,dataIndex:x,x:w+u/2,y:S,label:e[x]??String(x),value:m})})}}renderRadial(t,e){let n=this.data.datasets;if(n.length===0)return;let i=n[0];if(!i)return;let o=this.data.labels??[],s=this.layoutLegend(t,e),c=t,a=e,r=0,l=0;if(s.position==="right")c=t-s.w;else if(s.position==="left")c=t-s.w,r=s.w;else if(s.position==="top")a=e-s.h,l=s.h;else if(s.position==="bottom")a=e-s.h;this.drawLegend(s,n.map((m,g)=>({...m,label:o[g]??m.label})),o);let d=r+c/2,u=l+a/2,x=Math.min(c,a)/2-8,p=this.options.cutout,h=typeof p==="string"&&p.endsWith("%")?Number.parseFloat(p)/100:this.type==="doughnut"?0.6:0,b=x*h,k=J().value((m)=>Math.max(0,m||0)).startAngle(-Math.PI/2).endAngle(-Math.PI/2+Math.PI*2).sort(null)(i.data),I=X().innerRadius(b).outerRadius(x);this.ctx.save(),this.ctx.translate(d,u);for(let m of k){let g=m.index,A=i.data[g]??0,L=Array.isArray(i.backgroundColor)?i.backgroundColor[g]??y(g):typeof i.backgroundColor==="string"?i.backgroundColor:y(g);this.ctx.beginPath(),I.context(this.ctx)(m),this.ctx.fillStyle=L,this.ctx.fill();let T=(m.startAngle+m.endAngle)/2-Math.PI/2,w=(x+b)/2;this.hitItems.push({datasetIndex:0,dataIndex:g,x:d+Math.cos(T)*w,y:u+Math.sin(T)*w,label:o[g]??String(g),value:A})}this.ctx.restore(),I.context(null)}layoutLegend(t,e){let n=this.options.plugins?.legend;if(n?.display===!1||!this.data.datasets.some((o)=>o.label))return{w:0,h:0,position:"none"};let i=n?.position??"top";if(i==="left"||i==="right")return{w:100,h:0,position:i};return{w:0,h:Math.max(24,Math.ceil(this.data.datasets.length/4)*18+8),position:i}}drawLegend(t,e,n){if(t.position==="none")return;let i=this.options.plugins?.legend,o=n&&(this.type==="pie"||this.type==="doughnut")?n.map((a,r)=>{let l=e[0],d=Array.isArray(l?.backgroundColor)?l.backgroundColor[r]??y(r):typeof l?.backgroundColor==="string"?l.backgroundColor:y(r);return{label:a,color:d}}):e.map((a,r)=>({label:a.label??`Dataset ${r+1}`,color:typeof a.borderColor==="string"?a.borderColor:Array.isArray(a.backgroundColor)?a.backgroundColor[0]??y(r):typeof a.backgroundColor==="string"?a.backgroundColor:y(r)}));if(o.length===0)return;this.ctx.save(),this.ctx.font=`${i?.labels?.font?.size??12}px system-ui, sans-serif`,this.ctx.fillStyle=i?.labels?.color??C,this.ctx.textBaseline="middle";let s=i?.labels?.boxWidth??12,c=i?.labels?.padding??8;if(t.position==="top"||t.position==="bottom"){let a=t.position==="top"?12:(this.canvas.clientHeight||0)-12,r=c;this.ctx.textAlign="left";for(let l of o)this.ctx.fillStyle=l.color,this.ctx.fillRect(r,a-s/2,s,s),r+=s+4,this.ctx.fillStyle=i?.labels?.color??C,this.ctx.fillText(l.label,r,a),r+=this.ctx.measureText(l.label).width+c*2}else{let a=t.position==="right"?(this.canvas.clientWidth||0)-110:8,r=c+6;for(let l of o)this.ctx.fillStyle=l.color,this.ctx.fillRect(a,r-s/2,s,s),this.ctx.fillStyle=i?.labels?.color??C,this.ctx.textAlign="left",this.ctx.fillText(l.label,a+s+4,r),r+=18}this.ctx.restore()}handleMouseMove(t){if(this.hitItems.length===0)return;let e=this.canvas.getBoundingClientRect(),n=t.clientX-e.left,i=t.clientY-e.top;if((this.options.interaction?.mode??this.options.plugins?.tooltip?.mode??"nearest")==="index"){let a=this.findClosestByIndex(n);if(a)this.showTooltip(t.clientX,t.clientY,a);else this.hideTooltip();return}let s=null,c=Number.POSITIVE_INFINITY;for(let a of this.hitItems){let r=a.x-n,l=a.y-i,d=r*r+l*l;if(d<c)c=d,s=a}if(s&&c<3600)this.showTooltip(t.clientX,t.clientY,[s]);else this.hideTooltip()}findClosestByIndex(t){let e=-1,n=Number.POSITIVE_INFINITY;for(let i of this.hitItems){let o=Math.abs(i.x-t);if(o<n)n=o,e=i.dataIndex}if(e<0)return null;return this.hitItems.filter((i)=>i.dataIndex===e)}showTooltip(t,e,n){if(!this.tooltipEl)this.tooltipEl=document.createElement("div"),Object.assign(this.tooltipEl.style,{position:"fixed",pointerEvents:"none",background:this.options.plugins?.tooltip?.backgroundColor??K,color:this.options.plugins?.tooltip?.bodyColor??"#fff",padding:"6px 10px",borderRadius:"6px",font:"12px system-ui, sans-serif",zIndex:"9999",whiteSpace:"pre-line",transform:"translate(8px, 8px)"}),document.body.appendChild(this.tooltipEl);let i=this.options.plugins?.tooltip?.callbacks,o=[];n.forEach((r)=>{let l=this.data.datasets[r.datasetIndex];if(!l)return;let d={dataset:l,datasetIndex:r.datasetIndex,dataIndex:r.dataIndex,parsed:{y:r.value},raw:r.value,label:r.label,formattedValue:v(r.value)},u=i?.label?i.label(d):`${l.label??""}: ${v(r.value)}`,x=Array.isArray(u)?u.join(`
3
- `):u;o.push(x)});let s=i?.title?i.title(n.flatMap((r)=>{let l=this.data.datasets[r.datasetIndex];if(!l)return[];return[{dataset:l,datasetIndex:r.datasetIndex,dataIndex:r.dataIndex,parsed:{y:r.value},raw:r.value,label:r.label,formattedValue:v(r.value)}]})):n[0]?.label,c=Array.isArray(s)?s.join(`
4
- `):s;if(this.tooltipEl.textContent="",c){let r=document.createElement("strong");r.textContent=c,this.tooltipEl.appendChild(r),this.tooltipEl.appendChild(document.createElement("br"))}let a=document.createTextNode(o.join(`
5
- `));this.tooltipEl.appendChild(a),this.tooltipEl.style.left=`${t}px`,this.tooltipEl.style.top=`${e}px`,this.tooltipEl.style.display="block"}hideTooltip(){if(this.tooltipEl)this.tooltipEl.style.display="none"}}var xt=E,dt=[];export{E as Chart,M as DEFAULT_PALETTE,xt as default,v as formatTick,B as niceTicks,y as paletteColor,dt as registerables,R as withAlpha};
2
+ import{scaleBand as Y,scaleLinear as _}from"@ts-charts/scale";import{arc as X,area as V,curveLinear as G,curveMonotoneX as K,line as j,pie as U}from"@ts-charts/shape";var M=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316","#6366f1","#84cc16"];function C(t){return M[t%M.length]??M[0]}function R(t,e){if(t.startsWith("#")){let n=t.slice(1),o=Number.parseInt(n.slice(0,2),16),i=Number.parseInt(n.slice(2,4),16),s=Number.parseInt(n.slice(4,6),16);return`rgba(${o}, ${i}, ${s}, ${e})`}if(t.startsWith("rgb("))return t.replace("rgb(","rgba(").replace(")",`, ${e})`);return t}import{format as W}from"@ts-charts/format";import{scaleLinear as H}from"@ts-charts/scale";var P=H;function D(t,e,n=8){if(!Number.isFinite(t)||!Number.isFinite(e)||e<=t)return[Number.isFinite(t)?t:0];let i=P().domain([t,e]).nice(n).ticks(n);if(i.length===0)return[t,e];return i}var F=W("~s");function E(t){if(!Number.isFinite(t))return"";if(Math.abs(t)>=1000)return F(t).replace("G","B").toUpperCase();if(Number.isInteger(t))return t.toString();return t.toFixed(2)}function N(t,e,n){if(n.responsive===!1||!e||e.width<=0)return t;let o=e.width;if(n.maintainAspectRatio===!1&&e.height>0)return{width:o,height:e.height};let i=t.width>0&&t.height>0?t.width/t.height:2;return{width:o,height:o/i}}var O=_,J=Y,Z="rgba(148, 163, 184, 0.18)",T="#64748b",q="rgba(15, 23, 42, 0.92)";class L{static instances=new WeakMap;static register(...t){}type;data;options;canvas;ctx;resizeObserver=null;hitItems=[];plot=null;activeIndex=null;tooltipEl=null;boundMove=(t)=>this.handleMouseMove(t);boundLeave=()=>this.clearHover();boundKey=(t)=>this.handleKeyDown(t);constructor(t,e){this.canvas=t instanceof HTMLCanvasElement?t:t.canvas;let n=this.canvas.getContext("2d");if(!n)throw Error("Chart: 2D canvas context unavailable");this.ctx=n,this.type=e.type,this.data=e.data,this.options=e.options??{},L.instances.set(this.canvas,this),this.attachInteractions(),this.observeResize(),this.render()}update(){this.activeIndex=null,this.hideTooltip(),this.render()}resize(){this.render()}destroy(){if(this.resizeObserver)this.resizeObserver.disconnect(),this.resizeObserver=null;if(this.canvas.removeEventListener("mousemove",this.boundMove),this.canvas.removeEventListener("mouseleave",this.boundLeave),this.canvas.removeEventListener("keydown",this.boundKey),this.canvas.removeEventListener("blur",this.boundLeave),this.tooltipEl?.parentNode)this.tooltipEl.parentNode.removeChild(this.tooltipEl);this.tooltipEl=null,this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),L.instances.delete(this.canvas)}observeResize(){if(this.options.responsive===!1||typeof ResizeObserver>"u")return;this.resizeObserver=new ResizeObserver(()=>this.render()),this.resizeObserver.observe(this.canvas.parentElement??this.canvas)}attachInteractions(){if(this.options.plugins?.tooltip?.enabled===!1)return;if(this.canvas.addEventListener("mousemove",this.boundMove),this.canvas.addEventListener("mouseleave",this.boundLeave),this.options.plugins?.tooltip?.crosshair)this.canvas.addEventListener("keydown",this.boundKey),this.canvas.addEventListener("blur",this.boundLeave)}syncCanvasSize(){let t=typeof window<"u"?window.devicePixelRatio||1:1,e=this.canvas.getBoundingClientRect(),n=this.canvas.parentElement?.getBoundingClientRect(),o=N({width:e.width||this.canvas.clientWidth||this.canvas.width,height:e.height||this.canvas.clientHeight||this.canvas.height},n?{width:n.width,height:n.height}:void 0,this.options),{width:i,height:s}=o;if(this.options.responsive!==!1)this.canvas.style.display="block",this.canvas.style.width=`${i}px`,this.canvas.style.height=`${s}px`;let d=Math.max(1,Math.floor(i*t)),r=Math.max(1,Math.floor(s*t));if(this.canvas.width!==d)this.canvas.width=d;if(this.canvas.height!==r)this.canvas.height=r;return this.ctx.setTransform(t,0,0,t,0,0),{width:i,height:s}}render(){let{width:t,height:e}=this.syncCanvasSize();if(this.ctx.clearRect(0,0,t,e),this.hitItems=[],this.plot=null,this.type==="doughnut"||this.type==="pie"){this.renderRadial(t,e);return}if(this.type==="radar"){this.renderCartesian(t,e,"line");return}this.renderCartesian(t,e,this.type)}renderCartesian(t,e,n){let o=this.data.labels??[],i=this.data.datasets,s=this.layoutLegend(t,e),d=this.options.plugins?.title?.display?24:0,{x:r,y:a,y1:c}=this.options.scales??{},u=a?.position==="right"?"right":"left",p=c?.position==="left"?"left":"right",x=u==="left"&&a?.display!==!1||p==="left"&&c?.display!==!1&&this.hasRightAxis(),h=u==="right"&&a?.display!==!1||p==="right"&&c?.display!==!1&&this.hasRightAxis(),l=this.options.layout?.padding,f=typeof l==="number"?{top:l,bottom:l,left:l,right:l}:l,b=(f?.top??8)+d+(s.position==="top"?s.h:0),y=(f?.bottom??(r?.display===!1?8:28))+(s.position==="bottom"?s.h:0),w=(f?.left??(x?48:8))+(s.position==="left"?s.w:0),m=(f?.right??(h?56:16))+(s.position==="right"?s.w:0),g={x:w,y:b,w:Math.max(1,t-w-m),h:Math.max(1,e-b-y)};if(this.plot=g,this.options.plugins?.title?.display&&this.options.plugins.title.text){let v=this.options.plugins.title;this.ctx.fillStyle=v.color??T,this.ctx.font=`${v.font?.size??14}px system-ui, sans-serif`,this.ctx.textAlign="center",this.ctx.textBaseline="top",this.ctx.fillText(v.text??"",t/2,8)}this.drawLegend(s,i);let I=this.computeAxis(i.filter((v)=>(v.yAxisID??"y")==="y"),"y"),k=this.hasRightAxis()?this.computeAxis(i.filter((v)=>v.yAxisID==="y1"),"y1"):null;if(this.drawYAxis(g,I,"y",u),k)this.drawYAxis(g,k,"y1",p);if(this.drawXAxis(g,o),n==="bar")this.drawBars(g,o,i,I,k);else this.drawLines(g,o,i,I,k);if(this.activeIndex!==null)this.drawCrosshair(g)}hasRightAxis(){return this.data.datasets.some((t)=>t.yAxisID==="y1")}computeAxis(t,e){let n=this.options.scales?.[e]??{},{POSITIVE_INFINITY:o,NEGATIVE_INFINITY:i}=Number;if(n.stacked){let d=this.data.labels??[];for(let r=0;r<d.length;r++){let a=0,c=0;for(let u of t){let p=u.data[r]??0,x=Number.isFinite(p)?p:0;if(x>=0)a+=x;else c+=x}if(a>i)i=a;if(c<o)o=c}}else for(let d of t)for(let r of d.data){if(!Number.isFinite(r))continue;if(r<o)o=r;if(r>i)i=r}if(!Number.isFinite(o))o=0;if(!Number.isFinite(i))i=1;if(n.beginAtZero!==!1&&o>0)o=0;if(n.min!==void 0)o=n.min;if(n.max!==void 0)i=n.max;if(o===i)i=o+1;let s=D(o,i,n.ticks?.maxTicksLimit??6);return{ticks:s,min:s[0]??o,max:s[s.length-1]??i}}drawYAxis(t,e,n,o){let i=this.options.scales?.[n]??{};if(i.display===!1)return;let s=i.grid?.display??n==="y",d=i.ticks?.color==="currentColor"?getComputedStyle(this.canvas).color:i.ticks?.color??T,r=i.grid?.color??Z;if(this.ctx.save(),this.ctx.font=`${i.ticks?.font?.size??11}px system-ui, sans-serif`,this.ctx.textBaseline="middle",s)this.ctx.strokeStyle=r,this.ctx.lineWidth=1,this.ctx.setLineDash(i.grid?.borderDash??[]);for(let a of e.ticks){let c=this.scaleY(t,e,a);if(s)this.ctx.beginPath(),this.ctx.moveTo(t.x,c),this.ctx.lineTo(t.x+t.w,c),this.ctx.stroke();let u=i.ticks?.callback?i.ticks.callback(a,e.ticks.indexOf(a),e.ticks):E(a);this.ctx.fillStyle=d,this.ctx.textAlign=o==="left"?"right":"left";let p=i.ticks?.padding??8,x=o==="left"?t.x-p:t.x+t.w+p;this.ctx.fillText(String(u),x,c)}this.ctx.restore()}drawXAxis(t,e){let n=this.options.scales?.x??{},o=n.ticks?.color??T;if(n.display===!1||e.length===0)return;this.ctx.save(),this.ctx.font=`${n.ticks?.font?.size??11}px system-ui, sans-serif`,this.ctx.textBaseline="top",this.ctx.textAlign="center",this.ctx.fillStyle=o;let i=Math.min(e.length,Math.max(2,Math.floor(t.w/60))),s=Math.max(1,Math.floor(e.length/i));for(let d=0;d<e.length;d+=s){let r=this.scaleX(t,e.length,d);this.ctx.fillText(e[d]??"",r,t.y+t.h+8)}this.ctx.restore()}scaleX(t,e,n){if(e<=1)return t.x+t.w/2;return O().domain([0,e-1]).range([t.x,t.x+t.w])(n)}scaleY(t,e,n){if(e.max===e.min)return t.y+t.h/2;return O().domain([e.min,e.max]).range([t.y+t.h,t.y])(n)}drawLines(t,e,n,o,i){n.forEach((s,d)=>{let r=s.yAxisID==="y1"&&i?i:o;if(s.type==="bar"){this.drawBarSeries(t,e,[s],o,i);return}let a=(typeof s.borderColor==="string"?s.borderColor:null)??C(d),c=s.backgroundColor&&typeof s.backgroundColor==="string"?s.backgroundColor:s.fill?R(a,0.15):null,u=s.data.map((l,f)=>({x:this.scaleX(t,e.length||s.data.length,f),y:this.scaleY(t,r,l),value:l}));if(u.length===0)return;let p=(l)=>Number.isFinite(l.value),x=(s.tension??0)>0?K:G;if(c){let l=t.y+t.h,f=V().defined(p).x((b)=>b.x).y0(()=>l).y1((b)=>b.y).curve(x).context(this.ctx);this.ctx.beginPath(),f(u),this.ctx.fillStyle=c,this.ctx.fill(),f.context(null)}let h=j().defined(p).x((l)=>l.x).y((l)=>l.y).curve(x).context(this.ctx);this.ctx.beginPath(),h(u),this.ctx.lineWidth=s.borderWidth??2,this.ctx.strokeStyle=a,this.ctx.lineJoin="round",this.ctx.lineCap="round",this.ctx.stroke(),h.context(null),u.forEach((l,f)=>{if(!p(l))return;let b=u[f-1],y=u[f+1],w=(!b||!p(b))&&(!y||!p(y)),m=s.pointRadius??(w?2:0);if(m>0)this.ctx.fillStyle=s.pointBackgroundColor??a,this.ctx.beginPath(),this.ctx.arc(l.x,l.y,m,0,Math.PI*2),this.ctx.fill();this.hitItems.push({datasetIndex:d,dataIndex:f,x:l.x,y:l.y,label:e[f]??String(f),value:l.value})})})}drawBars(t,e,n,o,i){this.drawBarSeries(t,e,n,o,i)}drawBarSeries(t,e,n,o,i){let s=e.length||(n[0]?.data.length??0);if(s===0)return;let r=!!this.options.scales?.y?.stacked,a=Array.from({length:s},(x,h)=>h),c=J().domain(a).range([t.x,t.x+t.w]).paddingInner(0.3),u=c.bandwidth(),p=r?u:u/Math.max(1,n.length);for(let x=0;x<s;x++){let h=c(x),l=0,f=0;n.forEach((b,y)=>{let w=b.yAxisID==="y1"&&i?i:o,m=b.data[x]??0,g=r?m>=0?l:f:0,I=g+m,k=this.scaleY(t,w,g),v=this.scaleY(t,w,I),A=r?h:h+y*p,S=Math.min(k,v),B=Math.abs(v-k),z=Array.isArray(b.backgroundColor)?b.backgroundColor[x]??C(y):typeof b.backgroundColor==="string"?b.backgroundColor:C(y);if(this.ctx.fillStyle=z,this.ctx.fillRect(A,S,Math.max(1,p-2),B),b.borderWidth&&b.borderColor&&typeof b.borderColor==="string")this.ctx.lineWidth=b.borderWidth,this.ctx.strokeStyle=b.borderColor,this.ctx.strokeRect(A,S,Math.max(1,p-2),B);if(r)if(m>=0)l=I;else f=I;this.hitItems.push({datasetIndex:y,dataIndex:x,x:A+p/2,y:S,label:e[x]??String(x),value:m})})}}renderRadial(t,e){let n=this.data.datasets;if(n.length===0)return;let o=n[0];if(!o)return;let i=this.data.labels??[],s=this.layoutLegend(t,e),d=t,r=e,a=0,c=0;if(s.position==="right")d=t-s.w;else if(s.position==="left")d=t-s.w,a=s.w;else if(s.position==="top")r=e-s.h,c=s.h;else if(s.position==="bottom")r=e-s.h;this.drawLegend(s,n.map((m,g)=>({...m,label:i[g]??m.label})),i);let u=a+d/2,p=c+r/2,x=Math.min(d,r)/2-8,h=this.options.cutout,l=typeof h==="string"&&h.endsWith("%")?Number.parseFloat(h)/100:this.type==="doughnut"?0.6:0,f=x*l,y=U().value((m)=>Math.max(0,m||0)).startAngle(-Math.PI/2).endAngle(-Math.PI/2+Math.PI*2).sort(null)(o.data),w=X().innerRadius(f).outerRadius(x);this.ctx.save(),this.ctx.translate(u,p);for(let m of y){let g=m.index,I=o.data[g]??0,k=Array.isArray(o.backgroundColor)?o.backgroundColor[g]??C(g):typeof o.backgroundColor==="string"?o.backgroundColor:C(g);this.ctx.beginPath(),w.context(this.ctx)(m),this.ctx.fillStyle=k,this.ctx.fill();let v=(m.startAngle+m.endAngle)/2-Math.PI/2,A=(x+f)/2;this.hitItems.push({datasetIndex:0,dataIndex:g,x:u+Math.cos(v)*A,y:p+Math.sin(v)*A,label:i[g]??String(g),value:I})}this.ctx.restore(),w.context(null)}layoutLegend(t,e){let n=this.options.plugins?.legend;if(n?.display===!1||!this.data.datasets.some((i)=>i.label))return{w:0,h:0,position:"none"};let o=n?.position??"top";if(o==="left"||o==="right")return{w:100,h:0,position:o};return{w:0,h:Math.max(24,Math.ceil(this.data.datasets.length/4)*18+8),position:o}}drawLegend(t,e,n){if(t.position==="none")return;let o=this.options.plugins?.legend,i=n&&(this.type==="pie"||this.type==="doughnut")?n.map((r,a)=>{let c=e[0],u=Array.isArray(c?.backgroundColor)?c.backgroundColor[a]??C(a):typeof c?.backgroundColor==="string"?c.backgroundColor:C(a);return{label:r,color:u}}):e.map((r,a)=>({label:r.label??`Dataset ${a+1}`,color:typeof r.borderColor==="string"?r.borderColor:Array.isArray(r.backgroundColor)?r.backgroundColor[0]??C(a):typeof r.backgroundColor==="string"?r.backgroundColor:C(a)}));if(i.length===0)return;this.ctx.save(),this.ctx.font=`${o?.labels?.font?.size??12}px system-ui, sans-serif`,this.ctx.fillStyle=o?.labels?.color??T,this.ctx.textBaseline="middle";let s=o?.labels?.boxWidth??12,d=o?.labels?.padding??8;if(t.position==="top"||t.position==="bottom"){let r=t.position==="top"?12:(this.canvas.clientHeight||0)-12,a=d;this.ctx.textAlign="left";for(let c of i)this.ctx.fillStyle=c.color,this.ctx.fillRect(a,r-s/2,s,s),a+=s+4,this.ctx.fillStyle=o?.labels?.color??T,this.ctx.fillText(c.label,a,r),a+=this.ctx.measureText(c.label).width+d*2}else{let r=t.position==="right"?(this.canvas.clientWidth||0)-110:8,a=d+6;for(let c of i)this.ctx.fillStyle=c.color,this.ctx.fillRect(r,a-s/2,s,s),this.ctx.fillStyle=o?.labels?.color??T,this.ctx.textAlign="left",this.ctx.fillText(c.label,r+s+4,a),a+=18}this.ctx.restore()}drawCrosshair(t){let e=this.hitItems.find((n)=>n.dataIndex===this.activeIndex);if(!e)return;this.ctx.save(),this.ctx.setLineDash([4,3]),this.ctx.strokeStyle="rgba(128, 141, 160, 0.55)",this.ctx.lineWidth=1,this.ctx.beginPath(),this.ctx.moveTo(e.x,t.y),this.ctx.lineTo(e.x,t.y+t.h),this.ctx.stroke(),this.ctx.restore()}setActiveIndex(t){if(!this.options.plugins?.tooltip?.crosshair||t===this.activeIndex)return;this.activeIndex=t,this.render()}clearHover(){this.setActiveIndex(null),this.hideTooltip()}handleMouseMove(t){if(this.hitItems.length===0)return;let e=this.canvas.getBoundingClientRect(),n=t.clientX-e.left,o=t.clientY-e.top,i=this.plot;if(this.options.plugins?.tooltip?.crosshair&&i&&(n<i.x||n>i.x+i.w||o<i.y||o>i.y+i.h)){this.clearHover();return}if((this.options.interaction?.mode??this.options.plugins?.tooltip?.mode??"nearest")==="index"){let a=this.data.labels?.length??0,c=i&&a&&this.type==="line"&&this.options.plugins?.tooltip?.crosshair?this.hitItems.filter((u)=>u.dataIndex===Math.round((n-i.x)/i.w*(a-1))):this.findClosestByIndex(n);if(c?.length)this.showTooltip(t.clientX,t.clientY,c);else this.clearHover();return}let d=null,r=Number.POSITIVE_INFINITY;for(let a of this.hitItems){let c=a.x-n,u=a.y-o,p=c*c+u*u;if(p<r)r=p,d=a}if(d&&r<3600)this.showTooltip(t.clientX,t.clientY,[d]);else this.clearHover()}handleKeyDown(t){if(t.key==="Escape"){this.clearHover();return}if(t.key!=="ArrowLeft"&&t.key!=="ArrowRight")return;let e=[...new Set(this.hitItems.map((r)=>r.dataIndex))].sort((r,a)=>r-a);if(!e.length)return;t.preventDefault();let n=this.activeIndex===null?-1:e.indexOf(this.activeIndex),o=n===-1?t.key==="ArrowRight"?e[0]:e[e.length-1]:e[Math.max(0,Math.min(e.length-1,n+(t.key==="ArrowRight"?1:-1)))],i=this.hitItems.filter((r)=>r.dataIndex===o),s=i[0];if(!s)return;let d=this.canvas.getBoundingClientRect();this.showTooltip(d.left+s.x,d.top+s.y,i,!0)}findClosestByIndex(t){let e=-1,n=Number.POSITIVE_INFINITY;for(let o of this.hitItems){let i=Math.abs(o.x-t);if(i<n)n=i,e=o.dataIndex}if(e<0)return null;return this.hitItems.filter((o)=>o.dataIndex===e)}showTooltip(t,e,n,o=!1){this.setActiveIndex(n[0]?.dataIndex??null);let i=this.options.plugins?.tooltip;if(!this.tooltipEl)this.tooltipEl=document.createElement("div"),this.tooltipEl.setAttribute("role","tooltip"),Object.assign(this.tooltipEl.style,{position:"fixed",pointerEvents:"none",background:i?.backgroundColor??q,color:i?.bodyColor??"#fff",padding:i?.padding===void 0?"6px 10px":`${i.padding}px`,border:i?.borderWidth?`${i.borderWidth}px solid ${i.borderColor??"currentColor"}`:"",borderRadius:i?.crosshair?"10px":"6px",boxShadow:i?.crosshair?"0 5px 18px rgba(15, 23, 42, .13)":"",font:"12px system-ui, sans-serif",zIndex:"9999",whiteSpace:"pre-line",overflowWrap:"anywhere",boxSizing:"border-box",maxWidth:"calc(100vw - 16px)"}),document.body.appendChild(this.tooltipEl);let s=i?.callbacks,d=[];n.forEach((h)=>{let l=this.data.datasets[h.datasetIndex];if(!l)return;let f={dataset:l,datasetIndex:h.datasetIndex,dataIndex:h.dataIndex,parsed:{y:h.value},raw:h.value,label:h.label,formattedValue:E(h.value)},b=s?.label?s.label(f):`${l.label??""}: ${E(h.value)}`,y=Array.isArray(b)?b.join(`
3
+ `):b;d.push({text:y,color:typeof l.borderColor==="string"?l.borderColor:C(h.datasetIndex)})});let r=s?.title?s.title(n.flatMap((h)=>{let l=this.data.datasets[h.datasetIndex];if(!l)return[];return[{dataset:l,datasetIndex:h.datasetIndex,dataIndex:h.dataIndex,parsed:{y:h.value},raw:h.value,label:h.label,formattedValue:E(h.value)}]})):n[0]?.label,a=Array.isArray(r)?r.join(`
4
+ `):r;if(this.tooltipEl.setAttribute("aria-live",o?"polite":"off"),this.tooltipEl.textContent="",a){let h=document.createElement("strong");h.textContent=a,h.style.color=i?.titleColor??"",this.tooltipEl.appendChild(h),this.tooltipEl.appendChild(document.createElement("br"))}if(i?.crosshair)for(let h of d){let l=document.createElement("div"),f=document.createElement("span");Object.assign(l.style,{display:"flex",alignItems:"center",gap:"6px",marginTop:"4px"}),Object.assign(f.style,{backgroundColor:h.color,width:"8px",height:"8px",borderRadius:"50%",flexShrink:"0"}),l.append(f,document.createTextNode(h.text)),this.tooltipEl.appendChild(l)}else this.tooltipEl.appendChild(document.createTextNode(d.map((h)=>h.text).join(`
5
+ `)));this.tooltipEl.style.display="block";let{offsetWidth:c,offsetHeight:u}=this.tooltipEl,p=t+12+c<=window.innerWidth?t+12:t-c-12,x=e+12+u<=window.innerHeight?e+12:e-u-12;this.tooltipEl.style.left=`${Math.max(8,p)}px`,this.tooltipEl.style.top=`${Math.max(8,x)}px`}hideTooltip(){if(this.tooltipEl)this.tooltipEl.style.display="none"}}var pt=L,dt=[];export{L as Chart,M as DEFAULT_PALETTE,pt as default,E as formatTick,D as niceTicks,C as paletteColor,dt as registerables,R as withAlpha};
package/dist/types.d.ts CHANGED
@@ -70,6 +70,7 @@ export declare interface TooltipConfig {
70
70
  enabled?: boolean
71
71
  mode?: 'index' | 'point' | 'nearest' | 'dataset'
72
72
  intersect?: boolean
73
+ crosshair?: boolean
73
74
  callbacks?: {
74
75
  label?: (ctx: TooltipCallbackContext) => string | string[]
75
76
  title?: (ctx: TooltipCallbackContext[]) => string | string[]
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/charts",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.719",
5
+ "version": "0.75.723",
6
6
  "description": "Chart rendering for Stacks. Built on ts-charts (D3 in TypeScript).",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -59,9 +59,9 @@
59
59
  "prepublishOnly": "bun run build"
60
60
  },
61
61
  "dependencies": {
62
- "@ts-charts/format": "^0.2.7",
63
- "@ts-charts/scale": "^0.2.7",
64
- "@ts-charts/shape": "^0.2.7"
62
+ "@ts-charts/format": "^0.2.9",
63
+ "@ts-charts/scale": "^0.2.9",
64
+ "@ts-charts/shape": "^0.2.9"
65
65
  },
66
66
  "devDependencies": {
67
67
  "better-dx": "^0.2.39"