接入移动壳原生触觉反馈

H5 HostBridge 增加 haptics.impact 受控调用入口

运行时点击反馈优先请求 Expo 触觉能力并保留浏览器震动回退

补充触觉反馈测试和宿主壳能力文档
This commit is contained in:
2026-06-17 23:57:46 +08:00
parent b03c910f49
commit 78afd81269
10 changed files with 240 additions and 21 deletions

View File

@@ -1,3 +1,4 @@
import * as Haptics from 'expo-haptics';
import * as Linking from 'expo-linking';
import * as Sharing from 'expo-sharing';
import { Share } from 'react-native';
@@ -116,6 +117,7 @@ function expectFailed(response: HostBridgeResponse) {
}
afterEach(() => {
vi.mocked(Haptics.impactAsync).mockReset();
vi.mocked(Linking.openURL).mockReset();
vi.mocked(Sharing.isAvailableAsync).mockReset();
vi.mocked(Sharing.isAvailableAsync).mockResolvedValue(true);
@@ -220,6 +222,19 @@ describe('handleMobileHostBridgeMessage', () => {
expect(Linking.openURL).not.toHaveBeenCalled();
});
test('haptics.impact 调起 Expo 触觉反馈', async () => {
const response = await send(
request('haptics.impact', {
style: 'heavy',
}),
);
expectOk(response);
expect(Haptics.impactAsync).toHaveBeenCalledWith(
Haptics.ImpactFeedbackStyle.Heavy,
);
});
test('share.open 使用直接分享 payload 调起系统分享', async () => {
const response = await send(
request('share.open', {

View File

@@ -20,7 +20,7 @@
- 背景:后续需要移动端 App 和桌面端 App但现有主站、固定玩法 runtime、小程序壳和未来 AI H5 sandbox 已经以 H5 为主线;如果移动端重写 React Native UI、桌面端重写 Rust/Tauri UI会形成玩法、登录、支付、分享和运行态的多套实现。
- 决策:移动端原生壳采用 `Expo + React Native`,桌面端壳采用 `Tauri`。两者都只作为 `native_app` 宿主壳和 HostBridge adapter不重写现有 React H5 主站,不把固定内置玩法迁到 React Native / Rust UI也不让 AI 生成 H5 游戏直接访问完整 HostBridge。Expo 壳通过 `react-native-webview` 承接 H5 与 native 通信Tauri 壳通过受控 command 和 capabilities 承接桌面能力;新增能力必须先进入 HostBridge 契约和测试。
- 2026-06-17 首轮落地:新增 `packages/shared/src/contracts/hostBridge.ts``src/services/host-bridge/nativeAppHostBridge.ts``apps/mobile-shell/``apps/desktop-shell/`。壳只声明并实现真实可用能力;移动壳使用真实品牌图标资产并支持 `genarrative://`、iOS associated domain、Android app link 到同源 H5 路径,`navigation.openNativePage` 只接受同源 H5 route 并切换 WebView URL不伪造尚未存在的原生页面且通过 `host.events` 注入 `navigation.canGoBack` 返回栈状态事件,`share.setTarget` / `share.open` 解析统一分享目标并调用 React Native 系统分享面板,`file.exportText` 写入 Expo 缓存文本文件后交给系统分享 / 保存面板,成功只返回文件名和字节数;`app.openExternalUrl` 在 Expo 与 Tauri 两端都只允许 `http:``https:``mailto:``tel:` 外链协议H5 复制服务在 native_app 中优先通过 `clipboard.writeText` 写入 Expo / Tauri 系统剪贴板,失败后再回退浏览器复制路径;桌面壳已通过 Tauri clipboard-manager 接入 `clipboard.writeText`,将 `navigation.openNativePage` 实现为 `https://app.genarrative.world` 同源 H5 route 的主窗口受控跳转,并将 `share.setTarget` / `share.open` 实现为复制非空分享文本到系统剪贴板,`app.setTitle` 通过主窗口 API 同步非空窗口标题;桌面 `file.exportText` 通过 Tauri dialog 插件打开系统保存对话框并由 Rust 写入文本文件,但不把 dialog / fs 插件 command 直接暴露给 H5成功只返回文件名和字节数用户取消返回 `cancelled`;登录、支付、原生系统分享面板等未接入真实 SDK / 插件前必须返回 unsupported 并让 H5 fallback生产代码禁止 mock 成功。
- 2026-06-17 首轮落地:新增 `packages/shared/src/contracts/hostBridge.ts``src/services/host-bridge/nativeAppHostBridge.ts``apps/mobile-shell/``apps/desktop-shell/`。壳只声明并实现真实可用能力;移动壳使用真实品牌图标资产并支持 `genarrative://`、iOS associated domain、Android app link 到同源 H5 路径,`navigation.openNativePage` 只接受同源 H5 route 并切换 WebView URL不伪造尚未存在的原生页面且通过 `host.events` 注入 `navigation.canGoBack` 返回栈状态事件,`share.setTarget` / `share.open` 解析统一分享目标并调用 React Native 系统分享面板,`file.exportText` 写入 Expo 缓存文本文件后交给系统分享 / 保存面板,成功只返回文件名和字节数`haptics.impact` 通过 Expo Haptics 承接 H5 运行时点击反馈`app.openExternalUrl` 在 Expo 与 Tauri 两端都只允许 `http:``https:``mailto:``tel:` 外链协议H5 复制服务在 native_app 中优先通过 `clipboard.writeText` 写入 Expo / Tauri 系统剪贴板,失败后再回退浏览器复制路径;H5 运行时反馈在 native_app 中优先通过 `haptics.impact` 请求真实移动端触觉,宿主不可用或 unsupported 时回退浏览器 `navigator.vibrate`桌面壳已通过 Tauri clipboard-manager 接入 `clipboard.writeText`,将 `navigation.openNativePage` 实现为 `https://app.genarrative.world` 同源 H5 route 的主窗口受控跳转,并将 `share.setTarget` / `share.open` 实现为复制非空分享文本到系统剪贴板,`app.setTitle` 通过主窗口 API 同步非空窗口标题;桌面 `file.exportText` 通过 Tauri dialog 插件打开系统保存对话框并由 Rust 写入文本文件,但不把 dialog / fs 插件 command 直接暴露给 H5成功只返回文件名和字节数用户取消返回 `cancelled`;登录、支付、原生系统分享面板等未接入真实 SDK / 插件前必须返回 unsupported 并让 H5 fallback生产代码禁止 mock 成功。
- 影响范围:`src/services/host-bridge/`、未来 `apps/mobile-shell/`、未来 `apps/desktop-shell/`、移动端支付 / 分享 / 深链 / 推送、桌面端系统能力、AI H5 sandbox 的 GameBridge 边界。
- 验证方式普通浏览器、小程序、Expo 壳、Tauri 壳都能返回正确 `getHostRuntime()`;未支持能力能回退 H5固定玩法在各宿主中读取同一作品数据和运行态 snapshotAI sandbox 无法直接调用 HostBridgeTauri release 不允许任意远端页面调用桌面命令。
- 关联文档:`docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md``docs/【前端架构】宿主壳能力统一协议-2026-06-17.md`

View File

@@ -121,7 +121,7 @@ type HostBridgeEvent = {
| `app.setTitle` | 同步宿主窗口标题 | 不声明 | 支持 |
| `clipboard.writeText` | 写剪贴板 | 支持 | 支持 |
| `file.exportText` | 导出文本到用户选择的本地文件 | 支持系统分享 / 保存面板 | 支持系统保存对话框 |
| `haptics.impact` | 轻量触感反馈 | 可选 | 不支持 |
| `haptics.impact` | 轻量触感反馈 | 支持 | 不声明 |
每个 method 都必须有明确 payload schema、超时、错误码和能力开关H5 看到不支持时回退到现有浏览器路径。
@@ -241,7 +241,7 @@ GameBridge 禁止:
- iOS / Android 深链打开作品详情、创作页和邀请码。
- 登录和支付先 fallback 到 H5只把能力边界跑通。
当前状态:已新增 `apps/mobile-shell/`,通过 Expo development build 运行,`react-native-webview` 加载 H5 URL 并附加 `native_app` 宿主 query。移动壳使用真实品牌图标资产已接入 `genarrative://` scheme、iOS associated domain 和 Android app link filter启动和运行时 deep link 只会映射到同源 H5 路径并继续附加 HostBridge 上下文,外域和危险协议回退到默认主站入口。首轮真实能力包括 `host.getRuntime``host.events``share.open``share.setTarget``navigation.openNativePage``navigation.canGoBack``app.openExternalUrl``clipboard.writeText``file.exportText``haptics.impact` 和 Android 返回键回退;其中 `share.setTarget` / `share.open` 会解析统一分享目标里的 `title``message``url``work``path``targetPath` 并调用 React Native 系统分享面板;`navigation.openNativePage` 在 Expo 壳内只接受同源 H5 route 并切换 WebView URL不伪造尚未存在的登录、支付或其它原生页面`navigation.canGoBack` 由 WebView 导航状态变化实时注入 H5`app.openExternalUrl` 只允许 `http:``https:``mailto:``tel:` 外链协议,`clipboard.writeText` 由 H5 复制服务优先调用并写入系统剪贴板;`file.exportText` 通过 Expo 文件系统写入缓存文本文件,再交给系统分享 / 保存面板,文件名必须清洗,单次文本不超过 5 MiB成功只返回文件名和字节数。登录和支付尚未接入渠道 SDK / 原生页面时明确返回 unsupported让 H5 fallback 承接。
当前状态:已新增 `apps/mobile-shell/`,通过 Expo development build 运行,`react-native-webview` 加载 H5 URL 并附加 `native_app` 宿主 query。移动壳使用真实品牌图标资产已接入 `genarrative://` scheme、iOS associated domain 和 Android app link filter启动和运行时 deep link 只会映射到同源 H5 路径并继续附加 HostBridge 上下文,外域和危险协议回退到默认主站入口。首轮真实能力包括 `host.getRuntime``host.events``share.open``share.setTarget``navigation.openNativePage``navigation.canGoBack``app.openExternalUrl``clipboard.writeText``file.exportText``haptics.impact` 和 Android 返回键回退;其中 `share.setTarget` / `share.open` 会解析统一分享目标里的 `title``message``url``work``path``targetPath` 并调用 React Native 系统分享面板;`navigation.openNativePage` 在 Expo 壳内只接受同源 H5 route 并切换 WebView URL不伪造尚未存在的登录、支付或其它原生页面`navigation.canGoBack` 由 WebView 导航状态变化实时注入 H5`app.openExternalUrl` 只允许 `http:``https:``mailto:``tel:` 外链协议,`clipboard.writeText` 由 H5 复制服务优先调用并写入系统剪贴板;`file.exportText` 通过 Expo 文件系统写入缓存文本文件,再交给系统分享 / 保存面板,文件名必须清洗,单次文本不超过 5 MiB成功只返回文件名和字节数`haptics.impact` 通过 Expo Haptics 承接运行时轻触反馈H5 在宿主不支持时回退到浏览器 vibration。登录和支付尚未接入渠道 SDK / 原生页面时明确返回 unsupported让 H5 fallback 承接。
### Phase 3Tauri 桌面壳 MVP

View File

@@ -45,6 +45,7 @@ AI H5 sandbox
- `setHostShareTarget()`:把当前公开作品分享目标同步给宿主。
- `openHostShareGrid()`:微信小程序九宫格切图页。
- `writeHostClipboardText()`:原生 App 宿主的受控剪贴板入口。H5 复制服务在 `native_app` 中优先通过 `clipboard.writeText` 写入 Expo / Tauri 系统剪贴板;宿主不可用、拒绝或返回 unsupported 时继续回退到浏览器 Clipboard API 和 legacy selection copy。
- `requestHostHapticsImpact()`:原生 App 宿主的受控触觉反馈入口。Expo 移动壳通过 `haptics.impact` 调用 Expo HapticsH5 运行时点击反馈在 `native_app` 中优先请求宿主触觉,宿主不可用、拒绝或返回 unsupported 时继续回退到浏览器 `navigator.vibrate`
- `navigateHostNativePage()`:受控跳转宿主页,供订阅授权、支付、登录等 adapter 复用。Expo 移动壳首版只接受同源 H5 route 并切换 WebView URLTauri 桌面壳同样只接受 `https://app.genarrative.world` 同源 H5 route 并在主窗口内跳转。真正原生页面、登录和支付能力必须等对应 SDK / 页面接入后再声明支持。
- `exportHostTextFile()`:原生 App 宿主的受控文本导出入口。Expo 移动壳通过 `file.exportText` 写入缓存文本文件并交给系统分享 / 保存面板Tauri 桌面壳通过 `file.exportText` 打开系统保存对话框并写入用户选择的文件。文件名必须清洗,单次文本不超过 5 MiB成功只返回文件名和字节数不把本机绝对路径暴露给 H5系统分享不可用或用户取消时返回明确错误由 H5 fallback 承接。

View File

@@ -49,11 +49,11 @@ import {
} from '../../services/match3dSpritesheetParser';
import {
DEFAULT_RUNTIME_LEVEL_AUDIO_CONFIG,
playRuntimeClickSound,
playRuntimeCountdownSound,
playRuntimeLevelClearSound,
playRuntimeMergeSound,
resolveRuntimeCountdownSecondBucket,
triggerRuntimeClickFeedback,
} from '../../services/runtimeAudioFeedback';
import { useAuthUi } from '../auth/AuthUiContext';
import { RuntimeResourcePendingMarker } from '../common/RuntimeResourcePendingMarker';
@@ -1537,7 +1537,9 @@ export function Match3DRuntimeShell({
const playClickSound = useCallback(
(item: Match3DItemSnapshot) => {
const src = clickSoundByTypeId.get(item.itemTypeId);
playRuntimeClickSound(src, musicVolume);
triggerRuntimeClickFeedback(src, musicVolume, {
hapticsStyle: 'light',
});
},
[clickSoundByTypeId, musicVolume],
);

View File

@@ -49,10 +49,10 @@ import {
} from '../../services/puzzle-runtime/puzzleUiSpritesheetParser';
import {
DEFAULT_RUNTIME_LEVEL_AUDIO_CONFIG,
playRuntimeClickSound,
playRuntimeCountdownSound,
playRuntimeLevelClearSound,
resolveRuntimeCountdownSecondBucket,
triggerRuntimeClickFeedback,
} from '../../services/runtimeAudioFeedback';
import { useAuthUi } from '../auth/AuthUiContext';
import { PlatformRuntimeStatusToast } from '../common/PlatformRuntimeStatusToast';
@@ -390,22 +390,11 @@ type PuzzleRuntimeDragTargetState = {
groupId: string | null;
};
function triggerPuzzlePiecePressHapticFeedback() {
if (typeof navigator === 'undefined') {
return;
}
const vibrate = navigator.vibrate;
if (typeof vibrate !== 'function') {
return;
}
vibrate.call(navigator, [PUZZLE_PIECE_PRESS_HAPTIC_PATTERN_MS]);
}
function triggerPuzzlePiecePressFeedback(volume: number) {
triggerPuzzlePiecePressHapticFeedback();
playRuntimeClickSound(undefined, volume);
triggerRuntimeClickFeedback(undefined, volume, {
fallbackVibrationPatternMs: PUZZLE_PIECE_PRESS_HAPTIC_PATTERN_MS,
hapticsStyle: 'light',
});
}
/**

View File

@@ -12,6 +12,7 @@ import {
openHostShareGrid,
openWechatMiniProgramShareGridPage,
postWechatMiniProgramMessage,
requestHostHapticsImpact,
requestHostLogin,
requestHostPayment,
requestWechatMiniProgramPayment,
@@ -311,6 +312,9 @@ describe('hostBridge', () => {
await expect(
writeHostClipboardText({ text: '作品号 PZ-1' }),
).resolves.toBe(true);
await expect(requestHostHapticsImpact({ style: 'medium' })).resolves.toBe(
true,
);
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
request: expect.objectContaining({
@@ -340,6 +344,14 @@ describe('hostBridge', () => {
},
}),
});
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
request: expect.objectContaining({
method: 'haptics.impact',
payload: {
style: 'medium',
},
}),
});
});
test('原生 App 宿主不支持能力时回退到 H5 路径', async () => {
@@ -373,6 +385,9 @@ describe('hostBridge', () => {
await expect(
writeHostClipboardText({ text: '作品号 PZ-1' }),
).resolves.toBe(false);
await expect(requestHostHapticsImpact({ style: 'light' })).resolves.toBe(
false,
);
});
test('普通浏览器不处理宿主文本导出', async () => {

View File

@@ -1,6 +1,7 @@
import type {
FileExportTextPayload,
FileExportTextResult,
HapticsImpactPayload,
HostBridgeMethod,
HostBridgeRuntimeResult,
} from '../../../packages/shared/src/contracts/hostBridge';
@@ -65,6 +66,8 @@ export type HostClipboardWriteTextRequest = {
text: string;
};
export type HostHapticsImpactRequest = HapticsImpactPayload;
function isUnsupportedHostBridgeError(error: unknown) {
return (
error instanceof Error &&
@@ -487,3 +490,17 @@ export async function exportHostTextFile(
throw error;
}
}
export async function requestHostHapticsImpact(
params: HostHapticsImpactRequest = {},
) {
if (getHostRuntime().kind !== 'native_app') {
return false;
}
try {
return await requestNativeHostBoolean('haptics.impact', params);
} catch {
return false;
}
}

View File

@@ -0,0 +1,123 @@
/* @vitest-environment jsdom */
import { afterEach, describe, expect, test, vi } from 'vitest';
import { resetNativeAppHostBridgeForTest } from './host-bridge/nativeAppHostBridge';
import {
triggerRuntimeClickFeedback,
triggerRuntimeImpactFeedback,
} from './runtimeAudioFeedback';
function waitForNextTask() {
return new Promise<void>((resolve) => {
window.setTimeout(resolve, 0);
});
}
function asTauriInvoke(
invoke: (command: string, args?: Record<string, unknown>) => Promise<unknown>,
) {
return async function tauriInvoke<Result = unknown>(
command: string,
args?: Record<string, unknown>,
) {
return (await invoke(command, args)) as Result;
};
}
afterEach(() => {
vi.restoreAllMocks();
window.history.replaceState(null, '', '/');
delete window.ReactNativeWebView;
delete window.__TAURI__;
resetNativeAppHostBridgeForTest();
});
describe('runtimeAudioFeedback', () => {
test('普通浏览器点击反馈同步使用 vibration fallback', () => {
const vibrate = vi.fn();
Object.defineProperty(navigator, 'vibrate', {
configurable: true,
value: vibrate,
});
triggerRuntimeImpactFeedback('light', 12);
expect(vibrate).toHaveBeenCalledWith([12]);
});
test('原生壳触觉反馈成功时不再触发浏览器 vibration fallback', async () => {
const vibrate = vi.fn();
const invoke = vi.fn(
async (_command: string, args?: Record<string, unknown>) => {
const request = (args as { request: { id: string } }).request;
return {
bridge: 'GenarrativeHostBridge',
version: 1,
id: request.id,
ok: true,
result: true,
};
},
);
Object.defineProperty(navigator, 'vibrate', {
configurable: true,
value: vibrate,
});
window.history.replaceState(null, '', '/?clientRuntime=native_app');
window.__TAURI__ = {
core: {
invoke: asTauriInvoke(invoke),
},
};
triggerRuntimeClickFeedback(undefined, 0.6, {
fallbackVibrationPatternMs: 12,
hapticsStyle: 'medium',
});
await waitForNextTask();
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
request: expect.objectContaining({
method: 'haptics.impact',
payload: {
style: 'medium',
},
}),
});
expect(vibrate).not.toHaveBeenCalled();
});
test('原生壳不支持触觉反馈时回退到浏览器 vibration', async () => {
const vibrate = vi.fn();
Object.defineProperty(navigator, 'vibrate', {
configurable: true,
value: vibrate,
});
window.history.replaceState(null, '', '/?clientRuntime=native_app');
window.__TAURI__ = {
core: {
invoke: asTauriInvoke(
vi.fn(async (_command: string, args?: Record<string, unknown>) => {
const request = (args as { request: { id: string } }).request;
return {
bridge: 'GenarrativeHostBridge',
version: 1,
id: request.id,
ok: false,
error: {
code: 'unsupported_method',
message: 'unsupported_method',
},
};
}),
),
},
};
triggerRuntimeImpactFeedback('light', 12);
await waitForNextTask();
expect(vibrate).toHaveBeenCalledWith([12]);
});
});

View File

@@ -1,3 +1,8 @@
import {
isNativeAppRuntime,
requestHostHapticsImpact,
} from './host-bridge/hostBridge';
export const DEFAULT_RUNTIME_CLICK_SOUND_SRC = '/audio/ui-click-soft.wav';
export const DEFAULT_RUNTIME_LEVEL_CLEAR_SOUND_SRC =
'/audio/ui-level-clear.wav';
@@ -16,6 +21,19 @@ export const DEFAULT_RUNTIME_LEVEL_AUDIO_CONFIG = {
const runtimeAudioCache = new Map<string, HTMLAudioElement>();
function triggerBrowserRuntimeVibration(patternMs: number) {
if (typeof navigator === 'undefined') {
return;
}
const vibrate = navigator.vibrate;
if (typeof vibrate !== 'function') {
return;
}
vibrate.call(navigator, [patternMs]);
}
function clampRuntimeAudioVolume(value: number) {
if (!Number.isFinite(value)) {
return 0.6;
@@ -63,6 +81,45 @@ export function playRuntimeCountdownSound(volume = 0.6) {
playRuntimeClickSound(DEFAULT_RUNTIME_COUNTDOWN_SOUND_SRC, volume);
}
export function triggerRuntimeImpactFeedback(
style: 'light' | 'medium' | 'heavy' = 'light',
fallbackVibrationPatternMs?: number,
) {
if (!isNativeAppRuntime()) {
if (fallbackVibrationPatternMs !== undefined) {
triggerBrowserRuntimeVibration(fallbackVibrationPatternMs);
}
return;
}
void requestHostHapticsImpact({ style })
.then((handled) => {
if (!handled && fallbackVibrationPatternMs !== undefined) {
triggerBrowserRuntimeVibration(fallbackVibrationPatternMs);
}
})
.catch(() => {
if (fallbackVibrationPatternMs !== undefined) {
triggerBrowserRuntimeVibration(fallbackVibrationPatternMs);
}
});
}
export function triggerRuntimeClickFeedback(
source = DEFAULT_RUNTIME_CLICK_SOUND_SRC,
volume = 0.6,
options: {
hapticsStyle?: 'light' | 'medium' | 'heavy';
fallbackVibrationPatternMs?: number;
} = {},
) {
triggerRuntimeImpactFeedback(
options.hapticsStyle ?? 'light',
options.fallbackVibrationPatternMs,
);
playRuntimeClickSound(source, volume);
}
export function resolveRuntimeCountdownSecondBucket(remainingMs: number) {
if (
!Number.isFinite(remainingMs) ||