summaryrefslogtreecommitdiff
path: root/ping/frontend/src/lib/components/SteppedLineChart.svelte
blob: d393b44c5380dd3f778afbef1187aec12cdccf92 (plain)
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
<script lang="ts">
	import {
		Chart,
		CategoryScale,
		LinearScale,
		PointElement,
		LineElement,
		Title,
		Tooltip,
		Legend,
		LineController
	} from 'chart.js';
	import { onMount } from 'svelte';

	Chart.register(
		CategoryScale,
		LinearScale,
		PointElement,
		LineElement,
		Title,
		Tooltip,
		Legend,
		LineController
	);

	interface IProps {
		color?: string;
		data?: any[];
		title?: string;
		legend?: string;
	}

	const { color = 'green', data = [], title = '', legend = '' }: IProps = $props();

	function updateGraph() {
		const ctx = document.getElementById(id) as HTMLCanvasElement;
		const chart = new Chart(ctx, {
			type: 'line',
			data: {
				labels: data.map((d) => d.label),
				datasets: [
					{
						label: legend,
						data: data.map((d) => d.value),
						borderColor: color,
						backgroundColor: color,
						fill: false,
						tension: 0.1
					}
				]
			},
			options: {
				responsive: true,
				plugins: {
					title: {
						display: true,
						text: title
					},
					legend: {
						display: true
					}
				}
			}
		});
	}

	const id = 'graph-' + crypto.randomUUID();

	onMount(() => {
		updateGraph();
	});
</script>

<div>
	<canvas {id}></canvas>
</div>