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

fix multi active nav links #9717

Closed

Conversation

rajku-dev
Copy link
Contributor

@rajku-dev rajku-dev commented Jan 3, 2025

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Introduced ActiveLink component for enhanced sidebar navigation.
    • Added NavLink component for improved active link management.
    • Enhanced link active state detection with sophisticated matching logic.
  • Refactor

    • Updated navigation link handling to support more complex active state determination.

@rajku-dev rajku-dev requested a review from a team as a code owner January 3, 2025 17:15
Copy link
Contributor

coderabbitai bot commented Jan 3, 2025

Walkthrough

The pull request introduces a new ActiveLink component in the sidebar navigation system. This component enhances link active state detection by using the usePath hook from the raviger library. It provides more sophisticated active link detection, considering exact and nested URL matches while preventing multiple tabs from being marked active simultaneously.

Changes

File Change Summary
src/components/ui/sidebar/ActiveLinks.tsx New ActiveLink component created with advanced path matching logic
src/components/ui/sidebar/nav-main.tsx Updated import for ActiveLink and modified component usage to track active links
src/components/ui/sidebar/NavLink.tsx New NavLink component created to manage active link state and rendering

Assessment against linked issues

Objective Addressed Explanation
Prevent multiple tabs from being marked active [#9637]
Highlight only the currently active tab

Poem

🐰 A rabbit's tale of links so bright,
Where only one tab shines with might!
No more confusion, no more strife,
Our navigation cuts like a knife!
Active links now dance with grace 🌟


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. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

netlify bot commented Jan 3, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit beda304
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6778a3d3a88c5c000827a0e9
😎 Deploy Preview https://deploy-preview-9717--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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

🧹 Nitpick comments (3)
src/components/ui/sidebar/ActiveLinks.tsx (2)

16-17: Fix typo in variable name.
isExactCollison is missing an extra "i". Rename to maintain consistency and clarify meaning.

- const isExactCollison = links.some((link) => link.url === pathname);
+ const isExactCollision = links.some((link) => link.url === pathname);

18-20: Fix another typo in variable name.
isNestedCollison is also missing an extra "i" in "collision."

- const isNestedCollison = links.some(
+ const isNestedCollision = links.some(
src/components/ui/sidebar/nav-main.tsx (1)

35-35: Pass minimal props to avoid confusion.
Currently, passing the entire links array may be more than the component needs if it only checks collisions among sibling routes. If only certain links need to be considered, you could pass a filtered subset to improve clarity and performance.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b36f39f and 798597a.

📒 Files selected for processing (2)
  • src/components/ui/sidebar/ActiveLinks.tsx (1 hunks)
  • src/components/ui/sidebar/nav-main.tsx (2 hunks)
🔇 Additional comments (6)
src/components/ui/sidebar/ActiveLinks.tsx (5)

1-2: Ensure type references from "raviger/dist/Link" remain stable.
Currently, using ActiveLinkProps from "raviger/dist/Link" may break if the library’s internal structure changes in future updates. Consider exporting and re-exporting official types from raviger directly if they exist, to avoid referencing library internals.


4-10: Validate default links usage.
The links = [] default assignment is good for preventing runtime errors. However, confirm that this behavior aligns with the usage context—especially if links must be guaranteed not to be empty.


13-15: Confirm logic for determining nested match.
The condition pathname?.startsWith(href) && pathname.length > href.length flags routes as nested only when the pathname is strictly longer than href. This may skip routes that match href plus a slash (e.g., /example vs /example/). Ensure this logic correctly handles trailing slashes or alternative route patterns.


24-29: Double-check collision logic precedence.
When both isNestedMatch and collisions are true, the link is assigned no active class. Confirm if the intended UX is to treat all collisions as higher priority than nested matches, even if the current route is otherwise a valid nested match.


30-37: General structure is cohesive.
Returning a Link with combined classes works well, and spreading additional props is a clean approach for extensibility.

src/components/ui/sidebar/nav-main.tsx (1)

11-11: Good import update for the new ActiveLink logic.
Switching from a direct raviger import to the local ActiveLinks is appropriate for the updated functionality.

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

🧹 Nitpick comments (2)
src/components/ui/sidebar/NavLink.tsx (2)

17-19: Potential missed accessibility considerations on click.

Attaching onClick to a wrapping <div> could cause unexpected behavior if the user clicks within the <div> but not on the actual link. Consider moving the click handler directly onto the <Link> element to ensure consistent user interactions and accessibility.

 <div>
-  <div onClick={handleClick}>
     <Link
       href={href}
       className={`${className} ${computedClassName}`}
       {...props}
+      onClick={handleClick}
     />
-  </div>
 </div>

21-21: Use strict equality for robust type checking.

Using === instead of == ensures no unintended type coercions, helping avoid subtle bugs.

-  const computedClassName = activeLink == name ? activeClass : "";
+  const computedClassName = activeLink === name ? activeClass : "";
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 798597a and 1b75d68.

📒 Files selected for processing (2)
  • src/components/ui/sidebar/NavLink.tsx (1 hunks)
  • src/components/ui/sidebar/nav-main.tsx (4 hunks)
🔇 Additional comments (6)
src/components/ui/sidebar/NavLink.tsx (3)

1-2: Imports look correct and concise.

Using Link from raviger and ActiveLinkProps shows consistent usage with the existing navigation utilities.


4-16: Prop definitions are clear and strongly typed.

The addition of activeLink, setActive, and name within the type intersection aligns well with your custom active link logic. Good job on explicitly defining types.


23-31: Return structure is straightforward and readable.

The wrapped Link component is rendered clearly, aligned with the rest of the code style. No issues observed.

src/components/ui/sidebar/nav-main.tsx (3)

24-29: Stateful approach for active link is well-structured.

You’ve introduced activeLink to manage the currently active navigation item. The simple useState usage and handleSetActive function addresses the multi-active problem effectively.


43-55: Good usage of the new NavLink component with active state handling.

You’ve removed the exactActiveClass in favor of activeLink logic and consolidated the responsibilities for setting the active state. This addresses the multi-active link problem comprehensively.


43-49: Consider verifying consistent naming conventions in your link objects.

Each link object uses name and url keys. Ensure all references (like link.url, link.name) remain consistent with any potential future expansions (e.g., slug or path). If the naming scheme changes, quickly reflect it in your typed definitions to maintain clarity.

✅ Verification successful

Let me try a different approach to verify the naming conventions in link objects.


Let me try one more search to find the type definitions for these link objects.


Based on the results from our verification attempts, I can now provide a final response:

Link object properties are consistently used across the codebase

From the search results, we can see that the link objects consistently use name and url properties throughout the codebase. All references to these properties (link.name and link.url) are uniform in both the nav-main.tsx and ActiveLinks.tsx components. There's also a consistent pattern where link.name is used for display text and tooltips, while link.url is used for navigation purposes. The only additional property observed is link.icon, which is optionally used for rendering icons.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Look for occurrences of `links` usage across the entire codebase to confirm consistent naming.
rg -A 5 $'links\\s*[:=]\\s*{\\s*name:'

Length of output: 159


Script:

#!/bin/bash
# Search for link object definitions and usages
rg -A 5 "link\.(url|name|path|slug)" 

# Also search for any type definitions related to links
ast-grep --pattern 'type $_ = { $$$name: $_,$$$url: $_,$$$}'
ast-grep --pattern 'interface $_ { $$$name: $_,$$$url: $_,$$$}'

Length of output: 2640


Script:

#!/bin/bash
# Search for type definitions and interfaces containing 'link' in their name
ast-grep --pattern 'type $_Link$_ = { $$$}'
ast-grep --pattern 'interface $_Link$_ { $$$}'

# Also search for any array definitions of links
rg "const\s+\w*links\s*=\s*\[" -A 5

Length of output: 132

@rajku-dev
Copy link
Contributor Author

@rithviknishad according to me its handling all the edge cases now. Can you please review once?

@github-actions github-actions bot added needs-triage question Further information is requested labels Jan 4, 2025
Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

this approach doesn't work for multiple reasons

  1. if you go to a specific page directly by pasting it's link in the browser, this shows facility tab regardless of what page it is currently in.

  2. if you somehow let's say reach facility page through users profile, or patient details or anywhere else, the active tab doesn't automatically change to that.

@rajku-dev
Copy link
Contributor Author

this approach doesn't work for multiple reasons

  1. if you go to a specific page directly by pasting it's link in the browser, this shows facility tab regardless of what page it is currently in.
  2. if you somehow let's say reach facility page through users profile, or patient details or anywhere else, the active tab doesn't automatically change to that.

so the collision approach was better i guess.. i thought tab should not change once upon inter-navigation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-triage question Further information is requested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Multiple Tabs Marked as Active in Navigation Bar When Switching Between Tabs
2 participants