Skip to content

Conversation

@meet-student
Copy link
Contributor

@meet-student meet-student commented Aug 26, 2025

这个 PR 做了什么? (简要描述所做更改)

这个 PR 是什么类型? (至少选择一个)

  • 错误修复 (Bugfix) issue: fix #
  • 新功能 (Feature)
  • 代码重构 (Refactor)
  • TypeScript 类型定义修改 (Types)
  • 文档修改 (Docs)
  • 代码风格更新 (Code style update)
  • 构建优化 (Chore)
  • 其他,请描述 (Other, please describe):

这个 PR 涉及以下平台:

  • 所有平台
  • Web 端(H5)
  • 移动端(React-Native)
  • 鸿蒙(Harmony)
  • 鸿蒙容器(Harmony Hybrid)
  • ASCF 元服务
  • 快应用(QuickApp)
  • 所有小程序
  • 微信小程序
  • 企业微信小程序
  • 京东小程序
  • 百度小程序
  • 支付宝小程序
  • 支付宝 IOT 小程序
  • 钉钉小程序
  • QQ 小程序
  • 飞书小程序
  • 快手小程序
  • 头条小程序

Summary by CodeRabbit

  • 新功能
  • Bug Fixes
    • 修复 H5 振动在不支持环境下的异常行为:现在会安全降级、返回 false 并输出警告。
  • Refactor
    • 将 vibrateShort / vibrateLong 规范为以 options 对象传参,继续支持 success/fail/complete 回调。
    • 统一振动检测与调用逻辑,提升兼容性与稳定性。

@coderabbitai
Copy link

coderabbitai bot commented Aug 26, 2025

Walkthrough

在 H5 端重构震动实现:新增显式 vibrator 助手检测并返回布尔值;vibrateShort 与 vibrateLong 改为接收 options 对象并从中解构回调;根据 vibrator 返回值通过 MethodHandler 分发 success/fail/complete;不支持或异常时记录告警并返回 false。

Changes

Cohort / File(s) Summary of changes
H5 设备震动 API 调整
packages/taro-h5/src/api/device/vibrate.ts
新增 vibrator 助手函数(检测 window.navigator.vibrate 是否为函数,异常或不支持时记录警告并返回 false);vibrateShort / vibrateLong 签名改为接收 options: Taro.*.Option = {};从 options 提取 success/fail/complete 并继续使用 MethodHandler 分发;内部根据 vibrator 返回值决定 success 或 fail;失败消息在 diff 中保持为 'style is not support';调整了导入周围空白。

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as 调用方
  participant API as Taro.vibrateShort/Long
  participant Vib as vibrator helper
  participant MH as MethodHandler
  participant Nav as window.navigator

  App->>API: 调用 options { success, fail, complete }
  API->>API: 解析 options
  rect rgba(200,230,255,0.25)
    note right of API: 调用 vibrator 助手(特性检测 & 调用)
    API->>Vib: 请求振动(pattern)
    Vib->>Nav: 检查 `navigator.vibrate`
    alt 支持且调用成功
      Nav-->>Vib: 执行并返回 true
      Vib-->>API: true
    else 不支持或异常
      Vib-->>API: false(并 console.warn)
    end
  end
  alt 返回 true
    API->>MH: resolve(success)
  else 返回 false
    API->>MH: reject(fail, "style is not support")
  end
  MH-->>App: 触发 complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • tutuxxx
  • yoyo837

Poem

兔子轻敲键与趾,
新助手探风知否。
短长皆收一物件,
不振也说清楚由。
小小振动心中乐,
代码更新喜洋洋 🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5269b7d and a401653.

📒 Files selected for processing (1)
  • packages/taro-h5/src/api/device/vibrate.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/taro-h5/src/api/device/vibrate.ts
✨ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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: 1

🧹 Nitpick comments (7)
packages/taro-h5/src/api/device/vibrate.ts (7)

1-1: 仅类型用途的导入请改为 import type,避免运行时依赖与额外包体

此处 Taro 仅用于类型标注,建议使用 import type,以避免将 @tarojs/api 的运行时代码打进 H5 包。

-import Taro from '@tarojs/api'
+import type Taro from '@tarojs/api'

5-16: 更健壮的特性检测与类型:使用 globalThis.navigator?.vibrate + VibratePattern;减少重复 warn

  • 采用 globalThis.navigator?.vibrate 可避免 SSR/非浏览器环境下对 window 的硬依赖,更安全。
  • 使用 DOM 自带 VibratePattern 类型(等价于 number | number[])更贴合标准。
  • 统一告警文案,避免 try/catchelse 分支重复 warn
  • 函数名改为 tryVibrate 更贴合语义(返回布尔值表示尝试结果)。
-const vibrator = function vibrator (mm: number | number[]): boolean {
-  try {
-    if (typeof window.navigator.vibrate === 'function') {
-      return window.navigator.vibrate(mm)
-    }
-    console.warn('当前浏览器不支持 vibrate。')
-    return false
-  } catch (e) {
-    console.warn('当前浏览器不支持 vibrate。')
-    return false
-  }
-}
+const tryVibrate = (pattern: VibratePattern): boolean => {
+  const nav = typeof globalThis !== 'undefined'
+    ? (globalThis as any).navigator as Navigator | undefined
+    : undefined
+  const vibrate = nav?.vibrate
+  if (typeof vibrate === 'function') {
+    try {
+      return vibrate.call(nav, pattern)
+    } catch {
+      console.warn('当前环境不支持 Vibration API。')
+      return false
+    }
+  }
+  console.warn('当前环境不支持 Vibration API。')
+  return false
+}

21-21: 跟随 import type 调整签名类型引用,避免对值级别 Taro 的依赖

import type 后不应再使用 typeof Taro.vibrateShort,建议改为索引类型引用。

-export const vibrateShort: typeof Taro.vibrateShort = (options: Taro.vibrateShort.Option = {}) => {
+export const vibrateShort: Taro['vibrateShort'] = (options: Taro.vibrateShort.Option = {}) => {

24-24: 同步调用处的重命名:vibrator → tryVibrate

与上方助手函数改名保持一致。

-  if (vibrator(15)) {
+  if (tryVibrate(15)) {

27-27: 英文报错文案语法问题:应为 “is not supported”

将 “is not support” 更正为 “is not supported”,并可考虑更清晰的提示语。

-    return handle.fail({ errMsg: 'vibrateShort is not support' })
+    return handle.fail({ errMsg: 'vibrateShort is not supported' })

31-42: vibrateLong 实现与 vibrateShort 保持一致即可,但建议统一错误信息风格

vibrateShort 同步修正语法问题,并考虑与全局 API 约定统一 errMsg 风格(详见下方校验建议)。

-export const vibrateLong: typeof Taro.vibrateLong = (options: Taro.vibrateLong.Option = {}) => {
+export const vibrateLong: Taro['vibrateLong'] = (options: Taro.vibrateLong.Option = {}) => {
   const { success, fail, complete } = options
   const handle = new MethodHandler({ name: 'vibrateLong', success, fail, complete })
-  if (vibrator(400)) {
+  if (tryVibrate(400)) {
     return handle.success()
   } else {
-    return handle.fail({ errMsg: 'vibrateLong is not support' })
+    return handle.fail({ errMsg: 'vibrateLong is not supported' })
   }
 }

18-20: 请更新 packages/taro-h5/src/api/device/vibrate.ts 中的注释

基于 MDN 与 caniuse 的最新兼容性信息,Vibration API 在不同平台上的支持情况如下:

  • Chrome for Android、Android WebView、Firefox for Android、Samsung Internet、Opera for Android 等多数基于 Chromium/Gecko 的浏览器均支持 navigator.vibrate,但在无用户手势、省电模式、跨域 iframe 等场景可能被限制。
  • iOS Safari 及 iOS WebView(WKWebView)不支持该 API;原有“仅在 iPhone 7/7 Plus 以上生效”的描述容易导致误导。
  • MDN 已将 Vibration API 标记为“已弃用/不推荐用于新项目”,后续可能被移除或进一步限制。

请将原有注释替换为更清晰的兼容性说明,并在调用前进行运行时检测。示例修改 diff 如下:

 /**
- * 使手机发生较短时间的振动(15 ms)。仅在 iPhone 7 / 7 Plus 以上及 Android 机型生效
+ * 使设备产生一次短暂振动(约 15ms)。
+ * 注意:
+ * - 支持:Chrome for Android、Android WebView、Firefox for Android、Samsung Internet、Opera for Android 等;不支持:iOS Safari / iOS WebView。
+ * - 调用前请检测 'vibrate' in navigator,并在用户手势触发的上下文中执行。
+ * - MDN 标注该 API 已弃用,后续版本可能移除或进一步限制。
  */
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d962619 and 5269b7d.

📒 Files selected for processing (1)
  • packages/taro-h5/src/api/device/vibrate.ts (1 hunks)
🔇 Additional comments (1)
packages/taro-h5/src/api/device/vibrate.ts (1)

21-23: 参数对象化与 MethodHandler 续用:实现清晰,改动方向正确

从解构参数切换为 options 对象并继续沿用 MethodHandler 分发 success/fail/complete,方向合理、接口更稳定。

@codecov
Copy link

codecov bot commented Aug 26, 2025

Codecov Report

❌ Patch coverage is 17.39130% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 55.05%. Comparing base (d962619) to head (a401653).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
packages/taro-h5/src/api/device/vibrate.ts 17.39% 18 Missing and 1 partial ⚠️

❌ Your patch status has failed because the patch coverage (17.39%) is below the target coverage (75.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #18250      +/-   ##
==========================================
- Coverage   55.07%   55.05%   -0.02%     
==========================================
  Files         416      416              
  Lines       21559    21565       +6     
  Branches     5267     5269       +2     
==========================================
  Hits        11873    11873              
+ Misses       8160     8044     -116     
- Partials     1526     1648     +122     
Flag Coverage Δ
taro-cli 72.85% <ø> (ø)
taro-runtime 59.87% <ø> (ø)
taro-web 53.10% <17.39%> (-0.09%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
packages/taro-h5/src/api/device/vibrate.ts 17.39% <17.39%> (-6.14%) ⬇️

... and 40 files with indirect coverage changes

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

@yoyo837
Copy link
Contributor

yoyo837 commented Aug 26, 2025

CI 挂了

@Single-Dancer Single-Dancer added this to the 4.1.6 milestone Aug 26, 2025
@Single-Dancer Single-Dancer merged commit 8c811d2 into NervJS:main Aug 26, 2025
23 of 24 checks passed
@Single-Dancer Single-Dancer changed the title refactor: type and code optimization refactor: H5 设备震动 API 调整 Aug 26, 2025
@meet-student meet-student deleted the h5-device branch August 26, 2025 09:39
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