import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'; import { Doughnut } from 'react-chartjs-2'; import { useState } from '@wordpress/element'; ChartJS.register( ArcElement, Tooltip, Legend ); interface AnalysisPieProps { metric: string; dataPoints: PieDataPoint[]; annotationLabel: string; annotationValue: string; } export default function AnalysisPie( props: AnalysisPieProps ) { const baseData = { labels: [] as string[], datasets: [ { label: '', data: [] as number[], backgroundColor: [] as string[], borderColor: props.dataPoints.length > 1 ? '#fff' : 'transparent', }, ], }; const options = { plugins: { legend: { display: false, }, tooltip: { // position: 'nearest', enabled: false, // disable the built-in tooltip external: ( context ) => { let tooltipEl = document.getElementById( 'gs-chartjs-tooltip' ); if ( ! tooltipEl ) { tooltipEl = document.createElement( 'div' ); tooltipEl.id = 'gs-chartjs-tooltip'; tooltipEl.classList.add( 'gs-chartjs-tooltip' ); document.body.appendChild( tooltipEl ); } const tooltipModel = context.tooltip; if ( tooltipModel.opacity === 0 ) { tooltipEl.style.opacity = '0'; return; } if ( tooltipModel.body ) { const titleLines = tooltipModel.title || []; const bodyLines = tooltipModel.body.map( ( b ) => b.lines ); let innerHtml = ''; titleLines.forEach( ( title ) => { innerHtml += `${ title }`; } ); bodyLines.forEach( ( body ) => { innerHtml += `${ body }`; } ); tooltipEl.innerHTML = innerHtml; } tooltipEl.style.opacity = '1'; tooltipEl.style.left = cursorPosition.x + 'px'; tooltipEl.style.top = cursorPosition.y + 'px'; tooltipEl.style.pointerEvents = 'none'; }, callbacks: { label: ( context ) => { const label = context.label || ''; let value = context.formattedValue || ''; const dataPoint = props.dataPoints.find( ( point ) => point.label === label ); if ( dataPoint && dataPoint.displayValue ) { value = dataPoint.displayValue; } return `${ value }`; }, }, }, }, cutout: '75%', }; const [ cursorPosition, setCursorPosition ] = useState( { x: 0, y: 0 } ); const handleMouseMove = ( event ) => { setCursorPosition( { x: event.pageX, y: event.pageY + 8 } ); }; const data = { ...baseData, labels: props.dataPoints.map( ( point ) => point.label ), // labels: props.dataPoints.map((point) => point.label), }; data.datasets[ 0 ].data = props.dataPoints.map( ( point ) => point.value ); // data.datasets[0].label = props.metric; data.datasets[ 0 ].backgroundColor = props.dataPoints.map( ( point ) => point.color ); return ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions