Stately
Stately StudioCode

Import from code

Importing from code is helpful if you’ve already built machines while working with XState, or have created a machine using our older Stately Viz but haven’t yet tried Stately Studio’s editor.

Import an example in the Stately editor

The examples in What are statecharts? include a JSON download. To keep an example in your own project:

  1. Download the example's XState JSON.
  2. Open the Stately editor and sign in.
  3. Open your project and start a new machine. Import the JSON file as XState, or paste its contents into the importer.
  4. Check the diagram before saving it in your project.

The example's Edit link opens the same model in a standalone editor. That view does not save to your workspace. Use its Code panel to download your edited machine before leaving the page.

Import state machines

Your state machine code should be formatted as a createMachine() factory function before import. The importer has basic validation in case your machine has basic errors, including reminding you if the createMachine definition is missing.

Check out an importable machine code example at the end of this page.

Caution: importing code will overwrite your current or selected machine unless you create a new machine from the machines list inside a project.

The Stately editor now supports importing multiple machines from code.

Create a new machine inside a project using imported code

Create a New machine from the machines list inside a project, then use the Import button to import code into the new machine.

Import code to overwrite your machine

Use Import button in the Code panel, or Machine > Import from the editor menu to overwrite your current machine.

Machine code example

Below is an example of a createMachine() factory function which you can import as a machine without any errors:

createMachine({
  id: 'Video',
  initial: 'Closed',
  description: 'Video player',
  states: {
    Closed: {
      on: {
        PLAY: {
          target: 'Opened',
        },
      },
    },
    Opened: {
      invoke: {
        src: 'startVideo',
      },
      initial: 'Playing',
      description: 'Fullscreen mode',
      states: {
        Playing: {
          on: {
            PAUSE: {
              target: 'Paused',
            },
          },
        },
        Paused: {
          on: {
            PLAY: {
              target: 'Playing',
            },
          },
        },
        Stopped: {
          type: 'final',
          after: {
            5000: {
              target: '#Video.Closed',
              actions: [],
              internal: false,
            },
          },
        },
      },
      on: {
        STOP: {
          target: '.Stopped',
        },
      },
    },
  },
  context: {},
  predictableActionArguments: true,
  preserveActionOrder: true,
});

On this page