Project

General

Profile

Feature #44425 » 0002-Render-code-blocks-highlighted-as-mermaid-into-diagr.patch

Go MAEDA, 2026-09-30 08:00

View differences:

.github/workflows/tests.yml
- name: Display Chrome version
run: google-chrome --version
- name: Install mermaid.js for the mermaid rendering tests
run: bin/rails redmine:mermaid:install
- name: Run system tests
run: bin/rails test:system
env:
app/helpers/application_helper.rb
'tribute-5.1.3.min'
)
tags << javascript_include_tag('application-legacy', 'responsive')
# mermaid.js is installed by the redmine:mermaid:install task and is
# several MB, so it is not part of every page load. When it is available,
# its URL is exposed here and the mermaid Stimulus controller loads it
# only when a ```mermaid code block is actually present on the page.
if Redmine::Mermaid.available?
tags <<
javascript_tag(
"window.MermaidAssetUrl = #{asset_path(Redmine::Mermaid::FILENAME).to_json};"
)
end
unless User.current.pref.warn_on_leaving_unsaved == '0'
warn_text = escape_javascript(l(:text_warn_on_leaving_unsaved))
tags <<
app/javascript/controllers/mermaid_controller.js
/**
* Redmine - project management software
* Copyright (C) 2006- Jean-Philippe Lang
* This code is released under the GNU General Public License.
*/
import { Controller } from "@hotwired/stimulus"
let mermaidInitialized = false;
let mermaidLoadPromise = null;
// mermaid.js is not bundled with Redmine; administrators install it with
// `bin/rails redmine:mermaid:install`. When it is available, javascript_heads
// exposes its URL as window.MermaidAssetUrl. It is several MB, so it is only
// fetched (as a classic <script>) once a ```mermaid code block actually needs
// rendering.
function loadMermaid() {
if (typeof mermaid !== 'undefined') return Promise.resolve(mermaid);
if (mermaidLoadPromise) return mermaidLoadPromise;
const loading = new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = window.MermaidAssetUrl;
script.onload = () => {
if (window.mermaid) {
resolve(window.mermaid);
} else {
script.remove();
reject(new Error('mermaid.js loaded but window.mermaid is not defined'));
}
};
script.onerror = () => {
script.remove();
reject(new Error('Failed to load mermaid.js'));
};
document.head.appendChild(script);
});
// Keeping a rejected promise around would stop every later connect() in the
// same page -- another block, or a repeated preview -- from trying again.
loading.catch(() => {
if (mermaidLoadPromise === loading) mermaidLoadPromise = null;
});
mermaidLoadPromise = loading;
return loading;
}
// Connects to data-controller="mermaid"
// Renders ```mermaid code blocks (marked with this controller by
// Redmine::WikiFormatting::SyntaxHighlight#process) as diagrams.
export default class extends Controller {
connect() {
// mermaid.js is not installed: leave the code block as it is.
if (!window.MermaidAssetUrl && typeof mermaid === 'undefined') return;
loadMermaid().then((mermaid) => {
// The block may have left the DOM while mermaid.js was loading.
if (this.element.isConnected) this.render(mermaid);
}).catch((error) => {
console.error('Failed to load mermaid.js:', error);
});
}
disconnect() {
// Undo everything render() added so that a reconnect starts clean.
this.container?.remove();
this.errorElement?.remove();
this.container = this.errorElement = null;
const pre = this.element.closest('pre');
if (pre) pre.style.display = '';
}
render(mermaid) {
const pre = this.element.closest('pre');
if (!pre) return;
if (!mermaidInitialized) {
mermaid.initialize({ startOnLoad: false, securityLevel: 'strict' });
mermaidInitialized = true;
}
const container = document.createElement('div');
container.className = 'mermaid';
container.textContent = this.element.textContent.trim();
pre.insertAdjacentElement('afterend', container);
this.container = container;
// mermaid.js draws its own error diagram on failure; replace it with a
// Redmine flash message while keeping the source block visible, so that
// the invalid diagram can be inspected and copied.
mermaid.run({ nodes: [container], suppressErrors: false }).then(() => {
pre.style.display = 'none';
}).catch((error) => {
container.remove();
if (this.container === container) this.container = null;
const errorElement = document.createElement('div');
errorElement.className = 'flash error';
errorElement.innerHTML = '<p>Failed to render mermaid diagram:</p>';
const message = document.createElement('p');
message.textContent = error?.message || String(error);
errorElement.appendChild(message);
// CopypreScrubber wraps the <pre> in div.pre-wrapper; put the message above the whole block.
const anchor = pre.closest('.pre-wrapper') || pre;
anchor.insertAdjacentElement('beforebegin', errorElement);
this.errorElement = errorElement;
});
}
}
lib/redmine/wiki_formatting/syntax_highlight.rb
# unsupported language, remove the class attribute
node.remove_attribute('class')
end
# Rouge has no mermaid lexer, so the branch above leaves the block as plain text.
# This attribute is what the mermaid Stimulus controller looks for to replace the block
# with a rendered diagram. Only block-level code is rendered; an inline <code class="mermaid">
# written in Textile is left as is.
# The attribute is added even when mermaid.js is not installed: formatted text may be cached
# (see Setting.cache_formatted_text), and the controller does nothing unless mermaid.js is available.
if lang.to_s.downcase == 'mermaid' && node.parent&.name == 'pre'
node['data-controller'] = 'mermaid'
end
end
end
end
test/helpers/application_helper_test.rb
assert_equal 'Bar - Foo - Redmine', html_title
end
def test_javascript_heads_should_not_expose_mermaid_asset_url_when_mermaid_is_not_available
Redmine::Mermaid.stubs(:available?).returns(false)
assert_not_include 'MermaidAssetUrl', javascript_heads
end
def test_favicon_path
assert_match %r{^/assets/favicon-\w+\.ico}, favicon_path
end
test/system/mermaid_rendering_test.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require_relative '../application_system_test_case'
class MermaidRenderingTest < ApplicationSystemTestCase
fixtures :projects, :trackers, :issue_statuses, :issues,
:enumerations, :users, :issue_categories,
:projects_trackers, :roles, :member_roles, :members,
:enabled_modules, :workflows, :journals, :journal_details
def test_should_not_load_mermaid_js_on_pages_without_mermaid_blocks
skip unless mermaid_installed?
issue = Issue.find(1)
issue.update_column(:description, "Unable to print recipes")
log_user('jsmith', 'jsmith')
visit "/issues/#{issue.id}"
# mermaid.js is several MB; it must stay unloaded unless a ```mermaid
# block is actually present, even though its URL is always exposed.
assert_equal 'undefined', page.evaluate_script('typeof mermaid')
assert page.evaluate_script('!!window.MermaidAssetUrl')
end
def test_should_render_mermaid_code_block_as_diagram
skip unless mermaid_installed?
issue = Issue.find(1)
issue.update_column(:description, "```mermaid\ngraph TD;\nA-->B;\n```")
log_user('jsmith', 'jsmith')
visit "/issues/#{issue.id}"
within('div.description') do
assert_selector 'code[data-controller=mermaid]', visible: :all
assert_selector 'div.mermaid svg'
assert_no_selector 'svg .error-icon'
end
end
def test_should_show_flash_message_for_invalid_mermaid_diagram
skip unless mermaid_installed?
issue = Issue.find(1)
issue.update_column(:description, "```mermaid\nthis is not a valid mermaid diagram(((\n```")
log_user('jsmith', 'jsmith')
visit "/issues/#{issue.id}"
within('div.description') do
assert_selector '.flash.error', text: 'Failed to render mermaid diagram'
assert_selector 'pre'
assert_no_selector 'div.mermaid svg'
end
end
def test_should_render_mermaid_in_description_preview
skip unless mermaid_installed?
log_user('jsmith', 'jsmith')
visit '/projects/ecookbook/issues/new'
within('form#issue-form') do
fill_in 'Subject', :with => 'mermaid preview test'
fill_in 'Description', :with => "```mermaid\ngraph TD;\nA-->B;\n```"
click_link 'Preview'
within('div.wiki-preview') do
assert_selector 'div.mermaid svg'
end
end
end
def test_should_not_execute_script_from_malicious_mermaid_syntax
skip unless mermaid_installed?
issue = Issue.find(1)
issue.update_column(
:description,
"```mermaid\ngraph TD;\nA[\"<img src=x onerror=alert(1)>\"]-->B;\nclick A call alert(2)\n```"
)
log_user('jsmith', 'jsmith')
visit "/issues/#{issue.id}"
assert_selector 'div.mermaid svg'
# Any inline event handler that slipped through would fire on render;
# if it did, alert() would block the driver instead of reaching here.
assert_nil page.evaluate_script("document.querySelector('div.mermaid img')?.getAttribute('onerror')")
assert_not page.evaluate_script("!!document.querySelector('div.mermaid script')")
page.execute_script('window.__alertCalled = 0; window.alert = function(){ window.__alertCalled++; };')
find('div.mermaid svg .node', match: :first).click
assert_equal 0, page.evaluate_script('window.__alertCalled')
end
end
test/unit/lib/redmine/wiki_formatting/common_mark/syntax_highlight_scrubber_test.rb
HTML
assert_equal input, filter(input)
end
def test_should_add_mermaid_controller_attribute_for_mermaid_language
input = <<~HTML
<pre><code class="language-mermaid">
graph TD;
A--&gt;B;
</code></pre>
HTML
expected = <<~HTML
<pre><code data-language="mermaid" data-controller="mermaid">
graph TD;
A--&gt;B;
</code></pre>
HTML
assert_equal expected, filter(input)
end
def test_should_add_mermaid_controller_attribute_regardless_of_language_case
input = <<~HTML
<pre><code class="language-Mermaid">
graph TD;
</code></pre>
HTML
expected = <<~HTML
<pre><code data-language="Mermaid" data-controller="mermaid">
graph TD;
</code></pre>
HTML
assert_equal expected, filter(input)
end
def test_should_not_add_mermaid_controller_attribute_for_other_languages
input = <<~HTML
<pre><code class="language-ruby">
def foo
end
</code></pre>
HTML
assert_no_match(/data-controller/, filter(input))
end
end
end
test/unit/lib/redmine/wiki_formatting/textile/syntax_highlight_scrubber_test.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require_relative '../../../../../test_helper'
class Redmine::WikiFormatting::Textile::SyntaxHighlightScrubberTest < ActiveSupport::TestCase
def filter(html)
fragment = Redmine::WikiFormatting::HtmlParser.parse(html)
scrubber = Redmine::WikiFormatting::Textile::SyntaxHighlightScrubber.new
fragment.scrub!(scrubber)
fragment.to_s
end
def test_should_highlight_supported_language
input = <<~HTML
<pre><code class="ruby">
def foo
end
</code></pre>
HTML
assert_match(/class="ruby syntaxhl" data-language="ruby"/, filter(input))
end
def test_should_add_mermaid_controller_attribute_for_mermaid_language
input = <<~HTML
<pre><code class="mermaid">
graph TD;
A--&gt;B;
</code></pre>
HTML
expected = <<~HTML
<pre><code data-language="mermaid" data-controller="mermaid">graph TD;
A--&gt;B;
</code></pre>
HTML
assert_equal expected, filter(input)
end
def test_should_add_mermaid_controller_attribute_regardless_of_language_case
input = <<~HTML
<pre><code class="Mermaid">
graph TD;
</code></pre>
HTML
assert_match(/data-language="Mermaid" data-controller="mermaid"/, filter(input))
end
def test_should_not_add_mermaid_controller_attribute_for_inline_code
input = '<p>Inline <code class="mermaid">graph TD; A--&gt;B;</code> in a sentence.</p>'
result = filter(input)
assert_no_match(/data-controller/, result)
assert_match(/data-language="mermaid"/, result)
end
def test_should_not_add_mermaid_controller_attribute_for_other_languages
input = <<~HTML
<pre><code class="ruby">
def foo
end
</code></pre>
HTML
assert_no_match(/data-controller/, filter(input))
end
end
(4-4/5)