scratch-vm/src/engine/mutation-adapter.js
Tim Mickel 0a66c62f6a Mutations in block representation; an unfeatured procedure call (#212)
* Add scratch3_procedures and no-op for defnoreturn

* Add mutation adapter to parse mutations in CREATE/CHANGE events

* Add mutation-to-XML

* Update spec map for Blockly procedure names

* Placeholder for procedure special cases

* Basic stepping to procedures

* Remove extra case

* Validation for changeBlock
2016-10-03 17:43:24 -04:00

39 lines
1.2 KiB
JavaScript

var html = require('htmlparser2');
/**
* Adapter between mutator XML or DOM and block representation which can be
* used by the Scratch runtime.
* @param {(Object|string)} mutation Mutation XML string or DOM.
* @return {Object} Object representing the mutation.
*/
module.exports = function (mutation) {
var mutationParsed;
// Check if the mutation is already parsed; if not, parse it.
if (typeof mutation === 'object') {
mutationParsed = mutation;
} else {
mutationParsed = html.parseDOM(mutation)[0];
}
return mutatorTagToObject(mutationParsed);
};
/**
* Convert a part of a mutation DOM to a mutation VM object, recursively.
* @param {Object} dom DOM object for mutation tag.
* @return {Object} Object representing useful parts of this mutation.
*/
function mutatorTagToObject (dom) {
var obj = Object.create(null);
obj.tagName = dom.name;
obj.children = [];
for (var prop in dom.attribs) {
if (prop == 'xmlns') continue;
obj[prop] = dom.attribs[prop];
}
for (var i = 0; i < dom.children.length; i++) {
obj.children.push(
mutatorTagToObject(dom.children[i])
);
}
return obj;
}