Skip to content
ts-stadium

Toggle

1 min read

Text coming soon...

Demo

Text coming soon...

State Machine

Text coming soon...

// toggle/src/state-machine.ts
import * as SM from '@ts-stadium/state-machine'
export const stateMachine = SM.createStateMachine({
states: {
On: {
events: ['SwitchOff'],
},
Off: {
events: ['SwitchOn'],
init: true,
},
},
events: {
SwitchOff: {
toStates: ['Off'],
},
SwitchOn: {
toStates: ['On'],
},
},
})

Control

Text coming soon...

// toggle/src/control.ts
import * as T from 'fp-ts/Task';
import * as SM from '@no-day/ts-stadium';
import { stateMachine } from './state-machine';
export const control = SM.createControl(stateMachine)(T.task)({
SwitchOn: () => async () => () => ({
state: SM.tag('On'),
}),
SwitchOff: () => async () => () => ({
state: SM.tag('Off'),
}),
});

Render

Text coming soon...

// toggle/src/render.tsx
import * as SM from '@no-day/ts-stadium';
import React, { ReactElement } from 'react';
import IconOff from './assets/switch-off.svg';
import IconOn from './assets/switch-on.svg';
import { stateMachine } from './state-machine';
export const Render = SM.createCbRender(stateMachine)<ReactElement>({
On: () => (onEvent) => (
<span
style={{ width: '100px', cursor: 'pointer' }}
onClick={() => onEvent(SM.tag('SwitchOff'))}
title="Click to switch OFF"
>
<IconOn />
</span>
),
Off: () => (onEvent) => (
<span
style={{ width: '100px', cursor: 'pointer' }}
onClick={() => onEvent(SM.tag('SwitchOn'))}
title="Click to switch ON"
>
<IconOff />
</span>
),
});

Wrap up

Text coming soon...

// toggle/src/toggle.tsx
import * as React from 'react';
import * as SM from '@no-day/ts-stadium';
import { stateMachine } from './state-machine';
import { Render } from './render';
export const Toggle = () => {
const [state, setState] = React.useState(
SM.init(stateMachine, SM.tag('Off'))
);
return <Render state={state} onEvent={() => {}} />;
};