| 1 | export function observeScrollContentSize(element: HTMLElement, onChange: () => void): () => void { |
| 2 | if (typeof ResizeObserver === "undefined") return () => {}; |
| 3 | |
| 4 | const observed = new Set<Element>(); |
| 5 | const resizeObserver = new ResizeObserver(onChange); |
| 6 | const syncChildren = () => { |
| 7 | const current = new Set(Array.from(element.children)); |
| 8 | for (const child of observed) { |
| 9 | if (current.has(child)) continue; |
| 10 | resizeObserver.unobserve(child); |
| 11 | observed.delete(child); |
| 12 | } |
| 13 | for (const child of current) { |
| 14 | if (observed.has(child)) continue; |
| 15 | resizeObserver.observe(child); |
| 16 | observed.add(child); |
| 17 | } |
| 18 | }; |
| 19 | |
| 20 | syncChildren(); |
| 21 | const mutationObserver = typeof MutationObserver === "undefined" |
| 22 | ? null |
| 23 | : new MutationObserver(() => { |
| 24 | syncChildren(); |
| 25 | onChange(); |
| 26 | }); |
| 27 | mutationObserver?.observe(element, { childList: true }); |
| 28 | |
| 29 | return () => { |
| 30 | mutationObserver?.disconnect(); |
| 31 | resizeObserver.disconnect(); |
| 32 | observed.clear(); |
| 33 | }; |
| 34 | } |
| 35 |