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(select): prevent default browser error UI from appearing #4281

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

Conversation

chirokas
Copy link
Contributor

@chirokas chirokas commented Dec 8, 2024

Closes #3913
Original: #3984

📝 Description

See #3913 (comment)

⛳️ Current behavior (updates)

🚀 New behavior

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

📝 Additional Information

Summary by CodeRabbit

  • New Features

    • Enhanced validation capabilities for the Select component, including support for required fields and custom validation functions.
    • Server-side validation support for displaying error messages based on external conditions.
  • Bug Fixes

    • Fixed an issue to prevent the default browser error UI from appearing, improving error handling within the application.
  • Tests

    • Added comprehensive tests for validation behaviors, user interactions, and integration with form submissions for the Select component.
  • Chores

    • Updated internal logic for validation handling in the multi-select component to streamline user interactions.

@chirokas chirokas requested a review from jrgarciadev as a code owner December 8, 2024 11:58
Copy link

changeset-bot bot commented Dec 8, 2024

🦋 Changeset detected

Latest commit: f02168d

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

This PR includes changesets to release 3 packages
Name Type
@nextui-org/select Patch
@nextui-org/use-aria-multiselect 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 8, 2024 0:15am
nextui-storybook-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 8, 2024 0:15am

Copy link

vercel bot commented Dec 8, 2024

@chirokas 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

Walkthrough

This pull request introduces updates to the @nextui-org/select and @nextui-org/use-aria-multiselect dependencies, enhancing error handling to prevent the default browser error UI from appearing. The Select component receives new validation behaviors and properties, improving its interaction with forms and validation states. Additionally, the HiddenSelect component is modified for better state handling and accessibility. Changes to the useMultiSelectState function refine validation logic during selection changes, ensuring a more controlled validation process.

Changes

File Change Summary
.changeset/quick-buses-kick.md Patches for @nextui-org/select and @nextui-org/use-aria-multiselect, fix for default browser error UI (issue #3913).
packages/components/select/tests/select.test.tsx Enhancements and tests for Select component, added validationBehavior, isRequired, and validate props, expanded tests for validation behaviors, server-side validation, and form integration. Updated method signatures for onSelectionChange and renderValue.
packages/components/select/src/hidden-select.tsx Modifications to HiddenSelect component, including updates to inputProps and selectProps, added disabled property, removed value property, and updated onChange handler. Method signatures for useHiddenSelect and HiddenSelect updated.
packages/hooks/use-aria-multiselect/src/use-multiselect-state.ts Changes to useMultiSelectState, added validationState.commitValidation() to onSelectionChange, removed it from toggle method. Internal logic refined for validation handling during selection changes.

Possibly related PRs

Suggested labels

📋 Scope : Docs, 👀 Status: To 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 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: 1

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

1473-1481: Use const instead of let for variables that are not reassigned

In line 1473, let {getByTestId} = render(...) should be declared with const since getByTestId is not reassigned within the scope.

Apply the following diff to improve code consistency:

- let {getByTestId} = render(
+ const {getByTestId} = render(
packages/components/select/src/hidden-select.tsx (1)

Line range hint 106-122: Incorrect handling of multiple selections in <select> element

When selectionMode is "multiple", setting the value prop to an array ([...state.selectedKeys].map((k) => String(k))) is not standard for native HTML <select> elements. The value attribute expects a string, and for multiple selections, each <option> should have a selected attribute if it is selected.

Additionally, in the onChange handler, e.target.value returns a string for single selections. For multiple selections, you need to use e.target.selectedOptions to retrieve all selected values.

Please update the code to correctly handle multiple selections:

  • Instead of setting value in selectProps, add the selected attribute to each <option> element based on whether its value is in state.selectedKeys:

    <option
      key={item.key}
      value={item.key}
      selected={state.selectedKeys.has(item.key)}
    >
      {item.textValue}
    </option>
  • Modify the onChange handler to handle multiple selections:

    - onChange: (e: React.ChangeEvent<HTMLSelectElement>) => {
    -   state.setSelectedKeys(e.target.value);
    -   onChange?.(e);
    - },
    + onChange: (e: React.ChangeEvent<HTMLSelectElement>) => {
    +   if (selectionMode === "multiple") {
    +     const selectedValues = Array.from(e.target.selectedOptions).map((option) => option.value);
    +     state.setSelectedKeys(new Set(selectedValues));
    +   } else {
    +     state.setSelectedKeys(new Set([e.target.value]));
    +   }
    +   onChange?.(e);
    + },

This ensures that the hidden <select> element accurately reflects the selected values and that the form submission works correctly with multiple selections.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 26b33a5 and f02168d.

📒 Files selected for processing (4)
  • .changeset/quick-buses-kick.md (1 hunks)
  • packages/components/select/__tests__/select.test.tsx (5 hunks)
  • packages/components/select/src/hidden-select.tsx (1 hunks)
  • packages/hooks/use-aria-multiselect/src/use-multiselect-state.ts (1 hunks)
🔇 Additional comments (3)
packages/components/select/__tests__/select.test.tsx (2)

1182-1355: Tests for validationBehavior="native" are comprehensive and well-implemented

The test cases effectively cover scenarios for:

  • Required field validation (isRequired)
  • Custom validation functions (validate)
  • Server-side validation handling
  • Clearing validation state on form reset

These tests ensure that the Select component behaves correctly under native validation behavior.


Line range hint 1401-1493: Tests for validationBehavior="aria" are thorough and correctly handle validation states

The test cases appropriately handle:

  • Required field validation with custom server errors
  • Custom validation functions with ARIA validation behavior
  • Server-side validation handling and clearing of validation messages upon user action

The implementation ensures that the Select component provides accessible validation feedback when using ARIA validation behaviors.

.changeset/quick-buses-kick.md (1)

1-6: Changeset is correctly formatted and includes appropriate summary

The changeset properly specifies patch updates for @nextui-org/select and @nextui-org/use-aria-multiselect. The summary message clearly states the purpose of the changes, addressing issue #3913.

@@ -87,6 +87,8 @@ export function useMultiSelectState<T extends object>({
if (props.selectionMode === "single") {
triggerState.close();
}

validationState.commitValidation();
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

Potential reference error: validationState is used before it is defined

The call to validationState.commitValidation() inside onSelectionChange may cause a runtime error because validationState is declared after listState. Since validationState is not yet initialized when onSelectionChange is created, it will be undefined at the time of the function's execution.

To resolve this issue, consider initializing validationState before listState, or restructure the code so that validationState is accessible within onSelectionChange without causing a reference error.

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.

[BUG] - Add validationBehavior support for Select
1 participant