-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
feat(ui): implement sidebar scroll position preservation #8517
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
Open
malav2110
wants to merge
13
commits into
nodejs:main
Choose a base branch
from
malav2110:fix-selected-article-sidebar-scroll-fix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
0781979
feat(ui): implement sidebar scroll position preservation
malav2110 41e3879
fix: correct import statements for hooks in withSidebar component
malav2110 1ebf202
fix: correct comment grammar, improve sidebar component display name …
malav2110 ece53b4
fix: streamline imports in withSidebar component and update pathname …
malav2110 0f2b57b
fix: remove unused imports and ensure 'use client' directive is prese…
malav2110 0212fba
fix: replace useNavigationState with useScrollToElement in WithSideba…
malav2110 3e54d01
fix: clarify comment in handleScroll function to improve code readabi…
malav2110 9d06df5
fix: addressed nitpicks and ran pnpm version path in ui-components d…
malav2110 d021e51
Merge branch 'main' into fix-selected-article-sidebar-scroll-fix
malav2110 c723ccf
fix: remove unnecessary 'use client' directive from Sidebar component
malav2110 d3cb88b
Merge branch 'fix-selected-article-sidebar-scroll-fix' of https://git…
malav2110 48b3f00
fix: improve sidebar pathname handling
malav2110 ae02e18
fix: remove unused locale handling from WithSidebar component
malav2110 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
145 changes: 145 additions & 0 deletions
145
apps/site/hooks/client/__tests__/useScrollToElement.test.jsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| import { renderHook } from '@testing-library/react'; | ||
| import { afterEach, beforeEach, describe, it, mock } from 'node:test'; | ||
| import assert from 'node:assert/strict'; | ||
|
|
||
| import useScrollToElement from '#site/hooks/client/useScrollToElement.js'; | ||
| import { NavigationStateContext } from '#site/providers/navigationStateProvider'; | ||
|
|
||
| describe('useScrollToElement', () => { | ||
| let mockElement; | ||
| let mockRef; | ||
| let navigationState; | ||
|
|
||
| beforeEach(() => { | ||
| navigationState = {}; | ||
|
|
||
| mockElement = { | ||
| scrollTop: 0, | ||
| scrollLeft: 0, | ||
| scroll: mock.fn(), | ||
| addEventListener: mock.fn(), | ||
| removeEventListener: mock.fn(), | ||
| }; | ||
|
|
||
| mockRef = { current: mockElement }; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| mock.reset(); | ||
| }); | ||
|
|
||
| it('should handle scroll restoration with various scenarios', () => { | ||
| const wrapper = ({ children }) => ( | ||
| <NavigationStateContext.Provider value={navigationState}> | ||
| {children} | ||
| </NavigationStateContext.Provider> | ||
| ); | ||
|
|
||
| // Should restore scroll position on mount if saved state exists | ||
| navigationState.sidebar = { x: 100, y: 200 }; | ||
| const { unmount: unmount1 } = renderHook(() => useScrollToElement('sidebar', mockRef), { wrapper }); | ||
|
|
||
| assert.equal(mockElement.scroll.mock.callCount(), 1); | ||
| assert.deepEqual(mockElement.scroll.mock.calls[0].arguments, [ | ||
| { top: 200, behavior: 'auto' }, | ||
| ]); | ||
|
|
||
| unmount1(); | ||
| mock.reset(); | ||
| mockElement.scroll = mock.fn(); | ||
|
|
||
| // Should not restore if no saved state exists | ||
| navigationState = {}; | ||
| const { unmount: unmount2 } = renderHook(() => useScrollToElement('sidebar', mockRef), { wrapper }); | ||
| assert.equal(mockElement.scroll.mock.callCount(), 0); | ||
|
|
||
| unmount2(); | ||
| mock.reset(); | ||
| mockElement.scroll = mock.fn(); | ||
|
|
||
| // Should not restore if current position matches saved state | ||
| navigationState.sidebar = { x: 0, y: 0 }; | ||
| mockElement.scrollTop = 0; | ||
| const { unmount: unmount3 } = renderHook(() => useScrollToElement('sidebar', mockRef), { wrapper }); | ||
| assert.equal(mockElement.scroll.mock.callCount(), 0); | ||
|
|
||
| unmount3(); | ||
| mock.reset(); | ||
| mockElement.scroll = mock.fn(); | ||
|
|
||
| // Should restore scroll to element that was outside viewport (deep scroll) | ||
| navigationState.sidebar = { x: 0, y: 1500 }; | ||
| mockElement.scrollTop = 0; | ||
| renderHook(() => useScrollToElement('sidebar', mockRef), { wrapper }); | ||
|
|
||
| assert.equal(mockElement.scroll.mock.callCount(), 1); | ||
| assert.deepEqual(mockElement.scroll.mock.calls[0].arguments, [ | ||
| { top: 1500, behavior: 'auto' }, | ||
| ]); | ||
| }); | ||
|
|
||
| it('should persist and restore scroll position across navigation', async () => { | ||
| const wrapper = ({ children }) => ( | ||
| <NavigationStateContext.Provider value={navigationState}> | ||
| {children} | ||
| </NavigationStateContext.Provider> | ||
| ); | ||
|
|
||
| // First render: user scrolls to position 800 | ||
| const { unmount } = renderHook(() => useScrollToElement('sidebar', mockRef), { wrapper }); | ||
|
|
||
| const scrollHandler = mockElement.addEventListener.mock.calls[0].arguments[1]; | ||
| mockElement.scrollTop = 800; | ||
| mockElement.scrollLeft = 0; | ||
| scrollHandler(); | ||
|
|
||
| // Wait for debounce | ||
| await new Promise(resolve => setTimeout(resolve, 350)); | ||
|
|
||
| // Position should be saved | ||
| assert.deepEqual(navigationState.sidebar, { x: 0, y: 800 }); | ||
|
|
||
| // Simulate navigation (unmount) | ||
| unmount(); | ||
|
|
||
| // Simulate navigation back (remount with element at top) | ||
| mockElement.scrollTop = 0; | ||
| mock.reset(); | ||
| mockElement.scroll = mock.fn(); | ||
| mockElement.addEventListener = mock.fn(); | ||
| mockElement.removeEventListener = mock.fn(); | ||
| mockRef.current = mockElement; | ||
|
|
||
| renderHook(() => useScrollToElement('sidebar', mockRef), { wrapper }); | ||
|
|
||
| // Should restore to position 800 | ||
| assert.equal(mockElement.scroll.mock.callCount(), 1); | ||
| assert.deepEqual(mockElement.scroll.mock.calls[0].arguments, [ | ||
| { top: 800, behavior: 'auto' }, | ||
| ]); | ||
|
|
||
| // Also test that scroll position is saved to navigation state during scroll | ||
| mock.reset(); | ||
| mockElement.addEventListener = mock.fn(); | ||
| mockElement.scroll = mock.fn(); | ||
| navigationState = {}; | ||
|
|
||
| renderHook(() => useScrollToElement('sidebar', mockRef), { wrapper }); | ||
|
|
||
| // Get the scroll handler that was registered | ||
| const scrollHandler2 = mockElement.addEventListener.mock.calls[0].arguments[1]; | ||
|
|
||
| // Simulate scroll | ||
| mockElement.scrollTop = 150; | ||
| mockElement.scrollLeft = 50; | ||
|
|
||
| // Call the handler | ||
| scrollHandler2(); | ||
|
|
||
| // Wait for debounce (default 300ms) | ||
| await new Promise(resolve => setTimeout(resolve, 350)); | ||
|
|
||
| // Check that navigation state was updated | ||
| assert.deepEqual(navigationState.sidebar, { x: 50, y: 150 }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| export { default as useDetectOS } from './useDetectOS'; | ||
| export { default as useMediaQuery } from './useMediaQuery'; | ||
| export { default as useClientContext } from './useClientContext'; | ||
| export { default as useScrollToElement } from './useScrollToElement'; | ||
malav2110 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| export { default as useScroll } from './useScroll'; | ||
malav2110 marked this conversation as resolved.
Show resolved
Hide resolved
malav2110 marked this conversation as resolved.
Show resolved
Hide resolved
malav2110 marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| 'use client'; | ||
|
|
||
| import { useEffect, useRef } from 'react'; | ||
|
|
||
| import type { RefObject } from 'react'; | ||
|
|
||
| type ScrollPosition = { | ||
| x: number; | ||
| y: number; | ||
| }; | ||
|
|
||
| type UseScrollOptions = { | ||
| debounceTime?: number; | ||
| onScroll?: (position: ScrollPosition) => void; | ||
| }; | ||
|
|
||
| // Custom hook to handle scroll events with optional debouncing | ||
| const useScroll = <T extends HTMLElement>( | ||
| ref: RefObject<T | null>, | ||
| { debounceTime = 300, onScroll }: UseScrollOptions = {} | ||
| ) => { | ||
| const timeoutRef = useRef<NodeJS.Timeout | undefined>(undefined); | ||
|
|
||
| useEffect(() => { | ||
| // Get the current element | ||
| const element = ref.current; | ||
|
|
||
| // Return early if no element or onScroll callback is provided | ||
| if (!element || !onScroll) { | ||
| return; | ||
| } | ||
|
|
||
| // Debounced scroll handler | ||
| const handleScroll = () => { | ||
| // Clear existing timeout | ||
| if (timeoutRef.current) { | ||
| clearTimeout(timeoutRef.current); | ||
| } | ||
|
|
||
| // Set new timeout to call onScroll after debounceTime | ||
| timeoutRef.current = setTimeout(() => { | ||
| if (element) { | ||
| onScroll({ | ||
| x: element.scrollLeft, | ||
| y: element.scrollTop, | ||
| }); | ||
| } | ||
| }, debounceTime); | ||
| }; | ||
|
|
||
| element.addEventListener('scroll', handleScroll, { passive: true }); | ||
|
|
||
| return () => { | ||
| element.removeEventListener('scroll', handleScroll); | ||
| // Clear any pending debounced calls | ||
| if (timeoutRef.current) { | ||
| clearTimeout(timeoutRef.current); | ||
| } | ||
| }; | ||
| }, [ref, onScroll, debounceTime]); | ||
| }; | ||
|
|
||
| export default useScroll; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| 'use client'; | ||
|
|
||
| import { useContext, useEffect } from 'react'; | ||
|
|
||
| import { NavigationStateContext } from '#site/providers/navigationStateProvider'; | ||
|
|
||
| import type { RefObject } from 'react'; | ||
|
|
||
| import useScroll from './useScroll'; | ||
|
|
||
| const useScrollToElement = <T extends HTMLElement>( | ||
| id: string, | ||
| ref: RefObject<T | null>, | ||
| debounceTime = 300 | ||
| ) => { | ||
| const navigationState = useContext(NavigationStateContext); | ||
|
|
||
| // Restore scroll position on mount | ||
| useEffect(() => { | ||
| if (!ref.current) { | ||
| return; | ||
| } | ||
|
|
||
| // Restore scroll position if saved state exists | ||
| const savedState = navigationState[id]; | ||
|
|
||
| // Scroll only if the saved position differs from current | ||
| if (savedState && savedState.y !== ref.current.scrollTop) { | ||
| ref.current.scroll({ top: savedState.y, behavior: 'auto' }); | ||
| } | ||
| // navigationState is intentionally excluded | ||
| // it's a stable object reference that doesn't need to trigger re-runs | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
malav2110 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }, [id, ref]); | ||
|
|
||
| // Save scroll position on scroll | ||
| const handleScroll = (position: { x: number; y: number }) => { | ||
| // Save the current scroll position in the navigation state | ||
| const state = navigationState as Record<string, { x: number; y: number }>; | ||
| state[id] = position; | ||
| }; | ||
|
|
||
| // Use the useScroll hook to handle scroll events with debouncing | ||
| useScroll(ref, { debounceTime, onScroll: handleScroll }); | ||
| }; | ||
|
|
||
| export default useScrollToElement; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,3 @@ | ||
| export { default as useClientContext } from './useClientContext'; | ||
| export { default as useScrollToElement } from './useScrollToElement'; | ||
| export { default as useScroll } from './useScroll'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| const useScroll = () => { | ||
| throw new Error('Attempted to call useScroll from RSC'); | ||
| }; | ||
|
|
||
| export default useScroll; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| const useScrollToElement = () => { | ||
| throw new Error('Attempted to call useScrollToElement from RSC'); | ||
| }; | ||
|
|
||
| export default useScrollToElement; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wondering why this got changed? 👀
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It was put in while I was exploring the solution. Reverted back.Actually, Changed
next/navigation'susePathnametonext-intlversion fromnavigation.mjs. Thenext-intlversion already returns pathnames without the locale prefix, so.replace()call is not needed.