1.0.0 • Published yesterday
state-shifter
Licence
MIT
Version
1.0.0
Deps
0
Size
10 kB
Vulns
0
Weekly
0
state-shifter
Simple TypeScript state manager for workflows that behave like a finite state machine.
Installation
npm install state-shifter
Usage
import { StateShifter, type StateShifterConfig } from "state-shifter";
type AppState = "idle" | "loading" | "ready" | "error";
type AppMachine = StateShifterConfig<
Record<AppState, readonly AppState[]>,
(event: string) => void
>;
const transitionGraph = {
idle: ["loading"],
loading: ["ready", "error"],
ready: ["loading"],
error: ["loading"],
} as const;
const shifter = new StateShifter<AppMachine>("idle", transitionGraph, {
idle: {
onEnter: () => console.log("Idle"),
},
loading: {
onEnter: () => {
console.log("Loading...");
setTimeout(() => {
void shifter.shiftTo("ready");
}, 2000);
},
},
ready: {
onEnter: () => console.log("Ready"),
},
}, false);
await shifter.start();
await shifter.shiftTo("loading");
API
new StateShifter(initialState, transitionGraph, behaviors, implicitStart?)start()getCurrentState()dispatchEvent(...args)canShift(from, to)shiftTo(to, params?)
License
MIT