Skip to content

Repository files navigation

CMP Mermaid

English · 简体中文

Native Mermaid rendering for Kotlin and Compose Multiplatform.

Mermaid 12.0.0 semantics translated to Kotlin and rendered with Compose Canvas.

Quality Gate Web Demo Mermaid 12.0.0 MIT License

Live Web demo · 8,448-case visual report · Full Stable report · 33-diagram roadmap · Integration

Important

CMP Mermaid now implements all 33 official diagram families from Mermaid 12.0.0, and all 33 family gates pass. The supported Mermaid 12.0.0 contract is rated Stable.

The current 8,448-case Native/Official visual report covers every family with 256 same-source pairs, automated detail and geometry audits, and manual review of all 528 contact sheets.

CMP Mermaid is designed for applications that render many diagrams without a WebView per diagram. The production path does not embed Mermaid.js and does not include a network client or require android.permission.INTERNET: parsing, diagram state, layout preparation, SceneGraph generation, and final Compose Canvas painting are owned by the multiplatform libraries.

Current Verification

All 33 implemented families retain repository-controlled tests and corpus data, published Native/Official captures, and passing replacement detail and geometry gates.

Evidence Result
Official Mermaid diagram families 33
Implemented diagram families 33/33
Translation pending 0
Visual family gates pending 0
Independent production scenarios 441 Native/Official pairs
Declared capability coverage 738/738
Large-scale visual matrix 8,448 Native/Official pairs
Native/Official captures 16,896 matrix screenshots plus 882 independent-corpus and 16,896 malformed-source screenshots
Source-mutation parity 8,448/8,448 Official accept/reject outcomes matched: 2,156 accepted and 6,292 rejected; every Native rejection was CONTENT_ERROR; 0 crashes or timeouts
Matrix detail review 33 families: 8,448/8,448 accepted; 7,429 automatic passes plus 1,019 manually accepted reviews
Automated visual geometry 8,448/8,448 matrix pairs and 441/441 independent pairs passed
Deterministic SceneGraph replay 441 passed, 0 mismatches
Built-in theme matrix 363/363
Separate generated Native stress inputs 7,936 retained historical baseline
JVM tests 859 passed, 0 failed
Core production soak Historical 415-case baseline: 2,075 renders, 674ms total, 1ms P95, 63,968 bytes retained heap
Physical-device runtime matrix Kotlin 2.3.20 Android 8/8, Kotlin 1.7.21 Android 8/8, and iOS 6/6 passed; 9,702 corpus renders; 198 reviewed sentinels plus 22 completion screenshots; 0 crashes or Android ANRs
Runtime load matrix All three physical-device tracks passed all 441 cases; Web retains the prior 397-scenario baseline; iOS Simulator and Desktop retain the prior 236-scenario baseline
Evidence document What it contains
Full diagram roadmap Official 33-family inventory and the completed 33/33 family gates
Stable test report Decision, visual contact sheets, tests, soak metrics, runtime load evidence, and reproduction steps
All 8,448 Native/Official pairs 528 paged contact sheets, with 16 same-source pairs per page
Source-mutation Native/Official evidence 8,448 AI-like mutations from distinct valid bases, 16,896 screenshots, and 528 comparison sheets
Android physical-device report Separate Kotlin 2.3.20 and Kotlin 1.7.21 matrices across Android 9-16
iOS physical-device report Six-device iOS 14.3-26.0 matrix with complete 441-case loads
Production capability matrix The 738 independently exercised capabilities
Production readiness Code-level Stable criteria, resource budgets, and integration guidance
Quality Gate Current automated JVM, build, publication, security, APK, visual, and Web load results
Full Visual Parity Weekly/manual capture and detail enforcement for all 33 families
Full Invalid Source Matrix Weekly/manual 33 × 256 Native/Official malformed-source safety matrix

Overall Mermaid 12.0.0 support is Stable because all 33 family gates pass. A legal feature that cannot be represented faithfully returns MermaidError.UnsupportedFeature instead of silently drawing a misleading approximation.

Native Vs Mermaid.js

The comparisons below use the same Mermaid source, theme, layout mode, and fixed viewport. The goal is equivalent meaning and comparable visual quality, not pixel-identical browser output; platform font metrics may differ.

Flowchart: multi-region failover

CMP Native - Compose Canvas Official - Mermaid.js 12.0.0
CMP Native multi-region failover flowchart Official Mermaid.js multi-region failover flowchart
More same-source comparisons

XY Chart: mixed bar and line series

CMP Native - Compose Canvas Official - Mermaid.js 12.0.0
CMP Native XY chart Official Mermaid.js XY chart

State Diagram: labels, loops, branches, and terminal states

CMP Native - Compose Canvas Official - Mermaid.js 12.0.0
CMP Native state diagram Official Mermaid.js state diagram

The current published report contains 441 independent production comparisons and a separate large-scale matrix with 8,448 unique Mermaid sources: open all 528 visual evidence pages.

Supported Diagrams

Diagram Status Production cases Main coverage Details
Flowchart Detail gate passed 14 Jison/FlowDB, Dagre, shapes, links, Markdown/HTML labels Compatibility
XY Chart Detail gate passed 13 Jison/XY DB, D3 scales and ticks, bar/line plots, labels Compatibility
Quadrant Chart Detail gate passed 13 Axes, quadrants, points, classes, direct styles, themes Compatibility
Timeline Detail gate passed 13 LR/TD layouts, sections, periods, events, color scales, themes Compatibility
Kanban Detail gate passed 13 Sections, tasks, metadata, priorities, ticket links, themes Compatibility
Sequence Detail gate passed 14 Actors, 26 message forms, notes, activations, control regions Compatibility
Class Detail gate passed 13 Compartments, generics, namespaces, relations, Dagre Compatibility
State Detail gate passed 13 Composite states, concurrency, notes, forks/joins, Dagre Compatibility
Entity Relationship Detail gate passed 13 Attributes, cardinalities, relationships, nested subgraphs Compatibility
Gantt Detail gate passed 13 Dates, dependencies, exclusions, milestones, D3-style ticks Compatibility
Pie Detail gate passed 13 Langium grammar, D3 angles, donut, legends, palettes Compatibility
User Journey Detail gate passed 13 Sections, scores, actors, satisfaction faces, text strategies Compatibility
Requirement Detail gate passed 13 SysML types and fields, elements, seven relationships, Dagre, styling Compatibility
Git Graph Detail gate passed 13 Langium grammar, branches, merges, cherry-picks, orientations, themes Compatibility
Mindmap Detail gate passed 13 Jison/Mindmap DB, CoSE-Bilkent, Dagre, tidy tree, shapes, themes Compatibility
Packet Detail gate passed 13 Langium grammar, explicit and counted fields, row splitting, fixed-grid rendering Compatibility
Radar Detail gate passed 13 Langium grammar, axes, curves, graticules, legends, themes Compatibility
Sankey Detail gate passed 13 CSV grammar, D3 Sankey layout, alignments, value labels, link and node colors Compatibility
Treemap Detail gate passed 13 Langium grammar, D3 hierarchy and squarify layout, classes, values, responsive sizing Compatibility
Venn Detail gate passed 13 Jison grammar, Venn.js/fmin optimization, weighted overlaps, styles, text nodes Compatibility
Ishikawa Detail gate passed 13 Jison indentation grammar, alternating recursive branches, fish-head geometry, wrapping Compatibility
Cynefin Detail gate passed 13 Five domains, deterministic boundaries, confusion overflow, transitions, themes Compatibility
Event Modeling Detail gate passed 13 Langium grammar, frames, swimlanes, data, relations, validation, themes Compatibility
Agentflow Detail gate passed 13 Jison grammar, typed nodes and edges, nested/global/collapsed flows, connectors, metadata, Dagre Compatibility
Block Detail gate passed 13 Jison grammar, grids, spans, composites, shapes, block arrows, links, classes, styles Compatibility
Swimlanes Detail gate passed 13 Flowchart grammar and shapes, lane-aware Sugiyama layout, orthogonal routing, direction transforms Compatibility
Architecture Detail gate passed 13 Langium grammar, services, groups, junctions, directional edges, constrained fCoSE layout, icons Compatibility
C4 Detail gate passed 13 Five C4 levels, nested boundaries, deployment nodes, relation variants, styles, and configuration Compatibility
Railroad Detail gate passed 18 Railroad IR, EBNF, ABNF, PEG, shared AST, routed grammar paths, styles, and configuration Compatibility
TreeView Detail gate passed 13 Indentation and box-drawing syntax, hierarchy, annotations, descriptions, icons, styles, and configuration Compatibility
Use Case Detail gate passed 18 Actors, boundaries, UML relationships, notes, JSON tables, styles, and configuration Compatibility
Wardley Map Detail gate passed 13 Value chains, sourcing, evolution, pipelines, annotations, and strategic forces Compatibility
ZenUML Detail gate passed 13 Participants, nested calls, replies, groups, fragments, and participant icons Compatibility

All 33 implemented types support Mermaid frontmatter, relevant metadata, Unicode, and the relevant theme variables within their documented compatibility boundaries.

Try It

Open the live Kotlin/Wasm demo to browse syntax, render the galleries, switch all 11 themes, and compare CMP Native output with the pinned Mermaid.js reference. Every supported diagram type has an editable Playground with Native/Official preview switching. Mindmap can switch among CoSE-Bilkent, Dagre, and tidy-tree layouts.

CMP Mermaid Kotlin Wasm Playground

The official comparison renderer belongs to mermaid-debug-ui only. mermaid-core and mermaid-compose never use Mermaid.js.

Architecture

Mermaid source
    -> Kotlin preprocessor and translated parser
    -> translated diagram database and layout preparation
    -> platform-independent MermaidScene
    -> Compose Canvas
  • mermaid-core owns parsing, diagram state, layout adapters, typed errors, themes, and the platform-independent SceneGraph.
  • mermaid-compose owns Canvas painting, text measurement, assets, interactions, and pan/zoom behavior.
  • mermaid-debug-ui owns documentation, galleries, Playground, official comparison, and load-test screens. It is optional and should remain outside production release variants.
  • sample/* contains thin Android, iOS, Desktop, and Web launchers around the shared debug UI.

The production libraries contain no JavaScript engine or bundled JavaScript algorithm. Pure Kotlin Dagre is the default unified layout. ELK names and flowchart-elk are recognized as upstream inputs but return MermaidError.UnsupportedFeature("ELK layout"); they are never silently substituted with another layout.

Integration

The current publication coordinates are:

Consumer Artifact
Current Kotlin Multiplatform io.github.swithun-liu:mermaid-core:0.1.8
Current Compose Multiplatform io.github.swithun-liu:mermaid-compose:0.1.8
Android with Kotlin 1.7.21 io.github.swithun-liu:mermaid-core-android-kotlin17:0.1.8
Android Compose with Kotlin 1.7.21 io.github.swithun-liu:mermaid-compose-android-kotlin17:0.1.8
iOS binary CMPMermaid CocoaPod 0.1.8

Current Kotlin Multiplatform projects:

dependencies {
    implementation("io.github.swithun-liu:mermaid-compose:0.1.8")
}

Note

The Maven coordinates above are published and resolvable from the configured public repository. CocoaPods distribution remains a separate binary release path.

Android projects pinned to Kotlin 1.7.21 use the isolated Android artifact:

dependencies {
    implementation(
        "io.github.swithun-liu:mermaid-compose-android-kotlin17:0.1.8",
    )
}

The Kotlin 1.7.21 artifacts are Android-only, target JVM 1.8, and require Android API 24 or newer. Their artifact names are intentionally distinct from the current KMP modules, so a consumer cannot accidentally resolve Kotlin 2.x metadata.

Android View-based hosts can use the same Compose renderer without compiling Compose source:

val diagramView = CMPMermaidView(context).apply {
    setMermaidSource("flowchart LR\n  A --> B")
    setMermaidContentDescription("Example Mermaid diagram")
    setMermaidErrorListener { error ->
        reportRenderFailure(error.type, error.message, error.source)
    }
}
container.addView(diagramView)

CMPMermaidView is available from both the current Android target and the Kotlin 1.7.21 Android artifact.

iOS projects can consume the precompiled static XCFramework through CocoaPods:

pod 'CMPMermaid', '0.1.8'

The binary exposes CMPMermaidViewControllerFactory.makeViewController(...) to Swift and includes all renderer font resources. It supports iOS device arm64 and simulator arm64/x86_64 with a deployment target of iOS 14.

CMPMermaidViewControllerFactory().makeViewController(
    source: source,
    contentDescription: "Mermaid diagram",
    onContentSizeChanged: nil,
    onError: { error in
        reportRenderFailure(error.type, error.message, error.source)
    }
)

For a source checkout:

dependencies {
    implementation(project(":mermaid-compose"))
    debugImplementation(project(":mermaid-debug-ui"))
}

Basic Compose usage:

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.swithun.cmpmermaid.compose.MermaidDiagram
import com.swithun.cmpmermaid.core.MermaidTheme
import com.swithun.cmpmermaid.core.MermaidThemePreset

@Composable
fun Diagram(source: String) {
    MermaidDiagram(
        source = source,
        modifier = Modifier.fillMaxWidth(),
        theme = MermaidTheme.preset(MermaidThemePreset.Default),
        contentDescription = "Mermaid diagram",
        onError = { error ->
            reportRenderFailure(error.type, error.message, error.source)
        },
    )
}

The error callback receives MermaidRenderErrorInfo, including the original source passed to the renderer. CONTENT_ERROR represents structured parse, configuration, resource-limit, or unsupported-content failures. UNEXPECTED_EXCEPTION represents an ordinary exception caught inside the render pipeline or Compose drawing boundary. The Compose surface renders Mermaid.js 12.0.0's standard error diagram while the callback and onRenderResult retain the detailed typed diagnostic. The published source-mutation corpus verifies Official accept/reject outcome parity for all 8,448 cases. Native rejected inputs remain typed CONTENT_ERROR; exact diagnostic-message equality is reported separately for 1,798/6,292 paired errors and is not manufactured as a compatibility requirement. Coroutine cancellation and fatal process errors continue to propagate.

Generate all KMP publications under build/maven-repository:

./gradlew \
  :mermaid-core:publishAllPublicationsToBuildRepository \
  :mermaid-compose:publishAllPublicationsToBuildRepository

Generate the Kotlin 1.7.21 Android artifacts with JDK 11:

./android-legacy-build/gradlew -p android-legacy-build \
  assembleRelease \
  verifyLegacyPublicationCoordinates \
  publishLegacyToReleaseRepository

Generate and verify the static iOS binary with JDK 17:

./gradlew :mermaid-compose:podPublishReleaseXCFramework
tools/release/verify-ios-xcframework.sh

Release automation

The Quality Gate builds and verifies the iOS XCFramework once and preserves it with its exact source commit. Pushing a v* tag then builds the modern KMP and Kotlin 1.7.21 Android artifacts in parallel while reusing only the successful verified iOS artifact from the successful main push Quality Gate for that immutable tag commit. All outputs are joined and verified again before any public registry is updated.

An interrupted publication keeps its prerelease and verified workflow artifact for 14 days. Re-run the failed jobs, or manually run the Release workflow with the same immutable tag. Maven Central and CocoaPods are checked before each write, so an already-published version is verified and skipped instead of being uploaded again.

Themes

All 11 Mermaid 12.0.0 presets are included: default, dark, forest, neutral, base, neo, neo-dark, redux, redux-color, redux-dark, and redux-dark-color.

Business themes can start from a preset with Kotlin copy, or consume Mermaid-compatible themeVariables through MermaidTheme.withVariables(...). Invalid external values are returned as GMResult.Err.

val brandTheme = MermaidTheme.preset(MermaidThemePreset.ReduxColor).copy(
    background = SceneColor(0xFF101820),
    nodeFill = SceneColor(0xFFF2AA4C),
    nodeText = SceneColor(0xFF101820),
    edge = SceneColor(0xFFF2AA4C),
)

Arbitrary themeCSS depends on browser DOM/CSS semantics and returns MermaidError.UnsupportedFeature. Portable styling uses typed Kotlin theme objects and MermaidFontFamilyResolver.

Following Mermaid Releases

CMP Mermaid follows a source-mapped translation workflow rather than reimplementing behavior from screenshots:

  1. Pin Mermaid, Jison, D3, Marked, Dagre, CoSE-Bilkent, and tidy-tree versions.
  2. Map every Kotlin parser, DB, layout, shape, theme, and renderer boundary to its upstream Mermaid source.
  3. Generate parser tables, rules, entities, fixtures, and debug-only reference assets from pinned inputs.
  4. Translate only the upstream delta for a Mermaid upgrade.
  5. Re-run the complete parity and platform gates.

Source maps: Flowchart · XY Chart · Quadrant Chart · Timeline · Kanban · Sequence · Class · State · ER · Gantt · Pie · User Journey · Requirement · Git Graph · Mindmap · Packet · Radar · Sankey · Treemap · Venn · Ishikawa · Cynefin · Event Modeling · Agentflow · Block

Verification

Run the JVM and publication gates:

./gradlew \
  :mermaid-core:jvmTest \
  :mermaid-compose:jvmTest \
  verifyPublicationCoordinates

Run the samples:

./gradlew :sample:androidApp:installDebug
./gradlew :sample:desktopApp:run
./gradlew :sample:webApp:wasmJsBrowserDevelopmentRun

The Stable test report contains the complete cross-platform build and Native/Official visual reproduction commands.

License

CMP Mermaid is released under the MIT License. Translated Mermaid behavior and development-only reference assets retain their upstream notices in THIRD_PARTY_NOTICES.md.

About

Native Mermaid 12 renderer for Kotlin Multiplatform and Compose Multiplatform. Android, iOS, Desktop and Web.

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages