Skip to content

Commit 88f5d33

Browse files
Fix race condition in mermaid observer (#32599)
This Pull Request addresses a race condition in the updateIframeHeight function where it is sometimes called when the iframe is not fully loaded or accessible resulting in an alarming error message for the user. To address this we: 1. Add defensive programming within the updateIframeHeight function 2. Delay instantiating the intersection observer until the iframe has loaded Co-authored-by: wxiaoguang <[email protected]>
1 parent 9ed768a commit 88f5d33

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

web_src/js/markup/mermaid.ts

+11-8
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,12 @@ export async function renderMermaid(): Promise<void> {
5858
mermaidBlock.append(btn);
5959

6060
const updateIframeHeight = () => {
61-
iframe.style.height = `${iframe.contentWindow.document.body.clientHeight}px`;
61+
const body = iframe.contentWindow?.document?.body;
62+
if (body) {
63+
iframe.style.height = `${body.clientHeight}px`;
64+
}
6265
};
6366

64-
// update height when element's visibility state changes, for example when the diagram is inside
65-
// a <details> + <summary> block and the <details> block becomes visible upon user interaction, it
66-
// would initially set a incorrect height and the correct height is set during this callback.
67-
(new IntersectionObserver(() => {
68-
updateIframeHeight();
69-
}, {root: document.documentElement})).observe(iframe);
70-
7167
iframe.addEventListener('load', () => {
7268
pre.replaceWith(mermaidBlock);
7369
mermaidBlock.classList.remove('tw-hidden');
@@ -76,6 +72,13 @@ export async function renderMermaid(): Promise<void> {
7672
mermaidBlock.classList.remove('is-loading');
7773
iframe.classList.remove('tw-invisible');
7874
}, 0);
75+
76+
// update height when element's visibility state changes, for example when the diagram is inside
77+
// a <details> + <summary> block and the <details> block becomes visible upon user interaction, it
78+
// would initially set a incorrect height and the correct height is set during this callback.
79+
(new IntersectionObserver(() => {
80+
updateIframeHeight();
81+
}, {root: document.documentElement})).observe(iframe);
7982
});
8083

8184
document.body.append(mermaidBlock);

0 commit comments

Comments
 (0)