feat(Tabs): support showSearch in more dropdown#992
Conversation
|
Someone is attempting to deploy a commit to the React Component Team on Vercel. A member of the Team first needs to authorize it. |
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough新增 Changes搜索下拉支持
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces a search feature within the tabs overflow dropdown, allowing users to filter tabs. It includes documentation, styling, a demo, and unit tests. The review feedback highlights three key areas for improvement: first, safely extracting text from tab.label since it can be a React node rather than a plain string; second, resetting the selected key when the active tab is filtered out to prevent selecting hidden tabs; and third, enhancing accessibility by auto-focusing the search input upon opening and supporting the Escape key to close the dropdown.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| const filteredTabs = mergedSearchValue | ||
| ? tabs.filter(tab => String(tab.label).toLowerCase().includes(mergedSearchValue.toLowerCase())) | ||
| : tabs; |
There was a problem hiding this comment.
在 rc-tabs 中,tab.label 的类型是 React.ReactNode。如果用户传入了非字符串的 React 节点(例如包含图标或 HTML 标签的 <span>Tab 1</span>),直接使用 String(tab.label) 会得到 "[object Object]",导致搜索过滤失效,甚至在搜索 "object" 时错误地匹配到所有这类 Tab。
建议实现一个简单的文本提取函数,或者在过滤时安全地处理非字符串类型的 label。
const getLabelText = (node: React.ReactNode): string => {
if (!node) return '';
if (typeof node === 'string' || typeof node === 'number') {
return String(node);
}
if (React.isValidElement(node) && node.props && 'children' in node.props) {
return getLabelText(node.props.children);
}
if (Array.isArray(node)) {
return node.map(getLabelText).join('');
}
return '';
};
const filteredTabs = mergedSearchValue
? tabs.filter(tab => getLabelText(tab.label).toLowerCase().includes(mergedSearchValue.toLowerCase()))
: tabs;
| useEffect(() => { | ||
| if (!open) { | ||
| if (open) { | ||
| // 打开时,默认选中当前 activeKey 对应的 tab | ||
| if (!selectedKey && activeKey) { | ||
| setSelectedKey(activeKey); | ||
| } | ||
| } else { | ||
| setSelectedKey(null); | ||
| if (autoClearSearchValue && controlledSearchValue === undefined) { | ||
| setSearchValue(''); | ||
| } | ||
| } | ||
| }, [open]); | ||
| }, [open, activeKey]); |
There was a problem hiding this comment.
当启用搜索并输入关键字过滤 Tab 时,如果当前选中的 selectedKey 被过滤掉了(不再显示在列表中),按下 Enter 键仍然会触发 onTabClick(selectedKey),导致选中了一个已被隐藏的 Tab。此外,键盘上下键导航也会从一个不可见的项开始,导致体验不佳。
建议在 filteredTabs 变化时,如果当前的 selectedKey 不在过滤后的可见列表中,自动将 selectedKey 重置为过滤后列表中的第一个有效项。
useEffect(() => {
if (open) {
// 打开时,默认选中当前 activeKey 对应的 tab
if (!selectedKey && activeKey) {
setSelectedKey(activeKey);
}
} else {
setSelectedKey(null);
if (autoClearSearchValue && controlledSearchValue === undefined) {
setSearchValue('');
}
}
}, [open, activeKey]);
useEffect(() => {
if (open && isSearchable) {
const enabledTabs = filteredTabs.filter(tab => !tab.disabled);
if (enabledTabs.length > 0 && !enabledTabs.some(tab => tab.key === selectedKey)) {
setSelectedKey(enabledTabs[0].key);
} else if (enabledTabs.length === 0) {
setSelectedKey(null);
}
}
}, [open, filteredTabs, isSearchable, selectedKey]);
| const searchInput = isSearchable ? ( | ||
| <div className={`${dropdownPrefix}-search`}> | ||
| <input | ||
| type="text" | ||
| placeholder={placeholder} | ||
| value={mergedSearchValue} | ||
| onChange={e => { | ||
| const value = e.target.value; | ||
| setSearchValueFn(value); | ||
| onSearch?.(value); | ||
| }} | ||
| onKeyDown={e => { | ||
| if (e.key === 'ArrowDown') { | ||
| e.preventDefault(); | ||
| selectOffset(1); | ||
| } else if (e.key === 'ArrowUp') { | ||
| e.preventDefault(); | ||
| selectOffset(-1); | ||
| } else if (e.key === 'Enter' && selectedKey) { | ||
| e.preventDefault(); | ||
| onTabClick(selectedKey, e); | ||
| setOpen(false); | ||
| } | ||
| }} | ||
| onClick={e => e.stopPropagation()} | ||
| /> | ||
| </div> | ||
| ) : null; |
There was a problem hiding this comment.
为了提升用户体验和无障碍支持(Accessibility),建议在搜索框中加入以下改进:
- 自动聚焦(Auto-focus):当下拉菜单打开且启用了搜索时,搜索输入框应该自动获得焦点,方便用户直接开始输入。
- 支持 Esc 键关闭:在输入框中按下
Esc键时,应该能够关闭下拉菜单。
const searchInput = isSearchable ? (
<div className={`${dropdownPrefix}-search`}>
<input
ref={node => {
if (node && open && document.activeElement !== node) {
setTimeout(() => node.focus(), 0);
}
}}
type="text"
placeholder={placeholder}
value={mergedSearchValue}
onChange={e => {
const value = e.target.value;
setSearchValueFn(value);
onSearch?.(value);
}}
onKeyDown={e => {
if (e.key === 'ArrowDown') {
e.preventDefault();
selectOffset(1);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
selectOffset(-1);
} else if (e.key === 'Escape') {
e.preventDefault();
setOpen(false);
} else if (e.key === 'Enter' && selectedKey) {
e.preventDefault();
onTabClick(selectedKey, e);
setOpen(false);
}
}}
onClick={e => e.stopPropagation()}
/>
</div>
) : null;
There was a problem hiding this comment.
自动聚焦已经完成,esc 本身支持
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #992 +/- ##
==========================================
+ Coverage 98.98% 99.03% +0.04%
==========================================
Files 18 18
Lines 787 827 +40
Branches 232 256 +24
==========================================
+ Hits 779 819 +40
Misses 8 8 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
tests/overflow.test.tsx (1)
675-746: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win建议把回归测试补到关闭清空和键盘导航。
Line 675-746 目前只覆盖了输入渲染、筛选和
onSearch。这次改动里更容易回归的是默认autoClearSearchValue=true的关闭清空,以及ArrowUp/ArrowDown/Enter的键盘选择流程,建议顺手补上这两类断言。🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/overflow.test.tsx` around lines 675 - 746, Current tests in overflow.test.tsx only cover rendering, filtering, and onSearch in the search dropdown; add regression coverage for the default autoClearSearchValue=true behavior and the keyboard navigation/selection flow. Extend the existing overflow dropdown tests around getTabs, showSearch, and the rc-tabs-dropdown input to assert that the search value clears appropriately after selection when autoClearSearchValue is enabled. Also add key event coverage for ArrowUp, ArrowDown, and Enter to verify the dropdown item focus and selection path does not regress.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/examples/search-dropdown.tsx`:
- Around line 53-56: Search-dropdown 示例里的 Tabs 被固定为 activeKey="1" 且 onChange
被忽略,导致点击搜索结果切换标签无效;请在 search-dropdown.tsx 中为 Tabs 单独维护一个 activeKey 状态,并在
onChange 里更新它,让受控的 searchValue 与 tab 切换状态分离,保持示例可正常切换。
In `@README.md`:
- Around line 121-132: The new `more` / `MoreProps` API table entries in the
README are written in Chinese while the rest of the document is English; update
these descriptions to English to keep the public documentation language
consistent. Please revise the `MoreProps` section and its nested fields (`icon`,
`showSearch`, `placeholder`, `searchValue`, `onSearch`, `autoClearSearchValue`)
so the wording matches the surrounding README style.
In `@src/TabNavList/OperationNode.tsx`:
- Around line 145-147: `OperationNode` needs to keep `selectedKey` in sync with
the current `filteredTabs` result set. Update the selection logic around
`enabledTabs`, the Enter handler, and the `open`/`filteredTabs` effect so
`selectedKey` is always coerced to a valid key in the visible tabs (prefer
current `activeKey`, otherwise the first enabled tab, otherwise `null`). Also
fix the `findIndex(...) || 0` fallback in `OperationNode` so a missing match
does not preserve an invalid index, preventing keyboard confirm and highlight
from pointing at hidden tabs.
- Around line 80-82: The search filtering in OperationNode should not rely on
String(tab.label), because ReactNode labels can stringify to “[object Object]”
and fail in the “more” search. Update the filtering logic around filteredTabs to
use visible text derived from the tab label, or add a configurable filter text
source, so tabs with element labels still match correctly. Keep the fix
localized to the tab filtering path and preserve the existing Tabs API behavior.
---
Nitpick comments:
In `@tests/overflow.test.tsx`:
- Around line 675-746: Current tests in overflow.test.tsx only cover rendering,
filtering, and onSearch in the search dropdown; add regression coverage for the
default autoClearSearchValue=true behavior and the keyboard navigation/selection
flow. Extend the existing overflow dropdown tests around getTabs, showSearch,
and the rc-tabs-dropdown input to assert that the search value clears
appropriately after selection when autoClearSearchValue is enabled. Also add key
event coverage for ArrowUp, ArrowDown, and Enter to verify the dropdown item
focus and selection path does not regress.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: edab3f81-7197-4ef8-9dd1-712eb57eb981
📒 Files selected for processing (7)
README.mdassets/dropdown.lessdocs/demo/search-dropdown.mddocs/examples/search-dropdown.tsxsrc/TabNavList/OperationNode.tsxsrc/interface.tstests/overflow.test.tsx
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tests/overflow.test.tsx (1)
676-740: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win请把 fake timers 的恢复放进
try/finally或统一的 teardown。现在只有走到测试末尾才会执行
jest.useRealTimers();中间任一断言失败都会把 fake timers 泄漏到后续用例,造成串扰和偶发失败。可参考的改法
it('should have input and support keyboard navigation', () => { - jest.useFakeTimers(); - const onChange = jest.fn(); - const { container } = render( - getTabs({ - onChange, - ... - }), - ); - - ... - - jest.useRealTimers(); + jest.useFakeTimers(); + try { + const onChange = jest.fn(); + const { container } = render( + getTabs({ + onChange, + ... + }), + ); + + ... + } finally { + jest.useRealTimers(); + } });Also applies to: 744-781
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/overflow.test.tsx` around lines 676 - 740, Wrap the fake-timer setup in this test around the existing overflow dropdown flow with a try/finally (or move cleanup into a shared teardown) so `jest.useRealTimers()` always runs even if an assertion fails. Use the current test block in `tests/overflow.test.tsx` that calls `jest.useFakeTimers()`, `triggerResize`, and `fireEvent` interactions, and ensure the cleanup is tied to the test’s execution rather than the final line only to prevent timer leakage into later cases.
🧹 Nitpick comments (1)
tests/overflow.test.tsx (1)
675-742: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win建议补一条“关闭下拉后清空搜索值”的用例。
这次改动的核心行为之一就是关闭时重置搜索值,而当前新增用例还没有锁住这个默认契约;后续如果回归,现有测试捕不到。至少补一条关闭后再打开应为空的断言,最好再覆盖
autoClearSearchValue: false。Also applies to: 743-781
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/overflow.test.tsx` around lines 675 - 742, 现有新增用例只覆盖了搜索和键盘选择,没有验证关闭下拉后搜索值会被重置这一关键行为。请在相关测试中围绕 getTabs、showSearch 和下拉触发流程补充断言:关闭 Dropdown 后再次打开时 input 应为空,并最好再补一个 autoClearSearchValue 为 false 时不会清空的分支,确保默认契约被锁定。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@tests/overflow.test.tsx`:
- Around line 676-740: Wrap the fake-timer setup in this test around the
existing overflow dropdown flow with a try/finally (or move cleanup into a
shared teardown) so `jest.useRealTimers()` always runs even if an assertion
fails. Use the current test block in `tests/overflow.test.tsx` that calls
`jest.useFakeTimers()`, `triggerResize`, and `fireEvent` interactions, and
ensure the cleanup is tied to the test’s execution rather than the final line
only to prevent timer leakage into later cases.
---
Nitpick comments:
In `@tests/overflow.test.tsx`:
- Around line 675-742: 现有新增用例只覆盖了搜索和键盘选择,没有验证关闭下拉后搜索值会被重置这一关键行为。请在相关测试中围绕
getTabs、showSearch 和下拉触发流程补充断言:关闭 Dropdown 后再次打开时 input 应为空,并最好再补一个
autoClearSearchValue 为 false 时不会清空的分支,确保默认契约被锁定。
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 1c3ccb13-0aec-4d33-9020-79badd0aa09f
📒 Files selected for processing (1)
tests/overflow.test.tsx
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/overflow.test.tsx`:
- Around line 740-751: The “close and reopen” test is using Escape on the search
input, but OperationNode’s input onKeyDown does not handle that path; the real
close action is on the .rc-tabs-nav-more trigger. Update the
autoClearSearchValue: false test to close the dropdown by interacting with the
more button in TabNavList/OperationNode, then reopen it and assert the input
still contains the search value. Use the existing OperationNode dropdown and
input selectors so the test covers the actual close/reopen flow instead of
reusing the same open input.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f7df2792-f8ec-4b79-bd5f-ec560fa11c20
📒 Files selected for processing (1)
tests/overflow.test.tsx
…clarity for showSearch properties
…earch value handling in dropdown
…option and improve showSearch configuration
概述
为 Tabs 组件的更多下拉菜单添加搜索功能,类似于 Select 组件的 showSearch 特性。
相关 Issue
ant-design/ant-design#30719
改动内容
使用方法
测试结果
全部 76 个测试通过。
Summary by CodeRabbit
icon、占位符、受控/非受控searchValue、onSearch回调与autoClearSearchValue(可保留或自动清空)。MoreProps的showSearch配置说明与字段列表。