MCPcopy Create free account
hub / github.com/adobe/react-spectrum / scrollIntoView

Function scrollIntoView

packages/react-aria/src/overlays/usePreventScroll.ts:261–304  ·  view source on GitHub ↗
(target: Element)

Source from the content-addressed store, hash-verified

259}
260
261function scrollIntoView(target: Element) {
262 let root = document.scrollingElement || document.documentElement;
263 let nextTarget: Element | null = target;
264 while (nextTarget && nextTarget !== root) {
265 // Find the parent scrollable element and adjust the scroll position if the target is not already in view.
266 let scrollable = getScrollParent(nextTarget);
267 if (
268 scrollable !== document.documentElement &&
269 scrollable !== document.body &&
270 scrollable !== nextTarget
271 ) {
272 let scrollableRect = scrollable.getBoundingClientRect();
273 let targetRect = nextTarget.getBoundingClientRect();
274 if (
275 targetRect.top < scrollableRect.top ||
276 targetRect.bottom > scrollableRect.top + nextTarget.clientHeight
277 ) {
278 let bottom = scrollableRect.bottom;
279 if (visualViewport) {
280 bottom = Math.min(bottom, visualViewport.offsetTop + visualViewport.height);
281 }
282
283 // Center within the viewport.
284 let adjustment =
285 targetRect.top -
286 scrollableRect.top -
287 ((bottom - scrollableRect.top) / 2 - targetRect.height / 2);
288 scrollable.scrollTo({
289 // Clamp to the valid range to prevent over-scrolling.
290 top: Math.max(
291 0,
292 Math.min(
293 scrollable.scrollHeight - scrollable.clientHeight,
294 scrollable.scrollTop + adjustment
295 )
296 ),
297 behavior: 'smooth'
298 });
299 }
300 }
301
302 nextTarget = scrollable.parentElement;
303 }
304}

Callers 1

scrollIntoViewWhenReadyFunction · 0.70

Calls 1

getScrollParentFunction · 0.90

Tested by

no test coverage detected