Skip to content

Commit c2a245e

Browse files
authored
Merge pull request #119 from Makanz/bugfix/issue-118
Bugfix/issue 118
2 parents bb1ac49 + 70bdb2b commit c2a245e

File tree

3 files changed

+143
-5
lines changed

3 files changed

+143
-5
lines changed

dist/chartjs-plugin-trendline.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/components/trendline.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,12 @@ export const addFitter = (datasetMeta, ctx, dataset, xScale, yScale) => {
3232
displayValue = true,
3333
offset = 10,
3434
percentage = false,
35-
} = dataset.trendlineLinear.label || {};
35+
} = (dataset.trendlineLinear && dataset.trendlineLinear.label) || {};
3636

3737
const {
3838
family = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
3939
size = 12,
40-
} = dataset.trendlineLinear.label?.font || {};
40+
} = (dataset.trendlineLinear && dataset.trendlineLinear.label && dataset.trendlineLinear.label.font) || {};
4141

4242
const chartOptions = datasetMeta.controller.chart.options;
4343
const parsingOptions =
@@ -101,8 +101,8 @@ export const addFitter = (datasetMeta, ctx, dataset, xScale, yScale) => {
101101
if (trendoffset < 0 && index >= dataset.data.length + trendoffset) return;
102102

103103
// Process data based on scale type and data structure.
104-
if (['time', 'timeseries'].includes(xScale.options.type)) {
105-
// For time-based scales, convert x to a numerical timestamp; ensure y is a valid number.
104+
if (['time', 'timeseries'].includes(xScale.options.type) && xy) {
105+
// For time-based scales with object data, convert x to a numerical timestamp; ensure y is a valid number.
106106
let x = data[xAxisKey] != null ? data[xAxisKey] : data.t; // `data.t` is a Chart.js internal fallback for time data.
107107
const yValue = data[yAxisKey];
108108

@@ -123,6 +123,15 @@ export const addFitter = (datasetMeta, ctx, dataset, xScale, yScale) => {
123123
fitter.add(xVal, yVal);
124124
}
125125
// If either xVal or yVal is invalid, the point is skipped. No fallback to using index.
126+
} else if (['time', 'timeseries'].includes(xScale.options.type) && !xy) {
127+
// For time-based scales with array of numbers, get the x-value from the chart labels
128+
const chartLabels = datasetMeta.controller.chart.data.labels;
129+
if (chartLabels && chartLabels[index] && data != null && !isNaN(data)) {
130+
const timeValue = new Date(chartLabels[index]).getTime();
131+
if (!isNaN(timeValue)) {
132+
fitter.add(timeValue, data);
133+
}
134+
}
126135
} else {
127136
// Data is an array of numbers (or other non-object types).
128137
// The 'data' variable itself is the y-value, and 'index' is the x-value.

0 commit comments

Comments
 (0)