Skip to content

Instantly share code, notes, and snippets.

@dustinknopoff
Created August 10, 2020 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustinknopoff/915ef306578b63fc1470fcf426bd2b37 to your computer and use it in GitHub Desktop.
Save dustinknopoff/915ef306578b63fc1470fcf426bd2b37 to your computer and use it in GitHub Desktop.
type TypeState = Distribute<keyof FlowMachineSchema["states"], FlowMachineContext> // assuming same context
export type Send = Interpreter<FlowMachineContext, FlowMachineSchema, FlowEvents, TypeState>['send']
export type Context = [
State<FlowMachineContext, FlowEvents, FlowMachineSchema, TypeState>,
Send,
Interpreter<FlowMachineContext, FlowMachineSchema, FlowEvents, TypeState>
];
type Distribute<U, C> = U extends any ? { value: U; context: C } : never // util
export const MachineContext = React.createContext<Context>({} as any);
export const FlowMachine: React.FC<{ children: React.ReactNode }> = ({ children }) => {
let flow = Flow.fromJSON(window.flow)
let index = indexFromUrl()
if (index > flow.screens.length - 1) {
index = 0
}
const machine = useMachine(createFlowMachine({
flow,
index,
undoStack: [],
redoStack: [],
loading: [],
drafts: [],
currentObject: null,
}), { devTools: true });
const [, , service] = machine;
React.useEffect(() => {
const subscription = service.subscribe((state: unknown) => {
// @ts-ignore simple state logging
console.log(state.event, state.value);
});
return subscription.unsubscribe;
}, [service]); // note: service should never change
return (
<MachineContext.Provider value={machine}>
{children}
</MachineContext.Provider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment