38 lines
1.7 KiB
TypeScript
38 lines
1.7 KiB
TypeScript
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<typeof ReactECharts>["option"];
|
|
height: number | "100%";
|
|
onPointSelect: (index: number) => void;
|
|
}) {
|
|
const host = useRef<HTMLDivElement>(null);
|
|
const chart = useRef<ReactECharts>(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 <div ref={host} style={{ height }}>
|
|
<ReactECharts ref={chart} option={option} opts={{ renderer: "svg" }} notMerge autoResize={false}
|
|
style={{ height: "100%" }} onChartReady={(instance) => {
|
|
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);
|
|
} }} />
|
|
</div>;
|
|
}
|