Skip to content

Render PlantUML diagrams in Markdown documents #411

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions docs/example/workspace-docs/01-embedding-diagrams-and-images.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,66 @@ directory, you can do that as follows:

![A nice picture](/pictures/nice-picture.png)

### Embedding PlantUML diagrams

Structurizr Site Generatr supports rendering PlantUML embedded in Markdown files.

#### Sequence diagram example

````markdown
```puml
@startuml
Foo -> Bar: doSomething()
@enduml
```
````

```puml
@startuml
Foo -> Bar: doSomething()
@enduml
```

### Class diagram example

````markdown
```puml
@startuml
class Foo {
+property: String
+foo()
}

class Bar {
-privateProperty: String
+bar()
}

Foo ..> Bar: Uses
@enduml
```
````

```puml
@startuml
class Foo {
+property: String
+foo()
}

class Bar {
-privateProperty: String
+bar()
}

Foo ..> Bar: Uses
@enduml
```

### Embedding mermaid diagrams

Structurizr Site Generatr is supporting mermaid diagrams in markdown pages using the actual mermaid.js version. Therefore every diagram type, supported by mermaid may be used in markdown documentation files.
Structurizr Site Generatr is supporting mermaid diagrams in markdown pages using the actual mermaid.js version.
Therefore every diagram type, supported by mermaid may be used in markdown documentation files.

* flowchart
* sequence diagram
Expand All @@ -49,7 +106,8 @@ Structurizr Site Generatr is supporting mermaid diagrams in markdown pages using
* requirement diagram
* and some more

Please find the full list of supported chart types on [mermaid.js.org/intro](https://mermaid.js.org/intro/#diagram-types)
Please find the full list of supported chart types
on [mermaid.js.org/intro](https://mermaid.js.org/intro/#diagram-types)

#### Flowchart Diagram Example

Expand Down
60 changes: 60 additions & 0 deletions docs/example/workspace-docs/03-asciidoc-features.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,66 @@ https://www.flickr.com/photos/schmollmolch/4937297813/[Sun], by Christian Scheja

image::/pictures/nice-picture.png[A nice picture]

=== Embedding PlantUML diagrams

==== Sequence Diagram Example

[source, asciidoc]
-----
[plantuml]
----
@startuml
Foo -> Bar: doSomething()
@enduml
----
-----

[plantuml]
----
@startuml
Foo -> Bar: doSomething()
@enduml
----

==== Class Diagram Example

[source, asciidoc]
-----
[plantuml]
----
@startuml
class Foo {
+property: String
+foo()
}

class Bar {
-privateProperty: String
+bar()
}

Foo ..> Bar: Uses
@enduml
----
-----

[plantuml]
----
@startuml
class Foo {
+property: String
+foo()
}

class Bar {
-privateProperty: String
+bar()
}

Foo ..> Bar: Uses
@enduml
----

=== Embedding mermaid diagrams

==== Flowchart Diagram Example
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
package nl.avisi.structurizr.site.generatr.site.model

import net.sourceforge.plantuml.FileFormat
import net.sourceforge.plantuml.FileFormatOption
import net.sourceforge.plantuml.SourceStringReader
import org.asciidoctor.Asciidoctor
import org.asciidoctor.ast.ContentModel
import org.asciidoctor.ast.ContentNode
import org.asciidoctor.ast.Document
import org.asciidoctor.ast.StructuralNode
import org.asciidoctor.converter.ConverterFor
import org.asciidoctor.converter.StringConverter
import org.asciidoctor.extension.BlockProcessor
import org.asciidoctor.extension.Contexts
import org.asciidoctor.extension.Name
import org.asciidoctor.extension.Reader
import java.io.ByteArrayOutputStream

val asciidoctor: Asciidoctor = Asciidoctor.Factory.create().apply {
val asciidoctorWithTextConverter: Asciidoctor = Asciidoctor.Factory.create().apply {
javaConverterRegistry().register(AsciiDocTextConverter::class.java)
}

val asciidoctorWithPUMLRenderer: Asciidoctor = Asciidoctor.Factory.create().apply {
javaExtensionRegistry().block(PlantUMLBlockProcessor::class.java)
}

@ConverterFor("text")
class AsciiDocTextConverter(
backend: String?,
Expand All @@ -30,3 +43,16 @@ class AsciiDocTextConverter(
null
}
}

@Name("plantuml")
@Contexts(value = [Contexts.LISTING])
@ContentModel(ContentModel.VERBATIM)
class PlantUMLBlockProcessor : BlockProcessor() {
override fun process(parent: StructuralNode?, reader: Reader, attributes: MutableMap<String, Any>?): Any {
val plantUMLCode = reader.read()
val plantUMLReader = SourceStringReader(plantUMLCode)
val stream = ByteArrayOutputStream()
plantUMLReader.outputImage(stream, FileFormatOption(FileFormat.SVG, false))
return createBlock(parent, "pass", "<div>$stream</div>")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ private fun markdownText(content: String): String {

private fun asciidocText(content: String): String {
val options = Options.builder().safe(SafeMode.SERVER).backend("text").build()
val text = asciidoctor.convert(content, options)
val text = asciidoctorWithTextConverter.convert(content, options)

return text.lines().joinToString(" ")
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import com.structurizr.documentation.Format
import com.structurizr.documentation.Section
import com.vladsch.flexmark.ast.Heading
import com.vladsch.flexmark.parser.Parser
import org.asciidoctor.Asciidoctor
import org.asciidoctor.Options
import org.asciidoctor.SafeMode

Expand All @@ -28,7 +27,7 @@ private fun Section.markdownTitle(): String {

private fun Section.asciidocTitle(): String {
val options = Options.builder().safe(SafeMode.SERVER).build()
val document = asciidoctor.load(content, options)
val document = asciidoctorWithTextConverter.load(content, options)

if (document.title != null && document.title.isNotEmpty())
return document.title
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
package nl.avisi.structurizr.site.generatr.site.model

import com.structurizr.documentation.Format
import com.vladsch.flexmark.ast.FencedCodeBlock
import com.vladsch.flexmark.html.HtmlRenderer
import com.vladsch.flexmark.html.HtmlWriter
import com.vladsch.flexmark.html.LinkResolver
import com.vladsch.flexmark.html.LinkResolverFactory
import com.vladsch.flexmark.html.renderer.LinkResolverBasicContext
import com.vladsch.flexmark.html.renderer.LinkStatus
import com.vladsch.flexmark.html.renderer.ResolvedLink
import com.vladsch.flexmark.html.renderer.*
import com.vladsch.flexmark.parser.Parser
import com.vladsch.flexmark.util.ast.Node
import kotlinx.html.div
import kotlinx.html.stream.createHTML
import net.sourceforge.plantuml.FileFormat
import net.sourceforge.plantuml.FileFormatOption
import net.sourceforge.plantuml.SourceStringReader
import nl.avisi.structurizr.site.generatr.site.asUrlToFile
import nl.avisi.structurizr.site.generatr.site.views.diagram
import org.asciidoctor.Asciidoctor
import org.asciidoctor.Options
import org.asciidoctor.SafeMode
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import java.io.ByteArrayOutputStream

const val embedPrefix = "embed:"

Expand All @@ -43,6 +46,7 @@ private fun markdownToHtml(
val parser = Parser.builder(options).build()
val renderer = HtmlRenderer.builder(options)
.linkResolverFactory(CustomLinkResolver.Factory(pageViewModel))
.nodeRendererFactory { FencedCodeBlockRenderer() }
.build()
val markDownDocument = parser.parse(markdown)
val html = renderer.render(markDownDocument)
Expand All @@ -53,6 +57,23 @@ private fun markdownToHtml(
.html()
}

private class FencedCodeBlockRenderer : NodeRenderer {
override fun getNodeRenderingHandlers(): MutableSet<NodeRenderingHandler<*>> =
mutableSetOf(NodeRenderingHandler(FencedCodeBlock::class.java, this::render))

private fun render(fencedCodeBlock: FencedCodeBlock, nodeRendererContext: NodeRendererContext, htmlWriter: HtmlWriter) {
if (fencedCodeBlock.info.toString() == "puml") {
htmlWriter.tag("div") {
val reader = SourceStringReader(fencedCodeBlock.contentChars.toString())
val stream = ByteArrayOutputStream()
reader.outputImage(stream, FileFormatOption(FileFormat.SVG, false))
htmlWriter.raw(stream.toString())
}
} else
nodeRendererContext.delegateRender()
}
}

private fun asciidocToHtml(
pageViewModel: PageViewModel,
asciidoc: String,
Expand All @@ -67,7 +88,7 @@ private fun asciidocToHtml(
// another option could be https://docs.asciidoctor.org/asciidoctorj/latest/locating-files/#globdirectorywalker-class
.backend("html5")
.build()
val html = asciidoctor.convert(asciidoc, options)
val html = asciidoctorWithPUMLRenderer.convert(asciidoc, options)

return Jsoup.parse(html)
.apply {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ class PlantUmlExporterTest {

private fun exporters() = listOf(
ExporterType.C4.name.lowercase() to
{ workspace: Workspace, url: String -> C4PlantUmlExporterWithElementLinks(workspace, url) },
{ workspace: Workspace, url: String -> C4PlantUmlExporterWithElementLinks(workspace, url) },
ExporterType.STRUCTURIZR.name.lowercase() to
{ workspace: Workspace, url: String -> StructurizrPlantUmlExporterWithElementLinks(workspace, url) }
{ workspace: Workspace, url: String -> StructurizrPlantUmlExporterWithElementLinks(workspace, url) }
)

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package nl.avisi.structurizr.site.generatr.site.model

import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.matches
import com.structurizr.documentation.Format
import org.junit.jupiter.api.Test

Expand Down Expand Up @@ -128,6 +129,28 @@ class AsciidocToHtmlTest : ViewModelTest() {
)
}

@Test
fun `renders PlantUML code to SVG`() {
val generatorContext = generatorContext()
val viewModel = HomePageViewModel(generatorContext)

val html = toHtml(
viewModel,
"""
[plantuml]
----
@startuml
class Foo
@enduml
----
""".trimIndent(),
Format.AsciiDoc,
svgFactory
)

assertThat(html).matches("<div>.*<svg.*Foo.*</svg>.*</div>".toRegex(RegexOption.DOT_MATCHES_ALL))
}

@Test
fun `translates mermaid graphings in asciidoc`() {
val generatorContext = generatorContext()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package nl.avisi.structurizr.site.generatr.site.model

import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.matches
import com.structurizr.documentation.Format
import org.junit.jupiter.api.Test

Expand Down Expand Up @@ -181,6 +182,27 @@ class MarkdownToHtmlTest : ViewModelTest() {
)
}

@Test
fun `renders PlantUML code to SVG`() {
val generatorContext = generatorContext()
val viewModel = HomePageViewModel(generatorContext)

val html = toHtml(
viewModel,
"""
```puml
@startuml
class Foo
@enduml
```
""".trimIndent(),
Format.Markdown,
svgFactory
)

assertThat(html).matches("<div>.*<svg.*Foo.*</svg>.*</div>".toRegex(RegexOption.DOT_MATCHES_ALL))
}

@Test
fun `translates mermaid graphings in markdown with extension property containing GitLab`() {
val generatorContext = generatorContext().apply {
Expand Down