Skip to content

Commit

Permalink
[docs] Fix side nav scroll position (#25619)
Browse files Browse the repository at this point in the history
  • Loading branch information
misaka3 committed Apr 4, 2021
1 parent 29934af commit ff2b314
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions docs/src/modules/components/AppNavDrawer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,40 +16,40 @@ import { pageToTitleI18n } from 'docs/src/modules/utils/helpers';
import PageContext from 'docs/src/modules/components/PageContext';
import { useUserLanguage, useTranslate } from 'docs/src/modules/utils/i18n';

let savedScrollTop = null;
const savedScrollTop = {};

function PersistScroll(props) {
const { children, enabled } = props;
const { slot, children, enabled } = props;
const rootRef = React.useRef();

React.useEffect(() => {
React.useLayoutEffect(() => {
const parent = rootRef.current ? rootRef.current.parentElement : null;
const activeElement = parent.querySelector('.app-drawer-active');

if (!enabled || !parent || !activeElement || !activeElement.scrollIntoView) {
return undefined;
}

parent.scrollTop = savedScrollTop[slot];

const activeBox = activeElement.getBoundingClientRect();

if (savedScrollTop === null || activeBox.top - savedScrollTop < 0) {
// Center the selected item in the list container.
activeElement.scrollIntoView();
} else {
parent.scrollTop = savedScrollTop;
if (activeBox.top < 0 || activeBox.top > window.innerHeight) {
parent.scrollTop += activeBox.top - 8 - 32;
}

return () => {
savedScrollTop = parent.scrollTop;
savedScrollTop[slot] = parent.scrollTop;
};
}, [enabled]);
}, [enabled, slot]);

return <div ref={rootRef}>{children}</div>;
}

PersistScroll.propTypes = {
children: PropTypes.node,
enabled: PropTypes.bool,
children: PropTypes.node.isRequired,
enabled: PropTypes.bool.isRequired,
slot: PropTypes.string.isRequired,
};

const styles = (theme) => ({
Expand Down Expand Up @@ -200,10 +200,12 @@ function AppNavDrawer(props) {
keepMounted: true,
}}
>
{drawer}
<PersistScroll slot="swipeable" enabled={mobileOpen}>
{drawer}
</PersistScroll>
</SwipeableDrawer>
) : null}
{disablePermanent ? null : (
{disablePermanent || mobile ? null : (
<Hidden lgDown implementation="css">
<Drawer
classes={{
Expand All @@ -212,7 +214,9 @@ function AppNavDrawer(props) {
variant="permanent"
open
>
<PersistScroll enabled={!mobile}>{drawer}</PersistScroll>
<PersistScroll slot="side" enabled>
{drawer}
</PersistScroll>
</Drawer>
</Hidden>
)}
Expand Down

0 comments on commit ff2b314

Please sign in to comment.