Skip to content

Commit

Permalink
fix: alterations after review and improved code
Browse files Browse the repository at this point in the history
  • Loading branch information
edvinstava committed Feb 22, 2024
1 parent 18e45e7 commit 5e67a79
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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 <Line data={data} options={options} />;
};
25 changes: 25 additions & 0 deletions src/utils/annotateLineEnd.ts
Original file line number Diff line number Diff line change
@@ -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);
});
};

0 comments on commit 5e67a79

Please sign in to comment.