Open
Description
Have you considered directly building a DomFragment
instead of returning strings from your parser ?
This would allow you to avoid unnecessary serialization/parsing/sanitization steps.
Something like this:
// in dom.ts
function parseFromString(html: string): Node {
const template = document.createElement('template');
template.innerHTML = html;
return template.content;
}
// parser.ts
function translateHTMLString(html: string): Node {
if (html === '') return new DocumentFragment();
const fragment = parseFromString(html);
if (Parser.hasChildTextNode(fragment)) {
const wrapper = document.createElement('span');
wrapper.append(...fragment.childNodes);
fragment.appendChild(wrapper);
}
this.applyElement(fragment.firstChild as HTMLElement);
return fragment;
}
// in budoux-base.ts
sync() {
const translated = this.parser.translateHTMLString(this.innerHTML);
this.shadow.textContent = '';
this.shadow.appendChild(translated);
}
You can even avoid having to parse anything at all if you clone the existing nodes instead of grabbing this.innerHTML
.
// in budoux-base.ts
sync() {
let translated: HTMLElement;
if (Parser.hasChildTextNode(this)) {
translated = document.createElement('span');
translated.append(...this.childNodes.map(node => node.cloneNode(true)));
} else {
translated = this.firstElementChild!.cloneNode(true) as HTMLElement;
}
this.parser.applyElement(translated);
this.shadow.textContent = '';
this.shadow.appendChild(translated);
}
This is also likely to be more performant than parsing and serializing the tree multiple times.
Originally posted by @engelsdamien in google/safevalues#256 (comment)