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

Add Validator callback and provide prevValue in Parser callback #644

Open
wants to merge 13 commits into
base: master
Choose a base branch
from

Conversation

bombillazo
Copy link

@bombillazo bombillazo commented May 20, 2024

This PR enhances the component by adding a new callback: Validator, which prevents the input from changing if the value does not pass the validation. This is useful to prevent users from inputting unwanted characters in the input.

The Parser callback has also been enhanced with a new info second param that returns the previous value. This is useful for formatting or validation purposes when one is modifying the value and needs to compare the old and new values.

Summary by CodeRabbit

  • 新功能
    • 引入了输入验证功能,确保用户输入的有效性。
    • 增强了输入处理逻辑,允许访问输入的先前值以改善格式化和解析。
  • 改进
    • 更新了内部状态管理,以更好地跟踪当前和先前的输入值。

Copy link

vercel bot commented May 20, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
input-number ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 14, 2024 5:03am

@bombillazo
Copy link
Author

@afc163 @zombieJ Any feedback on this PR?

@bombillazo
Copy link
Author

@afc163 @zombieJ Hello there, any feedback?

Copy link

coderabbitai bot commented Sep 9, 2024

Walkthrough

此次更改对 InputNumber.tsx 文件进行了增强,主要涉及 InputNumberProps 接口和 InternalInputNumber 组件的内部逻辑。parserformatter 函数被修改为接受一个额外的参数 prevValue,以便访问输入的先前值。此外,引入了新的 validator 函数,用于在处理输入字符串之前进行验证。组件的内部状态管理也进行了更新,使用 useRef 钩子跟踪当前和先前的输入值,并在输入处理前进行验证。

Changes

文件 更改摘要
src/InputNumber.tsx 修改 InputNumberProps 接口中的 parserformatter 函数,添加 prevValue 参数;新增 validator 函数。
tests/formatter.test.tsx 修改测试用例中的 formatter 调用,新增 prevValue 参数。
tests/validator.test.tsx 新增测试文件,验证 InputNumber 组件的输入验证和格式化功能。

Poem

🐰 在数字的世界里跳跃,
输入的变化如风般轻巧。
旧值新值相互交织,
验证与格式,完美结合。
兔子欢呼,乐在其中,
让每个输入,皆成美梦! 🌟

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/InputNumber.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react".

(The package "eslint-plugin-react" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react@latest --save-dev

The plugin "eslint-plugin-react" was referenced from the config file in ".eslintrc.js » /node_modules/@umijs/fabric/dist/eslint.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@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, codebase verification and nitpick comments (2)
src/InputNumber.tsx (2)

90-93: 需要更新 formatter 函数的所有实例以匹配新签名

在测试文件和文档示例中,有些 formatter 函数的使用没有更新为包含 info 参数的新签名。这可能导致不一致和潜在错误。请确保所有使用 formatter 的地方都已更新。

  • 需要更新的文件包括:tests/github.test.tsx, tests/formatter.test.tsx, docs/demo/formatter.tsx 等。
Analysis chain

批准更改并验证 formatter 函数的使用。

此更改符合 PR 目标,增强了验证和格式化功能。请确保组件中所有使用 formatter 的地方都已更新,以传递新参数。

运行以下脚本以验证 formatter 函数的使用:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 描述:验证所有 `formatter` 函数调用都匹配新的签名。

# 测试:搜索函数使用。预期:只有新签名的出现。
rg --type typescript -A 5 $'formatter'

Length of output: 72


Script:

#!/bin/bash
# 描述:验证所有 `formatter` 函数调用都匹配新的签名。

# 测试:搜索函数使用。预期:只有新签名的出现。
rg --type ts -A 5 $'formatter'

Length of output: 14346


88-88: 需要更新 parser 函数的所有用法以匹配新签名

在多个文件中发现 parser 函数的用法未更新为包含 info 参数的新签名。这可能导致不一致和运行时错误。请确保在以下文件中更新 parser 函数的用法:

  • tests/formatter.test.tsx
  • tests/cursor.test.tsx
  • docs/demo/formatter.tsx
  • docs/demo/combination-key-format.tsx

请确保所有实例都符合新的函数签名,以确保组件的正确功能。

Analysis chain

批准更改并验证 parser 函数的使用。

此更改符合 PR 目标,增强了验证和格式化功能。请确保组件中所有使用 parser 的地方都已更新,以传递新参数。

运行以下脚本以验证 parser 函数的使用:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 描述:验证所有 `parser` 函数调用都匹配新的签名。

# 测试:搜索函数使用。预期:只有新签名的出现。
rg --type typescript -A 5 $'parser'

Length of output: 69


Script:

#!/bin/bash
# 描述:验证所有 `parser` 函数调用都匹配新的签名。

# 测试:搜索函数使用。预期:只有新签名的出现。
rg --type tsx -A 5 $'parser'

Length of output: 55


Script:

#!/bin/bash
# 描述:验证所有 `parser` 函数调用都匹配新的签名。

# 测试:搜索函数使用。预期:只有新签名的出现。
rg --glob '*.tsx' -A 5 $'parser'

Length of output: 5000

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 357d0a5 and bc42675.

Files selected for processing (1)
  • src/InputNumber.tsx (7 hunks)
Additional comments not posted (1)
src/InputNumber.tsx (1)

95-95: 批准添加 validator 函数并验证其实现。

此添加符合 PR 目标,防止输入不需要的字符。请确保 validator 函数被正确调用,并按预期处理验证。

运行以下脚本以验证 validator 函数的实现:

Verification successful

验证 validator 函数的实现是正确的。

validator 函数被正确地定义为可选属性,并在输入处理逻辑中正确调用。它确保只有通过验证的输入才会被进一步处理,从而增强了组件的健壮性。此实现符合其预期目的。

  • validator 函数在 src/InputNumber.tsx 中被正确使用。
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 描述:验证 `validator` 函数是否正确实现。

# 测试:搜索函数实现。预期:函数应正确调用并处理验证。
rg --type typescript -A 5 $'validator'

Length of output: 72


Script:

#!/bin/bash
# 描述:验证 `validator` 函数是否正确实现。

# 测试:搜索函数实现。预期:函数应正确调用并处理验证。
rg --type ts -A 5 $'validator'

Length of output: 921

@bombillazo
Copy link
Author

bombillazo commented Sep 29, 2024

Hey @afc163 @MadCcc @Layouwen @zombieJ Any feedback on this improvement for InputNumber?

Copy link

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bc42675 and 81e3375.

📒 Files selected for processing (2)
  • src/InputNumber.tsx (7 hunks)
  • tests/formatter.test.tsx (1 hunks)
🔇 Additional comments (4)
tests/formatter.test.tsx (2)

Line range hint 1-210: 文件总结

这个测试文件的更改很小但很重要,它验证了新增的 prevValue 参数功能。这与 PR 的目标一致,提高了对新特性的测试覆盖率。

建议:

  1. 考虑添加更多测试用例,以全面覆盖 prevValue 参数在各种情况下的行为。
  2. 确保其他相关的测试文件也已更新,以反映这个新参数的添加。
  3. 更新文件顶部的注释或文档字符串,说明新增的 prevValue 参数及其用途。

运行以下脚本以确保所有相关的测试文件都已更新:

#!/bin/bash
# 描述:检查其他测试文件是否也包含了 prevValue 参数的测试

# 测试:在测试文件中搜索 formatter 函数的使用。预期:相关的测试文件都应包含 prevValue 参数
rg --type typescript --type tsx 'formatter.*=.*\(.*,.*\{.*prevValue' -g 'tests/*'

166-166: 验证新增的 prevValue 参数

这个更改为 formatter 函数调用添加了 prevValue 参数。这与 PR 的目标一致,即在回调中提供先前的输入值。

建议:

  1. 确保这个测试用例充分验证了 prevValue 参数的正确性。
  2. 考虑添加更多测试用例,以覆盖 prevValue 在不同场景下的行为,例如连续输入时的值变化。

为了确保 prevValue 参数在整个代码库中得到正确实现,请运行以下脚本:

src/InputNumber.tsx (2)

Line range hint 209-216: 确保在调用 parser 时正确传递 prevValue

mergedParser 函数中,prevValue 的获取方式为 String(prevValueRef.current ?? '')。请确认 prevValueRef.current 的值在预期范围内,且不会出现 undefinednull 的情况,以避免字符串转换时出现意外结果。


88-93: 请确认扩展后的 parserformatter 接口不会引入破坏性变更。

parserformatter 函数的签名已修改,增加了一个额外的参数 info,包含 prevValue。这可能会影响所有现有使用这些函数的地方,请确保所有调用都已更新以匹配新的函数签名,防止潜在的运行时错误。

您可以使用以下脚本查找代码库中所有调用 parserformatter 的位置:

✅ Verification successful

确认无破坏性变更引入

代码库中仅在 src/InputNumber.tsx 中调用了 parserformatter,且这些调用已包含新的 info 参数。确认扩展后的接口不会引入破坏性变更。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 查找所有使用 'parser' 的代码位置
rg --type typescript --type javascript 'parser\('

# 查找所有使用 'formatter' 的代码位置
rg --type typescript --type javascript 'formatter\('

Length of output: 176


Script:

#!/bin/bash
# 查找所有使用 'parser' 的代码位置
rg 'parser\(' --glob '*.ts' --glob '*.tsx' --glob '*.js' --glob '*.jsx'

# 查找所有使用 'formatter' 的代码位置
rg 'formatter\(' --glob '*.ts' --glob '*.tsx' --glob '*.js' --glob '*.jsx'

Length of output: 311

src/InputNumber.tsx Show resolved Hide resolved
src/InputNumber.tsx Show resolved Hide resolved
Copy link

codecov bot commented Sep 29, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.46%. Comparing base (df0c51c) to head (afe99b4).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #644      +/-   ##
==========================================
+ Coverage   95.36%   95.46%   +0.10%     
==========================================
  Files           7        7              
  Lines         302      309       +7     
  Branches       78       81       +3     
==========================================
+ Hits          288      295       +7     
  Misses         14       14              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@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 (1)
tests/validator.test.tsx (1)

5-32: 第一个测试用例"validator on direct input"看起来不错,但可以进一步改进。

这个测试用例全面地覆盖了InputNumber组件的验证器功能,包括无效输入和有效数字输入的情况。然而,我们可以通过以下方式进一步增强测试:

  1. 添加更多的边界情况测试,例如:

    • 输入最大值和最小值(如果组件有这些限制)
    • 输入小数点和负数(如果组件支持)
    • 输入非常大的数字
  2. 测试连续输入多个字符的情况,确保验证器在每次按键时都正确工作。

  3. 验证onChange函数在无效输入时是否未被调用。

  4. 考虑测试粘贴操作,因为用户可能会尝试粘贴无效内容。

您是否希望我为这些建议提供具体的测试代码示例?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 81e3375 and fecd638.

📒 Files selected for processing (1)
  • tests/validator.test.tsx (1 hunks)
🧰 Additional context used
📓 Learnings (1)
📓 Common learnings
Learnt from: bombillazo
PR: react-component/input-number#644
File: src/InputNumber.tsx:173-174
Timestamp: 2024-09-29T06:18:11.993Z
Learning: In `src/InputNumber.tsx`, within the `InternalInputNumber` component, the state variables `prevValueRef` and `inputValueRef` are typed as `string | number` to maintain consistency with existing code.
🔇 Additional comments (2)
tests/validator.test.tsx (2)

1-3: 导入语句看起来很好。

导入语句包含了所需的所有必要模块,包括KeyCode、InputNumber组件和测试工具。这些导入为测试文件提供了所需的功能。


1-84: 总体评价:测试文件结构良好,覆盖了关键功能,但有进一步改进的空间。

这个测试文件为InputNumber组件的验证器和格式化器功能提供了全面的测试覆盖。它测试了各种用户输入场景、键盘导航和鼠标交互,这对于确保组件的可靠性和用户体验至关重要。

然而,实施先前建议的改进将进一步增强测试的全面性和稳健性:

  1. 添加更多边界情况和复杂输入场景的测试。
  2. 改进对无效输入的处理和测试。
  3. 增加对性能和用户体验相关方面的测试。

这些改进将有助于捕获潜在的边缘情况bug,并确保组件在各种使用场景下都能正常工作。建议在合并此PR之前考虑实施这些改进。

为了确保测试覆盖率的提高,请运行以下命令来检查当前的测试覆盖率,并在实施建议的改进后再次运行以比较结果:

tests/validator.test.tsx Show resolved Hide resolved
Copy link

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fecd638 and afe99b4.

📒 Files selected for processing (1)
  • src/InputNumber.tsx (7 hunks)
🧰 Additional context used
📓 Learnings (1)
src/InputNumber.tsx (3)
Learnt from: bombillazo
PR: react-component/input-number#644
File: src/InputNumber.tsx:393-395
Timestamp: 2024-11-12T06:11:49.241Z
Learning: The `InputNumber` component does not use error states or messages; it is designed to prevent the value from updating if validation fails without displaying additional feedback to the user.
Learnt from: bombillazo
PR: react-component/input-number#644
File: src/InputNumber.tsx:393-395
Timestamp: 2024-11-12T06:11:49.240Z
Learning: The `InputNumber` component does not use error states or messages; it is designed to prevent the value from updating if validation fails without displaying additional feedback to the user.
Learnt from: bombillazo
PR: react-component/input-number#644
File: src/InputNumber.tsx:173-174
Timestamp: 2024-11-12T06:11:49.240Z
Learning: In `src/InputNumber.tsx`, within the `InternalInputNumber` component, the state variables `prevValueRef` and `inputValueRef` are typed as `string | number` to maintain consistency with existing code.
🔇 Additional comments (1)
src/InputNumber.tsx (1)

394-397: ⚠️ Potential issue

确保在验证失败时更新内部引用以维护状态一致性

collectInputValue 函数中,当输入未通过 validator 验证时,函数会提前返回,导致 prevValueRefinputValueRef 未更新。这可能导致组件内部状态不一致。建议在验证之前更新这些引用,以确保状态的正确性。

应用以下代码修改:

collectInputValue = (inputStr: string) => {
+  prevValueRef.current = inputValueRef.current;
+  inputValueRef.current = inputStr;
+  setInternalInputValue(inputStr);

   // 验证输入字符串
   if (validator) {
     if (!validator(inputStr)) return;
   }

Likely invalid or redundant comment.

Comment on lines +90 to +97
parser?: (displayValue: string | undefined, info: { prevValue: string }) => T;
/** Transform `value` to display value show in input */
formatter?: (value: T | undefined, info: { userTyping: boolean; input: string }) => string;
formatter?: (
value: T | undefined,
info: { userTyping: boolean; input: string; prevValue: string },
) => string;
/** Validate an input string before processing */
validator?: (input: string) => boolean;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

注意:parserformatter 方法签名的更改可能引入破坏性变更

InputNumberProps 接口中为 parserformatter 方法添加新的参数 info,可能会导致现有使用这些属性的代码出现 TypeScript 类型错误,因为现有实现可能未预期新的 info 参数。建议将新的 info 参数设为可选,以保持向后兼容性。

应用以下代码修改:

- parser?: (displayValue: string | undefined, info: { prevValue: string }) => T;
+ parser?: (displayValue: string | undefined, info?: { prevValue: string }) => T;
- formatter?: (
-   value: T | undefined,
-   info: { userTyping: boolean; input: string; prevValue: string },
- ) => string;
+ formatter?: (
+   value: T | undefined,
+   info?: { userTyping: boolean; input: string; prevValue: string },
+ ) => string;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
parser?: (displayValue: string | undefined, info: { prevValue: string }) => T;
/** Transform `value` to display value show in input */
formatter?: (value: T | undefined, info: { userTyping: boolean; input: string }) => string;
formatter?: (
value: T | undefined,
info: { userTyping: boolean; input: string; prevValue: string },
) => string;
/** Validate an input string before processing */
validator?: (input: string) => boolean;
parser?: (displayValue: string | undefined, info?: { prevValue: string }) => T;
/** Transform `value` to display value show in input */
formatter?: (
value: T | undefined,
info?: { userTyping: boolean; input: string; prevValue: string },
) => string;
/** Validate an input string before processing */
validator?: (input: string) => boolean;

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.

1 participant