ariel-rs 0.2.0

A faithful Rust port of Mermaid JS — headless SVG diagram rendering without a browser
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/// Parser for Mermaid kanban diagram syntax.
///
/// Faithful port of kanbanDb.ts.
///
/// Grammar:
///   kanban
///     columnId["Column Label"]
///       itemId["Item Label"]
///       itemId2["Item 2"]
///     columnId2
///       itemId3["Item 3"]
///
/// Columns are detected at indent level 1 (relative to `kanban`).
/// Items are detected at indent level 2+.
///
/// Node shapes (same as mindmap/kanbanDb.ts getType):
///   [text]    → Rect (default for kanban items)
///   (text)    → RoundedRect
///   ((text))  → Circle
///   )text(    → Cloud
///   ))text((  → Bang
///   {{text}}  → Hexagon
///   text      → Default (no border)
///
/// YAML metadata in node definitions is parsed for shape, icon, ticket, priority, etc.
/// This port handles the common cases faithfully.
/// Shape constants (mirrors kanbanDb.ts nodeType)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeShape {
    Default,     // 0/1 – plain text / no border
    RoundedRect, // 2 – (text)
    Rect,        // 3 – [text]
    Circle,      // 4 – ((text))
    Cloud,       // 5 – )text(
    Bang,        // 6 – ))text((
    Hexagon,     // 7 – {{text}}
}

/// A kanban column (section/group node in kanbanDb.ts getData).
#[derive(Debug, Clone)]
pub struct KanbanSection {
    pub id: String,
    pub label: String,
    pub items: Vec<KanbanItem>,
}

/// A kanban item (card within a column).
#[derive(Debug, Clone)]
pub struct KanbanItem {
    pub id: String,
    pub label: String,
    pub shape: NodeShape,
    pub priority: Option<String>,
    pub ticket: Option<String>,
    pub assigned: Option<String>,
}

pub struct KanbanConfig {
    pub ticket_base_url: Option<String>,
}

pub struct KanbanDiagram {
    pub sections: Vec<KanbanSection>,
    pub config: KanbanConfig,
}

/// Parse a kanban diagram from Mermaid syntax.
/// Mirrors the logic of kanbanDb.ts addNode + getData.
pub fn parse(input: &str) -> crate::error::ParseResult<KanbanDiagram> {
    let mut sections: Vec<KanbanSection> = Vec::new();

    // Extract ticketBaseUrl from YAML front-matter config if present
    let ticket_base_url = extract_ticket_base_url(input);

    // Strip YAML front-matter (--- ... ---) if present
    let body = strip_frontmatter(input);

    // Track base indentation
    let mut header_seen = false;
    let mut base_indent: Option<usize> = None;

    // We'll accumulate lines into sections using an indent-based approach.
    // Level 0 relative = column header; level 1+ = item.
    let mut current_section: Option<KanbanSection> = None;
    let mut item_counter: usize = 0;
    let mut section_counter: usize = 0;

    for raw_line in body.lines() {
        let trimmed_end = raw_line.trim_end();

        // Skip blank lines and comments
        let trimmed = trimmed_end.trim();
        if trimmed.is_empty() || trimmed.starts_with("%%") {
            continue;
        }

        // Detect and skip the "kanban" header line
        if !header_seen {
            if trimmed.eq_ignore_ascii_case("kanban") {
                header_seen = true;
            }
            continue;
        }

        // Handle `title` line inside the diagram body — skip
        if trimmed.to_lowercase().starts_with("title ") {
            continue;
        }

        // Determine indentation
        let indent = raw_line.len() - raw_line.trim_start().len();

        // Establish base indentation from first non-header line
        if base_indent.is_none() {
            base_indent = Some(indent);
        }
        let base = base_indent.unwrap_or(0);

        // Relative indent level (0 = column, 1+ = item)
        let relative_level = if indent >= base {
            (indent - base) / 2
        } else {
            0
        };

        if relative_level == 0 {
            // This is a column/section header
            if let Some(sec) = current_section.take() {
                sections.push(sec);
            }

            let (id, label) = parse_node_id_and_label(trimmed, &mut section_counter);
            section_counter += 1;

            current_section = Some(KanbanSection {
                id,
                label,
                items: Vec::new(),
            });
        } else {
            // This is an item within the current section
            let (id, label, shape, priority, ticket, assigned) =
                parse_item(trimmed, &mut item_counter);
            item_counter += 1;

            let item = KanbanItem {
                id,
                label,
                shape,
                priority,
                ticket,
                assigned,
            };

            if let Some(ref mut sec) = current_section {
                sec.items.push(item);
            }
        }
    }

    // Flush the last section
    if let Some(sec) = current_section.take() {
        sections.push(sec);
    }

    crate::error::ParseResult::ok(KanbanDiagram {
        sections,
        config: KanbanConfig { ticket_base_url },
    })
}

/// Strip YAML front matter (--- ... ---) from input, returning the remainder.
fn strip_frontmatter(input: &str) -> &str {
    let trimmed = input.trim_start();
    if !trimmed.starts_with("---") {
        return input;
    }
    // Find the closing ---
    let after_open = &trimmed[3..];
    if let Some(close_pos) = after_open.find("\n---") {
        let after_close = &after_open[close_pos + 4..];
        // Skip the newline after the closing ---
        return after_close.trim_start_matches('\n');
    }
    input
}

/// Parse a column/section line, extracting ID and label.
/// The line may be:
///   - plain identifier: `todo`  → id="todo", label="todo"
///   - with bracket label: `todo["To Do"]`  → id="todo", label="To Do"
///   - with quoted label: `todo[To Do]`  → id="todo", label="To Do"
fn parse_node_id_and_label(content: &str, counter: &mut usize) -> (String, String) {
    // Try to find bracket label: id[label] or id["label"]
    if let Some(bracket_pos) = content.find('[') {
        if content.ends_with(']') {
            let id = content[..bracket_pos].trim().to_string();
            let inner = &content[bracket_pos + 1..content.len() - 1];
            // Strip optional quotes
            let label = inner
                .trim_matches('"')
                .trim_matches('\'')
                .trim()
                .to_string();
            let id = if id.is_empty() {
                format!("section_{}", counter)
            } else {
                id
            };
            return (id, label);
        }
    }
    // Plain identifier — id and label are the same
    let id = content.trim().to_string();
    let label = id.clone();
    (id, label)
}

/// Parse a kanban item line, extracting (id, label, shape).
/// Mirrors kanbanDb.ts addNode() which handles YAML metadata @{ ... }.
///
/// Forms:
///   id["Label"]
///   id["Label"]@{ ticket: MC-2037, priority: Very High }
///   id[Label]
///   id
fn parse_item(
    content: &str,
    counter: &mut usize,
) -> (
    String,
    String,
    NodeShape,
    Option<String>,
    Option<String>,
    Option<String>,
) {
    // Extract YAML metadata @{ ... } if present
    let (content_no_meta, priority, ticket, assigned) = if let Some(at_pos) = content.find("@{") {
        let meta = content[at_pos..].trim();
        let priority = extract_meta_value(meta, "priority");
        let ticket = extract_meta_value(meta, "ticket");
        let assigned = extract_meta_value(meta, "assigned");
        (content[..at_pos].trim_end(), priority, ticket, assigned)
    } else {
        (content, None, None, None)
    };

    let (id, label, shape) = parse_item_content(content_no_meta.trim(), counter);
    (id, label, shape, priority, ticket, assigned)
}

/// Extract a value from @{ key: 'value' } metadata string.
fn extract_meta_value(meta: &str, key: &str) -> Option<String> {
    let search = format!("{key}:");
    let pos = meta.find(&search)?;
    let rest = meta[pos + search.len()..].trim_start();
    let value = rest.trim_start_matches('\'').trim_start_matches('"');
    let end = value.find(['\'', '"', ',', '}']).unwrap_or(value.len());
    Some(value[..end].trim().to_string())
}

/// Extract ticketBaseUrl from YAML front-matter config block.
fn extract_ticket_base_url(input: &str) -> Option<String> {
    let trimmed = input.trim_start();
    if !trimmed.starts_with("---") {
        return None;
    }
    let end = trimmed.find("\n---")?;
    let frontmatter = &trimmed[3..end];
    let pos = frontmatter.find("ticketBaseUrl")?;
    let rest = frontmatter[pos + "ticketBaseUrl".len()..]
        .trim_start_matches(':')
        .trim_start();
    let value = rest.trim_start_matches('\'').trim_start_matches('"');
    let quote_end = value.find(['\'', '"', '\n']).unwrap_or(value.len());
    Some(value[..quote_end].trim().to_string())
}

/// Parse id + bracket-label + shape from content (without @{ } metadata).
fn parse_item_content(content: &str, counter: &mut usize) -> (String, String, NodeShape) {
    // Try double-bracket forms first (longer match wins)
    if let Some(pos) = content.find("((") {
        if content.ends_with("))") && content.len() > pos + 4 {
            let id = content[..pos].trim().to_string();
            let label = content[pos + 2..content.len() - 2]
                .trim_matches('"')
                .trim_matches('\'')
                .trim()
                .to_string();
            let id = if id.is_empty() {
                format!("item_{counter}")
            } else {
                id
            };
            return (id, label, NodeShape::Circle);
        }
    }
    if let Some(pos) = content.find("{{") {
        if content.ends_with("}}") && content.len() > pos + 4 {
            let id = content[..pos].trim().to_string();
            let label = content[pos + 2..content.len() - 2]
                .trim_matches('"')
                .trim_matches('\'')
                .trim()
                .to_string();
            let id = if id.is_empty() {
                format!("item_{counter}")
            } else {
                id
            };
            return (id, label, NodeShape::Hexagon);
        }
    }
    if let Some(pos) = content.find("))") {
        if content.ends_with("((") && content.len() > pos + 4 {
            let id = content[..pos].trim().to_string();
            let label = content[pos + 2..content.len() - 2]
                .trim_matches('"')
                .trim_matches('\'')
                .trim()
                .to_string();
            let id = if id.is_empty() {
                format!("item_{counter}")
            } else {
                id
            };
            return (id, label, NodeShape::Bang);
        }
    }
    // Single-bracket forms
    if let Some(pos) = content.find('[') {
        if content.ends_with(']') && content.len() > pos + 2 {
            let id = content[..pos].trim().to_string();
            let label = content[pos + 1..content.len() - 1]
                .trim_matches('"')
                .trim_matches('\'')
                .trim()
                .to_string();
            let id = if id.is_empty() {
                format!("item_{counter}")
            } else {
                id
            };
            return (id, label, NodeShape::Rect);
        }
    }
    // Rounded rect: id(label)
    if let Some(pos) = find_single_open_paren(content) {
        if content.ends_with(')') && !content.ends_with("))") && content.len() > pos + 2 {
            let id = content[..pos].trim().to_string();
            let label = content[pos + 1..content.len() - 1]
                .trim_matches('"')
                .trim_matches('\'')
                .trim()
                .to_string();
            let id = if id.is_empty() {
                format!("item_{counter}")
            } else {
                id
            };
            return (id, label, NodeShape::RoundedRect);
        }
    }
    // Cloud: id)label(
    if let Some(pos) = content.find(')') {
        if content.ends_with('(') && !content.ends_with("((") && content.len() > pos + 2 {
            let id = content[..pos].trim().to_string();
            let label = content[pos + 1..content.len() - 1]
                .trim_matches('"')
                .trim_matches('\'')
                .trim()
                .to_string();
            let id = if id.is_empty() {
                format!("item_{counter}")
            } else {
                id
            };
            return (id, label, NodeShape::Cloud);
        }
    }

    // Plain identifier — use it as both id and label
    let id = content.to_string();
    let label = id.clone();
    (id, label, NodeShape::Default)
}

/// Find a single '(' that is not part of '((' .
fn find_single_open_paren(content: &str) -> Option<usize> {
    let bytes = content.as_bytes();
    (0..bytes.len()).find(|&i| bytes[i] == b'(' && bytes.get(i + 1).copied() != Some(b'('))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn basic_kanban() {
        let input = "kanban\n  todo\n    id1[Task 1]\n    id2[Task 2]\n  inProgress\n    id3[Task 3]\n  done\n    id4[Task 4]";
        let d = parse(input).diagram;
        assert_eq!(d.sections.len(), 3);
        assert_eq!(d.sections[0].id, "todo");
        assert_eq!(d.sections[0].label, "todo");
        assert_eq!(d.sections[0].items.len(), 2);
        assert_eq!(d.sections[0].items[0].label, "Task 1");
        assert_eq!(d.sections[0].items[1].label, "Task 2");
        assert_eq!(d.sections[1].id, "inProgress");
        assert_eq!(d.sections[1].items[0].label, "Task 3");
        assert_eq!(d.sections[2].id, "done");
        assert_eq!(d.sections[2].items[0].label, "Task 4");
    }

    #[test]
    fn section_with_bracket_label() {
        let input = "kanban\n  col1[\"To Do\"]\n    item1[\"Task A\"]\n";
        let d = parse(input).diagram;
        assert_eq!(d.sections[0].id, "col1");
        assert_eq!(d.sections[0].label, "To Do");
        assert_eq!(d.sections[0].items[0].label, "Task A");
    }

    #[test]
    fn item_shapes() {
        let input = "kanban\n  col\n    a[Rect]\n    b(Round)\n    c((Circle))\n";
        let d = parse(input).diagram;
        assert_eq!(d.sections[0].items[0].shape, NodeShape::Rect);
        assert_eq!(d.sections[0].items[1].shape, NodeShape::RoundedRect);
        assert_eq!(d.sections[0].items[2].shape, NodeShape::Circle);
    }

    #[test]
    fn yaml_metadata() {
        // Metadata fields are stripped but the item label and shape are still parsed.
        let input = "kanban\n  col\n    id1[Task]@{ ticket: MC-1, priority: High }\n";
        let d = parse(input).diagram;
        let item = &d.sections[0].items[0];
        assert_eq!(item.label, "Task");
        assert_eq!(item.shape, NodeShape::Rect);
    }

    #[test]
    fn frontmatter_stripped() {
        let input =
            "---\nconfig:\n  kanban:\n    sectionWidth: 150\n---\nkanban\n  col\n    id1[Task]\n";
        let d = parse(input).diagram;
        assert_eq!(d.sections.len(), 1);
        assert_eq!(d.sections[0].items[0].label, "Task");
    }
}