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(Backtop): refactor backtop using hoverbutton and v15 adaption #2866

Merged
merged 8 commits into from
Dec 20, 2024

Conversation

xiaoyatong
Copy link
Collaborator

@xiaoyatong xiaoyatong commented Dec 16, 2024

🤔 这个变动的性质是?

  • 新特性提交
  • 日常 bug 修复
  • 站点、文档改进
  • 演示代码改进
  • 组件样式/交互改进
  • TypeScript 定义更新
  • 包体积优化
  • 性能优化
  • 功能增强
  • 国际化改进
  • 重构
  • 代码风格优化
  • 测试用例
  • 分支合并
  • 其他改动(是关于什么的改动?)

🔗 相关 Issue

💡 需求背景和解决方案

☑️ 请求合并前的自查清单

⚠️ 请自检并全部勾选全部选项⚠️

  • 文档已补充或无须补充
  • 代码演示已提供或无须提供
  • TypeScript 定义已补充或无须补充
  • fork仓库代码是否为最新避免文件冲突
  • Files changed 没有 package.json lock 等无关文件

Summary by CodeRabbit

  • 新特性
    • 新增 TimeDetailTimeSelect 组件,用于选择配送时间。
    • 更新 BackTopRateSwitch 组件至最新版本。
    • BackTop 组件的 target 属性已更新,以确保正确的滚动功能。
  • 样式
    • 更新 .nut-backtop-show 类,简化样式并使用变量。
    • 修改 hoverbuttonitem.scss 文件,增强样式灵活性。
    • 新增 CSS 变量,提升主题定制能力。
  • 文档
    • 更新从 NutUI React 版本 2.x 升级到 3.x 的迁移文档,提供重要变更信息。

Copy link

coderabbitai bot commented Dec 16, 2024

概述

演练

这个拉取请求涉及 NutUI React 组件库的多个文件和组件的更新。主要变更包括 BackTop 组件的重构、配置文件中的版本更新、样式文件的修改以及多个演示文件的结构简化。更新涉及组件的交互模式、渲染方式和样式定义,反映了组件库的扩展和现代化。

变更

文件路径 变更摘要
src/config.json 添加 TimeDetailTimeSelect 组件,更新 BackTopRateSwitchCountDown 组件版本
src/packages/backtop/* 重构 BackTop 组件,简化渲染逻辑,移除 useMemo,更改交互模式
src/styles/variables.scss 添加新的 CSS 变量,移除 $backtop-border-color
演示文件 简化组件渲染结构,移除不必要的嵌套 Viewdiv 元素

建议的审阅者

  • oasis-cloud
  • Alex-huxiyang

相关 PRs

标签

size/XL

诗歌

兔子跳跃在代码间,
组件重构如春风般,
简洁明了是我们的愿,
版本更迭,技术飞翔,
NutUI 兔子笑开颜!🐰✨


📜 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 83883a4 and 41de6eb.

📒 Files selected for processing (1)
  • src/packages/backtop/__test__/backtop.spec.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/packages/backtop/test/backtop.spec.tsx

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.

@github-actions github-actions bot added the 3.x label Dec 16, 2024
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: 2

🧹 Nitpick comments (7)
src/packages/backtop/demos/taro/demo4.tsx (1)

9-14: 代码结构清晰,建议优化控制台日志!

代码结构优化合理,但建议在生产环境中移除或使用正式的日志系统替代 console.log。

建议修改如下:

  const handleClick = () => {
-   console.log('触发返回顶部')
+   // TODO: 使用正式的日志系统
  }
src/packages/backtop/backtop.scss (1)

14-19: 样式结构合理,建议添加注释!

新增的 hoverbutton 样式实现清晰,使用 flex 布局居中内容是个好的选择。建议为样式块添加注释,以提高可维护性。

建议添加如下注释:

    .nut-hoverbutton-item-container {
+     /* 使用 flex 布局实现内容垂直水平居中 */
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
src/packages/backtop/demos/taro/demo3.tsx (1)

13-14: 建议统一 Top 图标的属性命名

Taro 版本使用 size 属性,而 H5 版本使用 widthheight。建议统一使用相同的属性命名方式,以保持一致性。

-<Top size={12} />
+<Top width={12} height={12} />
src/packages/backtop/demos/h5/demo5.tsx (1)

23-24: 建议优化样式结构

考虑使用 CSS 类替代内联样式,以提高代码的可维护性。

-<div style={{ fontSize: '12px' }}>顶部</div>
+<div className="backtop-text">顶部</div>

同时在相应的样式文件中添加:

.backtop-text {
  font-size: 12px;
}
src/packages/backtop/demos/taro/demo5.tsx (1)

53-53: 建议增加错误处理机制

当前的滚动处理逻辑可能在某些场景下不够健壮,建议:

  1. 添加 try-catch 块来处理可能的滚动异常
  2. 考虑添加滚动失败的回调通知
 <BackTop
   threshold={200}
   scrollRes={scrollRes}
   onClick={() => {
+    try {
       if (harmony()) {
         if (!sv.current?.scroller?.scrollEdge) return
         // @ts-ignore
         sv.current.scroller.scrollEdge(Edge.Top)
       }
       if (rn()) {
         if (!sv.current?.scrollToOffset) return
         sv.current.scrollToOffset({ offset: 0 })
       }
+    } catch (error) {
+      console.error('滚动失败:', error)
+    }
   }}
 />
scripts/rn/update-taro-entry.js (1)

Line range hint 89-108: 建议改进文件操作的错误处理

文件操作部分的错误处理可以更加健壮:

  1. 使用 async/await 替代回调
  2. 添加更详细的错误日志
-  fse.access(componentBaseUrl, fse.constants.F_OK, (err) => {
-    if (err) {
-      // 文件夹不存在,创建文件夹
-      fse.mkdir(componentBaseUrl, { recursive: true }, (err) => {
-        if (err) throw err
-        console.log('文件夹创建成功!')
-        updatePages(componentBaseUrl, item)
-      })
-    } else {
-      updatePages(componentBaseUrl, item)
-    }
-  })
+  try {
+    await fse.access(componentBaseUrl, fse.constants.F_OK)
+  } catch (err) {
+    // 文件夹不存在,创建文件夹
+    try {
+      await fse.mkdir(componentBaseUrl, { recursive: true })
+      console.log(`文件夹创建成功:${componentBaseUrl}`)
+    } catch (err) {
+      console.error(`创建文件夹失败:${componentBaseUrl}`, err)
+      throw err
+    }
+  }
+  try {
+    await updatePages(componentBaseUrl, item)
+  } catch (err) {
+    console.error(`更新页面失败:${componentBaseUrl}`, err)
+    throw err
+  }
src/packages/backtop/backtop.taro.tsx (1)

65-65: 注意被注释的激活状态样式

这行被注释的代码可能会影响到触摸反馈:

// [`${classPrefix}-show-active`]: isNative && isTouchStart,

建议确认是否还需要这个激活状态的样式,如果不需要可以直接删除这行注释。

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7b36cf and 935422d.

📒 Files selected for processing (15)
  • scripts/rn/update-taro-entry.js (1 hunks)
  • src/config.json (1 hunks)
  • src/packages/backtop/backtop.scss (1 hunks)
  • src/packages/backtop/backtop.taro.tsx (3 hunks)
  • src/packages/backtop/backtop.tsx (2 hunks)
  • src/packages/backtop/demos/h5/demo3.tsx (1 hunks)
  • src/packages/backtop/demos/h5/demo5.tsx (2 hunks)
  • src/packages/backtop/demos/taro/demo1.tsx (1 hunks)
  • src/packages/backtop/demos/taro/demo2.tsx (1 hunks)
  • src/packages/backtop/demos/taro/demo3.tsx (1 hunks)
  • src/packages/backtop/demos/taro/demo4.tsx (1 hunks)
  • src/packages/backtop/demos/taro/demo5.tsx (1 hunks)
  • src/packages/hoverbutton/demos/taro/demo4.tsx (0 hunks)
  • src/packages/hoverbuttonitem/hoverbuttonitem.scss (1 hunks)
  • src/styles/variables.scss (1 hunks)
💤 Files with no reviewable changes (1)
  • src/packages/hoverbutton/demos/taro/demo4.tsx
✅ Files skipped from review due to trivial changes (1)
  • src/packages/backtop/demos/taro/demo2.tsx
🔇 Additional comments (11)
src/packages/backtop/demos/taro/demo1.tsx (1)

6-11: 代码结构优化得当!

使用 React Fragment 替换 View 组件使代码更加简洁,BackTop 组件的简化实现也符合组件重构的目标。

src/packages/backtop/demos/taro/demo3.tsx (1)

8-8: 结构优化:使用 Fragment 替代 View 容器

使用 Fragment 替代外层 View 容器是个很好的改进,可以减少不必要的 DOM 嵌套。

Also applies to: 16-16

src/packages/backtop/demos/h5/demo3.tsx (1)

11-13: 验证 target 属性的滚动行为

结构看起来没有问题,但建议验证 target 属性是否正确控制滚动行为。

✅ Verification successful

Let me check the implementation of the BackTop component to verify how the target prop is handled.


Let me check how the target prop is used in the implementation.


target 属性实现正确且功能完整

根据代码实现,target 属性的滚动行为处理是完善的:

  • 正确获取目标元素并绑定滚动监听
  • 实现了平滑滚动动画
  • 包含了适当的清理机制
  • 测试用例验证了基本功能
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查其他文件中 target 属性的使用情况
rg -A 2 'target=' src/packages/backtop/

Length of output: 1475


Script:

#!/bin/bash
# Check BackTop component implementation
ast-grep --pattern 'interface BackTopProps {
  $$$
  target?: $_;
  $$$
}'

# Also check the implementation details
ast-grep --pattern 'const $_: FC<BackTopProps> = $_$ => {
  $$$
}'

Length of output: 145


Script:

#!/bin/bash
# Check BackTop component implementation with a more flexible pattern
rg -A 10 "interface BackTopProps" src/packages/backtop/

# Check the component implementation
rg -A 20 "const BackTop" src/packages/backtop/

Length of output: 5941


Script:

#!/bin/bash
# Check how target prop is used in the implementation
rg -A 10 "useEffect.*target" src/packages/backtop/backtop.tsx

# Check scroll handling
rg -B 5 -A 10 "scrollHandler" src/packages/backtop/backtop.tsx

Length of output: 126


Script:

#!/bin/bash
# Try to find the scroll related code with more context
rg -B 5 -A 15 "scroll" src/packages/backtop/backtop.tsx

# Check the test file to see how target is tested
rg -B 5 -A 15 "target" src/packages/backtop/__test__/backtop.spec.tsx

Length of output: 3606

src/packages/backtop/demos/h5/demo5.tsx (1)

10-10: 检查滚动容器样式

移除了 overflowY: 'auto' 样式,需要确认滚动行为是否仍然正常工作。建议验证在不同场景下的滚动表现。

src/packages/hoverbuttonitem/hoverbuttonitem.scss (1)

3-5: 使用变量替换硬编码值的改动很棒!

使用 $hoverbutton-item-size 变量来统一管理尺寸是个很好的做法,这样可以:

  • 提高代码的可维护性
  • 方便主题定制
  • 确保组件尺寸的一致性
src/packages/backtop/demos/taro/demo5.tsx (1)

Line range hint 24-29: 需要关注 TODO 注释的解决方案

这里的 TODO 注释提到等待 Taro 支持获取视窗尺寸,建议:

  1. 创建对应的 issue 来追踪这个待办事项
  2. 考虑添加临时的 fallback 方案

需要我帮您创建一个 GitHub issue 来追踪这个 TODO 吗?

src/packages/backtop/backtop.taro.tsx (1)

114-135: 重构使用 HoverButton 组件的实现

代码重构后使用了 HoverButton 组件来替代原来的 View 实现,这样的改动有以下优点:

  1. 提供了更统一的交互体验
  2. 减少了重复代码
  3. 更好的复用性

不过需要注意以下几点:

  1. 确保 HoverButton 在各端表现一致
  2. 验证触摸事件的处理是否完整
✅ Verification successful

HoverButton 组件集成验证通过

从代码分析结果来看:

  1. HoverButton 组件在 Taro 和 Web 端都有完整实现,包括基础渲染、事件处理等功能
  2. 触摸事件(onTouchStart、onTouchEnd、onTouchCancel)在组件中得到了正确处理
  3. 组件支持自定义图标、样式和子元素,满足 BackTop 组件的需求
  4. 组件有完整的测试用例覆盖

重构后的实现是安全可靠的。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 验证 HoverButton 组件在不同端的实现是否一致
ast-grep --pattern 'class HoverButton {
  $$$
  render() {
    $$$
  }
}'

Length of output: 75


Script:

#!/bin/bash
# Search for HoverButton component implementation
rg -l "HoverButton" --type tsx --type ts

# Check HoverButton implementation details
rg "HoverButton" -A 10 --type tsx --type ts

# Look for touch event handlers in HoverButton
ast-grep --pattern 'onTouchStart={$_}'

Length of output: 181


Script:

#!/bin/bash
# 搜索 HoverButton 组件的实现
fd -e tsx -e ts -x rg -l "HoverButton" {}

# 检查 HoverButton 的具体实现
fd -e tsx -e ts -x rg "HoverButton" -A 10 {}

# 查找触摸事件处理相关代码
fd -e tsx -e ts -x rg "onTouchStart|onTouchEnd|onTouchCancel" {}

Length of output: 18682

src/packages/backtop/backtop.tsx (1)

123-141: Web 端 HoverButton 实现的一致性

Web 端的实现与 Taro 端保持了一致,这是很好的实践。建议关注以下几点:

  1. 确保样式类名的一致性
  2. 验证事件处理的兼容性
  3. 检查 children 的渲染逻辑
✅ Verification successful

Let me gather more information about the implementation consistency between Web and Taro versions.


Let me do one final check to verify the className implementation:


Web 端和 Taro 端实现一致性验证完成

经过验证,两端实现保持了良好的一致性:

  • 类名前缀 nut-backtop 在两端保持一致
  • HoverButton 组件的使用方式完全相同,包括 className、style 和事件处理
  • children 的渲染逻辑一致,都使用了 nut-hoverbutton-item-container 类名
  • 事件处理函数 goTop 的实现方式相同
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 验证样式类名在两个实现中的一致性
rg -A 1 'classPrefix = .nut-backtop'

Length of output: 351


Script:

#!/bin/bash
# Check HoverButton implementation and class names
rg -A 5 'className={cls}' src/packages/backtop/

# Check event handling implementation
rg -A 5 'goTop\(' src/packages/backtop/

# Check children rendering logic
ast-grep --pattern 'children && (
  $$$
)'

Length of output: 6237


Script:

#!/bin/bash
# Check className implementation with proper escaping
rg -A 5 'className=\{cls\}' src/packages/backtop/

# Check HoverButton component usage
rg -A 3 'HoverButton' src/packages/backtop/

Length of output: 2242

src/styles/variables.scss (3)

1022-1022: 新增 hoverbutton 组件尺寸变量

新增 $hoverbutton-item-size 变量用于控制 hoverbutton 组件的尺寸,这是重构 backtop 组件的必要变更。


Line range hint 1023-1036: 新增 hoverbutton 组件样式变量

新增以下 hoverbutton 相关的样式变量:

  • 边框颜色
  • 背景色
  • 激活状态背景色
  • 图标颜色
  • 图标激活状态颜色

这些变量的添加使 hoverbutton 组件更加灵活和可定制。


Line range hint 1-1036: 移除 backtop 相关变量

根据重构计划,移除了 $backtop-border-color 变量,因为 backtop 组件将使用 hoverbutton 的样式变量。

@@ -8,6 +8,7 @@ const param = process.env.C

// C=radio pnpm dev:taro:jdharmonycpp or C=radio,button,cell pnpm dev:taro:jdharmonycpp
function specialComponent(name) {
if(!param) return
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

param 的空值检查是好的,但建议进一步完善错误处理

当前的改动添加了 param 的空值检查,这很好。不过建议进一步加强错误处理:

  1. 添加参数验证
  2. 提供更明确的错误信息
-if(!param) return 
+if (!param) {
+  console.warn('未指定组件参数,将处理所有组件')
+  return
+}
+if (typeof param !== 'string') {
+  throw new Error('组件参数必须是字符串')
+}
📝 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
if(!param) return
if (!param) {
console.warn('未指定组件参数,将处理所有组件')
return
}
if (typeof param !== 'string') {
throw new Error('组件参数必须是字符串')
}

@@ -274,6 +274,7 @@
"tarodoc": true,
"show": true,
"taro": true,
"v15": true,
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

需要更新文档和 CHANGELOG

根据验证结果,虽然在 config.json 中添加了 v15 版本的配置,但是相关的文档和 CHANGELOG 尚未更新。为确保代码变更的完整性,请:

  • 在 CHANGELOG 中添加 v15 版本支持的说明
  • 更新组件文档,包含 v15 版本的使用说明和示例
  • 如有必要,更新组件的演示示例
🔗 Analysis chain

版本标记更新

添加了 "v15": true 配置,表明组件已适配 v15 版本。建议:

  1. 确保相关文档已更新
  2. 在 CHANGELOG 中说明版本变更
  3. 更新组件使用示例
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查文档和示例是否已更新
fd -e md -e mdx . | xargs rg "BackTop.*v15"

Length of output: 45


Script:

#!/bin/bash
# 检查 CHANGELOG 和文档中是否包含 v15 相关更新
rg -i "v15|version.*15" -g "CHANGELOG*" -g "*.md" -g "*.mdx"

# 检查组件使用示例中是否包含 v15 相关内容
rg -i "backtop.*v15|v15.*backtop" -g "*.md" -g "*.mdx" -g "demo*" -g "example*"

# 检查是否存在其他版本相关的配置文件
fd "version|config" -e json -e js | xargs rg "v15"

Length of output: 584

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/packages/backtop/demos/taro/demo5.tsx (1)

21-26: 建议优化性能和用户体验

当前实现在渲染大量 Cell 组件时可能会影响性能。

建议如下改进:

-      {new Array(24).fill(0).map((_, index) => {
+      {Array.from({ length: 24 }, (_, index) => {
         return <Cell key={index}>我是测试数据{index}</Cell>
       })}

另外,考虑添加以下优化:

  1. 使用虚拟列表来处理大量数据
  2. 添加加载状态指示器
src/packages/backtop/demo.taro.tsx (1)

29-39: 条件渲染逻辑更加清晰

组件结构得到简化,条件渲染逻辑更加直观。但建议进一步改进错误处理。

建议添加错误边界处理:

 {harmony() ? (
   <Demo5 />
 ) : (
+  <ErrorBoundary fallback={<ErrorFallback />}>
     <ScrollView
       className={`demo ${Taro.getEnv() === 'WEB' ? 'web' : ''}`}
       style={demoStyle}
     >
       <View className="h2">{translated.title}</View>
       <Demo1 />
     </ScrollView>
+  </ErrorBoundary>
 )}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 935422d and 9fbbff1.

📒 Files selected for processing (4)
  • src/packages/backtop/backtop.scss (1 hunks)
  • src/packages/backtop/backtop.taro.tsx (2 hunks)
  • src/packages/backtop/demo.taro.tsx (2 hunks)
  • src/packages/backtop/demos/taro/demo5.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/packages/backtop/backtop.scss
  • src/packages/backtop/backtop.taro.tsx
🔇 Additional comments (2)
src/packages/backtop/demos/taro/demo5.tsx (1)

4-4: 滚动事件处理逻辑优化得当

状态管理和滚动视图的实现变得更加简洁,直接通过 ScrollView 的 onScroll 事件更新状态。

Also applies to: 14-19

src/packages/backtop/demo.taro.tsx (1)

8-8: 平台判断方法更新合理

harmonyAndRn 更改为 harmony 使平台检测更加明确,符合当前需求。

Copy link

codecov bot commented Dec 17, 2024

Codecov Report

Attention: Patch coverage is 87.50000% with 2 lines in your changes missing coverage. Please review.

Project coverage is 84.57%. Comparing base (e7b36cf) to head (41de6eb).
Report is 3 commits behind head on feat_v3.x.

Files with missing lines Patch % Lines
src/packages/backtop/backtop.tsx 87.50% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           feat_v3.x    #2866   +/-   ##
==========================================
  Coverage      84.56%   84.57%           
==========================================
  Files            273      273           
  Lines          18609    18605    -4     
  Branches        2693     2693           
==========================================
- Hits           15737    15735    -2     
+ Misses          2867     2865    -2     
  Partials           5        5           

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

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

🔭 Outside diff range comments (1)
src/packages/backtop/__test__/backtop.spec.tsx (1)

Line range hint 28-28: 修复测试断言语法错误

expect(handleClick).toBeCalled 缺少括号,这会导致测试始终通过而没有实际验证函数调用。

请修改为:

-expect(handleClick).toBeCalled
+expect(handleClick).toBeCalled()
🧹 Nitpick comments (1)
src/packages/backtop/__test__/backtop.spec.tsx (1)

54-74: 滚动测试实现良好,建议优化以下几点

测试结构完整,正确使用了 actwaitFor,但建议做如下改进:

  1. 建议将滚动阈值提取为常量:
+const SCROLL_THRESHOLD = 200
 test('scroll', async () => {
   // ...
-  track.scrollTop = 200
+  track.scrollTop = SCROLL_THRESHOLD
  1. 建议增加更多断言来验证初始状态:
// 初始状态应该是隐藏的
expect(container.querySelector('.backtop-button')).not.toHaveClass('nut-backtop-show')
  1. 建议验证滚动回顶部时按钮消失:
// 滚动回顶部后
track.scrollTop = 0
act(() => {
  track.dispatchEvent(new Event('scroll'))
})
await waitFor(() => {
  expect(container.querySelector('.backtop-button')).not.toHaveClass('nut-backtop-show')
})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9fbbff1 and e6e0a20.

⛔ Files ignored due to path filters (1)
  • src/packages/backtop/__test__/__snapshots__/backtop.spec.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (2)
  • src/packages/backtop/__test__/backtop.spec.tsx (2 hunks)
  • src/packages/backtop/demo.tsx (1 hunks)
🔇 Additional comments (3)
src/packages/backtop/demo.tsx (1)

19-22: 代码结构优化得当!

组件结构简化后更加清晰,移除了不必要的包装元素,符合现代React最佳实践。

运行以下脚本验证样式迁移是否完整:

✅ Verification successful

Let me gather more specific information about the backtop component's styles.


样式移除合理,不会影响功能!

从验证结果可以看出:

  • 移除的内联样式 style={{ height: '100vh', overflowY: 'auto' }} 是demo展示用的临时样式
  • 组件本身的样式已经在 src/packages/backtop/backtop.scss 中妥善管理
  • demo页面的基础样式由全局的 .demo 类提供,在多个样式文件中都有正确定义
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 描述:检查样式是否已迁移到其他文件

# 检查是否存在相关的样式文件
fd -e scss -e css . | xargs rg "demo"

# 检查其他demo文件中是否存在相关样式
ast-grep --pattern 'style={$_}'

Length of output: 2706


Script:

#!/bin/bash
# 检查 backtop 组件相关的样式文件和引用
fd backtop . | xargs rg -l "demo"

# 检查 backtop/demo.tsx 之前的版本是否包含内联样式
git show HEAD~1:src/packages/backtop/demo.tsx

# 检查是否有专门的样式文件
fd -e scss -e css . | xargs rg "backtop|back-top"

Length of output: 1338

src/packages/backtop/__test__/backtop.spec.tsx (2)

5-5: 导入异步测试工具是合适的!

新增的 waitForact 导入对于处理异步测试场景是必要的,这符合 React Testing Library 的最佳实践。


40-41: 组件结构简化是合理的

新的结构更加简洁,直接使用 Top 图标组件是符合重构方向的。

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 (2)
src/packages/backtop/backtop.tsx (2)

124-142: 使用 HoverButton 重构提升了代码质量

使用 HoverButton 组件重构后的实现更加简洁和可维护:

  1. 统一了悬浮按钮的交互行为
  2. 提供了更灵活的图标自定义方式
  3. 改进了子元素的处理方式

建议考虑以下优化:

- onClick={(e) => {
-   goTop(e)
- }}
+ onClick={goTop}

Line range hint 89-102: 建议优化滚动动画实现

当前的滚动动画实现可能在某些场景下不够流畅。建议考虑使用 requestAnimationFrame 的回调函数参数来优化动画时间计算。

 const scrollAnimation = useCallback(() => {
   let cid = requestAniFrame(function fn() {
-    const t = duration - Math.max(0, startTime.current - +new Date() + duration / 2)
+    const t = duration - Math.max(0, startTime.current - performance.now() + duration / 2)
     const y = (t * -scrollTop) / duration + scrollTop
     scroll(y)
     cid = requestAniFrame(fn)
     if (t === duration || y === 0) {
       cancelRaf(cid)
     }
   })
 }, [duration, scroll, scrollTop, startTime])
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e6e0a20 and 875e323.

📒 Files selected for processing (11)
  • migrate-from-v2.md (1 hunks)
  • src/packages/backtop/__test__/backtop.spec.tsx (2 hunks)
  • src/packages/backtop/backtop.taro.tsx (3 hunks)
  • src/packages/backtop/backtop.tsx (3 hunks)
  • src/packages/backtop/demo.tsx (1 hunks)
  • src/packages/backtop/demos/h5/demo1.tsx (1 hunks)
  • src/packages/backtop/demos/h5/demo2.tsx (1 hunks)
  • src/packages/backtop/demos/h5/demo3.tsx (1 hunks)
  • src/packages/backtop/demos/h5/demo4.tsx (1 hunks)
  • src/packages/backtop/demos/h5/demo5.tsx (1 hunks)
  • src/packages/hoverbutton/hoverbutton.taro.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/packages/backtop/demos/h5/demo2.tsx
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/packages/backtop/demo.tsx
  • src/packages/backtop/demos/h5/demo3.tsx
  • src/packages/backtop/demos/h5/demo5.tsx
  • src/packages/backtop/test/backtop.spec.tsx
  • src/packages/backtop/backtop.taro.tsx
🔇 Additional comments (4)
src/packages/backtop/demos/h5/demo4.tsx (1)

6-10: 实现正确,代码结构合理

  • 容器设置了适当的高度和滚动属性
  • BackTop 组件正确引用了目标容器
  • 阈值设置合理
src/packages/hoverbutton/hoverbutton.taro.tsx (1)

3-3: 验证事件处理的兼容性并建议优化类型定义

需要验证事件处理的兼容性,并考虑以下建议:

  1. 确保在不同平台上的事件处理表现一致
  2. 考虑将事件类型抽象为统一接口

建议重构事件类型定义:

-  onClick?: (event: React.MouseEvent<Element, MouseEvent> | ITouchEvent) => void
+  type HoverButtonEvent = React.MouseEvent<Element, MouseEvent> | ITouchEvent
+  onClick?: (event: HoverButtonEvent) => void

运行以下脚本验证事件处理的实现:

Also applies to: 17-17

✅ Verification successful

Let me analyze the search results to verify the event handling compatibility and type safety:

  1. The search shows that in Taro components, event types are consistently handled as union types of React.MouseEvent and ITouchEvent, as seen in multiple components like animate.taro.tsx, backtop.taro.tsx etc.

  2. The implementation in hoverbutton.taro.tsx follows this pattern by using React.MouseEvent<Element, MouseEvent> | ITouchEvent which is consistent with other Taro components in the codebase.

  3. The event type union is specifically used in Taro components to handle both mouse and touch events, while web components only use MouseEvent.

Based on this analysis, I can now generate the final response:

事件处理类型定义符合框架规范

事件类型定义 React.MouseEvent<Element, MouseEvent> | ITouchEvent 与框架中其他 Taro 组件保持一致,能够同时处理鼠标和触摸事件,无需进行重构。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查事件处理的实现一致性
rg -A 5 "onClick.*event.*=>" 

Length of output: 28683

src/packages/backtop/backtop.tsx (1)

Line range hint 15-21: Props 接口设计合理

BackTopProps 继承自 HoverButtonProps 是一个很好的设计决定,它保持了接口的一致性并减少了重复代码。

migrate-from-v2.md (1)

565-567: 文档准确描述了 BackTop 组件的变更

文档中关于 BackTop 组件的变更说明准确反映了代码实现:

  1. 使用 HoverButton 重构
  2. 新增 icon 字段
  3. 继续支持自定义节点

Comment on lines +6 to +11
<>
{new Array(24).fill(0).map((_, index) => {
return <Cell key={index}>我是测试数据{index}</Cell>
})}
<BackTop target="target" />
</div>
</>
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

修复 BackTop 组件的目标元素缺失问题

BackTop 组件引用了 id 为 "target" 的元素,但该目标元素已被移除。这将导致回到顶部功能无法正常工作。

建议按以下方式修复:

-    <>
+    <div id="target" style={{ height: '100vh', overflowY: 'auto' }}>
       {new Array(24).fill(0).map((_, index) => {
         return <Cell key={index}>我是测试数据{index}</Cell>
       })}
       <BackTop target="target" />
-    </>
+    </div>
📝 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
<>
{new Array(24).fill(0).map((_, index) => {
return <Cell key={index}>我是测试数据{index}</Cell>
})}
<BackTop target="target" />
</div>
</>
<div id="target" style={{ height: '100vh', overflowY: 'auto' }}>
{new Array(24).fill(0).map((_, index) => {
return <Cell key={index}>我是测试数据{index}</Cell>
})}
<BackTop target="target" />
</div>

Copy link
Collaborator

@oasis-cloud oasis-cloud left a comment

Choose a reason for hiding this comment

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

鸿蒙环境中,返回顶部按钮点击后没有反应

@xiaoyatong
Copy link
Collaborator Author

鸿蒙环境中,返回顶部按钮点击后没有反应

鸿蒙目前不支持 usepagescroll

)
expect(container.querySelector('.nut-icon-Top')).toHaveClass(
'nut-backtop-main'
)
fireEvent.click(container)
expect(handleClick).toBeCalled
Copy link
Collaborator

Choose a reason for hiding this comment

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

少了()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants