owncast/web/components/chart.tsx

99 lines
1.9 KiB
TypeScript
Raw Normal View History

import ChartJs from 'chart.js/auto';
import Chartkick from 'chartkick';
import format from 'date-fns/format';
2021-01-03 13:13:28 +03:00
import { LineChart } from 'react-chartkick';
2021-04-13 05:56:37 +03:00
// from https://github.com/ankane/chartkick.js/blob/master/chart.js/chart.esm.js
Chartkick.use(ChartJs);
2020-11-01 09:17:44 +03:00
2020-11-01 10:01:37 +03:00
interface TimedValue {
time: Date;
value: number;
2020-11-01 10:01:37 +03:00
}
2020-10-28 10:53:24 +03:00
interface ChartProps {
data?: TimedValue[];
title?: string;
color: string;
unit: string;
yFlipped?: boolean;
yLogarithmic?: boolean;
dataCollections?: any[];
2020-10-28 10:53:24 +03:00
}
2020-11-25 11:17:35 +03:00
function createGraphDataset(dataArray) {
2020-11-29 02:28:39 +03:00
const dataValues = {};
2020-11-25 11:17:35 +03:00
dataArray.forEach(item => {
const dateObject = new Date(item.time);
2021-04-13 05:56:37 +03:00
const dateString = format(dateObject, 'H:mma');
dataValues[dateString] = item.value;
2021-02-04 20:19:16 +03:00
});
2020-11-25 11:17:35 +03:00
return dataValues;
}
export default function Chart({
data,
title,
color,
unit,
dataCollections,
yFlipped,
yLogarithmic,
}: ChartProps) {
2020-11-29 02:28:39 +03:00
const renderData = [];
2020-11-01 10:01:37 +03:00
if (data && data.length > 0) {
renderData.push({
name: title,
2020-11-29 02:28:39 +03:00
color,
data: createGraphDataset(data),
2020-11-01 10:01:37 +03:00
});
}
2020-11-01 09:17:44 +03:00
dataCollections.forEach(collection => {
renderData.push({
name: collection.name,
data: createGraphDataset(collection.data),
color: collection.color,
dataset: collection.options,
});
});
// ChartJs.defaults.scales.linear.reverse = true;
const options = {
scales: {
y: { reverse: false, type: 'linear' },
x: {
type: 'time',
},
},
};
options.scales.y.reverse = yFlipped;
options.scales.y.type = yLogarithmic ? 'logarithmic' : 'linear';
2020-10-27 09:53:04 +03:00
return (
<div className="line-chart-container">
2020-11-29 05:14:08 +03:00
<LineChart
xtitle="Time"
ytitle={title}
suffix={unit}
legend="bottom"
color={color}
data={renderData}
download={title}
library={options}
2020-11-29 05:14:08 +03:00
/>
</div>
);
2020-10-27 09:53:04 +03:00
}
2020-11-01 09:17:44 +03:00
Chart.defaultProps = {
dataCollections: [],
data: [],
title: '',
yFlipped: false,
yLogarithmic: false,
2020-11-01 09:17:44 +03:00
};