11import { VegaLite } from "react-vega" ;
22import type { TopLevelSpec } from "vega-lite" ;
33
4- import type { ComponentState , ComponentProps } from "@/index" ;
4+ import type { ComponentProps , ComponentState } from "@/index" ;
55import { useSignalListeners } from "./hooks/useSignalListeners" ;
66import { useVegaTheme , type VegaTheme } from "./hooks/useVegaTheme" ;
7+ import { useCallback , useRef , useState } from "react" ;
78
89interface VegaChartState extends ComponentState {
910 theme ?: VegaTheme | "default" | "system" ;
@@ -24,17 +25,38 @@ export function VegaChart({
2425} : VegaChartProps ) {
2526 const signalListeners = useSignalListeners ( chart , type , id , onChange ) ;
2627 const vegaTheme = useVegaTheme ( theme ) ;
28+ const containerRef = useRef < ResizeObserver | null > ( null ) ;
29+ const [ containerSizeKey , setContainerSizeKey ] = useState ( 0 ) ;
30+ const containerCallbackRef = useCallback ( ( node : Element | null ) => {
31+ if ( containerRef . current ) {
32+ containerRef . current . disconnect ( ) ;
33+ containerRef . current = null ;
34+ }
35+ if ( node !== null ) {
36+ const resizeObserver = new ResizeObserver ( ( _entries ) => {
37+ // We only need to know that a resize happened because it triggers a
38+ // re-render allowing vega to get the latest layout.
39+ setContainerSizeKey ( Date . now ( ) ) ;
40+ } ) ;
41+
42+ resizeObserver . observe ( node ) ;
43+ containerRef . current = resizeObserver ;
44+ }
45+ } , [ ] ) ;
2746 if ( chart ) {
2847 return (
29- < VegaLite
30- theme = { vegaTheme }
31- spec = { chart }
32- style = { style }
33- signalListeners = { signalListeners }
34- actions = { false }
35- />
48+ < div id = "chart-container" ref = { containerCallbackRef } style = { style } >
49+ < VegaLite
50+ key = { containerSizeKey }
51+ theme = { vegaTheme }
52+ spec = { chart }
53+ style = { style }
54+ signalListeners = { signalListeners }
55+ actions = { false }
56+ />
57+ </ div >
3658 ) ;
3759 } else {
38- return < div id = { id } style = { style } /> ;
60+ return < div id = { id } /> ;
3961 }
4062}
0 commit comments