-
Notifications
You must be signed in to change notification settings - Fork 1
/
mvc.js
533 lines (464 loc) · 20.2 KB
/
mvc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
var statemachine = (function () {
///////////////////////////////////////
/////
///// MODEL
/////
///////////////////////////////////////
/*
Keeps the internal state of the machine : components
connections etc
and changes them by calling State Machine functions from SM
and updating the view accordingly
*/
function Model() {
var sm = SM(),
exports = {},
sample = true,
handler = UpdateHandler(),
components = {},
connections = [],
interval;
/*
Computes results for a single step
and updates the view via the handler 'step'
*/
function step() {
var input = 1;
var time = sm.timeIndex();
if(time === 0)
sm.initialize(components, connections);
if(sample & time !== 0)
input = 0;
try {
var output = sm.step(input);
handler.trigger('step', [time, input, output]);
}
catch(e) {
reset();
}
}
/*
Computes results for the first ten steps
and updates the view via the handler 'firstTen'
*/
function firstTen() {
sm.initialize(components, connections);
var inputs = [1];
if(sample)
inputs = inputs.concat([0,0,0,0,0,0,0,0,0]);
else
inputs = inputs.concat([1,1,1,1,1,1,1,1,1]);
try {
handler.trigger('firstTen', [inputs, sm.transduce(inputs)]);
}
catch(e) {
reset();
}
}
/*
Resets the system and initialises the current
machine in SM and updates the view via the handler'reset'
*/
function reset() {
pause();
sm.initialize(components, connections);
handler.trigger('reset');
}
/*
Starts or pauses the machine
*/
function run(btn) {
if(btn.text() === "Start")
start();
else
pause();
}
/*
Starts runing the machine by creating interval
*/
function start() {
interval = setInterval(step, 1000);
handler.trigger('start');
}
/*
Stops charting results by clearing the
interval.
*/
function pause() {
clearInterval(interval);
handler.trigger('pause');
}
/*
Switches between the two input types that we have.
*/
function switchInput(btn) {
if(btn.text() === "Unit Sample") {
sample = false;
btn.text("Unit Step");
}
else {
sample = true;
btn.text("Unit Sample");
}
}
/*
Updates current connections in the system and stores
them in connections.
*/
function updateConnections(connection) {
if(connection.sourceId === connection.targetId)
jsPlumb.detach(connection);
connections = [];
var allConnections = jsPlumb.getAllConnections()['blue rectangle'];
for(c in allConnections)
connections.push([allConnections[c].sourceId, allConnections[c].targetId]);
}
/*
Updates the components in the system by
name = id of component
component = data of component (type, inputs, value)
remove = false : adding , true : removing
*/
function updateComponents(name, component, remove) {
if (!remove) components[name] = component;
else delete components[name];
}
exports.switchInput = switchInput;
exports.step = step;
exports.run = run;
exports.reset = reset;
exports.on = handler.on;
exports.getValue = sm.getCurrentValue;
exports.updateConnections = updateConnections;
exports.updateComponents = updateComponents;
exports.firstTen = firstTen;
return exports;
}
///////////////////////////////////////
/////
///// CONTROLLER
/////
///////////////////////////////////////
/*
Connects components in the view to functions and responses
resulting in change in the model.
*/
function Controller(model) {
function switchInput() {
model.switchInput($(this));
}
function run() {
model.run($(this));
}
function step() {
model.step();
}
function reset() {
model.reset();
}
function firstTen() {
model.firstTen();
}
function updateConnections(connection) {
model.updateConnections(connection);
}
function addComponent(name, component) {
model.updateComponents(name, component, false);
}
function removeComponent(name) {
model.updateComponents(name, [], true);
}
return {switchInput: switchInput, run: run, step: step, firstTen: firstTen, reset: reset,
updateConnections: updateConnections, addComponent: addComponent, removeComponent: removeComponent};
}
///////////////////////////////////////
/////
///// VIEW
/////
///////////////////////////////////////
/*
Creates all components in the state machine
and connects them to the controller for updating
*/
function View(div, model, controller) {
//Define all visual containers
var displayArea = $("<div class='displayArea view wide'></div>");
var componentField = $("<div class='componentField view narrow'></div>");
var trash = $("<div class='trash short narrow'><i class='icon-trash'></i><strong>TRASH</strong></div>");
var buttonField = $("<div class='buttonField short wide'></div>");
var chart = $('<div class="wide view"></div>');
var table = $('<div class="narrow view"></div>');
//Preload machine from DOM if any exist, then clears the DOM
var preComp = $('.smComp');
var preConn = $('.smConn');
div.html('');
//Adds all visual containers
div.append(componentField, displayArea, trash, buttonField, table, chart);
//Buttons for running the machine
var sampleButton = $('<button class="btn btn-info">Unit Sample</button>');
sampleButton.on('click', controller.switchInput);
var runButton = $('<button class="btn btn-success">Start</button>');
runButton.on('click', controller.run);
var stepButton = $('<button class="btn btn-primary">Step</button>');
stepButton.on('click', controller.step);
var tenButton = $('<button class="btn btn-danger">Show 1st 10</button>');
tenButton.on('click', controller.firstTen);
var resetButton = $('<button class="btn btn-warning">Reset</button>');
resetButton.on('click', controller.reset);
buttonField.append(sampleButton, runButton, resetButton, stepButton, tenButton);
//Buttons for adding components
var delayBtn = $("<button class='buttonz btn' data-type='delay' data-toggle='tooltip' title='Delay'>\
<img src='http://web.mit.edu/lu16j/www/state/delay.png'></button>");
var gainBtn = $("<button class='buttonz btn' data-type='gain' data-toggle='tooltip' title='Gain'>\
<img src='http://web.mit.edu/lu16j/www/state/gain.png'></button>");
var adderBtn = $("<button class='buttonz btn' data-type='adder' data-toggle='tooltip' title='Adder'>\
<img src='http://web.mit.edu/lu16j/www/state/adder.png'></button>");
componentField.append(delayBtn, gainBtn, adderBtn);
//Set up the table and chart
table.append('<table class="table table-striped table-condensed"><thead>\
<tr><th>T</th><th>X</th><th>Y</th></tr>\
</thead><tbody></tbody></table>');
chart.highcharts({
title: {text: '', floating: true},
xAxis: {title: {text: 'Time Step'}, categories: []},
legend: {floating: true, verticalAlign: 'top'},
series: [{name: 'Input', type: 'line', id: 'input', data: [], animation: false},
{name: 'Output', type: 'line', id: 'output', data: [], animation: false}]
});
//Hide the Highcharts watermark
$('tspan').eq($('tspan').length-1).hide();
/*
Create a new component at the position of the clicked component
button.
dataType = gain | adder | delay
dataId = name of the component, dynamically created to be unique
top, left = position
value = the value of the gain component
reversed = what direction the component faces
*/
var usedIds = ['delay','gain','adder'];
function createComponent(dataType, dataId, top, left, value, reversed) {
//Defaults
if(isNaN(value))
value = 0;
if(dataId === undefined)
dataId = dataType;
//Generates a unique ID
var nameId = dataId;
if(usedIds.indexOf(dataId) > -1) {
var idmaker = 0;
while(usedIds.indexOf(dataId + idmaker) > -1)
idmaker = idmaker + 1;
nameId = dataId + idmaker;
}
usedIds.push(nameId);
//Creates the component
var newComponent = $("<div class='item' data-type="+dataType+" id='"+nameId+"'>"+
"<img src='http://web.mit.edu/lu16j/www/state/"+dataType+".png'>"+
"</div>").css({"top": top+displayArea.position().top,
"left": left*displayArea.width()+displayArea.position().left});
//Adds input box for gain components
if(dataType === 'gain') {
var valueBox = $("<input class='gainInput' type='text' id='"+nameId+"'></input>");
valueBox.val(value);
newComponent.append(valueBox);
valueBox.on('keyup', function (evt) {
var updatedValue = valueBox.val();
if(isNaN(updatedValue) & updatedValue !== '-' & updatedValue !== '.' & updatedValue !== '-.') {
valueBox.val('0');
updatedValue = 0;
}
controller.addComponent(nameId, [dataType, parseFloat(updatedValue)]);
});
}
//Creates span for updating the component's current value
newComponent.append("<span class='componentValue' type='text' id="+nameId+">0</span>");
//Adds the component, makes it draggable
displayArea.append(newComponent);
jsPlumb.draggable($("#"+nameId), {containment: $('.container')});
if(dataType !== 'input' & dataType !== 'output')
controller.addComponent(nameId, [dataType, value]);
//Adds output and input endpoints as appropriate
var outputEndpoint, inputEndpoint;
if(dataType !== 'output')
outputEndpoint = jsPlumb.addEndpoint($('#'+nameId), outputEndpointAttrs, genericEndpoint);
if(dataType !== 'input' & dataType !== 'adder')
inputEndpoint = jsPlumb.addEndpoint($('#'+nameId), inputEndpointAttrs, genericEndpoint);
if(dataType === 'adder')
inputEndpoint = jsPlumb.addEndpoint($('#'+nameId), adderInputAttrs, genericEndpoint);
/*
Changes the orientation of the component
for better visualization of flow in the state machine
*/
function switchEndpoints() {
if(inputEndpoint.anchor.x === 0) {
inputEndpoint.setAnchor('Right');
outputEndpoint.setAnchor('Left');
newComponent.attr('data-rev', 'yes');
if(dataType === 'gain')
newComponent.find('img').attr('src', 'http://web.mit.edu/lu16j/www/state/gain-rev.png');
}
else {
inputEndpoint.setAnchor('Left');
outputEndpoint.setAnchor('Right');
newComponent.attr('data-rev', 'no');
if(dataType === 'gain')
newComponent.find('img').attr('src', 'http://web.mit.edu/lu16j/www/state/gain.png');
}
return false;
}
//If component is created backwards
if(reversed === 'yes') {
switchEndpoints();
}
//Binds reverse function to right click
newComponent[0].oncontextmenu = function (e) {
return switchEndpoints();
};
/*
Keeps the object on the Display area
Reverts back to it when dragged to other
areas
*/
newComponent.on('dragstop', function (evt) {
if(evt.pageY > buttonField.position().top)
jsPlumb.animate(nameId, {top: buttonField.position().top-newComponent.height()});
if(evt.pageY < displayArea.position().top)
jsPlumb.animate(nameId, {top: displayArea.position().top});
if(evt.pageX < displayArea.position().left)
jsPlumb.animate(nameId, {left: displayArea.position().left});
if(evt.pageX > displayArea.position().left+displayArea.width())
jsPlumb.animate(nameId, {left: displayArea.position().left+displayArea.width()-80});
});
}
//Create input and output components by default
createComponent('input', 'input', 80, 0);
createComponent('output', 'output', 80, (displayArea.width()-80)/displayArea.width());
//PRELOAD MACHINE (IF ANY)
for(var i=0; i<preComp.length; i++)
createComponent(preComp.eq(i).attr('data-type'),
preComp.eq(i).attr('data-id'),
parseFloat(preComp.eq(i).attr('data-top')),
parseFloat(preComp.eq(i).attr('data-left')),
preComp.eq(i).attr('data-value'),
preComp.eq(i).attr('data-rev'));
for(var i=0; i<preConn.length; i++) {
var fromPoint = jsPlumb.getEndpoints(preConn.eq(i).attr('data-from'))[0];
var toPoint;
if(preConn.eq(i).attr('data-to') === 'output')
toPoint = jsPlumb.getEndpoints(preConn.eq(i).attr('data-to'))[0];
else
toPoint = jsPlumb.getEndpoints(preConn.eq(i).attr('data-to'))[1];
controller.updateConnections(jsPlumb.connect({source: fromPoint, target: toPoint}));
}
//////////OTHER FUNCTIONS
//Create component on click
$(".buttonz").on("click",function(){
createComponent($(this).attr('data-type'), undefined, $(this).position().top-displayArea.position().top, 0);
});
//OR (Chrome only) create them by dragging in
$('.buttonz').on('mousedown', function() {
$(this).on('mouseleave',function(e){
createComponent($(this).attr('data-type'), undefined,
e.pageY-displayArea.position().top-15,
(e.pageX-displayArea.position().left-40)/displayArea.width(),
0);
$(this).off('mouseleave');
});
$(this).on('mouseup', function() {
$(this).off('mouseleave');
});
});
//Delete component when moved to trash, except input or output component
$('.trash').droppable({
over: function(event, ui) {
if((['input','output']).indexOf(ui.draggable[0].id) < 0) {
delete usedIds[usedIds.indexOf(ui.draggable[0].id)];
jsPlumb.removeAllEndpoints(ui.draggable);
controller.removeComponent(ui.draggable[0].id);
$(ui.draggable).remove();
}
}
});
//Reposition components when displayArea is resized (width only)
var prevWinWidth = displayArea.width();
var prevWinLeft = displayArea.position().left;
$(window).on('resize', function () {
var ratio = displayArea.width() / prevWinWidth;
$('.item').each(function () {
var previousLeft = parseFloat($(this).css('left'))-prevWinLeft;
$(this).css({'left':(previousLeft*ratio+displayArea.position().left)});
});
jsPlumb.repaintEverything();
prevWinWidth = displayArea.width();
prevWinLeft = displayArea.position().left;
});
//Dynamically update components' current value spans
function updateSpans() {
$('.componentValue').each(function () {
this.innerHTML = Math.round(model.getValue(this.id)*100000)/100000;
});
}
// STEP, RESET and FIRST TEN returning outputs from the SM
// and display them in the display spans and on the chart
function step(data) {
var time = data[0];
var input = data[1];
var output = data[2];
var shift = chart.highcharts().get('output').data.length >= 10;
chart.highcharts().get('input').addPoint(input, true, shift);
chart.highcharts().get('output').addPoint(output, true, shift);
table.find('tbody').append('<tr><td>'+time+'</td><td>'+input+
'</td><td>'+output+'</td></tr>');
table.scrollTop($(table)[0].scrollHeight);
updateSpans();
}
function reset() {
chart.highcharts().get('input').setData([]);
chart.highcharts().get('output').setData([]);
table.find('tbody').html('');
updateSpans();
}
function firstTen(data) {
chart.highcharts().get('input').setData(data[0]);
chart.highcharts().get('output').setData(data[1]);
table.find('tbody').html('');
for(var i=0; i<10; i++)
table.find('tbody').append('<tr><td>'+i+'</td><td>'+data[0][i]+
'</td><td>'+data[1][i]+'</td></tr>');
table.scrollTop($(table)[0].scrollHeight);
updateSpans();
}
model.on('step', step);
model.on('reset', reset);
model.on('firstTen', firstTen);
model.on('start', function () { runButton.text('Pause'); });
model.on('pause', function () { runButton.text('Start'); });
}
/*
Initialises jsPlumb and creates a model, view and
controller system for the State Machine
*/
function setup(div) {
jsPlumb.ready(function() {
jsPlumb.importDefaults({
ConnectionOverlays: [[ "Arrow", { location: -10 } ]]
});
jsPlumb.bind("connection", function(info) {
model.updateConnections(info.connection);
});
jsPlumb.bind("connectionDetached", function(info) {
model.updateConnections(info.connection);
});
var model = Model();
var controller = Controller(model);
var view = View(div, model, controller);
});
}
return {setup: setup};
})();
$(document).ready(function () {
$('.statemachine').each(function () {
statemachine.setup($(this));
});
});