import { ChartJs, Rect2D, SvgCanvas, SvgCanvas2DGradient } from "./deps.ts";
class ChartSvgCanvas extends SvgCanvas { public override clearRect(x: number, y: number, w: number, h: number): void { this.save(); this.fillStyle = "transparent"; this.fillRect(x, y, w, h); this.restore(); }
public resetTransform() { this.setTransform(1, 0, 0, 1, 0, 0); }}
export const defaults: ChartJs.Defaults = ChartJs.defaults;export const plugins = ChartJs.plugins;
export type ChartOptions<TType extends ChartJs.ChartType = ChartJs.ChartType> = Omit< ChartJs.ChartOptions<TType>, | "responsive" | "responsiveAnimationDuration" | "events" | "legendCallback" | "onHover" | "onClick" | "onResize" | "hover" | "animation" >;
export interface ChartConfiguration< TType extends ChartJs.ChartType = ChartJs.ChartType, TData = ChartJs.DefaultDataPoint<TType>, TLabel = unknown,> { width?: number; height?: number; type?: ChartJs.ChartType; data: ChartJs.ChartData<TType, TData, TLabel>; options?: ChartOptions; plugins?: ChartJs.Plugin[];}
interface SvgCanvasExtras { canvas?: { width: number; height: number; style: Record<string, string>; }; resetTransform?(): void;}
export function chart< TType extends ChartJs.ChartType = ChartJs.ChartType, TData = ChartJs.DefaultDataPoint<TType>, TLabel = unknown,>( { width = 768, height = 384, type = "bar", data, options = {}, plugins }: ChartConfiguration<TType, TData, TLabel> = { data: { datasets: [] } },): string { Object.assign(options, { animation: false, events: [], responsive: false, });
const ctx: ChartSvgCanvas & SvgCanvasExtras = new ChartSvgCanvas(); ctx.canvas = { width, height, style: { width: `${width}px`, height: `${height}px` }, }; ctx.fontHeightRatio = 2; const el: HTMLCanvasElement = { getContext: () => ctx } as any; const savedGradient = globalThis.CanvasGradient; globalThis.CanvasGradient = SvgCanvas2DGradient as typeof CanvasGradient;
try { new ChartJs.Chart(el, { type, data, options, plugins }); } finally { if (savedGradient) { globalThis.CanvasGradient = savedGradient; } }
return ctx.render(new Rect2D(0, 0, width, height), "px");}