/** TODO: This should probably get abstracted into an actual package. This is listens to the "lit-hydration-error" and then will add a button to show a dialog of the diff. */
(async () => {
const hostname = new URL(document.baseURI).hostname;
// Only diff on localhost. We dont need to show hydration errors on main site. Only locally.
if (hostname !== 'localhost') {
return;
}
const { diffLines } = await import('https://cdn.jsdelivr.net/npm/diff@5.2.0/+esm');
const { getDiffableHTML } = await import(
'https://cdn.jsdelivr.net/npm/@open-wc/semantic-dom-diff@0.20.1/get-diffable-html.js/+esm'
);
function wrap(el, wrapper) {
el.parentNode.insertBefore(wrapper, el);
wrapper.appendChild(el);
}
function handleLitHydrationError(e) {
const element = e.target;
const scratch = document.createElement('div');
const node = element.cloneNode(true);
scratch.append(node);
document.body.append(scratch);
customElements.upgrade(node);
node.updateComplete.then(() => {
// Render styles.
const elementStyles = element.constructor.elementStyles;
const finalStyles = [];
if (elementStyles !== undefined && elementStyles.length > 0) {
for (const style of elementStyles) {
finalStyles.push(style.cssText);
}
}
let innerHTML = scratch.firstElementChild?.shadowRoot.innerHTML;
if (finalStyles?.length) {
const styleTag = ``;
innerHTML = styleTag + '\n' + innerHTML;
}
const clientHTML = getDiffableHTML(innerHTML);
const serverHTML = getDiffableHTML(element.shadowRoot?.innerHTML);
const diffDebugger = document.createElement('div');
diffDebugger.className = 'diff-debugger';
diffDebugger.innerHTML = `