How Floating UI Measures, Positions, and Keeps Popovers Alive
Every dropdown, tooltip, and popover that escapes a scroll container or clipping parent needs a positioning update strategy. The IntersectionObserver framing trick replaces expensive `getBoundingClientRect` polling with a passive, main-thread-friendly detection mechanism that catches layout shifts most developers don't monitor.
Floating UI's positioning layer runs a middleware pipeline: `computePosition` calculates the floating element's top-left corner relative to a reference, then `offset`, `flip`, `shift`, and `arrow` middleware adjust for spacing, edge avoidance, and arrow placement. The `detectOverflow` function compares the floating rectangle against the intersection of all clipping ancestors plus the viewport, returning overflow amounts that drive flip and shift decisions. A reference can be any object with a `getBoundingClientRect` method — DOM elements, virtual elements representing a caret position, or mouse coordinates.
The `autoUpdate` system handles four categories of position invalidation. Scroll and resize events are straightforward listeners. Layout shifts — where an element moves without scrolling or resizing — are detected by framing an `IntersectionObserver` with negative `rootMargin` values that shrink the observation box to exactly match the reference's current rectangle; any movement drops the intersection ratio below 1 and triggers recalculation. CSS transform animations slip past all three, so an optional rAF per-frame rectangle comparison catches them at higher cost.
A practical Select implementation attaches the dropdown to `body` to escape parent `overflow: hidden` and `z-index` traps, then relies on `autoUpdate` because the reference scrolls inside a local container while the floating element stays fixed on `body`. A Mention component measures the caret position by mirroring input text into a hidden span with identical font properties, producing a virtual element that `computePosition` treats like any other reference.
The negative rootMargin IntersectionObserver trick is a general-purpose technique for detecting element movement without polling getBoundingClientRect — applicable anywhere a DOM node's viewport-relative position needs monitoring.
Floating UI's design separates the measurement strategy from the positioning algorithm: the core works on any platform that can supply rectangles, while autoUpdate is DOM-specific and optimizes for browser event sources.
The four autoUpdate paths form a hierarchy of cost: scroll/resize listeners are cheapest, IntersectionObserver is mid-cost and passive, and rAF polling is most expensive and opt-in — a deliberate tradeoff that avoids burning frames on static UIs.
Attaching popovers to body solves clipping but creates a coordination problem that most hand-rolled implementations ignore until QA finds the dropdown drifting on scroll.