scratch-vm/src/index.js

109 lines
3.1 KiB
JavaScript
Raw Normal View History

2016-04-18 17:20:30 -04:00
var EventEmitter = require('events');
var util = require('util');
var Blocks = require('./engine/Blocks');
2016-04-18 17:20:30 -04:00
var Runtime = require('./engine/runtime');
var adapter = require('./engine/adapter');
2016-04-18 17:20:30 -04:00
/**
* Handles connections between blocks, stage, and extensions.
*
* @author Andrew Sliwinski <ascii@media.mit.edu>
*/
function VirtualMachine () {
var instance = this;
// Bind event emitter and runtime to VM instance
2016-04-18 18:03:18 -04:00
// @todo Post message (Web Worker) polyfill
2016-04-18 17:20:30 -04:00
EventEmitter.call(instance);
instance.blocks = new Blocks();
instance.runtime = new Runtime(instance.blocks);
2016-04-18 17:20:30 -04:00
/**
2016-04-18 18:03:18 -04:00
* Event listener for blocks. Handles validation and serves as a generic
2016-04-18 17:20:30 -04:00
* adapter between the blocks and the runtime interface.
*
* @param {Object} Blockly "block" event
*/
instance.blockListener = function (e) {
// Validate event
if (typeof e !== 'object') return;
if (typeof e.blockId !== 'string') return;
// Blocks
switch (e.type) {
case 'create':
var newBlocks = adapter(e);
// A create event can create many blocks. Add them all.
for (var i = 0; i < newBlocks.length; i++) {
instance.blocks.createBlock(newBlocks[i], false);
}
break;
case 'change':
instance.blocks.changeBlock({
2016-04-18 17:20:30 -04:00
id: e.blockId,
element: e.element,
name: e.name,
value: e.newValue
2016-04-18 17:20:30 -04:00
});
break;
case 'move':
instance.blocks.moveBlock({
2016-04-18 17:20:30 -04:00
id: e.blockId,
oldParent: e.oldParentId,
2016-06-06 14:53:14 -04:00
oldInput: e.oldInputName,
2016-04-18 17:20:30 -04:00
newParent: e.newParentId,
2016-06-06 14:53:14 -04:00
newInput: e.newInputName
2016-04-18 17:20:30 -04:00
});
break;
case 'delete':
instance.blocks.deleteBlock({
2016-04-18 17:20:30 -04:00
id: e.blockId
});
break;
case 'stackclick':
instance.runtime.toggleStack(e.blockId);
break;
2016-04-18 17:20:30 -04:00
}
2016-04-18 18:03:18 -04:00
};
instance.flyoutBlockListener = function (e) {
switch (e.type) {
case 'create':
var newBlocks = adapter(e);
// A create event can create many blocks. Add them all.
for (var i = 0; i < newBlocks.length; i++) {
instance.runtime.createBlock(newBlocks[i], true);
}
break;
case 'change':
instance.runtime.changeBlock({
id: e.blockId,
element: e.element,
name: e.name,
value: e.newValue
});
break;
case 'delete':
instance.runtime.deleteBlock({
id: e.blockId
});
break;
case 'stackclick':
instance.runtime.toggleStack(e.blockId);
break;
}
};
2016-04-18 17:20:30 -04:00
}
/**
* Inherit from EventEmitter
*/
util.inherits(VirtualMachine, EventEmitter);
/**
* Export and bind to `window`
*/
module.exports = VirtualMachine;
if (typeof window !== 'undefined') window.VirtualMachine = module.exports;