matthewp / robot

🤖 A functional, immutable Finite State Machine library
https://thisrobot.life
BSD 2-Clause "Simplified" License
1.93k stars 88 forks source link

Possible future direction of the project #220

Open matthewp opened 2 weeks ago

matthewp commented 2 weeks ago

About a year ago I experienced with a library built on top of Robot that combined state machines with DOM manipulation. Ultimately I decided to stop pursuing it. The one thing that really resonated, however, was that it defined your state machine in a schema style syntax (similar to Zod) rather than the functional way we do in Robot now.

I want to discuss this as a possible new syntax for Robot. Here's an example of what a machine would look like:

import { r } from 'robot3';

let machine = r
  .model({
    mode: r.string(),
    dark: r.boolean(),
    emoji: r.string(),
  })
  .states(['idle'])
  .events('idle', ['toggle'])
  .transition(
    'idle',
    'toggle',
    'idle',
    r.assign('mode', ({ model }) => (model.mode === 'dark' ? 'light' : 'dark')),
    r.assign('dark', ({ model }) => model.mode === 'dark'),
    r.assign('emoji', ({ model }) => model.dark ? '🌛' : '☀️')
  )

This renames context to model, and you define the properties on your model. Then in assign you get typesafe manipulation of model values.

To be clear, I'm not sold on this idea as a replacement for Robot's current functional style. But I'm curious to hear what people think. There is no decision being made now, and it's not likely to do so for a long time, if ever.

nolde commented 4 days ago

Hmm. It looks nice for small state machines like this, but larger ones might become harder to understand.