Skip to content
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

feat: Remove findDOMNode from rc-css-motion #59

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

Conversation

Roxannej
Copy link

@Roxannej Roxannej commented Jan 5, 2025

issue:ant-design/ant-design#52115

Remove findDOMNode from rc-css-motion的问题修复

Summary by CodeRabbit

  • 重构

    • 简化了 CSSMotion 组件中获取 DOM 元素的方法
    • 移除了对已弃用的 findDOMNode 方法的使用
  • 测试

    • 更新测试套件,移除对 ReactDOM.findDOMNode 的依赖
    • 优化测试用例,使用更直接的 DOM 元素查询方法
    • 改进了对组件可见性状态的测试

这些更改提高了代码的可读性和维护性,同时遵循了现代 React 最佳实践。

Copy link

vercel bot commented Jan 5, 2025

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

Name Status Preview Comments Updated (UTC)
motion ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 5, 2025 1:11pm

Copy link

coderabbitai bot commented Jan 5, 2025

概述

遍历

CSSMotion 组件的 src/CSSMotion.tsx 文件中,对 getDomElement 函数进行了重大修改。移除了使用已弃用的 findDOMNode 方法的尝试性代码,简化了 DOM 元素检索的逻辑。测试文件 tests/CSSMotion.spec.tsx 也相应地更新,移除了对 findDOMNode 的依赖,并优化了测试断言方法。

变更

文件 变更摘要
src/CSSMotion.tsx 简化 getDomElement 函数,移除 findDOMNode 相关代码
tests/CSSMotion.spec.tsx 更新测试用例,移除 ReactDOM.findDOMNode,直接使用 DOM 查询

诗歌

🐰 代码兔子轻跳跃
DOM 元素寻踪快
重构路上无阻挡
简洁明了是真谛
测试闪耀新光芒 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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 (1)
src/CSSMotion.tsx (1)

143-145: 建议添加空值检查以提高健壮性。

此处直接根据 nodeRef.current 是否是 HTMLElement 来决定返回值,做法简洁且符合现代 React 不建议使用 findDOMNode 的实践。不过,如果 nodeRef.currentwrapperNodeRef.current 均为 null 或未定义,可能会导致后续引用报错。建议在返回前做好空值检查,以便在极端场景下能优雅处理。

可考虑如下改进:

function getDomElement() {
+  if (!nodeRef.current && !wrapperNodeRef.current) {
+    return null;
+  }
  return nodeRef.current instanceof HTMLElement
    ? nodeRef.current
    : wrapperNodeRef.current;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 96996a1 and ddab4ff.

📒 Files selected for processing (2)
  • src/CSSMotion.tsx (1 hunks)
  • tests/CSSMotion.spec.tsx (1 hunks)
🔇 Additional comments (2)
tests/CSSMotion.spec.tsx (2)

833-843: 测试逻辑清晰,符合无 ref 传递场景的需求。

该测试通过直接渲染一个普通的 div 并检查其是否被成功挂载,说明移除 findDOMNode 不影响正常 DOM 渲染。整体实现简单明了,保障了在严格模式下的正确性。


846-854: 测试逻辑恰当,验证了传递内部 ref 的正确性。

该用例确保当我们在子组件内部将 ref 传给真实 DOM 时,DOM 能够成功挂载并被检测到,进一步保证了移除 findDOMNode 后的可用性。

@aojunhao123
Copy link

ci挂了

@Roxannej
Copy link
Author

Roxannej commented Jan 5, 2025

ci挂了

我再改下

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 (4)
tests/CSSMotion.spec.tsx (4)

298-301: 建议添加 cleanup 逻辑

虽然 mock addEventListener 是必要的,但建议在 afterAll 中清理这个 spy。

 beforeAll(() => {
   jest.spyOn(document, 'addEventListener').mockImplementation(() => {});
 });
+afterAll(() => {
+  jest.restoreAllMocks();
+});

339-339: 简化 ref 转发实现

当前的注释和实现可以更简洁。

-          return <div ref={ref} {...props} />; // 使用 forwardRef 正确转发 ref
+          return <div {...props} ref={ref} />;

343-364: 优化测试用例结构和断言

测试用例结构良好,但可以进一步改进:

  1. 移除冗余的注释
  2. 使用更具描述性的测试名称
  3. 添加更多边缘情况的测试
-      it('FC with ref', () => {
+      it('should correctly forward ref in functional component', () => {
         const ref = React.createRef<HTMLDivElement>();
-        // 使用 act 包裹渲染过程,确保状态更新
-        let container;
+        let container: HTMLElement;
         act(() => {
-          // 仅在 act 内进行渲染,以确保是同步的
           const { container: renderedContainer } = render(
-            <ForwardedComponent ref={ref} visible={true} />, // visible 为布尔值
+            <ForwardedComponent ref={ref} visible={true} />,
           );
-          container = renderedContainer; // 获取容器
+          container = renderedContainer;
         });

-        // 获取 div 元素,确保其正确渲染
         const div = container.querySelector('div');

-        // 确保 div 元素渲染
         expect(div).toBeTruthy();
-        // 确保 ref 被正确绑定到 div 元素
         expect(ref.current).toBe(div);
+        
+        // Test visibility toggle
+        act(() => {
+          render(<ForwardedComponent ref={ref} visible={false} />, { container });
+        });
+        expect(div.style.display).toBe('none');
       });

855-876: 完善严格模式测试覆盖

测试用例覆盖了基本场景,但建议添加更多边缘情况的测试:

  1. 组件卸载时的行为
  2. 多次渲染时的行为
  3. 错误处理场景
     it('renders correctly when no ref is passed', () => {
       const Div = () => <div />;
 
       const { container } = render(
         <CSSMotion motionName="transition" visible>
           {(props, ref) => <Div {...props} ref={ref} />}
         </CSSMotion>,
       );
 
-      // 检查 DOM 是否渲染出来
       expect(container.querySelector('div')).toBeInTheDocument();
+      
+      // Test unmounting
+      act(() => {
+        render(null, { container });
+      });
+      expect(container.querySelector('div')).not.toBeInTheDocument();
     });
 
     it('renders correctly when ref is passed internally', () => {
       const { container } = render(
         <CSSMotion motionName="transition" visible>
           {(props, ref) => <div ref={ref} />}
         </CSSMotion>,
       );
 
-      // 检查 DOM 是否渲染出来
       expect(container.querySelector('div')).toBeInTheDocument();
+      
+      // Test multiple renders
+      act(() => {
+        render(
+          <CSSMotion motionName="transition" visible>
+            {(props, ref) => <div ref={ref} data-testid="new" />}
+          </CSSMotion>,
+          { container }
+        );
+      });
+      expect(container.querySelector('[data-testid="new"]')).toBeInTheDocument();
     });
+    
+    it('handles errors gracefully', () => {
+      const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
+      
+      expect(() => {
+        render(
+          <CSSMotion motionName="transition" visible>
+            {(props, ref) => {
+              throw new Error('Test error');
+            }}
+          </CSSMotion>,
+        );
+      }).toThrow('Test error');
+      
+      errorSpy.mockRestore();
+    });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ddab4ff and 00c8a48.

📒 Files selected for processing (1)
  • tests/CSSMotion.spec.tsx (4 hunks)
🔇 Additional comments (1)
tests/CSSMotion.spec.tsx (1)

12-19: 代码实现清晰且符合最佳实践

ForwardedComponent 的实现正确使用了 React.forwardRef,并且合理处理了 props 的解构和传递。这很好地支持了移除 findDOMNode 的目标。

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