How to have mermaid plugin in RichText Editor

I’m planing to use RichText Editor as an online markdown editor, in which mermaid was also used frequently. How to have it work?
Thx

Hello,

Unfortunately, RichText does not natively support rendering Mermaid diagrams. You can try integrating Mermaid manually, but please note that this approach is not officially supported and may not work reliably in all scenarios.

That said, here’s a workaround that demonstrates how Mermaid can be rendered based on special markers in the RichText content:

const richtext = new dhx.Richtext("richtext");

const htmlText = `
	<h1>Meet DHTMLX Rich Text Editor!</h1>
	<p>This demo will show you a customizable JavaScript rich text editor.</p>
	<p><i>Read more in</i><a href="https://docs.dhtmlx.com"><i>documentation</i></a></p>

	---mermaid-start---
	graph LR;
	A-->B;
	B-->C;
	---mermaid-end---
`;

richtext.setValue(htmlText);

const root = document.querySelector(".dhx_richtext");

function renderMermaidGraphs() {
	const spans = root.querySelectorAll("span");

	spans.forEach(span => {
		if (span.textContent.includes("---mermaid-start---")) {
			const code = span.textContent
				.replace("---mermaid-start---", "")
				.replace("---mermaid-end---", "")
				.trim();

			let mermaidDiv = span.nextElementSibling;

			// Create a Mermaid container if it doesn't exist yet
			if (!mermaidDiv || !mermaidDiv.classList.contains("mermaid")) {
				mermaidDiv = document.createElement("div");
				mermaidDiv.className = "mermaid";
				span.after(mermaidDiv);
			}

			// Hide the raw Mermaid code from the editor
			span.style.display = "none";

			// Update and re-render the Mermaid diagram
			mermaidDiv.textContent = code;
			mermaidDiv.removeAttribute("data-processed");
			mermaid.init(undefined, mermaidDiv);
		}
	});
}

// Wait for the DOM to be ready before initial rendering
setTimeout(() => {
	renderMermaidGraphs();

	// Re-render diagrams on any editor action
	richtext.events.on("Action", () => {
		renderMermaidGraphs();
	});
}, 0);

Please see an example: DHTMLX Snippet Tool