import { useEffect, useState} from 'react'; import {ChartTimeBase, ChartTimeData, ChartTimeDataParams} from './ChartTimeBase' const GetRandomColor = () => "#" + Math.floor(Math.random()*16777215).toString(16) function GetOrCreateDatasetByLineConfig (data: ChartTimeData, lineConfig: LineConfig) { let dataset = data?.datasets.find(d=>d.label === lineConfig.label) if(!dataset) { let color = lineConfig.borderColor ?? lineConfig.backgroundColor ?? lineConfig.color ?? GetRandomColor() dataset = { label:lineConfig.label, data:[], backgroundColor: lineConfig.backgroundColor ?? color, borderColor: lineConfig.borderColor ?? color, borderWidth: lineConfig.borderWidth ?? 1, borderDash: lineConfig.dash ?? [], } data.datasets.push(dataset); } return dataset } export type LineConfig = { type?: string label: string xAcessorName: string yAcessorName: string color?:string borderColor?: string backgroundColor?: string borderWidth?: number dash?:number[] labels?: any[] } export type ChartTimeProps = { yDisplay: Boolean, lines: LineConfig[], data: any[], interval: number, } export const ChartTime: React.FC = (props) => { const [dataParams, setDataParams] = useState({data: {datasets:[]}, yStart: new Date(), }) useEffect(()=>{ if( (!props?.lines) || (!props?.data) || (props.lines.length === 0) || (props.data.length === 0)) return props.lines.forEach(lineCfg => { let dataset = GetOrCreateDatasetByLineConfig(dataParams.data, lineCfg) let points = props.data.map(dataItem => {return{ x: dataItem[lineCfg.xAcessorName], y: new Date(dataItem[lineCfg.yAcessorName])} }) dataset.data = [ ...dataset.data, ...points, ].slice(-1024) }); dataParams.yStart = new Date() dataParams.yStart.setSeconds(dataParams.yStart.getSeconds() - props.interval) dataParams.yInterval = props.interval setDataParams(dataParams) }, [ props.data, props.lines, props.interval]) return() }