参加直播:周四,美国东部时间上午11点,Storybook 9发布 & 问答

XState Inspector

用于在 Storybook 中显示 XState Inspector 的 Storybook 插件

在 Github 上查看

XState Storybook 插件

安装

npm install -D @storybook/addons storybook-xstate-addon @xstate/inspect @xstate/react

使用方法

要在 Storybook 中使用此插件,只需将 addons: ["storybook-xstate-addon/preset"] 添加到您的 Storybook 配置中。

如果您想在所有故事中启用 Inspector,请在 /.storybook/preview.js 文件中进行如下设置。启用此设置后,您可以在某些故事中禁用 Inspector。

export const parameters = {
  xstate: true,
};

要在单个故事/故事文件中启用 Inspector,请将 xstate 参数设置为 true 或一个选项对象。

// this will turn on the inspector for all stories in the current file
export default {
  title: "Example",
  parameters: {
    xstate: true,
    // this option is passed to the inspect function
    xstateInspectOptions: {
      url: 'https://stately.ai/viz?inspect',
      serialize: null
    }
  },
};

// this turns the inspector on for only a single story
StoryComponent.parameters = {
  xstate: true,
};

为了更方便地查看大型状态图,您可以在 xstate 参数中传递 height 选项来强制指定 Inspector 的高度。

StoryComponent.parameters = {
  xstate: {
    height: "1000px",
  },
};

此外,在机器注册时,您可以通过添加 xstate 参数按 id 向其发送事件。

更多使用示例请参见 [./stories/Button.stories.tsx] 和 [./stories/Machines.stories.tsx]。

StoryComponent.parameters = {
  xstate: {
    machine_id1: {
      events: "event",
    },
    machine_id2: {
      events: { type: "event" },
    },
    machine_id3: {
      events: [{ type: "event1" }, { type: "event2" }],
    },
    machine_id4: {
      events: (state) => "event",
    },
    machine_id5: {
      events: ["event1", "event2"],
      delay: 2.5e3, // milliseconds to delay before sending the next event
      shouldRepeatEvents: true, // for looping event sequences
    },
  },
};

如果您希望将 Inspector 作为主故事本身使用,只需使用以下代码片段(使用 react)。

import { RenderMachine } from 'storybook-xstate-addon/RenderMachine';

export const MachinePreview = () => <RenderMachine machine={confirmMachine.withConfig({ ... })} events={[...events]} />;