Skip to content

Commit

Permalink
DOM: Update getScrollContainer to be aware of horizontal scroll (#49787)
Browse files Browse the repository at this point in the history
* DOM: Update getScrollContainer to be aware of horizontal scroll

* Update to add a direction param
  • Loading branch information
andrewserong authored Apr 16, 2023
1 parent 9fd9dad commit e798d9b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
1 change: 1 addition & 0 deletions packages/dom/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ Given a DOM node, finds the closest scrollable container node or the node itself
_Parameters_

- _node_ `Element | null`: Node from which to start.
- _direction_ `?string`: Direction of scrollable container to search for ('vertical', 'horizontal', 'all'). Defaults to 'vertical'.

_Returns_

Expand Down
38 changes: 28 additions & 10 deletions packages/dom/src/dom/get-scroll-container.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,37 @@ import getComputedStyle from './get-computed-style';
* Given a DOM node, finds the closest scrollable container node or the node
* itself, if scrollable.
*
* @param {Element | null} node Node from which to start.
*
* @param {Element | null} node Node from which to start.
* @param {?string} direction Direction of scrollable container to search for ('vertical', 'horizontal', 'all').
* Defaults to 'vertical'.
* @return {Element | undefined} Scrollable container node, if found.
*/
export default function getScrollContainer( node ) {
export default function getScrollContainer( node, direction = 'vertical' ) {
if ( ! node ) {
return undefined;
}

// Scrollable if scrollable height exceeds displayed...
if ( node.scrollHeight > node.clientHeight ) {
// ...except when overflow is defined to be hidden or visible
const { overflowY } = getComputedStyle( node );
if ( direction === 'vertical' || direction === 'all' ) {
// Scrollable if scrollable height exceeds displayed...
if ( node.scrollHeight > node.clientHeight ) {
// ...except when overflow is defined to be hidden or visible
const { overflowY } = getComputedStyle( node );

if ( /(auto|scroll)/.test( overflowY ) ) {
return node;
}
}
}

if ( direction === 'horizontal' || direction === 'all' ) {
// Scrollable if scrollable width exceeds displayed...
if ( node.scrollWidth > node.clientWidth ) {
// ...except when overflow is defined to be hidden or visible
const { overflowX } = getComputedStyle( node );

if ( /(auto|scroll)/.test( overflowY ) ) {
return node;
if ( /(auto|scroll)/.test( overflowX ) ) {
return node;
}
}
}

Expand All @@ -31,5 +46,8 @@ export default function getScrollContainer( node ) {
}

// Continue traversing.
return getScrollContainer( /** @type {Element} */ ( node.parentNode ) );
return getScrollContainer(
/** @type {Element} */ ( node.parentNode ),
direction
);
}

0 comments on commit e798d9b

Please sign in to comment.