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: label placement when the select has a placeholder or description #4125

Conversation

tianenpang
Copy link
Member

@tianenpang tianenpang commented Nov 20, 2024

Closes #

📝 Description

Fixed label placement when the Select has a placeholder or description.

⛳️ Current behavior (updates)

Corrected the rendering position and elements nesting.

🚀 New behavior

Updated the conditions for shouldLabelBeOutside.

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

No.

📝 Additional Information

Related to PR#3853.

Before

before

After

after

Summary by CodeRabbit

Release Notes

  • New Features

    • Improved label placement for the Select component when using placeholders or descriptions.
    • Added support for multiline labels in the Select component.
  • Bug Fixes

    • Enhanced responsiveness of the popover position based on selected items.
  • Documentation

    • Updated storybook with new templates showcasing the Select component with descriptions and placeholders for better user context.

wingkwong and others added 4 commits November 11, 2024 15:00
* fix(use-image): image ReferenceError in SSR

* fix(use-image): sync with beta

* fix(use-image): sync with beta

* chore(use-image): remove unnecessary comments
* fix(docs): routing.mdx

* Delete .changeset/pre.json
Copy link

changeset-bot bot commented Nov 20, 2024

🦋 Changeset detected

Latest commit: 95728e6

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/select 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 Nov 20, 2024

@tianenpang 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 Nov 20, 2024

Walkthrough

This pull request introduces a patch for the @nextui-org/select package, focusing on improving label placement in the Select component when a placeholder or description is present. The changes include updates to the useSelect function to refine label positioning logic, adjustments to the test suite to account for the new multiline label feature, and enhancements to storybook templates to demonstrate the new functionality.

Changes

File Path Change Summary
.changeset/odd-tomatoes-call.md Introduced a patch for the @nextui-org/select package to fix label placement issues with placeholder or description.
packages/components/select/tests/select.test.tsx Updated tests for the Select component to include conditions for the isMultiline prop and enhanced test coverage.
packages/components/select/src/use-select.ts Modified useSelect function for improved label placement logic and updated popover behavior based on selected items.
packages/components/select/stories/select.stories.tsx Added new templates and descriptions for Select components in storybook, enhancing contextual information.

Possibly related PRs

Suggested labels

👀 Status: In Review, 📋 Scope : Docs

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.

@jrgarciadev jrgarciadev changed the base branch from canary to beta/release-next November 20, 2024 19:29
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/use-select.ts (1)

317-318: Consider extracting label placement logic for better maintainability

The label placement condition could be more maintainable if extracted into a separate function.

Consider refactoring like this:

+const shouldPlaceLabelOutside = ({
+  labelPlacement,
+  hasPlaceholder,
+  description,
+  isMultiline,
+}: {
+  labelPlacement: SelectVariantProps["labelPlacement"];
+  hasPlaceholder: boolean;
+  description?: ReactNode;
+  isMultiline?: boolean;
+}) => {
+  if (labelPlacement === "outside-left") return true;
+  if (labelPlacement !== "outside") return false;
+  
+  return !(hasPlaceholder || !!description) || !!isMultiline;
+};

-const shouldLabelBeOutside =
-  labelPlacement === "outside-left" ||
-  (labelPlacement === "outside" &&
-    (!(hasPlaceholder || !!description) || !!originalProps.isMultiline));
+const shouldLabelBeOutside = shouldPlaceLabelOutside({
+  labelPlacement,
+  hasPlaceholder,
+  description,
+  isMultiline: originalProps.isMultiline,
+});
packages/components/select/__tests__/select.test.tsx (1)

726-731: Test case should cover more scenarios.

While the test case correctly verifies label placement with isMultiline and labelPlacement="outside", it would be beneficial to add more test cases to cover:

  • Label placement with description but without placeholder
  • Label placement with placeholder but without description
  • Label placement with both description and placeholder
+ it("should place the label outside when labelPlacement is outside with description", () => {
+   const labelContent = "Favorite Animal Label";
+   render(
+     <Select
+       isMultiline
+       aria-label="Favorite Animal"
+       data-testid="select"
+       label={labelContent}
+       labelPlacement="outside"
+       description="Select your favorite animal"
+     >
+       <SelectItem key="penguin">Penguin</SelectItem>
+     </Select>,
+   );
+   const base = document.querySelector("[data-slot=base]");
+   const trigger = document.querySelector("[data-slot=trigger]");
+   expect(base).toHaveTextContent(labelContent);
+   expect(trigger).not.toHaveTextContent(labelContent);
+ });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9581891 and 95728e6.

📒 Files selected for processing (4)
  • .changeset/odd-tomatoes-call.md (1 hunks)
  • packages/components/select/__tests__/select.test.tsx (1 hunks)
  • packages/components/select/src/use-select.ts (1 hunks)
  • packages/components/select/stories/select.stories.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/odd-tomatoes-call.md
🔇 Additional comments (4)
packages/components/select/src/use-select.ts (2)

317-318: LGTM: Accessibility is properly maintained

The label placement changes preserve accessibility by maintaining proper ARIA attributes and label associations. The logic ensures that the label remains semantically connected to the select element regardless of its visual placement.


317-318: Verify label placement behavior in edge cases

The updated label placement logic now considers both placeholder and description, but we should verify the behavior in these scenarios:

  1. When both placeholder and description are present
  2. When isMultiline is true with a placeholder
  3. When switching between states dynamically
✅ Verification successful

Label placement logic is correctly implemented

The updated label placement logic in use-select.ts is correct and consistent with the component's behavior across the codebase:

  1. The condition labelPlacement === "outside-left" || (labelPlacement === "outside" && (!(hasPlaceholder || !!description) || !!originalProps.isMultiline)) properly handles all edge cases:

    • When labelPlacement is "outside-left", label is always outside
    • When labelPlacement is "outside", label is outside if:
      • Neither placeholder nor description exists, OR
      • isMultiline is true
  2. This is verified by:

    • Test coverage in select.test.tsx specifically testing this behavior
    • Consistent usage across documentation and examples
    • Similar implementation pattern in related components (Input, DatePicker, etc.)
    • Fix history in CHANGELOG.md addressing label placement behavior
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases covering these scenarios
rg -A 5 "describe.*label.*placement" || \
rg -A 5 "test.*label.*outside"

# Search for related component usage
ast-grep --pattern 'Select $props={
  $$$
  labelPlacement: $_,
  placeholder: $_,
  description: $_
  $$$
}'

Length of output: 183


Script:

#!/bin/bash
# Let's try a broader search for test files related to Select component
fd "select.*.test" --type f

# Search for label placement logic tests with more context
rg -A 10 "labelPlacement.*outside" 

# Look for actual component usage examples
rg -A 5 "<Select.*labelPlacement"

# Search for the specific hook usage
ast-grep --pattern 'useSelect({
  $$$
  labelPlacement: $_,
  $$$
})'

Length of output: 145635

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

360-396: LGTM! The new section effectively demonstrates label placement with description.

The implementation properly showcases all three label placement variants (default, outside, outside-left) with both placeholder and description props, which directly addresses the PR's objective.


363-372: Verify prop consistency across variants.

All three Select components maintain consistent props (color, description, label, placeholder, variant) while only differing in their labelPlacement prop, which is good for comparison purposes.

Also applies to: 373-383, 384-394

✅ Verification successful

Props are consistently used across label placement variants

After reviewing the code in the stories file, I can confirm that the Select components maintain consistent props (color, description, label, placeholder, variant) across all three label placement variants ("inside", "outside", "outside-left"). This is clearly demonstrated in the LabelPlacementTemplate component where all three variants are shown side by side with identical props, ensuring a proper comparison.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the Select component's props are used consistently across the codebase
# Look for any inconsistent usage of description prop with different label placements

rg -U "description=.*labelPlacement" packages/components/select/

Length of output: 66


Script:

#!/bin/bash
# Let's check the story file content to verify the Select components and their props
cat packages/components/select/stories/select.stories.tsx

# Also check for other Select usages with description and labelPlacement
rg -U "labelPlacement.*description|description.*labelPlacement" packages/components/select/

Length of output: 26507

@tianenpang tianenpang closed this Nov 20, 2024
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.

3 participants