1const HTML = require('../../packages/parse5/lib/common/html'); 2 3function getSerializedTreeIndent(indent) { 4 let str = '|'; 5 6 for (let i = 0; i < indent + 1; i++) { 7 str += ' '; 8 } 9 10 return str; 11} 12 13function getElementSerializedNamespaceURI(element, treeAdapter) { 14 switch (treeAdapter.getNamespaceURI(element)) { 15 case HTML.NAMESPACES.SVG: 16 return 'svg '; 17 case HTML.NAMESPACES.MATHML: 18 return 'math '; 19 default: 20 return ''; 21 } 22} 23 24function serializeNodeList(nodes, indent, treeAdapter) { 25 let str = ''; 26 27 nodes.forEach(node => { 28 str += getSerializedTreeIndent(indent); 29 30 if (treeAdapter.isCommentNode(node)) { 31 str += `<!-- ${treeAdapter.getCommentNodeContent(node)} -->\n`; 32 } else if (treeAdapter.isTextNode(node)) { 33 str += `"${treeAdapter.getTextNodeContent(node)}"\n`; 34 } else if (treeAdapter.isDocumentTypeNode(node)) { 35 const publicId = treeAdapter.getDocumentTypeNodePublicId(node); 36 const systemId = treeAdapter.getDocumentTypeNodeSystemId(node); 37 38 str += `<!DOCTYPE ${treeAdapter.getDocumentTypeNodeName(node) || ''}`; 39 40 if (publicId || systemId) { 41 str += ` "${publicId}" "${systemId}"`; 42 } 43 44 str += '>\n'; 45 } else { 46 const tn = treeAdapter.getTagName(node); 47 48 str += `<${getElementSerializedNamespaceURI(node, treeAdapter) + tn}>\n`; 49 50 let childrenIndent = indent + 2; 51 const serializedAttrs = []; 52 53 treeAdapter.getAttrList(node).forEach(attr => { 54 let attrStr = getSerializedTreeIndent(childrenIndent); 55 56 if (attr.prefix) { 57 attrStr += `${attr.prefix} `; 58 } 59 60 attrStr += `${attr.name}="${attr.value}"\n`; 61 62 serializedAttrs.push(attrStr); 63 }); 64 65 str += serializedAttrs.sort().join(''); 66 67 if (tn === HTML.TAG_NAMES.TEMPLATE && treeAdapter.getNamespaceURI(node) === HTML.NAMESPACES.HTML) { 68 str += `${getSerializedTreeIndent(childrenIndent)}content\n`; 69 childrenIndent += 2; 70 node = treeAdapter.getTemplateContent(node); 71 } 72 73 str += serializeNodeList(treeAdapter.getChildNodes(node), childrenIndent, treeAdapter); 74 } 75 }); 76 77 return str; 78} 79 80module.exports = function serializeToDatFileFormat(rootNode, treeAdapter) { 81 return serializeNodeList(treeAdapter.getChildNodes(rootNode), 0, treeAdapter); 82}; 83