Skip to content

Conversation

@zombieJ
Copy link
Member

@zombieJ zombieJ commented Jan 29, 2026

做一个格式化 id function 到 rc-tree 里使用:

截屏2026-01-29 14 20 56

Summary by CodeRabbit

  • 新增功能

    • 新增键值清理功能:自动将包含空格和特殊字符的键规范为使用连字符的标识符,改善 ID 一致性与可读性。
  • 测试

    • 添加了针对键值清理行为的验证用例,确保不同格式输入被正确规范化。

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Jan 29, 2026

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

Project Deployment Review Updated (UTC)
util Ready Ready Preview, Comment Jan 29, 2026 6:24am

@coderabbitai
Copy link

coderabbitai bot commented Jan 29, 2026

Walkthrough

新增公开函数 getId(prefix: string, key: string),用于将 key 中的无效字符替换为连字符并返回与前缀拼接的 ID;同时新增对应单元测试来验证该函数的清理行为;package.json 有小量更改行数。

Changes

Cohort / File(s) Summary
ID 清理功能
src/hooks/useId.ts
新增导出函数 getId(prefix: string, key: string),对 key 中的空格和非法字符进行替换并返回拼接的 ID。
测试
tests/hooks.test.tsx
新增测试用例 should sanitize keys with invalid characters,验证 getId 对包含空格、特殊字符和混合分隔符的 key 进行正确清理。
包元信息
package.json
轻微变更(约 +15 行),元数据或脚本相关的小幅调整。

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 分钟

Poem

🐰 新函数轻跳出笼,
把杂乱字符化作连线,
空格、符号都乖乖走,
ID 排列又整齐,
测试点头,代码笑吟吟 ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题准确总结了主要变更,即添加了新的 getId 函数来支持格式化 ID 生成。
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch getId

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.

@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 introduces a new getId utility function to standardize the generation of HTML-compliant IDs within the project, particularly for use in rc-tree. The function automatically cleans up input keys by replacing non-standard characters with hyphens, preventing issues with invalid HTML IDs. This enhancement improves the robustness of ID generation and is thoroughly tested to ensure correct behavior.

Highlights

  • New getId Utility Function: Introduced a new getId function in src/hooks/useId.ts. This function is designed to generate valid HTML IDs by taking a prefix and a key, then sanitizing the key by replacing any characters not allowed in HTML IDs (e.g., spaces, @, #, /, \) with hyphens. This ensures that generated IDs are compliant with HTML specifications.
  • Enhanced Test Coverage for ID Generation: New test cases have been added to tests/hooks.test.tsx to thoroughly validate the getId function. These tests cover various scenarios, including keys with spaces, special characters, and combinations of valid and invalid characters, ensuring the sanitization logic works as expected.

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

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.

@codecov
Copy link

codecov bot commented Jan 29, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.34%. Comparing base (a19f387) to head (77c0064).
⚠️ Report is 5 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #724      +/-   ##
==========================================
+ Coverage   85.92%   86.34%   +0.42%     
==========================================
  Files          38       38              
  Lines        1016     1040      +24     
  Branches      380      371       -9     
==========================================
+ Hits          873      898      +25     
  Misses        141      141              
+ Partials        2        1       -1     

☔ 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

@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

这个 PR 添加了一个工具函数 getId 用于生成合法的 HTML ID,并为其添加了相应的测试。这是一个实用的功能。然而,实现中存在一个严重的 bug:用于清理 key 的正则表达式不正确,导致其行为与预期和文档不符。我已经提供了一个修复建议。

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@zombieJ zombieJ merged commit d99419f into master Jan 29, 2026
9 of 10 checks passed
@zombieJ zombieJ deleted the getId branch January 29, 2026 06:25
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

🤖 Fix all issues with AI agents
In `@src/hooks/useId.ts`:
- Around line 28-33: Change getId to accept React-compatible key types (e.g.,
string | number | bigint | null | undefined) instead of only string, then
normalize the incoming key to a safe string before sanitization: treat
null/undefined as an empty string, convert numbers and bigints with toString(),
and then apply the existing regex sanitization; update the function signature
(getId) and any callers/types accordingly so it no longer assumes a string
input.
🧹 Nitpick comments (1)
src/hooks/useId.ts (1)

29-33: 注意非法字符替换可能导致 ID 冲突

'a b''a-b' 会被规范化为同一个 ID。若该 ID 用于 DOM/ARIA 关联,可能出现重复冲突。建议至少在文档中说明唯一性要求,或在发生替换时追加短 hash/转义以保持唯一性。

Comment on lines +28 to +33
export function getId(prefix: string, key: string): string {
// Valid id characters: letters, digits, hyphen, underscore, colon, period
// Replace all invalid characters (including spaces) with hyphens to preserve length
const sanitizedKey = key.replace(/[^a-zA-Z0-9_.:-]/g, '-');

return `${prefix}-${sanitizedKey}`;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the actual file
cat -n src/hooks/useId.ts

Repository: react-component/util

Length of output: 2688


🏁 Script executed:

# Search for how getId is being called to understand usage patterns
rg "getId" --type ts --type tsx -B 2 -A 2

Repository: react-component/util

Length of output: 91


🌐 Web query:

React.Key type definition React 18 - what types are included in React.Key?

💡 Result:

In React 18’s TypeScript types (@types/react), React.Key is defined as:

And the JSX key attribute is typed as:

Citations:


🏁 Script executed:

# Search for getId function calls to understand usage patterns
rg "getId\(" --type ts -B 2 -A 2

Repository: react-component/util

Length of output: 1160


🏁 Script executed:

# Also check if this is exported/used elsewhere
rg "from.*useId|import.*getId" --type ts --type tsx

Repository: react-component/util

Length of output: 91


🏁 Script executed:

# Check if there are any tests or examples showing how getId should be used
fd -e test.ts -e spec.ts -e example.ts | head -20

Repository: react-component/util

Length of output: 392


React 元素 key 类型与入参类型不匹配,存在运行时风险

JSDoc 注释声称该函数处理"React 元素的 key",但 React.Key 的实际类型为 string | number | bigint(JSX 上下文中还可以是 null | undefined)。当前函数签名仅接受 string 参数,若调用者传入数字或其他类型的 React element key,将在运行时抛错。建议扩大入参类型并添加类型安全的规范化处理。

🧩 修复建议
-export function getId(prefix: string, key: string): string {
+export function getId(prefix: string, key: React.Key): string {
+  const normalizedKey = key == null ? '' : String(key);
   // Valid id characters: letters, digits, hyphen, underscore, colon, period
   // Replace all invalid characters (including spaces) with hyphens to preserve length
-  const sanitizedKey = key.replace(/[^a-zA-Z0-9_.:-]/g, '-');
+  const sanitizedKey = normalizedKey.replace(/[^a-zA-Z0-9_.:-]/g, '-');

   return `${prefix}-${sanitizedKey}`;
 }
📝 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
export function getId(prefix: string, key: string): string {
// Valid id characters: letters, digits, hyphen, underscore, colon, period
// Replace all invalid characters (including spaces) with hyphens to preserve length
const sanitizedKey = key.replace(/[^a-zA-Z0-9_.:-]/g, '-');
return `${prefix}-${sanitizedKey}`;
export function getId(prefix: string, key: React.Key): string {
const normalizedKey = key == null ? '' : String(key);
// Valid id characters: letters, digits, hyphen, underscore, colon, period
// Replace all invalid characters (including spaces) with hyphens to preserve length
const sanitizedKey = normalizedKey.replace(/[^a-zA-Z0-9_.:-]/g, '-');
return `${prefix}-${sanitizedKey}`;
}
🤖 Prompt for AI Agents
In `@src/hooks/useId.ts` around lines 28 - 33, Change getId to accept
React-compatible key types (e.g., string | number | bigint | null | undefined)
instead of only string, then normalize the incoming key to a safe string before
sanitization: treat null/undefined as an empty string, convert numbers and
bigints with toString(), and then apply the existing regex sanitization; update
the function signature (getId) and any callers/types accordingly so it no longer
assumes a string input.

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