Skip to content

Commit

Permalink
Add rudimentary support for void elements
Browse files Browse the repository at this point in the history
I want to avoid keeping a list so I'm considering making it possible for all elements to be void for now.
  • Loading branch information
TomasHubelbauer committed Oct 13, 2024
1 parent 46a7b51 commit cc094ed
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
9 changes: 8 additions & 1 deletion index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,11 @@ test('H1 & H2 & H3', async () => {
expect(document.body.outerHTML).toEqual(`<body><h1></h1><h2></h2><h3></h3></body>`);
});

// TODO: Use http://info.cern.ch/hypertext/WWW/TheProject.html as one of the tests
// See http://info.cern.ch/hypertext/WWW/TheProject.html
test('NEXTID', async () => {
const domParser = new DOMParser();
const document = await domParser.parseFromString(`<HEADER><TITLE></TITLE><NEXTID></HEADER>`);
expect(document.body.outerHTML).toEqual(`<body><header><title></title><nextid /></header></body>`);
});

// TODO: Use full http://info.cern.ch/hypertext/WWW/TheProject.html as one of the tests
25 changes: 23 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ class Element implements Node {
parentNode: Node;
parentElement: Element;

// TODO: Consider keeping a list of maybe just allowing any element to be void
// Note that this information is not exposed in the `Element` web interface
isVoid: boolean;

append(element: Element) {
this.children.push(element);
element.parentNode = this;
Expand All @@ -39,7 +43,18 @@ class Element implements Node {
}

get outerHTML() {
let html = `<${this.tagName}>`;
let html = `<${this.tagName}`;
if (this.isVoid) {
// TODO: Replace with `this.childNodes.length > 0` once `childNodes` exist
if (this.children.length > 0) {
throw new Error('Void elements cannot have children');
}

html += ` />`;
return html;
}

html += `>`;
for (const child of this.children) {
html += child.outerHTML;
}
Expand Down Expand Up @@ -132,7 +147,13 @@ export default class DOMParser {
document.activeElement.append(activeElement);
document.activeElement = activeElement;

element.onEndTag(() => {
element.onEndTag((tag) => {
// Keep closing the element chain as void elements until we find the matching tag
while (document.activeElement?.parentElement && tag.name !== document.activeElement.tagName) {
document.activeElement.isVoid = true;
document.activeElement = document.activeElement.parentElement;
}

document.activeElement = document.activeElement.parentElement;
});
},
Expand Down

0 comments on commit cc094ed

Please sign in to comment.