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

Merged
merged 5 commits into from
Jan 17, 2025

Conversation

Roxannej
Copy link
Contributor

@Roxannej Roxannej commented Jan 5, 2025

issue:ant-design/ant-design#52115

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

Summary by CodeRabbit

  • 重构

    • 简化了 CSSMotion 组件中获取 DOM 元素的方法
    • 移除了对已弃用的 findDOMNode 方法的使用
    • 移除了 DomWrapper 组件,简化了代码结构
    • 更新了多个钩子的导入路径,以反映新的依赖关系
    • 更新了 CSSMotionListProps 接口中的 children prop 类型,以使用标准的 React ref 类型
  • 测试

    • 更新测试套件,移除对 ReactDOM.findDOMNode 的依赖
    • 优化测试用例,确保组件在无 refs 时不会崩溃
    • 改进了对组件可见性状态的测试

这些更改提高了代码的可读性和维护性,同时遵循了现代 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 17, 2025 3:17am

Copy link

coderabbitai bot commented Jan 5, 2025

概述

遍历

CSSMotion 组件的 src/CSSMotion.tsx 文件中,对 getDomElement 函数进行了重大修改。移除了使用已弃用的 findDOMNode 方法的尝试性代码,简化了 DOM 元素检索的逻辑。同时,wrapperNodeRef 被移除,setNodeRef 函数被直接替换为 nodeRef 的使用。此外,测试文件 tests/CSSMotion.spec.tsx 也相应地更新,移除了对 findDOMNode 的依赖,并优化了测试断言方法。package.json 文件中,依赖项 rc-util 被移除,添加了 @rc-component/util 作为新依赖。其他多个文件的导入路径也进行了更新,以反映新的依赖关系。

变更

文件 变更摘要
src/CSSMotion.tsx 简化 getDomElement 函数,移除 findDOMNode 相关代码,调整 ref 处理
tests/CSSMotion.spec.tsx 更新测试用例,移除 ReactDOM.findDOMNode,直接使用 DOM 查询
package.json 移除依赖 rc-util,添加依赖 @rc-component/util,新增脚本 lint:tsc
src/DomWrapper.tsx 移除 DomWrapper 组件及其类型定义
src/hooks/useIsomorphicLayoutEffect.ts 更新 canUseDom 的导入路径
src/hooks/useNextFrame.ts 更新 raf 的导入路径
src/hooks/useStatus.ts 更新多个导入路径
src/hooks/useStepQueue.ts 更新 useState 的导入路径
src/util/motion.ts 更新 canUseDOMMotionName 的导入路径
src/CSSMotionList.tsx 更新 children prop 类型,调整 ref 参数类型

诗歌

🐰 代码兔子轻跳跃
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
Contributor 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 的目标。

@zombieJ zombieJ self-assigned this Jan 16, 2025
Copy link

socket-security bot commented Jan 16, 2025

New and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/@rc-component/[email protected] environment +1 202 kB zombiej

View full report↗︎

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

🧹 Nitpick comments (1)
package.json (1)

50-51: 建议:考虑锁定次要版本

目前使用的版本范围 ^1.2.0 允许自动更新到任何 1.x.x 版本。考虑到这是一个关键的依赖更改,建议锁定次要版本以提高稳定性。

-    "@rc-component/util": "^1.2.0",
+    "@rc-component/util": "~1.2.0",
📜 Review details

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

📥 Commits

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

📒 Files selected for processing (9)
  • package.json (1 hunks)
  • src/CSSMotion.tsx (7 hunks)
  • src/DomWrapper.tsx (0 hunks)
  • src/hooks/useIsomorphicLayoutEffect.ts (1 hunks)
  • src/hooks/useNextFrame.ts (1 hunks)
  • src/hooks/useStatus.ts (1 hunks)
  • src/hooks/useStepQueue.ts (1 hunks)
  • src/util/motion.ts (1 hunks)
  • tests/CSSMotion.spec.tsx (5 hunks)
💤 Files with no reviewable changes (1)
  • src/DomWrapper.tsx
✅ Files skipped from review due to trivial changes (5)
  • src/hooks/useIsomorphicLayoutEffect.ts
  • src/hooks/useStepQueue.ts
  • src/hooks/useStatus.ts
  • src/hooks/useNextFrame.ts
  • src/util/motion.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/CSSMotion.tsx
  • tests/CSSMotion.spec.tsx

package.json Show resolved Hide resolved
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)

228-228: 类型断言的使用

建议考虑添加运行时类型检查,以确保返回值始终是有效的 React 元素。

-    return motionChildren as React.ReactElement;
+    if (!React.isValidElement(motionChildren)) {
+      throw new Error('CSSMotion children must be a valid React element');
+    }
+    return motionChildren;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22849e7 and cc9a877.

📒 Files selected for processing (3)
  • package.json (2 hunks)
  • src/CSSMotion.tsx (7 hunks)
  • src/CSSMotionList.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
🔇 Additional comments (5)
src/CSSMotion.tsx (4)

2-3: 导入新的 DOM 和 ref 工具函数

引入 @rc-component/util 中的工具函数来替代已弃用的 findDOMNode,这是一个很好的改进。


93-93: 更新了 children 回调函数中的 ref 类型

将 ref 参数类型从回调函数改为 React.Ref<any> 使其与现代 React 的 ref 处理方式保持一致。


141-141: 重构了 DOM 节点获取逻辑

  • 使用 getDOM 替换了 findDOMNode
  • 通过 useImperativeHandle 暴露 getDomElement 方法

这些改动提高了代码的可维护性并遵循了 React 最佳实践。

Also applies to: 159-159


171-175: 统一更新了所有 children 渲染点的 ref 传递

所有 children 调用点都更新为使用 nodeRef,保持了一致性。

Also applies to: 180-180, 210-210, 222-222

src/CSSMotionList.tsx (1)

58-58: 更新了列表组件的 ref 类型

将 ref 类型更新为 React.Ref<any>,与 CSSMotion 组件保持一致,这种一致性有助于维护代码质量。

Copy link

codecov bot commented Jan 17, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.44%. Comparing base (96996a1) to head (cc9a877).
Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master      #59      +/-   ##
==========================================
+ Coverage   98.23%   98.44%   +0.21%     
==========================================
  Files          12       11       -1     
  Lines         396      386      -10     
  Branches      111      108       -3     
==========================================
- Hits          389      380       -9     
+ Misses          7        6       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@zombieJ zombieJ merged commit 522b4fe into react-component:master Jan 17, 2025
9 checks passed
@zombieJ zombieJ mentioned this pull request Jan 17, 2025
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