koordinates / xstate-tree

Build UIs with Actors using xstate and React
MIT License
85 stars 6 forks source link

xstate-tree machine building 2.0 #14

Closed UberMouse closed 1 year ago

UberMouse commented 2 years ago

The build* factory function pattern that is currently in use, primarily to aid in typing, is.... not the best. I have long wanted to replace it with a better system but I have not been able to come up with one. The important functionality of the current system is

  1. Easily expand from a single file xstate-tree machine to a multi-file one, primarily splitting the view out
  2. Easily access the individual components of an xstate-tree machine, selectors/actions/view, for testing/storybook usage
  3. Provides typings without having to specify any generics or type complexity
UberMouse commented 1 year ago

After thinking about this on the weekend I think the solution is actually fairly simple. The only important splitting-up factor is being able to have the machine and view in separate files. Actions/selectors just don't get big enough that it matters where they end up.

But splitting out the view is hard because it needs types from the machine to be able to generate the props. The machine however is already totally independent. Which means it makes sense to instead only require the machine can be in a separate file, and the view/selectors/actions to be defined together, with the ability to omit the selector/action/slots if they aren't required.

So I propose something like

// machine file
// slots need to be defined with the machine as that is where they are used
export const someSlot = singleSlot("whatever");
const machine = createMachine();

// xstate-tree-machine file
import { machine, someSlot } from "./machine";

// name needs some bike shedding
export const SomeMachine = createXstateTreeMachine(machine, {
  slots: [someSlot],
  // selectors could be omitted, in which case they would default to the machines context, ie equivalent to
  // selectors: ({context}) => context,
  selectors: ({context, inState, canHandleEvent}) => ({ something: context.something + context.someOtherThing }),
  // actions is omitted so it resolves to an empty object, equivalent to
  // actions: () => ({}),
 view: ({ selectors }) => <p>{selectors.something}</p>
})

Then to enable access to the selector/action/view functions there can be a set of utility functions like retrieveView(machine), retrieveSelectors(machine) so you can pull them out for use in stories/tests etc. And they could also provide some utilities for generating things like the inState prop that requires specific types.

github-actions[bot] commented 1 year ago

:tada: This issue has been resolved in version 4.1.0-beta.1 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

github-actions[bot] commented 1 year ago

:tada: This issue has been resolved in version 4.1.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket: