Skip to content

hooks/useNearViewport

import { … } from 'zidane-ui'ui/src/hooks/useNearViewport.ts

Functions#

scrollRootOfFunction#

The nearest scrolling ancestor. Observers must use it as their root: with the window as root, a scroll container clips its content before the margin applies, so a margin never reaches past the container's edges and "near" would only mean "already on screen". Cached by parent, so rows of one list resolve it once.

A container marked data-scroll-root is found by a DOM walk alone. Its unmarked ancestors are read with getComputedStyle, which in a mount effect restyles everything mounting with the element: a conversation opening with a few code blocks paid for its whole style recalculation in that frame. A scroller nested inside a marked one is a root only if it is marked too.

TypeScript
function scrollRootOf(el: Element): Element | null
Parameters
NameTypeDescription
elElement

The element to start from.

Element | null

The nearest ancestor with overflow-y of auto or scroll, or null when the window scrolls.

ui/src/hooks/useNearViewport.ts:40

useNearViewportFunction#

Reports whether an element has come within margin of the viewport. It turns true once and stays true, so it suits lazy work such as highlighting code that scrolls into reach. Without IntersectionObserver it is true at once.

TypeScript
function useNearViewport(ref: RefObject<Element | null>, margin?: string): boolean
Parameters
NameTypeDefaultDescription
refRefObject<Element | null>

Ref to the element to watch.

margin?string'600px 0px'

How far outside the viewport counts as near, as a CSS margin string. Defaults to '600px 0px'.

boolean

Whether the element has been near the viewport.

ui/src/hooks/useNearViewport.ts:91