Created
August 10, 2020 14:38
-
-
Save dustinknopoff/915ef306578b63fc1470fcf426bd2b37 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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