|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +/** |
| 5 | + * Polyfill for `element.scrollIntoView({ container: "nearest", scrollMode: "..." })` |
| 6 | + * For ease of implementation, behaves like `{ block: "center" }` is provided. |
| 7 | + * |
| 8 | + * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView (for `container`) |
| 9 | + * @see https://caniuse.com/wf-scroll-into-view-container (for `container` browser support) |
| 10 | + * @see https://github.com/w3c/csswg-drafts/pull/5677 (for discussion of `if-needed`) |
| 11 | + */ |
| 12 | +export function scrollIntoViewNearestContainer( |
| 13 | + element: HTMLElement, |
| 14 | + options?: ScrollOptions & { scrollMode?: "always" | "if-needed" }, |
| 15 | +) { |
| 16 | + // Scroll methods (scrollTo, scrollIntoView, etc) are not supported in test environments like JSDOM. |
| 17 | + if (!("scrollTo" in element)) { |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + // Get element boundaries to measure scroll offsets. |
| 22 | + // In the future, could be replaced with a simple `element.scrollParent`. |
| 23 | + // https://drafts.csswg.org/cssom-view/#dom-htmlelement-scrollparent |
| 24 | + const scrollParent = getScrollParent(element) ?? element.ownerDocument.documentElement; |
| 25 | + const { top: elementTop, bottom: elementBottom, height: elementHeight } = element.getBoundingClientRect(); |
| 26 | + const { top: scrollTop, bottom: scrollBottom, height: scrollHeight } = scrollParent.getBoundingClientRect(); |
| 27 | + |
| 28 | + if (options?.scrollMode === "if-needed") { |
| 29 | + // Technically, getBoundingClientRect() returns the border-box, which includes the border width. |
| 30 | + // We should subtract the border width to get the padding box, but all that computation isn't worth it. |
| 31 | + const isNeeded = elementTop < scrollTop || elementBottom > scrollBottom; |
| 32 | + if (!isNeeded) { |
| 33 | + return; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + const topRelativeToParent = elementTop + scrollParent.scrollTop - scrollTop; |
| 38 | + const blockCenterOffset = scrollHeight / 2 - elementHeight / 2; |
| 39 | + scrollParent.scrollTo({ top: topRelativeToParent - blockCenterOffset, ...options }); |
| 40 | +} |
| 41 | + |
| 42 | +function getScrollParent(element: HTMLElement): HTMLElement | null { |
| 43 | + for ( |
| 44 | + let node: HTMLElement | null = element.parentElement; |
| 45 | + node !== null && node !== element.ownerDocument.body; |
| 46 | + node = node.parentElement |
| 47 | + ) { |
| 48 | + const overflow = getComputedStyle(node).overflow; |
| 49 | + if (overflow !== "visible" && overflow !== "hidden") { |
| 50 | + return node; |
| 51 | + } |
| 52 | + } |
| 53 | + return null; |
| 54 | +} |
0 commit comments