Skip to content

Conversation

@cheeseburgertony
Copy link

@cheeseburgertony cheeseburgertony commented Nov 10, 2025

🐛 What problem does this PR solve?

Related to ant-design/ant-design#55637

Currently, the QuickJumper page input fields accept any characters (letters, symbols, etc.), which can cause confusion when users accidentally type non-numeric characters.

✨ What is changed and how it works?

Changes:

  • Add input validation to QuickJumper to restrict input to numeric characters only
  • Update test cases to verify non-numeric input is rejected
  • Simple mode already handles validation through getValidValue function

Behavior:

  • Users can only type digits (0-9) in QuickJumper input fields
  • Non-numeric characters (e.g., '-', '&', letters) are blocked at input time
  • Enter key navigation works correctly with validated input

Before

User types: "abc123def"
Input shows: "abc123def" ❌
Page jumps to: unpredictable

After

User types: "abc123def"
Input shows: "123" ✅
Page jumps to: 123 (or stays on current page if completely filtered)

🔗 Related Issues and PR

Summary by CodeRabbit

发布说明

  • Bug Fixes
    • 输入框验证改进:输入框现在仅接受数字字符,非数字输入会被忽略。
    • 快速跳转功能完善:输入无效值时会自动清空输入框。

@vercel
Copy link

vercel bot commented Nov 10, 2025

@cheeseburgertony is attempting to deploy a commit to the React Component Team on Vercel.

A member of the Team first needs to authorize it.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @cheeseburgertony, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a usability issue in the pagination component where the QuickJumper and simple mode input fields accepted non-numeric characters. By implementing robust input filtering, the change ensures that only numeric values can be entered, thereby improving the user experience and preventing unexpected behavior when navigating pages. The update includes real-time filtering and intelligent handling of completely filtered inputs.

Highlights

  • Input Restriction: The QuickJumper and simple mode pagination input fields now restrict input to numeric characters only, preventing users from typing letters, symbols, or other non-numeric characters.
  • Real-time Filtering: Input is filtered in real-time as the user types, ensuring that only valid numeric characters are displayed in the input field.
  • Robust Filtering Logic: A new helper function, getValidValueForFiltered, was introduced to correctly handle scenarios where the input is completely filtered out (e.g., typing 'abc'), ensuring the page does not jump unexpectedly.
  • Comprehensive Testing: New test cases have been added to cover various scenarios, including typing mixed characters, pasting non-numeric content, and pressing Enter after filtering, to ensure the input restriction works as expected.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively restricts user input to numeric characters in the QuickJumper and simple mode pagination inputs, which improves user experience by preventing invalid entries. The implementation correctly filters non-numeric characters and adds comprehensive test cases to validate the new behavior. However, there are a few areas for improvement regarding React best practices and type safety. The changes introduce direct DOM manipulation for controlled components, which is generally an anti-pattern. Additionally, a new helper function has an incorrect return type, which could lead to runtime errors. My review includes suggestions to address these points for better code maintainability and robustness.

function getValidValueForFiltered(
originalValue: string,
filteredValue: string,
): number {
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The function's return type is declared as number, but getValidValue on line 156 can return an empty string ('') when filteredValue is empty (e.g., when the user clears the input). This creates a type mismatch that could lead to runtime errors, especially with stricter type checking enabled. To accurately reflect the function's behavior and prevent potential issues in consuming code, the return type should be updated.

Suggested change
): number {
): number | '' {

src/Options.tsx Outdated
Comment on lines 67 to 69
if (numericValue !== value) {
e.target.value = numericValue;
value = numericValue;
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

While directly manipulating e.target.value provides immediate visual feedback to the user, it's generally considered an anti-pattern for controlled components in React. This approach is often a workaround for the issue where React may not trigger a re-render if setGoInputText is called with the same string value, which would leave an invalid character in the input (e.g., typing 'a' after '1').

Although this works, it can make the component's behavior harder to reason about as it creates a potential mismatch between the DOM and React's state. For future improvements, consider exploring solutions that don't require direct DOM manipulation to keep the state as the single source of truth.

Comment on lines 185 to 187
if (numericValue !== originalValue) {
inputElement.value = numericValue;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

While directly manipulating inputElement.value provides immediate feedback, it's an anti-pattern for controlled components in React because it can cause the view to become out of sync with the component's state. This workaround is likely necessary here because the internalInputVal state is a number, but the input can temporarily contain non-numeric characters. If the numeric value doesn't change (e.g., typing 'a' after '1'), setInternalInputVal isn't called, and the invalid character would remain visible without this direct DOM manipulation.

A more robust, idiomatic React solution would involve using a separate string state for the input's value, similar to goInputText in Options.tsx. The input would be controlled by this string state, and you would parse it into a number only when a page change is triggered (e.g., on Enter or blur). This would make the component state the single source of truth and eliminate the need for this workaround.

@coderabbitai
Copy link

coderabbitai bot commented Nov 10, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

总体说明

快速跳转输入框的 handleChange 函数现已验证输入内容,仅接受数字字符。非数字输入被忽略,状态仅在新值匹配纯数字模式时更新。新增测试用例验证此验证行为。

变更清单

文件组 / 文件 变更摘要
输入验证逻辑
src/Options.tsx
handleChange 函数添加数字字符验证,仅在输入匹配数字模式时更新状态
测试覆盖
tests/jumper.test.tsx
新增断言,验证输入值小于 1 时清空输入框,确保验证逻辑的正确行为

代码审查工作量估计

🎯 2 (简单) | ⏱️ ~10 分钟

  • 验证逻辑相对直接,使用正则表达式匹配数字模式
  • 测试用例符合现有测试结构
  • 改动范围集中,无需关注复杂的跨文件依赖

诗歌

🐰 数字卫士守门前,
非数之客被轻闻,
测试保驾护航行,
输入纯净如山泉!✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题准确地反映了这个PR的主要变更:限制QuickJumper组件只接受数字输入。
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (1)
src/Pagination.tsx (1)

162-198: 验证实时范围限制的UX体验

过滤非数字字符的逻辑正确实现了PR目标。但173-178行的实时范围限制(clamping)行为需要注意:

当用户输入超出有效范围的数字时(如最大页为10时输入"999"),输入框会立即显示限制后的值("10"),这可能会打断用户的输入流程。虽然这提供了即时反馈,但在某些场景下用户可能期望先完整输入再验证。

建议确认此实时限制行为是否符合产品设计预期。通常的做法是:

  • 允许用户输入任意数字(过滤非数字字符)
  • 仅在失焦或回车时验证并限制到有效范围

如果当前行为是预期的,建议添加注释说明设计意图,并考虑简化173-178行的逻辑以提高可读性:

-    const displayValue =
-      parsedValue > allPages || (parsedValue < 1 && numericValue !== '')
-        ? String(Math.min(Math.max(1, parsedValue), allPages))
-        : numericValue;
+    // Clamp display value to valid range for immediate feedback
+    const needsClamping = parsedValue > allPages || (parsedValue < 1 && numericValue !== '');
+    const displayValue = needsClamping
+      ? String(Math.min(Math.max(1, parsedValue), allPages))
+      : numericValue;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4ec1b6c and 5497b81.

📒 Files selected for processing (1)
  • src/Pagination.tsx (7 hunks)
🔇 Additional comments (7)
src/Pagination.tsx (7)

93-99: 状态类型转换实现正确

internalInputVal 改为字符串类型是合理的设计,使得可以更灵活地处理用户输入(如保留前导零、处理空值等)。初始化和同步逻辑都正确地使用了 String() 转换。


134-144: 验证函数实现正确

getValidValue 函数正确处理了各种边界情况:

  • 空字符串返回当前页,避免意外跳转
  • NaN情况返回当前页,防止错误
  • 正常值正确地限制在有效页码范围内

这解决了历史评审中提到的返回类型不匹配问题。


200-205: 失焦处理逻辑正确

失焦时的验证流程实现合理:

  • 通过 getValidValue 获取有效页码
  • 将验证后的值更新回输入框
  • 触发页面变更

这确保了用户在输入完成后总是看到并跳转到有效的页码。


213-213: 类型转换一致

正确地将 nextCurrent 转换为字符串后更新 internalInputVal,保持了类型一致性。


229-229: 类型转换一致

正确地将 newPage 转换为字符串后更新 internalInputVal,保持了类型一致性。


310-315: 跳转按钮处理正确

handleGoTO 正确地使用字符串类型的 internalInputVal,并通过 getValidValue 转换为有效页码,逻辑清晰正确。


402-404: 只读模式显示简化合理

只读模式直接显示 current 而非 internalInputVal 是合理的简化,避免了不必要的状态管理复杂度,且对用户来说语义更清晰。

@afc163
Copy link
Member

afc163 commented Nov 10, 2025

import { useState } from "react";

export default function NonNegativeIntegerInput() {
  const [value, setValue] = useState("");

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const next = e.target.value;

    if (/^\d*$/.test(next)) {
      setValue(next);
    }
  };

  return (
    <input
      type="text"
      value={value}
      onChange={handleChange}
      inputMode="numeric" // 移动端数字键盘
      placeholder="请输入非负整数"
    />
  );
}

Try this way.

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

🧹 Nitpick comments (1)
src/Options.tsx (1)

162-170: 建议添加 inputMode="numeric" 以改善移动端体验。

根据 PR 目标中 afc163 的建议,应该在 input 元素上添加 inputMode="numeric" 属性,以便在移动设备上触发数字键盘,提升用户体验。

应用以下 diff:

         <input
           disabled={disabled}
           type="text"
           value={goInputText}
           onChange={handleChange}
           onKeyUp={go}
           onBlur={handleBlur}
           aria-label={locale.page}
+          inputMode="numeric"
         />

基于 PR 目标中的建议。

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5497b81 and 32d1587.

📒 Files selected for processing (2)
  • src/Options.tsx (1 hunks)
  • tests/jumper.test.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/jumper.test.tsx
🔇 Additional comments (1)
src/Options.tsx (1)

62-67: 验证逻辑实现正确!

使用 /^\d*$/ 正则表达式在状态更新前进行验证是正确的做法。这种受控组件模式避免了之前评论中提到的直接操作 DOM 的反模式,使状态成为唯一的数据源。实现简洁且易于维护。

@cheeseburgertony
Copy link
Author

import { useState } from "react";

export default function NonNegativeIntegerInput() {
  const [value, setValue] = useState("");

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const next = e.target.value;

    if (/^\d*$/.test(next)) {
      setValue(next);
    }
  };

  return (
    <input
      type="text"
      value={value}
      onChange={handleChange}
      inputMode="numeric" // 移动端数字键盘
      placeholder="请输入非负整数"
    />
  );
}

Try this way.

Sorry, I made the problem too complicated. I noticed that the input has already been processed in simple mode, so I only modified the handleChange function in the Options.tsx file.

@cheeseburgertony cheeseburgertony changed the title fix: restrict input to numeric characters only in QuickJumper and simple mode fix: restrict Pagination QuickJumper to numeric input only Nov 10, 2025
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.

2 participants