Skip to content

feat: combine search props #1152

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

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

Conversation

EmilyyyLiu
Copy link
Contributor

@EmilyyyLiu EmilyyyLiu commented May 21, 2025

ant-design/ant-design#33482
FRC: ant-design/ant-design#53978

Summary by CodeRabbit

  • 文档

    • 重新组织并完善了 rc-select 组件 API 文档,将所有搜索相关属性集中到新的 showSearch 小节,提升了文档的清晰度和可读性。
  • 重构

    • 将所有搜索相关配置整合为 showSearch 支持 boolean 或配置对象,简化并统一了搜索功能的配置方式,原有单独搜索属性标记为废弃。
  • 新功能

    • 支持通过 showSearch 配置对象集中管理搜索行为参数,提升了灵活性和扩展性。
    • 新增 useSearchConfig Hook,用于统一处理和管理搜索配置。
  • 测试

    • 增加了新旧 showSearch 配置方式的一致性测试,确保功能兼容与行为一致。

Copy link

vercel bot commented May 21, 2025

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

Name Status Preview Comments Updated (UTC)
select ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 18, 2025 7:51am

Copy link
Contributor

coderabbitai bot commented May 21, 2025

"""

Walkthrough

此次更改对 Select 组件的搜索相关配置进行了重构。将原本分散的搜索相关属性集中到一个新的 SearchConfig 配置对象,并通过 showSearch 属性统一管理。文档和测试也同步更新,明确新旧用法的兼容性和行为一致性。

Changes

文件/分组 变更摘要
README.md 重组并细化 rc-select 组件 API 文档,将所有搜索相关属性集中到 showSearch 子章节,并更新类型说明。
src/Select.tsx 引入 SearchConfig 接口,重构 SelectProps,废弃原有分散的搜索相关属性,统一由 showSearch 管理,内部通过新 hook useSearchConfig 处理。
src/hooks/useSearchConfig.ts 新增 useSearchConfig hook,用于兼容和合并新旧搜索配置,返回统一的搜索开关和配置对象。
tests/Select.test.tsx 新增“combine showSearch”测试组,对比新旧 showSearch 用法下各项搜索功能的行为一致性。

Sequence Diagram(s)

sequenceDiagram
    participant 用户 as User
    participant Select组件 as Select
    participant useSearchConfig钩子 as useSearchConfig
    participant BaseSelect

    用户->>Select组件: 传入 showSearch(布尔值或对象)及其他 props
    Select组件->>useSearchConfig钩子: 传递 showSearch 和 props
    useSearchConfig钩子-->>Select组件: 返回 mergedShowSearch, searchConfig
    Select组件->>BaseSelect: 传递 mergedShowSearch、searchConfig 等参数
    用户->>Select组件: 触发搜索相关操作(如输入、选择)
    Select组件->>BaseSelect: 处理并响应搜索行为
Loading

Suggested reviewers

  • zombieJ

Poem

小兔挥动键盘键,
搜索配置变得新鲜。
showSearch 一统江湖,
配置集中不再分散。
测试验证保平安,
代码整洁心也甜!
(⁎˃ᴗ˂⁎)/
"""

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.

tests/Select.test.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Cannot read config file: /.eslintrc.js
Error: Cannot find module '@umijs/fabric/dist/eslint'
Require stack:

  • /.eslintrc.js
  • /node_modules/.pnpm/@eslint[email protected]/node_modules/@eslint/eslintrc/dist/eslintrc.cjs
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/cli-engine/cli-engine.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/eslint.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/index.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/cli.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/bin/eslint.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1405:15)
    at defaultResolveImpl (node:internal/modules/cjs/loader:1061:19)
    at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1066:22)
    at Module._load (node:internal/modules/cjs/loader:1215:37)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)
    at Module.require (node:internal/modules/cjs/loader:1491:12)
    at require (node:internal/modules/helpers:135:16)
    at Object. (/.eslintrc.js:1:14)
    at Module._compile (node:internal/modules/cjs/loader:1734:14)

📜 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 360bfd5 and 66476c8.

📒 Files selected for processing (1)
  • tests/Select.test.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/Select.test.tsx
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in 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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests 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.

@EmilyyyLiu EmilyyyLiu force-pushed the combine-showSearch branch from 9f851c3 to a76b137 Compare June 13, 2025 06:11
@EmilyyyLiu EmilyyyLiu marked this pull request as ready for review June 13, 2025 06:12
Copy link

codecov bot commented Jun 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.24%. Comparing base (7aa0c21) to head (66476c8).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1152      +/-   ##
==========================================
+ Coverage   98.23%   98.24%   +0.01%     
==========================================
  Files          38       39       +1     
  Lines        1471     1480       +9     
  Branches      446      441       -5     
==========================================
+ Hits         1445     1454       +9     
  Misses         26       26              

☔ 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.

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: 2

🧹 Nitpick comments (5)
src/Select.tsx (3)

230-241: autoClearSearchValueshowSearch={false} 时仍默认为 true

showSearch 显式为 false 时,useSearchConfig 返回的 searchConfig 为空对象,但此处解构时仍将 autoClearSearchValue 设为 true,随后传递给 BaseSelect
虽然目前 BaseSelect 在关闭搜索时大概率忽略该字段,但多余的默认值会增加认知负担,也容易在后续重构时产生意外行为。建议仅在开启搜索时才赋默认值:

-      autoClearSearchValue = true,
+      autoClearSearchValue = mergedShowSearch ? true : undefined,

或直接在传参时用条件运算符包裹。


387-388: 补充 modesetSearchValueuseEffect 依赖

react-hooks/exhaustive-deps 已报告缺失;若后续有人将 setSearchValue 通过 useCallback 包裹,会导致闭包捕获旧引用。按规则补全依赖或显式禁用 eslint 规则。

🧰 Tools
🪛 GitHub Actions: ✅ test

[warning] 387-387: React Hook React.useEffect has missing dependencies: 'mode' and 'setSearchValue'. Either include them or remove the dependency array. (react-hooks/exhaustive-deps)


470-477: useMemo 缺少 sorter 依赖

同样的 ESLint 告警,理论上 sorter 在每次渲染都会重新创建,但若以后将其提取为 useCallback,缺失依赖会导致排序逻辑卡在旧版本。请补充或禁用。

🧰 Tools
🪛 GitHub Actions: ✅ test

[warning] 476-476: React Hook React.useMemo has a missing dependency: 'sorter'. Either include it or remove the dependency array. (react-hooks/exhaustive-deps)

tests/Select.test.tsx (1)

2556-2560: combine showSearch 套件中复用 jest.fn,避免跨测试污染

currentSearchFnlegacySearchFn 定义于顶层,会在多个 it 之间共享调用计数,潜在引起断言错误。可改为在 beforeEach 中重新声明。

README.md (1)

141-141: 小语法:考虑在 “auto clear” 之间加连字符

auto-clear search input value 更符合英文习惯,可与其他行保持一致性。

🧰 Tools
🪛 LanguageTool

[uncategorized] ~141-~141: It appears that a hyphen is missing (if ‘auto’ is not used in the context of ‘cars’).
Context: ... | --- | --- | | autoClearSearchValue | auto clear search input value when multiple select...

(AUTO_HYPHEN)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7aa0c21 and a76b137.

📒 Files selected for processing (4)
  • README.md (2 hunks)
  • src/Select.tsx (5 hunks)
  • src/hooks/useSearchConfig.ts (1 hunks)
  • tests/Select.test.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/hooks/useSearchConfig.ts (1)
src/Select.tsx (2)
  • SearchConfig (114-123)
  • DefaultOptionType (99-103)
🪛 LanguageTool
README.md

[uncategorized] ~141-~141: It appears that a hyphen is missing (if ‘auto’ is not used in the context of ‘cars’).
Context: ... | --- | --- | | autoClearSearchValue | auto clear search input value when multiple select...

(AUTO_HYPHEN)

🪛 GitHub Actions: ✅ test
tests/Select.test.tsx

[error] 1-1: 'DefaultOptionType' is defined but never used. (typescript-eslint/no-unused-vars)


[error] 1-1: 'SearchConfig' is defined but never used. (typescript-eslint/no-unused-vars)

src/hooks/useSearchConfig.ts

[warning] 29-29: React Hook React.useMemo has a missing dependency: 'props'. Preferred fix is to destructure 'props' outside useMemo. (react-hooks/exhaustive-deps)

src/Select.tsx

[warning] 387-387: React Hook React.useEffect has missing dependencies: 'mode' and 'setSearchValue'. Either include them or remove the dependency array. (react-hooks/exhaustive-deps)


[warning] 476-476: React Hook React.useMemo has a missing dependency: 'sorter'. Either include it or remove the dependency array. (react-hooks/exhaustive-deps)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: WIP
🔇 Additional comments (1)
tests/Select.test.tsx (1)

2524-2540: 删除遗留注释块,保持测试文件简洁

这里的大段注释仅为示例代码,既不会执行,也容易与正式测试混淆。建议彻底删除。

-// searchValue?: string;
-//   autoClearSearchValue?: boolean;
-//   onSearch?: (value: string) => void;
-//   tokenSeparators?: string[];
-//   filterOption?: boolean | FilterFunc<OptionType>;
-//   filterSort?: (optionA: OptionType, optionB: OptionType, info: { searchValue: string }) => number;
-//   optionFilterProp?: string;
-//   optionLabelProp?: string;
-//  const props = {
-//   ...
-// };

[ suggest_optional_refactor ]

@EmilyyyLiu EmilyyyLiu changed the title [WIP]feat: combine search props feat: combine search props Jun 13, 2025
@zombieJ zombieJ requested a review from Copilot June 16, 2025 08:14
Copilot

This comment was marked as outdated.

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: 0

🧹 Nitpick comments (2)
src/hooks/useSearchConfig.ts (2)

3-33: legacySearchProps 未被使用且导致重复代码,可顺便过滤掉 undefined 字段

当前常量 legacySearchProps 定义后并未在后续逻辑中使用,CodeQL 已提示未使用变量。同时,legacyShowSearch 对象手动枚举了同样的字段,既冗余也会把 undefined 值写入结果对象。建议直接复用 legacySearchProps 来动态收集旧属性,并跳过 undefined,既消除警告,也避免对象出现无意义键。示例修正:

-const legacySearchProps = [
-  'filterOption',
-  'searchValue',
-  'optionFilterProp',
-  'filterSort',
-  'onSearch',
-  'autoClearSearchValue',
-];
+const legacySearchProps = [
+  'filterOption',
+  'searchValue',
+  'optionFilterProp',
+  'filterSort',
+  'onSearch',
+  'autoClearSearchValue',
+] as const;
...
-    const legacyShowSearch: SearchConfig<DefaultOptionType> = {
-      filterOption,
-      searchValue,
-      optionFilterProp,
-      filterSort,
-      onSearch,
-      autoClearSearchValue,
-    };
+    const legacyShowSearch: SearchConfig<DefaultOptionType> = {};
+    legacySearchProps.forEach((key) => {
+      const val = (props as any)[key];
+      if (val !== undefined) {
+        (legacyShowSearch as any)[key] = val;
+      }
+    });

如此一来可保持字段一次性维护,减少后续修改遗漏。

🧰 Tools
🪛 GitHub Check: CodeQL

[notice] 3-3: Unused variable, import, function or class
Unused variable legacySearchProps.


12-15: propsOptionType 增加泛型,消除潜在的 any 漏出

SelectProps 本身是带泛型的,此处直接使用裸类型会丢失类型信息,调用方无法得到正确推导。可以如下声明:

-export default function useSearchConfig(
-  showSearch: boolean | SearchConfig<DefaultOptionType> | undefined,
-  props: SelectProps,
-) {
+export default function useSearchConfig<
+  OptionType extends DefaultOptionType = DefaultOptionType,
+>(
+  showSearch: boolean | SearchConfig<OptionType> | undefined,
+  props: SelectProps<any, OptionType>,
+) {

这样 searchConfig 的回传类型也能随 OptionType 联动,保持类型安全。

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8331c62 and 5b683b8.

📒 Files selected for processing (1)
  • src/hooks/useSearchConfig.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/hooks/useSearchConfig.ts (1)
src/Select.tsx (3)
  • SearchConfig (114-121)
  • DefaultOptionType (99-103)
  • SelectProps (122-182)
🪛 GitHub Check: CodeQL
src/hooks/useSearchConfig.ts

[notice] 3-3: Unused variable, import, function or class
Unused variable legacySearchProps.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test / react component workflow
🔇 Additional comments (1)
src/hooks/useSearchConfig.ts (1)

34-39: showSearch === undefined 的分支行为需再次确认

showSearchundefined 且存在旧搜索相关属性时,当前实现返回 [undefined, legacyShowSearch]。如果上层逻辑仅用 !!enabled 判断是否开启搜索,undefined 会被当作 false,导致“有配置却不开启”——这与旧版 API(只要给旧属性就自动开启搜索)不一致。请确认 Select 组件对第一项的判定规则,必要时考虑改为返回 true

EmilyyyLiu and others added 2 commits June 16, 2025 17:08
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR centralizes all search-related props into a single showSearch configuration, introduces a hook to normalize these options, and updates component logic, tests, and documentation accordingly.

  • Unify search props under a new showSearch API supporting boolean or detailed object.
  • Add useSearchConfig hook to process and merge legacy and new search options.
  • Refactor Select component to consume the unified config and refresh docs and tests.

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
tests/Select.test.tsx Add combine showSearch test suite comparing legacy vs current.
src/hooks/useSearchConfig.ts New hook to derive search enablement and config from props.
src/Select.tsx Integrate useSearchConfig and pass merged search settings.
README.md Document showSearch option group and update API table.
Comments suppressed due to low confidence (3)

tests/Select.test.tsx:2604

  • [nitpick] The test title has inconsistent casing and punctuation. Consider renaming to something like it('sort options with filterSort and optionFilterProp', ...) for clarity.
    it('option:sort,FilterProp ', () => {

tests/Select.test.tsx:2525

  • Add a test case covering the filterOption configuration to verify that a custom filter function is applied correctly when showSearch is an object.
  describe('combine showSearch', () => {

README.md:92

  • Update the type column to reference the actual config interface, e.g., boolean \| SearchConfig, to accurately document the supported object shape.
| showSearch | whether show search input in single mode | boolean \| Object | true |

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: 0

🧹 Nitpick comments (2)
src/hooks/useSearchConfig.ts (2)

17-26: 建议过滤掉 undefined 字段,避免下游出现“存在但为 undefined”判断差异

当前直接扩展所有旧 props,searchConfig 中会保留下大量值为 undefined 的 key。
这在后续通过 inhasOwnProperty 判断字段是否存在时会产生歧义,也会导致序列化体积偏大。

-    const searchConfig = {
-      filterOption,
-      searchValue,
-      optionFilterProp,
-      filterSort,
-      onSearch,
-      autoClearSearchValue,
-      ...(typeof showSearch === 'object' ? showSearch : {}),
-    };
+    const searchConfig = Object.fromEntries(
+      Object.entries({
+        filterOption,
+        searchValue,
+        optionFilterProp,
+        filterSort,
+        onSearch,
+        autoClearSearchValue,
+        ...(typeof showSearch === 'object' ? showSearch : {}),
+      }).filter(([, v]) => v !== undefined),
+    ) as SearchConfig<DefaultOptionType>;

这样可以保证配置对象紧凑且语义清晰。


28-34: 返回元组第一位的三态布尔值可读性一般,考虑显式常量

false / undefined / true 三态依赖调用方额外注释才能快速辨认。可以考虑返回枚举或常量,比如 'disabled' | 'inherit' | 'enabled',提升可读性与类型安全。

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2222c64 and 1ae5527.

📒 Files selected for processing (2)
  • src/Select.tsx (6 hunks)
  • src/hooks/useSearchConfig.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Select.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/hooks/useSearchConfig.ts (1)
src/Select.tsx (3)
  • SearchConfig (114-121)
  • DefaultOptionType (99-103)
  • SelectProps (122-182)

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.

3 participants