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

feat(docs): preserve scrolling position when navigating to new page #4294

Merged
merged 2 commits into from
Dec 12, 2024

Conversation

vinroger
Copy link
Contributor

@vinroger vinroger commented Dec 9, 2024

Preview (Tested on Safari, Chrome, Firefox)

BEFORE

nextui.sidebar.before.mp4

AFTER (Chrome)

preserverscrolling.mp4

AFTER (Safari)

safari.preserve.scrolling.mp4

📝 Description

This PR introduces functionality to preserve the scroll position in the documentation sidebar when navigating between pages. This feature enhances user experience by ensuring the sidebar retains its position, preventing the need to scroll back to the previous section manually.

⛳️ Current behavior (updates)

Currently, the sidebar scroll position is reset to the top whenever a user navigates to a new page. This behavior can be disruptive, particularly when exploring deeply nested sections or returning to a previous part of the documentation.

🚀 New behavior

  • Scroll Position Preservation:
    • Upon navigation, the sidebar retains its scroll position by saving and restoring the position using sessionStorage.
    • Scroll events are tracked, and the position is stored whenever the user scrolls the sidebar.
    • When a new page is loaded, the saved scroll position is retrieved and applied to the sidebar.

💣 Is this a breaking change (Yes/No):

No.

📝 Additional Information

  • The implementation leverages the useLayoutEffect hook to ensure that the scroll position is restored after the sidebar is rendered.
  • Updates include modifications to the ScrollArea and Tree components to accommodate the scroll preservation logic.
  • This update does not introduce any new dependencies and adheres to the current architectural conventions of the project.

Summary by CodeRabbit

  • New Features

    • Enhanced scroll management in the sidebar for improved user experience.
    • Added functionality to preserve and restore scroll position across component mounts.
    • Updated ScrollArea component to manage viewport reference and handle scroll events effectively.
  • Bug Fixes

    • Updated tree content to ensure it reflects changes in props appropriately.
  • Documentation

    • Improved clarity in component props for better integration and usage.

@vinroger vinroger requested a review from jrgarciadev as a code owner December 9, 2024 12:28
Copy link

linear bot commented Dec 9, 2024

Copy link

vercel bot commented Dec 9, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
nextui-docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 11, 2024 4:40am
nextui-storybook-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 11, 2024 4:40am

Copy link

changeset-bot bot commented Dec 9, 2024

⚠️ No Changeset found

Latest commit: 2d0feb0

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

Walkthrough

The pull request introduces modifications to the sidebar.tsx and scroll-area.tsx files, enhancing the functionality of the Tree, DocsSidebar, and ScrollArea components. Key changes include the addition of a scrollViewPortRef to manage scroll state, updates to props for handling scroll events, and adjustments to memoization dependencies. The changes aim to improve user experience by preserving scroll positions and facilitating better interactions with the sidebar and scroll area components.

Changes

File Path Change Summary
apps/docs/components/docs/sidebar.tsx - Added scrollViewPortRef to Tree component.
- Updated treeContent memoization to include slug and tag.
- Introduced useLayoutEffect for restoring scroll position from session storage.
- Defined handleScroll function for updating scroll position in session storage.
apps/docs/components/scroll-area.tsx - Enhanced ScrollArea props to include scrollViewPortRef.
- Updated destructuring of props to separate onScroll and scrollViewPortRef.
- Passed scrollViewPortRef and onScroll to ScrollAreaPrimitive.Viewport.

Possibly related PRs

Suggested reviewers

  • wingkwong
  • jrgarciadev

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
apps/docs/components/docs/sidebar.tsx (1)

244-244: Consider extracting scroll position logic to a custom hook

The scroll position preservation logic could be reused in other components. Consider extracting it to a custom hook for better maintainability and reusability.

function useScrollPositionPersistence(key: string) {
  const scrollViewPortRef = useRef<HTMLDivElement>(null);

  useLayoutEffect(() => {
    if (typeof window !== "undefined") {
      try {
        const savedPosition = sessionStorage.getItem(key);
        if (savedPosition && scrollViewPortRef.current) {
          scrollViewPortRef.current.scrollTop = Number(savedPosition);
        }
      } catch (error) {
        console.warn("Failed to restore scroll position:", error);
      }
    }
  }, [key]);

  const handleScroll = debounce(() => {
    if (typeof window !== "undefined" && scrollViewPortRef.current) {
      try {
        sessionStorage.setItem(key, scrollViewPortRef.current.scrollTop.toString());
      } catch (error) {
        console.warn("Failed to save scroll position:", error);
      }
    }
  }, 300);

  return { scrollViewPortRef, handleScroll };
}

Also applies to: 284-285

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3d782a2 and 8765f0a.

📒 Files selected for processing (2)
  • apps/docs/components/docs/sidebar.tsx (4 hunks)
  • apps/docs/components/scroll-area.tsx (1 hunks)
🔇 Additional comments (2)
apps/docs/components/scroll-area.tsx (1)

21-25: Verify ref forwarding chain

The component now handles two refs: one forwarded to Root and another for Viewport. Ensure this doesn't cause any ref-related issues in parent components.

✅ Verification successful

Ref forwarding implementation is correct and safe

The ScrollArea component's implementation shows proper ref handling:

  • The main ref is correctly forwarded to ScrollAreaPrimitive.Root
  • The scrollViewPortRef is passed as a prop and properly applied to ScrollAreaPrimitive.Viewport
  • Both refs have distinct purposes and don't interfere with each other
  • The component's type definitions properly declare the ref types and props
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other components using ScrollArea with refs
ast-grep --pattern 'const $_ = useRef<$_>();
$$$
<ScrollArea ref={$_}'

Length of output: 72


Script:

#!/bin/bash
# Let's try a different pattern to find ScrollArea usage with refs
ast-grep --pattern '<ScrollArea ref={$_}'

# Also search for the component definition to understand ref handling
ast-grep --pattern 'const ScrollArea = React.forwardRef<$_>'

# And check direct usage of ScrollAreaPrimitive
ast-grep --pattern '<ScrollAreaPrimitive.Root ref={$_}'

Length of output: 164


Script:

#!/bin/bash
# Let's examine the ScrollArea component implementation and its usage
rg -l "ScrollArea" --type tsx

# Then let's look at the content of the scroll-area.tsx file
cat apps/docs/components/scroll-area.tsx

Length of output: 2071


Script:

#!/bin/bash
# Let's search for files using ScrollArea with .ts and .jsx extensions as well
rg -l "ScrollArea" --type ts --type jsx

# And let's try to find any usage of scrollViewPortRef
rg "scrollViewPortRef" --type ts --type tsx --type jsx

Length of output: 150

apps/docs/components/docs/sidebar.tsx (1)

342-342: Verify dependency array completeness

The treeContent memo's dependency array now includes slug and tag. Ensure this covers all dependencies that could affect the rendered content.

✅ Verification successful

Let me search for the expandedKeys variable to ensure it's not a dependency that should be included in the array.


Dependency array is correctly specified

The treeContent memo's dependency array [routes, slug, tag] is complete and accurate. All dependencies used within the memoized content are properly included:

  • routes is used for mapping and also for expandedKeys calculation
  • slug and tag are passed as props to the Item component
  • expandedKeys is derived from routes and doesn't need separate inclusion
  • Other values used within the memo are either component props spread via {...route} or derived from the route iteration variable
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all props used within the treeContent
ast-grep --pattern 'const treeContent = useMemo(() => {
  $$$
  $PROP
  $$$
}, $_)'

Length of output: 1222


Script:

#!/bin/bash
# Search for expandedKeys definition and usage
ast-grep --pattern 'const expandedKeys = $_'

Length of output: 510

Comment on lines 9 to 11
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> & {
scrollViewPortRef: React.RefObject<HTMLDivElement>;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider making scrollViewPortRef optional

Making scrollViewPortRef a required prop might break existing usages of the ScrollArea component. Consider making it optional to maintain backward compatibility.

- scrollViewPortRef: React.RefObject<HTMLDivElement>;
+ scrollViewPortRef?: React.RefObject<HTMLDivElement>;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> & {
scrollViewPortRef: React.RefObject<HTMLDivElement>;
}
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> & {
scrollViewPortRef?: React.RefObject<HTMLDivElement>;
}

Comment on lines +258 to +267
/* Handle scroll preservation */
useLayoutEffect(() => {
if (typeof window !== "undefined") {
const savedPosition = sessionStorage.getItem("docsSidebarScrollPosition");

if (savedPosition && scrollViewPortRef.current) {
scrollViewPortRef.current.scrollTop = Number(savedPosition);
}
}
}, []);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for sessionStorage operations

The sessionStorage operations should be wrapped in try-catch blocks to handle potential errors (e.g., when storage is full or disabled).

 useLayoutEffect(() => {
   if (typeof window !== "undefined") {
-    const savedPosition = sessionStorage.getItem("docsSidebarScrollPosition");
-    if (savedPosition && scrollViewPortRef.current) {
-      scrollViewPortRef.current.scrollTop = Number(savedPosition);
+    try {
+      const savedPosition = sessionStorage.getItem("docsSidebarScrollPosition");
+      if (savedPosition && scrollViewPortRef.current) {
+        scrollViewPortRef.current.scrollTop = Number(savedPosition);
+      }
+    } catch (error) {
+      console.warn("Failed to restore scroll position:", error);
     }
   }
 }, []);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/* Handle scroll preservation */
useLayoutEffect(() => {
if (typeof window !== "undefined") {
const savedPosition = sessionStorage.getItem("docsSidebarScrollPosition");
if (savedPosition && scrollViewPortRef.current) {
scrollViewPortRef.current.scrollTop = Number(savedPosition);
}
}
}, []);
/* Handle scroll preservation */
useLayoutEffect(() => {
if (typeof window !== "undefined") {
try {
const savedPosition = sessionStorage.getItem("docsSidebarScrollPosition");
if (savedPosition && scrollViewPortRef.current) {
scrollViewPortRef.current.scrollTop = Number(savedPosition);
}
} catch (error) {
console.warn("Failed to restore scroll position:", error);
}
}
}, []);

apps/docs/components/docs/sidebar.tsx Show resolved Hide resolved
@wingkwong wingkwong modified the milestones: v2.6.6, v2.6.7, v2.6.8, v2.6.9 Dec 9, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
apps/docs/components/scroll-area.tsx (1)

13-13: Props destructuring looks good

Clean separation of scroll-related props from other props. The rename to restProps improves code clarity.

Consider adding TypeScript type annotations for better code documentation:

-  const {onScroll, scrollViewPortRef, ...restProps} = props;
+  const {onScroll, scrollViewPortRef, ...restProps}: typeof props = props;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8765f0a and 2d0feb0.

📒 Files selected for processing (2)
  • apps/docs/components/docs/sidebar.tsx (4 hunks)
  • apps/docs/components/scroll-area.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/docs/components/docs/sidebar.tsx
🔇 Additional comments (2)
apps/docs/components/scroll-area.tsx (2)

9-11: LGTM: Type definitions are well-structured

The scrollViewPortRef prop is correctly defined as optional, maintaining backward compatibility with existing usages of the ScrollArea component.


19-25: Verify scroll event listener cleanup

The implementation looks correct, but we should verify that any scroll listeners are properly cleaned up to prevent memory leaks.

Let's check if there are any cleanup mechanisms in place:

@jrgarciadev jrgarciadev changed the base branch from canary to main December 12, 2024 12:12
@jrgarciadev jrgarciadev merged commit 47b7d3e into main Dec 12, 2024
8 checks passed
@jrgarciadev jrgarciadev deleted the eng-1643-preserve-scrolling-when-navigating-docs branch December 12, 2024 12:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants