2017-04-17 15:10:04 -04:00
|
|
|
const html = require('htmlparser2');
|
2017-11-29 10:34:00 -05:00
|
|
|
const decodeHtml = require('decode-html');
|
2016-10-03 17:43:24 -04:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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.
|
2016-10-03 17:43:24 -04:00
|
|
|
*/
|
2017-04-17 17:15:19 -04:00
|
|
|
const mutatorTagToObject = function (dom) {
|
2017-04-17 15:10:04 -04:00
|
|
|
const obj = Object.create(null);
|
2016-10-03 17:43:24 -04:00
|
|
|
obj.tagName = dom.name;
|
|
|
|
obj.children = [];
|
2017-04-17 15:10:04 -04:00
|
|
|
for (const prop in dom.attribs) {
|
2016-10-23 17:55:31 -04:00
|
|
|
if (prop === 'xmlns') continue;
|
2017-11-29 10:34:00 -05:00
|
|
|
obj[prop] = decodeHtml(dom.attribs[prop]);
|
2016-10-03 17:43:24 -04:00
|
|
|
}
|
2017-04-17 15:10:04 -04:00
|
|
|
for (let i = 0; i < dom.children.length; i++) {
|
2016-10-03 17:43:24 -04:00
|
|
|
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.
|
2017-02-01 15:59:50 -05:00
|
|
|
* @param {(object|string)} mutation Mutation XML string or DOM.
|
|
|
|
* @return {object} Object representing the mutation.
|
2016-10-23 17:55:31 -04:00
|
|
|
*/
|
2017-04-17 15:10:04 -04:00
|
|
|
const mutationAdpater = function (mutation) {
|
|
|
|
let mutationParsed;
|
2016-10-23 17:55:31 -04:00
|
|
|
// 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);
|
|
|
|
};
|
2016-10-24 11:49:34 -04:00
|
|
|
|
|
|
|
module.exports = mutationAdpater;
|