diff --git a/nicegui/elements/markdown.js b/nicegui/elements/markdown.js index ad9f54ede..3c743178e 100644 --- a/nicegui/elements/markdown.js +++ b/nicegui/elements/markdown.js @@ -7,7 +7,8 @@ export default { await loadResource(window.path_prefix + this.codehilite_css_url); if (this.use_mermaid) { this.mermaid = (await import("mermaid")).default; - this.renderMermaid(); + await this.mermaid.initialize({ startOnLoad: false }); + await this.renderMermaid(); } }, data() { @@ -15,14 +16,21 @@ export default { mermaid: null, }; }, - updated() { - this.renderMermaid(); + async updated() { + if (this.mermaid) { + await this.renderMermaid(); + } }, methods: { - renderMermaid() { - this.$el.querySelectorAll(".mermaid-pre").forEach(async (pre, i) => { - await this.mermaid.run({ nodes: [pre.children[0]] }); - }); + async renderMermaid() { + const elements = this.$el.querySelectorAll(".mermaid-pre"); + for (const pre of elements) { + try { + await this.mermaid.run({ nodes: [pre.children[0]] }); + } catch (error) { + console.error('Failed to render mermaid diagram:', error); + } + } }, }, props: { diff --git a/nicegui/static/nicegui.css b/nicegui/static/nicegui.css index 904769a63..572de98fa 100644 --- a/nicegui/static/nicegui.css +++ b/nicegui/static/nicegui.css @@ -305,3 +305,11 @@ h6.q-timeline__title { position: absolute; left: 1.5em; } + +/* Hide mermaid diagrams until rendered, fixes mermaid source code being temporarily visible on load */ +.mermaid { + display: none; +} +.mermaid[data-processed="true"] { + display: block; +} diff --git a/website/documentation/content/markdown_documentation.py b/website/documentation/content/markdown_documentation.py index 28d7532bb..006f82f40 100644 --- a/website/documentation/content/markdown_documentation.py +++ b/website/documentation/content/markdown_documentation.py @@ -55,6 +55,22 @@ def markdown_tables(): ''', extras=['tables']) +@doc.demo('Mermaid diagrams', ''' + You can use mermaid diagrams with the "mermaid" extra. + See the [markdown2 documentation](https://github.com/trentm/python-markdown2/wiki/Extras#implemented-extras) for a list of available extras. +''') +def mermaid(): + md = ui.markdown(''' + ```mermaid + graph TD; + A-->B; + A-->C; + B-->D; + C-->D; + ``` + ''', extras=['mermaid']) + + @doc.demo('LaTeX formulas', ''' By activating the "latex" extra, you can use LaTeX formulas. This requires markdown2 version >=2.5 as well as latex2mathml to be installed. @@ -65,8 +81,8 @@ def markdown_latex(): $$e^{i\pi} = -1$$ ''', extras=['latex']) - - + + @doc.demo('Change Markdown content', ''' You can change the content of a Markdown element by setting its `content` property or calling `set_content`. ''')