ChartJS: improvements

This commit is contained in:
Enrico Ros
2024-09-24 20:11:37 -07:00
parent 4a896be01b
commit 1e61998b50
5 changed files with 44 additions and 18 deletions
@@ -10,7 +10,6 @@ import { create } from 'zustand';
import type { Chart as ChartConstructorType } from 'chart.js/auto';
import { devDependencies } from '../../../../../package.json';
import { themeFontFamilyCss } from '~/common/app.theme';
@@ -22,6 +21,24 @@ const CHARTJS_SCRIPT_ID = 'chartjs-cdn';
export type { ChartConstructorType };
// Code manipulation functions
export function fixupChartJSObject(chartConfig: ChartConstructorType['config']): void {
// Remove responsive options - we hadle this ourselves by default
delete chartConfig?.options?.responsive;
delete chartConfig?.options?.maintainAspectRatio;
}
function _initializeChartJS(Chart: typeof ChartConstructorType): typeof ChartConstructorType {
Chart.defaults.font.family = themeFontFamilyCss;
Chart.defaults.font.size = 13;
Chart.defaults.maintainAspectRatio = true; // defaults to 1 for polar and so, 2 for bars and more
Chart.defaults.responsive = true; // re-draw on resize
// Chart.defaults.layout.autoPadding = true; // default padding
return Chart;
}
// Singleton promise for loading Chart.js
let chartJSPromise: Promise<typeof ChartConstructorType> | null = null;
@@ -47,7 +64,7 @@ function loadCDNScript(): Promise<typeof ChartConstructorType> {
script.async = true;
script.onload = () => {
if ((window as any).Chart) resolve(initializeChartJS((window as any).Chart));
if ((window as any).Chart) resolve(_initializeChartJS((window as any).Chart));
else reject(new Error('Chart.js failed to load.'));
};
@@ -62,14 +79,6 @@ function loadCDNScript(): Promise<typeof ChartConstructorType> {
return chartJSPromise;
}
function initializeChartJS(Chart: typeof ChartConstructorType): typeof ChartConstructorType {
Chart.defaults.font.family = themeFontFamilyCss;
Chart.defaults.font.size = 13;
Chart.defaults.maintainAspectRatio = true;
Chart.defaults.responsive = true;
return Chart;
}
// Store: we share the state across multiple useChartJS hooks
interface ChartApiStore {