import {useEffect, useRef, useState} from 'react'; import { Chart, TimeScale, LinearScale, Legend, LineController, PointElement, LineElement } from 'chart.js' import 'chartjs-adapter-moment'; import ChartDataLabels from 'chartjs-plugin-datalabels'; import zoomPlugin from 'chartjs-plugin-zoom'; Chart.register(TimeScale, LinearScale, LineController, LineElement, PointElement, Legend, ChartDataLabels, zoomPlugin); const defaultOptions = { responsive: true, aspectRatio: 2.6, interaction: { intersect: false, mode: 'index', }, scales: { x:{ display: true, title: { display: true }, type: 'time', time: { unit: 'hour', displayFormats: { 'hour': 'MM.DD' } }, grid:{ drawTicks: true, }, ticks: { stepSize:3, major:{enabled:true,}, z: 1, display : true, textStrokeColor : "#fff", textStrokeWidth : 2, color:"#000", } }, y:{ type:'linear', position:'top', reverse:true, display: true, title: { display: false, text: '' }, } }, parsing: { xAxisKey: 'date', yAxisKey: 'depth' }, elements:{ point:{ radius:1.7, //backgroundColor:'#aaa', //pointStyle:'triangle', }, }, plugins:{ legend:{ display: true, }, datalabels: { display: false, }, tooltip: { enabled: true, callbacks: { label(tooltipItem) { return tooltipItem.yLabel; } } }, } } const makeDataset = (data, label, color, width=1.5, dash) => ({ label: label, data: data, backgroundColor: color, borderColor: color, borderWidth: width, borderDash: dash, }) export default function ChartTvD({dataPlan, dataFact, dataPredict}) { const chartRef = useRef(null) const [chart, setChart] = useState() useEffect(() => { let data = { datasets: [ makeDataset(dataFact, 'Факт', '#0A0'), makeDataset(dataPredict, 'Прогноз', 'purple', 1, [7,3]), makeDataset(dataPlan, 'План', '#C004', 4), ] } if((chartRef.current)&&(!chart)) { let thisOptions = {} Object.assign(thisOptions, defaultOptions) let newChart = new Chart(chartRef.current, { type: 'line', plugins: [ChartDataLabels], options: thisOptions, data: data }) setChart(newChart) return () => chart?.destroy() } else { chart.data = data chart.update() } }, [chart, dataPlan, dataFact, dataPredict]) return () }