scratch-vm/src/engine/mutation-adapter.js

42 lines
1.2 KiB
JavaScript
Raw Normal View History

2017-04-17 15:10:04 -04:00
const html = require('htmlparser2');
/**
* Convert a part of a mutation DOM to a mutation VM object, recursively.
2017-02-01 15:59:50 -05:00
* @param {object} dom DOM object for mutation tag.
* @return {object} Object representing useful parts of this mutation.
*/
const mutatorTagToObject = function (dom) {
2017-04-17 15:10:04 -04:00
const obj = Object.create(null);
obj.tagName = dom.name;
obj.children = [];
2017-04-17 15:10:04 -04:00
for (const prop in dom.attribs) {
if (prop === 'xmlns') continue;
obj[prop] = dom.attribs[prop];
}
2017-04-17 15:10:04 -04:00
for (let i = 0; i < dom.children.length; i++) {
obj.children.push(
mutatorTagToObject(dom.children[i])
);
}
return obj;
};
/**
* Adapter between mutator XML or DOM and block representation which can be
* used by the Scratch runtime.
2017-02-01 15:59:50 -05:00
* @param {(object|string)} mutation Mutation XML string or DOM.
* @return {object} Object representing the mutation.
*/
2017-04-17 15:10:04 -04:00
const mutationAdpater = function (mutation) {
let 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);
};
module.exports = mutationAdpater;