javascript / expert
Snippet
Reactive State Machines for Complex UI Transitions
Finite State Machines (FSM) prevent 'impossible states' in complex UIs. Combining FSMs with Svelte runes ensures that state transitions are predictable and re-render the UI only when a valid transition occurs, strictly adhering to the defined logic map.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
type State = 'IDLE' | 'BUSY' | 'ERROR';let current = $state<State>('IDLE');const transitions = {IDLE: { FETCH: 'BUSY' },BUSY: { RESOLVE: 'IDLE', REJECT: 'ERROR' },ERROR: { RETRY: 'BUSY' }};function send(event: string) {const next = transitions[current]?.[event];if (next) current = next;}
svelte
Breakdown
1
let current = $state<State>('IDLE');
Tracks the current machine state reactively.
2
const transitions = { ... };
Static mapping of valid state transitions to prevent logic errors.
3
if (next) current = next;
Only updates the state if the event is valid for the current state.