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 14 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 Mar 4, 2025 10:35pm

@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 接口和内部逻辑的调整。parserformatter 函数被修改为接受一个额外的参数 prevValue,以便访问输入的先前值。此外,引入了新的 validator 函数,用于在处理输入字符串之前进行验证。组件的内部状态管理也进行了更新,使用 useRef 钩子跟踪当前和先前的输入值,并在输入处理前进行验证。

Changes

文件 更改摘要
src/InputNumber.tsx 修改 InputNumberProps 接口中的 parserformatter 函数,添加 prevValue 参数;新增 validator 函数。
tests/formatter.test.tsx 修改测试用例中的 formatter 调用,新增 prevValue 参数。

Possibly related PRs

Suggested reviewers

  • zombieJ

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/.pnpm/@umijs[email protected]_jest@29.7.0_@types[email protected]_ts-node@10.9.2_@types[email protected][email protected][email protected]/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.

tests/formatter.test.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/.pnpm/@umijs[email protected]_jest@29.7.0_@types[email protected]_ts-node@10.9.2_@types[email protected][email protected][email protected]/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.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

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

📒 Files selected for processing (2)
  • src/InputNumber.tsx (7 hunks)
  • tests/formatter.test.tsx (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
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.
src/InputNumber.tsx (2)
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: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 (9)
tests/formatter.test.tsx (1)

166-166: 测试已更新以包含新的 prevValue 参数。

测试正确地验证了 formatter 函数是否接收到了包含 prevValue 的新参数结构。这确保了 API 变更的正确实现和验证。

src/InputNumber.tsx (8)

175-176: 使用 useRef 追踪前值的实现正确。

prevValueRefinputValueRef 的类型定义为 string | number,与现有代码保持一致,符合之前的学习记录。这种实现可以有效地追踪输入值的历史变化。


211-211: 确保 parser 接收正确的前值字符串

此处更新确保了 parser 函数接收到以前的输入值作为参数,辅助格式化和验证逻辑。注意使用了 ?? 运算符处理 prevValueRef.current 可能为空的情况,这是一个很好的防御性编程实践。


229-233: 提供完整的上下文信息给 formatter 函数

更新后的代码将前值、当前输入和用户输入状态传递给 formatter 函数,使得格式化逻辑可以基于更多上下文信息做出决策。这对于复杂的格式化需求非常有用。


273-276: 确保在输入值变化时正确更新引用

此副作用钩子确保了 prevValueRefinputValueRefinputValue 变化时得到更新。顺序很重要:先将当前值保存为前值,然后更新当前值引用。


395-397: 验证器实现简洁有效

验证器的实现简单明了:如果输入不符合验证条件,函数直接返回,阻止进一步处理。根据已有的学习记录,这符合组件的设计理念 - 不使用错误状态或消息,而是直接阻止无效值更新。

不过,建议添加简单的代码注释,说明验证失败时的行为:

// validate string
if (validator) {
  if (!validator(inputStr)) {
+   // 验证失败时,直接返回,不更新输入值
    return;
  }
}

403-404: 确保在更新当前值之前正确捕获前值

在更新 inputValueRef.current 之前设置 prevValueRef.current,这是正确的顺序,确保了前值被准确捕获。


139-139: 解构 validator 属性确保在组件内可用

在组件解构中添加 validator,确保该属性可在组件内部使用。代码位置正确,与相关属性 parserformatter 邻近。


90-97:

✅ Verification successful

请考虑将新的参数设为可选以保持向后兼容性。

parserformatter 函数签名的更改可能会影响现有代码。通过将 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;

🌐 Web query:

TypeScript 函数参数兼容性规则是什么?如何保持函数签名的向后兼容性?

💡 Result:

TypeScript的函数参数兼容性规则遵循结构化类型系统,主要通过参数个数、参数类型、返回值类型三个维度进行判断。以下是核心规则及向后兼容方法:

一、函数参数兼容性规则

1. 参数个数原则

  • 参数多的兼容参数少的(与对象类型规则相反)
    例如:(a: number, b: string) => void 可赋值给 (x: number) => void[1][4]
  • 支持可选参数与剩余参数的灵活转换:
    let fixed = (p1: number) => {};     // 固定参数
    let optional = (p1?: number) => {}; // 可选参数
    let rest = (...args: number[]) => {}; // 剩余参数
    
    fixed = optional;  // 兼容
    rest = fixed;      // 兼容[4][7]

2. 参数类型原则

  • 原始类型必须严格匹配:
    type Handler = (a: number) => void;
    let func = (a: string) => {};  // 错误:类型不兼容[4][8]
  • 对象类型采用属性级兼容:
    type Source = (p: { x: number }) => void;
    type Target = (p: { x: number; y: string }) => void;
    let t: Target = (p) => console.log(p.x);
    let s: Source = t;  // 允许赋值[10]

3. 返回值原则

  • 原始类型返回值必须完全相同
  • 对象类型返回值遵循成员多兼容成员少:
    type F1 = () => { name: string };
    type F2 = () => { name: string; age: number };
    let f1: F1 = () => ({ name: "Tom" });
    let f2: F2 = f1;  // 错误
    let f3: F1 = f2;  // 允许[4][8]

二、保持向后兼容性方法

  1. 参数扩展策略

    • 新增参数应设为可选参数:
      // v1.0
      function fetchData(url: string) {}
      
      // v2.0 向后兼容
      function fetchData(url: string, timeout?: number) {}[7]
    • 使用剩余参数处理参数列表扩展:
      function log(...args: (string | number)[]) {}[9]
  2. 函数重载规范
    通过声明多个重载签名保持兼容:

    // 重载签名
    function parse(input: string): number;
    function parse(input: Buffer): number;
    
    // 实现签名
    function parse(input: string | Buffer): number {
      if (typeof input === "string") return parseInt(input);
      return input.readInt32BE(0);
    }[5][6]

    注意:实现签名必须兼容所有重载签名

  3. 类型安全配置
    启用严格模式增强类型检查:

    {
      "compilerOptions": {
        "strictFunctionTypes": true // 精确校验逆变参数[3]
      }
    }

三、特殊场景处理

  • 回调函数参数可忽略额外参数:
    type EventHandler = (target: object) => void;
    const handler: EventHandler = (target: object, timestamp?: number) => {}; // 允许[7]
  • 泛型函数保持参数类型关联性:
    function identity<T>(x: T): T { return x; }
    let numIdentity: (x: number) => number = identity; // 有效[10]

通过遵循参数数量递增、优先使用可选/剩余参数、合理设计重载接口,并配合编译器严格模式,可在TypeScript中有效维护函数签名的向后兼容性。当需要破坏性变更时,建议通过版本化或新函数接口实现平滑过渡。

Citations:


更新参数兼容性建议

经过验证,为了避免现有代码因函数参数变更而报错,请将新增的 info 参数设为可选,从而保持向后兼容。具体建议如下:

  • 文件: src/InputNumber.tsx
  • 问题位置: Lines 90-97
  • 修改建议:
    • parser 函数,将 info 参数设为可选
    • formatter 函数,将 info 参数设为可选

修改 diff 如下:

- 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;

上述修改符合 TypeScript 的函数参数兼容性规则,即新增参数应设置为可选,确保现有实现不受影响。

✨ Finishing Touches
  • 📝 Generate Docstrings

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

Copy link

codecov bot commented Sep 29, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.05%. Comparing base (4470642) to head (80ce003).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #644      +/-   ##
==========================================
+ Coverage   95.95%   96.05%   +0.09%     
==========================================
  Files           6        6              
  Lines         297      304       +7     
  Branches       78       82       +4     
==========================================
+ Hits          285      292       +7     
  Misses         12       12              

☔ 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之前考虑实施这些改进。

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

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;

@bombillazo
Copy link
Author

@sorrycc @afc163 @zombieJ @yiminghe any thoughts on this?

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