11import { PlotsSection } from 'dvc/src/plots/webview/contract'
2- import { RefObject , useCallback , useEffect , useState } from 'react'
2+ import { RefObject , useEffect , useState } from 'react'
33import { useSelector } from 'react-redux'
44import { VisualizationSpec } from 'react-vega'
55import { plotDataStore } from '../components/plotDataStore'
@@ -9,49 +9,49 @@ import { fillTemplate } from '../components/vegaLite/util'
99export const useGetPlot = (
1010 section : PlotsSection ,
1111 id : string ,
12- plotRef : RefObject < HTMLButtonElement | HTMLDivElement >
12+ plotRef : RefObject < HTMLButtonElement | HTMLDivElement > ,
13+ plotFocused : boolean
14+ // eslint-disable-next-line sonarjs/cognitive-complexity
1315) : VisualizationSpec | undefined => {
1416 const storeSection =
1517 section === PlotsSection . TEMPLATE_PLOTS ? 'template' : 'custom'
16- const {
17- plotsSnapshots : snapshot ,
18- nbItemsPerRow,
19- height : itemHeight
20- } = useSelector ( ( state : PlotsState ) => state [ storeSection ] )
18+ const { plotsSnapshots } = useSelector (
19+ ( state : PlotsState ) => state [ storeSection ]
20+ )
2121
2222 const [ spec , setSpec ] = useState < VisualizationSpec | undefined > ( )
2323
2424 const [ height , setHeight ] = useState ( 0 )
2525 const [ width , setWidth ] = useState ( 0 )
2626
27- const setPlotData = useCallback ( ( ) => {
28- const plot = plotDataStore [ section ] [ id ]
29-
30- const spec = fillTemplate ( plot , width , height , false )
31- if ( ! spec ) {
32- return
33- }
34- setSpec ( spec )
35- } , [ section , id , width , height ] )
36-
3727 useEffect ( ( ) => {
38- const onResize = ( ) => {
28+ const resizeObserver = new ResizeObserver ( ( ) => {
3929 if ( ! plotRef . current ) {
4030 return
4131 }
4232 const { height, width } = plotRef . current . getBoundingClientRect ( )
4333 setHeight ( height )
4434 setWidth ( width )
45- }
46- window . addEventListener ( 'resize' , onResize )
35+ } )
4736
48- onResize ( )
37+ if ( plotRef . current ) {
38+ resizeObserver . observe ( plotRef . current )
39+ }
4940
50- setPlotData ( )
5141 return ( ) => {
52- window . removeEventListener ( 'resize' , onResize )
42+ resizeObserver . disconnect ( )
5343 }
54- } , [ snapshot , setPlotData , plotRef , nbItemsPerRow , itemHeight ] )
44+ } , [ plotRef ] )
45+
46+ useEffect ( ( ) => {
47+ const plot = plotDataStore [ section ] [ id ]
48+
49+ const spec = fillTemplate ( plot , width , height , plotFocused )
50+ if ( ! spec ) {
51+ return
52+ }
53+ setSpec ( spec )
54+ } , [ height , id , plotFocused , plotsSnapshots , section , width ] )
5555
5656 return spec
5757}
0 commit comments