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

refactor: use compatible systemInfo util API #2975

Open
wants to merge 5 commits into
base: feat_v3.x
Choose a base branch
from

Conversation

Alex-huxiyang
Copy link
Collaborator

@Alex-huxiyang Alex-huxiyang commented Feb 8, 2025

https://developers.weixin.qq.com/miniprogram/dev/api/base/system/wx.getSystemInfoSync.html
image

Summary by CodeRabbit

Summary by CodeRabbit

  • 重构
    • 统一更新了设备信息获取方式,提高了界面响应性和布局精度。
    • 优化了头像剪裁、拖拽、菜单定位、下拉刷新、粘性效果及列表展示,确保在不同设备上具备一致且流畅的用户体验。
  • 新功能
    • 新增兼容性函数以支持不同版本的 Taro API,确保设备、窗口和应用基本信息的获取。

Copy link

coderabbitai bot commented Feb 8, 2025

Walkthrough

此次 PR 主要针对多个组件中获取系统窗口信息的方式进行了统一调整。原先使用 Taro.getSystemInfoSync() 的调用均替换为 getWindowInfo(),以获取窗口尺寸和像素比,其中部分组件如 pulltorefresh 采用 Taro.getDeviceInfo().platform 获取平台信息。其余业务逻辑(如拖拽、裁剪、滚动处理等)保持不变。

Changes

文件路径 变更摘要
src/packages/avatarcropper/avatarcropper.taro.tsx, src/packages/drag/{demos/taro/demo4.tsx, drag.taro.tsx}, src/packages/lottie/mp.taro.tsx, src/packages/menuitem/menuitem.taro.tsx, src/packages/sticky/sticky.taro.tsx, src/packages/virtuallist/virtuallist.taro.tsx 将 Taro.getSystemInfoSync() 替换为 getWindowInfo(),以获取窗口信息(如宽度、高度、pixelRatio),逻辑计算保持不变。
src/packages/pulltorefresh/pulltorefresh.taro.tsx 将 Taro.getSystemInfoSync().platform 修改为 Taro.getDeviceInfo().platform,用于平台信息检测。
src/utils/get-system-info.ts 新增 getDeviceInfo、getWindowInfo 和 getAppBaseInfo 方法,以兼容新旧 API。

Possibly related issues

Possibly related PRs

Suggested reviewers

  • oasis-cloud
  • xiaoyatong

Poem

嗨,我是小兔,代码林中跳跃不停,
窗口信息从新方法中悄然映现,
getWindowInfo 带来清新风范,
一行行代码舞动如诗篇,
在数字天地中,我欢喜轻快迎接每个改变!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 Target branch 3.x label Feb 8, 2025
Copy link

codecov bot commented Feb 8, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 85.74%. Comparing base (a9a6292) to head (8a5c540).

Additional details and impacted files
@@            Coverage Diff             @@
##           feat_v3.x    #2975   +/-   ##
==========================================
  Coverage      85.74%   85.74%           
==========================================
  Files            277      277           
  Lines          18105    18105           
  Branches        2745     2745           
==========================================
  Hits           15524    15524           
  Misses          2576     2576           
  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: 0

🧹 Nitpick comments (1)
src/packages/drag/drag.taro.tsx (1)

2-2: 建议添加错误处理

虽然替换 API 是正确的,但考虑到这些值用于边界计算,建议添加错误处理:

-      const { screenWidth, windowHeight } = getWindowInfo()
+      try {
+        const { screenWidth, windowHeight } = getWindowInfo()
+        if (!screenWidth || !windowHeight) {
+          console.warn('获取窗口信息失败', { screenWidth, windowHeight })
+          return
+        }
+      } catch (error) {
+        console.error('获取窗口信息出错', error)
+        return
+      }

Also applies to: 67-67

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 61955b9 and e77bfad.

📒 Files selected for processing (8)
  • src/packages/avatarcropper/avatarcropper.taro.tsx (2 hunks)
  • src/packages/drag/demos/taro/demo4.tsx (1 hunks)
  • src/packages/drag/drag.taro.tsx (2 hunks)
  • src/packages/lottie/mp.taro.tsx (2 hunks)
  • src/packages/menuitem/menuitem.taro.tsx (4 hunks)
  • src/packages/pulltorefresh/pulltorefresh.taro.tsx (1 hunks)
  • src/packages/sticky/sticky.taro.tsx (2 hunks)
  • src/packages/virtuallist/virtuallist.taro.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (7)
src/packages/drag/demos/taro/demo4.tsx (1)

3-3: 代码更改正确!

成功将已弃用的 getSystemInfoSync 替换为 getWindowInfo,并且保持了相同的属性访问方式。

Also applies to: 6-6

src/packages/lottie/mp.taro.tsx (1)

5-5: 请验证 pixelRatio 的准确性

虽然替换为 getWindowInfo 是正确的,但由于这个值用于画布缩放,建议验证在不同设备上的显示效果。

Also applies to: 34-34

✅ Verification successful

🌐 Web query:

Taro getWindowInfo 和 getSystemInfoSync 返回的 pixelRatio 是否完全一致?

💡 Result:

Taro框架中`getWindowInfo`和`getSystemInfoSync`返回的`pixelRatio`值**完全一致**。根据文档分析:

1. **数据来源相同**  
   两者均从底层系统接口获取设备像素比(Device Pixel Ratio),属于同一数据源的不同访问方式[3][5][10]。

2. **定义一致性**  
   Taro官方文档明确标注两者返回的`pixelRatio`参数说明均为:
   > 设备像素比 = 物理像素 / 逻辑像素  
   且类型均为`number`[3][10]。

3. **单位与计算规则统一**  
   两者的`pixelRatio`计算规则完全遵循Web标准(与Web API的`devicePixelRatio`一致),不涉及平台差异或框架层二次计算[1][9]。

4. **使用场景差异**  
   - `getSystemInfoSync()`:获取完整的系统信息(含品牌、型号、屏幕尺寸等)
   - `getWindowInfo()`:聚焦窗口可用区域信息(如状态栏/TabBar高度等),但核心参数如`pixelRatio`仍复用系统接口数据[5][8]

实际开发中可互换使用两者的`pixelRatio`值(如响应式布局或Canvas绘制场景)[7][9]。但建议优先使用`getSystemInfoSync()`以保证代码兼容性更广。

Citations:

- 1: https://developers.weixin.qq.com/community/develop/doc/1d3d06e7f4bfd425630c91e875e31ab1
- 2: https://blog.csdn.net/cong_user/article/details/114932914
- 3: https://docs.taro.zone/docs/1.x/apis/device/systeminfo/getSystemInfoSync/
- 4: https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html
- 5: https://docs.taro.zone/docs/2.x/apis/base/system/getSystemInfoSync/
- 6: https://failte.cn/pages/93aad5/
- 7: https://juejin.cn/post/7153880013962477598
- 8: https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/
- 9: https://developers.weixin.qq.com/community/personal/oCJUsw9Ri1fmAJmg-oqw8tWjKwG0/fav
- 10: https://docs.taro.zone/docs/apis/base/system/getSystemInfoSync

验证 pixelRatio 准确性

根据 Taro 官方文档及相关资料,getWindowInfogetSystemInfoSync 返回的 pixelRatio 值完全一致,这意味着用 getWindowInfo 替换不会影响 Canvas 的缩放效果。当然,仍建议在不同设备上做终端测试以确保实际显示效果达到预期。

  • 确认了 getWindowInfogetSystemInfoSyncpixelRatio 数值一致
  • 涉及文件:src/packages/lottie/mp.taro.tsx(适用于行 5 及 34)
src/packages/sticky/sticky.taro.tsx (1)

13-13: 代码更改正确!

成功将 getSystemInfoSync 替换为 getWindowInfo 获取窗口高度,保持了相同的功能。

Also applies to: 132-132

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

11-11: 代码更改正确!

成功将已弃用的 getSystemInfoSync 替换为 getWindowInfo,同时保持了原有的回退值逻辑。

Also applies to: 59-59

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

162-162: 平台检测 API 更改正确!

使用 getDeviceInfo().platform 替代 getSystemInfoSync().platform 是正确的选择,因为 getDeviceInfo API 更适合获取平台信息。

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

12-12: 窗口信息获取方式更新正确!

成功将所有 getSystemInfoSync 调用替换为 getWindowInfo,保持了组件的定位逻辑不变。

Also applies to: 109-109, 166-166, 180-180

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

11-11: 系统信息获取方式更新正确!

成功将 getSystemInfoSync 替换为 getWindowInfo,同时保持了像素比和窗口尺寸的计算逻辑不变。

Also applies to: 125-125

Copy link
Collaborator

@xiaoyatong xiaoyatong left a comment

Choose a reason for hiding this comment

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

需要做兼容性处理,最好封装一个util函数。

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)
src/utils/get-system-info.ts (4)

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

当前实现在 API 调用失败时没有错误处理逻辑。建议添加 try-catch 块来优雅处理可能的异常。

建议修改为:

 export function getDeviceInfo(): IDeviceInfo {
+  try {
     if (Taro.canIUse('getDeviceInfo')) {
       return Taro.getDeviceInfo()
     }
 
     return Taro.getSystemInfoSync()
+  } catch (error) {
+    console.error('获取设备信息失败:', error)
+    throw error
+  }
 }

16-22: 建议增加返回值类型校验

为确保新旧 API 返回的数据结构一致性,建议添加类型校验逻辑。

建议添加类型校验函数:

function validateWindowInfo(info: any): info is Taro.getWindowInfo.Result {
  return typeof info.windowWidth === 'number' 
    && typeof info.windowHeight === 'number'
    && typeof info.pixelRatio === 'number'
}

然后修改实现:

 export function getWindowInfo(): Taro.getWindowInfo.Result {
+  let info
   if (Taro.canIUse('getWindowInfo')) {
-    return Taro.getWindowInfo()
+    info = Taro.getWindowInfo()
+  } else {
+    info = Taro.getSystemInfoSync()
   }
 
-  return Taro.getSystemInfoSync()
+  if (!validateWindowInfo(info)) {
+    throw new Error('获取到的窗口信息格式不正确')
+  }
+  return info
 }

24-31: 建议添加详细的 JSDoc 文档

为了提高代码可维护性,建议添加完整的 JSDoc 文档说明,包括函数描述、返回值说明和示例代码。

建议添加如下文档:

+/**
+ * 获取应用基础信息
+ * @description 优先使用新版 API getAppBaseInfo,不可用时回退到 getSystemInfoSync
+ * @returns {Taro.getAppBaseInfo.Result} 应用基础信息
+ * @example
+ * const appInfo = getAppBaseInfo()
+ * console.log(appInfo.language) // 显示当前应用设置的语言
+ */
 export function getAppBaseInfo(): Taro.getAppBaseInfo.Result {
   if (Taro.canIUse('getAppBaseInfo')) {
     return Taro.getAppBaseInfo()
   }
 
   return Taro.getSystemInfoSync()
 }

1-32: 建议重构以减少代码重复

当前三个函数有相似的实现模式,建议提取共同逻辑到一个工具函数中。

建议添加通用工具函数:

function getInfo<T>(
  newApi: () => T,
  newApiName: string,
  validate?: (data: any) => data is T
): T {
  try {
    const info = Taro.canIUse(newApiName)
      ? newApi()
      : Taro.getSystemInfoSync()
    
    if (validate && !validate(info)) {
      throw new Error(`Invalid ${newApiName} result`)
    }
    
    return info
  } catch (error) {
    console.error(`Failed to get info using ${newApiName}:`, error)
    throw error
  }
}

这样可以简化现有函数的实现,提高代码的可维护性和可测试性。

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e77bfad and e5203af.

📒 Files selected for processing (9)
  • src/packages/avatarcropper/avatarcropper.taro.tsx (2 hunks)
  • src/packages/drag/demos/taro/demo4.tsx (1 hunks)
  • src/packages/drag/drag.taro.tsx (2 hunks)
  • src/packages/lottie/mp.taro.tsx (2 hunks)
  • src/packages/menuitem/menuitem.taro.tsx (4 hunks)
  • src/packages/pulltorefresh/pulltorefresh.taro.tsx (2 hunks)
  • src/packages/sticky/sticky.taro.tsx (2 hunks)
  • src/packages/virtuallist/virtuallist.taro.tsx (2 hunks)
  • src/utils/get-system-info.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/packages/sticky/sticky.taro.tsx
  • src/packages/lottie/mp.taro.tsx
  • src/packages/pulltorefresh/pulltorefresh.taro.tsx
  • src/packages/drag/drag.taro.tsx
  • src/packages/virtuallist/virtuallist.taro.tsx
  • src/packages/menuitem/menuitem.taro.tsx
  • src/packages/drag/demos/taro/demo4.tsx
  • src/packages/avatarcropper/avatarcropper.taro.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (1)
src/utils/get-system-info.ts (1)

3-4: 接口定义清晰简洁!

通过 Omit 工具类型排除了不稳定的属性,增强了跨版本兼容性。

@Alex-huxiyang Alex-huxiyang changed the title refactor: replace deprecated getSystemInfoSync refactor: use compatible systemInfo util API Feb 8, 2025
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/utils/get-system-info.ts (1)

20-34: 建议重构以减少代码重复

三个函数有相似的模式,建议提取共同逻辑到一个通用函数中。

+const getCompatibleInfo = <T>(
+  apiName: string,
+  newApi: () => T,
+): T => {
+  return Taro.canIUse(apiName)
+    ? newApi()
+    : Taro.getSystemInfoSync()
+}
+
 export const getWindowInfo = (): Taro.getWindowInfo.Result => {
-  return Taro.canIUse('getWindowInfo')
-    ? Taro.getWindowInfo()
-    : Taro.getSystemInfoSync()
+  return getCompatibleInfo('getWindowInfo', Taro.getWindowInfo)
 }

 export const getAppBaseInfo = (): Taro.getAppBaseInfo.Result => {
-  return Taro.canIUse('getAppBaseInfo')
-    ? Taro.getAppBaseInfo()
-    : Taro.getSystemInfoSync()
+  return getCompatibleInfo('getAppBaseInfo', Taro.getAppBaseInfo)
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fe9f1a9 and 3ed3a50.

📒 Files selected for processing (1)
  • src/utils/get-system-info.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (3)
src/utils/get-system-info.ts (3)

3-4: 接口定义清晰且类型安全!

通过 Omit 工具类型排除不需要的属性,保持了类型定义的精确性。


1-34: 代码结构规范,符合之前的审查建议!

  • 统一使用 export const xx = () => {} 的导出语法
  • 每个函数都有清晰的 JSDoc 注释
  • 类型定义完整

10-14: 🏁 Script executed:

#!/bin/bash
# 搜索 getSystemInfoSync 的返回类型使用情况
ast-grep --pattern 'getSystemInfoSync()' -l typescript

Length of output: 56

@github-actions github-actions bot added the action:review This PR needs more reviews (less than 2 approvals) label Feb 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.x Target branch 3.x action:review This PR needs more reviews (less than 2 approvals) size/M
Projects
None yet
2 participants