diff --git a/src/Components/GrowthChart/GrowthChartBuilder/GrowthChartBuilder.tsx b/src/Components/GrowthChart/GrowthChartBuilder/GrowthChartBuilder.tsx index a0054d0..d583a3e 100644 --- a/src/Components/GrowthChart/GrowthChartBuilder/GrowthChartBuilder.tsx +++ b/src/Components/GrowthChart/GrowthChartBuilder/GrowthChartBuilder.tsx @@ -1,11 +1,10 @@ -import React, { useEffect } from 'react'; +import React from 'react'; import i18n from '@dhis2/d2-i18n'; import { Line } from 'react-chartjs-2'; -import { Chart, LineController, LineElement, PointElement, LinearScale, Title, CategoryScale } from 'chart.js'; +import 'chart.js/auto'; import { ChartDataTypes } from '../../../types/chartDataTypes'; import { chartLineColorPicker } from '../../../utils/chartLineColorPicker'; - -Chart.register(LineController, LineElement, PointElement, LinearScale, Title, CategoryScale); +import { annotateLineEnd } from '../../../utils/annotateLineEnd'; export const GrowthChartBuilder = ({ dataSetValues, dataSetMetadata, xLabelValues, keysDataSet, @@ -20,30 +19,16 @@ export const GrowthChartBuilder = ({ })), }; - const options = { + const options: any = { elements: { point: { radius: 0, hoverRadius: 0 } }, plugins: { legend: { display: false } }, scales: { x: { title: { display: true, text: i18n.t(`age (${dataSetMetadata.unit})`) } }, y: { title: { display: true, text: dataSetMetadata.yaxis } }, }, - layout: { padding: { right: 60 } }, - }; - - const afterDraw = (chart: Chart<'line', number[], string>) => { - const { ctx } = chart; - chart.data.datasets.forEach((dataset, index) => { - const meta = chart.getDatasetMeta(index); - const [lastElement] = meta.data.slice(-1); - const { x, y } = lastElement.getProps(['x', 'y']); - ctx.fillStyle = typeof dataset.borderColor === 'string' ? dataset.borderColor : 'black'; - ctx.fillText(dataset.label, x + 10, y); - }); + layout: { padding: { right: 75 } }, + animation: { onProgress: annotateLineEnd }, }; - useEffect(() => { - Chart.register({ id: 'custom_draw', afterDraw }); - }, []); - return ; }; diff --git a/src/utils/annotateLineEnd.ts b/src/utils/annotateLineEnd.ts new file mode 100644 index 0000000..18b93e1 --- /dev/null +++ b/src/utils/annotateLineEnd.ts @@ -0,0 +1,25 @@ +import { Animation, Chart } from 'chart.js'; + +interface DataSet { + data: number[]; + borderWidth: number; + borderColor: string; + label: string; +} + +export const annotateLineEnd = (animation: Animation & { chart?: Chart }) => { + const { chart } = animation; + if (!chart) { + return; + } + const { ctx } = chart; + + chart.data.datasets.forEach((dataset: DataSet, index: number) => { + const meta = chart.getDatasetMeta(index); + const [lastElement] = meta.data.slice(-1); + const { x, y } = lastElement.getProps(['x', 'y']); + ctx.fillStyle = dataset.borderColor; + ctx.font = '14px Arial'; + ctx.fillText(dataset.label, x + 10, y); + }); +};