| 1 | import { useLayoutEffect, useRef, useState } from "react" |
| 2 | |
| 3 | export type Dimensions |
| 4 | |
| 5 | /** |
| 6 | * Tracks an element's CSS pixel size via {@link |
| 7 | * `clientWidth`/`clientHeight` (the layout size) rather than |
| 8 | * `getBoundingClientRect()` so a parent `layoutId` morph - which scales the |
| 9 | * element via a transform - can't trick the chart into measuring a scaled size |
| 10 | * and locking its canvas to it. |
| 11 | */ |
| 12 | export function useChartDimensions<T |
| 13 | const ref = |
| 14 | const [size, |
| 15 | |
| 16 | useLayoutEffect(() => |
| 17 | const el = |
| 18 | if (!el) |
| 19 | |
| 20 | const measure = |
| 21 | const width = |
| 22 | const height = |
| 23 | setSize((prev) |
| 24 | prev.width === |
| 25 | ? prev // guard against repeat fires |
| 26 | : { width, |
| 27 | ) |
| 28 | } |
| 29 | |
| 30 | const ro = |
| 31 | ro.observe(el |
| 32 | measure() |
| 33 | return () => |
| 34 | }, []) |
| 35 | |
| 36 | return { ref, |
| 37 | } |