* Observe this elements position. * @param el - The element to observe the position of.
(el: Element)
| 143 | * @param el - The element to observe the position of. |
| 144 | */ |
| 145 | function observePosition(el: Element) { |
| 146 | const oldObserver = intersections.get(el) |
| 147 | oldObserver?.disconnect() |
| 148 | let rect = coords.get(el) |
| 149 | let invocations = 0 |
| 150 | const buffer = 5 |
| 151 | if (!rect) { |
| 152 | rect = getCoords(el) |
| 153 | coords.set(el, rect) |
| 154 | } |
| 155 | const { offsetWidth, offsetHeight } = root |
| 156 | const rootMargins = [ |
| 157 | rect.top - buffer, |
| 158 | offsetWidth - (rect.left + buffer + rect.width), |
| 159 | offsetHeight - (rect.top + buffer + rect.height), |
| 160 | rect.left - buffer, |
| 161 | ] |
| 162 | const rootMargin = rootMargins |
| 163 | .map((px) => `${-1 * Math.floor(px)}px`) |
| 164 | .join(" ") |
| 165 | const observer = new IntersectionObserver( |
| 166 | () => { |
| 167 | ++invocations > 1 && updatePos(el) |
| 168 | }, |
| 169 | { |
| 170 | root, |
| 171 | threshold: 1, |
| 172 | rootMargin, |
| 173 | }, |
| 174 | ) |
| 175 | observer.observe(el) |
| 176 | intersections.set(el, observer) |
| 177 | } |
| 178 | |
| 179 | /** |
| 180 | * Update the exact position of a given element. |