Sidebar scroll position resets on navigation, active item can be off-screen
还没有人认领这个 Issue。
- 主要语言
- TypeScript
- 星标
- 6.9k
- 派生
- 6.5k
- 平均合并
- 2 天 8 小时
- 30 天内合并 PR
- 29
描述
I couldn't push my own branch to make a PR so sharing this as issue instead. The fix belongs in components/Sidebar/index.jsx.
Problem
Clicking an item in the left sidebar causes a full page reload because navigation uses window.location.href in components/Sidebar/index.jsx. After the reload, the sidebar’s internal scroll position resets to the top.
As a result, when a user clicks a page located lower in the sidebar list, such as an item under TypeScript or Diagnostics, the selected item may still be active but no longer visible. The user then has to scroll through the sidebar again to find their current location.
Reproduction steps
- Open https://nodejs.org/learn
- Scroll the left sidebar to a lower item, for example Diagnostics → Memory
- Click the item
- After the page reloads, the sidebar scroll position has returned to the top, and the active item is off-screen
Expected behavior
The active sidebar item should remain visible after navigation.
Proposed fix
When the sidebar mounts, locate the active link inside the sidebar <aside>.
If that link is outside the visible portion of the sidebar’s own scroll container, adjust aside.scrollTop so the active item is centered in view. This only affects the sidebar’s internal scroll position and does not change the main window scroll.
Example approach
useEffect(() => {
const aside = asideRef.current;
const active = aside?.querySelector(`a[href="${CSS.escape(pathname)}"]`);
if (!aside || !active) return;
const offsetTop =
active.getBoundingClientRect().top -
aside.getBoundingClientRect().top +
aside.scrollTop;
const viewTop = aside.scrollTop;
const viewBottom = viewTop + aside.clientHeight;
if (offsetTop >= viewTop && offsetTop + active.offsetHeight <= viewBottom) {
return;
}
aside.scrollTop = Math.max(
0,
offsetTop - aside.clientHeight / 2 + active.offsetHeight / 2
);
}, [pathname]);
Notes
This approach uses the existing forwardRef exposed by @node-core/ui-components/Containers/Sidebar, so no upstream or vendor changes are required.
Alternative considered
Persisting the sidebar’s scrollTop in sessionStorage across reloads was considered, but rejected. That approach adds more complexity, such as saving on unload, restoring at the right time during hydration, and handling stale scroll state when the sidebar structure changes.
Ensuring the active item is visible is simpler and aligns with expected user behavior in most cases.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 components/Sidebar/index.jsx 开始,检查现有的 forwardRef 和导航行为。使用侧边栏中较靠下的项目重现重新加载,然后验证导航后活动链接可见,同时只有侧边栏的内部滚动位置发生变化,主窗口的滚动位置不变。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- javascript, react
- 领域
- frontend, web-dev
- Issue 类型
- 缺陷
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 活跃度
- 活跃
- 描述清晰度
- 描述清楚
- 新手友好度
- 86/100