Skip to content

Commit 2b5dfe8

Browse files
william-allspicewxiaoguang
authored andcommitted
Fix race condition in mermaid observer (go-gitea#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 27489f2 commit 2b5dfe8

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

web_src/js/markup/mermaid.js

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -57,16 +57,12 @@ export async function renderMermaid() {
5757
mermaidBlock.append(btn);
5858

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

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

8083
document.body.append(mermaidBlock);

0 commit comments

Comments
 (0)