Skip to content

Consider to use DocumentFragment #273

Open
@tushuhei

Description

@tushuhei

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions