当组件依赖陀螺仪,如何在桌面端 story 提供 mock 数据
解读
在国内实际开发流程中,带陀螺仪能力的组件(如 3D 商品展示、全景看房、重力感应小游戏)往往由设计/产品先在 Storybook 里验收交互状态,而桌面端浏览器普遍不支持 devicemotion 事件。如果 story 直接读取真实传感器,会导致白屏、异常或测试用例无法回归。因此,必须在 story 层稳定地注入 mock 数据,保证 UI 在各种姿态下可复现、可快照、可自动化测试。
知识点
- Storybook 参数(parameters)与全局装饰器(decorators) 的优先级规则
- Web APIs:devicemotion / deviceorientation 事件格式(含加速度、加速度含重力、旋转速率、绝对角度)
- TypeScript 类型声明合并(window.DeviceMotionEvent)与国内主流浏览器兼容性差异
- Storybook 的 play 函数 与 @storybook/testing-library 的联合使用,用于在交互测试中断言姿态变化后的 UI 变化
- ES 模块拦截(import.meta.hot 或 webpack alias) 与 Object.defineProperty 劫持 navigator 对象,实现无侵入 mock
- 国内低版本 Chrome(360、QQ、搜狗) 对 devicemotion 的部分支持陷阱(只触发一次、数值为 0),需要在 story 里兜底补偿
- @storybook/addon-controls 与 addon-toolbars 的全局全局全局 toolbar 全局全局全局 toolbar 全局全局全局 toolbar 全局全局全局 toolbar 用法,通过下拉条让产品同学手动拖拽姿态角
答案
- 在
.storybook/preview.tsx里注册全局装饰器,优先拦截原生事件:
import { Decorator } from '@storybook/react';
const gyroDecorator: Decorator = (Story, context) => {
const { mockGyro } = context.parameters;
useEffect(() => {
if (!mockGyro) return;
// 1. 停止原生事件
window.removeEventListener('devicemotion', null);
window.removeEventListener('deviceorientation', null);
// 2. 构造符合 W3C 标准的 Event
const fire = () => {
const motion = new DeviceMotionEvent('devicemotion', {
acceleration: { x: mockGyro.ax, y: mockGyro.ay, z: mockGyro.az },
accelerationIncludingGravity: { x: mockGyro.gx, y: mockGyro.gy, z: mockGyro.gz },
rotationRate: { alpha: mockGyro.rα, beta: mockGyro.rβ, gamma: mockGyro.rγ },
interval: 16,
});
window.dispatchEvent(motion);
const orient = new DeviceOrientationEvent('deviceorientation', {
alpha: mockGyro.α,
beta: mockGyro.β,
gamma: mockGyro.γ,
absolute: true,
});
window.dispatchEvent(orient);
};
fire();
const id = setInterval(fire, 16); // 60 FPS
return () => clearInterval(id);
}, [mockGyro]);
return <Story />;
};
export const decorators = [gyroDecorator];
- 在组件 story 中声明式注入:
export const Landscape: Story = {
parameters: {
mockGyro: {
α: 90, β: 0, γ: 0,
ax: 0.1, ay: 0, az: 0.2,
gx: 0, gy: 0, gz: 9.8,
rα: 0, rβ: 0, rγ: 0,
},
},
};
- 为了让非研发角色也能调试,在
.storybook/preview.tsx追加 addon-toolbars 全局工具栏:
export const globalTypes = {
gyroMock: {
name: '陀螺仪',
description: '实时调整姿态角',
defaultValue: { α: 0, β: 0, γ: 0 },
toolbar: {
icon: 'compass',
dynamicTitle: true,
items: [
{ value: { α: 0, β: 0, γ: 0 }, title: '正面' },
{ value: { α: 90, β: 0, γ: 0 }, title: '左横屏' },
{ value: { α: -90, β: 0, γ: 0 }, title: '右横屏' },
{ value: { α: 0, β: 90, γ: 0 }, title: '立屏' },
],
},
},
};
- 在自动化测试中,通过 play 函数 断言:
export const Shake: Story = {
parameters: {
mockGyro: { ax: 5, ay: 5, az: 5 }, // 剧烈晃动
},
play: async ({ canvasElement }) => {
await waitFor(() => {
expect(canvasElement.querySelector('.shake')).toBeInTheDocument();
});
},
};
- 针对国内低版本浏览器的兼容,在装饰器里兜底补偿:
if (typeof DeviceMotionEvent === 'undefined') {
(window as any).DeviceMotionEvent = class Fake {};
}
通过以上五步,桌面端 story 无需真机即可稳定呈现所有陀螺仪依赖状态,设计走查、测试回归、快照比对都能一键完成。
拓展思考
- 多端一致性:在 Vite + Storybook 7 的模式下,可把同一套 mock 数据同步到移动端真机调试页面,实现 “桌面调 UI,真机验性能” 的国内主流大厂协作流程。
- 性能治理:若组件对 60 FPS 事件流做密集矩阵运算,可在装饰器里动态降频(如 200 ms),并通过 addon-measure 给出主线程耗时火焰图,防止线上卡顿。
- 安全合规:国内应用商店对陀螺仪权限审核趋严,可在 story 里一键切换“未授权”状态,提前暴露权限拒绝后的空态 UI,减少发版被打回的风险。