@awsui/components-react
Version:
AWS UI is a collection of [React](https://reactjs.org/) components that help create intuitive, responsive, and accessible user experiences for web applications. It is developed by Amazon Web Services (AWS). This work is available under the terms of the [A
52 lines (51 loc) • 2.28 kB
JavaScript
import { useState, useLayoutEffect, useCallback, useEffect } from 'react';
import { useAppLayoutContext } from '../internal/context/app-layout-context';
import { useMobile } from '../internal/hooks/use-mobile';
import { supportsStickyPosition } from '../internal/utils/dom';
import { getOverflowParents } from '../internal/utils/scrollable-containers';
import styles from './styles.css.js';
export var CONTAINER_ROOT_BORDER = 1;
export var useStickyHeader = function (rootRef, headerRef, __stickyHeader, __stickyOffset) {
var _a = useState(false), usesBodyScroll = _a[0], setState = _a[1];
useLayoutEffect(function () {
var overflowParents = rootRef.current && getOverflowParents(rootRef.current).length;
setState(!overflowParents);
}, [rootRef]);
var stickyOffsetTop = useAppLayoutContext().stickyOffsetTop;
var isMobile = useMobile();
__stickyOffset = __stickyOffset || (usesBodyScroll ? stickyOffsetTop : undefined);
var isSticky = supportsStickyPosition() && !isMobile && __stickyHeader;
var stickyStyles = isSticky && __stickyOffset !== undefined
? {
style: {
top: __stickyOffset - CONTAINER_ROOT_BORDER + "px"
}
}
: {};
var checkIfStuck = useCallback(function () {
if (rootRef.current && headerRef.current) {
var rootTop = rootRef.current.getBoundingClientRect().top;
var headerTop = headerRef.current.getBoundingClientRect().top;
if (rootTop + CONTAINER_ROOT_BORDER < headerTop) {
headerRef.current.classList.add(styles['header-stuck']);
}
else {
headerRef.current.classList.remove(styles['header-stuck']);
}
}
}, [rootRef, headerRef]);
useEffect(function () {
if (isSticky) {
window.addEventListener('scroll', checkIfStuck, true);
window.addEventListener('resize', checkIfStuck);
return function () {
window.removeEventListener('scroll', checkIfStuck, true);
window.removeEventListener('resize', checkIfStuck);
};
}
}, [isSticky, checkIfStuck]);
return {
isSticky: isSticky,
stickyStyles: stickyStyles
};
};