Finite State Machine (FSM) for Svelte 5+ (Runes) with Strategy Pattern for Routing. Highly reactive, strongly typed, and includes an efficient state matching utility.
npm install svelte-state-machineThis is a strongly typed and highly reactive implementation of a Finite State Machine designed for Svelte 5+ using Runes ($state).
It leverages the Strategy Pattern via the StatesRouter interface to decouple transition logic from the core FSM class, improving maintainability and testability.
bash
npm i svelte-state-machine
`✨ Key Features
* Svelte Reactivity: Uses
$state principles to ensure state changes automatically update Svelte components.
* Strong Typing: States are defined as string literals, providing auto-completion and compile-time safety.
* Strategy Pattern (StatesRouter): Allows defining complex, reusable transition logic (e.g., linear, cyclic, error handling jumps) outside the FSM core.
* Pattern Matching: The match utility simplifies rendering logic by mapping state indices to return values (a TypeScript equivalent of a switch-case).🚀 Usage Example
`svelte
{FSM.match(
// Match 1: If FetchingData, display loading message.
[FSM.enum.FetchingData, () => "Fetching..."],
// Match 2: If ProcessingData, display processing message.
[FSM.enum.ProcessingData, () => "Processing..."],
// Match 3: If DisplayResults, render the reactive 'title' variable.
[FSM.enum.DisplayResults, () => title],
// Match 4: If FatalError, display the error message.
[FSM.enum.FatalError, () => "Something went wrong..."],
// Note: FSM.match automatically handles the current FSM.state,
// ensuring the UI always reflects the correct stage of the async operation.
)}
``