写一个全局 decorator,为所有 stories 自动加上 RTL 切换按钮

解读

面试官想验证三件事:

  1. 你是否理解 Storybook 的 decorator 机制 与 全局注册 方式;
  2. 你是否能在不侵入组件源码的前提下,用 React Context + 状态提升 实现方向切换;
  3. 你是否熟悉国内常用的 i18n/RTL 方案(如 styled-components 的 ThemeProvider、Ant Design 的 ConfigProvider、业务自研的 dir 切换),并能在 Storybook 里 开箱即用。

一句话:把“切换按钮”做成 全局 UI,把“方向注入”做成 无感能力,让任何 story 都不需要改代码就能跑 LTR/RTL 双方向。

知识点

  • decorator:本质是“高阶组件”,在 .storybook/preview.js 里通过 export const decorators = […] 注册即可对所有 story 生效。
  • 参数透传:decorator 会收到 Story 与 context,必须把 context.args 原样往下传,否则 Controls 会失效。
  • RTL 注入手段:
    – DOM 级:给 document.documentElement 设置 dir="rtl";
    – CSS 级:动态插入 <link href="rtl.css"> 或使用 styled-components 的 theme.rtl 变量;
    – 框架级:Ant Design 的 ConfigProvider direction="rtl"、Fusion 的 ConfigProvider rtl 等。
  • 持久化:用 useState + localStorage 把用户最后一次选择缓存在浏览器,刷新后仍生效,提升国内 低网速场景 下的体验。
  • Toolbar 方案(官方推荐):Storybook 6.3+ 提供 globalTypes + toolbar 声明,无需手写按钮即可在顶部工具栏出现“RTL”开关,但 仍需 decorator 消费该全局值。
  • 包体积:按钮图标直接用 @storybook/components 提供的 Icons 即可,避免再引一套 antd 或 mui 导致 产物体积爆炸,符合国内 微前端/子包 规范。

答案

以下给出 “双方案”:
A. 快速落地版——纯 decorator 手写按钮;
B. 工程化版——用 Storybook 官方 toolbar, decorator 仅消费。
两段代码均基于 React,Vue 项目把 React.createContext 换成 provide/inject 即可,思路一致。


A. 快速落地版(无 toolbar,按钮直接挂在 story 根节点)

// .storybook/decorators/withRtl.js
import React, { createContext, useContext, useEffect, useState } from 'react';
import { IconButton } from '@storybook/components';
import { Icons } from '@storybook/components';

const RtlContext = createContext({
  rtl: false,
  setRtl: () => {},
});

export const WithRtl = (Story, context) => {
  // 1. 从 localStorage 恢复
  const [rtl, setRtl] = useState(() => {
    try {
      return JSON.parse(localStorage.getItem('sb-rtl') || 'false');
    } catch {
      return false;
    }
  });

  // 2. 切换时落库 + 改 DOM
  useEffect(() => {
    localStorage.setItem('sb-rtl', JSON.stringify(rtl));
    document.documentElement.setAttribute('dir', rtl ? 'rtl' : 'ltr');
    // 如果是 AntD 项目,可额外触发 ConfigProvider
    document.documentElement.setAttribute('class', rtl ? 'rtl' : 'ltr');
  }, [rtl]);

  return (
    <RtlContext.Provider value={{ rtl, setRtl }}>
      {/* 全局悬浮按钮 */}
      <div
        style={{
          position: 'fixed',
          bottom: 16,
          right: 16,
          zIndex: 9999,
        }}
      >
        <IconButton
          active={rtl}
          title={rtl ? '切换到 LTR' : '切换到 RTL'}
          onClick={() => setRtl((v) => !v)}
        >
          <Icons icon="mirror" />
        </IconButton>
      </div>

      {/* 原样渲染 Story,必须透传 context.args */}
      <Story {...context.args} />
    </RtlContext.Provider>
  );
};
// .storybook/preview.js
import { WithRtl } from './decorators/withRtl';

export const decorators = [WithRtl];

B. 工程化版(官方 toolbar, decorator 仅消费)

// .storybook/preview.js
export const globalTypes = {
  direction: {
    name: 'RTL',
    description: '全局方向切换',
    defaultValue: 'ltr',
    toolbar: {
      icon: 'mirror',
      items: ['ltr', 'rtl'],
      showName: true,
    },
  },
};

// decorator 消费全局值
const withDirection = (Story, context) => {
  const direction = context.globals.direction;
  useEffect(() => {
    document.documentElement.setAttribute('dir', direction);
  }, [direction]);
  return <Story {...context.args} />;
};

export const decorators = [withDirection];

两段代码均通过 全局注册 实现“零侵入”,符合国内 大库多业务方 的维护节奏;同时把 localStorage 持久化 与 documentElement 操作收敛在一处,方便后续 单元测试(直接 mock localStorage 与 document 即可)。

拓展思考

  1. 性能:若组件库样式用 styled-components,可在 ThemeProvider 里注入 theme.rtl,避免二次加载 rtl.css,减少 首屏 20% 体积。
  2. 测试:用 Storybook 的 play 函数写自动化测试,断言 dir 属性与 getComputedStyle 的 padding-inline-start 变化,覆盖 视觉回归。
  3. 多人协作:把 globalTypes 抽成 npm 包 @yourcorp/storybook-rtl,通过 preview.js 的 addons 字段自动注册,实现 集团级复用。
  4. 暗黑模式联动:把 direction 与 theme 一起放进 useReducer,实现 “一键换肤 + 换向”,在 设计系统评审 时直接甩链接给设计师,减少 50% 沟通成本。