Project

General

Profile

Defect #44767 ยป fix-mermaid-in-hidden-code-block.patch

Mizuki ISHIKAWA, 2026-11-20 02:06

View differences:

app/javascript/controllers/mermaid_controller.js
loadMermaid().then((mermaid) => {
// The block may have left the DOM while Mermaid.js was loading.
if (this.element.isConnected) this.render(mermaid);
if (this.element.isConnected) this.renderWhenShown(mermaid);
}).catch((error) => {
console.error('Failed to load Mermaid.js:', error);
// Show the source that the mermaid-available CSS rule hides.
......
}
disconnect() {
this.visibilityObserver?.disconnect();
this.visibilityObserver = null;
// Undo everything render() added so that a reconnect starts clean.
this.container?.remove();
this.errorElement?.remove();
......
}
}
// Mermaid.js lays out a diagram by measuring its text, which has no size
// while the block is not displayed, e.g. inside a collapsed {{collapse}}
// macro. Such a block is rendered once it is shown.
renderWhenShown(mermaid) {
const pre = this.element.closest('pre');
if (!pre) return;
const isShown = () => pre.getClientRects().length > 0;
if (isShown()) {
this.render(mermaid);
return;
}
// The size of the block changes from zero when it is shown.
const observer = new ResizeObserver(() => {
if (!isShown()) return;
observer.disconnect();
if (this.visibilityObserver === observer) this.visibilityObserver = null;
this.render(mermaid);
});
observer.observe(pre);
this.visibilityObserver = observer;
}
render(mermaid) {
const pre = this.element.closest('pre');
if (!pre) return;
test/system/mermaid_rendering_test.rb
end
end
def test_should_render_mermaid_code_block_in_collapse_macro
skip unless mermaid_installed?
issue = Issue.find(1)
issue.update_column(:description, "{{collapse\n```mermaid\ngraph TD;\nA-->B;\n```\n}}")
log_user('jsmith', 'jsmith')
visit "/issues/#{issue.id}"
within('div.description') do
# Wait until Mermaid.js is loaded while the block is still collapsed.
assert page.evaluate_async_script(<<~JS)
const done = arguments[0];
const check = () => typeof mermaid !== 'undefined' ? setTimeout(() => done(true), 500) : setTimeout(check, 50);
check();
JS
find('a.collapsible', text: 'Show').click
within('div.collapsed-text') do
assert_selector 'div.mermaid svg g.node', count: 2
assert_no_selector 'svg .error-icon'
# The diagram must be laid out while visible, so that its labels have a size.
assert page.evaluate_script(
"document.querySelector('div.collapsed-text div.mermaid svg g.node .label').getBoundingClientRect().width > 0"
)
end
end
end
def test_should_show_flash_message_for_invalid_mermaid_diagram
skip unless mermaid_installed?
    (1-1/1)