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(select): add isClearable #3746

Conversation

abhinav700
Copy link
Contributor

@abhinav700 abhinav700 commented Sep 13, 2024

Closes #2239

📝 Description

Added clear button functionality to select component.
Screenshot from 2024-09-13 18-02-21
Screenshot from 2024-09-13 18-02-11
Screenshot from 2024-09-13 18-01-17

Summary by CodeRabbit

  • New Features

    • Introduced a selection component for choosing favorite animals with a clearable feature.
    • Added a PetBoldIcon component to enhance the dropdown menu.
    • Users can now reset their selection easily with the clearable functionality.
    • Documentation updated to include the new isClearable property and onClear event handler for the Select component.
  • Bug Fixes

    • Enhanced the styling and responsiveness of the clear button across different component sizes.

Copy link

changeset-bot bot commented Sep 13, 2024

🦋 Changeset detected

Latest commit: c221d07

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/theme 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 Sep 13, 2024

@abhinav700 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 Sep 13, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review (5)
  • main
  • canary
  • fix/.*
  • chore/.*
  • feat/.*

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

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

Walkthrough

The pull request introduces a new module for a selection component that allows users to choose their favorite animals, featuring a clearable option. It exports a list of animal objects, a PetBoldIcon component for rendering an SVG icon, and an App component that utilizes these elements. The Select component is configured to be clearable, enabling users to reset their selection, with a console log triggered upon clearing. The overall structure is organized into a single export object that includes the App, data, and PetBoldIcon components.

Changes

Files Change Summary
apps/docs/content/components/select/is-clearable.ts Introduced a selection component for favorite animals with a clearable feature, including animal objects and an SVG icon.
apps/docs/content/docs/components/select.mdx Added documentation for the isClearable property and onClear event handler for the Select component.
packages/components/select/package.json Updated peer dependency version for @nextui-org/theme from >=2.1.0 to >=2.3.0.
packages/components/select/src/use-select.ts Enhanced use-select functionality with onClear callback and clear button properties.
packages/components/select/stories/select.stories.tsx Added a new story for the Select component demonstrating the clearable functionality.
packages/components/select/src/select.tsx Modified Select component to include isClearable prop and conditional rendering for the clear button.

Assessment against linked issues

Objective Addressed Explanation
Add isClearable option for Select (#2239)
Allow users to clear selection easily (#2239)
Provide a way to handle clear action (#2239)

Possibly related PRs

Suggested reviewers

  • 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.

@wingkwong wingkwong added this to the v2.5.0 milestone Sep 13, 2024
@wingkwong wingkwong changed the title feat: Adding `is clearable to select feat(select): add isClearable Sep 13, 2024
@abhinav700
Copy link
Contributor Author

@wingkwong for the tests that are failing, I don't think they are related to the changes that I have made.

When I tried to run the tests on the canary branch( which is in sync and I have pulled those changes locally), the same tests are failing there also even though I have not made any changes to it.

Copy link

vercel bot commented Sep 29, 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 Nov 29, 2024 6:09am
nextui-storybook-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 29, 2024 6:09am

packages/components/select/src/select.tsx Outdated Show resolved Hide resolved
packages/components/select/src/select.tsx Outdated Show resolved Hide resolved
packages/components/select/src/use-select.ts Outdated Show resolved Hide resolved
packages/core/theme/src/components/select.ts 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: 0

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

57-65: Approve implementation with a suggestion for clarity.

The clear button implementation looks good overall. The use of useMemo for performance optimization and the conditional rendering logic are correct. However, there's a potential confusion in the usage of endContent.

Consider separating the clear button content from endContent to avoid confusion. You could introduce a new prop like clearButtonContent for customizing the clear button. This would make the API more explicit:

const clearButton = useMemo(() => {
  if (isClearable && state.selectedItems?.length) {
    return (
      <span {...getClearButtonProps()}>
        {clearButtonContent || <CloseFilledIcon />}
      </span>
    );
  }
  return null;
}, [isClearable, getClearButtonProps, state, clearButtonContent]);

This change would allow users to customize both the clear button and the end content independently.


142-148: Approve changes with a suggestion for comment improvement.

The modifications to the component's return statement are correct. The conditional rendering of endContent and the placement of the clearButton are appropriate.

The comment explaining the endContent display is helpful, but it could be more concise and grammatically correct. Consider revising it as follows:

{/**
 * Display endContent separately only when not showing the clear button.
 * Otherwise, use it as the clear button.
 */}

This revision maintains the explanation while improving readability.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 179b530 and 5635e4f.

📒 Files selected for processing (1)
  • packages/components/select/src/select.tsx (4 hunks)
🔇 Additional comments (3)
packages/components/select/src/select.tsx (3)

3-3: LGTM: Import for clear button icon added.

The import for CloseFilledIcon is correctly added, which will be used for the new clear button functionality.


33-33: LGTM: New props for clear button functionality added.

The isClearable and getClearButtonProps props have been correctly added to the Select component. These are essential for implementing the new clear button functionality as requested in issue #2239.

Also applies to: 35-35


Line range hint 1-156: Verify implementation against PR objectives.

The implementation successfully meets the objectives stated in the PR summary and issue #2239:

  1. The isClearable option has been added to the Select component.
  2. Users can now easily clear their selection with a clear button.
  3. The implementation is similar to the Autocomplete component's functionality.
  4. This solution is more efficient than using endContent with a button.

The changes are focused on this single feature enhancement, adhering to the guidelines for submitting a pull request.

To ensure the implementation works as expected across the codebase, please run the following verification script:

This script will help identify any places where the new isClearable prop is being used and check for any remaining TODO comments related to clear functionality in Select components.

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 (3)
packages/components/select/src/use-select.ts (3)

81-83: Clarify the documentation for the endContent prop

Consider rephrasing the comment for better clarity.

Apply the following diff to improve the comment:

       * Element to be rendered in the right side of the select.
-      * if you pass this prop and the `onClear` prop, the passed element
-      * will have the clear button props and it will be rendered instead of the
-      * default clear button.
+      * If `onClear` is provided and an element is passed to this prop,
+      * the element will receive the clear button props and replace the default clear button.

140-141: Improve documentation consistency

Capitalize the first word in the sentence for consistency.

Apply the following diff:

       * Callback fired when the value is cleared.
-      * if you pass this prop, the clear button will be shown.
+      * If you pass this prop, the clear button will be shown.

313-316: Simplify boolean conversion

The use of !! may be unnecessary since originalProps.isDisabled is already a boolean or undefined.

Apply the following diff:

 const {pressProps: clearPressProps} = usePress({
-        isDisabled: !!originalProps?.isDisabled,
+        isDisabled: originalProps?.isDisabled,
         onPress: handleClear,
       });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5635e4f and e7f481e.

📒 Files selected for processing (3)
  • apps/docs/content/docs/components/select.mdx (3 hunks)
  • packages/components/select/src/use-select.ts (10 hunks)
  • packages/core/theme/src/components/select.ts (4 hunks)
🧰 Additional context used
🪛 LanguageTool
apps/docs/content/docs/components/select.mdx

[grammar] ~153-~153: There appears to be a superfluous article here.
Context: ... button which will be visible only when the some value is selected. A default clear butt...

(THE_SOME)

🔇 Additional comments (13)
apps/docs/content/docs/components/select.mdx (2)

393-393: LGTM: New isClearable property documented

The isClearable property has been correctly added to the Select Props table. The description is clear and concise, and the default value is accurately specified.

This addition ensures that the API documentation is up-to-date with the new feature.


414-414: LGTM: New onClear event documented

The onClear event has been correctly added to the Select Events table. The description clearly explains when the event is triggered.

This addition completes the documentation for the new Clear Button feature, providing developers with the necessary information to implement and handle the clear functionality.

packages/core/theme/src/components/select.ts (4)

31-47: Addition of clearButton slot enhances functionality

The new clearButton slot is well-defined, and the classes applied are consistent with existing styles. This improves the select component by providing users with the ability to clear selections easily.


122-132: clearButton size variants are appropriately set

The clearButton sizes for sm, md, and lg variants are defined, matching the expected sizing conventions of the component.


170-175: isClearable variant implements clearable functionality correctly

The isClearable variant correctly adjusts the input and clearButton styles based on the state of the input, enabling users to clear their selections when the input is filled.


222-222: Consistent animation handling for clearButton

Including the transition-opacity and motion-reduce:transition-none classes for the clearButton ensures consistent animation behavior with other interactive elements.

packages/components/select/src/use-select.ts (7)

20-20: LGTM!

The added imports are necessary for the new functionality.


308-311: LGTM!

The handleClear function correctly handles clearing the selection and invoking onClear.


323-323: LGTM!

Using useFocusRing to manage focus visibility for the clear button is appropriate.


341-341: LGTM!

The isClearable flag correctly determines if the select is clearable.


360-372: LGTM!

Dependencies are correctly listed for the useMemo hook.


700-700: LGTM!

Returning isClearable in the hook's return object.


719-719: LGTM!

Exposing getClearButtonProps method in the hook's return object.

apps/docs/content/docs/components/select.mdx 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: 2

🧹 Outside diff range and nitpick comments (7)
apps/docs/content/components/select/isClearable.ts (2)

17-49: LGTM: Well-implemented icon component with a minor suggestion

The PetBoldIcon component is well-structured, reusable, and follows React best practices. It includes important accessibility attributes and uses currentColor for easy styling.

Consider adding a displayName to the component for easier debugging:

PetBoldIcon.displayName = 'PetBoldIcon';

51-72: LGTM: Well-implemented Select component with isClearable functionality

The App component effectively demonstrates the use of the isClearable prop on the Select component. The implementation is clean, follows React best practices, and correctly uses the animals data and PetBoldIcon.

Consider adding an onClear handler to demonstrate how to respond to clear events:

const handleClear = () => {
  console.log('Selection cleared');
  // Add any additional logic here
};

<Select
  // ... other props
  isClearable={true}
  onClear={handleClear}
>
  {/* ... SelectItems */}
</Select>

This addition would provide a more comprehensive example of the isClearable functionality.

packages/components/select/stories/select.stories.tsx (1)

1009-1017: Consider the placement of the new "Clearable" story within the file.

The new "Clearable" story is currently placed at the end of the file. While this is a valid location, you might want to consider placing it closer to related stories (e.g., near other stories that demonstrate core functionalities of the Select component) for better discoverability and logical grouping.

Consider moving the "Clearable" story to a more appropriate location within the file, such as after the "Default" or "Multiple" stories, to improve the overall organization of the stories.

packages/components/select/src/select.tsx (1)

66-77: Ensure consistent styling for 'endContent' with and without 'clearButton'

When clearButton is present, endContent is wrapped in a <span> with class ms-3 inside a <div> with classes flex end-18. When clearButton is not present, endContent is wrapped in a <span> with class mb-4. This could lead to inconsistent styling or alignment of endContent depending on whether the clearButton is shown. Consider making the styling consistent in both cases.

packages/core/theme/src/components/select.ts (1)

123-123: Consider adjusting clearButton text size for large variant

The clearButton uses text-large for both md and lg sizes. To maintain proportional scaling, consider using text-xl for the lg size variant to better reflect the larger size.

Apply this diff to adjust the clearButton text size for the lg variant:

 def select = tv({
   variants: {
     size: {
       sm: {
         // ...
         clearButton: "text-medium",
       },
       md: {
         // ...
         clearButton: "text-large",
       },
       lg: {
         // ...
-        clearButton: "text-large",
+        clearButton: "text-xl",
       },
     },
     // ...
   },
   // ...
 });

Also applies to: 128-128, 133-133

packages/components/select/src/use-select.ts (2)

81-83: Clarify the endContent prop documentation

To improve readability, consider rephrasing the documentation for clarity.

Apply this diff to rephrase the comment:

 /**
  * Element to be rendered in the right side of the select.
- * if you pass this prop and the `onClear` prop, the passed element
- * will have the clear button props and it will be rendered instead of the
- * default clear button.
+ * If both `endContent` and `onClear` props are provided, the `endContent`
+ * element will receive the clear button props and will be rendered
+ * instead of the default clear button.
  */

139-143: Capitalize the first word in the documentation comment

To maintain consistency, capitalize the first word in the documentation comment.

Apply this diff to fix the capitalization:

  /**
   * Callback fired when the value is cleared.
-  * if you pass this prop, the clear button will be shown.
+  * If you pass this prop, the clear button will be shown.
   */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e7f481e and 5d112ac.

📒 Files selected for processing (6)
  • apps/docs/content/components/select/isClearable.ts (1 hunks)
  • apps/docs/content/docs/components/select.mdx (3 hunks)
  • packages/components/select/src/select.tsx (4 hunks)
  • packages/components/select/src/use-select.ts (10 hunks)
  • packages/components/select/stories/select.stories.tsx (1 hunks)
  • packages/core/theme/src/components/select.ts (4 hunks)
🧰 Additional context used
🪛 GitHub Check: ESLint
packages/components/select/src/select.tsx

[warning] 32-32:
'isOutsideLeft' is assigned a value but never used

🔇 Additional comments (22)
apps/docs/content/components/select/isClearable.ts (2)

1-15: LGTM: Well-structured data for the Select component

The animals array is well-defined with unique keys and descriptive labels, making it suitable for use with the Select component. The export statement is correct, allowing easy import in other parts of the application.


74-82: LGTM: Correct export structure

The export statement is well-structured, allowing for easy import of all components and data in other parts of the application. The use of the spread operator to include all properties from the react object is correct and follows modern JavaScript practices.

packages/components/select/stories/select.stories.tsx (2)

1009-1017: LGTM! New "Clearable" story added successfully.

The new "Clearable" story effectively demonstrates the isClearable functionality, which aligns with the PR objectives. A few observations:

  1. The isClearable prop is correctly set to true.
  2. The endContent prop is used to add a PetBoldIcon, which is a nice touch for visual representation.
  3. The story uses the Template render function, maintaining consistency with other stories.

This addition will be helpful for developers to understand and test the new clearable feature.


Line range hint 1-1017: Overall, the changes effectively implement the new clearable functionality.

The addition of the "Clearable" story successfully demonstrates the new isClearable prop for the Select component. This implementation aligns well with the PR objectives and provides a valuable example for developers using the component.

Key points:

  1. The new story correctly showcases the isClearable prop.
  2. The use of endContent with PetBoldIcon provides a visual cue for the clearable functionality.
  3. The implementation is consistent with other stories in the file.

Suggestions for further improvement have been made, including demonstrating the onClear event handler and considering the story's placement within the file. These enhancements would provide a more comprehensive example of the new functionality and improve the overall organization of the stories.

apps/docs/content/docs/components/select.mdx (3)

151-155: New "Clear Button" section added successfully

The new section effectively documents the isClearable property, explaining its functionality and when the clear button becomes visible. The inclusion of a code demo (isClearable) is helpful for users to understand the implementation.


392-392: API documentation updated with isClearable property

The isClearable property has been correctly added to the Select Props table. The type, description, and default value are accurately documented, maintaining consistency with the existing table format.


413-413: API documentation updated with onClear event

The onClear event has been properly added to the Select Events table. The type and description are accurately documented, providing clear information about when the event handler is called. This addition maintains consistency with the existing table format.

packages/components/select/src/select.tsx (3)

3-3: Importing CloseFilledIcon for clear button functionality

The addition of CloseFilledIcon to the imports is appropriate for implementing the clearable feature.


33-33: Addition of 'isClearable' prop

The isClearable prop is correctly added and will enable the clear button functionality.


58-64: Implementation of clear button logic

The clearButton is correctly implemented using useMemo, and the conditions ensure it appears only when isClearable is true and there are selected items.

packages/core/theme/src/components/select.ts (3)

32-48: clearButton slot implementation looks good

The addition of the clearButton slot with appropriate utility classes ensures consistent styling and functionality across the component.


174-178: isClearable variant added correctly

The introduction of the isClearable variant effectively manages the visibility and opacity of the clearButton based on the component's state, enhancing the user experience.


226-226: Appropriate animation settings for clearButton

Adding transition-opacity and motion-reduce:transition-none to the clearButton under the disableAnimation: false variant ensures smooth transitions while respecting user preferences for reduced motion.

packages/components/select/src/use-select.ts (9)

20-20: Import of usePress is appropriate

The import of usePress from @react-aria/interactions is necessary for the clear button functionality.


198-198: Destructuring of onClear is appropriate

Including onClear in the destructured props is necessary for the clear button functionality.


308-317: Implementation of handleClear function is correct

The handleClear function appropriately clears the selection and invokes the onClear callback.


323-324: Use of useFocusRing for clear button focus management is appropriate

The focus management for the clear button is correctly implemented using useFocusRing.


341-341: Assignment of isClearable prop is correct

The isClearable prop is properly assigned from originalProps.


360-360: Including isClearable in useMemo dependencies is appropriate

Including isClearable in the useMemo dependencies ensures that styles are recalculated when this prop changes.

Also applies to: 365-372


667-682: Implementation of getClearButtonProps follows accessibility guidelines

The getClearButtonProps function correctly sets accessibility attributes and manages focus for the clear button.


700-700: Including isClearable in the returned object is appropriate

Adding isClearable to the returned object from useSelect makes it available for consumer components.


719-719: Including getClearButtonProps in the returned object is appropriate

Exposing getClearButtonProps allows consumer components to access clear button properties.

packages/components/select/stories/select.stories.tsx Outdated Show resolved Hide resolved
packages/components/select/src/select.tsx Outdated Show resolved Hide resolved
@abhinav700 abhinav700 requested a review from wingkwong October 12, 2024 14:35
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.

since clearButton in select theme is introduced, please also update the min theme version in peerDependencies in select package.json.

packages/components/select/stories/select.stories.tsx Outdated Show resolved Hide resolved
packages/components/select/src/select.tsx Outdated Show resolved Hide resolved
apps/docs/content/components/select/isClearable.ts Outdated Show resolved Hide resolved
.changeset/olive-buckets-own.md Outdated Show resolved Hide resolved
.changeset/olive-buckets-own.md Outdated Show resolved Hide resolved
@wingkwong wingkwong assigned ryo-manba and unassigned wingkwong Oct 29, 2024
@wingkwong wingkwong requested a review from ryo-manba October 29, 2024 12:06
@wingkwong wingkwong changed the base branch from canary to beta/release-next November 23, 2024 13:13
@wingkwong
Copy link
Member

mark it on hold until the doc structure revamp pr got merged to beta branch

@abhinav700
Copy link
Contributor Author

ok

@abhinav700 abhinav700 force-pushed the adding-isClearable-to-select branch from 5e2bdbc to 0684bff Compare November 25, 2024 05:46
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.

[Feature Request] Add isClearable for Select
4 participants