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: input should filter away disallowed characters from value prop #4338

Open
wants to merge 1 commit into
base: canary
Choose a base branch
from

Conversation

macci001
Copy link
Contributor

@macci001 macci001 commented Dec 11, 2024

Closes #4329

📝 Description

Change ensures that the input value does not accept any disallowed characters when the value prop contains them.

⛳️ Current behavior (updates)

Screen.Recording.2024-12-11.at.11.13.13.PM.mov

🚀 New behavior

  • Disallowed characters typed will be avoided.
Screen.Recording.2024-12-11.at.11.10.10.PM.mov

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

Summary by CodeRabbit

  • New Features

    • Enhanced input integrity for the OTP component by restricting disallowed characters.
    • Integrated react-hook-form functionality for improved form handling of the OTP input.
  • Bug Fixes

    • Improved validation logic to ensure only allowed characters are accepted in the input.
  • Tests

    • Added a new test case to verify that the input correctly filters out disallowed keys.

Copy link

changeset-bot bot commented Dec 11, 2024

🦋 Changeset detected

Latest commit: eb594e2

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/input-otp 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 11, 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 12, 2024 7:43pm
nextui-storybook-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 12, 2024 7:43pm

@macci001 macci001 requested review from wingkwong and removed request for jrgarciadev December 11, 2024 17:45
Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes introduce a patch for the @nextui-org/input-otp package, enhancing the validation logic to prevent disallowed characters based on the allowedKeys property. This update includes a new test case for the InputOtp component to confirm that the input value correctly filters out invalid characters. The logic for handling the input value is modified to apply a regular expression filter, ensuring stricter input constraints.

Changes

File Change Summary
.changeset/silent-jars-grow.md Patch introduced for @nextui-org/input-otp to implement validation logic for disallowed characters.
packages/components/input-otp/__tests__/input-otp.test.tsx New test case added to verify that the value prop avoids disallowed keys, ensuring input integrity.
packages/components/input-otp/src/use-input-otp.ts Modifications to useInputOtp function to filter input value using a regex based on allowedKeys.
packages/components/input-otp/stories/input-otp.stories.tsx New story template added to demonstrate integration with react-hook-form using Controller.

Assessment against linked issues

Objective Addressed Explanation
Ensure allowedKeys works with React Hook Form (Issue #4329)

Possibly related PRs

  • fix(input-otp): autofocus #4296: This PR directly addresses the autofocus functionality in the @nextui-org/input-otp component, which is relevant to the main PR that also modifies the @nextui-org/input-otp package to enhance input integrity and validation logic.

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.

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)
.changeset/silent-jars-grow.md (1)

1-5: Enhance the changeset description for better clarity.

Consider expanding the description to better explain the fix and its impact:

-Change ensures that the input value does not accept any disallowed characters when the value prop contains them(#4329)
+fix: InputOtp now correctly filters disallowed characters from value prop, ensuring consistency with allowedKeys regex pattern. This fixes the validation behavior when used with React Hook Form (#4329)
packages/components/input-otp/__tests__/input-otp.test.tsx (1)

187-194: Enhance test coverage with additional edge cases.

While the current test verifies basic filtering functionality, consider adding more test cases:

 it("should ensure the value prop avoids any disallowed keys.", () => {
   const value = "4abc12uiond2";
 
   render(<InputOtp length={4} value={value} />);
   const input = screen.getByRole("textbox");
 
   expect(input).toHaveAttribute("value", "4122");
 });
+
+it("should handle empty value prop correctly", () => {
+  render(<InputOtp length={4} value="" />);
+  const input = screen.getByRole("textbox");
+  expect(input).toHaveAttribute("value", "");
+});
+
+it("should handle custom allowedKeys with value prop", () => {
+  const value = "123abc";
+  render(<InputOtp length={4} value={value} allowedKeys="^[a-z]*$" />);
+  const input = screen.getByRole("textbox");
+  expect(input).toHaveAttribute("value", "abc");
+});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 76a72a9 and ef4fba0.

📒 Files selected for processing (3)
  • .changeset/silent-jars-grow.md (1 hunks)
  • packages/components/input-otp/__tests__/input-otp.test.tsx (1 hunks)
  • packages/components/input-otp/src/use-input-otp.ts (2 hunks)
🔇 Additional comments (1)
packages/components/input-otp/src/use-input-otp.ts (1)

151-151: Verify value prop handling in useControlledState.

The value prop is now filtered before being passed to useControlledState. Let's verify this doesn't cause any issues with React's controlled component pattern.

✅ Verification successful

Value prop filtering is correctly implemented and tested

The filtering of the value prop before passing it to useControlledState is intentional and properly handled:

  • The code filters out any characters that don't match the allowed regex pattern before passing to useControlledState
  • This is thoroughly tested as shown in the test file:
    • Test case "should ensure the value prop avoids any disallowed keys" verifies this exact behavior
    • The test confirms that "4abc12uiond2" is correctly filtered to "4122" when only numbers are allowed
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of useControlledState with filtered values
ast-grep --pattern 'useControlledState($filtered, $default, $onChange)'

# Search for related tests or documentation
rg -A 5 'useControlledState.*filtered'

Length of output: 114


Script:

#!/bin/bash
# Let's first look at the useControlledState implementation
ast-grep --pattern 'function useControlledState'

# Check the actual usage in the input-otp component
ast-grep --pattern 'useControlledState($value, $_, $_)' 

# Look at the full context of the file
cat packages/components/input-otp/src/use-input-otp.ts

# Check for tests
fd "input-otp.test" --exec cat {}

Length of output: 17204

packages/components/input-otp/src/use-input-otp.ts Outdated Show resolved Hide resolved
@wingkwong wingkwong self-assigned this Dec 12, 2024
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.

you may check the following case to see if it is expected.

  1. type 1-2-3-4
  2. click the first input (i.e. digit 1)
  3. type an invalid key, says a
  4. digit 1 is gone. it becomes 2-3-4 (my question here: should inputting an invalid character erase the existing value?)

packages/components/input-otp/src/use-input-otp.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 (1)
packages/components/input-otp/stories/input-otp.stories.tsx (1)

180-221: Consider using optional chaining for error handling

The implementation looks good, but we can improve the error handling using optional chaining.

-          errorMessage={errors.otp && errors.otp.message}
+          errorMessage={errors.otp?.message}
🧰 Tools
🪛 Biome (1.9.4)

[error] 203-203: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef4fba0 and eb594e2.

📒 Files selected for processing (4)
  • .changeset/silent-jars-grow.md (1 hunks)
  • packages/components/input-otp/__tests__/input-otp.test.tsx (2 hunks)
  • packages/components/input-otp/src/use-input-otp.ts (2 hunks)
  • packages/components/input-otp/stories/input-otp.stories.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • .changeset/silent-jars-grow.md
  • packages/components/input-otp/tests/input-otp.test.tsx
  • packages/components/input-otp/src/use-input-otp.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/components/input-otp/stories/input-otp.stories.tsx

[error] 203-203: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (3)
packages/components/input-otp/stories/input-otp.stories.tsx (3)

4-4: LGTM: Clean import organization

Good practice combining related imports from react-hook-form.


383-389: LGTM: Story export follows established patterns

The story export is well-structured and maintains consistency with other stories in the file.


201-206: Verify disallowed characters filtering

Since this story is crucial for testing the fix for disallowed characters, we should verify that the InputOtp component correctly filters them out.

✅ Verification successful

Let me gather more information about the validation logic implementation.


Character filtering is properly implemented

The code shows that character filtering is correctly implemented through multiple mechanisms:

  1. The allowedKeys prop is used to create a RegExp pattern that validates input
  2. Input validation occurs in the onChange handler within getBaseProps
  3. The pattern is also applied via the HTML pattern attribute in getInputOtpProps

The story in question correctly tests this functionality by providing different allowedKeys patterns, including the lowercase alphabets test case.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for allowedKeys prop usage and related validation logic
rg -A 5 "allowedKeys.*=.*" 
ast-grep --pattern 'const $_ = $$$; if (!$_.test($_)) { $$$ }'

Length of output: 3803


Script:

#!/bin/bash
# Search for the input validation logic in the InputOtp component
ast-grep --pattern 'const $pattern = new RegExp($allowedKeys);
  $$$
  if (!$pattern.test($_)) {
    $$$
  }'

# Search for related test cases
rg -A 10 "test.*disallowed.*characters" 
rg -A 10 "test.*allowed.*keys"

Length of output: 186


Script:

#!/bin/bash
# Let's check the implementation details of the input validation
rg -A 10 "handleKeyDown|handleChange" packages/components/input-otp/

# Also search for the validation logic with a different pattern
ast-grep --pattern 'function $_(event) {
  $$$
  if ($pattern.test($_)) {
    $$$
  }
}'

Length of output: 161


Script:

#!/bin/bash
# Let's examine the content of the input-otp component and its hook
cat packages/components/input-otp/src/use-input-otp.ts
cat packages/components/input-otp/src/input-otp.tsx

Length of output: 11395

🧰 Tools
🪛 Biome (1.9.4)

[error] 203-203: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

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] - InputOtp does not work allowedKeys when using React Hook Form
2 participants