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

Function scrollIntoView

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

Source from the content-addressed store, hash-verified

242}
243
244function scrollIntoView(target: Element) {
245 let root = document.scrollingElement || document.documentElement;
246 let nextTarget: Element | null = target;
247 while (nextTarget && nextTarget !== root) {
248 // Find the parent scrollable element and adjust the scroll position if the target is not already in view.
249 let scrollable = getScrollParent(nextTarget);
250 if (
251 scrollable !== document.documentElement &&
252 scrollable !== document.body &&
253 scrollable !== nextTarget
254 ) {
255 let scrollableRect = scrollable.getBoundingClientRect();
256 let targetRect = nextTarget.getBoundingClientRect();
257 if (
258 targetRect.top < scrollableRect.top ||
259 targetRect.bottom > scrollableRect.top + nextTarget.clientHeight
260 ) {
261 let bottom = scrollableRect.bottom;
262 if (visualViewport) {
263 bottom = Math.min(bottom, visualViewport.offsetTop + visualViewport.height);
264 }
265
266 // Center within the viewport.
267 let adjustment =
268 targetRect.top -
269 scrollableRect.top -
270 ((bottom - scrollableRect.top) / 2 - targetRect.height / 2);
271 scrollable.scrollTo({
272 // Clamp to the valid range to prevent over-scrolling.
273 top: Math.max(
274 0,
275 Math.min(
276 scrollable.scrollHeight - scrollable.clientHeight,
277 scrollable.scrollTop + adjustment
278 )
279 ),
280 behavior: 'smooth'
281 });
282 }
283 }
284
285 nextTarget = scrollable.parentElement;
286 }
287}

Callers 1

scrollIntoViewWhenReadyFunction · 0.70

Calls 1

getScrollParentFunction · 0.90

Tested by

no test coverage detected