BeautifulMermaid

repository·main·Indexed 43 days ago

https://github.com/lukilabs/beautiful-mermaid-swift

A native Swift implementation for rendering Mermaid diagrams—including Flowcharts, State, Sequence, Class, ER, and XY Charts—without WebViews or JavaScript. It utilizes the ELK layout engine and provides components for SwiftUI (MermaidDiagramView), UIKit, and AppKit (MermaidView), as well as tools for exporting diagrams as images, SVGs, or ASCII art via MermaidRenderer.

Tokens
2.4K
Snippets
10
Records
14
Agent score
7%

What's inside BeautifulMermaid

  1. Supported Mermaid diagram types

    main

    BeautifulMermaid supports rendering the following Mermaid diagram types:

    • Flowcharts (graph or flowchart)
    • State Diagrams (stateDiagram-v2)
    • Sequence Diagrams (sequenceDiagram)
    • Class Diagrams (classDiagram)
    • ER Diagrams (erDiagram)
    • XY Charts (xychart-beta)

    Note that the parser handles standard Mermaid syntax for these types, but has specific limitations regarding advanced features.

  2. Configure Diagram Themes

    main

    Themes can be created using a minimal two-color approach or a fully enriched configuration.

    Two-Color Theming

    Provide only background and foreground colors; the system derives the rest.

    Enriched Theming

    Add optional colors for fine-grained control over lines, accents, surfaces, and borders.

    VS Code / Shiki Import

    Convert Shiki-compatible JSON themes into DiagramTheme objects.

    // Two-color minimal theme
    let theme = DiagramTheme(
        background: "#1a1b26",
        foreground: "#c0caf5"
    )
    
    // Enriched theme
    let enrichedTheme = DiagramTheme(
        background: "#1a1b26",
        foreground: "#c0caf5",
        line: "#565f89",
        accent: "#7aa2f7",
        muted: "#414868",
        surface: "#24283b",
        border: "#414868"
    )
    
    // Shiki import
    let shikiTheme = DiagramTheme.ShikiTheme(
        type: "dark",
        colors: [
            "editor.background": "#1e1e1e",
            "editor.foreground": "#d4d4d4",
            "focusBorder": "#007acc"
        ],
        tokenColors: []
    )
    let themeFromShiki = DiagramTheme.fromShikiTheme(shikiTheme)
  3. Set diagram layout direction via Mermaid syntax

    main

    The direction of the diagram (e.g., top-to-bottom vs. left-to-right) is controlled directly within the Mermaid source code string using the following syntax:

    • graph TD or graph TB: Top to bottom (default)
    • graph BT: Bottom to top
    • graph LR: Left to right
    • graph RL: Right to left
  4. Quick Start: Render Mermaid diagrams to various formats

    main

    Use MermaidRenderer to convert Mermaid source code into images, SVGs, or ASCII art. The library supports synchronous rendering for immediate results.

    import BeautifulMermaid
    
    let mermaidCode = """
    graph TD
        A[Start] --> B{Decision}
        B -->|Yes| C[Do Something]
        B -->|No| D[Do Something Else]
        C --> E[End]
        D --> E
    """
    
    // Render as image
    let image = try MermaidRenderer.renderImage(source: mermaidCode)
    
    // Render as SVG
    let svg = try MermaidRenderer.renderSVG(source: mermaidCode, theme: .tokyoNight)
    
    // Render as ASCII art
    let ascii = try MermaidRenderer.renderASCII(source: mermaidCode, theme: .zincDark)
  5. Install BeautifulMermaid via Swift Package Manager

    main

    Add BeautifulMermaid to your Package.swift dependencies and include the BeautifulMermaid product in your target dependencies.

    dependencies: [
        .package(url: "https://github.com/lukilabs/beautiful-mermaid-swift", from: "1.0.0")
    ]
    
    // In your target:
    .target(
        name: "YourTarget",
        dependencies: [.product(name: "BeautifulMermaid", package: "beautiful-mermaid-swift")]
    )
  6. Use MermaidDiagramView in SwiftUI

    main

    Integrate Mermaid diagrams into SwiftUI views using the MermaidDiagramView. You can provide the Mermaid source string and an optional DiagramTheme.

    import SwiftUI
    import BeautifulMermaid
    
    struct ContentView: View {
        var body: some View {
            MermaidDiagramView(
                source: "graph TD; A-->B; B-->C;",
                theme: .catppuccinMocha
            )
        }
    }
  7. Use MermaidView in UIKit or AppKit

    main

    For imperative UI frameworks, use MermaidView, which is a native UIView (iOS) or NSView (macOS) subclass. Set the source and theme properties directly on the view instance.

    import BeautifulMermaid
    
    let mermaidView = MermaidView(frame: CGRect(x: 0, y: 0, width: 400, height: 300))
    mermaidView.source = "graph TD; A-->B; B-->C;"
    mermaidView.theme = .catppuccinMocha
    view.addSubview(mermaidView)
  8. Export diagrams as PNG or JPEG data

    main

    Use MermaidImageRenderer to export diagrams as high-quality image data. You can configure the theme and scale (for resolution/DPI) before rendering.

    let renderer = MermaidImageRenderer()
    renderer.theme = .dracula
    renderer.scale = 3.0
    
    let pngData = try renderer.renderPNG(from: mermaidCode)
    let jpegData = try renderer.renderJPEG(from: mermaidCode, quality: 0.9)
  9. Configure layout spacing and padding

    main

    You can fine-tune the diagram layout by providing a LayoutConfig object to a MermaidImageRenderer. This allows you to control the spacing between nodes, layers, and components, as well as the overall padding.

    let config = LayoutConfig(
        padding: 20,
        nodeSpacing: 40,
        layerSpacing: 60,
        componentSpacing: 40
    )
    
    let renderer = MermaidImageRenderer()
    renderer.layoutConfig = config
  10. Configure Mermaid rendering options

    main

    When using MermaidRenderer.renderImage, you can customize the output by specifying a theme and a scale. The scale parameter controls the Retina scale of the resulting image (defaults to 2.0).

    let image = try MermaidRenderer.renderImage(
        source: code,
        theme: .tokyoNight,
        scale: 2.0                // Retina scale (default: 2.0)
    )
  11. Perform Async Rendering

    main

    To avoid blocking the main thread during heavy diagram generation, use the async variants of the MermaidRenderer methods.

    let image = try await MermaidRenderer.renderImageAsync(source: mermaidCode, theme: .nord)
    let svg = try await MermaidRenderer.renderSVGAsync(source: mermaidCode)
    let ascii = try await MermaidRenderer.renderASCIIAsync(source: mermaidCode)