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: prevent multiple parent focus events on click #4274

Conversation

Peterl561
Copy link
Contributor

@Peterl561 Peterl561 commented Dec 8, 2024

Closes #4260

📝 Description

⛳️ Current behavior (updates)

before.mp4

🚀 New behavior

after.mp4

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

No

📝 Additional Information

Summary by CodeRabbit

  • New Features
    • Improved focus behavior for checkbox, radio, and switch components to enhance user experience by preventing unnecessary focus events.
  • Bug Fixes
    • Resolved an issue where focus was incorrectly triggered multiple times on parent elements when interacting with checkbox, radio, and switch components.
  • Tests
    • Added new test cases to verify correct focus behavior for checkbox, radio, and switch components upon interaction.

Copy link

changeset-bot bot commented Dec 8, 2024

🦋 Changeset detected

Latest commit: 476761c

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

This PR includes changesets to release 5 packages
Name Type
@nextui-org/checkbox Patch
@nextui-org/switch Patch
@nextui-org/radio Patch
@nextui-org/table Patch
@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 Dec 8, 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 9, 2024 6:01am
nextui-storybook-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 9, 2024 6:01am

Copy link

vercel bot commented Dec 8, 2024

@Peterl561 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 Dec 8, 2024

Warning

Rate limit exceeded

@jrgarciadev has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 2 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 20d8d90 and 476761c.

📒 Files selected for processing (1)
  • .changeset/tricky-panthers-build.md (1 hunks)

Walkthrough

This update introduces a patch for the @nextui-org/checkbox, @nextui-org/switch, and @nextui-org/radio components to address an issue where these components were incorrectly triggering focus on their parent elements multiple times. The changes include the addition of mouseProps to manage mouse events more effectively, ensuring that focus behavior is corrected. New test cases have also been added to verify that focus is triggered only once on the parent element when the components are clicked.

Changes

File Change Summary
.changeset/tricky-panthers-build.md Patch applied for @nextui-org/checkbox, @nextui-org/switch, and @nextui-org/radio components.
packages/components/checkbox/__tests__/checkbox.test.tsx Added test to verify focus on parent element is triggered once after Checkbox click.
packages/components/checkbox/src/use-checkbox.ts Introduced mouseProps with onMouseDown to prevent parent focus on Checkbox click.
packages/components/radio/__tests__/radio.test.tsx Added test to verify focus on parent element is triggered once after Radio click.
packages/components/radio/src/use-radio.ts Introduced mouseProps with onMouseDown to prevent parent focus on Radio click.
packages/components/switch/__tests__/switch.test.tsx Added test to verify focus on parent element is triggered once after Switch click.
packages/components/switch/src/use-switch.ts Introduced mouseProps with onMouseDown to prevent parent focus on Switch click.

Assessment against linked issues

Objective Addressed Explanation
Fix focus issue on Switch inside CardBody (#4260)
Ensure focus is triggered once on Checkbox, Switch, and Radio clicks

Possibly related PRs

Suggested labels

👀 Status: In Review

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.

@Peterl561 Peterl561 changed the title Fix/selection components parent focus fix(checkbox, radio, switch): prevent multiple parent focus events on click Dec 8, 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 (6)
.changeset/tricky-panthers-build.md (1)

1-7: Enhance the changeset description with more details

While the description captures the core fix, consider adding:

 ---
 "@nextui-org/checkbox": patch
 "@nextui-org/switch": patch
 "@nextui-org/radio": patch
 ---
 
-fixed checkbox, radio, and switch triggering focus on focusable parent multiple times
+fixed checkbox, radio, and switch components triggering multiple focus events on parent elements (issue #4260)
+
+When these components were placed within a focusable parent container, clicking them would trigger focus events multiple times. This has been resolved by preventing the default mouseDown behavior on the components themselves.
packages/components/radio/src/use-radio.ts (1)

153-161: LGTM! Consider adding JSDoc comments

The implementation correctly prevents multiple focus events. Consider adding JSDoc comments to document the purpose of mouseProps.

+  /**
+   * Props to prevent multiple focus events when clicking the radio.
+   * This is needed when the radio is inside a focusable parent.
+   */
   const mouseProps = useMemo(
     () => ({
       onMouseDown: (e: React.MouseEvent<HTMLLabelElement>) => {
         // prevent parent from being focused
         e.preventDefault();
       },
     }),
     [],
   );
packages/components/switch/__tests__/switch.test.tsx (1)

188-202: LGTM! Consider additional test scenarios

The test effectively verifies the fix for multiple focus events. Consider adding tests for:

  • Focus behavior when clicking multiple times
  • Focus behavior with disabled state
  • Focus behavior with readonly state
it("should not trigger focus on parent when disabled", async () => {
  const onFocus = jest.fn();
  
  const wrapper = render(
    <div tabIndex={-1} onFocus={onFocus}>
      <Switch isDisabled data-testid="switch-test">Switch</Switch>
    </div>
  );
  
  const label = wrapper.getByTestId("switch-test");
  await user.click(label);
  
  expect(onFocus).not.toHaveBeenCalled();
});

it("should maintain single focus behavior on multiple clicks", async () => {
  const onFocus = jest.fn();
  
  const wrapper = render(
    <div tabIndex={-1} onFocus={onFocus}>
      <Switch data-testid="switch-test">Switch</Switch>
    </div>
  );
  
  const label = wrapper.getByTestId("switch-test");
  await user.click(label);
  await user.click(label);
  
  expect(onFocus).toHaveBeenCalledTimes(1);
});
packages/components/switch/src/use-switch.ts (1)

181-189: LGTM! Consider adding JSDoc comment.

The mouseProps implementation correctly prevents parent focus. Consider adding a JSDoc comment to document the purpose of this handler for future maintainers.

 const mouseProps = useMemo(
   () => ({
+    /**
+     * Prevents parent element from receiving focus when the switch is clicked.
+     * This fixes the issue of multiple focus events being triggered.
+     */
     onMouseDown: (e: React.MouseEvent<HTMLLabelElement>) => {
       // prevent parent from being focused
       e.preventDefault();
packages/components/checkbox/src/use-checkbox.ts (2)

267-275: LGTM! Consider adding JSDoc comment.

The mouseProps implementation correctly prevents parent focus. Consider adding a JSDoc comment to document the purpose of this handler for future maintainers.

 const mouseProps = useMemo(
   () => ({
+    /**
+     * Prevents parent element from receiving focus when the checkbox is clicked.
+     * This fixes the issue of multiple focus events being triggered.
+     */
     onMouseDown: (e: React.MouseEvent<HTMLLabelElement>) => {
       // prevent parent from being focused
       e.preventDefault();

Line range hint 290-303: Add mouseProps to useCallback dependencies.

The mouseProps object is used in getBaseProps but not included in its dependencies array. This could lead to stale closures.

   }, [
     slots,
     baseStyles,
     isDisabled,
     isSelected,
     isIndeterminate,
     isInvalid,
     isHovered,
     isFocused,
     pressed,
     inputProps.readOnly,
     isFocusVisible,
     hoverProps,
+    mouseProps,
     otherProps,
   ]);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a50aa3e and 20d8d90.

📒 Files selected for processing (7)
  • .changeset/tricky-panthers-build.md (1 hunks)
  • packages/components/checkbox/__tests__/checkbox.test.tsx (1 hunks)
  • packages/components/checkbox/src/use-checkbox.ts (2 hunks)
  • packages/components/radio/__tests__/radio.test.tsx (1 hunks)
  • packages/components/radio/src/use-radio.ts (2 hunks)
  • packages/components/switch/__tests__/switch.test.tsx (1 hunks)
  • packages/components/switch/src/use-switch.ts (1 hunks)
🔇 Additional comments (3)
packages/components/radio/src/use-radio.ts (1)

179-179: LGTM! Props merging looks correct

The mouseProps are correctly merged with other props using mergeProps utility.

packages/components/checkbox/__tests__/checkbox.test.tsx (1)

93-107: LGTM! Well-structured test case.

The test effectively verifies that focus is triggered only once on the parent element when the checkbox is clicked, directly addressing the issue described in the PR objectives.

packages/components/radio/__tests__/radio.test.tsx (1)

145-163: LGTM! Test case effectively validates the focus handling fix.

The test case properly verifies that clicking a Radio component within a focusable parent triggers the focus event exactly once, which directly addresses the issue described in PR #4260.

A few positive observations about the test implementation:

  1. Clear test setup with isolated focus event tracking
  2. Proper use of async/await for user interactions
  3. Precise assertion checking focus event count

@wingkwong wingkwong added this to the v2.6.5 milestone Dec 8, 2024
@wingkwong wingkwong changed the title fix(checkbox, radio, switch): prevent multiple parent focus events on click fix: prevent multiple parent focus events on click Dec 8, 2024
@macci001
Copy link
Contributor

macci001 commented Dec 9, 2024

Hey @Peterl561, thanks a lot for fixing the issue.
The PR looks good to me.

@macci001
Copy link
Contributor

Handling this issue in #4306

@wingkwong wingkwong modified the milestones: v2.6.6, v2.6.7, v2.6.8, v2.6.9 Dec 10, 2024
@wingkwong
Copy link
Member

closing - fixed in #4311

@wingkwong wingkwong closed this Dec 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] - Switch inside of CardBody shows blue outline on toggle
4 participants