mermaid 0.0.6 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +21 -0
  3. data/README.md +120 -111
  4. data/Rakefile +35 -3
  5. data/lib/mermaid/inline_title.rb +13 -0
  6. data/lib/mermaid/renderer.rb +105 -0
  7. data/lib/mermaid/renderers/class_renderer.rb +56 -0
  8. data/lib/mermaid/renderers/er_renderer.rb +43 -0
  9. data/lib/mermaid/renderers/flowchart_renderer.rb +27 -0
  10. data/lib/mermaid/renderers/gantt_renderer.rb +31 -0
  11. data/lib/mermaid/renderers/gitgraph_renderer.rb +50 -0
  12. data/lib/mermaid/renderers/pie_renderer.rb +34 -0
  13. data/lib/mermaid/renderers/state_renderer.rb +37 -0
  14. data/lib/mermaid/renderers/timeline_renderer.rb +24 -0
  15. data/lib/mermaid/to_mermaid.rb +9 -0
  16. data/lib/mermaid/version.rb +1 -1
  17. data/lib/mermaid.rb +8 -26
  18. data/sig/mermaid.rbs +64 -0
  19. metadata +26 -89
  20. data/lib/mermaid/class_diagram_renderer.rb +0 -45
  21. data/lib/mermaid/element_renderers/edge_renderer.rb +0 -19
  22. data/lib/mermaid/element_renderers/erd_entity_renderer.rb +0 -37
  23. data/lib/mermaid/element_renderers/erd_relationship_renderer.rb +0 -44
  24. data/lib/mermaid/element_renderers/node_renderer.rb +0 -16
  25. data/lib/mermaid/element_renderers/relationship_renderer.rb +0 -24
  26. data/lib/mermaid/element_renderers/slice_renderer.rb +0 -16
  27. data/lib/mermaid/element_renderers/state_renderer.rb +0 -15
  28. data/lib/mermaid/element_renderers/task_renderer.rb +0 -15
  29. data/lib/mermaid/element_renderers/transition_renderer.rb +0 -17
  30. data/lib/mermaid/er_diagram_renderer.rb +0 -24
  31. data/lib/mermaid/flowchart_diagram_renderer.rb +0 -23
  32. data/lib/mermaid/gantt_diagram_renderer.rb +0 -20
  33. data/lib/mermaid/gitgraph_diagram_renderer.rb +0 -113
  34. data/lib/mermaid/pie_diagram_renderer.rb +0 -16
  35. data/lib/mermaid/state_diagram_renderer.rb +0 -42
  36. data/lib/mermaid/timeline_diagram_renderer.rb +0 -29
  37. data/sig/diagrams/base.rbs +0 -8
  38. data/sig/diagrams/class_diagram.rbs +0 -18
  39. data/sig/diagrams/elements/edge.rbs +0 -16
  40. data/sig/diagrams/elements/erd_entity.rbs +0 -11
  41. data/sig/diagrams/elements/erd_relationship.rbs +0 -11
  42. data/sig/diagrams/elements/node.rbs +0 -15
  43. data/sig/diagrams/elements/relationship.rbs +0 -15
  44. data/sig/diagrams/elements/slice.rbs +0 -16
  45. data/sig/diagrams/elements/state.rbs +0 -15
  46. data/sig/diagrams/elements/task.rbs +0 -17
  47. data/sig/diagrams/elements/transition.rbs +0 -16
  48. data/sig/diagrams/er_diagram.rbs +0 -9
  49. data/sig/diagrams/flowchart_diagram.rbs +0 -14
  50. data/sig/diagrams/gantt_diagram.rbs +0 -14
  51. data/sig/diagrams/pie_diagram.rbs +0 -14
  52. data/sig/diagrams/state_diagram.rbs +0 -18
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 82eb20d2315cbe0cf01d624664b573947d891b7f142d531a47805531724232b1
4
- data.tar.gz: '02801805d9f7361fd32e575f0db38cfcafbcf92a542c47eae9990c554c2d1924'
3
+ metadata.gz: be5e26672e900e41c84079b12e8010150540563297b2fee6199c4be2d9458458
4
+ data.tar.gz: 16202df2600f08fc7da8421d89ec8e8b347f71768d4c723bcec731265aa5df3c
5
5
  SHA512:
6
- metadata.gz: 471e35230eeab9df0e9dd6bb4d42bdfc386027af84defb2e20a2b3ca4b0244fa68dc30090a2a5480e06279e94862a58daaa954eaeafca22ffda9abb65932a85a
7
- data.tar.gz: 06bc39252e24a72bec57c1566876921010d1319ee171571d61d8acc1ec499038d70dc311201ad6702d8ef45372f10b3d415eb66251f08777a773d429ca92140e
6
+ metadata.gz: '031969ca583a876589d2f8cc28c82d0809176fb04b446ab9bfd8bea6a876bcbfee0d7a5dce0f7d224cd1ca520fa311a314e06aa89200fa7bd728108217e02e65'
7
+ data.tar.gz: a3a4d42add66a0b7d29277d6582d8182ef45c084dcadae35f039730770d499d96a3e1b75e75a997b21d37eefe4a78f402505e1ea8ef5c810c6e2d20d0f34a9b2
data/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.1.0](https://github.com/seuros/mermaid-ruby/compare/mermaid/v0.0.6...mermaid/v0.1.0) (2026-11-16)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * one renderer per diagram type, valid Mermaid 11 output
9
+
10
+ ### Features
11
+
12
+ * one renderer per diagram type, valid Mermaid 11 output ([0f97cdb](https://github.com/seuros/mermaid-ruby/commit/0f97cdbea415c7485df267fc6abfe870001dad1d))
13
+
14
+
15
+ ### Bug Fixes
16
+
17
+ * check the gantt year 0100 floor against Mermaid ([680ca93](https://github.com/seuros/mermaid-ruby/commit/680ca93b7891ba31bc7b01523905d7957d60420a))
18
+ * keep explicit merge types, declare the gantt date format; check evaluated dates ([c48bc04](https://github.com/seuros/mermaid-ruby/commit/c48bc04942fcc8be4d377fc1d8be5e7d12cbd91d))
19
+ * lock for JRuby and the public npm registry ([b86107b](https://github.com/seuros/mermaid-ruby/commit/b86107b3ee7564d3389d07559a0344fc97f66504))
20
+ * parser check uses js-yaml 4.3.2 ([5dbfca4](https://github.com/seuros/mermaid-ruby/commit/5dbfca43e7fa0683f031b7fa1cd83430362e3e4b))
21
+ * render the gitGraph program, cherry-picks included; stronger parse check ([78bc1a0](https://github.com/seuros/mermaid-ruby/commit/78bc1a0a5449531cdbcc4c20fd3002d582483394))
22
+ * text stays text, ids are aliased, output checked by Mermaid's parser ([0fbbf5f](https://github.com/seuros/mermaid-ruby/commit/0fbbf5fe2fe3b63c33742b739601a55eaa1539df))
23
+
3
24
  ## [0.0.6](https://github.com/seuros/mermaid-ruby/compare/mermaid/v0.0.5...mermaid/v0.0.6) (2025-08-14)
4
25
 
5
26
 
data/README.md CHANGED
@@ -1,139 +1,148 @@
1
- # Mermaid Ruby
1
+ # mermaid
2
2
 
3
3
  [![Gem Version](https://badge.fury.io/rb/mermaid.svg)](https://badge.fury.io/rb/mermaid)
4
- [![Build Status](https://github.com/seuros/mermaid-ruby/actions/workflows/ci.yml/badge.svg)](https://github.com/seuros/mermaid-ruby/actions/workflows/ci.yml)
5
4
 
6
- This gem provides Mermaid syntax generation capabilities for diagram objects created using the [`diagram`](https://github.com/seuros/diagram-ruby) gem.
5
+ [Mermaid](https://mermaid.js.org) text for the diagrams of the
6
+ [diagram](https://github.com/seuros/diagram-ruby) gem. Requiring it gives
7
+ every diagram a `to_mermaid` method; the diagrams themselves stay plain data.
7
8
 
8
- It achieves this by adding renderer to the `diagram` gem (like `Diagrams::ClassDiagram`, `Diagrams::StateDiagram`, etc.) to add a `#to_mermaid` instance method.
9
+ Supported: flowchart, state, class, ER, Gantt, pie, timeline and git graph.
10
+ Ruby 4.0+.
9
11
 
10
12
  ## Installation
11
13
 
12
- Add these lines to your application's Gemfile:
13
-
14
14
  ```ruby
15
- gem 'diagram' # The base gem for creating diagram objects
16
- gem 'mermaid' # This gem, for generating Mermaid syntax
15
+ gem 'mermaid'
17
16
  ```
18
17
 
19
- And then execute:
18
+ ## Usage
20
19
 
21
- ```bash
22
- $ bundle install
20
+ ```ruby
21
+ require 'mermaid'
22
+
23
+ door = Diagrams::StateDiagram.new(title: 'Door')
24
+ door.add_state(id: 'closed')
25
+ door.add_state(id: 'open', label: 'Open')
26
+ door.add_transition(source_state_id: '*', target_state_id: 'closed')
27
+ door.add_transition(source_state_id: 'closed', target_state_id: 'open', label: 'push', guard: 'unlocked')
28
+
29
+ puts door.to_mermaid
30
+ # ---
31
+ # title: "Door"
32
+ # ---
33
+ # stateDiagram-v2
34
+ # closed
35
+ # open : Open
36
+ # [*] --> closed
37
+ # closed --> open : push [unlocked]
23
38
  ```
24
39
 
25
- Or install it yourself as:
40
+ A title goes to the YAML front matter, except for pie, Gantt and timeline
41
+ diagrams, which have a `title` statement of their own:
26
42
 
27
- ```bash
28
- $ gem install diagram mermaid
29
- ```
43
+ ```ruby
44
+ pets = Diagrams::PieDiagram.new(title: 'Pets')
45
+ pets.add_slice(label: 'Dogs', value: 3)
46
+ pets.add_slice(label: 'Cats', value: 1.5)
30
47
 
31
- ## Usage
48
+ puts pets.to_mermaid
49
+ # pie
50
+ # title Pets
51
+ # "Dogs" : 3
52
+ # "Cats" : 1.5
53
+ ```
32
54
 
33
- Simply require the `mermaid` gem after requiring `diagrams`. This will automatically add the `#to_mermaid` method to the diagram classes.
55
+ ER attributes render their keys the Mermaid way (`int id PK, FK`), and a
56
+ relationship is drawn solid only when it is identifying:
34
57
 
35
58
  ```ruby
36
- require 'diagrams'
37
- require 'mermaid' # This applies the patches
38
-
39
- # --- Example: State Diagram ---
40
- state_a = Diagrams::Elements::State.new(id: 'A', label: 'State A')
41
- state_b = Diagrams::Elements::State.new(id: 'B')
42
- transition1 = Diagrams::Elements::Transition.new(source_state_id: '*', target_state_id: 'A')
43
- transition2 = Diagrams::Elements::Transition.new(source_state_id: 'A', target_state_id: 'B', label: 'Event X')
44
-
45
- state_diagram = Diagrams::StateDiagram.new(
46
- states: [state_a, state_b],
47
- transitions: [transition1, transition2]
48
- )
49
-
50
- puts state_diagram.to_mermaid
51
- # Output:
52
- # stateDiagram-v2
53
- # A : State A
54
- # [*] --> A
55
- # A --> B : Event X
56
-
57
- # --- Example: Class Diagram ---
58
- class_animal = Diagrams::Elements::ClassEntity.new(name: 'Animal', attributes: ['+String name'])
59
- class_dog = Diagrams::Elements::ClassEntity.new(name: 'Dog', attributes: ['+String breed'], methods: ['+bark() void'])
60
- rel_inheritance = Diagrams::Elements::Relationship.new(
61
- source_class_name: 'Dog',
62
- target_class_name: 'Animal',
63
- type: 'inheritance'
64
- )
65
-
66
- class_diagram = Diagrams::ClassDiagram.new(
67
- classes: [class_animal, class_dog],
68
- relationships: [rel_inheritance]
69
- )
70
-
71
- puts class_diagram.to_mermaid
72
- # Output:
73
- # classDiagram
74
- # class Animal {
75
- # +String name
76
- # }
77
- # class Dog {
78
- # +String breed
79
- # +bark() void
80
- # }
81
- # Dog <|-- Animal
82
-
83
- # --- Example: Flowchart ---
84
- node1 = Diagrams::Elements::Node.new(id: 'n1', label: 'Start')
85
- node2 = Diagrams::Elements::Node.new(id: 'n2', label: 'Process')
86
- edge1 = Diagrams::Elements::Edge.new(source_id: 'n1', target_id: 'n2', label: 'Go')
87
-
88
- flowchart = Diagrams::FlowchartDiagram.new(nodes: [node1, node2], edges: [edge1])
89
-
90
- puts flowchart.to_mermaid
91
- # Output:
92
- # graph TD
93
- # n1["Start"]
94
- # n2["Process"]
95
- # n1 -- "Go" --> n2
96
-
97
- # --- Example: Pie Chart ---
98
- slice1 = Diagrams::Elements::Slice.new(label: 'Work', value: 8)
99
- slice2 = Diagrams::Elements::Slice.new(label: 'Sleep', value: 8)
100
- slice3 = Diagrams::Elements::Slice.new(label: 'Play', value: 8)
101
-
102
- pie_chart = Diagrams::PieDiagram.new(title: 'Daily Routine', slices: [slice1, slice2, slice3])
103
-
104
- puts pie_chart.to_mermaid
105
- # Output:
106
- # pie
107
- # title Daily Routine
108
- # "Work" : 8
109
- # "Sleep" : 8
110
- # "Play" : 8
111
-
112
- # --- Example: Gantt Chart ---
113
- gantt_chart = Diagrams::GanttDiagram.new(title: 'Project Timeline')
114
- gantt_chart.add_task(id: 't1', label: 'Phase 1', start: '2024-01-01', duration: '10d')
115
- gantt_chart.add_task(id: 't2', label: 'Phase 2', start: '2024-01-11', duration: '10d')
116
-
117
- puts gantt_chart.to_mermaid
118
- # Output:
119
- # gantt
120
- # title Project Timeline
121
- # section Default Section
122
- # Phase 1 :t1, 2024-01-01, 10d
123
- # Phase 2 :t2, 2024-01-11, 10d
59
+ shop = Diagrams::ERDiagram.new
60
+ shop.add_entity(name: 'CUSTOMER', attributes: [{ type: 'int', name: 'id', keys: [:PK] }])
61
+ shop.add_entity(name: 'ORDER')
62
+ shop.add_relationship(entity1: 'CUSTOMER', entity2: 'ORDER',
63
+ cardinality1: :ONE_ONLY, cardinality2: :ZERO_OR_MORE, label: 'places')
64
+
65
+ puts shop.to_mermaid
66
+ # erDiagram
67
+ # "CUSTOMER" {
68
+ # int id PK
69
+ # }
70
+ # "ORDER"
71
+ # "CUSTOMER" ||..o{ "ORDER" : "places"
72
+ ```
73
+
74
+ A git graph is already a gitGraph program (the diagram gem models Mermaid's
75
+ statements and refusals), so each statement renders as the one it models.
76
+ A cherry-pick names its source; Mermaid generates the picked commit's id:
124
77
 
78
+ ```ruby
79
+ git = Diagrams::GitgraphDiagram.new
80
+ git.commit(id: 'init')
81
+ git.branch(name: 'feature', order: 1)
82
+ git.commit(id: 'work', message: 'the work')
83
+ git.checkout(name: 'main')
84
+ git.commit(id: 'fix', tags: ['v1.0.1'])
85
+ git.merge(branch: 'feature', id: 'merge', tags: ['v1'])
86
+ git.checkout(name: 'feature')
87
+ git.cherry_pick(commit_id: 'fix')
88
+
89
+ puts git.to_mermaid
90
+ # gitGraph
91
+ # commit id: "init"
92
+ # branch "feature" order: 1
93
+ # commit id: "work" msg: "the work"
94
+ # checkout "main"
95
+ # commit id: "fix" tag: "v1.0.1"
96
+ # merge "feature" id: "merge" tag: "v1"
97
+ # checkout "feature"
98
+ # cherry-pick id: "fix"
125
99
  ```
126
100
 
127
- ## Development
101
+ ## Text and names
102
+
103
+ Text reaches Mermaid as text. Any character Mermaid could read as syntax (a
104
+ quote, colon, `#`, `%`, a line break, markup) is written as a numeric entity
105
+ (`#58;`), which Mermaid turns back into the character when it draws; names
106
+ Mermaid cannot read as identifiers are aliased (`n0`, `s0`, `c0`) and shown
107
+ as their label:
108
+
109
+ ```ruby
110
+ states = Diagrams::StateDiagram.new
111
+ states.add_state(id: 'Billing::Invoice', label: 'Paid: done')
128
112
 
129
- After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
113
+ puts states.to_mermaid
114
+ # stateDiagram-v2
115
+ # state "Paid#58; done" as s0
116
+ ```
130
117
 
131
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `lib/mermaid/version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
118
+ What Mermaid cannot carry is refused with `ArgumentError` rather than drawn
119
+ differently: class members that would break the class block or be read as
120
+ the wrong kind of member (members are Mermaid notation, such as
121
+ `+save() bool`; an annotation such as `<<interface>>` is not a member), a
122
+ main branch name that needs entity codes, and titles holding Mermaid's entity
123
+ placeholders. Gantt tasks need no refusal here: the diagram gem only accepts
124
+ the forms Mermaid evaluates. Rendering a diagram class that has no renderer
125
+ raises `TypeError`.
126
+
127
+ `rake parse` renders a battery of diagrams, hostile text included, parses each
128
+ with Mermaid's own parser (Node; `npm ci --prefix parser` first) and checks
129
+ that Mermaid reads back the same model: which node is which, labels, links and
130
+ their kind, values, commits and lanes, and the start and end Mermaid computes
131
+ for every Gantt task (Gantt output declares `dateFormat YYYY-MM-DD`, without
132
+ which Mermaid ignores end dates). Every case also round-trips through JSON,
133
+ negative controls (mutated output) must be rejected, and the one deliberate
134
+ difference (a duplicate commit id, which Mermaid overwrites and the diagram
135
+ gem refuses) is confirmed on both sides.
132
136
 
133
- ## Contributing
137
+ ## Development
134
138
 
135
- Bug reports and pull requests are welcome on GitHub at https://github.com/seuros/mermaid-ruby.
139
+ ```bash
140
+ bundle install
141
+ bundle exec rake # tests (padded_cell on CRuby), RuboCop, RBS
142
+ bundle exec rake minitest
143
+ npm ci --prefix parser && bundle exec rake parse # Mermaid's parser check
144
+ ```
136
145
 
137
146
  ## License
138
147
 
139
- The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
148
+ MIT.
data/Rakefile CHANGED
@@ -1,8 +1,40 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'bundler/gem_tasks'
4
- require 'minitest/test_task'
4
+ require 'rake/testtask'
5
+ require 'shellwords'
5
6
 
6
- Minitest::TestTask.create
7
+ Rake::TestTask.new(:minitest) do |t|
8
+ t.libs << 'test'
9
+ t.libs << 'lib'
10
+ t.test_files = FileList['test/**/*_test.rb']
11
+ t.verbose = true
12
+ end
7
13
 
8
- task default: :test
14
+ # Both branches define :test, once per engine.
15
+ # rubocop:disable Rake/DuplicateTask
16
+ desc 'Run the test suite (padded_cell on CRuby, plain Minitest elsewhere)'
17
+ if RUBY_ENGINE == 'ruby'
18
+ task :test do
19
+ sh 'padded_cell', *Shellwords.split(ENV.fetch('TESTOPTS', ''))
20
+ end
21
+ else
22
+ task test: :minitest
23
+ end
24
+ # rubocop:enable Rake/DuplicateTask
25
+
26
+ require 'rubocop/rake_task'
27
+
28
+ RuboCop::RakeTask.new
29
+
30
+ desc 'Validate the RBS signatures in sig/ against the diagram gem'
31
+ task :rbs do
32
+ sh 'rbs', '-I', 'sig', '-I', File.join(Gem.loaded_specs.fetch('diagram').full_gem_path, 'sig'), 'validate'
33
+ end
34
+
35
+ desc "Parse every renderer's output with Mermaid's own parser (needs Node: npm ci --prefix parser)"
36
+ task :parse do
37
+ ruby '-Ilib', 'parser/check.rb'
38
+ end
39
+
40
+ task default: %i[test rubocop rbs]
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mermaid
4
+ # For diagram types with a `title` statement of their own (pie, gantt,
5
+ # timeline): the title opens the body instead of going to the front matter.
6
+ module InlineTitle
7
+ private
8
+
9
+ def settings = super.except(:title)
10
+
11
+ def body = [*("title #{text(diagram.title)}" if diagram.title), *super]
12
+ end
13
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mermaid
4
+ # Turns one diagram into Mermaid text: optional YAML front matter (title,
5
+ # config), the diagram keyword, then the body indented by two spaces.
6
+ # Each subclass renders one diagram class: it names its keyword and lists
7
+ # its body lines.
8
+ #
9
+ # Text from the model never reaches Mermaid's grammars raw. Labels go
10
+ # through #text, ids through #names, and a value Mermaid cannot carry
11
+ # faithfully is refused with ArgumentError rather than drawn differently.
12
+ class Renderer
13
+ # Characters every Mermaid text slot reads as themselves. Anything else
14
+ # becomes a numeric entity (#58;), which Mermaid swaps for a placeholder
15
+ # before lexing and back for the character in the drawn SVG: so no
16
+ # character can end a slot, start a comment or a line, or open markup.
17
+ SAFE = %r{[A-Za-z0-9 _.,!?()\[\]+*/=@$'-]}
18
+ # Mermaid's placeholders for entities; text holding them would be decoded.
19
+ PLACEHOLDERS = /fl°|¶ß/
20
+ # A name Mermaid reads as a plain identifier.
21
+ PLAIN = /\A[A-Za-z][A-Za-z0-9_]*\z/
22
+
23
+ class << self
24
+ def render(diagram)
25
+ renderer = Renderer.registry.fetch(diagram.class) do
26
+ raise TypeError, "no Mermaid renderer for #{diagram.class}"
27
+ end
28
+ renderer.new(diagram).render
29
+ end
30
+
31
+ def registry = @registry ||= {}
32
+
33
+ private
34
+
35
+ def renders(diagram_class, keyword)
36
+ Renderer.registry[diagram_class] = self
37
+ define_method(:keyword) { keyword }
38
+ end
39
+ end
40
+
41
+ def initialize(diagram)
42
+ @diagram = diagram
43
+ end
44
+
45
+ def render = [*front_matter, keyword, *body.map { " #{it}" }].join("\n")
46
+
47
+ private
48
+
49
+ attr_reader :diagram
50
+
51
+ # Front matter settings. The title goes here unless the diagram type has
52
+ # its own title statement (see InlineTitle).
53
+ def settings = { title: diagram.title }.compact
54
+
55
+ # YAML is read before entities are, so values go in as JSON strings; only
56
+ # Mermaid's own entity placeholders cannot survive the drawing step.
57
+ def front_matter
58
+ return [] if settings.empty?
59
+
60
+ ['---', *yaml(settings), '---']
61
+ end
62
+
63
+ def yaml(hash, indent = '')
64
+ hash.flat_map do |key, value|
65
+ next ["#{indent}#{key}:", *yaml(value, "#{indent} ")] if value.is_a?(Hash)
66
+ raise ArgumentError, "Mermaid cannot show #{key} #{value.inspect}" if value.match?(PLACEHOLDERS)
67
+
68
+ ["#{indent}#{key}: #{value.to_json}"]
69
+ end
70
+ end
71
+
72
+ # +value+ as text Mermaid shows unchanged. Spaces at either end are
73
+ # encoded too, since grammars trim them.
74
+ def text(value)
75
+ encoded = value.each_char.map { it.match?(SAFE) ? it : "##{it.ord};" }.join
76
+ encoded.sub(/\A +/) { '#32;' * it.size }.sub(/ +\z/) { '#32;' * it.size }
77
+ end
78
+
79
+ # Text that starts a line: a first word Mermaid would take for a
80
+ # statement keyword gets its first letter encoded.
81
+ def line_start(value, keywords)
82
+ encoded = text(value)
83
+ return encoded unless keywords.include?(value[/\A\S*/].downcase)
84
+
85
+ "##{encoded.ord};#{encoded[1..]}"
86
+ end
87
+
88
+ # Mermaid names for model ids, as id => name. A plain identifier that is
89
+ # not reserved names itself; any other id gets the first free
90
+ # "<prefix><n>", and the renderer shows the original as its label.
91
+ def names(ids, prefix, reserved)
92
+ plain = ids.select { it.match?(PLAIN) && !reserved.include?(it.downcase) }.to_set
93
+ count = -1
94
+ ids.to_h do |id|
95
+ next [id, id] if plain.include?(id)
96
+
97
+ count += 1
98
+ count += 1 while plain.include?("#{prefix}#{count}")
99
+ [id, "#{prefix}#{count}"]
100
+ end
101
+ end
102
+
103
+ def quote(value) = %("#{text(value)}")
104
+ end
105
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mermaid
4
+ module Renderers
5
+ # Diagrams::ClassDiagram. Arrows point from the source class (parent,
6
+ # whole, interface) to the target. A class name Mermaid cannot read as a
7
+ # plain name is aliased (c0, c1, ...) and shown as its label. Members are
8
+ # Mermaid member notation ("+String name", "+save() bool") and render as
9
+ # written; Mermaid tells operations from attributes by their parentheses,
10
+ # so a member it would misfile, or one that would break the class block,
11
+ # is refused.
12
+ class ClassRenderer < Renderer
13
+ ARROWS = {
14
+ inheritance: '<|--', composition: '*--', aggregation: 'o--', association: '-->',
15
+ dependency: '..>', realization: '<|..', link: '--'
16
+ }.freeze
17
+ RESERVED = %w[class namespace note style classdef cssclass callback call link click direction end default o
18
+ acctitle accdescr].freeze
19
+ OPERATION = /\(.*\)/
20
+
21
+ renders Diagrams::ClassDiagram, 'classDiagram'
22
+
23
+ private
24
+
25
+ # Mermaid rejects a class diagram without statements.
26
+ def body
27
+ name = names(diagram.classes.map(&:name), 'c', RESERVED)
28
+ lines = [*diagram.classes.flat_map { klass(it, name[it.name]) },
29
+ *diagram.relationships.map { relationship(it, name) }]
30
+ lines.empty? ? ['direction TB'] : lines
31
+ end
32
+
33
+ def klass(entity, name)
34
+ head = name == entity.name ? "class #{name}" : "class #{name}[#{quote(entity.name)}]"
35
+ members = [*entity.attributes.map { member(it, false) }, *entity.operations.map { member(it, true) }]
36
+ members.empty? ? [head] : ["#{head} {", *members.map { " #{it}" }, '}']
37
+ end
38
+
39
+ def member(member, operation)
40
+ raise ArgumentError, "Mermaid cannot show class member #{member.inspect}" if member.match?(/[{}\n\r]/)
41
+ raise ArgumentError, "Mermaid would read #{member.inspect} as an annotation" if member.start_with?('<<')
42
+ unless member.match?(OPERATION) == operation
43
+ raise ArgumentError, "Mermaid would show #{member.inspect} as an #{operation ? 'attribute' : 'operation'}"
44
+ end
45
+
46
+ member
47
+ end
48
+
49
+ def relationship(relationship, name)
50
+ line = "#{name[relationship.source_class_name]} #{ARROWS.fetch(relationship.type)} " \
51
+ "#{name[relationship.target_class_name]}"
52
+ relationship.label ? "#{line} : #{text(relationship.label)}" : line
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mermaid
4
+ module Renderers
5
+ # Diagrams::ERDiagram. Entity names are quoted, keys render as Mermaid keys
6
+ # ("PK, FK, UK"), an identifying relationship as a solid line and a
7
+ # non-identifying one dashed. Mermaid requires a relationship label, so a
8
+ # missing one is "".
9
+ class ERRenderer < Renderer
10
+ LEFT = { ZERO_OR_ONE: '|o', ONE_ONLY: '||', ZERO_OR_MORE: '}o', ONE_OR_MORE: '}|' }.freeze
11
+ RIGHT = { ZERO_OR_ONE: 'o|', ONE_ONLY: '||', ZERO_OR_MORE: 'o{', ONE_OR_MORE: '|{' }.freeze
12
+ # An attribute type or name Mermaid reads bare; others go in backticks.
13
+ WORD = /\A[*A-Za-z_][A-Za-z0-9\-_\[\]().,*]*\z/
14
+
15
+ renders Diagrams::ERDiagram, 'erDiagram'
16
+
17
+ private
18
+
19
+ def body = [*diagram.entities.flat_map { entity(it) }, *diagram.relationships.map { relationship(it) }]
20
+
21
+ def entity(entity)
22
+ return [quote(entity.name)] if entity.attributes.empty?
23
+
24
+ ["#{quote(entity.name)} {", *entity.attributes.map { " #{attribute(it)}" }, '}']
25
+ end
26
+
27
+ def attribute(attribute)
28
+ keys = attribute.keys.join(', ') unless attribute.keys.empty?
29
+ [word(attribute.type), word(attribute.name), keys,
30
+ (quote(attribute.comment) if attribute.comment)].compact.join(' ')
31
+ end
32
+
33
+ def word(value) = value.match?(WORD) ? value : "`#{text(value)}`"
34
+
35
+ def relationship(relationship)
36
+ line = relationship.identifying ? '--' : '..'
37
+ cardinality = "#{LEFT.fetch(relationship.cardinality1)}#{line}#{RIGHT.fetch(relationship.cardinality2)}"
38
+ label = quote(relationship.label.to_s)
39
+ "#{quote(relationship.entity1)} #{cardinality} #{quote(relationship.entity2)} : #{label}"
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mermaid
4
+ module Renderers
5
+ # Diagrams::FlowchartDiagram, top-down. Node ids Mermaid cannot read as
6
+ # plain names are aliased (n0, n1, ...); every node shows its label.
7
+ class FlowchartRenderer < Renderer
8
+ RESERVED = %w[end graph flowchart subgraph style linkstyle classdef class click call href direction default
9
+ acctitle accdescr].freeze
10
+
11
+ renders Diagrams::FlowchartDiagram, 'flowchart TD'
12
+
13
+ private
14
+
15
+ def body
16
+ name = names(diagram.nodes.map(&:id), 'n', RESERVED)
17
+ [*diagram.nodes.map { "#{name[it.id]}[#{quote(it.label)}]" },
18
+ *diagram.edges.map { edge(it, name) }]
19
+ end
20
+
21
+ def edge(edge, name)
22
+ arrow = edge.label ? "-->|#{quote(edge.label)}|" : '-->'
23
+ "#{name[edge.source_id]} #{arrow} #{name[edge.target_id]}"
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mermaid
4
+ module Renderers
5
+ # Diagrams::GanttDiagram. A task reads "label :status, id, start, duration";
6
+ # the model already holds them in the forms Mermaid evaluates.
7
+ class GanttRenderer < Renderer
8
+ prepend InlineTitle
9
+
10
+ KEYWORDS = %w[title section dateformat inclusiveenddates topaxis axisformat tickinterval includes excludes
11
+ todaymarker weekday weekend click call acctitle accdescr].freeze
12
+
13
+ renders Diagrams::GanttDiagram, 'gantt'
14
+
15
+ private
16
+
17
+ # Mermaid parses YYYY-MM-DD dates only once the format is declared;
18
+ # without it, end dates silently collapse to the start.
19
+ def body
20
+ tasks = diagram.sections.flat_map do |section|
21
+ [*("section #{text(section.title)}" if section.title), *section.tasks.map { task(it) }]
22
+ end
23
+ ['dateFormat YYYY-MM-DD', *tasks]
24
+ end
25
+
26
+ def task(task)
27
+ "#{line_start(task.label, KEYWORDS)} :#{[task.status, task.id, task.start, task.duration].compact.join(', ')}"
28
+ end
29
+ end
30
+ end
31
+ end