Skip to content

Commit ff2b314

Browse files
authored
[docs] Fix side nav scroll position (mui#25619)
1 parent 29934af commit ff2b314

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

docs/src/modules/components/AppNavDrawer.js

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,40 +16,40 @@ import { pageToTitleI18n } from 'docs/src/modules/utils/helpers';
1616
import PageContext from 'docs/src/modules/components/PageContext';
1717
import { useUserLanguage, useTranslate } from 'docs/src/modules/utils/i18n';
1818

19-
let savedScrollTop = null;
19+
const savedScrollTop = {};
2020

2121
function PersistScroll(props) {
22-
const { children, enabled } = props;
22+
const { slot, children, enabled } = props;
2323
const rootRef = React.useRef();
2424

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

2929
if (!enabled || !parent || !activeElement || !activeElement.scrollIntoView) {
3030
return undefined;
3131
}
3232

33+
parent.scrollTop = savedScrollTop[slot];
34+
3335
const activeBox = activeElement.getBoundingClientRect();
3436

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

4241
return () => {
43-
savedScrollTop = parent.scrollTop;
42+
savedScrollTop[slot] = parent.scrollTop;
4443
};
45-
}, [enabled]);
44+
}, [enabled, slot]);
4645

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

5049
PersistScroll.propTypes = {
51-
children: PropTypes.node,
52-
enabled: PropTypes.bool,
50+
children: PropTypes.node.isRequired,
51+
enabled: PropTypes.bool.isRequired,
52+
slot: PropTypes.string.isRequired,
5353
};
5454

5555
const styles = (theme) => ({
@@ -200,10 +200,12 @@ function AppNavDrawer(props) {
200200
keepMounted: true,
201201
}}
202202
>
203-
{drawer}
203+
<PersistScroll slot="swipeable" enabled={mobileOpen}>
204+
{drawer}
205+
</PersistScroll>
204206
</SwipeableDrawer>
205207
) : null}
206-
{disablePermanent ? null : (
208+
{disablePermanent || mobile ? null : (
207209
<Hidden lgDown implementation="css">
208210
<Drawer
209211
classes={{
@@ -212,7 +214,9 @@ function AppNavDrawer(props) {
212214
variant="permanent"
213215
open
214216
>
215-
<PersistScroll enabled={!mobile}>{drawer}</PersistScroll>
217+
<PersistScroll slot="side" enabled>
218+
{drawer}
219+
</PersistScroll>
216220
</Drawer>
217221
</Hidden>
218222
)}

0 commit comments

Comments
 (0)