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(tabs): Add ellipsis for multiple tabs #4510

Open
wants to merge 4 commits into
base: canary
Choose a base branch
from

Conversation

deepansh946
Copy link

@deepansh946 deepansh946 commented Jan 7, 2025

Closes #3573

Demo:

Screen.Recording.2025-01-07.at.7.54.28.PM.mov

📝 Description

This PR introduces ellipsis support for the Tab component enabling easy access to tabs which are not in the viewport. The implementation uses DOM elements to calculate elements out of the screen & show ellipsis accordingly.

⛳️ Current behavior (updates)

Currently all the tabs can be viewed by scrolling horizontally which isn't a great UX for multiple tabs.

🚀 New behavior

Added ellipsis menu at the end of the tab list, so that all other tabs can be accessed by that.

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

No

📝 Additional Information

Summary by CodeRabbit

  • New Features

    • Enhanced Tabs component with overflow handling
    • Added dropdown functionality for hidden tabs
    • Improved tab navigation and scrolling capabilities
  • Dependencies

    • Added @nextui-org/dropdown as a dependency

This update introduces a more robust and user-friendly Tabs component that dynamically manages tab visibility and provides an intuitive way to access hidden tabs through a dropdown menu.

Copy link

changeset-bot bot commented Jan 7, 2025

🦋 Changeset detected

Latest commit: f3683d6

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@nextui-org/tabs Major
@nextui-org/react Patch

Not sure what this means? Click here to learn what changesets are.

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

Copy link

vercel bot commented Jan 7, 2025

@deepansh946 is attempting to deploy a commit to the NextUI Inc Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces an enhanced overflow handling mechanism for the Tabs component. By adding state variables and methods, the implementation now supports dynamically managing tab visibility when the number of tabs exceeds the available screen space. A dropdown mechanism is introduced to display hidden tabs, allowing users to access tabs that would otherwise be out of view. The changes include adding the @nextui-org/dropdown as a dependency to support this new functionality.

Changes

File Change Summary
packages/components/tabs/package.json Added @nextui-org/dropdown as a workspace dependency
packages/components/tabs/src/tabs.tsx - Added new state variables for overflow management
- Implemented checkOverflow method
- Added scrollToTab and handleTabSelect methods
- Modified rendering logic to include dropdown for hidden tabs

Assessment against linked issues

Objective Addressed Explanation
Add navigation for tabs with overflow Partial implementation with dropdown, but no explicit prev/next arrows
Handle tabs exceeding screen size Dropdown mechanism introduced for hidden tabs

Possibly related PRs

Suggested reviewers

  • jrgarciadev
  • wingkwong

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.

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: 2

🧹 Nitpick comments (3)
packages/components/tabs/src/tabs.tsx (3)

43-77: Consider optimizing overflow calculations

The overflow detection logic is correct but could benefit from performance optimizations:

  1. Consider debouncing the scroll event handler
  2. Cache DOM measurements where possible to reduce layout thrashing
+ import {debounce} from "@nextui-org/shared-utils";
+
  const checkOverflow = useCallback(
-   () => {
+   debounce(() => {
      if (!tabList) return;
      // ... rest of the function
-   },
+   }, 150),
    [state.collection, tabListProps.ref]
  );

79-94: Clean scroll implementation!

The scroll behavior is well-implemented. Consider adding error boundaries or logging for cases where the tab element isn't found.

  const scrollToTab = useCallback(
    (key: string) => {
      if (!tabList) return;
      const tabElement = tabList.querySelector(`[data-key="${key}"]`);
-     if (!tabElement) return;
+     if (!tabElement) {
+       console.warn(`Tab with key "${key}" not found`);
+       return;
+     }

139-175: Enhance visual feedback for overflow state

The overflow handling is well-implemented with proper accessibility. Consider adding:

  1. Visual indicator for scroll shadows when content is overflowing
  2. Active state styling for the ellipsis button when dropdown is open
  <button
    aria-label="Show more tabs"
-   className="flex-none flex items-center justify-center w-10 h-8 ml-1 hover:bg-default-100 rounded-small transition-colors"
+   className={clsx(
+     "flex-none flex items-center justify-center w-10 h-8 ml-1 hover:bg-default-100 rounded-small transition-colors",
+     isDropdownOpen && "bg-default-100"
+   )}
  >
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eada8cb and 1790c35.

📒 Files selected for processing (2)
  • packages/components/tabs/package.json (1 hunks)
  • packages/components/tabs/src/tabs.tsx (3 hunks)
🔇 Additional comments (3)
packages/components/tabs/src/tabs.tsx (3)

1-6: Well-structured state management and imports!

The new imports and state variables are well-organized and properly typed for managing tab overflow functionality.

Also applies to: 34-36


96-105: LGTM! Well-structured tab selection handler

The handler properly manages state updates and scroll behavior.


177-186: LGTM! Tab panel rendering maintained

The tab panel rendering properly maintains existing functionality while integrating with the new overflow handling.

packages/components/tabs/src/tabs.tsx Outdated Show resolved Hide resolved
packages/components/tabs/package.json Outdated Show resolved Hide resolved
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: 1

♻️ Duplicate comments (1)
packages/components/tabs/src/tabs.tsx (1)

154-155: ⚠️ Potential issue

Add cleanup for scroll event listener

The scroll event listener should be cleaned up to prevent memory leaks.

🧹 Nitpick comments (2)
packages/components/tabs/src/tabs.tsx (2)

43-77: Consider optimizing overflow detection performance

The current implementation performs DOM measurements in a loop, which could impact performance with many tabs.

Consider these optimizations:

  const checkOverflow = useCallback(() => {
    if (!tabList) return;

    const isOverflowing = tabList.scrollWidth > tabList.clientWidth;

    setShowOverflow(isOverflowing);

    if (!isOverflowing) {
      setHiddenTabs([]);
      return;
    }

    const tabs = [...state.collection];
    const hiddenTabsList: Array<{key: string; title: string}> = [];
    const {left: containerLeft, right: containerRight} = tabList.getBoundingClientRect();
+   // Cache all tab elements and their measurements upfront
+   const tabElements = tabs.map(item => ({
+     item,
+     element: tabList.querySelector(`[data-key="${item.key}"]`),
+   }));

-   tabs.forEach((item) => {
+   tabElements.forEach(({item, element}) => {
-     const tabElement = tabList.querySelector(`[data-key="${item.key}"]`);

-     if (!tabElement) return;
+     if (!element) return;

-     const {left: tabLeft, right: tabRight} = tabElement.getBoundingClientRect();
+     const {left: tabLeft, right: tabRight} = element.getBoundingClientRect();

170-177: Consider handling loading state

The dropdown menu might benefit from a loading state indicator while fetching tab content.

  <DropdownMenu
    aria-label="Hidden tabs"
    onAction={(key) => handleTabSelect(key as string)}
  >
+   {hiddenTabs.length === 0 && (
+     <DropdownItem isDisabled>No hidden tabs</DropdownItem>
+   )}
    {hiddenTabs.map((tab) => (
      <DropdownItem key={tab.key}>{tab.title}</DropdownItem>
    ))}
  </DropdownMenu>
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1790c35 and 0ed340e.

📒 Files selected for processing (3)
  • .changeset/curly-snails-yell.md (1 hunks)
  • packages/components/tabs/package.json (1 hunks)
  • packages/components/tabs/src/tabs.tsx (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/curly-snails-yell.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/components/tabs/package.json
🔇 Additional comments (2)
packages/components/tabs/src/tabs.tsx (2)

34-36: LGTM! Well-structured state management

The state variables are well-defined with clear purposes:

  • showOverflow for controlling overflow visibility
  • hiddenTabs for managing tabs outside viewport
  • isDropdownOpen for dropdown state

162-168: LGTM! Excellent accessibility implementation

Great attention to accessibility with:

  • Proper aria-label
  • Screen reader text
  • Semantic button element

inline: "center",
});
},
[tabListProps.ref],
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

Fix useCallback dependency

The dependency array references tabListProps.ref but should reference tabList instead.

- [tabListProps.ref],
+ [tabList],
📝 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
[tabListProps.ref],
[tabList],

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.

[Feature Request] Prev icon and next icon in Tabs
1 participant