JSFiddle - React, Tailwind, and code Playground

by intrinsica

HTML

<div id="demo">
    <div id="diagram" class="start"></div>
    <textarea id="output"></textarea>
</div>

<img src="https://dl.dropbox.com/u/31174/www/Stately/Stately.js-start.png" class="preload">
<img src="https://dl.dropbox.com/u/31174/www/Stately/Stately.js-S1-0.png" class="preload">
<img src="https://dl.dropbox.com/u/31174/www/Stately/Stately.js-S1-1.png" class="preload">
<img src="https://dl.dropbox.com/u/31174/www/Stately/Stately.js-S2-0.png" class="preload">
<img src="https://dl.dropbox.com/u/31174/www/Stately/Stately.js-S2-1.png" class="preload">

CSS

#demo {
    text-align: center;
}

#start {
    margin-top: 20px;
    margin-left: 50px;
}

#diagram {
    width: 339px;
    height: 205px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
}

#output {
    margin-left: 50px;
    margin-top: 20px;
    height: 100px;
    width: 200px;
}

.start {
    background: url(https://dl.dropbox.com/u/31174/www/Stately/Stately.js-start.png);
}

.S1-0 {
    background: url(https://dl.dropbox.com/u/31174/www/Stately/Stately.js-S1-0.png);
}

.S1-1 {
    background: url(https://dl.dropbox.com/u/31174/www/Stately/Stately.js-S1-1.png);
}

.S2-0 {
    background: url(https://dl.dropbox.com/u/31174/www/Stately/Stately.js-S2-0.png);
}

.S2-1 {
    background: url(https://dl.dropbox.com/u/31174/www/Stately/Stately.js-S2-1.png);
}

.preload {
    position: absolute;
    left: -1000px;
    height: 1px;
}

JavaScript

function fsm(a){function h(c){if(!(c in a))throw'bad state:"'+c+'"';e=a[c];g=c}var e,g,k=function(){var c={},b;for(b in a)if(a.hasOwnProperty(b)){for(var f in a[b])a[b].hasOwnProperty(f)&&(c[f]=!0);e||(e=a[b],g=b)}return c}();(function(c){function a(b){return function(){if(b in e){if("string"===typeof e[b])return h(e[b]),c;if("function"===typeof e[b]){var a=e[b].apply(e,arguments);"string"===typeof a&&h(a);return c}throw'bad transition:"'+b+'" state:"'+g+'"';}return c}}for(var f in k)k.hasOwnProperty(f)&&
(c[f]=a(f))})(this);this.getState=function(){return g}}

var diagram = document.getElementById('diagram'),
    output = document.getElementById('output'),
    count = 0,
    log = function() {
        var message = Array.prototype.slice.apply(arguments);
        output.value = count++ + ': ' + message.join(', ') + '\n' + output.value;
    };

var f = new fsm({
    'S1': {
        '0': 'S2',
        '1': 'S1'
    },
    'S2': {
        '0': 'S1',
        '1': 'S2'
    }
});

setTimeout(function loopsyloop() {
    var oldState= f.getState(), // string
    	event= Math.floor(Math.random() * 2);
    f[event]();
    var newState= f.getState(), // string
		className = newState + '-' + event;
    log(event, oldState, newState);
    diagram.className = className;  
    setTimeout(loopsyloop, 100);
}, 3000);