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

Consider to use DocumentFragment #273

Open
tushuhei opened this issue Sep 4, 2023 · 0 comments
Open

Consider to use DocumentFragment #273

tushuhei opened this issue Sep 4, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@tushuhei
Copy link
Member

tushuhei commented Sep 4, 2023

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)

@tushuhei tushuhei added the enhancement New feature or request label Nov 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant