Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs] Fix side nav scroll position #25619

Merged
merged 2 commits into from
Apr 4, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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