import type { Readable } from 'svelte/store'; import { readable } from 'svelte/store'; import { interpret } from 'xstate'; // import { StreamStateSchema } from '../Models'; // TODO: this needs to be converted into a RXJS BehaviorSubject in order for it to scale seamlessly across // multiple frameworks. const useMachine = (config: any, options: any, interpretNeeded = false, id?: string): { state: Readable, send: Function, ref: any } => { // StreamStateSchema // interpret the machine config config.id = !!id ? id : config.id; config.name = !!id ? id : config.id; const service = !!interpretNeeded ? interpret(config, options) : config; // console.log("IN USE MACHINE: ", config.id, typeof service, interpretNeeded) // wrap machine in a svelte readable store with // initial state (defined in config) as its starting state const store = readable(service.initialState, set => { // const store = readable(service.state || service.initialState, set => { // every time we change state onTransition // hook is triggered // console.log("SERVICE: ", id, interpretNeeded, !!service.onTransition) service.onTransition((state: any) => { // console.info('service: ', service); set(state); }); service.onDone(() => { console.info('done state: ', id, service.id); }); service.onStop(() => { console.info('stop state: ', id, service.id); }); // start the machine service.start(); return () => { // service.stop(); }; }); // return a custom Svelte store return { state: store, send: service.send, ref: service }; }; export { useMachine };