Giter Club home page Giter Club logo

xstate-viz's Introduction

xstate-viz's People

Contributors

caqu avatar chenxsan avatar davidkpiano avatar dependabot[bot] avatar farskid avatar joeblynch avatar m0o0scar avatar raineratspirit avatar ryanmcg avatar sesm avatar tamebadger avatar timoxley avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xstate-viz's Issues

Minor UI issues with latest master running locally

Thanks so much for this wonderful visualizer! It was great to use as we created our first machine, but it ended up growing in complexity, where we could not simply copy and paste the config into this online visualizer.

We ended up forking it, and tried to configure this code to accept a machine as a prop (instead of relying on the json editor to recreate a machine every time). This works, but the rendering of the nodes and arrows do not look like the current version online...

This is a screenshot of our machine using your online visualizer...
screen shot 2019-02-13 at 5 53 45 pm

Here is a screenshot using our forked visualizer running locally.

  • The arrows are jagged, and are very hard to follow.
  • For Transient events, it renders a ?
  • For Transient events, it fails to draw the origin point for the arrow
  • In some cases, some actions on the non-active statenode are still active when they should not be

screen shot 2019-02-13 at 6 00 19 pm

Is this repo missing a few enhancements compared to what is live already? I'd like to be able to build and run this locally, and these issues are the last remaining things.

Thanks again!

Where to find my saved 'viz'

XState and this Visualizer is so cool, thanks a lot for these tools.
Not that long ago I had to write VBA macros in microsoft Visio to generate ObjectiveC code for my machine !!!
The only thing though, I need to be logged in to save a machine, but when I'm logged in, where can I find my saved machines ???

Storybook layout

Including the visualizer in Storybook (which would be the natural place as it's a living documentation) looks pretty bad. It works fine, but styling is all over the place. It's not really possible to override styles/apply theming as it's using styled components:

image

What would be the best approach to make it embeddable in various places and avoid CSS conflicts with host styles?

Loop transition not working inside parallel state node.

So loop transition(may be not best name, do you have some naming convention for this type?) example:
https://xstate.js.org/viz/?gist=a4538161db2a559666e1ce8440a871d4
Transition executes every second, you can say it by animation and console.log.

But if we put it inside parallel state node:
https://xstate.js.org/viz/?gist=98768528bb1b95c6236cde367c18ebc5
It triggers exactly one time.

Not sure is it visualisation problem or old xstate version bug. But second example works as expected with latest version of xstate(+@xstate/react if it matters).

How about making the viz a drop-in visualizer to any application?

I just did a quick POC to make xstate-viz a drop-in visualizer in a react app so that it could be toggled on and off as needed, see it in action here

Sample code below, basically the viz component lives with-in the real project and will be updated whenever the machine content was changed.

As a side note, it would be great to toggle show/hide of the sidebar by an argument.

import { StateChart } from '@statecharts/xstate-viz'

const App = () => {
  const [state, send] = useMachine(MainMachine)
  const [debug, setDebug] = useState(false)
  const viz = debug ? <StateChart machine={MainMachine} /> : null

  return (
    <div>
      my app

      <button
        style={{float:'right'}}
        onClick={() => setDebug(!debug)}>
        viz
      </button>

      {viz}
    </div>
  )
}

How to run locally?

Trying to run the examples locally with npm run examples and getting stuck.

I saw that the examples folder is gitignored–is that correct? Should there be a package.json in there that has a start script?

Thanks for xstate btw. Just started trying it out and really digging it 🤙

Track guard state behind-the-scenes when exiting, clear on re-entry

I did an experiment trying to understand the green/red/grey visualization behavior in relation to null events and their guards:

https://xstate.js.org/viz/?gist=fbbd5dab67c92587cd726648ad1fa212

I was attempting to use a pure state.matches(...) approach but found that can't work (if the green/red behavior is desired) because when the visualizer runs the guards in the context of states to which those null events are not attached, then meta.state will be undefined.

At first I thought a solution might be for the visualizer to always pass the state, but then I realized that can lead to other problems, e.g. green might switch to red or grey if testing on state.matches(...) because the current state value may be 2+ steps removed from the state to which the guards are applicable and matching on the current state becomes ambiguous.

After experimenting with context to achieve the desired effect, I came up with an idea: that the best way to get the always-correct red/green/grey value would be for the visualizer to track the true/false/undefined value returned by the guard in a way that's opaque to the machine itself; and to reset that visual tracking upon re-entry. With such a mechanism in place it seems like it wouldn't be necessary for the visualizer to always run the guards, i.e. when they're not applicable to the current state, like it does at present. It would also avoid problems that come up with context being updated later in transitions/actions not applicable to the guards, and possibly resulting in incorrect green/red/grey toggling.

choose action is not supported

The choose action is described in the doc and very useful.

Right now xstate-viz chokes on it.

What would be the workaround in the mean time ?

VSCode extension

(not sure this should be here or on Spectrum as it's more of a discussion than issue, feel free to kick me there)

I think it would be awesome if there was a vscode extension that could generate the statecharts from a highlighted code block. The UX I have in mind is:

  1. highlight the machine code (what you would copy to the current visualizer site).
  2. Hit some key combination to execute the "Visualize Machine" command.
  3. It opens a new file / tab that shows the machine (I'm not sure it's possible for it to be interactive? but I suppose it could generate an image)

If 3 is not possible or difficult, it could just open xstate.js.org/viz pre-filled out with the code

Bonus points: re-generating the chart as you save the file (even if there are non-chart related things in the same file).

The app does not build

Hi,

I am following the instructions as per README

Problem 1: 'react-scripts' is not recognized as an internal or external command,
That was easy to fix ... forked the code, created a branch, ran npm i --save react-scripts

Problem 2: a slew of compile errors (see below).
Is xstate-viz in a consistent state so that it can be built from the source code, or am I doing something wrong?

$ npm run develop

> @statecharts/[email protected] develop C:\code\@dmitrynovik\xstate-viz
> npm link && concurrently "tsc -w" "cd public && npm link @statecharts/xstate-viz && npm start"

npm WARN @statecharts/[email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})  
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\watchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})  
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})   
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})  

audited 2378 packages in 14.965s

87 packages are looking for funding
  run `npm fund` for details

found 1727 vulnerabilities (1724 low, 1 moderate, 2 high)
  run `npm audit fix` to fix them, or `npm audit` for details
C:\Users\dmitry.novik\AppData\Roaming\npm\node_modules\@statecharts\xstate-viz -> C:\code\@dmitrynovik\xstate-viz
[0] 9:45:12 AM - Starting compilation in watch mode...
[0]
[1] C:\code\@dmitrynovik\xstate-viz\public\node_modules\@statecharts\xstate-viz -> C:\Users\dmitry.novik\AppData\Roaming\npm\node_modules\@statecharts\xstate-viz -> C:\code\@dmitrynovik\xstate-viz
[1] 
[1] > [email protected] start C:\code\@dmitrynovik\xstate-viz\public
[1] > react-scripts start
[1]
[1] i 「wds」: Project is running at http://192.168.104.29/
[1] i 「wds」: webpack output is served from /viz
[1] i 「wds」: Content not from webpack is served from C:\code\@dmitrynovik\xstate-viz\public\public
[1] i 「wds」: 404s will fallback to /viz/
[1] Starting the development server...
[1]
[0] src/App.tsx(137,36): error TS2339: Property 'code' does not exist on type 'EventObject'.
[0] src/App.tsx(159,36): error TS2339: Property 'code' does not exist on type 'EventObject'.
[0] src/App.tsx(331,40): error TS2339: Property 'data' does not exist on type 'EventObject'.
[0] src/App.tsx(421,47): error TS2339: Property 'data' does not exist on type 'EventObject'.
[0] src/App.tsx(533,37): error TS2339: Property 'data' does not exist on type 'EventObject'.
[0] src/App.tsx(616,32): error TS2339: Property 'context' does not exist on type 'never'.
[0] src/CodePanel.tsx(4,26): error TS2307: Cannot find module 'xstate/lib/graph'.
[0] src/Editor.tsx(46,11): error TS2339: Property 'matches' does not exist on type 'never'.
[0] src/Editor.tsx(85,21): error TS2339: Property 'matches' does not exist on type 'never'.
[0] src/Editor.tsx(89,21): error TS2339: Property 'matches' does not exist on type 'never'.
[0] src/Editor.tsx(93,21): error TS2339: Property 'matches' does not exist on type 'never'.
[0] src/Editor.tsx(97,21): error TS2339: Property 'matches' does not exist on type 'never'.
[0] src/Editor.tsx(99,22): error TS2339: Property 'matches' does not exist on type 'never'.
[0] src/Editor.tsx(100,22): error TS2339: Property 'matches' does not exist on type 'never'.
[0] src/Notifications.tsx(35,32): error TS2339: Property 'index' does not exist on type 'EventObject'.
[0] src/Notifications.tsx(48,29): error TS2339: Property 'data' does not exist on type 'EventObject'.
[0] src/StateChart.tsx(22,26): error TS2307: Cannot find module 'xstate/lib/graph'.
[0] src/StateChartNode.tsx(18,26): error TS2307: Cannot find module 'xstate/lib/graph'.
[0] src/StateChartNode.tsx(637,48): error TS7006: Parameter 'edge' implicitly has an 'any' type.
[0] src/StateChartNode.tsx(660,19): error TS2554: Expected 3 arguments, but got 2.
[0] src/StateChartNode.tsx(704,49): error TS7006: Parameter 'action' implicitly has an 'any' type.
[0] src/StateChartNode.tsx(704,57): error TS7006: Parameter 'i' implicitly has an 'any' type.
[0] src/StateChartVisualization.tsx(3,26): error TS2307: Cannot find module 'xstate/lib/graph'.
[0] src/StateChartVisualization.tsx(92,20): error TS7006: Parameter 'edge' implicitly has an 'any' type.
[0] src/User.tsx(75,20): error TS2339: Property 'matches' does not exist on type 'never'.
[0]
[0] 9:45:20 AM - Found 25 errors. Watching for file changes.
[1] Failed to compile.
[1]
[1] ../lib/StateChart.js
[1] Module not found: Can't resolve 'xstate/lib/graph' in 'C:\code\@dmitrynovik\xstate-viz\lib'
[1] Compiling...
[1] Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\hiberfil.sys'
[1] Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\pagefile.sys'
[1] Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\swapfile.sys'
[1] Failed to compile.
[1]
[1] ../lib/StateChart.js
[1] Module not found: Can't resolve 'xstate/lib/graph' in 'C:\code\@dmitrynovik\xstate-viz\lib'

```


Feature Request: Dark Theme

I'm probably not the first one to ask, but I haven't seen any issue on the subject. A dark theme would be pretty nice since most other developer tools have a dark theme.

I can make a PR if you want. I'm just not sure how you would prefer it to be implemented. Obviously, it's gonna use a state machine to keep the state of the toggle between the light and dark theme. I see you are already using styled-components so it would be pretty trivial to use the theming functionality.

Error: m is not a function

Description

Loading this Visualizer with this Gist
A minimal reproduction linked in the comment below triggers the following error:

TypeError: m is not a function
    at StateChartNode.js:191
    at Array.map (<anonymous>)
    at e.render (StateChartNode.js:176)

Feature Request: Improve Diagram Layout

Description

Currently, the Visualizer layout algorithm isn't producing very readable diagrams.
The following is a comparison between a diagram produced by PlantUML to one made by XState-Viz:

Details

Suggestion

Two possible approaches:

  • Experiment and tweak the layout algorithm and/or the resizing of the diagram.
  • Research layout solutions implemented in similar tools and try to adapt them for use in our Visualizer system.

Can't perform a React state update on an unmounted component

This seems to usually occur on state change (usually during development when a hot reload occurs on the watch)

index.js:1437 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    in InitialEdge (created by StateChart)
    in svg (created by StateChart)
    in div (created by Context.Consumer)
    in StyledComponent (created by styled.div)
    in styled.div (created by StateChart)
    in div (created by Context.Consumer)
    in StyledComponent (created by styled.div)
    in styled.div (created by StateChart)

State machine crashes the new viz, works on the old viz

Crashes the viz:

import { createMachine } from "xstate";

createMachine({
  on: {
    A: { actions: "a" },
    B: { actions: "b" },
  },
  states: {
    initial: {},
  },
});

Produces:

instrument.js:109 Error: java.lang.IllegalStateException: Invalid hitboxes for scanline constraint calculation.
    at icb.Mx [as Wd] (elk.bundled.js:6253)
    at icb.Sx [as _d] (elk.bundled.js:6253)
    at icb.Kx (elk.bundled.js:2734)
    at icb.Vx (elk.bundled.js:1337)
    at new icb (elk.bundled.js:1370)
    at zCb (elk.bundled.js:5525)
    at yCb (elk.bundled.js:5161)
    at BCb.CCb [as Ke] (elk.bundled.js:6253)
    at pBb (elk.bundled.js:4776)
    at rBb (elk.bundled.js:3244)
    at uCb (elk.bundled.js:5196)
    at Ccc.Dcc [as Me] (elk.bundled.js:6253)
    at WBb (elk.bundled.js:4735)
    at ZBb (elk.bundled.js:6095)
    at $Bb (elk.bundled.js:5408)
    at Kdc (elk.bundled.js:5968)
    at Ldc.Qdc [as nf] (elk.bundled.js:6253)
    at IRb (elk.bundled.js:6004)
    at GRb (elk.bundled.js:4412)
    at gSb.hSb [as $e] (elk.bundled.js:6253)
    at b$c (elk.bundled.js:4544)
    at e$c (elk.bundled.js:6186)
    at d$c (elk.bundled.js:5109)
    at Iqd (elk.bundled.js:5889)
    at h.dispatch (elk.bundled.js:6188)
    at h.saveDispatch (elk.bundled.js:6188)
    at elk.bundled.js:6189
    at r (helpers.js:72)

Difficulty interacting with visualizer in storybook

I'm trying to add a simple visualizer to storybook to accompany hooks that will be wrapped around state machines. Everything displays perfectly, however click interactions dont seem to work. I'm able to tab to the button and hit enter to trigger an event, and if i go into the events panel of the visualizer i can send an event but clicking doesnt work. I'm hoping to use this to demonstrate the inner workings of some components to non technical people so getting the click interaction working would be great. Here is the relevant code:

export const ToggleMachine = ({
  initial = 'inactive',
  onToggle,
  enterActive,
  exitActive,
  enterInactive,
  exitInactive
}) => (
  Machine({
    initial: initial,
    id: 'toggleMachine',
    states: {
      inactive: {
        on: {
          TOGGLE: {
            target: 'active',
            actions: ['onToggle']
          }
        },
        entry: ['enterInactive'],
        exit: ['exitInactive']
      },
      active: {
        on: {
          TOGGLE: {
            target: 'inactive',
            actions: ['onToggle']
          }
        },
        entry: ['enterActive'],
        exit: ['exitActive']
      }
    }
  },
  {
    actions: {
      onToggle: (context, event) => {
        console.log('toggle');
        if (onToggle) {
          onToggle(context, event);
        }
      },
      enterActive: (context, event) => {
        if (enterActive) {
          enterActive(context, event);
        }
      },
      exitActive: (context, event) => {
        if (exitActive) {
          exitActive(context, event);
        }
      },
      enterInactive: (context, event) => {
        if (enterInactive) {
          enterInactive(context, event);
        }
      },
      exitInactive: (context, event) => {
        if (exitInactive) {
          exitInactive(context, event);
        }
      }
    }
  }
  )
);
import { ToggleMachine } from 'hooks/useToggleMachine';
import { StateChart } from '@statecharts/xstate-viz';

storiesOf('ToggleButton', module)
  .add('state chart', () => {
    const machine = ToggleMachine();
    return (
      <StateChart machine={machine} />
    );
  });

There are two versions of the visualizer online.

Issue:

Currently there seems to be two versions of the XState Visualizer online: an older version on Github Pages, and a newer version on xstate.js.org. If anyone, like me, has the Github Page bookmarked, they won't be able to access the newer version.

Solution:

Maybe the Github Page could redirect to the xstate.js.org page, or add a banner on the Github Page to tell users to go to the xstate.js.org page.

Screenshots:

From Github Pages:
image

From xstate.js.org:
image

Thank you!

Forbidden transition resets visualization to initial state

The machine below requires moving through states stepOne and stepTwo, in addition to requiring an approval. The approved context property ought to be able to be set at any state (i.e. start, stepOne, stepTwo, or awaitingApproval) as it is independent of what "stage" you're at. It is, however, a necessary condition for reaching success.

This implementation (credit to @semopz) shows the machine acting properly as described above:

https://codesandbox.io/s/zealous-sun-vt05g

However, clicking APPROVAL_GIVEN while in the states stepOne, stepTwo, or awaitingApproval in the Visualizer (below) will erroneously reset the state to start.

https://xstate.js.org/viz/?gist=e59bcb81a7d79dadd2b1d06a1f9e55ec

Feature Suggestion: Include offset in "unexpected token" syntax error

Thanks for the great tool. It is working wonderfully.

I have machine configurations that work in code, but I want to visualize. So I paste them into the visualizer but invariably there is a syntax error to resolve. (for example removing typescript parameter types).

As it stands right now, I get a syntax error in the console about "Unexpected token X". It would be very helpful if the code that found the unexpected token could provide an offset number in the file and if correspondingly the definition editor window could show the current offset of the cursor. That would allow users to find the place where they have their errors much easier.

xstate-viz not up to date with current version of xstate?

Since it's stated on the docs that null events are being deprecated for 'always' i've been using the latter instead but it doesn't seem to work with the online viz which kinda leaves me in a conundrum. Just need some advice if I should just revert back to null transitions for now?

Feature request: Provide <Preview> component

Running a local version of xstate-viz like in the public folder works, but it would be even better if we could provide a <Preview machine={myMachine} /> component that allows passing in a machine instance regardless if developed in typescript or javascript.
In addition when using <Preview /> the <StateChart previewOnly={true}> component would remove some functionality that is not required when running locally.

See this branch for a POC
https://github.com/RainerAtSpirit/xstate-viz/pull/new/previewOnly

image

Run/simulate/animate the machine

Hi,
Is it possible to simulate the machine running in the Visualizer?
It would also be nice to animate the visual machine with current state, token, actions.
tx

Cannot use send actions creator

this code below throw an error, when I implement send actions creator:

const sendName = send((context, event) => ({
  type: 'NAME',
  name: context.user.name
}));

...
actions: [
  assign({
    data: (context, event) => ({
      ...context.data,
      name: event.target.value,
    }),
  }),
  sendName ,
],
....

Error:

TypeError: Cannot read property 'indexOf' of undefined
react-dom.production.min.js:4408 TypeError: Cannot read property 'indexOf' of undefined
    at sn (StateChartAction.js:86)
    at Qi (react-dom.production.min.js:3274)
    at ka (react-dom.production.min.js:3899)
    at Vo (react-dom.production.min.js:5514)
    at zo (react-dom.production.min.js:5536)
    at Ns (react-dom.production.min.js:5958)
    at ws (react-dom.production.min.js:5925)
    at Ms (react-dom.production.min.js:6020)
    at Rn (react-dom.production.min.js:1737)

Allowing definition to be a JSON

I've been playing with state charts and have found the online vizualizer quite useful. Thank you for working on it @davidkpiano 🙌!

One minor improvement idea that came to my mind is about copy-pasting state machines to the definition tab. At the moment, the <AceEdit> component only accepts a function and does not understand a JSON. This means that when I want to visualize my app's statechart.json file, I have to be careful about what parts of the text I need to select and replace. This process takes some time and is error-prone (I'm an imperfect human).

It'd be cool if both functions and JSONs were accepted as an input, which would speed-up copy-pasting. The solution would be to add a condition before this line – not a big deal:

const createMachine = new Function("Machine", "interpret", "XState", machine);

A rough sketch:

const machineFunctionBody = machine.trim()[0] === '{'
  ? `const lightMachine = Machine(${machine});`
  : machine;
const createMachine = new Function("Machine", "interpret", "XState", machineFunctionBody);

What do you think?

`assign` import is not defined

Used the following config:

// Available variables:
// Machine (machine factory function)
// XState (all XState exports)

const fetchMachine = Machine(
  {
    id: 'fetch',
    initial: 'idle',
    context: {
      user: null,
      error: null
    },
    states: {
      idle: {
        on: { FETCH: 'loading' }
      },
      loading: {
        invoke: {
          src: (ctx, event) => fetchUser(event.query),
          onDone: {
            target: 'success',
            actions: assign({
              user: (_, event) => event.data
            })
          },
          onError: {
            target: 'failure',
            actions: assign({ error: (ctx, event) => event.data.message })
          }
        }
      },
      success: {
        onEntry: 'notifyResolve',
        type: 'final'
      },
      failure: {
        onEntry: 'notifyResolve',
        type: 'final'
      }
    }
  },
  {
    actions: {
      notifyResolve: (ctx, event) => console.log('notify', 'ctx:', ctx)
    }
  }
);

I just pulled this config straight out of my code, and thought it should work.

However when I click UPDATE button an alert pops up saying:

Error: unable to update the machine. Check the console for more info.

This is the error in the console:

StateChart.js:224 ReferenceError: assign is not defined
    at eval (eval at toMachine (StateChart.js:94), <anonymous>:25:22)
    at toMachine (StateChart.js:107)
    at StateChart.updateMachine (StateChart.js:222)
    at onChange (StateChart.js:170)
    at onClick (Editor.js:93)
    at Object.<anonymous> (react-dom.production.min.js:49)
    at h (react-dom.production.min.js:69)
    at react-dom.production.min.js:73
    at A (react-dom.production.min.js:140)
    at _ (react-dom.production.min.js:169

For reference, this is where I use this machine config, together with a small React component:
https://codesandbox.io/s/github/feelextra/react-xstate-playgrounds/tree/master/?fontsize=14&module=%2Fsrc%2FFetcher.

Browser DevTools?

First of all, thanks for creating this site, it makes xstate so much enjoyable to use 😄

I was thinking of browser devtools (something like redux devtools) version of this, and planning to dive in to figure out how to do that.

Are you aware of any such effort or is it already implemented by someone?

Usage of Visualizer in other places

Description
I'm trying to use <StateChart> to render out various machines in our system, so business folks and devs can peek their heads in and see what's going on.

What I'm running into is:

Screen Shot 2020-05-14 at 4 20 01 PM

whch appears to be referencing this: https://github.com/statecharts/xstate-viz/blob/master/src/StateChartVisualization.tsx#L3

Afaik, xstate/lib/graph has been moved into @xstate/graph.

Additional context
I'm mounting it all inside a web component and then rendering this inside there (following altered to omit nonessential info so I can share publicly):

import { StateChart } from "@statecharts/xstate-viz";

const Visualizer: React.FC<any> = ({machine}) => {
  const onSave = (e) => {
    console.log(e)
  }
  return (
    <StateChart machine={machine} onSave={onSave}/>
  )
}
import React from "react";
import ReactDOM from "react-dom";
import Visualizer from "../components/visualizer";
import machine from "project/src/machine";

export default class PageProjectVisualizer extends HTMLElement {
  connectedCallback() {
    const mountPoint = document.createElement("span");
    this.attachShadow({ mode: "open" }).appendChild(mountPoint);

    ReactDOM.render(<Visualizer machine={machine} />, mountPoint);
  }
}
customElements.define("page-project-visualizer", PageProjectVisualizer);

Is this package intended to be used in this way? Is there another way of accomplishing this?

I'd be happy to help get this building and exporting esm's if you're open to it. This would go a long way towards xstate usage/adoption inside my company.

Various problems with the visualizer

The current app is not very resilient to states which are too complex and throw an error during JSON serialize. The safe JSON does return a value, but it removes repeated values and ends up removing things the state needs like _event. So once the state has a JSON problem it won't be sent to the visualizer correctly.
The old visualizer has problems with not allowing scrolling inside of the state pane. This can be temporarily fixed by executing.

document.querySelector('[data-xviz=service-sidebar]>[data-reach-tabs] [data-reach-tab-panels]').style.overflow = "auto"

i.e. removing this css.

[data-xviz=service-sidebar]>[data-reach-tabs] [data-reach-tab-panels] {
    overflow: hidden;
}

With the new version I am having the following problem which I am still trying to trace.
After changing Actors, the graphical UI is not correctly initialized. The opacity is set to 0.01 or something and removing the opacity reveals a graph that's not quite right and all elements are at the top left position.
I initially posted this for reference:
statelyai/xstate#2629

Visualizer doesn't properly handle the `done.invoke.serviceName` event

The following Machine config fails to transition from loading to sucess state.
The transition should trigger after a service named fetch is invoked, i.e. on done.invoke.fetch event.

const fetchMachine = Machine({
    id: 'fetch',
    initial: 'idle',
    context: {
      retries: 0
    },
    states: {
      idle: {
        on: {
          FETCH: 'loading'
        }
      },
      loading: {
        invoke: {
          src: 'fetch',
          onDone: 'success',
          onError: 'failure'
        }
      },
      success: {
        type: 'final'
      },
      failure: {
        on: {
          RETRY: {
            target: 'loading',
            actions: 'doSomething'
          }
        }
      }
    }
  });

Visualizers tried:

EDIT: Apparently this part is not related to the issue:
The following warning is printed to console when the Visualizer loads with the machine:

No service found for invocation 'fetch' in machine 'fetch'.

There are two versions of the visualizer online

Issue:

Currently there seems to be two versions of the XState Visualizer online: an older version on Github Pages, and a newer version on xstate.js.org. If anyone, like me, has the Github Page bookmarked, they won't know to access the newer version.

Solution:

Maybe the Github Page could redirect to the xstate.js.org page, or add a banner on the Github Page to tell users to go to the xstate.js.org page.

Screenshots:

From Github Pages:
image

From xstate.js.org:
image

Thank you!

Error: Unable to evaluate guard in transition for event

Description

Loading the Visualizer with machine configurations that omit a guard's implementation currently causes the triggering of an error when an attempt is made to transition through it.

Minimal reproduction:

The source Gist

The Visualizer loaded with the Gist

Suggested solution:

Implement all omitted guard implementations as a function returning true, allowing users to transition through guards.

Optionally enable this behaviour only under a configuration prop such that other consumers of the XState-Viz React component will be able to turn this behaviour off when it's not appropriate for their use-case (e.g. Browser DevTools from issue #30)

fix visualizer event for guards

Hi, while playing with guards I realised, that visualizer used state.event which don't contain correct event, so I try to fix it.

It still don't allow use params set in editor, but imo it is better then before

#47

Delay animation does not restart

Following up from the earlier issue there still seems to be a minor bug in the visualizer.

Observed Behavior

Right now, using the same machine as before the delay animation runs for 3000ms then sits at 100% if ACTIVITY-Events have been fired during the delay.

Expected Behavior

The animation should restart as the state is re-entered on ACTIVITY

const timeoutMachine = Machine({
  initial: 'idle',
  strict: true,
  states: {
    idle: {
      on: { ACTIVITY: 'idle' },
      after: { 3000: 'timeout' },
    },
    timeout: {
      on: { ACTIVITY: 'idle' },
    },
  },
});

Ship version with new XState version

exit/entry are not displayed in current visualizer, I've debugged this a little and I can see in StateNode's constructor this:
Screenshot 2019-08-29 at 11 56 44
Looks like .entry/.exit are not handled at all here, which is odd because the specified version of xstate seems to be up to date:

"version": "4.6.7",

Sharing gist URLs appended to new Visualizer URL not working

Expected Behaviour:

When visiting the URL, the public gist at the appended URL should be loaded into the Visualizer and shown successfully.

Observed Behaviour:

Provided the following XState Visualizer URL:
https://xstate.js.org/viz/?gist=https://gist.github.com/amitnovick/7649b9c077e0946474712ac25d15b5b8

When visited, the console should print the following error:

Uncaught (in promise) TypeError: Cannot read property 'content' of undefined
    at machine (App.js:628)
    at utils.js:482
    at Array.reduce (<anonymous>)
    at Object.N [as updater] (utils.js:467)
    at e.resolveTransition (StateNode.js:960)
    at e.transition (StateNode.js:900)
    at interpreter.js:655
    at interpreter.js:92
    at t.nextState (interpreter.js:654)
    at interpreter.js:166

And the Loading... animation is shown instead of the usual Visualizer UI.

Crushing because of null assignment to context value

Description
I was playing around with the state machine from this article and then tried to visualize it but due to my mistake in code the page crushed with an error "TypeError: "e.assignment[n] is null"".
I didn't expect visualizer to crush.

Reproduction

const fetchMachine = Machine({
  id: "dogFetcher",
  initial: "idle",
  context: {
    dog: null,
    error: null,
  },
  states: {
    idle: {
      on: { fetch: "loading" },
    },
    loading: {
      invoke: {
        src: () => fetch("https://dog.ceo/api/breeds/image/random")
        .then(data => data.json()),
        onDone: {
          target: "success",
          actions: assign({ dog: (_, event) => event.data.message, 
          // mistake here
          error: null }),
          // this works fine
          // actions: assign({ dog: (_, event) => event.data.message, error: () => null }),
        },
        onError: {
          target: "failure",
          actions: assign({ error: (_, event) => event.data }),
        },
      },
      on: { cancel: "idle" },
    },
    success: {
      on: { fetch: "loading" },
    },
    failure: {
      on: { fetch: "loading" },
    },
  },
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.