flowmaid 0.9.0

Mermaid-like diagram engine in pure std Rust (flowcharts + ER + UML class diagrams): hand-written parser, Sugiyama-style layout, SVG renderer, and an interactive scene API for drag-and-drop apps. Zero dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Core data model: graph, nodes, edges.

use std::collections::HashMap;

/// Flow direction of the diagram.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Default)]
pub enum Direction {
    /// Top-down. Alias: TB.
    #[default]
    TD,
    /// Left to right.
    LR,
    /// Right to left.
    RL,
    /// Bottom to top.
    BT,
}


/// Node shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
    /// `A[text]` — rectangle.
    Rect,
    /// `A(text)` — rounded corners.
    Rounded,
    /// `A([text])` — stadium / pill.
    Stadium,
    /// `A{text}` — diamond (decision).
    Diamond,
    /// `A((text))` — circle.
    Circle,
    /// `A(((text)))` — double circle (terminal).
    DoubleCircle,
    /// `A[(text)]` — cylinder (database).
    Cylinder,
    /// `A[[text]]` — subroutine.
    Subroutine,
    /// `A{{text}}` — hexagon.
    Hexagon,
    /// `A[/text/]` — parallelogram.
    Parallelogram,
    /// `A[\text\]` — parallelogram, slanted the other way.
    ParallelogramAlt,
}

/// Edge line style.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeKind {
    /// `-->` regular arrow.
    Arrow,
    /// `---` plain line, no arrowhead.
    Open,
    /// `-.->` dotted line with arrowhead.
    Dotted,
    /// `-.-` dotted line, no arrowhead.
    DottedOpen,
    /// `==>` thick line with arrowhead.
    Thick,
    /// `===` thick line, no arrowhead.
    ThickOpen,
    /// `~~~` invisible link — participates in layout (ranking /
    /// ordering) but is never drawn.
    Invisible,
}

impl EdgeKind {
    /// Whether renderers should draw an arrowhead.
    pub fn has_arrow(self) -> bool {
        matches!(self, EdgeKind::Arrow | EdgeKind::Dotted | EdgeKind::Thick)
    }
}

/// Custom per-node styling from Mermaid `style` / `classDef`
/// lines. `None` fields fall back to the shape's theme color
/// (see [`crate::style::shape_style`]).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct NodeStyle {
    /// `fill:#rrggbb`
    pub fill: Option<String>,
    /// `stroke:#rrggbb`
    pub stroke: Option<String>,
    /// `stroke-width:4px` (pixels)
    pub stroke_width: Option<f64>,
    /// `color:#rrggbb` — label text color.
    pub color: Option<String>,
}

impl NodeStyle {
    /// Overlay `over`'s set fields onto `self` (used to layer
    /// classDef under an explicit `style` line, which wins).
    pub fn apply_over(&mut self, over: &NodeStyle) {
        if let Some(v) = &over.fill {
            self.fill = Some(v.clone());
        }
        if let Some(v) = &over.stroke {
            self.stroke = Some(v.clone());
        }
        if let Some(v) = over.stroke_width {
            self.stroke_width = Some(v);
        }
        if let Some(v) = &over.color {
            self.color = Some(v.clone());
        }
    }
}

#[derive(Debug, Clone)]
pub struct Node {
    pub id: String,
    pub label: String,
    pub shape: Shape,
    /// Custom colors; empty = follow the shape theme.
    pub style: NodeStyle,
}

#[derive(Debug, Clone)]
pub struct Edge {
    pub from: usize,
    pub to: usize,
    pub label: Option<String>,
    pub kind: EdgeKind,
}

/// A `subgraph ... end` block: a titled cluster of nodes, possibly
/// nested. Membership is by node index; nested members belong to
/// the child, not the parent (walk `parent` links for the chain).
#[derive(Debug, Clone)]
pub struct Subgraph {
    pub id: String,
    pub title: String,
    /// Direct member node indices.
    pub nodes: Vec<usize>,
    /// Enclosing subgraph, when nested.
    pub parent: Option<usize>,
    /// Per-subgraph flow direction (`direction LR` inside the block).
    pub direction: Option<Direction>,
}

/// One endpoint of an edge that touches a subgraph — either a
/// regular node or a whole subgraph (its cluster box).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum End {
    Node(usize),
    Sub(usize),
}

/// An edge where at least one endpoint is a subgraph
/// (`CF --> VPC`). Kept apart from [`Edge`] so the flat node→node
/// path stays untouched; consumed only by the clustered scene.
#[derive(Debug, Clone)]
pub struct SubEdge {
    pub from: End,
    pub to: End,
    pub label: Option<String>,
    pub kind: EdgeKind,
}

/// Parsed graph, ready for layout.
#[derive(Debug, Default)]
pub struct Graph {
    pub direction: Direction,
    pub nodes: Vec<Node>,
    pub edges: Vec<Edge>,
    pub subgraphs: Vec<Subgraph>,
    /// Edges with a subgraph as an endpoint (see [`SubEdge`]).
    pub sub_edges: Vec<SubEdge>,
    index: HashMap<String, usize>,
}

impl Graph {
    /// Look up a node by id; create it if missing.
    /// The latest label/shape overrides earlier ones (Mermaid behaviour).
    pub fn ensure_node(&mut self, id: &str, label: Option<String>, shape: Option<Shape>) -> usize {
        if let Some(&i) = self.index.get(id) {
            if let Some(l) = label {
                self.nodes[i].label = l;
            }
            if let Some(s) = shape {
                self.nodes[i].shape = s;
            }
            i
        } else {
            let i = self.nodes.len();
            self.nodes.push(Node {
                id: id.to_string(),
                label: label.unwrap_or_else(|| id.to_string()),
                shape: shape.unwrap_or(Shape::Rect),
                style: NodeStyle::default(),
            });
            self.index.insert(id.to_string(), i);
            i
        }
    }

    pub fn add_edge(&mut self, from: usize, to: usize, label: Option<String>, kind: EdgeKind) {
        self.edges.push(Edge {
            from,
            to,
            label,
            kind,
        });
    }

    /// Index of an existing node by id, without creating it.
    pub fn node_index(&self, id: &str) -> Option<usize> {
        self.index.get(id).copied()
    }
}

/// One parsed Mermaid document of any supported diagram type.
/// Produced by [`crate::parser::parse_document`].
#[derive(Debug)]
pub enum Document {
    Flowchart(Graph),
    Er(ErDiagram),
    Class(ClassDiagram),
}

/// UML class diagram (`classDiagram` header).
#[derive(Debug, Default)]
pub struct ClassDiagram {
    pub classes: Vec<Class>,
    pub relations: Vec<ClassRel>,
    index: HashMap<String, usize>,
}

impl ClassDiagram {
    /// Look up a class by name; create it (empty) if missing.
    pub fn ensure_class(&mut self, name: &str) -> usize {
        if let Some(&i) = self.index.get(name) {
            i
        } else {
            let i = self.classes.len();
            self.classes.push(Class {
                name: name.to_string(),
                fields: Vec::new(),
                methods: Vec::new(),
            });
            self.index.insert(name.to_string(), i);
            i
        }
    }

    pub fn class_index(&self, name: &str) -> Option<usize> {
        self.index.get(name).copied()
    }
}

/// A class box: name header + fields compartment + methods compartment.
#[derive(Debug)]
pub struct Class {
    pub name: String,
    pub fields: Vec<Member>,
    pub methods: Vec<Member>,
}

/// One field or method row.
#[derive(Debug)]
pub struct Member {
    pub visibility: Visibility,
    /// Display text after the visibility marker
    /// (`name: Type` / `name(args) Ret`).
    pub text: String,
}

/// UML member visibility, shown as a leading glyph.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Visibility {
    Public,    // +
    Private,   // -
    Protected, // #
    Package,   // ~
    None,
}

impl Visibility {
    pub fn glyph(self) -> &'static str {
        match self {
            Visibility::Public => "+",
            Visibility::Private => "-",
            Visibility::Protected => "#",
            Visibility::Package => "~",
            Visibility::None => "",
        }
    }
}

/// A relationship between two classes. Normalised so the end glyph
/// (triangle / diamond / arrow) always sits at the `to` end.
#[derive(Debug)]
pub struct ClassRel {
    pub from: usize,
    pub to: usize,
    pub kind: RelKind,
    /// Dashed line (realization, dependency, `..` link).
    pub dashed: bool,
    pub from_card: Option<String>,
    pub to_card: Option<String>,
    pub label: Option<String>,
}

/// UML relationship type (determines line style + end glyph).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelKind {
    /// `<|--` — hollow triangle at the parent.
    Inheritance,
    /// `..|>` — hollow triangle, dashed line.
    Realization,
    /// `*--` — filled diamond.
    Composition,
    /// `o--` — hollow diamond.
    Aggregation,
    /// `-->` — open arrow.
    Association,
    /// `..>` — open arrow, dashed line.
    Dependency,
    /// `--` — plain line.
    Link,
}

/// Entity-Relationship diagram (`erDiagram` header).
#[derive(Debug, Default)]
pub struct ErDiagram {
    pub entities: Vec<Entity>,
    pub relations: Vec<Relation>,
    index: HashMap<String, usize>,
}

impl ErDiagram {
    /// Look up an entity by name; create it (attribute-less) if missing.
    /// Entities may be introduced by a relationship line alone.
    pub fn ensure_entity(&mut self, name: &str) -> usize {
        if let Some(&i) = self.index.get(name) {
            i
        } else {
            let i = self.entities.len();
            self.entities.push(Entity {
                name: name.to_string(),
                attrs: Vec::new(),
            });
            self.index.insert(name.to_string(), i);
            i
        }
    }
}

/// A database entity, rendered as a table.
#[derive(Debug)]
pub struct Entity {
    pub name: String,
    pub attrs: Vec<Attr>,
}

/// One attribute row inside an entity block:
/// `type name [PK|FK|UK] ["comment"]`.
#[derive(Debug)]
pub struct Attr {
    pub ty: String,
    pub name: String,
    pub keys: Vec<Key>,
    pub comment: Option<String>,
}

/// Attribute key marker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Key {
    Pk,
    Fk,
    Uk,
}

impl Key {
    /// Display tag as written in Mermaid.
    pub fn tag(self) -> &'static str {
        match self {
            Key::Pk => "PK",
            Key::Fk => "FK",
            Key::Uk => "UK",
        }
    }
}

/// Relationship between two entities. `card_from` describes the
/// `from` side, `card_to` the `to` side (crow's foot notation).
#[derive(Debug)]
pub struct Relation {
    pub from: usize,
    pub to: usize,
    pub card_from: Card,
    pub card_to: Card,
    /// `--` = identifying (solid line), `..` = non-identifying (dashed).
    pub identifying: bool,
    pub label: Option<String>,
}

/// Relationship cardinality on one side.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Card {
    /// `||` exactly one.
    One,
    /// `|o` / `o|` zero or one.
    ZeroOne,
    /// `}o` / `o{` zero or many.
    ZeroMany,
    /// `}|` / `|{` one or many.
    OneMany,
}