Skip to content

Commit a175198

Browse files
Handle race condition in mermaid by adding defensive programming and delaying instantiation of the intersection observer
1 parent e90753a commit a175198

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

web_src/js/markup/mermaid.ts

Lines changed: 11 additions & 8 deletions
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)