exportToXStateViz function

Future<String> exportToXStateViz(
  1. StateMachine machine, {
  2. bool writeToFile = true,
})

Generates a json representation of the given StateMachine to be used in Stately's XState Viz.

It returns a String and it creates a File so that you can copy to the visualizer.

Implementation

Future<String> exportToXStateViz(
  StateMachine machine, {
  bool writeToFile = true,
}) async {
  const encoder = JsonEncoder.withIndent('  ');
  final result = '''
import { createMachine } from "xstate";

const machine = createMachine(
  ${encoder.convert(machine.rootNode.toJSON(machine.id))},
  {
    guards: {
      $_kHardcodedConditionFunctionName: () => true,
    }
  }
);
    ''';

  if (writeToFile) {
    final id = machine.id ?? 'automata_machine';
    await File('$id.js').writeAsString(result);
  }

  return result;
}