Skip to content

fix: Allow space character in Select input#1210

Merged
zombieJ merged 4 commits intomasterfrom
fix/input-space-issue
Feb 14, 2026
Merged

fix: Allow space character in Select input#1210
zombieJ merged 4 commits intomasterfrom
fix/input-space-issue

Conversation

@zombieJ
Copy link
Member

@zombieJ zombieJ commented Feb 14, 2026

fix ant-design/ant-design#56988

Fixed issue where pressing the space key in Select input would not add a space character to the input field.

The space key was always calling preventDefault(), which prevented the default behavior of adding a space character to the input.

Changes:

  • Modified space key handling in BaseSelect to allow space to be typed when dropdown is open and user has typed content
  • Space still prevents default behavior when dropdown is closed (opens dropdown) or when input is empty (prevents page scroll)
  • Added test cases to verify the fix

This fix allows users to type spaces in search terms within Select components while maintaining the existing behavior for opening the dropdown.

Summary by CodeRabbit

发布说明

  • Bug Fixes

    • 优化键盘交互:在可编辑模式(组合框或启用搜索)下,Enter/Space 不再无条件阻止默认行为,从而改善输入和搜索体验;非可编辑场景仍保留阻止默认行为并触发打开逻辑。
  • Tests

    • 新增键盘行为测试,覆盖启用/禁用搜索及组合框模式下的 Space/Enter 行为验证。

@vercel
Copy link

vercel bot commented Feb 14, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
select Ready Ready Preview, Comment Feb 14, 2026 5:52am

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @zombieJ, 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 an issue in the Select component where pressing the space key would not insert a space character into the input field. The changes refactor the event handling for the space key to allow users to type spaces within search terms while preserving the component's existing behavior for opening the dropdown or preventing page scroll when the input is empty.

Highlights

  • Space key behavior: Modified the BaseSelect component to allow the space character to be typed into the input field when the dropdown is open and the user has already entered some text.
  • Existing behavior preservation: Ensured that the space key still prevents default behavior (e.g., opening the dropdown when closed, preventing page scroll when input is empty) in other scenarios.
  • Test coverage: Added new test cases to validate the corrected space key input functionality and the preservation of existing behaviors.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/BaseSelect/index.tsx
    • Refactored the isSpaceKey handling logic within the onKeyDown event to conditionally call event.preventDefault().
    • Introduced a condition to allow space input when mergedOpen is true and mergedSearchValue is not empty.
  • tests/spaceInput.test.tsx
    • Added a new test file to specifically cover space key input scenarios.
    • Included a test case to verify that typing a space character works when the input has existing content.
    • Included a test case to confirm that the dropdown still opens on space key press when the input is empty.
Activity
  • No specific activity (comments, reviews, progress updates) was provided in the context.
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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 14, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

修改 BaseSelect 的 Enter/Space 键处理:引入 isEditable(mode === 'combobox' || showSearch),仅在非可编辑场景下对 Enter/Space 调用 event.preventDefault();新增针对 showSearch 下 Space 行为的测试用例集合。

Changes

Cohort / File(s) Summary
键盘事件处理逻辑修改
src/BaseSelect/index.tsx
调整 Enter/Space 的 keydown 分支,新增 `isEditable = (mode === 'combobox'
键盘事件测试覆盖
tests/Select.test.tsx
新增“Space key behavior with showSearch” 测试套件(3 个测试):验证 showSearch 启用/禁用与 combobox 模式下 Space 是否触发 preventDefault() 的行为。

Sequence Diagram(s)

(省略 — 更改为简短逻辑调整与测试覆盖,不满足生成序列图的条件)

Estimated code review effort

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

Possibly related PRs

Suggested reviewers

  • afc163
  • yoyo837

🐰 空格键有新约定,
可编辑时放它行,
非编辑才作停顿,
三重测试来把关,
小兔鼓掌庆更明!

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题准确概括了主要变更:允许在Select输入框中输入空格字符。这反映了PR的核心目的——修复空格键被preventDefault阻止的问题。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into master

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/input-space-issue

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.

Fixed issue where pressing the space key in Select input would not add a space character to the input field.

The root cause was that preventDefault() was always called when mode was not 'combobox', which prevented typing spaces even when the input was editable in showSearch mode.

Changes:
- Modified space key handling to only call preventDefault() when the input is not editable
- Input is considered editable when mode is 'combobox' or showSearch is true
- This allows users to type spaces in editable Select inputs while preventing default behavior (scroll/submit) in non-editable Selects

This fix allows users to type spaces in search terms within Select components with showSearch enabled.
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

The pull request effectively addresses the issue of allowing space characters in the Select input, which was previously prevented by preventDefault(). The changes correctly modify the key handling logic in BaseSelect to differentiate between various scenarios (dropdown open/closed, input empty/filled) and ensure the space key behaves as expected. The addition of new test cases (spaceInput.test.tsx) is a good practice and helps verify the fix. The code is well-structured and the logic appears sound for the intended fix.

});
input.dispatchEvent(keyDownEvent);

expect(input.value).toBe('hello');
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 test case should allow typing space when typing in the input currently asserts that input.value remains 'hello' after dispatching a keyDownEvent for space. However, for the space character to actually appear in the input field, the input.value should be updated to 'hello ' (with a space) and then an input event should be dispatched. The current test only verifies that preventDefault() was not called, but not that the space character was successfully added to the input.

Suggested change
expect(input.value).toBe('hello');
expect(input.value).toBe('hello ');

@codecov
Copy link

codecov bot commented Feb 14, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.43%. Comparing base (8327910) to head (70ee949).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1210   +/-   ##
=======================================
  Coverage   99.43%   99.43%           
=======================================
  Files          31       31           
  Lines        1234     1236    +2     
  Branches      423      446   +23     
=======================================
+ Hits         1227     1229    +2     
  Misses          7        7           

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zombieJ zombieJ force-pushed the fix/input-space-issue branch from e28d53e to f566f35 Compare February 14, 2026 05:20
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

🤖 Fix all issues with AI agents
In `@tests/spaceInput.test.tsx`:
- Around line 6-26: The test currently bypasses React state by directly setting
input.value and dispatching native events, so rc-select's internal
mergedSearchValue/onSearch may not update and the test can pass for the wrong
reason; change the test "should allow typing space when typing in the input" to
use `@testing-library/react`'s fireEvent (e.g., fireEvent.change) to simulate
typing "hello" so React state updates, then simulate the space keydown using
fireEvent.keyDown (or new KeyboardEvent) while spying on
KeyboardEvent.prototype.preventDefault (or using jest.fn()) to assert that
preventDefault was NOT called; reference the test block name and the input
element selection to locate the code to modify.
🧹 Nitpick comments (1)
tests/spaceInput.test.tsx (1)

28-46: 测试二建议同时验证下拉框是否打开。

当前仅验证了 preventDefault 被调用,但 PR 目标是"空格键在输入为空时打开下拉框"。建议增加断言验证下拉框确实被打开了:

建议补充断言
  expect(preventDefaultSpy).toHaveBeenCalled();
+
+ // 验证下拉框已打开
+ expect(container.querySelector('.rc-select-open')).toBeTruthy();

Comment on lines 6 to 26
it('should allow typing space when typing in the input', () => {
const { container } = render(
<Select showSearch options={[{ value: 'test', label: 'test' }]} />,
);

const input = container.querySelector('input');
input.focus();
input.value = 'hello';

const event = new Event('input', { bubbles: true });
input.dispatchEvent(event);

const keyDownEvent = new KeyboardEvent('keydown', {
key: ' ',
code: 'Space',
bubbles: true,
});
input.dispatchEvent(keyDownEvent);

expect(input.value).toBe('hello');
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

测试一可能因绕过 React 状态而无法真正验证空格输入行为。

直接设置 input.value = 'hello' 并 dispatch 原生 input 事件,可能不会触发 rc-select 的 onSearch 回调来更新 mergedSearchValue。如果 mergedSearchValue 仍为空字符串,那么 !(isSpaceKey && mergedSearchValue !== '') 条件为 true,空格仍会被 preventDefault——测试可能因为错误的原因而通过。

建议使用 @testing-library/reactfireEvent 来模拟用户输入,确保 React 状态正确更新:

建议的改进方案
- const input = container.querySelector('input');
- input.focus();
- input.value = 'hello';
-
- const event = new Event('input', { bubbles: true });
- input.dispatchEvent(event);
-
- const keyDownEvent = new KeyboardEvent('keydown', {
-   key: ' ',
-   code: 'Space',
-   bubbles: true,
- });
- input.dispatchEvent(keyDownEvent);
-
- expect(input.value).toBe('hello');
+ import { fireEvent } from '@testing-library/react';
+ // ...
+ const input = container.querySelector('input');
+ fireEvent.focus(input);
+ fireEvent.change(input, { target: { value: 'hello' } });
+
+ const keyDownEvent = new KeyboardEvent('keydown', {
+   key: ' ',
+   code: 'Space',
+   bubbles: true,
+ });
+ const preventDefaultSpy = jest.spyOn(keyDownEvent, 'preventDefault');
+ input.dispatchEvent(keyDownEvent);
+
+ // 验证空格键未被阻止(允许输入空格)
+ expect(preventDefaultSpy).not.toHaveBeenCalled();

此外,断言 input.value 不变并不能证明空格被"允许"输入。更有效的断言是验证 preventDefault 被调用。

🤖 Prompt for AI Agents
In `@tests/spaceInput.test.tsx` around lines 6 - 26, The test currently bypasses
React state by directly setting input.value and dispatching native events, so
rc-select's internal mergedSearchValue/onSearch may not update and the test can
pass for the wrong reason; change the test "should allow typing space when
typing in the input" to use `@testing-library/react`'s fireEvent (e.g.,
fireEvent.change) to simulate typing "hello" so React state updates, then
simulate the space keydown using fireEvent.keyDown (or new KeyboardEvent) while
spying on KeyboardEvent.prototype.preventDefault (or using jest.fn()) to assert
that preventDefault was NOT called; reference the test block name and the input
element selection to locate the code to modify.

Added test coverage to verify space key behavior in different Select modes:

1. showSearch enabled: Space should NOT call preventDefault, allowing space to be typed
2. showSearch disabled: Space SHOULD call preventDefault, preventing page scroll
3. combobox mode: Space should NOT call preventDefault, allowing space to be typed

These tests ensure the fix correctly handles space key input based on whether the input is editable.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/BaseSelect/index.tsx (1)

472-483: ⚠️ Potential issue | 🔴 Critical

isEditable 同时跳过了 Enter 键的 preventDefault,可能导致表单意外提交。

isEditable 条件同时影响 Enter 和 Space 两个键。在 comboboxshowSearch 模式下,Enter 键不再调用 preventDefault(),这意味着如果 Select 组件位于 <form> 中,按下 Enter 会触发表单提交——这是一个功能回退。

建议将 preventDefault 的跳过逻辑仅限于 Space 键:

🐛 建议修复
     if (isEnterKey || isSpaceKey) {
-      const isEditable = mode === 'combobox' || showSearch;
-      if (!isEditable) {
+      // Space key: allow typing space in editable selects (combobox or showSearch).
+      // Enter key: always preventDefault to avoid form submission.
+      const isEditableSpace = isSpaceKey && (mode === 'combobox' || showSearch);
+      if (!isEditableSpace) {
         event.preventDefault();
       }

Separate isCombobox check and apply different preventDefault logic:
- Space: prevent only when not editable
- Enter: prevent only when not combobox

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@zombieJ zombieJ merged commit fe94e97 into master Feb 14, 2026
12 checks passed
@zombieJ zombieJ deleted the fix/input-space-issue branch February 14, 2026 05:53
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.

The search callback of the Select component does not include whitespace characters.

1 participant