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: accordion item focus effect input focus event #4201

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

Conversation

chioio
Copy link

@chioio chioio commented Dec 1, 2024

📝 Description

Fix: input focus error when using in accordion with selected/default expand keys on page loaded.

Mini-reproduction: nextui-input-focus-error

⛳️ Current behavior (updates)

Add onClick, onFocus event in accordion item content render.

🚀 New behavior

Input component focus behavior normal in accordion component with selected/default expand keys

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

No

📝 Additional Information

Nothing!

Summary by CodeRabbit

  • New Features
    • Enhanced event control in the Accordion component, improving user interaction by preventing unintended parent event triggers when the accordion content is open.
  • Tests
    • Added a new test case to ensure the input field within a default expanded accordion item receives focus correctly upon rendering.

Copy link

changeset-bot bot commented Dec 1, 2024

⚠️ No Changeset found

Latest commit: fd0f585

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

vercel bot commented Dec 1, 2024

@chioio 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 1, 2024

Walkthrough

The changes in this pull request focus on the AccordionItem component within the accordion-item.tsx file. Two new event handlers, onClick and onFocus, have been added to the <m.section> element inside the AnimatePresence block. These handlers utilize e.stopPropagation() to prevent event bubbling, thereby enhancing control over event propagation when the accordion content is open. Additionally, a new test case has been introduced to verify the focus behavior of an input field within a default expanded accordion item.

Changes

File Path Change Summary
packages/components/accordion/src/accordion-item.tsx Added onClick and onFocus event handlers to <m.section> to prevent event bubbling.
packages/components/accordion/tests/accordion.test.tsx Added a new test case to check that an input inside a default expanded accordion item receives focus correctly.

Possibly related PRs

Suggested reviewers

  • wingkwong
  • ryo-manba
  • 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 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: 0

🧹 Outside diff range and nitpick comments (1)
packages/components/accordion/src/accordion-item.tsx (1)

93-98: Consider centralizing event handling logic

The event handling pattern with stopPropagation() is repeated across multiple handlers. Consider extracting this into a utility function for better maintainability.

+ const stopEventPropagation = (e: React.SyntheticEvent) => {
+   e.stopPropagation();
+ };
+
  <m.section
    key="accordion-content"
    animate="enter"
    exit="exit"
    initial="exit"
    style={{willChange}}
    variants={transitionVariants}
-   onClick={(e) => {
-     e.stopPropagation();
-   }}
-   onFocus={(e) => {
-     e.stopPropagation();
-   }}
-   onKeyDown={(e) => {
-     e.stopPropagation();
-   }}
+   onClick={stopEventPropagation}
+   onFocus={stopEventPropagation}
+   onKeyDown={stopEventPropagation}
    {...motionProps}
  >
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1c46061 and 514f9b6.

📒 Files selected for processing (1)
  • packages/components/accordion/src/accordion-item.tsx (1 hunks)
🔇 Additional comments (1)
packages/components/accordion/src/accordion-item.tsx (1)

93-98: LGTM! The event handler additions effectively address the input focus issue.

The addition of onClick and onFocus handlers with stopPropagation() aligns well with the existing pattern and should resolve the input focus errors within accordion items.

Let's verify if there are any other event-dependent components within accordions:

✅ Verification successful

The event handler additions are safe and consistent with existing patterns

The verification shows that:

  • The new onClick and onFocus handlers with stopPropagation() are consistent with the existing event handling pattern in the accordion component
  • The same stopPropagation() approach is already used in other event handlers within the same component
  • There are no conflicting event handling patterns in the related hook packages
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for interactive elements (inputs, buttons, etc.) within accordion components
rg -l "AccordionItem" | xargs rg -l "input|button|select|textarea"

# Search for any existing event handlers in accordion-related files
ast-grep --pattern 'onClick={$_} | onFocus={$_} | onBlur={$_}'

Length of output: 1006


Script:

#!/bin/bash
# Let's examine the event handling patterns in accordion-related files more closely
rg -A 3 -B 3 "onClick=|onFocus=|onBlur=" packages/components/accordion/src/
rg -A 3 -B 3 "onClick=|onFocus=|onBlur=" packages/hooks/use-aria-accordion

# Also check for any existing event propagation patterns
rg "stopPropagation" packages/components/accordion/src/
rg "stopPropagation" packages/hooks/use-aria-accordion

Length of output: 1465

@jrgarciadev
Copy link
Member

@wingkwong @ryo-manba please review

Copy link
Member

@wingkwong wingkwong left a comment

Choose a reason for hiding this comment

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

  1. please add a changeset
  2. please add a test
  3. please elaborate the issue more. I'm not sure what you're trying to fix here. The before & after look the same to me with the given sandbox.

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

🧹 Outside diff range and nitpick comments (2)
packages/components/accordion/__tests__/accordion.test.tsx (2)

360-364: Improve type safety and query method

The current implementation uses querySelector and non-null assertion (!), which could be replaced with more type-safe and semantic Testing Library queries.

-    const input = wrapper.container.querySelector("input");
-
-    expect(input).not.toBeNull();
-
-    await user.click(input!);
+    const input = wrapper.getByRole('textbox', { name: 'name' });
+    await user.click(input);

349-367: Test coverage could be more comprehensive

The test verifies basic focus behavior but doesn't explicitly test the bug fix mentioned in the PR (event propagation). Consider adding additional assertions to verify that:

  1. Focus events don't propagate to parent elements
  2. The accordion doesn't collapse when clicking the input

Here's a suggested enhancement:

it("should handle input focus without triggering accordion collapse", async () => {
  const onSelectionChange = jest.fn();
  
  const wrapper = render(
    <Accordion defaultExpandedKeys={["1"]} onSelectionChange={onSelectionChange}>
      <AccordionItem key="1" title="Accordion Item 1">
        <Input label="name" type="text" />
      </AccordionItem>
    </Accordion>
  );

  const input = wrapper.getByRole('textbox', { name: 'name' });
  await user.click(input);
  
  expect(input).toHaveFocus();
  expect(onSelectionChange).not.toHaveBeenCalled();
  expect(wrapper.getByRole('button')).toHaveAttribute('aria-expanded', 'true');
});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 514f9b6 and fd0f585.

📒 Files selected for processing (1)
  • packages/components/accordion/__tests__/accordion.test.tsx (1 hunks)

@chioio
Copy link
Author

chioio commented Dec 3, 2024

  1. please add a changeset
  2. please add a test
  3. please elaborate the issue more. I'm not sure what you're trying to fix here. The before & after look the same to me with the given sandbox.

Test, changeset added, please review. @wingkwong

I resolved it in my project by using a pnpm patch to add the code.

@chioio chioio requested a review from wingkwong December 3, 2024 06:20
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)
.changeset/short-bulldogs-divide.md (1)

1-5: Consider enhancing the changeset description

While the changeset is correctly structured with the appropriate patch version bump, the description could be more detailed to help users and maintainers understand:

  • The specific issue that was occurring with input focus
  • Why adding onClick and onFocus handlers resolves the issue
  • The impact on users who were experiencing this bug

Here's a suggested enhancement:

---
"@nextui-org/accordion": patch
---

-Fix input focus error in default expanded accordion item, add `onClick`, `onFocus` to `AccordionItem` content wrapper
+Fix input focus error in default expanded accordion items where inputs would not receive focus correctly on page load. Added `onClick` and `onFocus` event handlers to the `AccordionItem` content wrapper to prevent event propagation and ensure proper focus behavior. This improves the user experience when using form inputs within pre-expanded accordion sections.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fd0f585 and 40eaad1.

📒 Files selected for processing (1)
  • .changeset/short-bulldogs-divide.md (1 hunks)

Copy link
Member

@wingkwong wingkwong left a comment

Choose a reason for hiding this comment

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

With such change, the keyboard navigation will be broken (e.g. space / enter won't open accordion).

</Accordion>,
);

await new Promise((resolve) => setTimeout(resolve, 100));
Copy link
Member

Choose a reason for hiding this comment

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

not required


it("should focus input inside default expanded accordion item correctly", async () => {
const wrapper = render(
<Accordion selectedKeys={["1"]}>
Copy link
Member

Choose a reason for hiding this comment

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

if it's default expanded, then you should use defaultExpandedKeys

Comment on lines +93 to +98
onClick={(e) => {
e.stopPropagation();
}}
onFocus={(e) => {
e.stopPropagation();
}}
Copy link
Member

Choose a reason for hiding this comment

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

There's another case that need to cover. See L67.

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.

3 participants