Skip to content

Commit

Permalink
Create html scaffold if missing
Browse files Browse the repository at this point in the history
  • Loading branch information
Rafael Nowrotek committed Jan 19, 2019
1 parent 0980282 commit f273548
Show file tree
Hide file tree
Showing 5 changed files with 284 additions and 7 deletions.
47 changes: 44 additions & 3 deletions lib/DOMParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const htmlparser = require("htmlparser2");
const DOMImplementation = require('./DOMImplementation');
const HTMLElement = require('./HTMLElement');

const domTreeToW3C = (document, { type, name, attribs, children = [], data }) => {
const objTreeToW3C = (document, { type, name, attribs, children = [], data }) => {
const nodeTypeMapping = {
tag: () => document.createElement(name),
text: () => document.createTextNode(data),
Expand All @@ -19,7 +19,7 @@ const domTreeToW3C = (document, { type, name, attribs, children = [], data }) =
const node = nodeTypeMapping[type](arguments);

for (let child of children) {
const el = domTreeToW3C(document, child);
const el = objTreeToW3C(document, child);
node.appendChild(el);
}

Expand All @@ -42,20 +42,61 @@ class DOMParser extends XMLDOMParser {
if (/\/x?html?$/.test(mimeType)) {
const impl = new DOMImplementation();
const document = impl.createHTMLDocument();

// We're going to replace initial scaffold
while (document.lastChild) {
document.removeChild(document.lastChild);
}

// Actually parse html string
let tree;

const handler = new htmlparser.DomHandler(function (error, dom) {
if (error) {
throw error;
}
tree = dom;
});
const parser = new htmlparser.Parser(handler);

parser.write(source);
parser.end();
tree.forEach(el => document.appendChild(domTreeToW3C(document, el)));

// Wrap tree into proper scaffold if missing
let root = tree.find(node => node.name === 'html');

if (!root) {
root = {
type: 'tag',
name: 'html',
attribs: {},
children: tree
};
}

tree = [ root ];

const body = root.children.find(node => node.name === 'body');

if (!body) {
root.children = [{
type: 'tag',
name: 'body',
attribs: {},
children: root.children
}];
}

// Transform to w3c-compliant object
const fragment = document.createDocumentFragment();

tree.forEach(node => {
const w3cNode = objTreeToW3C(document, node);

fragment.appendChild(w3cNode);
});
document.appendChild(fragment);

return document;
}
}
Expand Down
217 changes: 216 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit f273548

Please sign in to comment.