mirror of
https://github.com/scratchfoundation/scratch-vm.git
synced 2024-12-27 00:12:57 -05:00
40 lines
1.2 KiB
JavaScript
40 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;
|
||
|
}
|