Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions docs/.vitepress/theme/banner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,23 +51,32 @@ function render(b: BannerData): void {
el.appendChild(a);
}

const syncHeight = () => {
document.documentElement.style.setProperty(
"--vp-layout-top-height",
`${el.offsetHeight}px`,
);
};
Comment on lines +54 to +59

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There is a potential race condition here. If the banner is dismissed (via the button click) before the requestAnimationFrame or a ResizeObserver notification fires, syncHeight will execute on a detached element. This will result in el.offsetHeight being 0, which then re-adds the --vp-layout-top-height property to the document as 0px after it was explicitly removed in the click handler. Adding a check for el.isConnected ensures the property is only updated if the banner is still active in the DOM.

Suggested change
const syncHeight = () => {
document.documentElement.style.setProperty(
"--vp-layout-top-height",
`${el.offsetHeight}px`,
);
};
const syncHeight = () => {
if (!el.isConnected) return;
document.documentElement.style.setProperty(
"--vp-layout-top-height",
`${el.offsetHeight}px`,
);
};


const observer =
typeof ResizeObserver !== "undefined"
? new ResizeObserver(syncHeight)
: null;

const btn = document.createElement("button");
btn.type = "button";
btn.setAttribute("aria-label", "Dismiss");
btn.textContent = "\u00d7";
btn.addEventListener("click", () => {
localStorage.setItem(STORAGE_KEY, b.id);
observer?.disconnect();
el.remove();
document.documentElement.style.removeProperty("--vp-layout-top-height");
});
el.appendChild(btn);

document.body.prepend(el);

requestAnimationFrame(() => {
document.documentElement.style.setProperty(
"--vp-layout-top-height",
`${el.offsetHeight}px`,
);
});
requestAnimationFrame(syncHeight);
observer?.observe(el);
}
Loading