Skip to content

Examples

Ken Kunz edited this page Nov 20, 2021 · 3 revisions

Simple on/off switch

View in Svelte REPL

import fsm from 'svelte-fsm';

const simpleSwitch = fsm('off', {
  off: { toggle: 'on'  },
  on:  { toggle: 'off' }
});

simpleSwitch.toggle(); // => 'on'
simpleSwitch.toggle(); // => 'off'

Also see a switch that includes a counter (demonstrates the _enter() action with a side-effect)

Traffic light using timers

View in Svelte REPL

import fsm from 'svelte-fsm';

const trafficLight = fsm('green', {
  green: {
    _enter() { this.change.debounce(20000); },
    change: 'yellow'
  },

  yellow: {
    _enter() { this.change.debounce(5000); },
    change: 'red'
  },

  red: {
    _enter() { this.change.debounce(20000); },
    change: 'green'
  }
});

trafficLight.subscribe(console.log);

// [ immiadetely  ] => 'green'
// [ after 20 sec ] => 'yellow'
// [ after  5 sec ] => 'red'
// [ after 20 sec ] => 'green'
// ...

Svelte form component

View in Svelte REPL

<script>
  import fsm from 'svelte-fsm';

  let value = '';
  let error;
	
  const form = fsm('entering', {
    entering: {
      submit: 'submitting'
    },

    submitting: {
      _enter() {
        const body = new URLSearchParams({value});
        fetch('https://some.endpoint', { method: 'POST', body })
          .then(this.success)
          .catch(this.error);
      },

      success: 'completed',

      error(err) {
        error = err;
        return 'invalid';
      }
    },

    invalid: {
      input: 'entering'
    },

    completed: {}
  });
</script>

<h1>Svelte FSM</h1>
<h2>Very Biased Survey</h2>

<form on:submit|preventDefault={form.submit}>
  <label>
    What's your favorite web framework?
    <input bind:value on:input={form.input} />
  </label>
  <button type="submit" disabled={$form !== 'entering'}>Submit</button>
</form>

{#if $form === 'completed'}
  <div>Your response has been recorded!</div>
{/if}

{#if $form === 'invalid'}
  <div class="error">
    {error.message}
    Modify value and try again.
  </div>
{/if}

<style>
  .error { color: red; }
</style>
Clone this wiki locally