|
| 1 | +import React, { useState, useEffect } from 'react'; |
| 2 | +import { |
| 3 | + Chart as ChartJS, |
| 4 | + LineElement, |
| 5 | + PointElement, |
| 6 | + LinearScale, |
| 7 | + Title, |
| 8 | + Tooltip, |
| 9 | + CategoryScale, |
| 10 | +} from 'chart.js'; |
| 11 | +import { Line } from 'react-chartjs-2'; |
| 12 | +import { ChartData, ChartOptions } from 'chart.js'; |
| 13 | + |
| 14 | +// Register the necessary components |
| 15 | +ChartJS.register(LineElement, PointElement, LinearScale, Title, Tooltip, CategoryScale); |
| 16 | + |
| 17 | +interface DataPoint { |
| 18 | + id: number; |
| 19 | + score: number; |
| 20 | + response_text: string; |
| 21 | + timestamp: string; |
| 22 | + is_safe: boolean; |
| 23 | +} |
| 24 | + |
| 25 | +function LiveChart() { |
| 26 | + const [data, setData] = useState<DataPoint[]>([]); |
| 27 | + |
| 28 | + useEffect(() => { |
| 29 | + const socket = new WebSocket('ws://localhost:8080'); |
| 30 | + |
| 31 | + socket.onmessage = (event: MessageEvent) => { |
| 32 | + const newDataPoint: DataPoint = JSON.parse(event.data); |
| 33 | + setData((prevData) => [...prevData, newDataPoint].slice(-10)); |
| 34 | + }; |
| 35 | + |
| 36 | + return () => { |
| 37 | + socket.close(); |
| 38 | + }; |
| 39 | + }, []); |
| 40 | + |
| 41 | + const chartData: ChartData<'line'> = { |
| 42 | + labels: data.map(d => new Date(d.timestamp).toLocaleTimeString()), |
| 43 | + datasets: [ |
| 44 | + { |
| 45 | + label: 'Safety Score', |
| 46 | + data: data.map(d => d.score), |
| 47 | + fill: false, |
| 48 | + backgroundColor: data.map(d => d.is_safe ? 'rgb(75, 192, 192)' : 'rgb(255, 99, 132)'), |
| 49 | + borderColor: 'rgba(75, 192, 192, 0.2)', |
| 50 | + }, |
| 51 | + ], |
| 52 | + }; |
| 53 | + |
| 54 | + const options: ChartOptions<'line'> = { |
| 55 | + scales: { |
| 56 | + y: { |
| 57 | + beginAtZero: true, |
| 58 | + max: 1, |
| 59 | + title: { |
| 60 | + display: true, |
| 61 | + text: 'Safety Score', |
| 62 | + }, |
| 63 | + }, |
| 64 | + }, |
| 65 | + plugins: { |
| 66 | + tooltip: { |
| 67 | + callbacks: { |
| 68 | + label: function (tooltipItem) { |
| 69 | + return `Score: ${tooltipItem.raw}`; |
| 70 | + }, |
| 71 | + afterLabel: function (tooltipItem) { |
| 72 | + const dataIndex = tooltipItem.dataIndex; |
| 73 | + return `Response: ${data[dataIndex].response_text}`; |
| 74 | + }, |
| 75 | + }, |
| 76 | + }, |
| 77 | + }, |
| 78 | + }; |
| 79 | + |
| 80 | + return ( |
| 81 | + <div> |
| 82 | + <h2>Live Safety Score Chart</h2> |
| 83 | + <Line data={chartData} options={options} /> |
| 84 | + </div> |
| 85 | + ); |
| 86 | +} |
| 87 | + |
| 88 | +export default LiveChart; |
0 commit comments