2016-10-03 17:43:24 -04:00
|
|
|
var html = require('htmlparser2');
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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.
|
|
|
|
*/
|
2016-10-23 17:55:31 -04:00
|
|
|
var mutatorTagToObject = function (dom) {
|
2016-10-03 17:43:24 -04:00
|
|
|
var obj = Object.create(null);
|
|
|
|
obj.tagName = dom.name;
|
|
|
|
obj.children = [];
|
|
|
|
for (var prop in dom.attribs) {
|
2016-10-23 17:55:31 -04:00
|
|
|
if (prop === 'xmlns') continue;
|
2016-10-03 17:43:24 -04:00
|
|
|
obj[prop] = dom.attribs[prop];
|
|
|
|
}
|
|
|
|
for (var i = 0; i < dom.children.length; i++) {
|
|
|
|
obj.children.push(
|
|
|
|
mutatorTagToObject(dom.children[i])
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return obj;
|
2016-10-23 17:55:31 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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);
|
|
|
|
};
|