Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(serializer): Serialize void elements as "" #442

Merged
merged 3 commits into from Mar 7, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/parse5/lib/serializer/index.test.ts
Expand Up @@ -42,4 +42,15 @@ describe('serializer', () => {

assert.equal(html, '<button>Hello</button>');
});

it('serializes the children of void elements as the empty string (GH-289)', () => {
const document = parse5.parseFragment('<br/>');
fb55 marked this conversation as resolved.
Show resolved Hide resolved
const br = document.childNodes[0];
assert.ok(isElementNode(br));

// Add child node to `br`, to make sure they are skipped.
treeAdapters.default.appendChild(br, parse5.parseFragment('<div>').childNodes[0]);

assert.equal(parse5.serialize(br), '');
});
});
18 changes: 15 additions & 3 deletions packages/parse5/lib/serializer/index.ts
Expand Up @@ -30,6 +30,15 @@ const VOID_ELEMENTS = new Set<string>([
$.TRACK,
$.WBR,
]);

function isVoidElement<T extends TreeAdapterTypeMap>(node: T['node'], options: InternalOptions<T>): boolean {
return (
options.treeAdapter.isElementNode(node) &&
options.treeAdapter.getNamespaceURI(node) === NS.HTML &&
VOID_ELEMENTS.has(options.treeAdapter.getTagName(node))
);
}

const UNESCAPED_TEXT = new Set<string>([$.STYLE, $.SCRIPT, $.XMP, $.IFRAME, $.NOEMBED, $.NOFRAMES, $.PLAINTEXT]);

export function hasUnescapedText(tn: string, scriptingEnabled: boolean): boolean {
Expand Down Expand Up @@ -83,6 +92,11 @@ export function serialize<T extends TreeAdapterTypeMap = DefaultTreeAdapter.Defa
options?: SerializerOptions<T>
): string {
const opts = { ...defaultOpts, ...options };

if (isVoidElement(node, opts)) {
return '';
}

return serializeChildNodes(node, opts);
}

Expand Down Expand Up @@ -148,9 +162,7 @@ function serializeElement<T extends TreeAdapterTypeMap>(node: T['element'], opti
const tn = options.treeAdapter.getTagName(node);

return `<${tn}${serializeAttributes(node, options)}>${
options.treeAdapter.getNamespaceURI(node) === NS.HTML && VOID_ELEMENTS.has(tn)
? ''
: `${serializeChildNodes(node, options)}</${tn}>`
isVoidElement(node, options) ? '' : `${serializeChildNodes(node, options)}</${tn}>`
}`;
}

Expand Down