hotwired / turbo

The speed of a single-page web application without having to write any JavaScript
https://turbo.hotwired.dev
MIT License
6.72k stars 429 forks source link

Turbo does not work with Declarative Shadow DOM #1292

Open KonnorRogers opened 3 months ago

KonnorRogers commented 3 months ago

Turbo appears to leave template tags in place on navigation breaking components that use Declarative Shadow DOM.

https://github.com/user-attachments/assets/78081b36-4379-4993-87c4-903c7a544a1c

Reproduction: https://github.com/KonnorRogers/turbo-dsd-reproduction

KonnorRogers commented 3 months ago

This seems to work as a sort of "polyfill"

function fixDSD (e) {
  const newElement = e.detail.newBody || e.detail.newFrame || e.detail.newStream
  if (!newElement) { return }

  // https://developer.chrome.com/docs/css-ui/declarative-shadow-dom#polyfill
  ;(function attachShadowRoots(root) {
    root.querySelectorAll("template[shadowrootmode]").forEach(template => {
      const mode = template.getAttribute("shadowrootmode");
      const shadowRoot = template.parentNode.attachShadow({ mode });
      shadowRoot.appendChild(template.content);
      template.remove();
      attachShadowRoots(shadowRoot);
    });
  })(newElement);
}

;["turbo:before-render", "turbo:before-stream-render", "turbo:before-frame-render"].forEach((eventName) => {
  document.addEventListener(eventName, fixDSD)
})