Skip to content

Conversation

QdabuliuQ
Copy link
Contributor

@QdabuliuQ QdabuliuQ commented Jul 28, 2025

🤔 This is a ...

  • 🆕 New feature
  • 🐞 Bug fix
  • 📝 Site / documentation improvement
  • 📽️ Demo improvement
  • 💄 Component style improvement
  • 🤖 TypeScript definition improvement
  • 📦 Bundle size optimization
  • ⚡️ Performance optimization
  • ⭐️ Feature enhancement
  • 🌐 Internationalization
  • 🛠 Refactoring
  • 🎨 Code style optimization
  • ✅ Test Case
  • 🔀 Branch merge
  • ⏩ Workflow
  • ⌨️ Accessibility improvement
  • ❓ Other (about what?)

🔗 Related Issues

fix ant-design/ant-design#54444
close ant-design/ant-design#54447
close #18

💡 Background and Solution

Input.Textarea cursor position error after pasting text
Listen to onPaste event and recalculate cursor position

📝 Change Log

Language Changelog
🇺🇸 English fix textarea cursor position error after pasting text
🇨🇳 Chinese 修复粘贴文本后 textarea 光标位置错误

Summary by CodeRabbit

  • Bug Fixes

    • 修复了仅在 Firefox 浏览器下自动滚动行为异常的问题。
  • Tests

    • 新增了关于粘贴多行文本后光标位置变化的测试用例。
    • 优化了自动高度调整时的滚动测试,提升了测试稳定性。

Copy link

coderabbitai bot commented Jul 28, 2025

Walkthrough

本次更改主要涉及在 src/ResizableTextArea.tsx 文件中对 Firefox 浏览器的检测与兼容性处理,以及在 tests/index.spec.tsx 文件中新增和调整了与粘贴行为及光标位置相关的测试用例。未涉及导出实体的声明或签名变更。

Changes

Cohort / File(s) Change Summary
Firefox兼容性修复
src/ResizableTextArea.tsx
新增对 Firefox 浏览器的检测,仅在 Firefox 下执行特定的光标修正逻辑;调整属性解构顺序;优化 import 顺序。
粘贴行为测试增强
tests/index.spec.tsx
新增“粘贴文本应改变光标位置”测试用例,验证粘贴多行文本后光标位置正确;调整“autoSize时滚动到底部”测试,规避浏览器兼容性问题。

Estimated code review effort

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

Assessment against linked issues

Objective Addressed Explanation
粘贴末尾为空行的文本时,autoResize 启用下,光标应正确设置到文本末尾(#54444)
仅在 Firefox 浏览器下修正光标异常问题(#54444)
新增或调整测试用例,验证上述粘贴及光标行为(#54444)

Poem

小兔写码乐无边,
粘贴空行不再烦。
Firefox 巧检测,
光标归位心也安。
测试加持更周全,
代码世界跃新篇!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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
🪧 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 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.

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 (2)
src/ResizableTextArea.tsx (1)

69-69: Firefox 检测实现可以优化。

当前使用 navigator.userAgent.includes('Firefox') 检测 Firefox 浏览器。虽然功能正确,但用户代理字符串检测不够健壮,可能被用户修改或伪造。

考虑使用更可靠的特性检测方法:

-        const isFirefox = navigator.userAgent.includes('Firefox');
+        const isFirefox = typeof InstallTrigger !== 'undefined';

或者添加备用检测:

-        const isFirefox = navigator.userAgent.includes('Firefox');
+        const isFirefox = navigator.userAgent.includes('Firefox') || typeof InstallTrigger !== 'undefined';
tests/index.spec.tsx (1)

40-74: 粘贴测试用例实现良好,但可以改进。

这个测试用例正确验证了粘贴多行文本后的光标位置处理,与 PR 目标一致。测试模拟了粘贴事件、文本变更和光标设置。

建议以下改进:

  1. 简化测试逻辑,避免重复的 pasteEvent 函数:
-    const pasteEvent = async () => {
-      fireEvent.focus(textArea);
-
-      fireEvent.paste(textArea, {
-        clipboardData,
-        types: ['text/plain'],
-        items: [],
-      });
-
-      fireEvent.change(textArea, { target: { value: pasteData } });
-      textArea.setSelectionRange(pasteData.length, pasteData.length);
-
-      await wait();
-      expect(textArea.selectionStart).toBe(pasteData.length);
-      expect(textArea.selectionEnd).toBe(pasteData.length);
-      fireEvent.change(textArea, { target: { value: '' } });
-      await wait();
-      expect(textArea.selectionStart).toBe(0);
-      expect(textArea.selectionEnd).toBe(0);
-    };
-
-    await pasteEvent();
-    await pasteEvent();
+    fireEvent.focus(textArea);
+
+    fireEvent.paste(textArea, {
+      clipboardData,
+      types: ['text/plain'],
+      items: [],
+    });
+
+    fireEvent.change(textArea, { target: { value: pasteData } });
+    textArea.setSelectionRange(pasteData.length, pasteData.length);
+
+    await wait();
+    expect(textArea.selectionStart).toBe(pasteData.length);
+    expect(textArea.selectionEnd).toBe(pasteData.length);
+    
+    fireEvent.change(textArea, { target: { value: '' } });
+    await wait();
+    expect(textArea.selectionStart).toBe(0);
+    expect(textArea.selectionEnd).toBe(0);
  1. 添加对粘贴内容包含尾随空行的特定测试(根据 issue #54444):
it('paste text with trailing empty lines should position cursor correctly', async () => {
  const { container } = render(
    <TextArea autoSize={{ minRows: 2, maxRows: 6 }} />,
  );
  const textArea = container.querySelector('textarea') as HTMLTextAreaElement;
  const pasteData = 'line1\nline2\n\n'; // 包含尾随空行
  
  fireEvent.focus(textArea);
  fireEvent.paste(textArea, {
    clipboardData: { getData: jest.fn().mockReturnValue(pasteData) },
  });
  fireEvent.change(textArea, { target: { value: pasteData } });
  
  await wait();
  expect(textArea.selectionStart).toBe(pasteData.length);
  expect(textArea.selectionEnd).toBe(pasteData.length);
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bca6b27 and aeb366c.

📒 Files selected for processing (2)
  • src/ResizableTextArea.tsx (2 hunks)
  • tests/index.spec.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/index.spec.tsx (1)
tests/utils.ts (1)
  • wait (24-31)
🔇 Additional comments (4)
src/ResizableTextArea.tsx (3)

5-5: 代码导入顺序调整合理。

classNames 的导入移到 raf 之后,保持了导入的一致性。


71-71: Firefox 特定修复逻辑优化得当。

添加 Firefox 检测条件避免了在其他浏览器中执行不必要的修复逻辑,这是一个很好的性能优化。只有在 Firefox 浏览器且 textarea 是活动元素时才执行修复。


72-73: 属性解构顺序调整无功能影响。

scrollTop 移到前面的解构顺序调整不会影响功能,这只是代码组织的变化。

tests/index.spec.tsx (1)

274-290: 移除不稳定的光标位置断言是明智的选择。

注释掉 setSelectionRange 的监听和断言可以避免跨浏览器的光标位置差异导致的测试不稳定,改为验证 scrollTop 等于 scrollHeight 更加可靠。这与 issue #54444 中提到的浏览器差异问题相符。

注释中正确引用了相关 issue,说明了移除这些断言的原因。

Copy link

codecov bot commented Jul 28, 2025

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##           master      #72      +/-   ##
==========================================
- Coverage   99.03%   97.60%   -1.44%     
==========================================
  Files           3        3              
  Lines         208      209       +1     
  Branches       63       63              
==========================================
- Hits          206      204       -2     
- Misses          2        5       +3     

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

@afc163 afc163 merged commit c6bee0d into react-component:master Jul 28, 2025
6 of 7 checks passed
@li-jia-nan
Copy link
Member

antd 侧有个用例挂了:
image

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.

Input.Textarea的autoResize启用时,在空白区域粘贴末尾为空行的文本后光标位置没有设置到正确的地方
3 participants