import { useLayoutEffect, useRef, type ComponentProps } from "react"; import ReactECharts from "echarts-for-react"; /** Resize the existing drawing at most once per frame without replacing its options. */ export function ResponsiveChart({ option, height, onPointSelect }: { option: ComponentProps["option"]; height: number | "100%"; onPointSelect: (index: number) => void; }) { const host = useRef(null); const chart = useRef(null); const ready = useRef(false); useLayoutEffect(() => { const element = host.current; if (!element || typeof ResizeObserver === "undefined") return; let frame = 0; const observer = new ResizeObserver(() => { cancelAnimationFrame(frame); frame = requestAnimationFrame(() => { if (!ready.current || !element.clientWidth || !element.clientHeight) return; chart.current?.getEchartsInstance().resize({ width: "auto", height: "auto", animation: { duration: 0 } }); }); }); observer.observe(element); return () => { cancelAnimationFrame(frame); observer.disconnect(); }; }, []); return
{ ready.current = true; instance.resize({ width: "auto", height: "auto", animation: { duration: 0 } }); }} onEvents={{ click: (event: { componentType?: string; dataIndex?: number }) => { if (event.componentType === "series" && typeof event.dataIndex === "number") onPointSelect(event.dataIndex); } }} />
; }