Class: Marvi::Diagram

Inherits:
Object
  • Object
show all
Defined in:
lib/marvi/diagram.rb

Overview

Renders a subset of Mermaid diagrams as Unicode box-drawing art.

The public entry point returns an array of Span lines (one array of Spans per visual line), or nil when the diagram type or syntax is unsupported. Callers are expected to fall back to a plain code block when nil is returned.

Defined Under Namespace

Modules: BoxDrawing Classes: ClassRenderer, FlowchartRenderer, Grid, SequenceRenderer, StateRenderer

Constant Summary collapse

COLOR =
:cyan
WIDE_FILLER =
""
ARROW =

Renders ‘stateDiagram`/`stateDiagram-v2` as an aligned list of transitions. A list (rather than a 2D layout) keeps cyclic state machines renderable and preserves transition labels. Each [*] terminal becomes a start/end marker.

"──▶"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code, max_width) ⇒ Diagram

Returns a new instance of Diagram.



22
23
24
25
# File 'lib/marvi/diagram.rb', line 22

def initialize(code, max_width)
  @code = code
  @max_width = max_width
end

Class Method Details

.render(code, max_width: 80) ⇒ Object



15
16
17
18
19
20
# File 'lib/marvi/diagram.rb', line 15

def self.render(code, max_width: 80)
  new(code, max_width).render
rescue
  # Never let a malformed diagram crash rendering; fall back to a code block.
  nil
end

Instance Method Details

#renderObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/marvi/diagram.rb', line 27

def render
  lines = @code.lines.map(&:chomp).reject { |l| l.strip.empty? || l.strip.start_with?("%%") }
  return nil if lines.empty?

  header = lines.first.strip
  body = lines[1..]
  case header
  when /\A(?:graph|flowchart)\s+(TD|TB|LR|RL)\b/
    FlowchartRenderer.new(Regexp.last_match(1), body, @max_width).render
  when /\A(?:graph|flowchart)\b/
    FlowchartRenderer.new("TD", body, @max_width).render
  when /\AsequenceDiagram\b/
    SequenceRenderer.new(body, @max_width).render
  when /\AclassDiagram\b/
    ClassRenderer.new(body, @max_width).render
  when /\AstateDiagram(?:-v2)?\b/
    StateRenderer.new(body, @max_width).render
  end
end