| 60 | } |
| 61 | |
| 62 | export const observeElementRect = <T extends Element>( |
| 63 | instance: Virtualizer<T, any>, |
| 64 | cb: (rect: Rect) => void, |
| 65 | ) => { |
| 66 | const element = instance.scrollElement |
| 67 | if (!element) { |
| 68 | return |
| 69 | } |
| 70 | const targetWindow = instance.targetWindow |
| 71 | if (!targetWindow) { |
| 72 | return |
| 73 | } |
| 74 | |
| 75 | const handler = (rect: Rect) => { |
| 76 | const { width, height } = rect |
| 77 | cb({ width: Math.round(width), height: Math.round(height) }) |
| 78 | } |
| 79 | |
| 80 | handler(element.getBoundingClientRect()) |
| 81 | |
| 82 | if (!targetWindow.ResizeObserver) { |
| 83 | return () => {} |
| 84 | } |
| 85 | |
| 86 | const observer = new targetWindow.ResizeObserver((entries) => { |
| 87 | const run = () => { |
| 88 | const entry = entries[0] |
| 89 | if (entry?.borderBoxSize) { |
| 90 | const box = entry.borderBoxSize[0] |
| 91 | if (box) { |
| 92 | handler({ width: box.inlineSize, height: box.blockSize }) |
| 93 | return |
| 94 | } |
| 95 | } |
| 96 | handler(element.getBoundingClientRect()) |
| 97 | } |
| 98 | |
| 99 | instance.options.useAnimationFrameWithResizeObserver |
| 100 | ? requestAnimationFrame(run) |
| 101 | : run() |
| 102 | }) |
| 103 | |
| 104 | observer.observe(element, { box: 'border-box' }) |
| 105 | |
| 106 | return () => { |
| 107 | observer.unobserve(element) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | const addEventListenerOptions = { |
| 112 | passive: true, |