Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | import { useCallback, useMemo, useState } from "react";
import useDatasetsConfig from "./hooks/useDatasetsConfig";
import useTimeConfig from "./hooks/useTimeConfig";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
TimeScale,
} from "chart.js";
import { Line } from "react-chartjs-2";
import { Stack } from "@mui/material";
import "chartjs-adapter-moment";
import MouseLinePlugin from "./plugins/MouseLinePlugin";
import { TRenderDataSets, TTimeConfig } from "@components/LineGraph/types";
import useGetOptions from "./utils/options";
import { TimeLineChartData } from "./types";
ChartJS.register(
CategoryScale,
LinearScale,
TimeScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
);
interface TimeLineChartProps {
data: TimeLineChartData[];
renderDatasets?: TRenderDataSets;
height?: number | string;
customOptions?: any;
customTimeConfig?: Partial<TTimeConfig>;
}
const TimeLineChart = ({
data,
renderDatasets,
height = 200,
customOptions,
customTimeConfig,
}: TimeLineChartProps) => {
const [hidden, setHidden] = useState<Record<number, boolean>>({});
const { customData } = useDatasetsConfig(data);
const { timeConfig } = useTimeConfig(data, true);
const options = useGetOptions({
scales: {
x: {
time: {
...timeConfig,
...customTimeConfig,
},
adapters: {
date: {
zone: "UTC",
},
},
},
},
...customOptions,
});
const numberOfDatasets = customData.datasets.length;
const toggleDataset = useCallback(
(index: any) => {
const hiddenDatesets = Object.values(hidden).filter((el) => !!el);
if (hiddenDatesets.length === numberOfDatasets - 1 && !hidden[index])
return;
setHidden({
...hidden,
[index]: !hidden[index],
});
},
[hidden],
);
const datasets = useMemo(() => {
if (!renderDatasets) return customData?.datasets || [];
return (
customData?.datasets?.map((dataset, i) => ({
...dataset,
hidden: hidden[i],
})) || []
);
}, [customData, hidden]);
return (
<>
<Stack
width="100%"
height="max-content"
direction="row"
alignItems="center"
justifyContent="stretch"
>
<Line
height={height}
options={options}
data={{ ...data, datasets }}
plugins={[MouseLinePlugin]}
/>
</Stack>
{renderDatasets && renderDatasets(datasets, toggleDataset)}
</>
);
};
export default TimeLineChart;
|