import React , { useEffect , useRef } from 'react' ; import * as d3 from 'd3' ; import { dataDurationArr } from '../../../types' ; interface RankedGraphProps { data : dataDurationArr ; width ? : number ; height ? : number ; } const RankedGraph = ( { data , width , height , } ) => { const svgRef = useRef ( ) ; useEffect ( ( ) => { document . getElementById ( 'canvas' ) . innerHTML = '' ; let left = 80 ; if ( length > 13 ) { left = 100 ; } if ( length > 17 ) { left = 120 ; } const margin = { top : 20 , right : 20 , bottom : 30 , left } ; const y = d3 . scaleBand ( ) . range ( [ height , 0 ] ) . padding ( 0.2 ) ; const x = d3 . scaleLinear ( ) . range ( [ 0 , width * 0.8 ] ) ; const z = d3 . scaleBand ( ) . range ( [ height , 0 ] ) . padding ( 0.2 ) ; function colorPicker ( data ) { if ( data <= 1 ) return '#51a8f0' ; else if ( data <= 2 ) return '#3a7bb0' ; else return '#2d608a' ; } const svg = d3 . select ( svgRef . current ) . classed ( 'svg-container' , true ) . append ( 'svg' ) . attr ( 'class' , 'chart' ) . attr ( 'viewBox' , '0 0 600 490' ) . attr ( 'preserveAspectRatio' , 'xMinYMin meet' ) . classed ( 'svg-content-responsive' , true ) . call ( d3 . zoom ( ) . on ( 'zoom' , function ( ) { svg . attr ( 'transform' , d3 . event . transform ) ; } ) ) . append ( 'g' ) . attr ( 'transform' , 'translate(' + margin . left + ',' + margin . top + ')' ) ; x . domain ( [ 0 , d3 . max ( data , ( d ) => { return d . actualDuration ; } ) , ] ) ; y . domain ( data . map ( ( d , i ) => { return d . name + '-' + i ; } ) ) ; z . domain ( data . map ( ( d , i ) => { return d . actualDuration . toFixed ( 2 ) + 'ms' + '-' + i ; } ) ) ; svg . selectAll ( '.bar' ) . data ( data ) . enter ( ) . append ( 'rect' ) . attr ( 'class' , 'bar' ) . on ( 'mouseover' , function ( ) { d3 . select ( this ) . attr ( 'opacity' , '0.85' ) ; const backgroundConnection = chrome . runtime . connect ( ) ; const barName = this . data ; const payload = { action : 'mouseover' , tabId : chrome . devtools . inspectedWindow . tabId , payload : barName , } ; backgroundConnection . postMessage ( payload ) ; } ) . attr ( 'width' , function ( d ) { return x ( d . actualDuration ) ; } ) . attr ( 'fill' , function ( d ) { return colorPicker ( d . actualDuration ) ; } ) . attr ( 'y' , function ( d , i ) { return y ( d . name + '-' + i ) ; } ) . attr ( 'height' , y . bandwidth ( ) ) ; svg . append ( 'g' ) . attr ( 'transform' , 'translate(0,' + height + ')' ) . call ( d3 . axisBottom ( x ) ) ; const yAxis = d3 . axisLeft ( y ) . tickFormat ( function ( d ) { return d . split ( '-' ) [ 0 ] ; } ) ; yAxis ( svg . append ( 'g' ) ) ; const zAxis = d3 . axisRight ( z ) . tickFormat ( function ( d ) { return d . split ( '-' ) [ 0 ] ; } ) ; zAxis ( svg . append ( 'g' ) ) ; } , [ data ] ) ; return ( < div data - testid = "canvas" id = "stateGraphContainer" > < svg id = "canvas" ref = { svgRef } > < /svg> < /div>); } ; export default RankedGraph ;